From 71ab9600a511de08c3f28fe7579dd50040f2b6a3 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Mon, 30 Nov 2026 07:01:32 -0500
Subject: [PATCH 01/17] fix: 1.3.0-rc.4 estate defects: generated-code checks,
manifest trust, upgrade guide
- Python gen/verify refuse generated Python that does not compile; every
port's code writer refuses indented text (ERR_WRITER_LEADING_WHITESPACE),
with commentLine() for block-comment lines.
- TypeScript gen and verify --codegen parse emitted TypeScript before writing.
- A committed legacy .hashes.json is authoritative over a stale ignored
.hashes/ in every port (ADR-0064 section 2 corrected).
- verify --db names and collapses SELECT * view drift; migrate recreates such
views on Postgres when a base table gains columns.
- Removed-marker refusal names every generator; service generators skip
objects whose entity module the run does not emit; new
WARN_DERIVED_COMMAND_BYPASSES_DECLARED in every port's rules gate.
- No false git-ignored warning on the run that migrates the manifest.
- Prerelease tooling: host redaction, per-lockfile unlink hint, unlink
restores the pre-link pins, estate-run restores ignored gen-state, and a
full candidate refuses unfolded changelog fragments.
- CHANGELOG 1.3.0: fragments folded; Upgrading from 1.2.0 corrected and
completed (owned generators, markers, queries primitives, Frag, uuid on
every dialect, docsFile/generateSite, hash manifest, formatting churn,
Python hooks); migration docs aligned.
---
CHANGELOG.md | 629 +++++++++++++++++-
changelog.d/agent-docs-native-every-port.md | 21 -
changelog.d/agent-pages-every-port.md | 32 -
changelog.d/bun-1-3-14-package-manager.md | 6 -
changelog.d/classic-docs-site-removed.md | 7 -
changelog.d/cli-install-smaller.md | 2 -
changelog.d/csharp-codegen-shims-removed.md | 3 -
.../docs-markdown-generator-removed.md | 13 -
changelog.d/explorer-3d-map.md | 9 -
changelog.d/explorer-app-stable-bundle.md | 7 -
changelog.d/explorer-app.md | 21 -
changelog.d/explorer-csharp-python.md | 13 -
changelog.d/explorer-jvm.md | 12 -
changelog.d/explorer-live-source.md | 10 -
changelog.d/explorer-rust.md | 23 -
.../format-ts-and-owned-copy-biome-removed.md | 7 -
.../generated-file-provenance-all-ports.md | 10 -
.../generator-legacy-markers-removed.md | 13 -
.../java-entity-writer-mustache-removed.md | 42 --
changelog.d/java-xpkg-qualified-names.md | 5 -
changelog.d/jvm-non-long-keys.md | 5 -
changelog.d/key-types-api-contract-corpus.md | 6 -
changelog.d/metamodel-docs-mustache.md | 17 -
changelog.d/python-codegen-writer-no-ruff.md | 55 --
changelog.d/python-rc21-view-vocabulary.md | 9 -
changelog.d/registry-type-level-ports.md | 11 -
changelog.d/rust-publish-stale-sources.md | 7 -
changelog.d/ts-crud-routes-non-id-key.md | 6 -
changelog.d/ts-poet-printer-removed.md | 10 -
docs/CONFORMANCE.md | 6 +-
docs/features/business-rules.md | 1 +
.../commit-the-gen-state-hash-manifest.md | 8 +-
.../migrations/default-list-page-of-fifty.md | 6 +-
.../migrations/docs-are-generators.md | 35 +
.../migrations/owned-generators-1.2-to-1.3.md | 35 +-
docs/features/prerelease.md | 2 +-
docs/recipes/write-your-own-generator.md | 6 +
.../codegen/templates/duration-wire-helper.ts | 8 +-
.../codegen/templates/jsdoc.ts | 10 +-
.../codegen/templates/duration-wire-helper.ts | 8 +-
examples/showcase/codegen/templates/jsdoc.ts | 10 +-
.../expected/agent/schema.md | 2 +-
.../expected/agent/schema.md | 2 +-
fixtures/rules-check-conformance/README.md | 4 +-
.../expected.json | 21 +
.../input/meta.purchasing.yaml | 43 ++
.../commands-all-declared-bypass/options.json | 1 +
.../expected.json | 12 +
.../cases/error-leading-tab-in-open.json | 20 +
.../error-leading-whitespace-in-line.json | 28 +
.../cases/py-doc-keeps-line-indentation.json | 29 +
scripts/lib/changelog-fragments.mjs | 21 +
scripts/prerelease.mjs | 10 +
scripts/test-changelog-fragments.mjs | 6 +-
.../HashManifestPerPackageTests.cs | 17 +
.../MetaObjects.Codegen/HashManifest.cs | 15 +-
.../Templates/agent/schema.md.mustache | 2 +-
.../MetaObjects.Codegen/Writer/CodeWriter.cs | 25 +-
.../MetaObjects.Codegen/Writer/CsWriter.cs | 6 +-
.../MetaObjects/Core/Transition/RulesCheck.cs | 25 +
.../javacode/ExtractorCodeGenerator.java | 28 +-
.../javacode/JavaObjectCodeGenerator.java | 8 +-
.../generator/util/HashManifest.java | 12 +-
.../generator/writer/CodeWriter.java | 27 +-
.../generator/writer/JavaWriter.java | 21 +-
.../generator/writer/WriterException.java | 2 +
.../templates/agent/schema.md.mustache | 2 +-
.../util/HashManifestPackagesTest.java | 21 +-
.../kotlin/KotlinDecimalWireEmitter.kt | 2 +-
.../kotlin/KotlinSpringControllerGenerator.kt | 42 +-
.../generator/kotlin/writer/KotlinWriter.kt | 32 +-
.../JUnitRequirementTestsGenerator.java | 7 +-
.../spring/LlmTraceHelperGenerator.java | 30 +-
.../SpringFilterAllowlistGenerator.java | 8 +-
.../spring/SpringNamesGenerator.java | 4 +-
.../spring/SpringOutputParserGenerator.java | 8 +-
.../spring/SpringRenderHelperGenerator.java | 4 +-
.../spring/SpringReportExportGenerator.java | 10 +-
.../spring/SpringRepositoryGenerator.java | 26 +-
.../java/com/metaobjects/api/RulesCheck.java | 26 +
.../codegen/generators/entity_model.py | 28 +-
.../metaobjects/codegen/overwrite_policy.py | 10 +-
.../python/src/metaobjects/codegen/runner.py | 32 +
.../metaobjects/codegen/writer/__init__.py | 3 +-
.../metaobjects/codegen/writer/code_writer.py | 27 +-
.../metaobjects/codegen/writer/py_writer.py | 5 +-
.../agent/schema.md.mustache | 2 +-
server/python/src/metaobjects/rules_check.py | 33 +
server/python/tests/codegen/test_cli.py | 23 +-
.../codegen/test_generated_python_compiles.py | 126 ++++
.../tests/codegen/test_manifest_store.py | 5 +-
.../codegen/test_overwrite_policy_hash.py | 17 +
server/rust/metaobjects-codegen/src/hashes.rs | 38 +-
server/rust/metaobjects-codegen/src/writer.rs | 36 +-
.../templates/agent/schema.md.mustache | 2 +-
.../tests/hash_manifest.rs | 5 +-
server/rust/metaobjects/src/rules_check.rs | 57 ++
.../packages/cli/src/commands/gen.ts | 10 +-
.../packages/cli/src/commands/verify.ts | 30 +-
.../typescript/packages/cli/src/lib/allow.ts | 23 +-
.../packages/cli/src/lib/codegen-drift.ts | 3 +
.../cli/src/lib/emitted-ts-parse-check.ts | 60 ++
.../packages/cli/src/lib/rules-check.ts | 31 +
.../cli/test/gen-emitted-ts-parses.test.ts | 101 +++
.../test/gen-manifest-ignore-advisory.test.ts | 81 +++
.../test/unit/verify-view-star-drift.test.ts | 31 +
.../packages/codegen-ts/src/generator.ts | 5 +
.../codegen-ts/src/generators/service-file.ts | 6 +-
.../src/generators/service-routes-file.ts | 6 +-
.../generators/service-routes-hono-file.ts | 6 +-
.../codegen-ts/src/hash-manifest-store.ts | 14 +-
.../src/reference/requirement-tests.ts | 14 +-
.../src/reference/service-routes-hono.ts | 5 +-
.../src/reference/service-routes.ts | 5 +-
.../codegen-ts/src/reference/service.ts | 5 +-
.../embedded-templates.generated.ts | 2 +-
.../packages/codegen-ts/src/runner.ts | 40 +-
.../packages/codegen-ts/src/service-walk.ts | 22 +
.../src/templates/duration-wire-helper.ts | 8 +-
.../codegen-ts/src/templates/jsdoc.ts | 10 +-
.../src/templates/requirement-test.ts | 14 +-
.../codegen-ts/src/writer/code-writer.ts | 26 +-
.../codegen-ts/src/writer/ts-writer.ts | 25 +-
.../templates/agent/schema.md.mustache | 2 +-
.../test/agent-docs-surface.test.ts | 5 +-
.../test/duration-wire-helper.test.ts | 4 +-
.../test/effective-package-filter.test.ts | 29 +
.../test/hash-manifest-store.test.ts | 17 +
.../packages/codegen-ts/test/runner.test.ts | 19 +
.../codegen-ts/test/service-file.test.ts | 39 ++
.../packages/metadata/src/shared/meta-data.ts | 3 +
.../packages/migrate-ts/src/diff/index.ts | 26 +-
.../unit/diff-view-star-add-column.test.ts | 58 ++
spec/code-writer.md | 5 +
...-0064-skip-codegen-when-nothing-changed.md | 16 +-
templates/agent/schema.md.mustache | 2 +-
tools/prerelease/detect-prerelease-pins.sh | 26 +-
tools/prerelease/estate-run.md | 2 +-
tools/prerelease/estate-run.sh | 38 +-
tools/prerelease/prerelease-link.sh | 120 +++-
tools/prerelease/test-estate-run.sh | 26 +
tools/prerelease/test-prerelease-link.sh | 72 ++
142 files changed, 2624 insertions(+), 672 deletions(-)
delete mode 100644 changelog.d/agent-docs-native-every-port.md
delete mode 100644 changelog.d/agent-pages-every-port.md
delete mode 100644 changelog.d/bun-1-3-14-package-manager.md
delete mode 100644 changelog.d/classic-docs-site-removed.md
delete mode 100644 changelog.d/cli-install-smaller.md
delete mode 100644 changelog.d/csharp-codegen-shims-removed.md
delete mode 100644 changelog.d/docs-markdown-generator-removed.md
delete mode 100644 changelog.d/explorer-3d-map.md
delete mode 100644 changelog.d/explorer-app-stable-bundle.md
delete mode 100644 changelog.d/explorer-app.md
delete mode 100644 changelog.d/explorer-csharp-python.md
delete mode 100644 changelog.d/explorer-jvm.md
delete mode 100644 changelog.d/explorer-live-source.md
delete mode 100644 changelog.d/explorer-rust.md
delete mode 100644 changelog.d/format-ts-and-owned-copy-biome-removed.md
delete mode 100644 changelog.d/generated-file-provenance-all-ports.md
delete mode 100644 changelog.d/generator-legacy-markers-removed.md
delete mode 100644 changelog.d/java-entity-writer-mustache-removed.md
delete mode 100644 changelog.d/java-xpkg-qualified-names.md
delete mode 100644 changelog.d/jvm-non-long-keys.md
delete mode 100644 changelog.d/key-types-api-contract-corpus.md
delete mode 100644 changelog.d/metamodel-docs-mustache.md
delete mode 100644 changelog.d/python-codegen-writer-no-ruff.md
delete mode 100644 changelog.d/python-rc21-view-vocabulary.md
delete mode 100644 changelog.d/registry-type-level-ports.md
delete mode 100644 changelog.d/rust-publish-stale-sources.md
delete mode 100644 changelog.d/ts-crud-routes-non-id-key.md
delete mode 100644 changelog.d/ts-poet-printer-removed.md
create mode 100644 fixtures/rules-check-conformance/commands-all-declared-bypass/expected.json
create mode 100644 fixtures/rules-check-conformance/commands-all-declared-bypass/input/meta.purchasing.yaml
create mode 100644 fixtures/rules-check-conformance/commands-all-declared-bypass/options.json
create mode 100644 fixtures/writer-conformance/cases/error-leading-tab-in-open.json
create mode 100644 fixtures/writer-conformance/cases/error-leading-whitespace-in-line.json
create mode 100644 fixtures/writer-conformance/cases/py-doc-keeps-line-indentation.json
create mode 100644 server/python/tests/codegen/test_generated_python_compiles.py
create mode 100644 server/typescript/packages/cli/src/lib/emitted-ts-parse-check.ts
create mode 100644 server/typescript/packages/cli/test/gen-emitted-ts-parses.test.ts
create mode 100644 server/typescript/packages/cli/test/gen-manifest-ignore-advisory.test.ts
create mode 100644 server/typescript/packages/cli/test/unit/verify-view-star-drift.test.ts
create mode 100644 server/typescript/packages/codegen-ts/test/effective-package-filter.test.ts
create mode 100644 server/typescript/packages/migrate-ts/test/unit/diff-view-star-add-column.test.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c91805ffa6..0ff470f383 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -135,10 +135,59 @@ 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`.
+ - **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 +234,105 @@ 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 `metaobjects verify` also refuse any generated `.py` file
+ that does not compile, naming the file and the generator:
+
+ ```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 +345,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 +370,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 +473,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,
@@ -450,6 +599,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 and the classic site stay 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()`,
@@ -464,8 +804,9 @@ there is described in full here. This list is where to start.
(`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`,
@@ -2139,6 +2480,147 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru
### Changed
+- **`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 the marker and its `provides` replacement, instead of
+ reading it. The name-based fallbacks that treated a copy named `queries-file`, `entity-file`,
+ `routes-file` or a UI generator's name as providing its tier are removed with them, as is
+ `UI_TIER_GENERATOR_NAMES`. A copy that carries a shipped generator's name and declares no
+ `provides` at all (one ejected before the markers) still runs, with one warning naming the
+ declaration the shipped generator makes (`SHIPPED_PROVIDES_BY_NAME`). Generator
+ copies ejected in 1.2 or earlier no longer load: re-eject them (`meta eject --force`) or
+ replace the markers with `provides` by hand.
+
+- **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/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/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..8c6e927759 100644
--- a/server/python/src/metaobjects/codegen/overwrite_policy.py
+++ b/server/python/src/metaobjects/codegen/overwrite_policy.py
@@ -265,12 +265,20 @@ 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)."""
+ winning), 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..bb75d7ca47 100644
--- a/server/python/src/metaobjects/codegen/runner.py
+++ b/server/python/src/metaobjects/codegen/runner.py
@@ -116,6 +116,33 @@ 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'."
+ )
+
+
def run_gen(
config: GenConfig,
metadata: MetaData,
@@ -269,6 +296,11 @@ 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)
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..81b177ff9c
--- /dev/null
+++ b/server/python/tests/codegen/test_generated_python_compiles.py
@@ -0,0 +1,126 @@
+"""`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
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-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/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..6ccaeb6d2b 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,34 @@ const DRIFT_PRESENTATION: Record>();
+ const dropped = new Set();
+ for (const c of changes) {
+ if (c.kind === "create-view") created.set(c.view.name, c);
+ else if (c.kind === "drop-view") dropped.add(c.view);
+ }
+ const out: Change[] = [];
+ for (const c of changes) {
+ if (c.kind === "create-view" && dropped.has(c.view.name)) continue; // folded into its drop
+ const make = c.kind === "drop-view" ? created.get(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..256f318e54 100644
--- a/server/typescript/packages/cli/src/lib/allow.ts
+++ b/server/typescript/packages/cli/src/lib/allow.ts
@@ -100,8 +100,8 @@ export function describeChange(c: Change): string {
return c.restore !== undefined
? `${c.table} check ${c.check} (${c.restore.expression})`
: `${c.table} check ${c.check}`;
- case "create-view": return withViewReason(c.view.name, c.reason);
- case "replace-view": return withViewReason(c.view.name, c.reason);
+ case "create-view": return withViewReason(c.view.name, c.reason, c.view.sql);
+ case "replace-view": return withViewReason(c.view.name, c.reason, c.view.sql);
case "drop-view": return withViewReason(c.view, c.reason);
}
// Exhaustive: a new Change kind fails to compile here rather than printing a JSON dump
@@ -115,11 +115,20 @@ export function describeChange(c: Change): string {
* ever printed, so a view whose definition matched the metadata — dropped and recreated only
* because the migration alters a table it reads — read exactly like one that differed (D3).
*/
-function withViewReason(name: string, reason: ViewChangeReason | undefined): string {
- return reason === undefined ? name : `${name} (${viewReasonText(reason)})`;
+function withViewReason(name: string, reason: ViewChangeReason | undefined, sql?: string): string {
+ return reason === undefined ? name : `${name} (${viewReasonText(reason, sql)})`;
}
-function viewReasonText(r: ViewChangeReason): string {
+/** Does a view body select `*` or `alias.*`? (`count(*)` is not a column list.) */
+function selectsStar(sql: string | undefined): boolean {
+ return sql !== undefined && /(^|[\s,(])(\w+\.)?\*(?=\s|,|$)/.test(sql.replace(/count\s*\(\s*\*\s*\)/gi, ""));
+}
+
+const STAR_HINT =
+ "the view selects `*`, which the database expanded when the view was created, and a table it reads has gained " +
+ "columns since: recreate the view (drop and create it), or list its columns explicitly";
+
+function viewReasonText(r: ViewChangeReason, sql?: string): string {
switch (r.kind) {
case "missing": return "declared by the metadata, not in the database";
case "undeclared": return "in the database, declared by no metadata object";
@@ -129,7 +138,9 @@ 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);
+ // A text difference on a `*` body is the stale expansion, not an edited definition.
+ const cause = r.compared === "text" && selectsStar(sql) ? `; ${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..8eff8d7049
--- /dev/null
+++ b/server/typescript/packages/cli/src/lib/emitted-ts-parse-check.ts
@@ -0,0 +1,60 @@
+// 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"]);
+const ERROR_MARK = "__JITI_ERROR__ = ";
+
+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 });
+ const out = parser.transform({ source: content, filename: fullPath, ts: true, jsx: true });
+ const at = out.indexOf(ERROR_MARK);
+ if (at === -1) return undefined;
+ const json = out.slice(at + ERROR_MARK.length).split("\n")[0]!.replace(/;\s*$/, "");
+ try {
+ const parsed: unknown = JSON.parse(json);
+ return typeof parsed === "object" && parsed !== null ? (parsed as JitiParseError) : {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * 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))) 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..78cec53158
--- /dev/null
+++ b/server/typescript/packages/cli/test/gen-emitted-ts-parses.test.ts
@@ -0,0 +1,101 @@
+// `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("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/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..d43b8222f0
--- /dev/null
+++ b/server/typescript/packages/cli/test/unit/verify-view-star-drift.test.ts
@@ -0,0 +1,31 @@
+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 `*` view whose text differs names the stale expansion", () => {
+ const text = describeChange({ kind: "replace-view", view: starView, reason, status: allowed });
+ expect(text).toContain("selects `*`");
+ expect(text).toContain("recreate the view");
+});
+
+test("a view that lists its columns gets no star hint", () => {
+ const view = { name: "v", sql: "SELECT count(*) AS n, o.id FROM orders o" };
+ expect(describeChange({ kind: "replace-view", view, reason, status: allowed })).not.toContain("selects `*`");
+});
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/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..dc78d5fc58 100644
--- a/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts
+++ b/server/typescript/packages/codegen-ts/src/hash-manifest-store.ts
@@ -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/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts
index a7a8c929ad..9a56f457fd 100644
--- a/server/typescript/packages/codegen-ts/src/runner.ts
+++ b/server/typescript/packages/codegen-ts/src/runner.ts
@@ -152,6 +152,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 +678,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 +700,8 @@ 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];
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
@@ -982,6 +998,8 @@ export async function runGen(opts: RunGenOpts): Promise {
...(entityNarrowed && { selected: isSelected }),
loadedRoot: root,
matches: (e) => generator.filter?.(e) ?? true,
+ // The run-level fact a service-layer generator reads: the entity modules this run writes.
+ ...(entityGens.length > 0 && { entityModuleCovers: (e: MetaObject) => entityGens.some((g) => g.filter?.(e) ?? true) }),
// 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 +1159,20 @@ export async function runGen(opts: RunGenOpts): Promise {
}
}
+ // 4c. 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..44dd9a8787 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.name)) {
+ warned.add(obj.name);
+ ctx.warn?.(
+ `${generator}: skipped "${obj.name}": 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/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-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/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/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..8e0759a83d 100644
--- a/server/typescript/packages/codegen-ts/test/service-file.test.ts
+++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts
@@ -120,6 +120,45 @@ 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('"OrderView"') && w.includes("filter"))).toBe(true);
+ }
+ } 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/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..31c442d887 100644
--- a/server/typescript/packages/migrate-ts/src/diff/index.ts
+++ b/server/typescript/packages/migrate-ts/src/diff/index.ts
@@ -1688,7 +1688,19 @@ function recreateViewsDependingOnChangedTables(
alteredTables.set(t, set);
}
}
- if (alteredTables.size === 0) return;
+ // Postgres expands `*` / `alias.*` when a view is CREATED and stores the column list, so a
+ // column added to a table later never reaches a view that selects `*` from it. That view
+ // is not stranded (ALTER TABLE ADD COLUMN succeeds), but it goes stale: every database built
+ // from the chain holds the narrow expansion while a freshly built one holds the wide one,
+ // and `verify --db` then reports drift no plan would ever clear. Recreating such a view in
+ // the migration that adds the column keeps the two in step.
+ const widenedTables = new Set();
+ if (columnScoped) {
+ for (const c of changes) {
+ if (c.kind === "add-column" && typeof c.table === "string") widenedTables.add(c.table);
+ }
+ }
+ if (alteredTables.size === 0 && widenedTables.size === 0) return;
// View identities already queued for a definition change, collected once instead of
// rescanning `changes` per expected view over a diff that can carry hundreds of changes.
@@ -1718,6 +1730,16 @@ function recreateViewsDependingOnChangedTables(
return viewReadsAnyColumn(sql, cols, readsEverything);
});
const prior = actualById.get(id);
+ // A `*` view over a table that gained columns (see `widenedTables`). The live body is
+ // what holds the stale expansion, so it is the live body that must read the table.
+ for (const t of widenedTables) {
+ if (tables.includes(t) || prior === undefined) continue;
+ const liveStar = prior.sql !== undefined && viewReadsEveryColumn(prior.sql);
+ const newStar = readsEverything && tracked.includes(t);
+ if ((liveStar || newStar) && liveViewReadsTable(prior, liveName(t))) {
+ tables.push(t);
+ }
+ }
// The view in the database is stranded by every table ITS body reads, and that body
// may read one `dependsOn` leaves out: a table the new body no longer reads, or one an
// `@sql` body joins (ADR-0043). Its own text says which. On Postgres it is stranded
@@ -1726,7 +1748,7 @@ function recreateViewsDependingOnChangedTables(
if (prior !== undefined) {
const priorReadsEverything = prior.sql !== undefined && viewReadsEveryColumn(prior.sql);
for (const [t, cols] of alteredTables) {
- if (tracked.includes(t) || !liveViewReadsTable(prior, liveName(t))) continue;
+ if (tracked.includes(t) || tables.includes(t) || !liveViewReadsTable(prior, liveName(t))) continue;
if (cols === null || prior.sql === undefined || viewReadsAnyColumn(prior.sql, cols, priorReadsEverything)) {
tables.push(t);
}
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..e72d422196
--- /dev/null
+++ b/server/typescript/packages/migrate-ts/test/unit/diff-view-star-add-column.test.ts
@@ -0,0 +1,58 @@
+/**
+ * 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 until it is recreated. The
+ * migration that adds the column must recreate it, or every database built from the chain
+ * differs from the shadow database `verify --db` builds, and no plan clears the drift.
+ */
+import { test, expect, describe } from "bun:test";
+import { diff } from "../../src/diff/index.js";
+import { viewFingerprint } from "../../src/view-fingerprint.js";
+import type { ColumnDescriptor, Dialect, 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 recreates a `*` view over the table (Postgres)", () => {
+ const dialect: Dialect = "postgres";
+ const star = "SELECT o.* FROM orders o";
+ const named = "SELECT o.id, o.status FROM orders o";
+
+ test("alias.* view is dropped and recreated with the migration", async () => {
+ const r = await diff(
+ snap(table([ID, STATUS, EXTRA]), view(star)), snap(table([ID, STATUS]), view(star)), { dialect },
+ );
+ expect(kinds(r)).toEqual(expect.arrayContaining(["add-column", "drop-view", "create-view"]));
+ });
+
+ test("a view naming its columns is left alone", async () => {
+ const r = await diff(
+ snap(table([ID, STATUS, EXTRA]), view(named)), snap(table([ID, STATUS]), view(named)), { dialect },
+ );
+ expect(kinds(r)).toEqual(["add-column"]);
+ });
+
+ test("count(*) does not count as selecting every column", async () => {
+ const body = "SELECT count(*) AS n FROM orders o";
+ const r = await diff(
+ snap(table([ID, STATUS, EXTRA]), view(body)), snap(table([ID, STATUS]), view(body)), { dialect },
+ );
+ expect(kinds(r)).toEqual(["add-column"]);
+ });
+
+ test("SQLite is unaffected (it expands * at query time)", async () => {
+ const r = await diff(
+ snap(table([ID, STATUS, EXTRA]), view(star)), snap(table([ID, STATUS]), view(star)), { dialect: "sqlite" },
+ );
+ expect(kinds(r)).toEqual(["add-column"]);
+ });
+});
diff --git a/spec/code-writer.md b/spec/code-writer.md
index ba95873d70..14932ec483 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` 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
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..a1988d2662 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[@]}"
+}
+
scan() { # scan