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 + `.md` per object under the docs target). `meta init --with-docs` now wires + `docsSiteFile()` and `apiDocsFile()`. `apiDocsFile({ modelSurface })` now defaults to `false` + (it used to follow whether `docsFile()` ran); `modelBaseUrl` is unchanged. The engine exports + `buildEntityDocData`, `buildTemplateDocData`, `renderMermaidErBlock`, the `EntityDocData` / + `TemplateDocData` types and `DocsApiSurface` / `ApiSurface` are removed with it. The metamodel + index page (every port) now says your entities are documented by the model explorer: a + one-sentence documentation change in `meta gen` output for projects that list `metamodel-docs`. + +- **Python: every generator writes through the code writer, and codegen no longer runs `ruff`** + (ADR-0063). The router and the last nine emitters (extractor, output parser, trace helper, + render helper, names, requirement tests, API docs and the extract delegate and schema emitters) + now lay out their files with `PyWriter`, so generated bytes no longer depend on whether `ruff` is + installed or on its version. The output changes in layout only: a line longer than 88 columns + breaks its last bracketed list, and imports are grouped `__future__`, absolute, then relative, + each in code-point order. Checked against a capture of every emitted file: same syntax tree, + comments and docstrings. One fix rides along: an unresolved `@objectRef` mapper argument used + to put its comma inside the trailing comment, which was a syntax error; it is now + `x=None, # unresolved @objectRef`. Generated-output change — regenerate to pick it up; + three-way merge preserves hand edits. + + Removed: the deprecated module aliases added in 1.1.0. An import of an old path now fails with + `ImportError` (or its subclass `ModuleNotFoundError`, depending on the import form); import + from the new path instead: + `metaobjects.codegen.extract_delegate_emitter` is `metaobjects.codegen.runtime.extract_delegate_emitter`, + `metaobjects.codegen.extract_schema_emitter` is `metaobjects.codegen.runtime.extract_schema_emitter`, + `metaobjects.codegen.fr010_field_mapping` is `metaobjects.codegen.runtime.fr010_field_mapping`, + `metaobjects.codegen.output_format_spec_emitter` is `metaobjects.codegen.runtime.output_format_spec_emitter`, + `metaobjects.codegen.generators.fr019_shared_enum` is `metaobjects.codegen.runtime.fr019_shared_enum`, + `metaobjects.codegen.generators.m2m_codegen` is `metaobjects.codegen.runtime.m2m_codegen`, + `metaobjects.apidocs.api_model` is `metaobjects.codegen.runtime.api_docs_model`, + `metaobjects.apidocs.builder` is `metaobjects.codegen.runtime.api_docs_builder`, + `metaobjects.apidocs.renderer` is `metaobjects.codegen.runtime.api_docs_renderer` and + `metaobjects.apidocs.paths` is `metaobjects.codegen.runtime.api_docs_paths`. The + `metaobjects.apidocs` package and `metaobjects.apidocs.naming` stay. An owned copy ejected + before 1.1.0 that still imports an old path needs its imports changed, or re-eject it. For + `output-parser`, changing the imports is not enough, because that copy calls the removed + `nested_mirror_dataclasses`, `nested_mappers` and `delegate_helpers`: re-eject it, or move it to + `write_nested_mirror_dataclasses`, `write_nested_mappers` and `write_delegate_helpers`. + +- **Java: the `entity` generator writes through the Java code writer, and the `mustache` + generator is removed** (ADR-0063). `JavaObjectCodeGenerator`'s four writers + (`BaseObjectCodeWriter`, `JavaCodeWriter`, `PojoAwareCodeWriter`, `ValueObjectCodeWriter`) now + write lines and blocks on `JavaWriter` instead of printing through an indentor. The output + changes in layout only: no trailing whitespace, no blank line straight after a class opens or + before it closes, and a one-sentence Javadoc fits on one line. Checked against a capture of + the interface, `pojoAware` and `valueObject` flavors over the fitness corpus: identical with + whitespace ignored, apart from that one Javadoc. The layout ratchet gains an `indented-print` + rule (`println(true, ...)`), the call that typed indentation without a literal and let this + family go unseen. Generated-output change — regenerate to pick it up; three-way merge + preserves hand edits. + + The deprecated `mustache` generator (`MustacheTemplateGenerator`) and its module + `metaobjects-codegen-mustache` are removed; `template` (`TemplateScopeGenerator`, in + `codegen-base`) replaces them. A pom that still names `MustacheTemplateGenerator` fails the build + with a `ClassNotFoundException`. + + The deprecated shims in the documentation generators are removed too: the attribute-name + constants and `register*Attributes` methods on `MetaDataAIDocumentationGenerator` and + `MetaDataFileJsonSchemaGenerator` (use the same names on `CodeGenMetaDataProvider`), + `MetaDataFileSchemaWriter.addConstraintFile` (a no-op since registry-based discovery), and the + old `SingleHtmlDirectGeneratorBase.writeHtml(MetaDataHtmlDocumentationWriter)` hook (override + `writeHtml(HtmlDirectWriter)`). + + So are the 1.0.x forwarding shims in `codegen-spring`. The static field and annotation helpers + on `SpringDtoGenerator` (`settableFields`, `scalarFields`, `dtoComponentFields`, + `valueObjectJsonbFields`, `valueObjectMapFields`, `isValueObjectJsonbField`, `componentType`, + `isRequired`, `originGuaranteedNonNull`, `validationAnnotations`, `sizeAnnotation`, `attrBool`, + `attrInt`, `hasValidator`, `escapeJavaString`) and on `SpringRepositoryGenerator` + (`m2mFinderName`, `m2mFinderNameForSubtype`, `targetSubtypeParam`) are gone: call the same name + on `SpringGeneratorSupport`, and `SpringGeneratorSupport.repositoryAppliesTo` for + `SpringRepositoryGenerator.appliesTo`. The `AutoSetSupport` selectors `stampFields`, + `onUpdateFields`, `hasAutoSetFields` and `hasOnUpdateFields` move the same way, to + `SpringGeneratorSupport`. + +- **C#: the obsolete codegen shims are removed.** `ValueObjectNames.Names` (marked `[Obsolete]`; + use `ValueObjectNames.TypeName`) and the string-building forms of `XmlDocBuilder` (`AppendTo`, + `Indent`, `Prepend`; use `WriteTo` with the code writer) are gone. Generated output is unchanged. + +- **The `meta` CLI installs 12 MB smaller** (34.6 MB, from 46.6 MB): it no longer depends on + `@biomejs/js-api` and `@biomejs/wasm-nodejs`, and `docs-site` no longer depends on `yaml`. + +- **Repository: Bun 1.3.14 is the declared package manager.** The root `package.json` now + declares `bun@1.3.14`, the version every workflow pins, in place of 1.3.8 (which segfaults on + exit). Rebuilding or checking the explorer app (`server/typescript/packages/docs-site/scripts/build-app.ts`, + the `explorer app copies` gate and its unit test) requires that exact version, because the + committed bundle is minified and minified output follows the Bun version; any other Bun stops + with an error naming 1.3.14. - **The agent pages sort in code-unit order.** `agent/requirements.md` (its node index and statements) and `agent/schema.md` (its tables and views) sorted names with `localeCompare`, whose collation differs between machines and could not be matched exactly by another port. @@ -3035,6 +3517,121 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru ### Fixed +- **TypeScript: the service generators no longer import an entity module nobody wrote.** When the + filter of `serviceFile()`, `serviceRoutesFile()` or `serviceRoutesHonoFile()` admitted an object + (a projection, typically) that `entityFile()`'s filter left out, the output imported a module + that did not exist (`TS2307`). The run now tells generators which objects the entity-module + generator emits; the service generators skip the rest with a warning that names the object and + both remedies (widen `entityFile()`'s filter, or narrow the service filter). Owned copies pick it + up when re-ejected. + +- **The first `meta gen` over a 1.2 tree no longer warns that `.gen-state/.hashes` is + git-ignored.** That run migrates the hash manifest and rewrites `.metaobjects/.gitignore` to + un-ignore the new directory, but the advisory was asked before the rewrite and reported the rule + the run had just removed. It is asked after the run's writes, so it fires only for a rule the run + does not own (one in the root `.gitignore`, say). + +- **Filtering generators by package is documented.** `obj.package` is the package a node declares + itself, so it is `undefined` for every object in a file whose package is on `"metadata.root"`, + and `filter: (e) => e.package === "acme::tasks"` matched nothing. Filter on + `effectivePackage(e)` (`@metaobjectsdev/codegen-ts`, or `effectivePackageOf` from + `@metaobjectsdev/metadata`), which resolves the file's package too; the generator recipe and the + getter's doc say so. + +- **`meta gen` trusts the committed `.hashes.json` over a stale ignored `.hashes/`** (every port). + The scaffold's 1.2 `.gitignore` ignores `.gen-state/.hashes/`, so a directory written by an + earlier 1.3 run (another checkout, a candidate you tried and reset) survives a reset, a clean and + a branch switch beside the committed `.hashes.json`. The reader merged it on top, so every file + the committed manifest vouched for read as hand-edited: `gen` reported "N merged", kept the old + output and exited 0, and `verify --codegen` failed only the names artifacts. While `.hashes.json` + is present it is now the whole manifest, and the migrating write replaces the stale files + (ADR-0064 §2, corrected). + +- **`meta gen` and `meta verify --codegen` refuse emitted TypeScript that does not parse.** Gen, + the zero-write regen and the drift gate compare text, so a generator that emitted a file + declaring `import { z } from "zod"` twice (an owned 1.2 entity composer joining the engine's + fragments with ts-poet's `joinCode`) passed all three and the adopter's build was the first to + object. Every emitted `.ts`, `.tsx`, `.mts` and `.cts` file is now parsed before anything is + written, with the parser `jiti` already carries for the config file, and a file that fails is + named with its generator, line and message; nothing from the run is written. The refusal of a + generator carrying a marker 1.3.0 removed now names every such generator at once instead of + one per run. + +- **Python: `metaobjects gen` and `metaobjects verify` refuse generated Python that does not + compile; the code writer refuses indented text in every port.** An `EntityModelGenerator` subclass written to the 1.2 hook contract returned members + carrying their own four-space indent; the code writer indents members itself, so those members + sat one level deeper than the rest and the module raised `IndentationError` on import, while + `gen` exited 0 and `verify --codegen` reported the tree in sync. The entity generator now refuses + such a member with `ERR_WRITER_LEADING_WHITESPACE`, naming the subclass and the contract, and + every emitted `.py` file (a template-spec output named `.py` included) is compiled in memory + before it is written or compared: one that does not compile fails the target, names the file, + the line and the generator, and nothing from that target is written. + +- **`meta verify --db` names a `SELECT *` view's drift, and `meta migrate` stops creating it.** A + hand-written `@sql` view that selects `*` or `alias.*` keeps the column list Postgres expanded + when the view was created, so a later migration that added a column to its base table left every + database built from the chain with the narrow expansion, and `verify --db` (which builds a fresh + shadow database) reported it as a drop plus a create that `meta migrate` never planned. On + Postgres, `meta migrate` now drops and recreates such a view in the migration that adds a column + to a table it reads, and `verify --db` shows a changed view as one `~` entry and says the cause: + the view selects `*` and a table it reads gained columns since; recreate the view, or list its + columns. A database that already holds the narrow expansion clears with the drop and create that + `meta migrate --from-db` plans. + +- **Prerelease tooling.** `tools/prerelease/detect-prerelease-pins.sh` (run by + `prerelease-link.sh unlink`) no longer prints the private registry's host in the lockfile lines + it reports. `unlink` without `--to` restores the pins the project had before `link`, recorded by + `link` outside the work tree, instead of the latest public release, and its reconcile hint is + one command per lockfile directory (`(cd sub && bun install)`) instead of `bun install npm + install`. `estate-run.sh` restores the ignored `.metaobjects/.gen-state` files a candidate wrote, + which used to survive the restore and make the next run read the candidate's hash manifest, and + no longer reports unlink's lockfile check as a failure. A full candidate (`--only all`) refuses + to cut while `changelog.d/` holds fragments beside a prepared release section. + +- **TypeScript: generated CRUD routes address a key not named `id`.** `mountCrudRoutes` (Fastify + and Hono) took the primary key to be the `id` column, so an entity keyed on a natural `code` + or an int `rank` answered every item route (`GET`/`PATCH`/`PUT`/`DELETE /:id`, and the create + re-read on MySQL) with a 500. The mounts take an `idColumn` option, and the generated routes + pass it when the key field has another name. Generated-output change for such entities only: + one `idColumn: "",` line in the mount call; regenerate to pick it up. + +- **Java and Kotlin: generated controllers serve uuid, string and int primary keys**, gated by the + shared `key-types` api-contract corpus in both generated lanes. The Kotlin controller now writes + an assigned primary key (no `@generation`, no `@default`) from the request body on create, + where it skipped the column and the insert failed `NOT NULL`, and a TPH subtype create that + omits it is a 400 (`invalid_type` on the key); increment and generated-uuid keys are unchanged. Generated-output change for assigned-key entities only. + +- **Java: the entity generator qualifies same-named types from two packages.** A file referencing + two value objects named alike in different metadata packages writes each fully qualified, where + it refused the model with `ERR_WRITER_IMPORT_CONFLICT`. Java, Kotlin and Python now run the + `xpkg-value-object-refs` codegen corpus. `KotlinApiDocsRenderer` moved onto `KotlinWriter`, + with byte-identical output. + +- **Python: the loader enforces the rc.21 view vocabulary.** `origin.function` signature and + identifier rules, dotted-path references in `origin.computed` and in an `origin.first` + `@filter`, a scalar `origin.aggregate` read from a computed field, passthrough from a `@grain` + value object and derived-field cycle detection now load and fail as they do in TypeScript and + C#. The two ledgered fixtures (`error-origin-function-free-sql`, + `projection-view-vocabulary-rc21`) pass, and the Python expected-failures ledger is empty. A + bare `@from` or base head on a projection now resolves in the file's default package. The + `xpkg-value-object-refs` codegen corpus and the generated `key-types` api-contract lane now run + in Python. + +- **The explorer app's bundle builds the same bytes every time.** `explorer-app/assets/explorer-app.js` + is now minified for whitespace and syntax only, and keeps its identifiers' names. Bun's choice of + short names was not stable between builds of unchanged sources, so the check that the committed + bundle is what the sources build failed at random. The bundle grows from about 95 KB to about + 120 KB. Every port's copy is refreshed, so the docs site's `assets/explorer-app.js` changes and + nothing else does. Generated-output change — regenerate to pick it up; three-way merge preserves + hand edits. + +- **CI: the Rust publish dry-run no longer verifies against stale source.** `cargo publish + --workspace` unpacks the crates it depends on from its temporary overlay registry into a + directory fixed per checkout, and never unpacks them again while the version is unchanged, so a + machine that had run the gate before a new module landed compiled the old `metaobjects-1.3.0` + and failed with "could not find `metamodel_docs`". The gate now first clears unpacked copies of + the workspace's own crates that differ from the tree + (`scripts/rust-clear-stale-publish-sources.sh`). - **codegen-ts-angular: the generated form binds its controls.** Each control in `.form.component.ts` read `[formControlName]=""email""`, a binding whose quoted expression was cut short by the attribute's own quotes, so Angular bound no control. It now @@ -3275,8 +3872,10 @@ four `rules.*` and `verify.lifecycle.unreachable` settings, held to `fixtures/ru literal ("invalid input syntax for type uuid"); `coerceIdForColumn` now rejects it, so GET, PATCH and DELETE answer 400 `{"error":"invalid_id"}` as a malformed numeric id already did. A `field.uuid` in the generated insert and update Zod schemas now checks the 8-4-4-4-12 shape, so - a malformed uuid foreign key in a POST or PATCH body answers 400 `validation`. SQLite stores a - uuid as text, so none of this showed there; a new integration test runs the stock + a malformed uuid foreign key in a POST or PATCH body answers 400 `validation`. The body check + is in the Zod schema, so it applies on every dialect: on SQLite and D1, which store a uuid as + text and never refused a malformed one, a body value that is not 8-4-4-4-12 is a new 400 (see + "Upgrading from 1.2.0"); the `:id` check runs only on a uuid column. A new integration test runs the stock `routesFile()` output against Postgres with uuid keys and a uuid foreign key. Owned copies pick the fix up when re-ejected. - **`meta migrate` warns when a renamed column is still named by a view.** A rename never diff --git a/changelog.d/agent-docs-native-every-port.md b/changelog.d/agent-docs-native-every-port.md deleted file mode 100644 index 217fe236ca..0000000000 --- a/changelog.d/agent-docs-native-every-port.md +++ /dev/null @@ -1,21 +0,0 @@ -- **`agent-docs` writes the agent files natively in C#, Java, Kotlin and Rust, with no Node.** - `dotnet meta agent-docs`, `mvn metaobjects:agent-docs` (Java and Kotlin) and the new - `cargo meta agent-docs` write `.metaobjects/AGENTS.md`, the `metaobjects-*` skills, the - `.metaobjects/.agent-context.json` manifest and the root `AGENTS.md` / `CLAUDE.md` import, byte - for byte what `meta agent-docs` and Python's `metaobjects agent-docs` write. Before, the C# and - Maven commands printed "run `npx meta agent-docs`" and exited 1, and Rust had no command. Each - copies one stack out of the built `agent-context-shipped/` tree it carries (C# and the Maven - plugin embed it at build time; the Rust crate, like the Python wheel, keeps a committed copy - that `scripts/sync-agent-context-shipped.sh` refreshes, renamed from - `sync-python-agent-context.sh`, and the `gates` lane fails when either copy is stale). The - flags are `--server`, `--client`, `--out` and `--no-wire-root` - (`-Dmetaobjects.servers`/`clients`/`outputDirectory`/`wireRoot` on Maven); with none, the - stack the last run recorded, else the port's own language. The re-run rules are the Node - CLI's: an unchanged file is not rewritten, a hand-edited one gets `.new`, an untouched - orphan is pruned. The Maven goal stamps the npm-line version (`8.3.0` writes `v1.3.0` links - and a `1.3.0` manifest), so the staleness check stays quiet after a native run. The `gen` - and `verify` staleness nudge in C# and Java now names the port's own command. Every port's - tests reproduce every `fixtures/agent-context-conformance/` stack, not only their own, so the - corpus is a cross-port gate. The shipped C#, Java and Kotlin skill references now tell an - agent to run the port's command instead of `npx meta agent-docs`; refresh the agent files to - pick that up. diff --git a/changelog.d/agent-pages-every-port.md b/changelog.d/agent-pages-every-port.md deleted file mode 100644 index be59f2b06c..0000000000 --- a/changelog.d/agent-pages-every-port.md +++ /dev/null @@ -1,32 +0,0 @@ -- **The agent pages in every port, from the docs view.** `requirements.toon`, - `agent/requirements.md` and the model-only `agent/schema.md` are now written by C#, Java, - Kotlin, Python, Rust and TypeScript alike: each port's `requirements` and `agent-docs` - generators build the page data from its own docs view and render the shared - `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what - `fixtures/docs-page-conformance/` pins. A TypeScript project with no dialect now gets the - model-only `agent/schema.md` too (it used to get no schema page); with a dialect it keeps the - physical page. `agent/schema.md` documents the project's own storage in every port: a - dependency's object that `scope.include` does not name is left out of its tables, views, - relationships and enums (Rust loads no dependency, and leaves out a reference node). The - TypeScript physical page used to list an imported table too. `agent/ui.md` stays - TypeScript's. Rust has no requirement ledger of its own yet, so its pages list every - requirement the view carries, an uninherited import's included. - - The docs view gains a `storage` section (`docs/features/docs-view.md`): every table and view - the model stores into, its columns (names from the port's naming helpers, each linked to its - field), keys and foreign keys. The physical facts (SQL types, defaults, indexes, checks, - constraint names and actions) are `null` outside a TypeScript run with a dialect, which fills - them. `explorer.json` carries the new key in every port. - - **Retired: the human `requirements.md` page.** The `requirements` generator writes only - `requirements.toon`; people read the ledger in the explorer (`docs-site`), and agents read it - embedded in `agent/requirements.md`. Upgrading: the next `gen` no longer writes - `requirements.md`; delete the committed copy (and its `.hashes/` entry goes with the run). - - **The always-on agent file points at the agent pages, only when they exist.** `meta init` - (and `--refresh-docs`) and every port's `agent-docs` command (`meta`, `metaobjects`, - `dotnet meta`, `mvn metaobjects:`, `cargo meta`) now add a "Pages - generated for this project" section to `.metaobjects/AGENTS.md`, naming each agent page the - project's last `gen` wrote (read from the committed `.metaobjects/.gen-state/.hashes/`) and - when to read it. A project that wires none of them gets the file unchanged. Refresh the agent - files after wiring `agent-docs`, `api-docs` or `requirements` for the first time. diff --git a/changelog.d/bun-1-3-14-package-manager.md b/changelog.d/bun-1-3-14-package-manager.md deleted file mode 100644 index 1958f0fcb1..0000000000 --- a/changelog.d/bun-1-3-14-package-manager.md +++ /dev/null @@ -1,6 +0,0 @@ -- **Repository: Bun 1.3.14 is the declared package manager.** The root `package.json` now - declares `bun@1.3.14`, the version every workflow pins, in place of 1.3.8 (which segfaults on - exit). Rebuilding or checking the explorer app (`server/typescript/packages/docs-site/scripts/build-app.ts`, - the `explorer app copies` gate and its unit test) requires that exact version, because the - committed bundle is minified and minified output follows the Bun version; any other Bun stops - with an error naming 1.3.14. diff --git a/changelog.d/classic-docs-site-removed.md b/changelog.d/classic-docs-site-removed.md deleted file mode 100644 index c825fb2f65..0000000000 --- a/changelog.d/classic-docs-site-removed.md +++ /dev/null @@ -1,7 +0,0 @@ -- **Breaking — the classic docs site is removed (TypeScript).** `docsSiteFile({ site: "classic" })` - now throws and points to the explorer (`docsSiteFile()`); an owned classic theme under - `codegen/docs-site/` is refused with an instruction to delete it and re-run - `meta eject docs-site`. `@metaobjectsdev/docs-site` no longer exports `generateSite`, - `DEFAULT_ASSET_BASE`, `SiteOptions`, `SiteResult`, `CLASSIC_TEMPLATE_NAMES` or - `CLASSIC_ASSET_NAMES`, and `meta eject docs-site` copies the explorer theme only. The - explorer's output is unchanged. diff --git a/changelog.d/cli-install-smaller.md b/changelog.d/cli-install-smaller.md deleted file mode 100644 index ab30b2ed74..0000000000 --- a/changelog.d/cli-install-smaller.md +++ /dev/null @@ -1,2 +0,0 @@ -- **The `meta` CLI installs 12 MB smaller** (34.6 MB, from 46.6 MB): it no longer depends on - `@biomejs/js-api` and `@biomejs/wasm-nodejs`, and `docs-site` no longer depends on `yaml`. diff --git a/changelog.d/csharp-codegen-shims-removed.md b/changelog.d/csharp-codegen-shims-removed.md deleted file mode 100644 index 7c7cdb4c80..0000000000 --- a/changelog.d/csharp-codegen-shims-removed.md +++ /dev/null @@ -1,3 +0,0 @@ -- **C#: the obsolete codegen shims are removed.** `ValueObjectNames.Names` (marked `[Obsolete]`; - use `ValueObjectNames.TypeName`) and the string-building forms of `XmlDocBuilder` (`AppendTo`, - `Indent`, `Prepend`; use `WriteTo` with the code writer) are gone. Generated output is unchanged. diff --git a/changelog.d/docs-markdown-generator-removed.md b/changelog.d/docs-markdown-generator-removed.md deleted file mode 100644 index 8fc8e1f7c8..0000000000 --- a/changelog.d/docs-markdown-generator-removed.md +++ /dev/null @@ -1,13 +0,0 @@ -- **Breaking — the docs Markdown generator is removed (TypeScript).** `docsFile()` and the - stable name `"docs"` (a Markdown page per object, the `README.md` overview with the ER diagram, - and the `apiSurfaces` option) are gone. The model explorer (`docsSiteFile()`, `"docs-site"`) is - the model's documentation for people, and `agentDocsFile()` (`"agent-docs"`) for a coding agent. - A config that still lists `"docs"` or imports `docsFile` makes `meta gen` fail with a message - that names the removal and the replacement; delete the pages it wrote (`README.md` and one - `.md` per object under the docs target). `meta init --with-docs` now wires - `docsSiteFile()` and `apiDocsFile()`. `apiDocsFile({ modelSurface })` now defaults to `false` - (it used to follow whether `docsFile()` ran); `modelBaseUrl` is unchanged. The engine exports - `buildEntityDocData`, `buildTemplateDocData`, `renderMermaidErBlock`, the `EntityDocData` / - `TemplateDocData` types and `DocsApiSurface` / `ApiSurface` are removed with it. The metamodel - index page (every port) now says your entities are documented by the model explorer: a - one-sentence documentation change in `meta gen` output for projects that list `metamodel-docs`. diff --git a/changelog.d/explorer-3d-map.md b/changelog.d/explorer-3d-map.md deleted file mode 100644 index fdb55c8545..0000000000 --- a/changelog.d/explorer-3d-map.md +++ /dev/null @@ -1,9 +0,0 @@ -- **docs-site: a 3D model map.** The explorer's map has a **View** control that switches - between the flat map and a 3D one drawn from the same nodes, edges, slice and colouring - (`#/map.html?view=3d`); click a node for the side panel and again to open its page. The 3D - library, 3d-force-graph 1.77.0 (MIT, bundling three.js; the licences of everything it bundles - head the file), ships with the site as `assets/3d-force-graph.min.js` and loads only when a - reader first chooses 3D, so it works offline and no other page pays for its size. A static - export given an `assetBase` loads it from the mirror instead. An owned - `explorer-map.html.mustache` without the control simply has no 3D mode. Generated-output - change — regenerate to pick it up; three-way merge preserves hand edits. diff --git a/changelog.d/explorer-app-stable-bundle.md b/changelog.d/explorer-app-stable-bundle.md deleted file mode 100644 index 34ea61646b..0000000000 --- a/changelog.d/explorer-app-stable-bundle.md +++ /dev/null @@ -1,7 +0,0 @@ -- **The explorer app's bundle builds the same bytes every time.** `explorer-app/assets/explorer-app.js` - is now minified for whitespace and syntax only, and keeps its identifiers' names. Bun's choice of - short names was not stable between builds of unchanged sources, so the check that the committed - bundle is what the sources build failed at random. The bundle grows from about 95 KB to about - 120 KB. Every port's copy is refreshed, so the docs site's `assets/explorer-app.js` changes and - nothing else does. Generated-output change — regenerate to pick it up; three-way merge preserves - hand edits. diff --git a/changelog.d/explorer-app.md b/changelog.d/explorer-app.md deleted file mode 100644 index 2536a21b47..0000000000 --- a/changelog.d/explorer-app.md +++ /dev/null @@ -1,21 +0,0 @@ -- **docs-site: the model explorer is one browser app.** `docsSiteFile()` now writes the - explorer as a few files (a shell, the app, the theme, Cytoscape and three data files: - `explorer.json`, `explorer-model.js`, `explorer-stamp.js`) in place of a page per screen. - The app draws every page when it is visited, with the same page code and templates, so each - page is byte-for-byte the one the static site wrote. It runs from `file://` with no server, - addresses each page as `index.html#/`, and follows the model while it is open: it polls - the stamp file about once a second and draws the current page again when `meta gen` rewrites - the model. Cytoscape 3.30.2 (MIT) ships with the site, so the graphs draw offline and the - CDN notice is gone. `docsSiteFile({ output: "static" })` (and `generateExplorerSite({ output: - "static" })`) writes the earlier page-per-screen site from the same code, for publishing - without scripts or for Pagefind; `assetBase` now applies to that export only, which given one - loads Cytoscape from it and ships no copy. The app's files live once at `explorer-app/` and - in every port's package (`scripts/sync-explorer-app.sh`, gated by `explorer app copies`); - the other ports' docs-site generators are still to write them. Generated-output change: the - next `meta gen` replaces the explorer's pages with the app's files, and `meta verify - --codegen` holds the new files to the model as before. - If you ejected the theme on a 1.3.0 candidate, your `codegen/docs-site/assets/explorer.js` - predates the app, which calls `window.MO_THEME` each time it draws a page: without that hook - search, the theme toggle and the graphs do nothing. Copy it again with `meta eject docs-site - --force` and carry your edits into the new copy (the app also needs its `window.MO_APP` link, - query and listener hooks, so adding the one line is not enough). diff --git a/changelog.d/explorer-csharp-python.md b/changelog.d/explorer-csharp-python.md deleted file mode 100644 index 203a179c20..0000000000 --- a/changelog.d/explorer-csharp-python.md +++ /dev/null @@ -1,13 +0,0 @@ -- **C# and Python: the model explorer with no Node.** Both ports build the docs view from their - loaded model (`MetaObjects.DocsView` in C#, `metaobjects.docs_view` in Python), byte for byte - what TypeScript builds for every `fixtures/explorer-conformance/` case. A new `docs-site` - generator in each registry (`DocsSiteGenerator` in `codegen/Generators.cs`; `docs-site` in a - Python target's `generators`) writes `explorer.json`, the explorer app, `explorer-model.js` - and `explorer-stamp.js`. Each object lists the files generated for it: this run's (the runner - runs the generator after every other one) and the committed manifest's outside the directories - the run's orphan sweep clears, so `verify --codegen` renders what `gen` wrote. Options name a - `verify --format json` payload and a routes file. The running application can serve the same - view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.MetaDocs(root)` (C#) and `meta_docs(root)` - (Python) build it once and carry its ETag; the host mounts it as it mounts `/_meta`. - C# and Python provenance now names a generator by its registry name (`entity`, - `filter-allowlist`, `routes`), as TypeScript and the JVM do. diff --git a/changelog.d/explorer-jvm.md b/changelog.d/explorer-jvm.md deleted file mode 100644 index 374709d7da..0000000000 --- a/changelog.d/explorer-jvm.md +++ /dev/null @@ -1,12 +0,0 @@ -- **Java and Kotlin: the model explorer with no Node.** The JVM builds the docs view from its - loaded model (`com.metaobjects.docsview.DocsView`), byte for byte what TypeScript builds for - every `fixtures/explorer-conformance/` case. A new `docs-site` generator - (`com.metaobjects.generator.DocsSiteGenerator`, in both the Java and Kotlin registries) writes - `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js`; each object - lists the files generated for it: this execution's (it builds the site after every other - generator it runs) and the committed manifest's for the module's other executions, so - `metaobjects:verify` renders what `generate` wrote. Optional args name a - `verify --format json` payload (`verifyFile`) and the routes (`routesFile`). The running - application can serve the same view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.docs(root)` - builds it once and carries its ETag, and the host mounts it as it mounts `/_meta`. The static - export and the classic site stay TypeScript's. diff --git a/changelog.d/explorer-live-source.md b/changelog.d/explorer-live-source.md deleted file mode 100644 index d87befbc62..0000000000 --- a/changelog.d/explorer-live-source.md +++ /dev/null @@ -1,10 +0,0 @@ -- **runtime-ts: `GET {apiPrefix}/_meta/docs` serves the loaded model's docs view, and the - explorer follows it.** New `mountMetaDocsRoute` (Fastify) and `mountMetaDocsRouteHono` mount - it beside `/_meta`, opt-in and guarded the same way, with `META_DOCS_ROUTE_PATH` and - `metaDocsJson(root, { routes })` for other hosts. The response carries an ETag and answers a - matching `If-None-Match` with `304`; `allowOrigin` opts in to cross-origin reads. Open the - explorer app as `index.html?source=` and it reads the running application's model - instead of the generated file, once a second, drawing the open page again when the - application restarts on a changed model. The route's shape is a cross-port contract - (`docs/features/metadata-api.md`); the other ports serve it once they have their docs view - builders. diff --git a/changelog.d/explorer-rust.md b/changelog.d/explorer-rust.md deleted file mode 100644 index ef1a3eee7c..0000000000 --- a/changelog.d/explorer-rust.md +++ /dev/null @@ -1,23 +0,0 @@ -- **Rust: the model explorer with no Node.** The Rust port builds the docs view from its loaded - model (`metaobjects::docs_view::build`), byte for byte what TypeScript builds for every - `fixtures/explorer-conformance/` case. A new opt-in `docs-site` generator writes - `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js` under - `site/`. It reads prompt texts from the metadata directories, `templates/` and a `prompts` - directory, and takes `subDir`, `title`, `stamp`, `verifyFile` and `routesFile` as options. - Each node lists the files generated for it: this run's (the engine runs the site after every - other generator) and the committed manifest's outside the run, so `cargo meta verify` renders - what `gen` wrote. The site builder is engine, as in every port: `cargo meta eject docs-site` - refuses, `gen --list` marks it `[package-only]`, and an owned theme in `codegen/docs-site/` - replaces the shipped one. The app files are a canonical copy in the crate - (`metaobjects-codegen/explorer-app/`, held to the root `explorer-app/` by the - `explorer app copies` gate) and ship in the published package. The running application can serve - the same view at `{apiPrefix}/_meta/docs`: `metaobjects::meta_endpoint::docs` builds it once and - carries its ETag, and the host mounts it as it mounts `/_meta` (`meta_endpoint::meta_json`, - new in Rust too). - - Rust codegen now also records which node each generated file came from, `{ "hash", - "generatedBy", "sourceNode" }` in the hash manifest, held to the shared `provenance` vector in - `fixtures/codegen-skip-conformance/manifests.json`. A file rendered for no single node, such as - a shared `meta_*` crate's, keeps the plain hash. Upgrading: the next `cargo meta gen` rewrites - the committed `.metaobjects/.gen-state/.hashes/` files once. Commit them; generated source - files do not change. diff --git a/changelog.d/format-ts-and-owned-copy-biome-removed.md b/changelog.d/format-ts-and-owned-copy-biome-removed.md deleted file mode 100644 index 977fe422f1..0000000000 --- a/changelog.d/format-ts-and-owned-copy-biome-removed.md +++ /dev/null @@ -1,7 +0,0 @@ -- **Breaking — `formatTs` and the Biome owned-copy comparison are removed (TypeScript).** The - no-op `formatTs` export, kept so an owned 1.2 generator copy still loaded, is gone: generation - runs no formatter, and a copy that wants one calls its own. `meta eject`'s owned-copy report no - longer loads Biome's WebAssembly build: it compares the copy and the reference line by line, - trimmed, ignoring trailing commas, blank lines and import order. A copy re-wrapped by your own - formatter (lines joined or split) now reads `differs` where it read `reformatted`. - `@metaobjectsdev/cli` drops its `@biomejs/js-api` and `@biomejs/wasm-nodejs` dependencies. diff --git a/changelog.d/generated-file-provenance-all-ports.md b/changelog.d/generated-file-provenance-all-ports.md deleted file mode 100644 index 7045ab47ca..0000000000 --- a/changelog.d/generated-file-provenance-all-ports.md +++ /dev/null @@ -1,10 +0,0 @@ -- **C#, Java and Python codegen record which node each generated file came from.** After a write - run, the hash manifest entry of a per-object file names its generator and the node's resolution - key, `{ "hash", "generatedBy", "sourceNode" }` (after the JVM's `generator` and `outputDir`), - exactly as TypeScript already wrote it. A docs view built from any of these ports' manifests now - lists each node's generated files, so the explorer's "generated files" panel is filled. A file - rendered from the whole model or a package keeps the plain hash. The shared `provenance` vector in - `fixtures/codegen-skip-conformance/manifests.json` holds all four ports to the same entries. - - Upgrading: the next `gen` rewrites the committed `.metaobjects/.gen-state/.hashes/` files once, - adding the two fields to each per-object entry. Commit them; generated source files do not change. diff --git a/changelog.d/generator-legacy-markers-removed.md b/changelog.d/generator-legacy-markers-removed.md deleted file mode 100644 index 16ec22656e..0000000000 --- a/changelog.d/generator-legacy-markers-removed.md +++ /dev/null @@ -1,13 +0,0 @@ -- **Breaking — the legacy generator markers are removed, and an owned 1.2 copy is refused - (TypeScript).** `emitsEntityModule`, `emitsQueries`, `emitsNames`, `emitsReportExport`, - `emitsUiTier`, `emitsHonoRoutes`, `mountsRoutes`, `emitsApiDocs` and `emitsModelDocs` (and - `provides.modelDocs`) are gone from `Generator`; the `provides` declaration (ADR-0034 - Amendment 12) is the only way to say what a generator writes. `meta gen` now refuses a - generator that still sets one, naming the marker and its `provides` replacement, instead of - reading it. The name-based fallbacks that treated a copy named `queries-file`, `entity-file`, - `routes-file` or a UI generator's name as providing its tier are removed with them, as is - `UI_TIER_GENERATOR_NAMES`. A copy that carries a shipped generator's name and declares no - `provides` at all (one ejected before the markers) still runs, with one warning naming the - declaration the shipped generator makes (`SHIPPED_PROVIDES_BY_NAME`). Generator - copies ejected in 1.2 or earlier no longer load: re-eject them (`meta eject --force`) or - replace the markers with `provides` by hand. diff --git a/changelog.d/java-entity-writer-mustache-removed.md b/changelog.d/java-entity-writer-mustache-removed.md deleted file mode 100644 index 2b1b600a60..0000000000 --- a/changelog.d/java-entity-writer-mustache-removed.md +++ /dev/null @@ -1,42 +0,0 @@ -- **Java: the `entity` generator writes through the Java code writer, and the `mustache` - generator is removed** (ADR-0063). `JavaObjectCodeGenerator`'s four writers - (`BaseObjectCodeWriter`, `JavaCodeWriter`, `PojoAwareCodeWriter`, `ValueObjectCodeWriter`) now - write lines and blocks on `JavaWriter` instead of printing through an indentor. The output - changes in layout only: no trailing whitespace, no blank line straight after a class opens or - before it closes, and a one-sentence Javadoc fits on one line. Checked against a capture of - the interface, `pojoAware` and `valueObject` flavors over the fitness corpus: identical with - whitespace ignored, apart from that one Javadoc. The layout ratchet gains an `indented-print` - rule (`println(true, ...)`), the call that typed indentation without a literal and let this - family go unseen. Generated-output change — regenerate to pick it up; three-way merge - preserves hand edits. - - The deprecated `mustache` generator (`MustacheTemplateGenerator`) and its module - `metaobjects-codegen-mustache` are removed; `template` (`TemplateScopeGenerator`, in - `codegen-base`) replaces them. A pom that still names `MustacheTemplateGenerator` fails the build - with a `ClassNotFoundException`. - - Upgrading: replace a `MustacheTemplateGenerator` `` with - `com.metaobjects.generator.template.TemplateScopeGenerator` and its args `templatesDir`, - `template`, `scope` and `outputPattern` (docs/features/codegen-concepts.md), and drop any - `metaobjects-codegen-mustache` dependency. An owned copy of the `entity` writers (from - `mvn metaobjects:eject -Dnames=entity`) keeps working as it is; to take the new layout, - re-eject, or write through `out()` (a `CodeWriter`; `java()` in `JavaCodeWriter`) instead of - `println`/`inc`/`dec`, which the entity writers no longer have. - - The deprecated shims in the documentation generators are removed too: the attribute-name - constants and `register*Attributes` methods on `MetaDataAIDocumentationGenerator` and - `MetaDataFileJsonSchemaGenerator` (use the same names on `CodeGenMetaDataProvider`), - `MetaDataFileSchemaWriter.addConstraintFile` (a no-op since registry-based discovery), and the - old `SingleHtmlDirectGeneratorBase.writeHtml(MetaDataHtmlDocumentationWriter)` hook (override - `writeHtml(HtmlDirectWriter)`). - - So are the 1.0.x forwarding shims in `codegen-spring`. The static field and annotation helpers - on `SpringDtoGenerator` (`settableFields`, `scalarFields`, `dtoComponentFields`, - `valueObjectJsonbFields`, `valueObjectMapFields`, `isValueObjectJsonbField`, `componentType`, - `isRequired`, `originGuaranteedNonNull`, `validationAnnotations`, `sizeAnnotation`, `attrBool`, - `attrInt`, `hasValidator`, `escapeJavaString`) and on `SpringRepositoryGenerator` - (`m2mFinderName`, `m2mFinderNameForSubtype`, `targetSubtypeParam`) are gone: call the same name - on `SpringGeneratorSupport`, and `SpringGeneratorSupport.repositoryAppliesTo` for - `SpringRepositoryGenerator.appliesTo`. The `AutoSetSupport` selectors `stampFields`, - `onUpdateFields`, `hasAutoSetFields` and `hasOnUpdateFields` move the same way, to - `SpringGeneratorSupport`. diff --git a/changelog.d/java-xpkg-qualified-names.md b/changelog.d/java-xpkg-qualified-names.md deleted file mode 100644 index 1687db5706..0000000000 --- a/changelog.d/java-xpkg-qualified-names.md +++ /dev/null @@ -1,5 +0,0 @@ -- **Java: the entity generator qualifies same-named types from two packages.** A file referencing - two value objects named alike in different metadata packages writes each fully qualified, where - it refused the model with `ERR_WRITER_IMPORT_CONFLICT`. Java, Kotlin and Python now run the - `xpkg-value-object-refs` codegen corpus. `KotlinApiDocsRenderer` moved onto `KotlinWriter`, - with byte-identical output. diff --git a/changelog.d/jvm-non-long-keys.md b/changelog.d/jvm-non-long-keys.md deleted file mode 100644 index 46b4c36aa3..0000000000 --- a/changelog.d/jvm-non-long-keys.md +++ /dev/null @@ -1,5 +0,0 @@ -- **Java and Kotlin: generated controllers serve uuid, string and int primary keys**, gated by the - shared `key-types` api-contract corpus in both generated lanes. The Kotlin controller now writes - an assigned primary key (no `@generation`, no `@default`) from the request body on create, - where it skipped the column and the insert failed `NOT NULL`, and a TPH subtype create that - omits it is a 400 (`invalid_type` on the key); increment and generated-uuid keys are unchanged. Generated-output change for assigned-key entities only. diff --git a/changelog.d/key-types-api-contract-corpus.md b/changelog.d/key-types-api-contract-corpus.md deleted file mode 100644 index b523f4bc41..0000000000 --- a/changelog.d/key-types-api-contract-corpus.md +++ /dev/null @@ -1,6 +0,0 @@ -- **Conformance: the `key-types/` api-contract sub-corpus.** Generated CRUD for a client-assigned - `field.uuid`, a natural `field.string` and a `field.int` primary key (list, get, 404, create, - patch and delete), run in the generated lane of every port. It found the TypeScript `id`-only - CRUD mounts and a C# defect: a `field.uuid` key's generated routes did not compile (no - `using System;`), and the key type is now spelled `global::System.Guid` in the item routes and - in the M:N traversal routes over uuid junction keys. diff --git a/changelog.d/metamodel-docs-mustache.md b/changelog.d/metamodel-docs-mustache.md deleted file mode 100644 index 1272c17519..0000000000 --- a/changelog.d/metamodel-docs-mustache.md +++ /dev/null @@ -1,17 +0,0 @@ -- **metamodel-docs: the vocabulary reference pages are shared Mustache templates, and every - port writes them.** `INDEX.md`, `providers.md` and the `types/.md` pages are now the - `templates/metamodel/` template set rendered over page data each port builds from its own - registry vocabulary manifest and its embedded provider definitions. C#, Java, Kotlin, Python - and Rust gain a `metamodel-docs` generator; every port is held to `fixtures/metamodel-docs/` - (the page data under `data/` and the bytes under `expected/`). A project can override a - page by placing a `templates/metamodel/.mustache` of its own. The TypeScript pages are - unchanged except one fix: `index.lookup` was missing its owning provider - (`metaobjects-core-types`) and the provider of its `@fields`, because the index definition - was left out of the provenance list. - - Upgrading: `@metaobjectsdev/metadata` no longer exports `renderMetamodelDocs`, - `renderCoreMetamodelDocs`, `buildMetamodelProvenance` or the `MetamodelProvenance` type; it - exports `coreMetamodelDocsPages()` and `buildMetamodelDocsPages()` (each page's path, - template ref and data) instead, and codegen-ts renders them. An ejected - `codegen/generators/metamodel-docs.ts` that calls `renderCoreMetamodelDocs` stops compiling: - eject it again (`meta eject metamodel-docs`). diff --git a/changelog.d/python-codegen-writer-no-ruff.md b/changelog.d/python-codegen-writer-no-ruff.md deleted file mode 100644 index 7d1e695e38..0000000000 --- a/changelog.d/python-codegen-writer-no-ruff.md +++ /dev/null @@ -1,55 +0,0 @@ -- **Python: every generator writes through the code writer, and codegen no longer runs `ruff`** - (ADR-0063). The router and the last nine emitters (extractor, output parser, trace helper, - render helper, names, requirement tests, API docs and the extract delegate and schema emitters) - now lay out their files with `PyWriter`, so generated bytes no longer depend on whether `ruff` is - installed or on its version. The output changes in layout only: a line longer than 88 columns - breaks its last bracketed list, and imports are grouped `__future__`, absolute, then relative, - each in code-point order. Checked against a capture of every emitted file: same syntax tree, - comments and docstrings. One fix rides along: an unresolved `@objectRef` mapper argument used - to put its comma inside the trailing comment, which was a syntax error; it is now - `x=None, # unresolved @objectRef`. Generated-output change — regenerate to pick it up; - three-way merge preserves hand edits. - - Upgrading: no reference generator calls `metaobjects.codegen.format.ruff_format` any more. It - stays exported, so an owned copy ejected from an earlier release that imports it still loads and - still formats its own output. These subclass hooks now take the writer `w` first and write, - instead of returning lines or a string: - `RouterGenerator._emit_repository_protocol(self, w, repo_class, m2m, pk_type)`, - `_emit_reverse_finders(self, w, entity)`, `_emit_route_handler(self, w, name, ...)`, - `_emit_m2m_route(self, w, d, ...)`, `_emit_tph_m2m_route(self, w, d, ...)`, - `_emit_tph_list_body(self, w, subtype_expr, ...)`, - `_emit_readonly_reject_handlers(self, w, snake, ...)`, `_report_list_with_export(self, w, ...)` - and `ExtractorGenerator._emit_mapper(self, w, vo, root)`. In `_emit_route_handler` the - `create_autoset`, `update_autoset`, `frozen_strip` and `denied_strip` arguments are now - `BodyStep` callables that write into `w`, not line lists. `RenderHelperGenerator._emit_document` - and `_emit_email` take `header` as `list[str]` instead of `str`. In the runtime emitters that - eject hands over, `extract_delegate_emitter.nested_mirror_dataclasses`, `nested_mappers` and - `delegate_helpers` are now `write_nested_mirror_dataclasses(w, vo, root)`, - `write_nested_mappers(w, vo, root)` and `write_delegate_helpers(w, used)`, and - `extract_schema_emitter.mirror_dataclass` and `mirror_initializer` are removed (the - mirror dataclasses come from `write_nested_mirror_dataclasses`; the new `schema_piece` is the - schema descriptor that `trace-helper` writes). Eject never overwrites an existing - `codegen/runtime/` copy, even with `--force`, so delete the old copy before you re-eject. - `output-parser` and `extractor` share `codegen/runtime/extract_delegate_emitter.py`: delete - it, then re-eject every one of the two that you own. For `trace-helper`, delete - `codegen/runtime/extract_schema_emitter.py`, then re-eject `trace-helper`. `ruff` stays a - dev dependency for the compile gate's `ruff check` lint only. - - Removed: the deprecated module aliases added in 1.1.0. An import of an old path now fails with - `ImportError` (or its subclass `ModuleNotFoundError`, depending on the import form); import - from the new path instead: - `metaobjects.codegen.extract_delegate_emitter` is `metaobjects.codegen.runtime.extract_delegate_emitter`, - `metaobjects.codegen.extract_schema_emitter` is `metaobjects.codegen.runtime.extract_schema_emitter`, - `metaobjects.codegen.fr010_field_mapping` is `metaobjects.codegen.runtime.fr010_field_mapping`, - `metaobjects.codegen.output_format_spec_emitter` is `metaobjects.codegen.runtime.output_format_spec_emitter`, - `metaobjects.codegen.generators.fr019_shared_enum` is `metaobjects.codegen.runtime.fr019_shared_enum`, - `metaobjects.codegen.generators.m2m_codegen` is `metaobjects.codegen.runtime.m2m_codegen`, - `metaobjects.apidocs.api_model` is `metaobjects.codegen.runtime.api_docs_model`, - `metaobjects.apidocs.builder` is `metaobjects.codegen.runtime.api_docs_builder`, - `metaobjects.apidocs.renderer` is `metaobjects.codegen.runtime.api_docs_renderer` and - `metaobjects.apidocs.paths` is `metaobjects.codegen.runtime.api_docs_paths`. The - `metaobjects.apidocs` package and `metaobjects.apidocs.naming` stay. An owned copy ejected - before 1.1.0 that still imports an old path needs its imports changed, or re-eject it. For - `output-parser`, changing the imports is not enough, because that copy calls the removed - `nested_mirror_dataclasses`, `nested_mappers` and `delegate_helpers`: re-eject it, or move it to - `write_nested_mirror_dataclasses`, `write_nested_mappers` and `write_delegate_helpers`. diff --git a/changelog.d/python-rc21-view-vocabulary.md b/changelog.d/python-rc21-view-vocabulary.md deleted file mode 100644 index c5533eb45a..0000000000 --- a/changelog.d/python-rc21-view-vocabulary.md +++ /dev/null @@ -1,9 +0,0 @@ -- **Python: the loader enforces the rc.21 view vocabulary.** `origin.function` signature and - identifier rules, dotted-path references in `origin.computed` and in an `origin.first` - `@filter`, a scalar `origin.aggregate` read from a computed field, passthrough from a `@grain` - value object and derived-field cycle detection now load and fail as they do in TypeScript and - C#. The two ledgered fixtures (`error-origin-function-free-sql`, - `projection-view-vocabulary-rc21`) pass, and the Python expected-failures ledger is empty. A - bare `@from` or base head on a projection now resolves in the file's default package. The - `xpkg-value-object-refs` codegen corpus and the generated `key-types` api-contract lane now run - in Python. diff --git a/changelog.d/registry-type-level-ports.md b/changelog.d/registry-type-level-ports.md deleted file mode 100644 index a8397dd6d5..0000000000 --- a/changelog.d/registry-type-level-ports.md +++ /dev/null @@ -1,11 +0,0 @@ -- **Registry manifest: a type can carry `ports`** (#549), the type-level twin of the attr-level - marker, for vocabulary that is language-specific by nature and never pending. The 13 generic - `view.*` controls move from `implementedIn: ["typescript"]` to `ports: ["typescript"]` (UI - vocabulary of the TypeScript client tier, which serves every backend), and `@object` moves from - `implementedIn: ["java"]` to `ports: ["java", "kotlin"]` (the JVM runtime). The rc.21 view - vocabulary (`origin.function`, `@union`, `@unionAll`, `@grain`, `@grainOrdinal`) is now - `implementedIn: ["csharp", "python", "typescript"]`, since the Python loader validates it; Java - and Kotlin remain pending on `origin.function`'s `@args`, `@params` and `@returns`. Every port - still registers and loads all of it strictly. The metamodel docs replace "Implemented in: … so - far" with "Language-specific to: …" on those pages; `meta types` marks ts-scoped types - `[ts-only]`, and the deprecated `tsOnly` field stays true for them. diff --git a/changelog.d/rust-publish-stale-sources.md b/changelog.d/rust-publish-stale-sources.md deleted file mode 100644 index 9a4aefcde2..0000000000 --- a/changelog.d/rust-publish-stale-sources.md +++ /dev/null @@ -1,7 +0,0 @@ -- **CI: the Rust publish dry-run no longer verifies against stale source.** `cargo publish - --workspace` unpacks the crates it depends on from its temporary overlay registry into a - directory fixed per checkout, and never unpacks them again while the version is unchanged, so a - machine that had run the gate before a new module landed compiled the old `metaobjects-1.3.0` - and failed with "could not find `metamodel_docs`". The gate now first clears unpacked copies of - the workspace's own crates that differ from the tree - (`scripts/rust-clear-stale-publish-sources.sh`). diff --git a/changelog.d/ts-crud-routes-non-id-key.md b/changelog.d/ts-crud-routes-non-id-key.md deleted file mode 100644 index 6142e1cd1f..0000000000 --- a/changelog.d/ts-crud-routes-non-id-key.md +++ /dev/null @@ -1,6 +0,0 @@ -- **TypeScript: generated CRUD routes address a key not named `id`.** `mountCrudRoutes` (Fastify - and Hono) took the primary key to be the `id` column, so an entity keyed on a natural `code` - or an int `rank` answered every item route (`GET`/`PATCH`/`PUT`/`DELETE /:id`, and the create - re-read on MySQL) with a 500. The mounts take an `idColumn` option, and the generated routes - pass it when the key field has another name. Generated-output change for such entities only: - one `idColumn: "",` line in the mount call; regenerate to pick it up. diff --git a/changelog.d/ts-poet-printer-removed.md b/changelog.d/ts-poet-printer-removed.md deleted file mode 100644 index 8b42e21f0f..0000000000 --- a/changelog.d/ts-poet-printer-removed.md +++ /dev/null @@ -1,10 +0,0 @@ -- **Breaking — the vendored ts-poet printer is removed; TypeScript codegen is writer-only.** - `@metaobjectsdev/codegen-ts` no longer exports `code`, `imp`, `joinCode`, `Code` or `Import`, - and `TsWriter` no longer accepts a `Code`. Use the writer fragments: `frag`, `joinFrags`, - `importName`, `importType`, `Frag` and `TsImport` (`writer/ts-fragment.ts`). The queries - template's `render*Fn` and `schemaInputType` forms are removed, and the config loader no longer - rewrites a `ts-poet` import. Generator copies ejected in 1.2 that use any of these no longer - load: re-eject them (`meta eject --force`). The `contract-types` output changes layout - only (one statement per line, double-quoted imports in the writer's order); the requirement-test - scaffolds and the client directive are now written through the writer, byte for byte as before. - `api-doc-render.ts` moved onto the code writer with unchanged output. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 3d256aca3f..afe30054cb 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -63,7 +63,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/model-lint-conformance/`](../fixtures/model-lint-conformance/) (the `verify` overlay, node-name and deprecated-reference authoring lints) | 17 | ✓ (reference) | planned | planned (through Java) | ✓ | planned | — | | [`fixtures/requirement-check-conformance/`](../fixtures/requirement-check-conformance/) (the `verify` requirement gate, ADR-0057) | 49 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | planned (RS-V2) | | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 27 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | — | -| [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 16 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | ✓ | +| [`fixtures/rules-check-conformance/`](../fixtures/rules-check-conformance/) (the `verify` business-rules gate, ADR-0066) | 17 cases | ✓ (reference) | ✓ | inherits via Java (one Maven `metaobjects:verify` goal) | ✓ | ✓ | ✓ | | [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases + 23 collection segments (`@collectionName`, `naming.collections`) | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`, `RouteNaming.collectionSegment`) | ✓ | ✓ | ✓ | | [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | the config blocks (`wire_block_corpus`) | | [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 5 cases + 1 overflow + 5 refusals; run by a port that sizes the column | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | — (sizes no column: emits no DDL or column type; the config reader accepts and shape-checks the `enums` block) | the config blocks (`enums_block_corpus`) | @@ -72,7 +72,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0064) | one case table in `cases.json`, plus the manifest layout vectors in `manifests.json` (ADR-0064 Amendment 1) | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | ✓ (every case but the three-way merge one) | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (vocabulary with no lowering yet: FR-044 reporting, what is lowered and what stays inert; ADR-0066 business rules, inert everywhere) | 2 model pairs (`reporting/` and `rules/`, each `with` vs `without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | `rules/` (the layer generators lower it; the flat ones stay inert) | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | -| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 88 cases (31 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | +| [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 91 cases (33 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 13 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | | [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | ✓ (`MetaObjects.DocsView`, and the `docs-site` generator end to end) | ✓ (`metaobjects.docs_view`, and the `docs-site` generator end to end) | ✓ (`metaobjects::docs_view`, and the `docs-site` generator end to end) | @@ -887,7 +887,7 @@ outside ASCII. The case list is in the Kotlin's identity function is the Java one; the names its generator emits are asserted by `server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementTestsGeneratorTest.kt`. -### `fixtures/rules-check-conformance/` (16 cases) +### `fixtures/rules-check-conformance/` (17 cases) All 16 cases → [features/business-rules.md](features/business-rules.md) ("What `verify` reports"). Each case is a directory: `input/` metadata, an optional `options.json` (the diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 3b67c181cf..28a58d9c0f 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -236,6 +236,7 @@ and reports: | `WARN_LIFECYCLE_INITIAL_TERMINAL` | warn | The initial state is terminal, so no row can ever move. | | `WARN_TRANSITION_UNREACHABLE` | `verify.lifecycle.unreachable` | A transition whose every `from` state is unreachable. | | `WARN_TRANSITION_PERMISSION_SHADOWED` | warn | A transition declares `permission` or `public: true` but derives no command of its own (every carrier's transition is claimed by a declared command, or `rules.lifecycle.commands` is `none`), so nothing reads it. | +| `WARN_DERIVED_COMMAND_BYPASSES_DECLARED` | warn, under `rules.lifecycle.commands: all` only | A transition a declared command claims also derives a command of its own, which makes the same transition without running the declared command's body (the business rule) and asks about the derived permission name. Use `unclaimed` (the default) unless you want both entry points. | | `WARN_PERMISSION_DERIVED_NAME` | `rules.permissions.names` | An operation, or a transition that derives a command, relies on a derived permission name. The message names it. A transition on an entity with no source derives no command and is not reported. | An error-severity finding fails the run. A model with no operation and no transition sees no diff --git a/docs/features/migrations/commit-the-gen-state-hash-manifest.md b/docs/features/migrations/commit-the-gen-state-hash-manifest.md index 542cdf5df2..2c19b071bc 100644 --- a/docs/features/migrations/commit-the-gen-state-hash-manifest.md +++ b/docs/features/migrations/commit-the-gen-state-hash-manifest.md @@ -1,8 +1,10 @@ -# Migration — commit `.gen-state/.hashes.json` +# Migration — commit `.gen-state/.hashes/` > **Since 1.3.0 the manifest is a directory, `.gen-state/.hashes/`, with one file per model -> package** (see [the per-package manifest migration](per-package-hash-manifest.md)). Read -> `.hashes.json` below as that directory; the first `gen` after upgrading converts it. +> package** (see [the per-package manifest migration](per-package-hash-manifest.md)); before +> 1.3.0 it was one file, `.gen-state/.hashes.json`. The first `gen` after upgrading converts the +> old file, deletes it and rewrites `.metaobjects/.gitignore`: commit the new directory, the +> deletion and the `.gitignore` change together. **Applies to:** every existing TypeScript project scaffolded by `meta init` before this release. **Action required:** one edit to `.metaobjects/.gitignore`, then commit the manifest. diff --git a/docs/features/migrations/default-list-page-of-fifty.md b/docs/features/migrations/default-list-page-of-fifty.md index a4eab9c163..a9fde6bab5 100644 --- a/docs/features/migrations/default-list-page-of-fifty.md +++ b/docs/features/migrations/default-list-page-of-fifty.md @@ -19,7 +19,11 @@ shipped) sees no change: its `defaultLimit` and `maxLimit` apply as before. | `meta verify` or `dotnet meta verify --codegen` advises `unbounded-list-pages` | the advisory is gone: the lists are bounded | | C#: `?limit=abc` or `?offset=-1` is ignored | it is `400 pagination.invalid_value`, as it already was with `api.pagination` set | -The generated TanStack list hooks are not affected: the grid hook always sends a `limit`. +**The generated TanStack list hooks are affected unless the caller passes a `limit`.** The grid hook always +sends one, so a grid pages as before. The plural list hooks (`useOrders(filter?)`, `useWidgetSummaries()`) +build the query string from the filter they are given, so a call with no `limit` now gets 50 rows: a screen +that listed a whole table that way (a picker, an editor that loads every child) shows the first 50. Pass +`limit` in the filter (`useOrders({ limit: 500 })`), page with `offset`, or raise the project's default below. **An owned runtime copy** (copied by `meta eject routes` or `meta eject routes-hono`) keeps the behaviour of the copy you took. Take a fresh copy with `meta eject routes --force` (or `routes-hono`) to get the default, or change `pageLimit` in your diff --git a/docs/features/migrations/docs-are-generators.md b/docs/features/migrations/docs-are-generators.md index fa52a1d11b..67389dae54 100644 --- a/docs/features/migrations/docs-are-generators.md +++ b/docs/features/migrations/docs-are-generators.md @@ -725,3 +725,38 @@ defaults to `false`. `modelBaseUrl` still works if you publish model pages elsew wrote under the `docs` target, list `docsSiteFile()`, and run `meta gen`. `mermaid-er`'s removal message now points at `docs-site` too. An owned copy from `meta eject docs` no longer loads; delete it and `codegen/generators/docs*`. + +## Since 1.3.0: `generateSite()` is removed + +**What breaks.** `@metaobjectsdev/docs-site` no longer exports `generateSite({ sourceDirs, ... })`, +the classic site's builder, which loaded the model itself. A script that called it fails with +`generateSite is not a function` (or `has no exported member 'generateSite'` under `tsc`). + +**To upgrade.** Prefer `docsSiteFile()` in `metaobjects.config.ts`, which `meta gen` runs and +`meta verify --codegen` gates. A script that must build the site itself does the three steps the +old builder did inside: load the model, build the docs view, and write the explorer. Pass +`output: "static"` for a page per object, which is the old site's shape; the default (`"app"`) +writes one browser app over the model. + +```ts +import { composeRegistry, coreProviders, MetaDataLoader, buildDocsView } from "@metaobjectsdev/metadata"; +import { DirectorySource } from "@metaobjectsdev/metadata/core"; +import { generateExplorerSite, readPromptTexts } from "@metaobjectsdev/docs-site"; + +const sourceDirs = ["metaobjects"]; +// Add the provider packs the project registers (its `providers`) beside the core ones. +const registry = composeRegistry([...coreProviders /*, ...packProviders */], { validate: true }); +const { root } = await new MetaDataLoader({ registry }).load(sourceDirs.map((d) => new DirectorySource(d))); +const view = buildDocsView({ root }); +generateExplorerSite({ + view, + outDir: "site", + title: "My model", + output: "static", + texts: readPromptTexts(view, ["templates", ...sourceDirs]), +}); +``` + +`buildDocsView` also takes `verify` (the parsed `meta verify --format json` output, for the +requirement ledger) and `manifest` (the merged `.gen-state/.hashes/` entries, for each object's +generated files); without them those panels are empty. diff --git a/docs/features/migrations/owned-generators-1.2-to-1.3.md b/docs/features/migrations/owned-generators-1.2-to-1.3.md index 3d87e97a4c..dd909c587b 100644 --- a/docs/features/migrations/owned-generators-1.2-to-1.3.md +++ b/docs/features/migrations/owned-generators-1.2-to-1.3.md @@ -23,8 +23,10 @@ copies you own) and make your edits again in the new file, or edit the copy to d ## Removed exports -- `formatTs` (a no-op) is no longer exported from `@metaobjectsdev/codegen-ts`. Delete the import - from an owned copy; the call did nothing. +- `formatTs` is no longer exported from `@metaobjectsdev/codegen-ts` or `/engine`: generation runs + no formatter (the writer lays out the text, ADR-0063). Replace `await formatTs(text)` with + `text`, or call a formatter of your own. A generator you wrote yourself, not only an ejected + copy, fails with `formatTs is not a function` until you do. - The vendored ts-poet printer (`poet.ts`) and its exports (`code`, `imp`, `joinCode`, `Code` and the rest) are removed, and so is the CLI's rewrite of ts-poet imports in ejected copies. Lay out output with the code writer (`CodeWriter`, `TsWriter`, ADR-0063), exported from @@ -32,9 +34,32 @@ copies you own) and make your edits again in the new file, or edit the copy to d writer's fragments replace the poet nodes: `frag` and `joinFrags` for `code` and `joinCode`, `importName` and `importType` for `imp`, and the `Frag` and `TsImport` types for `Code` and `Import`. A copy that imports `ts-poet` or those names does not compile; re-eject it. -- The queries template's `render*Fn` functions and `schemaInputType` are removed; the template - writes each function through the writer. A copy of the `queries` generator that called them - does not compile; re-eject it. +- The entity sub-renderers (`renderZodValidators`, `renderEnumTypeAliases`, + `renderValueObjectInterface`, `renderDrizzleSchema` and the rest) return a `Frag`, not a ts-poet + `Code`. A `Frag` carries its imports beside its text; `joinFrags` and the writer merge them. A + 1.2 entity composer that joins the sections with `joinCode(sections).toString()` runs, but each + section prints its own imports, so the file declares `import { z } from "zod"` once per section + and does not compile (`Identifier 'z' has already been declared`, TS2300). `meta gen` and + `meta verify --codegen` parse emitted TypeScript and refuse such a file by name, writing + nothing. Compose with `joinFrags(sections, "\n")` and write it with `TsWriter.fragment(...)`, or + re-eject `entity`. +- The queries template's seven primitives and `schemaInputType` are removed; the template writes + each function through the writer. Each `renderFn` returned a ts-poet `Code`; its + replacement writes into the `TsWriter` you pass and returns nothing: + + | 1.2 | 1.3 | + |---|---| + | `renderFindByIdFn(entity, ctx)` | `writeFindByIdFn(w, entity, ctx, readVar?)` | + | `renderListFn` | `writeListFn(w, entity, ctx, readVar?)` | + | `renderCreateFn` | `writeCreateFn(w, entity, ctx)` | + | `renderInsertPreservingFn` | `writeInsertPreservingFn(w, entity, ctx)` | + | `renderUpdateFn` | `writeUpdateFn(w, entity, ctx)` | + | `renderDeleteByIdFn` | `writeDeleteByIdFn(w, entity, ctx)` | + | `renderReverseFinderFns` | `writeReverseFinderFns(w, entity, fk, ctx, readVar?)` | + + A copy of the `queries` generator that called them fails `meta gen` with `renderFindByIdFn is + not a function`. Re-eject it (`meta eject queries --force`) and re-apply your changes; to change + one verb's body, write your own function in its place. ## `meta eject` compares trimmed lines diff --git a/docs/features/prerelease.md b/docs/features/prerelease.md index 52af1244ce..9280fdf8e7 100644 --- a/docs/features/prerelease.md +++ b/docs/features/prerelease.md @@ -272,7 +272,7 @@ npm install and to get back off it: ```bash -tools/prerelease/prerelease-link.sh unlink # --to defaults to the current npm `latest` +tools/prerelease/prerelease-link.sh unlink # --to defaults to the pins link found; with no record, the npm `latest` npm install ``` diff --git a/docs/recipes/write-your-own-generator.md b/docs/recipes/write-your-own-generator.md index d185d4601c..080dfeb221 100644 --- a/docs/recipes/write-your-own-generator.md +++ b/docs/recipes/write-your-own-generator.md @@ -414,6 +414,12 @@ the port's helper — `objectRefTarget` / `object_ref_target` / `ResolveFieldRef `ModelWalk.objectRefTarget` — never by matching a short name, because two packages can declare the same one). +To select by package, use the effective package, never the node's `package` property. A +package declared once on the file root (`"metadata.root": { "package": "acme::tasks" }`) is +the file's default: `obj.package` is `undefined` for every object in that file (it is only the +package the node declares itself), while `effectivePackage(obj)` returns `acme::tasks`, as +`obj.resolutionKey()` does. So `filter: (obj) => effectivePackage(obj) === "acme::tasks"`. + TypeScript's public helpers for the rest: `enumValues`, `objectRefTarget`, `effectivePackage`, `packageToPath`, `toCamelCase` / `toPascalCase` / `toSnakeCase` / `pluralize`, `servedPath(obj, prefix)` (the address the reference routes serve), and the diff --git a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts index 700b9b5f1d..521d60d9d1 100644 --- a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts +++ b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts @@ -146,13 +146,13 @@ export function durationColumnDataType(dialect: Dialect): string { * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or * month part is not a fixed-length span: reading one throws. */ -export function writeDurationColumnDecl(w: CodeWriter, dialect: Dialect, customTypeName: string): void { +export function writeDurationColumnDecl(w: TsWriter, dialect: Dialect, customTypeName: string): void { const postgres = dialect === "postgres"; - w.line("/** A field.duration column. Binds " + (postgres + w.commentLine("/** A field.duration column. Binds " + (postgres ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" : "the span as a 64-bit integer count of microseconds (refused past that range);")); - w.line(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); - w.line(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); + w.commentLine(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); + w.commentLine(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); w.block(`const ${DURATION_COLUMN_FN} = (() => {`, () => { writeUnits(w); w.line(`const INT64_MAX = BigInt("9223372036854775807");`); diff --git a/examples/advanced-modeling/codegen/templates/jsdoc.ts b/examples/advanced-modeling/codegen/templates/jsdoc.ts index 5b36aed32a..7e9b607320 100644 --- a/examples/advanced-modeling/codegen/templates/jsdoc.ts +++ b/examples/advanced-modeling/codegen/templates/jsdoc.ts @@ -6,7 +6,7 @@ import { DOC_ATTR_SEE_ALSO, DOC_ATTR_TITLE, } from "@metaobjectsdev/metadata"; -import { CodeWriter } from "@metaobjectsdev/codegen-ts/engine"; +import { TsWriter } from "@metaobjectsdev/codegen-ts/engine"; export interface DocAttrs { description?: string; @@ -60,8 +60,8 @@ export function jsDocLines(attrs: DocAttrs): string[] { } /** Write a node's JSDoc block (nothing when it has no doc attrs), one line at a time. */ -export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown }): void { - for (const l of jsDocLines(readDocAttrs(node))) w.line(l); +export function writeDocsFor(w: TsWriter, node: { attr: (n: string) => unknown }): void { + for (const l of jsDocLines(readDocAttrs(node))) w.commentLine(l); } /** @@ -69,8 +69,8 @@ export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown * with no final line break. Returns "" if no relevant attrs are set. */ export function renderJsDocBlock(attrs: DocAttrs): string { - const w = new CodeWriter(); - for (const l of jsDocLines(attrs)) w.line(l); + const w = new TsWriter(); + for (const l of jsDocLines(attrs)) w.commentLine(l); return w.toString().trimEnd(); } diff --git a/examples/showcase/codegen/templates/duration-wire-helper.ts b/examples/showcase/codegen/templates/duration-wire-helper.ts index 700b9b5f1d..521d60d9d1 100644 --- a/examples/showcase/codegen/templates/duration-wire-helper.ts +++ b/examples/showcase/codegen/templates/duration-wire-helper.ts @@ -146,13 +146,13 @@ export function durationColumnDataType(dialect: Dialect): string { * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or * month part is not a fixed-length span: reading one throws. */ -export function writeDurationColumnDecl(w: CodeWriter, dialect: Dialect, customTypeName: string): void { +export function writeDurationColumnDecl(w: TsWriter, dialect: Dialect, customTypeName: string): void { const postgres = dialect === "postgres"; - w.line("/** A field.duration column. Binds " + (postgres + w.commentLine("/** A field.duration column. Binds " + (postgres ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" : "the span as a 64-bit integer count of microseconds (refused past that range);")); - w.line(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); - w.line(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); + w.commentLine(" * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month"); + w.commentLine(" * part. Counted in bigint microseconds, so the column is the only limit. Generated. */"); w.block(`const ${DURATION_COLUMN_FN} = (() => {`, () => { writeUnits(w); w.line(`const INT64_MAX = BigInt("9223372036854775807");`); diff --git a/examples/showcase/codegen/templates/jsdoc.ts b/examples/showcase/codegen/templates/jsdoc.ts index 5b36aed32a..7e9b607320 100644 --- a/examples/showcase/codegen/templates/jsdoc.ts +++ b/examples/showcase/codegen/templates/jsdoc.ts @@ -6,7 +6,7 @@ import { DOC_ATTR_SEE_ALSO, DOC_ATTR_TITLE, } from "@metaobjectsdev/metadata"; -import { CodeWriter } from "@metaobjectsdev/codegen-ts/engine"; +import { TsWriter } from "@metaobjectsdev/codegen-ts/engine"; export interface DocAttrs { description?: string; @@ -60,8 +60,8 @@ export function jsDocLines(attrs: DocAttrs): string[] { } /** Write a node's JSDoc block (nothing when it has no doc attrs), one line at a time. */ -export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown }): void { - for (const l of jsDocLines(readDocAttrs(node))) w.line(l); +export function writeDocsFor(w: TsWriter, node: { attr: (n: string) => unknown }): void { + for (const l of jsDocLines(readDocAttrs(node))) w.commentLine(l); } /** @@ -69,8 +69,8 @@ export function writeDocsFor(w: CodeWriter, node: { attr: (n: string) => unknown * with no final line break. Returns "" if no relevant attrs are set. */ export function renderJsDocBlock(attrs: DocAttrs): string { - const w = new CodeWriter(); - for (const l of jsDocLines(attrs)) w.line(l); + const w = new TsWriter(); + for (const l of jsDocLines(attrs)) w.commentLine(l); return w.toString().trimEnd(); } diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md index 9eb3a5ada6..190ce7d130 100644 --- a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/agent/schema.md @@ -5,7 +5,7 @@ The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. - The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. ## Tables diff --git a/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md b/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md index 5872aad2eb..5ca213efcc 100644 --- a/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md +++ b/fixtures/docs-page-conformance/cases/schema-report-view/expected/agent/schema.md @@ -5,7 +5,7 @@ The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. - The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. > **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text `meta schema` emits as a `COMMENT ON`, so it lands in the database too. diff --git a/fixtures/rules-check-conformance/README.md b/fixtures/rules-check-conformance/README.md index efb7fd7e81..96cb729a10 100644 --- a/fixtures/rules-check-conformance/README.md +++ b/fixtures/rules-check-conformance/README.md @@ -23,6 +23,7 @@ work: read a loaded model, report diagnostics. | `WARN_LIFECYCLE_INITIAL_TERMINAL` | `warn` | The initial state is terminal: no transition lists it in `@from` (a self-transition counts as leaving). | | `WARN_TRANSITION_UNREACHABLE` | `verify.lifecycle.unreachable` | A transition whose every `@from` state is unreachable, so it can never be made. | | `WARN_TRANSITION_PERMISSION_SHADOWED` | `warn` | A transition that declares `@permission` or `@public: true` but derives no command of its own for any concrete entity with a source that carries it, so nothing reads the attribute: every carrier's transition is claimed by a declared command (`rules.lifecycle.commands: unclaimed`), or `rules.lifecycle.commands` is `none`. Never reported under `all`. One diagnostic per transition node, at its declaring address, naming the claiming commands as `.`. | +| `WARN_DERIVED_COMMAND_BYPASSES_DECLARED` | `warn`, only under `rules.lifecycle.commands: all` | A transition a declared command claims, which `all` also derives a command for: the derived command makes the same transition without running the declared command's body, and asks about the derived permission name. Reported per concrete entity with a source, at `::..`, naming the claiming commands as `.` and the derived command as `.`. Never reported under `unclaimed` or `none`, and independent of `rules.permissions.names`. | | `WARN_PERMISSION_DERIVED_NAME` | `rules.permissions.names`: `derive` (default) skips it, `advise` warns, `require` errors | An operation, or a transition that derives a command of its own, with no `@permission` and not `@public: true`. Which transitions derive a command is `rules.lifecycle.commands`: `unclaimed` (default) means those no declared command claims for that entity, `all` means every transition, `none` means none. | A command claims a transition NODE, for its target entity and every entity that extends the @@ -86,7 +87,8 @@ edited to make a port pass. | `lifecycle-create-any` | The same model with `rules.lifecycle.create: any`: the key is read and changes nothing `verify` reports. | | `permission-names-advise` | `rules.permissions.names: advise`: warns on the unclaimed `submit` transition and on the two operations without `@permission`; not on a claimed transition, one with `@permission`, or anything `@public`. | | `permission-names-require` | The same findings as errors under `require`. | -| `permission-names-commands-all` | `rules.lifecycle.commands: all`: the claimed transitions derive commands too, so they are reported as well. | +| `permission-names-commands-all` | `rules.lifecycle.commands: all`: the claimed transitions derive commands too, so they are reported as well, and as bypassing the declared command. | +| `commands-all-declared-bypass` | `rules.lifecycle.commands: all` at the default `rules.permissions.names`: each claimed transition is reported as bypassing its declaring command, and nothing else is. | | `permission-names-commands-none` | `rules.lifecycle.commands: none`: no transition derives a command, so only operations are reported for permission names, and each transition declaring `@permission` or `@public: true` is reported as shadowed. | | `unreachable-state` | Two unreachable states reported in one diagnostic, and the transition that starts only from them; a transition with one reachable `@from` state is not reported. | | `unreachable-state-error` | The same findings as errors under `verify.lifecycle.unreachable: error`. | diff --git a/fixtures/rules-check-conformance/commands-all-declared-bypass/expected.json b/fixtures/rules-check-conformance/commands-all-declared-bypass/expected.json new file mode 100644 index 0000000000..86ec4b6ccc --- /dev/null +++ b/fixtures/rules-check-conformance/commands-all-declared-bypass/expected.json @@ -0,0 +1,21 @@ +{ + "diagnostics": [ + { + "severity": "warn", + "code": "WARN_DERIVED_COMMAND_BYPASSES_DECLARED", + "path": "acme::purchasing::PurchaseRequest.status.approve", + "message": "transition \"approve\" of \"PurchaseRequest\" is claimed by \"Purchasing.decide\", but rules.lifecycle.commands is \"all\", so the derived command \"PurchaseRequest.approve\" makes the same transition without running its body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command." + }, + { + "severity": "warn", + "code": "WARN_DERIVED_COMMAND_BYPASSES_DECLARED", + "path": "acme::purchasing::PurchaseRequest.status.approveFirst", + "message": "transition \"approveFirst\" of \"PurchaseRequest\" is claimed by \"Purchasing.decide\", but rules.lifecycle.commands is \"all\", so the derived command \"PurchaseRequest.approveFirst\" makes the same transition without running its body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command." + } + ], + "summary": { + "operations": 4, + "lifecycles": 1, + "transitions": 5 + } +} diff --git a/fixtures/rules-check-conformance/commands-all-declared-bypass/input/meta.purchasing.yaml b/fixtures/rules-check-conformance/commands-all-declared-bypass/input/meta.purchasing.yaml new file mode 100644 index 0000000000..dc1fdce62d --- /dev/null +++ b/fixtures/rules-check-conformance/commands-all-declared-bypass/input/meta.purchasing.yaml @@ -0,0 +1,43 @@ +metadata: + package: acme::purchasing + children: + - object.entity: + name: PurchaseRequest + children: + - source.rdb: { table: purchase_requests } + - field.long: { name: id } + - identity.primary: { name: pk, fields: [id] } + - field.enum: + name: status + values: [draft, submitted, approved, rejected] + default: draft + children: + - transition.action: { name: submit, from: [draft], to: submitted } + - transition.action: { name: approve, from: [submitted], to: approved } + - transition.action: { name: reject, from: [submitted], to: rejected, permission: purchasing.review } + - transition.action: { name: approveFirst, from: [submitted], to: submitted } + - transition.action: { name: withdraw, from: [submitted], to: draft, public: true } + - object.value: + name: DecisionInput + children: + - field.long: { name: requestId, extends: PurchaseRequest.id } + - field.string: { name: comment } + - object.projection: + name: RequestSummary + children: + - source.rdb: { kind: view, view: v_request_summary } + - field.long: { name: id, extends: PurchaseRequest.id } + - identity.primary: { name: pk, extends: PurchaseRequest.pk } + - api.operational: + name: Purchasing + children: + - operation.command: + name: decide + inputRef: DecisionInput + transitions: [approve, approveFirst] + - operation.command: + name: escalate + inputRef: DecisionInput + permission: purchasing.escalate + - operation.query: { name: openRequests, outputRef: RequestSummary, many: true, public: true } + - operation.query: { name: requestSummary, outputRef: RequestSummary } diff --git a/fixtures/rules-check-conformance/commands-all-declared-bypass/options.json b/fixtures/rules-check-conformance/commands-all-declared-bypass/options.json new file mode 100644 index 0000000000..c3d09f7f53 --- /dev/null +++ b/fixtures/rules-check-conformance/commands-all-declared-bypass/options.json @@ -0,0 +1 @@ +{ "rules": { "lifecycle": { "commands": "all" } } } diff --git a/fixtures/rules-check-conformance/permission-names-commands-all/expected.json b/fixtures/rules-check-conformance/permission-names-commands-all/expected.json index 35923eadcd..03ee2b299f 100644 --- a/fixtures/rules-check-conformance/permission-names-commands-all/expected.json +++ b/fixtures/rules-check-conformance/permission-names-commands-all/expected.json @@ -1,5 +1,17 @@ { "diagnostics": [ + { + "severity": "warn", + "code": "WARN_DERIVED_COMMAND_BYPASSES_DECLARED", + "path": "acme::purchasing::PurchaseRequest.status.approve", + "message": "transition \"approve\" of \"PurchaseRequest\" is claimed by \"Purchasing.decide\", but rules.lifecycle.commands is \"all\", so the derived command \"PurchaseRequest.approve\" makes the same transition without running its body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command." + }, + { + "severity": "warn", + "code": "WARN_DERIVED_COMMAND_BYPASSES_DECLARED", + "path": "acme::purchasing::PurchaseRequest.status.approveFirst", + "message": "transition \"approveFirst\" of \"PurchaseRequest\" is claimed by \"Purchasing.decide\", but rules.lifecycle.commands is \"all\", so the derived command \"PurchaseRequest.approveFirst\" makes the same transition without running its body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or remove the declared command." + }, { "severity": "warn", "code": "WARN_PERMISSION_DERIVED_NAME", diff --git a/fixtures/writer-conformance/cases/error-leading-tab-in-open.json b/fixtures/writer-conformance/cases/error-leading-tab-in-open.json new file mode 100644 index 0000000000..5f1d77dcdd --- /dev/null +++ b/fixtures/writer-conformance/cases/error-leading-tab-in-open.json @@ -0,0 +1,20 @@ +{ + "description": "open() refuses text that starts with whitespace, a tab included.", + "dialect": "core", + "options": { + "indent": " ", + "width": 40, + "trailingComma": true + }, + "ops": [ + [ + "open", + "\tclass A {" + ], + [ + "close", + "}" + ] + ], + "error": "ERR_WRITER_LEADING_WHITESPACE" +} diff --git a/fixtures/writer-conformance/cases/error-leading-whitespace-in-line.json b/fixtures/writer-conformance/cases/error-leading-whitespace-in-line.json new file mode 100644 index 0000000000..ee17edb4ee --- /dev/null +++ b/fixtures/writer-conformance/cases/error-leading-whitespace-in-line.json @@ -0,0 +1,28 @@ +{ + "description": "line() refuses text that starts with whitespace: indentation comes only from open blocks, so a piece that carries its own indent would sit deeper than its siblings.", + "dialect": "core", + "options": { + "indent": " ", + "width": 40, + "trailingComma": true + }, + "ops": [ + [ + "open", + "class A {" + ], + [ + "line", + "a;" + ], + [ + "line", + " b;" + ], + [ + "close", + "}" + ] + ], + "error": "ERR_WRITER_LEADING_WHITESPACE" +} diff --git a/fixtures/writer-conformance/cases/py-doc-keeps-line-indentation.json b/fixtures/writer-conformance/cases/py-doc-keeps-line-indentation.json new file mode 100644 index 0000000000..7869f6770c --- /dev/null +++ b/fixtures/writer-conformance/cases/py-doc-keeps-line-indentation.json @@ -0,0 +1,29 @@ +{ + "description": "A docstring line keeps its own indentation (a worked example inside the text); the leading-whitespace refusal is for line(), open() and close().", + "dialect": "python", + "ops": [ + [ + "open", + "def f():" + ], + [ + "doc", + "Example:", + " f()" + ], + [ + "line", + "pass" + ], + [ + "dedent" + ] + ], + "expected": [ + "def f():", + " \"\"\"Example:", + " f()", + " \"\"\"", + " pass" + ] +} diff --git a/scripts/lib/changelog-fragments.mjs b/scripts/lib/changelog-fragments.mjs index aca9114feb..caf9d1bb5f 100644 --- a/scripts/lib/changelog-fragments.mjs +++ b/scripts/lib/changelog-fragments.mjs @@ -84,3 +84,24 @@ export function assembleChangelog(changelog, fragments) { const entries = fragments.map((f) => f.text.replace(/\s+$/, "")).join("\n\n"); return `${head}\n${entries}\n\n${rest}`; } + +/** + * Why a release candidate of `version` must not be cut yet, or `null`. A candidate is what + * adopters upgrade against with the CHANGELOG's upgrade list open, so when `## []` was + * prepared ahead of the cut, fragments still in `changelog.d/` are changes (and `Upgrading:` + * paragraphs) that list does not carry. Fold them in first. + * @param {string} changelog the CHANGELOG.md text + * @param {string} version the base version the candidate is of, e.g. `1.3.0` + * @param {{ name: string }[]} fragments + * @returns {string | null} + */ +export function unfoldedFragmentsProblem(changelog, version, fragments) { + if (fragments.length === 0) return null; + if (!changelog.includes(`\n## [${version}]`)) return null; + return ( + `CHANGELOG.md has a prepared [${version}] section and ${fragments.length} fragment(s) in ` + + `${FRAGMENT_DIR}/ are not folded into it (${fragments.map((f) => f.name).join(", ")}). ` + + `Fold them in (node scripts/changelog-fragments.mjs --assemble, then move each entry into the ` + + `section and each Upgrading: paragraph into its upgrade list) before cutting a candidate.` + ); +} diff --git a/scripts/prerelease.mjs b/scripts/prerelease.mjs index 905e94720e..c243b54d33 100644 --- a/scripts/prerelease.mjs +++ b/scripts/prerelease.mjs @@ -62,6 +62,7 @@ import { execSync } from "node:child_process"; import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from "node:fs"; import { join } from "node:path"; +import { FRAGMENT_DIR, readFragments, unfoldedFragmentsProblem } from "./lib/changelog-fragments.mjs"; import { mavenVersion } from "./maven-coordinate.mjs"; import { TIER_ORDER } from "./publish-set.mjs"; import { @@ -278,6 +279,15 @@ const VERSION_FILES = [ const dirty = sh(`git status --porcelain -- ${VERSION_FILES.map((f) => `'${f}'`).join(" ")}`).trim(); if (dirty) die(`version-bearing files are dirty — commit or stash first:\n${dirty}`); ok("version-bearing files clean"); +// ── GATE 7 — a full candidate carries a complete upgrade list ────────────────────────── +// A candidate (`--only all`) is what adopter estates run against the CHANGELOG's upgrade list, +// so fragments left beside a prepared section would ship changes that list does not explain. +if (ONLY.length === ALL.length) { + const unfolded = unfoldedFragmentsProblem( + readFileSync(join(ROOT, "CHANGELOG.md"), "utf8"), BASEVER, readFragments(join(ROOT, FRAGMENT_DIR))); + if (unfolded) die(unfolded); + ok("changelog fragments folded into the prepared section"); +} // Whether the tree the candidate is built from has uncommitted work, taken now, before any // version edit and before restore(). New untracked files count; the candidate log itself does not. const CANDIDATE_LOG = "tools/prerelease/candidates.md"; diff --git a/scripts/test-changelog-fragments.mjs b/scripts/test-changelog-fragments.mjs index b19405ef47..e12de918f5 100644 --- a/scripts/test-changelog-fragments.mjs +++ b/scripts/test-changelog-fragments.mjs @@ -6,7 +6,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; -import { assembleChangelog, fragmentNames, fragmentProblems, readFragments } from "./lib/changelog-fragments.mjs"; +import { assembleChangelog, fragmentNames, fragmentProblems, readFragments, unfoldedFragmentsProblem } from "./lib/changelog-fragments.mjs"; let fails = 0; const check = (cond, label) => (cond ? console.log(`ok: ${label}`) : (console.error(`FAIL: ${label}`), fails++)); @@ -38,6 +38,10 @@ check(fragmentProblems("x.md", "- one\n- two\n").some((p) => p.includes("one cha check(fragmentProblems("x.md", "- one\n - nested\n").length === 0, "a nested bullet is allowed"); check(fragmentProblems("x.md", "- one\n### Fixed\n").some((p) => p.includes("heading")), "a heading line is refused"); check(fragmentProblems("Bad Name.md", "- ok\n").some((p) => p.includes("name")), "a name with capitals or spaces is refused"); + +check(unfoldedFragmentsProblem(empty, "1.3.0", [A])?.includes("a-fix.md") === true, "a candidate of a prepared section refuses while a fragment is unfolded, naming it"); +check(unfoldedFragmentsProblem(empty, "1.3.0", []) === null, "a prepared section with no fragments may be cut"); +check(unfoldedFragmentsProblem(LOG, "1.3.0", [A]) === null, "with no prepared section the fragments wait for the release to assemble them"); check(fragmentProblems("x.txt", "- ok\n").some((p) => p.includes("name")), "a name not ending in .md is refused"); const dir = mkdtempSync(join(process.env.DEV_SCRATCH || tmpdir(), "changelog-fragments-")); diff --git a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs index 1bf10f59ff..d618b41899 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs @@ -416,4 +416,21 @@ public void A_non_migrating_save_leaves_gitignore_alone() Record(("gen/Order.cs", "a")); Assert.Equal(".gen-state/*\n!.gen-state/.hashes.json\n", File.ReadAllText(ignore)); } + + [Fact] + public void A_committed_legacy_manifest_beats_a_stale_hashes_dir() + { + // The old .gitignore ignores .hashes/, so one left by another checkout's run survives a + // reset beside the committed .hashes.json; its stale hashes must not count. + Directory.CreateDirectory(HashesDir); + File.WriteAllText(Path.Combine(StateDir, ".hashes.json"), "{\"gen/Order.cs\":\"committed\"}"); + File.WriteAllText(Path.Combine(HashesDir, "acme.shop.json"), + "{\"gen/Order.cs\":\"stale\",\"gen/Gone.cs\":\"stale\"}"); + var loaded = HashManifest.Load(StateDir); + Assert.Equal(new Dictionary { ["gen/Order.cs"] = "committed" }, loaded); + HashManifest.Save(StateDir, loaded); + Assert.False(File.Exists(Path.Combine(StateDir, ".hashes.json"))); + Assert.Equal(new Dictionary { ["gen/Order.cs"] = "committed" }, HashManifest.Load(StateDir)); + } } + diff --git a/server/csharp/MetaObjects.Codegen/HashManifest.cs b/server/csharp/MetaObjects.Codegen/HashManifest.cs index eeed5f0bed..7e0ec63a9a 100644 --- a/server/csharp/MetaObjects.Codegen/HashManifest.cs +++ b/server/csharp/MetaObjects.Codegen/HashManifest.cs @@ -267,13 +267,20 @@ private static Dictionary ReadRaw(string genStateDir) => } } - // The union: the legacy file underneath, then every file in .hashes/ in file-name order (a package file wins). + // Every file in .hashes/ in file-name order, or, while a legacy .hashes.json is still present, + // that file alone. A write deletes it right after writing the package files, so a .hashes/ + // beside it is left over from another checkout (the old .gitignore ignores that directory, so + // it survives a reset or a branch switch), and its stale hashes would make every file the + // committed manifest vouches for read as hand-edited. The next write replaces or removes them. private static Loaded ReadAll(string genStateDir) { var loaded = new Loaded { LegacyPresent = LegacyExists(genStateDir) }; - if (loaded.LegacyPresent && ReadOne(LegacyPath(genStateDir)) is { } legacy) - foreach (var (k, v) in legacy) loaded.Raw[k] = v; - if (Directory.Exists(DirPath(genStateDir))) + if (loaded.LegacyPresent) + { + if (ReadOne(LegacyPath(genStateDir)) is { } legacy) + foreach (var (k, v) in legacy) loaded.Raw[k] = v; + } + else if (Directory.Exists(DirPath(genStateDir))) { var names = Directory.EnumerateFiles(DirPath(genStateDir), "*.json") .Select(Path.GetFileName).OfType().Order(StringComparer.Ordinal); diff --git a/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache b/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache index ad91a93c2f..90dfc9bee4 100644 --- a/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache +++ b/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache @@ -14,7 +14,7 @@ The tables, columns and keys this model declares. Read it before writing a query - Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. {{/hasMigrate}} {{^hasMigrate}} -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. {{/hasMigrate}} - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. diff --git a/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs index 9c7424456e..c9e1554969 100644 --- a/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs +++ b/server/csharp/MetaObjects.Codegen/Writer/CodeWriter.cs @@ -25,6 +25,8 @@ public static class WriterErrors public const string NewlineInLine = "ERR_WRITER_NEWLINE_IN_LINE"; /// One local name imported from two different places. public const string ImportConflict = "ERR_WRITER_IMPORT_CONFLICT"; + /// Line(), Open() or Close() was handed text that starts with a space or tab. + public const string LeadingWhitespace = "ERR_WRITER_LEADING_WHITESPACE"; } /// A writer error: one of the codes and a message for people. @@ -161,9 +163,10 @@ public CodeWriter(CodeWriterOptions options) /// /// One line at the current indent. The parts are concatenated; when the line does not fit the /// width, the LAST non-empty list in it is printed one item per line. A line whose text is empty - /// is a blank-line request. + /// is a blank-line request. Text that starts with whitespace is ERR_WRITER_LEADING_WHITESPACE: + /// indentation comes only from open blocks. /// - public CodeWriter Line(params Piece[] parts) => Put(Piece.Seq(parts)); + public CodeWriter Line(params Piece[] parts) => Put(Unindented(Piece.Seq(parts), "Line")); /// Ask for one blank line before whatever is written next. Requests never stack. public CodeWriter Blank() @@ -173,10 +176,10 @@ public CodeWriter Blank() } /// Write the line that opens a block, then indent. - public CodeWriter Open(params Piece[] parts) => OpenPiece(Piece.Seq(parts)); + public CodeWriter Open(params Piece[] parts) => OpenPiece(Unindented(Piece.Seq(parts), "Open")); /// Dedent, then write the line that closes the block. - public CodeWriter Close(params Piece[] parts) => ClosePiece(Piece.Seq(parts)); + public CodeWriter Close(params Piece[] parts) => ClosePiece(Unindented(Piece.Seq(parts), "Close")); /// /// Open(head), then (on dispose) Close(tail): the indent cannot be left @@ -237,6 +240,20 @@ public override string ToString() /// protected virtual (string Before, Group List, string After)? BreakAt(Piece piece) => LastGroup(piece); + /// + /// Refuse text a caller indented itself: the writer adds the indent, so a pre-indented piece + /// would land one level too deep beside its siblings, silently. + /// + protected static Piece Unindented(Piece piece, string what) + { + var raw = piece.Flat(); + if (raw.Length > 0 && (raw[0] == ' ' || raw[0] == '\t')) + throw new WriterException( + WriterErrors.LeadingWhitespace, + $"{what}() text starts with whitespace; pass it without indentation, the writer indents it from the open blocks: \"{raw}\""); + return piece; + } + protected CodeWriter OpenPiece(Piece piece) { Put(piece); diff --git a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs index 560d8386a3..7b8a095c85 100644 --- a/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs +++ b/server/csharp/MetaObjects.Codegen/Writer/CsWriter.cs @@ -123,9 +123,9 @@ public IDisposable Braced(Piece head, string tail = "}") /// The text is written as given, so it carries any XML escaping it needs. public CsWriter DocSummary(params string[] lines) { - Line("/// "); - foreach (var l in lines) Line(l.Length == 0 ? "///" : "/// " + l); - Line("/// "); + Put("/// "); + foreach (var l in lines) Put(l.Length == 0 ? "///" : "/// " + l); + Put("/// "); return this; } diff --git a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs index 06b922a570..2dfbba3d91 100644 --- a/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs +++ b/server/csharp/MetaObjects/Core/Transition/RulesCheck.cs @@ -56,6 +56,7 @@ public static class RulesCheck public const string WARN_LIFECYCLE_INITIAL_TERMINAL = "WARN_LIFECYCLE_INITIAL_TERMINAL"; public const string WARN_TRANSITION_UNREACHABLE = "WARN_TRANSITION_UNREACHABLE"; public const string WARN_TRANSITION_PERMISSION_SHADOWED = "WARN_TRANSITION_PERMISSION_SHADOWED"; + public const string WARN_DERIVED_COMMAND_BYPASSES_DECLARED = "WARN_DERIVED_COMMAND_BYPASSES_DECLARED"; public const string WARN_PERMISSION_DERIVED_NAME = "WARN_PERMISSION_DERIVED_NAME"; private static string QuoteList(IEnumerable xs) => string.Join(", ", xs.Select(x => $"\"{x}\"")); @@ -226,6 +227,29 @@ private static void CheckShadowedPermissions(MetaData root, RulesSettings settin } } + /// Under rules.lifecycle.commands: all a transition a declared command claims derives a + /// command of its own as well, which makes the transition without running the declared command's body. + private static void CheckDerivedBypassesDeclared(MetaData root, RulesSettings settings, List output) + { + if (settings.LifecycleCommands != "all") return; + var claimed = ClaimedTransitions(root); + foreach (var entity in CommandEntities(root)) + { + foreach (var t in Lifecycles.EntityTransitions(entity)) + { + var claimers = ClaimsOn(claimed, entity, t) + .Select(c => $"{c.Op.Parent?.Name ?? ""}.{c.Op.Name}").Distinct(StringComparer.Ordinal).ToList(); + if (claimers.Count == 0) continue; + output.Add(new RequirementDiagnostic(SeverityWarn, WARN_DERIVED_COMMAND_BYPASSES_DECLARED, + $"{Address(entity)}.{t.Parent?.Name ?? ""}.{t.Name}", + $"transition \"{t.Name}\" of \"{entity.Name}\" is claimed by {QuoteList(claimers)}, but rules.lifecycle.commands is \"all\", " + + $"so the derived command \"{entity.Name}.{t.Name}\" makes the same transition without running " + + $"{(claimers.Count == 1 ? "its" : "their")} body. Set rules.lifecycle.commands to \"unclaimed\" (the default), or " + + "remove the declared command.")); + } + } + } + private static void CheckPermissionNames(MetaData root, RulesSettings settings, List output) { if (settings.PermissionNames == "derive") return; @@ -294,6 +318,7 @@ public static RulesCheckResult Check(MetaData root, RulesSettings settings) var diagnostics = new List(); foreach (var l in lifecycles) CheckLifecycle(l, settings, diagnostics); CheckShadowedPermissions(root, settings, diagnostics); + CheckDerivedBypassesDeclared(root, settings, diagnostics); CheckPermissionNames(root, settings, diagnostics); return new RulesCheckResult( diagnostics, diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java index ad67cbb6c9..ba91c5631b 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java @@ -161,12 +161,12 @@ public void emit(File outputDir, String javaPackage, String className, String re protected void writeHeader(JavaWriter w, String javaPackage, String className) { if (!isBlank(javaPackage)) w.packageName(javaPackage); w.line("/**"); - w.line(" * GENERATED — extractor for {@code " + className + "}."); - w.line(" *"); - w.line(" *

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

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

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

"); + w.commentLine(" */"); } /** Write the private {@code lookup(loader)} helper resolving the payload MetaObject by FQN. */ @@ -182,10 +182,10 @@ protected void writeLookupHelper(JavaWriter w, String resolutionKey) { */ protected void writeExtractMethod(JavaWriter w, String className) { w.line("/**"); - w.line(" * Extract a fully-typed {@code " + className + "} from dirty {@code text}."); - w.line(" *"); - w.line(" * @throws com.metaobjects.render.extract.ExtractException iff a required field was lost or malformed"); - w.line(" */"); + w.commentLine(" * Extract a fully-typed {@code " + className + "} from dirty {@code text}."); + w.commentLine(" *"); + w.commentLine(" * @throws com.metaobjects.render.extract.ExtractException iff a required field was lost or malformed"); + w.commentLine(" */"); try (var m = w.block("public static " + className + " extract(" + LOADER_FQN + " loader, String text) {")) { w.line("return (" + className + ") " + META_OBJECT_EXTRACT_FQN + ".extract(lookup(loader), text).orThrow();"); } @@ -198,10 +198,10 @@ protected void writeExtractMethod(JavaWriter w, String className) { protected void writeExtractLenientMethod(JavaWriter w, String className) { String result = EXTRACTION_RESULT_FQN + "<" + className + ">"; w.line("/**"); - w.line(" * Extract a {@code " + className + "} from dirty {@code text}, never throwing."); - w.line(" *"); - w.line(" * @return the typed result; inspect {@code report()} for lost/malformed/defaulted fields"); - w.line(" */"); + w.commentLine(" * Extract a {@code " + className + "} from dirty {@code text}, never throwing."); + w.commentLine(" *"); + w.commentLine(" * @return the typed result; inspect {@code report()} for lost/malformed/defaulted fields"); + w.commentLine(" */"); w.line("@SuppressWarnings(\"unchecked\")"); try (var m = w.block("public static " + result + " extractLenient(" + LOADER_FQN + " loader, String text) {")) { w.line("return (" + result + ") (" + EXTRACTION_RESULT_FQN + ") " diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java index 484216b6ba..d6c899c4d1 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java @@ -175,10 +175,10 @@ private void emitProviderSource(Map fqnToClass) throws IOExcepti w.use("java.util.Map"); w.use("java.util.HashMap"); w.line("/**"); - w.line(" * GENERATED — self-registering " + ObjectClassBindingProvider.class.getSimpleName() + " (ADR-0001)."); - w.line(" * Maps each generated object's metadata resolution key (\"pkg::Name\") to its"); - w.line(" * generated Java class, so MetaObject.newInstance() yields the generated type."); - w.line(" */"); + w.commentLine(" * GENERATED — self-registering " + ObjectClassBindingProvider.class.getSimpleName() + " (ADR-0001)."); + w.commentLine(" * Maps each generated object's metadata resolution key (\"pkg::Name\") to its"); + w.commentLine(" * generated Java class, so MetaObject.newInstance() yields the generated type."); + w.commentLine(" */"); try (var cls = w.block("public final class " + PROVIDER_SIMPLE_NAME + " implements " + ObjectClassBindingProvider.class.getName() + " {")) { w.line("@Override"); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java index eba31da290..f965c866f4 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java @@ -277,10 +277,17 @@ public static Map loadProvenance(Path genStateDir) { return out; } - /** The union of every manifest file: the legacy one underneath, package files in name order on top. */ + /** + * The manifest: the package files in name order, or, while a legacy {@code .hashes.json} is still + * present, that file alone. A write deletes it right after writing the package files, so a + * {@code .hashes/} beside it is left over from another checkout (the old {@code .gitignore} + * ignores that directory, so it survives a reset or a branch switch), and its stale hashes would + * make every file the committed manifest vouches for read as hand-edited. The next write + * replaces or removes those stale files. + */ private static Map entries(Path genStateDir) { Map out = new LinkedHashMap<>(); - readInto(legacyPath(genStateDir), out); + if (hasLegacy(genStateDir)) return readInto(legacyPath(genStateDir), out); for (Path p : packageFiles(genStateDir)) readInto(p, out); return out; } @@ -303,6 +310,7 @@ private static Map readInto(Path path, Map fileOfKeys(Path genStateDir) { Map out = new LinkedHashMap<>(); + if (hasLegacy(genStateDir)) return out; // the legacy file is authoritative, see entries() for (Path p : packageFiles(genStateDir)) { for (String key : readInto(p, new LinkedHashMap<>()).keySet()) out.put(key, p.getFileName().toString()); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java index f26880b748..0411f48603 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/CodeWriter.java @@ -46,10 +46,11 @@ public WriterOptions options() { /** * One line at the current indent. The parts are concatenated; when the line does not fit the * width, the LAST non-empty list in it is printed one item per line. A line whose text is - * empty is a blank-line request. + * empty is a blank-line request. Text that starts with whitespace is + * {@code ERR_WRITER_LEADING_WHITESPACE}: indentation comes only from open blocks. */ public CodeWriter line(Object... parts) { - return put(piece(Arrays.asList(parts))); + return put(unindented(piece(Arrays.asList(parts)), "line")); } /** Ask for one blank line before whatever is written next. Requests never stack. */ @@ -60,12 +61,12 @@ public CodeWriter blank() { /** Write the line that opens a block, then indent. */ public CodeWriter open(Object... parts) { - return openPiece(piece(Arrays.asList(parts))); + return openPiece(unindented(piece(Arrays.asList(parts)), "open")); } /** Dedent, then write the line that closes the block. */ public CodeWriter close(Object... parts) { - return closePiece(piece(Arrays.asList(parts))); + return closePiece(unindented(piece(Arrays.asList(parts)), "close")); } /** @@ -168,6 +169,24 @@ protected Split breakAt(Object piece) { return lastGroup(piece); } + /** + * Refuse text a caller indented itself: the writer adds the indent, so a pre-indented piece + * would land one level too deep beside its siblings, silently. + */ + protected Object unindented(Object piece, String what) { + String raw = flat(piece); + if (raw.startsWith(" ") || raw.startsWith("\t")) { + throw new WriterException( + WriterException.LEADING_WHITESPACE, + what + + "() text starts with whitespace; pass it without indentation, the writer indents it" + + " from the open blocks: \"" + + raw + + "\""); + } + return piece; + } + protected CodeWriter openPiece(Object piece) { put(piece); openers.add(flat(piece).strip()); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java index 7282736d62..c68f522869 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/JavaWriter.java @@ -132,12 +132,22 @@ public JavaWriter doc(String... lines) { for (String l : lines) safe.add(l.replace("*/", "*/")); String one = "/** " + safe.get(0) + " */"; if (safe.size() == 1 && fits(one)) { - line(one); + put(one); return this; } - line("/**"); - for (String l : safe) line(l.isEmpty() ? " *" : " * " + l); - line(" */"); + // put, not line(): the {@code * } lines of a Javadoc start with whitespace by design. + put("/**"); + for (String l : safe) put(l.isEmpty() ? " *" : " * " + l); + put(" */"); + return this; + } + + /** + * One line inside a block comment, such as {@code * text}: it starts with whitespace by design, + * and the writer still indents it from the open blocks. {@link #line} refuses such text. + */ + public JavaWriter commentLine(Object... parts) { + put(piece(Arrays.asList(parts))); return this; } @@ -163,7 +173,8 @@ protected CodeWriter sectionWriter() { /** The {@link #header} lines, as given. */ protected void writeHeader(CodeWriter w) { - for (String l : headLines) w.line(l); + // put, not line(): a header line is written as given, even one that starts with whitespace. + for (String l : headLines) w.put(l); } /** The {@code package} line, when one was set. */ diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java index 672be302c9..2fffbf8ea2 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/writer/WriterException.java @@ -16,6 +16,8 @@ public class WriterException extends RuntimeException { public static final String IMPORT_CONFLICT = "ERR_WRITER_IMPORT_CONFLICT"; /** A piece the writer does not know how to print. */ public static final String UNKNOWN_PIECE = "ERR_WRITER_UNKNOWN_PIECE"; + /** {@code line()}, {@code open()} or {@code close()} was handed text that starts with a space or tab. */ + public static final String LEADING_WHITESPACE = "ERR_WRITER_LEADING_WHITESPACE"; private final String code; diff --git a/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache index ad91a93c2f..90dfc9bee4 100644 --- a/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache +++ b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache @@ -14,7 +14,7 @@ The tables, columns and keys this model declares. Read it before writing a query - Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. {{/hasMigrate}} {{^hasMigrate}} -- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +- Change the schema by changing the **metadata** and writing the migration: with `meta migrate` when the project uses it, otherwise with the project's own migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. {{/hasMigrate}} - `Field` and `Declared` are the METADATA names. Edit those; the column name follows. diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java index a682ed0726..2c5326be93 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java @@ -338,13 +338,30 @@ public void readOnlyLoadOfALegacyManifestMigratesNothing() throws Exception { } @Test - public void aPackageFileWinsOverTheLegacyFile() throws Exception { + public void thePackageFilesAreUnreadWhileTheLegacyFileIsPresent() throws Exception { + // ADR-0064 §2 (corrected): a .hashes/ beside an unmigrated .hashes.json is stale. Path gs = genState(); Files.createDirectories(gs.resolve(".hashes")); Files.writeString(gs.resolve(".hashes.json"), "{\"gen/A.java\":\"old\",\"gen/B.java\":\"b\"}"); Files.writeString(gs.resolve(".hashes/acme.shop.json"), "{\"gen/A.java\":\"new\"}\n"); Map loaded = HashManifest.load(gs); - assertEquals("new", loaded.get("gen/A.java")); + assertEquals("old", loaded.get("gen/A.java")); assertEquals("b", loaded.get("gen/B.java")); } + + @Test + public void aCommittedLegacyManifestBeatsAStaleHashesDir() throws Exception { + // The old .gitignore ignores .hashes/, so one left by another checkout's run survives a + // reset beside the committed .hashes.json; its stale hashes must not count. + Path gs = tmp.newFolder("stale-hashes").toPath(); + Files.writeString(gs.resolve(".hashes.json"), "{\"gen/Order.java\":\"committed\"}"); + Files.createDirectories(gs.resolve(".hashes")); + Files.writeString(gs.resolve(".hashes").resolve("acme.shop.json"), + "{\"gen/Order.java\":\"stale\",\"gen/Gone.java\":\"stale\"}"); + Map loaded = HashManifest.load(gs); + assertEquals(Map.of("gen/Order.java", "committed"), loaded); + HashManifest.save(gs, new LinkedHashMap<>(loaded), new LinkedHashMap<>()); + assertFalse(Files.exists(gs.resolve(".hashes.json"))); + assertEquals(Map.of("gen/Order.java", "committed"), HashManifest.load(gs)); + } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt index dbe65197a3..3e4e05b8c5 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDecimalWireEmitter.kt @@ -72,7 +72,7 @@ object KotlinDecimalWireEmitter { * GENERATED (ADR-0019 Amendment 1) — do not hand-edit. The decimal wire rule: a decimal is """ ) - w.line( + w.commentLine( if (asString) " * written as a canonical string (plain notation, no trailing fraction zeros, zero as \"0\")," else " * written as the host serializer writes it,", ) diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt index a4845f3b53..532cc64b31 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt @@ -584,15 +584,15 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseExtracts the typed response VO from {@code input.llmResponseText()} and"); - w.line(" * persists ONE trace row (base envelope + raw I/O + typed voRequest/voResponse)"); - w.line(" * via the supplied recorder. The render-call-record helper is intentionally"); - w.line(" * not emitted (BYO vendor-neutral caller; Java LlmClient seam not ported).

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

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

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

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

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

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

"); + w.commentLine(" */"); try (var cls = w.block("public interface " + repoName + " {")) { writeSortClause(w); w.blank(); @@ -245,11 +245,11 @@ protected void emitTph(MetaObject base, Path outRoot) { SpringJavaWriter w = newWriter(pkg, true); w.line("/**"); - w.line(" * GENERATED TPH interface — consumer implements with their preferred persistence layer."); - w.line(" * Polymorphic operations span the single " + shortName + w.commentLine(" * GENERATED TPH interface — consumer implements with their preferred persistence layer."); + w.commentLine(" * Polymorphic operations span the single " + shortName + " table; the per-subtype operations are scoped to a discriminator value"); - w.line(" * (injected by the matching " + shortName + "Controller from the URL segment)."); - w.line(" */"); + w.commentLine(" * (injected by the matching " + shortName + "Controller from the URL segment)."); + w.commentLine(" */"); try (var cls = w.block("public interface " + repoName + " {")) { writeSortClause(w); w.blank(); diff --git a/server/java/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