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
+ `
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