diff --git a/.claude/rules/codegen-architecture.md b/.claude/rules/codegen-architecture.md index 90150fd479..d63bdf87ac 100644 --- a/.claude/rules/codegen-architecture.md +++ b/.claude/rules/codegen-architecture.md @@ -78,10 +78,10 @@ one file (#266: a shared artifact rendered from the whole loaded root, like the `enums.ts`, is emitted by every `entityFile()` instance); also errors on an unknown target, missing `importBase` for cross-target imports, or any generator throw, (6) writes each file under its target's `outDir`, deciding from `.metaobjects/.gen-state/` — a three-way merge against the snapshot body when one is -present, else the committed `.hashes.json` (hash matches what we recorded writing ⇒ +present, else the committed `.hashes/` (hash matches what we recorded writing ⇒ overwrite; edited or unrecorded ⇒ refused). The `@generated` header is **informational**: every use of it is an emitter stamping the marker into output, and the overwrite decision -never reads it. Because the snapshot bodies are gitignored while `.hashes.json` is +never reads it. Because the snapshot bodies are gitignored while `.hashes/` is committed, a fresh clone or CI runner takes the second branch — so a hand-edited generated file is REFUSED there rather than merged. diff --git a/AGENTS.md b/AGENTS.md index 23a0ff4d2c..356c785e2d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -263,7 +263,7 @@ import { EntityFetcherProvider, EntityGrid } from "@metaobjectsdev/tanstack"; - **TS runtime**: Bun-first for development (zero-config TS, native test runner). Node-compatible for distribution; users install via npm/pnpm/bun without lock-in to Bun's runtime. - **Module system**: ESM only. No CommonJS, no transpile step required. -- **Storage format**: JSON files in `metaobjects/meta..json` at project root. `.metaobjects/.gen-state/` holds the codegen merge base: the snapshot **bodies are gitignored** (a second full copy of all generated output), but **`.hashes.json` is COMMITTED** — one hash per generated path, and the only thing that lets `meta gen` tell "this file is exactly what I wrote" from "somebody edited this" on a machine that did not generate it. Ignore it and a fresh clone or CI runner silently overwrites hand edits; commit it and an edited file is refused by name instead. +- **Storage format**: JSON files in `metaobjects/meta..json` at project root. `.metaobjects/.gen-state/` holds the codegen merge base: the snapshot **bodies are gitignored** (a second full copy of all generated output), but **`.hashes/` (one file per model package) is COMMITTED** — one hash per generated path, and the only thing that lets `meta gen` tell "this file is exactly what I wrote" from "somebody edited this" on a machine that did not generate it. Ignore it and a fresh clone or CI runner silently overwrites hand edits; commit it and an edited file is refused by name instead. - **Codegen substrate**: the vendored ts-poet printer (`codegen-ts/src/poet.ts`) for greenfield emit, ts-morph for in-place edits, Biome for format pass, `git merge-file --diff3` for hand-edit-preserving regen. - **Runtime substrate**: Kysely for TS (user-provided connection, async-only). - **Migration substrate**: Postgres + SQLite for TS v0.3. @@ -304,7 +304,7 @@ project-root/ ├── .metaobjects/ # HIDDEN — tool state │ ├── config.json # static project state │ └── .gen-state/ # codegen merge base -│ ├── .hashes.json # COMMIT THIS — one hash per generated path +│ ├── .hashes/.json # COMMIT THIS — one hash per generated path, one file per package │ └── # gitignored (a 2nd copy of all output) └── metaobjects.config.ts # runtime config ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index bcf49f68ef..73f3309b42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,17 @@ Each item below is described in full under Security, Added, Changed or Fixed; th `codegen-kotlin` generators ignored a generator's `` and wrote every object; they now honour them, as the `codegen-base` generators always did. A pom whose filters were inert generates fewer files: remove the `` that no longer describe what you want. +- **The hash manifest is one file per package.** `.metaobjects/.gen-state/.hashes.json` is replaced + by `.metaobjects/.gen-state/.hashes/.json` (and `.root.json` for a path in no package), so + two branches that regenerate files in different packages no longer conflict on one file. Nothing to + do but commit: the first `meta gen` (or `dotnet meta gen`, `mvn metaobjects:generate`, + `metaobjects gen`, `cargo meta gen`) reads the old file, writes the package files, deletes the old + file and adds `!.gen-state/.hashes/` to `.metaobjects/.gitignore` when that file ignores + `.gen-state/*`. A project whose root `.gitignore` excludes `.metaobjects/.gen-state/` should + un-ignore the new directory the way it un-ignored the old file; `meta verify` still names the + rule that is in force. A pipeline that read `.hashes.json` directly reads every file in + `.hashes/` instead. ADR-0064 Amendment 1; + [docs/features/migrations/per-package-hash-manifest.md](docs/features/migrations/per-package-hash-manifest.md). - **`metamodelVersion` is `1.3`.** Upgrade every port together. ### Security @@ -215,6 +226,19 @@ Each item below is described in full under Security, Added, Changed or Fixed; th ### Added +- **The hash manifest is one file per package (ADR-0064 Amendment 1).** Every port that keeps hash + state, TypeScript, C#, Java, Kotlin, Python and Rust, writes `.gen-state/.hashes/.json` + instead of one `.gen-state/.hashes.json`. The file name is the package's `::` segments joined with + `.`, percent-encoding any byte outside `[A-Za-z0-9_-]`. A file is placed by the `sourceNode` the + entry records, else by the model object its file name names (matched by words, so `OrderLine.cs` + and `order_line.py` both find `OrderLine`), else it stays where it was, else it goes in + `.root.json`. Placement only decides which file holds an entry: a reader merges them all, so a + wrong placement costs a merge conflict and nothing else. A write touches only the files whose + bytes change, so a run that changes nothing still writes nothing. The shared vectors are + `fixtures/codegen-skip-conformance/manifests.json`, and a `legacy-manifest` case in that corpus + holds every port to the migration. A test merges two real git branches that change different + packages with no conflict. + - **Business rules: operations, permission names and lifecycles (ADR-0066). Experimental:** the shape may change in a MINOR, including removals and renames, until generated services run on it in an adopter estate (`docs/compatibility-policy.md`). The names ADR-0030 diff --git a/agent-context/skills/metaobjects-audit/references/typescript.md b/agent-context/skills/metaobjects-audit/references/typescript.md index 1929a98514..ce4485c972 100644 --- a/agent-context/skills/metaobjects-audit/references/typescript.md +++ b/agent-context/skills/metaobjects-audit/references/typescript.md @@ -24,7 +24,7 @@ Generated files carry the header: The header is **informational on this port** — the write decision never reads it. What the runner overwrites is decided by `.metaobjects/.gen-state/`: the snapshot body if the -machine has one (three-way merge), otherwise the committed `.hashes.json` (byte-for-byte +machine has one (three-way merge), otherwise the committed `.hashes/` (byte-for-byte what it wrote ⇒ overwrite; anything else ⇒ refused, exit 1). A sibling file you created (`.extra.ts` by convention) is never touched because it is not a path the runner records — not because of its name, and not because of the header. Locate generated output at the diff --git a/agent-context/skills/metaobjects-codegen/SKILL.md b/agent-context/skills/metaobjects-codegen/SKILL.md index 4ec8b55048..c30d6fc156 100644 --- a/agent-context/skills/metaobjects-codegen/SKILL.md +++ b/agent-context/skills/metaobjects-codegen/SKILL.md @@ -176,7 +176,7 @@ You run a `gen` step. The runner: 3. Runs each configured **generator** — most emit one file per entity; some emit a single shared file (a barrel, a DB-context, an app-config). 4. Decides whether it may overwrite a file, by a committed **hash manifest** - (`.metaobjects/.gen-state/.hashes.json`) on every port. If a file still hashes to what + (`.metaobjects/.gen-state/.hashes/`) on every port. If a file still hashes to what the generator recorded writing, it is safe to overwrite; if it was edited, or there is no record of it, the write is **refused by name**. TypeScript additionally three-way-merges against a snapshot when one is present locally. **Commit the @@ -189,7 +189,7 @@ You run a `gen` step. The runner: write). On Java and Kotlin a refusal is a warning and `mvn metaobjects:verify` is the gate that fails. The one-time fix for a project that predates the committed manifest is **`gen --baseline=adopt`**: it records the files you have as the baseline and writes - nothing, so there is finally a `.hashes.json` to commit — then `gen` again, and the + nothing, so there is finally a `.hashes/` to commit — then `gen` again, and the regeneration lands as its own diff. Adopting DECLARES those files to be generated output, so an edit already inside one is part of the baseline and that regeneration replaces it; commit before you run it. (TypeScript additionally has diff --git a/agent-context/skills/metaobjects-codegen/references/typescript.md b/agent-context/skills/metaobjects-codegen/references/typescript.md index 23651413e4..588e061158 100644 --- a/agent-context/skills/metaobjects-codegen/references/typescript.md +++ b/agent-context/skills/metaobjects-codegen/references/typescript.md @@ -314,16 +314,16 @@ npx meta gen Author Post # scope to named entities Generated files carry an `@generated by @metaobjectsdev/codegen-ts` header. It is **informational** — the write decision never reads it. `.metaobjects/.gen-state/` decides: the snapshot body if this machine has one (three-way merge), otherwise the -committed `.hashes.json` (byte-for-byte what it wrote ⇒ overwrite; anything else ⇒ +committed `.hashes/` (byte-for-byte what it wrote ⇒ overwrite; anything else ⇒ refused, path named, exit 1). So the merge is machine-local: a file you edited and pushed is REFUSED on a fresh clone or in CI, not merged. Recovery is in `docs/features/own-your-codegen.md`. A project with NO manifest at all (it predates the manifest being committed) is a different case with a different fix: every stale file refuses, and a run where everything -refuses writes no manifest — so "commit `.hashes.json`" has nothing to commit. Run +refuses writes no manifest — so "commit `.hashes/`" has nothing to commit. Run `meta gen --baseline=adopt` once: it records the files you have as the merge base and -writes nothing, leaving exactly one file to commit; the next `meta gen` is then the +writes nothing, leaving the manifest to commit; the next `meta gen` is then the regeneration, as its own reviewable diff. Adopting declares those files to BE generated output, so an edit already inside one is part of the base and that regeneration replaces it — `--baseline=fresh` + `git checkout` is the sequence that KEEPS an edit. diff --git a/agent-context/skills/metaobjects-verify/SKILL.md b/agent-context/skills/metaobjects-verify/SKILL.md index 4ec6d5567a..c5f0d69812 100644 --- a/agent-context/skills/metaobjects-verify/SKILL.md +++ b/agent-context/skills/metaobjects-verify/SKILL.md @@ -152,7 +152,7 @@ with `ERR_DEPENDENCY_SNAPSHOT_STALE` naming the fix: run `meta deps sync`. regen) fails the build. Wire it into CI so a stale `@generated` file fails. **A hand edit inside a generated file is reported apart from drift** — `meta gen` three-way-merges hand edits by design, and the Node gate judges the *generated - contribution* against the committed `.metaobjects/.gen-state/.hashes.json`, not the + contribution* against the committed `.metaobjects/.gen-state/.hashes/`, not the bytes, then lists every generated file carrying a hand edit (count + paths). Whether that list fails the build is `verify.handEdits` in `.metaobjects/config.json`: `"fail"` exits 1 (what `meta init` writes for a new project), `"notice"` (and a diff --git a/agent-context/templates/always-on.md.mustache b/agent-context/templates/always-on.md.mustache index 5f7cffe689..c6855d8568 100644 --- a/agent-context/templates/always-on.md.mustache +++ b/agent-context/templates/always-on.md.mustache @@ -36,7 +36,7 @@ is built (never before), a new node for new behaviour. {{verifySteps}}- `npx meta verify --db ` (the live schema matches the metadata). Commit the metadata, the generated code, `.metaobjects/migrations/` and -`.metaobjects/.gen-state/.hashes.json`. +`.metaobjects/.gen-state/.hashes/`. ## Calling the generated REST API diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 3f40e55b67..3cd4cc8e1e 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -63,7 +63,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 5 cases + 1 overflow + 5 refusals; run by a port that sizes the column | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | — (sizes no column: emits no DDL or column type; the config reader accepts and shape-checks the `enums` block) | | [`fixtures/check-constraint-conformance/`](../fixtures/check-constraint-conformance/) (the CHECK constraints `meta migrate` derives: name and expression text per dialect) | 1 model, 5 expected files (postgres, sqlite, d1, and both skip-redundant variants) | ✓ (reference, `migrate-ts`) | — (no CHECK in a generated model) | — (same) | ✓ (the EF context declares them; live-Postgres `EnsureCreated` lane) | — (same) | | [`fixtures/foreign-key-index-conformance/`](../fixtures/foreign-key-index-conformance/) (the indexes `migrate.foreignKeyIndexes` adds: which foreign keys are uncovered, and each index's name per dialect, a name over 63 bytes cut on Postgres; and the name each declared `identity.secondary` / `index.lookup` is created under) | 1 model, 4 expected files (FK and declared, postgres and sqlite) | ✓ (reference, `migrate-ts`; the Drizzle tables declare the declared names) | — (no index in a generated model) | ✓ (the Exposed tables declare them) | ✓ (the EF context declares them) | — (same as Java) | -| [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json` | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | +| [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | | [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 41 cases (31 core + 10 TypeScript) | ✓ (the first writer; core and TypeScript dialect) | — (writer not built yet) | — (writer not built yet) | — (writer not built yet) | — (writer not built yet) | diff --git a/docs/features/cli.md b/docs/features/cli.md index 63cdc99bb6..e92f5254ac 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -54,7 +54,7 @@ vocabulary everywhere, each port implementing the modes it supports. | Subverb | What it checks | Touches a DB? | |---|---|---| | `verify --db` | **Schema drift** — does the live database (or snapshot) match the metadata? (migrate engine, ADR-0015) | yes | -| `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.json` 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 --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 | @@ -289,7 +289,7 @@ ships. When `verify` renders, it compares in memory: no temp tree is written. ## `gen` refuses rather than guesses — and `--baseline` is how you answer it Every port's `gen` decides per file whether it may overwrite, from a committed hash -manifest (`.metaobjects/.gen-state/.hashes.json`). A file that still hashes to what the +manifest (`.metaobjects/.gen-state/.hashes/`). A file that still hashes to what the generator recorded writing is safe to overwrite; one that was edited, or that no record covers, is **refused by name and left exactly as it is**. @@ -324,10 +324,10 @@ Syntax per port, and the orphan rule both follow: [own-your-codegen](own-your-codegen.md#handedits-keep-or-discard-edits-to-one-generators-files). **`adopt` exists because the refusal's own remedy was unreachable.** It told you to commit -`.hashes.json` — but nothing writes a manifest until a `gen` succeeds, and a run where +`.hashes/` — but nothing writes a manifest until a `gen` succeeds, and a run where every file refuses writes none, so there was nothing to commit and the next run refused identically. `adopt` breaks that loop: it records what is on disk, writes not one byte of -output, and leaves exactly one file to commit. Then `gen` again, and the regeneration +output, and leaves the manifest to commit. Then `gen` again, and the regeneration arrives as its own reviewable diff. **What adopting declares** — say this out loud before running it: that the files you have diff --git a/docs/features/codegen-concepts.md b/docs/features/codegen-concepts.md index e75f9c4acf..d189e9648b 100644 --- a/docs/features/codegen-concepts.md +++ b/docs/features/codegen-concepts.md @@ -160,12 +160,12 @@ work. **Every port decides from the committed hash manifest, and the `@generated not the decision:** - **TypeScript** decides from `.metaobjects/.gen-state/` — the snapshot body if this - machine has one (three-way merge), otherwise the committed `.hashes.json` (byte-for-byte + machine has one (three-way merge), otherwise the committed `.hashes/` (byte-for-byte what we wrote ⇒ overwrite; anything else ⇒ refused, path named, exit 1). The `@generated` header is emitted for human readers and **the write decision never reads it**. Deleting it does not take ownership of a file — it changes the content, so the hash stops matching and the file is refused like any other edit. -- **C# and Python** decide the same way — from the committed `.hashes.json` — and refuse +- **C# and Python** decide the same way — from the committed `.hashes/` — and refuse rather than merge, since neither keeps a snapshot body to merge against. Their headers (`` and `@generated by metaobjects`) are informational too **whenever a gen-state directory is in play, which is every CLI run**. One caller can reach the diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index 5502ac514d..d96ac9d1d4 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -19,7 +19,7 @@ reads three documents, and a fourth optional input, the REST routes (see [`api`] | --- | --- | --- | | Effective canonical JSON | `meta export --effective` | nodes, inheritance, every model edge | | The verify payload | `meta verify --format json` | the requirement ledger, and the `implementedBy` / `supersededBy` edges | -| The generated-file manifest | `.metaobjects/.gen-state/.hashes.json`, written by `meta gen` | which generated files each node produced | +| The generated-file manifest | `.metaobjects/.gen-state/.hashes/`, written by `meta gen` | which generated files each node produced | Only the first is required. Without the verify payload there is no `ledger` and no requirement claim edge; without the manifest there is no `generated` section. @@ -88,7 +88,7 @@ subject is not a requirement. `node` names that other subject: a carries `""`. Read the subject from `path` and `node`, never from `message`, whose wording may change. The structured payload is TypeScript-only, as the rest of `--format json` is. -### Node provenance in `.hashes.json` +### Node provenance in the manifest Each generated file now records the metadata node it was rendered from. A generator built with `perEntity` sets this automatically. An `EmittedFile` can also name its node directly with @@ -208,14 +208,21 @@ two spaces, with one trailing newline. That makes the file safe to commit and di ## Building it ```ts -import { readFileSync, writeFileSync } from "node:fs"; +import { readdirSync, readFileSync, writeFileSync } from "node:fs"; import { buildExplorer, serializeExplorer } from "@metaobjectsdev/docs-site"; const read = (f: string) => JSON.parse(readFileSync(f, "utf8")); +// The manifest is one file per model package; the explorer wants their union. +const hashes = ".metaobjects/.gen-state/.hashes"; +const manifest = Object.assign( + {}, + ...readdirSync(hashes).filter((f) => f.endsWith(".json")).map((f) => read(`${hashes}/${f}`)), +); + writeFileSync("explorer.json", serializeExplorer(buildExplorer({ model: read("effective.json"), // meta export --effective --out effective.json verify: read("verify.json"), // meta verify --format json > verify.json - manifest: read(".metaobjects/.gen-state/.hashes.json"), + manifest, }))); ``` diff --git a/docs/features/migrations/commit-the-gen-state-hash-manifest.md b/docs/features/migrations/commit-the-gen-state-hash-manifest.md index 2268427542..215343f1b4 100644 --- a/docs/features/migrations/commit-the-gen-state-hash-manifest.md +++ b/docs/features/migrations/commit-the-gen-state-hash-manifest.md @@ -1,7 +1,11 @@ # Migration — commit `.gen-state/.hashes.json` +> **Since 1.3.0 the manifest is a directory, `.gen-state/.hashes/`, with one file per model +> package** (see [the per-package manifest migration](per-package-hash-manifest.md)). Read +> `.hashes.json` below as that directory; the first `gen` after upgrading converts it. + **Applies to:** every existing TypeScript project scaffolded by `meta init` before this -release. **Action required:** one edit to `.metaobjects/.gitignore`, then commit one file. +release. **Action required:** one edit to `.metaobjects/.gitignore`, then commit the manifest. ## What changed, and why it matters to you @@ -26,7 +30,7 @@ with: ```gitignore .gen-state/* -!.gen-state/.hashes.json +!.gen-state/.hashes/ ``` **The glob is load-bearing.** `.gen-state/` names a *directory*, and git does not descend @@ -38,7 +42,7 @@ Then produce the manifest and commit it: ```bash meta gen --baseline=adopt # records what you have; writes NOTHING else -git add .metaobjects/.gitignore .metaobjects/.gen-state/.hashes.json +git add .metaobjects/.gitignore .metaobjects/.gen-state/.hashes/ git commit -m "chore: commit the codegen hash manifest" meta gen # the regeneration, now on its own ``` @@ -49,7 +53,7 @@ it, which is the usual state of a project that has not regenerated in a few rele such file is refused, and a run where *everything* refuses writes **no manifest at all**: there is then nothing to commit, and the next run refuses identically. `--baseline=adopt` is the run that breaks that loop. It records the files you have as the merge base, writes -not one byte of output, and leaves you with exactly one file to commit. +not one byte of output, and leaves you with the manifest to commit. **What adopting declares.** That the files you have *are* generated output. It protects edits you make from that point on — they now have a base to merge against — but an edit @@ -61,7 +65,9 @@ something you meant to keep, the "Keep the differences" recipe below is the way `.gen-state/` holds two different things. The snapshot **bodies** are a full second copy of all your generated output — committing those doubles the generated bytes in your repository -and puts a second diff beside every real one. `.hashes.json` is one line per generated path: +and puts a second diff beside every real one. The manifest holds one line per generated path, +split across one file per model package (`.hashes/.json`). A package file looks like +this: ```json { @@ -107,16 +113,19 @@ That means those files differ from fresh output and there is no hash recording t Run it once, commit the manifest, and the refusals stop: from then on every machine can tell your edits from its own output. -## When two branches both regenerated: resolving a `.hashes.json` conflict +## When two branches both regenerated: resolving a manifest conflict + +Since 1.3.0 this only happens when both branches changed the same package's generated files, +because each package has its own manifest file. The advice below applies to that one file. Now that the manifest is committed, two people who both ran `meta gen` on different branches will conflict on it. This is expected and harmless — both sides are just records of generated content — but resolve it the right way: ```bash -git checkout --ours .metaobjects/.gen-state/.hashes.json # either side will do +git checkout --ours .metaobjects/.gen-state/.hashes/ # either side will do meta gen # rewrites every entry -git add .metaobjects/.gen-state/.hashes.json +git add .metaobjects/.gen-state/.hashes/ ``` Take **either** side, then re-run `meta gen`. It rewrites the entry for every path it diff --git a/docs/features/migrations/docs-are-generators.md b/docs/features/migrations/docs-are-generators.md index 797af53fa3..b379fff627 100644 --- a/docs/features/migrations/docs-are-generators.md +++ b/docs/features/migrations/docs-are-generators.md @@ -1,5 +1,9 @@ # Migration: documentation is a generator you declare +> **Since 1.3.0 the manifest is a directory, `.metaobjects/.gen-state/.hashes/`, with one file per +> model package** (see [the per-package manifest migration](per-package-hash-manifest.md)). Read +> `.hashes.json` below as that directory; the first `gen` after upgrading converts it. + **Removed in:** 1.1.0 (Maven 8.1.0) · **Ports affected:** all five **Automatic fix:** none. Each section below is written so you, or a coding agent working in your repository, can make the change by hand. @@ -120,7 +124,7 @@ export default defineConfig({ ``` **The first run after the upgrade.** 1.0 wrote its pages without recording them in -`.metaobjects/.gen-state/.hashes.json`, so `meta gen` cannot tell them from pages somebody +`.metaobjects/.gen-state/.hashes/`, so `meta gen` cannot tell them from pages somebody edited, and refuses each one whose content changed. Run the docs entries once with a fresh baseline, naming only the docs entries your config declares (this example declares all six): @@ -131,7 +135,7 @@ meta gen --generators docs,api-docs,requirements,agent-docs,docs-site,metamodel- This writes fresh pages over the 1.0 ones and records them. 1.0 overwrote these pages on every `meta docs`, so nothing of yours is in them to lose. `--generators` keeps the fresh baseline off your code: a generated code file you edited is still refused, not overwritten. Commit -`.metaobjects/.gen-state/.hashes.json` with the pages. From then on, run `meta gen`: +`.metaobjects/.gen-state/.hashes/` with the pages. From then on, run `meta gen`: ``` meta gen diff --git a/docs/features/migrations/jvm-codegen-hash-manifest.md b/docs/features/migrations/jvm-codegen-hash-manifest.md index 5cf562eff8..b214072ab9 100644 --- a/docs/features/migrations/jvm-codegen-hash-manifest.md +++ b/docs/features/migrations/jvm-codegen-hash-manifest.md @@ -1,8 +1,14 @@ # Migration: Java and Kotlin commit the codegen hash manifest +> **Since 1.3.0 the manifest is a directory, `.gen-state/.hashes/`, with one file per model +> package** (see [the per-package manifest migration](per-package-hash-manifest.md)). Read +> `.hashes.json` below as that directory; the first `gen` after upgrading converts it. The +> commands and ignore rule below already name the directory: a repo-level ignore that still +> un-ignores only `.hashes.json` ignores `.hashes/`, and nothing warns you. + **Changed in:** Maven 8.1.0 (npm, PyPI and NuGet 1.1.0) · **Ports affected:** Java and Kotlin -**Automatic fix:** the first `mvn metaobjects:generate` run does it; you commit one file per -module. Decision record: +**Automatic fix:** the first `mvn metaobjects:generate` run does it; you commit the manifest +directory in each module. Decision record: [ADR-0060](https://github.com/metaobjectsdev/metaobjects/blob/main/spec/decisions/ADR-0060-jvm-codegen-hash-manifest.md). ## What changed @@ -16,10 +22,10 @@ From 8.1.0 the Java and Kotlin generators record every file they write in a comm manifest, the same one TypeScript, Python and C# use: ``` -/.metaobjects/.gen-state/.hashes.json +/.metaobjects/.gen-state/.hashes/.json ``` -It maps each generated file's module-relative path to the SHA-256 of what was written and +Each file maps each generated file's module-relative path to the SHA-256 of what was written and to its owner: the generator that wrote it (its registry id, or the class name of a generator of your own) and that generator's output directory within the module: @@ -49,21 +55,21 @@ With it: writes fresh output and records it. It deletes nothing. It prints one notice: ``` - mvn metaobjects:generate: created the codegen hash manifest `.metaobjects/.gen-state/.hashes.json` and adopted N existing generated file(s) into it. Commit it: ... + mvn metaobjects:generate: created the codegen hash manifest `.metaobjects/.gen-state/.hashes/` and adopted N existing generated file(s) into it. Commit it: ... ``` 2. Commit the manifest, in every module that runs the plugin: ```bash - git add .metaobjects/.gen-state/.hashes.json + git add .metaobjects/.gen-state/.hashes/ git commit -m "chore: commit the codegen hash manifest" ``` - If a `.gitignore` excludes `.metaobjects/` or `.gen-state/`, re-include the one file: + If a `.gitignore` excludes `.metaobjects/` or `.gen-state/`, re-include the directory: ```gitignore .metaobjects/.gen-state/* - !.metaobjects/.gen-state/.hashes.json + !.metaobjects/.gen-state/.hashes/ ``` Exclude the directory's contents (`.gen-state/*`), not the directory itself: git does not diff --git a/docs/features/migrations/per-package-hash-manifest.md b/docs/features/migrations/per-package-hash-manifest.md new file mode 100644 index 0000000000..4dd89fa700 --- /dev/null +++ b/docs/features/migrations/per-package-hash-manifest.md @@ -0,0 +1,43 @@ +# Migration: the hash manifest is one file per package + +**Applies to:** every project that commits `.metaobjects/.gen-state/.hashes.json`, in every +port. **Action required:** run `gen` once and commit the result. + +## What changed + +The manifest that records what `gen` wrote was one file for the whole project, so any two +branches that regenerated anything conflicted on it, even when they touched different +packages. It is now a directory, `.metaobjects/.gen-state/.hashes/`, with one file per model +package: + +``` +.metaobjects/.gen-state/.hashes/acme.shop.json +.metaobjects/.gen-state/.hashes/acme.crm.json +.metaobjects/.gen-state/.hashes/.root.json # generated paths in no package +``` + +A package file is named by the package's `::` segments joined with `.`. A byte outside +`[A-Za-z0-9_-]` is written as `%XX`. Keys are sorted and each file ends with a newline. A +file is placed by the node the entry records, else by the model object its name starts with +(by words: `OrderLine.cs` and `order_line.py` both belong to `OrderLine`), else where it +already was, else in `.root.json`. Two branches that change generated files in different +packages now change different files, and merge without a conflict. + +## What you do + +1. Upgrade, then run your usual `gen` (`meta gen`, `dotnet meta gen`, `mvn + metaobjects:generate`, `metaobjects gen` or `cargo meta gen`). It reads the old file, + writes the package files, deletes `.hashes.json`, and adds `!.gen-state/.hashes/` to + `.metaobjects/.gitignore` when that file ignores `.gen-state/*`. +2. Commit the new directory and the deleted file. + +If your ignore rules live elsewhere (a root `.gitignore` that excludes +`.metaobjects/.gen-state/`), un-ignore `.gen-state/.hashes/` the way you un-ignored the old +file. `meta verify` names the rule that is in force. + +A script that read `.hashes.json` directly should read every `*.json` in the directory and +merge them. A path appears in exactly one file, and readers find it wherever it is, so a +misplaced entry costs a merge conflict and nothing else. + +A run that only verifies (`verify --codegen`) never converts the manifest; the first `gen` +does. diff --git a/docs/features/migrations/upgrading-1.0-to-1.1.md b/docs/features/migrations/upgrading-1.0-to-1.1.md index 64b0b34e21..7a6721c23c 100644 --- a/docs/features/migrations/upgrading-1.0-to-1.1.md +++ b/docs/features/migrations/upgrading-1.0-to-1.1.md @@ -1,5 +1,9 @@ # Upgrading from 1.0 to 1.1 (1.0.x → 1.1.0) +> **Since 1.3.0 the manifest is a directory, `.metaobjects/.gen-state/.hashes/`, with one file per +> model package** (see [the per-package manifest migration](per-package-hash-manifest.md)). Read +> `.hashes.json` below as that directory; the first `gen` after upgrading converts it. + This is the one page for moving a project from any 1.0.x release to 1.1.0 (npm, PyPI and NuGet `1.1.0`; Maven Central `8.1.0`). It lists the steps in order and every change that needs something from you, per port, each with its fix. The per-change detail is in `CHANGELOG.md` @@ -56,7 +60,7 @@ skip them, so read the whole list before you regenerate. 3 and 4 are done: a bare cross-package `extends` now fails with `ERR_UNRESOLVED_SUPER`, and the message names the spelling to write (see "References and `extends`"). 6. **Java and Kotlin: let `mvn metaobjects:generate` write the hash manifest, then commit - `.metaobjects/.gen-state/.hashes.json`** in every module (see "JVM hash manifest"). + `.metaobjects/.gen-state/.hashes/`** in every module (see "JVM hash manifest"). 7. **Resync the generators you own.** `meta eject --list` (TypeScript; `metaobjects gen --list` in Python, which has no `eject --list`; `dotnet meta gen --list`, `mvn metaobjects:eject -Dlist=true` in the other ports) @@ -121,7 +125,7 @@ that records the existing pages: [docs-are-generators.md](docs-are-generators.md ### JVM hash manifest (Java and Kotlin) -`mvn metaobjects:generate` records what it writes in `.metaobjects/.gen-state/.hashes.json`, +`mvn metaobjects:generate` records what it writes in `.metaobjects/.gen-state/.hashes/`, the committed manifest the other ports already use, and decides overwrites from it. An edited generated file is refused by name (1.0 overwrote it), and a file no generator emits any more is deleted. The first run adopts your existing generated files and tells you to commit the diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 273d1ee3cd..cbc55b7a96 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -453,7 +453,7 @@ are in: they touch the same lines. - **Anywhere else** — a fresh clone, a teammate's checkout, CI — the snapshot bodies are gitignored and absent, so there is nothing to merge against. What *is* committed is - `.gen-state/.hashes.json`, one hash per generated path. That is enough to tell a file + `.gen-state/.hashes/`, one hash per generated path. That is enough to tell a file nobody has touched (safe to regenerate) from one carrying an edit, and an edited file is **refused with its path named** rather than overwritten. On TypeScript, Python and C# a refusal fails the run (exit 1); on Java and Kotlin it is a warning. @@ -513,7 +513,7 @@ forbids renaming it, so the body has to stay where it is. **Java and Kotlin decide from the same committed hash manifest (since 8.1.0, ADR-0060).** Generated **source** on these ports, the code MetaObjects authors, goes through `GeneratedFileWriter`, which records every file it writes in -`/.metaobjects/.gen-state/.hashes.json`, the same file as the other +`/.metaobjects/.gen-state/.hashes/`, the same file as the other ports. Two executions in one module share it: each entry the JVM writes names the generator and output directory that wrote it, and a run never deletes a file another configured generator owns, even in an output directory they share; two modules have two manifests. A file that still hashes to its record is @@ -582,7 +582,7 @@ Neither write could reach disk, so there is no order-dependent output to report failing the build there would punish exactly the person the refusal exists to protect. Restore the file to generated output and the collision is raised again on the next run. -Keep `.gen-state/.hashes.json` committed. Ignoring it is what turns the second case into +Keep `.gen-state/.hashes/` committed. Ignoring it is what turns the second case into a silent overwrite, since a machine with neither a snapshot nor a hash cannot tell your edit from its own output. @@ -599,7 +599,7 @@ handles those files by one rule: out, deletes nothing, because the files of the part it skipped would all look stale. So does `--baseline=adopt`, which writes nothing by definition. - **A candidate is a file the manifest says `gen` wrote.** It lies under an output directory - of the run, `.metaobjects/.gen-state/.hashes.json` records writing it, and no generator + of the run, `.metaobjects/.gen-state/.hashes/` records writing it, and no generator emitted it this run. A file the manifest does not record is not generated output, whatever its name or header, and is never a candidate. In TypeScript a full `meta gen` covers every declared output directory (`outDir` and each `targets.*.outDir`), whether or not a @@ -675,7 +675,7 @@ regenerate, which would change nothing. A project whose manifest records nothing first run, before anything is committed) has no evidence either way, so the gate reports every extra file plainly and `gen` deletes none. -Keep `.hashes.json` committed: it is the only record that says which files in an output +Keep `.hashes/` committed: it is the only record that says which files in an output directory `gen` wrote, so without it a clean clone can neither delete a stale file nor protect an edited one. @@ -763,7 +763,7 @@ the pointer is good advice — but nothing in the toolchain implements it, and i knowing exactly what that means: - **It is safe, but not because of its name.** `meta gen` writes only the paths it records - in `.gen-state/.hashes.json`, and the orphan sweep deletes only from that same set. Any + in `.gen-state/.hashes/`, and the orphan sweep deletes only from that same set. Any file you create in the output directory is untouched, whatever you call it. Renaming `Order.extra.ts` to `order-helpers.ts` changes nothing. - **The generated barrel does not re-export it.** `index.ts` carries one diff --git a/docs/llms/llms-full.txt b/docs/llms/llms-full.txt index f2870454c2..cd040daba1 100644 --- a/docs/llms/llms-full.txt +++ b/docs/llms/llms-full.txt @@ -65,7 +65,7 @@ Reference generators you own, ejectable in every port. They emit per-language co - C#: EF Core + ASP.NET (.NET 8). **Keep your EF model:** an object declared with no `source.rdb` generates a POCO with DataAnnotations and no EF mapping, a contract separate from your entities - Python: Pydantic + FastAPI (Python 3.11+). **Keep your ORM:** the `entity` generator writes Pydantic models with no ORM of any kind -Hand-edit-preserving regeneration is **TypeScript-only**: `meta gen` three-way-merges your edits into regenerated output on the machine that generated the file. C#, Python, Java and Kotlin do not merge. Each decides from a committed hash manifest (`.metaobjects/.gen-state/.hashes.json`): a file that still matches what the generator wrote is overwritten, an edited one is refused by name (Java and Kotlin can be told to replace it with `handEdits=overwrite`), and `eject` hands you the generator to own instead. +Hand-edit-preserving regeneration is **TypeScript-only**: `meta gen` three-way-merges your edits into regenerated output on the machine that generated the file. C#, Python, Java and Kotlin do not merge. Each decides from a committed hash manifest (`.metaobjects/.gen-state/.hashes/`): a file that still matches what the generator wrote is overwritten, an edited one is refused by name (Java and Kotlin can be told to replace it with `handEdits=overwrite`), and `eject` hands you the generator to own instead. `gen` skips a run when nothing changed (ADR-0064). Before it renders anything, it computes a key from the loaded model and everything the generators are built from. When the key matches the last successful run and every generated file still holds the bytes that run left, `gen` says so and writes nothing. `gen --force` (Maven: `-Dmetaobjects.force=true`) renders everything anyway. In CI, `verify --codegen` always renders and compares everything, so a key that missed an input is caught before it ships. A generator that reads something the key does not cover declares it (`inputs` in TypeScript), or sets `cache: false` so a run that includes it never skips. The skip rules are gated by the `codegen-skip-conformance` corpus (`fixtures/codegen-skip-conformance/`) in every port. M:N relationship codegen (FR-018) ships in all five ports: entity navigation, idiomatic ORM wiring (Drizzle m2m / EF Core `UsingEntity` / Spring repo interface / Exposed / Pydantic), and REST traversal (`GET //{id}/`). diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index e72a40b341..3f1e6653b4 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -10,7 +10,7 @@ built for earlier runtimes. ## Regeneration and hand edits `dotnet meta gen` has no three-way merge (that is TypeScript-only). It decides per file from a -committed hash manifest, `.metaobjects/.gen-state/.hashes.json`: a file that still matches what +committed hash manifest, `.metaobjects/.gen-state/.hashes/`: a file that still matches what the generator wrote is overwritten, and an edited one is refused by name. To change what a generator emits, `dotnet meta eject ` copies it into `codegen/generators/` for you to own. Commit the manifest. diff --git a/docs/ports/java.md b/docs/ports/java.md index ec7540a879..452f8f8c0d 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -27,7 +27,7 @@ Prompt / template drift is still checked via the `metaobjects-render` `Verify` A ## Regeneration and hand edits There is no three-way merge on the JVM (that is TypeScript-only). `mvn metaobjects:generate` -records each file it writes in `.metaobjects/.gen-state/.hashes.json`: a file that still matches +records each file it writes in `.metaobjects/.gen-state/.hashes/`: a file that still matches is overwritten, and an edited one is refused by name (`keep`, the default) or replaced (`overwrite`). `mvn metaobjects:eject -Dnames=` copies a generator into your repo to own. Commit the manifest. Details: diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index 34ba5779db..c8ea1b98c0 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -26,7 +26,7 @@ Two modules: There is no three-way merge on the JVM (that is TypeScript-only). Kotlin runs through the same `mvn metaobjects:generate` write path as Java: a file that still matches the committed hash -manifest (`.metaobjects/.gen-state/.hashes.json`) is overwritten, and an edited one is refused by +manifest (`.metaobjects/.gen-state/.hashes/`) is overwritten, and an edited one is refused by name (or replaced with `overwrite`). `mvn metaobjects:eject -Dnames=` copies a generator into your repo to own. diff --git a/docs/ports/python.md b/docs/ports/python.md index b08c562d12..12f5c40b2e 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -14,7 +14,7 @@ Python port has no `migrate` command by design; it consumes the canonical ## Regeneration and hand edits `metaobjects gen` has no three-way merge (that is TypeScript-only). It decides per file from a -committed hash manifest, `.metaobjects/.gen-state/.hashes.json`: a file that still matches what +committed hash manifest, `.metaobjects/.gen-state/.hashes/`: a file that still matches what the generator wrote is overwritten, and an edited one is refused by name. To change what a generator emits, `metaobjects eject ` copies it into `codegen/generators/` for you to own. Commit the manifest. diff --git a/docs/ports/rust.md b/docs/ports/rust.md index eeb2b496e5..66f08010bb 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -41,7 +41,7 @@ cargo install --path /server/rust/metaobjects-cli | Command | What it does | |---|---| -| `cargo meta init [--project ]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes.json` committed) and a first `metaobjects/meta.app.yaml`. It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | +| `cargo meta init [--project ]` | Scaffolds `.metaobjects/config.json`, `.metaobjects/.gitignore` (which keeps `.gen-state/.hashes/` committed) and a first `metaobjects/meta.app.yaml`. It writes only what is missing, and never adds an empty metadata file to a project that already has metadata. | | `cargo meta gen [ENTITY...]` | Generates the crates. It skips the whole run when the model, the project config and the generators are unchanged ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)), writes only files whose bytes changed, removes a generated file nothing emits any more, and refuses to overwrite or delete a generated file that was edited by hand. It prints what it created, updated and removed, and the crates to re-check. | | `cargo meta verify [--codegen] [--full]` | The codegen drift gate: renders in memory, compares with disk, writes nothing, and exits 1 on drift, naming each file. Locally it may answer from the stored skip key; `--full`, or a set `CI` variable, always renders. `--codegen` is the only gate the port ships, so a bare `verify` runs it. `--db`, `--templates` and `--deps` exit 2 with the reason and where that check lives. | | `cargo meta eject ...` | Copies a shipped generator into the project to own. `--undo` takes back copies still identical to the shipped source; `--list` shows what can be ejected and how each owned copy compares. See [Owning a generator](#owning-a-generator). | diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index e2fa545f33..ae0af49d13 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -12,7 +12,7 @@ build), and Bun is simply the fastest dev workflow in this repo. Three-way merge is a TypeScript feature: on the machine that generated a file, `meta gen` merges your edits into regenerated output. On a fresh clone or in CI the snapshot bodies are not present, so an edited file is refused by name rather than merged (commit -`.metaobjects/.gen-state/.hashes.json`). The other ports do not merge at all. +`.metaobjects/.gen-state/.hashes/`). The other ports do not merge at all. ## Keep your ORM (Prisma, TypeORM, Drizzle you already have) diff --git a/docs/recipes/typed-client-for-the-reference-routes.md b/docs/recipes/typed-client-for-the-reference-routes.md index 3d2a973681..3fdf9a5dde 100644 --- a/docs/recipes/typed-client-for-the-reference-routes.md +++ b/docs/recipes/typed-client-for-the-reference-routes.md @@ -283,7 +283,7 @@ meta verify --codegen exit 1 ``` The client and the routes move together or the build fails. Commit -`.metaobjects/.gen-state/.hashes.json` so a fresh clone can tell a hand edit from stale output. +`.metaobjects/.gen-state/.hashes/` so a fresh clone can tell a hand edit from stale output. ## See also diff --git a/docs/recipes/write-your-own-generator.md b/docs/recipes/write-your-own-generator.md index 6ee8140f15..f9f077189d 100644 --- a/docs/recipes/write-your-own-generator.md +++ b/docs/recipes/write-your-own-generator.md @@ -391,7 +391,7 @@ generator as `ctx.renderContext?.apiPrefix`. `content` is the file as written — TypeScript, JSON, YAML, SQL, Markdown. No port formats it or adds a header for you. On TypeScript, C# and Python a header is optional: the write -decision uses the committed `.metaobjects/.gen-state/.hashes.json`, so a JSON file is +decision uses the committed `.metaobjects/.gen-state/.hashes/`, so a JSON file is protected like any other. On the JVM, `FileEmittingGenerator` routes a file whose content carries the `GENERATED` header comment through the ownership guard and writes a file that cannot carry one (JSON) as given. diff --git a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/.root.json b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/.root.json new file mode 100644 index 0000000000..89a7a6d206 --- /dev/null +++ b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/.root.json @@ -0,0 +1,3 @@ +{ + "src/generated/index.ts": "b542ee705d68fe1695f930a14bd7fb54bf8e89f4f0688aaba58b7df2c2fb29db" +} diff --git a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes.json b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json similarity index 97% rename from examples/advanced-modeling/.metaobjects/.gen-state/.hashes.json rename to examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json index 9380c9de35..c67f9bf9ad 100644 --- a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes.json +++ b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json @@ -109,6 +109,5 @@ "hash": "655f1fdd3c2f104fe48e8fb9a4147c3977a820f82e2b0a6ce1db8e4bd1b3ca2c", "generatedBy": "entity-file", "sourceNode": "acme::learn::SyllabusSection" - }, - "src/generated/index.ts": "b542ee705d68fe1695f930a14bd7fb54bf8e89f4f0688aaba58b7df2c2fb29db" + } } diff --git a/examples/advanced-modeling/.metaobjects/.gitignore b/examples/advanced-modeling/.metaobjects/.gitignore index fe926fbc91..8c12b0baef 100644 --- a/examples/advanced-modeling/.metaobjects/.gitignore +++ b/examples/advanced-modeling/.metaobjects/.gitignore @@ -1,9 +1,10 @@ # Gen-state bodies are a second full copy of all generated output — not worth -# committing. The MANIFEST is: `.hashes.json` is the only thing that lets -# `meta gen` tell "this file is exactly what I wrote" from "somebody edited -# this" on a machine that did not generate it (CLAUDE.md, Storage format). +# committing. The MANIFEST is: the `.hashes/` directory (one file per model +# package) is the only thing that lets `meta gen` tell "this file is exactly +# what I wrote" from "somebody edited this" on a machine that did not +# generate it (CLAUDE.md, Storage format). # # The glob matters. Git will not descend into an excluded DIRECTORY, so a # negation under `.gen-state/` can never apply — it has to be `.gen-state/*`. .gen-state/* -!.gen-state/.hashes.json +!.gen-state/.hashes/ diff --git a/examples/dynamic-grid/.metaobjects/.gen-state/.hashes.json b/examples/dynamic-grid/.metaobjects/.gen-state/.hashes/demo.workshop.json similarity index 100% rename from examples/dynamic-grid/.metaobjects/.gen-state/.hashes.json rename to examples/dynamic-grid/.metaobjects/.gen-state/.hashes/demo.workshop.json diff --git a/examples/dynamic-grid/.metaobjects/.gitignore b/examples/dynamic-grid/.metaobjects/.gitignore index fe926fbc91..8c12b0baef 100644 --- a/examples/dynamic-grid/.metaobjects/.gitignore +++ b/examples/dynamic-grid/.metaobjects/.gitignore @@ -1,9 +1,10 @@ # Gen-state bodies are a second full copy of all generated output — not worth -# committing. The MANIFEST is: `.hashes.json` is the only thing that lets -# `meta gen` tell "this file is exactly what I wrote" from "somebody edited -# this" on a machine that did not generate it (CLAUDE.md, Storage format). +# committing. The MANIFEST is: the `.hashes/` directory (one file per model +# package) is the only thing that lets `meta gen` tell "this file is exactly +# what I wrote" from "somebody edited this" on a machine that did not +# generate it (CLAUDE.md, Storage format). # # The glob matters. Git will not descend into an excluded DIRECTORY, so a # negation under `.gen-state/` can never apply — it has to be `.gen-state/*`. .gen-state/* -!.gen-state/.hashes.json +!.gen-state/.hashes/ diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes/.root.json b/examples/showcase/.metaobjects/.gen-state/.hashes/.root.json new file mode 100644 index 0000000000..ed3f44c020 --- /dev/null +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/.root.json @@ -0,0 +1,6 @@ +{ + "generated/csharp/AppDbContext.g.cs": "4d441b4283d074cd98d11385bd8c9a2294a9378d3b392b451aea3130b5d2ca28", + "generated/python/__init__.py": "daa04cec586768866d0996c779f62073e6773fe63750ff668327991fac2fd0f5", + "generated/ts/index.ts": "2c915565fd8711503dbcd0b0139c657bb927c7f0f502d8d2a8b51e026b257694", + "generated/ts/prompts.ts": "9eec821ec8cb6063f98b52b78ae1758cfd22c81a71cbb90b0555dee347a687af" +} diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes.json b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json similarity index 83% rename from examples/showcase/.metaobjects/.gen-state/.hashes.json rename to examples/showcase/.metaobjects/.gen-state/.hashes/acme.json index f4df6e4669..1c71c30927 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes/acme.json @@ -1,5 +1,4 @@ { - "generated/csharp/AppDbContext.g.cs": "4d441b4283d074cd98d11385bd8c9a2294a9378d3b392b451aea3130b5d2ca28", "generated/csharp/Subscriber.g.cs": "a7701fda82e3eb27dad5a01f326c0893ecd2ac418eea6e3afc5c4a2b81535bc2", "generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed", "generated/csharp/SubscriberFilterAllowlist.g.cs": "3839b04884e4e393d4f7d7bf4c7d4fe5b3852bd3a92b1ecb282cb8935a3c98e5", @@ -7,7 +6,6 @@ "generated/csharp/SubscriberRoutes.g.cs": "2a217ff5a37674ce5038802631b1d8fd90b22b9849e0288f7daf3bba7f9e862f", "generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762", "generated/python/SubscriberBlurbPayload.py": "a5ef8a08e63efbe0f73e39a21a368cff5150c68cc8beeea6e8aab0c755f8bbdd", - "generated/python/__init__.py": "daa04cec586768866d0996c779f62073e6773fe63750ff668327991fac2fd0f5", "generated/python/subscriber_filter_allowlist.py": "b0414cc95ff3982c80a0e1a06839f090c0b423e41f5a94275df93426cea09df5", "generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561", "generated/python/subscriber_router.py": "16502ff815bf9ae29c7dba4700d0465d06058a9fd7ea8db5f98334d52d284851", @@ -31,7 +29,5 @@ "generatedBy": "entity-file", "sourceNode": "acme::SubscriberBlurbPayload" }, - "generated/ts/index.ts": "2c915565fd8711503dbcd0b0139c657bb927c7f0f502d8d2a8b51e026b257694", - "generated/ts/prompts.ts": "9eec821ec8cb6063f98b52b78ae1758cfd22c81a71cbb90b0555dee347a687af", "generated/ts/requirements/subscriberCanBePausedWithoutErasingHistory.field.enum.test.ts": "a5d2494ce5340673da43f2ee3ef13d7505ee349724e8d85f377a84eafeea50ae" } diff --git a/examples/showcase/.metaobjects/.gitignore b/examples/showcase/.metaobjects/.gitignore index fe926fbc91..8c12b0baef 100644 --- a/examples/showcase/.metaobjects/.gitignore +++ b/examples/showcase/.metaobjects/.gitignore @@ -1,9 +1,10 @@ # Gen-state bodies are a second full copy of all generated output — not worth -# committing. The MANIFEST is: `.hashes.json` is the only thing that lets -# `meta gen` tell "this file is exactly what I wrote" from "somebody edited -# this" on a machine that did not generate it (CLAUDE.md, Storage format). +# committing. The MANIFEST is: the `.hashes/` directory (one file per model +# package) is the only thing that lets `meta gen` tell "this file is exactly +# what I wrote" from "somebody edited this" on a machine that did not +# generate it (CLAUDE.md, Storage format). # # The glob matters. Git will not descend into an excluded DIRECTORY, so a # negation under `.gen-state/` can never apply — it has to be `.gen-state/*`. .gen-state/* -!.gen-state/.hashes.json +!.gen-state/.hashes/ diff --git a/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes.json b/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes/.root.json similarity index 87% rename from examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes.json rename to examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes/.root.json index 2a66c5c029..fb2e37a5e5 100644 --- a/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes.json +++ b/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes/.root.json @@ -1,6 +1,5 @@ { "crates/tasks-axi-gen/Cargo.toml": "8264f393b6d8dc42a9aa7343d4db4b0e40aaf7d295860620c4fa563dee1190e1", - "crates/tasks-axi-gen/src/cli.rs": "9eae5b155001caf4ca344658087a4e73e080a4fa031726ea8c7de73626267cf0", "crates/tasks-axi-gen/src/dispatch.rs": "53c03673a89e480c6fe6324d4fc94f22b3f9117feb56613ac2fbd13dd9f60f3e", "crates/tasks-axi-gen/src/enums.rs": "6cefaacbe7536d636455fa71684f53e5ae2ca110fc0cf809f0d57c92e04548af", "crates/tasks-axi-gen/src/errors.rs": "b8c91ca62bca287aa0505ead5c9604bbbcec72a7aa90b4253febb1bd4a80a367", diff --git a/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes/tasksaxi.cli.json b/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes/tasksaxi.cli.json new file mode 100644 index 0000000000..840bcce3de --- /dev/null +++ b/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes/tasksaxi.cli.json @@ -0,0 +1,3 @@ +{ + "crates/tasks-axi-gen/src/cli.rs": "9eae5b155001caf4ca344658087a4e73e080a4fa031726ea8c7de73626267cf0" +} diff --git a/examples/tasks-axi-rust/.metaobjects/.gitignore b/examples/tasks-axi-rust/.metaobjects/.gitignore index fe926fbc91..8c12b0baef 100644 --- a/examples/tasks-axi-rust/.metaobjects/.gitignore +++ b/examples/tasks-axi-rust/.metaobjects/.gitignore @@ -1,9 +1,10 @@ # Gen-state bodies are a second full copy of all generated output — not worth -# committing. The MANIFEST is: `.hashes.json` is the only thing that lets -# `meta gen` tell "this file is exactly what I wrote" from "somebody edited -# this" on a machine that did not generate it (CLAUDE.md, Storage format). +# committing. The MANIFEST is: the `.hashes/` directory (one file per model +# package) is the only thing that lets `meta gen` tell "this file is exactly +# what I wrote" from "somebody edited this" on a machine that did not +# generate it (CLAUDE.md, Storage format). # # The glob matters. Git will not descend into an excluded DIRECTORY, so a # negation under `.gen-state/` can never apply — it has to be `.gen-state/*`. .gen-state/* -!.gen-state/.hashes.json +!.gen-state/.hashes/ diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md index 4ec8b55048..c30d6fc156 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -176,7 +176,7 @@ You run a `gen` step. The runner: 3. Runs each configured **generator** — most emit one file per entity; some emit a single shared file (a barrel, a DB-context, an app-config). 4. Decides whether it may overwrite a file, by a committed **hash manifest** - (`.metaobjects/.gen-state/.hashes.json`) on every port. If a file still hashes to what + (`.metaobjects/.gen-state/.hashes/`) on every port. If a file still hashes to what the generator recorded writing, it is safe to overwrite; if it was edited, or there is no record of it, the write is **refused by name**. TypeScript additionally three-way-merges against a snapshot when one is present locally. **Commit the @@ -189,7 +189,7 @@ You run a `gen` step. The runner: write). On Java and Kotlin a refusal is a warning and `mvn metaobjects:verify` is the gate that fails. The one-time fix for a project that predates the committed manifest is **`gen --baseline=adopt`**: it records the files you have as the baseline and writes - nothing, so there is finally a `.hashes.json` to commit — then `gen` again, and the + nothing, so there is finally a `.hashes/` to commit — then `gen` again, and the regeneration lands as its own diff. Adopting DECLARES those files to be generated output, so an edit already inside one is part of the baseline and that regeneration replaces it; commit before you run it. (TypeScript additionally has diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-verify/SKILL.md index 4ec6d5567a..c5f0d69812 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -152,7 +152,7 @@ with `ERR_DEPENDENCY_SNAPSHOT_STALE` naming the fix: run `meta deps sync`. regen) fails the build. Wire it into CI so a stale `@generated` file fails. **A hand edit inside a generated file is reported apart from drift** — `meta gen` three-way-merges hand edits by design, and the Node gate judges the *generated - contribution* against the committed `.metaobjects/.gen-state/.hashes.json`, not the + contribution* against the committed `.metaobjects/.gen-state/.hashes/`, not the bytes, then lists every generated file carrying a hand edit (count + paths). Whether that list fails the build is `verify.handEdits` in `.metaobjects/config.json`: `"fail"` exits 1 (what `meta init` writes for a new project), `"notice"` (and a diff --git a/fixtures/agent-context-conformance/csharp/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/csharp/expected/.metaobjects/AGENTS.md index 8022ea6a6f..f997451732 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/csharp/expected/.metaobjects/AGENTS.md @@ -54,7 +54,7 @@ is built (never before), a new node for new behaviour. - `npx meta verify --db ` (the live schema matches the metadata). Commit the metadata, the generated code, `.metaobjects/migrations/` and -`.metaobjects/.gen-state/.hashes.json`. +`.metaobjects/.gen-state/.hashes/`. ## Calling the generated REST API diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md index 4ec8b55048..c30d6fc156 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -176,7 +176,7 @@ You run a `gen` step. The runner: 3. Runs each configured **generator** — most emit one file per entity; some emit a single shared file (a barrel, a DB-context, an app-config). 4. Decides whether it may overwrite a file, by a committed **hash manifest** - (`.metaobjects/.gen-state/.hashes.json`) on every port. If a file still hashes to what + (`.metaobjects/.gen-state/.hashes/`) on every port. If a file still hashes to what the generator recorded writing, it is safe to overwrite; if it was edited, or there is no record of it, the write is **refused by name**. TypeScript additionally three-way-merges against a snapshot when one is present locally. **Commit the @@ -189,7 +189,7 @@ You run a `gen` step. The runner: write). On Java and Kotlin a refusal is a warning and `mvn metaobjects:verify` is the gate that fails. The one-time fix for a project that predates the committed manifest is **`gen --baseline=adopt`**: it records the files you have as the baseline and writes - nothing, so there is finally a `.hashes.json` to commit — then `gen` again, and the + nothing, so there is finally a `.hashes/` to commit — then `gen` again, and the regeneration lands as its own diff. Adopting DECLARES those files to be generated output, so an edit already inside one is part of the baseline and that regeneration replaces it; commit before you run it. (TypeScript additionally has diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md index 4ec6d5567a..c5f0d69812 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -152,7 +152,7 @@ with `ERR_DEPENDENCY_SNAPSHOT_STALE` naming the fix: run `meta deps sync`. regen) fails the build. Wire it into CI so a stale `@generated` file fails. **A hand edit inside a generated file is reported apart from drift** — `meta gen` three-way-merges hand edits by design, and the Node gate judges the *generated - contribution* against the committed `.metaobjects/.gen-state/.hashes.json`, not the + contribution* against the committed `.metaobjects/.gen-state/.hashes/`, not the bytes, then lists every generated file carrying a hand edit (count + paths). Whether that list fails the build is `verify.handEdits` in `.metaobjects/config.json`: `"fail"` exits 1 (what `meta init` writes for a new project), `"notice"` (and a diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/AGENTS.md index dffa83cffa..bfe7f2dba9 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/AGENTS.md @@ -66,7 +66,7 @@ is built (never before), a new node for new behaviour. - `npx meta verify --db ` (the live schema matches the metadata). Commit the metadata, the generated code, `.metaobjects/migrations/` and -`.metaobjects/.gen-state/.hashes.json`. +`.metaobjects/.gen-state/.hashes/`. ## Calling the generated REST API diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md index 4ec8b55048..c30d6fc156 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -176,7 +176,7 @@ You run a `gen` step. The runner: 3. Runs each configured **generator** — most emit one file per entity; some emit a single shared file (a barrel, a DB-context, an app-config). 4. Decides whether it may overwrite a file, by a committed **hash manifest** - (`.metaobjects/.gen-state/.hashes.json`) on every port. If a file still hashes to what + (`.metaobjects/.gen-state/.hashes/`) on every port. If a file still hashes to what the generator recorded writing, it is safe to overwrite; if it was edited, or there is no record of it, the write is **refused by name**. TypeScript additionally three-way-merges against a snapshot when one is present locally. **Commit the @@ -189,7 +189,7 @@ You run a `gen` step. The runner: write). On Java and Kotlin a refusal is a warning and `mvn metaobjects:verify` is the gate that fails. The one-time fix for a project that predates the committed manifest is **`gen --baseline=adopt`**: it records the files you have as the baseline and writes - nothing, so there is finally a `.hashes.json` to commit — then `gen` again, and the + nothing, so there is finally a `.hashes/` to commit — then `gen` again, and the regeneration lands as its own diff. Adopting DECLARES those files to be generated output, so an edit already inside one is part of the baseline and that regeneration replaces it; commit before you run it. (TypeScript additionally has diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-verify/SKILL.md index 4ec6d5567a..c5f0d69812 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -152,7 +152,7 @@ with `ERR_DEPENDENCY_SNAPSHOT_STALE` naming the fix: run `meta deps sync`. regen) fails the build. Wire it into CI so a stale `@generated` file fails. **A hand edit inside a generated file is reported apart from drift** — `meta gen` three-way-merges hand edits by design, and the Node gate judges the *generated - contribution* against the committed `.metaobjects/.gen-state/.hashes.json`, not the + contribution* against the committed `.metaobjects/.gen-state/.hashes/`, not the bytes, then lists every generated file carrying a hand edit (count + paths). Whether that list fails the build is `verify.handEdits` in `.metaobjects/config.json`: `"fail"` exits 1 (what `meta init` writes for a new project), `"notice"` (and a diff --git a/fixtures/agent-context-conformance/java-react/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/java-react/expected/.metaobjects/AGENTS.md index d65e4cf718..4e429eee00 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/java-react/expected/.metaobjects/AGENTS.md @@ -56,7 +56,7 @@ is built (never before), a new node for new behaviour. - `npx meta verify --db ` (the live schema matches the metadata). Commit the metadata, the generated code, `.metaobjects/migrations/` and -`.metaobjects/.gen-state/.hashes.json`. +`.metaobjects/.gen-state/.hashes/`. ## Calling the generated REST API diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md index 4ec8b55048..c30d6fc156 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -176,7 +176,7 @@ You run a `gen` step. The runner: 3. Runs each configured **generator** — most emit one file per entity; some emit a single shared file (a barrel, a DB-context, an app-config). 4. Decides whether it may overwrite a file, by a committed **hash manifest** - (`.metaobjects/.gen-state/.hashes.json`) on every port. If a file still hashes to what + (`.metaobjects/.gen-state/.hashes/`) on every port. If a file still hashes to what the generator recorded writing, it is safe to overwrite; if it was edited, or there is no record of it, the write is **refused by name**. TypeScript additionally three-way-merges against a snapshot when one is present locally. **Commit the @@ -189,7 +189,7 @@ You run a `gen` step. The runner: write). On Java and Kotlin a refusal is a warning and `mvn metaobjects:verify` is the gate that fails. The one-time fix for a project that predates the committed manifest is **`gen --baseline=adopt`**: it records the files you have as the baseline and writes - nothing, so there is finally a `.hashes.json` to commit — then `gen` again, and the + nothing, so there is finally a `.hashes/` to commit — then `gen` again, and the regeneration lands as its own diff. Adopting DECLARES those files to be generated output, so an edit already inside one is part of the baseline and that regeneration replaces it; commit before you run it. (TypeScript additionally has diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-verify/SKILL.md index 4ec6d5567a..c5f0d69812 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -152,7 +152,7 @@ with `ERR_DEPENDENCY_SNAPSHOT_STALE` naming the fix: run `meta deps sync`. regen) fails the build. Wire it into CI so a stale `@generated` file fails. **A hand edit inside a generated file is reported apart from drift** — `meta gen` three-way-merges hand edits by design, and the Node gate judges the *generated - contribution* against the committed `.metaobjects/.gen-state/.hashes.json`, not the + contribution* against the committed `.metaobjects/.gen-state/.hashes/`, not the bytes, then lists every generated file carrying a hand edit (count + paths). Whether that list fails the build is `verify.handEdits` in `.metaobjects/config.json`: `"fail"` exits 1 (what `meta init` writes for a new project), `"notice"` (and a diff --git a/fixtures/agent-context-conformance/python/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/python/expected/.metaobjects/AGENTS.md index 605df568b6..03f5afaab0 100644 --- a/fixtures/agent-context-conformance/python/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/python/expected/.metaobjects/AGENTS.md @@ -55,7 +55,7 @@ is built (never before), a new node for new behaviour. - `npx meta verify --db ` (the live schema matches the metadata). Commit the metadata, the generated code, `.metaobjects/migrations/` and -`.metaobjects/.gen-state/.hashes.json`. +`.metaobjects/.gen-state/.hashes/`. ## Calling the generated REST API diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md index 1929a98514..ce4485c972 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md @@ -24,7 +24,7 @@ Generated files carry the header: The header is **informational on this port** — the write decision never reads it. What the runner overwrites is decided by `.metaobjects/.gen-state/`: the snapshot body if the -machine has one (three-way merge), otherwise the committed `.hashes.json` (byte-for-byte +machine has one (three-way merge), otherwise the committed `.hashes/` (byte-for-byte what it wrote ⇒ overwrite; anything else ⇒ refused, exit 1). A sibling file you created (`.extra.ts` by convention) is never touched because it is not a path the runner records — not because of its name, and not because of the header. Locate generated output at the diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md index 4ec8b55048..c30d6fc156 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/SKILL.md @@ -176,7 +176,7 @@ You run a `gen` step. The runner: 3. Runs each configured **generator** — most emit one file per entity; some emit a single shared file (a barrel, a DB-context, an app-config). 4. Decides whether it may overwrite a file, by a committed **hash manifest** - (`.metaobjects/.gen-state/.hashes.json`) on every port. If a file still hashes to what + (`.metaobjects/.gen-state/.hashes/`) on every port. If a file still hashes to what the generator recorded writing, it is safe to overwrite; if it was edited, or there is no record of it, the write is **refused by name**. TypeScript additionally three-way-merges against a snapshot when one is present locally. **Commit the @@ -189,7 +189,7 @@ You run a `gen` step. The runner: write). On Java and Kotlin a refusal is a warning and `mvn metaobjects:verify` is the gate that fails. The one-time fix for a project that predates the committed manifest is **`gen --baseline=adopt`**: it records the files you have as the baseline and writes - nothing, so there is finally a `.hashes.json` to commit — then `gen` again, and the + nothing, so there is finally a `.hashes/` to commit — then `gen` again, and the regeneration lands as its own diff. Adopting DECLARES those files to be generated output, so an edit already inside one is part of the baseline and that regeneration replaces it; commit before you run it. (TypeScript additionally has diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md index 23651413e4..588e061158 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md @@ -314,16 +314,16 @@ npx meta gen Author Post # scope to named entities Generated files carry an `@generated by @metaobjectsdev/codegen-ts` header. It is **informational** — the write decision never reads it. `.metaobjects/.gen-state/` decides: the snapshot body if this machine has one (three-way merge), otherwise the -committed `.hashes.json` (byte-for-byte what it wrote ⇒ overwrite; anything else ⇒ +committed `.hashes/` (byte-for-byte what it wrote ⇒ overwrite; anything else ⇒ refused, path named, exit 1). So the merge is machine-local: a file you edited and pushed is REFUSED on a fresh clone or in CI, not merged. Recovery is in `docs/features/own-your-codegen.md`. A project with NO manifest at all (it predates the manifest being committed) is a different case with a different fix: every stale file refuses, and a run where everything -refuses writes no manifest — so "commit `.hashes.json`" has nothing to commit. Run +refuses writes no manifest — so "commit `.hashes/`" has nothing to commit. Run `meta gen --baseline=adopt` once: it records the files you have as the merge base and -writes nothing, leaving exactly one file to commit; the next `meta gen` is then the +writes nothing, leaving the manifest to commit; the next `meta gen` is then the regeneration, as its own reviewable diff. Adopting declares those files to BE generated output, so an edit already inside one is part of the base and that regeneration replaces it — `--baseline=fresh` + `git checkout` is the sequence that KEEPS an edit. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md index 4ec6d5567a..c5f0d69812 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-verify/SKILL.md @@ -152,7 +152,7 @@ with `ERR_DEPENDENCY_SNAPSHOT_STALE` naming the fix: run `meta deps sync`. regen) fails the build. Wire it into CI so a stale `@generated` file fails. **A hand edit inside a generated file is reported apart from drift** — `meta gen` three-way-merges hand edits by design, and the Node gate judges the *generated - contribution* against the committed `.metaobjects/.gen-state/.hashes.json`, not the + contribution* against the committed `.metaobjects/.gen-state/.hashes/`, not the bytes, then lists every generated file carrying a hand edit (count + paths). Whether that list fails the build is `verify.handEdits` in `.metaobjects/config.json`: `"fail"` exits 1 (what `meta init` writes for a new project), `"notice"` (and a diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/AGENTS.md index 356c218047..022cc22db3 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/AGENTS.md @@ -66,7 +66,7 @@ is built (never before), a new node for new behaviour. - `npx meta verify --db ` (the live schema matches the metadata). Commit the metadata, the generated code, `.metaobjects/migrations/` and -`.metaobjects/.gen-state/.hashes.json`. +`.metaobjects/.gen-state/.hashes/`. ## Calling the generated REST API diff --git a/fixtures/codegen-skip-conformance/README.md b/fixtures/codegen-skip-conformance/README.md index dcbdfd3ff3..0b47c0586e 100644 --- a/fixtures/codegen-skip-conformance/README.md +++ b/fixtures/codegen-skip-conformance/README.md @@ -24,3 +24,21 @@ The values: in full). - `verify`: `may-answer-no-drift` (a local `verify --codegen` may answer from the stored key and the manifest without rendering) or `must-render` (it must render and compare). + +## `manifests.json`: the hash manifest is one file per package + +[ADR-0064 Amendment 1](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md) replaces the +single `.metaobjects/.gen-state/.hashes.json` with one file per model package under `.hashes/`. The +vectors in `manifests.json` are run by each port's manifest unit tests, beside the cases above: + +- `fileNames`: a package's manifest file name (`null` is the root manifest, `.root.json`). +- `placement`: for the loaded `objects`, which manifest a recorded path (and its entry) is filed + under: the `sourceNode` rule first, then the stem rule, else the root. +- `legacySplit`: a legacy `.hashes.json` is split into exactly `files` (parsed content; `goldenText` + is one file's bytes in full), the legacy file is removed, and a second identical write changes no + file. `gitignoreBefore` becomes `gitignoreAfter`; a file that already holds the new line, or has no + `.gen-state/*` rule, is left alone. + +A port's tests also assert what the vectors cannot: two writes that change entries in two packages +change two files and no third, a save that changes nothing writes nothing, a package that loses its +last entry loses its file, and a read-only command migrates nothing. diff --git a/fixtures/codegen-skip-conformance/cases.json b/fixtures/codegen-skip-conformance/cases.json index dde4de25e4..3d337503ca 100644 --- a/fixtures/codegen-skip-conformance/cases.json +++ b/fixtures/codegen-skip-conformance/cases.json @@ -110,6 +110,12 @@ "gen": "regenerate", "verify": "must-render" }, + { + "id": "legacy-manifest", + "change": "The manifest is put back in its pre-1.3.0 form: every file in .hashes/ is merged into one .hashes.json and the directory is removed (ADR-0064 Amendment 1). The next write run splits it again, so gen does not skip.", + "gen": "regenerate", + "verify": "may-answer-no-drift" + }, { "id": "generated-file-deleted", "change": "A file the manifest records is deleted.", diff --git a/fixtures/codegen-skip-conformance/manifests.json b/fixtures/codegen-skip-conformance/manifests.json new file mode 100644 index 0000000000..ed5b57ff50 --- /dev/null +++ b/fixtures/codegen-skip-conformance/manifests.json @@ -0,0 +1,281 @@ +{ + "$comment": "ADR-0064 Amendment 1. Every port with hash state runs these vectors against its own manifest store: fileNames (a package's manifest file name), placement (which manifest a path is filed under, given the loaded objects) and legacySplit (a legacy .hashes.json becomes these package files, byte for byte, and is removed). 'package': null is the root manifest (.root.json). A manifest file's text is the object with keys sorted, two-space indentation and a trailing newline ('goldenText' is one file in full).", + "version": 1, + "objects": [ + { + "name": "Order", + "package": "acme::shop" + }, + { + "name": "OrderLine", + "package": "acme::lines" + }, + { + "name": "Customer", + "package": "acme::crm" + }, + { + "name": "Invoice", + "package": "acme::billing" + }, + { + "name": "Item", + "package": "acme::shop" + }, + { + "name": "Item", + "package": "acme::crm" + }, + { + "name": "Widget", + "package": "" + }, + { + "name": "URLMap", + "package": "acme::web" + } + ], + "fileNames": [ + { + "package": "acme::shop", + "file": "acme.shop.json" + }, + { + "package": "acme", + "file": "acme.json" + }, + { + "package": "acme::shop-v2", + "file": "acme.shop-v2.json" + }, + { + "package": "Acme::Shop", + "file": "Acme.Shop.json" + }, + { + "package": "a b", + "file": "a%20b.json" + }, + { + "package": "acme::shöp", + "file": "acme.sh%C3%B6p.json" + }, + { + "package": "acme::a.b", + "file": "acme.a%2Eb.json" + }, + { + "package": null, + "file": ".root.json" + } + ], + "placement": [ + { + "path": "gen/acme/shop/Order.ts", + "package": "acme::shop", + "why": "stem equals an object name" + }, + { + "path": "gen/Order.hooks.ts", + "package": "acme::shop", + "why": "the stem stops at the first dot" + }, + { + "path": "gen/Order.generated.v2.ts", + "package": "acme::shop", + "why": "still the first dot" + }, + { + "path": "gen/OrderDto.java", + "package": "acme::shop", + "why": "the rest of the stem is more words" + }, + { + "path": "gen/Order_v2.ts", + "package": "acme::shop", + "why": "'_' ends a word" + }, + { + "path": "gen/OrderLineDto.java", + "package": "acme::lines", + "why": "the match with the most words wins" + }, + { + "path": "gen/OrderLine.ts", + "package": "acme::lines" + }, + { + "path": "gen/Ordered.ts", + "package": null, + "why": "'ordered' is one word, not 'order' and 'ed'" + }, + { + "path": "gen/order.hooks.ts", + "package": "acme::shop", + "why": "words match without regard to case" + }, + { + "path": "gen/Order/index.ts", + "package": null, + "why": "only the base name counts, and 'index' matches no object" + }, + { + "path": "gen/Item.ts", + "package": null, + "why": "the longest name is declared in two packages" + }, + { + "path": "gen/Widget.ts", + "package": null, + "why": "an object in no package has no package manifest" + }, + { + "path": "gen/index.ts", + "package": null, + "why": "a file of the whole model" + }, + { + "path": "gen/index.ts", + "package": "acme::crm", + "entry": { + "hash": "h", + "generatedBy": "entity", + "sourceNode": "acme::crm::Customer" + }, + "why": "a sourceNode wins over the stem" + }, + { + "path": "gen/Order.ts", + "package": "acme::crm", + "entry": { + "hash": "h", + "generatedBy": "entity", + "sourceNode": "acme::crm::Customer" + }, + "why": "a sourceNode wins even when the stem names another object" + }, + { + "path": "gen/Order.ts", + "package": "acme::shop", + "entry": { + "hash": "h", + "generatedBy": "entity", + "sourceNode": "acme::shop::Order.id" + }, + "why": "a sourceNode stops at its first dot" + }, + { + "path": "gen/Order.ts", + "package": null, + "entry": { + "hash": "h", + "generatedBy": "entity", + "sourceNode": "Widget" + }, + "why": "a sourceNode with no '::' is an object in no package" + }, + { + "path": "gen/Order.ts", + "package": "acme::shop", + "entry": { + "hash": "h", + "generator": "java:dto", + "outputDir": "gen" + }, + "why": "owner fields are not provenance: the stem decides" + }, + { + "path": "gen/order_line.py", + "package": "acme::lines", + "why": "a snake_case stem matches a PascalCase name" + }, + { + "path": "gen/order_line_dto.py", + "package": "acme::lines", + "why": "more words after the match" + }, + { + "path": "gen/order.py", + "package": "acme::shop", + "why": "a one-word snake_case stem" + }, + { + "path": "gen/order_names.py", + "package": "acme::shop", + "why": "the match with the most words wins: 'order' has no 'order_names'" + }, + { + "path": "gen/order-line.hooks.ts", + "package": "acme::lines", + "why": "'-' ends a word" + }, + { + "path": "gen/orders.py", + "package": null, + "why": "'orders' is one word, not 'order' and 's'" + }, + { + "path": "gen/url_map.py", + "package": "acme::web", + "why": "an acronym name matches its snake_case stem" + }, + { + "path": "gen/URLMap.cs", + "package": "acme::web", + "why": "a run of capitals ends before the last one when a lowercase letter follows" + }, + { + "path": "gen/Order2.ts", + "package": null, + "why": "digits stay with the word before them: 'order2' is one word" + } + ], + "legacySplit": { + "legacy": { + "gen/Customer.ts": { + "hash": "h3", + "generatedBy": "entity", + "sourceNode": "acme::crm::Customer" + }, + "gen/Invoice.ts": "h5", + "gen/Order.ts": "h1", + "gen/OrderDto.java": { + "hash": "h2", + "generator": "java:dto", + "outputDir": "gen" + }, + "gen/OrderLine.ts": "h6", + "gen/index.ts": "h4" + }, + "files": { + ".root.json": { + "gen/index.ts": "h4" + }, + "acme.shop.json": { + "gen/Order.ts": "h1", + "gen/OrderDto.java": { + "hash": "h2", + "generator": "java:dto", + "outputDir": "gen" + } + }, + "acme.crm.json": { + "gen/Customer.ts": { + "hash": "h3", + "generatedBy": "entity", + "sourceNode": "acme::crm::Customer" + } + }, + "acme.billing.json": { + "gen/Invoice.ts": "h5" + }, + "acme.lines.json": { + "gen/OrderLine.ts": "h6" + } + }, + "goldenFile": "acme.shop.json", + "goldenText": "{\n \"gen/Order.ts\": \"h1\",\n \"gen/OrderDto.java\": {\n \"hash\": \"h2\",\n \"generator\": \"java:dto\",\n \"outputDir\": \"gen\"\n }\n}\n", + "gitignoreBefore": ".gen-state/*\n!.gen-state/.hashes.json\n", + "gitignoreAfter": ".gen-state/*\n!.gen-state/.hashes/\n" + } +} diff --git a/server/csharp/MetaObjects.Cli.Tests/GenCommandTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenCommandTests.cs index faa67858e7..ad047f338b 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenCommandTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenCommandTests.cs @@ -56,11 +56,11 @@ public void Gen_writes_the_hash_manifest_beside_the_metadata_not_in_cwd() Assert.True(outcome.Ok, string.Join("; ", outcome.LoadErrors)); Assert.True( - File.Exists(Path.Combine(_tmp, ".metaobjects", ".gen-state", ".hashes.json")), + Directory.Exists(Path.Combine(_tmp, ".metaobjects", ".gen-state", ".hashes")), "expected the manifest beside the project's metaobjects/ dir"); Assert.False( - File.Exists(Path.Combine( - Directory.GetCurrentDirectory(), ".metaobjects", ".gen-state", ".hashes.json")), + Directory.Exists(Path.Combine( + Directory.GetCurrentDirectory(), ".metaobjects", ".gen-state", ".hashes")), "gen must not scatter .metaobjects/ into the current working directory"); } @@ -83,6 +83,6 @@ public void Gen_baseline_adopt_records_without_writing() Assert.True(outcome.Ok); Assert.Equal(onDisk, File.ReadAllText(stale)); // not one byte written Assert.Contains(outcome.Result!.Files, f => f.Status == "adopted"); - Assert.True(File.Exists(Path.Combine(_tmp, ".metaobjects", ".gen-state", ".hashes.json"))); + Assert.True(Directory.Exists(Path.Combine(_tmp, ".metaobjects", ".gen-state", ".hashes"))); } } diff --git a/server/csharp/MetaObjects.Cli.Tests/GenEntitiesSelectionTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenEntitiesSelectionTests.cs index a953e7e49a..f170288592 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenEntitiesSelectionTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenEntitiesSelectionTests.cs @@ -13,7 +13,9 @@ public sealed class GenEntitiesSelectionTests : IDisposable private readonly string _tmp = Path.Combine(Path.GetTempPath(), "meta-entities-" + Guid.NewGuid().ToString("N")); private string MetaDir => Path.Combine(_tmp, "metaobjects"); private string OutDir => Path.Combine(_tmp, "generated"); - private string Manifest => Path.Combine(_tmp, ".metaobjects", ".gen-state", ".hashes.json"); + private string ManifestText() => string.Concat( + Directory.GetFiles(Path.Combine(_tmp, ".metaobjects", ".gen-state", ".hashes"), "*.json").Order(StringComparer.Ordinal) + .Select(File.ReadAllText)); private static string Entity(string name, string table) => $$$""" { "object.entity": { "name": "{{{name}}}", "children": [ @@ -120,7 +122,7 @@ public void A_narrowed_run_neither_deletes_nor_forgets_the_unselected_files() { Assert.Equal(0, Gen().ExitCode); var widget = Read("Widget.g.cs"); - var manifestBefore = File.ReadAllText(Manifest); + var manifestBefore = ManifestText(); Assert.Contains("Widget.g.cs", manifestBefore); // Metadata drops Widget: a full run would sweep its files, a narrowed one must not. @@ -131,7 +133,7 @@ public void A_narrowed_run_neither_deletes_nor_forgets_the_unselected_files() Assert.True(exit == 0, $"exit={exit}\n{stdout}\n{stderr}"); Assert.Equal(widget, Read("Widget.g.cs")); Assert.DoesNotContain("removed:", stdout); - var manifestAfter = File.ReadAllText(Manifest); + var manifestAfter = ManifestText(); Assert.Contains("Widget.g.cs", manifestAfter); Assert.Contains("WidgetNames.g.cs", manifestAfter); Assert.Contains("Supplier.g.cs", manifestAfter); diff --git a/server/csharp/MetaObjects.Cli.Tests/GenRefusalExitCodeTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenRefusalExitCodeTests.cs index 798af77299..be2a889a29 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenRefusalExitCodeTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenRefusalExitCodeTests.cs @@ -64,7 +64,7 @@ public void A_refused_file_fails_the_run_and_baseline_adopt_clears_it() Assert.Equal(0, adoptRun.ExitCode); Assert.Equal(onDisk, File.ReadAllText(stale)); // adopting writes nothing either - Assert.True(File.Exists(Path.Combine(_tmp, ".metaobjects", ".gen-state", ".hashes.json"))); + Assert.True(Directory.Exists(Path.Combine(_tmp, ".metaobjects", ".gen-state", ".hashes"))); } [Fact] diff --git a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs index ebf0bd42af..6d618d9a03 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs @@ -154,6 +154,7 @@ public void The_case_table_decides_gen_and_verify(string id, string gen, string string[] more = []; string? ci = null; + var legacy = false; switch (id) { case "no-change": break; @@ -212,6 +213,17 @@ public void The_case_table_decides_gen_and_verify(string id, string gen, string case "fingerprint-missing": File.Delete(FingerprintPath()); break; case "force": more = ["--force"]; break; case "ci": ci = "true"; break; + case "legacy-manifest": + // Back to the pre-1.3.0 form: every file in .hashes/ merged into one .hashes.json, the directory removed. + var merged = new SortedDictionary(StringComparer.Ordinal); + foreach (var f in Directory.GetFiles(P(".metaobjects/.gen-state/.hashes"), "*.json")) + foreach (var kv in System.Text.Json.JsonSerializer.Deserialize>(File.ReadAllText(f))!) + merged[kv.Key] = kv.Value; + File.WriteAllText(P(".metaobjects/.gen-state/.hashes.json"), + System.Text.Json.JsonSerializer.Serialize(merged, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }) + "\n"); + Directory.Delete(P(".metaobjects/.gen-state/.hashes"), recursive: true); + legacy = true; + break; case "failed-run": var good = File.ReadAllText(P("metaobjects/meta.order.json")); File.WriteAllText(P("metaobjects/meta.order.json"), "{ not json"); @@ -224,15 +236,25 @@ public void The_case_table_decides_gen_and_verify(string id, string gen, string // verify first: it changes nothing. gen second: a regenerate stores a new key. Assert.Equal(verify, VerifyDecision(declared, more, ci)); + if (legacy) + { + // verify is read-only: it migrates nothing. + Assert.True(File.Exists(P(".metaobjects/.gen-state/.hashes.json"))); + Assert.False(Directory.Exists(P(".metaobjects/.gen-state/.hashes"))); + } Assert.Equal(gen, GenDecision(declared, more)); + if (legacy) + { + Assert.False(File.Exists(P(".metaobjects/.gen-state/.hashes.json"))); + Assert.NotEmpty(Directory.GetFiles(P(".metaobjects/.gen-state/.hashes"), "*.json")); + } } [Fact] public void A_skipped_gen_renders_nothing_and_leaves_every_file_and_the_key_untouched() { Assert.Equal(0, RunGen(Declared()).Exit); - var manifest = P(".metaobjects/.gen-state/.hashes.json"); - var files = Directory.GetFiles(OutDir).Append(manifest).Append(FingerprintPath()).ToList(); + var files = Directory.GetFiles(OutDir).Concat(Directory.GetFiles(P(".metaobjects/.gen-state/.hashes"))).Append(FingerprintPath()).ToList(); var stamp = DateTime.UtcNow.AddHours(-2); foreach (var f in files) File.SetLastWriteTimeUtc(f, stamp); diff --git a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs new file mode 100644 index 0000000000..df0fa80adf --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs @@ -0,0 +1,262 @@ +// ADR-0064 Amendment 1: the hash manifest is one file per model package. Runs the shared vectors +// (fixtures/codegen-skip-conformance/manifests.json) against this port's manifest store, and asserts +// what the vectors cannot: file-level separation, write-only-what-changed, and read-only loads. + +using System.Text.Json; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class HashManifestPerPackageTests : IDisposable +{ + private readonly string _root = Path.Combine( + Environment.GetEnvironmentVariable("DEV_SCRATCH") is { Length: > 0 } s ? s : Path.GetTempPath(), + "mo-pkg-hash-" + Guid.NewGuid().ToString("N")); + + private string StateDir => Path.Combine(_root, ".metaobjects", ".gen-state"); + private string HashesDir => Path.Combine(StateDir, ".hashes"); + + public void Dispose() { try { Directory.Delete(_root, recursive: true); } catch { } } + + private static JsonElement Vectors() + { + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) + { + var p = Path.Combine(dir.FullName, "fixtures", "codegen-skip-conformance", "manifests.json"); + if (File.Exists(p)) return JsonDocument.Parse(File.ReadAllText(p)).RootElement.Clone(); + } + throw new InvalidOperationException("manifests.json not found"); + } + + private static List VectorObjects(JsonElement v) => + v.GetProperty("objects").EnumerateArray() + .Select(o => new HashManifest.ManifestObject(o.GetProperty("name").GetString()!, o.GetProperty("package").GetString()!)) + .ToList(); + + private static string? Str(JsonElement e, string name) => + e.TryGetProperty(name, out var p) && p.ValueKind == JsonValueKind.String ? p.GetString() : null; + + [Fact] + public void FileNames_match_the_vectors() + { + foreach (var c in Vectors().GetProperty("fileNames").EnumerateArray()) + Assert.Equal(c.GetProperty("file").GetString(), HashManifest.FileNameFor(Str(c, "package"))); + } + + [Fact] + public void Placement_matches_the_vectors() + { + var v = Vectors(); + var objects = VectorObjects(v); + foreach (var c in v.GetProperty("placement").EnumerateArray()) + { + JsonElement? entry = c.TryGetProperty("entry", out var e) ? e : null; + Assert.Equal( + HashManifest.FileNameFor(Str(c, "package")), + HashManifest.PlaceFile(c.GetProperty("path").GetString()!, entry, objects)); + } + } + + + [Fact] + public void LegacySplit_matches_the_vectors() + { + var split = Vectors().GetProperty("legacySplit"); + var objects = VectorObjects(Vectors()); + Directory.CreateDirectory(StateDir); + File.WriteAllText(Path.Combine(StateDir, ".hashes.json"), split.GetProperty("legacy").GetRawText()); + var ignore = Path.Combine(_root, ".metaobjects", ".gitignore"); + File.WriteAllText(ignore, split.GetProperty("gitignoreBefore").GetString()); + + using (var batch = HashManifest.Batch(StateDir, objects)) + { + Assert.True(HashManifest.HasLegacy(StateDir)); + // A session over a legacy manifest saves even when it records nothing new. + var session = new HashManifest.Session(StateDir); + session.Save(); + batch.Complete(); + } + + Assert.False(File.Exists(Path.Combine(StateDir, ".hashes.json"))); + var expected = split.GetProperty("files"); + var actualNames = Directory.GetFiles(HashesDir).Select(Path.GetFileName).Order(StringComparer.Ordinal).ToList(); + Assert.Equal(expected.EnumerateObject().Select(p => p.Name).Order(StringComparer.Ordinal).ToList(), actualNames); + foreach (var f in expected.EnumerateObject()) + { + using var actual = JsonDocument.Parse(File.ReadAllText(Path.Combine(HashesDir, f.Name))); + Assert.Equal(f.Value.GetRawText().Replace(" ", "").Replace("\n", "").Replace("\r", ""), + actual.RootElement.GetRawText().Replace(" ", "").Replace("\n", "").Replace("\r", "")); + } + Assert.Equal(split.GetProperty("goldenText").GetString()!, + File.ReadAllText(Path.Combine(HashesDir, split.GetProperty("goldenFile").GetString()!))); + Assert.Equal(split.GetProperty("gitignoreAfter").GetString(), File.ReadAllText(ignore)); + + // A second identical write changes no file. + var stamp = DateTime.UtcNow.AddHours(-2); + foreach (var f in Directory.GetFiles(HashesDir)) File.SetLastWriteTimeUtc(f, stamp); + File.SetLastWriteTimeUtc(ignore, stamp); + using (var batch = HashManifest.Batch(StateDir, objects)) + { + HashManifest.Save(StateDir, HashManifest.Load(StateDir)); + batch.Complete(); + } + foreach (var f in Directory.GetFiles(HashesDir)) Assert.Equal(stamp, File.GetLastWriteTimeUtc(f)); + Assert.Equal(stamp, File.GetLastWriteTimeUtc(ignore)); + Assert.Equal(split.GetProperty("gitignoreAfter").GetString(), File.ReadAllText(ignore)); + } + + private static readonly List Objs = + [ + new("Order", "acme::shop"), new("Customer", "acme::crm"), + ]; + + private void Record(params (string Path, string Content)[] files) + { + using var batch = HashManifest.Batch(StateDir, Objs); + var session = new HashManifest.Session(StateDir); + foreach (var (path, content) in files) session.Record(path, content); + session.Save(); + batch.Complete(); + } + + [Fact] + public void A_change_in_one_package_rewrites_only_that_packages_file() + { + Record(("gen/Order.cs", "a"), ("gen/Customer.cs", "b"), ("gen/index.cs", "c")); + Assert.Equal([".root.json", "acme.crm.json", "acme.shop.json"], + Directory.GetFiles(HashesDir).Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray()); + + var stamp = DateTime.UtcNow.AddHours(-2); + foreach (var f in Directory.GetFiles(HashesDir)) File.SetLastWriteTimeUtc(f, stamp); + var crmBytes = File.ReadAllBytes(Path.Combine(HashesDir, "acme.crm.json")); + + Record(("gen/Order.cs", "a2")); + Assert.NotEqual(stamp, File.GetLastWriteTimeUtc(Path.Combine(HashesDir, "acme.shop.json"))); + Assert.Equal(stamp, File.GetLastWriteTimeUtc(Path.Combine(HashesDir, "acme.crm.json"))); + Assert.Equal(stamp, File.GetLastWriteTimeUtc(Path.Combine(HashesDir, ".root.json"))); + Assert.Equal(crmBytes, File.ReadAllBytes(Path.Combine(HashesDir, "acme.crm.json"))); + + // A no-op save writes nothing. + foreach (var f in Directory.GetFiles(HashesDir)) File.SetLastWriteTimeUtc(f, stamp); + Record(("gen/Order.cs", "a2"), ("gen/Customer.cs", "b")); + foreach (var f in Directory.GetFiles(HashesDir)) Assert.Equal(stamp, File.GetLastWriteTimeUtc(f)); + } + + [Fact] + public void A_package_that_loses_its_last_entry_loses_its_file_and_an_empty_manifest_keeps_root() + { + Record(("gen/Order.cs", "a"), ("gen/Customer.cs", "b")); + using (var batch = HashManifest.Batch(StateDir, Objs)) + { + HashManifest.Save(StateDir, new Dictionary { ["gen/Customer.cs"] = HashManifest.ContentHash("b") }); + batch.Complete(); + } + Assert.False(File.Exists(Path.Combine(HashesDir, "acme.shop.json"))); + Assert.True(File.Exists(Path.Combine(HashesDir, "acme.crm.json"))); + + using (var batch = HashManifest.Batch(StateDir, Objs)) + { + HashManifest.Save(StateDir, new Dictionary()); + batch.Complete(); + } + Assert.Equal([".root.json"], Directory.GetFiles(HashesDir).Select(Path.GetFileName).ToArray()); + Assert.Equal("{}\n", File.ReadAllText(Path.Combine(HashesDir, ".root.json"))); + Assert.True(HashManifest.Exists(StateDir)); + } + + [Fact] + public void A_read_only_load_of_a_legacy_manifest_migrates_nothing() + { + Directory.CreateDirectory(StateDir); + var legacy = Path.Combine(StateDir, ".hashes.json"); + const string text = "{\n \"gen/Order.cs\": \"h1\"\n}\n"; + File.WriteAllText(legacy, text); + + Assert.True(HashManifest.Exists(StateDir)); + Assert.Equal("h1", HashManifest.Load(StateDir)["gen/Order.cs"]); + Assert.True(HashManifest.IsRecorded(StateDir, "gen/Order.cs")); + + Assert.Equal(text, File.ReadAllText(legacy)); + Assert.False(Directory.Exists(HashesDir)); + } + + private sealed class PerObject : IGenerator + { + public string Name => "per-object"; + public IEnumerable Generate(GenContext ctx) => + ctx.Root.Objects().Select(o => new EmittedFile($"{o.Name}.g.cs", $"// {o.Name}\n")) + .Append(new EmittedFile("index.g.cs", "// index\n")); + } + + private static string Pkg(string package, string name) => $$$""" + { "metadata.root": { "package": "{{{package}}}", "children": [ + { "object.value": { "name": "{{{name}}}", "children": [ { "field.string": { "name": "label" } } ] } } + ]}} + """; + + [Fact] + public void A_run_over_a_multi_package_model_writes_one_manifest_per_package_and_a_root_one() + { + var r = new MetaDataLoader().Load([ + new InMemoryStringSource(Pkg("acme::shop", "Order"), id: "shop.json"), + new InMemoryStringSource(Pkg("acme::crm", "Customer"), id: "crm.json"), + ]); + Assert.Empty(r.Errors); + var config = new GenConfig { OutDir = Path.Combine(_root, "gen"), Namespace = "Probe", GenStateDir = StateDir }; + + var result = CodegenRunner.Run(config, r.Root, [new PerObject()]); + Assert.All(result.Files, f => Assert.Equal("written", f.Status)); + + Assert.Equal([".root.json", "acme.crm.json", "acme.shop.json"], + Directory.GetFiles(HashesDir).Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray()); + Assert.False(File.Exists(Path.Combine(StateDir, ".hashes.json"))); + Assert.Contains("Order.g.cs", File.ReadAllText(Path.Combine(HashesDir, "acme.shop.json"))); + Assert.Contains("Customer.g.cs", File.ReadAllText(Path.Combine(HashesDir, "acme.crm.json"))); + Assert.Contains("index.g.cs", File.ReadAllText(Path.Combine(HashesDir, ".root.json"))); + + // The next run changes nothing, and writes no manifest file. + var stamp = DateTime.UtcNow.AddHours(-2); + foreach (var f in Directory.GetFiles(HashesDir)) File.SetLastWriteTimeUtc(f, stamp); + CodegenRunner.Run(config, r.Root, [new PerObject()]); + foreach (var f in Directory.GetFiles(HashesDir)) Assert.Equal(stamp, File.GetLastWriteTimeUtc(f)); + } + + private string MigrateWith(string gitignore) + { + Directory.CreateDirectory(StateDir); + File.WriteAllText(Path.Combine(StateDir, ".hashes.json"), "{\n \"gen/Order.cs\": \"h1\"\n}\n"); + var ignore = Path.Combine(_root, ".metaobjects", ".gitignore"); + File.WriteAllText(ignore, gitignore); + using (var batch = HashManifest.Batch(StateDir, Objs)) + { + new HashManifest.Session(StateDir).Save(); + batch.Complete(); + } + return File.ReadAllText(ignore); + } + + [Fact] + public void Migration_inserts_the_new_line_after_the_rule_when_there_is_no_legacy_line() + => Assert.Equal(".gen-state/*\n!.gen-state/.hashes/\nother\n", MigrateWith(".gen-state/*\nother\n")); + + [Fact] + public void Migration_only_drops_the_legacy_line_when_the_new_one_is_there() + => Assert.Equal(".gen-state/*\n!.gen-state/.hashes/\n", + MigrateWith(".gen-state/*\n!.gen-state/.hashes.json\n!.gen-state/.hashes/\n")); + + [Fact] + public void Migration_leaves_a_gitignore_without_the_rule_alone() + => Assert.Equal("node_modules\n", MigrateWith("node_modules\n")); + + [Fact] + public void A_non_migrating_save_leaves_gitignore_alone() + { + Directory.CreateDirectory(Path.Combine(_root, ".metaobjects")); + var ignore = Path.Combine(_root, ".metaobjects", ".gitignore"); + File.WriteAllText(ignore, ".gen-state/*\n!.gen-state/.hashes.json\n"); + Record(("gen/Order.cs", "a")); + Assert.Equal(".gen-state/*\n!.gen-state/.hashes.json\n", File.ReadAllText(ignore)); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs index 578a035734..1338694cf4 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs @@ -22,7 +22,7 @@ public sealed class OrphanSweepTests : IDisposable private string Meta => Path.Combine(_root, "metaobjects"); private string Out => Path.Combine(_root, "gen"); private string Docs => Path.Combine(_root, "docs"); - private string ManifestPath => Path.Combine(_root, ".metaobjects", ".gen-state", ".hashes.json"); + private string ManifestPath => Path.Combine(_root, ".metaobjects", ".gen-state", ".hashes"); public OrphanSweepTests() => Directory.CreateDirectory(Meta); public void Dispose() { try { Directory.Delete(_root, recursive: true); } catch { } } @@ -80,7 +80,9 @@ private void Model(string package, params string[] values) => private (int Code, string Out, string Err) Verify() => Run("verify", "--codegen", "--full", Meta, "--out", Out, "--namespace", "Acme.Generated"); private Dictionary Manifest() => - JsonSerializer.Deserialize>(File.ReadAllText(ManifestPath))!; + Directory.GetFiles(ManifestPath, "*.json").Order(StringComparer.Ordinal) + .SelectMany(f => JsonSerializer.Deserialize>(File.ReadAllText(f))!) + .ToDictionary(kv => kv.Key, kv => kv.Value); [Fact] public void A_renamed_value_object_is_deleted_and_verify_goes_green() @@ -368,7 +370,9 @@ public void Overwrite_never_replaces_a_file_gen_has_no_record_of_writing() Model("acme", "Telemetry"); Assert.Equal(0, Gen().Code); var file = Path.Combine(Out, "Telemetry.g.cs"); - File.WriteAllText(ManifestPath, "{}"); + Directory.Delete(ManifestPath, recursive: true); + Directory.CreateDirectory(ManifestPath); + File.WriteAllText(Path.Combine(ManifestPath, ".root.json"), "{}"); File.WriteAllText(file, "// not generated\n"); Gen(); diff --git a/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs index 6979ed85b4..acb23ee248 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs @@ -33,6 +33,7 @@ public class OverwriteHashManifestTests : IDisposable private string OutDir => Path.Combine(_root, "generated"); private string StateDir => Path.Combine(_root, ".metaobjects", ".gen-state"); + private string RootManifest => Path.Combine(StateDir, ".hashes", ".root.json"); private string TargetPath => Path.Combine(OutDir, "A.cs"); [Fact] @@ -47,7 +48,7 @@ public void JvmObjectEntry_IsReadAsRecordedHashAndPreservedOnRecord() HashManifest.Record(StateDir, "Other.cs", "other"); - using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(StateDir, ".hashes.json"))); + using var doc = JsonDocument.Parse(File.ReadAllText(RootManifest)); var jvm = doc.RootElement.GetProperty("Jvm.java"); Assert.Equal(JsonValueKind.Object, jvm.ValueKind); Assert.Equal(jvmHash, jvm.GetProperty("hash").GetString()); @@ -57,7 +58,7 @@ public void JvmObjectEntry_IsReadAsRecordedHashAndPreservedOnRecord() Assert.Equal(HashManifest.ContentHash("other"), doc.RootElement.GetProperty("Other.cs").GetString()); HashManifest.Record(StateDir, "Jvm.java", "jvm body v2"); - using var after = JsonDocument.Parse(File.ReadAllText(Path.Combine(StateDir, ".hashes.json"))); + using var after = JsonDocument.Parse(File.ReadAllText(RootManifest)); var updated = after.RootElement.GetProperty("Jvm.java"); Assert.Equal(HashManifest.ContentHash("jvm body v2"), updated.GetProperty("hash").GetString()); Assert.Equal("java:dto", updated.GetProperty("generator").GetString()); @@ -118,7 +119,7 @@ public IEnumerable Generate(GenContext ctx) { for (var i = 0; i < contents.Length; i++) { - ManifestOnDisk.Add(File.Exists(Path.Combine(stateDir, ".hashes.json"))); + ManifestOnDisk.Add(Directory.Exists(Path.Combine(stateDir, ".hashes"))); yield return new EmittedFile($"F{i}.cs", contents[i]); } } @@ -139,7 +140,7 @@ public void ARun_WritesTheManifestOnce_AtTheEnd() Assert.All(first.Files, f => Assert.Equal("written", f.Status)); // Not on disk while the run is writing: it is saved once, after the last file. Assert.Equal(new[] { false, false, false, false }, gen.ManifestOnDisk); - var manifest = Path.Combine(StateDir, ".hashes.json"); + var manifest = RootManifest; var recorded = File.ReadAllText(manifest); using (var doc = JsonDocument.Parse(recorded)) Assert.Equal(4, doc.RootElement.EnumerateObject().Count()); @@ -161,7 +162,7 @@ void FailingRun() using var batch = HashManifest.Batch(StateDir); HashManifest.Record(StateDir, "A.cs", "class A { }\n"); // A directory where the manifest goes: the end-of-batch write now fails. - Directory.CreateDirectory(Path.Combine(StateDir, ".hashes.json")); + Directory.CreateDirectory(Path.Combine(StateDir, ".hashes", ".root.json")); throw new InvalidOperationException("the generator's own failure"); } var ex = Assert.Throws(FailingRun); @@ -227,7 +228,7 @@ public void MarkerIsNoLongerConsulted_OurOwnFileIsOurs() // ── Baseline = "adopt" ──────────────────────────────────────────────────────── // - // The no-manifest refusal used to LEAD with "commit '.gen-state/.hashes.json'", which + // The no-manifest refusal used to LEAD with "commit '.gen-state/.hashes/'", which // the population it names cannot do: nothing writes a manifest until a gen succeeds, // and a run where every file refuses writes none. `adopt` records what is on disk as // the baseline and writes nothing — the run that produces the file to commit. @@ -243,7 +244,7 @@ public void Adopt_RecordsTheFile_AndWritesNothing() Assert.Equal("adopted", result.Files[0].Status); Assert.Equal(onDisk, File.ReadAllText(TargetPath)); // not one byte written - Assert.True(File.Exists(Path.Combine(StateDir, ".hashes.json"))); // the file to commit + Assert.True(File.Exists(RootManifest)); // the file to commit } [Fact] @@ -255,7 +256,7 @@ public void Adopt_SaysWhatToDoNext_Once() var result = Run("// \nclass A { }\n", baseline: "adopt"); var notice = Assert.Single(result.Warnings, w => w.Contains("baseline")); - Assert.Contains(".hashes.json", notice); + Assert.Contains(".hashes/", notice); Assert.Contains("regenerat", notice); } @@ -295,7 +296,7 @@ public void TheNoManifestRefusal_LeadsWithThePerformableRemedy() var msg = Assert.Single(result.Warnings, w => w.Contains("no codegen hash manifest")); Assert.Contains("--baseline=adopt", msg); // What it must no longer do: prescribe committing a file this project cannot produce. - Assert.DoesNotContain("Commit \'.gen-state/.hashes.json\' and re-run", msg); + Assert.DoesNotContain("Commit \'.gen-state/.hashes/\' and re-run", msg); } [Fact] @@ -308,7 +309,7 @@ public void Manifest_IsSorted_BecauseItIsCommitted() }; CodegenRunner.Run(config, Load(), gens); - var json = File.ReadAllText(Path.Combine(StateDir, ".hashes.json")); + var json = File.ReadAllText(RootManifest); var keys = JsonSerializer.Deserialize>(json)!.Keys.ToList(); // Insertion order would make a committed diff depend on generation order. Assert.Equal(new[] { "a.cs", "m.cs", "z.cs" }, keys.ToArray()); @@ -339,7 +340,7 @@ public void NoManifest_ManyRefusals_ProduceOneAggregatedMessage() Assert.Equal(3, result.Files.Count(f => f.Status == "refused")); Assert.Single(result.Warnings); Assert.Contains("3 existing file(s)", result.Warnings[0]); - Assert.Contains(".hashes.json", result.Warnings[0]); + Assert.Contains(".hashes/", result.Warnings[0]); } // ---- manifest KEY: project-root-relative, so two out dirs cannot collide ---- @@ -402,7 +403,7 @@ public void RerunWithNoChange_KeepsGeneratedFileAndManifestTimestamps() { const string content = "// \nv1\n"; RunIn(OutDir, content, _root); - var manifest = Path.Combine(StateDir, ".hashes.json"); + var manifest = RootManifest; var bytes = File.ReadAllBytes(manifest); var stamp = DateTime.UtcNow.AddHours(-2); File.SetLastWriteTimeUtc(TargetPath, stamp); diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 3d2049436d..961ed8aa47 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -245,7 +245,7 @@ public static GenOutcome RunGen( EmitAbstractShapes = emitAbstractShapes, // The hash manifest lives beside the project's other tool state. Supplying it // is what gives real hand-edit detection; without it CodegenRunner falls back - // to the legacy -marker rule. COMMIT .gen-state/.hashes.json. + // to the legacy -marker rule. COMMIT .gen-state/.hashes/. GenStateDir = Path.Combine(root, ".metaobjects", ".gen-state"), ProjectRoot = root, // ADR-0058 — one project setting, read from the loaded root rather than a CLI diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index eb2fd8e5ac..4d501b44ea 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -107,7 +107,7 @@ internal static RunResult Run( var hadManifest = config.GenStateDir is null || HashManifest.Exists(config.GenStateDir); // One manifest write for the whole run (the writes and the orphan sweep), not one // per recorded file. - using var manifestBatch = HashManifest.Batch(config.GenStateDir); + using var manifestBatch = HashManifest.Batch(config.GenStateDir, HashManifest.ObjectsOf(root)); var selection = config.EntitySelection is { } names ? names.ToHashSet(StringComparer.Ordinal) : null; @@ -140,7 +140,7 @@ internal static RunResult Run( } // The manifest key. Project-root-relative when the caller names a project, // so two runs with different --out cannot collide on one entry inside the - // single manifest that is anchored on that project. `file.Path` rides + // manifest that is anchored on that project. `file.Path` rides // along as the legacy spelling — it is what the manifest used to be keyed // by, and it is still what a refusal is REPORTED as (the name the reader // sees under --out). @@ -156,7 +156,7 @@ internal static RunResult Run( : file.Path; // A file written OUTSIDE the project has no place in the project's // manifest: its key would be `../`-relative and committed into - // .hashes.json. It gets the manifest-less rule a run with no project gets. + // .hashes/. It gets the manifest-less rule a run with no project gets. var outside = config.ProjectRoot is not null && (key.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(key)); if (outside) { untracked++; outsidePaths.Add(full); } @@ -199,7 +199,7 @@ internal static RunResult Run( if (untracked > 0) warnings.Add( $"{untracked} generated file(s) were written outside the project root and are " + - "not recorded in .metaobjects/.gen-state/.hashes.json, so hand-edit protection " + + "not recorded in .metaobjects/.gen-state/.hashes/, so hand-edit protection " + "does not apply to them beyond the marker rule."); ReportRefusals(refused, hadManifest, warnings); ReportAdoptions(adopted, warnings); @@ -388,7 +388,7 @@ private static void ReportRefusals(List refused, bool hadManifest, List< $"output, and will not guess. This is the expected first run for a project " + $"created before the manifest was committed. ONE-TIME FIX: re-run with " + $"--baseline=adopt — it records the files you have as the baseline and writes " + - $"NOTHING — then commit '.gen-state/.hashes.json' and run gen again, where the " + + $"NOTHING — then commit '.gen-state/.hashes/' and run gen again, where the " + $"regeneration arrives as its own reviewable diff. Adopting DECLARES these files " + $"to be generated output, so an edit already inside one of them is part of the " + $"baseline and that regeneration will replace it — commit before you run it. " + @@ -419,7 +419,7 @@ private static void ReportAdoptions(List adopted, List warnings) var more = adopted.Count > maxNamed ? $", and {adopted.Count - maxNamed} more" : ""; warnings.Add( $"Recorded {adopted.Count} existing file(s) as the codegen baseline and wrote " + - $"nothing. NEXT: commit '.gen-state/.hashes.json', then run gen again — these " + + $"nothing. NEXT: commit '.gen-state/.hashes/', then run gen again — these " + $"files regenerate normally from here, as their own reviewable diff. Adopting " + $"DECLARED them to be generated output: an edit already inside one is part of the " + $"baseline and that regeneration will replace it, so check the diff against git. " + diff --git a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs index 5f0a2f4a4b..3adffd1284 100644 --- a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs +++ b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs @@ -332,6 +332,8 @@ private static bool MatchesStored(string projectRoot, string model, string ident public static bool CanSkipGen(string projectRoot, string model, string identity) { if (!MatchesStored(projectRoot, model, identity)) return false; + // A pre-1.3.0 manifest is migrated by a write run, so gen runs (verify, read-only, may still answer). + if (HashManifest.HasLegacy(GenStateDir(projectRoot))) return false; if (ManifestOf(projectRoot) is not { } manifest) return false; // Amendment A: every recorded file must still be what the stored run left. A missing entry is a mismatch. var stored = Read(projectRoot)!; diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 5320424372..6fcd864560 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -25,7 +25,7 @@ public sealed record GenConfig public required string OutDir { get; init; } /// - /// Where the codegen hash manifest lives (<GenStateDir>/.hashes.json), + /// Where the codegen hash manifest lives (<GenStateDir>/.hashes/, one file per package), /// recording what this generator wrote so a later run can tell its own output from a /// hand edit. /// diff --git a/server/csharp/MetaObjects.Codegen/HashManifest.cs b/server/csharp/MetaObjects.Codegen/HashManifest.cs index 56ba6dac98..7376494318 100644 --- a/server/csharp/MetaObjects.Codegen/HashManifest.cs +++ b/server/csharp/MetaObjects.Codegen/HashManifest.cs @@ -1,6 +1,6 @@ // The codegen hash manifest — how a run tells its own output from a hand edit. // -// Mirrors codegen-ts's `.gen-state/.hashes.json` and Python's overwrite_policy, using +// Mirrors codegen-ts's `.gen-state/.hashes/` and Python's overwrite_policy, using // the same algorithm — sha-256 hex of the UTF-8 content — so the same file content // hashes identically on every port. // @@ -20,6 +20,10 @@ // out-dir-relative spelling is still READ as a legacy key so an existing manifest keeps // working, and is dropped as each file converges on the new one. // +// ADR-0064 Amendment 1: the manifest is one file per model package under +// `.gen-state/.hashes/` (`.root.json` for paths in no package). The in-memory model stays +// flat (path -> entry); only load, save and exists know about the files. +// // This file is meant to be COMMITTED. It is one hash per generated path — small and // reviewable — where a full snapshot of previously-generated content would be a second // copy of everything. A hash is already sufficient to answer the only question the @@ -28,15 +32,122 @@ using System.Security.Cryptography; using System.Text; using System.Text.Json; +using MetaObjects.Meta; namespace MetaObjects.Codegen; /// Reads and writes the per-path hash record of generated output. public static class HashManifest { - private const string FileName = ".hashes.json"; + private const string LegacyFileName = ".hashes.json"; + private const string DirName = ".hashes"; + private const string RootFileName = ".root.json"; + private const string IgnoreLine = "!.gen-state/.hashes/"; + private const string LegacyIgnoreLine = "!.gen-state/.hashes.json"; + + private static string LegacyPath(string genStateDir) => Path.Combine(genStateDir, LegacyFileName); + private static string DirPath(string genStateDir) => Path.Combine(genStateDir, DirName); + + /// A root-level model object: its name and effective package ("" for none). + public readonly record struct ManifestObject(string Name, string Package); + + /// The objects a run's placement rule reads: every root-level object of the loaded model. + public static IReadOnlyList ObjectsOf(MetaRoot root) => + root.Objects().Select(o => new ManifestObject(o.Name, NamingRefs.EffectivePackageOf(o))).ToList(); + + /// A package's manifest file name; null is the root manifest. + public static string FileNameFor(string? package) + { + if (string.IsNullOrEmpty(package)) return RootFileName; + var sb = new StringBuilder(); + var first = true; + foreach (var segment in package.Split("::")) + { + if (!first) sb.Append('.'); + first = false; + foreach (var b in Encoding.UTF8.GetBytes(segment)) + { + var c = (char)b; + if (b < 0x80 && (char.IsAsciiLetterOrDigit(c) || c is '_' or '-')) sb.Append(c); + else sb.Append('%').Append(b.ToString("X2")); + } + } + return sb.Append(".json").ToString(); + } + + /// + /// The manifest file an entry is filed under (ADR-0064 Amendment 1 section 3): its + /// sourceNode when it has one, else the object whose name the file's stem begins with. + /// null when there is no model to ask and no sourceNode: the caller keeps the + /// entry where it is. + /// + public static string? PlaceFile(string path, JsonElement? entry, IReadOnlyList? objects) + { + if (entry is { ValueKind: JsonValueKind.Object } e + && e.TryGetProperty("sourceNode", out var sn) && sn.ValueKind == JsonValueKind.String + && sn.GetString() is { Length: > 0 } node) + { + var dot = node.IndexOf('.'); + var qualified = dot < 0 ? node : node[..dot]; + var cut = qualified.LastIndexOf("::", StringComparison.Ordinal); + return FileNameFor(cut < 0 ? null : qualified[..cut]); + } + if (objects is null) return null; + var slash = path.LastIndexOfAny(['/', '\\']); + var baseName = slash < 0 ? path : path[(slash + 1)..]; + var stemDot = baseName.IndexOf('.'); + var stem = stemDot < 0 ? baseName : baseName[..stemDot]; + var stemWords = Words(stem); + var bestCount = 0; + var packages = new HashSet(StringComparer.Ordinal); + foreach (var o in objects) + { + var words = Words(o.Name); + if (words.Count == 0 || words.Count > stemWords.Count) continue; + if (!words.SequenceEqual(stemWords.Take(words.Count), StringComparer.Ordinal)) continue; + if (words.Count > bestCount) { bestCount = words.Count; packages.Clear(); } + if (words.Count == bestCount) packages.Add(o.Package); + } + return packages.Count == 1 && packages.First().Length > 0 ? FileNameFor(packages.First()) : RootFileName; + } + + // Lowercase words: split at '_' and '-', before an uppercase letter after a lowercase letter or digit, and + // before the last capital of a run followed by a lowercase letter (HTTPServer -> http, server). + private static List Words(string name) + { + static bool Up(char c) => c is >= 'A' and <= 'Z'; + static bool Low(char c) => c is >= 'a' and <= 'z'; + static bool Dig(char c) => c is >= '0' and <= '9'; + var words = new List(); + var cur = new StringBuilder(); + void Flush() { if (cur.Length > 0) { words.Add(cur.ToString()); cur.Clear(); } } + for (var i = 0; i < name.Length; i++) + { + var c = name[i]; + if (c is '_' or '-') { Flush(); continue; } + if (Up(c) && i > 0) + { + var prev = name[i - 1]; + if (Low(prev) || Dig(prev) || (Up(prev) && i + 1 < name.Length && Low(name[i + 1]))) Flush(); + } + cur.Append(Up(c) ? (char)(c + 32) : c); + } + Flush(); + return words; + } - private static string PathFor(string genStateDir) => Path.Combine(genStateDir, FileName); + private sealed class Loaded + { + public Dictionary Raw = new(StringComparer.Ordinal); + /// The package file each entry was read from; absent for a legacy entry. + public Dictionary Origin = new(StringComparer.Ordinal); + public bool LegacyPresent; + } + + private static bool LegacyExists(string genStateDir) => File.Exists(LegacyPath(genStateDir)); + + private static bool DirHasManifest(string genStateDir) => + Directory.Exists(DirPath(genStateDir)) && Directory.EnumerateFiles(DirPath(genStateDir), "*.json").Any(); /// sha-256 hex of . public static string ContentHash(string content) => @@ -49,11 +160,16 @@ public static string ContentHash(string content) => /// rather than one warning per file. /// public static bool Exists(string genStateDir) => - File.Exists(PathFor(genStateDir)) || (BatchFor(genStateDir)?.Dirty ?? false); + LegacyExists(genStateDir) || DirHasManifest(genStateDir) || (BatchFor(genStateDir)?.Dirty ?? false); - private sealed class ManifestBatch(Dictionary raw) + /// Whether a pre-1.3.0 .hashes.json is still on disk: the next write run migrates it. + public static bool HasLegacy(string genStateDir) => LegacyExists(genStateDir); + + private sealed class ManifestBatch(Loaded loaded, IReadOnlyList? objects) { - public Dictionary Raw = raw; + public Dictionary Raw = loaded.Raw; + public readonly Dictionary Origin = loaded.Origin; + public readonly IReadOnlyList? Objects = objects; public bool Dirty; } @@ -77,14 +193,14 @@ private sealed class ManifestBatch(Dictionary raw) /// unwinding an exception, and a failed manifest write then must not replace that /// exception, so it is swallowed. /// - public static BatchScope Batch(string? genStateDir) + public static BatchScope Batch(string? genStateDir, IReadOnlyList? objects = null) { if (genStateDir is null) return BatchScope.None; var key = Path.GetFullPath(genStateDir); lock (Batches) { if (Batches.ContainsKey(key)) return BatchScope.None; - Batches[key] = new ManifestBatch(ReadFile(genStateDir)); + Batches[key] = new ManifestBatch(ReadAll(genStateDir), objects); } return new BatchScope(genStateDir, key); } @@ -121,12 +237,12 @@ public void Dispose() if (!batch.Dirty) return; if (_completed) { - WriteFile(_genStateDir, batch.Raw); + WriteAll(_genStateDir, batch.Raw, batch.Origin, batch.Objects); return; } try { - WriteFile(_genStateDir, batch.Raw); + WriteAll(_genStateDir, batch.Raw, batch.Origin, batch.Objects); } catch (Exception) { @@ -136,23 +252,38 @@ public void Dispose() } private static Dictionary ReadRaw(string genStateDir) => - BatchFor(genStateDir)?.Raw ?? ReadFile(genStateDir); + BatchFor(genStateDir)?.Raw ?? ReadAll(genStateDir).Raw; - private static Dictionary ReadFile(string genStateDir) + private static Dictionary? ReadOne(string path) { - var path = PathFor(genStateDir); - if (!File.Exists(path)) return new Dictionary(StringComparer.Ordinal); try { var parsed = JsonSerializer.Deserialize>(File.ReadAllText(path)); - return parsed is null - ? new Dictionary(StringComparer.Ordinal) - : new Dictionary(parsed, StringComparer.Ordinal); + return parsed is null ? null : new Dictionary(parsed, StringComparer.Ordinal); } catch (Exception e) when (e is JsonException or IOException or UnauthorizedAccessException) { - return new Dictionary(StringComparer.Ordinal); + return null; // an unreadable or corrupt file reads as empty: fails closed, replaced on the next write + } + } + + // The union: the legacy file underneath, then every file in .hashes/ in file-name order (a package file wins). + private static Loaded ReadAll(string genStateDir) + { + var loaded = new Loaded { LegacyPresent = LegacyExists(genStateDir) }; + if (loaded.LegacyPresent && ReadOne(LegacyPath(genStateDir)) is { } legacy) + foreach (var (k, v) in legacy) loaded.Raw[k] = v; + if (Directory.Exists(DirPath(genStateDir))) + { + var names = Directory.EnumerateFiles(DirPath(genStateDir), "*.json") + .Select(Path.GetFileName).OfType().Order(StringComparer.Ordinal); + foreach (var name in names) + { + if (ReadOne(Path.Combine(DirPath(genStateDir), name)) is not { } entries) continue; + foreach (var (k, v) in entries) { loaded.Raw[k] = v; loaded.Origin[k] = name; } + } } + return loaded; } private static string? EntryHash(JsonElement value) => value.ValueKind switch @@ -205,15 +336,69 @@ public static void Save(string genStateDir, Dictionary hashes) batch.Dirty = true; return; } - WriteFile(genStateDir, next); + WriteAll(genStateDir, next, ReadAll(genStateDir).Origin, null); } - private static void WriteFile(string genStateDir, Dictionary raw) + private static string TextOf(Dictionary entries) { - Directory.CreateDirectory(genStateDir); - var ordered = new SortedDictionary(raw, StringComparer.Ordinal); - var json = JsonSerializer.Serialize(ordered, new JsonSerializerOptions { WriteIndented = true }); - File.WriteAllText(PathFor(genStateDir), json + "\n"); + var ordered = new SortedDictionary(entries, StringComparer.Ordinal); + return JsonSerializer.Serialize(ordered, new JsonSerializerOptions { WriteIndented = true }) + "\n"; + } + + // Files every entry by the placement rule, writes ONLY the files whose bytes changed, deletes package files + // left empty and the legacy file, keeps .root.json ({}) when no entry exists at all. + private static void WriteAll( + string genStateDir, Dictionary raw, Dictionary origin, + IReadOnlyList? objects) + { + var files = new Dictionary>(StringComparer.Ordinal); + foreach (var (key, value) in raw) + { + var file = PlaceFile(key, value, objects) + ?? (origin.TryGetValue(key, out var kept) ? kept : RootFileName); + if (!files.TryGetValue(file, out var group)) files[file] = group = new(StringComparer.Ordinal); + group[key] = value; + } + if (files.Count == 0) files[RootFileName] = new(StringComparer.Ordinal); + + var dir = DirPath(genStateDir); + Directory.CreateDirectory(dir); + foreach (var (name, entries) in files) + { + var path = Path.Combine(dir, name); + var text = TextOf(entries); + if (File.Exists(path) && File.ReadAllText(path) == text) continue; + File.WriteAllText(path, text); + } + foreach (var existing in Directory.EnumerateFiles(dir, "*.json").ToList()) + if (!files.ContainsKey(Path.GetFileName(existing))) File.Delete(existing); + if (LegacyExists(genStateDir)) + { + File.Delete(LegacyPath(genStateDir)); + MigrateIgnoreFile(genStateDir); // only a migrating run touches .gitignore + } + } + + // The `.gen-state/*` rule would git-ignore the new directory: replace the legacy negation with the new one + // (or insert it after the rule when there is no legacy line). A file without the rule is left alone. + private static void MigrateIgnoreFile(string genStateDir) + { + var path = Path.GetFullPath(Path.Combine(genStateDir, "..", ".gitignore")); + if (!File.Exists(path)) return; + var text = File.ReadAllText(path); + var lines = text.Split('\n').ToList(); + bool Is(string l, string v) => l.TrimEnd('\r') == v; + var rule = lines.FindIndex(l => Is(l, ".gen-state/*")); + if (rule < 0) return; + var hasNew = lines.Any(l => Is(l, IgnoreLine)); + var legacy = lines.FindIndex(l => Is(l, LegacyIgnoreLine)); + if (legacy >= 0) + { + if (hasNew) lines.RemoveAt(legacy); else lines[legacy] = IgnoreLine; + } + else if (!hasNew) lines.Insert(rule + 1, IgnoreLine); + var next = string.Join("\n", lines); + if (next != text) File.WriteAllText(path, next); } /// Record that was written with this content. @@ -281,6 +466,8 @@ public Session(string genStateDir) { _genStateDir = genStateDir; _hashes = Load(genStateDir); + // A pre-1.3.0 manifest is migrated by the next write run even when nothing else changed. + _dirty = LegacyExists(genStateDir); } /// The in-memory entries, for a reader that needs the whole set. diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java index 181252873c..81f2ba7a6d 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java @@ -37,7 +37,7 @@ * it were somebody's hand-written source. The marker still matters at the ONE moment the * manifest cannot help: an existing file at a generated path that has never been recorded. * There, carrying the marker is what lets a pre-manifest file (adopted from before this - * project committed {@code .metaobjects/.gen-state/.hashes.json}) be taken as this + * project committed {@code .metaobjects/.gen-state/.hashes/}) be taken as this * toolchain's own rather than refused as hand-written — see {@link #write} for the full * decision tree. Absent any manifest configuration on the active {@link Run} (an embedder, * or a test driving a generator directly), the marker alone still decides, exactly as @@ -146,6 +146,9 @@ public static final class Run implements AutoCloseable { private Map hashes; private Map owners; private boolean dirty; + // Where each entry is filed among the per-package manifests; set by the runner once the + // model is loaded. Unset: an entry stays in the file it is in. + private HashManifest.Placement placement; // Every path write() was asked to produce this run, whatever the outcome — written, // unchanged, refused or adopted. This is the "emitted" set the caller's orphan sweep @@ -192,7 +195,7 @@ public Run attributeTo(String generatorName, String handEdits, HashManifest.Owne /** * Turn on manifest-aware writes for this run: {@code genStateDir} is the directory - * holding {@code .hashes.json} (typically {@code /.metaobjects/.gen-state}), + * holding {@code .hashes/} (typically {@code /.metaobjects/.gen-state}), * and {@code projectRoot} is what manifest keys are relative to (typically the * module basedir). Called once, by the Mojo, right after {@link #beginRun}. Leaving * this unset keeps every write on the legacy marker-only rule. @@ -202,6 +205,20 @@ public Run configureManifest(Path genStateDir, Path projectRoot) { this.projectRoot = projectRoot; this.hashes = HashManifest.load(genStateDir); this.owners = HashManifest.loadOwners(genStateDir); + // A run that finds the pre-1.3.0 single manifest always saves, so it is migrated. + this.dirty = HashManifest.hasLegacy(genStateDir); + return this; + } + + /** The placement the runner set, or {@code null}. */ + public HashManifest.Placement placement() { + return placement; + } + + /** File each manifest entry under the package of the model object it belongs to + * (ADR-0064 Amendment 1). Called by the runner once the model is loaded. */ + public Run placeBy(HashManifest.Placement placement) { + this.placement = placement; return this; } @@ -210,7 +227,7 @@ public Run configureManifest(Path genStateDir, Path projectRoot) { * calls it for whatever is still unwritten. */ public void flush() { if (!dirty) return; - HashManifest.save(genStateDir, hashes, owners); + HashManifest.save(genStateDir, hashes, owners, placement); dirty = false; } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java index 8dcd96e761..bcba020a0f 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java @@ -15,7 +15,12 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.LinkedHashMap; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; import java.util.TreeMap; /** @@ -24,8 +29,9 @@ * *

Mirrors the shape and algorithm the TypeScript, Python and C# ports already share: * a JSON object {@code { "": "" }}, keys sorted, - * pretty-printed, one trailing newline, at - * {@code /.metaobjects/.gen-state/.hashes.json} where {@code } is the + * pretty-printed, one trailing newline, split into one file per model package under + * {@code /.metaobjects/.gen-state/.hashes/} (ADR-0064 Amendment 1; a pre-1.3.0 + * {@code .hashes.json} is still read and is removed by the next write) where {@code } is the * Maven project base dir. The KEYS are not meant to be portable between ports — each * keys relative to its own notion of "the project" — only the shape and the hashing * algorithm (sha-256 hex of the UTF-8 content) are shared, so identical content hashes @@ -58,11 +64,117 @@ public String toString() { } } - private static final String FILE_NAME = ".hashes.json"; + /** The pre-1.3.0 single manifest, still read (underneath the package files) and removed by the next write. */ + private static final String LEGACY_FILE_NAME = ".hashes.json"; + /** The directory of per-package manifests (ADR-0064 Amendment 1). */ + private static final String DIR_NAME = ".hashes"; + /** The manifest of every path that belongs to no package. */ + public static final String ROOT_FILE_NAME = ".root.json"; private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - private static Path pathFor(Path genStateDir) { - return genStateDir.resolve(FILE_NAME); + private static Path legacyPath(Path genStateDir) { + return genStateDir.resolve(LEGACY_FILE_NAME); + } + + private static Path dirPath(Path genStateDir) { + return genStateDir.resolve(DIR_NAME); + } + + /** A model object as placement sees it: its name and its {@code ::}-separated package ({@code ""}: none). */ + public record ModelObject(String name, String pkg) {} + + /** + * Which package manifest a recorded path belongs to, from the loaded model's root-level + * objects: the entry's {@code sourceNode} first, then the object whose name the file's + * stem begins with (ADR-0064 Amendment 1 section 3). A pure function of the model and the + * entry, so an entry moves only when its object does. + */ + public static final class Placement { + // Each name's lowercase words (joined by a space) -> the packages declaring a name of those words. + private final Map> packagesByWords = new java.util.HashMap<>(); + + public Placement(Iterable objects) { + for (ModelObject o : objects) { + if (o.name() == null || o.name().isEmpty()) continue; + List words = words(o.name()); + if (words.isEmpty()) continue; + packagesByWords.computeIfAbsent(String.join(" ", words), k -> new java.util.HashSet<>()) + .add(o.pkg() == null ? "" : o.pkg()); + } + } + + /** The package of {@code path}'s manifest, or {@code null} for the root manifest. {@code entry} may be null. */ + public String packageOf(String path, JsonObject entry) { + String sourceNode = entry == null ? null : stringField(entry, "sourceNode"); + if (sourceNode != null) { + int dot = sourceNode.indexOf('.'); + String qualified = dot < 0 ? sourceNode : sourceNode.substring(0, dot); + int sep = qualified.lastIndexOf("::"); + return sep <= 0 ? null : qualified.substring(0, sep); + } + String base = path.substring(path.lastIndexOf('/') + 1); + int dot = base.indexOf('.'); + List stem = words(dot < 0 ? base : base.substring(0, dot)); + for (int n = stem.size(); n >= 1; n--) { + java.util.Set packages = packagesByWords.get(String.join(" ", stem.subList(0, n))); + if (packages == null) continue; + if (packages.size() != 1) return null; + String only = packages.iterator().next(); + return only.isEmpty() ? null : only; + } + return null; + } + + /** Lowercase words of a name: split at '_' and '-', before an uppercase letter after a lowercase + * letter or digit, and before the last capital of a run that a lowercase letter follows. */ + static List words(String name) { + List out = new ArrayList<>(); + StringBuilder word = new StringBuilder(); + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (c == '_' || c == '-') { + flush(out, word); + continue; + } + boolean upper = c >= 'A' && c <= 'Z'; + if (upper && word.length() > 0) { + char prev = name.charAt(i - 1); + boolean prevLowerOrDigit = (prev >= 'a' && prev <= 'z') || (prev >= '0' && prev <= '9'); + boolean prevUpper = prev >= 'A' && prev <= 'Z'; + boolean nextLower = i + 1 < name.length() && name.charAt(i + 1) >= 'a' && name.charAt(i + 1) <= 'z'; + if (prevLowerOrDigit || (prevUpper && nextLower)) flush(out, word); + } + word.append(Character.toLowerCase(c)); + } + flush(out, word); + return out; + } + + private static void flush(List out, StringBuilder word) { + if (word.length() > 0) out.add(word.toString()); + word.setLength(0); + } + } + + /** The manifest file name of {@code pkg} ({@code null} or empty: the root manifest). */ + public static String fileName(String pkg) { + if (pkg == null || pkg.isEmpty()) return ROOT_FILE_NAME; + StringBuilder sb = new StringBuilder(); + boolean first = true; + for (String segment : pkg.split("::", -1)) { + if (!first) sb.append('.'); + first = false; + for (byte b : segment.getBytes(StandardCharsets.UTF_8)) { + int c = b & 0xFF; + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-') { + sb.append((char) c); + } else { + sb.append('%').append(Character.toUpperCase(Character.forDigit(c >> 4, 16))) + .append(Character.toUpperCase(Character.forDigit(c & 0xF, 16))); + } + } + } + return sb.append(".json").toString(); } /** sha-256 hex (lowercase) of {@code content}'s UTF-8 bytes. */ @@ -89,7 +201,25 @@ public static String contentHash(String content) { * carries the marker) rather than a cold refusal. */ public static boolean exists(Path genStateDir) { - return Files.isRegularFile(pathFor(genStateDir)); + return hasLegacy(genStateDir) || !packageFiles(genStateDir).isEmpty(); + } + + /** Whether the pre-1.3.0 single manifest is still on disk: the next write run migrates it. */ + public static boolean hasLegacy(Path genStateDir) { + return Files.isRegularFile(legacyPath(genStateDir)); + } + + /** The per-package manifest files, in file-name order. */ + private static List packageFiles(Path genStateDir) { + Path dir = dirPath(genStateDir); + if (!Files.isDirectory(dir)) return List.of(); + try (Stream s = Files.list(dir)) { + return s.filter(p -> p.getFileName().toString().endsWith(".json") && Files.isRegularFile(p)) + .sorted(Comparator.comparing(p -> p.getFileName().toString())) + .collect(Collectors.toList()); + } catch (IOException e) { + return List.of(); + } } /** @@ -122,9 +252,15 @@ public static Map loadOwners(Path genStateDir) { return out; } + /** The union of every manifest file: the legacy one underneath, package files in name order on top. */ private static Map entries(Path genStateDir) { Map out = new LinkedHashMap<>(); - Path path = pathFor(genStateDir); + readInto(legacyPath(genStateDir), out); + for (Path p : packageFiles(genStateDir)) readInto(p, out); + return out; + } + + private static Map readInto(Path path, Map out) { if (!Files.isRegularFile(path)) return out; JsonElement parsed; try { @@ -139,40 +275,142 @@ private static Map entries(Path genStateDir) { return out; } + /** The package file each key is recorded in now (a key only in the legacy file is not listed). */ + private static Map fileOfKeys(Path genStateDir) { + Map out = new LinkedHashMap<>(); + for (Path p : packageFiles(genStateDir)) { + for (String key : readInto(p, new LinkedHashMap<>()).keySet()) out.put(key, p.getFileName().toString()); + } + return out; + } + private static String stringField(JsonObject object, String field) { JsonElement v = object.get(field); return v != null && v.isJsonPrimitive() && v.getAsJsonPrimitive().isString() ? v.getAsString() : null; } + /** {@link #save(Path, Map, Map, Placement)} with no model: each entry stays in the file it is in, else the root. */ + public static void save(Path genStateDir, Map hashes, Map owners) { + save(genStateDir, hashes, owners, null); + } + /** - * Persist the manifest with SORTED keys, pretty-printed, one trailing newline. A key - * with an owner is written as {@code { "hash", "generator", "outputDir" }}, one without - * as the plain hash. Sorted because the file is committed: insertion order would make - * the diff — and any merge conflict between two people who both regenerated — depend - * on which generator happened to run first. + * Persist the manifest as one file per package: each file holds exactly what the single + * manifest held for its paths, with SORTED keys, pretty-printed, one trailing newline. A key + * with an owner is written as {@code { "hash", "generator", "outputDir" }}, one without as + * the plain hash; any other field the entry already carried (another port's provenance) is + * kept. Sorted because the files are committed: insertion order would make the diff, and + * any merge between two people who both regenerated, depend on which generator ran first. + * + *

Each entry is filed by {@code placement} ({@code null}: where it already is, else the + * root). Only files whose bytes change are written, a package file left empty is deleted, + * the root file stays as {@code {}} when nothing is recorded at all, and the legacy single + * file is removed. */ - public static void save(Path genStateDir, Map hashes, Map owners) { + public static void save(Path genStateDir, Map hashes, Map owners, + Placement placement) { try { - Files.createDirectories(genStateDir); - JsonObject root = new JsonObject(); + Map existing = entries(genStateDir); + Map currentFile = placement == null ? fileOfKeys(genStateDir) : Map.of(); + Map files = new java.util.TreeMap<>(); for (Map.Entry e : new TreeMap<>(hashes).entrySet()) { - Owner owner = owners.get(e.getKey()); - if (owner == null) { - root.addProperty(e.getKey(), e.getValue()); + String key = e.getKey(); + Owner owner = owners.get(key); + JsonElement prior = existing.get(key); + JsonObject extras = new JsonObject(); + if (prior != null && prior.isJsonObject()) { + for (Map.Entry f : prior.getAsJsonObject().entrySet()) { + String name = f.getKey(); + if (!name.equals("hash") && !name.equals("generator") && !name.equals("outputDir") + && !name.equals("owner")) { + extras.add(name, f.getValue()); + } + } + } + JsonElement value; + if (owner == null && extras.size() == 0) { + value = new com.google.gson.JsonPrimitive(e.getValue()); } else { JsonObject entry = new JsonObject(); entry.addProperty("hash", e.getValue()); - entry.addProperty("generator", owner.generator()); - entry.addProperty("outputDir", owner.outputDir()); - root.add(e.getKey(), entry); + if (owner != null) { + entry.addProperty("generator", owner.generator()); + entry.addProperty("outputDir", owner.outputDir()); + } + for (Map.Entry f : extras.entrySet()) entry.add(f.getKey(), f.getValue()); + value = entry; } + String file = placement != null + ? fileName(placement.packageOf(key, value.isJsonObject() ? value.getAsJsonObject() : null)) + : currentFile.getOrDefault(key, ROOT_FILE_NAME); + files.computeIfAbsent(file, k -> new JsonObject()).add(key, value); + } + if (files.isEmpty()) files.put(ROOT_FILE_NAME, new JsonObject()); + + Path dir = dirPath(genStateDir); + Files.createDirectories(dir); + for (Map.Entry f : files.entrySet()) { + writeIfChanged(dir.resolve(f.getKey()), GSON.toJson(f.getValue()) + "\n"); + } + for (Path stale : packageFiles(genStateDir)) { + if (!files.containsKey(stale.getFileName().toString())) Files.delete(stale); } - Files.writeString(pathFor(genStateDir), GSON.toJson(root) + "\n", StandardCharsets.UTF_8); + if (Files.deleteIfExists(legacyPath(genStateDir))) ensureGitignore(genStateDir); // only a migrating write } catch (IOException e) { throw new UncheckedIOException("Could not write codegen hash manifest at " + genStateDir, e); } } + private static void writeIfChanged(Path path, String text) throws IOException { + if (Files.isRegularFile(path) && Files.readString(path, StandardCharsets.UTF_8).equals(text)) return; + Files.writeString(path, text, StandardCharsets.UTF_8); + } + + private static final String GITIGNORE_RULE = ".gen-state/*"; + private static final String GITIGNORE_LEGACY_NEGATION = "!.gen-state/.hashes.json"; + private static final String GITIGNORE_DIR_NEGATION = "!.gen-state/.hashes/"; + + /** + * Run by a migrating write only. The scaffolded {@code .metaobjects/.gitignore} ignores + * {@code .gen-state/*} and re-includes the manifest; the new directory needs its own negation. + * With the rule present, the legacy negation is replaced by {@code !.gen-state/.hashes/} (or the + * new line goes right after the rule when there was none); a file that already has the new line + * only loses the legacy one. A file with no such rule is left alone. + */ + private static void ensureGitignore(Path genStateDir) throws IOException { + Path parent = genStateDir.toAbsolutePath().getParent(); + if (parent == null) return; + Path file = parent.resolve(".gitignore"); + if (!Files.isRegularFile(file)) return; + String[] lines = Files.readString(file, StandardCharsets.UTF_8).split("\n", -1); + boolean hasRule = false; + boolean hasNew = false; + for (String l : lines) { + String t = l.trim(); + if (t.equals(GITIGNORE_RULE)) hasRule = true; + if (t.equals(GITIGNORE_DIR_NEGATION)) hasNew = true; + } + if (!hasRule) return; + List out = new ArrayList<>(); + boolean added = hasNew; + boolean afterRule = false; + for (String l : lines) { + String t = l.trim(); + if (t.equals(GITIGNORE_LEGACY_NEGATION)) { + if (!added) { out.add(GITIGNORE_DIR_NEGATION); added = true; } + continue; + } + out.add(l); + if (t.equals(GITIGNORE_RULE)) afterRule = true; + } + if (!added && afterRule) { + int at = out.indexOf(GITIGNORE_RULE) + 1; + out.add(at, GITIGNORE_DIR_NEGATION); + } + String text = String.join("\n", out); + if (!text.equals(String.join("\n", lines))) Files.writeString(file, text, StandardCharsets.UTF_8); + } + /** Record that {@code owner} wrote {@code key} with {@code content}: load, mutate, save. */ public static void record(Path genStateDir, String key, String content, Owner owner) { recordHash(genStateDir, key, contentHash(content), owner); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/OrphanSweep.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/OrphanSweep.java index 021dbb0b7e..7e0fbc8d9c 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/OrphanSweep.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/OrphanSweep.java @@ -159,6 +159,13 @@ public static boolean isCandidate(HashManifest.Owner owner, boolean inRunDir, */ public static Result sweep(Path genStateDir, Path projectRoot, List dirs, Set emitted, Set runOwners, Supplier> configured) { + return sweep(genStateDir, projectRoot, dirs, emitted, runOwners, configured, null); + } + + /** {@link #sweep} that files the surviving entries by {@code placement} ({@code null}: where they are). */ + public static Result sweep(Path genStateDir, Path projectRoot, List dirs, Set emitted, + Set runOwners, Supplier> configured, + HashManifest.Placement placement) { if (!HashManifest.exists(genStateDir)) { return new Result(List.of(), List.of(), List.of()); } @@ -216,7 +223,7 @@ public static Result sweep(Path genStateDir, Path projectRoot, List dirs, if (!forget.isEmpty()) { Map updated = new LinkedHashMap<>(hashes); for (String key : forget) updated.remove(key); - HashManifest.save(genStateDir, updated, owners); + HashManifest.save(genStateDir, updated, owners, placement); } removed.sort(String::compareTo); diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java index 2747ef9cb9..9d0a0bfed9 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java @@ -285,16 +285,16 @@ public void runThatChangesNothing_leavesTheManifestFileAlone() throws Exception Path out = project.resolve("gen/X.java"); Files.createDirectories(out.getParent()); Files.writeString(out, GENERATED_BODY); - Files.createDirectories(genState); + Files.createDirectories(genState.resolve(".hashes")); String manifest = "{\"gen/X.java\": \"" + HashManifest.contentHash(GENERATED_BODY) + "\"}"; - Files.writeString(genState.resolve(".hashes.json"), manifest); + Files.writeString(genState.resolve(".hashes/.root.json"), manifest); try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { run.configureManifest(genState, project); assertEquals(GeneratedFileWriter.Outcome.UNCHANGED, GeneratedFileWriter.write(out, GENERATED_BODY)); } assertEquals("not rewritten (a rewrite would pretty-print it)", manifest, - Files.readString(genState.resolve(".hashes.json"))); + Files.readString(genState.resolve(".hashes/.root.json"))); } @Test @@ -519,7 +519,7 @@ public void aRunThatChangesNothingLeavesTheManifestAlone() throws Exception { run.configureManifest(genState, project); GeneratedFileWriter.write(out, GENERATED_BODY); } - Path manifest = genState.resolve(".hashes.json"); + Path manifest = genState.resolve(".hashes/.root.json"); String before = Files.readString(manifest); Files.setLastModifiedTime(manifest, LONG_AGO); diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java new file mode 100644 index 0000000000..5ab8f378f5 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java @@ -0,0 +1,255 @@ +package com.metaobjects.generator.util; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** ADR-0064 Amendment 1: the hash manifest is one file per model package. Runs the shared vectors. */ +public class HashManifestPackagesTest { + + private static final Path VECTORS = Path.of("../../../fixtures/codegen-skip-conformance/manifests.json"); + private static final FileTime LONG_AGO = FileTime.fromMillis(1_000_000_000_000L); + private static final HashManifest.Owner OWNER = new HashManifest.Owner("entity", "gen"); + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private JsonObject vectors() throws IOException { + return JsonParser.parseString(Files.readString(VECTORS)).getAsJsonObject(); + } + + private HashManifest.Placement placement(JsonObject v) { + List objects = new ArrayList<>(); + for (JsonElement el : v.getAsJsonArray("objects")) { + JsonObject o = el.getAsJsonObject(); + objects.add(new HashManifest.ModelObject(o.get("name").getAsString(), o.get("package").getAsString())); + } + return new HashManifest.Placement(objects); + } + + private static String nullable(JsonElement el) { + return el == null || el.isJsonNull() ? null : el.getAsString(); + } + + private Path genState() { + return tmp.getRoot().toPath().resolve(".metaobjects/.gen-state"); + } + + private static String textOf(Path file) throws IOException { + return Files.readString(file); + } + + private Map filesIn(Path dir) throws IOException { + Map out = new LinkedHashMap<>(); + try (var s = Files.list(dir)) { + for (Path p : s.sorted().toList()) out.put(p.getFileName().toString(), Files.readString(p)); + } + return out; + } + + @Test + public void fileNames() throws Exception { + for (JsonElement el : vectors().getAsJsonArray("fileNames")) { + JsonObject c = el.getAsJsonObject(); + assertEquals(nullable(c.get("package")), c.get("file").getAsString(), + HashManifest.fileName(nullable(c.get("package")))); + } + } + + @Test + public void placement() throws Exception { + JsonObject v = vectors(); + HashManifest.Placement placement = placement(v); + for (JsonElement el : v.getAsJsonArray("placement")) { + JsonObject c = el.getAsJsonObject(); + JsonObject entry = c.has("entry") ? c.getAsJsonObject("entry") : null; + assertEquals(c.get("path").getAsString() + ": " + nullable(c.get("why")), + nullable(c.get("package")), placement.packageOf(c.get("path").getAsString(), entry)); + } + } + + @Test + public void legacySplit() throws Exception { + JsonObject v = vectors(); + JsonObject split = v.getAsJsonObject("legacySplit"); + Path gs = genState(); + Files.createDirectories(gs); + Files.writeString(gs.resolve(".hashes.json"), split.getAsJsonObject("legacy").toString()); + Path gitignore = gs.getParent().resolve(".gitignore"); + Files.writeString(gitignore, split.get("gitignoreBefore").getAsString()); + + Map hashes = HashManifest.load(gs); + Map owners = HashManifest.loadOwners(gs); + HashManifest.save(gs, hashes, owners, placement(v)); + + assertFalse("the legacy file is removed", Files.exists(gs.resolve(".hashes.json"))); + Map written = filesIn(gs.resolve(".hashes")); + JsonObject expected = split.getAsJsonObject("files"); + assertEquals(new TreeSet<>(expected.keySet()), new TreeSet<>(written.keySet())); + for (String name : expected.keySet()) { + assertEquals(name, expected.get(name), JsonParser.parseString(written.get(name))); + } + assertEquals(split.get("goldenText").getAsString(), written.get(split.get("goldenFile").getAsString())); + assertEquals(split.get("gitignoreAfter").getAsString(), Files.readString(gitignore)); + + // A second identical write changes no file. + for (Path p : Files.list(gs.resolve(".hashes")).toList()) Files.setLastModifiedTime(p, LONG_AGO); + HashManifest.save(gs, HashManifest.load(gs), HashManifest.loadOwners(gs), placement(v)); + assertEquals(written, filesIn(gs.resolve(".hashes"))); + for (Path p : Files.list(gs.resolve(".hashes")).toList()) { + assertEquals(p.toString(), LONG_AGO, Files.getLastModifiedTime(p)); + } + assertEquals(split.get("gitignoreAfter").getAsString(), Files.readString(gitignore)); + } + + @Test + public void gitignoreIsTouchedOnlyByAMigratingWrite() throws Exception { + Path gs = genState(); + Files.createDirectories(gs); + Path gitignore = gs.getParent().resolve(".gitignore"); + String legacyIgnore = ".gen-state/*\n!.gen-state/.hashes.json\n"; + Files.writeString(gitignore, legacyIgnore); + // A non-migrating save leaves it untouched, even with the legacy line in it. + HashManifest.record(gs, "gen/A.java", "a", OWNER); + assertEquals(legacyIgnore, Files.readString(gitignore)); + // A migrating write replaces the legacy negation. + Files.writeString(gs.resolve(".hashes.json"), "{\"gen/B.java\":\"b\"}"); + HashManifest.record(gs, "gen/C.java", "c", OWNER); + assertEquals(".gen-state/*\n!.gen-state/.hashes/\n", Files.readString(gitignore)); + } + + @Test + public void migrationInsertsAfterTheRuleOrOnlyDropsTheLegacyLine() throws Exception { + Path gs = genState(); + Files.createDirectories(gs); + Path gitignore = gs.getParent().resolve(".gitignore"); + Files.writeString(gs.resolve(".hashes.json"), "{\"gen/B.java\":\"b\"}"); + Files.writeString(gitignore, ".gen-state/*\n"); + HashManifest.record(gs, "gen/C.java", "c", OWNER); + assertEquals(".gen-state/*\n!.gen-state/.hashes/\n", Files.readString(gitignore)); + + Files.writeString(gs.resolve(".hashes.json"), "{\"gen/B.java\":\"b\"}"); + Files.writeString(gitignore, ".gen-state/*\n!.gen-state/.hashes.json\n!.gen-state/.hashes/\n"); + HashManifest.record(gs, "gen/D.java", "d", OWNER); + assertEquals(".gen-state/*\n!.gen-state/.hashes/\n", Files.readString(gitignore)); + + Files.writeString(gs.resolve(".hashes.json"), "{\"gen/B.java\":\"b\"}"); + String other = "node_modules/\n!.gen-state/.hashes.json\n"; + Files.writeString(gitignore, other); + HashManifest.record(gs, "gen/E.java", "e", OWNER); + assertEquals("no .gen-state/* rule: untouched", other, Files.readString(gitignore)); + } + + private HashManifest.Placement twoPackages() { + return new HashManifest.Placement(List.of( + new HashManifest.ModelObject("Order", "acme::shop"), + new HashManifest.ModelObject("Customer", "acme::crm"))); + } + + private void save(Path gs, Map hashes, HashManifest.Placement p) { + Map owners = new LinkedHashMap<>(); + for (String k : hashes.keySet()) owners.put(k, OWNER); + HashManifest.save(gs, hashes, owners, p); + } + + @Test + public void differentPackagesDifferentFiles() throws Exception { + Path gs = genState(); + Map hashes = new LinkedHashMap<>(); + hashes.put("gen/Order.java", "h1"); + hashes.put("gen/Customer.java", "h2"); + hashes.put("gen/index.java", "h3"); + save(gs, hashes, twoPackages()); + Path dir = gs.resolve(".hashes"); + assertEquals(new TreeSet<>(List.of(".root.json", "acme.crm.json", "acme.shop.json")), + new TreeSet<>(filesIn(dir).keySet())); + for (Path p : Files.list(dir).toList()) Files.setLastModifiedTime(p, LONG_AGO); + Map before = filesIn(dir); + + // A no-op save writes nothing. + save(gs, hashes, twoPackages()); + assertEquals(before, filesIn(dir)); + for (Path p : Files.list(dir).toList()) assertEquals(LONG_AGO, Files.getLastModifiedTime(p)); + + // A change in one package changes only that package's file. + hashes.put("gen/Order.java", "h1b"); + save(gs, hashes, twoPackages()); + Map after = filesIn(dir); + assertTrue(after.get("acme.shop.json").contains("h1b")); + assertEquals(before.get("acme.crm.json"), after.get("acme.crm.json")); + assertEquals(before.get(".root.json"), after.get(".root.json")); + assertTrue(Files.getLastModifiedTime(dir.resolve("acme.shop.json")).compareTo(LONG_AGO) > 0); + assertEquals(LONG_AGO, Files.getLastModifiedTime(dir.resolve("acme.crm.json"))); + assertEquals(LONG_AGO, Files.getLastModifiedTime(dir.resolve(".root.json"))); + + // Removing a package's last entry deletes its file. + hashes.remove("gen/Customer.java"); + save(gs, hashes, twoPackages()); + assertFalse(Files.exists(dir.resolve("acme.crm.json"))); + assertTrue(Files.exists(dir.resolve("acme.shop.json"))); + + // An empty manifest keeps the root file as {}. + save(gs, new LinkedHashMap<>(), twoPackages()); + assertEquals(java.util.Set.of(".root.json"), filesIn(dir).keySet()); + assertEquals("{}\n", textOf(dir.resolve(".root.json"))); + assertTrue(HashManifest.exists(gs)); + } + + @Test + public void withoutAModelAnEntryStaysWhereItIs() throws Exception { + Path gs = genState(); + save(gs, new LinkedHashMap<>(Map.of("gen/Order.java", "h1", "gen/Other.java", "h2")), twoPackages()); + Path dir = gs.resolve(".hashes"); + assertTrue(Files.exists(dir.resolve("acme.shop.json"))); + HashManifest.record(gs, "gen/New.java", "n", OWNER); // no model: a new entry is root, the rest stay + assertTrue(textOf(dir.resolve("acme.shop.json")).contains("gen/Order.java")); + assertTrue(textOf(dir.resolve(".root.json")).contains("gen/New.java")); + assertTrue(textOf(dir.resolve(".root.json")).contains("gen/Other.java")); + } + + @Test + public void readOnlyLoadOfALegacyManifestMigratesNothing() throws Exception { + Path gs = genState(); + Files.createDirectories(gs); + String legacy = "{\"gen/A.java\":\"h\"}"; + Files.writeString(gs.resolve(".hashes.json"), legacy); + Files.writeString(gs.getParent().resolve(".gitignore"), ".gen-state/*\n!.gen-state/.hashes.json\n"); + + assertTrue(HashManifest.exists(gs)); + assertTrue(HashManifest.hasLegacy(gs)); + assertEquals("h", HashManifest.load(gs).get("gen/A.java")); + HashManifest.loadOwners(gs); + + assertEquals(legacy, Files.readString(gs.resolve(".hashes.json"))); + assertFalse(Files.exists(gs.resolve(".hashes"))); + assertEquals(".gen-state/*\n!.gen-state/.hashes.json\n", Files.readString(gs.getParent().resolve(".gitignore"))); + } + + @Test + public void aPackageFileWinsOverTheLegacyFile() throws Exception { + Path gs = genState(); + Files.createDirectories(gs.resolve(".hashes")); + Files.writeString(gs.resolve(".hashes.json"), "{\"gen/A.java\":\"old\",\"gen/B.java\":\"b\"}"); + Files.writeString(gs.resolve(".hashes/acme.shop.json"), "{\"gen/A.java\":\"new\"}\n"); + Map loaded = HashManifest.load(gs); + assertEquals("new", loaded.get("gen/A.java")); + assertEquals("b", loaded.get("gen/B.java")); + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestTest.java index 062bd337f7..0367576c83 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestTest.java @@ -57,7 +57,7 @@ public void savedFileIsSortedPrettyAndTrailingNewline() throws Exception { HashManifest.record(genState, "src/Z.java", "z", OWNER); HashManifest.record(genState, "src/A.java", "a", OWNER); - String raw = Files.readString(genState.resolve(".hashes.json")); + String raw = Files.readString(genState.resolve(".hashes/.root.json")); assertTrue("expected a trailing newline", raw.endsWith("\n")); // Sorted: A before Z. assertTrue(raw.indexOf("src/A.java") < raw.indexOf("src/Z.java")); @@ -108,7 +108,7 @@ public void ownedEntryIsWrittenWithItsOwner_plainAndExecutionIdEntriesReadAsUnow assertEquals(Map.of("src/Owned.java", OWNER), owners); com.google.gson.JsonObject raw = com.google.gson.JsonParser.parseString( - Files.readString(genState.resolve(".hashes.json"))).getAsJsonObject(); + Files.readString(genState.resolve(".hashes/.root.json"))).getAsJsonObject(); assertEquals("abc", raw.get("src/Plain.java").getAsString()); assertEquals("def", raw.get("src/Legacy.java").getAsString()); com.google.gson.JsonObject owned = raw.getAsJsonObject("src/Owned.java"); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java index b8ee63edc7..496915ea46 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java @@ -588,6 +588,8 @@ private boolean planWholeRun(MetaDataLoader loader) { // the stored fingerprint alone: the recorded output hashes already stop a later full run // from trusting a file this run changed. if ( narrowed() ) return false; + // A manifest still in the pre-1.3.0 single-file form is migrated by this run's write, so it runs. + if ( HashManifest.hasLegacy(genStateDir) ) return false; try { fingerprintFile = GenFingerprint.fileFor(genStateDir, fingerprintOwnerTag()); fingerprintBase = fingerprintInputs(loader); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java index 62b97cdf37..d1c4b059e0 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java @@ -154,6 +154,7 @@ protected void executeGenerators(MetaDataLoader loader, List generato try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { if (genStateDir != null) { run.configureManifest(genStateDir, projectRoot); + run.placeBy(placementOf(loader)); } // Every output dir THIS EXECUTION's generators write to, with the handEdits @@ -189,13 +190,14 @@ protected void executeGenerators(MetaDataLoader loader, List generato boolean sweepRefused = false; if (migrating) { getLog().info("MetaData Mojo > Recorded the generator and output dir of every generated " - + "file in `.metaobjects/.gen-state/.hashes.json`; this build deletes no orphaned file."); + + "file in `.metaobjects/.gen-state/.hashes/`; this build deletes no orphaned file."); } else if (selected != null) { // A narrowed run did not try to produce the other objects' files, so not // emitting them says nothing about whether they are orphans. getLog().info("MetaData Mojo > Deleted no orphaned file: meta.entities narrowed this build."); } else if (genStateDir != null) { - sweepRefused = sweepOrphans(genStateDir, projectRoot, handEditsByDir, emittedThisBuild, runOwners); + sweepRefused = sweepOrphans(genStateDir, projectRoot, handEditsByDir, emittedThisBuild, runOwners, + run.placement()); } reportManifestNotices(run, genStateDir, hadManifestAtStart); @@ -277,7 +279,8 @@ private void noteOwnedStock() { * generator the module configures in no execution any more. */ private boolean sweepOrphans(Path genStateDir, Path projectRoot, Map> handEditsByDir, - Set emitted, Set runOwners) { + Set emitted, Set runOwners, + HashManifest.Placement placement) { List dirs = new ArrayList<>(); for (Map.Entry> e : handEditsByDir.entrySet()) { boolean allOverwrite = !e.getValue().isEmpty() && e.getValue().stream() @@ -285,7 +288,7 @@ private boolean sweepOrphans(Path genStateDir, Path projectRoot, Map Removed orphaned generated file no longer produced: " + path); } @@ -335,6 +338,18 @@ private Set refuseSharedPaths(Map> e return emittedThisBuild; } + /** Where manifest entries are filed (ADR-0064 Amendment 1): the loaded model's root-level objects, by name and package. */ + static HashManifest.Placement placementOf(MetaDataLoader loader) { + if (loader == null) return null; + List objects = new ArrayList<>(); + for (com.metaobjects.object.MetaObject child : loader.getRoot().getChildren(com.metaobjects.object.MetaObject.class, false)) { + // getName() is package-qualified ("pkg::Name"); placement matches the bare name. + String name = child.getName() == null ? "" : child.getName(); + objects.add(new HashManifest.ModelObject(name.substring(name.lastIndexOf("::") + 2), child.getPackage())); + } + return new HashManifest.Placement(objects); + } + private record Emission(HashManifest.Owner owner, String hash) {} /** @@ -362,16 +377,16 @@ private void reportManifestNotices(GeneratedFileWriter.Run run, Path genStateDir String lead = hadManifestAtStart ? OWNER + ": adopted " + run.adoptedPaths().size() + " existing generated file(s) into the codegen hash manifest " - + "`.metaobjects/.gen-state/.hashes.json`." + + "`.metaobjects/.gen-state/.hashes/`." : OWNER + ": created the codegen hash manifest " - + "`.metaobjects/.gen-state/.hashes.json` and adopted " + run.adoptedPaths().size() + + "`.metaobjects/.gen-state/.hashes/` and adopted " + run.adoptedPaths().size() + " existing generated file(s) into it."; getLog().warn(lead + " Commit it: it is how the next run tells a file it generated " + "from one you edited, and how it removes files no generator emits any more."); } if (run.untrackedCount() > 0) { getLog().warn(run.untrackedCount() + " generated file(s) were written outside the project " - + "root and are not recorded in `.metaobjects/.gen-state/.hashes.json`, so " + + "root and are not recorded in `.metaobjects/.gen-state/.hashes/`, so " + "hand-edit protection does not apply to them beyond the GENERATED marker rule."); } } diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DeclaresNothingWritesNothingTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DeclaresNothingWritesNothingTest.java index 681789f7e1..0e3c33375d 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DeclaresNothingWritesNothingTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DeclaresNothingWritesNothingTest.java @@ -92,7 +92,8 @@ public void java_aPomThatListsOnlyEntityGetsItsClassesAndNoExtractorOrApiReferen assertEquals(List.of( // The codegen hash manifest — not a generator's output, but something every // `generate` run now writes/updates alongside it (see HashManifest). - ".metaobjects/.gen-state/.hashes.json", + ".metaobjects/.gen-state/.hashes/.root.json", + ".metaobjects/.gen-state/.hashes/verify.demo.json", "generated/META-INF/services/com.metaobjects.registry.ObjectClassBindingProvider", "generated/com/metaobjects/generated/GeneratedObjectClassBindingProvider.java", "generated/verify/demo/Gadget.java", @@ -109,7 +110,7 @@ public void kotlin_aPomThatListsOnlyEntityGetsItsFilesAndNoApiReference() throws assertFalse("the listed generator wrote nothing", written.isEmpty()); assertTrue("a file the entry did not declare: " + written, written.stream().allMatch(f -> - f.equals(".metaobjects/.gen-state/.hashes.json") + f.startsWith(".metaobjects/.gen-state/.hashes/") || (f.startsWith("generated/verify/demo/") && f.endsWith(".kt")))); } } diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java index e6e72d6d47..690a7f6c95 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java @@ -22,6 +22,7 @@ import java.util.Map; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -299,6 +300,22 @@ private void applyChange(String id) throws Exception { case "selection-changed" -> lax = true; case "declared-extra-edited" -> Files.writeString(project.resolve("lookup.txt"), "lookup 2"); case "uncacheable-generator" -> { } // set up before the first run + case "legacy-manifest" -> { + // Put the manifest back in its pre-1.3.0 form: every file of .hashes/ merged into one .hashes.json. + Path gs = project.resolve(".metaobjects/.gen-state"); + assertTrue("a package manifest exists after the first run", Files.isDirectory(gs.resolve(".hashes"))); + JsonObject merged = new JsonObject(); + try (var s = Files.list(gs.resolve(".hashes"))) { + for (Path f : s.sorted().toList()) { + for (var e : JsonParser.parseString(Files.readString(f)).getAsJsonObject().entrySet()) { + merged.add(e.getKey(), e.getValue()); + } + } + } + Files.writeString(gs.resolve(".hashes.json"), merged + "\n"); + deleteTree(gs.resolve(".hashes")); + Files.delete(gs.resolve(".hashes")); + } case "generated-file-deleted" -> Files.delete(project.resolve("gen/Out.java")); case "generated-file-edited" -> Files.writeString(project.resolve("gen/Out.java"), Files.readString(project.resolve("gen/Out.java")) + "// hand edit\n"); @@ -375,11 +392,21 @@ private void runCase(String id, String expectGen, String expectVerify) throws Ex } ci = null; verifyFull = false; + if (id.equals("legacy-manifest")) { + Path gs = project.resolve(".metaobjects/.gen-state"); + assertTrue("a read-only verify migrates nothing", Files.isRegularFile(gs.resolve(".hashes.json"))); + assertFalse("a read-only verify writes no package manifest", Files.exists(gs.resolve(".hashes"))); + } int before = FixtureGenerator.runs; gen(id.equals("force")); boolean ran = FixtureGenerator.runs > before; assertEquals(id + ": gen " + expectGen, expectGen.equals("regenerate"), ran); + if (id.equals("legacy-manifest")) { + Path gs = project.resolve(".metaobjects/.gen-state"); + assertFalse("the write run removed the legacy manifest", Files.exists(gs.resolve(".hashes.json"))); + assertTrue("and left package manifests", Files.isRegularFile(gs.resolve(".hashes/.root.json"))); + } } private void setUp0() throws IOException { diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/PerPackageManifestTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/PerPackageManifestTest.java new file mode 100644 index 0000000000..8f186d1e93 --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/PerPackageManifestTest.java @@ -0,0 +1,91 @@ +package com.metaobjects.mojo; + +import com.metaobjects.generator.direct.object.javacode.JavaObjectCodeGenerator; +import com.metaobjects.generator.util.HashManifest; +import org.apache.maven.project.MavenProject; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** ADR-0064 Amendment 1, end to end: a gen over a two-package model writes one manifest file per package. */ +public class PerPackageManifestTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private Path module; + + private MetaDataGeneratorMojo generate() throws Exception { + return generate(""); + } + + private MetaDataGeneratorMojo generate(String extraChildren) throws Exception { + module = tmp.getRoot().toPath().resolve("module"); + Files.createDirectories(module.resolve("metaobjects")); + Files.writeString(module.resolve("metaobjects/meta.shop.json"), """ + {"metadata.root": {"package": "acme::shop", "children": [ + {"object.entity": {"name": "Order", "children": [ {"field.long": {"name": "id"}} ]}}EXTRA + ]}} + """.replace("EXTRA", extraChildren)); + Files.writeString(module.resolve("metaobjects/meta.crm.json"), """ + {"metadata.root": {"package": "acme::crm", "children": [ + {"object.entity": {"name": "Customer", "children": [ {"field.long": {"name": "id"}} ]}} + ]}} + """); + MetaDataGeneratorMojo mojo = new MetaDataGeneratorMojo(); + MavenProject project = Mockito.mock(MavenProject.class); + Mockito.when(project.getBasedir()).thenReturn(module.toFile()); + mojo.project = project; + mojo.setLoader(LoaderParam.builder("per-package") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(module.resolve("metaobjects").toString()) + .build()); + mojo.setGenerators(new ArrayList<>(List.of(GeneratorParam.builder(JavaObjectCodeGenerator.class.getName()) + .withArg("outputDir", "generated").withArg("type", "class").withArg("flavor", "pojoAware").build()))); + mojo.setGlobals(java.util.Collections.emptyMap()); + return mojo; + } + + private List manifestFiles() throws Exception { + try (Stream s = Files.list(module.resolve(".metaobjects/.gen-state/.hashes"))) { + return s.map(p -> p.getFileName().toString()).sorted().toList(); + } + } + + @Test + public void aMultiPackageModelWritesOneManifestPerPackageAndARootOne() throws Exception { + generate().execute(); + + assertEquals(List.of(".root.json", "acme.crm.json", "acme.shop.json"), manifestFiles()); + Path dir = module.resolve(".metaobjects/.gen-state/.hashes"); + assertTrue(Files.readString(dir.resolve("acme.shop.json")).contains("Order.java")); + assertFalse(Files.readString(dir.resolve("acme.shop.json")).contains("Customer.java")); + assertTrue(Files.readString(dir.resolve("acme.crm.json")).contains("Customer.java")); + assertFalse(Files.exists(module.resolve(".metaobjects/.gen-state/.hashes.json"))); + // Every path is still found through the one flat reader. + assertEquals(new TreeSet<>(List.of("generated/acme/shop/Order.java", "generated/acme/crm/Customer.java")), + new TreeSet<>(HashManifest.load(module.resolve(".metaobjects/.gen-state")).keySet().stream() + .filter(k -> k.endsWith("Order.java") || k.endsWith("Customer.java")).toList())); + } + + @Test + public void aNonObjectRootNodeNamedLikeAFileDoesNotChangePlacement() throws Exception { + // A template named "Customer" in acme::shop must not claim Customer.java away from acme::crm. + generate(",\n {\"object.value\": {\"name\": \"Payload\", \"children\": [ {\"field.string\": {\"name\": \"x\"}} ]}},\n {\"template.output\": {\"name\": \"Customer\", \"@payloadRef\": \"acme::shop::Payload\", \"@textRef\": \"p/customer\"}}").execute(); + Path dir = module.resolve(".metaobjects/.gen-state/.hashes"); + assertTrue(Files.readString(dir.resolve("acme.crm.json")).contains("Customer.java")); + assertFalse(Files.exists(dir.resolve("acme.shop.json")) && Files.readString(dir.resolve("acme.shop.json")).contains("Customer.java")); + } +} diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 468568f07c..0f82b625dd 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -114,11 +114,14 @@ from metaobjects.codegen.overwrite_policy import ( STATUS_SKIPPED, STATUS_UNCHANGED, + HASHES_FILE, HashManifest, has_hash_manifest, is_pristine_generated, manifest_batch, + objects_of_root, read_generated_hash, + set_placement_objects, ) from metaobjects.codegen.project_config import ( CONFIG_FILENAME, @@ -969,7 +972,7 @@ def _run_suite( # The hash manifest gives `metaobjects gen` hand-edit detection: without it the # write path falls back to the legacy @generated-marker rule, which cannot tell an # edited generated file from a pristine one (an edited file keeps its marker). - # COMMIT `.gen-state/.hashes.json`. + # COMMIT `.gen-state/.hashes/`. # # Anchored on the caller's project, NEVER on `Path.cwd()`. cwd is whatever directory # the process happens to sit in, so a cwd default leaks a `.metaobjects/` into any @@ -2055,6 +2058,8 @@ def _cmd_gen_config_run(args: argparse.Namespace, state: _SkipState) -> int: identity = _skip_identity(args, config, _find_config(args), strict=strict, baseline=baseline) if ( not narrowed + # A legacy manifest is migrated by the next write run (ADR-0064 Amendment 1). + and not os.path.exists(os.path.join(gen_state_dir, HASHES_FILE)) and _skip_matches(config, identity, root) and not getattr(args, "force", False) and baseline != "adopt" @@ -2070,6 +2075,7 @@ def _cmd_gen_config_run(args: argparse.Namespace, state: _SkipState) -> int: sweep_refused: list[str] = [] # Every target and the orphan sweep share one in-memory manifest: one write per run. The # batch closes before the stored key is made, which hashes the manifest as written. + set_placement_objects(gen_state_dir, objects_of_root(root)) with manifest_batch(gen_state_dir): written, errors = _run_gen_targets( config, targets, root, @@ -3457,7 +3463,7 @@ def _build_parser() -> argparse.ArgumentParser: "first-time-on-existing-file behaviour. 'default' refuses a file that cannot " "be proved to be generated output; 'adopt' records the files you have as the " "baseline and writes NOTHING — the one run a project with no committed " - ".gen-state/.hashes.json can perform, since nothing writes a manifest until a " + ".gen-state/.hashes/ can perform, since nothing writes a manifest until a " "gen succeeds. Adopting DECLARES those files to be generated output: the next " "gen regenerates over them, so commit before you run it." ), diff --git a/server/python/src/metaobjects/codegen/config.py b/server/python/src/metaobjects/codegen/config.py index 3b928ff648..09d6d48093 100644 --- a/server/python/src/metaobjects/codegen/config.py +++ b/server/python/src/metaobjects/codegen/config.py @@ -14,9 +14,9 @@ @dataclass class GenConfig: out_dir: str - # Where the codegen hash manifest lives (``/.hashes.json``), which - # records what this generator wrote so a later run can tell its own output from a - # hand edit. None disables that detection and falls back to the legacy + # Where the codegen hash manifest lives (``/.hashes/``, one file per + # package), which records what this generator wrote so a later run can tell its own + # output from a hand edit. None disables that detection and falls back to the legacy # @generated-marker rule — mirroring TS, where a runGen with no projectRoot also # gets weaker guarantees. The CLI always sets it to # ``/.metaobjects/.gen-state``. COMMIT the manifest: it is the only thing diff --git a/server/python/src/metaobjects/codegen/overwrite_policy.py b/server/python/src/metaobjects/codegen/overwrite_policy.py index b62ce7c17e..9a63beec2c 100644 --- a/server/python/src/metaobjects/codegen/overwrite_policy.py +++ b/server/python/src/metaobjects/codegen/overwrite_policy.py @@ -11,8 +11,8 @@ too: a file this generator wrote, whose template later stopped emitting the header, was refused as though it were somebody's hand-written source. -The decision now comes from a hash manifest at ``/.hashes.json``, -recording what we wrote: +The decision now comes from a hash manifest at ``/.hashes/``, +recording what we wrote (one file per model package under ``.hashes/``, ADR-0064 Amendment 1): identical fresh content -> "unchanged" file still hashes to what we wrote -> "overwrite" (nothing is lost) @@ -41,7 +41,15 @@ # status: "new" | "unchanged" | "overwrite" | "refused" | "adopted" | "skipped" +#: The legacy single manifest. Read underneath the per-package files; removed by the next write. HASHES_FILE = ".hashes.json" +#: ADR-0064 Amendment 1: one manifest file per model package lives in this directory. +HASHES_DIR = ".hashes" +#: The manifest for paths that belong to no package. +ROOT_MANIFEST = ".root.json" +_GITIGNORE_RULE = ".gen-state/*" +_GITIGNORE_LEGACY = "!.gen-state/.hashes.json" +_GITIGNORE_DIR = "!.gen-state/.hashes/" def content_hash(content: str) -> str: @@ -66,23 +74,134 @@ def _manifest_path(gen_state_dir: str) -> str: return os.path.join(gen_state_dir, HASHES_FILE) +def _hashes_dir(gen_state_dir: str) -> str: + return os.path.join(gen_state_dir, HASHES_DIR) + + +# --- placement (ADR-0064 Amendment 1, section 3) ---------------------------------------- + + +def package_file_name(package: str | None) -> str: + """The manifest file name for a package; ``None`` (or empty) is the root manifest.""" + if not package: + return ROOT_MANIFEST + segments = [] + for seg in package.split("::"): + out = [] + for byte in seg.encode("utf-8"): + ch = chr(byte) + if byte < 0x80 and (ch.isalnum() or ch in "_-"): + out.append(ch) + else: + out.append(f"%{byte:02X}") + segments.append("".join(out)) + return ".".join(segments) + ".json" + + +def place_entry( + path: str, entry: object, objects: list[tuple[str, str]] +) -> str | None: + """The package a manifest entry is filed under, or ``None`` for the root manifest. + + ``objects`` is the loaded root-level objects as ``(name, package)`` (package ``""`` for + none). A ``sourceNode`` wins; else the object whose name the file's stem begins with. + """ + if isinstance(entry, dict) and isinstance(entry.get("sourceNode"), str): + head = entry["sourceNode"].split(".", 1)[0] + idx = head.rfind("::") + return head[:idx] if idx >= 0 else None + stem = _words(os.path.basename(path).split(".", 1)[0]) + best_len = 0 + packages: set[str] = set() + for name, package in objects: + words = _words(name) + if not words or words != stem[: len(words)]: + continue + if len(words) > best_len: + best_len, packages = len(words), {package} + elif len(words) == best_len: + packages.add(package) + if len(packages) != 1: + return None + return next(iter(packages)) or None + + +def _words(text: str) -> list[str]: + """Lowercase words: split at ``_`` and ``-``, before an uppercase letter that follows a + lowercase letter or digit, and before the last capital of a run followed by a lowercase + letter (``HTTPServer`` is ``http``, ``server``). Digits stay with the word before them.""" + words: list[str] = [] + cur = "" + for i, ch in enumerate(text): + if ch in "_-": + if cur: + words.append(cur) + cur = "" + continue + if ch.isascii() and ch.isupper() and cur: + prev = text[i - 1] + nxt = text[i + 1] if i + 1 < len(text) else "" + lower_before = prev.isascii() and (prev.islower() or prev.isdigit()) + run_end = prev.isascii() and prev.isupper() and nxt.isascii() and nxt.islower() + if lower_before or run_end: + words.append(cur) + cur = "" + cur += ch.lower() if ch.isascii() else ch + if cur: + words.append(cur) + return words + + +def objects_of_root(root: object) -> list[tuple[str, str]]: + """The ``(name, package)`` of every root-level object of a loaded root.""" + from .template_codegen.template_data import package_of # lazy: avoids an import cycle + + # ADR-0039 sanctioned own: top-level scan of the loader ROOT (never extended). + return [ + (c.name, package_of(c)) + for c in root.own_children() # type: ignore[attr-defined] + if c.type == "object" + ] + + +# The loaded model's objects, per gen-state dir, supplied by the runner once the model is +# loaded. Without one the writer keeps each entry where it was found (rule 3). +_placements: dict[str, list[tuple[str, str]] | None] = {} + + +def set_placement_objects(gen_state_dir: str | None, objects: list[tuple[str, str]] | None) -> None: + if gen_state_dir is not None: + _placements[os.path.abspath(gen_state_dir)] = objects + + def has_hash_manifest(gen_state_dir: str) -> bool: - """Whether this project has a manifest AT ALL. + """Whether this project has a manifest AT ALL (the legacy file or a file in ``.hashes/``). Distinct from "the manifest has no entry for this path": a project with no manifest predates the manifest being committed, so all its refusals share one cause and deserve one instruction rather than one warning per file. """ batch = _batches.get(os.path.abspath(gen_state_dir)) - return os.path.exists(_manifest_path(gen_state_dir)) or bool(batch and batch.dirty) + return bool( + os.path.exists(_manifest_path(gen_state_dir)) + or _package_files(gen_state_dir) + or (batch and batch.dirty) + ) + + +def _package_files(gen_state_dir: str) -> list[str]: + try: + return sorted(n for n in os.listdir(_hashes_dir(gen_state_dir)) if n.endswith(".json")) + except OSError: + return [] class _ManifestBatch: __slots__ = ("raw", "dirty") - def __init__(self, raw: dict[str, object]) -> None: + def __init__(self, raw: dict[str, object], dirty: bool = False) -> None: self.raw = raw - self.dirty = False + self.dirty = dirty # One in-memory manifest per gen-state dir while a run is in progress. Without it every @@ -107,7 +226,10 @@ def manifest_batch(gen_state_dir: str | None) -> Iterator[None]: if key in _batches: yield return - batch = _ManifestBatch(_read_manifest_file(gen_state_dir)) + # A legacy manifest makes the run dirty: the next write run migrates it. + batch = _ManifestBatch( + _read_manifest_file(gen_state_dir), os.path.exists(_manifest_path(gen_state_dir)) + ) _batches[key] = batch try: yield @@ -130,10 +252,7 @@ def _read_raw(gen_state_dir: str) -> dict[str, object]: return _read_manifest_file(gen_state_dir) -def _read_manifest_file(gen_state_dir: str) -> dict[str, object]: - path = _manifest_path(gen_state_dir) - if not os.path.exists(path): - return {} +def _read_json_object(path: str) -> dict[str, object]: try: with open(path, encoding="utf-8") as fh: parsed = json.load(fh) @@ -141,9 +260,26 @@ def _read_manifest_file(gen_state_dir: str) -> dict[str, object]: # Unreadable or corrupt reads as ABSENT, which fails closed: every file then # refuses rather than being assumed ours. return {} - if not isinstance(parsed, dict): - return {} - return parsed + return parsed if isinstance(parsed, dict) else {} + + +def _read_union(gen_state_dir: str) -> tuple[dict[str, object], dict[str, str]]: + """The union of every manifest file (legacy underneath, package files in name order + winning), and the file each key was found in (``""`` for the legacy file).""" + merged: dict[str, object] = {} + where: dict[str, str] = {} + for key, value in _read_json_object(_manifest_path(gen_state_dir)).items(): + merged[key] = value + where[key] = "" + for name in _package_files(gen_state_dir): + for key, value in _read_json_object(os.path.join(_hashes_dir(gen_state_dir), name)).items(): + merged[key] = value + where[key] = name + return merged, where + + +def _read_manifest_file(gen_state_dir: str) -> dict[str, object]: + return _read_union(gen_state_dir)[0] def _entry_hash(value: object) -> str | None: @@ -165,7 +301,7 @@ def _load_hashes(gen_state_dir: str) -> dict[str, str]: def _save_hashes(gen_state_dir: str, hashes: dict[str, str]) -> None: raw = _read_raw(gen_state_dir) - # Keys SORTED, because this file is committed. Insertion order would make the + # Keys SORTED, because these files are committed. Insertion order would make the # diff — and any merge conflict between two people who both regenerated — depend # on which entity happened to generate first. ordered: dict[str, object] = {} @@ -183,11 +319,77 @@ def _save_hashes(gen_state_dir: str, hashes: dict[str, str]) -> None: _write_manifest_file(gen_state_dir, ordered) +def _manifest_text(entries: dict[str, object]) -> str: + return json.dumps({k: entries[k] for k in sorted(entries)}, indent=2) + "\n" + + def _write_manifest_file(gen_state_dir: str, ordered: dict[str, object]) -> None: - os.makedirs(gen_state_dir, exist_ok=True) - with open(_manifest_path(gen_state_dir), "w", encoding="utf-8") as fh: - json.dump(ordered, fh, indent=2) - fh.write("\n") + """Write every manifest file whose bytes changed (ADR-0064 Amendment 1, section 4).""" + _, where = _read_union(gen_state_dir) + objects = _placements.get(os.path.abspath(gen_state_dir)) + files: dict[str, dict[str, object]] = {} + for key, entry in ordered.items(): + if objects is not None: + package = place_entry(key, entry, objects) + name = package_file_name(package) + else: + name = where.get(key) or ROOT_MANIFEST + files.setdefault(name, {})[key] = entry + if not ordered: + files[ROOT_MANIFEST] = {} + + directory = _hashes_dir(gen_state_dir) + os.makedirs(directory, exist_ok=True) + for name, entries in files.items(): + text = _manifest_text(entries) + path = os.path.join(directory, name) + try: + with open(path, encoding="utf-8") as fh: + if fh.read() == text: + continue + except OSError: + pass + with open(path, "w", encoding="utf-8") as fh: + fh.write(text) + for name in _package_files(gen_state_dir): + if name not in files: + os.remove(os.path.join(directory, name)) + legacy = _manifest_path(gen_state_dir) + if os.path.exists(legacy): + os.remove(legacy) + _ensure_gitignore(gen_state_dir) + + +def _ensure_gitignore(gen_state_dir: str) -> None: + """Replace the legacy negation with ``!.gen-state/.hashes/`` (or add it after the rule when + there is no legacy line), when the ignore file has the ``.gen-state/*`` rule (``/../.gitignore``).""" + path = os.path.join(os.path.dirname(os.path.abspath(gen_state_dir)), ".gitignore") + try: + with open(path, encoding="utf-8") as fh: + text = fh.read() + except OSError: + return + lines = text.split("\n") + if _GITIGNORE_RULE not in [ln.strip() for ln in lines]: + return + out: list[str] = [] + have_new = _GITIGNORE_DIR in [ln.strip() for ln in lines] + for ln in lines: + if ln.strip() == _GITIGNORE_LEGACY: + if not have_new: # the legacy negation is REPLACED by the directory one + out.append(_GITIGNORE_DIR) + have_new = True + continue + out.append(ln) + if ln.strip() == _GITIGNORE_RULE and not have_new: + # No legacy line anywhere: the new negation follows the rule. + if _GITIGNORE_LEGACY not in [x.strip() for x in lines]: + out.append(_GITIGNORE_DIR) + have_new = True + new_text = "\n".join(out) + if new_text != text: + with open(path, "w", encoding="utf-8") as fh: + fh.write(new_text) class HashManifest: @@ -203,7 +405,8 @@ class HashManifest: def __init__(self, gen_state_dir: str) -> None: self.gen_state_dir = gen_state_dir self.hashes: dict[str, str] = _load_hashes(gen_state_dir) - self.dirty = False + # A legacy manifest is migrated by the next write run, even when nothing else changed. + self.dirty = os.path.exists(_manifest_path(gen_state_dir)) def get(self, rel_path: str, legacy_rel_path: str | None = None) -> str | None: recorded = self.hashes.get(rel_path) diff --git a/server/python/src/metaobjects/codegen/runner.py b/server/python/src/metaobjects/codegen/runner.py index ce22aaabbd..2e18db69b1 100644 --- a/server/python/src/metaobjects/codegen/runner.py +++ b/server/python/src/metaobjects/codegen/runner.py @@ -25,6 +25,8 @@ decide_and_write, has_hash_manifest, manifest_batch, + objects_of_root, + set_placement_objects, ) _VALID_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") @@ -233,6 +235,7 @@ def is_selected(o: MetaObject) -> bool: # Captured BEFORE any write, because the first write creates the manifest — read # it afterwards and every project looks migrated. tracking_hashes = config.gen_state_dir is not None + set_placement_objects(config.gen_state_dir, objects_of_root(metadata)) had_manifest = tracking_hashes and has_hash_manifest(config.gen_state_dir or "") refused: list[str] = [] @@ -294,7 +297,7 @@ def _write_all( else rel ) # A file written OUTSIDE the project has no place in the project's manifest: its - # key would be `../`-relative and committed into `.hashes.json`. It gets the + # key would be `../`-relative and committed into the manifest. It gets the # manifest-less rule a run with no project gets — written, never recorded. outside = bool(config.project_root) and (key.startswith("..") or os.path.isabs(key)) if outside: @@ -334,7 +337,7 @@ def _finish( if untracked: result.warnings.append( f"{untracked} generated file(s) were written outside the project root and are " - f"not recorded in .metaobjects/.gen-state/.hashes.json, so hand-edit protection " + f"not recorded in .metaobjects/.gen-state/.hashes/, so hand-edit protection " f"does not apply to them beyond the @generated header rule." ) @@ -366,7 +369,7 @@ def _finish( f"for a project created before the manifest was committed. ONE-TIME FIX: " f"re-run with --baseline=adopt — it records the files you have as the " f"baseline and writes NOTHING — then commit " - f"'.metaobjects/.gen-state/.hashes.json' and run gen again, where the " + f"'.metaobjects/.gen-state/.hashes/' and run gen again, where the " f"regeneration arrives as its own reviewable diff. Adopting DECLARES these " f"files to be generated output, so an edit already inside one of them is " f"part of the baseline and that regeneration will replace it — commit " @@ -393,7 +396,7 @@ def _finish( ) result.warnings.append( f"Recorded {len(adopted)} existing file(s) as the codegen baseline and wrote " - f"nothing. NEXT: commit '.metaobjects/.gen-state/.hashes.json', then run gen " + f"nothing. NEXT: commit '.metaobjects/.gen-state/.hashes/', then run gen " f"again — these files regenerate normally from here, as their own reviewable " f"diff. Adopting DECLARED them to be generated output: an edit already inside " f"one is part of the baseline and that regeneration will replace it, so check " diff --git a/server/python/src/metaobjects/codegen/skip.py b/server/python/src/metaobjects/codegen/skip.py index 4d05ad3baa..cfa5b6e80c 100644 --- a/server/python/src/metaobjects/codegen/skip.py +++ b/server/python/src/metaobjects/codegen/skip.py @@ -25,13 +25,13 @@ from pathlib import Path from typing import Iterable -from .overwrite_policy import HASHES_FILE, content_hash +from .overwrite_policy import _read_union, content_hash, has_hash_manifest #: Bump when the fingerprint's own recipe changes: every stored fingerprint then misses. FINGERPRINT_FORMAT = 2 #: Where this port keeps its fingerprint, beside the (committed) manifest and never -#: committed itself (``.gen-state/*`` is ignored except ``.hashes.json``). +#: committed itself (``.gen-state/*`` is ignored except ``.hashes/``). FINGERPRINT_FILE = ".fingerprint-python.json" #: The hash of an input that does not exist. A file that appears or disappears changes it. @@ -255,13 +255,10 @@ def current_key( def _manifest_records(gen_state_dir: str) -> dict[str, str] | None: """key -> recorded hash, or ``None`` when there is no readable manifest.""" - try: - with open(os.path.join(gen_state_dir, HASHES_FILE), encoding="utf-8") as fh: - raw = json.load(fh) - except (OSError, ValueError): - return None - if not isinstance(raw, dict): + # The union of every manifest file (ADR-0064 Amendment 1); none at all is "no manifest". + if not has_hash_manifest(gen_state_dir): return None + raw, _where = _read_union(gen_state_dir) records: dict[str, str] = {} for key, value in raw.items(): if isinstance(value, str): diff --git a/server/python/tests/codegen/manifest_helpers.py b/server/python/tests/codegen/manifest_helpers.py new file mode 100644 index 0000000000..47fc1620f1 --- /dev/null +++ b/server/python/tests/codegen/manifest_helpers.py @@ -0,0 +1,31 @@ +"""Read the hash manifest the way the product does: the union of every file (ADR-0064 Amendment 1).""" +from __future__ import annotations + +import json +from pathlib import Path + + +def manifest_files(gen_state: Path) -> dict[str, dict[str, object]]: + """file name -> parsed content, for every file in ``.hashes/``.""" + directory = gen_state / ".hashes" + if not directory.is_dir(): + return {} + return { + p.name: json.loads(p.read_text(encoding="utf-8")) + for p in sorted(directory.glob("*.json")) + } + + +def read_manifest(gen_state: Path) -> dict[str, object]: + """Every recorded entry (the legacy file underneath, package files winning).""" + merged: dict[str, object] = {} + legacy = gen_state / ".hashes.json" + if legacy.exists(): + merged.update(json.loads(legacy.read_text(encoding="utf-8"))) + for entries in manifest_files(gen_state).values(): + merged.update(entries) + return merged + + +def has_manifest(gen_state: Path) -> bool: + return (gen_state / ".hashes.json").exists() or bool(manifest_files(gen_state)) diff --git a/server/python/tests/codegen/test_cli.py b/server/python/tests/codegen/test_cli.py index e30ac6214b..ee0dd202e0 100644 --- a/server/python/tests/codegen/test_cli.py +++ b/server/python/tests/codegen/test_cli.py @@ -14,6 +14,7 @@ from metaobjects.cli import main from tests.codegen.gen_suite import GEN_SUITE from tests.codegen.config_helpers import as_config +from tests.codegen.manifest_helpers import has_manifest, read_manifest FIXTURE = ( Path(__file__).parents[4] @@ -383,9 +384,7 @@ def test_gen_manifest_keys_are_project_relative(tmp_path: Path) -> None: out = tmp_path / "build" / "gen" assert main(as_config(["gen", "--generators", GEN_SUITE, meta_dir, "--out", str(out)])) == 0 - manifest = json.loads( - (tmp_path / ".metaobjects" / ".gen-state" / ".hashes.json").read_text() - ) + manifest = read_manifest(tmp_path / ".metaobjects" / ".gen-state") assert manifest, "gen recorded no manifest" # Every key carries the out dir's path from the project root — the thing that makes # two out dirs distinguishable inside one manifest. @@ -401,9 +400,7 @@ def test_two_out_dirs_write_disjoint_manifest_entries(tmp_path: Path) -> None: assert main(as_config(["gen", "--generators", GEN_SUITE, meta_dir, "--out", str(tmp_path / "a")])) == 0 assert main(as_config(["gen", "--generators", GEN_SUITE, meta_dir, "--out", str(tmp_path / "b")])) == 0 - manifest = json.loads( - (tmp_path / ".metaobjects" / ".gen-state" / ".hashes.json").read_text() - ) + manifest = read_manifest(tmp_path / ".metaobjects" / ".gen-state") assert "a/Program.py" in manifest assert "b/Program.py" in manifest @@ -448,7 +445,7 @@ def test_gen_baseline_adopt_records_without_writing(tmp_path: Path, capsys) -> N assert main(as_config(["gen", "--generators", GEN_SUITE, meta_dir, "--out", str(out), "--baseline=adopt"])) == 0 assert stale.read_text() == "# @generated by metaobjects\n# from an older engine\n" - assert (tmp_path / ".metaobjects" / ".gen-state" / ".hashes.json").exists() + assert has_manifest(tmp_path / ".metaobjects" / ".gen-state") assert "as the codegen baseline" in capsys.readouterr().out diff --git a/server/python/tests/codegen/test_gen_run_core.py b/server/python/tests/codegen/test_gen_run_core.py index 5317a6a591..06fc0d703a 100644 --- a/server/python/tests/codegen/test_gen_run_core.py +++ b/server/python/tests/codegen/test_gen_run_core.py @@ -12,6 +12,7 @@ from metaobjects.cli import main from metaobjects.codegen import overwrite_policy +from tests.codegen.manifest_helpers import read_manifest from tests.codegen.config_helpers import as_config from tests.codegen.gen_suite import GEN_SUITE @@ -49,8 +50,8 @@ def counting(gen_state_dir: str, ordered: dict[str, object]) -> None: def _manifest(tmp_path: Path) -> dict[str, object]: - [path] = list(tmp_path.rglob(".hashes.json")) - return json.loads(path.read_text()) + [state] = {p.parent for p in tmp_path.rglob(".hashes") if p.is_dir()} + return read_manifest(state) def test_a_run_writes_the_manifest_once(tmp_path: Path, manifest_writes: list[str]) -> None: @@ -65,10 +66,11 @@ def test_a_run_writes_the_manifest_once(tmp_path: Path, manifest_writes: list[st # Two files regenerate and are recorded again: still one write. (Deleting a file # alone is not enough: it regenerates to the hash already recorded, which writes # nothing.) - [path] = list(tmp_path.rglob(".hashes.json")) - trimmed = {k: v for k, v in recorded.items() if k not in ("out/Program.py", "out/Week.py")} - assert len(trimmed) == len(recorded) - 2 - path.write_text(json.dumps(trimmed)) + gone = ("out/Program.py", "out/Week.py") + for path in tmp_path.rglob(".hashes/*.json"): + kept = {k: v for k, v in json.loads(path.read_text()).items() if k not in gone} + path.write_text(json.dumps(kept)) + assert len(_manifest(tmp_path)) == len(recorded) - 2 (out / "Program.py").unlink() (out / "Week.py").unlink() manifest_writes.clear() diff --git a/server/python/tests/codegen/test_gen_state_keying.py b/server/python/tests/codegen/test_gen_state_keying.py index 72f8d1f568..d5ef095ebd 100644 --- a/server/python/tests/codegen/test_gen_state_keying.py +++ b/server/python/tests/codegen/test_gen_state_keying.py @@ -35,10 +35,11 @@ ) from tests.codegen.gen_suite import GEN_SUITE from tests.codegen.config_helpers import as_config +from tests.codegen.manifest_helpers import read_manifest def _manifest(gen_state: Path) -> dict[str, str]: - return json.loads((gen_state / ".hashes.json").read_text(encoding="utf-8")) + return read_manifest(gen_state) def test_key_is_project_relative_not_out_relative(tmp_path: Path) -> None: @@ -171,9 +172,7 @@ def test_a_project_reached_through_a_symlink_keeps_its_jurisdiction( monkeypatch.chdir(tmp_path) assert main(as_config(["gen", "--generators", GEN_SUITE, str(link / "metaobjects"), "--out", str(link / "gen")])) == 0 - manifest = json.loads( - (real / ".metaobjects" / ".gen-state" / ".hashes.json").read_text(encoding="utf-8") - ) + manifest = read_manifest(real / ".metaobjects" / ".gen-state") assert manifest, "gen recorded no manifest" # Not one key escapes the project. A `../` key is the whole defect. assert not any(k.startswith("..") for k in manifest), sorted(manifest)[:3] @@ -212,7 +211,6 @@ def test_output_outside_the_project_is_not_recorded_in_its_manifest( assert main(as_config(["gen", "--generators", GEN_SUITE, str(proj / "metaobjects"), "--out", str(elsewhere)])) == 0 assert any(elsewhere.iterdir()) - hashes = proj / ".metaobjects" / ".gen-state" / ".hashes.json" - keys = list(json.loads(hashes.read_text(encoding="utf-8"))) if hashes.exists() else [] + keys = list(read_manifest(proj / ".metaobjects" / ".gen-state")) assert not any(k.startswith("..") for k in keys), sorted(keys)[:3] assert "outside the project" in capsys.readouterr().out diff --git a/server/python/tests/codegen/test_gen_unchanged.py b/server/python/tests/codegen/test_gen_unchanged.py index d6db5fb9a6..1d8f5c2a22 100644 --- a/server/python/tests/codegen/test_gen_unchanged.py +++ b/server/python/tests/codegen/test_gen_unchanged.py @@ -46,9 +46,10 @@ def test_unchanged_files_keep_mtime_manifest_untouched_and_report_unchanged( assert main(["gen"]) == 0 files = [f for f in (root / "gen").rglob("*.py")] assert files - manifest = root / ".metaobjects" / ".gen-state" / ".hashes.json" - before = manifest.read_bytes() - for f in [*files, manifest]: + manifests = sorted((root / ".metaobjects" / ".gen-state" / ".hashes").glob("*.json")) + assert manifests + before = [m.read_bytes() for m in manifests] + for f in [*files, *manifests]: os.utime(f, (1, 1)) capsys.readouterr() @@ -56,8 +57,8 @@ def test_unchanged_files_keep_mtime_manifest_untouched_and_report_unchanged( out = capsys.readouterr().out assert all(f.stat().st_mtime == 1 for f in files), "an identical file was rewritten" - assert manifest.stat().st_mtime == 1, "an unchanged manifest was rewritten" - assert manifest.read_bytes() == before + assert all(m.stat().st_mtime == 1 for m in manifests), "an unchanged manifest was rewritten" + assert [m.read_bytes() for m in manifests] == before assert "wrote 0 file(s)" in out and f"{len(files)} file(s) left as they were" in out assert not [ln for ln in out.splitlines() if ln.startswith(str(root / "gen"))] @@ -92,10 +93,12 @@ def test_manifest_bytes_keep_sorted_keys_and_extra_fields(tmp_path: Path) -> Non session.record("b.py", "new", None) session.record("a.py", "x", None) assert session.save() is True - raw = json.loads((state / ".hashes.json").read_text()) + assert not (state / ".hashes.json").exists() + [only] = list((state / ".hashes").glob("*.json")) + raw = json.loads(only.read_text()) assert list(raw) == ["a.py", "b.py"] assert raw["b.py"]["owner"] == "jvm" and raw["b.py"]["hash"] == overwrite_policy.content_hash("new") - assert (state / ".hashes.json").read_text().endswith("}\n") + assert only.read_text().endswith("}\n") assert session.save() is False @@ -137,8 +140,8 @@ def counting(gen_state_dir: str, hashes: dict[str, str]) -> None: files = [f for f in (root / "gen").rglob("*") if f.is_file()] assert len(files) > 4 and {f.relative_to(root).parts[1] for f in files} == {"models", "api"} assert len(saves) == 1, f"first run saved the manifest {len(saves)} times" - manifest = root / ".metaobjects" / ".gen-state" / ".hashes.json" - for f in [*files, manifest]: + manifests = sorted((root / ".metaobjects" / ".gen-state" / ".hashes").glob("*.json")) + for f in [*files, *manifests]: os.utime(f, (1, 1)) saves.clear() capsys.readouterr() @@ -146,7 +149,7 @@ def counting(gen_state_dir: str, hashes: dict[str, str]) -> None: assert main(["gen", "--force"]) == 0 rewritten = [str(f) for f in files if f.stat().st_mtime != 1] assert rewritten == [], f"unchanged files were rewritten: {rewritten}" - assert saves == [] and manifest.stat().st_mtime == 1 + assert saves == [] and all(m.stat().st_mtime == 1 for m in manifests) assert "wrote 0 file(s)" in capsys.readouterr().out diff --git a/server/python/tests/codegen/test_hand_edits.py b/server/python/tests/codegen/test_hand_edits.py index 7efea3d84c..b6e16d24ea 100644 --- a/server/python/tests/codegen/test_hand_edits.py +++ b/server/python/tests/codegen/test_hand_edits.py @@ -13,9 +13,10 @@ import pytest from metaobjects.cli import main +from tests.codegen.manifest_helpers import read_manifest from metaobjects.codegen.project_config import load_project_config -MANIFEST = Path(".metaobjects") / ".gen-state" / ".hashes.json" +MANIFEST = Path(".metaobjects") / ".gen-state" KEEP = "targets:\n app:\n outDir: gen\n generators: [entity]\n" OVERWRITE = ( "targets:\n app:\n outDir: gen\n generators:\n" @@ -48,7 +49,7 @@ def _file(out: Path, stem: str) -> Path: def _manifest(root: Path) -> dict[str, str]: - return json.loads((root / MANIFEST).read_text(encoding="utf-8")) + return read_manifest(root / MANIFEST) @pytest.mark.parametrize("config", [KEEP, OVERWRITE], ids=["keep", "overwrite"]) @@ -127,7 +128,8 @@ def test_a_file_nobody_generated_is_never_overwritten( assert main(["gen"]) == 0 target = _file(out, "telemetry") # Forget the record: the file is now someone else's as far as gen can prove. - (tmp_path / MANIFEST).write_text("{}", encoding="utf-8") + for f in (tmp_path / MANIFEST / ".hashes").glob("*.json"): + f.write_text("{}\n", encoding="utf-8") target.write_text("# not generated\n", encoding="utf-8") assert main(["gen"]) == 1 assert target.read_text(encoding="utf-8") == "# not generated\n" diff --git a/server/python/tests/codegen/test_manifest_store.py b/server/python/tests/codegen/test_manifest_store.py new file mode 100644 index 0000000000..a60a5632e1 --- /dev/null +++ b/server/python/tests/codegen/test_manifest_store.py @@ -0,0 +1,196 @@ +"""ADR-0064 Amendment 1: the hash manifest is one file per model package. + +Runs the shared vectors (``fixtures/codegen-skip-conformance/manifests.json``) against the +Python manifest store, plus the file-level separation, the read-only guarantee and an end-to-end +multi-package ``gen``. +""" +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +from metaobjects.cli import main +from metaobjects.codegen import overwrite_policy as op +from metaobjects.codegen.overwrite_policy import ( + HashManifest, + has_hash_manifest, + package_file_name, + place_entry, + set_placement_objects, +) +from tests.codegen.config_helpers import as_config +from tests.codegen.gen_suite import GEN_SUITE +from tests.codegen.manifest_helpers import manifest_files, read_manifest + +VECTORS = json.loads( + (Path(__file__).parents[4] / "fixtures" / "codegen-skip-conformance" / "manifests.json").read_text() +) +OBJECTS = [(o["name"], o["package"]) for o in VECTORS["objects"]] + + +@pytest.mark.parametrize("case", VECTORS["fileNames"], ids=lambda c: c["file"]) +def test_file_names(case: dict) -> None: + assert package_file_name(case["package"]) == case["file"] + + +@pytest.mark.parametrize("case", VECTORS["placement"], ids=lambda c: f'{c["path"]}->{c["package"]}') +def test_placement(case: dict) -> None: + entry = case.get("entry", "h") + package = place_entry(case["path"], entry, OBJECTS) + assert package == case["package"] + + +def _state(tmp_path: Path) -> Path: + state = tmp_path / ".metaobjects" / ".gen-state" + state.mkdir(parents=True) + return state + + +def test_legacy_split(tmp_path: Path) -> None: + split = VECTORS["legacySplit"] + state = _state(tmp_path) + gitignore = state.parent / ".gitignore" + gitignore.write_text(split["gitignoreBefore"]) + (state / ".hashes.json").write_text(json.dumps(split["legacy"])) + set_placement_objects(str(state), OBJECTS) + + session = HashManifest(str(state)) + assert session.dirty, "a run that finds a legacy manifest always saves" + session.save() + + assert {n: c for n, c in manifest_files(state).items()} == split["files"] + assert (state / ".hashes" / split["goldenFile"]).read_text() == split["goldenText"] + assert not (state / ".hashes.json").exists() + assert gitignore.read_text() == split["gitignoreAfter"] + + before = {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in (state / ".hashes").glob("*.json")} + again = HashManifest(str(state)) + assert not again.dirty + again.dirty = True + again.save() + after = {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in (state / ".hashes").glob("*.json")} + assert after == before, "a second identical write changes no file" + + +def test_different_packages_different_files(tmp_path: Path) -> None: + state = _state(tmp_path) + set_placement_objects(str(state), OBJECTS) + m = HashManifest(str(state)) + m.record("gen/Order.ts", "a") + m.record("gen/Customer.ts", "b") + m.record("gen/index.ts", "c") + m.save() + files = manifest_files(state) + assert sorted(files) == [".root.json", "acme.crm.json", "acme.shop.json"] + + paths = {n: state / ".hashes" / n for n in files} + for p in paths.values(): + os.utime(p, (1, 1)) + crm_bytes = paths["acme.crm.json"].read_bytes() + + m = HashManifest(str(state)) + m.record("gen/Order.ts", "changed") # package A only + m.save() + assert paths["acme.shop.json"].stat().st_mtime != 1 + assert paths["acme.crm.json"].stat().st_mtime == 1 + assert paths[".root.json"].stat().st_mtime == 1 + assert paths["acme.crm.json"].read_bytes() == crm_bytes + + # A no-op save writes nothing: recording identical content again keeps the session + # clean, and a save changes no file's bytes or mtime. + for p in paths.values(): + os.utime(p, (2, 2)) + before = {n: p.read_bytes() for n, p in paths.items()} + m = HashManifest(str(state)) + m.record("gen/Order.ts", "changed") # identical to what the last save recorded + m.record("gen/Customer.ts", "b") + m.record("gen/index.ts", "c") + assert not m.dirty, "an unchanged re-record must keep the session clean" + assert m.save() is False + assert {n: p.read_bytes() for n, p in paths.items()} == before + assert all(p.stat().st_mtime == 2 for p in paths.values()) + + # Removing a package's last entry deletes its file. + raw = read_manifest(state) + del raw["gen/Customer.ts"] + op._save_hashes(str(state), {k: op._entry_hash(v) or "" for k, v in raw.items()}) + assert not paths["acme.crm.json"].exists() + assert paths["acme.shop.json"].exists() + + +def test_empty_manifest_keeps_the_root_file(tmp_path: Path) -> None: + state = _state(tmp_path) + set_placement_objects(str(state), OBJECTS) + m = HashManifest(str(state)) + m.record("gen/Order.ts", "a") + m.save() + op._save_hashes(str(state), {}) + assert manifest_files(state) == {".root.json": {}} + assert has_hash_manifest(str(state)) + + +def test_read_only_load_migrates_nothing(tmp_path: Path) -> None: + state = _state(tmp_path) + legacy = state / ".hashes.json" + legacy.write_text(json.dumps({"gen/Order.ts": "h1"})) + os.utime(legacy, (1, 1)) + assert has_hash_manifest(str(state)) + assert op.read_generated_hash(str(state), "gen/Order.ts") == "h1" + assert legacy.read_bytes() == json.dumps({"gen/Order.ts": "h1"}).encode() + assert legacy.stat().st_mtime == 1 + assert not (state / ".hashes").exists() + + +def test_union_prefers_package_files_over_the_legacy_file(tmp_path: Path) -> None: + state = _state(tmp_path) + (state / ".hashes").mkdir() + (state / ".hashes.json").write_text(json.dumps({"a": "old", "b": "legacy"})) + (state / ".hashes" / "x.json").write_text(json.dumps({"a": "new"})) + assert op.read_generated_hash(str(state), "a") == "new" + assert op.read_generated_hash(str(state), "b") == "legacy" + + +def test_gen_on_a_multi_package_model_writes_one_manifest_per_package(tmp_path: Path) -> None: + meta = tmp_path / "metaobjects" + meta.mkdir() + for pkg, name in (("shop", "Order"), ("crm", "Customer")): + (meta / f"meta.{pkg}.json").write_text(json.dumps({"metadata.root": { + "package": f"acme::{pkg}", + "children": [{"object.entity": {"name": name, "children": [ + {"field.long": {"name": "id"}}, {"field.string": {"name": "title"}}]}}], + }})) + out = tmp_path / "gen" + assert main(as_config(["gen", "--generators", GEN_SUITE, str(meta), "--out", str(out)])) == 0 + state = tmp_path / ".metaobjects" / ".gen-state" + files = manifest_files(state) + assert "acme.shop.json" in files and "acme.crm.json" in files + assert all(k.endswith(("Order.py", "Order.json")) or "Order" in os.path.basename(k) + for k in files["acme.shop.json"]) + assert all("Customer" in os.path.basename(k) for k in files["acme.crm.json"]) + assert not (state / ".hashes.json").exists() + # Each key is recorded exactly once across the files. + keys = [k for entries in files.values() for k in entries] + assert len(keys) == len(set(keys)) + + +@pytest.mark.parametrize( + ("before", "after"), + [ + (".gen-state/*\n!.gen-state/.hashes.json\n", ".gen-state/*\n!.gen-state/.hashes/\n"), + (".gen-state/*\n", ".gen-state/*\n!.gen-state/.hashes/\n"), + ( + ".gen-state/*\n!.gen-state/.hashes.json\n!.gen-state/.hashes/\n", + ".gen-state/*\n!.gen-state/.hashes/\n", + ), + ("other\n", "other\n"), + ], +) +def test_gitignore_migration(tmp_path: Path, before: str, after: str) -> None: + state = _state(tmp_path) + (state.parent / ".gitignore").write_text(before) + (state / ".hashes.json").write_text(json.dumps({"gen/Order.ts": "h"})) + HashManifest(str(state)).save() + assert (state.parent / ".gitignore").read_text() == after diff --git a/server/python/tests/codegen/test_orphan_sweep.py b/server/python/tests/codegen/test_orphan_sweep.py index d677b4e2ed..fc100effe6 100644 --- a/server/python/tests/codegen/test_orphan_sweep.py +++ b/server/python/tests/codegen/test_orphan_sweep.py @@ -16,8 +16,9 @@ import pytest from metaobjects.cli import main +from tests.codegen.manifest_helpers import read_manifest -MANIFEST = Path(".metaobjects") / ".gen-state" / ".hashes.json" +MANIFEST = Path(".metaobjects") / ".gen-state" def _value(name: str) -> dict: @@ -49,7 +50,7 @@ def _project(root: Path, children: list[dict], *, package: str = "acme", def _manifest(root: Path) -> dict[str, str]: - return json.loads((root / MANIFEST).read_text(encoding="utf-8")) + return read_manifest(root / MANIFEST) def _find(out: Path, name: str) -> list[Path]: diff --git a/server/python/tests/codegen/test_overwrite_policy_hash.py b/server/python/tests/codegen/test_overwrite_policy_hash.py index ec2d2c0de9..b8517be50f 100644 --- a/server/python/tests/codegen/test_overwrite_policy_hash.py +++ b/server/python/tests/codegen/test_overwrite_policy_hash.py @@ -23,6 +23,7 @@ import json from pathlib import Path +from tests.codegen.manifest_helpers import read_manifest from metaobjects.codegen.constants import generated_header from metaobjects.codegen.overwrite_policy import ( content_hash, @@ -106,7 +107,7 @@ def test_manifest_is_sorted_and_detectable(tmp_path: Path) -> None: assert has_hash_manifest(str(state)) is True # Sorted, because this file is committed: insertion order would make the diff # depend on which entity generated first. - data = json.loads((state / ".hashes.json").read_text()) + data = read_manifest(state) assert list(data.keys()) == ["a.py", "m.py", "z.py"] @@ -146,7 +147,7 @@ def test_jvm_object_entry_is_read_and_preserved_on_record(tmp_path: Path) -> Non target = tmp_path / "Other.py" assert _gen(target, "other\n", state) == "new" - saved = json.loads((state / ".hashes.json").read_text(encoding="utf-8")) + saved = read_manifest(state) assert saved["Jvm.java"] == jvm assert saved["Plain.txt"] == "abc" assert saved["Other.py"] == content_hash("other\n") @@ -154,7 +155,7 @@ def test_jvm_object_entry_is_read_and_preserved_on_record(tmp_path: Path) -> Non jvm_file = tmp_path / "Jvm.java" jvm_file.write_text("jvm body", encoding="utf-8") assert _gen(jvm_file, "jvm body v2", state) == "overwrite" - saved = json.loads((state / ".hashes.json").read_text(encoding="utf-8")) + saved = read_manifest(state) assert saved["Jvm.java"]["generator"] == "java:dto" assert saved["Jvm.java"]["outputDir"] == "target/gen" assert saved["Jvm.java"]["hash"] == content_hash("jvm body v2") diff --git a/server/python/tests/codegen/test_runner.py b/server/python/tests/codegen/test_runner.py index 822f10dd7f..b111b1c6fc 100644 --- a/server/python/tests/codegen/test_runner.py +++ b/server/python/tests/codegen/test_runner.py @@ -8,6 +8,7 @@ from metaobjects.codegen.config import GenConfig from metaobjects.codegen.constants import GENERATED_MARKER from metaobjects.codegen.runner import run_gen +from tests.codegen.manifest_helpers import has_manifest from metaobjects.codegen.generators.entity_model import entity_model @@ -118,7 +119,7 @@ def test_run_gen_errors_on_path_collision(tmp_path: Path) -> None: # ── `baseline="adopt"` — the first run a pre-manifest project can perform ────────── # -# The no-manifest refusal used to LEAD with "commit .metaobjects/.gen-state/.hashes.json", +# The no-manifest refusal used to LEAD with "commit .metaobjects/.gen-state/.hashes/", # which the population it names cannot do: nothing writes a manifest until a gen succeeds, # and a run where every file refuses writes none. `adopt` records what is on disk as the # baseline and writes nothing, which is the run that produces the file to commit. @@ -149,7 +150,7 @@ def test_adopt_records_the_files_and_writes_nothing(tmp_path: Path) -> None: statuses = {Path(p).name: s for p, s in result.files} assert statuses["Subscriber.py"] == "adopted" assert (out / "Subscriber.py").read_text() == before # not one byte written - assert (state / ".hashes.json").exists() # …and the file to commit now exists + assert has_manifest(state) # …and the file to commit now exists def test_adopt_says_what_to_do_next_once(tmp_path: Path) -> None: @@ -164,7 +165,7 @@ def test_adopt_says_what_to_do_next_once(tmp_path: Path) -> None: notices = [w for w in result.warnings if "baseline" in w] assert len(notices) == 1 - assert ".hashes.json" in notices[0] + assert ".hashes/" in notices[0] assert "replace" in notices[0] or "regenerat" in notices[0] @@ -209,7 +210,7 @@ def test_the_no_manifest_refusal_leads_with_the_performable_remedy(tmp_path: Pat assert len(msgs) == 1 assert "--baseline=adopt" in msgs[0] # What it must no longer do: prescribe committing a file this project cannot produce. - assert "Commit '.metaobjects/.gen-state/.hashes.json' and re-run" not in msgs[0] + assert "Commit '.metaobjects/.gen-state/.hashes/' and re-run" not in msgs[0] def test_run_gen_refuses_a_model_with_colliding_collection_names(tmp_path: Path) -> None: diff --git a/server/python/tests/test_gen_skip_conformance.py b/server/python/tests/test_gen_skip_conformance.py index 2db8423830..618527dee6 100644 --- a/server/python/tests/test_gen_skip_conformance.py +++ b/server/python/tests/test_gen_skip_conformance.py @@ -8,6 +8,7 @@ import json import os +import shutil from dataclasses import dataclass from pathlib import Path from typing import Callable @@ -231,6 +232,15 @@ def _failed_run(p: Project, h: Harness) -> None: (p.root / "metaobjects" / "meta.a.json").write_text(good) +def _legacy_manifest(p: Project, h: Harness) -> None: + """Put the manifest back in its pre-1.3.0 form: one .hashes.json, no .hashes/ directory.""" + merged: dict[str, object] = {} + for f in sorted((p.state / ".hashes").glob("*.json")): + merged.update(json.loads(f.read_text())) + shutil.rmtree(p.state / ".hashes") + (p.state / ".hashes.json").write_text(json.dumps(dict(sorted(merged.items())), indent=2) + "\n") + + def _write(rel: str, text: str) -> Callable[[Project, Harness], None]: def go(p: Project, h: Harness) -> None: f = p.root / rel @@ -281,6 +291,7 @@ def _engine_changed(p: Project, h: Harness) -> None: "force": (_NOOP, ("--force",)), "ci": (_NOOP, ()), "failed-run": (_failed_run, ()), + "legacy-manifest": (_legacy_manifest, ()), } @@ -316,6 +327,8 @@ def test_case(case: dict[str, str], tmp_path: Path, monkeypatch, capsys) -> None assert rendered, "verify must render and compare" else: assert not rendered and v_rc == 0, "verify may answer from the fingerprint" + if case["id"] == "legacy-manifest": + assert (project.state / ".hashes.json").exists(), "verify must not migrate" monkeypatch.delenv("CI", raising=False) rc, skipped = h.gen(*flags) @@ -325,6 +338,9 @@ def test_case(case: dict[str, str], tmp_path: Path, monkeypatch, capsys) -> None assert skipped and rc == 0 else: assert not skipped + if case["id"] == "legacy-manifest": + assert not (project.state / ".hashes.json").exists(), "the write run removes the legacy file" + assert list((project.state / ".hashes").glob("*.json")), "and leaves per-package files" def test_unchanged_files_keep_their_timestamp_and_report_unchanged( @@ -338,14 +354,16 @@ def test_unchanged_files_keep_their_timestamp_and_report_unchanged( assert files for f in files: os.utime(f, (1, 1)) - manifest = project.state / ".hashes.json" - manifest_bytes = manifest.read_bytes() - os.utime(manifest, (1, 1)) + manifests = sorted((project.state / ".hashes").glob("*.json")) + assert manifests + manifest_bytes = [m.read_bytes() for m in manifests] + for m in manifests: + os.utime(m, (1, 1)) assert h.gen("--force")[0] == 0 out = h.out assert all(f.stat().st_mtime == 1 for f in files), "an identical file was rewritten" - assert manifest.stat().st_mtime == 1, "an unchanged manifest was rewritten" - assert manifest.read_bytes() == manifest_bytes + assert all(m.stat().st_mtime == 1 for m in manifests), "an unchanged manifest was rewritten" + assert [m.read_bytes() for m in manifests] == manifest_bytes assert "wrote 0 file(s)" in out and "left as they were" in out assert not [ln for ln in out.splitlines() if ln.startswith(str(generated))] diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 5ee9656457..4d949c3eea 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -542,7 +542,7 @@ fn init_files() -> [(&'static str, &'static str); 3] { ), ( ".metaobjects/.gitignore", - "# The generation state. `.hashes.json` is committed: it is one hash per generated\n# path, and the only thing that lets `gen` tell \"this file is exactly what I wrote\" from\n# \"somebody edited this\" on a machine that did not generate it. Everything else here (the\n# skip key) describes one machine's last run and is not.\n#\n# The glob form matters: `.gen-state/` (a directory) would stop git descending, and the\n# negation below could never take effect.\n.gen-state/*\n!.gen-state/.hashes.json\n", + "# The generation state. `.hashes/` is committed: it is one hash per generated\n# path (one file per model package), and the only thing that lets `gen` tell \"this file is exactly what I wrote\" from\n# \"somebody edited this\" on a machine that did not generate it. Everything else here (the\n# skip key) describes one machine's last run and is not.\n#\n# The glob form matters: `.gen-state/` (a directory) would stop git descending, and the\n# negation below could never take effect.\n.gen-state/*\n!.gen-state/.hashes/\n", ), ( "metaobjects/meta.app.yaml", @@ -596,7 +596,7 @@ fn cmd_init( let _ = writeln!( out, "next: declare your objects in metaobjects/ (JSON or YAML), then run `{TOOL} gen`.\n\ - Commit .metaobjects/.gen-state/.hashes.json with the generated crates.\n\ + Commit .metaobjects/.gen-state/.hashes/ with the generated crates.\n\ Schema migrations are the Node `meta` command's (`meta migrate`), for every server language." ); Ok(0) diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 92df31145a..40358c613a 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -32,7 +32,7 @@ use crate::fingerprint::{ use crate::generator::{ ERR_OUT_DIR, ERR_PATH_COLLISION, EmittedFile, GenContext, GenError, Generator, }; -use crate::hashes::{HashManifest, content_hash}; +use crate::hashes::{HASHES_DIR, HashManifest, content_hash}; use crate::project::{LoadedProject, load_project}; use crate::sha256::sha256_hex; @@ -221,7 +221,7 @@ impl std::fmt::Display for RunError { write!( f, "refused to overwrite {} file(s) that differ from what the last run wrote \ - (edited by hand, or not recorded in {DEFAULT_METAOBJECTS_DIR}/{GEN_STATE_DIR}/.hashes.json): {}. \ + (edited by hand, or not recorded in {DEFAULT_METAOBJECTS_DIR}/{GEN_STATE_DIR}/.hashes/): {}. \ Restore them, or delete them to generate them afresh.", r.edited.len(), r.edited.join(", ") @@ -394,7 +394,17 @@ fn prepare<'g>( let gen_state = project_root .join(DEFAULT_METAOBJECTS_DIR) .join(GEN_STATE_DIR); - let manifest = HashManifest::load(&gen_state); + let mut manifest = HashManifest::load(&gen_state); + // The model's root-level objects decide which package's manifest file records a path. + // ADR-0039 sanctioned own: a top-level scan of the loader ROOT, as in `build_model_tree`. + let tree = &loaded.result.tree; + manifest.set_objects( + tree.own_children(loaded.result.root) + .iter() + .filter(|&&c| tree.node(c).type_name == "object") + .map(|&c| (tree.node(c).name.clone(), tree.effective_package(c))) + .collect(), + ); let model = build_model_tree(&loaded.result.tree, loaded.result.root); let cacheable = selected.iter().all(|g| g.cacheable()); let mut entries = vec![ @@ -497,6 +507,9 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result Some("no stored key"), @@ -611,7 +624,7 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result String { @@ -33,46 +49,242 @@ fn entry_hash(value: &Value) -> Option<&str> { } } +/// The file name of a package's manifest: its `::` segments joined with `.`, each byte +/// outside `[A-Za-z0-9_-]` written as `%XX`, then `.json`. `None` is the root manifest. +pub fn package_file_name(package: Option<&str>) -> String { + let Some(package) = package else { + return ROOT_FILE.to_string(); + }; + let segments: Vec = package + .split(PACKAGE_SEP) + .map(|seg| { + let mut out = String::new(); + for b in seg.bytes() { + if b.is_ascii_alphanumeric() || b == b'_' || b == b'-' { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out + }) + .collect(); + format!("{}.json", segments.join(".")) +} + +/// The package a recorded path files under, or `None` for the root manifest: the entry's +/// `sourceNode` first, then the longest root-level object name the file's stem begins with. +/// `objects` are the loaded model's root-level objects as `(name, package)`. +pub fn place(path: &str, entry: &Value, objects: &[(String, String)]) -> Option { + if let Some(node) = entry + .as_object() + .and_then(|o| o.get("sourceNode")) + .and_then(Value::as_str) + { + let object = node.split('.').next().unwrap_or(node); + return object + .rsplit_once(PACKAGE_SEP) + .map(|(pkg, _)| pkg.to_string()) + .filter(|p| !p.is_empty()); + } + let base = path.rsplit('/').next().unwrap_or(path); + let stem = words(base.split('.').next().unwrap_or(base)); + let mut best: Vec<&str> = Vec::new(); // packages of the matches with the most words + let mut best_len = 0; + for (name, package) in objects { + let w = words(name); + if w.is_empty() || w.len() > stem.len() || stem[..w.len()] != w[..] { + continue; + } + if w.len() > best_len { + best_len = w.len(); + best.clear(); + } + if w.len() == best_len { + best.push(package); + } + } + best.sort_unstable(); + best.dedup(); + match best.as_slice() { + [p] if !p.is_empty() => Some((*p).to_string()), + _ => None, + } +} + +/// Split a name or file stem into lowercase words: at `_` and `-`, before an uppercase +/// letter that follows a lowercase letter or digit, and before the last uppercase of a run +/// that a lowercase letter follows (`HTTPServer` is `http`, `server`). +fn words(s: &str) -> Vec { + let chars: Vec = s.chars().collect(); + let mut out: Vec = Vec::new(); + let mut cur = String::new(); + for (i, &c) in chars.iter().enumerate() { + if c == '_' || c == '-' { + out.push(std::mem::take(&mut cur)); + continue; + } + if c.is_uppercase() && i > 0 { + let prev = chars[i - 1]; + let next_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase()); + if prev.is_lowercase() || prev.is_ascii_digit() || (prev.is_uppercase() && next_lower) { + out.push(std::mem::take(&mut cur)); + } + } + cur.extend(c.to_lowercase()); + } + out.push(cur); + out.retain(|w| !w.is_empty()); + out +} + +/// `.gitignore` text with the legacy `!.gen-state/.hashes.json` line replaced by +/// `!.gen-state/.hashes/` (or the new line inserted after `.gen-state/*` when there is no +/// legacy line), or `None` when nothing needs to change (no `.gen-state/*` rule, or neither +/// the legacy line nor a missing new line). +pub fn migrate_gitignore(text: &str) -> Option { + let lines: Vec<&str> = text.lines().collect(); + if !lines.iter().any(|l| l.trim() == GITIGNORE_RULE) { + return None; + } + let has_dir = lines.iter().any(|l| l.trim() == GITIGNORE_DIR); + let has_legacy = lines.iter().any(|l| l.trim() == GITIGNORE_LEGACY); + if has_dir && !has_legacy { + return None; + } + let mut out = String::new(); + let mut added = has_dir; + for l in &lines { + let t = l.trim(); + if t == GITIGNORE_LEGACY || (!added && !has_legacy && t == GITIGNORE_RULE) { + if t == GITIGNORE_RULE { + out.push_str(l); + out.push('\n'); + } + if !added { + out.push_str(GITIGNORE_DIR); + out.push('\n'); + added = true; + } + continue; + } + out.push_str(l); + out.push('\n'); + } + Some(out) +} + +fn read_object(path: &Path) -> (Option>, bool) { + // (entries, present-but-unusable) + match std::fs::read_to_string(path) { + Err(_) => (None, path.exists()), + Ok(t) => match serde_json::from_str::(&t) { + Ok(Value::Object(m)) => (Some(m), false), + _ => (None, true), + }, + } +} + +fn manifest_text(entries: &Map) -> String { + let mut keys: Vec<&String> = entries.keys().collect(); + keys.sort(); + let mut sorted = Map::new(); + for k in keys { + sorted.insert(k.clone(), entries[k].clone()); + } + let mut text = + serde_json::to_string_pretty(&Value::Object(sorted)).expect("a map of strings serializes"); + text.push('\n'); + text +} + /// The manifest as one in-memory session. #[derive(Debug)] pub struct HashManifest { - path: PathBuf, + dir: PathBuf, entries: Map, + /// The manifest file each entry was read from (absent for the legacy file and for new + /// entries): where a writer with no model leaves it. + origin: HashMap, + /// The loaded model's root-level objects, `(name, package)`, once the runner has them. + objects: Option>, existed: bool, + legacy: bool, dirty: bool, } impl HashManifest { - /// Read the manifest in `gen_state_dir`. A missing file is an empty manifest; an - /// unreadable or corrupt one reads as empty too, which fails closed: every existing - /// generated file is then refused rather than assumed ours. + /// Read the manifest of `gen_state_dir`: the union of `.hashes/*.json` over the legacy + /// `.hashes.json`. A missing file is an empty manifest; an unreadable or corrupt one + /// reads as empty too, which fails closed: every existing generated file is then + /// refused rather than assumed ours. pub fn load(gen_state_dir: &Path) -> Self { - let path = gen_state_dir.join(HASHES_FILE); - let text = std::fs::read_to_string(&path).ok(); - let parsed = text - .as_deref() - .and_then(|t| serde_json::from_str::(t).ok()); - let corrupt = text.is_some() && !matches!(parsed, Some(Value::Object(_))); - let entries = match parsed { - Some(Value::Object(map)) => map, - _ => Map::new(), - }; - // A corrupt file is present but unusable: the next save replaces it. - let existed = text.is_some(); - let dirty = corrupt; + let mut entries = Map::new(); + let mut origin = HashMap::new(); + let mut existed = false; + let mut dirty = false; + + let legacy_path = gen_state_dir.join(HASHES_FILE); + let legacy = legacy_path.exists(); + if legacy { + existed = true; + let (map, bad) = read_object(&legacy_path); + dirty |= bad; + entries = map.unwrap_or_default(); + } + + let dir = gen_state_dir.join(HASHES_DIR); + for name in Self::files_in(&dir) { + existed = true; + let (map, bad) = read_object(&dir.join(&name)); + // A corrupt file is present but unusable: the next save replaces it. + dirty |= bad; + for (k, v) in map.unwrap_or_default() { + origin.insert(k.clone(), name.clone()); + entries.insert(k, v); + } + } Self { - path, + dir, entries, + origin, + objects: None, existed, + legacy, dirty, } } - /// Whether the project had a manifest file at all. + fn files_in(dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.path().is_file()) + .filter_map(|e| e.file_name().into_string().ok()) + .filter(|n| n.ends_with(".json")) + .collect(); + names.sort(); + names + } + + /// Hand the manifest the loaded model's root-level objects (`(name, package)`), so a + /// save files each entry by [`place`] instead of leaving it where it was read. + pub fn set_objects(&mut self, objects: Vec<(String, String)>) { + self.objects = Some(objects); + } + + /// Whether the project had a manifest at all (the legacy file or a per-package one). pub fn existed(&self) -> bool { self.existed } + /// Whether the manifest was read from the legacy single file, which the next save + /// migrates. + pub fn is_legacy(&self) -> bool { + self.legacy + } + /// The recorded hash for `key` (a project-relative path), if any. pub fn hash_of(&self, key: &str) -> Option<&str> { self.entries.get(key).and_then(entry_hash) @@ -105,41 +317,93 @@ impl HashManifest { /// Drop the record for `key`. pub fn remove(&mut self, key: &str) { if self.entries.shift_remove(key).is_some() { + self.origin.remove(key); self.dirty = true; } } - /// Whether the in-memory manifest differs from what was loaded. + /// Whether the in-memory manifest differs from what was loaded (a legacy manifest + /// counts: it is always migrated). pub fn is_dirty(&self) -> bool { - self.dirty + self.dirty || self.legacy + } + + fn file_of(&self, key: &str, value: &Value) -> String { + match &self.objects { + Some(objects) => package_file_name(place(key, value, objects).as_deref()), + None => self + .origin + .get(key) + .cloned() + .unwrap_or_else(|| ROOT_FILE.to_string()), + } } - /// The manifest's text: keys sorted, two-space indent, trailing newline. - pub fn to_text(&self) -> String { - let mut keys: Vec<&String> = self.entries.keys().collect(); - keys.sort(); - let mut sorted = Map::new(); - for k in keys { - sorted.insert(k.clone(), self.entries[k].clone()); + /// Every manifest file's text, by file name, as a save would write them. + pub fn to_files(&self) -> BTreeMap { + let mut groups: BTreeMap> = BTreeMap::new(); + for (k, v) in &self.entries { + groups + .entry(self.file_of(k, v)) + .or_default() + .insert(k.clone(), v.clone()); } - let mut text = serde_json::to_string_pretty(&Value::Object(sorted)) - .expect("a map of strings serializes"); - text.push('\n'); - text + // With no entry at all the root manifest stays (as `{}`), so "no manifest" is + // distinguishable from "empty"; otherwise it exists only when it holds an entry. + if groups.is_empty() { + groups.insert(ROOT_FILE.to_string(), Map::new()); + } + groups + .into_iter() + .map(|(name, m)| (name, manifest_text(&m))) + .collect() } - /// Write the manifest once, and only when an entry changed. Returns whether it wrote. + /// Write the manifest, once, and only the files whose bytes changed; delete a package + /// file that holds no entry; migrate the legacy file. Returns whether it wrote anything. pub fn save(&mut self) -> std::io::Result { - if !self.dirty { + if !self.is_dirty() { return Ok(false); } - if let Some(dir) = self.path.parent() { - std::fs::create_dir_all(dir)?; + let files = self.to_files(); + std::fs::create_dir_all(&self.dir)?; + let mut wrote = false; + for (name, text) in &files { + let path = self.dir.join(name); + if std::fs::read_to_string(&path).ok().as_deref() != Some(text.as_str()) { + std::fs::write(&path, text)?; + wrote = true; + } + } + for name in Self::files_in(&self.dir) { + if !files.contains_key(&name) { + std::fs::remove_file(self.dir.join(&name))?; + wrote = true; + } + } + if self.legacy { + let gen_state = self.dir.parent().unwrap_or(Path::new(".")); + std::fs::remove_file(gen_state.join(HASHES_FILE))?; + if let Some(parent) = gen_state.parent() { + let ignore = parent.join(".gitignore"); + if let Some(next) = std::fs::read_to_string(&ignore) + .ok() + .and_then(|t| migrate_gitignore(&t)) + { + std::fs::write(&ignore, next)?; + } + } + self.legacy = false; + wrote = true; } - std::fs::write(&self.path, self.to_text())?; + self.origin = self + .entries + .iter() + .map(|(k, v)| (k.clone(), self.file_of(k, v))) + .collect(); self.dirty = false; self.existed = true; - Ok(true) + Ok(wrote) } } @@ -157,6 +421,10 @@ mod tests { dir } + fn root_file(dir: &Path) -> PathBuf { + dir.join(HASHES_DIR).join(ROOT_FILE) + } + #[test] fn saves_sorted_with_a_trailing_newline_and_only_when_dirty() { let dir = scratch("save"); @@ -165,7 +433,7 @@ mod tests { m.record("b/two.rs", "22"); m.record("a/one.rs", "11"); assert!(m.save().unwrap()); - let text = std::fs::read_to_string(dir.join(HASHES_FILE)).unwrap(); + let text = std::fs::read_to_string(root_file(&dir)).unwrap(); assert_eq!( text, "{\n \"a/one.rs\": \"11\",\n \"b/two.rs\": \"22\"\n}\n" @@ -193,7 +461,11 @@ mod tests { assert_eq!(m.hash_of("x.rs"), Some("old")); m.record("x.rs", "new"); m.save().unwrap(); - let text = std::fs::read_to_string(dir.join(HASHES_FILE)).unwrap(); + assert!( + !dir.join(HASHES_FILE).exists(), + "the legacy file is migrated" + ); + let text = std::fs::read_to_string(root_file(&dir)).unwrap(); assert!(text.contains("\"generator\": \"entity\""), "{text}"); assert!(text.contains("\"hash\": \"new\""), "{text}"); let _ = std::fs::remove_dir_all(&dir); @@ -208,10 +480,7 @@ mod tests { assert_eq!(m.records().count(), 0); assert!(m.is_dirty()); assert!(m.save().unwrap()); - assert_eq!( - std::fs::read_to_string(dir.join(HASHES_FILE)).unwrap(), - "{}\n" - ); + assert_eq!(std::fs::read_to_string(root_file(&dir)).unwrap(), "{}\n"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/server/rust/metaobjects-codegen/src/sha256.rs b/server/rust/metaobjects-codegen/src/sha256.rs index 0f33ade2fe..df0780b471 100644 --- a/server/rust/metaobjects-codegen/src/sha256.rs +++ b/server/rust/metaobjects-codegen/src/sha256.rs @@ -1,6 +1,6 @@ //! SHA-256 (FIPS 180-4), std only. //! -//! The hash manifest (`.metaobjects/.gen-state/.hashes.json`) records the SHA-256 of +//! 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` diff --git a/server/rust/metaobjects-codegen/tests/hash_manifest.rs b/server/rust/metaobjects-codegen/tests/hash_manifest.rs new file mode 100644 index 0000000000..fd78bce477 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/hash_manifest.rs @@ -0,0 +1,345 @@ +//! The per-package hash manifest (ADR-0064 Amendment 1): the shared vectors, file-level +//! separation between packages, a read-only load that migrates nothing, and an end-to-end run. + +mod common; + +use std::path::{Path, PathBuf}; +use std::thread::sleep; +use std::time::Duration; + +use common::{Scratch, shop_files}; +use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError}; +use metaobjects_codegen::hashes::{ + HASHES_DIR, HASHES_FILE, HashManifest, ROOT_FILE, migrate_gitignore, package_file_name, place, +}; +use metaobjects_codegen::{Generator, RunOptions, run}; +use serde_json::{Map, Value}; + +const VECTORS: &str = include_str!("../../../../fixtures/codegen-skip-conformance/manifests.json"); + +fn vectors() -> Value { + serde_json::from_str(VECTORS).unwrap() +} + +fn objects(v: &Value) -> Vec<(String, String)> { + v["objects"] + .as_array() + .unwrap() + .iter() + .map(|o| { + ( + o["name"].as_str().unwrap().to_string(), + o["package"].as_str().unwrap().to_string(), + ) + }) + .collect() +} + +fn scratch(tag: &str) -> PathBuf { + let base = std::env::var_os("DEV_SCRATCH") + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!("mo-hash-manifest-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A gen-state directory inside `/.metaobjects`, as a project lays it out. +fn gen_state(root: &Path) -> PathBuf { + let dir = root.join(".metaobjects/.gen-state"); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn files_of(gen_state: &Path) -> std::collections::BTreeMap { + let dir = gen_state.join(HASHES_DIR); + std::fs::read_dir(&dir) + .map(|rd| { + rd.flatten() + .map(|e| { + ( + e.file_name().into_string().unwrap(), + std::fs::read_to_string(e.path()).unwrap(), + ) + }) + .collect() + }) + .unwrap_or_default() +} + +fn tick() { + sleep(Duration::from_millis(30)); +} + +#[test] +fn file_names_follow_the_vectors() { + for c in vectors()["fileNames"].as_array().unwrap() { + let got = package_file_name(c["package"].as_str()); + assert_eq!(got, c["file"].as_str().unwrap(), "{}", c["package"]); + } +} + +#[test] +fn placement_follows_the_vectors() { + let v = vectors(); + let objs = objects(&v); + for c in v["placement"].as_array().unwrap() { + let path = c["path"].as_str().unwrap(); + let entry = c.get("entry").cloned().unwrap_or(Value::String("h".into())); + let got = place(path, &entry, &objs); + assert_eq!( + got.as_deref(), + c["package"].as_str(), + "{path}: {}", + c["why"] + ); + } +} + +#[test] +fn a_legacy_manifest_splits_exactly_as_the_vector_says() { + let v = vectors(); + let split = &v["legacySplit"]; + let root = scratch("split"); + let gs = gen_state(&root); + let ignore = root.join(".metaobjects/.gitignore"); + std::fs::write(&ignore, split["gitignoreBefore"].as_str().unwrap()).unwrap(); + std::fs::write( + gs.join(HASHES_FILE), + serde_json::to_string_pretty(&split["legacy"]).unwrap(), + ) + .unwrap(); + + let mut m = HashManifest::load(&gs); + assert!(m.existed() && m.is_legacy()); + m.set_objects(objects(&v)); + assert!(m.save().unwrap()); + + assert!(!gs.join(HASHES_FILE).exists(), "the legacy file is removed"); + let got = files_of(&gs); + let want = split["files"].as_object().unwrap(); + assert_eq!( + got.keys().collect::>(), + want.keys() + .collect::>() + .into_iter() + .collect::>() + ); + for (name, text) in &got { + let parsed: Value = serde_json::from_str(text).unwrap(); + assert_eq!(&parsed, &want[name], "{name}"); + } + let golden = split["goldenFile"].as_str().unwrap(); + assert_eq!(got[golden], split["goldenText"].as_str().unwrap()); + assert_eq!( + std::fs::read_to_string(&ignore).unwrap(), + split["gitignoreAfter"].as_str().unwrap() + ); + + // A second identical write changes no file. + let mtimes = |gs: &Path| -> Vec<_> { + files_of(gs) + .keys() + .map(|n| { + std::fs::metadata(gs.join(HASHES_DIR).join(n)) + .unwrap() + .modified() + .unwrap() + }) + .collect() + }; + let before = (files_of(&gs), mtimes(&gs)); + tick(); + let mut again = HashManifest::load(&gs); + again.set_objects(objects(&v)); + assert!(!again.is_legacy() && !again.save().unwrap()); + assert_eq!((files_of(&gs), mtimes(&gs)), before); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn the_gitignore_is_left_alone_when_it_has_the_line_or_no_rule() { + let after = vectors()["legacySplit"]["gitignoreAfter"] + .as_str() + .unwrap() + .to_string(); + assert_eq!(migrate_gitignore(&after), None); + assert_eq!(migrate_gitignore("target/\n"), None); +} + +#[test] +fn different_packages_are_different_files() { + let root = scratch("packages"); + let gs = gen_state(&root); + let objs = vec![ + ("Order".to_string(), "acme::shop".to_string()), + ("Customer".to_string(), "acme::crm".to_string()), + ]; + let mut m = HashManifest::load(&gs); + m.set_objects(objs.clone()); + m.record("gen/Order.rs", "o1"); + m.record("gen/Customer.rs", "c1"); + m.record("gen/index.rs", "i1"); + assert!(m.save().unwrap()); + let names: Vec = files_of(&gs).into_keys().collect(); + assert_eq!(names, [".root.json", "acme.crm.json", "acme.shop.json"]); + + let mtime = |n: &str| { + std::fs::metadata(gs.join(HASHES_DIR).join(n)) + .unwrap() + .modified() + .unwrap() + }; + let (crm, shop, root_m) = ( + mtime("acme.crm.json"), + mtime("acme.shop.json"), + mtime(ROOT_FILE), + ); + let shop_text = files_of(&gs)["acme.shop.json"].clone(); + tick(); + + // A no-op save writes nothing. + let mut m = HashManifest::load(&gs); + m.set_objects(objs.clone()); + m.record("gen/Order.rs", "o1"); + assert!(!m.save().unwrap()); + assert_eq!(mtime("acme.shop.json"), shop); + + // A change in package A touches A's file only. + m.record("gen/Customer.rs", "c2"); + assert!(m.save().unwrap()); + assert_ne!(mtime("acme.crm.json"), crm); + assert_eq!(mtime("acme.shop.json"), shop); + assert_eq!(mtime(ROOT_FILE), root_m); + assert_eq!(files_of(&gs)["acme.shop.json"], shop_text); + + // The last entry of a package takes its file with it. + m.remove("gen/Customer.rs"); + assert!(m.save().unwrap()); + assert!(!gs.join(HASHES_DIR).join("acme.crm.json").exists()); + + // An emptied manifest keeps `.root.json` as `{}`. + m.remove("gen/Order.rs"); + m.remove("gen/index.rs"); + assert!(m.save().unwrap()); + let left = files_of(&gs); + assert_eq!(left.len(), 1); + assert_eq!(left[ROOT_FILE], "{}\n"); + assert!(HashManifest::load(&gs).existed()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_read_only_load_of_a_legacy_manifest_migrates_nothing() { + let root = scratch("readonly"); + let gs = gen_state(&root); + let text = "{\n \"gen/Order.rs\": \"o1\"\n}\n"; + std::fs::write(gs.join(HASHES_FILE), text).unwrap(); + let mut m = HashManifest::load(&gs); + m.set_objects(vec![("Order".into(), "acme::shop".into())]); + assert_eq!(m.hash_of("gen/Order.rs"), Some("o1")); + drop(m); + assert_eq!(std::fs::read_to_string(gs.join(HASHES_FILE)).unwrap(), text); + assert!(!gs.join(HASHES_DIR).exists()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn a_package_file_wins_over_the_legacy_file() { + let root = scratch("union"); + let gs = gen_state(&root); + std::fs::write(gs.join(HASHES_FILE), "{\"a.rs\":\"old\",\"b.rs\":\"b\"}").unwrap(); + std::fs::create_dir_all(gs.join(HASHES_DIR)).unwrap(); + std::fs::write(gs.join(HASHES_DIR).join(ROOT_FILE), "{\"a.rs\":\"new\"}").unwrap(); + let m = HashManifest::load(&gs); + assert_eq!(m.hash_of("a.rs"), Some("new")); + assert_eq!(m.hash_of("b.rs"), Some("b")); + let _ = std::fs::remove_dir_all(&root); +} + +/// Emits one snake_case file per object, named for the object (`src/order.txt`), so the stem rule can place it. +struct PerObject; + +impl Generator for PerObject { + fn name(&self) -> &str { + "per-object" + } + fn identity(&self) -> String { + "per-object:1".into() + } + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + let mut out = Vec::new(); + for &c in ctx.tree.own_children(ctx.root) { + if ctx.tree.node(c).type_name == "object" { + let name = &ctx.tree.node(c).name; + out.push(EmittedFile::new( + format!("src/{}.txt", name.to_lowercase()), + format!("// {name}\n"), + )); + } + } + out.push(EmittedFile::new( + "index.txt".to_string(), + "// all\n".to_string(), + )); + Ok(out) + } +} + +#[test] +fn a_run_over_a_two_package_model_writes_a_manifest_per_package_and_a_root_one() { + let p = Scratch::project("e2e", &shop_files()); + let opts = RunOptions::new(p.path()); + let gens: Vec> = vec![Box::new(PerObject)]; + let r = run(&opts, &gens).unwrap_or_else(|e| panic!("{e}")); + assert!(r.manifest_written); + let gs = p.path().join(".metaobjects/.gen-state"); + assert!(!gs.join(HASHES_FILE).exists()); + let files = files_of(&gs); + assert!(files.contains_key("shop.json"), "{:?}", files.keys()); + assert!( + files.contains_key("shop.billing.json"), + "{:?}", + files.keys() + ); + assert!(files.contains_key(ROOT_FILE), "{:?}", files.keys()); + let shop: Map = serde_json::from_str(&files["shop.json"]).unwrap(); + let billing: Map = serde_json::from_str(&files["shop.billing.json"]).unwrap(); + assert!(shop.keys().any(|k| k.ends_with("/order.txt")), "{shop:?}"); + assert!( + billing.keys().any(|k| k.ends_with("/invoice.txt")), + "{billing:?}" + ); + assert!(files[ROOT_FILE].contains("index.txt")); +} + +#[test] +fn the_gitignore_migration_replaces_the_legacy_line_or_inserts_after_the_rule() { + let new = ".gen-state/*\n!.gen-state/.hashes/\n"; + assert_eq!( + migrate_gitignore(".gen-state/*\n!.gen-state/.hashes.json\n").as_deref(), + Some(new) + ); + assert_eq!(migrate_gitignore(".gen-state/*\n").as_deref(), Some(new)); + assert_eq!( + migrate_gitignore(".gen-state/*\n!.gen-state/.hashes/\n!.gen-state/.hashes.json\n") + .as_deref(), + Some(new) + ); +} + +#[test] +fn a_manifest_whose_entries_are_all_in_packages_has_no_root_file() { + let root = scratch("noroot"); + let gs = gen_state(&root); + std::fs::create_dir_all(gs.join(HASHES_DIR)).unwrap(); + std::fs::write(gs.join(HASHES_DIR).join(ROOT_FILE), "{}\n").unwrap(); + let mut m = HashManifest::load(&gs); + m.set_objects(vec![("Order".into(), "acme::shop".into())]); + m.record("gen/Order.rs", "o1"); + assert!(m.save().unwrap()); + let names: Vec = files_of(&gs).into_keys().collect(); + assert_eq!(names, ["acme.shop.json"]); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index 15d39da472..87e9685d9e 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -18,7 +18,7 @@ use metaobjects_codegen::{ run, verify, }; -const MANIFEST: &str = ".metaobjects/.gen-state/.hashes.json"; +const MANIFEST: &str = ".metaobjects/.gen-state/.hashes/shop.json"; fn generators() -> Vec> { vec![Box::new(EntityGenerator)] @@ -203,7 +203,12 @@ fn an_orphan_with_a_hand_edit_is_never_deleted_and_fails_the_run_by_name() { other => panic!("expected a refusal, got {other}"), } assert_eq!(p.read(orphan), "// mine\n", "the edit is left in place"); - assert!(p.read(MANIFEST).contains(orphan), "and it stays recorded"); + // The object is gone, so nothing places the orphan any more: it is filed under the root. + assert!( + p.read(".metaobjects/.gen-state/.hashes/.root.json") + .contains(orphan), + "and it stays recorded" + ); assert!( !p.exists(&format!(".metaobjects/.gen-state/{FINGERPRINT_FILE}")), "a refused run is not a current one" diff --git a/server/rust/metaobjects-codegen/tests/skip_conformance.rs b/server/rust/metaobjects-codegen/tests/skip_conformance.rs index ef32e8e320..6c9ab29813 100644 --- a/server/rust/metaobjects-codegen/tests/skip_conformance.rs +++ b/server/rust/metaobjects-codegen/tests/skip_conformance.rs @@ -162,6 +162,8 @@ fn write_json(p: &Scratch, rel: &str, doc: &Value) { const SHOP_FILE: &str = "metaobjects/meta.shop.json"; const BILLING_FILE: &str = "metaobjects/meta.billing.json"; +const LEGACY_MANIFEST: &str = ".metaobjects/.gen-state/.hashes.json"; +const MANIFEST_DIR: &str = ".metaobjects/.gen-state/.hashes"; const KEY_FILE: &str = ".metaobjects/.gen-state/.fingerprint-rust.json"; /// Apply the case's change and run the next `gen`. @@ -334,6 +336,23 @@ fn next_run(id: &str, p: &Scratch, ask: Ask) -> Answer { p.write(©, "// the owned generator, edited\n"); ask.go(p, Probe::default(), |_| {}) } + "legacy-manifest" => { + // Back to the pre-1.3.0 form: every per-package file merged into one `.hashes.json`. + let dir = p.path().join(".metaobjects/.gen-state/.hashes"); + let mut merged = serde_json::Map::new(); + for e in std::fs::read_dir(&dir).unwrap() { + let text = std::fs::read_to_string(e.unwrap().path()).unwrap(); + let Value::Object(m) = serde_json::from_str(&text).unwrap() else { + panic!("a manifest file is an object"); + }; + merged.extend(m); + } + std::fs::remove_dir_all(&dir).unwrap(); + let mut text = serde_json::to_string_pretty(&Value::Object(merged)).unwrap(); + text.push('\n'); + p.write(LEGACY_MANIFEST, &text); + ask.go(p, Probe::default(), |_| {}) + } "failed-run" => { let original = p.read(SHOP_FILE); let mut doc = shop_json(); @@ -412,6 +431,17 @@ fn every_case_in_the_shared_corpus_behaves_as_it_says() { "regenerate" => { let r = result.unwrap_or_else(|e| panic!("{id}: the run failed: {e}")); assert_eq!(r.outcome, Outcome::Generated, "{id}: {}", case["change"]); + if id == "legacy-manifest" { + assert!( + r.manifest_written, + "{id}: the migration is a manifest write" + ); + assert!( + !p.exists(LEGACY_MANIFEST), + "{id}: the legacy file is removed" + ); + assert!(p.exists(MANIFEST_DIR), "{id}: per-package files are left"); + } } other => panic!("{id}: unknown gen expectation {other}"), } @@ -443,6 +473,10 @@ fn every_case_in_the_shared_corpus_behaves_as_it_says() { "{id}: nothing drifted: {}", case["change"] ); + if id == "legacy-manifest" { + assert!(p.exists(LEGACY_MANIFEST), "{id}: verify migrates nothing"); + assert!(!p.exists(MANIFEST_DIR), "{id}: verify migrates nothing"); + } } (expected, other) => panic!("{id}: verify should {expected}, got {other:?}"), } diff --git a/server/typescript/packages/cli/src/commands/init.ts b/server/typescript/packages/cli/src/commands/init.ts index 3acc0e46cd..8c6a638cce 100644 --- a/server/typescript/packages/cli/src/commands/init.ts +++ b/server/typescript/packages/cli/src/commands/init.ts @@ -51,16 +51,17 @@ const META_COMMON_JSON = JSON.stringify( // pattern, then explicitly re-include `migrations/` and `config.json` so the // tracked artifacts are never swept up even if a future broad pattern were added. const METAOBJECTS_GITIGNORE_BODY = `# The codegen merge base. The snapshot BODIES are a second full copy of all -# generated output — never commit those. \`.hashes.json\` is different: it is one -# hash per generated path, and it is the only thing that lets \`meta gen\` tell "this -# file is exactly what I wrote" from "somebody edited this" on a machine that did -# not generate it. Without it committed, every fresh clone and every CI runner has -# no merge base, and a hand-edited generated file cannot be recognised as such. +# generated output — never commit those. \`.hashes/\` is different: it holds one +# hash per generated path (a file per model package), and it is the only thing +# that lets \`meta gen\` tell "this file is exactly what I wrote" from "somebody +# edited this" on a machine that did not generate it. Without it committed, every +# fresh clone and every CI runner has no merge base, and a hand-edited generated +# file cannot be recognised as such. # # The glob form matters: \`.gen-state/\` (a directory) would stop git descending, and # the negation below could never take effect. .gen-state/* -!.gen-state/.hashes.json +!.gen-state/.hashes/ # Per-target codegen output routed under .metaobjects// is regenerable # (re-run \`meta gen\`); never commit it. The canonical output is your configured diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts index 3f09ef4d6b..ea7c5af0ff 100644 --- a/server/typescript/packages/cli/src/index.ts +++ b/server/typescript/packages/cli/src/index.ts @@ -78,7 +78,7 @@ GEN FLAGS: First-time-on-existing-file behavior. Default: refuse a file that cannot be proved to be generated output. "adopt" records the files you have as the merge base and writes NOTHING — the first run a - project with no committed .hashes.json can perform. "fresh" + project with no committed .hashes/ manifest can perform. "fresh" overwrites them with fresh output and re-baselines (discards edits). --no-antipatterns Suppress the advisory "hand-rolled what MetaObjects can model" pass --limit How many advisory lines TEXT output prints before it truncates @@ -217,7 +217,7 @@ FLAGS: First-time-on-existing-file behavior. Default: refuse a file that cannot be proved to be generated output. "adopt" records the files you have as the merge base and writes NOTHING — the first run a - project with no committed .hashes.json can perform. "fresh" + project with no committed .hashes/ manifest can perform. "fresh" overwrites them with fresh output and re-baselines (discards edits). --no-antipatterns Suppress the advisory "hand-rolled what MetaObjects can model" pass --limit Advisory lines TEXT output prints before truncating (default 20) diff --git a/server/typescript/packages/cli/src/lib/codegen-drift.ts b/server/typescript/packages/cli/src/lib/codegen-drift.ts index 04da0095d2..608fbf40b6 100644 --- a/server/typescript/packages/cli/src/lib/codegen-drift.ts +++ b/server/typescript/packages/cli/src/lib/codegen-drift.ts @@ -15,7 +15,7 @@ // so the next run failed identically. Requirement-test stubs were the worst case, // being worthless until hand-edited. // -// The discriminator is `.gen-state/.hashes.json`, which records what the GENERATOR +// The discriminator is the manifest under `.gen-state/.hashes/`, which records what the GENERATOR // WROTE rather than what the file became, and is the committed half of `.gen-state` // precisely so this is answerable on a machine that did not generate the output. // When a fresh regen hashes to what we recorded writing, the generator's diff --git a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts index f81a7739ba..3a62b84d17 100644 --- a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts +++ b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts @@ -21,6 +21,7 @@ import { existsSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import type { Collection } from "@metaobjectsdev/sdk/collection"; +import { readManifestState } from "@metaobjectsdev/codegen-ts"; import { GEN_CONFIG_FILE } from "./gen-collection.js"; /** Bumped whenever what goes into the fingerprint changes, so an old stored key never matches. */ @@ -60,7 +61,6 @@ export interface StoredFingerprint { } export const FINGERPRINT_FILE = ".fingerprint-typescript.json"; -const HASHES_FILE = ".hashes.json"; /** Directories never descended into: dependencies, VCS and tool state, build caches. */ const SKIP_DIRS = new Set(["node_modules", ".git", ".turbo", ".cache", ".metaobjects"]); @@ -444,12 +444,11 @@ export function clearStoredFingerprint(genStateDir: string): void { rmSync(join(genStateDir, FINGERPRINT_FILE), { force: true }); } -/** The manifest's recorded paths and hashes; empty when there is none. */ +/** The manifest's recorded paths and hashes (every package's manifest, ADR-0064 Amendment 1); + * empty when there is none. */ function recordedFiles(genStateDir: string): Map { const out = new Map(); - const raw = readJson(join(genStateDir, HASHES_FILE)); - if (raw === undefined) return out; - for (const [path, value] of Object.entries(raw)) { + for (const [path, value] of Object.entries(readManifestState(genStateDir).entries)) { if (typeof value === "string") out.set(path, value); else if (typeof value === "object" && value !== null && typeof (value as { hash?: unknown }).hash === "string") { out.set(path, (value as { hash: string }).hash); @@ -468,6 +467,16 @@ export type SkipVerdict = * the generated files (no render, no write); a file changed since then makes the run render. */ export function decideGenSkip(inputs: GenInputs): SkipVerdict { + // A run that finds the pre-1.3.0 single manifest migrates it (ADR-0064 Amendment 1), which + // is a write, so it never skips. + if (readManifestState(inputs.genStateDir).legacy) { + return { skip: false, reason: "the manifest is still in its single-file form" }; + } + return decideKeyAndOutputs(inputs); +} + +/** The skip decision without the migration rule: what a read-only `verify` may rely on. */ +function decideKeyAndOutputs(inputs: GenInputs): SkipVerdict { // Never decide without the model half: the generator half alone says nothing about it. if (!inputs.entries.some((e) => e.kind === "model")) return { skip: false, reason: "the model was not hashed" }; const stored = readStoredFingerprint(inputs.genStateDir); @@ -492,7 +501,7 @@ export function decideGenSkip(inputs: GenInputs): SkipVerdict { * hand edit is not an input, so `gen` may skip over one, but `verify` must still see it. */ export function decideVerifyNoDrift(inputs: GenInputs): SkipVerdict { - const verdict = decideGenSkip(inputs); + const verdict = decideKeyAndOutputs(inputs); if (!verdict.skip) return verdict; const recorded = recordedFiles(inputs.genStateDir); if (recorded.size === 0) return { skip: false, reason: "the manifest records no file" }; diff --git a/server/typescript/packages/cli/src/lib/manifest-ignored-check.ts b/server/typescript/packages/cli/src/lib/manifest-ignored-check.ts index 169a0576d9..11c40f0a34 100644 --- a/server/typescript/packages/cli/src/lib/manifest-ignored-check.ts +++ b/server/typescript/packages/cli/src/lib/manifest-ignored-check.ts @@ -1,6 +1,6 @@ // Advisory: is the codegen hash manifest git-ignored? // -// `.gen-state/.hashes.json` is what lets `meta gen` tell "this file is exactly what +// `.gen-state/.hashes/` (one manifest per model package) is what lets `meta gen` tell "this file is exactly what // I wrote" from "somebody edited this" on a machine that did not generate it. If it // is ignored, that knowledge never leaves the generating machine, and on every other // machine a hand-edited generated file cannot be recognised as such. @@ -20,9 +20,9 @@ import { join } from "node:path"; import { log } from "./log.js"; import { gitIgnoreSource, isGitIgnored } from "./git-ignore.js"; -/** Project-relative path of the manifest — the one artifact of `.gen-state/` that is - * meant to be committed. */ -export const HASH_MANIFEST_REL = join(".metaobjects", ".gen-state", ".hashes.json"); +/** Project-relative path of the manifest directory — the one artifact of `.gen-state/` that is + * meant to be committed (one file per model package, ADR-0064 Amendment 1). */ +export const HASH_MANIFEST_REL = join(".metaobjects", ".gen-state", ".hashes"); /** * Warn once when the hash manifest is git-ignored, naming the fix. @@ -55,7 +55,7 @@ export function warnIfManifestIgnored(cwd: string): string | undefined { src !== undefined ? `The rule is '${src.pattern}' at ${src.file}:${src.line} — replace it there with ` + `a '/*' form plus a '!' negation for the manifest ` + - `(e.g. '${src.pattern.replace(/\/$/, "")}/*' and '!${src.pattern.replace(/\/$/, "")}/.hashes.json')` + `(e.g. '${src.pattern.replace(/\/$/, "")}/*' and '!${src.pattern.replace(/\/$/, "")}/.hashes/')` : `Find the rule with 'git check-ignore -v ${HASH_MANIFEST_REL}' and replace it with ` + `a '/*' form plus a '!' negation for the manifest`; diff --git a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap index 07c38e7a02..735baf8e22 100644 --- a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap +++ b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap @@ -56,7 +56,7 @@ GEN FLAGS: First-time-on-existing-file behavior. Default: refuse a file that cannot be proved to be generated output. "adopt" records the files you have as the merge base and writes NOTHING — the first run a - project with no committed .hashes.json can perform. "fresh" + project with no committed .hashes/ manifest can perform. "fresh" overwrites them with fresh output and re-baselines (discards edits). --no-antipatterns Suppress the advisory "hand-rolled what MetaObjects can model" pass --limit How many advisory lines TEXT output prints before it truncates diff --git a/server/typescript/packages/cli/test/gen-skip-conformance.test.ts b/server/typescript/packages/cli/test/gen-skip-conformance.test.ts index b891dc73f5..b978e9db6d 100644 --- a/server/typescript/packages/cli/test/gen-skip-conformance.test.ts +++ b/server/typescript/packages/cli/test/gen-skip-conformance.test.ts @@ -6,7 +6,7 @@ // A case id this runner does not know fails, so a case added to the table reaches this // port at once. import { afterAll, describe, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs"; import * as fs from "node:fs"; import { join, resolve } from "node:path"; import { genCommand } from "../src/commands/gen.js"; @@ -156,6 +156,8 @@ interface Runner { engine?: FingerprintEntry[]; /** `verify --codegen --full`. */ full?: boolean; + /** Checked after both answers: what the read-only questions must have left alone. */ + after?: (p: Project) => void; } const append = (path: string, text: string) => writeFileSync(path, readFileSync(path, "utf-8") + text); @@ -220,6 +222,22 @@ const RUNNERS: Record = { }, }, "fingerprint-missing": { change: (p) => unlinkSync(stateFile(p)) }, + // ADR-0064 Amendment 1: put the manifest back in its pre-1.3.0 single-file form. + "legacy-manifest": { + change: (p) => { + const state = join(p.root, ".metaobjects", ".gen-state"); + const merged: Record = {}; + for (const name of readdirSync(join(state, ".hashes")).sort()) { + Object.assign(merged, JSON.parse(readFileSync(join(state, ".hashes", name), "utf-8"))); + } + rmSync(join(state, ".hashes"), { recursive: true, force: true }); + writeFileSync(join(state, ".hashes.json"), JSON.stringify(merged, null, 2) + "\n"); + }, + // A local verify reads the union and migrates nothing, so the legacy file is still there. + after: (p) => { + expect(existsSync(join(p.root, ".metaobjects", ".gen-state", ".hashes.json"))).toBe(true); + }, + }, "force": { args: ["--force"], full: true }, "ci": { env: { CI: "true" } }, "failed-run": { @@ -248,6 +266,7 @@ describe("codegen-skip-conformance (ADR-0064)", () => { await runner.change?.(p); expect(await genSkips(p, runner)).toBe(c.gen === "skip"); expect(await verifyMayAnswer(p, runner)).toBe(c.verify === "may-answer-no-drift"); + runner.after?.(p); }, 30_000); } }); @@ -258,7 +277,7 @@ describe("meta gen with nothing changed (ADR-0064)", () => { expect(await gen(p)).toBe(0); const watched = [ join(p.root, "generated", "mine.txt"), - join(p.root, ".metaobjects", ".gen-state", ".hashes.json"), + join(p.root, ".metaobjects", ".gen-state", ".hashes", ".root.json"), stateFile(p), ]; const before = watched.map((f) => statSync(f).mtimeMs); @@ -277,7 +296,7 @@ describe("meta gen with nothing changed (ADR-0064)", () => { expect(await gen(p)).toBe(0); const watched = [ join(p.root, "generated", "mine.txt"), - join(p.root, ".metaobjects", ".gen-state", ".hashes.json"), + join(p.root, ".metaobjects", ".gen-state", ".hashes", ".root.json"), ]; const before = watched.map((f) => statSync(f).mtimeMs); await new Promise((r) => setTimeout(r, 20)); diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-ejected-generator.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-ejected-generator.test.ts index 8be02aa874..1acbd83753 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-ejected-generator.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-ejected-generator.test.ts @@ -21,7 +21,7 @@ * 3. The printed remedy terminates. That is NOT free: it is precisely where the * 0.24.3 hand-edit loop lived. There the remedy could not work, because * `meta gen` re-merged the edit and the next verify failed identically. Here it - * does work, because the discriminator is `.gen-state/.hashes.json` — a record + * does work, because the discriminator is `.gen-state/.hashes/` — a record * of what the GENERATOR WROTE — and re-running `meta gen` writes through the new * generator and re-records the hash. The two cases must not be conflated: a hand * edit in a generated FILE is preserved and forgiven, while a change to the diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts index 3556d35d8b..501a51cb35 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts @@ -10,7 +10,7 @@ * letter therefore ended in `verify --codegen` exiting 1 on a project with no * drift of any kind, naming sixteen files it does not own. * - * The rule is JURISDICTION, not staleness: `.gen-state/.hashes.json` records what + * The rule is JURISDICTION, not staleness: `.gen-state/.hashes/` records what * the generator WROTE, and `meta gen`'s own orphan sweep already scopes itself to * those paths (`listGeneratedPaths`) before it will delete anything. The gate now * asks the same question of the same evidence, so the two doors agree. @@ -26,6 +26,7 @@ import { cpSync, mkdtempSync, mkdirSync, + readdirSync, rmSync, writeFileSync, readFileSync, @@ -38,7 +39,10 @@ const FIXTURES = resolve(import.meta.dirname, "../fixtures"); const WORKSPACE_TMP = resolve(import.meta.dirname, "../fixtures/__tmp__"); const OUT = "generated"; -const MANIFEST = join(".metaobjects", ".gen-state", ".hashes.json"); +const MANIFEST = join(".metaobjects", ".gen-state", ".hashes"); +/** Every manifest file, concatenated. */ +const manifestText = (root: string): string => + readdirSync(join(root, MANIFEST)).map((n) => readFileSync(join(root, MANIFEST, n), "utf8")).join("\n"); function setupRepo(): string { mkdirSync(WORKSPACE_TMP, { recursive: true }); @@ -167,7 +171,7 @@ describe("meta verify --codegen — files MetaObjects never wrote", () => { out = []; err = []; expect(await run(["gen", "--cwd", root])).toBe(0); expect(existsSync(join(root, OUT, "Tag.ts"))).toBe(false); - expect(readFileSync(join(root, MANIFEST), "utf8")).not.toContain("Tag.ts"); + expect(manifestText(root)).not.toContain("Tag.ts"); out = []; err = []; expect(await run(["verify", "--cwd", root, "--codegen"])).toBe(0); @@ -258,7 +262,7 @@ export default defineConfig({ // No records ⇒ nothing distinguishes our stale output from a stranger's // file, so the gate keeps convicting rather than going quiet. expect(existsSync(join(root, MANIFEST))).toBe(true); - rmSync(join(root, MANIFEST)); + rmSync(join(root, MANIFEST), { recursive: true, force: true }); out = []; err = []; const exit = await run(["verify", "--cwd", root, "--codegen"]); diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts index 8922cea153..c3922c70b9 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts @@ -10,7 +10,7 @@ * the edit again, so the next verify failed identically. An unbreakable loop for * anyone doing the sanctioned thing. * - * The discriminator is `.gen-state/.hashes.json`, which records what the GENERATOR + * The discriminator is `.gen-state/.hashes/`, which records what the GENERATOR * WROTE (not what the file became) and is committed while the snapshot bodies are * not — the split exists so this question is answerable on a machine that did not * generate the output. @@ -20,6 +20,7 @@ import { cpSync, mkdtempSync, mkdirSync, + readdirSync, rmSync, writeFileSync, readFileSync, @@ -325,9 +326,9 @@ describe("meta verify --codegen — hand-edited generated output", () => { expect(await run(["gen", "--cwd", root])).toBe(0); // No manifest ⇒ nothing is proven ⇒ the old, conservative verdict stands. - const manifest = join(root, ".metaobjects", ".gen-state", ".hashes.json"); + const manifest = join(root, ".metaobjects", ".gen-state", ".hashes"); expect(existsSync(manifest)).toBe(true); - rmSync(manifest); + rmSync(manifest, { recursive: true, force: true }); out = []; err = []; const exit = await run(["verify", "--cwd", root, "--codegen"]); @@ -419,10 +420,12 @@ describe("meta verify --codegen — hand edits are visible", () => { weakenValidator(root); // Simulate the clone: keep only the committed half of .gen-state. const genState = join(root, ".metaobjects", ".gen-state"); - const hashes = readFileSync(join(genState, ".hashes.json"), "utf8"); + const hashes = Object.fromEntries( + readdirSync(join(genState, ".hashes")).map((n) => [n, readFileSync(join(genState, ".hashes", n), "utf8")]), + ); rmSync(genState, { recursive: true, force: true }); - mkdirSync(genState, { recursive: true }); - writeFileSync(join(genState, ".hashes.json"), hashes); + mkdirSync(join(genState, ".hashes"), { recursive: true }); + for (const [n, text] of Object.entries(hashes)) writeFileSync(join(genState, ".hashes", n), text); out = []; err = []; expect(await run(["verify", "--cwd", root, "--codegen"])).toBe(0); diff --git a/server/typescript/packages/cli/test/manifest-ignored-check.test.ts b/server/typescript/packages/cli/test/manifest-ignored-check.test.ts index dd8337ecc1..1cf9191360 100644 --- a/server/typescript/packages/cli/test/manifest-ignored-check.test.ts +++ b/server/typescript/packages/cli/test/manifest-ignored-check.test.ts @@ -1,6 +1,6 @@ // The check that ships with the fix. // -// A project whose `.gitignore` still excludes `.gen-state/.hashes.json` looks +// A project whose `.gitignore` still excludes `.gen-state/.hashes/` looks // completely healthy — gen succeeds, output is correct — while hand-edit detection // silently does not work anywhere but the generating machine. That invisibility is // the whole reason a doc is not enough. @@ -27,7 +27,7 @@ function gitInit(): void { } function writeManifest(): void { - const p = join(root, HASH_MANIFEST_REL); + const p = join(root, HASH_MANIFEST_REL, ".root.json"); mkdirSync(dirname(p), { recursive: true }); writeFileSync(p, "{}\n"); } @@ -51,18 +51,18 @@ describe("warnIfManifestIgnored", () => { writeManifest(); // The naive form. git will not descend into an excluded directory, so the `!` // below it never applies — the manifest stays ignored and nobody notices. - writeIgnore(".gen-state/\n!.gen-state/.hashes.json\n"); + writeIgnore(".gen-state/\n!.gen-state/.hashes/\n"); const warnings = captureWarnings(() => warnIfManifestIgnored(root)); expect(warnings.length).toBe(1); - expect(warnings[0]).toContain(".hashes.json"); + expect(warnings[0]).toContain(".hashes"); expect(warnings[0]).toContain(".gen-state/*"); }); test("SILENT on the correct glob form", () => { gitInit(); writeManifest(); - writeIgnore(".gen-state/*\n!.gen-state/.hashes.json\n"); + writeIgnore(".gen-state/*\n!.gen-state/.hashes/\n"); expect(captureWarnings(() => warnIfManifestIgnored(root))).toEqual([]); }); @@ -124,7 +124,7 @@ describe("the advisory names the rule that is actually in force", () => { const warns = captureWarnings(() => warnIfManifestIgnored(root)); expect(warns).toHaveLength(1); expect(warns[0]).toContain(".metaobjects/.gitignore:1"); - expect(warns[0]).toContain("!.gen-state/.hashes.json"); + expect(warns[0]).toContain("!.gen-state/.hashes/"); }); test("when git cannot say, it degrades to the generic form and asserts no location", () => { diff --git a/server/typescript/packages/codegen-ts/README.md b/server/typescript/packages/codegen-ts/README.md index 5cd9c88968..3aec031ce5 100644 --- a/server/typescript/packages/codegen-ts/README.md +++ b/server/typescript/packages/codegen-ts/README.md @@ -57,7 +57,7 @@ const newPost = await createPost({ title: 'Hello', body: 'World', authorId: 1 }) Generated files carry an `@generated by @metaobjectsdev/codegen-ts` header. On this port the header is **informational** — the write decision never reads it. What decides is `.metaobjects/.gen-state/`: the snapshot body if this machine has one (three-way -merge), otherwise the committed `.hashes.json` (byte-for-byte what we wrote ⇒ +merge), otherwise the committed manifest under `.gen-state/.hashes/` (byte-for-byte what we wrote ⇒ overwrite; anything else ⇒ refused, path named, exit code 1). Deleting the header does not take ownership of a file here — it just changes the content, so the hash stops matching and the file is refused like any other edit. (The JVM ports are the opposite: @@ -68,7 +68,7 @@ Hand-written code that metadata can't express — custom queries, derived-column goes in a **sibling module you create and import yourself**, conventionally `.extra.ts` beside the generated output. The name is a convention, not a mechanism: the file is safe because codegen only ever writes the paths recorded in -`.gen-state/.hashes.json`, and for the same reason the generated barrel — built from the +`.gen-state/.hashes/`, and for the same reason the generated barrel — built from the model, not from a directory listing — does **not** re-export it. Import it directly. ### Allowlists opt-in diff --git a/server/typescript/packages/codegen-ts/src/constants.ts b/server/typescript/packages/codegen-ts/src/constants.ts index 426c94bca6..9be22ee1d6 100644 --- a/server/typescript/packages/codegen-ts/src/constants.ts +++ b/server/typescript/packages/codegen-ts/src/constants.ts @@ -48,7 +48,7 @@ export const NAMES_FILE_SUFFIX = ".names.ts"; // wired to nothing: no generator, orphan sweep or write path ever compared a path // against it, so its presence implied tool support for a name that is pure convention. // A `.extra.ts` sibling is safe because codegen only writes the paths it -// records in `.gen-state/.hashes.json` — not because of its name — and the generated +// records in the `.gen-state/.hashes/` manifest — not because of its name — and the generated // barrel is built from the model, so it does not re-export it. Say that in prose; // do not re-add a constant that suggests the engine knows the name. diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts index 9ea59e4120..3c6debf9f2 100644 --- a/server/typescript/packages/codegen-ts/src/generator.ts +++ b/server/typescript/packages/codegen-ts/src/generator.ts @@ -19,7 +19,7 @@ export interface EmittedFile { /** Set by the runner from generator.name — generators should not set this. */ generatedBy?: string; /** The resolution key of the metadata node this file was rendered from - * (`acme::shop::Order`), recorded beside the file's hash in `.gen-state/.hashes.json`. + * (`acme::shop::Order`), recorded beside the file's hash in the manifest under `.gen-state/.hashes/`. * `perEntity` sets it for you; a generator rendering one file from one node by other * means sets it itself. Leave it unset for a file rendered from the whole model or a * whole package (a barrel, a docs index). */ @@ -153,7 +153,7 @@ export interface GenContext { * The files this run generated, for a generator marked `readsRunOutput` (the docs site's * model explorer, which lists what was generated from each node). The runner runs such a * generator after every other one, so the list is complete. Paths are project-relative, - * as `.gen-state/.hashes.json` keys them. A run narrowed with `--generators` adds the + * as the manifest under `.gen-state/.hashes/` keys them. A run narrowed with `--generators` adds the * files the committed manifest records for the generators it did not run, so a narrowed * run lists what a full run lists. Absent for a generator without the marker. */ diff --git a/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts b/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts new file mode 100644 index 0000000000..3f2c202708 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts @@ -0,0 +1,209 @@ +// The hash manifest as files on disk: one per model package (ADR-0064 Amendment 1). +// +// `.gen-state/.hashes.json` used to be one file for the whole project, so any two branches +// that regenerated anything both rewrote it and conflicted, whether or not they shared a +// generated file. The manifest is now `.gen-state/.hashes/.json`, one file per +// model package, plus `.root.json` for a path in no package. +// +// This module reads the manifest and decides placement; `overwrite-policy.ts` writes it. The rest of codegen keeps seeing one flat map of +// path → entry (`overwrite-policy.ts` holds it in memory and every reader goes through it); +// what changes is where the bytes live. That is also why a wrong placement is harmless: a +// reader merges every file and finds a path wherever it is, so a misplaced entry costs a +// merge conflict that could have been avoided and nothing else. +// +// Placement is a pure function of the entry and the loaded model, so it is stable: an entry +// moves only when its object moves package or is renamed. See the ADR for the rule; the +// vectors every port runs are `fixtures/codegen-skip-conformance/manifests.json`. + +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +export const LEGACY_HASHES_FILE = ".hashes.json"; +export const HASHES_DIR = ".hashes"; +export const ROOT_MANIFEST = ".root.json"; + +/** The metadata package separator. */ +const PACKAGE_SEPARATOR = "::"; + +/** A loaded root-level object, as the stem rule needs it. `package` is `""` for none. */ +export interface PlacementObject { + name: string; + package: string; +} + +/** Everything the stem rule needs from the loaded model. Built once per run. */ +export interface PlacementIndex { + /** Each distinct object name as words, with the distinct packages that declare it. */ + readonly names: readonly { words: readonly string[]; packages: readonly string[] }[]; +} + +/** + * Split a name or file stem into lowercase words: at `_` and `-`, before an uppercase letter + * that follows a lowercase letter or digit, and before the last capital of a run that a + * lowercase letter follows (`HTTPServer` is `http`, `server`). Digits stay with the word + * before them. Only ASCII letters carry case. + */ +export function splitWords(text: string): string[] { + const words: string[] = []; + let word = ""; + const flush = (): void => { + if (word !== "") words.push(word.toLowerCase()); + word = ""; + }; + const upper = (c: string | undefined): boolean => c !== undefined && c >= "A" && c <= "Z"; + const lower = (c: string | undefined): boolean => c !== undefined && ((c >= "a" && c <= "z") || (c >= "0" && c <= "9")); + for (let i = 0; i < text.length; i++) { + const c = text[i]!; + if (c === "_" || c === "-") { + flush(); + continue; + } + if (upper(c) && word !== "") { + const prev = text[i - 1]; + const next = text[i + 1]; + const nextLower = next !== undefined && next >= "a" && next <= "z"; + if (lower(prev) || (upper(prev) && nextLower)) flush(); + } + word += c; + } + flush(); + return words; +} + +export function buildPlacementIndex(objects: readonly PlacementObject[]): PlacementIndex { + const byName = new Map>(); + for (const o of objects) { + let set = byName.get(o.name); + if (set === undefined) byName.set(o.name, (set = new Set())); + set.add(o.package); + } + const names = [...byName.entries()].map(([name, packages]) => ({ + words: splitWords(name), + packages: [...packages], + })); + return { names }; +} + +/** The manifest file name of a package, or of the root when `pkg` is `null`. */ +export function manifestFileName(pkg: string | null): string { + if (pkg === null) return ROOT_MANIFEST; + const encoder = new TextEncoder(); + const segment = (s: string): string => { + let out = ""; + for (const ch of s) { + if (/^[A-Za-z0-9_-]$/.test(ch)) out += ch; + else for (const b of encoder.encode(ch)) out += `%${b.toString(16).toUpperCase().padStart(2, "0")}`; + } + return out; + }; + return `${pkg.split(PACKAGE_SEPARATOR).map(segment).join(".")}.json`; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** The package a `sourceNode` names, `null` for an object in no package. */ +function packageOfSourceNode(sourceNode: string): string | null { + const dot = sourceNode.indexOf("."); + const key = dot === -1 ? sourceNode : sourceNode.slice(0, dot); + const at = key.lastIndexOf(PACKAGE_SEPARATOR); + return at <= 0 ? null : key.slice(0, at); +} + +/** The package whose object the file's stem names (the stem rule), `null` when none. */ +function packageOfStem(path: string, index: PlacementIndex): string | null { + const base = path.slice(path.lastIndexOf("/") + 1); + const dot = base.indexOf("."); + const stem = splitWords(dot === -1 ? base : base.slice(0, dot)); + let best = 0; + const packages = new Set(); + for (const { words, packages: declared } of index.names) { + if (words.length === 0 || words.length > stem.length || words.length < best) continue; + if (!words.every((w, i) => w === stem[i])) continue; + // More words win; objects with equally many words pool their packages. + if (words.length > best) packages.clear(); + best = words.length; + for (const p of declared) packages.add(p); + } + if (packages.size !== 1) return null; + const only = [...packages][0]!; + return only === "" ? null : only; +} + +/** + * Which manifest an entry is filed under: its package, `null` for the root, or `undefined` + * when nothing here decides (no `sourceNode` and no model), which keeps the entry where it is. + */ +export function placeEntry( + path: string, + entry: unknown, + index: PlacementIndex | undefined, +): string | null | undefined { + if (isRecord(entry) && typeof entry.sourceNode === "string") return packageOfSourceNode(entry.sourceNode); + if (index !== undefined) return packageOfStem(path, index); + return undefined; +} + +/** What one read of the manifest found. */ +export interface ManifestState { + /** Every entry: the union of the legacy file and every package file. */ + entries: Record; + /** The manifest file each entry was read from (the legacy file is not a placement). */ + fileOf: Map; + /** The text of every file in `.hashes/` as read, so a write can skip a file that did not change. */ + texts: Map; + /** True when a legacy `.hashes.json` was found: the next write run migrates it. */ + legacy: boolean; +} + +function readEntries(file: string): { entries: Record; text: string } | undefined { + let text: string; + try { + text = readFileSync(file, "utf-8"); + } catch { + return undefined; + } + try { + const parsed: unknown = JSON.parse(text); + return { entries: isRecord(parsed) ? parsed : {}, text }; + } catch { + // Corrupt reads as empty, which fails closed; the next write replaces it. + return { entries: {}, text }; + } +} + +function packageFiles(genStateDir: string): string[] { + try { + return readdirSync(join(genStateDir, HASHES_DIR)) + .filter((n) => n.endsWith(".json")) + .sort(); + } catch { + return []; + } +} + +/** True when the project has a manifest at all: the legacy file or a package file. */ +export function manifestExists(genStateDir: string): boolean { + return existsSync(join(genStateDir, LEGACY_HASHES_FILE)) || packageFiles(genStateDir).length > 0; +} + +/** Read the whole manifest. Absent, unreadable or corrupt files read as empty. */ +export function readManifestState(genStateDir: string): ManifestState { + const state: ManifestState = { entries: {}, fileOf: new Map(), texts: new Map(), legacy: false }; + const legacy = readEntries(join(genStateDir, LEGACY_HASHES_FILE)); + if (legacy !== undefined) { + state.legacy = true; + Object.assign(state.entries, legacy.entries); + } + for (const name of packageFiles(genStateDir)) { + const read = readEntries(join(genStateDir, HASHES_DIR, name)); + if (read === undefined) continue; + state.texts.set(name, read.text); + for (const [path, entry] of Object.entries(read.entries)) { + state.entries[path] = entry; + state.fileOf.set(path, name); + } + } + return state; +} diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index ebeaf31954..e15436e26b 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -96,6 +96,15 @@ export { decideAndWrite, GitMissingError, WRITE_STATUSES } from "./overwrite-pol // written — which is how the gate scopes itself to its own output instead of // convicting every stranger's file that happens to sit in the same directory. export { contentHash, readGeneratedHash, listGeneratedPaths, recordGeneratedProvenance } from "./overwrite-policy.js"; +export { + HASHES_DIR, + LEGACY_HASHES_FILE, + ROOT_MANIFEST, + manifestExists, + manifestFileName, + readManifestState, + type PlacementObject, +} from "./hash-manifest-store.js"; export type { GeneratedProvenance } from "./overwrite-policy.js"; export { modelHashTree, MODEL_HASH_FORMAT, type ModelHashTree, type ModelHashNode } from "./model-hash.js"; diff --git a/server/typescript/packages/codegen-ts/src/overwrite-policy.ts b/server/typescript/packages/codegen-ts/src/overwrite-policy.ts index 912b973e90..b88db195ff 100644 --- a/server/typescript/packages/codegen-ts/src/overwrite-policy.ts +++ b/server/typescript/packages/codegen-ts/src/overwrite-policy.ts @@ -21,7 +21,7 @@ // `baseline: "fresh"` flag opts into "overwrite from fresh and re-baseline". // // Integrity (caveat 2 from the spike): we keep a sha-256 of each canonical -// snapshot at `.gen-state/.hashes.json`. +// snapshot, in the manifest under `.gen-state/.hashes/` (one file per model package). // // THE MANIFEST IS COMMITTED; THE BODIES ARE NOT. That split is what makes step 4 // possible. A hash per path is small and reviewable, where a second full copy of @@ -42,6 +42,19 @@ import { } from "node:fs"; import { dirname, join, isAbsolute, relative, resolve } from "node:path"; import { spawnSync } from "node:child_process"; +import { + HASHES_DIR, + LEGACY_HASHES_FILE, + ROOT_MANIFEST, + buildPlacementIndex, + manifestExists, + manifestFileName, + placeEntry, + readManifestState, + type ManifestState, + type PlacementIndex, + type PlacementObject, +} from "./hash-manifest-store.js"; import { tmpdir } from "node:os"; import { createHash, randomBytes } from "node:crypto"; @@ -91,7 +104,7 @@ export type MergeStrategy = "overwrite" | "skip-existing"; * "adopt" — opt-in via `meta gen --baseline=adopt`. Same population, opposite * half: where the run would REFUSE, record the file's CURRENT content as the * merge base and write nothing. It exists because the refusal's leading remedy - * ("commit .hashes.json") could not be performed by the population it named — + * ("commit .hashes/") could not be performed by the population it named — * nothing writes a manifest until a gen succeeds, and gen refuses until one * exists. `adopt` is the run that produces the file to commit. * @@ -142,8 +155,6 @@ export interface WriteResult { discardedEdit?: boolean; } -const HASHES_FILE = ".hashes.json"; - type HashesFile = Record; function sha256(content: string | Buffer): string { @@ -153,7 +164,7 @@ function sha256(content: string | Buffer): string { /** * The manifest of a run in progress, held in memory and written once at its end. * - * Every write updates `.hashes.json`, and the file is the whole project's record, so + * Every write updates the manifest, and the manifest is the whole project's record, so * rewriting it per written file made bookkeeping quadratic in the project's size: at * a thousand generated files the rewrites were most of a run's wall time, for the same * bytes one write at the end produces. `withManifestBatch` holds the manifest for one @@ -166,6 +177,10 @@ function sha256(content: string | Buffer): string { interface ManifestBatch { raw: Record; dirty: boolean; + /** Where each entry was read from, so a write rewrites only the files that changed. */ + state: ManifestState; + /** The run's model, for placing entries that carry no `sourceNode`. */ + index: PlacementIndex | undefined; } const manifestBatches = new Map(); @@ -184,11 +199,26 @@ function batchFor(genStateDir: string): ManifestBatch | undefined { * read them as unrecorded and refuse them next run. When `fn` threw, a failed manifest * write is swallowed so `fn`'s error stays the one reported. A nested call for the same * directory joins the outer batch. + * + * `objects` is the run's loaded model (root-level object names and packages): the manifest + * is one file per package, and an entry that records no `sourceNode` is filed under the + * package of the object its file is named for. A run that finds the legacy single + * `.hashes.json` writes even when nothing else changed, because that is the migration. */ -export function withManifestBatch(genStateDir: string, fn: () => T): T { +export function withManifestBatch( + genStateDir: string, + fn: () => T, + objects?: readonly PlacementObject[], +): T { const key = resolve(genStateDir); if (manifestBatches.has(key)) return fn(); - const batch: ManifestBatch = { raw: readManifestFile(genStateDir), dirty: false }; + const state = readManifestState(genStateDir); + const batch: ManifestBatch = { + raw: state.entries, + dirty: state.legacy, + state, + index: objects !== undefined ? buildPlacementIndex(objects) : undefined, + }; manifestBatches.set(key, batch); let result: T; try { @@ -196,34 +226,120 @@ export function withManifestBatch(genStateDir: string, fn: () => T): T { } catch (err) { manifestBatches.delete(key); try { - if (batch.dirty) writeManifestFile(genStateDir, batch.raw); + if (batch.dirty) flushBatch(genStateDir, batch); } catch { // `fn`'s error is the cause to report; a failed manifest write must not replace it. } throw err; } manifestBatches.delete(key); - if (batch.dirty) writeManifestFile(genStateDir, batch.raw); + if (batch.dirty) flushBatch(genStateDir, batch); return result; } -function readRawManifest(genStateDir: string): Record { - const batch = batchFor(genStateDir); - return batch !== undefined ? batch.raw : readManifestFile(genStateDir); +function flushBatch(genStateDir: string, batch: ManifestBatch): void { + writeManifestFiles(genStateDir, batch.raw, batch.state, batch.index); } -function readManifestFile(genStateDir: string): Record { - const f = join(genStateDir, HASHES_FILE); - if (!existsSync(f)) return {}; +function manifestText(entries: Record): string { + // Keys SORTED, because this file is committed: insertion order would make the diff + // depend on which entity happened to generate first. + const sorted: Record = {}; + for (const key of Object.keys(entries).sort()) sorted[key] = entries[key]; + return JSON.stringify(sorted, null, 2) + "\n"; +} + +const NEGATION_LEGACY = "!.gen-state/.hashes.json"; +const NEGATION_DIR = "!.gen-state/.hashes/"; + +/** + * The scaffolded `.metaobjects/.gitignore` ignores `.gen-state/*` and un-ignores the legacy + * file only, so the new directory would be ignored and never reach another machine. Put its + * negation where the legacy one was and drop the legacy one, which names a file that no longer + * exists; with no legacy line, add it after the `.gen-state/*` rule. A file with no such rule + * is left alone. Only the migration calls this. + */ +export function ensureHashesDirNotIgnored(genStateDir: string): void { + const file = join(dirname(genStateDir), ".gitignore"); + let text: string; try { - const parsed: unknown = JSON.parse(readFileSync(f, "utf-8")); - if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { - return parsed as Record; - } - return {}; + text = readFileSync(file, "utf-8"); } catch { - return {}; + return; + } + const lines = text.split("\n"); + if (!lines.some((l) => l.trim() === ".gen-state/*")) return; + const hasDir = lines.some((l) => l.trim() === NEGATION_DIR); + const firstLegacy = lines.findIndex((l) => l.trim() === NEGATION_LEGACY); + const out: string[] = []; + let placed = hasDir; + lines.forEach((line, i) => { + const t = line.trim(); + if (t === NEGATION_LEGACY) { + if (i === firstLegacy && !placed) { + out.push(NEGATION_DIR); + placed = true; + } + return; + } + out.push(line); + if (!placed && firstLegacy === -1 && t === ".gen-state/*") { + out.push(NEGATION_DIR); + placed = true; + } + }); + const next = out.join("\n"); + if (next !== text) writeFileSync(file, next); +} + +/** + * Write `entries` as per-package manifests. Writes only the files whose bytes changed, + * removes package files that no longer hold an entry, and removes the legacy file (the + * migration). Returns nothing: a caller that wanted "did anything change" asked before. + */ +export function writeManifestFiles( + genStateDir: string, + entries: Record, + state: ManifestState, + index: PlacementIndex | undefined, +): void { + const groups = new Map>(); + for (const [path, entry] of Object.entries(entries)) { + const pkg = placeEntry(path, entry, index); + const name = pkg === undefined ? (state.fileOf.get(path) ?? ROOT_MANIFEST) : manifestFileName(pkg); + let group = groups.get(name); + if (group === undefined) groups.set(name, (group = {})); + group[path] = entry; } + // "No manifest" must stay distinguishable from "an empty one". + if (groups.size === 0) groups.set(ROOT_MANIFEST, {}); + + const dir = join(genStateDir, HASHES_DIR); + mkdirSync(dir, { recursive: true }); + for (const [name, group] of groups) { + const text = manifestText(group); + if (state.texts.get(name) === text) continue; + writeFileSync(join(dir, name), text); + state.texts.set(name, text); + } + for (const name of [...state.texts.keys()]) { + if (groups.has(name)) continue; + rmSync(join(dir, name), { force: true }); + state.texts.delete(name); + } + state.fileOf = new Map(); + for (const [name, group] of groups) for (const path of Object.keys(group)) state.fileOf.set(path, name); + + if (state.legacy) { + rmSync(join(genStateDir, LEGACY_HASHES_FILE), { force: true }); + state.legacy = false; + ensureHashesDirNotIgnored(genStateDir); + } +} + +function readRawManifest(genStateDir: string): Record { + const batch = batchFor(genStateDir); + return batch !== undefined ? batch.raw : readManifestState(genStateDir).entries; } function isRecord(value: unknown): value is Record { @@ -254,7 +370,7 @@ function saveHashes(genStateDir: string, hashes: HashesFile): void { } // A run that changed nothing writes nothing (ADR-0064 §1): the manifest is only written // when an entry was added, changed or removed. - if (existsSync(join(genStateDir, HASHES_FILE)) || manifestBatchOpen(genStateDir)) { + if (manifestExists(genStateDir) || manifestBatchOpen(genStateDir)) { const same = Object.keys(next).length === Object.keys(raw).length && Object.keys(next).every((k) => JSON.stringify(next[k]) === JSON.stringify(raw[k])); @@ -279,18 +395,8 @@ function writeRawManifest(genStateDir: string, entries: Record) batch.dirty = true; return; } - writeManifestFile(genStateDir, entries); -} - -function writeManifestFile(genStateDir: string, entries: Record): void { - mkdirSync(genStateDir, { recursive: true }); - // Keys SORTED, because this file is committed. Insertion order would make the - // diff — and any merge conflict between two people who both regenerated — - // depend on which entity happened to generate first, which is noise nobody can - // review. - const sorted: Record = {}; - for (const key of Object.keys(entries).sort()) sorted[key] = entries[key]; - writeFileSync(join(genStateDir, HASHES_FILE), JSON.stringify(sorted, null, 2) + "\n"); + // Outside a batch: read what is there (for the files' current bytes), then write. + writeManifestFiles(genStateDir, entries, readManifestState(genStateDir), undefined); } /** What produced one generated file: the generator, and the metadata node it was rendered @@ -372,7 +478,7 @@ export function listGeneratedProvenance( // --------------------------------------------------------------------------- // FR-038 §8 — readers for orphan reconciliation. // -// `.hashes.json`'s key set is the ONLY record of what a previous run wrote, so +// The manifest's key set is the ONLY record of what a previous run wrote, so // it is also the only way to notice that a file we used to generate is no longer // generated. These three functions expose that record without widening the write // path: nothing here decides anything (see reconcile-orphans.ts) and nothing here @@ -392,7 +498,7 @@ export function listGeneratedPaths(genStateDir: string): string[] { } /** - * sha-256 of `content`, hex — the same function that produces `.hashes.json`. + * sha-256 of `content`, hex — the same function that produces the manifest's hashes. * * Exported so a caller can ask the one question the manifest exists to answer * ("is this file byte-for-byte what we recorded writing?") without needing the @@ -456,7 +562,7 @@ export function readGeneratedSnapshot( /** * Drop both halves of the record for paths this run no longer generates — each - * snapshot file and its `.hashes.json` entry. + * snapshot file and its manifest entry. * * BOTH halves, or the next run sees the path again in `listGeneratedPaths` and * re-decides an orphan that has already been dealt with. A no-op for a path that was @@ -489,7 +595,7 @@ const ENGINE_FILE = ".engine.json"; /** * The codegen engine version that last wrote this `.gen-state`, or undefined if it * was never stamped (a pre-#232 snapshot, or a fresh project). Informational only — - * a separate reserved file from `.hashes.json`, it never participates in the + * a separate reserved file from the hash manifest, it never participates in the * three-way merge decision. (#232) */ export function loadEngineVersion(genStateDir: string): string | undefined { @@ -519,7 +625,7 @@ export function saveEngineVersion(genStateDir: string, version: string): void { } function snapshotPath(genStateDir: string, relPath: string): string { - // `.hashes.json` is reserved at the top of .gen-state/; relPath must never + // `.hashes/` (and the legacy `.hashes.json`) is reserved at the top of .gen-state/; relPath must never // collide with it. Output paths derived from entity names ("Post.ts" etc.) // are JS-identifier-shape so this is a non-issue in practice. return join(genStateDir, relPath); @@ -677,7 +783,7 @@ function resolveGenStateDir(opts: DecideAndWriteOpts): string { * instead of a wall of per-file warnings. */ export function hasHashManifest(genStateDir: string): boolean { if (batchFor(genStateDir)?.dirty === true) return true; - return existsSync(join(genStateDir, HASHES_FILE)); + return manifestExists(genStateDir); } /** Normalize the legacy `MergeStrategy` string shorthand into an options object. */ diff --git a/server/typescript/packages/codegen-ts/src/reconcile-orphans.ts b/server/typescript/packages/codegen-ts/src/reconcile-orphans.ts index 0af5ff1953..f7bd6a616d 100644 --- a/server/typescript/packages/codegen-ts/src/reconcile-orphans.ts +++ b/server/typescript/packages/codegen-ts/src/reconcile-orphans.ts @@ -18,7 +18,7 @@ /** * A generator's opt-in to orphan reconciliation, and the namespace it applies to. * - * Declaring this is the ONLY way in: `.gen-state/.hashes.json` records paths, not + * Declaring this is the ONLY way in: the manifest under `.gen-state/.hashes/` records paths, not * which generator produced each one, so the runner genuinely cannot work out who * owns what. Deriving ownership from the output directory instead would be worse * than useless — every generator in a single-target project writes to the same @@ -67,7 +67,7 @@ export interface OrphanDecision { export interface ReconcileOrphansArgs { /** Relative paths this generator emitted on some previous run — in practice the - * keys of `.gen-state/.hashes.json`. */ + * keys of the manifest under `.gen-state/.hashes/`. */ readonly previouslyGenerated: readonly string[]; /** Relative paths emitted on THIS run. */ readonly emitted: readonly string[]; diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index 6868fbbdeb..bbdbf5cb1a 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -384,7 +384,7 @@ export async function runGen(opts: RunGenOpts): Promise { ? join(projectRoot, ".metaobjects", ".gen-state") : join(tmpdir(), `meta-gen-state-${process.pid}`)); // A file written OUTSIDE the project has no place in the project's gen-state: its - // manifest key would be `../..`-relative, committed into `.hashes.json`, and its snapshot + // manifest key would be `../..`-relative, committed into the hash manifest, and its snapshot // body — stored at `/` — would walk out of `.gen-state/` and land a second // copy of the output in the project tree. Such files get the process-isolated state a run // with no project gets: written, never recorded. @@ -422,14 +422,14 @@ export async function runGen(opts: RunGenOpts): Promise { if (untrackedCount === 0) return; warnings.push( `${untrackedCount} generated file(s) were written outside the project root and are not ` + - `recorded in .metaobjects/.gen-state/.hashes.json, so hand-edit protection does not apply ` + + `recorded in .metaobjects/.gen-state/.hashes/, so hand-edit protection does not apply ` + `to them: a later run overwrites them without checking for edits.`, ); }; // #232 — make an unexplained regen diff explained: if the codegen engine changed // since the last gen, note it (generated output may legitimately differ). Purely - // informational — the version file is separate from `.hashes.json` and never + // informational — the version file is separate from the hash manifest and never // affects the merge. Only fires when a prior stamp exists AND differs. // Captured BEFORE any write, because the first write creates the manifest — read // it afterwards and every project looks migrated. @@ -1118,8 +1118,8 @@ export async function runGen(opts: RunGenOpts): Promise { `project created before the manifest was committed. ` + `ONE-TIME FIX: re-run with --baseline=adopt — it records the files you have as ` + `the merge base and writes NOTHING — then commit ` + - `'.metaobjects/.gen-state/.hashes.json' (un-ignore it in .metaobjects/.gitignore ` + - `with '.gen-state/*' + '!.gen-state/.hashes.json') and run 'meta gen' again, where ` + + `'.metaobjects/.gen-state/.hashes/' (un-ignore it in .metaobjects/.gitignore ` + + `with '.gen-state/*' + '!.gen-state/.hashes/') and run 'meta gen' again, where ` + `the regeneration arrives as its own reviewable diff. Adopting DECLARES these files ` + `to be generated output, so an edit already inside one of them is part of the ` + `baseline and that regeneration will replace it — commit before you run it. ` + @@ -1167,7 +1167,7 @@ export async function runGen(opts: RunGenOpts): Promise { // `--baseline=adopt` — the counterpart of the aggregate above, and aggregated for the // same reason: every adopted file has one cause and one next step. Reported even though // nothing failed, because a run that writes nothing and exits 0 is otherwise - // indistinguishable from a no-op, and the file it DID produce (`.hashes.json`) is the + // indistinguishable from a no-op, and the file it DID produce (the hash manifest) is the // one the adopter now has to commit. const reportAdoptions = (): void => { const adopted = writes.filter((w) => w.status === "adopted"); @@ -1176,8 +1176,8 @@ export async function runGen(opts: RunGenOpts): Promise { const more = adopted.length > MAX_NAMED ? `, and ${adopted.length - MAX_NAMED} more` : ""; warnings.push( `Recorded ${adopted.length} existing file(s) as the codegen baseline and wrote ` + - `nothing. NEXT: commit '.metaobjects/.gen-state/.hashes.json' (un-ignore it in ` + - `.metaobjects/.gitignore with '.gen-state/*' + '!.gen-state/.hashes.json'), then run ` + + `nothing. NEXT: commit '.metaobjects/.gen-state/.hashes/' (un-ignore it in ` + + `.metaobjects/.gitignore with '.gen-state/*' + '!.gen-state/.hashes/'), then run ` + `'meta gen' — these files regenerate normally from here, as their own reviewable ` + `diff. Adopting DECLARED them to be generated output: an edit already inside one is ` + `part of the baseline and that regeneration will replace it, so check the diff ` + @@ -1398,7 +1398,7 @@ export async function runGen(opts: RunGenOpts): Promise { // first would be unrecoverable if a later write threw. Ordering cannot change // the decision — a path this run emitted is never an orphan either way. sweep(false); - }); + }, root.objects().map((o) => ({ name: o.name, package: effectivePackage(o) ?? "" }))); // #232 — stamp the engine version that produced this snapshot, so the NEXT gen can // detect an engine change. Written after a successful run only, and only by a run that diff --git a/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts b/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts index 8c29f20f87..bee24e8e1a 100644 --- a/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts +++ b/server/typescript/packages/codegen-ts/test/adopt-baseline.test.ts @@ -1,6 +1,6 @@ // `--baseline=adopt` — the first step a pre-manifest project can actually perform. // -// The no-manifest refusal used to LEAD with "commit .metaobjects/.gen-state/.hashes.json", +// The no-manifest refusal used to LEAD with "commit .metaobjects/.gen-state/.hashes/", // which the population it names cannot do: nothing writes a manifest until a `gen` succeeds, // and `gen` refuses until one exists. The only escape was `--baseline=fresh`, framed — // correctly — as the lossy one, so an adopter whose committed output was already a @@ -12,6 +12,7 @@ // next regen replaces it. That is pinned below, because the message says it and a message // nothing tests goes stale. +import { manifestEntries, manifestExists } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync, statSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -32,7 +33,6 @@ afterEach(() => { rmSync(projectRoot, { recursive: true, force: true }); }); const genStateDir = (): string => join(projectRoot, ".metaobjects", ".gen-state"); const outDir = (): string => join(projectRoot, "generated"); -const hashesFile = (): string => join(genStateDir(), ".hashes.json"); async function gen(opts: { baseline?: BaselineMode; dryRun?: boolean } = {}) { const { root } = await new MetaDataLoader().load([new FileSource(FIXTURE)]); @@ -91,8 +91,8 @@ describe("--baseline=adopt", () => { // Not one byte written: this is the whole promise of the mode. expect(filesOnDisk()).toEqual(before); // …and the manifest the adopter is told to commit now exists, naming those files. - expect(existsSync(hashesFile())).toBe(true); - const hashes = JSON.parse(readFileSync(hashesFile(), "utf-8")) as Record; + expect(manifestExists(genStateDir())).toBe(true); + const hashes = manifestEntries(genStateDir()); expect(Object.keys(hashes).length).toBeGreaterThanOrEqual(stale.length); }); @@ -105,7 +105,7 @@ describe("--baseline=adopt", () => { const notice = result.warnings.filter((w) => w.includes("baseline")); expect(notice.length).toBe(1); - expect(notice[0]).toContain(".hashes.json"); + expect(notice[0]).toContain(".hashes/"); // The honesty clause: adopt declares your files to BE generated output. expect(notice[0]).toMatch(/replace|regenerat/i); }); @@ -165,8 +165,9 @@ describe("--baseline=adopt", () => { const walk = (dir: string): void => { for (const e of readdirSync(dir)) { const full = join(dir, e); - if (statSync(full).isDirectory()) { walk(full); rmSync(full, { recursive: true, force: true }); } - else if (e !== ".hashes.json" && e !== ".engine.json") rmSync(full, { force: true }); + if (e === ".hashes") continue; // the manifest directory is what a clone keeps + if (statSync(full).isDirectory()) { walk(full); rmSync(full, { recursive: true, force: true }); } + else if (e !== ".engine.json") rmSync(full, { force: true }); } }; walk(genStateDir()); @@ -185,7 +186,7 @@ describe("--baseline=adopt", () => { const result = await gen({ baseline: "adopt", dryRun: true }); expect(result.files.some((f) => f.status === "adopted")).toBe(true); - expect(existsSync(hashesFile())).toBe(false); + expect(manifestExists(genStateDir())).toBe(false); }); }); diff --git a/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts b/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts index a28c5cfc31..5d37d3de0e 100644 --- a/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts +++ b/server/typescript/packages/codegen-ts/test/baseline-fresh-stale-snapshot.test.ts @@ -6,6 +6,7 @@ // it used to three-way merge against such a body instead, keeping the old content as a "hand // edit" that `verify --codegen` then reported. +import { removeManifest, seedLegacyManifest } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync, statSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -26,7 +27,6 @@ afterEach(() => { rmSync(projectRoot, { recursive: true, force: true }); }); const genStateDir = (): string => join(projectRoot, ".metaobjects", ".gen-state"); const outDir = (): string => join(projectRoot, "generated"); -const hashesFile = (): string => join(genStateDir(), ".hashes.json"); const STALE = "STALE LINE WRITTEN BY AN OLDER ENGINE\n"; @@ -50,7 +50,8 @@ async function gen(baseline?: BaselineMode) { function staleAndUnrecorded(): string[] { const names = readdirSync(outDir()).filter((e) => statSync(join(outDir(), e)).isFile()); for (const n of names) writeFileSync(join(outDir(), n), readFileSync(join(outDir(), n), "utf-8") + STALE); - writeFileSync(hashesFile(), "{}\n"); + removeManifest(genStateDir()); + seedLegacyManifest(genStateDir(), {}); return names; } diff --git a/server/typescript/packages/codegen-ts/test/dry-run-reports-refusals.test.ts b/server/typescript/packages/codegen-ts/test/dry-run-reports-refusals.test.ts index 938cd34410..00c945461d 100644 --- a/server/typescript/packages/codegen-ts/test/dry-run-reports-refusals.test.ts +++ b/server/typescript/packages/codegen-ts/test/dry-run-reports-refusals.test.ts @@ -11,6 +11,7 @@ // comparison, which a preview can do exactly. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { manifestExists } from "./support/manifest.js"; import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -83,7 +84,7 @@ describe("previewWriteStatus agrees with decideAndWrite", () => { writeFileSync(path, "// hand-written\n"); previewWriteStatus(path, "fresh\n", opts()); expect(readFileSync(path, "utf-8")).toBe("// hand-written\n"); - expect(existsSync(join(state, ".hashes.json"))).toBe(false); + expect(manifestExists(state)).toBe(false); }); test("with the snapshot body present it stays coarse, and says so honestly", () => { diff --git a/server/typescript/packages/codegen-ts/test/engine-version-stamp.test.ts b/server/typescript/packages/codegen-ts/test/engine-version-stamp.test.ts index 1c451a4615..8c2410cda2 100644 --- a/server/typescript/packages/codegen-ts/test/engine-version-stamp.test.ts +++ b/server/typescript/packages/codegen-ts/test/engine-version-stamp.test.ts @@ -1,6 +1,7 @@ // #232 — the gen-state records the codegen engine version, and `meta gen` notes an // engine change since the last run (so an unexplained regen diff is explained). The -// stamp is a separate file from `.hashes.json` and never affects the three-way merge. +// stamp is a separate file from the `.hashes/` manifest and never affects the three-way merge. +import { manifestExists } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -16,14 +17,14 @@ describe("#232 — gen-state engine-version stamp", () => { expect(loadEngineVersion(state)).toBeUndefined(); }); - test("save then load round-trips the version, in a separate .engine.json (not .hashes.json)", () => { + test("save then load round-trips the version, in a separate .engine.json (not the manifest)", () => { saveEngineVersion(state, "0.20.9"); expect(loadEngineVersion(state)).toBe("0.20.9"); expect(existsSync(join(state, ".engine.json"))).toBe(true); // Must NOT pollute the hashes file (the merge input). const engine = JSON.parse(readFileSync(join(state, ".engine.json"), "utf-8")); expect(engine).toEqual({ codegenVersion: "0.20.9" }); - expect(existsSync(join(state, ".hashes.json"))).toBe(false); + expect(manifestExists(state)).toBe(false); }); test("malformed .engine.json → undefined, never throws (informational only)", () => { diff --git a/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts b/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts index 7e6afadacd..e7d834ed3c 100644 --- a/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts +++ b/server/typescript/packages/codegen-ts/test/fresh-clone-regen.test.ts @@ -1,7 +1,7 @@ // The scenario this whole mechanism exists for, driven end to end through runGen. // // A teammate clones the repo. The generated output is committed; the `.gen-state` -// snapshot BODIES are gitignored so they are absent; `.gen-state/.hashes.json` is +// snapshot BODIES are gitignored so they are absent; `.gen-state/.hashes/` is // committed so it is present. One generated file carries a hand edit — the // `leadingWildcard: true` change the docs explicitly tell adopters to make inside a // generated allowlist. They run `meta gen`. @@ -11,6 +11,7 @@ // decision that runGen never reaches is worth nothing — which is exactly how the // orphan mechanism shipped inert earlier in this branch. +import { manifestExists, removeManifest } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, readFileSync, writeFileSync, readdirSync, existsSync, statSync, @@ -47,18 +48,19 @@ async function gen(opts: { baselineFresh?: boolean } = {}) { }); } -/** Delete every snapshot body but keep `.hashes.json` — what a clone actually has, +/** Delete every snapshot body but keep `.hashes/` — what a clone actually has, * given the gitignore `meta init` now scaffolds. */ function simulateFreshClone(): void { const walk = (dir: string): void => { for (const entry of readdirSync(dir)) { const full = join(dir, entry); + if (entry === ".hashes") continue; // the manifest directory is what a clone keeps if (statSync(full).isDirectory()) { walk(full); rmSync(full, { recursive: true, force: true }); } - else if (entry !== ".hashes.json" && entry !== ".engine.json") rmSync(full, { force: true }); + else if (entry !== ".engine.json") rmSync(full, { force: true }); } }; walk(genStateDir()); - expect(existsSync(join(genStateDir(), ".hashes.json"))).toBe(true); + expect(manifestExists(genStateDir())).toBe(true); } describe("regen on a fresh clone: hashes committed, bodies absent", () => { @@ -127,7 +129,7 @@ describe("regen on a fresh clone: hashes committed, bodies absent", () => { await gen(); const target = join(projectRoot, "generated", "Post.ts"); simulateFreshClone(); - rmSync(join(genStateDir(), ".hashes.json"), { force: true }); + removeManifest(genStateDir()); writeFileSync(target, "// my edit\n"); const result = await gen(); diff --git a/server/typescript/packages/codegen-ts/test/gen-state-readers.test.ts b/server/typescript/packages/codegen-ts/test/gen-state-readers.test.ts index d67d77cf49..8a8459e70e 100644 --- a/server/typescript/packages/codegen-ts/test/gen-state-readers.test.ts +++ b/server/typescript/packages/codegen-ts/test/gen-state-readers.test.ts @@ -1,11 +1,12 @@ // FR-038 §8 — the gen-state readers orphan reconciliation is built on. // -// `.gen-state/.hashes.json` is the only record of what a previous run wrote, so +// the `.gen-state/.hashes/` manifest is the only record of what a previous run wrote, so // its key set IS the "previously generated" universe. These tests pin the three // properties the reconciliation decision depends on: the key list is complete, // the snapshot read REFUSES a tampered snapshot (returns undefined rather than // stale text), and forgetting a path removes both halves of the record. +import { manifestEntries, manifestFiles } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -89,9 +90,7 @@ describe("forgetGeneratedPaths", () => { expect(readGeneratedSnapshot(genStateDir, "out/Keep.ts")).toBe( "export const b = 2;\n", ); - const hashes = JSON.parse( - readFileSync(join(genStateDir, ".hashes.json"), "utf-8"), - ) as Record; + const hashes = manifestEntries(genStateDir); expect(Object.keys(hashes)).toEqual(["out/Keep.ts"]); }); @@ -117,8 +116,8 @@ describe("forgetGeneratedPaths", () => { test("an empty set leaves the manifest untouched", () => { generate("out/Keep.ts", "export const b = 2;\n"); - const before = readFileSync(join(genStateDir, ".hashes.json"), "utf-8"); + const before = manifestFiles(genStateDir); forgetGeneratedPaths(genStateDir, []); - expect(readFileSync(join(genStateDir, ".hashes.json"), "utf-8")).toBe(before); + expect(manifestFiles(genStateDir)).toEqual(before); }); }); diff --git a/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts b/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts index e1c027716d..38aa806231 100644 --- a/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts +++ b/server/typescript/packages/codegen-ts/test/generated-provenance.test.ts @@ -1,6 +1,7 @@ // Node provenance in the generated-file manifest: `perEntity` stamps each file with the node -// it rendered, and the runner records that on the file's `.hashes.json` entry, so a reader +// it rendered, and the runner records that on the file's `.hashes/` entry, so a reader // (the explorer builder) can say which files a node produced without matching names. +import { LEGACY_HASHES_FILE, manifestEntries, manifestExists, manifestFiles, seedLegacyManifest } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -19,7 +20,7 @@ beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), "codegen-provenance-")); }); afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); const manifest = (dir: string): Record => - JSON.parse(readFileSync(join(dir, ".metaobjects", ".gen-state", ".hashes.json"), "utf8")); + manifestEntries(join(dir, ".metaobjects", ".gen-state")); describe("perEntity stamps the source node", () => { test("each file carries its entity's resolution key unless the generator set one", async () => { @@ -32,7 +33,7 @@ describe("perEntity stamps the source node", () => { }); }); -describe("runGen records provenance in .hashes.json", () => { +describe("runGen records provenance in the .hashes/ manifest", () => { test("a per-entity file gets { hash, generatedBy, sourceNode }; a whole-model file stays plain", async () => { const { root } = await new MetaDataLoader().load([new FileSource(FIXTURE)]); const entity: Generator = { name: "alpha", generate: perEntity((e) => ({ path: `${e.name}.alpha.ts`, content: "// a\n" })) }; @@ -55,11 +56,11 @@ describe("runGen records provenance in .hashes.json", () => { describe("recordGeneratedProvenance", () => { function seed(entries: Record): string { const dir = join(tmp, ".gen-state"); - mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, ".hashes.json"), JSON.stringify(entries)); + // A legacy single-file manifest on purpose: the write below migrates it. + seedLegacyManifest(dir, entries); return dir; } - const read = (dir: string): Record => JSON.parse(readFileSync(join(dir, ".hashes.json"), "utf8")); + const read = (dir: string): Record => manifestEntries(dir); test("keeps the JVM owner fields beside the provenance", () => { const dir = seed({ "a.kt": { hash: "h1", generator: "kotlin-entity", outputDir: "src" } }); @@ -75,14 +76,15 @@ describe("recordGeneratedProvenance", () => { test("never records a path the manifest has no hash for, and writes nothing when nothing changes", () => { const dir = seed({ "a.ts": "h3" }); - const before = readFileSync(join(dir, ".hashes.json"), "utf8"); + const before = readFileSync(join(dir, LEGACY_HASHES_FILE), "utf8"); recordGeneratedProvenance(dir, new Map([["b.ts", { generatedBy: "g", sourceNode: "x::B" }], ["a.ts", { generatedBy: "g" }]])); - expect(readFileSync(join(dir, ".hashes.json"), "utf8")).toBe(before); + expect(readFileSync(join(dir, LEGACY_HASHES_FILE), "utf8")).toBe(before); + expect(manifestFiles(dir)).toEqual({}); // not migrated either }); test("no manifest, no file", () => { const dir = join(tmp, "none"); recordGeneratedProvenance(dir, new Map([["a.ts", { generatedBy: "g", sourceNode: "x::A" }]])); - expect(() => readFileSync(join(dir, ".hashes.json"))).toThrow(); + expect(manifestExists(dir)).toBe(false); }); }); diff --git a/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts b/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts new file mode 100644 index 0000000000..76122ee5bc --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts @@ -0,0 +1,168 @@ +// ADR-0064 Amendment 1: the hash manifest is one file per model package. The vectors are the +// shared ones every port runs (`fixtures/codegen-skip-conformance/manifests.json`). +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { + buildPlacementIndex, + manifestFileName, + placeEntry, + readManifestState, +} from "../src/hash-manifest-store.js"; +import { forgetGeneratedPaths, listGeneratedPaths, withManifestBatch, writeManifestFiles } from "../src/overwrite-policy.js"; + +interface Vectors { + objects: { name: string; package: string }[]; + fileNames: { package: string | null; file: string }[]; + placement: { path: string; package: string | null; entry?: unknown }[]; + legacySplit: { + legacy: Record; + files: Record>; + goldenFile: string; + goldenText: string; + gitignoreBefore: string; + gitignoreAfter: string; + }; +} + +const VECTORS = JSON.parse( + readFileSync(resolve(import.meta.dir, "../../../../../fixtures/codegen-skip-conformance/manifests.json"), "utf-8"), +) as Vectors; +const INDEX = buildPlacementIndex(VECTORS.objects); + +let tmp: string; +let state: string; +beforeEach(() => { + tmp = mkdtempSync(join(process.env.DEV_SCRATCH ?? "/tmp", "hash-manifest-store-")); + state = join(tmp, ".metaobjects", ".gen-state"); + mkdirSync(state, { recursive: true }); +}); +afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); + +const dirOf = (): string => join(state, ".hashes"); +const files = (): string[] => (existsSync(dirOf()) ? readdirSync(dirOf()).sort() : []); +const read = (name: string): unknown => JSON.parse(readFileSync(join(dirOf(), name), "utf-8")); +const save = (entries: Record, index = INDEX): void => { + writeManifestFiles(state, entries, readManifestState(state), index); +}; + +describe("shared vectors", () => { + test("file names", () => { + for (const v of VECTORS.fileNames) expect(manifestFileName(v.package)).toBe(v.file); + }); + + test("placement", () => { + for (const v of VECTORS.placement) { + const placed = placeEntry(v.path, v.entry ?? "h", INDEX); + expect({ path: v.path, package: placed ?? null }).toEqual({ path: v.path, package: v.package }); + } + }); + + test("a legacy manifest splits into the package files, byte for byte, and is removed", () => { + const { legacy, files: expected, goldenFile, goldenText, gitignoreBefore, gitignoreAfter } = VECTORS.legacySplit; + writeFileSync(join(state, ".hashes.json"), JSON.stringify(legacy, null, 2) + "\n"); + writeFileSync(join(tmp, ".metaobjects", ".gitignore"), gitignoreBefore); + withManifestBatch(state, () => {}, VECTORS.objects); + expect(existsSync(join(state, ".hashes.json"))).toBe(false); + expect(files()).toEqual(Object.keys(expected).sort()); + for (const [name, entries] of Object.entries(expected)) expect(read(name)).toEqual(entries); + expect(readFileSync(join(dirOf(), goldenFile), "utf-8")).toBe(goldenText); + expect(readFileSync(join(tmp, ".metaobjects", ".gitignore"), "utf-8")).toBe(gitignoreAfter); + + // A second identical run changes no file. + const before = files().map((f) => statSync(join(dirOf(), f)).mtimeMs); + withManifestBatch(state, () => {}, VECTORS.objects); + expect(files().map((f) => statSync(join(dirOf(), f)).mtimeMs)).toEqual(before); + }); + + test("the gitignore rewrite replaces the legacy negation, or adds one after .gen-state/*", () => { + const ignore = join(tmp, ".metaobjects", ".gitignore"); + const cases: [string, string][] = [ + [".gen-state/*\n!.gen-state/.hashes.json\n", ".gen-state/*\n!.gen-state/.hashes/\n"], + ["a/\n.gen-state/*\n", "a/\n.gen-state/*\n!.gen-state/.hashes/\n"], + [".gen-state/*\n!.gen-state/.hashes/\n!.gen-state/.hashes.json\n", ".gen-state/*\n!.gen-state/.hashes/\n"], + [".gen-state/*\n!.gen-state/.hashes/\n", ".gen-state/*\n!.gen-state/.hashes/\n"], + ["node_modules/\n!.gen-state/.hashes.json\n", "node_modules/\n!.gen-state/.hashes.json\n"], + ]; + for (const [before, after] of cases) { + writeFileSync(ignore, before); + writeFileSync(join(state, ".hashes.json"), JSON.stringify({ "a.ts": "h" })); + withManifestBatch(state, () => {}); + expect(readFileSync(ignore, "utf-8")).toBe(after); + } + }); + + test("a save that does not migrate leaves .gitignore alone", () => { + const ignore = join(tmp, ".metaobjects", ".gitignore"); + writeFileSync(ignore, ".gen-state/*\n!.gen-state/.hashes.json\n"); + save({ "gen/Order.ts": "o1" }); + expect(readFileSync(ignore, "utf-8")).toBe(".gen-state/*\n!.gen-state/.hashes.json\n"); + }); +}); + +describe("different packages, different files", () => { + const entries = (): Record => ({ + "gen/Order.ts": "o1", + "gen/Customer.ts": "c1", + "gen/index.ts": "i1", + }); + + test("a change in one package rewrites that package's file and no other", async () => { + save(entries()); + expect(files()).toEqual([".root.json", "acme.crm.json", "acme.shop.json"]); + const mtime = (f: string): number => statSync(join(dirOf(), f)).mtimeMs; + const before = Object.fromEntries(files().map((f) => [f, mtime(f)])); + await new Promise((r) => setTimeout(r, 20)); + save({ ...entries(), "gen/Order.ts": "o2" }); + expect(mtime("acme.crm.json")).toBe(before["acme.crm.json"]!); + expect(mtime(".root.json")).toBe(before[".root.json"]!); + expect(mtime("acme.shop.json")).toBeGreaterThan(before["acme.shop.json"]!); + expect(read("acme.shop.json")).toEqual({ "gen/Order.ts": "o2" }); + }); + + test("a save that changes nothing writes nothing", async () => { + save(entries()); + const before = files().map((f) => statSync(join(dirOf(), f)).mtimeMs); + await new Promise((r) => setTimeout(r, 20)); + save(entries()); + expect(files().map((f) => statSync(join(dirOf(), f)).mtimeMs)).toEqual(before); + }); + + test("a package that loses its last entry loses its file", () => { + save(entries()); + const { "gen/Customer.ts": _gone, ...rest } = entries(); + save(rest); + expect(files()).toEqual([".root.json", "acme.shop.json"]); + }); + + test("an empty manifest keeps .root.json as {} so it is not mistaken for no manifest", () => { + save({}); + expect(files()).toEqual([".root.json"]); + expect(readFileSync(join(dirOf(), ".root.json"), "utf-8")).toBe("{}\n"); + }); + + test("an entry with no opinion stays in the file it was read from", () => { + save(entries()); + // No model: `Order.ts` has no sourceNode, so the stem rule cannot run and it must stay. + writeManifestFiles(state, { ...entries(), "gen/Order.ts": "o3" }, readManifestState(state), undefined); + expect(read("acme.shop.json")).toEqual({ "gen/Order.ts": "o3" }); + expect(read(".root.json")).toEqual({ "gen/index.ts": "i1" }); + }); + + test("readers see the union, and forgetting a path removes it from its own file", () => { + save(entries()); + expect(listGeneratedPaths(state).sort()).toEqual(["gen/Customer.ts", "gen/Order.ts", "gen/index.ts"]); + forgetGeneratedPaths(state, ["gen/Customer.ts"]); + expect(listGeneratedPaths(state).sort()).toEqual(["gen/Order.ts", "gen/index.ts"]); + expect(files()).toEqual([".root.json", "acme.shop.json"]); + }); +}); + +describe("a read does not migrate", () => { + test("reading a legacy manifest leaves the legacy file and creates no package file", () => { + writeFileSync(join(state, ".hashes.json"), JSON.stringify({ "a.ts": "h" })); + expect(listGeneratedPaths(state)).toEqual(["a.ts"]); + expect(existsSync(join(state, ".hashes.json"))).toBe(true); + expect(existsSync(dirOf())).toBe(false); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/layout-ratchet/allowlist.json b/server/typescript/packages/codegen-ts/test/layout-ratchet/allowlist.json index d4db4dd03a..79dc71217a 100644 --- a/server/typescript/packages/codegen-ts/test/layout-ratchet/allowlist.json +++ b/server/typescript/packages/codegen-ts/test/layout-ratchet/allowlist.json @@ -80,7 +80,7 @@ "exempt": { "codegen-ts/src/generators/contract-schema-file.ts": "Writes the contract-schema generator's JSON Schema documents as JSON.stringify(value, null, 2) plus a final newline. The layout is the JSON serializer's, so there is no code to lay out and no writer to move to.", "codegen-ts/src/generators/openapi-file.ts": "Writes the openapi generator's OpenAPI document as JSON.stringify(value, null, 2) plus a final newline. The layout is the JSON serializer's, so there is no code to lay out and no writer to move to.", - "codegen-ts/src/overwrite-policy.ts": "Writes the codegen tool-state files (.metaobjects/.gen-state/.hashes.json and the engine stamp) as JSON.stringify output plus a final newline. That is a data file the runner owns, not generated code, so it has no writer to move to.", + "codegen-ts/src/overwrite-policy.ts": "Writes the codegen tool-state files (the per-package manifests under .metaobjects/.gen-state/.hashes/ and the engine stamp) as JSON.stringify output plus a final newline. That is a data file the runner owns, not generated code, so it has no writer to move to.", "codegen-ts/src/poet.ts": "The vendored ts-poet printer, the engine the writer replaces: its import emitter prints the import lines of a Code file. It is retired when the last generator moves to the writer, not converted to it.", "codegen-ts/src/reference/contract-schema.ts": "The reference (ejectable) copy of the contract-schema generator; writes JSON Schema documents as JSON.stringify(value, null, 2) plus a final newline. The layout is the JSON serializer's, so there is no code to lay out and no writer to move to.", "codegen-ts/src/reference/openapi.ts": "The reference (ejectable) copy of the openapi generator; writes the OpenAPI document as JSON.stringify(value, null, 2) plus a final newline. The layout is the JSON serializer's, so there is no code to lay out and no writer to move to." diff --git a/server/typescript/packages/codegen-ts/test/manifest-branch-merge.test.ts b/server/typescript/packages/codegen-ts/test/manifest-branch-merge.test.ts new file mode 100644 index 0000000000..d42e94ce02 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/manifest-branch-merge.test.ts @@ -0,0 +1,109 @@ +// The point of ADR-0064 Amendment 1, proven with real git: two branches that change generated +// files in DIFFERENT packages produce manifests that merge with nothing to resolve. With the +// single `.hashes.json` the same two branches conflict on that one file. +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { join } from "node:path"; +import { MetaDataLoader } from "@metaobjectsdev/metadata"; +import { FileSource } from "@metaobjectsdev/metadata/core"; +import { runGen } from "../src/runner.js"; +import { defineConfig } from "../src/metaobjects-config.js"; +import { perEntity, perModel, type Generator } from "../src/generator.js"; + +let tmp: string; +beforeEach(() => { tmp = mkdtempSync(join(process.env.DEV_SCRATCH ?? "/tmp", "manifest-merge-")); }); +afterEach(() => { rmSync(tmp, { recursive: true, force: true }); }); + +const entity = (pkg: string, name: string): string => JSON.stringify({ + "metadata.root": { package: pkg, children: [{ "object.entity": { name, children: [ + { "source.rdb": { "@table": name.toLowerCase() } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "primary", "@fields": ["id"], "@generation": "increment" } }, + ] } }] }, +}); + +const git = (...args: string[]): { status: number; out: string } => { + const r = spawnSync("git", ["-C", tmp, ...args], { encoding: "utf-8" }); + return { status: r.status ?? 1, out: `${r.stdout}${r.stderr}` }; +}; + +/** Run `meta gen` for the project, with each entity's output taken from `bodies`. */ +async function gen(bodies: Record): Promise { + mkdirSync(join(tmp, "metaobjects"), { recursive: true }); + writeFileSync(join(tmp, "metaobjects", "shop.json"), entity("acme::shop", "Order")); + writeFileSync(join(tmp, "metaobjects", "crm.json"), entity("acme::crm", "Customer")); + const loader = new MetaDataLoader(); + const { root } = await loader.load([ + new FileSource(join(tmp, "metaobjects", "shop.json")), + new FileSource(join(tmp, "metaobjects", "crm.json")), + ]); + const own: Generator = { name: "own", generate: perEntity((e) => ({ path: `${e.name}.ts`, content: bodies[e.name] ?? "// base\n" })) }; + const barrel: Generator = { name: "barrel", generate: perModel(() => ({ path: "index.ts", content: "// index\n" })) }; + await runGen({ + config: defineConfig({ outDir: join(tmp, "gen"), extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [own, barrel] }), + metadata: root, + projectRoot: tmp, + }); +} + +describe("two branches, two packages", () => { + test("the manifests merge with no conflict", async () => { + git("init", "-q", "-b", "main"); + git("config", "user.email", "t@example.com"); + git("config", "user.name", "t"); + git("config", "commit.gpgsign", "false"); + await gen({}); + const manifestDir = join(tmp, ".metaobjects", ".gen-state", ".hashes"); + expect(existsSync(join(manifestDir, "acme.shop.json"))).toBe(true); + expect(existsSync(join(manifestDir, "acme.crm.json"))).toBe(true); + // Nothing else under .gen-state is committed in a real project; mimic its .gitignore. + writeFileSync(join(tmp, ".metaobjects", ".gitignore"), ".gen-state/*\n!.gen-state/.hashes/\n"); + git("add", "-A"); + expect(git("commit", "-q", "-m", "base").status).toBe(0); + expect(git("ls-files", ".metaobjects/.gen-state").out).toContain(".hashes/acme.shop.json"); + + git("checkout", "-q", "-b", "orders"); + await gen({ Order: "// orders changed\n" }); + git("add", "-A"); + expect(git("commit", "-q", "-m", "orders").status).toBe(0); + + git("checkout", "-q", "main"); + git("checkout", "-q", "-b", "customers"); + await gen({ Customer: "// customers changed\n" }); + git("add", "-A"); + expect(git("commit", "-q", "-m", "customers").status).toBe(0); + + const merged = git("merge", "--no-edit", "orders"); + expect(merged.out).not.toContain("CONFLICT"); + expect(merged.status).toBe(0); + + // The merged manifests record both changes, and match what a fresh run produces. + const shop = JSON.parse(readFileSync(join(manifestDir, "acme.shop.json"), "utf-8")) as Record; + const crm = JSON.parse(readFileSync(join(manifestDir, "acme.crm.json"), "utf-8")) as Record; + expect(Object.keys(shop)).toEqual(["gen/Order.ts"]); + expect(Object.keys(crm)).toEqual(["gen/Customer.ts"]); + const rootBefore = readFileSync(join(manifestDir, ".root.json"), "utf-8"); + await gen({ Order: "// orders changed\n", Customer: "// customers changed\n" }); + const rerun = git("status", "--porcelain"); + expect(rerun.out.trim()).toBe(""); + expect(readFileSync(join(manifestDir, ".root.json"), "utf-8")).toBe(rootBefore); + }, 60_000); + + test("the same two branches conflict on the single legacy manifest", () => { + git("init", "-q", "-b", "main"); + git("config", "user.email", "t@example.com"); + git("config", "user.name", "t"); + git("config", "commit.gpgsign", "false"); + const file = join(tmp, "hashes.json"); + const write = (o: string, c: string): void => writeFileSync(file, JSON.stringify({ + "gen/Customer.ts": c, "gen/Order.ts": o, + }, null, 2) + "\n"); + write("o0", "c0"); + git("add", "-A"); git("commit", "-q", "-m", "base"); + git("checkout", "-q", "-b", "a"); write("o1", "c0"); git("commit", "-qam", "a"); + git("checkout", "-q", "main"); git("checkout", "-q", "-b", "b"); write("o0", "c1"); git("commit", "-qam", "b"); + // Adjacent lines of one file: git cannot tell they are independent. + expect(git("merge", "--no-edit", "a").out).toContain("CONFLICT"); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/manifest-write-once.test.ts b/server/typescript/packages/codegen-ts/test/manifest-write-once.test.ts index 6838969626..1fd5f12e9f 100644 --- a/server/typescript/packages/codegen-ts/test/manifest-write-once.test.ts +++ b/server/typescript/packages/codegen-ts/test/manifest-write-once.test.ts @@ -1,4 +1,4 @@ -// `.gen-state/.hashes.json` is written ONCE per `meta gen`, however many files the run +// The `.gen-state/.hashes/` manifest files are written ONCE per `meta gen`, however many files the run // writes. It used to be rewritten per written file — quadratic bookkeeping that was most // of a large project's run time, for the same bytes one write produces. import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test"; @@ -13,15 +13,16 @@ import { decideAndWrite, withManifestBatch } from "../src/overwrite-policy.js"; import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import { barrel } from "../src/generators/barrel.js"; +import { isManifestPath, manifestEntries, manifestFiles, removeManifest, seedLegacyManifest } from "./support/manifest.js"; const FIXTURE = resolve(import.meta.dir, "fixtures", "two-entities-fk.json"); -const MANIFEST = ".hashes.json"; let project: string; beforeEach(() => { project = mkdtempSync(join(tmpdir(), "codegen-manifest-once-")); }); afterEach(() => { rmSync(project, { recursive: true, force: true }); }); -async function gen(): Promise { +/** Manifest-file writes during one run: path -> times written. */ +async function gen(): Promise> { const { root, errors } = await new MetaDataLoader().load([new FileSource(FIXTURE)]); expect(errors).toEqual([]); const spy = spyOn(fs, "writeFileSync"); @@ -35,18 +36,22 @@ async function gen(): Promise { projectRoot: project, }); expect(result.files.length).toBeGreaterThan(2); - return spy.mock.calls.filter(([path]) => String(path).endsWith(MANIFEST)).length; + const counts: Record = {}; + for (const [path] of spy.mock.calls) if (isManifestPath(path)) counts[String(path)] = (counts[String(path)] ?? 0) + 1; + return counts; } finally { spy.mockRestore(); } } -const manifestPath = (): string => join(project, ".metaobjects", ".gen-state", MANIFEST); +const genState = (): string => join(project, ".metaobjects", ".gen-state"); describe("the hash manifest is written once per run", () => { test("a first run that writes every file writes the manifest once, recording each", async () => { - expect(await gen()).toBe(1); - const recorded = Object.keys(JSON.parse(readFileSync(manifestPath(), "utf-8"))); + const writes = await gen(); + expect(Object.keys(writes).length).toBeGreaterThan(1); // one file per package + expect(Object.values(writes).every((n) => n === 1)).toBe(true); + const recorded = Object.keys(manifestEntries(genState())); expect(recorded).toContain("src/generated/Post.ts"); expect(recorded).toContain("src/generated/User.queries.ts"); expect(recorded).toContain("src/generated/index.ts"); @@ -56,21 +61,23 @@ describe("the hash manifest is written once per run", () => { await gen(); // Two files to write again whose records are gone: both are recorded, in one manifest // write. (A file rewritten under an unchanged record changes no entry, so it writes none.) - const entries = JSON.parse(readFileSync(manifestPath(), "utf-8")) as Record; + const entries = manifestEntries(genState()); delete entries["src/generated/Post.ts"]; delete entries["src/generated/User.ts"]; - writeFileSync(manifestPath(), JSON.stringify(entries)); + removeManifest(genState()); + seedLegacyManifest(genState(), entries); rmSync(join(project, "src/generated/Post.ts")); rmSync(join(project, "src/generated/User.ts")); - expect(await gen()).toBe(1); - expect(Object.keys(JSON.parse(readFileSync(manifestPath(), "utf-8")))).toContain("src/generated/Post.ts"); + const writes = await gen(); + expect(Object.values(writes).every((n) => n === 1)).toBe(true); + expect(Object.keys(manifestEntries(genState()))).toContain("src/generated/Post.ts"); }); test("a run that changes nothing leaves the manifest unwritten", async () => { await gen(); - const before = readFileSync(manifestPath(), "utf-8"); - expect(await gen()).toBe(0); - expect(readFileSync(manifestPath(), "utf-8")).toBe(before); + const before = manifestFiles(genState()); + expect(await gen()).toEqual({}); + expect(manifestFiles(genState())).toEqual(before); }); test("a run that throws keeps its own error when the manifest write fails too", () => { @@ -78,8 +85,8 @@ describe("the hash manifest is written once per run", () => { expect(() => withManifestBatch(genStateDir, () => { decideAndWrite(join(project, "a.ts"), "export {};\n", { genStateDir, outputRelPath: "a.ts" }); - // A directory where the manifest goes: the end-of-batch write now fails (EISDIR). - mkdirSync(join(genStateDir, MANIFEST), { recursive: true }); + // A file where the manifest directory goes: the end-of-batch write now fails. + writeFileSync(join(genStateDir, ".hashes"), "not a directory"); throw new Error("the generator's own failure"); }), ).toThrow("the generator's own failure"); diff --git a/server/typescript/packages/codegen-ts/test/no-manifest-upgrade-message.test.ts b/server/typescript/packages/codegen-ts/test/no-manifest-upgrade-message.test.ts index ac18e66834..16dd0afe1f 100644 --- a/server/typescript/packages/codegen-ts/test/no-manifest-upgrade-message.test.ts +++ b/server/typescript/packages/codegen-ts/test/no-manifest-upgrade-message.test.ts @@ -10,6 +10,7 @@ // exists but lacks a path ⇒ per-file naming, because there the file IS the // information. Self-extinguishing either way. +import { manifestExists } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readdirSync, statSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -57,8 +58,9 @@ function dropBodiesOnly(): void { const walk = (dir: string): void => { for (const e of readdirSync(dir)) { const full = join(dir, e); + if (e === ".hashes") continue; // the manifest directory is what a clone keeps if (statSync(full).isDirectory()) { walk(full); rmSync(full, { recursive: true, force: true }); } - else if (e !== ".hashes.json" && e !== ".engine.json") rmSync(full, { force: true }); + else if (e !== ".engine.json") rmSync(full, { force: true }); } }; walk(genStateDir()); @@ -94,7 +96,7 @@ describe("no manifest at all — the upgrade path", () => { const msg = result.warnings[0]!; expect(msg).toContain(`${refused.length} existing file(s)`); expect(msg).toContain("--baseline=fresh"); - expect(msg).toContain(".hashes.json"); + expect(msg).toContain(".hashes/"); // Names some files so it is actionable, without pasting all of them. expect(msg).toContain("Post.ts"); }); @@ -147,6 +149,6 @@ describe("a migrated project", () => { const result = await gen(); expect(result.files.some((f) => f.status === "refused")).toBe(false); expect(result.warnings.filter((w) => w.includes("Refused"))).toEqual([]); - expect(existsSync(join(genStateDir(), ".hashes.json"))).toBe(true); + expect(manifestExists(genStateDir())).toBe(true); }); }); diff --git a/server/typescript/packages/codegen-ts/test/orphan-sweep.test.ts b/server/typescript/packages/codegen-ts/test/orphan-sweep.test.ts index 13bab733fb..43def1de76 100644 --- a/server/typescript/packages/codegen-ts/test/orphan-sweep.test.ts +++ b/server/typescript/packages/codegen-ts/test/orphan-sweep.test.ts @@ -9,6 +9,7 @@ // hand, so the gen-state these tests reconcile is the gen-state `meta gen` // actually produces. +import { setManifestEntry } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, existsSync, writeFileSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -170,10 +171,7 @@ describe("sweepOrphans", () => { // The manifest is the trust root. An entry that disagrees with the file on // disk means the file is not what we wrote, whatever the reason. generate(STUB_A, "// stub a\n"); - const hashesPath = join(genStateDir, ".hashes.json"); - const hashes = JSON.parse(readFileSync(hashesPath, "utf-8")) as Record; - hashes[STUB_A] = "0".repeat(64); - writeFileSync(hashesPath, JSON.stringify(hashes, null, 2) + "\n"); + setManifestEntry(genStateDir, STUB_A, "0".repeat(64)); const result = sweepOrphans({ genStateDir, diff --git a/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts b/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts index 3c2bd6dfd5..0a82e71374 100644 --- a/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts +++ b/server/typescript/packages/codegen-ts/test/out-of-project-output.test.ts @@ -2,7 +2,7 @@ // // The manifest keys every generated file by its path relative to the project root, so a // target whose outDir is outside the project (a scratch preview, a sibling checkout) was -// recorded as `../..//X.ts` in the COMMITTED `.hashes.json` — 87 such keys on +// recorded as `../..//X.ts` in the COMMITTED `.hashes/` manifest — 87 such keys on // one adopter estate after a single preview run. Worse, the snapshot body is stored at // `/`, so the `../..` walked out of `.gen-state/` and wrote a second full // copy of the output into the project tree itself. @@ -10,6 +10,7 @@ // Such a file is now written untracked, exactly as a run with no project root writes it: // no manifest key, no snapshot under the project, and one warning saying so. +import { manifestEntries } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, readFileSync, readdirSync, existsSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -48,7 +49,7 @@ async function genInto(outDir: string) { }); } -const hashesFile = (): string => join(projectRoot, ".metaobjects", ".gen-state", ".hashes.json"); +const genState = (): string => join(projectRoot, ".metaobjects", ".gen-state"); describe("output outside the project root", () => { test("is written, but recorded nowhere in the project", async () => { @@ -56,7 +57,7 @@ describe("output outside the project root", () => { const result = await genInto(out); expect(readdirSync(out).length).toBeGreaterThan(0); - const keys = existsSync(hashesFile()) ? Object.keys(JSON.parse(readFileSync(hashesFile(), "utf-8"))) : []; + const keys = Object.keys(manifestEntries(genState())); expect(keys.filter((k) => k.startsWith(".."))).toEqual([]); // Nothing but the (possibly absent) gen-state directory appeared in the project. expect(readdirSync(projectRoot).filter((e) => e !== ".metaobjects")).toEqual([]); @@ -65,7 +66,7 @@ describe("output outside the project root", () => { test("output inside the project is still tracked", async () => { await genInto(join(projectRoot, "generated")); - const keys = Object.keys(JSON.parse(readFileSync(hashesFile(), "utf-8"))); + const keys = Object.keys(manifestEntries(genState())); expect(keys.length).toBeGreaterThan(0); expect(keys.every((k) => k.startsWith("generated/"))).toBe(true); }); diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy.test.ts index f7e6d6ef92..c99e798229 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy.test.ts @@ -2,6 +2,7 @@ // More elaborate scenarios (clean merge, conflict, integrity, missing git, // first-time-existing) live in test/overwrite-policy/*.test.ts. +import { manifestEntries, seedLegacyManifest } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -96,8 +97,8 @@ describe("decideAndWrite (three-way merge)", () => { describe("shared manifest with object-valued entries", () => { test("reads an object entry's hash and preserves its fields on record and forget", () => { const jvm = { hash: contentHash("jvm body"), generator: "java:dto", outputDir: "target/gen" }; - const manifest = join(state, ".hashes.json"); - writeFileSync(manifest, JSON.stringify({ "Jvm.java": jvm, "Plain.txt": "abc", "Gone.java": { ...jvm } }, null, 2) + "\n"); + // Seeded as the legacy single file on purpose: the runs below migrate it. + seedLegacyManifest(state, { "Jvm.java": jvm, "Plain.txt": "abc", "Gone.java": { ...jvm } }); expect(readGeneratedHash(state, "Jvm.java")).toBe(jvm.hash); @@ -109,7 +110,8 @@ describe("shared manifest with object-valued entries", () => { forgetGeneratedPaths(state, ["Gone.java"]); - const saved = JSON.parse(readFileSync(manifest, "utf-8")); + const saved = manifestEntries(state); + expect(existsSync(join(state, ".hashes.json"))).toBe(false); // migrated expect(saved["Jvm.java"]).toEqual(jvm); expect(saved["Plain.txt"]).toBe("abc"); expect(saved["Other.ts"]).toBe(contentHash("x\n")); @@ -119,7 +121,7 @@ describe("shared manifest with object-valued entries", () => { writeFileSync(jvmFile, "jvm body"); const rewrite = decideAndWrite(jvmFile, "jvm body v2", { genStateDir: state, outputRelPath: "Jvm.java" }); expect(rewrite.status).not.toBe("refused"); - const after = JSON.parse(readFileSync(manifest, "utf-8")); + const after = manifestEntries(state); expect(after["Jvm.java"]).toEqual({ ...jvm, hash: contentHash("jvm body v2") }); }); }); diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/integrity.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/integrity.test.ts index fe1abd4d42..7bfd2bea1f 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/integrity.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/integrity.test.ts @@ -3,6 +3,7 @@ // stored value (someone tampered with .gen-state), we treat the snapshot as // absent and fall back to first-time-existing semantics. +import { manifestEntries, manifestExists } from "../support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -66,8 +67,8 @@ describe(".gen-state integrity", () => { decideAndWrite(path, v1, { genStateDir: state, outputRelPath: "User.ts" }); // Hashes file is present. - expect(existsSync(join(state, ".hashes.json"))).toBe(true); - const hashes = JSON.parse(readFileSync(join(state, ".hashes.json"), "utf-8")); + expect(manifestExists(state)).toBe(true); + const hashes = manifestEntries(state); expect(hashes["User.ts"]).toBeDefined(); // User edits the "field email" line (line 2) diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts index 6bf41f35d2..1a9711b388 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts @@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { isManifestPath, manifestEntries, manifestFiles, manifestMtimes } from "../support/manifest.js"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { decideAndWrite, mergeTempDir, withManifestBatch } from "../../src/overwrite-policy.js"; @@ -18,8 +19,6 @@ afterEach(() => { rmSync(state, { recursive: true, force: true }); }); -const MANIFEST = () => join(state, ".hashes.json"); - function run(files: Record): void { withManifestBatch(state, () => { for (const [name, content] of Object.entries(files)) { @@ -29,7 +28,7 @@ function run(files: Record): void { } const manifestWrites = (spy: { mock: { calls: unknown[][] } }) => - spy.mock.calls.filter((c) => String(c[0]).endsWith(".hashes.json")).length; + spy.mock.calls.filter((c) => String(c[0]).includes("/.hashes/")).length; describe("hash manifest, once per run", () => { test("a run that writes many files writes the manifest once", () => { @@ -38,18 +37,20 @@ describe("hash manifest, once per run", () => { run({ "A.ts": "a\n", "B.ts": "b\n", "C.ts": "c\n" }); expect(manifestWrites(spy)).toBe(1); } finally { spy.mockRestore(); } - expect(Object.keys(JSON.parse(readFileSync(MANIFEST(), "utf-8"))).sort()).toEqual(["A.ts", "B.ts", "C.ts"]); + expect(Object.keys(manifestEntries(state)).sort()).toEqual(["A.ts", "B.ts", "C.ts"]); }); test("a run that changes nothing does not write the manifest", () => { run({ "A.ts": "a\n", "B.ts": "b\n" }); - const before = statSync(MANIFEST()).mtimeMs; + const before = manifestMtimes(state); + const beforeBytes = manifestFiles(state); const spy = spyOn(fs, "writeFileSync"); try { run({ "A.ts": "a\n", "B.ts": "b\n" }); expect(manifestWrites(spy)).toBe(0); } finally { spy.mockRestore(); } - expect(statSync(MANIFEST()).mtimeMs).toBe(before); + expect(manifestMtimes(state)).toEqual(before); + expect(manifestFiles(state)).toEqual(beforeBytes); }); }); diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/pristine-hash.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/pristine-hash.test.ts index a94eafdb02..f3b54697b5 100644 --- a/server/typescript/packages/codegen-ts/test/overwrite-policy/pristine-hash.test.ts +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/pristine-hash.test.ts @@ -8,7 +8,7 @@ // false in exactly the situation adopters spend most of their time in. // // The fix rests on one question, asked of one piece of evidence: IS THIS FILE -// BYTE-FOR-BYTE WHAT WE RECORDED WRITING? `.hashes.json` answers it without the +// BYTE-FOR-BYTE WHAT WE RECORDED WRITING? the `.hashes/` manifest answers it without the // snapshot body, which is why the manifest is the part that gets committed — // a hash per path is small and reviewable, where a second full copy of all // generated output is neither. @@ -21,6 +21,7 @@ // hand-edited content as though we had written it would launder the edit into the // manifest, and the NEXT run would then overwrite it with a clear conscience. +import { manifestFiles } from "../support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -222,7 +223,7 @@ describe("the manifest is a committed artifact", () => { outputRelPath: rel, }); } - const raw = readFileSync(join(state, ".hashes.json"), "utf-8"); + const raw = manifestFiles(state)[".root.json"]!; // no model, so every path files under the root const keys = Object.keys(JSON.parse(raw) as Record); expect(keys).toEqual(["a.ts", "m.ts", "z.ts"]); }); diff --git a/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts b/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts index 76d2cc5649..4ac280a454 100644 --- a/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts +++ b/server/typescript/packages/codegen-ts/test/ownership-seam.test.ts @@ -14,6 +14,7 @@ // 3. The refusal names no remedy a `requirementTests()` owner cannot perform, and the // recovery that DOES keep the edit is printed once per run rather than per file. + import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, readFileSync, writeFileSync, readdirSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -99,11 +100,11 @@ function writeMyBody(path: string): void { function dropSnapshotBodies(projectRoot: string): void { const genState = join(projectRoot, ".metaobjects", ".gen-state"); for (const entry of readdirSync(genState)) { - if (entry !== ".hashes.json") { + if (entry !== ".hashes") { rmSync(join(genState, entry), { recursive: true, force: true }); } } - expect(readdirSync(genState)).toEqual([".hashes.json"]); + expect(readdirSync(genState)).toEqual([".hashes"]); } describe("`.extra.ts` is a convention, not a mechanism", () => { diff --git a/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts b/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts index 310f37a7e6..d7fd26cf8c 100644 --- a/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts +++ b/server/typescript/packages/codegen-ts/test/run-wide-orphan-sweep.test.ts @@ -6,6 +6,7 @@ // on disk, `verify --codegen` convicted it and said "run 'meta gen'", and gen never // deleted anything, so the gate failed the same way after every run. +import { manifestFiles } from "./support/manifest.js"; import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -16,7 +17,7 @@ import { entityFile } from "../src/generators/entity-file.js"; import type { Generator } from "../src/generator.js"; const OUT = "gen"; -const MANIFEST = join(".metaobjects", ".gen-state", ".hashes.json"); +const GEN_STATE = join(".metaobjects", ".gen-state"); async function model(...names: string[]): Promise { const doc = JSON.stringify({ @@ -41,7 +42,8 @@ afterEach(() => { }); const abs = (rel: string): string => join(projectRoot, rel); -const manifest = (): string => readFileSync(abs(MANIFEST), "utf8"); +// Every manifest file, concatenated: the assertions ask whether a path is recorded anywhere. +const manifest = (): string => Object.values(manifestFiles(abs(GEN_STATE))).join("\n"); async function gen( names: string[], diff --git a/server/typescript/packages/codegen-ts/test/support/manifest.ts b/server/typescript/packages/codegen-ts/test/support/manifest.ts new file mode 100644 index 0000000000..a6c0f50c8d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/support/manifest.ts @@ -0,0 +1,61 @@ +// Test helpers for the per-package hash manifest (`.gen-state/.hashes/.json`, +// ADR-0064 Amendment 1). Tests read the manifest through these instead of one file. +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + HASHES_DIR, + LEGACY_HASHES_FILE, + manifestExists, + readManifestState, +} from "../../src/hash-manifest-store.js"; + +export { HASHES_DIR, LEGACY_HASHES_FILE, manifestExists }; + +/** Every recorded entry: the union of all manifest files (and a legacy file, if present). */ +export function manifestEntries(genStateDir: string): Record { + return readManifestState(genStateDir).entries as Record; +} + +/** File name -> text of every file in `.hashes/`. */ +export function manifestFiles(genStateDir: string): Record { + const dir = join(genStateDir, HASHES_DIR); + const out: Record = {}; + if (!existsSync(dir)) return out; + for (const name of readdirSync(dir).sort()) out[name] = readFileSync(join(dir, name), "utf-8"); + return out; +} + +/** File name -> mtime (ms) of every file in `.hashes/`. */ +export function manifestMtimes(genStateDir: string): Record { + const dir = join(genStateDir, HASHES_DIR); + const out: Record = {}; + if (!existsSync(dir)) return out; + for (const name of readdirSync(dir).sort()) out[name] = statSync(join(dir, name)).mtimeMs; + return out; +} + +/** Remove the whole manifest (per-package dir and legacy file). */ +export function removeManifest(genStateDir: string): void { + rmSync(join(genStateDir, HASHES_DIR), { recursive: true, force: true }); + rmSync(join(genStateDir, LEGACY_HASHES_FILE), { force: true }); +} + +/** Write the OLD single-file layout, as a pre-amendment checkout would have it. */ +export function seedLegacyManifest(genStateDir: string, entries: Record): void { + mkdirSync(genStateDir, { recursive: true }); + writeFileSync(join(genStateDir, LEGACY_HASHES_FILE), JSON.stringify(entries, null, 2) + "\n"); +} + +/** True for paths of a file inside `.hashes/`. */ +export const isManifestPath = (p: unknown): boolean => String(p).includes(`/${HASHES_DIR}/`); + +/** Replace one recorded entry in place, in whichever manifest file holds it. */ +export function setManifestEntry(genStateDir: string, path: string, entry: unknown): void { + const state = readManifestState(genStateDir); + const name = state.fileOf.get(path); + if (name === undefined) throw new Error(`no manifest file records ${path}`); + const file = join(genStateDir, HASHES_DIR, name); + const entries = JSON.parse(readFileSync(file, "utf-8")) as Record; + entries[path] = entry; + writeFileSync(file, JSON.stringify(entries, null, 2) + "\n"); +} diff --git a/server/typescript/packages/docs-site/src/explorer/build.ts b/server/typescript/packages/docs-site/src/explorer/build.ts index 344fbc4afd..817e1f93f4 100644 --- a/server/typescript/packages/docs-site/src/explorer/build.ts +++ b/server/typescript/packages/docs-site/src/explorer/build.ts @@ -6,7 +6,7 @@ // overlays already resolved, references already in their canonical spelling. // verify the `meta verify --format json` payload: the requirement ledger rows, each // link as the gate resolved it, the counts and the findings. -// manifest `.metaobjects/.gen-state/.hashes.json`: which generated file came from which +// manifest the entries of `.metaobjects/.gen-state/.hashes/`: which generated file came from which // node, where the port records it. // // Every port already has a canonical serializer and writes the same manifest, so a Java, C# @@ -61,7 +61,7 @@ export interface ExplorerInput { /** Parsed `meta verify --format json` output. Without it there is no ledger and no * `implementedBy` / `supersededBy` edge. */ verify?: unknown; - /** Parsed `.metaobjects/.gen-state/.hashes.json`. Without it there is no `generated`. */ + /** The merged entries of `.metaobjects/.gen-state/.hashes/`. Without it there is no `generated`. */ manifest?: unknown; /** The routes the project mounts: `[{ node, method, path }]`, one per route, `node` a node * id. A route whose node is not in the model is dropped. Without it there is no `api`. */ diff --git a/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md b/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md index 7a929d8fff..83b0d2e129 100644 --- a/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md +++ b/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md @@ -120,3 +120,104 @@ and the manifest is keyed by output path, so per-unit records will not collide. - A generator that reads something it did not declare could make a skip wrong. The defenses are the declared extras, `cache: false`, `--force`, and CI's full `verify --codegen`. - Nothing changes for an adopter who never runs `gen` twice without a change in between. + +## Amendment 1 (2026-11-20): the hash manifest is one file per package + +Registers no vocabulary: `metamodelVersion` is unchanged. For 1.3.0, in every port that keeps hash +state (TypeScript, Python, C#, Java and Kotlin, and Rust in preview). This is the "per-package keys +come next" step of §6, applied to the one file every generated path is recorded in. + +### Context + +The committed manifest, `.metaobjects/.gen-state/.hashes.json`, is one file for the whole project. Any +two branches that regenerate any file in any package both rewrite it, so they conflict on it even +when they share no generated file, and an adopter with parallel branches cannot validate them side by +side. The file's bytes are already deterministic (sorted keys), so the conflict is not noise from +ordering: it is one file standing for many independent facts. + +### Decision + +**1. One manifest per model package.** The manifests live in +`.metaobjects/.gen-state/.hashes/` (on the JVM, under the module's basedir like the file they +replace), one JSON file per model package: + +- A package file is named for the package: its `::`-separated segments joined with `.`, each segment + with every byte outside `[A-Za-z0-9_-]` written as `%XX` (uppercase hex of the UTF-8 byte), then + `.json`. `acme::shop` is `acme.shop.json`. Package segments never contain a `.`, so the name is + unambiguous. +- A generated path that belongs to no package goes in one root manifest, `.root.json`. A leading dot + cannot start a package name, so the root cannot collide with a package. +- A file holds exactly what the single manifest held for its paths, unchanged: one JSON object keyed + by project-relative path, keys sorted, two-space indentation, a trailing newline, each value a + SHA-256 hex string or an object carrying `hash` and any owner or provenance fields the port keeps + (`generator` and `outputDir` on the JVM, `generatedBy` and `sourceNode` in TypeScript). Nothing + about a value changes, so no reader of one entry changes. + +**2. Reading is a union.** A reader merges every `*.json` file in `.hashes/`, in file-name order, with +the legacy `.hashes.json` underneath them (a key in a package file wins). An absent, unreadable or +corrupt file reads as empty, which fails closed as before, and is replaced on the next write. "The +project has a manifest" means the legacy file or at least one file in `.hashes/` exists. Which file +an entry was found in is never evidence about the path: a reader asks for a path and gets its +record from wherever it is. This is what makes placement (below) safe to get wrong: a misplaced +entry costs a merge conflict that could have been avoided and nothing else. + +**3. Placement is a pure function, so it is stable.** A writer files each entry under: + +1. **Its recorded `sourceNode`**, when it has one (TypeScript records it). The package is the + `sourceNode` up to its first `.`, minus its last `::` segment (`acme::shop::Order.id` files under + `acme::shop`). A `sourceNode` with no `::` names an object in no package: the root manifest. +2. **Else the object whose name the file's stem begins with, word by word.** The stem is the file's + base name up to its first `.` (`gen/OrderDto.java` has the stem `OrderDto`). Both the stem and an + object's name are split into lowercase words: at every `_` and `-`, before an uppercase letter that + follows a lowercase letter or a digit, and before the last uppercase letter of a run that is + followed by a lowercase letter (`HTTPServer` is `http` and `server`; `order_line` and `OrderLine` + are both `order` and `line`; digits stay with the word before them). A loaded root-level object + matches when its words are the first words of the stem's (`Order` matches `OrderDto`, + `order_names` and `order-line`, not `Ordered` or `orders`). The matches with the most words win; + when they are declared in more than one package, or in none, the file has no package. + Otherwise the matched objects' package is the file's. Matching by words, not by exact spelling, is what lets + a snake_case port (Python, Rust) and a PascalCase one place a file the same way. +3. **Else where the entry already is**, when the writer has no model (a tool that edits the + manifest without loading one), and +4. **Else the root manifest.** + +Every port implements 1 and 2 as one function over the loaded model and runs it for every entry on +every write, so an entry moves when its object moves package or is renamed, and does not move +otherwise. `fixtures/codegen-skip-conformance/manifests.json` holds the vectors. + +**4. A write touches only the files that changed.** A writer computes every manifest's bytes and +writes a file only when they differ from what it read, deletes a package file that no longer holds +an entry, and keeps `.root.json` present (as `{}`) when no entry exists at all, so "no manifest" stays +distinguishable from "an empty one". Within a run each manifest is still written at most once, only +when something changed (§1). So two branches that regenerate files in different packages change +different files, and git merges them with nothing to resolve; only a file recorded in the root +manifest, or one path in one package, can still collide, and those are the files whose own bytes +would collide too. + +**5. A legacy manifest is migrated by the next write run.** A run that finds `.hashes.json` reads +it, files every entry by §3, writes the per-package files, deletes `.hashes.json`, and counts as a +run that changed the manifest, so it happens even when no generated file changed. A read-only +command (`verify`) reads the union and migrates nothing. The migration also adds +`!.gen-state/.hashes/` to `.metaobjects/.gitignore`, in the place of the `!.gen-state/.hashes.json` +line (which it removes: it names a file that no longer exists), or after `.gen-state/*` when there +is no such line, when that file holds the `.gen-state/*` rule the scaffold writes, because without +it git would ignore the new directory. Only a migrating run touches `.gitignore`; a project whose rule lives elsewhere gets the existing "manifest is git-ignored" +advisory, now naming `.hashes/`. The adopter commits the result and does nothing else. A branch that +still holds the legacy file merges as an ordinary add/delete; take the migrated side and run `gen`. + +**6. Everything that read the manifest reads the union.** The write decision (overwrite, refuse, +merge), the orphan sweep, `verify --codegen`, the explorer's list of generated files and the skip +state (§3's stored-key check, which asks every recorded file whether it still hashes to its record) +go through the one reader, so a run keys on the same set of paths as before. The stored skip key +(`.fingerprint-.json`) is not committed and is unchanged. + +### Consequences + +- Two branches that change generated files in different packages produce manifests that merge with + no conflict. The conformance cases and each port's unit tests assert the file-level separation; + the TypeScript suite proves the merge with git. +- An adopter's first `gen` on 1.3.0 rewrites its manifest into `.hashes/` and removes + `.hashes.json`. Commit both changes; there is no flag and no second step. +- A file the writer cannot attribute (a barrel, an index, a docs page) is in the root manifest. Those + files are the ones whose own contents collide when two branches touch them. +- A project that named `.hashes.json` in a script or an ignore rule must name `.hashes/`. diff --git a/spec/decisions/README.md b/spec/decisions/README.md index b8690ab60c..3bedaf6e51 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -56,11 +56,11 @@ Write one when a decision is **cross-cutting** (affects more than one language p - [ADR-0057 — Requirement checks and requirement tests run in every port](ADR-0057-requirement-checks-and-tests-in-every-port.md) — *Accepted* (reverses the "Checks — TypeScript only" split recorded in `docs/CONFORMANCE.md`) - [ADR-0058 — One physical-naming setting, read by every port](ADR-0058-one-physical-naming-setting.md) — *Accepted* (one `naming` block in `.metaobjects/config.json` replaces the per-port column-naming flags, pom args, config keys and runtime setters) - [ADR-0059 — References resolve once, after the tree](ADR-0059-references-resolve-once-after-the-tree.md) — *Accepted* (sources keep references as written; one resolver per port binds them before freeze and the serializer writes them canonical; supersedes ADR-0032 §3–§4, amends ADR-0042) -- [ADR-0060 — Java and Kotlin codegen decide overwrites from the committed hash manifest](ADR-0060-jvm-codegen-hash-manifest.md) — *Accepted* (the JVM plugin records each file it writes in `.metaobjects/.gen-state/.hashes.json`, refuses an edited one, and deletes an untouched orphan, owned per generator and output directory) +- [ADR-0060 — Java and Kotlin codegen decide overwrites from the committed hash manifest](ADR-0060-jvm-codegen-hash-manifest.md) — *Accepted* (the JVM plugin records each file it writes in the `.metaobjects/.gen-state/` hash manifest, refuses an edited one, and deletes an untouched orphan, owned per generator and output directory; the manifest's layout is ADR-0064 Amendment 1's) - [ADR-0061 — A template body may use a per-port engine, chosen by its file](ADR-0061-per-port-template-engines.md) — *Accepted* (Python and TypeScript render and check Jinja bodies — `.jinja` / `.j2` / `.jinja2` — against the same payload check; the metadata never names an engine; Java, Kotlin and C# refuse Jinja with `ERR_TEMPLATE_ENGINE_UNSUPPORTED`) - [ADR-0062 — Two providers may not claim one attribute name on a node type](ADR-0062-provider-attribute-ownership.md) — *Accepted* (the registry records which provider registered each attribute and refuses a second provider's claim on the same name on the same slot, the shared root or a descendant subtype: `ERR_PROVIDER_ATTR_CONFLICT` for the same slot, new `ERR_PROVIDER_ATTR_SHADOW` for the related slots; each provider keeps its own idiomatic physical-name word, a store without a provider uses `attr.properties`, no wire-name attribute is added) - [ADR-0063 — Generators own their layout; formatters are test oracles only](ADR-0063-generators-own-layout.md) — *Accepted* (a writer in each port lays generated text out and no formatter runs in generation; output aims for clean code, not parity with today's formatting; a syntax-tree ratchet holds generator source to it, with an allowlist that only shrinks) -- [ADR-0064 — `gen` skips rendering when the loaded model and its generators are unchanged](ADR-0064-skip-codegen-when-nothing-changed.md) — *Accepted* (every port keys a run on the loaded model and its generator inputs, and a matching key with every generated file unchanged renders and writes nothing; the manifest is written once per run; a local `verify --codegen` may answer from the key) +- [ADR-0064 — `gen` skips rendering when the loaded model and its generators are unchanged](ADR-0064-skip-codegen-when-nothing-changed.md) — *Accepted* (every port keys a run on the loaded model and its generator inputs, and a matching key with every generated file unchanged renders and writes nothing; the manifest is written once per run; a local `verify --codegen` may answer from the key; Amendment 1: the manifest is one file per model package) - [ADR-0065 — Rust is the sixth port](ADR-0065-rust-is-the-sixth-port.md) — *Accepted* (a Rust port under `server/rust/`, in preview and unpublished, on its own 0.x line when it publishes; the command is `cargo meta`; no `migrate`, Jinja refused, generated code as one crate per MetaObjects package; gated by `registry-conformance` and the metamodel corpus with a shrink-only ledger. **Amendment 1**: `cargo meta init` / `gen` / `verify --codegen` / `eject`, an owned generator as a crate the project builds, the generated crate shape, and the `client` and `commands` generators, the second Rust-only by decision) - [ADR-0066 — Business rules: operations, permission points and lifecycles](ADR-0066-business-rules-operations-and-lifecycles.md) — *Accepted* (registers `api.*`, `operation.*`, `binding.*` and `transition.*` in all five ports, experimental, with eleven loader errors and a rules gate in every `verify`; the lifecycle, its states and a transition's command are derived; `transition.timed` reserved; the enforcing shells are later work) - [ADR-0067 — Generated code is layered, and hand-written code attaches at the service seam](ADR-0067-layering-and-the-service-seam.md) — *Accepted* (layers 0 to 6; a service module per metadata package whose surface is its operations; hand-written bodies, policy and event handling implement generated interfaces and are passed in, in every language; generator sets chosen per package; amends ADR-0045)