diff --git a/CHANGELOG.md b/CHANGELOG.md index c91805ffa6..b407990cfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -128,6 +128,13 @@ there is described in full here. This list is where to start. unique** (`FkTargetNotUniqueError`, listing every offending reference at once), where the database refused it at apply time after earlier statements had run. A foreign key onto a hand-made unique index can fail `verify --db` that passed before. +- **Postgres, by hand: `meta verify --db` can report a `SELECT *` view as changed.** A + hand-written `@sql` view that selects `*` keeps the columns its base tables had when it was + created, while the shadow database `verify --db` builds expands `*` over every column. The + entry names the cause. To clear the drift, list the view's columns explicitly, or drop and + recreate the view by hand. Offline `meta migrate` plans nothing for this drift; `meta migrate + --from-db` compares through the shadow database and can plan a replace, or a drop and create, + so review that plan before `--apply`. - **On Postgres the primary key's name is compared.** A convention switch or a table rename renames the key in place, and `meta verify --db` reports a mismatch it used to pass. - **`meta verify` exits 2 when `metaobjects.config.ts` exists but fails to load**, and prints that @@ -135,10 +142,74 @@ there is described in full here. This list is where to start. config's providers and report an unknown subtype. - **TypeScript and Python: two shared enums with one name are `ERR_NAME_COLLISION`.** The second used to be dropped silently and its fields typed with the first one's members. Rename one. -- **TypeScript: an owned generator that imports one of ts-poet's `def`, `literalOf`, `arrayOf`, - `asOneline`, `Import.fromMaybeString`, `saveFiles`, `conditionalOutput` or its `toString` import - options no longer loads.** The printer is now vendored without them; `code`, `imp`, `joinCode`, - `Import` and the `Code` type still resolve from a bare `ts-poet` import. +- **Breaking, TypeScript, by hand for owned generators: a generator copy ejected in 1.2 or earlier + no longer loads or typechecks.** TypeScript codegen writes only through the code writer, so + `@metaobjectsdev/codegen-ts` no longer exports `formatTs`, the ts-poet printer's `code`, `imp`, + `joinCode`, `Import` and `Code`, the queries primitives, or `schemaInputType`; the config loader + no longer rewrites a bare `ts-poet` import. These are not coming back as compatibility exports: + an owned 1.2 copy is re-ejected or ported, as below. A copy that uses any of them fails + `meta gen` (`formatTs is not a function`, `renderFindByIdFn is not a function`) or `tsc` (`has no + exported member 'formatTs'`, `'code'`, `'Code'`, `'renderFindByIdFn'`). Re-eject it + (`meta eject --force`) and re-apply your changes, or port it by hand: write through + `TsWriter` and the writer fragments (`frag`, `joinFrags`, `importName`, `importType`, `Frag`, + `TsImport`), declare `provides` instead of a marker, and call your own formatter if you want one. + What replaces what: + + - **The seven queries primitives** the ejected `queries` copy was built from become writer + functions that write into the `TsWriter` you pass, and return nothing: `renderFindByIdFn` → + `writeFindByIdFn(w, entity, ctx, readVar?)`, `renderListFn` → `writeListFn`, `renderCreateFn` + → `writeCreateFn`, `renderInsertPreservingFn` → `writeInsertPreservingFn`, `renderUpdateFn` + → `writeUpdateFn`, `renderDeleteByIdFn` → `writeDeleteByIdFn`, `renderReverseFinderFns` → + `writeReverseFinderFns(w, entity, fk, ctx, readVar?)`. To change one verb's body, write your own function in its place, as the + re-ejected `queries` copy shows. + - **The entity sub-renderers return `Frag`, not ts-poet `Code`** (`renderZodValidators`, + `renderEnumTypeAliases`, `renderValueObjectInterface`, `renderDrizzleSchema` and the rest). A + `Frag` carries its imports beside its text, and only `joinFrags` and the writer merge them. An + owned 1.2 entity composer that joins them with ts-poet's `joinCode(sections).toString()` does + not fail where it runs: each section prints its own import lines, so every file gets one + `import { z } from "zod"` per section and the build fails with `Identifier 'z' has already + been declared` (TS2300). Since 1.3.0 `meta gen` and `meta verify --codegen` parse every + emitted TypeScript file and refuse such output by file and generator, writing nothing. + Compose with `joinFrags(sections, "\n")` and write the result with `TsWriter.fragment(...)`, + or re-eject `entity`. A composer that puts a `Frag` in a template literal (`${renderZodValidators(e)}`), + adds it to a string or joins an array of them got the text ts-poet's `Code` printed; a `Frag` + has no text of its own, so that now throws `ERR_FRAG_AS_TEXT` naming the fix, and any output + still carrying `[object Object]` is refused by `meta gen` and `meta verify` (see Fixed). An + owned entity generator moving onto the writer can subclass `EntityFileWriter`, now exported + from `@metaobjectsdev/codegen-ts/engine`. + - **The engine name helpers return `Frag`, not ts-poet `Code`**: `physicalNameExpr`, + `columnExpr`, `indexNameExpr` and `sourceSchemaExpr` (`Frag | undefined`) return one, and + `namesRef` and `namesConstArg` return one as their `symbol`. An owned 1.2 template that + interpolates one into a ts-poet `` code`...` `` template (pointed at a `ts-poet` copy from + elsewhere in `node_modules`) wrote `pgTable([object Object], { ... })` into every entity file + and passed `meta gen` and `meta verify --codegen`. That output is now refused by name, and a + `Frag` in a template literal throws `ERR_FRAG_AS_TEXT`. There is no compatibility export: + re-eject every owned TypeScript generator (`meta eject --force`) and reapply your + changes, or pass the result to `frag(...)` or a `TsWriter` line instead of a template + literal. + - **The nine generator markers become `provides`**, and `meta gen` refuses a generator that + still sets one, naming every such generator in one run: `emitsEntityModule` → + `provides: { entityModule: true }`, `emitsQueries` → `{ queries: true }`, `emitsNames` → + `{ names: true }`, `emitsReportExport` → `{ reportExport: true }`, `emitsUiTier` → + `{ uiTier: true }`, `emitsHonoRoutes` → `{ routes: { framework: "hono" } }`, `mountsRoutes` → + `{ routes: { framework: "fastify", expose, filter } }`, `emitsApiDocs` → + `{ apiDocs: { subDir } }`, and `emitsModelDocs` is dropped with nothing in its place (the docs + Markdown generator it marked is removed). The refusal prints the declaration for each. + - **`formatTs` and the ts-poet printer** go; write through `TsWriter`: + + ```ts + // 1.2 + import { code, formatTs } from "@metaobjectsdev/codegen-ts"; + return [{ path, content: await formatTs(code`export const x = 1;`.toString()) }]; + // 1.3 + import { TsWriter } from "@metaobjectsdev/codegen-ts"; + const w = new TsWriter(); + w.line("export const x = 1;"); + return [{ path, content: w.toString() }]; + ``` + + The whole move, item by item: + [owned-generators-1.2-to-1.3](docs/features/migrations/owned-generators-1.2-to-1.3.md). - **TypeScript: `valueObjectModuleSpecifier` takes the value object's node first.** An owned template copied from 1.2 calls `valueObjectModuleSpecifier(name, ctx.packageOf, fromPkg, ctx.outputLayout, ctx.extStyle)`; the 1.3 signature is `valueObjectModuleSpecifier(vo, voName, @@ -185,8 +256,107 @@ there is described in full here. This list is where to start. A fresh writer starts at column 0, where `members` indented its lines by four spaces; to keep the old layout, write into the writer the class body is written with, inside the body's block. -- **`docsSiteFile()` builds the model explorer by default.** The site under `site/` changes, with - object pages under `model/`. Pass `docsSiteFile({ site: "classic" })` to keep the earlier site. +- **Breaking, TypeScript: `docsSiteFile()` builds the model explorer, and the classic site and the + docs Markdown generator are removed.** The site under `site/` changes, with object pages under + `model/`. `docsSiteFile({ site: "classic" })` now throws, an owned classic theme under + `codegen/docs-site/` is refused (delete it and re-run `meta eject docs-site`), and `docsFile()` + (the stable name `"docs"`: a Markdown page per object and the `README.md` overview) is gone. + Remove `docsFile()` from `metaobjects.config.ts` and delete the pages it wrote; the explorer is + the model's documentation for people and `agentDocsFile()` the one for a coding agent. A script + that called `@metaobjectsdev/docs-site`'s `generateSite({ sourceDirs })` loads the model itself + now and calls `buildDocsView` and `generateExplorerSite({ ..., output: "static" })`: + [docs-are-generators](docs/features/migrations/docs-are-generators.md#since-130-generatesite-is-removed). +- **`requirementsFile()` no longer writes `requirements.md`** (every port). The `requirements` + generator writes only `requirements.toon`; people read the ledger in the explorer and agents in + `agent/requirements.md`. The next `gen` deletes the generated `requirements.md` without a + warning, and `meta verify` reports a committed copy as one regeneration would not emit: delete + it, and repoint any README link at the explorer or `agent/requirements.md`. +- **The hash manifest gains which node each file came from (C#, Java, Python, Rust).** The next + `gen` rewrites the committed `.metaobjects/.gen-state/.hashes/` files once, adding `generatedBy` + and `sourceNode` to each per-object entry, as TypeScript already wrote. Commit them; generated + source files do not change. +- **Generated create models now refuse what the cross-field validators and `field.uuid` forbid + (every port).** `validator.comparison`, `requiredWhen`, `presentIff`, `atLeastOne` and + `exactlyOne` used to be enforced only by the database `CHECK`; the regenerated create model now + enforces them too: the TypeScript insert schema's `.superRefine`, the Java and Kotlin create + DTO's class-level constraint, C#'s `IValidatableObject`, and the `model_validator` on Python's + `Create`. The TypeScript insert and update schemas also check a `field.uuid`'s + 8-4-4-4-12 shape. A write that the database used to refuse, or accepted because the store has + no `CHECK` (a graph or document store), is now answered `400 validation` before it reaches the + store. Check any client or import job that relied on the store to decide. PATCH models are + unchanged by the cross-field validators. + + The uuid check is new on **every** dialect, not only Postgres: SQLite and D1 store a uuid as + text and accepted any string, so a POST or PATCH body whose `field.uuid` value (a key or a + foreign key) is not canonical, such as `"mbr1"`, now gets + `400 {"error":"validation", ... "format":"regex" ... "message":"Invalid uuid"}` where it got + 201 or 200. Check seed scripts, fixtures, imported rows and hand-inserted ids before you + upgrade: a row already stored with such an id still reads, and `GET //` on SQLite + still answers it, but no client can write that value again. Rewrite the ids to canonical + uuids, or declare the field `field.string` if it was never a uuid. +- **By hand for owned generators, every port: the code writer refuses text that starts with + whitespace.** `line`, `open` and `close` (and TypeScript's and Kotlin's `reopen`) throw + `ERR_WRITER_LEADING_WHITESPACE` when handed indented text, because the writer indents from the + open blocks and a hand-indented line came out one level too deep. A generator of your own, or a + copy ejected from an earlier 1.3 candidate, that writes a block comment's continuation lines + through `line(" * ...")` now fails `gen` with that code, naming the text. Write those lines with + the new `commentLine("...")` (TypeScript `TsWriter`, Java `JavaWriter`, Kotlin `KotlinWriter`), + which prints the ` * ` prefix, or drop the leading spaces; `doc()` and file headers keep their + own layout. Re-ejected copies already do. +- **Python, by hand for owned subclasses: `EntityModelGenerator` hooks return members without + indentation.** The entity generator writes through the code writer, so generated model modules + change layout once (imports in one section, a long `Field(...)` one keyword per line), and the + writer indents each member itself. A subclass written for 1.2 or earlier whose + `_emit_field_lines`, `_emit_create_lines` or `_emit_patch_lines` returns lines carrying their own + four-space indent is refused with `ERR_WRITER_LEADING_WHITESPACE`, naming the subclass (in + 1.3.0 release candidates it wrote a module that did not compile). Drop the indent. + `_emit_cross_field_rules` returns a step that writes the method onto the writer (or `None`) + instead of lines. `metaobjects gen` and every `metaobjects verify` mode that includes codegen + (`--codegen`, and a bare `verify`) also refuse any generated `.py` file that does not compile, + naming the file and the generator; `verify --templates` alone checks prompt templates only and + does not compile generated code: + + ```python + # 1.2 + def _emit_field_lines(self, entity, imports, object_index, config=None): + lines, uses = super()._emit_field_lines(entity, imports, object_index, config) + return [' model_config = ConfigDict(extra="forbid")', *lines], uses + # 1.3 + def _emit_field_lines(self, entity, imports, object_index, config=None): + lines, uses = super()._emit_field_lines(entity, imports, object_index, config) + return ['model_config = ConfigDict(extra="forbid")', *lines], uses + ``` +- **Python, by hand for owned subclasses: the router and extractor hooks take the writer.** + `RouterGenerator._emit_repository_protocol`, `_emit_reverse_finders`, `_emit_route_handler`, + `_emit_m2m_route`, `_emit_tph_m2m_route`, `_emit_tph_list_body`, + `_emit_readonly_reject_handlers`, `_report_list_with_export` and + `ExtractorGenerator._emit_mapper` now take the writer `w` first and write, instead of returning + lines or a string; `_emit_route_handler`'s `create_autoset`, `update_autoset`, `frozen_strip` and + `denied_strip` are `BodyStep` callables, and `RenderHelperGenerator._emit_document` and + `_emit_email` take `header` as `list[str]`. No reference generator calls + `metaobjects.codegen.format.ruff_format` any more (it stays exported). The runtime emitters eject + hands over changed too: delete `codegen/runtime/extract_delegate_emitter.py` and re-eject every + one of `output-parser` and `extractor` you own; delete + `codegen/runtime/extract_schema_emitter.py` and re-eject `trace-helper` (eject never overwrites + an existing `codegen/runtime/` copy, even with `--force`). The module aliases added in 1.1.0 + (`metaobjects.codegen.extract_delegate_emitter` and the others listed under Changed) are removed: + import from `metaobjects.codegen.runtime.*`. +- **Java: the `mustache` generator is removed.** Replace a `MustacheTemplateGenerator` + `` with `com.metaobjects.generator.template.TemplateScopeGenerator` and its args + `templatesDir`, `template`, `scope` and `outputPattern` (docs/features/codegen-concepts.md), and + drop any `metaobjects-codegen-mustache` dependency. An owned copy of the `entity` writers keeps + working; to take the new layout, re-eject, or write through `out()` instead of + `println`/`inc`/`dec`. The deprecated documentation-generator and `codegen-spring` forwarding + shims are gone: call the same names on `CodeGenMetaDataProvider` and `SpringGeneratorSupport` + (under Changed). +- **C#: the obsolete codegen shims are removed.** Use `ValueObjectNames.TypeName` for + `ValueObjectNames.Names`, and `XmlDocBuilder.WriteTo` with the code writer for `AppendTo`, + `Indent` and `Prepend`. +- **TypeScript: `@metaobjectsdev/metadata` no longer exports the metamodel-docs renderers.** + `renderMetamodelDocs`, `renderCoreMetamodelDocs`, `buildMetamodelProvenance` and + `MetamodelProvenance` are replaced by `coreMetamodelDocsPages()` and + `buildMetamodelDocsPages()`; an ejected `codegen/generators/metamodel-docs.ts` that calls + `renderCoreMetamodelDocs` stops compiling: `meta eject metamodel-docs` again. - **C#: an int-backed enum throws on write for a value its `@intValueMap` does not describe**, as the read side already did. A cast such as `(Status)99` used to be stored as the last member's integer. @@ -199,9 +369,11 @@ there is described in full here. This list is where to start. `meta gen` rewrites most generated files once, in layout only**; a hand edit in a generated file meets the three-way merge against a base with the new layout. The Hono routes no longer carry a `// biome-ignore` line above `registerAllRoutes` and each `mount...Routes` function; a - project that lints generated code with Biome adds its own ignore. `formatTs` is still exported from - `@metaobjectsdev/codegen-ts` and now returns its input unchanged, so a generator ejected in 1.2 - keeps loading and running. Run your formatter over the generated tree if you want your layout. + project that lints generated code with Biome adds its own ignore. Expect that first regeneration + to be a large diff that changes formatting only (every generated TypeScript file that Biome had + re-wrapped): it is safe to commit as one change, and a later regeneration is quiet. Run your + formatter over the generated tree if you want your layout. `formatTs` is removed (the item on + owned generators above). - **`drizzle-orm` and `zod` are optional peers of `@metaobjectsdev/codegen-ts`.** Installing the CLI no longer installs the ORM (about 17 MB); only the code `meta gen` writes imports it. A project installs both when it takes a generator that writes code importing them: `meta eject` @@ -222,7 +394,8 @@ there is described in full here. This list is where to start. every port's standard says. An explicit `limit` is still served as asked, and a project that sets `api.pagination` is unchanged. In C# a `limit` or `offset` that is not a non-negative integer is now `400 pagination.invalid_value`, and `limit=0` is a page of zero rows. Check any client that reads a whole - list without a `limit`: + list without a `limit`, the generated TanStack plural list hooks (`use(filter?)`) included, + which send none unless the caller passes one: [default-list-page-of-fifty](docs/features/migrations/default-list-page-of-fifty.md). - **C#: the route helpers are the `MetaObjects.AspNetCore` package.** `MetaObjects.Codegen` and the `dotnet meta` tool no longer carry EF Core or ASP.NET Core, and the helpers (`FilterParser`, @@ -324,7 +497,7 @@ there is described in full here. This list is where to start. - **C#: a bare `?field=value` on a generated list route answers 400** (`filter.bare_field`) where it used to answer every row; write `?filter[field]=value`. The generated list routes also read `?search=` and nested `filter[or]` / `filter[and]` groups. -- **Doc pages move under package directories on the flat default.** A TypeScript project's `docsFile()` and +- **Doc pages move under package directories on the flat default.** A TypeScript project's `apiDocsFile()` pages, and a Java or Kotlin api-docs `layout` left at its default, move on the next generate. Set `layout` to `flat` on the Java or Kotlin generator to keep the old paths. - **TypeScript and C#: the next migrate adds CHECKs to an existing TPH table.** A concrete subtype's enum, @@ -332,6 +505,14 @@ there is described in full here. This list is where to start. `meta migrate` proposes them and `meta verify --db` reports a table that lacks them. - **`meta migrate` reads a Postgres `character(n)` column as itself.** A model that declared a plain `field.string` over one sees a type change until it declares `@dbColumnType: character(n)`. +- **Java and Kotlin prompt renders: a zero or `NaN` number is a falsy section, and a standalone + comment line leaves no blank line.** `{{#count}}…{{/count}}` with `count = 0` used to render its + body in Java (mustache.java treats any non-null number as true) and now drops it, as mustache.js, + C# and Python do; `{{^count}}` now renders for 0. A prompt that prints a count which can be zero + (`{{#away}}{{away}} crossing(s) away{{/away}}`) loses that clause when it is 0, so its bytes and + its prompt-cache prefix change. To keep printing a zero, test a boolean the payload sets + (`{{#hasAway}}`) or print the number outside a section. Run `mvn metaobjects:verify` and + re-snapshot prompt tests after upgrading. - **`metamodelVersion` is `1.3`.** Upgrade every port together. ### Security @@ -450,6 +631,197 @@ there is described in full here. This list is where to start. ### Added +- **`WARN_DERIVED_COMMAND_BYPASSES_DECLARED` in every port's rules gate.** Under + `rules.lifecycle.commands: all`, a transition a declared command claims also gets a derived + command, which makes the same transition without running the declared command's body and asks + for the derived permission name. `meta verify` now warns once per entity and transition, naming + the claiming command and the derived one; `unclaimed` (the default) derives no command for a + claimed transition. Gated by the new `commands-all-declared-bypass` rules-check case. + +- **`agent-docs` writes the agent files natively in C#, Java, Kotlin and Rust, with no Node.** + `dotnet meta agent-docs`, `mvn metaobjects:agent-docs` (Java and Kotlin) and the new + `cargo meta agent-docs` write `.metaobjects/AGENTS.md`, the `metaobjects-*` skills, the + `.metaobjects/.agent-context.json` manifest and the root `AGENTS.md` / `CLAUDE.md` import, byte + for byte what `meta agent-docs` and Python's `metaobjects agent-docs` write. Before, the C# and + Maven commands printed "run `npx meta agent-docs`" and exited 1, and Rust had no command. Each + copies one stack out of the built `agent-context-shipped/` tree it carries (C# and the Maven + plugin embed it at build time; the Rust crate, like the Python wheel, keeps a committed copy + that `scripts/sync-agent-context-shipped.sh` refreshes, renamed from + `sync-python-agent-context.sh`, and the `gates` lane fails when either copy is stale). The + flags are `--server`, `--client`, `--out` and `--no-wire-root` + (`-Dmetaobjects.servers`/`clients`/`outputDirectory`/`wireRoot` on Maven); with none, the + stack the last run recorded, else the port's own language. The re-run rules are the Node + CLI's: an unchanged file is not rewritten, a hand-edited one gets `.new`, an untouched + orphan is pruned. The Maven goal stamps the npm-line version (`8.3.0` writes `v1.3.0` links + and a `1.3.0` manifest), so the staleness check stays quiet after a native run. The `gen` + and `verify` staleness nudge in C# and Java now names the port's own command. Every port's + tests reproduce every `fixtures/agent-context-conformance/` stack, not only their own, so the + corpus is a cross-port gate. The shipped C#, Java and Kotlin skill references now tell an + agent to run the port's command instead of `npx meta agent-docs`; refresh the agent files to + pick that up. + +- **The agent pages in every port, from the docs view.** `requirements.toon`, + `agent/requirements.md` and the model-only `agent/schema.md` are now written by C#, Java, + Kotlin, Python, Rust and TypeScript alike: each port's `requirements` and `agent-docs` + generators build the page data from its own docs view and render the shared + `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what + `fixtures/docs-page-conformance/` pins. A TypeScript project with no dialect now gets the + model-only `agent/schema.md` too (it used to get no schema page); with a dialect it keeps the + physical page. `agent/schema.md` documents the project's own storage in every port: a + dependency's object that `scope.include` does not name is left out of its tables, views, + relationships and enums (Rust loads no dependency, and leaves out a reference node). The + TypeScript physical page used to list an imported table too. `agent/ui.md` stays + TypeScript's. Rust has no requirement ledger of its own yet, so its pages list every + requirement the view carries, an uninherited import's included. + + The docs view gains a `storage` section (`docs/features/docs-view.md`): every table and view + the model stores into, its columns (names from the port's naming helpers, each linked to its + field), keys and foreign keys. The physical facts (SQL types, defaults, indexes, checks, + constraint names and actions) are `null` outside a TypeScript run with a dialect, which fills + them. `explorer.json` carries the new key in every port. + + **Retired: the human `requirements.md` page.** The `requirements` generator writes only + `requirements.toon`; people read the ledger in the explorer (`docs-site`), and agents read it + embedded in `agent/requirements.md`. + + **The always-on agent file points at the agent pages, only when they exist.** `meta init` + (and `--refresh-docs`) and every port's `agent-docs` command (`meta`, `metaobjects`, + `dotnet meta`, `mvn metaobjects:`, `cargo meta`) now add a "Pages + generated for this project" section to `.metaobjects/AGENTS.md`, naming each agent page the + project's last `gen` wrote (read from the committed `.metaobjects/.gen-state/.hashes/`) and + when to read it. A project that wires none of them gets the file unchanged. Refresh the agent + files after wiring `agent-docs`, `api-docs` or `requirements` for the first time. + +- **docs-site: the model explorer is one browser app.** `docsSiteFile()` now writes the + explorer as a few files (a shell, the app, the theme, Cytoscape and three data files: + `explorer.json`, `explorer-model.js`, `explorer-stamp.js`) in place of a page per screen. + The app draws every page when it is visited, with the same page code and templates, so each + page is byte-for-byte the one the static site wrote. It runs from `file://` with no server, + addresses each page as `index.html#/`, and follows the model while it is open: it polls + the stamp file about once a second and draws the current page again when `meta gen` rewrites + the model. Cytoscape 3.30.2 (MIT) ships with the site, so the graphs draw offline and the + CDN notice is gone. `docsSiteFile({ output: "static" })` (and `generateExplorerSite({ output: + "static" })`) writes the earlier page-per-screen site from the same code, for publishing + without scripts or for Pagefind; `assetBase` now applies to that export only, which given one + loads Cytoscape from it and ships no copy. The app's files live once at `explorer-app/` and + in every port's package (`scripts/sync-explorer-app.sh`, gated by `explorer app copies`); + the other ports' docs-site generators are still to write them. Generated-output change: the + next `meta gen` replaces the explorer's pages with the app's files, and `meta verify + --codegen` holds the new files to the model as before. + If you ejected the theme on a 1.3.0 candidate, your `codegen/docs-site/assets/explorer.js` + predates the app, which calls `window.MO_THEME` each time it draws a page: without that hook + search, the theme toggle and the graphs do nothing. Copy it again with `meta eject docs-site + --force` and carry your edits into the new copy (the app also needs its `window.MO_APP` link, + query and listener hooks, so adding the one line is not enough). + +- **docs-site: a 3D model map.** The explorer's map has a **View** control that switches + between the flat map and a 3D one drawn from the same nodes, edges, slice and colouring + (`#/map.html?view=3d`); click a node for the side panel and again to open its page. The 3D + library, 3d-force-graph 1.77.0 (MIT, bundling three.js; the licences of everything it bundles + head the file), ships with the site as `assets/3d-force-graph.min.js` and loads only when a + reader first chooses 3D, so it works offline and no other page pays for its size. A static + export given an `assetBase` loads it from the mirror instead. An owned + `explorer-map.html.mustache` without the control simply has no 3D mode. Generated-output + change — regenerate to pick it up; three-way merge preserves hand edits. + +- **runtime-ts: `GET {apiPrefix}/_meta/docs` serves the loaded model's docs view, and the + explorer follows it.** New `mountMetaDocsRoute` (Fastify) and `mountMetaDocsRouteHono` mount + it beside `/_meta`, opt-in and guarded the same way, with `META_DOCS_ROUTE_PATH` and + `metaDocsJson(root, { routes })` for other hosts. The response carries an ETag and answers a + matching `If-None-Match` with `304`; `allowOrigin` opts in to cross-origin reads. Open the + explorer app as `index.html?source=` and it reads the running application's model + instead of the generated file, once a second, drawing the open page again when the + application restarts on a changed model. The route's shape is a cross-port contract + (`docs/features/metadata-api.md`); the other ports serve it once they have their docs view + builders. + +- **C# and Python: the model explorer with no Node.** Both ports build the docs view from their + loaded model (`MetaObjects.DocsView` in C#, `metaobjects.docs_view` in Python), byte for byte + what TypeScript builds for every `fixtures/explorer-conformance/` case. A new `docs-site` + generator in each registry (`DocsSiteGenerator` in `codegen/Generators.cs`; `docs-site` in a + Python target's `generators`) writes `explorer.json`, the explorer app, `explorer-model.js` + and `explorer-stamp.js`. Each object lists the files generated for it: this run's (the runner + runs the generator after every other one) and the committed manifest's outside the directories + the run's orphan sweep clears, so `verify --codegen` renders what `gen` wrote. Options name a + `verify --format json` payload and a routes file. The running application can serve the same + view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.MetaDocs(root)` (C#) and `meta_docs(root)` + (Python) build it once and carry its ETag; the host mounts it as it mounts `/_meta`. + C# and Python provenance now names a generator by its registry name (`entity`, + `filter-allowlist`, `routes`), as TypeScript and the JVM do. + +- **Java and Kotlin: the model explorer with no Node.** The JVM builds the docs view from its + loaded model (`com.metaobjects.docsview.DocsView`), byte for byte what TypeScript builds for + every `fixtures/explorer-conformance/` case. A new `docs-site` generator + (`com.metaobjects.generator.DocsSiteGenerator`, in both the Java and Kotlin registries) writes + `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js`; each object + lists the files generated for it: this execution's (it builds the site after every other + generator it runs) and the committed manifest's for the module's other executions, so + `metaobjects:verify` renders what `generate` wrote. Optional args name a + `verify --format json` payload (`verifyFile`) and the routes (`routesFile`). The running + application can serve the same view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.docs(root)` + builds it once and carries its ETag, and the host mounts it as it mounts `/_meta`. The static + export stays TypeScript's. + +- **Rust: the model explorer with no Node.** The Rust port builds the docs view from its loaded + model (`metaobjects::docs_view::build`), byte for byte what TypeScript builds for every + `fixtures/explorer-conformance/` case. A new opt-in `docs-site` generator writes + `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js` under + `site/`. It reads prompt texts from the metadata directories, `templates/` and a `prompts` + directory, and takes `subDir`, `title`, `stamp`, `verifyFile` and `routesFile` as options. + Each node lists the files generated for it: this run's (the engine runs the site after every + other generator) and the committed manifest's outside the run, so `cargo meta verify` renders + what `gen` wrote. The site builder is engine, as in every port: `cargo meta eject docs-site` + refuses, `gen --list` marks it `[package-only]`, and an owned theme in `codegen/docs-site/` + replaces the shipped one. The app files are a canonical copy in the crate + (`metaobjects-codegen/explorer-app/`, held to the root `explorer-app/` by the + `explorer app copies` gate) and ship in the published package. The running application can serve + the same view at `{apiPrefix}/_meta/docs`: `metaobjects::meta_endpoint::docs` builds it once and + carries its ETag, and the host mounts it as it mounts `/_meta` (`meta_endpoint::meta_json`, + new in Rust too). + + Rust codegen now also records which node each generated file came from, `{ "hash", + "generatedBy", "sourceNode" }` in the hash manifest, held to the shared `provenance` vector in + `fixtures/codegen-skip-conformance/manifests.json`. A file rendered for no single node, such as + a shared `meta_*` crate's, keeps the plain hash. + +- **C#, Java and Python codegen record which node each generated file came from.** After a write + run, the hash manifest entry of a per-object file names its generator and the node's resolution + key, `{ "hash", "generatedBy", "sourceNode" }` (after the JVM's `generator` and `outputDir`), + exactly as TypeScript already wrote it. A docs view built from any of these ports' manifests now + lists each node's generated files, so the explorer's "generated files" panel is filled. A file + rendered from the whole model or a package keeps the plain hash. The shared `provenance` vector in + `fixtures/codegen-skip-conformance/manifests.json` holds all four ports to the same entries. + +- **metamodel-docs: the vocabulary reference pages are shared Mustache templates, and every + port writes them.** `INDEX.md`, `providers.md` and the `types/.md` pages are now the + `templates/metamodel/` template set rendered over page data each port builds from its own + registry vocabulary manifest and its embedded provider definitions. C#, Java, Kotlin, Python + and Rust gain a `metamodel-docs` generator; every port is held to `fixtures/metamodel-docs/` + (the page data under `data/` and the bytes under `expected/`). A project can override a + page by placing a `templates/metamodel/.mustache` of its own. The TypeScript pages are + unchanged except one fix: `index.lookup` was missing its owning provider + (`metaobjects-core-types`) and the provider of its `@fields`, because the index definition + was left out of the provenance list. + +- **Registry manifest: a type can carry `ports`** (#549), the type-level twin of the attr-level + marker, for vocabulary that is language-specific by nature and never pending. The 13 generic + `view.*` controls move from `implementedIn: ["typescript"]` to `ports: ["typescript"]` (UI + vocabulary of the TypeScript client tier, which serves every backend), and `@object` moves from + `implementedIn: ["java"]` to `ports: ["java", "kotlin"]` (the JVM runtime). The rc.21 view + vocabulary (`origin.function`, `@union`, `@unionAll`, `@grain`, `@grainOrdinal`) is now + `implementedIn: ["csharp", "python", "typescript"]`, since the Python loader validates it; Java + and Kotlin remain pending on `origin.function`'s `@args`, `@params` and `@returns`. Every port + still registers and loads all of it strictly. The metamodel docs replace "Implemented in: … so + far" with "Language-specific to: …" on those pages; `meta types` marks ts-scoped types + `[ts-only]`, and the deprecated `tsOnly` field stays true for them. + +- **Conformance: the `key-types/` api-contract sub-corpus.** Generated CRUD for a client-assigned + `field.uuid`, a natural `field.string` and a `field.int` primary key (list, get, 404, create, + patch and delete), run in the generated lane of every port. It found the TypeScript `id`-only + CRUD mounts and a C# defect: a `field.uuid` key's generated routes did not compile (no + `using System;`), and the key type is now spelled `global::System.Guid` in the item routes and + in the M:N traversal routes over uuid junction keys. + - **cli: `meta init --with-services` and the `unenforced-lifecycle` advisory (ADR-0067 §6, §8).** `init` still writes an empty generator list; `--with-services` writes the recommended service list instead (`entityFile()`, `rulesNamesFile()`, `contractTypes()`, `serviceFile()`, @@ -460,12 +832,13 @@ there is described in full here. This list is where to start. it. - **codegen-ts: a generator declares what it provides in one place.** `provides` on a `Generator` (`entityModule`, `queries`, `names`, `reportExport`, `routes` with its framework, `expose` and - `filter`, `uiTier`, `modelDocs`, `apiDocs`) replaces the nine single-purpose markers + `filter`, `uiTier`, `apiDocs`) replaces the nine single-purpose markers (`emitsEntityModule`, `emitsQueries`, `emitsNames`, `emitsReportExport`, `emitsHonoRoutes`, `mountsRoutes`, `emitsUiTier`, `emitsModelDocs`, `emitsApiDocs`). The runner, the docs generators and the gates read it through one function, `providesOf`, so a generator of your own - under any name is seen as the stock one is. The old markers are deprecated and still read, so an - owned copy that sets them keeps working; a re-ejected copy declares `provides`. + under any name is seen as the stock one is. The old markers are removed: `meta gen` refuses a + generator that still sets one, naming its `provides` replacement, so an owned copy ejected in 1.2 + or earlier is re-ejected or edited to declare `provides` (under "Upgrading from 1.2.0"). - **C#: the route helpers are their own package, `MetaObjects.AspNetCore`, and `MetaObjects.Codegen` and the `dotnet meta` tool no longer carry EF Core.** `FilterParser`, `FilterParseResult`, `FilterPredicate`, `EfCoreFilterDispatch`, `ValueObjectValidator`, `ConstraintErrors`, @@ -1716,8 +2089,9 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru (ADR-0063). A generator says what a line contains, and the writer decides where it sits. It builds the file in memory with no formatter. It collects imports while the body is written, treats blank lines as requests that collapse, and prints a list on one line when the line fits - 120 columns, otherwise one item per line. `TsWriter` accepts ts-poet `Code` fragments and - collects their `imp()` imports, so a generator can move to it one function at a time. The + 120 columns, otherwise one item per line. Imports travel with the writer fragments + (`frag`, `joinFrags`, `importName`, `importType`); the ts-poet `Code` bridge it first carried was + removed later in this release (see Changed, "the vendored ts-poet printer is removed"). The writer is exported from the package root and from `@metaobjectsdev/codegen-ts/engine`, so an owned (ejected) generator can use it too. Both classes are built to be extended: every method is public or protected, so a subclass can override one step, such as import order, @@ -2139,6 +2513,154 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru ### Changed +- **Java and Kotlin: Mustache treats a zero or `NaN` number as a falsy section.** mustache.java + treats any non-null `Number` as true, so `{{#count}}…{{/count}}` with `count = 0` rendered its + body in Java and dropped it in TypeScript, C# and Python. `com.metaobjects.render.Renderer` now + treats `0`, `0.0`, a zero `BigDecimal` and `NaN` as false (`{{^count}}` renders for them), matching + mustache.js. A Java or Kotlin prompt body with a numeric section changes bytes, and its prompt-cache + prefix, when the number is zero; see "Upgrading from 1.2.0". + +- **`agent/schema.md` names `meta migrate` to a project that has not set `migrate.dialect`.** + The page told such a project to write migrations with "the project's migration tool", which + steered an agent away from `meta migrate` in a project that runs it without the setting. It now + says to write the migration with `meta migrate` when the project uses it, otherwise with the + project's own tool. Generated-output change — regenerate to pick it up; three-way merge + preserves hand edits. + +- **Breaking — the vendored ts-poet printer is removed; TypeScript codegen is writer-only.** + `@metaobjectsdev/codegen-ts` no longer exports `code`, `imp`, `joinCode`, `Code` or `Import`, + and `TsWriter` no longer accepts a `Code`. Use the writer fragments: `frag`, `joinFrags`, + `importName`, `importType`, `Frag` and `TsImport` (`writer/ts-fragment.ts`). The queries + template's `render*Fn` and `schemaInputType` forms are removed, and the config loader no longer + rewrites a `ts-poet` import. Generator copies ejected in 1.2 that use any of these no longer + load: re-eject them (`meta eject --force`). The `contract-types` output changes layout + only (one statement per line, double-quoted imports in the writer's order); the requirement-test + scaffolds and the client directive are now written through the writer, byte for byte as before. + `api-doc-render.ts` moved onto the code writer with unchanged output. + +- **Breaking — `formatTs` and the Biome owned-copy comparison are removed (TypeScript).** The + no-op `formatTs` export, kept so an owned 1.2 generator copy still loaded, is gone: generation + runs no formatter, and a copy that wants one calls its own. `meta eject`'s owned-copy report no + longer loads Biome's WebAssembly build: it compares the copy and the reference line by line, + trimmed, ignoring trailing commas, blank lines and import order. A copy re-wrapped by your own + formatter (lines joined or split) now reads `differs` where it read `reformatted`. + `@metaobjectsdev/cli` drops its `@biomejs/js-api` and `@biomejs/wasm-nodejs` dependencies. + +- **Breaking — the legacy generator markers are removed, and an owned 1.2 copy is refused + (TypeScript).** `emitsEntityModule`, `emitsQueries`, `emitsNames`, `emitsReportExport`, + `emitsUiTier`, `emitsHonoRoutes`, `mountsRoutes`, `emitsApiDocs` and `emitsModelDocs` (and + `provides.modelDocs`) are gone from `Generator`; the `provides` declaration (ADR-0034 + Amendment 12) is the only way to say what a generator writes. `meta gen` now refuses a + generator that still sets one, naming every such generator in one run with each marker and its + `provides` replacement, instead of reading it. The name-based fallbacks that treated a copy named `queries-file`, `entity-file`, + `routes-file` or a UI generator's name as providing its tier are removed with them, as is + `UI_TIER_GENERATOR_NAMES`. A copy that carries a shipped generator's name and declares no + `provides` at all (one ejected before the markers) still runs, with one warning naming the + declaration the shipped generator makes (`SHIPPED_PROVIDES_BY_NAME`). Generator + copies ejected in 1.2 or earlier no longer load: re-eject them (`meta eject --force`) or + replace the markers with `provides` by hand. + +- **Breaking — the classic docs site is removed (TypeScript).** `docsSiteFile({ site: "classic" })` + now throws and points to the explorer (`docsSiteFile()`); an owned classic theme under + `codegen/docs-site/` is refused with an instruction to delete it and re-run + `meta eject docs-site`. `@metaobjectsdev/docs-site` no longer exports `generateSite`, + `DEFAULT_ASSET_BASE`, `SiteOptions`, `SiteResult`, `CLASSIC_TEMPLATE_NAMES` or + `CLASSIC_ASSET_NAMES`, and `meta eject docs-site` copies the explorer theme only. The + explorer's output is unchanged. + +- **Breaking — the docs Markdown generator is removed (TypeScript).** `docsFile()` and the + stable name `"docs"` (a Markdown page per object, the `README.md` overview with the ER diagram, + and the `apiSurfaces` option) are gone. The model explorer (`docsSiteFile()`, `"docs-site"`) is + the model's documentation for people, and `agentDocsFile()` (`"agent-docs"`) for a coding agent. + A config that still lists `"docs"` or imports `docsFile` makes `meta gen` fail with a message + that names the removal and the replacement; delete the pages it wrote (`README.md` and one + `.md` per object under the docs target). `meta init --with-docs` now wires + `docsSiteFile()` and `apiDocsFile()`. `apiDocsFile({ modelSurface })` now defaults to `false` + (it used to follow whether `docsFile()` ran); `modelBaseUrl` is unchanged. The engine exports + `buildEntityDocData`, `buildTemplateDocData`, `renderMermaidErBlock`, the `EntityDocData` / + `TemplateDocData` types and `DocsApiSurface` / `ApiSurface` are removed with it. The metamodel + index page (every port) now says your entities are documented by the model explorer: a + one-sentence documentation change in `meta gen` output for projects that list `metamodel-docs`. + +- **Python: every generator writes through the code writer, and codegen no longer runs `ruff`** + (ADR-0063). The router and the last nine emitters (extractor, output parser, trace helper, + render helper, names, requirement tests, API docs and the extract delegate and schema emitters) + now lay out their files with `PyWriter`, so generated bytes no longer depend on whether `ruff` is + installed or on its version. The output changes in layout only: a line longer than 88 columns + breaks its last bracketed list, and imports are grouped `__future__`, absolute, then relative, + each in code-point order. Checked against a capture of every emitted file: same syntax tree, + comments and docstrings. One fix rides along: an unresolved `@objectRef` mapper argument used + to put its comma inside the trailing comment, which was a syntax error; it is now + `x=None, # unresolved @objectRef`. Generated-output change — regenerate to pick it up; + three-way merge preserves hand edits. + + Removed: the deprecated module aliases added in 1.1.0. An import of an old path now fails with + `ImportError` (or its subclass `ModuleNotFoundError`, depending on the import form); import + from the new path instead: + `metaobjects.codegen.extract_delegate_emitter` is `metaobjects.codegen.runtime.extract_delegate_emitter`, + `metaobjects.codegen.extract_schema_emitter` is `metaobjects.codegen.runtime.extract_schema_emitter`, + `metaobjects.codegen.fr010_field_mapping` is `metaobjects.codegen.runtime.fr010_field_mapping`, + `metaobjects.codegen.output_format_spec_emitter` is `metaobjects.codegen.runtime.output_format_spec_emitter`, + `metaobjects.codegen.generators.fr019_shared_enum` is `metaobjects.codegen.runtime.fr019_shared_enum`, + `metaobjects.codegen.generators.m2m_codegen` is `metaobjects.codegen.runtime.m2m_codegen`, + `metaobjects.apidocs.api_model` is `metaobjects.codegen.runtime.api_docs_model`, + `metaobjects.apidocs.builder` is `metaobjects.codegen.runtime.api_docs_builder`, + `metaobjects.apidocs.renderer` is `metaobjects.codegen.runtime.api_docs_renderer` and + `metaobjects.apidocs.paths` is `metaobjects.codegen.runtime.api_docs_paths`. The + `metaobjects.apidocs` package and `metaobjects.apidocs.naming` stay. An owned copy ejected + before 1.1.0 that still imports an old path needs its imports changed, or re-eject it. For + `output-parser`, changing the imports is not enough, because that copy calls the removed + `nested_mirror_dataclasses`, `nested_mappers` and `delegate_helpers`: re-eject it, or move it to + `write_nested_mirror_dataclasses`, `write_nested_mappers` and `write_delegate_helpers`. + +- **Java: the `entity` generator writes through the Java code writer, and the `mustache` + generator is removed** (ADR-0063). `JavaObjectCodeGenerator`'s four writers + (`BaseObjectCodeWriter`, `JavaCodeWriter`, `PojoAwareCodeWriter`, `ValueObjectCodeWriter`) now + write lines and blocks on `JavaWriter` instead of printing through an indentor. The output + changes in layout only: no trailing whitespace, no blank line straight after a class opens or + before it closes, and a one-sentence Javadoc fits on one line. Checked against a capture of + the interface, `pojoAware` and `valueObject` flavors over the fitness corpus: identical with + whitespace ignored, apart from that one Javadoc. The layout ratchet gains an `indented-print` + rule (`println(true, ...)`), the call that typed indentation without a literal and let this + family go unseen. Generated-output change — regenerate to pick it up; three-way merge + preserves hand edits. + + The deprecated `mustache` generator (`MustacheTemplateGenerator`) and its module + `metaobjects-codegen-mustache` are removed; `template` (`TemplateScopeGenerator`, in + `codegen-base`) replaces them. A pom that still names `MustacheTemplateGenerator` fails the build + with a `ClassNotFoundException`. + + The deprecated shims in the documentation generators are removed too: the attribute-name + constants and `register*Attributes` methods on `MetaDataAIDocumentationGenerator` and + `MetaDataFileJsonSchemaGenerator` (use the same names on `CodeGenMetaDataProvider`), + `MetaDataFileSchemaWriter.addConstraintFile` (a no-op since registry-based discovery), and the + old `SingleHtmlDirectGeneratorBase.writeHtml(MetaDataHtmlDocumentationWriter)` hook (override + `writeHtml(HtmlDirectWriter)`). + + So are the 1.0.x forwarding shims in `codegen-spring`. The static field and annotation helpers + on `SpringDtoGenerator` (`settableFields`, `scalarFields`, `dtoComponentFields`, + `valueObjectJsonbFields`, `valueObjectMapFields`, `isValueObjectJsonbField`, `componentType`, + `isRequired`, `originGuaranteedNonNull`, `validationAnnotations`, `sizeAnnotation`, `attrBool`, + `attrInt`, `hasValidator`, `escapeJavaString`) and on `SpringRepositoryGenerator` + (`m2mFinderName`, `m2mFinderNameForSubtype`, `targetSubtypeParam`) are gone: call the same name + on `SpringGeneratorSupport`, and `SpringGeneratorSupport.repositoryAppliesTo` for + `SpringRepositoryGenerator.appliesTo`. The `AutoSetSupport` selectors `stampFields`, + `onUpdateFields`, `hasAutoSetFields` and `hasOnUpdateFields` move the same way, to + `SpringGeneratorSupport`. + +- **C#: the obsolete codegen shims are removed.** `ValueObjectNames.Names` (marked `[Obsolete]`; + use `ValueObjectNames.TypeName`) and the string-building forms of `XmlDocBuilder` (`AppendTo`, + `Indent`, `Prepend`; use `WriteTo` with the code writer) are gone. Generated output is unchanged. + +- **The `meta` CLI installs 12 MB smaller** (34.6 MB, from 46.6 MB): it no longer depends on + `@biomejs/js-api` and `@biomejs/wasm-nodejs`, and `docs-site` no longer depends on `yaml`. + +- **Repository: Bun 1.3.14 is the declared package manager.** The root `package.json` now + declares `bun@1.3.14`, the version every workflow pins, in place of 1.3.8 (which segfaults on + exit). Rebuilding or checking the explorer app (`server/typescript/packages/docs-site/scripts/build-app.ts`, + the `explorer app copies` gate and its unit test) requires that exact version, because the + committed bundle is minified and minified output follows the Bun version; any other Bun stops + with an error naming 1.3.14. - **The agent pages sort in code-unit order.** `agent/requirements.md` (its node index and statements) and `agent/schema.md` (its tables and views) sorted names with `localeCompare`, whose collation differs between machines and could not be matched exactly by another port. @@ -2553,9 +3075,9 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru `docsSiteFile()` gets a different site under `site/` on its next `meta gen`, with new page paths (object pages move under `model/`); `meta gen` removes the old pages it wrote, as it does any untouched generated file it no longer emits, and `meta verify --codegen` reports - drift until it has run. Pass `docsSiteFile({ site: "classic" })` to keep the earlier - site byte for byte. A project that ejected the classic theme gets a warning and the packaged - explorer theme; run `meta eject docs-site` again to copy the explorer's files. + drift until it has run. The classic site is removed in this release (see Changed, "the classic + docs site is removed"): `docsSiteFile({ site: "classic" })` throws, and an owned classic theme + is refused; delete it and run `meta eject docs-site` again to copy the explorer's files. - **Python and Java report a missing provider's errors in the same order as the other ports.** When a file holds both an unknown subtype and unknown attributes, Python used to drop the whole @@ -2797,18 +3319,12 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru - **`@metaobjectsdev/cli` no longer installs `dprint-node`.** The TypeScript generators printed code with `ts-poet`, which loads `dprint-node` on import, and dprint-node ships all seven of its platform binaries in one package (24 MB, of which a machine runs one). `codegen-ts` now - vendors the part of ts-poet the generators use (`src/poet.ts`, Apache-2.0, licence in - `LICENSE.ts-poet`) and runs the same dprint TypeScript plugin as WebAssembly - (`@dprint/typescript`, pinned to 0.87.1, the version dprint-node 1.0.8 compiles in, 5 MB) with - ts-poet's configuration, so generated code is byte-identical: every codegen golden and - conformance fixture is unchanged. `codegen-ts-react`, `codegen-ts-tanstack` and - `codegen-ts-angular` drop their `ts-poet` dependency and import the printer from - `@metaobjectsdev/codegen-ts/engine`, which an ejected template also uses. A bare `ts-poet` - import in an older owned generator is still pointed at that entry by `meta gen`, which - carries `code`, `imp`, `joinCode`, `Import` and the `Code` type; ts-poet's `def`, `literalOf`, - `arrayOf`, `asOneline`, `Import.fromMaybeString`, `saveFiles`, `conditionalOutput` and its - `toString` import options are not carried over, so an owned generator that imports one of them - no longer loads. A fresh npm + writes code with its own code writer (ADR-0063; the vendored ts-poet printer and the dprint + WebAssembly formatter this entry first carried were removed later in this release, see Changed, + "the vendored ts-poet printer is removed"). `codegen-ts-react`, `codegen-ts-tanstack` and + `codegen-ts-angular` drop their `ts-poet` dependency. A `ts-poet` import in an owned generator + no longer loads: `code`, `imp`, `joinCode`, `Import` and `Code` are not carried over in any + form; see "Upgrading from 1.2.0". A fresh npm install of the CLI drops from 151 MB (134,641,989 bytes) to 133 MB (115,302,944 bytes) of `node_modules`. `scripts/check-peer-ranges.ts` now also fails a publishable package that requires `dprint-node`, `ts-poet` or any `@types/*` package through `dependencies`, @@ -3035,6 +3551,148 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru ### Fixed +- **TypeScript: the service, queries and CRUD-route generators no longer import an entity module + nobody wrote.** When the filter of `serviceFile()`, `serviceRoutesFile()`, + `serviceRoutesHonoFile()`, `queriesFile()`, `routesFile()` or `routesFileHono()` admitted an + object (a projection, typically) that `entityFile()`'s filter left out, the output imported a + module that did not exist (`TS2307`). The run now knows which objects the entity-module + generator emits, and these generators skip the rest with a warning naming the object and both + remedies (widen `entityFile()`'s filter, or narrow the other generator's). For the queries and + routes the runner applies it to any generator declaring `provides.queries` or `provides.routes`, + so an owned copy gets it without a re-eject; an owned service copy picks it up when re-ejected. + +- **The first `meta gen` over a 1.2 tree no longer warns that `.gen-state/.hashes` is + git-ignored.** That run migrates the hash manifest and rewrites `.metaobjects/.gitignore` to + un-ignore the new directory, but the advisory was asked before the rewrite and reported the rule + the run had just removed. It is asked after the run's writes, so it fires only for a rule the run + does not own (one in the root `.gitignore`, say). + +- **Filtering generators by package is documented.** `obj.package` is the package a node declares + itself, so it is `undefined` for every object in a file whose package is on `"metadata.root"`, + and `filter: (e) => e.package === "acme::tasks"` matched nothing. Filter on + `effectivePackage(e)` (`@metaobjectsdev/codegen-ts`, or `effectivePackageOf` from + `@metaobjectsdev/metadata`), which resolves the file's package too; the generator recipe and the + getter's doc say so. + +- **`meta gen` trusts the committed `.hashes.json` over a stale ignored `.hashes/`** (every port). + The scaffold's 1.2 `.gitignore` ignores `.gen-state/.hashes/`, so a directory written by an + earlier 1.3 run (another checkout, a candidate you tried and reset) survives a reset, a clean and + a branch switch beside the committed `.hashes.json`. The reader merged it on top, so every file + the committed manifest vouched for read as hand-edited: `gen` reported "N merged", kept the old + output and exited 0, and `verify --codegen` failed only the names artifacts. While `.hashes.json` + is present it is now the whole manifest, and the migrating write replaces the stale files + (ADR-0064 §2, corrected). + +- **`gen` and `verify` refuse generated output containing `[object Object]`, in every port.** A + generator that turns an object into text, most often an owned TypeScript generator putting an + engine `Frag` in a template literal where ts-poet's `Code` used to print itself, writes + `[object Object]` where code belongs; one estate's TypeScript generation wrote it into 236 + files, and since the text often still compiles, gen, the zero-write regen and the drift gate all + passed. `meta gen`/`meta verify --codegen` (TypeScript), `metaobjects gen`/`verify` (Python), + `dotnet meta gen`/`verify` (C#), `mvn metaobjects:generate`/`:verify` (Java and Kotlin) and the + Rust `run`/`verify` now refuse such output by file and generator + (`ERR_GEN_STRINGIFIED_OBJECT`) before writing or comparing it. The exact quoted string literal + `"[object Object]"` is allowed, since it is code on purpose (the Rust port's emitted + query-string encoder mirrors JavaScript's), and so is the marker when a string value in the + model carries it (an `@description` or a requirement counterexample naming the symptom, copied + into a comment or a docs page). In TypeScript a `Frag` also refuses to become a + string (`ERR_FRAG_AS_TEXT`), so the stack points at the line that did it. + +- **`EntityFileWriter` is exported from `@metaobjectsdev/codegen-ts/engine`.** It was reachable only + through the `templates/*` subpaths, so an owned entity generator moving onto the writer could + not subclass it from the engine entry. + +- **`meta gen` and `meta verify --codegen` refuse emitted TypeScript that does not parse.** Gen, + the zero-write regen and the drift gate compare text, so a generator that emitted a file + declaring `import { z } from "zod"` twice (an owned 1.2 entity composer joining the engine's + fragments with ts-poet's `joinCode`) passed all three and the adopter's build was the first to + object. Every emitted `.ts`, `.tsx`, `.mts` and `.cts` file is now parsed before anything is + written, with the parser `jiti` already carries for the config file, and a file that fails is + named with its generator, line and message; nothing from the run is written. The refusal of a + generator carrying a marker 1.3.0 removed now names every such generator at once instead of + one per run. + +- **Python: `metaobjects gen` and `metaobjects verify` refuse generated Python that does not + compile; the code writer refuses indented text in every port.** An `EntityModelGenerator` subclass written to the 1.2 hook contract returned members + carrying their own four-space indent; the code writer indents members itself, so those members + sat one level deeper than the rest and the module raised `IndentationError` on import, while + `gen` exited 0 and `verify --codegen` reported the tree in sync. The entity generator now refuses + such a member with `ERR_WRITER_LEADING_WHITESPACE`, naming the subclass and the contract, and + every emitted `.py` file (a template-spec output named `.py` included) is compiled in memory + before it is written or compared: one that does not compile fails the target, names the file, + the line and the generator, and nothing from that target is written. Every `verify` mode that + includes codegen compiles it; `verify --templates` alone is the prompt-template gate and does + not. + +- **`meta verify --db` names a `SELECT *` view's drift.** A hand-written `@sql` view that selects + `*` or `alias.*` keeps the column list Postgres expanded when the view was created, so after a + migration added a column to its base table, every database built from the chain holds the + narrow expansion, and `verify --db` (which builds a fresh shadow database) reported it as a drop + plus a create that offline `meta migrate` never planned. `verify --db` now shows a changed view as one + `~` entry, and when the declared body selects `*` and the two definitions first differ in the + select list, it names the likely cause: Postgres expanded `*` when the view was created. To + clear the drift, list the view's columns explicitly, or drop and recreate the view by hand. + Offline `meta migrate` plans nothing for this drift; `meta migrate --from-db` compares through + the shadow database and can plan a replace, or a drop and create, so review that plan before + `--apply`. + +- **Prerelease tooling.** `tools/prerelease/detect-prerelease-pins.sh` (run by + `prerelease-link.sh unlink`) no longer prints the private registry's host in the lockfile lines + it reports. `unlink` without `--to` restores the pins the project had before `link`, recorded by + `link` outside the work tree, instead of the latest public release, and its reconcile hint is + one command per lockfile directory (`(cd sub && bun install)`) instead of `bun install npm + install`. `estate-run.sh` restores the ignored `.metaobjects/.gen-state` files a candidate wrote, + which used to survive the restore and make the next run read the candidate's hash manifest, and + no longer reports unlink's lockfile check as a failure. On a Java, Python or C# estate it now + installs every TypeScript package the link repinned, one install per lockfile root, before the + port's own install, so a frozen-lockfile `bun install` inside the JVM build no longer fails on the + repin. A full candidate (`--only all`) refuses + to cut while `changelog.d/` holds fragments beside a prepared release section. + +- **TypeScript: generated CRUD routes address a key not named `id`.** `mountCrudRoutes` (Fastify + and Hono) took the primary key to be the `id` column, so an entity keyed on a natural `code` + or an int `rank` answered every item route (`GET`/`PATCH`/`PUT`/`DELETE /:id`, and the create + re-read on MySQL) with a 500. The mounts take an `idColumn` option, and the generated routes + pass it when the key field has another name. Generated-output change for such entities only: + one `idColumn: "",` line in the mount call; regenerate to pick it up. + +- **Java and Kotlin: generated controllers serve uuid, string and int primary keys**, gated by the + shared `key-types` api-contract corpus in both generated lanes. The Kotlin controller now writes + an assigned primary key (no `@generation`, no `@default`) from the request body on create, + where it skipped the column and the insert failed `NOT NULL`, and a TPH subtype create that + omits it is a 400 (`invalid_type` on the key); increment and generated-uuid keys are unchanged. Generated-output change for assigned-key entities only. + +- **Java: the entity generator qualifies same-named types from two packages.** A file referencing + two value objects named alike in different metadata packages writes each fully qualified, where + it refused the model with `ERR_WRITER_IMPORT_CONFLICT`. Java, Kotlin and Python now run the + `xpkg-value-object-refs` codegen corpus. `KotlinApiDocsRenderer` moved onto `KotlinWriter`, + with byte-identical output. + +- **Python: the loader enforces the rc.21 view vocabulary.** `origin.function` signature and + identifier rules, dotted-path references in `origin.computed` and in an `origin.first` + `@filter`, a scalar `origin.aggregate` read from a computed field, passthrough from a `@grain` + value object and derived-field cycle detection now load and fail as they do in TypeScript and + C#. The two ledgered fixtures (`error-origin-function-free-sql`, + `projection-view-vocabulary-rc21`) pass, and the Python expected-failures ledger is empty. A + bare `@from` or base head on a projection now resolves in the file's default package. The + `xpkg-value-object-refs` codegen corpus and the generated `key-types` api-contract lane now run + in Python. + +- **The explorer app's bundle builds the same bytes every time.** `explorer-app/assets/explorer-app.js` + is now minified for whitespace and syntax only, and keeps its identifiers' names. Bun's choice of + short names was not stable between builds of unchanged sources, so the check that the committed + bundle is what the sources build failed at random. The bundle grows from about 95 KB to about + 120 KB. Every port's copy is refreshed, so the docs site's `assets/explorer-app.js` changes and + nothing else does. Generated-output change — regenerate to pick it up; three-way merge preserves + hand edits. + +- **CI: the Rust publish dry-run no longer verifies against stale source.** `cargo publish + --workspace` unpacks the crates it depends on from its temporary overlay registry into a + directory fixed per checkout, and never unpacks them again while the version is unchanged, so a + machine that had run the gate before a new module landed compiled the old `metaobjects-1.3.0` + and failed with "could not find `metamodel_docs`". The gate now first clears unpacked copies of + the workspace's own crates that differ from the tree + (`scripts/rust-clear-stale-publish-sources.sh`). - **codegen-ts-angular: the generated form binds its controls.** Each control in `.form.component.ts` read `[formControlName]=""email""`, a binding whose quoted expression was cut short by the attribute's own quotes, so Angular bound no control. It now @@ -3275,8 +3933,10 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru literal ("invalid input syntax for type uuid"); `coerceIdForColumn` now rejects it, so GET, PATCH and DELETE answer 400 `{"error":"invalid_id"}` as a malformed numeric id already did. A `field.uuid` in the generated insert and update Zod schemas now checks the 8-4-4-4-12 shape, so - a malformed uuid foreign key in a POST or PATCH body answers 400 `validation`. SQLite stores a - uuid as text, so none of this showed there; a new integration test runs the stock + a malformed uuid foreign key in a POST or PATCH body answers 400 `validation`. The body check + is in the Zod schema, so it applies on every dialect: on SQLite and D1, which store a uuid as + text and never refused a malformed one, a body value that is not 8-4-4-4-12 is a new 400 (see + "Upgrading from 1.2.0"); the `:id` check runs only on a uuid column. A new integration test runs the stock `routesFile()` output against Postgres with uuid keys and a uuid foreign key. Owned copies pick the fix up when re-ejected. - **`meta migrate` warns when a renamed column is still named by a view.** A rename never @@ -3311,8 +3971,8 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru emits nothing, so it never collides: a layered model's abstract `enterprise::Payer` beside a concrete `core::Payer` generates. The naming-conformance corpus gains `shapeOnlyCases` and `crossPackageCollisionCases`. -- **Doc pages are keyed by package**. TypeScript's `docsFile()` and `apiDocsFile()` now - place every page under its package path whatever the docs target's `outputLayout` (which still +- **Doc pages are keyed by package**. TypeScript's `apiDocsFile()` now + places every page under its package path whatever the docs target's `outputLayout` (which still places code), and Java's and Kotlin's api-docs `layout` defaults to `package` (`flat` is still honoured). Two same-named nodes in two packages are two pages, and an index entry that shares its short name carries its package. In every port, two page paths that differ only in case diff --git a/agent-context-shipped/files/ad2ac665832abd65.md b/agent-context-shipped/files/61d9c5d06a2af7fd.md similarity index 99% rename from agent-context-shipped/files/ad2ac665832abd65.md rename to agent-context-shipped/files/61d9c5d06a2af7fd.md index 3c3b010c8f..bee4e9c856 100644 --- a/agent-context-shipped/files/ad2ac665832abd65.md +++ b/agent-context-shipped/files/61d9c5d06a2af7fd.md @@ -48,7 +48,9 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`. (The `formatTs` no-op export was removed in 1.3.0; delete the import from an owned copy.) The config's `apiPrefix` is +`pluralize`. (`formatTs` was removed in 1.3.0: replace each `await formatTs(text)` with `text` or +your own formatter; see `docs/features/migrations/owned-generators-1.2-to-1.3.md` in the +MetaObjects repository.) The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index bb23892212..c1ddd502bc 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -179,7 +179,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -397,7 +397,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -617,7 +617,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -841,7 +841,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1066,7 +1066,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1295,7 +1295,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1523,7 +1523,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1743,7 +1743,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", diff --git a/agent-context/skills/metaobjects-codegen/references/typescript.md b/agent-context/skills/metaobjects-codegen/references/typescript.md index 3c3b010c8f..bee4e9c856 100644 --- a/agent-context/skills/metaobjects-codegen/references/typescript.md +++ b/agent-context/skills/metaobjects-codegen/references/typescript.md @@ -48,7 +48,9 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`. (The `formatTs` no-op export was removed in 1.3.0; delete the import from an owned copy.) The config's `apiPrefix` is +`pluralize`. (`formatTs` was removed in 1.3.0: replace each `await formatTs(text)` with `text` or +your own formatter; see `docs/features/migrations/owned-generators-1.2-to-1.3.md` in the +MetaObjects repository.) The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. diff --git a/changelog.d/agent-docs-native-every-port.md b/changelog.d/agent-docs-native-every-port.md deleted file mode 100644 index 217fe236ca..0000000000 --- a/changelog.d/agent-docs-native-every-port.md +++ /dev/null @@ -1,21 +0,0 @@ -- **`agent-docs` writes the agent files natively in C#, Java, Kotlin and Rust, with no Node.** - `dotnet meta agent-docs`, `mvn metaobjects:agent-docs` (Java and Kotlin) and the new - `cargo meta agent-docs` write `.metaobjects/AGENTS.md`, the `metaobjects-*` skills, the - `.metaobjects/.agent-context.json` manifest and the root `AGENTS.md` / `CLAUDE.md` import, byte - for byte what `meta agent-docs` and Python's `metaobjects agent-docs` write. Before, the C# and - Maven commands printed "run `npx meta agent-docs`" and exited 1, and Rust had no command. Each - copies one stack out of the built `agent-context-shipped/` tree it carries (C# and the Maven - plugin embed it at build time; the Rust crate, like the Python wheel, keeps a committed copy - that `scripts/sync-agent-context-shipped.sh` refreshes, renamed from - `sync-python-agent-context.sh`, and the `gates` lane fails when either copy is stale). The - flags are `--server`, `--client`, `--out` and `--no-wire-root` - (`-Dmetaobjects.servers`/`clients`/`outputDirectory`/`wireRoot` on Maven); with none, the - stack the last run recorded, else the port's own language. The re-run rules are the Node - CLI's: an unchanged file is not rewritten, a hand-edited one gets `.new`, an untouched - orphan is pruned. The Maven goal stamps the npm-line version (`8.3.0` writes `v1.3.0` links - and a `1.3.0` manifest), so the staleness check stays quiet after a native run. The `gen` - and `verify` staleness nudge in C# and Java now names the port's own command. Every port's - tests reproduce every `fixtures/agent-context-conformance/` stack, not only their own, so the - corpus is a cross-port gate. The shipped C#, Java and Kotlin skill references now tell an - agent to run the port's command instead of `npx meta agent-docs`; refresh the agent files to - pick that up. diff --git a/changelog.d/agent-pages-every-port.md b/changelog.d/agent-pages-every-port.md deleted file mode 100644 index be59f2b06c..0000000000 --- a/changelog.d/agent-pages-every-port.md +++ /dev/null @@ -1,32 +0,0 @@ -- **The agent pages in every port, from the docs view.** `requirements.toon`, - `agent/requirements.md` and the model-only `agent/schema.md` are now written by C#, Java, - Kotlin, Python, Rust and TypeScript alike: each port's `requirements` and `agent-docs` - generators build the page data from its own docs view and render the shared - `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what - `fixtures/docs-page-conformance/` pins. A TypeScript project with no dialect now gets the - model-only `agent/schema.md` too (it used to get no schema page); with a dialect it keeps the - physical page. `agent/schema.md` documents the project's own storage in every port: a - dependency's object that `scope.include` does not name is left out of its tables, views, - relationships and enums (Rust loads no dependency, and leaves out a reference node). The - TypeScript physical page used to list an imported table too. `agent/ui.md` stays - TypeScript's. Rust has no requirement ledger of its own yet, so its pages list every - requirement the view carries, an uninherited import's included. - - The docs view gains a `storage` section (`docs/features/docs-view.md`): every table and view - the model stores into, its columns (names from the port's naming helpers, each linked to its - field), keys and foreign keys. The physical facts (SQL types, defaults, indexes, checks, - constraint names and actions) are `null` outside a TypeScript run with a dialect, which fills - them. `explorer.json` carries the new key in every port. - - **Retired: the human `requirements.md` page.** The `requirements` generator writes only - `requirements.toon`; people read the ledger in the explorer (`docs-site`), and agents read it - embedded in `agent/requirements.md`. Upgrading: the next `gen` no longer writes - `requirements.md`; delete the committed copy (and its `.hashes/` entry goes with the run). - - **The always-on agent file points at the agent pages, only when they exist.** `meta init` - (and `--refresh-docs`) and every port's `agent-docs` command (`meta`, `metaobjects`, - `dotnet meta`, `mvn metaobjects:`, `cargo meta`) now add a "Pages - generated for this project" section to `.metaobjects/AGENTS.md`, naming each agent page the - project's last `gen` wrote (read from the committed `.metaobjects/.gen-state/.hashes/`) and - when to read it. A project that wires none of them gets the file unchanged. Refresh the agent - files after wiring `agent-docs`, `api-docs` or `requirements` for the first time. diff --git a/changelog.d/bun-1-3-14-package-manager.md b/changelog.d/bun-1-3-14-package-manager.md deleted file mode 100644 index 1958f0fcb1..0000000000 --- a/changelog.d/bun-1-3-14-package-manager.md +++ /dev/null @@ -1,6 +0,0 @@ -- **Repository: Bun 1.3.14 is the declared package manager.** The root `package.json` now - declares `bun@1.3.14`, the version every workflow pins, in place of 1.3.8 (which segfaults on - exit). Rebuilding or checking the explorer app (`server/typescript/packages/docs-site/scripts/build-app.ts`, - the `explorer app copies` gate and its unit test) requires that exact version, because the - committed bundle is minified and minified output follows the Bun version; any other Bun stops - with an error naming 1.3.14. diff --git a/changelog.d/classic-docs-site-removed.md b/changelog.d/classic-docs-site-removed.md deleted file mode 100644 index c825fb2f65..0000000000 --- a/changelog.d/classic-docs-site-removed.md +++ /dev/null @@ -1,7 +0,0 @@ -- **Breaking — the classic docs site is removed (TypeScript).** `docsSiteFile({ site: "classic" })` - now throws and points to the explorer (`docsSiteFile()`); an owned classic theme under - `codegen/docs-site/` is refused with an instruction to delete it and re-run - `meta eject docs-site`. `@metaobjectsdev/docs-site` no longer exports `generateSite`, - `DEFAULT_ASSET_BASE`, `SiteOptions`, `SiteResult`, `CLASSIC_TEMPLATE_NAMES` or - `CLASSIC_ASSET_NAMES`, and `meta eject docs-site` copies the explorer theme only. The - explorer's output is unchanged. diff --git a/changelog.d/cli-install-smaller.md b/changelog.d/cli-install-smaller.md deleted file mode 100644 index ab30b2ed74..0000000000 --- a/changelog.d/cli-install-smaller.md +++ /dev/null @@ -1,2 +0,0 @@ -- **The `meta` CLI installs 12 MB smaller** (34.6 MB, from 46.6 MB): it no longer depends on - `@biomejs/js-api` and `@biomejs/wasm-nodejs`, and `docs-site` no longer depends on `yaml`. diff --git a/changelog.d/csharp-codegen-shims-removed.md b/changelog.d/csharp-codegen-shims-removed.md deleted file mode 100644 index 7c7cdb4c80..0000000000 --- a/changelog.d/csharp-codegen-shims-removed.md +++ /dev/null @@ -1,3 +0,0 @@ -- **C#: the obsolete codegen shims are removed.** `ValueObjectNames.Names` (marked `[Obsolete]`; - use `ValueObjectNames.TypeName`) and the string-building forms of `XmlDocBuilder` (`AppendTo`, - `Indent`, `Prepend`; use `WriteTo` with the code writer) are gone. Generated output is unchanged. diff --git a/changelog.d/docs-markdown-generator-removed.md b/changelog.d/docs-markdown-generator-removed.md deleted file mode 100644 index 8fc8e1f7c8..0000000000 --- a/changelog.d/docs-markdown-generator-removed.md +++ /dev/null @@ -1,13 +0,0 @@ -- **Breaking — the docs Markdown generator is removed (TypeScript).** `docsFile()` and the - stable name `"docs"` (a Markdown page per object, the `README.md` overview with the ER diagram, - and the `apiSurfaces` option) are gone. The model explorer (`docsSiteFile()`, `"docs-site"`) is - the model's documentation for people, and `agentDocsFile()` (`"agent-docs"`) for a coding agent. - A config that still lists `"docs"` or imports `docsFile` makes `meta gen` fail with a message - that names the removal and the replacement; delete the pages it wrote (`README.md` and one - `.md` per object under the docs target). `meta init --with-docs` now wires - `docsSiteFile()` and `apiDocsFile()`. `apiDocsFile({ modelSurface })` now defaults to `false` - (it used to follow whether `docsFile()` ran); `modelBaseUrl` is unchanged. The engine exports - `buildEntityDocData`, `buildTemplateDocData`, `renderMermaidErBlock`, the `EntityDocData` / - `TemplateDocData` types and `DocsApiSurface` / `ApiSurface` are removed with it. The metamodel - index page (every port) now says your entities are documented by the model explorer: a - one-sentence documentation change in `meta gen` output for projects that list `metamodel-docs`. diff --git a/changelog.d/explorer-3d-map.md b/changelog.d/explorer-3d-map.md deleted file mode 100644 index fdb55c8545..0000000000 --- a/changelog.d/explorer-3d-map.md +++ /dev/null @@ -1,9 +0,0 @@ -- **docs-site: a 3D model map.** The explorer's map has a **View** control that switches - between the flat map and a 3D one drawn from the same nodes, edges, slice and colouring - (`#/map.html?view=3d`); click a node for the side panel and again to open its page. The 3D - library, 3d-force-graph 1.77.0 (MIT, bundling three.js; the licences of everything it bundles - head the file), ships with the site as `assets/3d-force-graph.min.js` and loads only when a - reader first chooses 3D, so it works offline and no other page pays for its size. A static - export given an `assetBase` loads it from the mirror instead. An owned - `explorer-map.html.mustache` without the control simply has no 3D mode. Generated-output - change — regenerate to pick it up; three-way merge preserves hand edits. diff --git a/changelog.d/explorer-app-stable-bundle.md b/changelog.d/explorer-app-stable-bundle.md deleted file mode 100644 index 34ea61646b..0000000000 --- a/changelog.d/explorer-app-stable-bundle.md +++ /dev/null @@ -1,7 +0,0 @@ -- **The explorer app's bundle builds the same bytes every time.** `explorer-app/assets/explorer-app.js` - is now minified for whitespace and syntax only, and keeps its identifiers' names. Bun's choice of - short names was not stable between builds of unchanged sources, so the check that the committed - bundle is what the sources build failed at random. The bundle grows from about 95 KB to about - 120 KB. Every port's copy is refreshed, so the docs site's `assets/explorer-app.js` changes and - nothing else does. Generated-output change — regenerate to pick it up; three-way merge preserves - hand edits. diff --git a/changelog.d/explorer-app.md b/changelog.d/explorer-app.md deleted file mode 100644 index 2536a21b47..0000000000 --- a/changelog.d/explorer-app.md +++ /dev/null @@ -1,21 +0,0 @@ -- **docs-site: the model explorer is one browser app.** `docsSiteFile()` now writes the - explorer as a few files (a shell, the app, the theme, Cytoscape and three data files: - `explorer.json`, `explorer-model.js`, `explorer-stamp.js`) in place of a page per screen. - The app draws every page when it is visited, with the same page code and templates, so each - page is byte-for-byte the one the static site wrote. It runs from `file://` with no server, - addresses each page as `index.html#/`, and follows the model while it is open: it polls - the stamp file about once a second and draws the current page again when `meta gen` rewrites - the model. Cytoscape 3.30.2 (MIT) ships with the site, so the graphs draw offline and the - CDN notice is gone. `docsSiteFile({ output: "static" })` (and `generateExplorerSite({ output: - "static" })`) writes the earlier page-per-screen site from the same code, for publishing - without scripts or for Pagefind; `assetBase` now applies to that export only, which given one - loads Cytoscape from it and ships no copy. The app's files live once at `explorer-app/` and - in every port's package (`scripts/sync-explorer-app.sh`, gated by `explorer app copies`); - the other ports' docs-site generators are still to write them. Generated-output change: the - next `meta gen` replaces the explorer's pages with the app's files, and `meta verify - --codegen` holds the new files to the model as before. - If you ejected the theme on a 1.3.0 candidate, your `codegen/docs-site/assets/explorer.js` - predates the app, which calls `window.MO_THEME` each time it draws a page: without that hook - search, the theme toggle and the graphs do nothing. Copy it again with `meta eject docs-site - --force` and carry your edits into the new copy (the app also needs its `window.MO_APP` link, - query and listener hooks, so adding the one line is not enough). diff --git a/changelog.d/explorer-csharp-python.md b/changelog.d/explorer-csharp-python.md deleted file mode 100644 index 203a179c20..0000000000 --- a/changelog.d/explorer-csharp-python.md +++ /dev/null @@ -1,13 +0,0 @@ -- **C# and Python: the model explorer with no Node.** Both ports build the docs view from their - loaded model (`MetaObjects.DocsView` in C#, `metaobjects.docs_view` in Python), byte for byte - what TypeScript builds for every `fixtures/explorer-conformance/` case. A new `docs-site` - generator in each registry (`DocsSiteGenerator` in `codegen/Generators.cs`; `docs-site` in a - Python target's `generators`) writes `explorer.json`, the explorer app, `explorer-model.js` - and `explorer-stamp.js`. Each object lists the files generated for it: this run's (the runner - runs the generator after every other one) and the committed manifest's outside the directories - the run's orphan sweep clears, so `verify --codegen` renders what `gen` wrote. Options name a - `verify --format json` payload and a routes file. The running application can serve the same - view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.MetaDocs(root)` (C#) and `meta_docs(root)` - (Python) build it once and carry its ETag; the host mounts it as it mounts `/_meta`. - C# and Python provenance now names a generator by its registry name (`entity`, - `filter-allowlist`, `routes`), as TypeScript and the JVM do. diff --git a/changelog.d/explorer-jvm.md b/changelog.d/explorer-jvm.md deleted file mode 100644 index 374709d7da..0000000000 --- a/changelog.d/explorer-jvm.md +++ /dev/null @@ -1,12 +0,0 @@ -- **Java and Kotlin: the model explorer with no Node.** The JVM builds the docs view from its - loaded model (`com.metaobjects.docsview.DocsView`), byte for byte what TypeScript builds for - every `fixtures/explorer-conformance/` case. A new `docs-site` generator - (`com.metaobjects.generator.DocsSiteGenerator`, in both the Java and Kotlin registries) writes - `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js`; each object - lists the files generated for it: this execution's (it builds the site after every other - generator it runs) and the committed manifest's for the module's other executions, so - `metaobjects:verify` renders what `generate` wrote. Optional args name a - `verify --format json` payload (`verifyFile`) and the routes (`routesFile`). The running - application can serve the same view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.docs(root)` - builds it once and carries its ETag, and the host mounts it as it mounts `/_meta`. The static - export and the classic site stay TypeScript's. diff --git a/changelog.d/explorer-live-source.md b/changelog.d/explorer-live-source.md deleted file mode 100644 index d87befbc62..0000000000 --- a/changelog.d/explorer-live-source.md +++ /dev/null @@ -1,10 +0,0 @@ -- **runtime-ts: `GET {apiPrefix}/_meta/docs` serves the loaded model's docs view, and the - explorer follows it.** New `mountMetaDocsRoute` (Fastify) and `mountMetaDocsRouteHono` mount - it beside `/_meta`, opt-in and guarded the same way, with `META_DOCS_ROUTE_PATH` and - `metaDocsJson(root, { routes })` for other hosts. The response carries an ETag and answers a - matching `If-None-Match` with `304`; `allowOrigin` opts in to cross-origin reads. Open the - explorer app as `index.html?source=` and it reads the running application's model - instead of the generated file, once a second, drawing the open page again when the - application restarts on a changed model. The route's shape is a cross-port contract - (`docs/features/metadata-api.md`); the other ports serve it once they have their docs view - builders. diff --git a/changelog.d/explorer-rust.md b/changelog.d/explorer-rust.md deleted file mode 100644 index ef1a3eee7c..0000000000 --- a/changelog.d/explorer-rust.md +++ /dev/null @@ -1,23 +0,0 @@ -- **Rust: the model explorer with no Node.** The Rust port builds the docs view from its loaded - model (`metaobjects::docs_view::build`), byte for byte what TypeScript builds for every - `fixtures/explorer-conformance/` case. A new opt-in `docs-site` generator writes - `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js` under - `site/`. It reads prompt texts from the metadata directories, `templates/` and a `prompts` - directory, and takes `subDir`, `title`, `stamp`, `verifyFile` and `routesFile` as options. - Each node lists the files generated for it: this run's (the engine runs the site after every - other generator) and the committed manifest's outside the run, so `cargo meta verify` renders - what `gen` wrote. The site builder is engine, as in every port: `cargo meta eject docs-site` - refuses, `gen --list` marks it `[package-only]`, and an owned theme in `codegen/docs-site/` - replaces the shipped one. The app files are a canonical copy in the crate - (`metaobjects-codegen/explorer-app/`, held to the root `explorer-app/` by the - `explorer app copies` gate) and ship in the published package. The running application can serve - the same view at `{apiPrefix}/_meta/docs`: `metaobjects::meta_endpoint::docs` builds it once and - carries its ETag, and the host mounts it as it mounts `/_meta` (`meta_endpoint::meta_json`, - new in Rust too). - - Rust codegen now also records which node each generated file came from, `{ "hash", - "generatedBy", "sourceNode" }` in the hash manifest, held to the shared `provenance` vector in - `fixtures/codegen-skip-conformance/manifests.json`. A file rendered for no single node, such as - a shared `meta_*` crate's, keeps the plain hash. Upgrading: the next `cargo meta gen` rewrites - the committed `.metaobjects/.gen-state/.hashes/` files once. Commit them; generated source - files do not change. diff --git a/changelog.d/format-ts-and-owned-copy-biome-removed.md b/changelog.d/format-ts-and-owned-copy-biome-removed.md deleted file mode 100644 index 977fe422f1..0000000000 --- a/changelog.d/format-ts-and-owned-copy-biome-removed.md +++ /dev/null @@ -1,7 +0,0 @@ -- **Breaking — `formatTs` and the Biome owned-copy comparison are removed (TypeScript).** The - no-op `formatTs` export, kept so an owned 1.2 generator copy still loaded, is gone: generation - runs no formatter, and a copy that wants one calls its own. `meta eject`'s owned-copy report no - longer loads Biome's WebAssembly build: it compares the copy and the reference line by line, - trimmed, ignoring trailing commas, blank lines and import order. A copy re-wrapped by your own - formatter (lines joined or split) now reads `differs` where it read `reformatted`. - `@metaobjectsdev/cli` drops its `@biomejs/js-api` and `@biomejs/wasm-nodejs` dependencies. diff --git a/changelog.d/generated-file-provenance-all-ports.md b/changelog.d/generated-file-provenance-all-ports.md deleted file mode 100644 index 7045ab47ca..0000000000 --- a/changelog.d/generated-file-provenance-all-ports.md +++ /dev/null @@ -1,10 +0,0 @@ -- **C#, Java and Python codegen record which node each generated file came from.** After a write - run, the hash manifest entry of a per-object file names its generator and the node's resolution - key, `{ "hash", "generatedBy", "sourceNode" }` (after the JVM's `generator` and `outputDir`), - exactly as TypeScript already wrote it. A docs view built from any of these ports' manifests now - lists each node's generated files, so the explorer's "generated files" panel is filled. A file - rendered from the whole model or a package keeps the plain hash. The shared `provenance` vector in - `fixtures/codegen-skip-conformance/manifests.json` holds all four ports to the same entries. - - Upgrading: the next `gen` rewrites the committed `.metaobjects/.gen-state/.hashes/` files once, - adding the two fields to each per-object entry. Commit them; generated source files do not change. diff --git a/changelog.d/generator-legacy-markers-removed.md b/changelog.d/generator-legacy-markers-removed.md deleted file mode 100644 index 16ec22656e..0000000000 --- a/changelog.d/generator-legacy-markers-removed.md +++ /dev/null @@ -1,13 +0,0 @@ -- **Breaking — the legacy generator markers are removed, and an owned 1.2 copy is refused - (TypeScript).** `emitsEntityModule`, `emitsQueries`, `emitsNames`, `emitsReportExport`, - `emitsUiTier`, `emitsHonoRoutes`, `mountsRoutes`, `emitsApiDocs` and `emitsModelDocs` (and - `provides.modelDocs`) are gone from `Generator`; the `provides` declaration (ADR-0034 - Amendment 12) is the only way to say what a generator writes. `meta gen` now refuses a - generator that still sets one, naming the marker and its `provides` replacement, instead of - reading it. The name-based fallbacks that treated a copy named `queries-file`, `entity-file`, - `routes-file` or a UI generator's name as providing its tier are removed with them, as is - `UI_TIER_GENERATOR_NAMES`. A copy that carries a shipped generator's name and declares no - `provides` at all (one ejected before the markers) still runs, with one warning naming the - declaration the shipped generator makes (`SHIPPED_PROVIDES_BY_NAME`). Generator - copies ejected in 1.2 or earlier no longer load: re-eject them (`meta eject --force`) or - replace the markers with `provides` by hand. diff --git a/changelog.d/java-entity-writer-mustache-removed.md b/changelog.d/java-entity-writer-mustache-removed.md deleted file mode 100644 index 2b1b600a60..0000000000 --- a/changelog.d/java-entity-writer-mustache-removed.md +++ /dev/null @@ -1,42 +0,0 @@ -- **Java: the `entity` generator writes through the Java code writer, and the `mustache` - generator is removed** (ADR-0063). `JavaObjectCodeGenerator`'s four writers - (`BaseObjectCodeWriter`, `JavaCodeWriter`, `PojoAwareCodeWriter`, `ValueObjectCodeWriter`) now - write lines and blocks on `JavaWriter` instead of printing through an indentor. The output - changes in layout only: no trailing whitespace, no blank line straight after a class opens or - before it closes, and a one-sentence Javadoc fits on one line. Checked against a capture of - the interface, `pojoAware` and `valueObject` flavors over the fitness corpus: identical with - whitespace ignored, apart from that one Javadoc. The layout ratchet gains an `indented-print` - rule (`println(true, ...)`), the call that typed indentation without a literal and let this - family go unseen. Generated-output change — regenerate to pick it up; three-way merge - preserves hand edits. - - The deprecated `mustache` generator (`MustacheTemplateGenerator`) and its module - `metaobjects-codegen-mustache` are removed; `template` (`TemplateScopeGenerator`, in - `codegen-base`) replaces them. A pom that still names `MustacheTemplateGenerator` fails the build - with a `ClassNotFoundException`. - - Upgrading: replace a `MustacheTemplateGenerator` `` with - `com.metaobjects.generator.template.TemplateScopeGenerator` and its args `templatesDir`, - `template`, `scope` and `outputPattern` (docs/features/codegen-concepts.md), and drop any - `metaobjects-codegen-mustache` dependency. An owned copy of the `entity` writers (from - `mvn metaobjects:eject -Dnames=entity`) keeps working as it is; to take the new layout, - re-eject, or write through `out()` (a `CodeWriter`; `java()` in `JavaCodeWriter`) instead of - `println`/`inc`/`dec`, which the entity writers no longer have. - - The deprecated shims in the documentation generators are removed too: the attribute-name - constants and `register*Attributes` methods on `MetaDataAIDocumentationGenerator` and - `MetaDataFileJsonSchemaGenerator` (use the same names on `CodeGenMetaDataProvider`), - `MetaDataFileSchemaWriter.addConstraintFile` (a no-op since registry-based discovery), and the - old `SingleHtmlDirectGeneratorBase.writeHtml(MetaDataHtmlDocumentationWriter)` hook (override - `writeHtml(HtmlDirectWriter)`). - - So are the 1.0.x forwarding shims in `codegen-spring`. The static field and annotation helpers - on `SpringDtoGenerator` (`settableFields`, `scalarFields`, `dtoComponentFields`, - `valueObjectJsonbFields`, `valueObjectMapFields`, `isValueObjectJsonbField`, `componentType`, - `isRequired`, `originGuaranteedNonNull`, `validationAnnotations`, `sizeAnnotation`, `attrBool`, - `attrInt`, `hasValidator`, `escapeJavaString`) and on `SpringRepositoryGenerator` - (`m2mFinderName`, `m2mFinderNameForSubtype`, `targetSubtypeParam`) are gone: call the same name - on `SpringGeneratorSupport`, and `SpringGeneratorSupport.repositoryAppliesTo` for - `SpringRepositoryGenerator.appliesTo`. The `AutoSetSupport` selectors `stampFields`, - `onUpdateFields`, `hasAutoSetFields` and `hasOnUpdateFields` move the same way, to - `SpringGeneratorSupport`. diff --git a/changelog.d/java-xpkg-qualified-names.md b/changelog.d/java-xpkg-qualified-names.md deleted file mode 100644 index 1687db5706..0000000000 --- a/changelog.d/java-xpkg-qualified-names.md +++ /dev/null @@ -1,5 +0,0 @@ -- **Java: the entity generator qualifies same-named types from two packages.** A file referencing - two value objects named alike in different metadata packages writes each fully qualified, where - it refused the model with `ERR_WRITER_IMPORT_CONFLICT`. Java, Kotlin and Python now run the - `xpkg-value-object-refs` codegen corpus. `KotlinApiDocsRenderer` moved onto `KotlinWriter`, - with byte-identical output. diff --git a/changelog.d/jvm-non-long-keys.md b/changelog.d/jvm-non-long-keys.md deleted file mode 100644 index 46b4c36aa3..0000000000 --- a/changelog.d/jvm-non-long-keys.md +++ /dev/null @@ -1,5 +0,0 @@ -- **Java and Kotlin: generated controllers serve uuid, string and int primary keys**, gated by the - shared `key-types` api-contract corpus in both generated lanes. The Kotlin controller now writes - an assigned primary key (no `@generation`, no `@default`) from the request body on create, - where it skipped the column and the insert failed `NOT NULL`, and a TPH subtype create that - omits it is a 400 (`invalid_type` on the key); increment and generated-uuid keys are unchanged. Generated-output change for assigned-key entities only. diff --git a/changelog.d/key-types-api-contract-corpus.md b/changelog.d/key-types-api-contract-corpus.md deleted file mode 100644 index b523f4bc41..0000000000 --- a/changelog.d/key-types-api-contract-corpus.md +++ /dev/null @@ -1,6 +0,0 @@ -- **Conformance: the `key-types/` api-contract sub-corpus.** Generated CRUD for a client-assigned - `field.uuid`, a natural `field.string` and a `field.int` primary key (list, get, 404, create, - patch and delete), run in the generated lane of every port. It found the TypeScript `id`-only - CRUD mounts and a C# defect: a `field.uuid` key's generated routes did not compile (no - `using System;`), and the key type is now spelled `global::System.Guid` in the item routes and - in the M:N traversal routes over uuid junction keys. diff --git a/changelog.d/metamodel-docs-mustache.md b/changelog.d/metamodel-docs-mustache.md deleted file mode 100644 index 1272c17519..0000000000 --- a/changelog.d/metamodel-docs-mustache.md +++ /dev/null @@ -1,17 +0,0 @@ -- **metamodel-docs: the vocabulary reference pages are shared Mustache templates, and every - port writes them.** `INDEX.md`, `providers.md` and the `types/.md` pages are now the - `templates/metamodel/` template set rendered over page data each port builds from its own - registry vocabulary manifest and its embedded provider definitions. C#, Java, Kotlin, Python - and Rust gain a `metamodel-docs` generator; every port is held to `fixtures/metamodel-docs/` - (the page data under `data/` and the bytes under `expected/`). A project can override a - page by placing a `templates/metamodel/.mustache` of its own. The TypeScript pages are - unchanged except one fix: `index.lookup` was missing its owning provider - (`metaobjects-core-types`) and the provider of its `@fields`, because the index definition - was left out of the provenance list. - - Upgrading: `@metaobjectsdev/metadata` no longer exports `renderMetamodelDocs`, - `renderCoreMetamodelDocs`, `buildMetamodelProvenance` or the `MetamodelProvenance` type; it - exports `coreMetamodelDocsPages()` and `buildMetamodelDocsPages()` (each page's path, - template ref and data) instead, and codegen-ts renders them. An ejected - `codegen/generators/metamodel-docs.ts` that calls `renderCoreMetamodelDocs` stops compiling: - eject it again (`meta eject metamodel-docs`). diff --git a/changelog.d/python-codegen-writer-no-ruff.md b/changelog.d/python-codegen-writer-no-ruff.md deleted file mode 100644 index 7d1e695e38..0000000000 --- a/changelog.d/python-codegen-writer-no-ruff.md +++ /dev/null @@ -1,55 +0,0 @@ -- **Python: every generator writes through the code writer, and codegen no longer runs `ruff`** - (ADR-0063). The router and the last nine emitters (extractor, output parser, trace helper, - render helper, names, requirement tests, API docs and the extract delegate and schema emitters) - now lay out their files with `PyWriter`, so generated bytes no longer depend on whether `ruff` is - installed or on its version. The output changes in layout only: a line longer than 88 columns - breaks its last bracketed list, and imports are grouped `__future__`, absolute, then relative, - each in code-point order. Checked against a capture of every emitted file: same syntax tree, - comments and docstrings. One fix rides along: an unresolved `@objectRef` mapper argument used - to put its comma inside the trailing comment, which was a syntax error; it is now - `x=None, # unresolved @objectRef`. Generated-output change — regenerate to pick it up; - three-way merge preserves hand edits. - - Upgrading: no reference generator calls `metaobjects.codegen.format.ruff_format` any more. It - stays exported, so an owned copy ejected from an earlier release that imports it still loads and - still formats its own output. These subclass hooks now take the writer `w` first and write, - instead of returning lines or a string: - `RouterGenerator._emit_repository_protocol(self, w, repo_class, m2m, pk_type)`, - `_emit_reverse_finders(self, w, entity)`, `_emit_route_handler(self, w, name, ...)`, - `_emit_m2m_route(self, w, d, ...)`, `_emit_tph_m2m_route(self, w, d, ...)`, - `_emit_tph_list_body(self, w, subtype_expr, ...)`, - `_emit_readonly_reject_handlers(self, w, snake, ...)`, `_report_list_with_export(self, w, ...)` - and `ExtractorGenerator._emit_mapper(self, w, vo, root)`. In `_emit_route_handler` the - `create_autoset`, `update_autoset`, `frozen_strip` and `denied_strip` arguments are now - `BodyStep` callables that write into `w`, not line lists. `RenderHelperGenerator._emit_document` - and `_emit_email` take `header` as `list[str]` instead of `str`. In the runtime emitters that - eject hands over, `extract_delegate_emitter.nested_mirror_dataclasses`, `nested_mappers` and - `delegate_helpers` are now `write_nested_mirror_dataclasses(w, vo, root)`, - `write_nested_mappers(w, vo, root)` and `write_delegate_helpers(w, used)`, and - `extract_schema_emitter.mirror_dataclass` and `mirror_initializer` are removed (the - mirror dataclasses come from `write_nested_mirror_dataclasses`; the new `schema_piece` is the - schema descriptor that `trace-helper` writes). Eject never overwrites an existing - `codegen/runtime/` copy, even with `--force`, so delete the old copy before you re-eject. - `output-parser` and `extractor` share `codegen/runtime/extract_delegate_emitter.py`: delete - it, then re-eject every one of the two that you own. For `trace-helper`, delete - `codegen/runtime/extract_schema_emitter.py`, then re-eject `trace-helper`. `ruff` stays a - dev dependency for the compile gate's `ruff check` lint only. - - Removed: the deprecated module aliases added in 1.1.0. An import of an old path now fails with - `ImportError` (or its subclass `ModuleNotFoundError`, depending on the import form); import - from the new path instead: - `metaobjects.codegen.extract_delegate_emitter` is `metaobjects.codegen.runtime.extract_delegate_emitter`, - `metaobjects.codegen.extract_schema_emitter` is `metaobjects.codegen.runtime.extract_schema_emitter`, - `metaobjects.codegen.fr010_field_mapping` is `metaobjects.codegen.runtime.fr010_field_mapping`, - `metaobjects.codegen.output_format_spec_emitter` is `metaobjects.codegen.runtime.output_format_spec_emitter`, - `metaobjects.codegen.generators.fr019_shared_enum` is `metaobjects.codegen.runtime.fr019_shared_enum`, - `metaobjects.codegen.generators.m2m_codegen` is `metaobjects.codegen.runtime.m2m_codegen`, - `metaobjects.apidocs.api_model` is `metaobjects.codegen.runtime.api_docs_model`, - `metaobjects.apidocs.builder` is `metaobjects.codegen.runtime.api_docs_builder`, - `metaobjects.apidocs.renderer` is `metaobjects.codegen.runtime.api_docs_renderer` and - `metaobjects.apidocs.paths` is `metaobjects.codegen.runtime.api_docs_paths`. The - `metaobjects.apidocs` package and `metaobjects.apidocs.naming` stay. An owned copy ejected - before 1.1.0 that still imports an old path needs its imports changed, or re-eject it. For - `output-parser`, changing the imports is not enough, because that copy calls the removed - `nested_mirror_dataclasses`, `nested_mappers` and `delegate_helpers`: re-eject it, or move it to - `write_nested_mirror_dataclasses`, `write_nested_mappers` and `write_delegate_helpers`. diff --git a/changelog.d/python-rc21-view-vocabulary.md b/changelog.d/python-rc21-view-vocabulary.md deleted file mode 100644 index c5533eb45a..0000000000 --- a/changelog.d/python-rc21-view-vocabulary.md +++ /dev/null @@ -1,9 +0,0 @@ -- **Python: the loader enforces the rc.21 view vocabulary.** `origin.function` signature and - identifier rules, dotted-path references in `origin.computed` and in an `origin.first` - `@filter`, a scalar `origin.aggregate` read from a computed field, passthrough from a `@grain` - value object and derived-field cycle detection now load and fail as they do in TypeScript and - C#. The two ledgered fixtures (`error-origin-function-free-sql`, - `projection-view-vocabulary-rc21`) pass, and the Python expected-failures ledger is empty. A - bare `@from` or base head on a projection now resolves in the file's default package. The - `xpkg-value-object-refs` codegen corpus and the generated `key-types` api-contract lane now run - in Python. diff --git a/changelog.d/registry-type-level-ports.md b/changelog.d/registry-type-level-ports.md deleted file mode 100644 index a8397dd6d5..0000000000 --- a/changelog.d/registry-type-level-ports.md +++ /dev/null @@ -1,11 +0,0 @@ -- **Registry manifest: a type can carry `ports`** (#549), the type-level twin of the attr-level - marker, for vocabulary that is language-specific by nature and never pending. The 13 generic - `view.*` controls move from `implementedIn: ["typescript"]` to `ports: ["typescript"]` (UI - vocabulary of the TypeScript client tier, which serves every backend), and `@object` moves from - `implementedIn: ["java"]` to `ports: ["java", "kotlin"]` (the JVM runtime). The rc.21 view - vocabulary (`origin.function`, `@union`, `@unionAll`, `@grain`, `@grainOrdinal`) is now - `implementedIn: ["csharp", "python", "typescript"]`, since the Python loader validates it; Java - and Kotlin remain pending on `origin.function`'s `@args`, `@params` and `@returns`. Every port - still registers and loads all of it strictly. The metamodel docs replace "Implemented in: … so - far" with "Language-specific to: …" on those pages; `meta types` marks ts-scoped types - `[ts-only]`, and the deprecated `tsOnly` field stays true for them. diff --git a/changelog.d/rust-publish-stale-sources.md b/changelog.d/rust-publish-stale-sources.md deleted file mode 100644 index 9a4aefcde2..0000000000 --- a/changelog.d/rust-publish-stale-sources.md +++ /dev/null @@ -1,7 +0,0 @@ -- **CI: the Rust publish dry-run no longer verifies against stale source.** `cargo publish - --workspace` unpacks the crates it depends on from its temporary overlay registry into a - directory fixed per checkout, and never unpacks them again while the version is unchanged, so a - machine that had run the gate before a new module landed compiled the old `metaobjects-1.3.0` - and failed with "could not find `metamodel_docs`". The gate now first clears unpacked copies of - the workspace's own crates that differ from the tree - (`scripts/rust-clear-stale-publish-sources.sh`). diff --git a/changelog.d/ts-crud-routes-non-id-key.md b/changelog.d/ts-crud-routes-non-id-key.md deleted file mode 100644 index 6142e1cd1f..0000000000 --- a/changelog.d/ts-crud-routes-non-id-key.md +++ /dev/null @@ -1,6 +0,0 @@ -- **TypeScript: generated CRUD routes address a key not named `id`.** `mountCrudRoutes` (Fastify - and Hono) took the primary key to be the `id` column, so an entity keyed on a natural `code` - or an int `rank` answered every item route (`GET`/`PATCH`/`PUT`/`DELETE /:id`, and the create - re-read on MySQL) with a 500. The mounts take an `idColumn` option, and the generated routes - pass it when the key field has another name. Generated-output change for such entities only: - one `idColumn: "",` line in the mount call; regenerate to pick it up. diff --git a/changelog.d/ts-poet-printer-removed.md b/changelog.d/ts-poet-printer-removed.md deleted file mode 100644 index 8b42e21f0f..0000000000 --- a/changelog.d/ts-poet-printer-removed.md +++ /dev/null @@ -1,10 +0,0 @@ -- **Breaking — the vendored ts-poet printer is removed; TypeScript codegen is writer-only.** - `@metaobjectsdev/codegen-ts` no longer exports `code`, `imp`, `joinCode`, `Code` or `Import`, - and `TsWriter` no longer accepts a `Code`. Use the writer fragments: `frag`, `joinFrags`, - `importName`, `importType`, `Frag` and `TsImport` (`writer/ts-fragment.ts`). The queries - template's `render*Fn` and `schemaInputType` forms are removed, and the config loader no longer - rewrites a `ts-poet` import. Generator copies ejected in 1.2 that use any of these no longer - load: re-eject them (`meta eject --force`). The `contract-types` output changes layout - only (one statement per line, double-quoted imports in the writer's order); the requirement-test - scaffolds and the client directive are now written through the writer, byte for byte as before. - `api-doc-render.ts` moved onto the code writer with unchanged output. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 3d256aca3f..ddfacc4a3b 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/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 17 | ✓ (reference) | planned | planned (through Java) | ✓ | planned | — | | [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 49 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | planned (RS-V2) | | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 27 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | — | -| [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 16 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | ✓ | +| [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 17 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | ✓ | | [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases + 23 collection segments (`@collectionName`, `naming.collections`) | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`, `RouteNaming.collectionSegment`) | ✓ | ✓ | ✓ | | [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | the config blocks (`wire_block_corpus`) | | [`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) | the config blocks (`enums_block_corpus`) | @@ -72,7 +72,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`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) | ✓ | ✓ | ✓ (every case but the three-way merge one) | | [`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) | ✓ | ✓ | ✓ | ✓ | `rules/` (the layer generators lower it; the flat ones stay inert) | | [`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) | 88 cases (31 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 91 cases (33 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 13 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | ✓ (`MetaObjects.DocsView`, and the `docs-site` generator end to end) | ✓ (`metaobjects.docs_view`, and the `docs-site` generator end to end) | ✓ (`metaobjects::docs_view`, and the `docs-site` generator end to end) | @@ -887,9 +887,9 @@ outside ASCII. The case list is in the Kotlin's identity function is the Java one; the names its generator emits are asserted by `server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementTestsGeneratorTest.kt`. -### `fixtures/rules-check-conformance/` (16 cases) +### `fixtures/rules-check-conformance/` (17 cases) -All 16 cases → [features/business-rules.md](features/business-rules.md) ("What `verify` +All 17 cases → [features/business-rules.md](features/business-rules.md) ("What `verify` reports"). Each case is a directory: `input/` metadata, an optional `options.json` (the `rules` and `verify` blocks of `.metaobjects/config.json`, read through each port's own config reader) and an `expected.json` holding the gate's diagnostics (severity, code, node address, diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 3b67c181cf..989b965c9b 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -236,6 +236,7 @@ and reports: | `WARN_LIFECYCLE_INITIAL_TERMINAL` | warn | The initial state is terminal, so no row can ever move. | | `WARN_TRANSITION_UNREACHABLE` | `verify.lifecycle.unreachable` | A transition whose every `from` state is unreachable. | | `WARN_TRANSITION_PERMISSION_SHADOWED` | warn | A transition declares `permission` or `public: true` but derives no command of its own (every carrier's transition is claimed by a declared command, or `rules.lifecycle.commands` is `none`), so nothing reads it. | +| `WARN_DERIVED_COMMAND_BYPASSES_DECLARED` | warn, under `rules.lifecycle.commands: all` only | A transition a declared command claims also derives a command of its own, which makes the same transition without running the declared command's body (the business rule) and asks about the derived permission name. Use `unclaimed` (the default) unless you want both entry points. | | `WARN_PERMISSION_DERIVED_NAME` | `rules.permissions.names` | An operation, or a transition that derives a command, relies on a derived permission name. The message names it. A transition on an entity with no source derives no command and is not reported. | An error-severity finding fails the run. A model with no operation and no transition sees no @@ -419,6 +420,9 @@ or narrow `serviceFile()` with its `filter`, as with any generator. In a project lifecycle and wires no service generator covering it, `meta verify` advises that nothing generated enforces it (rule `unenforced-lifecycle`); the flat routes write the lifecycle field like any other. +The service generators skip an object whose entity module the run does not emit (the entity +generator's `filter` leaves it out), and warn when it would have had operations. + Both import the entity module (`entity`, for the table and the allowlists) and the contract types (`contract-types`), written to the same target, and `@metaobjectsdev/runtime-ts`'s `service` and `service/fastify` (or `service/hono`) entries; `meta eject service`, `meta eject service-routes` and diff --git a/docs/features/cli.md b/docs/features/cli.md index f0160ddd13..9b2fb4ee5e 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -217,11 +217,14 @@ which is a stricter answer to the same question and stays as it is. **Port status (staged per ADR-0021):** the **TypeScript Node `meta` is the reference** and implements all three subverbs today. **Python `metaobjects` -ships the subverbs**: `verify --codegen` (regen-to-temp + diff vs `--out`), `verify --templates` (each `template.*` node's `{{field}}` +ships the subverbs**: `verify --codegen` (regen-to-temp + diff vs `--out`; every emitted `.py` +module must compile first, so generated Python that does not compile fails), `verify --templates` (each `template.*` node's `{{field}}` ↔ payload-VO field tree via the render `verify()` gate, resolving refs through a -filesystem provider rooted at `--prompts`), and `verify --db` which is +filesystem provider rooted at `--prompts`; on its own it checks prompt templates only and +neither compares nor compiles generated code), and `verify --db` which is **cleanly rejected with exit 2** ("schema verify is the migrate engine, -ADR-0015"). Bare `verify` runs `--codegen` and `--templates` (the template gate is skipped +ADR-0015"). Bare `verify` runs `--codegen` and `--templates`, so it compiles generated Python too +(the template gate is skipped with a note when the run names no config and no `--prompts`). The **C# `dotnet meta`** port likewise ships the codegen-side subverbs: `verify --templates` (its historical template/prompt drift gate), `verify diff --git a/docs/features/codegen-concepts.md b/docs/features/codegen-concepts.md index 67e5a07b1d..10afb615a7 100644 --- a/docs/features/codegen-concepts.md +++ b/docs/features/codegen-concepts.md @@ -180,6 +180,19 @@ the decision, except on Java and Kotlin for a file the manifest has no record of warning, not a build failure. The full rule is in [own-your-codegen.md](own-your-codegen.md#hand-edits-and-the-hash-manifest-every-port). +**Emitted text is checked before anything is written or compared**, in `gen` and in every +`verify` mode that runs codegen. A failure names the file. In TypeScript, Python and Rust the +run then writes none of its files. C#, Java and Kotlin check file by file, so the refused file is +not written: + +- **Every port** refuses output that carries `[object Object]`, an object turned into text + (`ERR_GEN_STRINGIFIED_OBJECT`). The exact quoted literal `"[object Object]"` is allowed, and + so is any output when a string value in the model carries the marker itself. +- **TypeScript** (the `meta` CLI) refuses a `.ts`, `.tsx`, `.mts` or `.cts` file that does not + parse (declaration files are not checked). It does not type-check. A caller of `runGen()` gets + this check only when it passes `checkEmitted`. +- **Python** refuses a `.py` file that does not compile. + ## 8. Bind metadata → native types at build time, never runtime reflection Resolving an object's native class/module from its FQN happens in **generated code** diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 7c4b418653..a9ea20bf94 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -953,6 +953,15 @@ migrate` never creates, drops, or drift-checks it, and `meta verify --db` report *external (declared)*. The two are mutually exclusive. See [ADR-0043](../../spec/decisions/ADR-0043-ddl-ownership-escape-valves.md). +**An `@sql` view that selects `*` can drift on Postgres.** Postgres expands `*` when the view +is created, so the live view keeps the columns its tables had then. The scratch database +`meta verify --db` compares through expands `*` over every column the tables have now. The report +shows one changed view (also when the plan behind it is a drop and a create) and names `*` as a +possible cause. To clear the drift, list the view's columns explicitly, or drop and recreate the +view by hand. The offline `meta migrate` plans nothing for it. `meta migrate --from-db` makes the +same comparison and can plan a replace, or a drop and a create, so review that plan before +`--apply`. + **Removing a column a view reads.** For a view the tool derives, `meta migrate` finds the views that read the column and drops and recreates them around the change. Two kinds of view are not rewritten, so you edit them yourself: 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 542cdf5df2..2c19b071bc 100644 --- a/docs/features/migrations/commit-the-gen-state-hash-manifest.md +++ b/docs/features/migrations/commit-the-gen-state-hash-manifest.md @@ -1,8 +1,10 @@ -# Migration — commit `.gen-state/.hashes.json` +# Migration — commit `.gen-state/.hashes/` > **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. +> package** (see [the per-package manifest migration](per-package-hash-manifest.md)); before +> 1.3.0 it was one file, `.gen-state/.hashes.json`. The first `gen` after upgrading converts the +> old file, deletes it and rewrites `.metaobjects/.gitignore`: commit the new directory, the +> deletion and the `.gitignore` change together. **Applies to:** every existing TypeScript project scaffolded by `meta init` before this release. **Action required:** one edit to `.metaobjects/.gitignore`, then commit the manifest. diff --git a/docs/features/migrations/default-list-page-of-fifty.md b/docs/features/migrations/default-list-page-of-fifty.md index a4eab9c163..a9fde6bab5 100644 --- a/docs/features/migrations/default-list-page-of-fifty.md +++ b/docs/features/migrations/default-list-page-of-fifty.md @@ -19,7 +19,11 @@ shipped) sees no change: its `defaultLimit` and `maxLimit` apply as before. | `meta verify` or `dotnet meta verify --codegen` advises `unbounded-list-pages` | the advisory is gone: the lists are bounded | | C#: `?limit=abc` or `?offset=-1` is ignored | it is `400 pagination.invalid_value`, as it already was with `api.pagination` set | -The generated TanStack list hooks are not affected: the grid hook always sends a `limit`. +**The generated TanStack list hooks are affected unless the caller passes a `limit`.** The grid hook always +sends one, so a grid pages as before. The plural list hooks (`useOrders(filter?)`, `useWidgetSummaries()`) +build the query string from the filter they are given, so a call with no `limit` now gets 50 rows: a screen +that listed a whole table that way (a picker, an editor that loads every child) shows the first 50. Pass +`limit` in the filter (`useOrders({ limit: 500 })`), page with `offset`, or raise the project's default below. **An owned runtime copy** (copied by `meta eject routes` or `meta eject routes-hono`) keeps the behaviour of the copy you took. Take a fresh copy with `meta eject routes --force` (or `routes-hono`) to get the default, or change `pageLimit` in your diff --git a/docs/features/migrations/docs-are-generators.md b/docs/features/migrations/docs-are-generators.md index fa52a1d11b..67389dae54 100644 --- a/docs/features/migrations/docs-are-generators.md +++ b/docs/features/migrations/docs-are-generators.md @@ -725,3 +725,38 @@ defaults to `false`. `modelBaseUrl` still works if you publish model pages elsew wrote under the `docs` target, list `docsSiteFile()`, and run `meta gen`. `mermaid-er`'s removal message now points at `docs-site` too. An owned copy from `meta eject docs` no longer loads; delete it and `codegen/generators/docs*`. + +## Since 1.3.0: `generateSite()` is removed + +**What breaks.** `@metaobjectsdev/docs-site` no longer exports `generateSite({ sourceDirs, ... })`, +the classic site's builder, which loaded the model itself. A script that called it fails with +`generateSite is not a function` (or `has no exported member 'generateSite'` under `tsc`). + +**To upgrade.** Prefer `docsSiteFile()` in `metaobjects.config.ts`, which `meta gen` runs and +`meta verify --codegen` gates. A script that must build the site itself does the three steps the +old builder did inside: load the model, build the docs view, and write the explorer. Pass +`output: "static"` for a page per object, which is the old site's shape; the default (`"app"`) +writes one browser app over the model. + +```ts +import { composeRegistry, coreProviders, MetaDataLoader, buildDocsView } from "@metaobjectsdev/metadata"; +import { DirectorySource } from "@metaobjectsdev/metadata/core"; +import { generateExplorerSite, readPromptTexts } from "@metaobjectsdev/docs-site"; + +const sourceDirs = ["metaobjects"]; +// Add the provider packs the project registers (its `providers`) beside the core ones. +const registry = composeRegistry([...coreProviders /*, ...packProviders */], { validate: true }); +const { root } = await new MetaDataLoader({ registry }).load(sourceDirs.map((d) => new DirectorySource(d))); +const view = buildDocsView({ root }); +generateExplorerSite({ + view, + outDir: "site", + title: "My model", + output: "static", + texts: readPromptTexts(view, ["templates", ...sourceDirs]), +}); +``` + +`buildDocsView` also takes `verify` (the parsed `meta verify --format json` output, for the +requirement ledger) and `manifest` (the merged `.gen-state/.hashes/` entries, for each object's +generated files); without them those panels are empty. diff --git a/docs/features/migrations/owned-generators-1.2-to-1.3.md b/docs/features/migrations/owned-generators-1.2-to-1.3.md index 3d87e97a4c..dd909c587b 100644 --- a/docs/features/migrations/owned-generators-1.2-to-1.3.md +++ b/docs/features/migrations/owned-generators-1.2-to-1.3.md @@ -23,8 +23,10 @@ copies you own) and make your edits again in the new file, or edit the copy to d ## Removed exports -- `formatTs` (a no-op) is no longer exported from `@metaobjectsdev/codegen-ts`. Delete the import - from an owned copy; the call did nothing. +- `formatTs` is no longer exported from `@metaobjectsdev/codegen-ts` or `/engine`: generation runs + no formatter (the writer lays out the text, ADR-0063). Replace `await formatTs(text)` with + `text`, or call a formatter of your own. A generator you wrote yourself, not only an ejected + copy, fails with `formatTs is not a function` until you do. - The vendored ts-poet printer (`poet.ts`) and its exports (`code`, `imp`, `joinCode`, `Code` and the rest) are removed, and so is the CLI's rewrite of ts-poet imports in ejected copies. Lay out output with the code writer (`CodeWriter`, `TsWriter`, ADR-0063), exported from @@ -32,9 +34,32 @@ copies you own) and make your edits again in the new file, or edit the copy to d writer's fragments replace the poet nodes: `frag` and `joinFrags` for `code` and `joinCode`, `importName` and `importType` for `imp`, and the `Frag` and `TsImport` types for `Code` and `Import`. A copy that imports `ts-poet` or those names does not compile; re-eject it. -- The queries template's `render*Fn` functions and `schemaInputType` are removed; the template - writes each function through the writer. A copy of the `queries` generator that called them - does not compile; re-eject it. +- The entity sub-renderers (`renderZodValidators`, `renderEnumTypeAliases`, + `renderValueObjectInterface`, `renderDrizzleSchema` and the rest) return a `Frag`, not a ts-poet + `Code`. A `Frag` carries its imports beside its text; `joinFrags` and the writer merge them. A + 1.2 entity composer that joins the sections with `joinCode(sections).toString()` runs, but each + section prints its own imports, so the file declares `import { z } from "zod"` once per section + and does not compile (`Identifier 'z' has already been declared`, TS2300). `meta gen` and + `meta verify --codegen` parse emitted TypeScript and refuse such a file by name, writing + nothing. Compose with `joinFrags(sections, "\n")` and write it with `TsWriter.fragment(...)`, or + re-eject `entity`. +- The queries template's seven primitives and `schemaInputType` are removed; the template writes + each function through the writer. Each `renderFn` returned a ts-poet `Code`; its + replacement writes into the `TsWriter` you pass and returns nothing: + + | 1.2 | 1.3 | + |---|---| + | `renderFindByIdFn(entity, ctx)` | `writeFindByIdFn(w, entity, ctx, readVar?)` | + | `renderListFn` | `writeListFn(w, entity, ctx, readVar?)` | + | `renderCreateFn` | `writeCreateFn(w, entity, ctx)` | + | `renderInsertPreservingFn` | `writeInsertPreservingFn(w, entity, ctx)` | + | `renderUpdateFn` | `writeUpdateFn(w, entity, ctx)` | + | `renderDeleteByIdFn` | `writeDeleteByIdFn(w, entity, ctx)` | + | `renderReverseFinderFns` | `writeReverseFinderFns(w, entity, fk, ctx, readVar?)` | + + A copy of the `queries` generator that called them fails `meta gen` with `renderFindByIdFn is + not a function`. Re-eject it (`meta eject queries --force`) and re-apply your changes; to change + one verb's body, write your own function in its place. ## `meta eject` compares trimmed lines diff --git a/docs/features/prerelease.md b/docs/features/prerelease.md index 52af1244ce..9280fdf8e7 100644 --- a/docs/features/prerelease.md +++ b/docs/features/prerelease.md @@ -272,7 +272,7 @@ npm install and to get back off it: ```bash -tools/prerelease/prerelease-link.sh unlink # --to defaults to the current npm `latest` +tools/prerelease/prerelease-link.sh unlink # --to defaults to the pins link found; with no record, the npm `latest` npm install ``` diff --git a/docs/recipes/write-your-own-generator.md b/docs/recipes/write-your-own-generator.md index d185d4601c..65a98e524e 100644 --- a/docs/recipes/write-your-own-generator.md +++ b/docs/recipes/write-your-own-generator.md @@ -343,6 +343,13 @@ way as the stock one it replaces. The single-purpose markers that came before (` and a copy is no longer treated as providing something because of its name. An owned 1.2 copy must be re-ejected (`meta eject --force`) or edited to declare `provides`. +The declaration also narrows what a generator is offered. Queries and route files import the +entity module. So in a run with a `provides.entityModule` generator, `ctx.matches` is false, for a +generator declaring `provides.queries` or `provides.routes`, on an object that no entity-module +generator's `filter` accepts. The run warns, naming the generator and the object, and the API +reference and the OpenAPI document leave out the same query helpers and routes. Widen the +entity-module generator's filter, or narrow the other generator's. + ## Reads outside the model: declare them, or `meta gen` may skip your output `meta gen` skips a run when nothing it is built from has changed ([ADR-0064](../../spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md)). @@ -414,6 +421,12 @@ the port's helper — `objectRefTarget` / `object_ref_target` / `ResolveFieldRef `ModelWalk.objectRefTarget` — never by matching a short name, because two packages can declare the same one). +To select by package, use the effective package, never the node's `package` property. A +package declared once on the file root (`"metadata.root": { "package": "acme::tasks" }`) is +the file's default: `obj.package` is `undefined` for every object in that file (it is only the +package the node declares itself), while `effectivePackage(obj)` returns `acme::tasks`, as +`obj.resolutionKey()` does. So `filter: (obj) => effectivePackage(obj) === "acme::tasks"`. + TypeScript's public helpers for the rest: `enumValues`, `objectRefTarget`, `effectivePackage`, `packageToPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / `pluralize`, `servedPath(obj, prefix)` (the address the reference routes serve), and the diff --git a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts index 700b9b5f1d..521d60d9d1 100644 --- a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts +++ b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts @@ -146,13 +146,13 @@ export function durationColumnDataType(dialect: Dialect): string { * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or * month part is not a fixed-length span: reading one throws. */ -export function writeDurationColumnDecl(w: CodeWriter, dialect: Dialect, customTypeName: string): void { +export function writeDurationColumnDecl(w: TsWriter, dialect: Dialect, customTypeName: string): void { const postgres = dialect === "postgres"; - w.line("/** A field.duration column. Binds " + (postgres + w.commentLine("/** A field.duration column. Binds " + (postgres ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" : "the span as a 64-bit integer count of microseconds (refused past that range);")); - w.line(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); - w.line(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); + w.commentLine(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); + w.commentLine(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); w.block(`const ${DURATION_COLUMN_FN} = (() => {`, () => { writeUnits(w); w.line(`const INT64_MAX = BigInt("9223372036854775807");`); diff --git a/examples/advanced-modeling/codegen/templates/jsdoc.ts b/examples/advanced-modeling/codegen/templates/jsdoc.ts index 5b36aed32a..7e9b607320 100644 --- a/examples/advanced-modeling/codegen/templates/jsdoc.ts +++ b/examples/advanced-modeling/codegen/templates/jsdoc.ts @@ -6,7 +6,7 @@ import { DOC_ATTR_SEE_ALSO, DOC_ATTR_TITLE, } from "@metaobjectsdev/metadata"; -import { CodeWriter } from "@metaobjectsdev/codegen-ts/engine"; +import { TsWriter } from "@metaobjectsdev/codegen-ts/engine"; export interface DocAttrs { description?: string; @@ -60,8 +60,8 @@ export function jsDocLines(attrs: DocAttrs): string[] { } /** Write a node's JSDoc block (nothing when it has no doc attrs), one line at a time. */ -export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown }): void { - for (const l of jsDocLines(readDocAttrs(node))) w.line(l); +export function writeDocsFor(w: TsWriter, node: { attr: (n: string) => unknown }): void { + for (const l of jsDocLines(readDocAttrs(node))) w.commentLine(l); } /** @@ -69,8 +69,8 @@ export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown * with no final line break. Returns "" if no relevant attrs are set. */ export function renderJsDocBlock(attrs: DocAttrs): string { - const w = new CodeWriter(); - for (const l of jsDocLines(attrs)) w.line(l); + const w = new TsWriter(); + for (const l of jsDocLines(attrs)) w.commentLine(l); return w.toString().trimEnd(); } diff --git a/examples/showcase/codegen/templates/duration-wire-helper.ts b/examples/showcase/codegen/templates/duration-wire-helper.ts index 700b9b5f1d..521d60d9d1 100644 --- a/examples/showcase/codegen/templates/duration-wire-helper.ts +++ b/examples/showcase/codegen/templates/duration-wire-helper.ts @@ -146,13 +146,13 @@ export function durationColumnDataType(dialect: Dialect): string { * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or * month part is not a fixed-length span: reading one throws. */ -export function writeDurationColumnDecl(w: CodeWriter, dialect: Dialect, customTypeName: string): void { +export function writeDurationColumnDecl(w: TsWriter, dialect: Dialect, customTypeName: string): void { const postgres = dialect === "postgres"; - w.line("/** A field.duration column. Binds " + (postgres + w.commentLine("/** A field.duration column. Binds " + (postgres ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" : "the span as a 64-bit integer count of microseconds (refused past that range);")); - w.line(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); - w.line(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); + w.commentLine(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); + w.commentLine(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); w.block(`const ${DURATION_COLUMN_FN} = (() => {`, () => { writeUnits(w); w.line(`const INT64_MAX = BigInt("9223372036854775807");`); diff --git a/examples/showcase/codegen/templates/jsdoc.ts b/examples/showcase/codegen/templates/jsdoc.ts index 5b36aed32a..7e9b607320 100644 --- a/examples/showcase/codegen/templates/jsdoc.ts +++ b/examples/showcase/codegen/templates/jsdoc.ts @@ -6,7 +6,7 @@ import { DOC_ATTR_SEE_ALSO, DOC_ATTR_TITLE, } from "@metaobjectsdev/metadata"; -import { CodeWriter } from "@metaobjectsdev/codegen-ts/engine"; +import { TsWriter } from "@metaobjectsdev/codegen-ts/engine"; export interface DocAttrs { description?: string; @@ -60,8 +60,8 @@ export function jsDocLines(attrs: DocAttrs): string[] { } /** Write a node's JSDoc block (nothing when it has no doc attrs), one line at a time. */ -export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown }): void { - for (const l of jsDocLines(readDocAttrs(node))) w.line(l); +export function writeDocsFor(w: TsWriter, node: { attr: (n: string) => unknown }): void { + for (const l of jsDocLines(readDocAttrs(node))) w.commentLine(l); } /** @@ -69,8 +69,8 @@ export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown * with no final line break. Returns "" if no relevant attrs are set. */ export function renderJsDocBlock(attrs: DocAttrs): string { - const w = new CodeWriter(); - for (const l of jsDocLines(attrs)) w.line(l); + const w = new TsWriter(); + for (const l of jsDocLines(attrs)) w.commentLine(l); return w.toString().trimEnd(); } 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 3c3b010c8f..bee4e9c856 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 @@ -48,7 +48,9 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`. (The `formatTs` no-op export was removed in 1.3.0; delete the import from an owned copy.) The config's `apiPrefix` is +`pluralize`. (`formatTs` was removed in 1.3.0: replace each `await formatTs(text)` with `text` or +your own formatter; see `docs/features/migrations/owned-generators-1.2-to-1.3.md` in the +MetaObjects repository.) The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md index 9eb3a5ada6..190ce7d130 100644 --- a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md @@ -5,7 +5,7 @@ The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. - The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. ## Tables diff --git a/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md b/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md index 5872aad2eb..5ca213efcc 100644 --- a/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md +++ b/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md @@ -5,7 +5,7 @@ The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. - The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. > **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text `meta schema` emits as a `COMMENT ON`, so it lands in the database too. diff --git a/fixtures/rules-check-conformance/README.md b/fixtures/rules-check-conformance/README.md index efb7fd7e81..96cb729a10 100644 --- a/fixtures/rules-check-conformance/README.md +++ b/fixtures/rules-check-conformance/README.md @@ -23,6 +23,7 @@ work: read a loaded model, report diagnostics. | `WARN_LIFECYCLE_INITIAL_TERMINAL` | `warn` | The initial state is terminal: no transition lists it in `@from` (a self-transition counts as leaving). | | `WARN_TRANSITION_UNREACHABLE` | `verify.lifecycle.unreachable` | A transition whose every `@from` state is unreachable, so it can never be made. | | `WARN_TRANSITION_PERMISSION_SHADOWED` | `warn` | A transition that declares `@permission` or `@public: true` but derives no command of its own for any concrete entity with a source that carries it, so nothing reads the attribute: every carrier's transition is claimed by a declared command (`rules.lifecycle.commands: unclaimed`), or `rules.lifecycle.commands` is `none`. Never reported under `all`. One diagnostic per transition node, at its declaring address, naming the claiming commands as `.`. | +| `WARN_DERIVED_COMMAND_BYPASSES_DECLARED` | `warn`, only under `rules.lifecycle.commands: all` | A transition a declared command claims, which `all` also derives a command for: the derived command makes the same transition without running the declared command's body, and asks about the derived permission name. Reported per concrete entity with a source, at `::..`, naming the claiming commands as `.` and the derived command as `.`. Never reported under `unclaimed` or `none`, and independent of `rules.permissions.names`. | | `WARN_PERMISSION_DERIVED_NAME` | `rules.permissions.names`: `derive` (default) skips it, `advise` warns, `require` errors | An operation, or a transition that derives a command of its own, with no `@permission` and not `@public: true`. Which transitions derive a command is `rules.lifecycle.commands`: `unclaimed` (default) means those no declared command claims for that entity, `all` means every transition, `none` means none. | A command claims a transition NODE, for its target entity and every entity that extends the @@ -86,7 +87,8 @@ edited to make a port pass. | `lifecycle-create-any` | The same model with `rules.lifecycle.create: any`: the key is read and changes nothing `verify` reports. | | `permission-names-advise` | `rules.permissions.names: advise`: warns on the unclaimed `submit` transition and on the two operations without `@permission`; not on a claimed transition, one with `@permission`, or anything `@public`. | | `permission-names-require` | The same findings as errors under `require`. | -| `permission-names-commands-all` | `rules.lifecycle.commands: all`: the claimed transitions derive commands too, so they are reported as well. | +| `permission-names-commands-all` | `rules.lifecycle.commands: all`: the claimed transitions derive commands too, so they are reported as well, and as bypassing the declared command. | +| `commands-all-declared-bypass` | `rules.lifecycle.commands: all` at the default `rules.permissions.names`: each claimed transition is reported as bypassing its declaring command, and nothing else is. | | `permission-names-commands-none` | `rules.lifecycle.commands: none`: no transition derives a command, so only operations are reported for permission names, and each transition declaring `@permission` or `@public: true` is reported as shadowed. | | `unreachable-state` | Two unreachable states reported in one diagnostic, and the transition that starts only from them; a transition with one reachable `@from` state is not reported. | | `unreachable-state-error` | The same findings as errors under `verify.lifecycle.unreachable: error`. | diff --git a/fixtures/rules-check-conformance/commands-all-declared-bypass/expected.json b/fixtures/rules-check-conformance/commands-all-declared-bypass/expected.json new file mode 100644 index 0000000000..86ec4b6ccc --- /dev/null +++ b/fixtures/rules-check-conformance/commands-all-declared-bypass/expected.json @@ -0,0 +1,21 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_DERIVED_COMMAND_BYPASSES_DECLARED", + "path": "acme::purchasing::PurchaseRequest.status.approve", + "message": "transition \"approve\" of \"PurchaseRequest\" is claimed by \"Purchasing.decide\", but rules.lifecycle.commands is \"all\", so the derived command \"PurchaseRequest.approve\" makes the same transition without running its body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command." + }, + { + "severity": "warn", + "code": "WARN_DERIVED_COMMAND_BYPASSES_DECLARED", + "path": "acme::purchasing::PurchaseRequest.status.approveFirst", + "message": "transition \"approveFirst\" of \"PurchaseRequest\" is claimed by \"Purchasing.decide\", but rules.lifecycle.commands is \"all\", so the derived command \"PurchaseRequest.approveFirst\" makes the same transition without running its body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command." + } + ], + "summary": { + "operations": 4, + "lifecycles": 1, + "transitions": 5 + } +} diff --git a/fixtures/rules-check-conformance/commands-all-declared-bypass/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/commands-all-declared-bypass/input/meta.purchasing.yaml new file mode 100644 index 0000000000..dc1fdce62d --- /dev/null +++ b/fixtures/rules-check-conformance/commands-all-declared-bypass/input/meta.purchasing.yaml @@ -0,0 +1,43 @@ +metadata: + package: acme::purchasing + children: + - object.entity: + name: PurchaseRequest + children: + - source.rdb: { table: purchase_requests } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.enum: + name: status + values: [draft, submitted, approved, rejected] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - transition.action: { name: reject, from: [submitted], to: rejected, permission: purchasing.review } + - transition.action: { name: approveFirst, from: [submitted], to: submitted } + - transition.action: { name: withdraw, from: [submitted], to: draft, public: true } + - object.value: + name: DecisionInput + children: + - field.long: { name: requestId, extends: PurchaseRequest.id } + - field.string: { name: comment } + - object.projection: + name: RequestSummary + children: + - source.rdb: { kind: view, view: v_request_summary } + - field.long: { name: id, extends: PurchaseRequest.id } + - identity.primary: { name: pk, extends: PurchaseRequest.pk } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, approveFirst] + - operation.command: + name: escalate + inputRef: DecisionInput + permission: purchasing.escalate + - operation.query: { name: openRequests, outputRef: RequestSummary, many: true, public: true } + - operation.query: { name: requestSummary, outputRef: RequestSummary } diff --git a/fixtures/rules-check-conformance/commands-all-declared-bypass/options.json b/fixtures/rules-check-conformance/commands-all-declared-bypass/options.json new file mode 100644 index 0000000000..c3d09f7f53 --- /dev/null +++ b/fixtures/rules-check-conformance/commands-all-declared-bypass/options.json @@ -0,0 +1 @@ +{ "rules": { "lifecycle": { "commands": "all" } } } diff --git a/fixtures/rules-check-conformance/permission-names-commands-all/expected.json b/fixtures/rules-check-conformance/permission-names-commands-all/expected.json index 35923eadcd..03ee2b299f 100644 --- a/fixtures/rules-check-conformance/permission-names-commands-all/expected.json +++ b/fixtures/rules-check-conformance/permission-names-commands-all/expected.json @@ -1,5 +1,17 @@ { "diagnostics": [ + { + "severity": "warn", + "code": "WARN_DERIVED_COMMAND_BYPASSES_DECLARED", + "path": "acme::purchasing::PurchaseRequest.status.approve", + "message": "transition \"approve\" of \"PurchaseRequest\" is claimed by \"Purchasing.decide\", but rules.lifecycle.commands is \"all\", so the derived command \"PurchaseRequest.approve\" makes the same transition without running its body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command." + }, + { + "severity": "warn", + "code": "WARN_DERIVED_COMMAND_BYPASSES_DECLARED", + "path": "acme::purchasing::PurchaseRequest.status.approveFirst", + "message": "transition \"approveFirst\" of \"PurchaseRequest\" is claimed by \"Purchasing.decide\", but rules.lifecycle.commands is \"all\", so the derived command \"PurchaseRequest.approveFirst\" makes the same transition without running its body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command." + }, { "severity": "warn", "code": "WARN_PERMISSION_DERIVED_NAME", diff --git a/fixtures/writer-conformance/cases/error-leading-tab-in-open.json b/fixtures/writer-conformance/cases/error-leading-tab-in-open.json new file mode 100644 index 0000000000..5f1d77dcdd --- /dev/null +++ b/fixtures/writer-conformance/cases/error-leading-tab-in-open.json @@ -0,0 +1,20 @@ +{ + "description": "open() refuses text that starts with whitespace, a tab included.", + "dialect": "core", + "options": { + "indent": " ", + "width": 40, + "trailingComma": true + }, + "ops": [ + [ + "open", + "\tclass A {" + ], + [ + "close", + "}" + ] + ], + "error": "ERR_WRITER_LEADING_WHITESPACE" +} diff --git a/fixtures/writer-conformance/cases/error-leading-whitespace-in-line.json b/fixtures/writer-conformance/cases/error-leading-whitespace-in-line.json new file mode 100644 index 0000000000..ee17edb4ee --- /dev/null +++ b/fixtures/writer-conformance/cases/error-leading-whitespace-in-line.json @@ -0,0 +1,28 @@ +{ + "description": "line() refuses text that starts with whitespace: indentation comes only from open blocks, so a piece that carries its own indent would sit deeper than its siblings.", + "dialect": "core", + "options": { + "indent": " ", + "width": 40, + "trailingComma": true + }, + "ops": [ + [ + "open", + "class A {" + ], + [ + "line", + "a;" + ], + [ + "line", + " b;" + ], + [ + "close", + "}" + ] + ], + "error": "ERR_WRITER_LEADING_WHITESPACE" +} diff --git a/fixtures/writer-conformance/cases/py-doc-keeps-line-indentation.json b/fixtures/writer-conformance/cases/py-doc-keeps-line-indentation.json new file mode 100644 index 0000000000..7869f6770c --- /dev/null +++ b/fixtures/writer-conformance/cases/py-doc-keeps-line-indentation.json @@ -0,0 +1,29 @@ +{ + "description": "A docstring line keeps its own indentation (a worked example inside the text); the leading-whitespace refusal is for line(), open() and close().", + "dialect": "python", + "ops": [ + [ + "open", + "def f():" + ], + [ + "doc", + "Example:", + " f()" + ], + [ + "line", + "pass" + ], + [ + "dedent" + ] + ], + "expected": [ + "def f():", + " \"\"\"Example:", + " f()", + " \"\"\"", + " pass" + ] +} diff --git a/scripts/lib/changelog-fragments.mjs b/scripts/lib/changelog-fragments.mjs index aca9114feb..caf9d1bb5f 100644 --- a/scripts/lib/changelog-fragments.mjs +++ b/scripts/lib/changelog-fragments.mjs @@ -84,3 +84,24 @@ export function assembleChangelog(changelog, fragments) { const entries = fragments.map((f) => f.text.replace(/\s+$/, "")).join("\n\n"); return `${head}\n${entries}\n\n${rest}`; } + +/** + * Why a release candidate of `version` must not be cut yet, or `null`. A candidate is what + * adopters upgrade against with the CHANGELOG's upgrade list open, so when `## []` was + * prepared ahead of the cut, fragments still in `changelog.d/` are changes (and `Upgrading:` + * paragraphs) that list does not carry. Fold them in first. + * @param {string} changelog the CHANGELOG.md text + * @param {string} version the base version the candidate is of, e.g. `1.3.0` + * @param {{ name: string }[]} fragments + * @returns {string | null} + */ +export function unfoldedFragmentsProblem(changelog, version, fragments) { + if (fragments.length === 0) return null; + if (!changelog.includes(`\n## [${version}]`)) return null; + return ( + `CHANGELOG.md has a prepared [${version}] section and ${fragments.length} fragment(s) in ` + + `${FRAGMENT_DIR}/ are not folded into it (${fragments.map((f) => f.name).join(", ")}). ` + + `Fold them in (node scripts/changelog-fragments.mjs --assemble, then move each entry into the ` + + `section and each Upgrading: paragraph into its upgrade list) before cutting a candidate.` + ); +} diff --git a/scripts/prerelease.mjs b/scripts/prerelease.mjs index 905e94720e..c243b54d33 100644 --- a/scripts/prerelease.mjs +++ b/scripts/prerelease.mjs @@ -62,6 +62,7 @@ import { execSync } from "node:child_process"; import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from "node:fs"; import { join } from "node:path"; +import { FRAGMENT_DIR, readFragments, unfoldedFragmentsProblem } from "./lib/changelog-fragments.mjs"; import { mavenVersion } from "./maven-coordinate.mjs"; import { TIER_ORDER } from "./publish-set.mjs"; import { @@ -278,6 +279,15 @@ const VERSION_FILES = [ const dirty = sh(`git status --porcelain -- ${VERSION_FILES.map((f) => `'${f}'`).join(" ")}`).trim(); if (dirty) die(`version-bearing files are dirty — commit or stash first:\n${dirty}`); ok("version-bearing files clean"); +// ── GATE 7 — a full candidate carries a complete upgrade list ────────────────────────── +// A candidate (`--only all`) is what adopter estates run against the CHANGELOG's upgrade list, +// so fragments left beside a prepared section would ship changes that list does not explain. +if (ONLY.length === ALL.length) { + const unfolded = unfoldedFragmentsProblem( + readFileSync(join(ROOT, "CHANGELOG.md"), "utf8"), BASEVER, readFragments(join(ROOT, FRAGMENT_DIR))); + if (unfolded) die(unfolded); + ok("changelog fragments folded into the prepared section"); +} // Whether the tree the candidate is built from has uncommitted work, taken now, before any // version edit and before restore(). New untracked files count; the candidate log itself does not. const CANDIDATE_LOG = "tools/prerelease/candidates.md"; diff --git a/scripts/test-changelog-fragments.mjs b/scripts/test-changelog-fragments.mjs index b19405ef47..e12de918f5 100644 --- a/scripts/test-changelog-fragments.mjs +++ b/scripts/test-changelog-fragments.mjs @@ -6,7 +6,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; -import { assembleChangelog, fragmentNames, fragmentProblems, readFragments } from "./lib/changelog-fragments.mjs"; +import { assembleChangelog, fragmentNames, fragmentProblems, readFragments, unfoldedFragmentsProblem } from "./lib/changelog-fragments.mjs"; let fails = 0; const check = (cond, label) => (cond ? console.log(`ok: ${label}`) : (console.error(`FAIL: ${label}`), fails++)); @@ -38,6 +38,10 @@ check(fragmentProblems("x.md", "- one\n- two\n").some((p) => p.includes("one cha check(fragmentProblems("x.md", "- one\n - nested\n").length === 0, "a nested bullet is allowed"); check(fragmentProblems("x.md", "- one\n### Fixed\n").some((p) => p.includes("heading")), "a heading line is refused"); check(fragmentProblems("Bad Name.md", "- ok\n").some((p) => p.includes("name")), "a name with capitals or spaces is refused"); + +check(unfoldedFragmentsProblem(empty, "1.3.0", [A])?.includes("a-fix.md") === true, "a candidate of a prepared section refuses while a fragment is unfolded, naming it"); +check(unfoldedFragmentsProblem(empty, "1.3.0", []) === null, "a prepared section with no fragments may be cut"); +check(unfoldedFragmentsProblem(LOG, "1.3.0", [A]) === null, "with no prepared section the fragments wait for the release to assemble them"); check(fragmentProblems("x.txt", "- ok\n").some((p) => p.includes("name")), "a name not ending in .md is refused"); const dir = mkdtempSync(join(process.env.DEV_SCRATCH || tmpdir(), "changelog-fragments-")); diff --git a/server/csharp/MetaObjects.Codegen.Tests/ApiDocsRunTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ApiDocsRunTests.cs index 4ac1cb1148..34650bf21d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ApiDocsRunTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ApiDocsRunTests.cs @@ -149,6 +149,78 @@ public void Two_pages_at_one_path_fail_the_run() e.Contains("duplicate generated output path \"api/csharp/X.md\"", StringComparison.Ordinal)); } + [Fact] + public void Gen_refuses_output_containing_a_stringified_object_naming_file_and_generator() + { + var outcome = Gen(new OwnedDocs(Docs, "api/csharp/X.md", "value: [object Object]\n")); + + Assert.False(outcome.Ok); + Assert.Contains(outcome.LoadErrors, e => + e.Contains("ERR_GEN_STRINGIFIED_OBJECT", StringComparison.Ordinal) + && e.Contains("api/csharp/X.md", StringComparison.Ordinal) + && e.Contains("\"api-docs\"", StringComparison.Ordinal)); + Assert.Empty(FilesUnder(Docs)); + } + + /// Copies each entity's @description into a page, the way documentation does. + private sealed class DescribesEntities(string outDir) : IGenerator + { + public string Name => "describe-entities"; + public string? OutDir => outDir; + public IEnumerable Generate(GenContext ctx) => + [new EmittedFile("described.md", string.Concat(ctx.Entities.Select(e => $"{e.Name}: {e.Attr("description")}\n")))]; + } + + [Fact] + public void Text_a_model_string_carries_is_written_a_description_naming_the_symptom_generates() + { + const string prose = "Fixes the [object Object] label bug"; + var model = Path.Combine(_root, "meta.described.json"); + File.WriteAllText(model, """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Widget", "@description": "Fixes the [object Object] label bug", "children": [ + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } ] } } ] } } + """); + var load = new MetaDataLoader().Load([new FileSource(model)]); + Assert.Empty(load.Errors.Select(e => e.Code + ": " + e.Message)); + + var outcome = CodegenCli.RunGen(load, Out, "Acme.Generated", false, [new DescribesEntities(Docs)], _root); + + Assert.True(outcome.Ok, string.Join("\n", outcome.LoadErrors)); + Assert.Contains($"Widget: {prose}", File.ReadAllText(Path.Combine(Docs, "described.md"))); + } + + [Fact] + public void The_refusal_says_no_model_string_carries_the_marker() + { + var outcome = Gen(new OwnedDocs(Docs, "api/csharp/X.md", "value: [object Object]\n")); + + Assert.Contains(outcome.LoadErrors, e => e.Contains("which no string in the model carries", StringComparison.Ordinal)); + } + + [Fact] + public void The_quoted_string_literal_is_code_on_purpose_and_is_written() + { + var outcome = Gen(new OwnedDocs(Docs, "api/csharp/X.md", "var text = \"[object Object]\";\n")); + + Assert.True(outcome.Ok, string.Join("\n", outcome.LoadErrors)); + Assert.Equal(["api/csharp/X.md"], FilesUnder(Docs)); + } + + [Fact] + public void The_drift_check_fails_on_output_containing_a_stringified_object() + { + var load = Load(); + var config = new GenConfig { OutDir = Out, Namespace = "Acme.Generated" }; + CodegenRunner.Run(config, load.Root, [new EntityGenerator()]); + + var drift = CodegenDrift.Compute(config, load.Root, [new EntityGenerator(), new OwnedDocs(Docs, "api/csharp/X.md", "[object Object]")]); + + Assert.False(drift.Clean); + Assert.Contains("ERR_GEN_STRINGIFIED_OBJECT", drift.Error ?? string.Join("\n", drift.Lines), StringComparison.Ordinal); + } + [Fact] public void The_drift_check_compares_the_entry_directory_and_names_a_hand_edit_by_it() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/ExpressionIndexesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ExpressionIndexesGeneratorTests.cs index 915be1f5ca..a5dbeff0b8 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ExpressionIndexesGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ExpressionIndexesGeneratorTests.cs @@ -45,6 +45,24 @@ private static string Sql(string model) return Assert.Single(new ExpressionIndexesGenerator().Generate(ctx)).Content; } + [Fact] + public void A_multi_line_expression_keeps_its_authors_indentation() + { + var sql = Sql(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Account", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "tenantId" } }, + { "field.string": { "name": "email", "@maxLength": 80 } }, + { "identity.primary": { "@fields": "id" } }, + { "index.lookup": { "name": "ix_accounts_email_tenant", "@expr": "lower(email),\n coalesce(tenant_id, 0)" } } + ] } } + ] } } + """); + Assert.Contains("CREATE INDEX IF NOT EXISTS \"ix_accounts_email_tenant\" ON \"accounts\" (lower(email),\n coalesce(tenant_id, 0));\n", sql); + } + [Fact] public void An_expression_index_an_abstract_base_declares_is_written_on_the_concrete_table() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs index 1bf10f59ff..d618b41899 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs @@ -416,4 +416,21 @@ public void A_non_migrating_save_leaves_gitignore_alone() Record(("gen/Order.cs", "a")); Assert.Equal(".gen-state/*\n!.gen-state/.hashes.json\n", File.ReadAllText(ignore)); } + + [Fact] + public void A_committed_legacy_manifest_beats_a_stale_hashes_dir() + { + // The old .gitignore ignores .hashes/, so one left by another checkout's run survives a + // reset beside the committed .hashes.json; its stale hashes must not count. + Directory.CreateDirectory(HashesDir); + File.WriteAllText(Path.Combine(StateDir, ".hashes.json"), "{\"gen/Order.cs\":\"committed\"}"); + File.WriteAllText(Path.Combine(HashesDir, "acme.shop.json"), + "{\"gen/Order.cs\":\"stale\",\"gen/Gone.cs\":\"stale\"}"); + var loaded = HashManifest.Load(StateDir); + Assert.Equal(new Dictionary { ["gen/Order.cs"] = "committed" }, loaded); + HashManifest.Save(StateDir, loaded); + Assert.False(File.Exists(Path.Combine(StateDir, ".hashes.json"))); + Assert.Equal(new Dictionary { ["gen/Order.cs"] = "committed" }, HashManifest.Load(StateDir)); + } } + diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index 4df44858e7..7d7cd44c14 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -19,6 +19,29 @@ namespace MetaObjects.Codegen; /// Runs a generator set and writes the emitted files. public static class CodegenRunner { + /// "[object Object]" anywhere but as the exact quoted string literal, which is code + /// on purpose (an emitted query-string encoder mirroring JavaScript's). + private static readonly System.Text.RegularExpressions.Regex StringifiedObject = + new("(?True when a string value the model declares contains , so + /// output carrying it may be the model's own prose (an @description, a requirement + /// counterexample). Walks every node's own attrs (ADR-0039: each node is visited, so an + /// inherited value is read on its declaring node). + private static bool ModelMentions(MetaData node, string text) => + node.OwnAttrs().Values.Any(v => ValueMentions(v, text)) + || node.OwnChildren().Any(child => ModelMentions(child, text)); + + private static bool ValueMentions(object? value, string text) => value switch + { + string s => s.Contains(text, StringComparison.Ordinal), + System.Collections.IDictionary d => d.Values.Cast().Any(v => ValueMentions(v, text)), + System.Collections.IEnumerable e => e.Cast().Any(v => ValueMentions(v, text)), + _ => false, + }; + /// Files carrying this marker are owned by codegen and safe to overwrite. public const string GeneratedMarker = ""; @@ -131,6 +154,7 @@ captureKeys is { } ck var manifest = config.GenStateDir is { } stateDir ? new HashManifest.Session(stateDir) : null; // Which generator wrote each recorded path, and from which node (HashManifest.RecordGeneratedProvenance). var provenance = new Dictionary(StringComparer.Ordinal); + bool? modelMentionsMarker = null; // Saved even when a generator throws, so the manifest keeps matching the files already written. try @@ -152,6 +176,15 @@ captureKeys is { } ck throw new InvalidOperationException( $"duplicate generated output path \"{file.Path}\" — emitted by both " + $"\"{emitted[full]}\" and \"{generator.Name}\"."); + // Text an object was turned into reads "[object Object]"; it often still + // compiles, so it is refused by name here, before the write or the drift + // comparison, in gen and verify alike. + if (StringifiedObject.IsMatch(file.Content) && !(modelMentionsMarker ??= ModelMentions(root, StringifiedObjectText))) + throw new InvalidOperationException( + $"ERR_GEN_STRINGIFIED_OBJECT: generated output contains \"[object Object]\", which no string " + + "in the model carries, so " + + $"\"{shown + file.Path}\" (generator \"{generator.Name}\") was not written. A generator " + + "turned an object into text where code belongs; build the text with the code writer instead."); if (generator.HandEdits == HandEdits.Overwrite) overwritePaths.Add(full); if (capture is not null) { diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs index b3587acde6..a86b78ae0a 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExpressionIndexesGenerator.cs @@ -106,16 +106,12 @@ protected virtual void WriteFileHeader(CsWriter w) } /// - /// The statements, in order. The writer still owns the line breaks: an expression written over - /// several lines stays on several lines, each handed to the writer on its own. + /// The statements, in order. An expression written over several lines stays on several lines, + /// each keeping the indentation its author gave it. /// protected virtual void WriteStatements(CsWriter w, IEnumerable statements) { - foreach (var statement in statements) - { - using var lines = new StringReader(statement); - while (lines.ReadLine() is { } line) w.Line(line); - } + foreach (var statement in statements) w.Text(statement); } protected static IEnumerable IndexNodes(MetaObject o) => diff --git a/server/csharp/MetaObjects.Codegen/HashManifest.cs b/server/csharp/MetaObjects.Codegen/HashManifest.cs index eeed5f0bed..7e0ec63a9a 100644 --- a/server/csharp/MetaObjects.Codegen/HashManifest.cs +++ b/server/csharp/MetaObjects.Codegen/HashManifest.cs @@ -267,13 +267,20 @@ private static Dictionary ReadRaw(string genStateDir) => } } - // The union: the legacy file underneath, then every file in .hashes/ in file-name order (a package file wins). + // Every file in .hashes/ in file-name order, or, while a legacy .hashes.json is still present, + // that file alone. A write deletes it right after writing the package files, so a .hashes/ + // beside it is left over from another checkout (the old .gitignore ignores that directory, so + // it survives a reset or a branch switch), and its stale hashes would make every file the + // committed manifest vouches for read as hand-edited. The next write replaces or removes them. 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))) + if (loaded.LegacyPresent) + { + if (ReadOne(LegacyPath(genStateDir)) is { } legacy) + foreach (var (k, v) in legacy) loaded.Raw[k] = v; + } + else if (Directory.Exists(DirPath(genStateDir))) { var names = Directory.EnumerateFiles(DirPath(genStateDir), "*.json") .Select(Path.GetFileName).OfType().Order(StringComparer.Ordinal); diff --git a/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache b/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache index ad91a93c2f..90dfc9bee4 100644 --- a/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache +++ b/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache @@ -14,7 +14,7 @@ The tables, columns and keys this model declares. Read it before writing a query - Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. {{/hasMigrate}} {{^hasMigrate}} -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. {{/hasMigrate}} - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. diff --git a/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs index 9c7424456e..c9e1554969 100644 --- a/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs +++ b/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs @@ -25,6 +25,8 @@ public static class WriterErrors public const string NewlineInLine = "ERR_WRITER_NEWLINE_IN_LINE"; /// One local name imported from two different places. public const string ImportConflict = "ERR_WRITER_IMPORT_CONFLICT"; + /// Line(), Open() or Close() was handed text that starts with a space or tab. + public const string LeadingWhitespace = "ERR_WRITER_LEADING_WHITESPACE"; } /// A writer error: one of the codes and a message for people. @@ -161,9 +163,10 @@ public CodeWriter(CodeWriterOptions options) /// /// One line at the current indent. The parts are concatenated; when the line does not fit the /// width, the LAST non-empty list in it is printed one item per line. A line whose text is empty - /// is a blank-line request. + /// is a blank-line request. Text that starts with whitespace is ERR_WRITER_LEADING_WHITESPACE: + /// indentation comes only from open blocks. /// - public CodeWriter Line(params Piece[] parts) => Put(Piece.Seq(parts)); + public CodeWriter Line(params Piece[] parts) => Put(Unindented(Piece.Seq(parts), "Line")); /// Ask for one blank line before whatever is written next. Requests never stack. public CodeWriter Blank() @@ -173,10 +176,10 @@ public CodeWriter Blank() } /// Write the line that opens a block, then indent. - public CodeWriter Open(params Piece[] parts) => OpenPiece(Piece.Seq(parts)); + public CodeWriter Open(params Piece[] parts) => OpenPiece(Unindented(Piece.Seq(parts), "Open")); /// Dedent, then write the line that closes the block. - public CodeWriter Close(params Piece[] parts) => ClosePiece(Piece.Seq(parts)); + public CodeWriter Close(params Piece[] parts) => ClosePiece(Unindented(Piece.Seq(parts), "Close")); /// /// Open(head), then (on dispose) Close(tail): the indent cannot be left @@ -237,6 +240,20 @@ public override string ToString() /// protected virtual (string Before, Group List, string After)? BreakAt(Piece piece) => LastGroup(piece); + /// + /// Refuse text a caller indented itself: the writer adds the indent, so a pre-indented piece + /// would land one level too deep beside its siblings, silently. + /// + protected static Piece Unindented(Piece piece, string what) + { + var raw = piece.Flat(); + if (raw.Length > 0 && (raw[0] == ' ' || raw[0] == '\t')) + throw new WriterException( + WriterErrors.LeadingWhitespace, + $"{what}() text starts with whitespace; pass it without indentation, the writer indents it from the open blocks: \"{raw}\""); + return piece; + } + protected CodeWriter OpenPiece(Piece piece) { Put(piece); diff --git a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs index 560d8386a3..7b8a095c85 100644 --- a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs +++ b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs @@ -123,9 +123,9 @@ public IDisposable Braced(Piece head, string tail = "}") /// The text is written as given, so it carries any XML escaping it needs. public CsWriter DocSummary(params string[] lines) { - Line("/// "); - foreach (var l in lines) Line(l.Length == 0 ? "///" : "/// " + l); - Line("/// "); + Put("/// "); + foreach (var l in lines) Put(l.Length == 0 ? "///" : "/// " + l); + Put("/// "); return this; } diff --git a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs index 06b922a570..2dfbba3d91 100644 --- a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs +++ b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs @@ -56,6 +56,7 @@ public static class RulesCheck public const string WARN_LIFECYCLE_INITIAL_TERMINAL = "WARN_LIFECYCLE_INITIAL_TERMINAL"; public const string WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE"; public const string WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED"; + public const string WARN_DERIVED_COMMAND_BYPASSES_DECLARED = "WARN_DERIVED_COMMAND_BYPASSES_DECLARED"; public const string WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME"; private static string QuoteList(IEnumerable xs) => string.Join(", ", xs.Select(x => $"\"{x}\"")); @@ -226,6 +227,29 @@ private static void CheckShadowedPermissions(MetaData root, RulesSettings settin } } + /// Under rules.lifecycle.commands: all a transition a declared command claims derives a + /// command of its own as well, which makes the transition without running the declared command's body. + private static void CheckDerivedBypassesDeclared(MetaData root, RulesSettings settings, List output) + { + if (settings.LifecycleCommands != "all") return; + var claimed = ClaimedTransitions(root); + foreach (var entity in CommandEntities(root)) + { + foreach (var t in Lifecycles.EntityTransitions(entity)) + { + var claimers = ClaimsOn(claimed, entity, t) + .Select(c => $"{c.Op.Parent?.Name ?? ""}.{c.Op.Name}").Distinct(StringComparer.Ordinal).ToList(); + if (claimers.Count == 0) continue; + output.Add(new RequirementDiagnostic(SeverityWarn, WARN_DERIVED_COMMAND_BYPASSES_DECLARED, + $"{Address(entity)}.{t.Parent?.Name ?? ""}.{t.Name}", + $"transition \"{t.Name}\" of \"{entity.Name}\" is claimed by {QuoteList(claimers)}, but rules.lifecycle.commands is \"all\", " + + $"so the derived command \"{entity.Name}.{t.Name}\" makes the same transition without running " + + $"{(claimers.Count == 1 ? "its" : "their")} body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or " + + "remove the declared command.")); + } + } + } + private static void CheckPermissionNames(MetaData root, RulesSettings settings, List output) { if (settings.PermissionNames == "derive") return; @@ -294,6 +318,7 @@ public static RulesCheckResult Check(MetaData root, RulesSettings settings) var diagnostics = new List(); foreach (var l in lifecycles) CheckLifecycle(l, settings, diagnostics); CheckShadowedPermissions(root, settings, diagnostics); + CheckDerivedBypassesDeclared(root, settings, diagnostics); CheckPermissionNames(root, settings, diagnostics); return new RulesCheckResult( diagnostics, diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java index ad67cbb6c9..ba91c5631b 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java @@ -161,12 +161,12 @@ public void emit(File outputDir, String javaPackage, String className, String re protected void writeHeader(JavaWriter w, String javaPackage, String className) { if (!isBlank(javaPackage)) w.packageName(javaPackage); w.line("/**"); - w.line(" * GENERATED — extractor for {@code " + className + "}."); - w.line(" *"); - w.line(" *

Turns dirty LLM text into a fully-typed {@code " + className + "} graph (nested"); - w.line(" * objects + arrays-of-objects populated) in one call, by delegating to the Phase-B"); - w.line(" * runtime extract ({@code " + META_OBJECT_EXTRACT_FQN + "}).

"); - w.line(" */"); + w.commentLine(" * GENERATED — extractor for {@code " + className + "}."); + w.commentLine(" *"); + w.commentLine(" *

Turns dirty LLM text into a fully-typed {@code " + className + "} graph (nested"); + w.commentLine(" * objects + arrays-of-objects populated) in one call, by delegating to the Phase-B"); + w.commentLine(" * runtime extract ({@code " + META_OBJECT_EXTRACT_FQN + "}).

"); + w.commentLine(" */"); } /** Write the private {@code lookup(loader)} helper resolving the payload MetaObject by FQN. */ @@ -182,10 +182,10 @@ protected void writeLookupHelper(JavaWriter w, String resolutionKey) { */ protected void writeExtractMethod(JavaWriter w, String className) { w.line("/**"); - w.line(" * Extract a fully-typed {@code " + className + "} from dirty {@code text}."); - w.line(" *"); - w.line(" * @throws com.metaobjects.render.extract.ExtractException iff a required field was lost or malformed"); - w.line(" */"); + w.commentLine(" * Extract a fully-typed {@code " + className + "} from dirty {@code text}."); + w.commentLine(" *"); + w.commentLine(" * @throws com.metaobjects.render.extract.ExtractException iff a required field was lost or malformed"); + w.commentLine(" */"); try (var m = w.block("public static " + className + " extract(" + LOADER_FQN + " loader, String text) {")) { w.line("return (" + className + ") " + META_OBJECT_EXTRACT_FQN + ".extract(lookup(loader), text).orThrow();"); } @@ -198,10 +198,10 @@ protected void writeExtractMethod(JavaWriter w, String className) { protected void writeExtractLenientMethod(JavaWriter w, String className) { String result = EXTRACTION_RESULT_FQN + "<" + className + ">"; w.line("/**"); - w.line(" * Extract a {@code " + className + "} from dirty {@code text}, never throwing."); - w.line(" *"); - w.line(" * @return the typed result; inspect {@code report()} for lost/malformed/defaulted fields"); - w.line(" */"); + w.commentLine(" * Extract a {@code " + className + "} from dirty {@code text}, never throwing."); + w.commentLine(" *"); + w.commentLine(" * @return the typed result; inspect {@code report()} for lost/malformed/defaulted fields"); + w.commentLine(" */"); w.line("@SuppressWarnings(\"unchecked\")"); try (var m = w.block("public static " + result + " extractLenient(" + LOADER_FQN + " loader, String text) {")) { w.line("return (" + result + ") (" + EXTRACTION_RESULT_FQN + ") " diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java index 484216b6ba..d6c899c4d1 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java @@ -175,10 +175,10 @@ private void emitProviderSource(Map fqnToClass) throws IOExcepti w.use("java.util.Map"); w.use("java.util.HashMap"); w.line("/**"); - w.line(" * GENERATED — self-registering " + ObjectClassBindingProvider.class.getSimpleName() + " (ADR-0001)."); - w.line(" * Maps each generated object's metadata resolution key (\"pkg::Name\") to its"); - w.line(" * generated Java class, so MetaObject.newInstance() yields the generated type."); - w.line(" */"); + w.commentLine(" * GENERATED — self-registering " + ObjectClassBindingProvider.class.getSimpleName() + " (ADR-0001)."); + w.commentLine(" * Maps each generated object's metadata resolution key (\"pkg::Name\") to its"); + w.commentLine(" * generated Java class, so MetaObject.newInstance() yields the generated type."); + w.commentLine(" */"); try (var cls = w.block("public final class " + PROVIDER_SIMPLE_NAME + " implements " + ObjectClassBindingProvider.class.getName() + " {")) { w.line("@Override"); 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 cc5655f293..dee258ecb9 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 @@ -1,6 +1,7 @@ package com.metaobjects.generator.util; import com.metaobjects.MetaData; +import com.metaobjects.attr.MetaAttribute; import com.metaobjects.generator.GeneratorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -182,9 +183,20 @@ public static final class Run implements AutoCloseable { // output directory it stands in for. private final Map generated = new LinkedHashMap<>(); private Map realDirByRendered = Map.of(); + // True when a string value in the loaded model carries the stringified-object marker, so + // output carrying it may be the model's own prose. Set by the runner once the model is loaded. + private boolean modelCarriesStringifiedObject; private Run() {} + /** Read the loaded model's string values for the stringified-object marker, so an + * {@code @description} or a requirement counterexample naming it still generates. + * Called by the runner once the model is loaded. */ + public Run readModelText(MetaData root) { + this.modelCarriesStringifiedObject = root != null && mentions(root, STRINGIFIED_OBJECT_TEXT); + return this; + } + /** * The files this run has generated so far, {@code path → provenance}, keyed as the manifest * keys them, after the committed files the runner carried in ({@link #carryCommittedFiles}); @@ -539,6 +551,7 @@ public static Outcome writeUnmarked(Path outFile, byte[] utf8) throws IOExceptio private static Outcome write(Path outFile, String content, boolean unmarked) throws IOException { Run run = ACTIVE_RUN.get(); + refuseStringifiedObject(outFile, content, run); if (run != null) { run.emittedPaths.add(outFile.toAbsolutePath().normalize()); } @@ -632,6 +645,43 @@ private static Outcome writeMarkerOnly(Path outFile, String content, Run run, bo return Outcome.WRITTEN; } + /** + * {@code [object Object]} anywhere but as the exact quoted string literal, which is code on + * purpose (an emitted query-string encoder mirroring JavaScript's). + */ + private static final Pattern STRINGIFIED_OBJECT = Pattern.compile("(? attr && String.valueOf(attr.getValue()).contains(text)) return true; + if (mentions(child, text)) return true; + } + return false; + } + + /** + * Text an object was turned into reads {@code [object Object]} where code belongs. It often + * still compiles, so it is refused by name before the write, and a capture run (the drift + * gate) fails on it the same way instead of reporting the tree in sync. + */ + static void refuseStringifiedObject(Path outFile, String content, Run run) { + if (!STRINGIFIED_OBJECT.matcher(content).find()) return; + if (run != null && run.modelCarriesStringifiedObject) return; + String by = run == null || run.current == null ? "" : " (generator '" + run.current + "')"; + throw new GeneratorException( + "ERR_GEN_STRINGIFIED_OBJECT: generated output contains \"[object Object]\", which no string in the " + + "model carries, so " + outFile + + by + " was not written. A generator turned an object into text where code belongs; " + + "build the text with the code writer instead."); + } + /** * Claim the path in the active run (the ordering/collision check — raised, never * warned, since an order-dependent output is not something the user can act on from a 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 eba31da290..f965c866f4 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 @@ -277,10 +277,17 @@ public static Map loadProvenance(Path genStateDir) { return out; } - /** The union of every manifest file: the legacy one underneath, package files in name order on top. */ + /** + * The manifest: the package files in name order, or, while a legacy {@code .hashes.json} is still + * present, that file alone. A write deletes it right after writing the package files, so a + * {@code .hashes/} beside it is left over from another checkout (the old {@code .gitignore} + * ignores that directory, so it survives a reset or a branch switch), and its stale hashes would + * make every file the committed manifest vouches for read as hand-edited. The next write + * replaces or removes those stale files. + */ private static Map entries(Path genStateDir) { Map out = new LinkedHashMap<>(); - readInto(legacyPath(genStateDir), out); + if (hasLegacy(genStateDir)) return readInto(legacyPath(genStateDir), out); for (Path p : packageFiles(genStateDir)) readInto(p, out); return out; } @@ -303,6 +310,7 @@ private static Map readInto(Path path, Map fileOfKeys(Path genStateDir) { Map out = new LinkedHashMap<>(); + if (hasLegacy(genStateDir)) return out; // the legacy file is authoritative, see entries() for (Path p : packageFiles(genStateDir)) { for (String key : readInto(p, new LinkedHashMap<>()).keySet()) out.put(key, p.getFileName().toString()); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java index f26880b748..0411f48603 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java @@ -46,10 +46,11 @@ public WriterOptions options() { /** * One line at the current indent. The parts are concatenated; when the line does not fit the * width, the LAST non-empty list in it is printed one item per line. A line whose text is - * empty is a blank-line request. + * empty is a blank-line request. Text that starts with whitespace is + * {@code ERR_WRITER_LEADING_WHITESPACE}: indentation comes only from open blocks. */ public CodeWriter line(Object... parts) { - return put(piece(Arrays.asList(parts))); + return put(unindented(piece(Arrays.asList(parts)), "line")); } /** Ask for one blank line before whatever is written next. Requests never stack. */ @@ -60,12 +61,12 @@ public CodeWriter blank() { /** Write the line that opens a block, then indent. */ public CodeWriter open(Object... parts) { - return openPiece(piece(Arrays.asList(parts))); + return openPiece(unindented(piece(Arrays.asList(parts)), "open")); } /** Dedent, then write the line that closes the block. */ public CodeWriter close(Object... parts) { - return closePiece(piece(Arrays.asList(parts))); + return closePiece(unindented(piece(Arrays.asList(parts)), "close")); } /** @@ -168,6 +169,24 @@ protected Split breakAt(Object piece) { return lastGroup(piece); } + /** + * Refuse text a caller indented itself: the writer adds the indent, so a pre-indented piece + * would land one level too deep beside its siblings, silently. + */ + protected Object unindented(Object piece, String what) { + String raw = flat(piece); + if (raw.startsWith(" ") || raw.startsWith("\t")) { + throw new WriterException( + WriterException.LEADING_WHITESPACE, + what + + "() text starts with whitespace; pass it without indentation, the writer indents it" + + " from the open blocks: \"" + + raw + + "\""); + } + return piece; + } + protected CodeWriter openPiece(Object piece) { put(piece); openers.add(flat(piece).strip()); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java index 7282736d62..c68f522869 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java @@ -132,12 +132,22 @@ public JavaWriter doc(String... lines) { for (String l : lines) safe.add(l.replace("*/", "*/")); String one = "/** " + safe.get(0) + " */"; if (safe.size() == 1 && fits(one)) { - line(one); + put(one); return this; } - line("/**"); - for (String l : safe) line(l.isEmpty() ? " *" : " * " + l); - line(" */"); + // put, not line(): the {@code * } lines of a Javadoc start with whitespace by design. + put("/**"); + for (String l : safe) put(l.isEmpty() ? " *" : " * " + l); + put(" */"); + return this; + } + + /** + * One line inside a block comment, such as {@code * text}: it starts with whitespace by design, + * and the writer still indents it from the open blocks. {@link #line} refuses such text. + */ + public JavaWriter commentLine(Object... parts) { + put(piece(Arrays.asList(parts))); return this; } @@ -163,7 +173,8 @@ protected CodeWriter sectionWriter() { /** The {@link #header} lines, as given. */ protected void writeHeader(CodeWriter w) { - for (String l : headLines) w.line(l); + // put, not line(): a header line is written as given, even one that starts with whitespace. + for (String l : headLines) w.put(l); } /** The {@code package} line, when one was set. */ diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java index 672be302c9..2fffbf8ea2 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java @@ -16,6 +16,8 @@ public class WriterException extends RuntimeException { public static final String IMPORT_CONFLICT = "ERR_WRITER_IMPORT_CONFLICT"; /** A piece the writer does not know how to print. */ public static final String UNKNOWN_PIECE = "ERR_WRITER_UNKNOWN_PIECE"; + /** {@code line()}, {@code open()} or {@code close()} was handed text that starts with a space or tab. */ + public static final String LEADING_WHITESPACE = "ERR_WRITER_LEADING_WHITESPACE"; private final String code; diff --git a/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache index ad91a93c2f..90dfc9bee4 100644 --- a/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache +++ b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache @@ -14,7 +14,7 @@ The tables, columns and keys this model declares. Read it before writing a query - Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. {{/hasMigrate}} {{^hasMigrate}} -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. {{/hasMigrate}} - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. 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 39c8fd3fef..e136173123 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 @@ -543,6 +543,48 @@ public void writeIfChanged_writesOnlyWhenTheBytesDiffer() throws Exception { assertEquals("two", Files.readString(out)); } + // === a stringified object never reaches a generated file =========================== + + @Test + public void refusesOutputContainingAStringifiedObject_namingFileAndGenerator() throws Exception { + Path out = tmp.getRoot().toPath().resolve("gen/helper.ts"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.attributeTo("ts-helper"); + GeneratedFileWriter.write(out, "export const x = [object Object];\n"); + fail("expected ERR_GEN_STRINGIFIED_OBJECT"); + } catch (GeneratorException e) { + assertTrue(e.getMessage(), e.getMessage().contains("ERR_GEN_STRINGIFIED_OBJECT")); + assertTrue(e.getMessage(), e.getMessage().contains("helper.ts") && e.getMessage().contains("'ts-helper'")); + } + assertFalse(Files.exists(out)); + } + + @Test + public void thePlainByteWriterIsNotACodegenPathAndWritesTheTextAsGiven() throws Exception { + Path out = tmp.getRoot().toPath().resolve("meta/meta.base.json"); + String metadata = "{ \"@description\": \"Fixes the [object Object] label bug\" }\n"; + assertTrue(GeneratedFileWriter.writeIfChanged(out, metadata)); + assertEquals(metadata, Files.readString(out)); + } + + @Test + public void aCaptureRunFailsOnAStringifiedObjectToo() throws Exception { + Path out = tmp.getRoot().toPath().resolve("virtual/helper.ts"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginCaptureRun()) { + GeneratedFileWriter.write(out, "[object Object]"); + fail("expected ERR_GEN_STRINGIFIED_OBJECT"); + } catch (GeneratorException e) { + assertTrue(e.getMessage().contains("ERR_GEN_STRINGIFIED_OBJECT")); + } + } + + @Test + public void theQuotedStringLiteralIsCodeOnPurposeAndIsWritten() throws Exception { + Path out = tmp.getRoot().toPath().resolve("gen/Q.java"); + String body = "/** GENERATED */\nclass Q { String t = \"[object Object]\"; }\n"; + assertEquals(GeneratedFileWriter.Outcome.WRITTEN, GeneratedFileWriter.write(out, body)); + } + @Test public void captureRun_holdsEveryWriteInMemoryAndWritesNothing() throws Exception { Path a = tmp.getRoot().toPath().resolve("virtual/out/A.java"); 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 index a682ed0726..2c5326be93 100644 --- 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 @@ -338,13 +338,30 @@ public void readOnlyLoadOfALegacyManifestMigratesNothing() throws Exception { } @Test - public void aPackageFileWinsOverTheLegacyFile() throws Exception { + public void thePackageFilesAreUnreadWhileTheLegacyFileIsPresent() throws Exception { + // ADR-0064 §2 (corrected): a .hashes/ beside an unmigrated .hashes.json is stale. 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("old", loaded.get("gen/A.java")); assertEquals("b", loaded.get("gen/B.java")); } + + @Test + public void aCommittedLegacyManifestBeatsAStaleHashesDir() throws Exception { + // The old .gitignore ignores .hashes/, so one left by another checkout's run survives a + // reset beside the committed .hashes.json; its stale hashes must not count. + Path gs = tmp.newFolder("stale-hashes").toPath(); + Files.writeString(gs.resolve(".hashes.json"), "{\"gen/Order.java\":\"committed\"}"); + Files.createDirectories(gs.resolve(".hashes")); + Files.writeString(gs.resolve(".hashes").resolve("acme.shop.json"), + "{\"gen/Order.java\":\"stale\",\"gen/Gone.java\":\"stale\"}"); + Map loaded = HashManifest.load(gs); + assertEquals(Map.of("gen/Order.java", "committed"), loaded); + HashManifest.save(gs, new LinkedHashMap<>(loaded), new LinkedHashMap<>()); + assertFalse(Files.exists(gs.resolve(".hashes.json"))); + assertEquals(Map.of("gen/Order.java", "committed"), HashManifest.load(gs)); + } } diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/StringifiedObjectModelTextTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/StringifiedObjectModelTextTest.java new file mode 100644 index 0000000000..6298c77f8f --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/StringifiedObjectModelTextTest.java @@ -0,0 +1,62 @@ +package com.metaobjects.generator.util; + +import com.metaobjects.generator.GeneratorException; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.loader.MetaDataLoaderTestBase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * The stringified-object refusal allows the marker when the loaded model's own string values carry + * it: an {@code @description} naming the symptom is prose, not an object turned into text. + */ +public class StringifiedObjectModelTextTest extends MetaDataLoaderTestBase { + + @Rule public TemporaryFolder tmp = new TemporaryFolder(); + + private static final String PROSE = "Fixes the [object Object] label bug"; + + private MetaDataLoader load(String description) throws Exception { + Path model = tmp.getRoot().toPath().resolve("meta.widget.json"); + Files.writeString(model, "{ \"metadata.root\": { \"package\": \"acme\", \"children\": [\n" + + " { \"object.value\": { \"name\": \"Widget\", \"@description\": \"" + description + "\", \"children\": [\n" + + " { \"field.string\": { \"name\": \"label\" } } ] } } ] } }\n"); + return initLoader(List.of(model.toUri())); + } + + @Test + public void textAModelStringCarriesIsWritten() throws Exception { + MetaDataLoader loader = load(PROSE); + Path out = tmp.getRoot().toPath().resolve("gen/Widget.md"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.readModelText(loader.getRoot()).attributeTo("docs"); + assertEquals(GeneratedFileWriter.Outcome.WRITTEN, GeneratedFileWriter.write(out, "Widget: " + PROSE + "\n")); + } + assertTrue(Files.readString(out).contains(PROSE)); + } + + @Test + public void aStringifiedObjectIsStillRefusedWhenNoModelStringCarriesIt() throws Exception { + MetaDataLoader loader = load("Fixes the label bug"); + Path out = tmp.getRoot().toPath().resolve("gen/helper.ts"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.readModelText(loader.getRoot()).attributeTo("ts-helper"); + GeneratedFileWriter.write(out, "export const x = [object Object];\n"); + fail("expected ERR_GEN_STRINGIFIED_OBJECT"); + } catch (GeneratorException e) { + assertTrue(e.getMessage(), e.getMessage().contains("which no string in the model carries")); + assertTrue(e.getMessage(), e.getMessage().contains("'ts-helper'")); + } + assertFalse(Files.exists(out)); + } +} diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt index dbe65197a3..3e4e05b8c5 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt @@ -72,7 +72,7 @@ object KotlinDecimalWireEmitter { * GENERATED (ADR-0019 Amendment 1) — do not hand-edit. The decimal wire rule: a decimal is """ ) - w.line( + w.commentLine( if (asString) " * written as a canonical string (plain notation, no trailing fraction zeros, zero as \"0\")," else " * written as the host serializer writes it,", ) diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt index a4845f3b53..532cc64b31 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt @@ -584,15 +584,15 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseExtracts the typed response VO from {@code input.llmResponseText()} and"); - w.line(" * persists ONE trace row (base envelope + raw I/O + typed voRequest/voResponse)"); - w.line(" * via the supplied recorder. The render-call-record helper is intentionally"); - w.line(" * not emitted (BYO vendor-neutral caller; Java LlmClient seam not ported).

"); - w.line(" */"); + w.commentLine(" * Typed LLM-trace helper for {@code " + shortName + "}."); + w.commentLine(" *"); + w.commentLine(" *

Extracts the typed response VO from {@code input.llmResponseText()} and"); + w.commentLine(" * persists ONE trace row (base envelope + raw I/O + typed voRequest/voResponse)"); + w.commentLine(" * via the supplied recorder. The render-call-record helper is intentionally"); + w.commentLine(" * not emitted (BYO vendor-neutral caller; Java LlmClient seam not ported).

"); + w.commentLine(" */"); try (var cls = w.block("public final class " + helperClass + " {")) { w.line("private " + helperClass + "() { /* no instances */ }"); w.blank(); @@ -242,14 +242,14 @@ protected void emit(MetaObject entity, MetaDataLoader loader, Path outRoot) { protected void writeRecordMethod(SpringJavaWriter w, MetaObject entity, MetaObject responseVo, String shortName, String resultClass, String fnName, String formatEnum) { w.line("/**"); - w.line(" * Record a single {@code " + shortName + "} LLM call: extract the response VO and persist a"); - w.line(" * trace row via {@code recorder} regardless of whether extraction succeeded."); - w.line(" *"); - w.line(" * @param loader the loader the trace + response MetaObjects resolve against"); - w.line(" * @param recorder the never-throwing write-side seam (Slice-1 OMDB recorder)"); - w.line(" * @param input the LLM call fields; {@code llmRequest()} is the typed request payload,"); - w.line(" * threaded through as voRequest and JSON-stringified into the raw column"); - w.line(" */"); + w.commentLine(" * Record a single {@code " + shortName + "} LLM call: extract the response VO and persist a"); + w.commentLine(" * trace row via {@code recorder} regardless of whether extraction succeeded."); + w.commentLine(" *"); + w.commentLine(" * @param loader the loader the trace + response MetaObjects resolve against"); + w.commentLine(" * @param recorder the never-throwing write-side seam (Slice-1 OMDB recorder)"); + w.commentLine(" * @param input the LLM call fields; {@code llmRequest()} is the typed request payload,"); + w.commentLine(" * threaded through as voRequest and JSON-stringified into the raw column"); + w.commentLine(" */"); w.line("public static " + resultClass + " " + fnName + "("); w.continuation(LOADER_FQN + " loader,"); w.continuation(RECORDER_FQN + " recorder,"); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java index 8c88429053..ada74716b8 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java @@ -256,10 +256,10 @@ protected void emit(MetaObject entity, Path outRoot, MetaDataLoader loader) { w.use("java.util.Map"); w.use("java.util.Set"); w.line("/**"); - w.line(" * GENERATED — per-entity FR-009 filter allowlist for " + shortName + "."); - w.line(" * FIELDS lists the filterable field names; OPS_BY_FIELD constrains the"); - w.line(" * operator vocabulary for each field by its subtype."); - w.line(" */"); + w.commentLine(" * GENERATED — per-entity FR-009 filter allowlist for " + shortName + "."); + w.commentLine(" * FIELDS lists the filterable field names; OPS_BY_FIELD constrains the"); + w.commentLine(" * operator vocabulary for each field by its subtype."); + w.commentLine(" */"); try (var cls = w.block("public final class " + className + " {")) { // FIELDS — the field-name set. Use Set.of() for the empty + small cases. w.line("public static final Set FIELDS = Set.of(" + quotedList(opsByField.keySet()) + ");"); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java index 7cf2fb04ae..fab269d2ee 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java @@ -632,8 +632,8 @@ protected boolean emit(MetaObject entity, Path outRoot, String strategy, boolean if (!pkg.isEmpty()) w.packageName(pkg); w.use("java.util.Map"); w.line("/**"); - w.line(" * GENERATED — per-object physical database names for " + shortName + "."); - w.line(" */"); + w.commentLine(" * GENERATED — per-object physical database names for " + shortName + "."); + w.commentLine(" */"); // `abstract`, not `final`: this class is now a base other names classes extend // rather than restate. Java inherits static members, so `CouponAuthNames.ID_COLUMN` // resolves through the base and every consumption site is unchanged; `abstract` diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java index 443a0417aa..68db921c1c 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java @@ -250,10 +250,10 @@ protected void emit(MetaTemplate template, MetaDataLoader loader, Path outRoot) /** The strict tier: {@code parse(text)}, Jackson over the response record, failing on any mismatch. */ protected void writeStrictParse(SpringJavaWriter w, String payloadClass) { w.line("/**"); - w.line(" * Parse an LLM response into a typed {@link " + payloadClass + "}."); - w.line(" *"); - w.line(" * @throws JsonProcessingException when the input is not valid JSON for the response schema."); - w.line(" */"); + w.commentLine(" * Parse an LLM response into a typed {@link " + payloadClass + "}."); + w.commentLine(" *"); + w.commentLine(" * @throws JsonProcessingException when the input is not valid JSON for the response schema."); + w.commentLine(" */"); try (var m = w.block("public static " + payloadClass + " parse(String text) throws JsonProcessingException {")) { w.line("return MAPPER.readValue(text, " + payloadClass + ".class);"); } diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java index b684a77d08..e6637348e6 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java @@ -245,8 +245,8 @@ protected void emit(MetaTemplate template, MetaDataLoader loader, Path outRoot, if (!outPkg.isEmpty()) w.packageName(outPkg); w.line("/** Typed render helper for the `" + templateShort + "` template." + template.getSubType() + ". Wraps the render() engine; the payload field tree is"); - w.line(" * baked into the RenderRequest so render()'s runtime drift check matches the"); - w.line(" * build-time gate enforced when this file was generated. */"); + w.commentLine(" * baked into the RenderRequest so render()'s runtime drift check matches the"); + w.commentLine(" * build-time gate enforced when this file was generated. */"); try (var cls = w.block("public final class " + helperClass + " {")) { w.line("private " + helperClass + "() { /* no instances */ }"); w.blank(); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java index 5b79fd820e..bde44cdd44 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java @@ -229,10 +229,10 @@ protected void writeExportClass(SpringJavaWriter w, MetaObject entity, String pk if (!writerPackage.equals(pkg)) w.use(writerPackage + "." + WRITER_NAME); w.use("java.util.List"); w.line("/**"); - w.line(" * GENERATED — the export of the " + shortName + " report: its columns in"); - w.line(" * derived-field order, each cell's wire form, and the CSV and XML bodies. The"); - w.line(" * route reads {@link #MAX_ROWS}; the shared {@link " + WRITER_NAME + "} writes the bytes."); - w.line(" */"); + w.commentLine(" * GENERATED — the export of the " + shortName + " report: its columns in"); + w.commentLine(" * derived-field order, each cell's wire form, and the CSV and XML bodies. The"); + w.commentLine(" * route reads {@link #MAX_ROWS}; the shared {@link " + WRITER_NAME + "} writes the bytes."); + w.commentLine(" */"); try (var cls = w.block("public final class " + className + " {")) { w.line("private " + className + "() {}"); w.blank(); @@ -264,7 +264,7 @@ protected void writeExportClass(SpringJavaWriter w, MetaObject entity, String pk /** {@code cells(row)}: one row's cells in wire form, one factory call per exported field. */ protected void writeCellsMethod(SpringJavaWriter w, String dto, List fields) { w.line("/** One row's cells in wire form: currency as integer minor units, a date as YYYY-MM-DD,"); - w.line(" * a decimal as the wire setting writes it, a boolean as true/false, null as null. */"); + w.commentLine(" * a decimal as the wire setting writes it, a boolean as true/false, null as null. */"); try (var m = w.block("public static List<" + WRITER_NAME + ".Cell> cells(" + dto + " row) {")) { if (fields.isEmpty()) { w.line("return List.of();"); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java index cc030c916c..9c0342dadd 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java @@ -120,9 +120,9 @@ protected void emit(MetaObject entity, Path outRoot) { SpringJavaWriter w = newWriter(pkg, true); w.line("/**"); - w.line(" * GENERATED interface — consumer implements with their preferred persistence layer"); - w.line(" * (Spring Data JPA / jOOQ / plain JDBC). The matching " + shortName + "Controller delegates to this interface."); - w.line(" */"); + w.commentLine(" * GENERATED interface — consumer implements with their preferred persistence layer"); + w.commentLine(" * (Spring Data JPA / jOOQ / plain JDBC). The matching " + shortName + "Controller delegates to this interface."); + w.commentLine(" */"); try (var cls = w.block("public interface " + repoName + " {")) { writeSortClause(w); w.blank(); @@ -201,12 +201,12 @@ protected void emitReadOnly(MetaObject entity, Path outRoot) { SpringJavaWriter w = newWriter(pkg, hasItem); w.line("/**"); - w.line(" * GENERATED interface — consumer implements with their preferred persistence layer"); - w.line(" * (Spring Data JPA / jOOQ / plain JDBC). The matching " + shortName + "Controller delegates to this interface."); - w.line(" *"); - w.line(" *

READ-ONLY: " + shortName + " is a " + noun + " over a database view, so there is no write method to"); - w.line(" * implement. Its controller answers every write verb with 405.

"); - w.line(" */"); + w.commentLine(" * GENERATED interface — consumer implements with their preferred persistence layer"); + w.commentLine(" * (Spring Data JPA / jOOQ / plain JDBC). The matching " + shortName + "Controller delegates to this interface."); + w.commentLine(" *"); + w.commentLine(" *

READ-ONLY: " + shortName + " is a " + noun + " over a database view, so there is no write method to"); + w.commentLine(" * implement. Its controller answers every write verb with 405.

"); + w.commentLine(" */"); try (var cls = w.block("public interface " + repoName + " {")) { writeSortClause(w); w.blank(); @@ -245,11 +245,11 @@ protected void emitTph(MetaObject base, Path outRoot) { SpringJavaWriter w = newWriter(pkg, true); w.line("/**"); - w.line(" * GENERATED TPH interface — consumer implements with their preferred persistence layer."); - w.line(" * Polymorphic operations span the single " + shortName + w.commentLine(" * GENERATED TPH interface — consumer implements with their preferred persistence layer."); + w.commentLine(" * Polymorphic operations span the single " + shortName + " table; the per-subtype operations are scoped to a discriminator value"); - w.line(" * (injected by the matching " + shortName + "Controller from the URL segment)."); - w.line(" */"); + w.commentLine(" * (injected by the matching " + shortName + "Controller from the URL segment)."); + w.commentLine(" */"); try (var cls = w.block("public interface " + repoName + " {")) { writeSortClause(w); w.blank(); 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 ad0212c462..1f878597d5 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 @@ -152,6 +152,7 @@ protected void executeGenerators(MetaDataLoader loader, List generato // not, and a selection whose output depended on generator order produced a WARN and // a green build. Opening the run here is what makes the check reach a real build. try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + if (loader != null) run.readModelText(loader.getRoot()); if (genStateDir != null) { run.configureManifest(genStateDir, projectRoot); run.placeBy(placementOf(loader)); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java index 37c8f467b8..1f3a00e29c 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java @@ -696,6 +696,7 @@ private Map renderInMemory(MetaDataLoader loader, List List targets, Path projectRoot, boolean announce) { List params = getGenerators(); try (GeneratedFileWriter.Run capture = GeneratedFileWriter.beginCaptureRun()) { + if (loader != null) capture.readModelText(loader.getRoot()); if (projectRoot != null) { Map realDirByRendered = new LinkedHashMap<>(); for (GenTarget t : targets) realDirByRendered.put(t.tempDir, t.realDir); diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/FmtSupportTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/FmtSupportTest.java index 4dcf8c122a..7061c7e937 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/FmtSupportTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/FmtSupportTest.java @@ -84,6 +84,27 @@ public void checkModeNeverWritesAByte() throws IOException { java.util.Arrays.equals(before, Files.readAllBytes(base))); } + @Test + public void metadataTextThatReadsLikeAStringifiedObjectIsStillFormatted() throws IOException { + Path base = dir.resolve("meta.base.json"); + Files.writeString(base, MESSY_WIDGET.replace("A widget", "Fixes the [object Object] label bug"), + StandardCharsets.UTF_8); + MetaDataLoader baseline = loadBaseline(base, false); + + FmtSupport.RunResult result = FmtSupport.run( + baseline, + List.of(base), + List.of(base), + List.of(), + () -> freshLoader(false), + loaderName -> freshLoader(false), + /* check = */ false); + + assertEquals(1, result.files.size()); + assertEquals(FmtSupport.Status.FORMATTED, result.files.get(0).status); + assertTrue(Files.readString(base).contains("\"Fixes the [object Object] label bug\"")); + } + @Test public void anUnsafeCandidateIsNeverWritten() throws IOException { Path base = dir.resolve("meta.base.json"); diff --git a/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java b/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java index bbb29d22a7..223a31a742 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java +++ b/server/java/metadata/src/main/java/com/metaobjects/api/RulesCheck.java @@ -52,6 +52,7 @@ private RulesCheck() {} public static final String WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE"; public static final String WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME"; public static final String WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED"; + public static final String WARN_DERIVED_COMMAND_BYPASSES_DECLARED = "WARN_DERIVED_COMMAND_BYPASSES_DECLARED"; /** What the model declares, for the line {@code verify} prints. */ public record Summary(int operations, int lifecycles, int transitions) {} @@ -247,6 +248,30 @@ private static void checkShadowedPermissions(MetaRoot root, RulesSettings settin } } + /** + * Under {@code rules.lifecycle.commands: all} a transition a declared command claims derives a + * command of its own as well, which makes the transition without running the declared command's body. + */ + private static void checkDerivedBypassesDeclared(MetaRoot root, RulesSettings settings, List out) { + if (settings.lifecycleCommands() != RulesSettings.LifecycleCommands.ALL) return; + Map> claimed = claimedTransitions(root); + for (MetaData entity : commandEntities(root)) { + for (MetaData t : Lifecycles.entityTransitions(entity)) { + Set claimers = new java.util.LinkedHashSet<>(); + for (Claim c : claimsOn(claimed, entity, t)) { + claimers.add((c.op().getParent() == null ? "" : c.op().getParent().getShortName()) + "." + c.op().getShortName()); + } + if (claimers.isEmpty()) continue; + out.add(new Diagnostic(Severity.WARN, WARN_DERIVED_COMMAND_BYPASSES_DECLARED, + rulesAddress(entity) + "." + (t.getParent() == null ? "" : t.getParent().getShortName()) + "." + t.getShortName(), + "transition \"" + t.getShortName() + "\" of \"" + entity.getShortName() + "\" is claimed by " + quoteList(claimers) + + ", but rules.lifecycle.commands is \"all\", so the derived command \"" + entity.getShortName() + "." + t.getShortName() + + "\" makes the same transition without running " + (claimers.size() == 1 ? "its" : "their") + + " body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command.")); + } + } + } + private static void checkPermissionNames(MetaRoot root, RulesSettings settings, List out) { if (settings.permissionNames() == RulesSettings.PermissionNames.DERIVE) return; Severity severity = settings.permissionNames() == RulesSettings.PermissionNames.REQUIRE ? Severity.ERROR : Severity.WARN; @@ -287,6 +312,7 @@ public static Result check(MetaRoot root, RulesSettings settings) { List diagnostics = new ArrayList<>(); for (Lifecycle l : lifecycles) checkLifecycle(l, settings, diagnostics); checkShadowedPermissions(root, settings, diagnostics); + checkDerivedBypassesDeclared(root, settings, diagnostics); checkPermissionNames(root, settings, diagnostics); int transitions = 0; for (Lifecycle l : lifecycles) transitions += l.transitions().size(); diff --git a/server/python/src/metaobjects/agent_context/shipped/files/ad2ac665832abd65.md b/server/python/src/metaobjects/agent_context/shipped/files/61d9c5d06a2af7fd.md similarity index 99% rename from server/python/src/metaobjects/agent_context/shipped/files/ad2ac665832abd65.md rename to server/python/src/metaobjects/agent_context/shipped/files/61d9c5d06a2af7fd.md index 3c3b010c8f..bee4e9c856 100644 --- a/server/python/src/metaobjects/agent_context/shipped/files/ad2ac665832abd65.md +++ b/server/python/src/metaobjects/agent_context/shipped/files/61d9c5d06a2af7fd.md @@ -48,7 +48,9 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`. (The `formatTs` no-op export was removed in 1.3.0; delete the import from an owned copy.) The config's `apiPrefix` is +`pluralize`. (`formatTs` was removed in 1.3.0: replace each `await formatTs(text)` with `text` or +your own formatter; see `docs/features/migrations/owned-generators-1.2-to-1.3.md` in the +MetaObjects repository.) The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. diff --git a/server/python/src/metaobjects/agent_context/shipped/manifest.json b/server/python/src/metaobjects/agent_context/shipped/manifest.json index bb23892212..c1ddd502bc 100644 --- a/server/python/src/metaobjects/agent_context/shipped/manifest.json +++ b/server/python/src/metaobjects/agent_context/shipped/manifest.json @@ -179,7 +179,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -397,7 +397,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -617,7 +617,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -841,7 +841,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1066,7 +1066,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1295,7 +1295,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1523,7 +1523,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1743,7 +1743,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 33d56713f0..402e30ca01 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -21,7 +21,8 @@ across ports): --codegen regenerate into a temp dir + diff against the committed - ``--out`` tree. + ``--out`` tree. Every emitted ``.py`` module must compile + first, so generated Python that does not compile fails. The column naming comes from ``naming.columns`` in ``.metaobjects/config.json`` (ADR-0058), the same setting ``gen`` reads, so the ``names`` generator's constants match @@ -33,7 +34,9 @@ render ``verify()`` gate — resolving each ``template.*`` node's refs via a filesystem provider rooted at ``templates`` in ``metaobjects.config.yaml`` (else - ``--prompts``), over the config's ``metadata``. + ``--prompts``), over the config's ``metadata``. Alone it + checks prompt templates only: it neither compares nor + compiles generated code. --deps dependency drift (FR-023): re-resolve each declared dependency's ``path`` and compare its artifact's hash with ``.metaobjects/deps.lock.json`` (``metaobjects deps check`` @@ -3775,7 +3778,10 @@ def _build_parser() -> argparse.ArgumentParser: verify.add_argument( "--codegen", action="store_true", - help="codegen drift: regenerate to a temp dir + diff vs --out (default)", + help=( + "codegen drift: regenerate to a temp dir + diff vs --out (default); generated " + "Python that does not compile fails" + ), ) verify.add_argument( "--column-naming", @@ -3792,7 +3798,9 @@ def _build_parser() -> argparse.ArgumentParser: help=( "template drift: each template.* node's {{field}} ↔ payload-VO " "field tree (render verify); reads `metadata` and `templates` from " - "metaobjects.config.yaml, or takes with --prompts" + "metaobjects.config.yaml, or takes with --prompts. Alone it " + "checks prompt templates only and neither compares nor compiles generated code; " + "every mode that includes --codegen compiles it" ), ) verify.add_argument( diff --git a/server/python/src/metaobjects/codegen/generators/entity_model.py b/server/python/src/metaobjects/codegen/generators/entity_model.py index 1aee551092..fc6cf98b9f 100644 --- a/server/python/src/metaobjects/codegen/generators/entity_model.py +++ b/server/python/src/metaobjects/codegen/generators/entity_model.py @@ -49,7 +49,17 @@ from metaobjects.codegen.config import GenConfig from metaobjects.codegen.constants import GENERATED_MARKER, generated_header_lines from metaobjects.codegen.type_map import field_is_array, py_type_for -from metaobjects.codegen.writer import CodeWriter, Piece, PyWriter, call, flat, group, str_lit +from metaobjects.codegen.writer import ( + ERR_WRITER_LEADING_WHITESPACE, + CodeWriter, + Piece, + PyWriter, + WriterError, + call, + flat, + group, + str_lit, +) from metaobjects.codegen.generator import EmittedFile, GenContext, Generator, per_entity from metaobjects.codegen.generators.tph_plan import tph_plan_for, tph_subtype_binding from metaobjects.codegen.import_path import ( @@ -1422,12 +1432,28 @@ def _write_model( w.line(f'"""{doc}"""') w.blank() for member in members: + self._refuse_indented(member) w.line(member) if extra is not None: extra(w) w.dedent() w.gap() + def _refuse_indented(self, member: Piece) -> None: + """A member that carries its own indent is the 1.1.x/1.2.x hook contract (a string + with four leading spaces). The writer indents members itself, so such a member lands + one level deeper than its siblings and the module no longer compiles. Refused here, + naming the generator that returned it, rather than by the writer's generic message.""" + text = flat(member) + if text[:1] in (" ", "\t"): + raise WriterError( + ERR_WRITER_LEADING_WHITESPACE, + f"{type(self).__module__}.{type(self).__qualname__} returned the model member " + f"{text!r}, which starts with whitespace. Since 1.3.0 _emit_field_lines, " + f"_emit_create_lines and _emit_patch_lines return members WITHOUT indentation " + f"(the code writer indents them, ADR-0063): drop the leading spaces.", + ) + @staticmethod def _deferred_nav_imports( entity: MetaObject, diff --git a/server/python/src/metaobjects/codegen/overwrite_policy.py b/server/python/src/metaobjects/codegen/overwrite_policy.py index 20c788fd1a..f05c5ceda8 100644 --- a/server/python/src/metaobjects/codegen/overwrite_policy.py +++ b/server/python/src/metaobjects/codegen/overwrite_policy.py @@ -41,7 +41,8 @@ # status: "new" | "unchanged" | "overwrite" | "refused" | "adopted" | "skipped" -#: The legacy single manifest. Read underneath the per-package files; removed by the next write. +#: The legacy single manifest. While present it is read instead of 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" @@ -264,13 +265,21 @@ def _read_json_object(path: str) -> dict[str, object]: 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).""" + """The manifest entries (the package files in name order, or the legacy file alone while + it is present), and the file each key was found in (``""`` for the legacy file). + + A legacy ``.hashes.json`` that is still present is authoritative: a write deletes it right + after writing the package files, so a ``.hashes/`` beside it is left over from another + checkout (the old ``.gitignore`` ignores that directory, so it survives a reset or a branch + switch), and its stale hashes would make every file the committed manifest vouches for read + as hand-edited. The next write replaces or removes those stale files.""" 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] = "" + if os.path.exists(_manifest_path(gen_state_dir)): + return merged, where 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 diff --git a/server/python/src/metaobjects/codegen/runner.py b/server/python/src/metaobjects/codegen/runner.py index dcff866f35..a94d84dfc7 100644 --- a/server/python/src/metaobjects/codegen/runner.py +++ b/server/python/src/metaobjects/codegen/runner.py @@ -116,6 +116,74 @@ def _stable_name(generator_name: str) -> str: return stable_name_of(generator_name) +class GeneratedSyntaxError(ValueError): + """A generator emitted a ``.py`` file that is not valid Python.""" + + +def assert_emitted_python_compiles(out_dir: str, emitted: dict[str, tuple[str, str]]) -> None: + """Raise :class:`GeneratedSyntaxError` naming each emitted ``.py`` file that does not + compile and the generator that emitted it. Compiles in memory; writes nothing.""" + broken: list[str] = [] + for full, (content, by) in emitted.items(): + if not full.endswith(".py"): + continue + rel = os.path.relpath(full, out_dir) + try: + compile(content, rel, "exec", dont_inherit=True) + except SyntaxError as err: # IndentationError is a SyntaxError + broken.append( + f"{rel} (generator {by!r}) line {err.lineno}: {type(err).__name__}: {err.msg}" + ) + if broken: + raise GeneratedSyntaxError( + "generated Python does not compile, so none of these files were written: " + + "; ".join(broken) + + ". A generator subclass written for 1.2 or earlier may be returning pre-indented " + "lines; see CHANGELOG 'Upgrading from 1.2.0'." + ) + + +class StringifiedObjectError(ValueError): + """A generator emitted text carrying ``[object Object]``: an object turned into a string.""" + + +_STRINGIFIED_OBJECT = "[object Object]" +# The marker anywhere but as the exact quoted string literal, which is code on purpose (an +# emitted query-string encoder mirroring JavaScript's). +_STRINGIFIED_OBJECT_RE = re.compile(r'(? bool: + """True when a string value the model declares contains ``text``, so output carrying it may + be the model's own prose (an ``@description``, a requirement counterexample). Walks every + node's own attrs (ADR-0039: each node is visited, so an inherited value is read on its + declaring node).""" + if any(text in (v if isinstance(v, str) else repr(v)) for v in node.own_attrs().values()): + return True + return any(_model_mentions(child, text) for child in node.own_children()) + + +def assert_no_stringified_object( + out_dir: str, emitted: dict[str, tuple[str, str]], metadata: MetaData +) -> None: + """Raise :class:`StringifiedObjectError` naming each emitted file that carries + ``[object Object]`` and the generator that emitted it, unless a string value in the model + carries the marker itself. Reads memory; writes nothing.""" + hits = [ + f"{os.path.relpath(full, out_dir)} (generator {by!r})" + for full, (content, by) in emitted.items() + if _STRINGIFIED_OBJECT_RE.search(content) + ] + if hits and not _model_mentions(metadata, _STRINGIFIED_OBJECT): + raise StringifiedObjectError( + f"ERR_GEN_STRINGIFIED_OBJECT: generated output contains {_STRINGIFIED_OBJECT!r}, " + "which no string in the model carries, so none of these files were written: " + + "; ".join(hits) + + ". A generator turned an object into text where code belongs; build the text " + "with the code writer instead." + ) + + def run_gen( config: GenConfig, metadata: MetaData, @@ -269,6 +337,14 @@ def is_selected(o: MetaObject) -> bool: emitted[full] = (f.content, gen.name) if f.source_node is not None: sources[full] = f.source_node + # Every emitted Python module must compile before anything is written or compared: a + # generator (most often an owned subclass on an older hook contract) that hands back + # malformed source would otherwise be written by `gen` and reported "in sync" by + # `verify`, and the adopter's import is the first thing to disagree. + assert_emitted_python_compiles(config.out_dir, emitted) + # Text an object was turned into (`[object Object]`) is refused the same way, in gen and + # verify alike: it often still compiles, so nothing else would catch it. + assert_no_stringified_object(config.out_dir, emitted, metadata) if config.plan is not None: config.plan.files.update( (_manifest_key(config, full), (_stable_name(by), sources.get(full))) diff --git a/server/python/src/metaobjects/codegen/writer/__init__.py b/server/python/src/metaobjects/codegen/writer/__init__.py index 7c69527f6a..9eac5215f6 100644 --- a/server/python/src/metaobjects/codegen/writer/__init__.py +++ b/server/python/src/metaobjects/codegen/writer/__init__.py @@ -1,6 +1,7 @@ """The code writer every Python generator writes through (ADR-0063).""" from .code_writer import ( ERR_WRITER_IMPORT_CONFLICT, + ERR_WRITER_LEADING_WHITESPACE, ERR_WRITER_NEWLINE_IN_LINE, ERR_WRITER_UNBALANCED_CLOSE, ERR_WRITER_UNCLOSED_BLOCK, @@ -18,6 +19,6 @@ __all__ = [ "CodeWriter", "PyWriter", "Group", "Piece", "WriterError", "flat", "group", "call", "kwarg", "mapping", "seq", "str_lit", - "ERR_WRITER_IMPORT_CONFLICT", "ERR_WRITER_NEWLINE_IN_LINE", "ERR_WRITER_UNBALANCED_CLOSE", + "ERR_WRITER_IMPORT_CONFLICT", "ERR_WRITER_LEADING_WHITESPACE", "ERR_WRITER_NEWLINE_IN_LINE", "ERR_WRITER_UNBALANCED_CLOSE", "ERR_WRITER_UNCLOSED_BLOCK", "ERR_WRITER_UNKNOWN_PIECE", "TWO_SPACE_INDENT", ] diff --git a/server/python/src/metaobjects/codegen/writer/code_writer.py b/server/python/src/metaobjects/codegen/writer/code_writer.py index 57fe3fcdb5..b580a34919 100644 --- a/server/python/src/metaobjects/codegen/writer/code_writer.py +++ b/server/python/src/metaobjects/codegen/writer/code_writer.py @@ -22,10 +22,12 @@ ERR_WRITER_NEWLINE_IN_LINE = "ERR_WRITER_NEWLINE_IN_LINE" ERR_WRITER_IMPORT_CONFLICT = "ERR_WRITER_IMPORT_CONFLICT" ERR_WRITER_UNKNOWN_PIECE = "ERR_WRITER_UNKNOWN_PIECE" +ERR_WRITER_LEADING_WHITESPACE = "ERR_WRITER_LEADING_WHITESPACE" -class WriterError(Exception): - """A writer failure: one of the shared codes plus a message for people.""" +class WriterError(ValueError): + """A writer failure: one of the shared codes plus a message for people. A ``ValueError``, + so ``gen`` and ``verify`` report it as a clean per-target error and exit non-zero.""" def __init__(self, code: str, message: str) -> None: super().__init__(f"{code}: {message}") @@ -108,8 +110,9 @@ def __init__(self, indent: str = " ", width: int = 88, trailing_comma: bool = def line(self, *parts: object) -> "CodeWriter": """One line at the current indent. The parts are concatenated; when the line does not fit the width, the LAST non-empty list in it is printed one item per line. A - line whose text is empty is a blank-line request.""" - return self._put(self.piece(parts)) + line whose text is empty is a blank-line request. Text that starts with whitespace is + ``ERR_WRITER_LEADING_WHITESPACE``: indentation comes only from open blocks.""" + return self._put(self._unindented(self.piece(parts), "line")) def blank(self) -> "CodeWriter": """Ask for one blank line before whatever is written next. Requests never stack.""" @@ -118,11 +121,11 @@ def blank(self) -> "CodeWriter": def open(self, *parts: object) -> "CodeWriter": """Write the line that opens a block, then indent.""" - return self._open_piece(self.piece(parts)) + return self._open_piece(self._unindented(self.piece(parts), "open")) def close(self, *parts: object) -> "CodeWriter": """Dedent, then write the line that closes the block.""" - return self._close_piece(self.piece(parts)) + return self._close_piece(self._unindented(self.piece(parts), "close")) def block(self, head: object, body: Callable[[], None], tail: object = "}") -> "CodeWriter": """``open(head)``, the body, then ``close(tail)``: the indent cannot be left @@ -206,6 +209,18 @@ def _body(self) -> str: ) return _NEWLINE.join(self._out) + def _unindented(self, piece: Piece, what: str) -> Piece: + """Refuse text a caller indented itself: the writer adds the indent, so a pre-indented + piece would land one level too deep beside its siblings, silently.""" + raw = flat(piece) + if raw[:1] in (" ", "\t"): + raise WriterError( + ERR_WRITER_LEADING_WHITESPACE, + f"{what}() text starts with whitespace; pass it without indentation, the " + f"writer indents it from the open blocks: {raw!r}", + ) + return piece + def _prefix(self) -> str: return self.indent * len(self._openers) diff --git a/server/python/src/metaobjects/codegen/writer/py_writer.py b/server/python/src/metaobjects/codegen/writer/py_writer.py index be45916bbe..3a3e9a278e 100644 --- a/server/python/src/metaobjects/codegen/writer/py_writer.py +++ b/server/python/src/metaobjects/codegen/writer/py_writer.py @@ -137,7 +137,8 @@ def doc(self, *lines: str) -> "PyWriter": written as ``\\\\`` and ``\"\"\"`` in the text is escaped, and so is a double quote that would end a one-line docstring.""" for ln in self._doc_lines(lines, len(self._prefix())): - self.line(ln) + # _put, not line(): a docstring line keeps the text's own indentation. + self._put(ln) return self def module_doc(self, *lines: str) -> "PyWriter": @@ -187,7 +188,7 @@ def _section_writer(self) -> CodeWriter: def write_header(self, w: CodeWriter) -> None: """The ``header(...)`` lines, as given.""" for ln in self._head: - w.line(ln) + w._put(ln) # as given: a header line is never re-indented or refused def write_imports(self, w: CodeWriter) -> None: """Every collected import, one blank line between the ``__future__`` import, the diff --git a/server/python/src/metaobjects/render/bundled_templates/agent/schema.md.mustache b/server/python/src/metaobjects/render/bundled_templates/agent/schema.md.mustache index ad91a93c2f..90dfc9bee4 100644 --- a/server/python/src/metaobjects/render/bundled_templates/agent/schema.md.mustache +++ b/server/python/src/metaobjects/render/bundled_templates/agent/schema.md.mustache @@ -14,7 +14,7 @@ The tables, columns and keys this model declares. Read it before writing a query - Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. {{/hasMigrate}} {{^hasMigrate}} -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. {{/hasMigrate}} - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. diff --git a/server/python/src/metaobjects/rules_check.py b/server/python/src/metaobjects/rules_check.py index 8fc85a4a81..0488e7cfde 100644 --- a/server/python/src/metaobjects/rules_check.py +++ b/server/python/src/metaobjects/rules_check.py @@ -17,6 +17,8 @@ * ``WARN_LIFECYCLE_INITIAL_TERMINAL``: the initial state is one no transition leaves * ``WARN_TRANSITION_UNREACHABLE``: a transition whose every @from state is unreachable (severity: ``verify.lifecycle.unreachable``) +* ``WARN_DERIVED_COMMAND_BYPASSES_DECLARED``: under ``rules.lifecycle.commands: all``, a transition a + declared command claims also derives a command that skips the declared body (always a warning). * ``WARN_TRANSITION_PERMISSION_SHADOWED``: a transition declaring @permission or @public: true that derives no command of its own, so the attribute is never read (always a warning) * ``WARN_PERMISSION_DERIVED_NAME``: a transition that derives its own command, or an @@ -63,6 +65,7 @@ WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE" WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME" WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED" +WARN_DERIVED_COMMAND_BYPASSES_DECLARED = "WARN_DERIVED_COMMAND_BYPASSES_DECLARED" @dataclass(frozen=True) @@ -282,6 +285,35 @@ def _check_shadowed_permissions(root: MetaData, settings: RulesSettings, out: li )) +def _check_derived_bypasses_declared(root: MetaData, settings: RulesSettings, out: list[Diagnostic]) -> None: + """Under ``rules.lifecycle.commands: all`` a transition a declared command claims derives a command + of its own as well, which makes the transition without running the declared command's body.""" + if settings.lifecycle_commands != "all": + return + claimed = _claimed_transitions(root) + for entity in _command_entities(root): + for t in entity_transitions(entity): + claimers = list(dict.fromkeys( + f"{c.op.parent.name if c.op.parent is not None else ''}.{c.op.name}" + for c in _claims_on(claimed, entity, t) + )) + if not claimers: + continue + field_name = t.parent.name if t.parent is not None else "" + their = "its" if len(claimers) == 1 else "their" + out.append(Diagnostic( + severity=SEVERITY_WARN, + code=WARN_DERIVED_COMMAND_BYPASSES_DECLARED, + path=f"{rules_address(entity)}.{field_name}.{t.name}", + message=( + f'transition "{t.name}" of "{entity.name}" is claimed by {_quote_list(claimers)}, ' + f'but rules.lifecycle.commands is "all", so the derived command "{entity.name}.{t.name}" ' + f"makes the same transition without running {their} body. " + 'Set rules.lifecycle.commands to "unclaimed" (the default), or remove the declared command.' + ), + )) + + def _check_permission_names(root: MetaData, settings: RulesSettings, out: list[Diagnostic]) -> None: if settings.permission_names == "derive": return @@ -335,6 +367,7 @@ def check_rules(root: MetaData, settings: RulesSettings) -> RulesCheckResult: for l in lifecycles: _check_lifecycle(l, settings, diagnostics) _check_shadowed_permissions(root, settings, diagnostics) + _check_derived_bypasses_declared(root, settings, diagnostics) _check_permission_names(root, settings, diagnostics) return RulesCheckResult( diagnostics=diagnostics, diff --git a/server/python/tests/codegen/test_cli.py b/server/python/tests/codegen/test_cli.py index ee0dd202e0..2bee3f0f68 100644 --- a/server/python/tests/codegen/test_cli.py +++ b/server/python/tests/codegen/test_cli.py @@ -289,8 +289,11 @@ def test_verify_codegen_clean_for_a_py_emitting_spec(tmp_path: Path) -> None: know about. (A spec emitting any OTHER extension hit the opposite failure: it was not compared at all. Both are covered here.)""" root = _spec_project(tmp_path, spec_name=None) + # A .py output is held to compiling (gen refuses one that does not), so the template + # renders Python. + (root / "templates" / "service.mustache").write_text("class {{name}}Service:\n pass\n") (root / "template-spec.json").write_text( - '{"generators": [{"name": "svc", "template": "entity", ' + '{"generators": [{"name": "svc", "template": "service", ' '"scope": "perEntity", "outputPattern": "{name}Service.py"}]}' ) out = root / "out" @@ -302,6 +305,24 @@ def test_verify_codegen_clean_for_a_py_emitting_spec(tmp_path: Path) -> None: assert rc == 0, "the reported `extra:` false-conviction is back" +def test_gen_refuses_a_py_emitting_spec_whose_output_does_not_compile( + tmp_path: Path, capsys +) -> None: + """A template-spec output named .py is Python, so it is compiled like every other + emitted module: one that does not compile fails the run and is not written.""" + root = _spec_project(tmp_path, spec_name=None) + (root / "template-spec.json").write_text( + '{"generators": [{"name": "svc", "template": "entity", ' + '"scope": "perEntity", "outputPattern": "{name}Service.py"}]}' + ) + out = root / "out" + rc = main(as_config(["gen", "--generators", GEN_SUITE, str(root / "meta"), "--out", str(out), + "--templates", str(root / "templates")])) + assert rc == 1 + assert "generated Python does not compile" in capsys.readouterr().err + assert not (out / "ProductService.py").exists() + + def test_verify_codegen_ignores_a_file_it_never_wrote(tmp_path: Path) -> None: """JURISDICTION. Broadening the comparison past *.py means the gate now sees every stranger's file in outDir. `out_dir` is a directory, not a namespace this tool owns diff --git a/server/python/tests/codegen/test_generated_python_compiles.py b/server/python/tests/codegen/test_generated_python_compiles.py new file mode 100644 index 0000000000..edb9cfb940 --- /dev/null +++ b/server/python/tests/codegen/test_generated_python_compiles.py @@ -0,0 +1,173 @@ +"""`gen` and `verify` refuse generated Python that does not compile. + +The reported case: an owned ``EntityModelGenerator`` subclass written to the 1.1.x hook +contract returns members carrying their own four-space indent. The 1.3.0 code writer indents +members itself, so those members landed one level deeper than the rest, the module raised +``IndentationError`` on import, and both ``gen`` and ``verify`` exited 0 over it. + +Two guards, each pinned here: the entity generator refuses a pre-indented member and names +the generator and the new contract; and every emitted ``.py`` is compiled before it is +written or compared, which catches malformed output the first guard does not describe. +""" +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import pytest + +from metaobjects.cli import main + +WIDGET = { + "metadata.root": { + "package": "app::w", + "children": [ + { + "object.value": { + "name": "Widget", + "children": [{"field.string": {"name": "label", "@required": True}}], + } + } + ], + } +} + +_GENERATOR = """ +from metaobjects.codegen.generators.entity_model import EntityModelGenerator + + +class Strict(EntityModelGenerator): + def _emit_field_lines(self, entity, imports, object_index, config=None): + lines, uses = super()._emit_field_lines(entity, imports, object_index, config) + return [{member!r}, *lines], uses + + +def strict(): + return Strict() +""" + +# The 1.1.x contract: the member carries its own indent. +PRE_INDENTED = ' model_config = ConfigDict(extra="forbid")' +# No leading whitespace, so the writer accepts it, but it is not Python. +MALFORMED = "model_config = ConfigDict(extra=" + + +@pytest.fixture +def project(tmp_path: Path): + """A project whose one target runs an owned generator module, with the config dir on + the import path the way `gen` puts it there. Yields a function writing the generator.""" + module = f"gens_{tmp_path.name.replace('-', '_')}" + (tmp_path / "metaobjects").mkdir() + (tmp_path / "metaobjects" / "meta.widget.json").write_text(json.dumps(WIDGET)) + (tmp_path / module).mkdir() + (tmp_path / module / "__init__.py").write_text("") + (tmp_path / "metaobjects.config.yaml").write_text( + f"targets:\n model:\n outDir: out\n generators: [{module}.strict:strict]\n" + ) + + def write(member: str) -> Path: + (tmp_path / module / "strict.py").write_text(_GENERATOR.format(member=member)) + for name in [m for m in sys.modules if m == module or m.startswith(module + ".")]: + del sys.modules[name] + return tmp_path + + yield write + for name in [m for m in sys.modules if m == module or m.startswith(module + ".")]: + del sys.modules[name] + if str(tmp_path) in sys.path: + sys.path.remove(str(tmp_path)) + + +def _run(root: Path, *args: str) -> int: + return main([*args, "--config", str(root / "metaobjects.config.yaml")]) + + +def test_gen_refuses_a_pre_indented_member_naming_the_generator(project, capsys) -> None: + root = project(PRE_INDENTED) + assert _run(root, "gen") == 1 + err = capsys.readouterr().err + assert "ERR_WRITER_LEADING_WHITESPACE" in err + assert ".strict.Strict" in err + assert "_emit_field_lines" in err and "WITHOUT indentation" in err + assert not (root / "out" / "Widget.py").exists() + + +def test_gen_refuses_emitted_python_that_does_not_compile(project, capsys) -> None: + root = project(MALFORMED) + assert _run(root, "gen") == 1 + err = capsys.readouterr().err + assert "generated Python does not compile" in err + assert "Widget.py" in err and "entity-model" in err + assert not (root / "out" / "Widget.py").exists() + + +@pytest.mark.parametrize( + "flags", + [ + ["--codegen"], + ["--codegen", "--full"], + ["--codegen", "--require-implementers"], + ], +) +@pytest.mark.parametrize("member", [PRE_INDENTED, MALFORMED]) +def test_verify_fails_on_generated_python_that_does_not_compile( + project, capsys, flags: list[str], member: str +) -> None: + """A tree generated from a valid generator, then the generator turned malformed: the + regeneration verify compares against does not compile, so verify fails rather than + report the broken render "in sync".""" + root = project('model_config = {"extra": "forbid"}') + assert _run(root, "gen") == 0 + project(member) + capsys.readouterr() + assert _run(root, "verify", *flags) == 1 + out = capsys.readouterr() + assert "in sync" not in out.out + + +# A member that compiles but carries what an object turned into text reads as. +STRINGIFIED = 'model_config = "x" # [object Object]' + + +def test_gen_refuses_output_containing_a_stringified_object(project, capsys) -> None: + root = project(STRINGIFIED) + assert _run(root, "gen") == 1 + err = capsys.readouterr().err + assert "ERR_GEN_STRINGIFIED_OBJECT" in err + assert "Widget.py" in err and "entity-model" in err + assert not (root / "out" / "Widget.py").exists() + + +def test_verify_fails_on_output_containing_a_stringified_object(project, capsys) -> None: + root = project('model_config = {"extra": "forbid"}') + assert _run(root, "gen") == 0 + project(STRINGIFIED) + capsys.readouterr() + assert _run(root, "verify", "--codegen") == 1 + assert "in sync" not in capsys.readouterr().out + + +def test_the_quoted_literal_is_allowed(project) -> None: + root = project('model_config = {"extra": "forbid"} # "[object Object]"') + assert _run(root, "gen") == 0 + + +PROSE = "Fixes the [object Object] label bug" + + +def test_text_a_model_string_carries_is_allowed(project) -> None: + """The marker in output is the model's own prose when a model string carries it: an + ``@description`` naming the symptom, copied into a comment, generates.""" + root = project(f'model_config = {{"extra": "forbid"}} # {PROSE}') + described = json.loads(json.dumps(WIDGET)) + described["metadata.root"]["children"][0]["object.value"]["@description"] = PROSE + (root / "metaobjects" / "meta.widget.json").write_text(json.dumps(described)) + assert _run(root, "gen") == 0 + assert PROSE in (root / "out" / "Widget.py").read_text() + + +def test_the_refusal_says_no_model_string_carries_the_marker(project, capsys) -> None: + root = project(STRINGIFIED) + assert _run(root, "gen") == 1 + assert "which no string in the model carries" in capsys.readouterr().err diff --git a/server/python/tests/codegen/test_manifest_store.py b/server/python/tests/codegen/test_manifest_store.py index 26d0d38467..eae9a2adad 100644 --- a/server/python/tests/codegen/test_manifest_store.py +++ b/server/python/tests/codegen/test_manifest_store.py @@ -144,12 +144,13 @@ def test_read_only_load_migrates_nothing(tmp_path: Path) -> None: assert not (state / ".hashes").exists() -def test_union_prefers_package_files_over_the_legacy_file(tmp_path: Path) -> None: +def test_package_files_are_unread_while_the_legacy_file_is_present(tmp_path: Path) -> None: + # ADR-0064 §2 (corrected): a .hashes/ beside an unmigrated .hashes.json is stale. 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), "a") == "old" assert op.read_generated_hash(str(state), "b") == "legacy" diff --git a/server/python/tests/codegen/test_overwrite_policy_hash.py b/server/python/tests/codegen/test_overwrite_policy_hash.py index b8517be50f..505fab76a0 100644 --- a/server/python/tests/codegen/test_overwrite_policy_hash.py +++ b/server/python/tests/codegen/test_overwrite_policy_hash.py @@ -159,3 +159,20 @@ def test_jvm_object_entry_is_read_and_preserved_on_record(tmp_path: Path) -> Non assert saved["Jvm.java"]["generator"] == "java:dto" assert saved["Jvm.java"]["outputDir"] == "target/gen" assert saved["Jvm.java"]["hash"] == content_hash("jvm body v2") + + +def test_a_committed_legacy_manifest_beats_a_stale_hashes_dir(tmp_path: Path) -> None: + """The old .gitignore ignores .hashes/, so one left by another checkout's run survives a + reset beside the committed .hashes.json. A file the committed manifest vouches for must be + overwritten, not read as hand-edited against the stale hash.""" + state = tmp_path / ".gen-state" + (state / ".hashes").mkdir(parents=True) + out = tmp_path / "a.py" + out.write_text("v1\n") + (state / ".hashes.json").write_text(json.dumps({"a.py": content_hash("v1\n")})) + (state / ".hashes" / ".root.json").write_text(json.dumps({"a.py": content_hash("other")})) + assert read_generated_hash(str(state), "a.py") == content_hash("v1\n") + assert _gen(out, "v2\n", state) != "refused" + assert out.read_text() == "v2\n" + assert not (state / ".hashes.json").exists() + assert read_generated_hash(str(state), "a.py") == content_hash("v2\n") diff --git a/server/rust/metaobjects-cli/agent-context-shipped/files/ad2ac665832abd65.md b/server/rust/metaobjects-cli/agent-context-shipped/files/61d9c5d06a2af7fd.md similarity index 99% rename from server/rust/metaobjects-cli/agent-context-shipped/files/ad2ac665832abd65.md rename to server/rust/metaobjects-cli/agent-context-shipped/files/61d9c5d06a2af7fd.md index 3c3b010c8f..bee4e9c856 100644 --- a/server/rust/metaobjects-cli/agent-context-shipped/files/ad2ac665832abd65.md +++ b/server/rust/metaobjects-cli/agent-context-shipped/files/61d9c5d06a2af7fd.md @@ -48,7 +48,9 @@ Everything a generator reads comes from `@metaobjectsdev/codegen-ts`: `perEntity `perPackage` / `perModel`, `isAbstract`, `hasAnyRdbSource`, `isProjection`, `servesReadApi` / `servesWriteApi`, `objectRefTarget`, `enumValues`, `effectivePackage`, `packageToPath`, `servedPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / -`pluralize`. (The `formatTs` no-op export was removed in 1.3.0; delete the import from an owned copy.) The config's `apiPrefix` is +`pluralize`. (`formatTs` was removed in 1.3.0: replace each `await formatTs(text)` with `text` or +your own formatter; see `docs/features/migrations/owned-generators-1.2-to-1.3.md` in the +MetaObjects repository.) The config's `apiPrefix` is `ctx.renderContext?.apiPrefix`. Worked JSON Schema and OpenAPI 3.1 generators to copy: `docs/recipes/generators/typescript/` in the MetaObjects repository. diff --git a/server/rust/metaobjects-cli/agent-context-shipped/manifest.json b/server/rust/metaobjects-cli/agent-context-shipped/manifest.json index bb23892212..c1ddd502bc 100644 --- a/server/rust/metaobjects-cli/agent-context-shipped/manifest.json +++ b/server/rust/metaobjects-cli/agent-context-shipped/manifest.json @@ -179,7 +179,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -397,7 +397,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -617,7 +617,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -841,7 +841,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1066,7 +1066,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1295,7 +1295,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1523,7 +1523,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", @@ -1743,7 +1743,7 @@ }, { "path": ".claude/skills/metaobjects-codegen/references/typescript.md", - "file": "ad2ac665832abd65.md" + "file": "61d9c5d06a2af7fd.md" }, { "path": ".claude/skills/metaobjects-codegen/references/wire-format.md", diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 0703d31e5a..645a8d8ec0 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -34,7 +34,8 @@ use crate::fingerprint::{ hash_tree_except, }; use crate::generator::{ - ERR_OUT_DIR, ERR_PATH_COLLISION, EmittedFile, GenContext, GenError, Generator, + ERR_GEN_STRINGIFIED_OBJECT, ERR_OUT_DIR, ERR_PATH_COLLISION, EmittedFile, GenContext, GenError, + Generator, }; use crate::generator_list; use crate::hashes::{HASHES_DIR, HashManifest, content_hash}; @@ -814,10 +815,63 @@ fn render(p: &mut Prepared<'_>, opts: &RunOptions) -> Result, RunE ))); } } + // Text an object was turned into reads `[object Object]`. It often still compiles, so it + // is refused by name here, before anything is written or compared, in gen and verify alike. + let stringified: Vec = emitted + .iter() + .filter(|r| has_stringified_object(&r.file.content)) + .map(|r| format!("{} (generator \"{}\")", r.file.path, r.generated_by)) + .collect(); + if !stringified.is_empty() && !model_mentions(ctx.tree, ctx.root, STRINGIFIED_OBJECT) { + return Err(RunError::Generator(GenError::new( + ERR_GEN_STRINGIFIED_OBJECT, + format!( + "generated output contains \"[object Object]\", which no string in the model carries, \ + so none of this run's files were written: {}. \ + A generator turned an object into text where code belongs; build the text with the code writer instead.", + stringified.join("; ") + ), + ))); + } p.timings.add_phase(STAGE_RENDER, start.elapsed()); Ok(emitted) } +/// What JavaScript writes for an object turned into text without a `toString` of its own. +const STRINGIFIED_OBJECT: &str = "[object Object]"; + +/// `[object Object]` anywhere but as the exact quoted string literal, which is code on purpose +/// (the emitted query-string encoder mirrors JavaScript's). +fn has_stringified_object(text: &str) -> bool { + text.match_indices(STRINGIFIED_OBJECT).any(|(at, _)| { + let before = text[..at].ends_with('"'); + let after = text[at + STRINGIFIED_OBJECT.len()..].starts_with('"'); + !before && !after + }) +} + +/// True when a string value `id` or a node under it declares contains `text`, so output +/// carrying it may be the model's own prose (an `@description`, a requirement counterexample). +/// Walks every node's own attrs (ADR-0039: each node is visited, so an inherited value is read +/// on its declaring node). +fn model_mentions(tree: &metaobjects::Tree, id: metaobjects::NodeId, text: &str) -> bool { + tree.own_attrs(id) + .any(|(_, attr)| value_mentions(&attr.value, text)) + || tree + .own_children(id) + .iter() + .any(|&child| model_mentions(tree, child, text)) +} + +fn value_mentions(value: &Value, text: &str) -> bool { + match value { + Value::String(s) => s.contains(text), + Value::Array(items) => items.iter().any(|v| value_mentions(v, text)), + Value::Object(map) => map.values().any(|v| value_mentions(v, text)), + _ => false, + } +} + /// The generated files a reader of the run's output sees: every manifest entry that names /// its generator and node, less the ones this run owns (under its output directory, unless /// the run is narrowed and cannot tell), then this run's own files. @@ -1180,6 +1234,16 @@ fn remove_empty_parents(path: &Path, stop: &Path) { #[cfg(test)] mod tests { + #[test] + fn a_stringified_object_is_found_and_the_quoted_literal_is_not() { + assert!(super::has_stringified_object("let x = [object Object];")); + assert!(super::has_stringified_object("a\n[object Object]\n")); + assert!(!super::has_stringified_object( + "Param::Map(_) => \"[object Object]\".to_string()," + )); + assert!(!super::has_stringified_object("nothing here")); + } + use super::*; #[test] diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index 839943cb2d..d38b6ff94b 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -98,6 +98,8 @@ impl std::error::Error for GenError {} pub const ERR_NAME_COLLISION: &str = "ERR_NAME_COLLISION"; /// Two generators (or two objects) claim one output path. pub const ERR_PATH_COLLISION: &str = "ERR_PATH_COLLISION"; +/// A generated file carries `[object Object]`: an object was turned into text where code belongs. +pub const ERR_GEN_STRINGIFIED_OBJECT: &str = "ERR_GEN_STRINGIFIED_OBJECT"; /// A field or reference the generator cannot turn into Rust. pub const ERR_UNSUPPORTED: &str = "ERR_RUST_UNSUPPORTED"; /// Crate dependencies between packages form a cycle, which Cargo refuses. diff --git a/server/rust/metaobjects-codegen/src/hashes.rs b/server/rust/metaobjects-codegen/src/hashes.rs index 725c240d4c..d049e1517f 100644 --- a/server/rust/metaobjects-codegen/src/hashes.rs +++ b/server/rust/metaobjects-codegen/src/hashes.rs @@ -8,7 +8,8 @@ //! carrying a `hash` field (owner fields other tools keep there are preserved). //! //! In memory the manifest is one flat map. A reader gets the union of every file in -//! `.hashes/` over the legacy `.metaobjects/.gen-state/.hashes.json`; a writer files each +//! `.hashes/`, or the legacy `.metaobjects/.gen-state/.hashes.json` alone while it is +//! present (ADR-0064 §2); a writer files each //! entry by [`place`] (a pure function of the entry and the loaded model) and writes only //! the files whose bytes changed. A run that finds the legacy file migrates it on its next //! save; a read-only command never saves. @@ -217,8 +218,8 @@ pub struct HashManifest { } impl HashManifest { - /// 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 + /// Read the manifest of `gen_state_dir`: the union of `.hashes/*.json`, or the legacy + /// `.hashes.json` alone while it is present (ADR-0064 §2). 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 { @@ -236,9 +237,17 @@ impl HashManifest { entries = map.unwrap_or_default(); } + // While the legacy file is present it is authoritative: a save deletes it right after + // writing the package files, so a `.hashes/` beside it is left over from another checkout + // (the old `.gitignore` ignores that directory, so it survives a reset or a branch + // switch), and its stale hashes would make every file the committed manifest vouches for + // read as hand-edited. The next save replaces or removes those stale files. let dir = gen_state_dir.join(HASHES_DIR); for name in Self::files_in(&dir) { existed = true; + if legacy { + continue; + } let (map, bad) = read_object(&dir.join(&name)); // A corrupt file is present but unusable: the next save replaces it. dirty |= bad; @@ -505,6 +514,29 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_committed_legacy_manifest_beats_a_stale_hashes_dir() { + // The old .gitignore ignores .hashes/, so one left by another checkout's run survives a + // reset beside the committed .hashes.json; its stale hashes must not count. + let dir = scratch("stale-hashes"); + std::fs::write(dir.join(HASHES_FILE), "{\"gen/order.rs\":\"committed\"}").unwrap(); + std::fs::create_dir_all(dir.join(HASHES_DIR)).unwrap(); + std::fs::write( + dir.join(HASHES_DIR).join(ROOT_FILE), + "{\"gen/order.rs\":\"stale\",\"gen/gone.rs\":\"stale\"}", + ) + .unwrap(); + let mut m = HashManifest::load(&dir); + assert_eq!(m.hash_of("gen/order.rs"), Some("committed")); + assert_eq!(m.hash_of("gen/gone.rs"), None); + m.save().unwrap(); + assert!(!dir.join(HASHES_FILE).exists()); + let again = HashManifest::load(&dir); + assert_eq!(again.hash_of("gen/order.rs"), Some("committed")); + assert_eq!(again.hash_of("gen/gone.rs"), None); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn keeps_owner_fields_of_object_entries() { let dir = scratch("owner"); diff --git a/server/rust/metaobjects-codegen/src/writer.rs b/server/rust/metaobjects-codegen/src/writer.rs index 730864ded1..0f5590b781 100644 --- a/server/rust/metaobjects-codegen/src/writer.rs +++ b/server/rust/metaobjects-codegen/src/writer.rs @@ -25,6 +25,8 @@ pub const ERR_WRITER_UNBALANCED_CLOSE: &str = "ERR_WRITER_UNBALANCED_CLOSE"; pub const ERR_WRITER_UNCLOSED_BLOCK: &str = "ERR_WRITER_UNCLOSED_BLOCK"; /// `line()` was handed text containing a line break. pub const ERR_WRITER_NEWLINE_IN_LINE: &str = "ERR_WRITER_NEWLINE_IN_LINE"; +/// `line()`, `open()` or `close()` was handed text that starts with a space or tab. +pub const ERR_WRITER_LEADING_WHITESPACE: &str = "ERR_WRITER_LEADING_WHITESPACE"; /// The width a generated Rust line may reach before its last list breaks. pub const RUST_WIDTH: usize = 100; @@ -418,10 +420,13 @@ impl CodeWriter { /// One line at the current indent. When the line does not fit the width, the LAST /// non-empty list in it is printed one item per line. A line whose text is empty is a - /// blank-line request. + /// blank-line request. Text that starts with whitespace is `ERR_WRITER_LEADING_WHITESPACE`: + /// indentation comes only from open blocks. pub fn line(&mut self, piece: impl Into) -> &mut Self { let piece = piece.into(); - self.put(&piece); + if self.unindented(&piece, "line") { + self.put(&piece); + } self } @@ -436,14 +441,18 @@ impl CodeWriter { /// Write the line that opens a block, then indent. pub fn open(&mut self, piece: impl Into) -> &mut Self { let piece = piece.into(); - self.open_piece(&piece); + if self.unindented(&piece, "open") { + self.open_piece(&piece); + } self } /// Dedent, then write the line that closes the block. pub fn close(&mut self, piece: impl Into) -> &mut Self { let piece = piece.into(); - self.close_piece(&piece); + if self.unindented(&piece, "close") { + self.close_piece(&piece); + } self } @@ -643,6 +652,25 @@ impl CodeWriter { } } + /// False (and the error recorded) when the text starts with whitespace: the writer adds the + /// indent, so a pre-indented piece would land one level too deep beside its siblings. + fn unindented(&mut self, piece: &Piece, what: &str) -> bool { + if self.error.is_some() { + return false; + } + let raw = flat(piece); + if raw.starts_with([' ', '\t']) { + self.fail( + ERR_WRITER_LEADING_WHITESPACE, + format!( + "{what}() text starts with whitespace; pass it without indentation, the writer indents it from the open blocks: {raw:?}" + ), + ); + return false; + } + true + } + fn open_piece(&mut self, piece: &Piece) { if self.error.is_some() { return; diff --git a/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache b/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache index ad91a93c2f..90dfc9bee4 100644 --- a/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache +++ b/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache @@ -14,7 +14,7 @@ The tables, columns and keys this model declares. Read it before writing a query - Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. {{/hasMigrate}} {{^hasMigrate}} -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. {{/hasMigrate}} - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. diff --git a/server/rust/metaobjects-codegen/tests/hash_manifest.rs b/server/rust/metaobjects-codegen/tests/hash_manifest.rs index b87d6846ee..306462dfa4 100644 --- a/server/rust/metaobjects-codegen/tests/hash_manifest.rs +++ b/server/rust/metaobjects-codegen/tests/hash_manifest.rs @@ -302,14 +302,15 @@ fn a_read_only_load_of_a_legacy_manifest_migrates_nothing() { } #[test] -fn a_package_file_wins_over_the_legacy_file() { +fn the_package_files_are_unread_while_the_legacy_file_is_present() { + // ADR-0064 §2 (corrected): a `.hashes/` beside an unmigrated `.hashes.json` is stale. 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("a.rs"), Some("old")); assert_eq!(m.hash_of("b.rs"), Some("b")); let _ = std::fs::remove_dir_all(&root); } diff --git a/server/rust/metaobjects-codegen/tests/stringified_object.rs b/server/rust/metaobjects-codegen/tests/stringified_object.rs new file mode 100644 index 0000000000..fd73388be3 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/stringified_object.rs @@ -0,0 +1,129 @@ +//! A generator that turns an object into text writes `[object Object]` where code belongs. It +//! often still compiles, so `run` (gen) and `verify` both refuse any output carrying it, before +//! anything is written or compared. The exact quoted string literal is code on purpose (the +//! emitted query-string encoder mirrors JavaScript's), so it is allowed. + +mod common; + +use std::path::PathBuf; + +use common::{Scratch, shop_files}; +use metaobjects_codegen::generator::ERR_GEN_STRINGIFIED_OBJECT; +use metaobjects_codegen::{ + EmittedFile, GenContext, GenError, Generator, RunError, RunOptions, run, verify, +}; + +struct Emits(&'static str); + +impl Generator for Emits { + fn name(&self) -> &str { + "stringify-helper" + } + fn identity(&self) -> String { + format!("stringify-helper:1:{}", self.0) + } + fn generate(&self, _: &GenContext<'_>) -> Result, GenError> { + Ok(vec![EmittedFile::new("helper.ts", self.0.to_string())]) + } +} + +fn opts(p: &Scratch) -> RunOptions { + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + opts +} + +fn refused(r: Result<(), RunError>) { + match r { + Err(RunError::Generator(e)) => { + assert_eq!(e.code, ERR_GEN_STRINGIFIED_OBJECT); + assert!( + e.message + .contains("helper.ts (generator \"stringify-helper\")"), + "{}", + e.message + ); + } + other => panic!("expected ERR_GEN_STRINGIFIED_OBJECT, got {other:?}"), + } +} + +#[test] +fn gen_refuses_output_containing_a_stringified_object_and_writes_nothing() { + let p = Scratch::project("stringified-gen", &shop_files()); + let g: Vec> = vec![Box::new(Emits("export const x = [object Object];\n"))]; + refused(run(&opts(&p), &g).map(|_| ())); + assert!(!p.exists("generated/helper.ts")); +} + +#[test] +fn verify_refuses_output_containing_a_stringified_object() { + let p = Scratch::project("stringified-verify", &shop_files()); + let good: Vec> = vec![Box::new(Emits("export const x = 1;\n"))]; + run(&opts(&p), &good).unwrap(); + let bad: Vec> = vec![Box::new(Emits("export const x = [object Object];\n"))]; + refused(verify(&opts(&p), &bad).map(|_| ())); +} + +#[test] +fn the_quoted_string_literal_is_written() { + let p = Scratch::project("stringified-quoted", &shop_files()); + let g: Vec> = + vec![Box::new(Emits("export const t = \"[object Object]\";\n"))]; + run(&opts(&p), &g).unwrap(); + assert!(p.exists("generated/helper.ts")); +} + +const PROSE: &str = "Fixes the [object Object] label bug"; + +/// Copies the first object's `@description` into a doc comment, the way documentation does. +struct Describes; + +impl Generator for Describes { + fn name(&self) -> &str { + "describe-entities" + } + fn identity(&self) -> String { + "describe-entities:1".to_string() + } + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + let described: Vec = ctx + .tree + .own_children(ctx.root) + .iter() + .filter_map(|&id| ctx.tree.attr(id, "description")) + .filter_map(|v| v.as_str().map(|s| format!("// {s}\n"))) + .collect(); + Ok(vec![EmittedFile::new("described.ts", described.concat())]) + } +} + +#[test] +fn text_a_model_string_carries_is_written() { + let model = format!( + r#"{{ "metadata.root": {{ "package": "acme", "children": [ + {{ "object.value": {{ "name": "Widget", "@description": "{PROSE}", "children": [ + {{ "field.string": {{ "name": "label" }} }} ] }} }} ] }} }}"# + ); + let p = Scratch::project( + "stringified-prose", + &[("metaobjects/meta.widget.json", model.as_str())], + ); + let g: Vec> = vec![Box::new(Describes)]; + run(&opts(&p), &g).unwrap(); + assert!(p.read("generated/described.ts").contains(PROSE)); +} + +#[test] +fn the_refusal_says_no_model_string_carries_the_marker() { + let p = Scratch::project("stringified-message", &shop_files()); + let g: Vec> = vec![Box::new(Emits("export const x = [object Object];\n"))]; + match run(&opts(&p), &g) { + Err(RunError::Generator(e)) => assert!( + e.message.contains("which no string in the model carries"), + "{}", + e.message + ), + other => panic!("expected ERR_GEN_STRINGIFIED_OBJECT, got {other:?}"), + } +} diff --git a/server/rust/metaobjects/src/rules_check.rs b/server/rust/metaobjects/src/rules_check.rs index 99988422b8..f756850c0e 100644 --- a/server/rust/metaobjects/src/rules_check.rs +++ b/server/rust/metaobjects/src/rules_check.rs @@ -24,6 +24,8 @@ //! (severity: `verify.lifecycle.unreachable`) //! * `WARN_TRANSITION_PERMISSION_SHADOWED`: a transition declaring `@permission` or //! `@public: true` that derives no command of its own, so the attribute is never read +//! * `WARN_DERIVED_COMMAND_BYPASSES_DECLARED`: under `rules.lifecycle.commands: all`, a transition a +//! declared command claims also derives a command that skips the declared body //! * `WARN_PERMISSION_DERIVED_NAME`: a transition that derives its own command, or an //! operation, with no `@permission` and not `@public` (severity: `rules.permissions.names`) //! @@ -50,6 +52,7 @@ pub const WARN_LIFECYCLE_INITIAL_TERMINAL: &str = "WARN_LIFECYCLE_INITIAL_TERMIN pub const WARN_TRANSITION_UNREACHABLE: &str = "WARN_TRANSITION_UNREACHABLE"; pub const WARN_PERMISSION_DERIVED_NAME: &str = "WARN_PERMISSION_DERIVED_NAME"; pub const WARN_TRANSITION_PERMISSION_SHADOWED: &str = "WARN_TRANSITION_PERMISSION_SHADOWED"; +pub const WARN_DERIVED_COMMAND_BYPASSES_DECLARED: &str = "WARN_DERIVED_COMMAND_BYPASSES_DECLARED"; const T_API: &str = "api"; const T_OPERATION: &str = "operation"; @@ -523,6 +526,59 @@ fn check_shadowed_permissions( } } +/// Under `rules.lifecycle.commands: all` a transition a declared command claims derives a command of +/// its own as well, which makes the transition without running the declared command's body. +fn check_derived_bypasses_declared( + env: &Env<'_>, + root: NodeId, + settings: &RulesSettings, + out: &mut Vec, +) { + if settings.lifecycle_commands != RulesLifecycleCommands::All { + return; + } + let tree = env.tree; + let claimed = claimed_transitions(env, root); + for entity in command_entities(tree, root) { + for t in entity_transitions(tree, entity) { + let mut claimers: Vec = Vec::new(); + for c in claims_on(tree, &claimed, entity, t) { + let api = tree + .node(c.op) + .parent + .map(|p| tree.node(p).name.as_str()) + .unwrap_or(""); + let label = format!("{api}.{}", tree.node(c.op).name); + if !claimers.contains(&label) { + claimers.push(label); + } + } + if claimers.is_empty() { + continue; + } + let field_name = tree + .node(t) + .parent + .map(|f| tree.node(f).name.as_str()) + .unwrap_or(""); + let entity_name = tree.node(entity).name.as_str(); + let t_name = tree.node(t).name.as_str(); + out.push(Diagnostic { + severity: Severity::Warn, + code: WARN_DERIVED_COMMAND_BYPASSES_DECLARED, + path: format!("{}.{field_name}.{t_name}", rules_address(tree, entity)), + message: format!( + "transition \"{t_name}\" of \"{entity_name}\" is claimed by {}, but rules.lifecycle.commands is \"all\", \ + so the derived command \"{entity_name}.{t_name}\" makes the same transition without running {} body. \ + Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command.", + quote_list(&claimers), + if claimers.len() == 1 { "its" } else { "their" }, + ), + }); + } + } +} + fn check_permission_names( env: &Env<'_>, root: NodeId, @@ -613,6 +669,7 @@ pub fn check_rules( check_lifecycle(tree, l, settings, &mut diagnostics); } check_shadowed_permissions(&env, root, settings, &mut diagnostics); + check_derived_bypasses_declared(&env, root, settings, &mut diagnostics); check_permission_names(&env, root, settings, &mut diagnostics); RulesCheckResult { diagnostics, diff --git a/server/typescript/packages/cli/src/commands/gen.ts b/server/typescript/packages/cli/src/commands/gen.ts index 90dba4444a..0fe55a827e 100644 --- a/server/typescript/packages/cli/src/commands/gen.ts +++ b/server/typescript/packages/cli/src/commands/gen.ts @@ -48,6 +48,7 @@ import { clearStoredFingerprint, computeGenInputs, decideGenSkip, keyFor, withModel, writeStoredFingerprint, type GenInputs, } from "../lib/gen-fingerprint.js"; import { GEN_CONFIG_FILE } from "../lib/gen-collection.js"; +import { emittedTypeScriptProblems } from "../lib/emitted-ts-parse-check.js"; /** * Print a load failure with everything the loader's ADR-0009 envelope carried — the stable @@ -171,7 +172,10 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat // machine that did not generate the output. Silent unless it is ignored. Keyed on // projectRoot, not cwd, for the same reason its neighbour is — the manifest belongs to // whichever directory `resolveCollection` decided the metadata lives in. - advise(warnIfManifestIgnored(projectRoot)); + // Asked AFTER the run's own writes (or on the skip path, where nothing is written): the first 1.3 run + // over a 1.2 tree migrates the manifest and rewrites `.metaobjects/.gitignore` to un-ignore it, so a + // check made up front reported a rule this very run had just removed. + const adviseManifestIgnored = (): void => advise(warnIfManifestIgnored(projectRoot)); // Owned generator copies that are the shipped reference, unchanged: they miss every later fix. // Says nothing when the project owns none, and never affects the exit code. const stockNotice = await stockCopyNotice(projectRoot).catch(() => undefined); @@ -260,6 +264,7 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat if (skipInputs !== undefined && genMaySkip(flags)) { const verdict = decideGenSkip(skipInputs); if (verdict.skip) { + adviseManifestIgnored(); await reportGenSkip(fmt, verdict.recorded.length, warnings); return 0; } @@ -321,6 +326,8 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat config: forgeConfig, metadata, projectRoot, + // Emitted TypeScript must parse before any of it is written (the same check verify runs). + checkEmitted: (files) => emittedTypeScriptProblems(files, projectRoot), // The COMPOSED catalog, so the requires / api-framework gates can see the react // and tanstack entries too. codegen-ts only knows its own slice. catalog, @@ -368,6 +375,7 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat } for (const w of result.warnings) { log.warn(w); warnings.push(w); } + adviseManifestIgnored(); // Requirements the project declares (its own and the inherited ones it keeps, as the // requirement-tests generator itself walks them) and nothing that tests them: say which line diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index ab24edaec0..0a9be5d163 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -1789,7 +1789,7 @@ export async function verifyCommand( for (const line of schemaAdvisoryLines(driftResult.advisories)) log.warn(`verify: ${line}`); - const changes = driftResult.changes; + const changes = collapseViewPairs(driftResult.changes); schemaDrift = { changes: changes.map(toSchemaDriftRow), findings: ledgerDrift }; if (changes.length === 0 && ledgerDrift.length === 0) { say(`meta verify — schema in sync with ${displayUrl}.`); @@ -2113,6 +2113,35 @@ const DRIFT_PRESENTATION: Record `${schema ?? ""}\u0000${name}`; + const created = new Map>(); + const dropped = new Set(); + for (const c of changes) { + if (c.kind === "create-view") created.set(key(c.schema, c.view.name), c); + else if (c.kind === "drop-view") dropped.add(key(c.schema, c.view)); + } + const out: Change[] = []; + for (const c of changes) { + if (c.kind === "create-view" && dropped.has(key(c.schema, c.view.name))) continue; // folded into its drop + const make = c.kind === "drop-view" ? created.get(key(c.schema, c.view)) : undefined; + if (c.kind !== "drop-view" || make === undefined) { out.push(c); continue; } + out.push({ + kind: "replace-view", view: make.view, status: make.status, + ...(make.schema !== undefined ? { schema: make.schema } : {}), + ...(c.restore !== undefined ? { restore: c.restore } : {}), + ...(make.reason !== undefined ? { reason: make.reason } : {}), + }); + } + return out; +} + /** Human-readable one-line-per-change drift summary (table/column/index/fk/view). */ function summarizeDrift(changes: Change[]): string[] { return changes.map((c) => { diff --git a/server/typescript/packages/cli/src/lib/allow.ts b/server/typescript/packages/cli/src/lib/allow.ts index ef94d006a2..d91466f758 100644 --- a/server/typescript/packages/cli/src/lib/allow.ts +++ b/server/typescript/packages/cli/src/lib/allow.ts @@ -119,6 +119,12 @@ function withViewReason(name: string, reason: ViewChangeReason | undefined): str return reason === undefined ? name : `${name} (${viewReasonText(reason)})`; } +const STAR_HINT = + "the view selects `*`, which Postgres expanded when the view was created, so a table it reads may have gained " + + "columns since; to clear the drift, list the view's columns explicitly, or drop and recreate the view by hand " + + "(offline meta migrate plans nothing for it; meta migrate --from-db compares through the shadow database and " + + "can plan a replace, or a drop and create, so review that plan before --apply)"; + function viewReasonText(r: ViewChangeReason): string { switch (r.kind) { case "missing": return "declared by the metadata, not in the database"; @@ -129,7 +135,8 @@ function viewReasonText(r: ViewChangeReason): string { : r.firstDifference !== undefined ? `definition text differs: metadata «${r.firstDifference.expected}» vs database «${r.firstDifference.actual}»` : "definition text differs"; - return recreatedAround(what, r.tables); + const cause = r.starExpansion === true ? `; ${STAR_HINT}` : ""; + return `${recreatedAround(what, r.tables)}${cause}`; } case "unfingerprinted": return recreatedAround( diff --git a/server/typescript/packages/cli/src/lib/codegen-drift.ts b/server/typescript/packages/cli/src/lib/codegen-drift.ts index 608fbf40b6..13b46137b5 100644 --- a/server/typescript/packages/cli/src/lib/codegen-drift.ts +++ b/server/typescript/packages/cli/src/lib/codegen-drift.ts @@ -44,6 +44,7 @@ import type { MetaobjectsGenConfig, RunGenOpts } from "@metaobjectsdev/codegen-t import { DEFAULT_TARGET_NAME } from "@metaobjectsdev/codegen-ts/engine"; import { gitIgnored } from "./git-ignore.js"; import { toPosix } from "./rel-posix.js"; +import { emittedTypeScriptProblems } from "./emitted-ts-parse-check.js"; import type { MetaData } from "@metaobjectsdev/metadata"; /** Per-target config as carried on MetaobjectsGenConfig (TargetConfig isn't @@ -212,6 +213,8 @@ export async function computeCodegenDrift( metadata, projectRoot: root, dryRun: true, + // A render that does not parse fails the gate, as it fails `meta gen`. + checkEmitted: (files) => emittedTypeScriptProblems(files, root), // A generator that reads the project's files (`ctx.inputRoot`) reads them here. inputRoot: root, ...(scope !== undefined ? { scope } : {}), diff --git a/server/typescript/packages/cli/src/lib/emitted-ts-parse-check.ts b/server/typescript/packages/cli/src/lib/emitted-ts-parse-check.ts new file mode 100644 index 0000000000..3ec2670bb6 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/emitted-ts-parse-check.ts @@ -0,0 +1,87 @@ +// Parse check of the TypeScript a `meta gen` run emitted, run before anything is written +// (`RunGenOpts.checkEmitted`). The three-way merge, the zero-write regeneration and +// `meta verify --codegen` all compare text and never read it as code, so output that does not +// parse passed every one of them and the adopter's build was the first thing to object. The +// reported case: an owned 1.2 entity composer joined the engine's fragments with ts-poet's +// `joinCode`, which prints each fragment's imports again, and every entity file declared +// `import { z } from "zod"` twice. +// +// The parser is the one `jiti` already carries to load `metaobjects.config.ts` (Babel's), so +// the check adds no dependency. It reports syntax errors and the early errors a module parser +// raises, a binding declared twice among them; it does not type-check. +import { extname, relative } from "node:path"; +import { createJiti } from "jiti"; + +const CHECKED = new Set([".ts", ".tsx", ".mts", ".cts"]); +/** Declaration files hold ambient declarations a module parser refuses (`export const a: number;`). */ +const DECLARATION_FILE = /\.d\.[mc]?ts$/; +const ERROR_MARK = "__JITI_ERROR__ = "; +/** Babel's message for valid syntax behind a parser plugin it was not given: its limit, not the output's. */ +const MISSING_PLUGIN = "Support for the experimental syntax"; + +interface JitiParseError { + line?: number; + column?: number; + message?: string; +} + +let parser: ReturnType | undefined; + +function parseError(fullPath: string, content: string): JitiParseError | undefined { + // No disk cache: a check writes nothing. + parser ??= createJiti(import.meta.url, { fsCache: false, moduleCache: false, jsx: true }); + // Global-hooks hygiene, as in `loadMetaobjectsConfig`. Babel's rewrite-stack-trace replaces + // `Error.prepareStackTrace` the first time it runs in a process and never again. On Bun the + // value it wraps is Bun's native default, which throws `TypeError: First argument must be an + // Error object` for an ES5-style error constructor (libsql's `SqliteError`), so a leaked + // wrapper turns every later such error into that TypeError. Because the installer runs only + // once, a leak here cannot be undone by the config loader's own restore: snapshot and restore. + const prepareStackTraceBefore = Error.prepareStackTrace; + const stackTraceLimitBefore = Error.stackTraceLimit; + let out: string; + try { + out = parser.transform({ + source: content, + filename: fullPath, + ts: true, + jsx: true, + babel: { parserOpts: { plugins: ["decoratorAutoAccessors"] } }, + }); + } finally { + if (Error.prepareStackTrace !== prepareStackTraceBefore) Error.prepareStackTrace = prepareStackTraceBefore; + if (Error.stackTraceLimit !== stackTraceLimitBefore) Error.stackTraceLimit = stackTraceLimitBefore; + } + const at = out.indexOf(ERROR_MARK); + if (at === -1) return undefined; + const json = out.slice(at + ERROR_MARK.length).split("\n")[0]!.replace(/;\s*$/, ""); + let parsed: unknown; + try { + parsed = JSON.parse(json); + } catch { + return {}; + } + if (typeof parsed !== "object" || parsed === null) return {}; + const err = parsed as JitiParseError; + return err.message?.startsWith(MISSING_PLUGIN) ? undefined : err; +} + +/** + * One line per emitted TypeScript file that does not parse: the path (relative to `root` + * when given), the generator that emitted it, and the parser's position and message. + */ +export function emittedTypeScriptProblems( + files: readonly { fullPath: string; content: string; generatedBy: string }[], + root?: string, +): string[] { + const problems: string[] = []; + for (const f of files) { + if (!CHECKED.has(extname(f.fullPath)) || DECLARATION_FILE.test(f.fullPath)) continue; + const err = parseError(f.fullPath, f.content); + if (err === undefined) continue; + const where = root !== undefined ? relative(root, f.fullPath) : f.fullPath; + const pos = err.line !== undefined ? ` line ${err.line}${err.column !== undefined ? `:${err.column}` : ""}` : ""; + const msg = (err.message ?? "parse error").split("\n")[0]!.replace(/\s*\(\d+:\d+\)$/, ""); + problems.push(`${where} (generator "${f.generatedBy}")${pos}: ${msg}`); + } + return problems; +} diff --git a/server/typescript/packages/cli/src/lib/rules-check.ts b/server/typescript/packages/cli/src/lib/rules-check.ts index ee78704e35..5c6cdf4ed2 100644 --- a/server/typescript/packages/cli/src/lib/rules-check.ts +++ b/server/typescript/packages/cli/src/lib/rules-check.ts @@ -19,6 +19,10 @@ // WARN_TRANSITION_PERMISSION_SHADOWED a transition declaring @permission or @public: true that // derives no command of its own, so the attribute is never // read (always a warning) +// WARN_DERIVED_COMMAND_BYPASSES_DECLARED a transition a declared command claims that +// `rules.lifecycle.commands: all` ALSO derives a command +// for, so the derived one runs without the declared body +// (always a warning) // WARN_PERMISSION_DERIVED_NAME a transition that derives its own command, or an // operation, with no @permission and not @public // (severity: `rules.permissions.names`) @@ -65,6 +69,7 @@ export const WARN_LIFECYCLE_INITIAL_TERMINAL = "WARN_LIFECYCLE_INITIAL_TERMINAL" export const WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE"; export const WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME"; export const WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED"; +export const WARN_DERIVED_COMMAND_BYPASSES_DECLARED = "WARN_DERIVED_COMMAND_BYPASSES_DECLARED"; /** What the model declares, for the line `meta verify` prints on every run. */ export interface RulesSummary { @@ -194,6 +199,31 @@ function checkShadowedPermissions(root: MetaData, settings: RulesSettings, out: } } +/** Under `rules.lifecycle.commands: all`, a transition a declared command claims derives a command + * of its own as well. Both make the transition, but the derived one runs none of the declared + * command's body (the business rule) and asks about the derived permission name. Reported per + * concrete entity with a source, so each entity's derived command is named. */ +function checkDerivedBypassesDeclared(root: MetaData, settings: RulesSettings, out: Diagnostic[]): void { + if (settings.lifecycleCommands !== "all") return; + const claimed = claimedTransitions(root); + for (const entity of commandEntities(root)) { + for (const t of entityTransitions(entity)) { + const claimers = [...new Set(claimsOn(claimed, entity, t).map((c) => `${c.op.parent?.name ?? ""}.${c.op.name}`))]; + if (claimers.length === 0) continue; + out.push({ + severity: "warn", + code: WARN_DERIVED_COMMAND_BYPASSES_DECLARED, + path: `${rulesAddress(entity)}.${t.parent?.name ?? ""}.${t.name}`, + message: + `transition "${t.name}" of "${entity.name}" is claimed by ${quoteList(claimers)}, but rules.lifecycle.commands is "all", ` + + `so the derived command "${entity.name}.${t.name}" makes the same transition without running ` + + `${claimers.length === 1 ? "its" : "their"} body. Set rules.lifecycle.commands to "unclaimed" (the default), or ` + + `remove the declared command.`, + }); + } + } +} + function checkPermissionNames(root: MetaData, settings: RulesSettings, out: Diagnostic[]): void { if (settings.permissionNames === "derive") return; const severity: Severity = settings.permissionNames === "require" ? "error" : "warn"; @@ -240,6 +270,7 @@ export function checkRules(root: MetaData, settings: RulesSettings): RulesCheckR const diagnostics: Diagnostic[] = []; for (const l of lifecycles) checkLifecycle(l, settings, diagnostics); checkShadowedPermissions(root, settings, diagnostics); + checkDerivedBypassesDeclared(root, settings, diagnostics); checkPermissionNames(root, settings, diagnostics); return { diagnostics, diff --git a/server/typescript/packages/cli/test/gen-emitted-ts-parses.test.ts b/server/typescript/packages/cli/test/gen-emitted-ts-parses.test.ts new file mode 100644 index 0000000000..5daa009577 --- /dev/null +++ b/server/typescript/packages/cli/test/gen-emitted-ts-parses.test.ts @@ -0,0 +1,118 @@ +// `meta gen` and `meta verify --codegen` refuse emitted TypeScript that does not parse. +// +// The reported case: an owned 1.2 entity composer joined the engine's fragments (which since +// 1.3.0 are writer `Frag`s, not ts-poet `Code`) with `joinCode`, which prints each fragment's +// imports again, so every entity file declared `import { z } from "zod"` twice. Gen, the +// zero-write regen and `verify --codegen` all passed, because none of them reads the output +// as code; the adopter's build was the first thing to object. +import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { existsSync, mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { run } from "../src/index.js"; +import { emittedTypeScriptProblems } from "../src/lib/emitted-ts-parse-check.js"; + +const WORKSPACE_TMP = resolve(import.meta.dirname, "fixtures", "__tmp__"); +const DUP = 'import { z } from "zod";\nimport { z } from "zod";\nexport const S = z.string();\n'; +const GOOD = 'import { z } from "zod";\nexport const S = z.string();\n'; + +function setupRepo(content: string): string { + mkdirSync(WORKSPACE_TMP, { recursive: true }); + const root = mkdtempSync(join(WORKSPACE_TMP, "gen-ts-parses-")); + mkdirSync(join(root, "metaobjects"), { recursive: true }); + writeFileSync(join(root, "metaobjects", "meta.app.json"), JSON.stringify({ + "metadata.root": { package: "app", children: [ + { "object.entity": { name: "Note", children: [ + { "source.rdb": { "@table": "notes" } }, { "field.long": { name: "id" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + ] }, + }), "utf8"); + mkdirSync(join(root, ".metaobjects"), { recursive: true }); + writeFileSync(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, sources: [] }), "utf8"); + writeConfig(root, content); + return root; +} + +function writeConfig(root: string, content: string): void { + writeFileSync(join(root, "metaobjects.config.ts"), ` +import { defineConfig } from "@metaobjectsdev/codegen-ts"; +export default defineConfig({ + outDir: ${JSON.stringify(join(root, "generated"))}, + dialect: "postgres", + extStyle: "none", + generators: [{ name: "owned-composer", generate: () => [{ path: "Note.ts", content: ${JSON.stringify(content)} }] }], +}); +`); +} + +let err: string[]; +let origLog: typeof console.log; +let origErr: typeof console.error; +beforeEach(() => { + err = []; + origLog = console.log; + origErr = console.error; + console.log = () => {}; + console.error = (...a: unknown[]) => { err.push(a.map(String).join(" ")); }; +}); +afterEach(() => { + console.log = origLog; + console.error = origErr; +}); + +describe("emitted TypeScript must parse", () => { + test("the check names the file, the generator and the duplicate binding, and passes good output", () => { + const files = [ + { fullPath: "/p/gen/Note.ts", content: DUP, generatedBy: "owned-composer" }, + { fullPath: "/p/gen/Ok.ts", content: GOOD, generatedBy: "entity-file" }, + { fullPath: "/p/gen/View.tsx", content: "export const V = () =>
{1}
;\n", generatedBy: "form-file" }, + { fullPath: "/p/gen/notes.md", content: "import { z } from 'a';\nimport { z } from 'a';\n", generatedBy: "docs" }, + ]; + const problems = emittedTypeScriptProblems(files, "/p"); + expect(problems).toHaveLength(1); + expect(problems[0]).toMatch(/^gen\/Note\.ts \(generator "owned-composer"\) line 2:\d+: Identifier 'z' has already been declared/); + }); + + test("valid TypeScript passes: declaration files and an accessor class field", () => { + const files = [ + { fullPath: "/p/gen/types.d.ts", content: "export const a: number;\nexport declare function f(x: string): void;\n", generatedBy: "types" }, + { fullPath: "/p/gen/types.d.mts", content: "export const b: string;\n", generatedBy: "types" }, + { fullPath: "/p/gen/types.d.cts", content: "export const c: boolean;\n", generatedBy: "types" }, + { fullPath: "/p/gen/Store.ts", content: "export class Store {\n accessor count: number = 0;\n}\n", generatedBy: "store" }, + ]; + expect(emittedTypeScriptProblems(files, "/p")).toEqual([]); + }); + + test("a file with an accessor field is still checked past it", () => { + const content = "export class Store {\n accessor count = 0;\n}\n" + DUP; + const problems = emittedTypeScriptProblems([{ fullPath: "/p/gen/Store.ts", content, generatedBy: "store" }], "/p"); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("Identifier 'z' has already been declared"); + }); + + test("meta gen refuses and writes nothing", async () => { + const root = setupRepo(DUP); + try { + expect(await run(["gen", "--cwd", root, "--format", "text"])).toBe(1); + const text = err.join("\n"); + expect(text).toContain("generated code does not parse"); + expect(text).toContain("owned-composer"); + expect(text).toContain("Identifier 'z' has already been declared"); + expect(existsSync(join(root, "generated", "Note.ts"))).toBe(false); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("meta verify --codegen fails on a render that does not parse", async () => { + const root = setupRepo(GOOD); + try { + expect(await run(["gen", "--cwd", root, "--format", "text"])).toBe(0); + writeConfig(root, DUP); + err = []; + expect(await run(["verify", "--codegen", "--cwd", root, "--format", "text"])).not.toBe(0); + expect(err.join("\n")).toContain("generated code does not parse"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/server/typescript/packages/cli/test/gen-manifest-ignore-advisory.test.ts b/server/typescript/packages/cli/test/gen-manifest-ignore-advisory.test.ts new file mode 100644 index 0000000000..32b5972cd3 --- /dev/null +++ b/server/typescript/packages/cli/test/gen-manifest-ignore-advisory.test.ts @@ -0,0 +1,81 @@ +// The first `meta gen` over a 1.2-shaped tree migrates the hash manifest and, in the same run, rewrites +// `.metaobjects/.gitignore` to un-ignore `.gen-state/.hashes/`. The advisory "the manifest is git-ignored" +// used to be asked BEFORE that rewrite, so the run reported a rule it had just removed and the next run +// was silent. It is now asked after the run's own writes. Real git repositories, because the verdict +// is git's, not ours. +import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test"; +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { run } from "../src/index.js"; +import { log } from "../src/lib/log.js"; + +let root: string; +let warned: string[]; +let origLog: typeof console.log; +let origErr: typeof console.error; +const spies: Array<{ mockRestore(): void }> = []; + +beforeEach(() => { + warned = []; + origLog = console.log; + origErr = console.error; + console.log = () => {}; + console.error = () => {}; + spies.push(spyOn(log, "warn").mockImplementation((m: string) => { warned.push(m); })); + root = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "gen-ignore-advisory-")); +}); +afterEach(() => { + console.log = origLog; + console.error = origErr; + for (const s of spies.splice(0)) s.mockRestore(); + rmSync(root, { recursive: true, force: true }); +}); + +/** A 1.2-shaped project: legacy `.hashes.json`, plus a leftover `.hashes/` (which the old rule ignores). */ +function setup(ignoreFile: { rel: string; body: string }): void { + spawnSync("git", ["-C", root, "init", "-q"], { encoding: "utf-8" }); + mkdirSync(join(root, "metaobjects"), { recursive: true }); + writeFileSync(join(root, "metaobjects", "meta.app.json"), JSON.stringify({ + "metadata.root": { package: "app", children: [ + { "object.entity": { name: "Note", children: [ + { "source.rdb": { "@table": "notes" } }, { "field.long": { name: "id" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + ] }, + }), "utf8"); + mkdirSync(join(root, ".metaobjects", ".gen-state", ".hashes"), { recursive: true }); + writeFileSync(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, sources: [] }), "utf8"); + writeFileSync(join(root, ".metaobjects", ".gen-state", ".hashes.json"), "{}\n"); + writeFileSync(join(root, ".metaobjects", ".gen-state", ".hashes", ".root.json"), "{}\n"); + writeFileSync(join(root, ignoreFile.rel), ignoreFile.body); + writeFileSync(join(root, "metaobjects.config.ts"), ` +import { defineConfig } from "@metaobjectsdev/codegen-ts"; +export default defineConfig({ + outDir: ${JSON.stringify(join(root, "generated"))}, + dialect: "postgres", + extStyle: "none", + generators: [{ name: "one", generate: () => [{ path: "Note.ts", content: "export const N = 1;\\n" }] }], +}); +`); +} + +const manifestWarnings = (): string[] => warned.filter((w) => w.includes("is git-ignored")); + +describe("meta gen: the manifest-ignored advisory reflects the state after the run's own rewrite", () => { + test("a 1.2 .metaobjects/.gitignore is fixed by the run, and the run does not warn about it", async () => { + setup({ rel: ".metaobjects/.gitignore", body: ".gen-state/*\n!.gen-state/.hashes.json\n" }); + await run(["gen", "--cwd", root]); + expect(readFileSync(join(root, ".metaobjects", ".gitignore"), "utf8")).toContain("!.gen-state/.hashes/"); + expect(existsSync(join(root, ".metaobjects", ".gen-state", ".hashes.json"))).toBe(false); + expect(manifestWarnings()).toEqual([]); + }); + + test("a rule the run does not rewrite (root .gitignore) still warns", async () => { + setup({ rel: ".gitignore", body: ".metaobjects/.gen-state/\n" }); + await run(["gen", "--cwd", root]); + expect(manifestWarnings()).toHaveLength(1); + expect(manifestWarnings()[0]).toContain(".gitignore:1"); + }); +}); + diff --git a/server/typescript/packages/cli/test/unit/emitted-ts-parse-check-hygiene.test.ts b/server/typescript/packages/cli/test/unit/emitted-ts-parse-check-hygiene.test.ts new file mode 100644 index 0000000000..fa99827d94 --- /dev/null +++ b/server/typescript/packages/cli/test/unit/emitted-ts-parse-check-hygiene.test.ts @@ -0,0 +1,38 @@ +// The emitted-TypeScript parse check runs jiti's bundled Babel transformer, the same one the +// config loader falls back to. Babel's rewrite-stack-trace installs a `prepareStackTrace` +// wrapper the first time it runs in a process and never again, so if the parse check leaks +// it, no later restore can undo it. On Bun that wrapper delegates to Bun's native default, +// which throws `TypeError: First argument must be an Error object` for an ES5-style error +// constructor (libsql's `SqliteError` shape). This file pins that the check leaves the +// process's error hooks exactly as it found them. +import { describe, test, expect } from "bun:test"; +import { emittedTypeScriptProblems } from "../../src/lib/emitted-ts-parse-check.js"; + +describe("emittedTypeScriptProblems — global hooks hygiene", () => { + test("a parse check leaves Error.prepareStackTrace and Error.stackTraceLimit untouched", () => { + const before = Error.prepareStackTrace; + const limit = Error.stackTraceLimit; + const problems = emittedTypeScriptProblems([ + { fullPath: "/x/Good.ts", content: "export const a = 1;\n", generatedBy: "probe" }, + { fullPath: "/x/Bad.ts", content: "export const = ;\n", generatedBy: "probe" }, + ]); + expect(problems).toHaveLength(1); + expect(Error.prepareStackTrace).toBe(before); + expect(Error.stackTraceLimit).toBe(limit); + }); + + test("a legacy-constructor error still carries its own message after a parse check", () => { + emittedTypeScriptProblems([{ fullPath: "/x/Bad.ts", content: "export const = ;\n", generatedBy: "probe" }]); + + function LegacyError(this: Record, msg: string) { + this["message"] = msg; + Error.captureStackTrace(this, LegacyError); + } + LegacyError.prototype = Object.create(Error.prototype); + + const constructed = new (LegacyError as unknown as new (m: string) => { message: string })( + "CHECK constraint failed: things", + ); + expect(constructed.message).toMatch(/CHECK constraint failed/); + }); +}); diff --git a/server/typescript/packages/cli/test/unit/verify-view-star-drift.test.ts b/server/typescript/packages/cli/test/unit/verify-view-star-drift.test.ts new file mode 100644 index 0000000000..2de9c883b4 --- /dev/null +++ b/server/typescript/packages/cli/test/unit/verify-view-star-drift.test.ts @@ -0,0 +1,56 @@ +import { test, expect } from "bun:test"; +import type { Change } from "@metaobjectsdev/migrate-ts"; +import { describeChange } from "../../src/lib/allow.js"; +import { collapseViewPairs } from "../../src/commands/verify.js"; + +const allowed = { state: "allowed" } as const; +const starView = { name: "order_line_view", sql: "SELECT o.*, l.id AS line_id FROM orders o LEFT JOIN line l ON true" }; +const reason = { + kind: "definition", compared: "text", firstDifference: { expected: "o.new_col", actual: "l.id AS line_id" }, +} as const; + +test("a changed view renders as one entry, not a drop/create pair", () => { + const changes: Change[] = [ + { kind: "drop-view", view: "order_line_view", reason, status: allowed }, + { kind: "create-view", view: starView, reason, status: allowed }, + { kind: "drop-view", view: "gone", reason: { kind: "undeclared" }, status: allowed }, + ]; + const out = collapseViewPairs(changes); + expect(out.map((c) => c.kind)).toEqual(["replace-view", "drop-view"]); +}); + +test("a pair folds only when the drop and the create name the same view in the same schema", () => { + const v = { name: "order_summary", sql: "SELECT 1" }; + const changes: Change[] = [ + { kind: "drop-view", view: "order_summary", schema: "public", reason: { kind: "undeclared" }, status: allowed }, + { kind: "create-view", view: v, schema: "reporting", reason: { kind: "missing" }, status: allowed }, + { kind: "drop-view", view: "v", schema: "a", reason, status: allowed }, + { kind: "create-view", view: { name: "v", sql: "SELECT 'a'" }, schema: "a", reason, status: allowed }, + { kind: "drop-view", view: "v", schema: "b", reason, status: allowed }, + { kind: "create-view", view: { name: "v", sql: "SELECT 'b'" }, schema: "b", reason, status: allowed }, + ]; + const out = collapseViewPairs(changes); + const row = (c: Change) => + c.kind === "drop-view" ? [c.kind, c.schema, c.view] + : c.kind === "create-view" || c.kind === "replace-view" ? [c.kind, c.schema, c.view.sql] + : [c.kind]; + expect(out.map(row)) + .toEqual([ + ["drop-view", "public", "order_summary"], + ["create-view", "reporting", "SELECT 1"], + ["replace-view", "a", "SELECT 'a'"], + ["replace-view", "b", "SELECT 'b'"], + ]); +}); + +test("a difference diff marks as a possible `*` expansion names it as a possible cause", () => { + const text = describeChange({ + kind: "replace-view", view: starView, reason: { ...reason, starExpansion: true }, status: allowed, + }); + expect(text).toContain("selects `*`"); + expect(text).toContain("to clear the drift, list the view's columns explicitly, or drop and recreate the view by hand"); +}); + +test("a text difference diff does not mark gets no star hint, even on a `*` body", () => { + expect(describeChange({ kind: "replace-view", view: starView, reason, status: allowed })).not.toContain("selects `*`"); +}); diff --git a/server/typescript/packages/codegen-ts/src/engine.ts b/server/typescript/packages/codegen-ts/src/engine.ts index 88c4959fa1..cd10120bbe 100644 --- a/server/typescript/packages/codegen-ts/src/engine.ts +++ b/server/typescript/packages/codegen-ts/src/engine.ts @@ -61,4 +61,7 @@ export * from "./view-context.js"; export * from "./writer/code-writer.js"; export * from "./writer/ts-fragment.js"; export * from "./writer/ts-writer.js"; +// The entity-file writer class, by name: an owned entity generator moving onto the writer +// subclasses it. Its module stays a template `meta eject` copies, so it is not an engine module. +export { EntityFileWriter, type EntityFileWriterClass } from "./templates/entity-file.js"; export { AUTHORING_SURFACE, ENGINE_MODULES } from "./engine-surface.js"; diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts index ffa55c6a47..649c536765 100644 --- a/server/typescript/packages/codegen-ts/src/generator.ts +++ b/server/typescript/packages/codegen-ts/src/generator.ts @@ -42,6 +42,11 @@ export interface GenContext { * filter is set). Always call this from helpers; do not call generator.filter * directly. */ matches: (entity: MetaObject) => boolean; + /** Does a generator in this run that provides the entity modules (`provides.entityModule`) emit + * this object's module? Read from the run, so a generator that imports another's module (the + * service layer) skips what the entity-module generator's own `filter` left out, rather than + * import a file nothing writes. Absent (a hand-built context) ⇒ every object is covered. */ + entityModuleCovers?: (entity: MetaObject) => boolean; /** FR-023 §11.1 item 2 — the model-wide output-scope predicate over a node's * `resolutionKey()` (the runner's own `RunGenOpts.scope`, verbatim). A * DIFFERENT knob from `matches`: `matches` is the per-generator `filter` diff --git a/server/typescript/packages/codegen-ts/src/generators/api-model.ts b/server/typescript/packages/codegen-ts/src/generators/api-model.ts index 26278b1dcc..37301002c2 100644 --- a/server/typescript/packages/codegen-ts/src/generators/api-model.ts +++ b/server/typescript/packages/codegen-ts/src/generators/api-model.ts @@ -309,6 +309,9 @@ export interface ApiModelContext { * mounts only its own verbs, so each surface documents the same subset. A surface left * out means every verb, which documents byte-identically to before. */ expose?: RoutesExpose; + /** Does the run write this object's entity module? The query helpers import it, so an object + * the run leaves out gets none documented. Absent ⇒ every object is covered. */ + entityModuleCovers?: (entity: MetaObject) => boolean; } // --------------------------------------------------------------------------- @@ -338,7 +341,12 @@ export function buildApiModel(root: MetaRoot, ctx: ApiModelContext): ApiModel { // every symbol documents is the derived one. `generatableObjects` is the same swap // `runGen` hands the generators, so the units are the objects code was emitted for. for (const obj of generatableObjects(root.objects(), root)) { - units.push(buildEntityUnit(obj, pkCtx, root, layout, relationMap, includeHono, surfaces, apiPrefix, expose)); + // An object whose entity module no generator in this run emits has neither that module + // nor the query helpers built on it, so the reference must not tell readers to import + // either (the runner skips its queries and routes for the same reason). + const covered = ctx.entityModuleCovers?.(obj) ?? true; + const objSurfaces = { ...surfaces, entity: surfaces.entity && covered, queries: surfaces.queries && covered }; + units.push(buildEntityUnit(obj, pkCtx, root, layout, relationMap, includeHono, objSurfaces, apiPrefix, expose)); } for (const tmpl of templateOutputs(root)) { @@ -1303,6 +1311,7 @@ export function buildApiModelForRun(ctx: GenContext): ApiModel { // The verbs the routes generators actually mount (`expose`), so a page never lists a // route the project does not serve. ...(ctx.config.routesExpose !== undefined && { expose: ctx.config.routesExpose }), + ...(ctx.entityModuleCovers !== undefined && { entityModuleCovers: ctx.entityModuleCovers }), apiPrefix: ctx.renderContext?.apiPrefix ?? "", ...(ctx.renderContext?.pkMap !== undefined && { pkMap: ctx.renderContext.pkMap }), }); diff --git a/server/typescript/packages/codegen-ts/src/generators/service-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-file.ts index 65c13430b0..4a2b807e85 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-file.ts @@ -1,6 +1,6 @@ -import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { MetaObject } from "@metaobjectsdev/metadata"; import type { EmittedFile, GenContext, Generator } from "../generator.js"; -import { serviceModelOf, serviceRenderContext } from "../service-walk.js"; +import { serviceMatcher, serviceModelOf, serviceRenderContext } from "../service-walk.js"; import { renderServiceFiles } from "../templates/service-file.js"; /** @@ -45,7 +45,7 @@ export function serviceFile(opts?: ServiceFileOpts): Generator { const generator: Generator = { name: "service", generate: (ctx: GenContext): EmittedFile[] => { - const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const matches = serviceMatcher(ctx, "service"); const model = serviceModelOf(ctx.loadedRoot, { matches }); if (model.length === 0) return []; const rc = serviceRenderContext(ctx, "service", opts?.runtimeImport); diff --git a/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts index 780bc6f402..ec0e976008 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts @@ -1,6 +1,6 @@ -import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { MetaObject } from "@metaobjectsdev/metadata"; import type { EmittedFile, GenContext, Generator } from "../generator.js"; -import { serviceModelOf, serviceRenderContext } from "../service-walk.js"; +import { serviceMatcher, serviceModelOf, serviceRenderContext } from "../service-walk.js"; import { renderFastifyTransport } from "../templates/service-file.js"; /** @@ -23,7 +23,7 @@ export function serviceRoutesFile(opts?: ServiceRoutesFileOpts): Generator { const generator: Generator = { name: "service-routes", generate: (ctx: GenContext): EmittedFile[] => { - const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const matches = serviceMatcher(ctx, "service-routes"); const model = serviceModelOf(ctx.loadedRoot, { matches }); if (model.length === 0) return []; const rc = serviceRenderContext(ctx, "service-routes", opts?.runtimeImport); diff --git a/server/typescript/packages/codegen-ts/src/generators/service-routes-hono-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-routes-hono-file.ts index 5e656b3945..d0f42fae67 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-routes-hono-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-routes-hono-file.ts @@ -1,6 +1,6 @@ -import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { MetaObject } from "@metaobjectsdev/metadata"; import type { EmittedFile, GenContext, Generator } from "../generator.js"; -import { serviceModelOf, serviceRenderContext } from "../service-walk.js"; +import { serviceMatcher, serviceModelOf, serviceRenderContext } from "../service-walk.js"; import { renderHonoTransport } from "../templates/service-file.js"; /** @@ -24,7 +24,7 @@ export function serviceRoutesHonoFile(opts?: ServiceRoutesHonoFileOpts): Generat const generator: Generator = { name: "service-routes-hono", generate: (ctx: GenContext): EmittedFile[] => { - const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const matches = serviceMatcher(ctx, "service-routes-hono"); const model = serviceModelOf(ctx.loadedRoot, { matches }); if (model.length === 0) return []; const rc = serviceRenderContext(ctx, "service-routes-hono", opts?.runtimeImport); diff --git a/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts b/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts index 3f2c202708..8b0576fa02 100644 --- a/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts +++ b/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts @@ -147,7 +147,7 @@ export function placeEntry( /** What one read of the manifest found. */ export interface ManifestState { - /** Every entry: the union of the legacy file and every package file. */ + /** Every entry: the union of the package files, or the legacy file's alone while it is present. */ entries: Record; /** The manifest file each entry was read from (the legacy file is not a placement). */ fileOf: Map; @@ -188,7 +188,18 @@ 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. */ +/** + * Read the whole manifest. Absent, unreadable or corrupt files read as empty. + * + * A legacy `.hashes.json` that is still present is AUTHORITATIVE: its entries are the manifest + * and the files under `.hashes/` are not read for entries. A write run deletes the legacy file + * right after writing the package files, so a project that still has it has not migrated, and a + * `.hashes/` beside it is left over from another checkout or another engine's run: the old + * `.gitignore` (`.gen-state/*`, `!.gen-state/.hashes.json`) ignores that directory, so it + * survives a reset, a clean and a branch switch. Read on top, its stale hashes made every file + * the committed manifest vouches for look hand-edited, and `gen` kept the old output. The stale + * files' texts are still read, so the migrating write replaces or removes each of them. + */ 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)); @@ -200,6 +211,7 @@ export function readManifestState(genStateDir: string): ManifestState { const read = readEntries(join(genStateDir, HASHES_DIR, name)); if (read === undefined) continue; state.texts.set(name, read.text); + if (state.legacy) continue; for (const [path, entry] of Object.entries(read.entries)) { state.entries[path] = entry; state.fileOf.set(path, name); diff --git a/server/typescript/packages/codegen-ts/src/reference/requirement-tests.ts b/server/typescript/packages/codegen-ts/src/reference/requirement-tests.ts index add012d425..45a9279e59 100644 --- a/server/typescript/packages/codegen-ts/src/reference/requirement-tests.ts +++ b/server/typescript/packages/codegen-ts/src/reference/requirement-tests.ts @@ -119,12 +119,12 @@ function docBlock(w: TsWriter, value: string, first = " * "): void { value .replace(/\*\//g, "* /") .split(/\r\n?|\n/) - .forEach((line, n) => w.line(n === 0 ? first : " * ", line)); + .forEach((line, n) => w.commentLine(n === 0 ? first : " * ", line)); } function writeClaims(w: TsWriter, targets: readonly ResolvedClaim[]): void { if (targets.length === 0) { - w.line(" * (none — this requirement names no model nodes)"); + w.commentLine(" * (none — this requirement names no model nodes)"); return; } for (const t of targets) docBlock(w, `${t.ref} (${t.concern})`, " * - "); @@ -135,7 +135,7 @@ function writeGap(w: TsWriter, a: RequirementTestArgs): void { if (a.disposition === undefined && tracked.length === 0) return; const decided = a.disposition ?? "undecided"; const refs = tracked.length > 0 ? ` — ${tracked.join(", ")}` : ""; - w.line(" *"); + w.commentLine(" *"); docBlock(w, `Known gap: ${decided}${refs}`); } @@ -166,13 +166,13 @@ export function renderRequirementTest(a: RequirementTestArgs): string { w.blank(); w.line("/**"); docBlock(w, a.statement); - w.line(" *"); + w.commentLine(" *"); docBlock(w, `Counterexample: ${a.counterexample}`); writeGap(w, a); - w.line(" *"); - w.line(" * Claims:"); + w.commentLine(" *"); + w.commentLine(" * Claims:"); writeClaims(w, a.targets); - w.line(" */"); + w.commentLine(" */"); w.block(`${runner}("${testName}", () => {`, () => { // A `live` or `partial` stub asserts FAILURE until someone writes the real // assertion over it. `expect.unreachable` names the requirement in the failure diff --git a/server/typescript/packages/codegen-ts/src/reference/service-routes-hono.ts b/server/typescript/packages/codegen-ts/src/reference/service-routes-hono.ts index 8bc6014feb..1eb1063bc2 100644 --- a/server/typescript/packages/codegen-ts/src/reference/service-routes-hono.ts +++ b/server/typescript/packages/codegen-ts/src/reference/service-routes-hono.ts @@ -21,6 +21,7 @@ // composes-with: service.ts and contract-types.ts, in the same target. import { ownedRuntimeImport, + serviceMatcher, serviceModelOf, serviceRenderContext, type EmittedFile, @@ -28,7 +29,7 @@ import { type Generator, } from "@metaobjectsdev/codegen-ts/engine"; import { renderHonoTransport } from "../templates/service-file.js"; -import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { MetaObject } from "@metaobjectsdev/metadata"; export interface ServiceRoutesHonoFileOpts { /** Narrow which entities get routes. Keep it the same as the service generator's. */ @@ -47,7 +48,7 @@ export function serviceRoutesHonoFile(opts?: ServiceRoutesHonoFileOpts): Generat const generator: Generator = { name: "service-routes-hono", generate: (ctx: GenContext): EmittedFile[] => { - const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const matches = serviceMatcher(ctx, "service-routes-hono"); const model = serviceModelOf(ctx.loadedRoot, { matches }); if (model.length === 0) return []; const runtimeImport = diff --git a/server/typescript/packages/codegen-ts/src/reference/service-routes.ts b/server/typescript/packages/codegen-ts/src/reference/service-routes.ts index a140e067cc..462c8a7283 100644 --- a/server/typescript/packages/codegen-ts/src/reference/service-routes.ts +++ b/server/typescript/packages/codegen-ts/src/reference/service-routes.ts @@ -21,6 +21,7 @@ // composes-with: service.ts and contract-types.ts, in the same target. import { ownedRuntimeImport, + serviceMatcher, serviceModelOf, serviceRenderContext, type EmittedFile, @@ -28,7 +29,7 @@ import { type Generator, } from "@metaobjectsdev/codegen-ts/engine"; import { renderFastifyTransport } from "../templates/service-file.js"; -import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { MetaObject } from "@metaobjectsdev/metadata"; export interface ServiceRoutesFileOpts { /** Narrow which entities get routes. Keep it the same as the service generator's. */ @@ -47,7 +48,7 @@ export function serviceRoutesFile(opts?: ServiceRoutesFileOpts): Generator { const generator: Generator = { name: "service-routes", generate: (ctx: GenContext): EmittedFile[] => { - const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const matches = serviceMatcher(ctx, "service-routes"); const model = serviceModelOf(ctx.loadedRoot, { matches }); if (model.length === 0) return []; const runtimeImport = diff --git a/server/typescript/packages/codegen-ts/src/reference/service.ts b/server/typescript/packages/codegen-ts/src/reference/service.ts index e896df46a5..088fee2031 100644 --- a/server/typescript/packages/codegen-ts/src/reference/service.ts +++ b/server/typescript/packages/codegen-ts/src/reference/service.ts @@ -28,6 +28,7 @@ // A SEPARATE generator: a project that does not list it sees no change (fixtures/codegen-noop/rules). import { ownedRuntimeImport, + serviceMatcher, serviceModelOf, serviceRenderContext, type EmittedFile, @@ -35,7 +36,7 @@ import { type Generator, } from "@metaobjectsdev/codegen-ts/engine"; import { renderServiceFiles } from "../templates/service-file.js"; -import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { MetaObject } from "@metaobjectsdev/metadata"; export interface ServiceFileOpts { /** Narrow which entities get operations. ANDed with the generator's own gates, so it can only narrow. */ @@ -63,7 +64,7 @@ export function serviceFile(opts?: ServiceFileOpts): Generator { const generator: Generator = { name: "service", generate: (ctx: GenContext): EmittedFile[] => { - const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const matches = serviceMatcher(ctx, "service"); const model = serviceModelOf(ctx.loadedRoot, { matches }); if (model.length === 0) return []; const runtimeImport = diff --git a/server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts b/server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts index 31540d1757..fcf15f53cd 100644 --- a/server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts +++ b/server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts @@ -7,7 +7,7 @@ // (path under templates/ minus the .mustache suffix). export const EMBEDDED_FRAMEWORK_TEMPLATES: Record = { "agent/requirements.md": "{{{generatedMarker}}}\n\n# Requirements\n\nRead this before adding a capability, and before extending anything that looks like it already does what you were asked for.\n\n- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild.\n- The **node index** below answers *\"does anything claim the thing I am about to change?\"*. Match the literal FQN.\n- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet.\n\n## Node index\n\n{{#hasNodeIndex}}\n| Node | Kind | Claimed by |\n|---|---|---|\n{{#nodeIndex}}\n| `{{{address}}}` | `{{{concern}}}` | {{{claims}}} |\n{{/nodeIndex}}\n{{#hasStatements}}\n\n### What those requirements say\n\n{{#statements}}\n- `{{{path}}}` (`{{{subType}}}`) — {{{statement}}}\n{{/statements}}\n{{/hasStatements}}\n{{/hasNodeIndex}}\n{{^hasNodeIndex}}\nNo requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which.\n{{/hasNodeIndex}}\n\n## The ledger\n\n{{{ledger}}}\n", - "agent/schema.md": "{{{generatedMarker}}}\n\n# Schema\n\n{{#physical}}\nThe physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column.\n{{/physical}}\n{{^physical}}\nThe tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them.\n{{/physical}}\n\n- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce.\n{{#hasMigrate}}\n- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate.\n{{/hasMigrate}}\n{{^hasMigrate}}\n- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration.\n{{/hasMigrate}}\n- `Field` and `Declared` are the METADATA names. Edit those; the column name follows.\n\n{{#descriptionNudge}}\n> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text {{#hasMigrate}}`meta migrate`{{/hasMigrate}}{{^hasMigrate}}`meta schema`{{/hasMigrate}} emits as a `COMMENT ON`, so it lands in the database too.\n\n{{/descriptionNudge}}\n{{#hasTables}}\n## Tables\n\n{{#tables}}\n### {{{heading}}}\n\n{{#tableDeclaredBy}}\nDeclared by `{{{.}}}`.\n{{/tableDeclaredBy}}\n{{#tableDescription}}\n\n> {{{.}}}\n{{/tableDescription}}\n\n{{#physical}}\n| Column | Field | Declared | SQL type | Null | Default | Key |\n|---|---|---|---|---|---|---|\n{{/physical}}\n{{^physical}}\n| Column | Field | Declared | Null | Key |\n|---|---|---|---|---|\n{{/physical}}\n{{#columns}}\n| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} |\n{{/columns}}\n{{#hasDescribed}}\n\n{{#described}}\n- `{{{name}}}` — {{{text}}}\n{{/described}}\n{{/hasDescribed}}\n{{#hasIndexes}}\n\n**Indexes**\n\n{{#indexes}}\n- {{{.}}}\n{{/indexes}}\n{{/hasIndexes}}\n{{#hasForeignKeys}}\n\n**Foreign keys**\n\n{{#foreignKeys}}\n- {{{.}}}\n{{/foreignKeys}}\n{{/hasForeignKeys}}\n{{#hasChecks}}\n\n**Checks**\n\n{{#checks}}\n- {{{.}}}\n{{/checks}}\n{{/hasChecks}}\n\n{{/tables}}\n{{/hasTables}}\n{{#hasViews}}\n## Views\n\nA view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see.\n\n{{#views}}\n### {{{heading}}}\n\n{{#viewDeclaredBy}}\nDeclared by `{{{.}}}`.\n{{/viewDeclaredBy}}\n{{#hasLineage}}\n\n| Column | Lineage |\n|---|---|\n{{#lineage}}\n| `{{{column}}}` | {{{text}}} |\n{{/lineage}}\n{{/hasLineage}}\n\n{{/views}}\n{{/hasViews}}\n{{#hasRelationships}}\n## Relationships\n\n{{#relationships}}\n- {{{.}}}\n{{/relationships}}\n\n{{/hasRelationships}}\n{{#hasEnums}}\n## Enums\n\nMembers are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}}\n\n| Field | Members | Storage |\n|---|---|---|\n{{#enums}}\n| `{{{field}}}` | {{{members}}} | {{{storage}}} |\n{{/enums}}\n{{/hasEnums}}\n", + "agent/schema.md": "{{{generatedMarker}}}\n\n# Schema\n\n{{#physical}}\nThe physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column.\n{{/physical}}\n{{^physical}}\nThe tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them.\n{{/physical}}\n\n- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce.\n{{#hasMigrate}}\n- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate.\n{{/hasMigrate}}\n{{^hasMigrate}}\n- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration.\n{{/hasMigrate}}\n- `Field` and `Declared` are the METADATA names. Edit those; the column name follows.\n\n{{#descriptionNudge}}\n> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text {{#hasMigrate}}`meta migrate`{{/hasMigrate}}{{^hasMigrate}}`meta schema`{{/hasMigrate}} emits as a `COMMENT ON`, so it lands in the database too.\n\n{{/descriptionNudge}}\n{{#hasTables}}\n## Tables\n\n{{#tables}}\n### {{{heading}}}\n\n{{#tableDeclaredBy}}\nDeclared by `{{{.}}}`.\n{{/tableDeclaredBy}}\n{{#tableDescription}}\n\n> {{{.}}}\n{{/tableDescription}}\n\n{{#physical}}\n| Column | Field | Declared | SQL type | Null | Default | Key |\n|---|---|---|---|---|---|---|\n{{/physical}}\n{{^physical}}\n| Column | Field | Declared | Null | Key |\n|---|---|---|---|---|\n{{/physical}}\n{{#columns}}\n| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} |\n{{/columns}}\n{{#hasDescribed}}\n\n{{#described}}\n- `{{{name}}}` — {{{text}}}\n{{/described}}\n{{/hasDescribed}}\n{{#hasIndexes}}\n\n**Indexes**\n\n{{#indexes}}\n- {{{.}}}\n{{/indexes}}\n{{/hasIndexes}}\n{{#hasForeignKeys}}\n\n**Foreign keys**\n\n{{#foreignKeys}}\n- {{{.}}}\n{{/foreignKeys}}\n{{/hasForeignKeys}}\n{{#hasChecks}}\n\n**Checks**\n\n{{#checks}}\n- {{{.}}}\n{{/checks}}\n{{/hasChecks}}\n\n{{/tables}}\n{{/hasTables}}\n{{#hasViews}}\n## Views\n\nA view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see.\n\n{{#views}}\n### {{{heading}}}\n\n{{#viewDeclaredBy}}\nDeclared by `{{{.}}}`.\n{{/viewDeclaredBy}}\n{{#hasLineage}}\n\n| Column | Lineage |\n|---|---|\n{{#lineage}}\n| `{{{column}}}` | {{{text}}} |\n{{/lineage}}\n{{/hasLineage}}\n\n{{/views}}\n{{/hasViews}}\n{{#hasRelationships}}\n## Relationships\n\n{{#relationships}}\n- {{{.}}}\n{{/relationships}}\n\n{{/hasRelationships}}\n{{#hasEnums}}\n## Enums\n\nMembers are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}}\n\n| Field | Members | Storage |\n|---|---|---|\n{{#enums}}\n| `{{{field}}}` | {{{members}}} | {{{storage}}} |\n{{/enums}}\n{{/hasEnums}}\n", "api/agent-api.md": "{{{generatedMarker}}}\n\n# {{title}}\n\nGenerated API reference for {{project}}; call these exactly as written. {{importNote}}\n{{#hasSetup}}\n\n## Setup\n{{#setup}}\n- `{{handle}}` — {{{note}}} `{{{snippetInline}}}`\n{{/setup}}\n{{/hasSetup}}\n{{#units}}\n\n## {{node}}\n{{#groups}}\n\n`{{importHeader}}`\n{{#symbols}}\n- `{{signature}}` — {{usage}}{{#throwsMarker}} {{throwsMarker}}{{/throwsMarker}}\n{{/symbols}}\n{{/groups}}\n{{#example}}\n\nExample:\n```ts\n{{{example}}}\n```\n{{/example}}\n{{/units}}\n", "api/entity-api.md": "{{{generatedMarker}}}\n\n# {{node}} API\n{{#modelPageHref}}\n\n**Model / metadata:** [{{node}}]({{modelPageHref}})\n{{/modelPageHref}}\n\n> Import paths are relative to your generated-output directory.\n{{#hasSetup}}\n\n## Setup\n\nObtain the runtime handles the calls below need:\n{{#setup}}\n\n- `{{handle}}` — {{{note}}}\n\n```ts\n{{{snippet}}}\n```\n{{/setup}}\n{{/hasSetup}}\n{{#unitExample}}\n\n## Example\n\n```ts\n{{{unitExample}}}\n```\n{{/unitExample}}\n{{#sections}}\n\n## {{heading}}\n{{#symbols}}\n\n### `{{signature}}`\n\n{{usage}}\n\n```ts\n{{importLine}}\n```\n{{#hasFields}}\n\n{{fieldsCaption}}:\n\n| Field | Type | Required | Notes |\n|---|---|---|---|\n{{#fieldRows}}\n| `{{field}}` | `{{{type}}}` | {{required}} | {{notes}} |\n{{/fieldRows}}\n{{/hasFields}}\n{{#mountNote}}\n\nMount: {{{mountNote}}}\n{{/mountNote}}\n{{#throws}}\n\nThrows: {{throws}}\n{{/throws}}\n{{#example}}\n\n```ts\n{{{example}}}\n```\n{{/example}}\n{{/symbols}}\n{{/sections}}\n", "api/index.md": "{{{generatedMarker}}}\n\n# {{title}}\n\n{{intro}}\n{{#hasEntities}}\n\n## Entities\n\n{{#entities}}\n- [{{node}}]({{href}}) — {{summary}} ({{symbolCount}} symbol{{^one}}s{{/one}})\n{{/entities}}\n{{/hasEntities}}\n{{#hasTemplates}}\n\n## Templates\n\n{{#templates}}\n- [{{node}}]({{href}}) — {{summary}} ({{symbolCount}} symbol{{^one}}s{{/one}})\n{{/templates}}\n{{/hasTemplates}}\n", diff --git a/server/typescript/packages/codegen-ts/src/routes-expose.ts b/server/typescript/packages/codegen-ts/src/routes-expose.ts index 86fde8e4d8..b12b53269e 100644 --- a/server/typescript/packages/codegen-ts/src/routes-expose.ts +++ b/server/typescript/packages/codegen-ts/src/routes-expose.ts @@ -1,6 +1,6 @@ import type { MetaObject } from "@metaobjectsdev/metadata"; import { CodeWriter } from "./writer/code-writer.js"; -import { docSample, legacyMemberLines } from "./writer/ts-writer.js"; +import { docSample, legacyMemberLines, TsWriter } from "./writer/ts-writer.js"; /** * The five CRUD verbs a generated routes file can mount. @@ -182,7 +182,7 @@ export function exposeLine(verbs: readonly CrudVerb[] | undefined, indent: strin * lines to `TsWriter.doc`. */ export function authSeamJsDoc(opts: Parameters[0]): string { - const w = new CodeWriter(); - for (const l of authSeamDoc(opts)) w.line(l === "" ? " *" : ` * ${l}`); + const w = new TsWriter(); + for (const l of authSeamDoc(opts)) w.commentLine(l === "" ? " *" : ` * ${l}`); return w.toString().trimEnd(); } diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index a7a8c929ad..d1a723a002 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -64,6 +64,24 @@ function isNestedIn(path: string, dir: string): boolean { return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); } + +/** What JavaScript writes for an object turned into text without a `toString` of its own. */ +const STRINGIFIED_OBJECT = "[object Object]"; +/** {@link STRINGIFIED_OBJECT} anywhere but as the exact quoted string literal. */ +const STRINGIFIED_OBJECT_RE = /(? modelMentions(child, text)); +} + export interface RunGenOpts { config: MetaobjectsGenConfig; metadata: MetaData; @@ -152,6 +170,16 @@ export interface RunGenOpts { * option explicitly) can omit this with no behavior change elsewhere. */ sourceFiles?: readonly string[]; + /** + * Checks every file this run emitted before any of it is written or compared, and returns + * one problem per file that fails (empty when all pass). A non-empty result fails the run + * and writes nothing. The CLI passes a parse check of emitted TypeScript + * (`emittedTypeScriptProblems`), because neither the three-way merge, the zero-write regen + * nor `verify --codegen` reads the output as code: a generator that emits text that does + * not parse passed all three. codegen-ts carries no parser at runtime, so the caller that + * has one supplies it. + */ + checkEmitted?: (files: readonly { fullPath: string; content: string; generatedBy: string }[]) => string[]; /** * The collection's metadata source directories, with each dependency artifact's directory, * threaded onto `GenContext.sourceRoots` for a generator that runs a loader of its own over @@ -668,10 +696,15 @@ export async function runGen(opts: RunGenOpts): Promise { for (const g of config.generators) targetOf(g); // An owned copy from 1.2 or earlier declares what it provides through markers 1.3.0 removed. // Run as it is, the fact would be silently lost (the api reference, `agent/ui.md` and the - // cross-target imports read `provides` alone), so it is refused by name instead. + // cross-target imports read `provides` alone), so it is refused by name instead. Every such + // generator is named in the one refusal: an estate with several owned copies would otherwise + // find them one failed run at a time. + const markerRefusals = config.generators + .map((g) => ({ name: g.name, markers: removedGeneratorMarkers(g) })) + .filter((r) => r.markers.length > 0) + .map((r) => removedMarkersMessage(r.name, r.markers)); + if (markerRefusals.length > 0) throw new Error(markerRefusals.join(" ")); for (const g of config.generators) { - const markers = removedGeneratorMarkers(g); - if (markers.length > 0) throw new Error(removedMarkersMessage(g.name, markers)); // Older still: a copy with a shipped generator's name and no declaration at all. It runs, // so this warns rather than refuses, but the fact it should state is otherwise lost silently. const missing = undeclaredProvides(g); @@ -685,7 +718,35 @@ export async function runGen(opts: RunGenOpts): Promise { } } - const entityGen = config.generators.find((g) => providesOf(g).entityModule === true); + const entityGens = config.generators.filter((g) => providesOf(g).entityModule === true); + const entityGen = entityGens[0]; + // The entity modules this run writes, as the union of the entity-module generators' filters. + const entityModuleCovers = (e: MetaObject): boolean => entityGens.some((g) => g.filter?.(e) ?? true); + // A generator whose output imports the entity module (the queries and the CRUD routes) covers + // only the objects whose module this run writes. One that another generator's filter kept out + // (a projection, typically, when `entityFile()` is narrowed to entities) would import a file + // nothing writes (`TS2307`), so it is skipped with a warning naming the object and both remedies. + // Read here, not in each generator, so an owned copy that declares `provides` gets it too. + const skippedForModule = new Set(); + const matchesFor = (generator: Generator): ((e: MetaObject) => boolean) => { + const own = (e: MetaObject): boolean => generator.filter?.(e) ?? true; + const p = providesOf(generator); + if (entityGens.length === 0 || p.entityModule || (!p.queries && p.routes === undefined)) return own; + return (e) => { + if (!own(e)) return false; + if (entityModuleCovers(e)) return true; + const key = `${generator.name} ${e.resolutionKey()}`; + if (!skippedForModule.has(key)) { + skippedForModule.add(key); + warnings.push( + `[${generator.name}] skipped "${e.resolutionKey()}": no generator in this run emits its entity module, which ` + + `this generator's output imports. Widen the entity-module generator's filter to include it, or ` + + `narrow this generator's filter to exclude it.`, + ); + } + return false; + }; + }; const entityModuleTarget = entityGen ? targetOf(entityGen) : targets[DEFAULT_TARGET_NAME]!; // Refuse before any generator runs: a name two objects claim in the scope it lives in @@ -748,7 +809,7 @@ export async function runGen(opts: RunGenOpts): Promise { // The `expose` option each routes surface was built with, so the api reference lists only // the verbs the routes files mount. Run-scoped, read off the whole declared list. - const routesExpose = runRoutesExpose(config.generators); + const routesExpose = runRoutesExpose(config.generators, entityGens.length > 0 ? entityModuleCovers : undefined); // Per-target scoping for the report-export generator: the routes import `./.export` // relative to themselves, so the module must land in the route file's own target. @@ -981,7 +1042,9 @@ export async function runGen(opts: RunGenOpts): Promise { entities: safeEntities, ...(entityNarrowed && { selected: isSelected }), loadedRoot: root, - matches: (e) => generator.filter?.(e) ?? true, + matches: matchesFor(generator), + // The run-level fact a service-layer generator reads: the entity modules this run writes. + ...(entityGens.length > 0 && { entityModuleCovers }), // FR-023 §11.1 item 2 — the SAME `scope` predicate that already narrowed // `entities` above, re-exposed for a template that renders once over the // WHOLE loaded root (the shared-enums module, so far the only one) rather @@ -1141,6 +1204,38 @@ export async function runGen(opts: RunGenOpts): Promise { } } + // 4c. Text a generator built by stringifying an object (a template literal or `+` over a + // fragment, a writer piece or a model node) reads `[object Object]` where the code should be. + // It compiles often enough to slip through, so it is refused by name here, before the write, + // in gen and in verify alike. Written as the exact string literal `"[object Object]"` it is + // code on purpose (an emitted query-string encoder mirroring JavaScript's), so that is allowed, + // and so is the marker when a string value in the model carries it (prose copied into output). + const stringified = emitted.filter((f) => STRINGIFIED_OBJECT_RE.test(f.content)); + if (stringified.length > 0 && !modelMentions(root, STRINGIFIED_OBJECT)) { + const named = stringified.map((f) => `${projectRoot === undefined ? f.fullPath : relative(projectRoot, f.fullPath)} (generator "${f.generatedBy}")`); + throw new Error( + `ERR_GEN_STRINGIFIED_OBJECT: generated output contains "${STRINGIFIED_OBJECT}", which no string in the model ` + + `carries, so none of this run's ` + + `files were written: ${named.join("; ")}. A generator turned an object into text, most often a ` + + `fragment (Frag) put in a template literal, joined or added to a string. Splice it into frag(...) ` + + `or write it with a TsWriter (w.line(..., f), w.fragment(f)) instead.`, + ); + } + + // 4d. The caller's check of the emitted text (`checkEmitted`): before the write, so a file + // that does not parse is never written, merged or recorded, and `verify --codegen` (a dry + // run through here) fails on it instead of reporting the tree in sync. + if (opts.checkEmitted !== undefined) { + const problems = opts.checkEmitted(emitted); + if (problems.length > 0) { + throw new Error( + `generated code does not parse, so none of this run's files were written: ${problems.join("; ")}. ` + + `An owned generator copied in 1.2 or earlier may be composing engine fragments with ts-poet ` + + `(joinCode), which repeats each fragment's imports; see CHANGELOG "Upgrading from 1.2.0".`, + ); + } + } + // 5. Write phase. const writes: WriteResult[] = []; const conflicts: WriteResult[] = []; diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 20fc35c4d2..4d9e09b455 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -496,6 +496,28 @@ export function runtimeSpecifierFrom( return ctx.extStyle === "js" ? `${base}/${entry.file}.js` : `${base}/${entry.file}`; } +/** + * Which objects a service-layer generator covers: its own `filter` and the run's selection, and + * only those whose entity module (the Drizzle table or view the service imports) this run emits. + * An object another generator's filter kept out of the entity modules would import a file nothing + * writes (`TS2307`), so it is skipped with a run warning naming the object and both remedies. + */ +export function serviceMatcher(ctx: GenContext, generator: string): (obj: MetaData) => boolean { + const warned = new Set(); + return (obj: MetaData): boolean => { + if (!isMetaObject(obj) || !ctx.matches(obj) || !(ctx.selected?.(obj) ?? true)) return false; + if (ctx.entityModuleCovers === undefined || ctx.entityModuleCovers(obj)) return true; + if (hasServiceOperations(obj) && !warned.has(obj.resolutionKey())) { + warned.add(obj.resolutionKey()); + ctx.warn?.( + `${generator}: skipped "${obj.resolutionKey()}": no generator in this run emits its entity module, which the service imports. ` + + `Widen the entity-module generator's filter to include it, or narrow this generator's filter to exclude it.`, + ); + } + return false; + }; +} + /** * The render context a service-layer generator runs with. Refused when the run supplies none, or * when the generator writes to another target than the entity module: the service and transport diff --git a/server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts b/server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts index 2634cd1070..0e8526acf9 100644 --- a/server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts +++ b/server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts @@ -146,13 +146,13 @@ export function durationColumnDataType(dialect: Dialect): string { * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or * month part is not a fixed-length span: reading one throws. */ -export function writeDurationColumnDecl(w: CodeWriter, dialect: Dialect, customTypeName: string): void { +export function writeDurationColumnDecl(w: TsWriter, dialect: Dialect, customTypeName: string): void { const postgres = dialect === "postgres"; - w.line("/** A field.duration column. Binds " + (postgres + w.commentLine("/** A field.duration column. Binds " + (postgres ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" : "the span as a 64-bit integer count of microseconds (refused past that range);")); - w.line(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); - w.line(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); + w.commentLine(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); + w.commentLine(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); w.block(`const ${DURATION_COLUMN_FN} = (() => {`, () => { writeUnits(w); w.line(`const INT64_MAX = BigInt("9223372036854775807");`); diff --git a/server/typescript/packages/codegen-ts/src/templates/jsdoc.ts b/server/typescript/packages/codegen-ts/src/templates/jsdoc.ts index 250efe6a38..4be82d6490 100644 --- a/server/typescript/packages/codegen-ts/src/templates/jsdoc.ts +++ b/server/typescript/packages/codegen-ts/src/templates/jsdoc.ts @@ -6,7 +6,7 @@ import { DOC_ATTR_SEE_ALSO, DOC_ATTR_TITLE, } from "@metaobjectsdev/metadata"; -import { CodeWriter } from "../writer/code-writer.js"; +import { TsWriter } from "../writer/ts-writer.js"; export interface DocAttrs { description?: string; @@ -60,8 +60,8 @@ export function jsDocLines(attrs: DocAttrs): string[] { } /** Write a node's JSDoc block (nothing when it has no doc attrs), one line at a time. */ -export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown }): void { - for (const l of jsDocLines(readDocAttrs(node))) w.line(l); +export function writeDocsFor(w: TsWriter, node: { attr: (n: string) => unknown }): void { + for (const l of jsDocLines(readDocAttrs(node))) w.commentLine(l); } /** @@ -69,8 +69,8 @@ export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown * with no final line break. Returns "" if no relevant attrs are set. */ export function renderJsDocBlock(attrs: DocAttrs): string { - const w = new CodeWriter(); - for (const l of jsDocLines(attrs)) w.line(l); + const w = new TsWriter(); + for (const l of jsDocLines(attrs)) w.commentLine(l); return w.toString().trimEnd(); } diff --git a/server/typescript/packages/codegen-ts/src/templates/requirement-test.ts b/server/typescript/packages/codegen-ts/src/templates/requirement-test.ts index 5bfe1ab199..598bb6b74e 100644 --- a/server/typescript/packages/codegen-ts/src/templates/requirement-test.ts +++ b/server/typescript/packages/codegen-ts/src/templates/requirement-test.ts @@ -82,12 +82,12 @@ function docBlock(w: TsWriter, value: string, first = " * "): void { value .replace(/\*\//g, "* /") .split(/\r\n?|\n/) - .forEach((line, n) => w.line(n === 0 ? first : " * ", line)); + .forEach((line, n) => w.commentLine(n === 0 ? first : " * ", line)); } function writeClaims(w: TsWriter, targets: readonly ResolvedClaim[]): void { if (targets.length === 0) { - w.line(" * (none — this requirement names no model nodes)"); + w.commentLine(" * (none — this requirement names no model nodes)"); return; } for (const t of targets) docBlock(w, `${t.ref} (${t.concern})`, " * - "); @@ -98,7 +98,7 @@ function writeGap(w: TsWriter, a: RequirementTestArgs): void { if (a.disposition === undefined && tracked.length === 0) return; const decided = a.disposition ?? "undecided"; const refs = tracked.length > 0 ? ` — ${tracked.join(", ")}` : ""; - w.line(" *"); + w.commentLine(" *"); docBlock(w, `Known gap: ${decided}${refs}`); } @@ -129,13 +129,13 @@ export function renderRequirementTest(a: RequirementTestArgs): string { w.blank(); w.line("/**"); docBlock(w, a.statement); - w.line(" *"); + w.commentLine(" *"); docBlock(w, `Counterexample: ${a.counterexample}`); writeGap(w, a); - w.line(" *"); - w.line(" * Claims:"); + w.commentLine(" *"); + w.commentLine(" * Claims:"); writeClaims(w, a.targets); - w.line(" */"); + w.commentLine(" */"); w.block(`${runner}("${testName}", () => {`, () => { // A `live` or `partial` stub asserts FAILURE until someone writes the real // assertion over it. `expect.unreachable` names the requirement in the failure diff --git a/server/typescript/packages/codegen-ts/src/ui-tier-gate.ts b/server/typescript/packages/codegen-ts/src/ui-tier-gate.ts index 1e01e7d9bc..7906c1a1b4 100644 --- a/server/typescript/packages/codegen-ts/src/ui-tier-gate.ts +++ b/server/typescript/packages/codegen-ts/src/ui-tier-gate.ts @@ -53,25 +53,36 @@ export function runEmitsRestRoutes(generators: readonly Generator[]): boolean { * Per surface, because the Fastify and Hono routes files are separate generators with their * own option: several generators on one surface union their verbs, and a generator with no * `expose` mounts all five. A generator's own `filter` removes the entities it rejects, so an - * entity no generator on the surface accepts is documented with no routes. Undefined when no - * generator on any surface carries an `expose` or a `filter`. + * entity no generator on the surface accepts is documented with no routes. `entityModuleCovers` + * (the run's entity-module generators) narrows every surface the same way: a routes file imports + * the entity module, so the run skips an object whose module it does not write. Undefined when no + * generator on any surface carries an `expose` or a `filter` and no `entityModuleCovers` is given. */ -export function runRoutesExpose(generators: readonly Generator[]): RoutesExpose | undefined { +export function runRoutesExpose( + generators: readonly Generator[], + entityModuleCovers?: (entity: MetaObject) => boolean, +): RoutesExpose | undefined { const routes = generators.map((g) => providesOf(g).routes).filter((r): r is GeneratorRoutes => r !== undefined); - const rest = surfaceExpose(routes.filter((r) => r.framework === "fastify")); - const restHono = surfaceExpose(routes.filter((r) => r.framework === "hono")); + const rest = surfaceExpose(routes.filter((r) => r.framework === "fastify"), entityModuleCovers); + const restHono = surfaceExpose(routes.filter((r) => r.framework === "hono"), entityModuleCovers); if (rest === undefined && restHono === undefined) return undefined; return { - ...(rest !== undefined && { rest: rest.expose, restMounted: rest.mounted }), - ...(restHono !== undefined && { restHono: restHono.expose, restHonoMounted: restHono.mounted }), + ...(rest?.expose !== undefined && { rest: rest.expose }), + ...(rest !== undefined && { restMounted: rest.mounted }), + ...(restHono?.expose !== undefined && { restHono: restHono.expose }), + ...(restHono !== undefined && { restHonoMounted: restHono.mounted }), }; } function surfaceExpose( mounts: readonly GeneratorRoutes[], -): { expose: ExposeOption; mounted: (entity: MetaObject) => boolean } | undefined { - if (mounts.length === 0 || mounts.some((m) => m.expose === undefined && m.filter === undefined)) return undefined; - const accepts = (m: (typeof mounts)[number], entity: MetaObject): boolean => m.filter === undefined || m.filter(entity); + covers: ((entity: MetaObject) => boolean) | undefined, +): { expose?: ExposeOption; mounted: (entity: MetaObject) => boolean } | undefined { + if (mounts.length === 0) return undefined; + const unnarrowed = mounts.some((m) => m.expose === undefined && m.filter === undefined); + if (unnarrowed) return covers === undefined ? undefined : { mounted: covers }; + const accepts = (m: (typeof mounts)[number], entity: MetaObject): boolean => + (covers?.(entity) ?? true) && (m.filter === undefined || m.filter(entity)); return { mounted: (entity) => mounts.some((m) => accepts(m, entity)), expose: (entity) => { diff --git a/server/typescript/packages/codegen-ts/src/writer/code-writer.ts b/server/typescript/packages/codegen-ts/src/writer/code-writer.ts index 538a45ad94..6010d3d9be 100644 --- a/server/typescript/packages/codegen-ts/src/writer/code-writer.ts +++ b/server/typescript/packages/codegen-ts/src/writer/code-writer.ts @@ -21,6 +21,8 @@ export const WRITER_ERRORS = { importConflict: "ERR_WRITER_IMPORT_CONFLICT", /** A piece the writer does not know how to print. */ unknownPiece: "ERR_WRITER_UNKNOWN_PIECE", + /** `line()`, `open()` or `close()` was handed text that starts with a space or tab. */ + leadingWhitespace: "ERR_WRITER_LEADING_WHITESPACE", } as const; export type WriterErrorCode = (typeof WRITER_ERRORS)[keyof typeof WRITER_ERRORS]; @@ -100,10 +102,11 @@ export class CodeWriter { /** * One line at the current indent. The parts are concatenated; when the line does not fit * the width, the LAST non-empty list in it is printed one item per line. A line whose - * text is empty is a blank-line request. + * text is empty is a blank-line request. Text that starts with whitespace is + * `ERR_WRITER_LEADING_WHITESPACE`: indentation comes only from open blocks. */ line(...parts: readonly unknown[]): this { - return this.put(this.piece(parts)); + return this.put(this.unindented(this.piece(parts), "line")); } /** Ask for one blank line before whatever is written next. Requests never stack. */ @@ -114,12 +117,12 @@ export class CodeWriter { /** Write the line that opens a block, then indent. */ open(...parts: readonly unknown[]): this { - return this.openPiece(this.piece(parts)); + return this.openPiece(this.unindented(this.piece(parts), "open")); } /** Dedent, then write the line that closes the block. */ close(...parts: readonly unknown[]): this { - return this.closePiece(this.piece(parts)); + return this.closePiece(this.unindented(this.piece(parts), "close")); } /** `open(head)`, the body, then `close(tail)`: the indent cannot be left unbalanced. */ @@ -217,6 +220,21 @@ export class CodeWriter { return lastGroup(piece); } + /** + * Refuse text a caller indented itself: the writer adds the indent, so a pre-indented piece + * would land one level too deep beside its siblings, silently. + */ + protected unindented(piece: Piece, what: string): Piece { + const raw = flat(piece); + if (raw.startsWith(" ") || raw.startsWith("\t")) { + throw new WriterError( + WRITER_ERRORS.leadingWhitespace, + `${what}() text starts with whitespace; pass it without indentation, the writer indents it from the open blocks: ${JSON.stringify(raw)}`, + ); + } + return piece; + } + protected openPiece(piece: Piece): this { this.put(piece); this.openers.push(flat(piece).trim()); diff --git a/server/typescript/packages/codegen-ts/src/writer/ts-fragment.ts b/server/typescript/packages/codegen-ts/src/writer/ts-fragment.ts index 082356d0c6..732c394b4a 100644 --- a/server/typescript/packages/codegen-ts/src/writer/ts-fragment.ts +++ b/server/typescript/packages/codegen-ts/src/writer/ts-fragment.ts @@ -38,6 +38,21 @@ export class Needs { */ export class Frag { constructor(readonly parts: readonly unknown[]) {} + + /** + * A fragment has no text until a writer lays it out, so turning one into a string (a + * template literal, `+`, `join`) is refused here rather than writing `[object Object]` into + * the generated file. ts-poet's `Code` printed itself, so a generator written against 1.2 + * that interpolates an engine fragment lands here. + */ + toString(): string { + throw new Error( + "ERR_FRAG_AS_TEXT: a code fragment (Frag) was turned into a string, which would write " + + "\"[object Object]\" into the generated file. Splice it into frag(...) or joinFrags(...), " + + "or write it with a TsWriter (w.line(..., f), w.fragment(f)); to read one fragment's text, " + + "use new TsWriter().fragment(f).toString().", + ); + } } /** A fragment of the parts given, in order. */ diff --git a/server/typescript/packages/codegen-ts/src/writer/ts-writer.ts b/server/typescript/packages/codegen-ts/src/writer/ts-writer.ts index 09c48b627c..5edeb9b838 100644 --- a/server/typescript/packages/codegen-ts/src/writer/ts-writer.ts +++ b/server/typescript/packages/codegen-ts/src/writer/ts-writer.ts @@ -157,7 +157,7 @@ export class TsWriter extends CodeWriter { * `}).superRefine((row, ctx) => {` or `} else {`. */ reopen(...parts: readonly unknown[]): this { - const p = this.piece(parts); + const p = this.unindented(this.piece(parts), "reopen"); this.closePiece(p); this.openers.push(flat(p).trim()); this.atBlockStart = true; @@ -170,15 +170,24 @@ export class TsWriter extends CodeWriter { return this; } + /** + * One line inside a block comment, such as ` * text`: it starts with whitespace by design, and + * the writer still indents it from the open blocks. `line()` refuses such text. + */ + commentLine(...parts: readonly unknown[]): this { + return this.put(this.piece(parts)); + } + /** A doc comment: one line when it fits, otherwise a block with one ` * ` line per entry. */ doc(...lines: readonly string[]): this { if (lines.length === 0) return this; const safe = lines.map((l) => l.replaceAll("*/", "*\\/")); const one = `/** ${safe[0]} */`; - if (safe.length === 1 && this.fits(one)) return this.line(one); - this.line("/**"); - for (const l of safe) this.line(l === "" ? " *" : ` * ${l}`); - return this.line(" */"); + // put, not line(): the ` * ` lines of a doc comment start with whitespace by design. + if (safe.length === 1 && this.fits(one)) return this.put(one); + this.put("/**"); + for (const l of safe) this.put(l === "" ? " *" : ` * ${l}`); + return this.put(" */"); } /** A fragment, possibly many lines: its imports are collected, its text re-indented. */ @@ -222,7 +231,11 @@ export class TsWriter extends CodeWriter { /** The `header(...)` lines, as given. */ protected writeHeader(w: CodeWriter): void { - for (const l of this.headLines) w.line(l); + // verbatim, not line(): a header line is written as given, even one that starts with whitespace. + for (const l of this.headLines) { + if (l.trim() === "") w.blank(); + else w.verbatim(l); + } } /** Every collected import, one module at a time in `orderModules` order. */ diff --git a/server/typescript/packages/codegen-ts/templates/agent/schema.md.mustache b/server/typescript/packages/codegen-ts/templates/agent/schema.md.mustache index ad91a93c2f..90dfc9bee4 100644 --- a/server/typescript/packages/codegen-ts/templates/agent/schema.md.mustache +++ b/server/typescript/packages/codegen-ts/templates/agent/schema.md.mustache @@ -14,7 +14,7 @@ The tables, columns and keys this model declares. Read it before writing a query - Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. {{/hasMigrate}} {{^hasMigrate}} -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. {{/hasMigrate}} - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. diff --git a/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts b/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts index fa8e88c400..83e97e8316 100644 --- a/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts +++ b/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts @@ -280,8 +280,9 @@ describe("agent/schema.md", () => { const withMigrate = renderAgentSchemaPage(await load(MODEL), input(), "snake_case"); expect(withMigrate).toContain("Change the schema by changing the **metadata** and running `meta migrate`."); const without = renderAgentSchemaPage(await load(MODEL), input({ migrate: false }), "snake_case"); - expect(without).toContain("writing the migration with the project's migration tool, from the schema `meta schema` prints."); - expect(without).not.toContain("meta migrate"); + expect(without).toContain("otherwise with the project's own migration tool, from the schema `meta schema` prints."); + // A project that runs `meta migrate` without setting `migrate.dialect` is still told it may. + expect(without).toContain("with `meta migrate` when the project uses it"); expect(without).not.toContain("{{"); }); diff --git a/server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts b/server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts index 1b6245585d..58d74a9117 100644 --- a/server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts +++ b/server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts @@ -18,7 +18,7 @@ import { writeDurationColumnDecl, } from "../src/templates/duration-wire-helper.js"; import type { Dialect } from "../src/metaobjects-config.js"; -import { CodeWriter } from "../src/writer/code-writer.js"; +import { TsWriter } from "../src/writer/ts-writer.js"; interface Vectors { wire: { @@ -54,7 +54,7 @@ interface Codec { dataType(): string; toDriver(v: string): string | number | big /** The column codec exactly as a generated module spells it; `customType` hands back its config. */ function columnCodec(dialect: Dialect): Codec { - const w = new CodeWriter(); + const w = new TsWriter(); writeDurationColumnDecl(w, dialect, "customType"); const js = transpiler.transformSync(`${w.toString()}export const codec = ${DURATION_COLUMN_FN};`); const body = js.replace(/export const codec =/, "return"); diff --git a/server/typescript/packages/codegen-ts/test/effective-package-filter.test.ts b/server/typescript/packages/codegen-ts/test/effective-package-filter.test.ts new file mode 100644 index 0000000000..249fb66abd --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/effective-package-filter.test.ts @@ -0,0 +1,29 @@ +// A package declared once on the file root ("metadata.root": { "package": ... }) is the file's DEFAULT, +// not a property of each node: `obj.package` is the package the node itself declares (undefined here, and +// the canonical serializer relies on that to not re-emit an inherited package), while the resolution key +// and `effectivePackage()` carry the effective one. A generator `filter` that selects by package uses +// the effective one. +import { test, expect } from "bun:test"; +import { MetaDataLoader, isMetaObject, effectivePackageOf } from "@metaobjectsdev/metadata"; +import { effectivePackage } from "../src/index.js"; + +const model = JSON.stringify({ + "metadata.root": { package: "acme::tasks", children: [ + { "object.entity": { name: "Task", children: [{ "field.long": { name: "id" } }] } }, + { "object.entity": { package: "acme::other", name: "Tag", children: [{ "field.long": { name: "id" } }] } }, + ] }, +}); + +test("a file-root package is visible through effectivePackage, not through the declared `package`", async () => { + const r = await MetaDataLoader.fromString(model, "json"); + const objs = r.root.children().filter(isMetaObject); + const task = objs.find((o) => o.name === "Task")!; + const tag = objs.find((o) => o.name === "Tag")!; + expect(task.resolutionKey()).toBe("acme::tasks::Task"); + expect(task.package).toBeUndefined(); + expect(effectivePackage(task)).toBe("acme::tasks"); + expect(effectivePackageOf(task)).toBe("acme::tasks"); + expect(tag.package).toBe("acme::other"); + expect(effectivePackage(tag)).toBe("acme::other"); + expect(objs.filter((o) => effectivePackage(o) === "acme::tasks").map((o) => o.name)).toEqual(["Task"]); +}); diff --git a/server/typescript/packages/codegen-ts/test/engine-entity-file-writer.test.ts b/server/typescript/packages/codegen-ts/test/engine-entity-file-writer.test.ts new file mode 100644 index 0000000000..965b5f011a --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/engine-entity-file-writer.test.ts @@ -0,0 +1,10 @@ +// An owned entity generator moving onto the writer subclasses EntityFileWriter, so the engine +// entry exports it by name: before 1.3.0 it was reachable only through the templates/* subpaths. +import { expect, test } from "bun:test"; +import { EntityFileWriter as FromEngine, TsWriter } from "../src/engine.js"; +import { EntityFileWriter } from "../src/templates/entity-file.js"; + +test("the engine entry exports EntityFileWriter, the same class the entity template uses", () => { + expect(FromEngine).toBe(EntityFileWriter); + expect(FromEngine.prototype).toBeInstanceOf(TsWriter); +}); 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 index 438c7ef8f8..88b4f7930c 100644 --- a/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts +++ b/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts @@ -205,3 +205,20 @@ describe("a read does not migrate", () => { expect(existsSync(dirOf())).toBe(false); }); }); + +describe("a committed legacy manifest beats a stale .hashes/", () => { + // The old .gitignore ignores .hashes/, so one written by another checkout's run survives a + // reset and a branch switch beside the committed .hashes.json. Its hashes must not count. + test("entries come from .hashes.json alone, and the migrating write replaces the stale files", () => { + writeFileSync(join(state, ".hashes.json"), JSON.stringify({ "gen/Order.ts": "committed" })); + mkdirSync(dirOf(), { recursive: true }); + writeFileSync(join(dirOf(), "acme.shop.json"), JSON.stringify({ "gen/Order.ts": "stale", "gen/Gone.ts": "stale" })); + const st = readManifestState(state); + expect(st.entries).toEqual({ "gen/Order.ts": "committed" }); + expect(listGeneratedPaths(state)).toEqual(["gen/Order.ts"]); + writeManifestFiles(state, st.entries, st, INDEX); + expect(existsSync(join(state, ".hashes.json"))).toBe(false); + const all = Object.assign({}, ...files().map((f) => read(f) as Record)); + expect(all).toEqual({ "gen/Order.ts": "committed" }); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/routes-expose.test.ts b/server/typescript/packages/codegen-ts/test/routes-expose.test.ts index 53d6c99db5..c1b36478c1 100644 --- a/server/typescript/packages/codegen-ts/test/routes-expose.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-expose.test.ts @@ -17,7 +17,7 @@ import { resolve } from "node:path"; import { MetaDataLoader, InMemoryStringSource, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; import { renderRoutesFile } from "../src/templates/routes-file.js"; import { renderRoutesFileHono } from "../src/templates/routes-file-hono.js"; -import { CRUD_VERBS, resolveExpose, intersectExpose } from "../src/routes-expose.js"; +import { CRUD_VERBS, resolveExpose, intersectExpose, authSeamJsDoc } from "../src/routes-expose.js"; import { makeRenderContext } from "../src/render-context.js"; import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; @@ -160,3 +160,41 @@ describe("#348 — the verb vocabulary cannot drift from the runtime it calls", } }); }); + +describe("authSeamJsDoc — the 1.2 string form an owned routes generator still calls", () => { + test("returns the 1.2 doc lines byte for byte, with no trailing break", () => { + // Oracle: the string `authSeamJsDoc` returned in 1.2.3, copied from that release. An owned + // 1.2 generator wraps the result in `/**` ... ` */` itself, so a re-indented, unprefixed or + // reworded line changes its output. + const fastify = [ + " *", + " * Auth: these endpoints are unauthenticated. Register this inside a scope that", + " * carries your hook and every verb below is guarded — routes outside that scope", + " * are not:", + " *", + " * app.register(async (s) => {", + ' * s.addHook("preHandler", requireAuth);', + " * await registerUserRoutes(s);", + " * });", + " *", + ' * A row-ownership rule ("only the owner may read this row") is not expressible in a', + " * mount. Hand-write those verbs and narrow this file with", + ' * routesFile({ expose: ["list", "get"] }) rather than mounting them open.', + ]; + const hono = [ + " *", + " * Auth: these endpoints are unauthenticated. Guard the mount path with", + " * middleware before calling this:", + " *", + " * app.use(`/api/users/*`, requireAuth); // matches the collection path too", + " * mountUserRoutes(app, { db });", + " *", + ' * A row-ownership rule ("only the owner may read this row") is not expressible in a', + " * mount. Hand-write those reads rather than exposing this one open.", + ]; + expect(authSeamJsDoc({ framework: "fastify", handlerName: "registerUserRoutes", narrowable: true })) + .toBe(fastify.join("\n")); + expect(authSeamJsDoc({ framework: "hono", handlerName: "mountUserRoutes", mountPathExpr: "`/api/users/*`", narrowable: false })) + .toBe(hono.join("\n")); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/runner.test.ts b/server/typescript/packages/codegen-ts/test/runner.test.ts index eea73831ca..5724884871 100644 --- a/server/typescript/packages/codegen-ts/test/runner.test.ts +++ b/server/typescript/packages/codegen-ts/test/runner.test.ts @@ -183,6 +183,25 @@ describe("runGen — removed generator markers", () => { expect(readdirSync(tmp)).toEqual([]); }); + test("every generator carrying a removed marker is named in the one refusal", async () => { + const { root } = await new MetaDataLoader().load([new FileSource(FIXTURE)]); + const a = { name: "entity-file", emitsEntityModule: true, generate: () => [] } as unknown as Generator; + const b = { name: "form-file", emitsUiTier: true, generate: () => [] } as unknown as Generator; + let message = ""; + try { + await runGen({ + config: defineConfig({ outDir: tmp, extStyle: "none", dbImport: "../db", dialect: "sqlite", generators: [a, b] }), + metadata: root, + }); + } catch (err) { + message = (err as Error).message; + } + expect(message).toContain('Generator "entity-file"'); + expect(message).toContain("provides: { entityModule: true }"); + expect(message).toContain('Generator "form-file"'); + expect(message).toContain("provides: { uiTier: true }"); + }); + test("warns about a copy with a shipped generator's name and no provides declaration", async () => { const loader = new MetaDataLoader(); const { root } = await loader.load([new FileSource(FIXTURE)]); diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts index 6ab1b6e5ce..f88e30cf2b 100644 --- a/server/typescript/packages/codegen-ts/test/service-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -6,7 +6,7 @@ import { describe, expect, test } from "bun:test"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { InMemoryStringSource, loadUris, MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; -import { contractTypes, entityFile, queriesFile, serviceFile, serviceRoutesFile, serviceRoutesHonoFile } from "../src/generators/index.js"; +import { apiDocsFile, contractTypes, entityFile, openApiFile, queriesFile, routesFile, routesFileHono, serviceFile, serviceRoutesFile, serviceRoutesHonoFile } from "../src/generators/index.js"; import { defineConfig, runGen, type OutputLayout } from "../src/index.js"; import { serviceHonoRoutesName, serviceModelOf, serviceRoutesName, serviceTypeName } from "../src/service-walk.js"; import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; @@ -120,6 +120,202 @@ describe("service generators — what they write", () => { expect(files["acme/shop/service/index.ts"]).not.toContain("Customer"); }); + test("a projection the entity-module generator's filter excludes is skipped with a warning, never imported", async () => { + const view = { + "object.projection": { + name: "OrderView", + children: [ + { "source.rdb": { "@kind": "view", "@view": "v_order" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + { "identity.primary": { name: "pk", extends: "Order.pk" } }, + { "field.string": { name: "title", children: [{ "origin.passthrough": { "@from": "Order.title" } }] } }, + ], + }, + }; + const root = await load("acme::shop", [entity("Order"), view]); + const entitiesOnly = (e: { subType: string }) => e.subType === "entity"; + const dir = makeScratchDir("service-file-"); + try { + const r = await runGen({ + config: defineConfig({ + outDir: "gen", extStyle: "js", dialect: "postgres", outputLayout: "package", + generators: [entityFile({ filter: entitiesOnly }), contractTypes({ filter: entitiesOnly }), serviceFile(), serviceRoutesFile(), serviceRoutesHonoFile()], + }), + metadata: root, + projectRoot: dir, + dryRun: true, + }); + const out = join(dir, "gen"); + const files = Object.fromEntries([...(r.rendered ?? new Map())].map(([path, content]) => [path.slice(out.length + 1), content])); + expect(Object.keys(files).some((p) => p.endsWith("OrderView.ts"))).toBe(false); + const service = Object.entries(files).filter(([p]) => p.includes("/service/") || p.includes("/transport/")).map(([, c]) => c).join("\n"); + expect(service).toContain("Order"); + expect(service).not.toContain("OrderView"); + for (const gen of ["service", "service-routes", "service-routes-hono"]) { + expect(r.warnings.some((w) => w.includes(`[${gen}]`) && w.includes('"acme::shop::OrderView"') && w.includes("filter"))).toBe(true); + } + } finally { + removeTree(dir); + } + }); + + test("the queries and CRUD routes skip a projection whose entity module is filtered out, never importing it", async () => { + const view = { + "object.projection": { + name: "OrderView", + children: [ + { "source.rdb": { "@kind": "view", "@view": "v_order" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + { "identity.primary": { name: "pk", extends: "Order.pk" } }, + { "field.string": { name: "title", children: [{ "origin.passthrough": { "@from": "Order.title" } }] } }, + ], + }, + }; + const root = await load("acme::shop", [entity("Order"), view]); + const entitiesOnly = (e: { subType: string }) => e.subType === "entity"; + const dir = makeScratchDir("routes-queries-filtered-"); + try { + const r = await runGen({ + config: defineConfig({ + outDir: "gen", extStyle: "js", dialect: "postgres", dbImport: "../db", + generators: [entityFile({ filter: entitiesOnly }), queriesFile(), routesFile(), routesFileHono()], + }), + metadata: root, + projectRoot: dir, + dryRun: true, + }); + const rendered = [...(r.rendered ?? new Map())]; + expect(rendered.some(([p]) => p.includes("OrderView"))).toBe(false); + expect(rendered.map(([, c]) => c).join("\n")).not.toContain("OrderView"); + expect(rendered.some(([p]) => p.endsWith("Order.queries.ts"))).toBe(true); + for (const gen of ["queries-file", "routes-file", "routes-file-hono"]) { + expect(r.warnings.some((w) => w.includes(`[${gen}]`) && w.includes('"acme::shop::OrderView"') && w.includes("filter"))).toBe(true); + } + } finally { + removeTree(dir); + } + }); + + test("the OpenAPI document and the api reference leave out the routes and queries a skipped projection never got", async () => { + const view = { + "object.projection": { + name: "OrderView", + children: [ + { "source.rdb": { "@kind": "view", "@view": "v_order" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + { "identity.primary": { name: "pk", extends: "Order.pk" } }, + { "field.string": { name: "title", children: [{ "origin.passthrough": { "@from": "Order.title" } }] } }, + ], + }, + }; + const root = await load("acme::shop", [entity("Order"), view]); + const entitiesOnly = (e: { subType: string }) => e.subType === "entity"; + const dir = makeScratchDir("docs-skipped-projection-"); + try { + const r = await runGen({ + config: defineConfig({ + outDir: "gen", extStyle: "js", dialect: "postgres", dbImport: "../db", + targets: { docs: { outDir: "docs" } }, + generators: [entityFile({ filter: entitiesOnly }), queriesFile(), routesFile(), openApiFile(), apiDocsFile()], + }), + metadata: root, + projectRoot: dir, + dryRun: true, + }); + const rendered = new Map([...(r.rendered ?? new Map())].map(([p, c]) => [p.slice(dir.length + 1), c])); + const paths = Object.keys((JSON.parse(rendered.get("gen/openapi.json")!) as { paths: Record }).paths); + expect(paths).toContain("/orders"); + expect(paths.filter((p) => p.startsWith("/order_views"))).toEqual([]); + const reference = rendered.get("docs/api/AGENT-API.md")!; + const imported = [...reference.matchAll(/from "\.\/([^"]+\.(?:queries|routes))"/g)].map((m) => `gen/${m[1]}.ts`); + expect(imported).toContain("gen/Order.queries.ts"); + expect(imported.filter((p) => !rendered.has(p))).toEqual([]); + expect(reference).not.toContain("/order_views"); + } finally { + removeTree(dir); + } + }); + + test("the api reference names no entity module for a projection whose entity module was filtered out", async () => { + const view = { + "object.projection": { + name: "OrderView", + children: [ + { "source.rdb": { "@kind": "view", "@view": "v_order" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + { "identity.primary": { name: "pk", extends: "Order.pk" } }, + { "field.string": { name: "title", children: [{ "origin.passthrough": { "@from": "Order.title" } }] } }, + ], + }, + }; + const root = await load("acme::shop", [entity("Order"), view]); + const entitiesOnly = (e: { subType: string }) => e.subType === "entity"; + const dir = makeScratchDir("docs-skipped-entity-module-"); + try { + const r = await runGen({ + config: defineConfig({ + outDir: "gen", extStyle: "js", dialect: "postgres", dbImport: "../db", + targets: { docs: { outDir: "docs" } }, + generators: [entityFile({ filter: entitiesOnly }), queriesFile(), routesFile(), apiDocsFile()], + }), + metadata: root, + projectRoot: dir, + dryRun: true, + }); + const rendered = new Map([...(r.rendered ?? new Map())].map(([p, c]) => [p.slice(dir.length + 1), c])); + expect(rendered.has("gen/Order.ts")).toBe(true); + expect(rendered.has("gen/OrderView.ts")).toBe(false); + const reference = rendered.get("docs/api/AGENT-API.md")!; + // Every module the reference tells a reader to import must be one this run wrote. + const imported = [...reference.matchAll(/from "\.\/([^"]+)"/g)].map((m) => `gen/${m[1]}.ts`); + expect(imported).toContain("gen/Order.ts"); + expect(imported.filter((p) => !rendered.has(p))).toEqual([]); + } finally { + removeTree(dir); + } + }); + + test("two same-named projections in different packages are each warned about by qualified name", async () => { + const view = { + "object.projection": { + name: "OrderView", + children: [ + { "source.rdb": { "@kind": "view", "@view": "v_order" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + { "identity.primary": { name: "pk", extends: "Order.pk" } }, + { "field.string": { name: "title", children: [{ "origin.passthrough": { "@from": "Order.title" } }] } }, + ], + }, + }; + const source = (pkg: string) => + new InMemoryStringSource( + JSON.stringify({ "metadata.root": { package: pkg, children: [entity("Order", [], `${pkg.replace("::", "_")}_orders`), view] } }), + { id: `${pkg}.json` }, + ); + const loaded = await new MetaDataLoader({ strict: true }).load([source("a::shop"), source("b::shop")]); + expect(loaded.errors.map((e) => e.message)).toEqual([]); + const entitiesOnly = (e: { subType: string }) => e.subType === "entity"; + const dir = makeScratchDir("skip-warn-qualified-"); + try { + const r = await runGen({ + config: defineConfig({ + outDir: "gen", extStyle: "js", dialect: "postgres", outputLayout: "package", dbImport: "../db", + generators: [entityFile({ filter: entitiesOnly }), contractTypes({ filter: entitiesOnly }), queriesFile(), serviceFile()], + }), + metadata: loaded.root, + projectRoot: dir, + dryRun: true, + }); + for (const gen of ["queries-file", "service"]) { + for (const key of ["a::shop::OrderView", "b::shop::OrderView"]) { + expect(r.warnings.filter((w) => w.includes(`[${gen}]`) && w.includes(`"${key}"`))).toHaveLength(1); + } + } + } finally { + removeTree(dir); + } + }); + test("a relative runtimeImport (an owned copy) is resolved from the file, one folder below the package", async () => { const root = await load("acme::shop", [entity("Order")]); const files = await gen(root, [entityFile(), contractTypes(), serviceFile({ runtimeImport: "../codegen/runtime" }), serviceRoutesFile({ runtimeImport: "../codegen/runtime" })]); diff --git a/server/typescript/packages/codegen-ts/test/stringified-object.test.ts b/server/typescript/packages/codegen-ts/test/stringified-object.test.ts new file mode 100644 index 0000000000..6975d51761 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/stringified-object.test.ts @@ -0,0 +1,101 @@ +// A generator that turns an object into text writes "[object Object]" where code belongs. An +// estate's TypeScript generation wrote it into 236 files; nothing refused them. Two guards: +// a code fragment refuses to become a string, and the runner refuses any output carrying the +// marker, in gen and in verify (a dry run) alike. +import { describe, expect, test } from "bun:test"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { MetaDataLoader } from "@metaobjectsdev/metadata"; +import { FileSource } from "@metaobjectsdev/metadata/core"; +import { oncePerRun, type Generator } from "../src/generator.js"; +import { defineConfig } from "../src/metaobjects-config.js"; +import { runGen } from "../src/runner.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; +import { frag, importName, TsWriter } from "../src/engine.js"; + +const FIXTURE = resolve(import.meta.dir, "fixtures", "single-entity.json"); + +const emitting = (content: string): Generator => ({ + name: "stringify-helper", + generate: oncePerRun(() => [{ path: "helper.ts", content }]), +}); + +async function run(content: string, dryRun: boolean): Promise<{ dir: string; run: Promise }> { + const { root } = await new MetaDataLoader().load([new FileSource(FIXTURE)]); + const dir = makeScratchDir("stringified-"); + const run = runGen({ config: defineConfig({ outDir: "gen", dialect: "postgres", generators: [emitting(content)] }), metadata: root, projectRoot: dir, dryRun }); + return { dir, run }; +} + +const PROSE = "Fixes the [object Object] label bug"; + +// Copies each entity's @description into a doc comment, the way entity JSDoc and docs pages do. +const describing: Generator = { + name: "describe-entities", + generate: oncePerRun((entities) => [ + { path: "described.ts", content: entities.map((e) => `/** ${String(e.attr("description"))} */\nexport const ${e.name} = 1;\n`).join("") }, + ]), +}; + +async function runWithDescription(generators: Generator[]): Promise<{ dir: string; run: Promise }> { + const dir = makeScratchDir("stringified-prose-"); + const model = JSON.parse(readFileSync(FIXTURE, "utf8")) as { "metadata.root": { children: Array<{ "object.entity": Record }> } }; + model["metadata.root"].children[0]!["object.entity"]["@description"] = PROSE; + const modelPath = join(dir, "meta.described.json"); + writeFileSync(modelPath, JSON.stringify(model)); + const { root } = await new MetaDataLoader().load([new FileSource(modelPath)]); + const run = runGen({ config: defineConfig({ outDir: "gen", dialect: "postgres", generators }), metadata: root, projectRoot: dir }); + return { dir, run }; +} + +describe("a stringified object never reaches a generated file", () => { + test("a fragment refuses to become a string, in a template literal, + or join", () => { + const f = frag("const x = ", importName("z", "zod"), ";"); + expect(() => `${f}`).toThrow("ERR_FRAG_AS_TEXT"); + expect(() => "a" + f).toThrow("ERR_FRAG_AS_TEXT"); + expect(() => [f].join("")).toThrow("ERR_FRAG_AS_TEXT"); + // Written by a writer, the same fragment is fine. + expect(new TsWriter().fragment(f).toString()).toContain("const x = z;"); + }); + + for (const dryRun of [false, true]) { + test(`${dryRun ? "verify (dry run)" : "gen"} refuses output containing [object Object], naming file and generator`, async () => { + const { dir, run: r } = await run("export const helper = [object Object];\n", dryRun); + try { + await expect(r).rejects.toThrow(/ERR_GEN_STRINGIFIED_OBJECT.*gen\/helper\.ts \(generator "stringify-helper"\)/); + expect(existsSync(join(dir, "gen", "helper.ts"))).toBe(false); + } finally { + removeTree(dir); + } + }); + } + + test("the exact quoted string literal is code on purpose and is allowed", async () => { + const { dir, run: r } = await run('export const text = "[object Object]";\n', false); + try { + await r; + expect(existsSync(join(dir, "gen", "helper.ts"))).toBe(true); + } finally { + removeTree(dir); + } + }); + + test("text the model's own string values carry is allowed: a description naming the symptom generates", async () => { + const { dir, run: r } = await runWithDescription([describing]); + try { + await r; + expect(readFileSync(join(dir, "gen", "described.ts"), "utf8")).toContain(`/** ${PROSE} */`); + } finally { + removeTree(dir); + } + }); + + test("a stringified object is still refused when the model carries no such string", async () => { + const { dir, run: r } = await run("/** Fixes the label bug */\nexport const helper = [object Object];\n", false); + try { + await expect(r).rejects.toThrow(/ERR_GEN_STRINGIFIED_OBJECT: generated output contains "\[object Object\]", which no string in the model carries/); + } finally { + removeTree(dir); + } + }); +}); diff --git a/server/typescript/packages/metadata/src/shared/meta-data.ts b/server/typescript/packages/metadata/src/shared/meta-data.ts index 179be29e0e..2e8900a432 100644 --- a/server/typescript/packages/metadata/src/shared/meta-data.ts +++ b/server/typescript/packages/metadata/src/shared/meta-data.ts @@ -25,6 +25,9 @@ export abstract class MetaData { // Identity / packaging // Accessor, not a bare field: a root child's `package` is part of its resolution key, // so a write must tell the root its top-level index (top-level-index.ts) is stale. + /** The package THIS node declares; `undefined` when it takes its file root's package (see + * `fileDefaultPackage`). The canonical serializer depends on that. For the effective package use + * `effectivePackageOf(node)` (`@metaobjectsdev/metadata`) or `effectivePackage(node)` (codegen-ts). */ get package(): string | undefined { return this._package; } diff --git a/server/typescript/packages/migrate-ts/src/diff/index.ts b/server/typescript/packages/migrate-ts/src/diff/index.ts index b55117c724..994d355122 100644 --- a/server/typescript/packages/migrate-ts/src/diff/index.ts +++ b/server/typescript/packages/migrate-ts/src/diff/index.ts @@ -12,9 +12,9 @@ import { sqlTypeEquals } from "../sql-type.js"; import { applyStatus } from "./status.js"; import { PrimaryKeyChangeError } from "../errors.js"; import { detectColumnRenames, detectTableRenames } from "./rename-heuristic.js"; -import { firstViewSqlDifference, viewSqlEquals } from "../view-sql-compare.js"; +import { firstViewSqlDifference, firstViewSqlDifferenceInSelectList, viewSqlEquals } from "../view-sql-compare.js"; import { viewReplaceIsLegal, type ViewReplaceProbe } from "../view-replace.js"; -import { liveViewReadsTable, sqlNamesIdentifier } from "../view-reads.js"; +import { liveViewReadsTable, sqlNamesIdentifier, viewSelectsStar } from "../view-reads.js"; import { viewsNamingRenamedColumns } from "../view-change-reason.js"; import { expectedFromShadow, shadowIdentityProbe, type ShadowSchemaSource } from "../shadow-expected.js"; import { checkExprEquals, checkExprRespelledNullSafe, renameExprIdentifiers } from "../check-expr-compare.js"; @@ -1344,8 +1344,11 @@ async function diffViews( if (body !== undefined) { if (a.sql === body) continue; const firstDifference = a.sql !== undefined ? firstViewSqlDifference(body, a.sql) : undefined; + const starExpansion = v.sql !== undefined && viewSelectsStar(v.sql) + && a.sql !== undefined && firstViewSqlDifferenceInSelectList(body, a.sql); await pushViewUpdate(v, a, changes, probe, a.fingerprint === undefined, { kind: "definition", compared: "text", ...(firstDifference !== undefined ? { firstDifference } : {}), + ...(starExpansion ? { starExpansion: true as const } : {}), }); continue; } diff --git a/server/typescript/packages/migrate-ts/src/types.ts b/server/typescript/packages/migrate-ts/src/types.ts index e77928709e..77d175306e 100644 --- a/server/typescript/packages/migrate-ts/src/types.ts +++ b/server/typescript/packages/migrate-ts/src/types.ts @@ -481,11 +481,15 @@ export type ViewChangeReason = * never match. `firstDifference` (text comparisons only) holds each side's normalized * text from a little before the first character that differs. `tables` is set when the * change became a drop/create pair because the migration also alters those tables. + * `starExpansion` is set on Postgres when the declared body selects `*` and the two + * definitions first differ in the select list: Postgres expands `*` when the view is + * created, so a table that gained columns since may be the cause. */ | { kind: "definition"; compared: "text" | "fingerprint"; firstDifference?: { expected: string; actual: string }; + starExpansion?: true; tables?: readonly string[]; } /** diff --git a/server/typescript/packages/migrate-ts/src/view-reads.ts b/server/typescript/packages/migrate-ts/src/view-reads.ts index 9e11c94976..17ef2b850c 100644 --- a/server/typescript/packages/migrate-ts/src/view-reads.ts +++ b/server/typescript/packages/migrate-ts/src/view-reads.ts @@ -32,3 +32,62 @@ export function sqlNamesIdentifier(sql: string, identifier: string): boolean { export function liveViewReadsTable(live: ViewDescriptor, table: string): boolean { return live.sql === undefined || sqlNamesIdentifier(live.sql, table); } + +/** A qualifier before `.*`: `o.`, `"o".`, `public.orders.`. */ +const STAR_QUALIFIER = String.raw`(?:(?:\w+|"(?:[^"]|"")*")\s*\.\s*)*`; +/** `(...)` holding up to two further levels of balanced parentheses: `(lower(trim(x)))`. */ +const BALANCED_PARENS = String.raw`\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\)`; +/** + * `*` or `qualifier.*` as a select-list item: right after `SELECT` (with `ALL`, `DISTINCT` or + * `DISTINCT ON (...)`) or a comma, and followed by a comma or `FROM`. + */ +const SELECT_LIST_STAR_RE = new RegExp( + String.raw`(?:\bselect(?:\s+all|\s+distinct(?:\s+on\s*${BALANCED_PARENS})?)?|,)\s*${STAR_QUALIFIER}\*\s*(?:,|\bfrom\b)`, + "i", +); + +/** + * `sql` with every `-- line` and `/* block *\/` comment outside a `'…'` literal or a `"…"` + * identifier replaced by one space. + */ +function stripSqlComments(sql: string): string { + let out = ""; + let i = 0; + const n = sql.length; + while (i < n) { + const ch = sql[i] as string; + if (ch === "'" || ch === '"') { + let j = i + 1; + while (j < n) { + if (sql[j] === ch) { + if (sql[j + 1] === ch) { j += 2; continue; } + j++; + break; + } + j++; + } + out += sql.slice(i, j); + i = j; + } else if (ch === "-" && sql[i + 1] === "-") { + const eol = sql.indexOf("\n", i); + i = eol === -1 ? n : eol; + out += " "; + } else if (ch === "/" && sql[i + 1] === "*") { + const end = sql.indexOf("*/", i + 2); + i = end === -1 ? n : end + 2; + out += " "; + } else { + out += ch; + i++; + } + } + return out; +} + +/** + * Does the body select `*` or `alias.*` as a column list? `count(*)`, `price * qty` and a + * comment are not column lists. + */ +export function viewSelectsStar(sql: string): boolean { + return SELECT_LIST_STAR_RE.test(stripSqlComments(sql)); +} diff --git a/server/typescript/packages/migrate-ts/src/view-sql-compare.ts b/server/typescript/packages/migrate-ts/src/view-sql-compare.ts index cb220b295b..a46e775467 100644 --- a/server/typescript/packages/migrate-ts/src/view-sql-compare.ts +++ b/server/typescript/packages/migrate-ts/src/view-sql-compare.ts @@ -102,3 +102,45 @@ export function firstViewSqlDifference( }; return { expected: excerpt(e), actual: excerpt(a) }; } + +/** + * Where the select list ends in a normalized body: its first `FROM` outside parentheses and + * quotes, so the `FROM` in `EXTRACT(YEAR FROM x)` or in a subquery does not end it. + */ +function selectListEnd(s: string): number { + let depth = 0; + for (let i = 0; i < s.length; i++) { + const ch = s[i] as string; + if (ch === "'" || ch === '"' || ch === "`") { + let j = i + 1; + while (j < s.length) { + if (s[j] === ch) { + if (s[j + 1] === ch) { j += 2; continue; } + break; + } + j++; + } + i = j; + } else if (ch === "(") { + depth++; + } else if (ch === ")") { + if (depth > 0) depth--; + } else if (depth === 0 && /\s/.test(ch) && /^from\b/i.test(s.slice(i + 1, i + 6))) { + return i; + } + } + return s.length; +} + +/** + * Do two view definitions first differ inside their select lists, before either one's first top-level + * `FROM`? `false` when they are equal. + */ +export function firstViewSqlDifferenceInSelectList(expected: string, actual: string): boolean { + const e = normalizeViewSql(expected); + const a = normalizeViewSql(actual); + if (e === a) return false; + let i = 0; + while (i < e.length && i < a.length && e[i] === a[i]) i++; + return i <= selectListEnd(e) && i <= selectListEnd(a); +} diff --git a/server/typescript/packages/migrate-ts/test/unit/diff-view-star-add-column.test.ts b/server/typescript/packages/migrate-ts/test/unit/diff-view-star-add-column.test.ts new file mode 100644 index 0000000000..4c87257736 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/diff-view-star-add-column.test.ts @@ -0,0 +1,90 @@ +/** + * A `*` view over a table that gains a column. Postgres expands `*` when the view is + * created, so the live view keeps the narrow column list. The offline diff (no shadow + * schema) leaves that view alone; `meta migrate --from-db` compares through the shadow + * database and can plan a replace, or a drop and create. `verify --db` names the likely cause. + */ +import { test, expect, describe } from "bun:test"; +import { diff } from "../../src/diff/index.js"; +import { viewFingerprint } from "../../src/view-fingerprint.js"; +import type { Change, ColumnDescriptor, SchemaSnapshot, TableDescriptor, ViewDescriptor } from "../../src/types.js"; + +function table(cols: ColumnDescriptor[]): TableDescriptor { + return { name: "orders", columns: cols, indexes: [], foreignKeys: [], primaryKey: ["id"], checks: [] }; +} +const ID: ColumnDescriptor = { name: "id", sqlType: { kind: "integer", bits: 64 }, nullable: false }; +const STATUS: ColumnDescriptor = { name: "status", sqlType: { kind: "text" }, nullable: false }; +const EXTRA: ColumnDescriptor = { name: "extra", sqlType: { kind: "text" }, nullable: true }; + +function view(body: string): ViewDescriptor { + return { name: "order_view", sql: body, fingerprint: viewFingerprint(body), dependsOn: ["orders"] }; +} +const snap = (t: TableDescriptor, v: ViewDescriptor): SchemaSnapshot => ({ tables: [t], views: [v] }); +const kinds = (r: { changes: { kind: string }[] }) => r.changes.map((c) => c.kind); + +describe("add-column leaves a `*` view over the table alone (Postgres)", () => { + for (const body of ["SELECT o.* FROM orders o", "SELECT * FROM orders", "SELECT o.id, o.status FROM orders o"]) { + test(`${body}: the plan is the add-column only`, async () => { + const r = await diff( + snap(table([ID, STATUS, EXTRA]), view(body)), snap(table([ID, STATUS]), view(body)), { dialect: "postgres" }, + ); + expect(kinds(r)).toEqual(["add-column"]); + }); + } +}); + +describe("verify --db names a possible `*` expansion only where it can be the cause (Postgres shadow path)", () => { + const T = table([ID, STATUS, EXTRA]); + const live = (body: string): ViewDescriptor => ({ name: "order_view", sql: body, fingerprint: "stamped-earlier" }); + /** The shadow database's deparse of the declared view: Postgres expanded `*` at create. */ + const shadowOf = (body: string) => async () => ({ catalog: { tables: [T], views: [live(body)] } }); + const viewReason = (changes: Change[]) => { + const c = changes.find((x) => x.kind === "replace-view" || x.kind === "create-view"); + return c !== undefined && "reason" in c ? c.reason : undefined; + }; + + test("a `*` body whose deparse gained a column is marked", async () => { + const r = await diff(snap(T, view("SELECT o.* FROM orders o")), snap(T, live("SELECT o.id, o.status FROM orders o")), { + dialect: "postgres", shadowSchema: shadowOf("SELECT o.id, o.status, o.extra FROM orders o"), + }); + expect(viewReason(r.changes)).toMatchObject({ kind: "definition", compared: "text", starExpansion: true }); + }); + + test("a `*` body that differs only after FROM is not marked", async () => { + const r = await diff( + snap(T, view("SELECT * FROM orders WHERE id = 2")), snap(T, live("SELECT orders.id FROM orders WHERE (id = 1)")), + { dialect: "postgres", shadowSchema: shadowOf("SELECT orders.id FROM orders WHERE (id = 2)") }, + ); + const reason = viewReason(r.changes); + expect(reason).toMatchObject({ kind: "definition", compared: "text" }); + expect(reason).not.toHaveProperty("starExpansion"); + }); + + test("a `*` body whose select list holds EXTRACT(... FROM ...) is marked when the select list differs", async () => { + const r = await diff( + snap(T, view("SELECT EXTRACT(YEAR FROM o.created) AS y, o.* FROM orders o")), + snap(T, live("SELECT EXTRACT(year FROM o.created) AS y, o.id, o.status FROM orders o")), + { dialect: "postgres", shadowSchema: shadowOf("SELECT EXTRACT(year FROM o.created) AS y, o.id, o.status, o.extra FROM orders o") }, + ); + expect(viewReason(r.changes)).toMatchObject({ kind: "definition", compared: "text", starExpansion: true }); + }); + + test("a body that multiplies, not selects `*`, is not marked", async () => { + const body = "SELECT o.id, o.price * o.qty AS total FROM orders o"; + const r = await diff(snap(T, view(body)), snap(T, live("SELECT o.id FROM orders o")), { + dialect: "postgres", shadowSchema: shadowOf("SELECT o.id, (o.price * o.qty) AS total FROM orders o"), + }); + const reason = viewReason(r.changes); + expect(reason).toMatchObject({ kind: "definition", compared: "text" }); + expect(reason).not.toHaveProperty("starExpansion"); + }); + + test("SQLite never marks a text difference (it expands `*` at query time)", async () => { + const r = await diff(snap(T, view("SELECT * FROM orders WHERE id = 2")), snap(T, live("SELECT * FROM orders WHERE id = 1")), { + dialect: "sqlite", + }); + const reason = viewReason(r.changes); + expect(reason).toMatchObject({ kind: "definition", compared: "text" }); + expect(reason).not.toHaveProperty("starExpansion"); + }); +}); diff --git a/spec/code-writer.md b/spec/code-writer.md index ba95873d70..2e697e5263 100644 --- a/spec/code-writer.md +++ b/spec/code-writer.md @@ -46,6 +46,11 @@ means the same thing in every port. opened the innermost open block. - Line text containing a line break (`\n`, `\r\n` or `\r`) is **`ERR_WRITER_NEWLINE_IN_LINE`**. Write each line separately, or use `text`. +- Text passed to `line`, `open` or `close` (and a dialect's `reopen`) whose first character is + a space or tab is **`ERR_WRITER_LEADING_WHITESPACE`**: the writer adds the indent, so a + caller-indented piece would sit deeper than its siblings. `text` keeps indentation beyond the common margin, and + a dialect's doc-comment, header and import helpers write their own lines (such as ` * foo`) + without the check. ### Blank lines are requests @@ -116,6 +121,8 @@ units. The comparison includes the indent, and a line exactly `width` long fits. - **`reopen(parts...)`** closes the open block and opens the next on one line: it dedents, writes the line, and indents again, as in `}).superRefine((row, ctx) => {` or `} else {`. With no block open it is **`ERR_WRITER_UNBALANCED_CLOSE`**. +- **`commentLine(parts...)`** writes one line of a block comment the generator lays out itself, + such as ` * text`: its leading space is kept and the line is still indented from the open blocks. - **`doc(lines...)`** writes `/** text */` when there is one entry and it fits. Otherwise it writes a block of ` * ` lines, with a bare ` *` line for an empty entry. A `*/` inside the text is written as `*\/`. @@ -167,6 +174,8 @@ writes the head, indents, and on leaving the `try` dedents and writes `}`. - **`doc(lines...)`** writes `/** text */` when there is one entry and it fits. Otherwise it writes a block of ` * ` lines, with a bare ` *` line for an empty entry. A `*/` inside the text is written as `*/`. +- **`commentLine(parts...)`** works as in the TypeScript dialect: it writes a hand-laid + block-comment line, such as ` * text`. - Helpers: `str` (a quoted string literal) and `call` (`fn(a, b)`, a list that breaks one item per line with no trailing comma). - A part is a `String`, a list (`Group`, built with `CodeWriter.list` or `CodeWriter.padded`) or a @@ -198,6 +207,8 @@ conventions write them. - **`doc(lines...)`** writes `/** text */` when there is one entry and it fits. Otherwise it writes a block of ` * ` lines, with a bare ` *` line for an empty entry. Kotlin comments nest, so both `*/` and `/*` inside the text are neutralised (`*/`, `/*`). +- **`commentLine(parts...)`** works as in the TypeScript dialect: it writes a hand-laid + block-comment line, such as ` * text`. - **Scoped forms.** `block(head) { ... }` writes the head, indents, runs the lambda, dedents and writes `}`. `reopen(parts)` closes the open block and opens the next on one line (`} else {`); with no block open it is `ERR_WRITER_UNBALANCED_CLOSE`. `indented { ... }` writes its lines one 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 8bfa619523..e53fe62949 100644 --- a/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md +++ b/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md @@ -156,8 +156,18 @@ replace), one JSON file per model package: (`generator` and `outputDir` on the JVM, `generatedBy` and `sourceNode` in TypeScript, C#, Java and Python). 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 +**2. Reading is a union.** A reader merges every `*.json` file in `.hashes/`, in file-name order. While +a legacy `.hashes.json` is present it is read **instead** of them (corrected 2026-11-30; this read +first "with the legacy file underneath, a key in a package file wins"). A migrating write deletes the +legacy file right after writing the package files (§5), so a project that still has it has not +migrated, and a `.hashes/` beside it was left by another checkout or another engine's run: the +scaffold's old `.gitignore` (`.gen-state/*`, `!.gen-state/.hashes.json`) ignores that directory, so +it survives a reset, a clean and a branch switch. Read on top, its stale hashes made every file the +committed manifest vouches for look hand-edited, `gen` kept the old output and exited 0, and only the +names artifacts failed `verify`. The one case the old order served better, a write that stopped +between writing the package files and deleting the legacy one, now fails closed (the newer files read +as edited and are refused by name), which is the direction §2 already chose. The write that migrates +replaces or removes the stale package files. 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 @@ -208,7 +218,7 @@ it git would ignore the new directory. Only a migrating run touches `.gitignore` 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, +**6. Everything that read the manifest reads the union (§2).** 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 diff --git a/templates/agent/schema.md.mustache b/templates/agent/schema.md.mustache index ad91a93c2f..90dfc9bee4 100644 --- a/templates/agent/schema.md.mustache +++ b/templates/agent/schema.md.mustache @@ -14,7 +14,7 @@ The tables, columns and keys this model declares. Read it before writing a query - Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. {{/hasMigrate}} {{^hasMigrate}} -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. {{/hasMigrate}} - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. diff --git a/tools/prerelease/detect-prerelease-pins.sh b/tools/prerelease/detect-prerelease-pins.sh index 4b86d7b531..3d19fddc70 100755 --- a/tools/prerelease/detect-prerelease-pins.sh +++ b/tools/prerelease/detect-prerelease-pins.sh @@ -167,6 +167,20 @@ other_hit=0 agent_context_hit=0 hit() { echo " ✖ $1" >&2; fail=1; other_hit=1; } +# Everything this script prints about a matched line goes through here first. The matched +# lines of a lockfile hold tarball URLs on the private registry, and this output lands in +# terminals, CI logs and PR bodies: print the file, the line and the package/version text, +# never the host. A URL keeps only its last path segment (`/pkg-1.3.0-rc.1.tgz`, +# which still names the package and version); a bare registry host and an auth token go too. +redact() { + local sedhost=() + [ -n "$REGISTRY_HOST" ] && sedhost=( -e "s#$(printf '%s' "$REGISTRY_HOST" | sed 's/[][\\.*^$#]/\\&/g')##g" ) + sed -E \ + -e 's#[A-Za-z][A-Za-z0-9+.-]*://[^ "'"'"'<>)/]*(/[^ "'"'"'<>)?\#]*/)?([^/ "'"'"'<>)?\#]*)[^ "'"'"'<>)]*#/\2#g' \ + -e 's#(_authToken=)[^ ]*#\1#g' \ + ${sedhost+"${sedhost[@]}"} +} + scan() { # scan