diff --git a/.claude/skills/metaobjects-audit/SKILL.md b/.claude/skills/metaobjects-audit/SKILL.md index 21a2973..bc50fba 100644 --- a/.claude/skills/metaobjects-audit/SKILL.md +++ b/.claude/skills/metaobjects-audit/SKILL.md @@ -1,22 +1,42 @@ --- name: metaobjects-audit -description: Use when assessing how well a project has adopted MetaObjects — greenfield first-pass or deep double-check; produces a scored, prioritized adoption-audit report covering codegen, runtime, drift-gates, and prompts. +description: Use when assessing how well a project that already uses MetaObjects has adopted it — a first-pass or deep audit that finds hand-written code the metadata could own and produces a scored, prioritized adoption-audit report (JSON plus Markdown) covering codegen, runtime, drift gates and prompts. Read-only. --- # MetaObjects adoption audit -**Thesis.** Typed metadata is the durable spine; generated code is the disposable -artifact. Hand-writing a layer the metadata could own creates a second source of -truth for one fact — it will drift. This audit hunts those second sources of truth -and proposes folding them into the spine — where the generator code plus its generated output -and added metadata is fewer lines than the hand-written code it replaces, more of that shape -are coming, or silent drift is the risk. A one-off layer -that fails that cost test is acceptable, not a defect. - -**Boundary — read-only.** Deliverables: `.metaobjects/adoption-audit.json` (machine-readable -findings) + a rendered Markdown report. The audit **never edits code, never authors -metadata** — `metadata_sketch` per finding is a read-only proposal for human review. -Actual cutovers run through the existing skills mapped per finding tier (§ Bridge). +Typed metadata is what lasts; generated code is replaceable. A hand-written layer the +metadata could own is a second source of truth for one fact, and it will drift. This audit +finds those second sources and proposes folding them into the model where that pays: the +generator plus its output and added metadata is fewer lines than the hand-written code it +replaces, more of that shape are coming, or silent drift is the risk. A one-off layer that +fails that cost test is acceptable, not a defect. + +## Essentials + +- **Read-only.** The deliverables are `.metaobjects/adoption-audit.json` and a rendered + Markdown report. The audit never edits code and never authors metadata: each finding's + `metadata_sketch` is a proposal for a human to review, and cutovers run through the other + skills (the bridge at the end). +- **Metadata follows the code.** This is an existing project, so its code and live schema are + the specification. Every `metadata_sketch` reproduces the code's native types, names and + nullability (`field.uuid` where the code uses `UUID`; carry over `@column` / `@table` / + `@required`), and every cutover leaves code the generator is not replacing alone: propose + customizing the generator to match the existing shape before proposing edits to working + call sites. When a choice is ambiguous, flag it for the human; do not pick the option + with more churn. (`metaobjects-authoring`, "Adopting onto an existing codebase".) +- **Read the code behind every hit before raising a finding, and check + `references/calibration.md` first.** A grep hit is a lead. Calibration lists the port gaps + and non-defects that are never the adopter's fault. Under-flag: a false finding costs the + report more trust than a missed one. +- **Parity-gate every cutover.** Prove the generated replacement behaves the same before + hand-written code is deleted; generated schemas are often looser. +- **Check the database artifact, not only the types.** A contract can claim a computed + column the view DDL dropped. +- **One bespoke action does not block generating the entity.** Generate the CRUD and mount + the custom action beside it. +- **Check resolved package versions, not declared ones.** Consuming a fix means a coordinated + version bump and rebuild, not a copied dist file. ## Reference files — open the one your task needs @@ -25,104 +45,129 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid | `references/calibration.md` | Before raising any finding: it lists the port gaps and non-defects that are never the adopter's fault. | | `references/surface-review-axes.md` | Working any axis (A–I) of Phase 1b. | | `references/capability-checklist.md` | On every axis: the exhaustive list of what the metamodel can express, one hunt per capability. | -| `references/drift-signatures.md` | Hunting hand-written second sources of truth (validators, mappers, comments, views, JSON bags). | +| `references/drift-signatures.md` | Hunting hand-written second sources of truth (validators, mappers, comments, views, JSON bags, physical-name literals, enum-member and event-name literals). | | `references/prompt-anti-patterns.md` | Axis D: the project builds text sent to an LLM or parses a reply. | | `references/vocabulary-hygiene.md` | Axis I: retired or deprecated authoring forms, custom vocabulary, vocabulary opportunities. | | `references/requirements.md` | Axis E2: the project declares `requirement.*` nodes. | | `references/typescript.md`, `java.md`, `kotlin.md`, `csharp.md`, `python.md` | The server port the project uses (only the ports in the project's stack are installed). | -## Guardrails - -- **Adoption direction — metadata follows the code.** This is a brownfield project: existing - code and the live schema are the spec. Every `metadata_sketch` must **reproduce the code's - existing native types, names, and nullability** (model `field.uuid` where the code uses - `UUID`, carry over `@column`/`@table`/`@required`) and every cutover must **minimize churn to - code the generator is not replacing** — customize the codegen to match the existing shape - before proposing edits to working call sites. A sketch that would re-type or rename working - code the generator isn't replacing is modeling the wrong thing; when a choice is ambiguous, - flag it for the human rather than proposing the churnier option. (Full doctrine: - `metaobjects-authoring` → "Adopting onto an existing codebase".) -- **Parity-gate every cutover** — prove behavior-equivalent before deleting hand-written code; generated schemas are often looser. -- **Verify, don't assume** — read the code behind a grep hit. -- **Calibrate before flagging** — `references/calibration.md` lists what is never the adopter's fault. -- **Verify the DB artifact, not just the types** — the contract may claim a column the view DDL dropped. -- **Don't let one bespoke action block generating the entity** — generate CRUD; mount the custom action alongside. -- **Consumption ≠ a dist copy across versions** — bump + rebuild lockstep and install. - -## Phase 0 — Triage (fast, mechanical) - -- [ ] MetaObjects present? (`metaobjects/` dir, metadata sources, `@metaobjectsdev/*` / - `com.metaobjects:*` / `metaobjects` / `MetaObjects.*` deps). -- [ ] Count metadata source lines + all `@generated` / `DO NOT EDIT` files repo-wide. -- [ ] **Owned-generators check:** which generators does the project own at - `codegen/generators/*` (via `meta eject`, or `meta init` on a CLI before 1.0.4), and - which does it import from `@metaobjectsdev/codegen-ts/generators`? Both are supported - from 1.1. Two findings to look for. **An unmodified owned copy** is duplication that - falls behind the reference: `meta eject --list --format text` marks each copy, and one - marked `identical to the reference` should be replaced by the package import. That is - the only mark that proves a copy unmodified. `same content as the reference, your - formatting` and `DIFFERS` with `0 line(s) of your own` rule out added or edited lines, - not removed or reordered ones: confirm those from the file's history - (`git log -p -- codegen/generators/.ts` shows no edit after the eject) first, and - report a copy you cannot confirm as "possibly customized: check its history", not as a - copy to drop. For `entity`, - `routes` and `routes-hono` that holds only when every `codegen/runtime/` file the copy - reaches is also marked identical: an edited adapter is a customization, and such a copy - is not a finding. Those runtime rows appear only with `--format text` (or as the - `runtimeCopy` array inside the row's `source` object in `meta gen --list --format - json`); a listing with no runtime rows is not evidence that the adapter is unmodified. **An import of `entityFile` / - `queriesFile` / `routesFile` / `barrel` on a 1.0.x install** fails to load, because 1.0 - removed those four and 1.1 restored them: there it is an upgrade blocker, fixed by - upgrading to 1.1 or by ejecting. Importing anything from that subpath is otherwise - correct and is never a finding by itself. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) -- [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. - ---- - -## Phase 1a — Greenfield path +## Phase 0: triage -- [ ] **Shape inventory.** Catalog modelable shapes: entities/tables, DTOs, validation - schemas, routes, UI lists/forms, prompt sites. -- [ ] **Pick wedge:** one real entity (single-column PK, standard CRUD) to model first. -- [ ] **From-zero roadmap:** `meta init` → model the wedge → `meta gen` the data layer → - author a projection view → expand to routes/UI → add prompt pillar where LLM calls exist. - Owning the generators from day 1 is part of the roadmap. +- Is MetaObjects present? (A `metaobjects/` directory or other metadata sources; the + `@metaobjectsdev/*` / `com.metaobjects:*` / `metaobjects` / `MetaObjects.*` dependencies.) +- Count metadata source lines and every `@generated` / `DO NOT EDIT` file in the repo. +- Run the owned-generators check and the version check below. +- Classify the project **Greenfield** (none or minimal), **Partial** or **Deep**, and take + the matching path. -## Phase 1b — Partial / Deep path +### Owned generators -**Census:** generated output line/file counts + metadata/owned-generator lines. -Compute **leverage ratio** = `generated_lines / (metadata_lines + generator_lines)`; -healthy = multi-× (example: ~4.7k spine → ~15.7k generated ≈ 3.3×). **Never report a -generated-share or leverage figure alone, and never as a target:** pair it with the **net -hand-written line change**, a figure to report and not the cost test (hand-written lines -removed minus generator and metadata lines added). A share can rise while total hand-written -code grows. +Find which generators the project owns at `codegen/generators/*` (through `meta eject`, or +`meta init` on a CLI before 1.0.4) and which it imports from +`@metaobjectsdev/codegen-ts/generators`. Both are supported from 1.1. The import is the right +choice for a generator the project does not change, and is never a finding by itself. -**Coverage matrix:** per entity/projection/value — query helpers? view? routes? UI? -The gap between "modeled + query helpers" and "has view + route + UI" is the headline -lopsidedness. +Every port owns generators the same way. Run each port's listing (TypeScript +`meta eject --list --format text`, Python `metaobjects gen --list`, Java / Kotlin +`mvn metaobjects:eject -Dlist`, C# `dotnet meta gen --list`) and read each row for what it +proves: -**Surface review — 8 axes (independently runnable).** -Work the full `references/capability-checklist.md` on every axis. Check calibration -guards (`references/calibration.md`) before raising a finding. **Verify, don't assume** — read the -code behind a grep hit; a "duplicate" validator's *divergence* is the finding. - -Axes (the full hunt for each is in `references/surface-review-axes.md` — open it before working an axis): +| The listing says | What that proves | What to do | +|---|---|---| +| `identical to the reference` | The copy is unmodified. This is the only mark that proves it. | Duplication that falls behind the reference: recommend the package import. | +| `same content as the reference, your formatting`, or `DIFFERS` with `0 line(s) of your own` | No added or edited lines. Removed or reordered lines are not ruled out. | Confirm from the file's history (`git log -p -- codegen/generators/.ts` shows no edit after the eject). A copy you cannot confirm is reported as "possibly customized: check its history", not as a copy to drop. | +| `DIFFERS` with lines of its own | Nothing by itself. The listing prints `DIFFERS` both for a deliberate customization and for a copy gone stale by version, and `M of your own` includes every line the reference has since removed or rewritten, which are older upstream lines. | Run the history check on every such row. Report two figures separately: lines behind the reference, and lines of the project's own that the history confirms. A copy stale by version is a finding (`owned-generator-stale`). | + +- **Runtime adapters.** For `entity`, `routes` and `routes-hono`, "unmodified" holds only when + every `codegen/runtime/` file the copy reaches is also marked identical: an edited adapter + is a customization, and such a copy is not a finding. Those runtime rows appear only with + `--format text` (or as the `runtimeCopy` array inside the row's `source` object in + `meta gen --list --format json`); a listing with no runtime rows is not evidence that the + adapter is unmodified. +- **A 1.0.x install.** An import of `entityFile` / `queriesFile` / `routesFile` / `barrel` + fails to load there, because 1.0 removed those four and 1.1 restored them. That is an + upgrade blocker, fixed by upgrading to 1.1 or by `meta eject ` if the project has to + stay on 1.0.x. +- **One total across every port:** unmodified owned-generator lines over all owned-generator + lines, where unmodified counts only copies proven unmodified. Report the proven copies + together as one finding, `owned-generator-stock-copies`, listing each copy and its port's + undo command. + +### Cross-language version consistency + +If the project uses MetaObjects in more than one language (a TypeScript web client with a +Java, Python or C# backend, say), list every MetaObjects package across every ecosystem (npm +`@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and +record each resolved version. + +**The version lines differ by ecosystem, so drift cannot be judged by eye.** npm, PyPI and +NuGet are on `0.x` / `1.x` and Maven on `7.x` / `8.x`: a `0.12` beside a `7.7` looks fine and +can be badly out of step. Compare instead: + +- **The `metamodelVersion` each port reports** (the shared spec version on the registry + manifest). A mismatch is real cross-language drift and a finding: the ports disagree on + vocabulary or wire behavior. +- **Each port's release.** A match on `metamodelVersion` is not enough, because added + vocabulary does not move it. Line up each ecosystem's version for the same CHANGELOG entry; + a port on an older release is a finding when the model uses vocabulary that release lacks. +- **The latest release.** Also flag any port not on the latest release for its ecosystem. + +This failure has been seen in practice: newest backend, stale client, invisible because the +numbers differ. + +## Phase 1a: the Greenfield path + +- **Shape inventory.** Catalog the modelable shapes: entities and tables, DTOs, validation + schemas, routes, UI lists and forms, prompt sites. +- **Pick a wedge:** one real entity (single-column PK, standard CRUD) to model first. +- **From-zero roadmap:** `meta init` → model the wedge → `meta gen` the data layer → author a + projection view → expand to routes and UI → add the prompt pillar where LLM calls exist. + Choosing and owning generators from day one is part of the roadmap. + +## Phase 1b: the Partial / Deep path + +**Census.** Generated output line and file counts, plus metadata and owned-generator lines. +Compute the **leverage ratio**, `generated_lines / (metadata_lines + generator_lines)`; a +healthy one is a multiple (for example about 4.7k lines of model and generators to about +15.7k generated, 3.3×). Do not report a generated-share or leverage figure alone, or as a +target: pair it with the **net hand-written line change** (hand-written lines removed minus +generator and metadata lines added), because a share can rise while total hand-written code +grows. + +**Coverage matrix.** Per entity, projection and value object: query helpers? view? routes? +UI? The gap between "modeled, with query helpers" and "has view, route and UI" is the +headline lopsidedness. + +**Shape coverage census.** The coverage matrix lists modelled entities only, so a shape +nobody modelled never appears in it. Count the other side too. List every shape that crosses +a boundary: database tables and views, request and response bodies, queue and socket +messages, prompt inputs, LLM replies, and file formats the project reads or writes. For each +shape, record whether it is modelled, and for each layer that states it (DDL or migration, +ORM model, validator, DTO, client type, prompt payload, reply parser) whether that statement +is **generated**, **derived** from generated code (a type built from a generated type, a +`z.infer` of a generated schema), or **hand-declared**. Report +`generated or derived statements / all statements` and list the unmodelled shapes. A table +present in the database or the migrations with no entity or projection behind it is a +finding (`unmodelled-table`). Like the leverage ratio this is a measurement, never a target: +an unmodelled shape is a finding only where the cost test says modelling it pays, or it is a +table. + +**Surface review.** The axes can be run independently. Work the full +`references/capability-checklist.md` on every axis; the hunt for each axis is in +`references/surface-review-axes.md`. For a "duplicate" validator, the place where it +diverges from the model is the finding. - **A.** Codegen candidates — API / server routes · **B.** Codegen candidates — web / client - **C.** Drift hotspot — validators, mappers, runtime models · **D.** Prompt pillar - **E.** Owned generators and scaffold-and-own · **E2.** Capability ledger (`requirement.*`, opt-in) -- **F.** Drift-gate adoption · **F2.** Over-generation (codegen waste) -- **G.** Runtime-contract anti-patterns · **G2.** `own*()` accessor discipline (a correctness defect, not advisory) +- **F.** Drift-gate adoption — does it block? · **F2.** Over-generation and generated-but-bypassed (codegen waste) +- **G.** Runtime-contract anti-patterns · **G2.** `own*()` accessor discipline (a correctness defect, not advisory) · **G3.** Guarded status transitions (every write to a status-like enum column is conditional on the current value; the fix goes through the port's ORM with generated constants, never raw SQL) - **H.** Authoring correctness / ADR conformance · **H2.** Wrong native type (`field.string` + `@dbColumnType: uuid`) - **I.** Vocabulary hygiene / modernization (advisory, never a failing finding) -**Phase 4 — Synthesize** into the tiered roadmap and populate both artifacts. - ---- +Then synthesize the findings into the tiered roadmap and write both artifacts. -## Classification scheme (every surface; classify on codegen AND runtime) +## Classifying a surface (on codegen and on runtime) | Class | Meaning | Action | |---|---|---| @@ -135,102 +180,105 @@ Axes (the full hunt for each is in `references/surface-review-axes.md` — open | **BESPOKE (keep)** | Genuine custom: irreducible SQL (recursive CTEs, window functions, set ops — NOT plain count/sum/avg rollups, which are `origin.aggregate` on a projection), graph, SSE, auth, search, viz. | Leave hand-written — still import generated types. | | **VOCAB CANDIDATE (advisory)** | A recurring, closed hand-coded pattern (parallel integration modules / an ad-hoc string discriminator) that project-registered vocabulary — a custom subtype/attr via a provider — plus a small owned generator would own. | Propose the provider + `metadata_sketch`; apply the ADR-0037 ordered test; advisory only. | -**Gold-standard exception.** A hand-written component that *derives* from generated metadata -cannot drift — flag as good. A "bespoke" component hardcoding a shape metadata knows is a -hidden candidate. **Stub trap:** demo-data routes have nothing to replace — classify -"candidate (future) — not DB-backed". - ---- - -## Owned-codegen & scaffold-and-own assessment - -- A config may import `entityFile` / `queriesFile` / `routesFile` / `barrel` from - `@metaobjectsdev/codegen-ts/generators` or from owned `codegen/generators/*`. Both are - supported from 1.1, and the import is the right choice for a generator the project does - not change. The import is a blocker only on a 1.0.x install, where those four do not - resolve: recommend upgrading to 1.1, or `meta eject ` if the project has to stay - on 1.0.x. On 1.1 the finding is the reverse case, an owned copy proven unmodified by - the Phase 0 owned-generators check: recommend the package import. Importing any other - generator from that subpath is correct and is not a finding. -- Audit owned generators: (a) regenerate clean? (b) drifted from reference templates — - intentional (good) vs stale/accidental (missed upstream fix)? (c) hand-rolling a walk - that a declarative `scope` + `outputPattern` could replace? (d) bespoke shape better as - a `templateGenerator` than a forked generator? -- **Authoring ladder:** built-in fits → import it as shipped · close → **eject it and - customize the copy** - · new shape → **author a declarative template-spec / custom generator from the metadata** - · genuinely un-modelable → hand-write (still import the generated types). -- **Generator-gap check:** missing generators that block the biggest wins? Recommend per gap: - own + customize / author a template-spec / fix upstream / stopgap. **Cost-test every - recommendation to generate** (`metaobjects-codegen` → `references/owning-generators.md`): an - owned generator is worth it only if generator + output is smaller than the code it replaces, - more instances are expected, or drift protection is the point. A layer that fails is - ACCEPTABLE, and an owned generator larger than the code it replaced is itself a finding. - A general-shape generator belongs in the library, not in each app. -- **Verify the DB artifact, not just the types** — computed view columns may appear in the - contract but be dropped from the view DDL; the contract may lie. -- **An *undeclared* hand-authored DB view is invisible to `meta verify --db`.** A view that is - neither modeled nor carried in the `source.rdb` `@sql` / `@unmanaged` escapes is *unmanaged* - (informational only — never actionable drift, never auto-dropped), so a hand-written view - standing in for an expressible `object.projection` / entity read-view can never be outsourced - to the drift gate; hunt it here (drift signature 8 in `references/drift-signatures.md`). Once carried in `@sql` (#208) it IS - registered, fingerprinted, and drift-checked — no longer audit-only. -- **Version skew:** check *actually-resolved* package versions, not declared; consuming a fix - requires a coordinated lockstep bump, not a source-file copy. - ---- - -## Semantic-constraint ratification (prevents over-modeling) - -When folding hand validators into metadata, apply human judgment per constraint. -A constraint enters **shared metadata** only if it is a **true cross-language domain -invariant**; a one-consumer preference stays in a thin local refinement layer. - -Cross-field rules **are** modelable (`comparison` / `atLeastOne` / `requiredWhen` / -`presentIff`); ratification decides *which* belong in shared metadata. Output a -**ratification table**: KEEP-IN-METADATA / LOCAL-REFINEMENT / DROP + rationale — -human-approved, never applied silently. Distinguish `required` from has-a-safe-default -(`@default` often fixes the over-requiring bug). A core attr ripples cross-port; for a -one-consumer need, read it codegen-locally. - ---- - -## Scoring & maturity model — three surfaces (no single global score; bands not decimals) - -1. **Headline MATURITY TIER** — Greenfield → Partial → Deep → Exemplary; worst-of with - prerequisite gating (a missing pillar can't be averaged away); rendered with **the single - next unmet check** ("you're Partial; the next rung needs `verify` in CI"). -2. **Per-pillar breakdown (never rolled into one number)** — `pillar | tier | top gap` over +**A hand-written component that derives from generated metadata cannot drift: flag it as +good.** A "bespoke" component hardcoding a shape the metadata knows is a hidden candidate. +A demo-data route has nothing to replace: classify it "candidate (future), not DB-backed". + +## Owned generators and generator gaps + +- **Audit each owned generator.** Does it regenerate clean? Has it drifted from the + reference on purpose (good) or gone stale (a missed upstream fix)? Decide that from the + copy's history, as in Phase 0, not from the listing's count. Does it hand-roll a walk that + a declarative `scope` + `outputPattern` could replace? Would a bespoke shape be better as a + `templateGenerator` than a forked generator? +- **The authoring ladder to recommend from:** a built-in fits → import it as shipped; close → + eject it and customize the copy; a new shape → author a declarative template-spec or a + custom generator from the metadata; cannot be modelled → hand-write, still importing the + generated types. +- **Generator gaps.** Are missing generators blocking the biggest wins? Recommend per gap: + own and customize, author a template-spec, fix upstream, or a stopgap. Cost-test every + recommendation to generate (`metaobjects-codegen`, `references/owning-generators.md`): an + owned generator is worth it only if generator plus output is smaller than the code it + replaces, more instances are expected, or drift protection is the point. A layer that + fails is ACCEPTABLE, and an owned generator larger than the code it replaced is itself a + finding. A general-shape generator belongs in the library, not in each app. +- **An undeclared hand-written database view is invisible to `meta verify --db`.** A view + that is neither modeled nor carried in the `source.rdb` `@sql` / `@unmanaged` escapes is + reported as informational only, so a hand-written view standing in for an expressible + `object.projection` or entity read-view can only be found here (drift signature 8 in + `references/drift-signatures.md`). Once carried in `@sql` it is registered and + drift-checked. + +## Ratifying constraints before they enter the model + +When folding hand-written validators into metadata, each constraint needs a human decision, +because a constraint in shared metadata reaches every port. It belongs there only if it is a +true cross-language domain invariant; one consumer's preference stays in a thin local +refinement layer. + +Cross-field rules are modelable (`comparison` / `atLeastOne` / `exactlyOne` / +`requiredWhen` / `presentIff`); ratification decides which belong in shared metadata. Output +a **ratification table**: KEEP-IN-METADATA / LOCAL-REFINEMENT / DROP, with the rationale, +for a human to approve. Never apply it silently. Tell `required` apart from has-a-safe-default +(`@default` often fixes an over-requiring bug). + +## Scoring: no single score, bands not decimals + +1. **Headline maturity tier.** Greenfield → Partial → Deep → Exemplary, worst-of with + prerequisite gating (a missing pillar cannot be averaged away), shown with the single + next unmet check ("you're Partial; the next rung needs a blocking `verify` in CI"). +2. **Per-pillar breakdown, never rolled into one number.** `pillar | tier | top gap` over codegen / runtime / drift-gate / prompts. This is the core deliverable. -3. **Binary CI drift gate** — prominent and separate: **"Is `meta verify` drift detection - wired into CI?"** It is binary because the risk is binary. - -Coarse bands only (none / some / most / all). Worst-of within a pillar. On re-run, grade -the delta. Lead with gaps, not the grade. - -**Vocabulary hygiene (axis I) is advisory** — it surfaces as modernization -opportunities in the roadmap, scored as such, and **never gates a tier or fails the -audit.** Dated-but-working vocabulary is a quality nudge, not a defect. - ---- - -## Report - -**Two artifacts:** `.metaobjects/adoption-audit.json` + rendered Markdown. - -**Markdown sections (lead with Scorecard):** 0. Scorecard (tier + pillar table + CI gate) · -1. Triage + census · 2. Coverage matrix · 3. Per-surface classification tables · 4. Drift -findings (active bugs first) · 5. Owned-codegen + generator gaps · 6. Drift-gate adoption · -7. Runtime-contract + authoring-correctness (axes G+H) · 8. Semantic-constraint ratification · +3. **Binary CI drift gate**, prominent and separate: "Does `meta verify` drift detection + block every route to production?" It is binary because the risk is. YES only when axis F + scores the gate **BLOCKING**; RUNS BUT DOES NOT BLOCK and ABSENT both answer NO, with the + reason (exit code swallowed, tolerated error count, a deploy path that skips it, no CI). + Local hooks with no tracked installer do not count. +4. **Used as described.** One line, separate from the tier: does the project use what it + adopted the way MetaObjects documents it? Built from four measurements, each shown with + its numbers: generated artifacts consumed rather than bypassed (axis F2, `consumed / + emitted` and the `generated-and-bypassed` count); the gate blocks (axis F score); prompt + payload fields linked to entity fields (axis D, `linked / (linked + unlinked copies)`); + and boundary shapes generated or derived (the shape coverage census). Render it as + `Used as described: — generated forms 5/12 consumed · gate RUNS BUT DOES NOT + BLOCK · payload fields 6/10 linked · shapes 50% generated or derived`, banded by its worst + part. + +Coarse bands only (none / some / most / all), worst-of within a pillar. Lead with the gaps, +not the grade. Vocabulary hygiene (axis I) is advisory: it appears as modernization +opportunities in the roadmap and never gates a tier, because dated vocabulary that works is +not a defect. + +**On a re-run, compare with the previous audit.** If `.metaobjects/adoption-audit.json` +already exists, read it before starting and keep it as the baseline. Match each earlier +finding to this run's by `id` plus location, and give every earlier finding a `status`: +**fixed** (the location no longer shows it; say what changed), **open** (still present, +carrying its original `first_seen`), or **deferred** (the project recorded a decision not to +fix it now, in a commit, an ADR, a tracked issue or a code comment, quoted as +`deferred_reason`). A finding that is still present with no recorded decision is open, never +deferred. New findings are `new`. Report the counts per status at the top of the report, +and show each scorecard line beside its previous value. + +## The report + +Two artifacts: `.metaobjects/adoption-audit.json` and the rendered Markdown. + +**Markdown sections, Scorecard first:** 0. Scorecard (tier, pillar table, CI gate, used as +described; on a re-run, the fixed / open / deferred / new counts) · 1. Triage and census +(including the owned-generator unmodified-lines total and the shape coverage census) · +2. Coverage matrix · 3. Per-surface classification tables · 4. Drift findings (active bugs +first) · 5. Owned generators and generator gaps · 6. Drift-gate adoption · +7. Runtime-contract and authoring-correctness (axes G and H) · 8. Constraint ratification · 9. Prompt-pillar assessment · 10. Prioritized roadmap: Tier 1 drift kill → Tier 2 existing -generators → Tier 3 new generators/projections → Tier 4 dynamic-runtime/prompts/cross-port. -Each roadmap item: LOC retired, prerequisite, **parity-gate before deleting hand-written code**. +generators → Tier 3 new generators and projections → Tier 4 dynamic runtime, prompts, +cross-port. Each roadmap item: lines retired, prerequisite, and the parity gate to pass +before hand-written code is deleted. **Each finding in `.metaobjects/adoption-audit.json`:** | Field | Content | |---|---| -| `id` | stable kebab id (e.g. `handwritten-crud-route`, `manual-zod-validator`) | +| `id` | stable kebab id (e.g. `handwritten-crud-route`, `manual-zod-validator`, `enum-literal-spelling`, `unguarded-status-transition`, `owned-generator-stale`) | | `title` | "you hand-wrote X that metadata can generate / model" | | `pillar` | `codegen` / `runtime` / `drift` / `prompt` | | `surface` | `entity` / `route` / `validator` / `repository` / `dto` / `hooks` / `prompt` / `migration` | @@ -243,19 +291,34 @@ Each roadmap item: LOC retired, prerequisite, **parity-gate before deleting hand | `next_command` | the exact command / skill that performs the cutover (see bridge below) | | `parity_gate` | the specific check proving behavior-equivalence | | `tier` | 1–4 | +| `status` | `new` / `open` / `fixed` / `deferred` against the previous audit (`new` on a first run) | +| `first_seen` | date of the audit that first raised it (carried forward on re-runs) | +| `deferred_reason` | for `deferred` only: the recorded decision, quoted, and where it is recorded | + +Fixed findings stay in the file with `status: fixed` for one run, so the next reader sees +what closed. + +**Top-level fields**, beside `findings[]`: + +| Field | Content | +|---|---| +| `audited_at`, `commit` | when the audit ran and the commit it read | +| `previous` | `audited_at` and `commit` of the baseline audit, or `null` on a first run | +| `tier`, `pillars[]` | headline tier and `{ pillar, tier, top_gap }` per pillar | +| `ci_gate` | `{ score: "BLOCKING" \| "RUNS_BUT_DOES_NOT_BLOCK" \| "ABSENT", exit_code, error_count, swallowed_at[], deploy_paths_skipping[] }` | +| `used_as_described` | `{ band, generated_consumed, generated_emitted, bypassed_count, gate_score, payload_fields_linked, payload_fields_unlinked, shape_statements_generated_or_derived, shape_statements_total, unmodelled_shapes[] }` | +| `owned_generators` | `{ unmodified_lines, total_lines, copies[] }`, one total across every port | +| `status_counts` | `{ new, open, fixed, deferred }` | Within each tier, sort by impact ÷ effort (quick wins first). Tier 1 leads. -### Audit → action bridge +### From audit to action -The audit never edits code. Pattern: **dry-run → review the diff → apply**. +The audit never edits code. The pattern for whoever acts on it is dry-run → review the diff → +apply, one surface at a time, one commit each. -- Propose metadata → `metaobjects-authoring` + brainstorming flow (human reviews). -- Generate → `meta gen`; **`meta gen --dry-run`** is the review-the-diff step → skill: - `metaobjects-codegen`. -- Prove parity → **`meta verify --codegen`** is the drift gate → skill: `metaobjects-verify`. -- Routes / runtime / web → skill: `metaobjects-runtime-ui`. -- Prompts → skill: `metaobjects-prompts`. -- Cut over **one surface at a time, one commit each**. -- A separate guided-cutover skill (not this one) reads `adoption-audit.json` and walks - findings one tier/surface at a time with human approval at each step. +- Propose metadata → `metaobjects-authoring`, with a human reviewing. +- Generate → `meta gen`; `meta gen --dry-run` is the review-the-diff step → `metaobjects-codegen`. +- Prove parity → `meta verify --codegen` is the drift gate → `metaobjects-verify`. +- Routes, runtime, web → `metaobjects-runtime-ui`. +- Prompts → `metaobjects-prompts`. diff --git a/.claude/skills/metaobjects-audit/references/calibration.md b/.claude/skills/metaobjects-audit/references/calibration.md index 4271e57..fb00f1f 100644 --- a/.claude/skills/metaobjects-audit/references/calibration.md +++ b/.claude/skills/metaobjects-audit/references/calibration.md @@ -10,6 +10,9 @@ - Planned, not shipped - Cross-port version-number skew - Stale upstream prose +- Include-only templates +- Owned generator copies with lines of their own +- Enum-member literals at a checked position - **Filter-operator route codegen — the baseline grammar ships in all five ports.** The `?filter[field][op]=value` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`, @@ -17,9 +20,11 @@ `invalid-op` / `in`-over-cap 400s) is **generated in every port** (Java `SpringControllerGenerator`, C# `RoutesGenerator`, Python `router_generator`, Kotlin `KotlinSpringControllerGenerator`, TS) — gated by the api-contract corpus in BOTH lanes. **Flag hand-rolled filter parsing anywhere.** - Only the *richer* surface is genuinely **TS-only**: free-text `?search=`, the explicit - `filter[or][N]` / `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and - leading-wildcard gating — do NOT flag the absence of those in a non-TS port. + The *richer* list surface — free-text `?search=`, the explicit `filter[or][N]` / + `filter[and][N]` nested boolean combinators (+ their nesting-depth cap), and leading-wildcard + gating (ADR-0068) — passes in TypeScript and C#, and is **pending** in each other port until that port's + 1.3.0 REST-standard work lands. Do NOT flag the absence of those in a port that has not landed + them yet. - **Output-parser codegen** ships in **all five ports** — Java's `SpringOutputParserGenerator` *generates* the `Parser` (the Jackson `readValue` lives inside that generated file). A hand-rolled parser in a **non-generated** file where a **responding `template.prompt`** @@ -29,6 +34,9 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. +- **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). +- **An owned generator copy with lines of its own is not thereby customized.** The listing prints `DIFFERS` for a deliberate customization and for a copy stale by version, and counts lines the reference later removed as "of your own". Check the copy's history before calling either (Phase 0, owned-generators check). +- **An enum-member literal at a position the type checker verifies is not drift.** A value narrowed by the generated union or enum type breaks the build when the member is renamed. Signature 13 scores only a literal in a position nothing checks: a string-typed parameter, raw SQL, a JSON payload, an event name (`references/drift-signatures.md`). diff --git a/.claude/skills/metaobjects-audit/references/capability-checklist.md b/.claude/skills/metaobjects-audit/references/capability-checklist.md index e145d1c..5b79c83 100644 --- a/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -58,7 +58,11 @@ classify it (using the classification scheme in `SKILL.md`) and route the cutove - **`field.date` / `field.time` / `field.timestamp`** (`@autoSet`) — hunt hand-stamped `createdAt` / `updatedAt` assignments and ad-hoc temporal parsing; `@autoSet` stamps them. - **`field.enum`** (`@values`) — hunt hand-written TS unions, language `enum`s, or DB - `CHECK ... IN (...)` lists that restate a modeled enum's members. + `CHECK ... IN (...)` lists that restate a modeled enum's members. Two more hunts on the same + capability: a member or event name typed as a hand string beside the generated constant + (`drift-signatures.md`, signature 13), and a status-like enum column written without a + condition on its current value (`surface-review-axes.md`, G3: every write conditional, through + the port's ORM with generated constants, never raw SQL). - **`field.uuid`** — hunt UUIDs typed as bare strings / hand-validated. - **`field.object`** (`@objectRef`, `@storage`) — hunt hand-flattened owned columns or hand-rolled jsonb (de)serialization the `@storage` mode (`flattened`/`jsonb`/`subdocument`) @@ -182,10 +186,11 @@ soft-delete / status / type view it models. `validator.regex`** — hunt hand field-level validation (presence, length, numeric range, array bounds, `@pattern` regex) the validator subtypes model. - **Cross-field validators** — `validator.comparison` (`@left`/`@op`/`@right`, e.g. - "end ≥ start"), `validator.atLeastOne` (one-of-N present), `validator.requiredWhen` + "end ≥ start"), `validator.atLeastOne` (one-of-N present), `validator.exactlyOne` (exactly one of N + present), `validator.requiredWhen` (conditional-required), `validator.presentIff` (mutual presence). Hunt these as hand-coded - multi-field rules — they ARE modelable (see the Semantic-constraint ratification section in - `SKILL.md` to decide what belongs in shared metadata vs port-local). + multi-field rules — they ARE modelable (see "Ratifying constraints before they enter the + model" in `SKILL.md` to decide what belongs in shared metadata vs port-local). - **`validator.base`** — abstract base. ## View / Layout — `view.*`, `layout.*` @@ -343,8 +348,10 @@ to nothing, and does not check that each claimed node complies). - **CALIBRATION — per-port codegen gaps:** the core `?filter[field][op]` filter grammar (all 9 operators + the generated allowlist + `invalid-field` / `invalid-op` / `in`-over-cap 400s) is **generated in all five ports** (api-contract corpus, both lanes) — **flag hand-rolled - filter parsing anywhere.** Only the richer surface (`?search=`, explicit - `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating) is TS-only. + filter parsing anywhere.** The richer list surface (`?search=`, explicit + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript and C#, and is pending in each other port until its 1.3.0 REST-standard work lands — do not + flag its absence in a port before then. Output-parser codegen also ships in **all five ports**, keyed on a **responding `template.prompt`** (`@responseRef`), never on a `template.output` (ADR-0052) — Java's `SpringOutputParserGenerator` *generates* the parser (the Jackson `readValue` lives inside @@ -353,14 +360,18 @@ to nothing, and does not check that each claimed node complies). non-`table` source-kind / flattened-object codegen is partial). **C#** has no ObjectManager runtime tier (EF Core *is* the runtime) — hand services over the generated `DbContext` are expected. -- **Single-source config** — `apiPrefix` (URL prefix wired into routes + hooks), the +- **Single-source config** — `apiPrefix` (where the generated routes mount; the web client + takes its prefix from `baseUrl` on the fetcher provider, so check the two agree), the `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — planned, not yet shipped:** the declared-API surface (`api.base`, - `api.operational`, `operation.query`, `operation.command`, `binding.rest`) and MCP exposure - of declared prompts/tools are **not yet in the registry** — their absence is not an adopter - defect; do NOT audit for them. +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface + (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles + (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* version drift (mixed package versions within one port, or a runtime package in diff --git a/.claude/skills/metaobjects-audit/references/drift-signatures.md b/.claude/skills/metaobjects-audit/references/drift-signatures.md index 351893d..492c015 100644 --- a/.claude/skills/metaobjects-audit/references/drift-signatures.md +++ b/.claude/skills/metaobjects-audit/references/drift-signatures.md @@ -13,6 +13,7 @@ - 10. N declarations of one field across objects - 11. A metadata-derived value spelled a second time by hand - 12. An open JSON bag whose readers agree on a shape +- 13. An enum member or event name typed by hand beside the generated constant Per finding: `file:line` → what → generated-equivalent exists? → recommendation. @@ -35,7 +36,7 @@ Per finding: `file:line` → what → generated-equivalent exists? → recommend **Hunt from the declaration outward, never from code shapes inward.** (1) Build the value list from the generated artifacts, because they already carry every derived value after every transform — naming strategy, pluralized path, humanized label: read `Names` and, on TypeScript, the `.meta.ts` twin. Where the port emits no names artifact yet, derive the list from the metadata directly (`@table` / `@schema` / `@column`, else the naming strategy applied to the field name; `@values`; `@title`) and record the un-wired generator as the first finding (below). (2) Grep the non-generated tree once — code AND checked-in config, fixtures, YAML, JSON, `.env`, OpenAPI fragments — with an alternation of those VALUES as literals; distinctive values (`"email_address"`, `"/subscribers"`, `"edited_approved"`) score on the hit, generic ones (`"id"`, `"name"`, `255`) only by reading the consumer, never by count. This step is what finds the topic name, the index field, the `COPY` header and the flag key without knowing they exist. (3) Trace each hit to its CONSUMER and ask what that consumer matches it against. Matched against the schema, the generated route table, a generated wire shape or a generated label → the metadata owns it, apply the discriminator. Matched against something the app chose — its own page-route table, its own copy deck — → not owned, not this finding. (4) Only then run the shape greps — raw SQL, `fetch(` / `app.get(` / a `queryKey`, a hand validator — as the second pass, for what a value grep cannot see: a literal that has ALREADY drifted from the declared value, a concatenated or interpolated name, a case-transformed one. - **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a flattened value-object composite column belongs to no single field of either object; a relationship-synthesized FK column is derived, never declared; a write-through entity's replica view name is not in the artifact, which holds the PRIMARY source's. A hand-written repository that imports `Names` is the gold standard — call it out as good. + **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a relationship-synthesized FK column is derived, never declared. (A flattened value object's member column and a write-through entity's replica view name are NOT exempt: the artifact carries both, as the field's member column constant and the source in role `replica`.) A hand-written repository that imports `Names` is the gold standard — call it out as good. **Score only where a constant actually exists.** A fact declared in the project's CODEGEN CONFIG rather than in metadata — a bespoke route mount path, a hand-chosen JSON envelope key — is genuinely spelled twice when a client re-types it, but no generated constant holds it. That is a GENERATOR GAP, reported as one, never a literal-site finding: never invent a constant that the emitters do not emit. @@ -55,3 +56,12 @@ Per finding: `file:line` → what → generated-equivalent exists? → recommend **Do NOT flag:** a bag whose readers genuinely pass it through (logged, echoed, stored, forwarded to a third party) without reading a key; a third-party or LLM raw response whose shape is not the adopter's to declare; an **array of scalars**, which is `isArray: true` on the base subtype and never an object; a bag the metadata's own comment justifies as open with a reason. **Remedy — a ladder, chosen by the WRITER's declared type, and every rung gives the consumer a TYPED HANDLE rather than a string to get and set.** `list[X]` ⇒ the base subtype + `isArray: true`. `dict[str, X]` with a known `X` ⇒ **`field.map` + `@objectRef`** (a value object) or `@valueType` (a scalar) — registered vocabulary that emits `jsonb("col").$type>()` and `z.record(z.string(), X)`. **Check the CONSUMER before recommending this rung: `field.map` codegen now completes on all five ports** (Java types it `java.util.Map`; C# emits the `Dictionary` property and its EF jsonb storage mapping), **but no persistence- or api-contract-conformance fixture exercises `field.map` on ANY port, and the runtime persistence tier is uneven** — only Python's `ObjectManager` encodes a map, while `runtime-ts`, Java's OMDB and the Kotlin Exposed lane carry none. So where GENERATED CODE is the consumer, check the port before recommending this rung — nested map values are validated on every write path on every port as of 1.0.1 ([#362](https://github.com/metaobjectsdev/metaobjects/issues/362) — before that, Java skipped the cascade on TPH write paths and C# skipped it everywhere, silently accepting invalid values rather than erroring). **Check the adopter's pinned version before recommending this rung to a Java-TPH or C# consumer: on 1.0.0 the hole is open and they need their own boundary check.** Prefer a value object where a PORT RUNTIME must read the column back; a genuinely dynamic key set stays a bag. A serialized DTO / dataclass / `@Serializable` class ⇒ declare it as an `object.value` and point the field at it with `field.object` + `@objectRef` + `@storage: jsonb`. Only `dict[str, Any]` whose readers pin no key stays an open bag. **What the adopter GETS, per port** — this is the point of the conversion and worth stating in the finding: TypeScript emits the Drizzle column as `.$type()` plus the VO's own Zod schema and inferred type; Python annotates the field with the referenced VO's Pydantic model (and its `Create` on the wire, so a nested violation still validates); Kotlin emits typed Exposed jsonb codecs backed by a shared Jackson `MetaJsonbMapper`. In none of them does the consumer touch a JSON string — that is what the open bag costs them today, since `unknown` forces every reader to cast. The column stays jsonb, so this is a codegen/contract change and not necessarily a migration; what changes is that `unknown` becomes a generated type, the casts delete, and the keys become metadata-owned — which also promotes their literals into drift signature 11's scope, where the `->>'key'` sites were previously exempt because the metadata owned nothing. **Verify the column type is genuinely unchanged before promising no migration**, and parity-gate each converted read against the raw-SQL one before deleting it. Convert one column at a time: the shape is a judgment per bag, and a wrong guess declares a contract the writers do not honor. + +13. **An enum member or event name typed as a hand string beside the generated constant.** Signature 11 covers physical names; this is the same rule for a model's enum values and for the event or message names an enum member spells. A literal in non-generated code that EQUALS a member of a generated enum (or the name of a declared event) is a second spelling, and it is the commonest drift an estate that already uses the constants carries: the file imports `CouncilStatusEnum` and uses `CouncilStatusEnum.enum.complete` on one line, then writes `status: "error"` on the next. The two spellings agree today and nothing ties them together. **Hunt VALUE-first, from the declaration outward:** list every enum's members from the metadata (`@values` on each `field.enum`, plus the member names of any enum-backed event or message type), then grep the non-generated tree, config and fixtures included, for each member as a quoted literal. Distinctive members (`"edited_approved"`, `"awaiting_review"`) score on the hit; generic ones (`"error"`, `"done"`, `"active"`) only by reading the site, because the same word may belong to something the metadata does not own. **A file that already imports the enum's generated constant is the strongest tell**: its author knew the constant existed, so a bare literal of another member of that enum in the same file is almost never intentional. Count those first. + + **Apply signature 11's discriminator, then say which side of it the site is on.** Rename the member in metadata and regenerate. Where the site is RESOLVED, the regeneration breaks it before anything runs and it is not a finding: a value narrowed by the generated union (`export type = "a" | "b"` on TypeScript, a `Literal[...]` annotation on Python, a generated `enum` type on Java, Kotlin and C#) at a position the compiler or type checker actually checks. Where the site is COMPARED, it survives the regeneration and fails later, on data: a literal in a string-typed position (a `Record`, a `string` parameter, a loosely typed object spread into a `.set(...)`, a `dict`), in raw SQL (`WHERE status = 'error'`), in a JSON payload or fixture, as a broker topic or an SSE / websocket event name, in a `switch` over a `string` that the type checker cannot exhaust, or in a comparison against a column read back as `string`. **Verify the position before scoring it, never the shape of the literal:** the TypeScript case that earned the exemption (332 narrowed literals, 0 findings) and the case that earned this signature (`status: "error"` beside `CouncilStatusEnum.enum.complete`) look identical in a grep, and only the type at the site separates them. If you cannot tell which side a site is on, read the declared type of the target; report it as unverified rather than skipping it. + + **Do not flag:** a literal narrowed by the generated union or enum type at a checked position; a value the metadata does not own (an application-level state machine's label that merely coincides with a member, a page route, copy); a literal inside a generated file; and a test asserting the wire value of a member on purpose (a test that pins `"complete"` is a contract test and says so). A literal inside a `source.rdb` `@sql` body is metadata and is exempt, as in signature 11. + + **Remedy:** reference the generated constant, which is the one rule for every port: the Zod enum's member (for example `CouncilStatusEnum.enum.complete`) or the generated union type on TypeScript, the generated `Literal` alias or enum on Python, the generated enum constant on Java, Kotlin and C#. In raw SQL the value moves to a bound parameter fed from the constant (never a literal inside the SQL text), and the table and column in that statement are signature 11's names artifact. Report the site count as `/ sites` exactly as signature 11 does, and carry a deferral forward with its count. This signature needs no names artifact; it needs the generated enum type. If the project generates none, the un-wired `entity` generator is the first finding. + diff --git a/.claude/skills/metaobjects-audit/references/prompt-anti-patterns.md b/.claude/skills/metaobjects-audit/references/prompt-anti-patterns.md index 92cfb47..af230bb 100644 --- a/.claude/skills/metaobjects-audit/references/prompt-anti-patterns.md +++ b/.claude/skills/metaobjects-audit/references/prompt-anti-patterns.md @@ -3,7 +3,7 @@ ## Contents - Census scope - Keeping the result in place -- Anti-pattern list +- Anti-pattern list (includes the unlinked-payload ratio) - Template-text duplication **The census covers EVERY module**, not only the application: test harnesses, simulators, @@ -26,6 +26,24 @@ format-built argument at the project's own LLM request call sites. **sourceless `object.projection`** carrying those origins (#210 — assembly origins on an `object.value` fail load with `ERR_SUBTYPE_RULE_VIOLATION`; `@payloadRef` accepts the sourceless projection). +- **Unlinked payload.** A declared payload shape is necessary, not sufficient: the check above + asks whether the payload IS a shape, this one asks where its fields COME FROM. For each object + a `@payloadRef` names, class every field: + - **LINKED** — a dotted `extends: Entity.field` (for example `"extends": "Customer.email"`), + or an origin that resolves to an entity field (`origin.passthrough` with + `@from: Customer.email`, or an `aggregate` / `first` origin whose `@of` names one). + - **CALLER-SUPPLIED** — no entity owns the value (the user's question, a run-time setting, a + date the caller computes). Say why for each; "the caller fills it" is not a reason when the + caller reads it off an entity. + - **UNLINKED COPY** — declared as a free-standing field, while the call site fills it from an + entity property (`payload.email = customer.email`, `email=customer.email`). + Report `linked / (linked + unlinked copies)` per payload and in total. Each unlinked copy is a + finding (`unlinked-payload-field`): renaming or re-typing the entity field will not fail + `verify --templates`, because the payload declares its own copy and the template still + matches that copy. Remedy: replace the field with `extends: Entity.field` (or a passthrough + origin on a sourceless projection). The `parity_gate` is a scratch-copy proof: rename the + entity field in a throwaway copy of the metadata and confirm the project's verify now fails, + where before the change it passed. - Silent-degradation hack (`try/except KeyError` or `?? ''` around formatting) — flag every instance. - Hand-rolled output parsing (regex / XML / ad-hoc JSON) vs a declared **responding `template.prompt`** (one carrying `@responseRef`) + generated `parse*` / `safeParse*` / @@ -41,4 +59,4 @@ format-built argument at the project's own LLM request call sites. `voRequest` / `voResponse` jsonb columns must be authored `field.object` — the loader must not mutate the tree; vendor SDK client + pricing are BYO (ADR-0024). - No `meta verify --templates` gate; no declared `@maxChars` / `@maxTokens` budget. -- **Template-text duplication.** Hash every external template file (`md5sum` the template dir) and diff within groups sharing a `payloadRef`. A byte-identical cluster, or N≥3 templates sharing an identical skeleton with only slot lines differing, is ONE prompt maintained N times — a wording fix must be applied N times and WILL be missed. Recommend a shared `{{> group/partial }}` include (the render engine inlines partials recursively) or one template + payload-carried variant fields. Do NOT flag: the per-node `payloadRef` / `@format` repetition across `template.prompt` nodes (loader-forced, not a copy); templates meant to diverge independently — require N≥3 and structural identity before flagging. +- **Template-text duplication.** Hash every external template file (`md5sum` the template dir; skip include-only files, below) and diff within groups sharing a `payloadRef`. A byte-identical cluster, or N≥3 templates sharing an identical skeleton with only slot lines differing, is ONE prompt maintained N times — a wording fix must be applied N times and WILL be missed. Recommend a shared `{{> group/partial }}` include (the render engine inlines partials recursively) or one template + payload-carried variant fields. Do NOT flag: the per-node `payloadRef` / `@format` repetition across `template.prompt` nodes (loader-forced, not a copy); templates meant to diverge independently — require N≥3 and structural identity before flagging; **an include-only template**. A template whose body is nothing but partial includes (every non-blank line is a `{{> group/partial }}` and there is no prose of its own) is already the fix this section recommends: the wording lives once in the partial, and the stub is the per-prompt entry point the loader requires. Several such stubs being byte-identical, or sharing the same include list, is the recommended shape, not a cluster. Drop include-only files from the hash groups BEFORE comparing, and apply the cluster test to what remains. A template that mixes includes with a skeleton of its own prose still counts, and its prose is what is compared. When every member of a cluster is include-only, report it as the gold standard, the way a repository that imports `Names` is called out as good. diff --git a/.claude/skills/metaobjects-audit/references/requirements.md b/.claude/skills/metaobjects-audit/references/requirements.md new file mode 100644 index 0000000..2bcebe9 --- /dev/null +++ b/.claude/skills/metaobjects-audit/references/requirements.md @@ -0,0 +1,154 @@ +# Requirements — the audit dimension + +This project declares `requirement.*` nodes, so the ledger is an auditable surface. Audit it +for **truthfulness**, not volume. A large ledger that lies is worse than a small one that +does not, because every later reader trusts it. + +Run `verify` first — the project's own: `meta verify`, `metaobjects verify`, +`mvn metaobjects:verify` or `dotnet meta verify`. Every port runs the same requirement +gate. It settles referential integrity mechanically — do not spend audit effort re-deriving +what a green run already proves. + +## Contents +- What verify has already proven (do not re-check by hand) +- Currency checks — run these before sampling +- What only a human or an agent reading the code can catch +- Scope — do NOT flag these as defects +- Reporting + +## What verify has already proven (do not re-check by hand) + +A run answers two different questions in two separate sections. Both are already-proven +ground; neither is worth an auditor's time. + +**The gate** settles referential integrity: links sit at or below the L4 floor, nesting +agrees with levels, `@status` values are legal, and references resolve (with dangling allowed +on `planned`, whose nodes do not exist yet). + +**The authoring lint** — printed under its own heading, advisory, and unable to change the +exit code — settles the naming and prose defects you would otherwise find by reading every +entry. **Only the Node `meta verify` prints it.** On a Python, Java, Kotlin or C# project +whose pipeline runs that port's `verify` alone, nothing below has been proven: run +the Node `meta verify` over the same metadata, or audit these by hand. + +| code | what a clean run has already proven | +|---|---| +| `WARN_REQUIREMENT_NAME_NOT_ADDRESSABLE` | no `name` is blank, space-padded, or carries a `.` / `/` / `:` that breaks the dotted path or the generated stub's filename | +| `WARN_REQUIREMENT_NAME_READS_AS_PROSE` | no `name` is a sentence sitting in the address slot | +| `WARN_REQUIREMENT_NAME_RESTATES_STATEMENT` | no `name` and `@statement` are the same sentence written twice | +| `WARN_REQUIREMENT_PROSE_EMPTY` | no `@statement` / `@counterexample` is declared-but-blank (the loader enforces presence, never content) | +| `WARN_REQUIREMENT_PROSE_DUPLICATED` | no `description` repeats `@statement` whole or as its opening sentence, and no `@counterexample` repeats it | +| `WARN_REQUIREMENT_INERT_DOC_SLOT` | no `summary` is set — nothing reads it, and `@statement` is already the required one-liner | +| `WARN_REQUIREMENT_TITLE_IS_AN_ID` | no `title` leads with a catalogue or ticket id | + +Three limits, and each puts something back on your list: + +- **It is one port's.** See above: establish which `verify` the project's CI runs before + crediting a green pipeline with the table. +- **The lint is mutable.** `--no-requirement-lint` / `META_NO_REQUIREMENT_LINT=1` silences the + advisory half while the gate still runs. **Establish whether the project mutes it** (§F of + the checklist asks this) — against a muted lint the whole table above proves nothing. +- **It reports only EXACT repeats.** A paraphrase — `description` restating `@statement` in + different words, a `@counterexample` that merely negates it — is invisible to the tool and + is a legitimate hand finding. + +`title` is deliberately NOT flagged as an inert slot; it is chartered as the entry's label and +is rendered (see item 6). Do not report a populated `title` as a defect. + +## Currency checks — run these before sampling + +A green gate proves the ledger's links resolve, not that the ledger keeps up with the code. +These three checks measure that, and the first one chooses the sample for item 1 below. + +**(a) Ledger stale.** From git history, take the commits that add a feature (a `feat:` / +`feat(...)` subject under Conventional Commits; otherwise merged feature branches or PRs +labelled as features) over the last six months or the last 50 such commits, whichever is +fewer. Report two numbers: the share of those commits that also change requirement metadata +(any file holding `requirement.*` nodes), and the count of feature commits since the most +recent change to that metadata. A share **under half**, or **more than ten** feature commits +since the last ledger change, is the finding `ledger-stale`, stating both numbers. The +feature commits that did not touch the ledger are the sample for item 1: read what each one +built and check that a requirement says so with a true status. + +**(b) Nothing implements a live claim.** Run the project's verify with the strict switch: +`meta verify --require-implementers`, `metaobjects verify --require-implementers`, +`mvn metaobjects:verify -Dmeta.verify.requireImplementers=true` or +`dotnet meta verify --require-implementers` (all ports also read +`META_REQUIRE_IMPLEMENTERS=1`). Each `WARN_REQUIREMENT_NOTHING_IMPLEMENTS` on a `live` entry +is a finding (`live-claim-unimplemented`) naming the entry. State whether the project's own +gate passes the switch; if it does not and the ledger has no such entries, recommend adding +it so the ledger cannot fall behind again. + +**(c) Live claim, unwired implementer.** For each `@implementedBy` target of a `live` entry, +find the generated code that target produces and confirm hand-written code imports or calls +it. A live claim whose implementer is generated code nothing uses is the finding +`live-claim-unwired-implementer`: the claim resolves, so verify is satisfied, but the +capability is not reachable. Before raising it, rule out a runtime use: code that reaches the +entity through the runtime `ObjectManager` (or a metadata-driven admin or tool registry) +uses it without importing anything generated, so search for the entity's name in those calls +too. + +## What only a human or an agent reading the code can catch + +**1. Statuses that are false.** The highest-value finding in the whole dimension. A +requirement marked `live` whose implementation was gutted; one marked `partial` that is now +complete; one marked `planned` that was quietly built months ago. Sample the claims +and read the nodes, starting with the feature commits currency check (a) found outside the +ledger. `status` is the only payload with controlled evidence behind it — the +resurrection protection rides entirely on it being true. + +**2. Non-violable statements.** Every requirement must state what breaking it looks like. +*"Every entity has a uuid primary key"* is violable — point at one with a composite key. +*"Things are persisted"* is not; it is a description wearing a requirement's shape. Flag +these: they inflate the ledger while proving nothing. + +**3. Claim-padding.** An entity appended to an existing unrelated requirement's +`implementedBy` purely to silence the coverage warning. The claim resolves, so verify is +happy, but it carries no information about what the entity is *for*. Look for entities whose +only claim is a high-fan-out architectural rule when they plainly have product meaning. + +**4. Misfiled kind.** `functional` is checked by EXISTENCE, `architectural` by UNIVERSALITY — +opposite polarity, and nothing mechanical catches a misfile. The discriminator: did this +exist because someone asked for something (functional), or because every entity here looks +like this (architectural)? An architectural entry with one claimant is usually a misfiled +functional one. + +**5. Levels used as decoration.** L1–L3 are organisational and must never reference the +model. If the tree is flat, or every entry is L3, the levels are carrying no information and +should be simplified rather than defended. + +**6. Titles that are not labels.** `title` is now **rendered** — `meta gen`'s +`requirementsFile()` heads each entry `## checkout.payment — Payment capture`, the path +first and the label after it — so a slot +that used to be inert is read by every reader of the generated page. The lint catches only +the id-shaped case (`FR-448 …`); it cannot tell a *useless* label from a good one. Read the +titles: one that restates `@statement`, or repeats the path in prose, is now visible noise in +a heading rather than a private authoring habit. An absent `title` is NOT a finding — the +entry heads by its path alone, which is what every sibling surface addresses it by. + +**7. Witnesses that do not test the claim.** Where the project generates requirement tests +(the `requirement-tests` generator, in any port), a passing generated test proves only that +its witness — or, in TypeScript, the hand-filled stub — ran. Sample the witnesses and read +them against the counterexample each generated test carries: one that asserts nothing, or asserts +something else, is the same defect `@verifiedBy` had. Check also for witnesses that have +gone stale silently: a Java witness that lacks the override annotation, a C# witness implemented +implicitly, and any Python witness keep existing after their requirement is retired or +deleted, and nothing reports them. + +## Scope — do NOT flag these as defects + +- **Unclaimed `object.value` / `object.projection`.** Exempt by design: a value is a shape, a + projection derives from a claimable entity. +- **Fields, views, validators and identities without their own requirement.** Member-grain + coverage is explicitly rejected — plumbing members are covered by architectural + requirements with high fan-out. L5 exists so a member claim *can* be made where it means + something, never so every member must carry one. +- **Dangling links on `planned`.** Correct — the plan precedes the nodes. +- **A project with no requirements at all.** The feature is opt-in by declaration; absence is + not a finding. + +## Reporting + +Report findings as claims to verify, not as a score. "These 4 requirements are marked `live` +and I could not find their implementation" is actionable; "ledger maturity: 62%" is not, and +invites optimising the number. diff --git a/.claude/skills/metaobjects-audit/references/surface-review-axes.md b/.claude/skills/metaobjects-audit/references/surface-review-axes.md index 98cb470..69ea3be 100644 --- a/.claude/skills/metaobjects-audit/references/surface-review-axes.md +++ b/.claude/skills/metaobjects-audit/references/surface-review-axes.md @@ -13,6 +13,7 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in - F2. Over-generation — unnecessary generated files - G. Runtime-contract anti-patterns - G2. `own*()` accessor discipline +- G3. Guarded status transitions - H. Authoring correctness / ADR conformance - H2. Wrong native type - I. Vocabulary hygiene / modernization (advisory) @@ -22,8 +23,10 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in grids/forms/filters vs `layout.dataGrid` / form generators / filter-allowlist. - [ ] **C. Drift hotspot — validators, mappers, runtime models.** Hand validators / DTO-mappers / dataclasses shadowing a generated shape. Diff field-by-field; the divergence is the bug. -- [ ] **D. Prompt pillar.** Every LLM prompt-construction site (see `prompt-anti-patterns.md`). -- [ ] **E. Owned generators & scaffold-and-own** (see "Owned-codegen & scaffold-and-own assessment" in `SKILL.md`). +- [ ] **D. Prompt pillar.** Every LLM prompt-construction site (see `prompt-anti-patterns.md`), + including the **unlinked payload** count: for each `@payloadRef` object, how many of its + fields are linked to the entity field they copy. +- [ ] **E. Owned generators & scaffold-and-own** (see "Owned generators and generator gaps" in `SKILL.md`). - [ ] **E2. Capability ledger — `requirement.*`** (see `references/requirements.md` and the Requirement axis of the capability checklist). The one axis whose hunt is hand-written PROSE rather than hand-written code: a `CAPABILITIES.md`, a README features table, a @@ -34,6 +37,9 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in design, and a real estate reports most of itself unclaimed on day one). Score the prose it would replace, and prefer ONE concrete claim an author can check over a whole-estate migration. + Where a ledger exists, run the three **currency checks** in `references/requirements.md` + (ledger stale, `--require-implementers`, live claim with an unwired implementer) before + sampling statuses. **First establish the estate LOADS.** An older ledger fails the load outright, so `meta verify` never runs and everything in `references/requirements.md` is unavailable: `@violation` and `@verifiedBy` were retired in **0.24.0** (no deprecation shim — ADR-0023 @@ -53,6 +59,52 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in subverbs (`--codegen` / `--templates` / `--db`)? Committed-codegen freshness gate? Advisories heeded? Routine `--no-verify` bypass? Loader `ERR_*` / warnings addressed? Parse the stable `code` field, not message text (ADR-0009). + **No CI means NO, whatever local hooks exist.** A git hook is not part of the clone: it + counts only when a tracked setup step installs it (a `prepare` / `postinstall` script, a + `core.hooksPath` set by a committed setup script, a hook manager declared in the + project's dependencies). An untracked `.git/hooks/pre-push` on one machine is not a gate. + A project with no CI workflow and no tracked hook installer answers the Binary CI drift + gate **NO**, and that is a **Tier 1 finding** whose `next_command` is the snippet below + for the project's port, ready to paste. + + | Port | Verify commands for the snippet (one per subverb the project's artifacts need) | + |---|---| + | TypeScript | `npx meta verify --codegen --templates`; add `npx meta verify --db` against a provisioned database | + | Python | `metaobjects verify --codegen` and `metaobjects verify --templates` | + | Java / Kotlin | `mvn -B metaobjects:verify -Dmeta.verify.mode=codegen` and `-Dmeta.verify.mode=templates` | + | C# | `dotnet meta verify --codegen` and `dotnet meta verify --templates` | + + The snippet is one CI job that checks out the repo, installs the toolchain and runs those + commands with nothing after them, for example GitHub Actions steps + `- run: npx meta verify --codegen --templates`. Where the project has no CI host, it is a + tracked `pre-push` hook that runs the same commands plus the tracked setup line that + installs it. Schema drift (`--db`) runs through the Node `meta` CLI in every port. + **Does it block?** Wired is not blocking. A gate that runs and is ignored scores the same as + no gate, so answer all three before scoring this axis: + - **(a) The exit code propagates.** Search CI files, package scripts, Makefiles, shell + scripts and build files on every path that runs verify for anything that swallows its + failure: `|| true`, `|| echo`, `; exit 0`, `continue-on-error: true`, `set +e`, + `allow_failure: true`, `ignore_errors`, a step or job marked optional or non-required, + a Maven `testFailureIgnore` / `failOnError=false` style switch, an MSBuild + `ContinueOnError`, a `-Dmeta.lax=true` or other option that turns a verify failure into a + warning, and verify output piped into a command whose exit code is the one that counts + (`meta verify | tee log` without `pipefail`). Each one is a finding naming the file and + line. + - **(b) It is green now.** Run the project's own verify command, the exact one its gate + runs, and record the exit code and the error count. A non-zero exit the project tolerates + ("known errors", a baseline file, a count it compares against) is a finding that states + the count and recommends a **ratchet**: the gate stores today's count and fails when it + rises, so the number can only fall (see the CI ratchet gate in `metaobjects-verify`). A + tolerated count with no ratchet is a gate that will absorb every new error. + - **(c) Every route to production passes it.** List each deploy entry point: CI deploy + jobs, release workflows, deploy scripts, `Makefile` / package-script deploy targets, a + hosting platform's build command, a manual `deploy.sh`. Flag each one that ships without + verify having passed on the same commit (a deploy job that does not depend on the verify + job, a script that builds and pushes directly, a `skip-checks` / `--no-verify` input). + Score the gate **BLOCKING** (verify runs on every route to production and a failure stops + it), **RUNS BUT DOES NOT BLOCK** (it runs somewhere, but (a), (b) or (c) failed) or + **ABSENT**. Only **BLOCKING** passes the drift-gate pillar's tier and answers YES on the + Binary CI drift gate; report the other two as **NO** and name which of (a), (b), (c) failed. **Is any advisory half switched OFF?** A gate can be wired, green, and muted. The requirements authoring lint is advisory and mutable — `--no-requirement-lint` or `META_NO_REQUIREMENT_LINT=1` silences it while the gate above it still runs and can still @@ -73,7 +125,7 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in (Node `meta` only) for DB drift. Flag a gate that is WIRED BUT INCOMPLETE for the artifacts present, and recommend the specific missing coverage. - [ ] **F2. Over-generation — unnecessary generated files (codegen WASTE).** - Generated code is disposable, but that is NOT license to generate what nothing + Generated code is regenerated output, but that is NOT license to generate what nothing consumes. Every generated file is a merge/review/maintenance surface and inflates the leverage ratio falsely. Hunt OVER-generation (the inverse of A/B's under-generation): @@ -96,9 +148,24 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in code imports: drop the generator rather than generate into the void. - **Wrong target / duplicate output** — the same logical artifact emitted to two places (a mis-set per-target `outDir`), one of which is orphaned. + - **Consumed / emitted, per generator kind.** For each generator kind (entity, routes, + query hooks, grid, form, and so on) report `consumed / emitted` files, where consumed is + confirmed by an import or reference from hand-written code, not by the file existing. + - **Generated and bypassed.** Where a kind is under half consumed and axis B found a + hand-written equivalent for the same entity (a hand-built admin page, form or grid + beside the unused generated one), raise ONE finding, `generated-and-bypassed`, that + names both files. This is not the same as dead output: the project needed the surface + and built it again by hand, so the generated one is a second, unused source of truth. + The app chooses per entity: **use the generated artifact** (customising the owned + generator until it fits, then deleting the hand-written page after a parity gate), or + **filter it out** with the generator's `filter` and record the hand-written page as + ACCEPTABLE with a stated reason. Emitted and unused is not an end state: the finding + closes only when each entity is on one side or the other. Recommend generating ONLY what is consumed — decide per generator: drop the ones whose whole output class nothing imports, and narrow the ones that over-emit with - their `filter`. A smaller, fully-consumed generated surface beats a large one with + their `filter`. Dropping is the remedy only when no hand-written equivalent exists; + where one does, the finding is `generated-and-bypassed` above. A smaller, + fully-consumed generated surface beats a large one with dead files (which also make the leverage ratio lie; discount them from the census). - [ ] **G. Runtime-contract anti-patterns.** Module-global `db` vs context-as-parameter (ADR-0008); wire-canonicalization in the query path vs native in-process return types @@ -134,6 +201,37 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in deliberately-own attribute `@dbColumnType` (a physical column-type override, never inherited). Any own read that carries a comment naming one of these cases is fine; an uncommented own read of an effective property is the defect. +- [ ] **G3. Guarded status transitions (a correctness check, `unguarded-status-transition`).** + For each model whose enum column is status-like (a `field.enum`, or a `field.string` named + `status` / `state` / `phase` / `stage`, whose members read as a lifecycle: pending, running, + complete, error), list **every write to that column** in non-generated code: an ORM + `update(...).set({ status })`, a `UPDATE ... SET status`, an entity property assignment that is + then saved, an upsert. For each write ask one question: **is it conditional on the current + value?** A guarded write names the state it moves from (`WHERE id = ? AND status = `, a + compare-and-set whose affected-row count is checked, an optimistic-lock version, a database + constraint that rejects the move). An unguarded write (`SET status = 'complete' WHERE id = ?`) + lets two workers, a retry or a late callback move a row backwards or out of a terminal state + (`complete` overwritten by `error`), and nothing reports it. An insert's initial value is not a + transition. A write that is the only possible transition and has one writer is lower + confidence, not exempt: say why it is safe to leave. Score `guarded writes / all writes` per + status column and list the unguarded ones; also state whether the allowed `from` states are + written down anywhere, because a rule held only in scattered `WHERE` clauses is a second + source of truth. + **The remedy never uses raw SQL.** Raw SQL spells the table, the column and the enum member by + hand, and those names drift. At a minimum the guarded write references the generated constants + for the table, the field and the enum member; ideally it goes through the port's ORM, which + carries them as typed handles, with the constraints the model already generates (the enum's + `CHECK`) behind it. Per port the guard is a predicate on the current value inside the ORM + update: Drizzle / Kysely `.where(and(eq(t.id, id), eq(t.status, )))` on TypeScript; + SQLAlchemy `update(T).where(T.id == id, T.status == )` or the `ObjectManager` on Python; + OMDB or the generated repository, or a JPA modifying query over entity attributes, on Java; + Exposed `T.update({ (T.id eq id) and (T.status eq ) })` on Kotlin; EF Core + `ExecuteUpdateAsync` after a `Where(x => x.Status == )` on C#. Each checks the + affected-row count. `` is the generated enum constant, never a literal (signature 13 in + `drift-signatures.md`). **The allowed transitions have a declared form**, `transition.action` + under a `field.enum` (ADR-0066, experimental): cite that table in the sketch, never a new + attribute (ADR-0023). The sketch proposes the ORM guard. Pillar `runtime`, surface `repository`. + - [ ] **H. Authoring-correctness / ADR-conformance (deep).** Invented/unregistered `@`-attrs or post-bootstrap registration (ADR-0023 — custom attrs belong in a registered provider or `attr.properties`); retired source-v2 forms (`source.dbTable` / `@name` / @@ -142,7 +240,8 @@ The full hunt for each axis of Phase 1b (Partial / Deep path). Each axis runs in `object.projection`; `value` carrying identity/source, ADR-0028); copy-pasted base-field blocks — or the same-named field re-declared across objects (drift signature 10) — instead of abstract + `extends`; `@`-prefixed YAML keys (ADR-0006); DB-type-as-logical-subtype (ADR-0013); per-port - migration engine where schema is Node-`meta`-owned (ADR-0015). + migration engine where the project's own tool or the `meta migrate` reference helper + already migrates (ADR-0015). - [ ] **H2. Wrong native type — `field.` + `@dbColumnType` that hides the real type (CORRECTNESS-ADJACENT finding, NOT advisory axis-I).** The headline instance is a **UUID diff --git a/.claude/skills/metaobjects-audit/references/typescript.md b/.claude/skills/metaobjects-audit/references/typescript.md index 3fc9924..5738f1b 100644 --- a/.claude/skills/metaobjects-audit/references/typescript.md +++ b/.claude/skills/metaobjects-audit/references/typescript.md @@ -24,7 +24,7 @@ Generated files carry the header: The header is **informational on this port** — the write decision never reads it. What the runner overwrites is decided by `.metaobjects/.gen-state/`: the snapshot body if the -machine has one (three-way merge), otherwise the committed `.hashes.json` (byte-for-byte +machine has one (three-way merge), otherwise the committed `.hashes/` (byte-for-byte what it wrote ⇒ overwrite; anything else ⇒ refused, exit 1). A sibling file you created (`.extra.ts` by convention) is never touched because it is not a path the runner records — not because of its name, and not because of the header. Locate generated output at the @@ -40,7 +40,7 @@ the default single-target config, generated files land at the one configured meta gen # render → 3-way merge → write (overwrites @generated files only) meta gen --dry-run # preview without writing meta gen Author Post # scope to named entities -meta verify --codegen # regenerate to temp, diff vs committed output +meta verify --codegen # regenerate in memory, diff vs committed output meta verify --templates # check {{field}} refs vs payload VO (a bare `meta verify` runs this and `--codegen`) meta verify --db # schema drift — live DB vs metadata (requires DB connection) meta verify --codegen --templates --db # all three drift checks in one pass @@ -70,6 +70,8 @@ here — the table is its second pass, not its definition. | the resource path in an API call or mount — `app.get("/subscribers")`, the `/subscribers` inside `fetch("/api/subscribers")`, a TanStack `queryKey` path | second spelling of `$path` on the entity module and its `.meta.ts` twin. The `/api` prefix is NOT part of the finding: the constants surface deliberately carries no prefix member — it is the provider's `baseUrl`, a deployment fact — so the prefix has no constant by design and is never a gap either | | a field name passed as text where the parameter's type is a bare `string` — `sort: "created_at"`, `filter["email"]`, a column-id string in a grid config | the per-field constants object carries `name`. Check the parameter type first: where the generated hook types it as a union of field names it is resolved and this row does not apply, exactly as a typed property access does not | | a form label or a validation limit/message re-typed in hand JSX or a hand validator (`maxLength={255}`, `"Email is required"`) | derived from `@title` and the field's validator children into `label` / `rules`; the hand copy is a second source of truth | +| a member of a generated enum typed as a hand string where the file already imports its constant (`status: "error"` beside `CouncilStatusEnum.enum.complete`), in a string-typed position, raw SQL, a JSON payload or an event name | **signature 13.** Value-first: grep the non-generated tree for each enum's `@values`. Check the declared type at the site first: a position narrowed by the generated `export type ` union is resolved and exempt; a `Record`, a `string` parameter or a `sql` fragment is compared and scores | +| a status-like column written with `.set({ status })` and no condition on the current value, or a `sql` `UPDATE ... SET status` | **axis G3.** Guard it through Drizzle / Kysely: `.where(and(eq(t.id, id), eq(t.status, )))` with the generated constant, and check the affected-row count. Never raw SQL | | **NOT a finding — the rule's consequences, not a list:** anything RESOLVED (a typed handle, a typed property access, a typed filter key, an enum member narrowed by the generated `export type ` union — measured: 332 such literals on one estate, 0 real) and anything the metadata does not OWN (a page route or link, `` / `` — 11 apparent `$path` hits on another estate, 0 real; the deployment prefix above) | rewriting a resolved reference to a string lookup is a regression; converting a page route couples the site's URL structure to the API's. Emitted `options: [...] as const` populates a dropdown, not replaces checked literals. A shape that is neither resolved nor unowned and has a constant → score it, whatever it is | --- @@ -118,8 +120,22 @@ are the `--format text` labels. In `--format json` or `toon` the same row carrie `diff -u node_modules/@metaobjectsdev/codegen-ts/src/reference/.ts codegen/generators/.ts` showing only upstream changes. Confirmed, it is the same finding. Not confirmed, report it as **possibly customized: check its history**, never as a copy to drop. -- A copy with lines of its own is an intentional customization. Check only how far behind - it is. +- A copy with lines of its own (`M > 0`) is **not** thereby an intentional customization. The + listing prints `DIFFERS` for both a deliberate customization and a copy gone stale by + version, and `M line(s) of your own` counts every line absent from today's reference: after + the reference moved on, a line it removed or rewrote reads as "yours" and is an older + upstream line. Run the same history check on any `DIFFERS` row, `M > 0` included + (`git log -p -- codegen/generators/.ts`): lines the copy's later commits added are the + project's own; lines already in the eject commit are upstream's, and count as behind. Report + ` lines behind the reference` and ` lines of the project's own (confirmed from + history)` as two figures. A copy whose own lines history does not confirm is **possibly + customized or stale: check its history**; a copy that is stale by version is a finding + (`owned-generator-stale`): re-eject at the current version or return to the package import. + +Count lines for the Phase 0 total: lines in copies proven unmodified, with the +`codegen/runtime/` files they reach, over all lines the project owns under `codegen/` +(`generators/`, `runtime/`, and the `templates/` modules an eject copies). +`meta eject --undo` removes every identical copy and prints the config edit. **`entity`, `routes` and `routes-hono` own more than the generator file.** Ejecting one also copies the HTTP adapter its output imports into `codegen/runtime/`, and a route fix @@ -195,8 +211,8 @@ via `metamodelVersion` (see the Phase 0 cross-language consistency item). TypeScript is the reference implementation — it ships the full feature set: -- Filter-operator codegen: **complete** — the core `?filter[field][op]` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`, `FilterAllowlist`) generates in every port; TS additionally ships the richer surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating). +- Filter-operator codegen: **complete** — the core `?filter[field][op]` grammar (all 9 operators `eq/ne/gt/gte/lt/lte/in/like/isNull`, `FilterAllowlist`) generates in every port; the richer list surface (`?search=`, `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in TypeScript and C#; each other port is pending until its 1.3.0 REST-standard work lands. - Output-parser codegen: **complete** (`outputParser()` generator; `parse*`/`safeParse*`/`extract*` emitted as `.response.ts` per **responding `template.prompt`** — one carrying `@responseRef`; ADR-0052). - ObjectManager: **complete** (`@metaobjectsdev/runtime-ts`; `kyselyDriver` / `inMemoryDriver`). -- Schema migrate / `meta verify --db`: **complete** (TS owns the shared migrate engine — ADR-0015). +- Schema migrate / `meta verify --db`: **complete** (the Node CLI hosts the reference migration helper, one option for every port). - D1 dialect: **TS-only by design** — `migrate.dialect: "d1"` (and `meta migrate --dialect d1`) targets Cloudflare D1 via the Wrangler CLI layout; codegen's `dialect` in `metaobjects.config.ts` is `"sqlite"` for D1 and `"d1"` there is refused. Do NOT recommend porting D1 support to other languages. diff --git a/.claude/skills/metaobjects-audit/references/vocabulary-hygiene.md b/.claude/skills/metaobjects-audit/references/vocabulary-hygiene.md index 0457d76..cc5ec19 100644 --- a/.claude/skills/metaobjects-audit/references/vocabulary-hygiene.md +++ b/.claude/skills/metaobjects-audit/references/vocabulary-hygiene.md @@ -39,13 +39,20 @@ such, surfaced in the roadmap, but **non-failing** (the code works; the form is URL validation) — a distinct native type + behavior is a subtype, not a validated string. - A `field.string` that **holds an IP address** → recommend **`field.inet`** (native IP type; Postgres `inet` column). +- A `field.string` (or a CLR/JVM type override) that **holds a time span** (`TimeSpan`, an + `interval` column, "seconds until…") → recommend **`field.duration`** (native duration type; + Postgres `interval` column; ISO-8601 on the wire). Not a calendar span: months and years + are not durations. **Custom-provider vocabulary (adopters who register their own types/attrs):** check new/custom vocab against the ADR-0037 procedure (advisory) — e.g. *a custom subtype that differs from an existing one only by a property should be an attribute, not a subtype*; an email/hostname string-validation is an **attribute** (`@stringFormat`, native type unchanged), while a URL or IP is a **native type** (`field.uri` / -`field.inet`, a subtype). Recommend re-shaping against the ordered test. +`field.inet`, a subtype). Recommend re-shaping against the ordered test. Also advisory: +custom vocabulary that names a product, a version or a step, a subtype only one node could +ever be, or things flattened into list attributes (the `metaobjects-authoring` skill's +`references/semantic-modelling.md`). **Hand-rolled reverse-query repository methods (ADR-0038) → recommend the generated reverse FK finder.** Reverse navigation — *"find all the rows that reference this one"* — is now diff --git a/.claude/skills/metaobjects-authoring/SKILL.md b/.claude/skills/metaobjects-authoring/SKILL.md index 85ac7bc..211102d 100644 --- a/.claude/skills/metaobjects-authoring/SKILL.md +++ b/.claude/skills/metaobjects-authoring/SKILL.md @@ -1,20 +1,41 @@ --- name: metaobjects-authoring -description: Use when authoring or modifying MetaObjects metadata — fields, entities, relationships, sources, enums, abstracts/inheritance — in YAML or canonical JSON; includes deciding whether and how to register custom vocabulary (new subtypes or attributes via a provider). +description: Use when authoring or modifying MetaObjects metadata — fields, entities, relationships, sources, enums, abstracts/inheritance — in YAML or canonical JSON; includes designing, registering or changing custom vocabulary (your own types, subtypes or attributes via a provider), and putting a domain, a config file or infrastructure into the metadata. --- # Authoring MetaObjects metadata -MetaObjects metadata is the durable spine of your app: typed entity declarations -that drive code generation, runtime behavior, and drift detection. You author it, -the loader reads it, the codegen emits idiomatic per-language code from it. This -skill is the procedure for writing it correctly. - -Metadata lives in files under the project's metadata directory (`metaobjects/` unless -the project's configuration names another: `sources` in `.metaobjects/config.json`, or the -port's own setting), one file per domain -concept (`meta.commerce.json`, `meta.users.yaml`, …). Each file declares a -`package` on its root node. Files in the same `package` with the same object +Metadata is the typed declaration of the application's model. The loader reads it, codegen +emits code in each language from it, and the drift gates check everything against it. + +## Essentials + +- **Declare it; do not hand-write it.** Persistence, data access, validation, APIs and UI + scaffolding are derived from metadata. When you reach for a hand-written query, route, + validator, relationship or aggregate, that is usually metadata nobody has declared yet: + look for the construct first (`meta types `). Declare it when the cost test favours + it: smaller declared than hand-written, more than one instance, or drift protection a + hand-write cannot give. A one-off with none of these can stay hand-written. +- **Adoption reverses the direction.** When working code or a populated schema already + exists, it is the specification and the metadata reproduces it: its names, types and + nullability. Read `references/adopting-existing-code.md` before modeling anything. +- **Every node is `{ ".": { } }`.** Reserved keys (`name`, `isArray`, + `children`, …) are bare; every attribute is `@`-prefixed in JSON and bare in YAML. +- **Never invent a subtype or attribute.** The loader is strict, so an unregistered name + fails the load. `meta types` says what exists; vocabulary of your own is a provider class, + shaped by `references/semantic-modelling.md` (what a thing is, never a product or a step). +- **Choose a field's shape by what the value is, not how it is stored**: a UUID is + `field.uuid`, money is `field.currency`, a list is `isArray: true`, and a JSON column takes + the type its writer already declares. The canonical-form table below covers the common + cases. +- **A relationship's subtype sets the default delete action, and the FK-owning (child) side + governs.** Modeling every link as `composition` arms cascades nobody asked for. +- **In YAML, quote any scalar that looks like a boolean, number, date or null.** + +Metadata lives in files under the project's metadata directory (`metaobjects/` unless the +project's configuration names another: `sources` in `.metaobjects/config.json`, or the port's +own setting), one file per domain concept (`meta.commerce.json`, `meta.users.yaml`, …). Each +file declares a `package` on its root node. Files in the same `package` with the same object `name` are merged by the loader. ## Reference files — open only the one your task needs @@ -25,80 +46,67 @@ This file covers what almost every model needs. The topics below live in | File | Open it when | |---|---| | `references/adopting-existing-code.md` | working code or a populated schema already exists for what you are modeling | +| `references/adopting-existing-models.md` | moving existing Zod, Drizzle or Pydantic models into the model: the step-by-step recipe, and how to prove the generated types match before the switch | | `references/choosing-a-shape.md` | no row of "Canonical form for common field needs" fits; you need the full UUID / timestamp / URI / `@autoSet` rule; or you are registering your own vocabulary | +| `references/semantic-modelling.md` | **open first** when adding or changing custom vocabulary (a type, subtype, attribute or provider), or asked to put a config file, a script or infrastructure "in the metadata" | | `references/json-columns.md` | a JSON column beyond the ladder below: coverage per port, `field.map` at runtime, version caveats, bag → native array | | `references/identities-and-indexes.md` | declaring a primary, secondary or reference identity, an FK, or a non-unique `index.lookup` | | `references/sources.md` | the `source.rdb` shape and `@kind`; a store MetaObjects does not manage; a derived or computed column (reach for an entity read-view first) | | `references/abstracts-and-overlay.md` | a shared `abstract` base, `extends`, or a layered `overlay` file | -| `references/declaring-reports.md` | declaring `dimension.*`, `measure.*`, `segment.filter` or an `object.report` | +| `references/declaring-reports.md` | **open first** for a report, dashboard, totals, `GROUP BY`, "per client / per month" or a read-only summary view: declaring `dimension.*`, `measure.*`, `segment.filter` or an `object.report` | | `references/model-first-rationale.md` | someone argues that hand-writing a layer is cheaper this once | | `references/relationships.md` | a many-to-many link or self-join, or a "rows that reference this one" query | -| `references/read-views-and-projections.md` | an `object.projection`, `origin.*` vocabulary, `@filter` / `@expr`, or an `@sql` / `@unmanaged` view | +| `references/read-views-and-projections.md` | an `object.projection`, `origin.*` vocabulary, `@filter` / `@expr`, or an `@sql` / `@unmanaged` view (a grouped or aggregate view is `declaring-reports.md` first) | | `references/inheritance-tph.md` | several entities are variants of one thing sharing a single table (`@discriminator`) | | `references/metadata-dependencies.md` | the project builds on another package's metadata (`dependencies`, cross-package `overlay`) | | `references/reporting.md` | what a declared report gives you: what columns a report gets, time grains, null rules, rows with no facts (`@spine`), defaults (`@default`), engine differences | -| `references/requirements.md` | installed only when the project declares `requirement.*` nodes | - -## The operating principle: model-first, generate-first - -You are not hand-writing an application — you are **declaring the model it is -generated from.** Persistence, data access, validation, APIs, and UI scaffolding are -**derived from metadata, never authored by hand.** Model-first is the default for -*every* capability; hand-writing one of these layers is an exception you must -**justify**, not a convenience you reach for. - -**This requires thinking differently.** Imperative code asks *"how do I implement -this endpoint?"* Model-first asks *"what is this resource, and what is true about -it?"* — and lets codegen own the *how*. **Describe WHAT, not HOW.** The metadata is -the source of truth; generated code is a disposable, regenerable artifact — delete -it and `meta gen` restores it identically. - -**Before you hand-write anything data-shaped, STOP and find the model.** The moment -you reach for a hand-written query, route, validator, form, relationship, or -aggregate — that is almost always **metadata you have not declared yet.** In order: -1. **Check whether the design already ships.** `meta gen --list --format json` - carries `kind: "library"` rows — declared design MetaObjects ships, each with a - `useWhen`. If one matches the capability you are about to declare, opt in and adapt - rather than author it from scratch: you inherit its entities, its requirements, and - the rulings recorded with them. The bare name is the core layer (sourceless — no - tables, no generated code); `/db` is the separate opt-in that adds the schema. -2. **Search the vocabulary** — `meta types `, or `meta types --all - ` to search by behavior. There are field subtypes, relationships, - projections, origins, identities, sources, and attributes you may not know exist. - Find the construct that models it. Add `--detail` for one construct's valid - `@attrs`, or `--format json` for the same answer as one machine-readable document - — that form carries every match (`--limit` never truncates it) with each attr's - `allowedValues`, so you read the accepted values rather than guessing them. -3. **Declare it and generate** — then *consume* the generated query/type/route; - never reimplement it alongside. -4. **If the model is right but the generated OUTPUT is wrong, change your generator.** - Naming, file layout, imports, framework, signatures are generator concerns, not - reasons to hand-write. The generators are in *your* repo and are yours to edit — a - standing rule not to change the MetaObjects repo does not reach them; they are a - different repository. Editing one is ordinary work, not an escalation. (See - `metaobjects-codegen` → "Your generators are yours".) -5. **Only if no construct can express it** — and you have actually looked — - hand-write it, wired to generated types. Business algorithms, external - integrations, and bespoke interactions are legitimately hand-written; CRUD, - validation, finders, relationships, and derived/aggregate data are not. - -Rule of thumb: **if the metadata could describe it, declaring it is never the wrong -call** — even when a one-off hand-write would be faster today. - -## Adopting onto an existing codebase — metadata FOLLOWS the code - -The principle above is the **greenfield** default. **Adoption reverses the direction:** when -working code or a populated schema already exists for what you are modeling, that code is the -specification, and the metadata's first job is to reproduce it — its native types, column and -table names, nullability, and the types its JSON writers already declare. Tune the generator to -match the code before you change the code, and default to the choice that changes the least -existing code. **Read `references/adopting-existing-code.md` before you model anything in an -adoption.** - -## The fused-key encoding (non-negotiable) +| `references/requirements.md` | you add, change or review a `requirement.*` node | + +## Model first, then generate + +You are declaring the model the application is generated from: the question is "what is this +resource, and what is true about it?", and codegen owns the "how". Hand-writing a layer the +model can describe is the exception, because a hand-written copy is checked by nothing and +drifts the day the model changes. + +When you are about to hand-write something data-shaped, find the model for it: + +1. **Check whether the design already ships.** `meta gen --list --format json` carries + `kind: "library"` rows, each with a `useWhen`. If one matches, opt in and adapt it: you + inherit its entities, requirements and recorded rulings. The bare name is the core layer + (sourceless: no tables, no generated code); `/db` adds the schema. +2. **Search the vocabulary.** `meta types `, or `meta types --all ` to + search by behavior; there are subtypes, origins, identities and attributes you may not + know exist. `--detail` shows one construct's valid `@attrs`; `--format json` gives every + match with each attr's `allowedValues`, so you read the accepted values, not guess them. +3. **Declare it, generate, and consume the generated query, type or route.** Once declared, + do not reimplement it alongside. +4. **If the model is right and the generated output is wrong, change your generator.** + Naming, file layout, imports, framework and signatures are generator concerns. The + generators are in your repo and yours to edit; a rule against changing MetaObjects itself + does not reach them (`metaobjects-codegen`, "When generated output does not fit"). +5. **Hand-write only what no construct can express**, wired to the generated types: business + algorithms, external integrations, bespoke interactions. CRUD, validation, finders, + relationships and derived or aggregate data are not in that group, unless the cost test + below says a one-off can stay hand-written. + +If the metadata could describe it, declare it when the cost test favours it: the shape +is smaller declared than hand-written, it will have more than one instance, or declaring it +buys drift protection a hand-write cannot. A one-off with none of these can stay hand-written +(`references/model-first-rationale.md`). + +## Adopting onto an existing codebase: metadata follows the code + +Model-first is the greenfield default. When working code or a populated schema already exists +for what you are modeling, that code is the specification and the metadata's first job is to +reproduce it: its native types, column and table names, nullability, and the types its JSON +writers already declare. Tune the generator to match the code before you change the code. +`references/adopting-existing-code.md` has the rules; read it before modeling. + +## The fused-key encoding Every node is `{ ".": { } }`. The wrapper key fuses type and -subtype — there is **no** separate `subType` body key. +subtype; there is no separate `subType` body key. ```json { "object.entity": { "name": "User" } } @@ -164,16 +172,12 @@ name package extends abstract overlay isArray children value load with `ERR_RESERVED_ATTR`. Use the bare `isArray: true` (YAML) or the `[]` key-suffix sugar (`field.long[]: weekIds`). -## Two violation rules — internalize these - -1. **Attribute-name uniqueness within a node.** A node body must not declare the - same attribute name twice. `{ "field.string": { "name": "x", "@maxLength": 10, - "@maxLength": 20 } }` is malformed. +## Declare each attribute once -2. **An inline `@attr` IS an `attr` child — never both.** An inline attribute and - a child `attr.*` node with the same name are the same slot expressed two ways. - Declare a given attribute once, in one form. Don't set `@required` inline AND - also add an `attr.boolean` child named `required` — that's a double-declaration. +A node body must not declare the same attribute name twice. An inline `@attr` and a child +`attr.*` node with the same name are the same slot written two ways, so use one form: setting +`@required` inline and also adding an `attr.boolean` child named `required` is a double +declaration. ## Field subtypes (closed vocabulary) @@ -198,23 +202,16 @@ name package extends abstract overlay isArray children value Common field attributes: `@required`, `@maxLength`, `@column` (physical column name), `@default`, `@filterable`, `@sortable`. On temporal fields (`field.date`/`field.time`/`field.timestamp`) `@autoSet` stamps the value -automatically (see "Four rules behind those rows" below). - -#### What `@required` actually means +automatically (`references/choosing-a-shape.md`). -`@required: true` is **NOT NULL** (presence). Two consequences that are easy to -get wrong: +#### What `@required` means -1. **On a non-array string it also rejects `""` — but only at the wire tier.** - Generated *input* validation (the create/patch models behind POST/PATCH) - rejects the empty string by default; whitespace-only IS accepted. Generated - in-process read models never enforce this at construction, so reading an - existing row containing `""` does not throw. -2. **To say "must be provided, but may be empty", author an explicit - `validator.length` with `@min: 0`.** An explicitly authored `@min` is always - authoritative over that implicit non-empty floor; the floor applies only when - no `@min` is authored at all. Dropping `@required` is NOT the way to express - this — that makes the field optional and loses presence typing. +`@required: true` is NOT NULL (presence). On a non-array string, generated *input* validation +(the create and patch models behind POST and PATCH) also rejects `""`; whitespace-only is +accepted, and read models never enforce it, so reading an existing row containing `""` does +not throw. To say "must be provided, but may be empty", author a `validator.length` with +`@min: 0`: an authored `@min` always wins over the implicit non-empty floor. Dropping +`@required` is not the way to say it, because that makes the field optional. ```jsonc // must be provided; empty string allowed @@ -232,7 +229,7 @@ Reach for these before inventing anything. When no row fits, run the decision pr | Need | Author it as | Note | |---|---|---| -| IDs / unique keys / **any UUID column** | `field.uuid` | native UUID type. **NEVER `field.string` + `@dbColumnType: uuid`** — see "Four rules behind those rows" below | +| IDs / unique keys / any UUID column | `field.uuid` | native UUID type. `field.string` + `@dbColumnType: uuid` generates a string over a uuid column: a smell no drift gate catches | | Money | `field.currency` | integer minor units; never a float | | Closed set of symbols | `field.enum` | `@values` required | | Instant / event time (created/updated) | `field.timestamp` + `@autoSet` | instant / tz-aware by default (Postgres `timestamptz`; native `Instant`/`DateTimeOffset`/aware `datetime`); `@autoSet: onCreate` for `createdAt`, `@autoSet: onUpdate` for `updatedAt` — never hand-stamp | @@ -244,15 +241,9 @@ Reach for these before inventing anything. When no row fits, run the decision pr | Open JSON, no reader narrows it | `field.string` + `@dbColumnType: jsonb` | the LAST rung — see "A JSON column" | | URL / URI | `field.uri` | native `URI`/`Uri`; `text` column; strict absolute-URI validation (add `@lenient: true` to store any string) — a real native type + behavior, so a subtype (not a validated string) | | IP address | `field.inet` | native IP type; Postgres `inet` column; strict IPv4/IPv6-literal validation (add `@lenient: true` for a plain-string `text` column) | +| Elapsed time / timeout / delay | `field.duration` | native `TimeSpan`/`Duration`/`timedelta`; Postgres `interval` column; wire form is the port's native one by default, canonical ISO-8601 (`PT1H30M`) under `wire.durations: iso`. Not for a calendar span ("every 3 months"): that is an int and a unit. Never a string or a count of seconds | | Validated plain string (email / hostname) | `field.string` + `@stringFormat` | `@stringFormat: email` or `@stringFormat: hostname` — idiomatic per-port validation; don't hand-write the `validator.regex` | -Four rules behind those rows, in short (full text: `references/choosing-a-shape.md`): -**a UUID is `field.uuid`** — `field.string` + `@dbColumnType: uuid` generates a `String` over a -uuid column and is a smell; **`field.timestamp` is an instant**, and `@localTime: true` is the -opt-out for a wall clock; **`field.uri` / `field.inet` are strict**, and `@lenient: true` stores -any string; **`@autoSet: onCreate` / `onUpdate`** stamps created/updated times, so never set them -by hand. - ### Currency `field.currency` stores money as **integer minor units** (cents for USD, yen for @@ -284,10 +275,10 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `field.object` embeds another `object` declaration. `@objectRef` names it; `@storage` controls persistence: -- `flattened` — one DB column per sub-field (`address_street`, `address_city`, …). - Illegal on array fields. -- `jsonb` — one `jsonb` column. -- `subdocument` (default, back-compat) — single jsonb column. +- `flattened` — one DB column per sub-field (`address_street`, …); illegal on arrays. `@flattenedColumnPrefix` + replaces the `_` prefix verbatim (`""` keeps the members' own columns). +- `jsonb` — one `jsonb` column; also the default when `@storage` is not set. +- `subdocument` — single jsonb column (a hint for document-store targets). ```json { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } } @@ -305,15 +296,15 @@ generated Postgres column is typed `.$type()` and the Zod schema is ### A JSON column — choose the rung by the type the WRITER already declares -**"Add a jsonb column and cast on read" is the ORM-tutorial reflex, and it is the one column -shape this metamodel exists to replace.** Every other subtype binds a native type in five -languages; `field.string` + `@dbColumnType: jsonb` binds `unknown` / `Any` / `Object` — so every -reader casts, the keys live in N call sites instead of one declaration, and no gate can see it -(`verify --db` sees a jsonb column that matches; `--codegen` sees output that is correct for a -bag). **The cast you write on read is the shape you declined to declare.** +"Add a jsonb column and cast on read" is the habit to drop here. Every other subtype binds a +native type in five languages; `field.string` + `@dbColumnType: jsonb` binds `unknown` / `Any` +/ `Object`, so every reader casts, the keys live in each call site and not in one +declaration, and no gate can see it (`verify --db` sees a jsonb column that matches; +`--codegen` sees output that is correct for a bag). The cast you write on read is the shape +you did not declare. -**The test is mechanical and language-agnostic: read the signature of the function that WRITES -the column.** It already names the type — that is the metadata. Take the first rung that fits: +**The test: read the signature of the function that writes the column.** It already names the +type, and that is the metadata. Take the first rung that fits: | The writer's type | Author it as | What comes back | |---|---|---| @@ -409,12 +400,10 @@ no Drizzle `many()` member; reverse navigation is the generated finder Reverse finders (`findBy` and the batched `…In`) are **generated** for every FK, so never hand-write a `WHERE fk = ?` helper. -**Adoption footgun — pin BOTH actions.** `@onDelete` defaults *per subtype* (above) -and `@onUpdate` defaults to `cascade` — but a plain SQL foreign key is `NO ACTION` on -both. If you're adopting an existing database (matching metadata to a live schema), -leaving these implicit makes the metadata declare a referential action the DB doesn't -have — a perpetual `verify --db` drift. Pin **both** explicitly to the DB's real -behavior: +**Adopting an existing database: pin both actions.** `@onDelete` defaults per subtype +(above) and `@onUpdate` defaults to `cascade`, but a plain SQL foreign key is `NO ACTION` on +both. Left implicit, the metadata declares a referential action the database does not have, +which is a permanent `verify --db` drift. Pin both to what the database really does: ```json { "relationship.association": { "name": "author", "@objectRef": "User", @@ -425,20 +414,29 @@ behavior: Entity-scoped `validator.*` children declare invariants that reference sibling fields **by name** (the same name-reference pattern as `identity.*`). The backend derives the -enforcement (a CHECK constraint / cross-field assertion) — no raw expression is stored. +enforcement — no raw expression is stored. A DB `CHECK` constraint is emitted by `meta migrate`, +and the generated full create/record model also enforces the rule in every port (Zod refinement, +Bean Validation class-level constraint, `IValidatableObject`, Pydantic `model_validator`), so a +store with no `CHECK` support is still covered. PATCH and partial-update models do not enforce them +(a partial body cannot see the merged row); the DB `CHECK` is the enforcement there. | Subtype | Rule | Key attrs | |---|---|---| -| `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` | +| `validator.comparison` | two fields stand in a relational order (`@left @op @right`). Numerics compare with each other; strings, temporals and durations only with the same subtype and `@localTime`; boolean, enum, uuid, uri and inet only `eq`/`ne`. Any other pair is skipped, never rejected. | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` | | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` | | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` | | `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` | +| `validator.exactlyOne` | exactly one of `@fields` (2+) is present | `@fields` | + +All five take an optional `@condition` (the `origin.computed` grammar): the rule holds only where it does. +Every validator that becomes a CHECK takes an optional `@constraintName`. ```json { "validator.comparison": { "name": "hpInRange", "@left": "currentHp", "@op": "lte", "@right": "maxHp" } } { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } +{ "validator.exactlyOne": { "name": "oneOwner", "@fields": ["customerId", "accountId"] } } ``` These are children of `object.entity`, alongside its fields and identities. @@ -450,23 +448,46 @@ Several variants of one thing sharing **one table**: the base `object.entity` de `@discriminatorValue`. Codegen emits per-subtype routes with the discriminator injected and immutable. Supported in all five ports; the worked example is in `references/inheritance-tph.md`. -## Requirements — capability ledger (opt-in) +## Your own vocabulary: a provider class, in every language -**This capability exists whether or not the project uses it yet.** `requirement.functional` and `requirement.architectural` are registered metadata types, declared in the metadata directory beside the entities they describe and loaded by the same loader — no side file, no bespoke parser. They record *why* each part of the model exists, so a field with no reason to exist becomes visible as one. +A subtype or attribute the core does not ship (a `layout.picker`, `@searchable` on fields) is +registered by a **provider class** in the project's own language, never a side file and +never a loosened `strict`. Model it semantically first (`references/semantic-modelling.md`: +what the thing is and relates to, never a product, a version or a step), then decide each +concept's shape (`references/choosing-a-shape.md`, which also has the register and extend +rules). List the provider once in the port's project +configuration and every command that loads metadata (gen and its docs generators, verify, +fmt) composes it. Where each port lists it, with a worked example: +`references/typescript-providers.md`, `references/python-providers.md`, +`references/csharp-providers.md`, `references/java-providers.md`, +`references/kotlin-providers.md` (only this stack's are installed). -Reach for it when the project needs to answer any of: +Every port whose tools load the metadata needs its own copy: a TypeScript-only provider +leaves the Java, Python or C# side, and its docs build, failing with `ERR_UNKNOWN_SUBTYPE` / +`ERR_UNKNOWN_ATTR`. -- **"Why is this field here?"** — an L5 requirement binds a claim to a specific member. Authoring these exhaustively is what surfaces columns nothing reads and vocabularies nobody documented. -- **"What is broken but known?"** — `@status: partial` plus `@disposition: accepted | deferred`. Absent disposition means *undecided*, and `meta verify` counts those: the gaps nobody has ruled on. -- **"What did we say we would build and have not?"** — `@status: planned` is the one status where a dangling `@implementedBy` is *correct*, because the entry precedes the nodes. -- **"What have we committed to build?"** — `@status: planned`. Its references may dangle, and it never counts toward object coverage. -- **"Which ticket covers this?"** — `@trackedBy`. +## Requirements: a capability ledger (opt-in) -Every requirement must be **violable**: if you cannot say what breaking it looks like, it is a description, not a requirement. +`requirement.functional` and `requirement.architectural` are registered metadata types, +declared beside the entities they describe and loaded by the same loader, available whether +or not the project uses them yet. They record why each part of the model exists, so a field +with no reason to exist becomes visible. Reach for them when the project needs to answer: -**A commit that adds, changes or removes behaviour updates the ledger in the same commit** (the new or changed claim, its `@status` and `@implementedBy`), or says in the commit message why it does not. `verify` checks that links resolve, not that the ledger is current. +- **"Why is this field here?"** A requirement binds a claim to a specific member. +- **"What is broken but known?"** `@status: partial` plus `@disposition: accepted | deferred`. + No disposition means undecided, and `meta verify` counts those. +- **"What have we committed to build and not built yet?"** `@status: planned`: the one status + where a dangling `@implementedBy` is correct. It never counts toward object coverage. +- **"Which ticket covers this?"** `@trackedBy`. -If the project declares any `requirement.*` node, `references/requirements.md` is installed with the full authoring rules. If it does not and you are adding the first one, the shape is: +Every requirement must be violable: if you cannot say what breaking it looks like, it is a +description, not a requirement. + +A commit that adds, changes or removes behaviour updates the ledger in the same commit (the +claim, its `@status` and `@implementedBy`), or says in the commit message why it does not: +`verify` checks that links resolve, not that the ledger is current. + +`references/requirements.md` has the full authoring rules. The shape of one node: ```yaml - requirement.architectural: @@ -476,8 +497,3 @@ If the project declares any `requirement.*` node, `references/requirements.md` i counterexample: A row that can be inserted but never pointed at. implementedBy: [acme::shop::Order] ``` - ---- - -For non-trivial schema design, use `/superpowers:brainstorming` if installed; -otherwise proceed. diff --git a/.claude/skills/metaobjects-authoring/references/adopting-existing-code.md b/.claude/skills/metaobjects-authoring/references/adopting-existing-code.md index 5d26581..b611b9d 100644 --- a/.claude/skills/metaobjects-authoring/references/adopting-existing-code.md +++ b/.claude/skills/metaobjects-authoring/references/adopting-existing-code.md @@ -13,6 +13,9 @@ redefining it. (The metadata is still the durable spine *going forward*; only th **The observable predicate:** does working code or a populated schema already exist for what you're modeling? If yes, you are in adoption mode and these rules apply. +For Zod schemas, Drizzle tables or Pydantic models, `adopting-existing-models.md` is the +step-by-step recipe: generate beside them, prove the types match, move one call site at a time. + **Author metadata to match what the code ALREADY IS — not what you'd design fresh.** Read the existing code and schema *first*, then model to reproduce them: - The **native types the code uses** are the spec — model `field.uuid` when the code diff --git a/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md new file mode 100644 index 0000000..6854ed8 --- /dev/null +++ b/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -0,0 +1,388 @@ +# Adopting existing models + +> Part of the `metaobjects-authoring` skill. Read it when a project already has Zod schemas, Drizzle tables or Pydantic models and you are moving them into the model. + +MetaObjects never reads the project's source. You read the existing types and write the model, and +the language's own tools compare the two: `tsc` for TypeScript, `model_json_schema()` for Python. + +## Contents +- The recipe +- Drizzle +- Zod +- Pydantic +- Fixing the differences +- What the proof does not cover + +## The recipe + +1. **Write the model from the existing types.** Read the types and model what they are, not what + you would design fresh. `references/adopting-existing-code.md` in the `metaobjects-authoring` + skill has the rules. +2. **Generate beside them.** Send the output to a new directory. Nothing imports it yet. +3. **Write the proof.** It is one test file that names each pair of types. +4. **See it fail once.** Break one field in the model, regenerate, and check that the proof names + that field. Then undo it. +5. **Fix the differences in the model,** not in the existing code, until the proof passes. +6. **Check the database,** if the project has one. +7. **Move one call site at a time.** Run the proof and the project's tests after each move. +8. **Retire the old code,** delete the proof, and keep `meta verify` in CI. + +Step 4 is not optional. A proof that cannot fail looks the same as one that passes. If the proof +stays green with a field broken, its file is outside `include` in `tsconfig.json`, or `strict` is +off, or pytest never collected it. + +### Drizzle + +Install the CLI with `npm i -D @metaobjectsdev/cli @metaobjectsdev/codegen-ts typescript`, then run +`npx meta init` once in the project root. + +Write the model. Field names are the TypeScript property names. `snake_case` is the default for +columns, so `displayName` already means `display_name`. Reuse the names the database has: the name +of a `.unique()` index goes on `identity.secondary`, and an existing foreign key name goes in +`constraintName`. + +```yaml +metadata: + package: shop + children: + - object.entity: + name: Customer + children: + - source.rdb: { table: customers } + - field.uuid: { name: id, required: true } + - field.string: { name: email, required: true, maxLength: 254 } + - field.string: { name: displayName, required: true, maxLength: 120 } + - field.int: { name: loyaltyPoints, required: true, default: 0 } + - field.string: { name: notes } + - field.timestamp: { name: createdAt, required: true, default: now(), mutability: readOnly } + - identity.primary: { fields: id, generation: uuid } + - identity.secondary: { name: customers_email_unique, fields: email } +``` + +Generate beside the existing schema: + +```ts +// metaobjects.config.ts +import { defineConfig } from "@metaobjectsdev/cli"; + +export default defineConfig({ + outDir: "src/generated", // beside the existing code; nothing imports it yet + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own + dialect: "postgres", + timestampMode: "date", // when the existing timestamp columns read as Date + generators: ["entity"], +}); +``` + +Run `npx meta gen` to generate. + +Copy this helper into `proof/differs.ts`: + +```ts +// Names every field that differs between two object types, or `never` when they match. +// +// Mutual assignability alone is not enough. A field that is optional and present on only one +// side passes both ways, and `any` is assignable to and from everything, so this compares +// key by key and treats `any` on one side as a difference. Pick<> keeps each field's optional +// modifier. It looks one level down: give a nested type its own line in equivalence.ts. +type Mutual = [A] extends [B] ? ([B] extends [A] ? true : false) : false; +type IsAny = 0 extends 1 & T ? true : false; + +export type Differs = { + [K in keyof A | keyof B]: K extends keyof A & keyof B + ? [IsAny] extends [IsAny] + ? Mutual, Pick> extends true + ? never + : K + : K + : K; +}[keyof A | keyof B]; + +// tsc reports each differing field as: Type '"name"' does not satisfy the constraint 'never'. +export type Same<_NoDifferences extends never> = true; +``` + +Then name each pair in `proof/equivalence.ts`, inside `include` in `tsconfig.json`, with `strict` +on. Compare what a query reads and what an insert takes: + +```ts +import type { Customer, NewCustomer } from "../src/db/schema.js"; +import type { Customer as GeneratedCustomer, CustomerInsert } from "../src/generated/Customer.js"; +import type { Differs, Same } from "./differs.js"; + +export type Proof = [ + Same>, + Same>, +]; +``` + +`npx tsc --noEmit` is the check. + +Types do not include column names, so `tsc` passes even with a wrong column. `meta verify --db` is +the check for those (it needs `pg` installed): + +```sh +npx meta verify --codegen --db "$DATABASE_URL" +``` + +`--db` runs only the database check unless you name the others, so keep `--codegen` beside it. + +Two Drizzle objects for one table can exist side by side, since each only describes SQL. Move a +call site by changing its import, with an alias where the generated name differs: + +```ts +import { type Customer, customers, type CustomerInsert as NewCustomer } from "./generated/Customer.js"; +``` + +When the last one has moved, replace the old table definitions with re-exports and delete +`proof/`: + +```ts +export { customers } from "../generated/Customer.js"; +export { orders } from "../generated/Order.js"; +``` + +Keep one migration tool per database. To stay on drizzle-kit, point it at this file. To move to +`meta migrate`, adopt the live schema with `meta migrate baseline --from-db`. + +### Zod + +Install the CLI with `npm i -D @metaobjectsdev/cli @metaobjectsdev/codegen-ts typescript`, then run +`npx meta init` once in the project root. + +A Zod project often has no ORM, so generate a contract-only target. An object with no table is an +`object.value`: + +```ts +// metaobjects.config.ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; + +export default defineConfig({ + outDir: "src/generated", + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own + dialect: "postgres", + targets: { + contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM + }, + generators: [entityFile({ target: "contract" })], +}); +``` + +```yaml +metadata: + package: api + children: + - object.value: + name: CreateCustomer + children: + - field.string: { name: email, required: true, maxLength: 254 } + - field.int: { name: seats } + - field.string[]: { name: tags, required: true } +``` + +Run `npx meta gen` to generate. The schema for `CreateCustomer` is `CreateCustomerInsertSchema`. The generated `CreateCustomer` is +the type. Use the same `proof/differs.ts` as above, and compare both `z.input` and `z.output`, +because a default or a transform changes one without the other: + +```ts +import type { z } from "zod"; +import type { CreateCustomer } from "../src/api/schemas.js"; +import type { CreateCustomerInsertSchema } from "../src/generated/CreateCustomer.js"; +import type { Differs, Same } from "./differs.js"; + +export type Proof = [ + Same, z.input>>, + Same, z.output>>, +]; +``` + +`tsc` cannot see `.min()`, `.max()` or `.email()`, because they do not change the type. Zod can +describe them, so add `proof/rules.ts` and run it with your test runner, or with node or bun: + +```ts +import assert from "node:assert/strict"; +import { z } from "zod"; +import { CreateCustomer } from "../src/api/schemas.js"; +import { CreateCustomerInsertSchema } from "../src/generated/CreateCustomer.js"; + +// `required` follows the order of the fields, which does not change what a schema accepts. +const rules = (schema: z.ZodType, io: "input" | "output") => + JSON.parse( + JSON.stringify(z.toJSONSchema(schema, { io, unrepresentable: "any" }), (key, value) => + key === "required" && Array.isArray(value) ? [...value].sort() : value, + ), + ); + +for (const io of ["input", "output"] as const) { + assert.deepEqual(rules(CreateCustomer, io), rules(CreateCustomerInsertSchema, io)); +} +``` + +`z.toJSONSchema` is Zod 4. On Zod 3, sort and compare `zodToJsonSchema(schema)` from the +`zod-to-json-schema` package instead. + +A required string generates `.min(1)`, so a hand-written `z.string()` with no minimum shows up here +as a `minLength` difference. If the existing schema really accepts an empty string, say so in the +model with `validator.length: { min: 0 }` as a child of the field. + +Move a call site by swapping the import and the schema name: + +```ts +import { type CreateCustomer, CreateCustomerInsertSchema } from "./generated/CreateCustomer.js"; + +export function parseSignup(body: unknown): CreateCustomer { + return CreateCustomerInsertSchema.parse(body); +} +``` + +### Pydantic + +Install with `pip install metaobjects "pydantic>=2.8"`. + +The model's field name is the Pydantic attribute, so keep `snake_case` names in the model. A shared +`str` Enum is an abstract `field.enum` that each field `extends`. An enum declared inline on the +field generates a `Literal` instead. + +```yaml +metadata: + package: shop + children: + - field.enum: + name: OrderStatus + abstract: true + values: [pending, paid, shipped] + - object.entity: + name: Order + children: + - source.rdb: { table: orders } + - field.long: { name: id, required: true } + - field.enum: { name: status, extends: OrderStatus, required: true, default: pending } + - field.string[]: { name: tags, required: true, default: "{}" } + - field.date: { name: placed_on, required: true } + - identity.primary: { fields: id, generation: increment } +``` + +Generate beside the existing models: + +```yaml +# metaobjects.config.yaml +metadata: metaobjects +targets: + app: + outDir: generated # beside the existing code; nothing imports it yet + generators: [entity] +``` + +Run `metaobjects gen` from the project root to generate. + +mypy cannot compare two Pydantic models, because a class is its own type, whatever its fields are. +Pydantic can describe a model as JSON Schema, so compare those. Pydantic validates input and writes +output differently, so check both modes. Copy this into `proof/test_equivalence.py` and name each +pair: + +```python +from typing import Any + +import pytest +from pydantic import BaseModel + +import app.models as existing +from generated import Customer, Order, ShippingAddress + + +def shape(model: type[BaseModel], mode: str) -> dict[str, Any]: + """The schema with what does not change behaviour removed: titles and descriptions, the + order of `required`, and `$ref`, which is inlined so a `str` Enum matches a Literal.""" + schema = model.model_json_schema(mode=mode) + defs = schema.pop("$defs", {}) + + def walk(node: Any, seen: tuple[str, ...] = ()) -> Any: + if isinstance(node, list): + return [walk(item, seen) for item in node] + if not isinstance(node, dict): + return node + if "$ref" in node: + name = node["$ref"].rsplit("/", 1)[-1] + if name in seen: # a model that contains itself + return {"$recursive": name} + rest = {key: value for key, value in node.items() if key != "$ref"} + return walk({**defs[name], **rest}, (*seen, name)) + out: dict[str, Any] = {} + for key, value in node.items(): + if key in ("title", "description"): + continue + if key == "properties": + out[key] = {field: walk(prop, seen) for field, prop in value.items()} + elif key == "required": + out[key] = sorted(value) + elif key == "default": + out[key] = value + else: + out[key] = walk(value, seen) + return out + + return walk(schema) + + +@pytest.mark.parametrize("mode", ["validation", "serialization"]) +@pytest.mark.parametrize( + ("hand_written", "generated"), + [ + (existing.Customer, Customer.Customer), + (existing.CustomerCreate, Customer.CustomerCreate), + (existing.ShippingAddress, ShippingAddress.ShippingAddress), + (existing.Order, Order.Order), + ], +) +def test_same_shape(hand_written: type[BaseModel], generated: type[BaseModel], mode: str) -> None: + assert shape(hand_written, mode) == shape(generated, mode) +``` + +Run `python -m pytest proof/ -vv` from the project root. `-vv` prints the whole difference, with +the field name in it. Schemas carry field constraints such as `max_length`, so this also catches a +rule the Python type does not show. + +Move a call site by changing its import: + +```python +from generated.Customer import Customer, CustomerCreate +``` + +Move models that nest together. Pydantic refuses an instance of a different class even when the +shape matches, so a generated `ShippingAddress` passed to the hand-written `Order` raises a +`ValidationError`. If they cannot move together, hand over `address.model_dump()` at the seam. + +The check against a database is `meta verify --db`, which needs the Node CLI, because schema +tooling is TypeScript only. `metaobjects verify` compares the generated code with the model. + +## Fixing the differences + +Fix each one in the model or the config, and leave the existing code alone until it has moved. + +| What you see | Why | Fix | +|---|---|---| +| A timestamp is `Date` on one side and `string` on the other | Generated timestamps read as strings by default | `timestampMode: "date"` in the config (Postgres) | +| A field the database fills is required on insert | The model has no default | Add `default:` to the field | +| A database-set timestamp is accepted on create | The field is writable | `default: now(), mutability: readOnly` | +| An array column's default is reported by `verify --db` | An array `default` must be a string | `default: "{}"`, not `default: []` | +| `verify --db` reports a different foreign key name | The generated name differs | `constraintName` on `identity.reference` | +| `verify --db` reports a different unique index name | The name comes from the identity | Name `identity.secondary` after the existing index | +| A `tsc` failure names a field that is `T \| null` on one side | The existing type allows both null and absent | Model what the code relies on. If the difference is deliberate, keep it visible: `Same, "notes">>` with a comment | + +## What the proof does not cover + +- **Custom logic.** A `.refine()`, a `.transform()` or a Pydantic validator is not in the type or + in the JSON Schema, so neither side of the proof sees it, and the model does not carry it. Keep + it in your code: refine the generated schema, or subclass the generated model. +- **Behaviour.** The proof compares declared shapes. The project's own tests still have to pass + after each move. +- **Native Postgres enums.** A `pgEnum` column cannot be modelled: `field.enum` is text plus a + CHECK. `tsc` passes and `meta verify --db` reports the missing CHECK. Convert the column to text + with a CHECK first, or leave that table out for now. +- **Python enum member names.** JSON Schema sees the values, not the member names. A generated enum + has `UPPER_CASE` members, so `OrderStatus.pending` in a call site must become + `OrderStatus.PENDING`. mypy or pyright finds those call sites. +- **Extra optional fields on a nested TypeScript type.** `Differs` compares a nested field as a + whole, so an optional extra inside it still assigns both ways. Give each nested type its own line. +- **Pairs you did not name.** The proof compares only what it lists, so list every exported type. diff --git a/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md b/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md index 7ae8965..1997e78 100644 --- a/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md +++ b/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md @@ -150,8 +150,9 @@ codegen emit the idiomatic check; don't hand-write a `validator.regex` for it. ## Extending the metamodel — custom providers, and the downstream lifecycle -The decision procedure at the top of this file governs new vocabulary you register — apply it -mechanically before registering anything. A would-be subtype that differs from an +Model the domain semantically first (`semantic-modelling.md`: types, their relationships and +what stays out of the model). The decision procedure at the top of this file then governs each +piece of new vocabulary you register — apply it mechanically before registering anything. A would-be subtype that differs from an existing one only by a *property* is an **attribute**, not a subtype (a "short string" isn't a new field subtype — that is `@maxLength`); a plain string that merely needs validating is a **validation attribute**, not a subtype (its native type is @@ -162,6 +163,17 @@ or behavior is a **subtype**, and structural variants *within* such a subtype ar (including any `@kind` value-set) carry `allowedValues` in the gate (ADR-0036). ADR-0037 is the authority. +**What a provider does.** It names an `id` and the provider ids it depends on, then does one +or both of two things. It **registers** a new `(type, subType)` with its own attributes, which +may be required, and a node class (reuse the type's existing one unless the node has new +behaviour). It **extends** an existing `(type, subType)` with attributes, which must be +optional: a required one is `ERR_EXTEND_REQUIRED_ATTR` (ADR-0050), because removing your +provider must never weaken a type someone else owns. A new type allowed at the document root +also needs `extend` on `metadata.root` to admit it, or it fails with `ERR_CHILD_NOT_ALLOWED`. +An attribute no provider declares is `ERR_UNKNOWN_ATTR` under a strict load, and a subtype +nobody registered is `ERR_UNKNOWN_SUBTYPE`; that refusal is what keeps a typo from loading. +The per-language example and wiring is in the skill's `references/-providers.md`. + **Converge before inventing.** Search the shipped vocabulary first (`meta types `) and check the roadmap — if core already models (or plans) the concept, model yours in a fold-in-friendly shape. The type names `api`, `operation`, `surface`, and @@ -175,9 +187,19 @@ and address-free — the subtype names the *concept*; transport/protocol is a cl Declare config as the *names* of required keys (values stay in env/config) and generate a fail-closed check. Reference typed payloads instead of inlining shapes. +**Name your attributes so they cannot collide.** Two providers may not claim one attribute +name on a node type (ADR-0062): the registry refuses the second at composition with +`ERR_PROVIDER_ATTR_CONFLICT` (same `(type, subType)`) or `ERR_PROVIDER_ATTR_SHADOW` (the shared +`.base` root, or a subtype of it), naming both providers. A physical address takes your +store's own idiomatic word (`@column` relational, `@field` document), unique on that node type; +`meta types --detail` shows which provider holds each name. A store with no provider of its own +uses the registered `attr.properties` bag rather than an invented attribute. + **Lifecycle.** Register with explicit provider wiring — never loosen `strict` to free-ride ad-hoc attrs. When core later ships the concept your provider shrinks from `register` to `extend` (the `template.toolcall` precedent). A second independent consumer wanting the same concept is a consumer→core promotion candidate (ADR-0011) — -open an upstream issue rather than adding core vocabulary yourself. Full guidance: +open an upstream issue rather than adding core vocabulary yourself. In this repo new +vocabulary lives in its own provider pack, never in `metaobjects-core-types` (GOVERNANCE.md, +"Extension packs and the core metamodel"). Full guidance: `docs/features/downstream-metadata-decisions.md`. diff --git a/.claude/skills/metaobjects-authoring/references/declaring-reports.md b/.claude/skills/metaobjects-authoring/references/declaring-reports.md index 544a7fb..ecaaa30 100644 --- a/.claude/skills/metaobjects-authoring/references/declaring-reports.md +++ b/.claude/skills/metaobjects-authoring/references/declaring-reports.md @@ -18,6 +18,10 @@ and an `object.report` combines them by name. Four node kinds: `field.boolean` `@of`, or no `@of` and a `@filter` or `@segment`: `{ "name": "hasError", "@agg": "any", "@filter": { "success": false } }` is "some row has `success` false" (a row whose condition is null does not pass); +- `measure.derived` — `@expr` arithmetic (`add`, `subtract`, `multiply`, `divide`, two operands + each) over `{ "field": }` and `{ "value": }`: + utilization is `billableHours × 100 ÷ (weeklyCapacityHours × 52 ÷ 12)`. A dimension it reads + must be in the report's `@dimensions`; it never reads another derived measure; - `segment.filter` — a named, reusable `@filter` ("active purchase"); - `object.report` — a top-level object: `@from` an entity, `@dimensions` (`name` or `name:grain`), `@measures`. @@ -72,6 +76,11 @@ Three rules an author trips on: measure (a time dimension at a grain is ``, so `purchasedAt:day` is `purchasedAtDay`). A `field.*` or `identity.*` child on a report is an error. +**Money.** `@of` may name a member of a `@storage: flattened` value object, +`Payment.amount.amount`. A `sum`, `avg`, `min` or `max` of it loads only when the report also +lists a dimension over each non-numeric member (`Payment.amount.currency`), so currencies are +never added together. A jsonb value object's members are refused. + Two questions to answer for every report: - **Do I want the rows that have no facts?** A report's rows come from the facts, so a @@ -99,8 +108,8 @@ A report `@from` a TPH subtype is refused when its view is derived (the subtype base's table): declare it `@from` the base with an `@filter` on the discriminator field. What does not exist: no grid or form for a report (TypeScript generates a list hook; no other port has a client tier), no way to narrow which -derived fields are filterable, no `measure.derived` -(arithmetic between measures beyond `measure.ratio`), no query-time choice of dimensions or +derived fields are filterable, no product measure +(`sum(hours × rate)`), no member of a jsonb value object, no query-time choice of dimensions or measures (a report is a fixed, compiled combination), and no time-zone vocabulary (grains and relative dates are UTC). Column types, the null rules, Monday weeks and per-engine differences are in `references/reporting.md`. diff --git a/.claude/skills/metaobjects-authoring/references/identities-and-indexes.md b/.claude/skills/metaobjects-authoring/references/identities-and-indexes.md index f21a5d0..22b3ef1 100644 --- a/.claude/skills/metaobjects-authoring/references/identities-and-indexes.md +++ b/.claude/skills/metaobjects-authoring/references/identities-and-indexes.md @@ -42,10 +42,16 @@ An `identity.secondary` can index an **expression** instead of plain columns: us index method — `gin` / `gist` / `hash`; default `btree`) and `@where` (a partial-index predicate). +**Name every `identity.secondary` and `index.lookup` after its table.** The name is used +verbatim as the database index name, and index names are unique across the whole schema, +not per table. Two entities that both declare `byName` load and generate cleanly, then +`meta migrate` stops with `ERR_DUPLICATE_SQL_NAME`. Prefix the entity (`clientByName`, +`tagByName`). + ```json { "identity.primary": { "name": "id", "@fields": ["id"], "@generation": "increment" } } -{ "identity.secondary": { "name": "byEmail", "@fields": ["email"] } } -{ "identity.secondary": { "name": "byEmailCI", "@expr": "lower(email)" } } +{ "identity.secondary": { "name": "userByEmail", "@fields": ["email"] } } +{ "identity.secondary": { "name": "userByEmailCI", "@expr": "lower(email)" } } { "identity.reference": { "name": "fkAuthor", "@fields": ["authorId"], "@references": "Author", "@enforce": true } } ``` @@ -73,10 +79,10 @@ The db provider contributes physical-tuning attrs alongside either form: `@order `btree`), and `@where` (partial-index predicate). ```json -{ "index.lookup": { "name": "byCreatedAt", "@fields": ["createdAt"], "@orders": ["desc"] } } -{ "index.lookup": { "name": "byStatusCreatedAt", "@fields": ["status", "createdAt"] } } -{ "index.lookup": { "name": "byEmailCI", "@expr": "lower(email)" } } -{ "identity.secondary": { "name": "uniqLowerEmail", "@expr": "lower(email)" } } +{ "index.lookup": { "name": "orderByCreatedAt", "@fields": ["createdAt"], "@orders": ["desc"] } } +{ "index.lookup": { "name": "orderByStatusCreatedAt", "@fields": ["status", "createdAt"] } } +{ "index.lookup": { "name": "userByEmailCI", "@expr": "lower(email)" } } +{ "identity.secondary": { "name": "userUniqLowerEmail", "@expr": "lower(email)" } } ``` `index.lookup` is a sibling of `identity.*` — declare it as a direct child of an `object.entity`, diff --git a/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fc..9ef1b62 100644 --- a/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md b/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md index 2574655..35ac248 100644 --- a/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md +++ b/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md @@ -9,10 +9,14 @@ committed snapshot — that snapshot loads BEFORE your own files, so a foreign abstract resolves via `extends` and a foreign node re-opens via `overlay: true` exactly like a local one. A dependency names one transport: `path` (a directory relative to the directory holding `.metaobjects/`), `npm` (an installed npm -package, e.g. `{ "name": "acme-model", "npm": "@acme/model", "dir": "metaobjects" }`) -or `python` (an installed Python package by its import name, e.g. -`{ "name": "acme-model", "python": "acme_model", "dir": "metaobjects" }`). For -`npm`/`python`, install the package with the project's package manager first; +package, e.g. `{ "name": "acme-model", "npm": "@acme/model", "dir": "metaobjects" }`), +`python` (an installed Python package by its import name, e.g. +`{ "name": "acme-model", "python": "acme_model", "dir": "metaobjects" }`), `maven` +(`{ "name": "acme-model", "maven": "com.acme:acme-model", "version": "1.0.0" }`, a JAR in the +local Maven repository) or `nuget` +(`{ "name": "acme-model", "nuget": "Acme.Model", "version": "1.0.0" }`, a package in the NuGet +global packages folder). For +`npm`/`python`/`maven`/`nuget`, install or restore the package with the project's package manager first; `meta deps sync` locates it, copies its shared model into the snapshot, and says what to install when it is missing. Prefer the package transport over a `path` into someone else's checkout when the publisher releases a package. Two rules are diff --git a/.claude/skills/metaobjects-authoring/references/model-first-rationale.md b/.claude/skills/metaobjects-authoring/references/model-first-rationale.md index 7937be3..bd51b49 100644 --- a/.claude/skills/metaobjects-authoring/references/model-first-rationale.md +++ b/.claude/skills/metaobjects-authoring/references/model-first-rationale.md @@ -1,14 +1,14 @@ # Why model-first wins -The case behind the operating principle in `SKILL.md`: why declaring the model beats hand-writing a layer, even when the hand-written version is cheaper this once. +The case behind the operating principle in `SKILL.md`: why declaring the model usually beats hand-writing a layer, even when the hand-written version is cheaper this once. The cost test in `SKILL.md` still decides a one-off. ## Contents - Second source of truth - The consistency tax - One change, every layer -**Why model-first wins even when hand-writing is cheaper this once — and it often -is, this once:** +**Why model-first usually wins, even when hand-writing is cheaper this once — and it often +is, this once (the cost test in `SKILL.md` still decides a true one-off):** - **Hand-writing a layer the metadata could own creates a second source of truth for one fact.** A field's type, validation, column, route, and form then change in N places and must stay consistent forever — not drift *risk*, but two sources of diff --git a/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md b/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md index c58b0e5..99422ce 100644 --- a/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md +++ b/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md @@ -1,6 +1,6 @@ # Projections, `origin.*`, and managed views -> Part of the `metaobjects-authoring` skill. The skill covers the entity read-view, which is the right answer for most grids. Read this when you need an independent exposure (`object.projection`), the `origin.*` vocabulary, `@filter` / `@expr` shapes, or an `@sql` / `@unmanaged` view. +> Part of the `metaobjects-authoring` skill. The skill covers the entity read-view, which is the right answer for most grids. Read this when you need an independent exposure (`object.projection`), the `origin.*` vocabulary, `@filter` / `@expr` shapes, or an `@sql` / `@unmanaged` view. A grouped total or report (per client, per month) is an `object.report`: `declaring-reports.md`. ## Contents - Read-view or projection? @@ -125,8 +125,9 @@ non-aggregate-derived** projection fields: naming an undeclared field fails the **The `CREATE VIEW` body is generated from those `origin.*` children by the Node `meta migrate` — never hand-author view SQL for a shape origins can express** (an unmodeled -view is *unmanaged*, so `meta verify --db` can't even catch the drift). For a genuinely -irreducible body (recursive CTE, window function, set operation) that origins can't express, +view is *unmanaged*, so `meta verify --db` can't even catch the drift). **An `@sql` body that +`GROUP BY`s: check `declaring-reports.md` first** (`object.report`, `@spine`, `@default`). +For a genuinely irreducible body (recursive CTE, window function, set operation) that origins can't express, carry it in the `source.rdb` **`@sql`** escape (#208, ADR-0043) — a hand-written body the tool registers, fingerprints, and drift-checks (adopt a pre-existing view with `meta migrate --allow adopt-view`) — rather than a hand-edited migration file where it goes @@ -153,6 +154,13 @@ walls it off (#208).** Author an `@sql` source under these constraints or the lo - Today `meta migrate` **lowers `@sql` only on `@kind: view`**; on matview / storedProc / tableFunction it is registered but not yet migrate-managed (mark those `@unmanaged`). +**Removing a column an `@sql` body reads: edit the body in the same change.** The tool never +parses an `@sql` body, so it cannot see that the body still names the column. The migration +is still written: on Postgres it fails at apply (`column "…" does not exist`); on SQLite it +applies and leaves a view that errors when queried. An `@unmanaged` view is not rewritten +either: with `--from-db`, `meta migrate` blocks a drop of a column such a view still reads +and names the view (`--allow drop-column-read-by-view` to proceed); fix the view first. + **A `passthrough` field must match its `@from` source's type.** A passthrough forwards the source value unchanged, so the projection field's `field.` and array-ness must be identical to the source field's — a `field.uuid` source diff --git a/.claude/skills/metaobjects-authoring/references/reporting.md b/.claude/skills/metaobjects-authoring/references/reporting.md index 33c60ec..be43b2d 100644 --- a/.claude/skills/metaobjects-authoring/references/reporting.md +++ b/.claude/skills/metaobjects-authoring/references/reporting.md @@ -49,6 +49,7 @@ A report declares no fields. Its columns are one per `@dimensions` item in liste | `min` / `max` | the measure's name | the `@of` field's type | no | | `any` / `all` (boolean OR / AND, `bool_or` / `bool_and`; over a `field.boolean` `@of`, or with no `@of` over the measure's `@filter` / `@segment`) | the measure's name | `boolean` | no | | `measure.ratio` | the measure's name | `decimal` | no | +| `measure.derived` | the measure's name | `decimal` | no | | any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads the default instead of null | | in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the field is `@required` or in that entity's `identity.primary`; no for a dimension beyond the spine entity | @@ -72,6 +73,7 @@ Add `"startOf": "day"`, `"week"` or `"month"` to cut the window to a calendar bo - A `sum` of nothing is **null**, not zero: no matching rows, or a filtered measure that matched none of a group's rows. So are `avg`, `min` and `max`. - An `any` or `all` over no rows, or only null values, is **null**, not `false`. `"@default": 0` reads `false` and `"@default": 1` reads `true` (any other number is refused). - A ratio is `numerator / NULLIF(denominator, 0)`: a zero denominator is **null**. Each operand must be a numeric measure: a `count`, a `sum`, an `avg`, or a `min` or `max` of a numeric field. An `any` or `all` (a boolean), or a `min` or `max` of a date, timestamp, string, uuid or enum, is refused as `@numerator` or `@denominator`. For a share, use an `@agg: count` with a `@filter`. +- A derived measure's `divide` divides as a ratio does (null on a zero divisor); a null operand makes it null, so default the operand measure when `0` is meant. - A report with no dimensions is one row for the whole table, and still one row over an empty table (counts `0`, sums and ratios null). **Ask: is zero true here, or is null?** If "nothing to aggregate" means zero (revenue of a program nobody bought is `0`), declare `"@default": 0` on the measure (`revenue` in the example under "Rows with no facts"). If it means unknown (the average rating of a product with no ratings is not `0`), leave it null. Do not default in the client what the model can state once. @@ -169,7 +171,7 @@ A concrete report whose read source is `@kind: view` is served by every port's g - **Every derived field with filter operators is filterable and sortable**, dimension and measure alike, with its type's own operators. You cannot narrow that set: a report has no field to put `@filterable` on. A field of the `@from` entity that the report does not expose is refused with a `400`. - A time dimension at `day` or coarser is `YYYY-MM-DD`; a null measure is `null` with the key present (a measure with `@default` is never null); `currency` is integer minor units. - **A decimal (`avg`, a ratio, a `sum` of a decimal) is written per the project's `wire` setting**: by default, the port's language-standard form (a JSON number in C#, Java and Kotlin; a string in Python and TypeScript), and under `"wire": { "decimals": "string" }` one canonical string in every port (`12.5`, never `12.50` or an exponent). Do not parse it as a float to compare. -- `meta gen` writes a model page for every report (`docsFile()`; a sourceless one is marked "Not served") and an API page for a served one (`apiDocsFile()`) — each an ordinary entry in `generators`. +- `meta gen` shows every report in the model explorer (`docsSiteFile()`; a sourceless one is marked "Not served") and writes an API page for a served one (`apiDocsFile()`) — each an ordinary entry in `generators`. The files each port generates are in the `metaobjects-codegen` skill's reference for that language ("Reports"). diff --git a/.claude/skills/metaobjects-authoring/references/requirements.md b/.claude/skills/metaobjects-authoring/references/requirements.md new file mode 100644 index 0000000..e2e6396 --- /dev/null +++ b/.claude/skills/metaobjects-authoring/references/requirements.md @@ -0,0 +1,225 @@ +# Requirements — `requirement.functional` / `requirement.architectural` + +Capabilities are **metadata**, declared in the metadata directory beside the entities they +describe. Read the existing requirement nodes before designing anything. Two rules matter +more than the rest. + +## Contents +- A requirement is PRESCRIPTIVE — it states what should be true, never what happened +- Do not delete a retired capability's entry +- When you add an entity, claim it +- A feature commit updates the ledger in the same commit +- Every requirement states its counterexample +- Four prose slots, and `statement` is the one that means "description" +- `title` is a LABEL and is chartered here; `summary` is not +- Never put a catalogue or ticket id in `title` +- The `name` is an address, so write it as an identifier +- Hierarchy is nesting, and links live at the bottom +- Write an L5 ref as a dotted `pkg::Owner.member` path +- L1–L3 are levels of abstraction and ownership in the problem domain +- Architectural requirements are the other kind +- Record gaps rather than rounding them off +- `status: planned` locks in work you have not started +- Which `verify` says what +- A requirement's name and package end up in generated test names + +**1. A requirement is PRESCRIPTIVE — it states what should be true, never what happened.** +`status` is `planned | live | partial | retired`, and every one of them states something +meant to be true. `retired` is not the exception: it means **"this was built, then +deliberately removed, and must not be rebuilt"** — a prohibition in force, falsifiable by +exactly one observable, the capability reappearing. + +So write a retired entry as a rule, not a diary. `statement: "An unpaid order is never +expired by a wall-clock timer"` is a prohibition; `"We used to expire orders on a timer"` is +history wearing a requirement's shape, and no gate will catch it. On a retired entry +`counterexample` describes **the revival** — the thing a future reader is about to propose. + +**Do not delete a retired capability's entry.** Keeping it is the single most load-bearing +thing this vocabulary does: given a brief for a capability that had been retired, agents +working from the model alone proposed rebuilding it 24 times out of 24. The entry is what +stops that, so a retirement is a status change plus a rewritten statement, never a deletion. + +Three rules the loader enforces on `retired`: + +- **`implementedBy` is REFUSED** — a retired capability has no implementation by definition. + What used to implement it goes in `notes`. If deleting the references feels wrong, the + capability is probably not retired: an entry whose nodes are still there is `live` or + `partial`. +- **`supersededBy` names the requirement that replaced it**, legal here only, and RESOLVED — + so the chain still works when the replacement is itself retired later. +- It never counts toward object coverage, and is exempt from the architectural universality + check. + +Leaving a dangling `implementedBy` is **correct only on `planned`**: the entry precedes the +nodes. On `live` or `partial` the same dangling reference is an error — the model moved and +the requirement went stale. + +**2. When you add an entity, claim it.** Every `object.entity` should appear in some +requirement's `implementedBy`, or `verify` says so. + +**A commit that adds, changes or removes behaviour updates the ledger in the same commit.** +`verify` checks that the ledger's links resolve, never that it is current, so nothing fails +when a feature ships and its requirement does not move. In the same commit, write the new or +changed claim, set its `@status` (`planned` to `live` when it lands, `retired` when it is +removed) and keep its `@implementedBy` pointing at the real nodes (a retired entry carries +none). If the commit should not +touch the ledger, say why in the commit message. + +**Every requirement states its counterexample.** One sentence: what breaking it looks like. +*"Every entity has a uuid primary key"* is violable — point at one with a composite string +key. *"Things are persisted"* is not, and is a description rather than a requirement. Same +rule kills *"the system is reliable"*. If you cannot say what breaking it looks like, +delete it. + +**Four prose slots, and `statement` is the one that means "description".** A requirement can +also carry the common `description` and `notes`, and they overlap badly unless you decide the +split before writing any of them: + +- `statement` — **the claim**. This IS the description of what the requirement is +- `counterexample` — **what would falsify the claim**, which is what makes it checkable +- `description` — **the scope**: what the claim covers, what it deliberately does not, and + which sibling entry owns the rest +- `notes` — **the evidence**: how you know the `status` is true — citations, vocabularies, the + control you ran to prove an absence was real + +**`title` is a LABEL and is chartered here; `summary` is not.** A requirement's `name` is an +identifier and its address renders as a dotted camelCase path, so a short noun-phrase `title` is +what an index shows — the requirement attribute table in `spec/capability-ledger.md` says so by +name, and the generated requirements page renders it in the heading after the path +(`## checkout.payment — Payment capture`). `summary` is different: `statement` is already the +required one-line sentence, so a `summary` can only repeat it and nothing reads it (`verify` warns, +`WARN_REQUIREMENT_INERT_DOC_SLOT`). `notes` is unrendered on purpose — chartered internal-only. + +**Never put a catalogue or ticket id in `title`.** A title is a noun phrase; an id is not a name. +`title: "FR-467 — Order recording"` is two things in one slot — put the id in `trackedBy` and +keep the phrase as the title. `verify` warns (`WARN_REQUIREMENT_TITLE_IS_AN_ID`). + +**The `name` is an address, so write it as an identifier.** It is the segment of the dotted +path (`Ordering.Placement.Recorded`) and the filename of the generated test stub. A `.` in a +name is indistinguishable from nesting — `Orders.Recorded` and `Orders` containing `Recorded` +produce the same path — and a sentence for a name puts the claim somewhere nothing reads it. +Both load; `verify` warns (`WARN_REQUIREMENT_NAME_NOT_ADDRESSABLE`, +`WARN_REQUIREMENT_NAME_READS_AS_PROSE`, `WARN_REQUIREMENT_NAME_RESTATES_STATEMENT`). + +Two failure modes, both of which look like diligence. A `description` that **paraphrases the +statement** is padding, and it makes every later reader trust the ledger less — leave it off +instead, it is optional. A `description` that **narrates the evidence** belongs in `notes`; +the tell is a fact you had to read the implementation to learn. Mechanical test for the last +line: *would this sentence have to change if the code changed but the model did not?* Then it +is `notes`. `verify` warns on the exact repeats (`WARN_REQUIREMENT_PROSE_DUPLICATED`), and on +a `statement` or `counterexample` that is present but blank (`WARN_REQUIREMENT_PROSE_EMPTY`) — +the loader requires those attrs to exist, never to say anything. + +**Hierarchy is nesting, and links live at the bottom.** L1 solution, L2 segment, L3 +service — these never reference the model. **L4** binds a declared top-level node — an +`object.*` **or a `template.*`** — and **L5** binds a member of one: a field, view, +validator, identity, a template's child, an operation, or a transition. `implementedBy` above L4 is an error. +Regrouping *moves* a node; it does not edit a parent string. + +**Write an L5 ref as a dotted `pkg::Owner.member` path** — the level and the shape of the +ref must agree, and this is the single easiest thing to get wrong: + +```yaml +# L4 binds the OBJECT +level: 4 +implementedBy: ["acme::orders::Order"] + +# L5 binds ONE MEMBER of it — dotted owner.member, not the object +level: 5 +implementedBy: ["acme::orders::Order.placedAt"] +``` + +Both mismatches are caught and they are symmetric: an L5 whose ref names an object is +`ERR_REQUIREMENT_L5_NOT_MEMBER`, an L4 whose ref names a member is +`ERR_REQUIREMENT_L4_NOT_OBJECT`. **In both cases the fix is to move the entry to the other +level, not to rewrite the ref** — the ref is usually right and the level is usually the +mistake. The instinct that produces the error is reaching for the object a rule is *about*; +what L5 wants is the member the rule is *carried by*. Copying an L4 block and changing only +`level: 5` produces exactly this failure. + +Reach for L5 when the statement is about ONE column and its entity's own requirement could +not express it — "this lifecycle is `resolvedAt IS NULL` and never `status`", "this id is +nullable, which is why the parent is `partial`". Do NOT use L5 for a blanket rule that +happens to touch many fields; that is an architectural requirement. + +Claim your prompts. A `template.prompt` is a model node realising a capability exactly as +an entity is, and it is the node whose retirement is hardest to see later — a removed +prompt leaves no table behind. A prompt estate with no requirement entries is the same +blind spot this whole mechanism exists to close. + +**L1–L3 are levels of abstraction and ownership in the problem domain** — whose need is +this, and at what altitude — and are NEVER a directory, package, deployable or module. +Technical constructs appear only at L4/L5, which is the allocation step. Test every node: +*if a refactor that changes no behaviour would force it to move, its level is wrong.* + +**Architectural requirements are the other kind.** `requirement.architectural` is flat by +default — a uuid-PK rule, change attribution, tenant scoping. Its check is *universality* +rather than existence, so one that is `live` and claimed by nothing fails: a policy +declared and applied to nothing. A `@level` is OPTIONAL here and opts the node into a tree +(for organising non-functional requirements under a quality taxonomy); once levelled, the +same nesting and link-floor rules apply as to a functional node. + +`@status` is a closed enum enforced by the loader, so a typo fails the load rather than +silently disabling the entry. + +**Record gaps rather than rounding them off.** `partial` says *this works and here is what +is wrong with it*, and it is the most useful status in the enum — a ledger with none is +usually one nobody read carefully. Then say what was DECIDED, which is a separate question: + +- `@disposition: accepted` — understood, deliberately not being closed +- `@disposition: deferred` — will be closed, not now (name a ticket in `@trackedBy`, or + `verify` warns; deferring without one is how a known problem becomes an unknown one) +- **absent** — undecided, and that is a real state. `verify` counts these, because + *"which gaps has nobody ruled on?"* is the question a review exists to answer. + +A `partial` nobody intends to finish is `partial` + `@disposition: accepted` — the gap is +understood and deliberately not being closed. If the capability itself is gone, delete the +requirement instead. + +**`status: planned` locks in work you have not started.** Its references may dangle (write +the requirement before the entity), and it never counts toward object coverage — otherwise +declaring an intention would clear the unclaimed-entity warning and the gate would measure +ambition rather than work. + +```yaml +- requirement.functional: + name: Pacing + level: 3 + status: live + statement: "Scene pacing follows story beats" + counterexample: "A scene that advances on a clock rather than on the story" + children: + - requirement.functional: + name: BeatProgression + level: 4 + status: planned # not built yet -- refs may dangle + statement: "A scene advances when its beat completes" + counterexample: "A scene that advances with its beat unresolved" + trackedBy: ["acme/game#412"] + implementedBy: ["game::turn::BeatProgression"] # does not exist YET + +- requirement.architectural: + name: UuidPrimaryKeys + status: live + statement: "Every entity has a uuid primary key" + counterexample: "An entity keyed by a composite string" + implementedBy: ["game::turn::Turn", "game::world::Location"] +``` + +**Which `verify` says what.** The gate — dangling references, links above the floor, +level and nesting errors, an unclaimed entity, a live requirement nothing implements — runs +in every port's `verify` (`meta verify`, `metaobjects verify`, `mvn metaobjects:verify`, +`dotnet meta verify`). The authoring warnings named on this page (`WARN_REQUIREMENT_NAME_*`, +`WARN_REQUIREMENT_PROSE_*`, `WARN_REQUIREMENT_INERT_DOC_SLOT`, +`WARN_REQUIREMENT_TITLE_IS_AN_ID`) are printed by the Node `meta verify` only, so on another +port follow these rules without waiting for a warning. + +**A requirement's name and package end up in generated test names.** Every port's +`requirement-tests` generator names a test from the requirement's package and dotted path +(`acme::shop::Orders.Recorded` becomes `req_acme_shop_Orders_Recorded…`), and two +requirements whose names differ only in punctuation (`Orders.Recorded` beside +`Orders_Recorded`) are refused as a collision outside TypeScript. Another reason to keep +names plain identifiers. + +There is **no `satisfies:` on a field or entity** — links live on the requirement node, not +on the nodes it claims. Full reference: the repo's `spec/capability-ledger.md`. diff --git a/.claude/skills/metaobjects-authoring/references/semantic-modelling.md b/.claude/skills/metaobjects-authoring/references/semantic-modelling.md new file mode 100644 index 0000000..2a08603 --- /dev/null +++ b/.claude/skills/metaobjects-authoring/references/semantic-modelling.md @@ -0,0 +1,210 @@ +# Semantic modelling: shaping vocabulary of your own + +> Part of the `metaobjects-authoring` skill. Read it before you add or change a custom type, +> subtype, attribute or provider, and before you author nodes of vocabulary this project +> registered itself. Vocabulary someone else registered (core, a pack, a library) is used the +> way its own documentation says. + +## Contents +- The habit to drop +- Three tiers +- Where one fact goes +- Things, not actions +- Type, subtype, attribute, child node or instance +- One base, variants that extend it +- Generated output: cover every fact, then do better +- Worked example +- Check before you register or commit + +## The habit to drop + +You will be handed a config file, a script or a block of code and asked to "put it in the +metadata". **Do not transcribe it.** A transcription carries the product's name, its version, +its statements and this environment's addresses into the model, and the model then has to +change every time one of those does. + +The model says **what a thing is and how it relates to other things**. How it is realised +belongs to the generators and their configuration. The payoff is what the project owner wants +from custom metadata: the project decides once, in its generators, how it uses a kind of +database, queue or platform, and after that a new queue, role or plan is a few lines of +metadata that the generators already know how to set up. The model also stays portable, +because it never named the product. This layers on top of the tools that do the work +(Terraform, a Dockerfile, a platform's config) by generating their input. It does not replace +them. + +## Three tiers + +| Tier | Holds | Changes when | +|---|---|---| +| **Type** | What the thing is, and how it relates to other things: what holds it, what it holds, what it refers to | the domain is understood differently | +| **Subtype** | The kinds of that thing. Adds attributes and constraints. **Never adds a relationship** | a new kind appears | +| **Implementation** | Products, versions, syntax, file layout, names, addresses. Generated, tuned by configuration | a product is swapped, upgraded or moved | + +Core is the model to copy: `source` (an object keeps its data somewhere) / `source.rdb` (that +somewhere is relational) / Postgres or SQLite as the `dialect` setting, with the DDL generated. +`source.rdb` says *relational*. It does not say Postgres and it does not say 18. + +**The upgrade test.** If the product were swapped, its version upgraded, or the system moved to +another environment, would this line of the model have to change? Then it is not semantic and +does not belong in the model. A required *capability* ("supports full-text search") passes the +test and may be stated. The product that provides it does not. + +## Where one fact goes + +Ask in order; the first match decides. + +| # | Question | Put it in | +|---|---|---| +| 0 | Computable from metadata already there? | nothing new: the generator derives it | +| 1 | What exists, what kind it is, what it relates to, who may do what to it, a rule it keeps, and it passes the upgrade test? | **metadata** | +| 2 | How one target writes things down: syntax, layout, an idiom, a sensible default? | **the generator**, as a default | +| 3 | A choice the same in every environment: product, version, dialect, naming? | **project configuration**, overriding the default | +| 4 | A *value* that differs per environment: address, credential, size? | **environment configuration**. The model may declare its name, never its value | +| 5 | A *fact* that differs per environment: one has something the others lack? | **metadata**, as a variant extending a shared base | + +Configuration is layered, each over the one before: generator defaults, then optional shared +configuration (a module or file several projects load), then project configuration (the +project's MetaObjects config and its generator options), then environment configuration. A +generator must write working output from the model alone. If nothing useful generates until +configuration exists, move those answers into the generator as defaults. + +## Things, not actions + +Model what exists and what each thing holds. Never the steps that set it up. + + +```yaml +# Wrong: an action, which is one generator's output written down as metadata +- action.grant: + name: grantReportingSelect + statement: GRANT SELECT ON ALL TABLES IN SCHEMA ledger TO reporting_ro +``` + + +```yaml +# Right: an identity, and the grants it holds, each typed by the kind of asset it is on +- role.service: + name: reporting + children: + - grant.relational: { name: ledgerAccess, asset: ledger, access: read } + - grant.queue: { name: exportsAccess, asset: exports, access: publish } +``` + +(These names are an illustration, not shipped vocabulary.) A thing can be referred to, +extended, overridden and queried ("who can read the ledger?"). The generator derives the verbs +from it: the statements that grant, and the ones that take away what is no longer declared. + +The tell is a verb in a type, subtype or node name: `create`, `send`, `grant`, `sync`, `run`, +`enable`. The one exception is an operation the application offers its callers (an `approve` +command): that exists, takes input and is guarded, so it is a thing. + +## Type, subtype, attribute, child node or instance + +First write one sentence per thing that names no product and no step: *"A role is an identity +that acts in the system. It holds grants. A grant is on one asset."* Nouns are candidate types. +"Holds" and "is on" are relationships, and relationships belong to types. + +| It is | Model it as | +|---|---| +| A thing with its own nature, relating to others as no existing type does | a **type** | +| A kind of an existing thing, relating to everything exactly as its siblings do | a **subtype** | +| A variant of one subtype that changes only the generated shape | **`@kind`** | +| A fact about one node: a flag, a closed choice, a limit | an **attribute** | +| Something a node has several of, each with facts of its own | a **child node** | +| One particular role, plan or queue | an **instance** (a node with a `name`), never a subtype | + +- A subtype may narrow a relationship its type has (`grant.queue` requires a queue asset). It + may not add a child type or a reference its siblings lack. If it needs one, put it on the + type or make a new type. In a provider definition file the shared reference attributes and + child rules go on `.base`, and each subtype sets `extendsBase: true`. +- `role.billingService` or `plan.enterprise` is an instance promoted to vocabulary. Write + `role.service` with `name: billing`. +- A list of names with their facts in sibling attributes (`features: [projects, exports]` + beside `maxProjects: 50`) is a set of child nodes that was flattened. "Prefer an attribute to + a new subtype" (`references/choosing-a-shape.md`) is about one concept on an existing type. + It is not a reason to fold separate things into their parent. + +Then run `references/choosing-a-shape.md` for each concept, and search before registering +(`meta types `). + +## One base, variants that extend it + +Several nodes that are the same thing in different circumstances (per environment, tier, +region) share one `abstract: true` node. Each variant `extends` it and holds only its +differences. A child with the same type and name as a base child replaces it. A variant that +repeats a line of its base is a copy that will drift: delete the line. Mechanics: +`references/abstracts-and-overlay.md`. + +## Generated output: cover every fact, then do better + +The target is not a byte-for-byte copy of the hand-written file. It is a better one. + +1. **Coverage.** List every fact the hand-written file states. Each needs a source: a node or + attribute, a generator default, or a configuration key. A fact with no source is a gap to + fix, never one to drop silently. +2. **Improvement.** The generator writes the file every time, so it states every default, + grants the narrowest access the model allows, names things consistently, cleans up what was + removed and traces each line to its node. + +Improving never means changing a fact other code or stored data depends on: an existing table +name, column type or route is the specification (`references/adopting-existing-code.md`). + +## Worked example + +Asked to put an app's subscription plans in the metadata, the transcription looks like this: + + +```yaml +- plan.stripe: # a product as the subtype + name: proMonthlyV2 # a version in the name + stripeApiVersion: "2025-08-27" # a product version + stripePriceId: price_1QxYz # an environment value (test and live differ) + features: [projects, exports] # things flattened to names + maxProjects: 50 # ...with their facts beside them + children: + - action.syncToStripe: { name: pushPrice } # a step the tooling runs +``` + +The sentences: *a plan is something an account subscribes to; it holds entitlements; an +entitlement is what the plan gives on one object of the model.* + + +```yaml +- plan.recurring: + name: Base + abstract: true + interval: month + children: + - entitlement.access: { name: projects, objectRef: Project } + - entitlement.quota: { name: projectLimit, objectRef: Project, limit: 3 } + +- plan.recurring: + name: Pro + extends: Base + children: + - entitlement.access: { name: exports, objectRef: ProjectExport } + - entitlement.quota: { name: projectLimit, objectRef: Project, limit: 50 } # replaces Base's +``` + +The billing product became project configuration, its API version a generator default, the +price id an environment value, and the sync a generated script. A new API version or a new +billing provider changes no line of the model. A new limit changes one. + +`objectRef` reuses the shipped name for a reference to an object. Reusing the name resolves +nothing by itself: register it in the provider as a reference to an object, so a renamed +`Project` fails the load instead of leaving the plans pointing at nothing. + +## Check before you register or commit + +1. Each type has a one-sentence description with no product, version or step in it. +2. Every relationship is on a type. No subtype adds one. +3. Every subtype is a kind that more than one node could be. +4. Anything with facts of its own is a child node, not an attribute value. +5. Every line passes the upgrade test. +6. Shared facts are on an abstract base. Variants hold only differences. +7. Every fact of a hand-written equivalent has a source, and the generators work with no + configuration. + +Tell the user where each fact of their original file went (model, generator default, project +or environment configuration), so nothing looks lost. The full page, with the reasoning: +`docs/features/semantic-modelling.md`. diff --git a/.claude/skills/metaobjects-authoring/references/sources.md b/.claude/skills/metaobjects-authoring/references/sources.md index 5f7f94c..bff437f 100644 --- a/.claude/skills/metaobjects-authoring/references/sources.md +++ b/.claude/skills/metaobjects-authoring/references/sources.md @@ -94,4 +94,6 @@ column because the filter tier runs against the view. **When you need an independent exposure** — a subset, renamed columns, a row-filtered view, a versioned or external shape — that is an `object.projection`. It, the `origin.*` vocabulary, the structured `@filter` / `@expr` shapes and the `@sql` / `@unmanaged` escapes -are in `references/read-views-and-projections.md`. +are in `references/read-views-and-projections.md`. A grouped or aggregate view (totals per client +or per month) is an `object.report` (`references/declaring-reports.md`); `@sql` is for what neither +can express (a recursive CTE, a window function, a set operation). diff --git a/.claude/skills/metaobjects-authoring/references/typescript-providers.md b/.claude/skills/metaobjects-authoring/references/typescript-providers.md new file mode 100644 index 0000000..e2d943e --- /dev/null +++ b/.claude/skills/metaobjects-authoring/references/typescript-providers.md @@ -0,0 +1,75 @@ +# Your own vocabulary in TypeScript — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its TypeScript tools load the +> metadata. +> Shape the vocabulary first: `semantic-modelling.md`. + +A provider is an object implementing `MetaDataTypeProvider`: an `id`, the provider ids it +depends on, and a `registerTypes(registry)` body that calls `register` (a new subtype) and +`extend` (attributes on an existing one). This one registers `layout.picker` and adds +`@searchable` and `@valueLabels` to `field.string`: + +```ts +// codegen/vocabulary.ts +import { TypeId, MetaLayout, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; +import { + TYPE_FIELD, TYPE_LAYOUT, FIELD_SUBTYPE_STRING, + ATTR_SUBTYPE_STRING, ATTR_SUBTYPE_BOOLEAN, +} from "@metaobjectsdev/metadata/constants"; + +export const vocabulary: MetaDataTypeProvider = { + id: "acme-vocabulary", + dependencies: ["metaobjects-core-types"], + registerTypes(registry) { + // A new subtype, with its own attribute (an own attribute may be required). + registry.register({ + typeId: new TypeId(TYPE_LAYOUT, "picker"), + description: "A picker over the owning object.", + factory: (typeId, name) => new MetaLayout(typeId, name), + childRules: [], + attributes: [ + { name: "displayField", valueType: ATTR_SUBTYPE_STRING, required: false, description: "Field shown per choice." }, + ], + }); + // Attributes on a type another provider owns: always optional. + registry.extend(TYPE_FIELD, FIELD_SUBTYPE_STRING, { + attributes: [ + { name: "searchable", valueType: ATTR_SUBTYPE_BOOLEAN, required: false, description: "Offer in search." }, + { name: "valueLabels", valueType: ATTR_SUBTYPE_STRING, isArray: true, required: false, description: "Display labels." }, + ], + }); + }, +}; +``` + +Wire it once, in `metaobjects.config.ts`: + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { vocabulary } from "./codegen/vocabulary"; + +export default defineConfig({ + generators: [/* ... */], + providers: [vocabulary], +}); +``` + +Every `meta` command that loads metadata reads that list: `gen` (with the docs generators and +the docs site), `verify`, `migrate`, `fmt`, `types`, `export`, `deps`, `upgrade`. `meta types +picker` then lists the new subtype. A config that fails to load is reported as its own error, +never as an unknown subtype. Code that loads the model itself passes the same provider: +`loadMemory(root, { providers: [vocabulary] })`. + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `meta verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (same `id`, same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/.claude/skills/metaobjects-codegen/SKILL.md b/.claude/skills/metaobjects-codegen/SKILL.md index f57fad8..fd6904e 100644 --- a/.claude/skills/metaobjects-codegen/SKILL.md +++ b/.claude/skills/metaobjects-codegen/SKILL.md @@ -1,40 +1,50 @@ --- name: metaobjects-codegen -description: Use when you need ANY output derived from the MetaObjects model — write your own generator (OpenAPI, JSON Schema, Zod, DTOs, a client, docs, anything) or eject a reference one — and when configuring or running code generation: editing the gen config (metaobjects.config.ts) to choose generators, targets or the SQL dialect (e.g. postgres to sqlite), the gen command, and hand-edit-preserving regeneration. +description: Use when you need ANY output derived from the MetaObjects model — write your own generator (Zod, DTOs, a client, docs, anything) or eject a reference one — and when configuring or running code generation: editing the gen config (metaobjects.config.ts) to choose generators, targets or the SQL dialect (e.g. postgres to sqlite), the gen command, and hand-edit-preserving regeneration. --- # MetaObjects code generation -Codegen is the first pillar: MetaObjects reads your typed metadata and emits -**idiomatic per-language code** — entity types, DB tables/schemas, query helpers, -REST routes, validators, payload value-objects, output parsers. The metadata is the -durable spine; the generated code is a disposable artifact. It has **no -proprietary runtime**: entity and model code imports nothing from MetaObjects, and the -REST, prompt and client tiers import ordinary Apache-2.0 packages you can vendor or -replace — if the libraries disappeared tomorrow, you keep working code. - -**MetaObjects is the core; the generators are yours** (ADR-0034 Amendments 3 and 4). The -core — model, loader, registry, `verify`, `migrate`, prompt render and reply extract — is -what MetaObjects guarantees. On it, you build the generators the application needs. The -generators MetaObjects ships are reference helpers: run one as shipped when it already -emits what you want, copy it with `eject` when it is close and you need to change it, and -write your own when nothing fits. When a generated file is -wrong, fix the generator that emitted it — do not hand-edit around it, and do not treat it -as a broken core guarantee. - -This skill is the port-agnostic procedure. The exact config file, generator names, -and command for *this* project's server language live in a reference fragment -(see the table below). +MetaObjects reads the typed metadata and emits ordinary code in your language: entity types, +tables, query helpers, REST routes, validators, payload types, reply parsers. The metadata is +what lasts; generated code is replaceable. Entity and model code imports nothing from +MetaObjects, and the REST, prompt and client tiers import ordinary Apache-2.0 packages you +can vendor or replace. + +## Essentials + +- **MetaObjects is the core; the generators are yours.** The model, loader, registry, + `verify`, `migrate` and prompt render are what MetaObjects guarantees. The generators it + ships are reference helpers: run one as shipped, copy it with `eject` to change it, or write + your own. A generator in this repo is ordinary source you own, and editing or writing one + needs no permission. A rule against changing MetaObjects itself is about a different + repository. +- **When generated output is wrong, fix what produced it, in this order:** the metadata if + the model is wrong; your generator if the model is right and the emit is wrong; hand-write + only what metadata cannot express. Hand-editing generated files, or hand-writing a layer + the model describes, restates the model somewhere nothing checks. +- **Need an output the model describes? Write a generator now, in this change.** It is about + 20 lines in every port. +- **Nothing is generated until you choose it.** No port has a default generator set; the + project's generator list is the complete list. `meta gen --list --format json --probe` is + the catalog. +- **Do not eject a generator you will not change.** Wire it from its package so upgrades + reach you; an unmodified copy only falls behind. +- **Commit `.metaobjects/.gen-state/.hashes/`.** It is how `gen` tells a file it wrote from + one somebody edited, and it refuses by name to overwrite the second. +- **Read your server language's reference file** for the config file, generator names and + commands: this file is the part every port shares. ## Reference files — open only the one your task needs Your server language's file (`references/typescript.md`, `references/java.md`, -`references/kotlin.md`, `references/csharp.md` or `references/python.md`) has the -exact config, generator names and commands for this project; read it. The other files in -`references/` are topics — open one when its row matches what you are doing. +`references/kotlin.md`, `references/csharp.md` or `references/python.md`) has the exact +config, generator names and commands for this project; only the ones for this project's +stack are installed. The other files are topics: open one when its row matches the task. | File | Open it when | |---|---| +| `references/principles.md` | a rule in the always-on file does not settle the case: the full standing principles (adopting onto existing code, the schema and live database, prompts, requirements, owning and writing generators, physical names) with their reasons | | `references/any-stack.md` | **the database, data store, HTTP framework or UI framework is not one a reference generator targets** — MySQL, MongoDB, DynamoDB, Express, NestJS, Next.js, Vue, … | | `references/owning-generators.md` | generated output is wrong; your framework is not the one a reference emits for; you write or review a generator (the `own*()` accessor table) | | `references/choosing-layers.md` | the generated API does not fit, you need joined or derived data, or you are adopting onto existing code | @@ -47,47 +57,60 @@ exact config, generator names and commands for this project; read it. The other | `references/typescript-prisma.md` | a TypeScript project that keeps Prisma as its ORM | | `references/typescript-retargeting.md` | a TypeScript project on a framework other than Fastify, Hono or React | | `references/typescript-templates.md` | declarative Mustache template-codegen in a TypeScript project | -| `references/typescript-docs.md` | the docs generators (`docsFile`, `apiDocsFile`, `agentDocsFile`, `requirementsFile`, `metamodelDocsFile`, `docsSiteFile`) in a TypeScript project | +| `references/typescript-docs.md` | the docs generators (`apiDocsFile`, `agentDocsFile`, `requirementsFile`, `metamodelDocsFile`, `docsSiteFile`) in a TypeScript project | + +## When generated output does not fit + +1. **The metadata**, if the model is wrong: a wrong column type, a missing relationship, a + join that should be a projection. Fixing the model fixes every port at once. +2. **Your own generator**, if the model is right and the emit is wrong: naming, file layout, + imports, framework, signatures. +3. **Hand-write** only what metadata cannot express (business logic, calls to other systems), + in a non-generated file that imports the generated types. + +Hand-writing something the metadata already describes is step 3 used as step 1. Whatever +follows a pattern from the metadata is regenerated, never hand-coded: FK columns, CRUD, +validator chains, type-safe finders, `relations()` blocks. Most views are in that group too: +model one as an `object.projection` and the view DDL is generated +(`references/choosing-layers.md`). A view body origins cannot express (a recursive CTE, a +window function, a set operation) goes in the `source.rdb` `@sql` escape, so the tool still +registers and drift-checks it. + +**Your generators are yours.** The model is scaffold-and-own: a reference generator you eject +is copied into your repo, its header says it is now yours to change, and it carries no +`@generated` header. The mistake to avoid has been seen in practice: an agent told not to +touch upstream drops "edit the generator" from its options and hand-writes the layer. If the +generated shape is wrong, the generator is the file to open. + +**A defect in generated code is a defect in your generator.** When output does not compile, +has the wrong shape or collides with your code, fix the generator that emitted it (or the +runtime file `eject` copied beside it) in the same change. Do not file an issue upstream, pin +an older release or patch a clone of MetaObjects for it. What is upstream is only what you +cannot own: the loader and metamodel, the core runtime, the codegen engine and +`meta migrate`. Per-port steps: `references/owning-generators.md`. -## Upgrading a project from 1.0 to 1.1 +**Do not hand-edit generated output for a change you want to keep.** Every file a reference +generator emits carries a generated header (`@generated by …` on TypeScript and Python, +`` on C#, `GENERATED` on Java and Kotlin; a generator you write adds one +only if it chooses to). An edit inside one is a second copy of a rule the model owns, and a +diff on a generated file that `gen` did not produce is a smell in review. This is a rule +about emitted output, not about your generators, which are edited like any other source. -Read the one upgrade guide, https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-1.0-to-1.1.md, before the first `gen`, for every -port the project uses; the build can stay green while the result is wrong. It lists the steps -in order and every change that needs action. +**Wire a generator only for output you will consume.** An emitted file nobody imports reads +as an invitation to adopt a surface you decided against. -- The default column and table names are now `snake_case` in every port (C#, Java, Kotlin's - runtime and Python defaulted to the field names). A database whose columns are named like - its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or - regenerated code queries columns that do not exist. The per-port naming flags and generator - args are removed. -- Documentation is a generator in the project's list, and the docs commands are removed. C# - and Python also need a generator list (`dotnet meta init`; `metaobjects.config.yaml`). -- Upgrade to 1.1.2 or later. With no `wire` setting, each port writes its language's standard - JSON (C#, Java and Kotlin keep their 1.0.x decimals and null members). A project whose clients - expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", - "nullMembers": "omit" }`; see `references/wire-format.md`. A fractional validator `@min` or - `@max` is refused (write an integer bound). -- **Resync the generators you own.** An ejected copy keeps the logic it was copied with, and a - plain `gen` does not refresh it. `meta eject --list` (TypeScript; `metaobjects gen --list` in Python, which has no - `eject --list`; `dotnet meta gen --list`; `mvn metaobjects:eject -Dlist=true` in Java and Kotlin) - reports each copy that differs from the reference; - `eject --force` takes the new reference for a copy you never edited, and a copy you - edited is three-way merged instead. Steps for 1.0.x: https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-within-1.0.md. - -## Need an output? Write the generator — this is the primary path - -**When.** You need an output the model fully describes and no reference generator emits — -or none emits it the way this application needs it. OpenAPI, JSON Schema, Zod schemas, -DTOs or a client for a framework nothing here ships, a service layer in the house style, -a data dictionary, a search-index mapping, test fixtures. That is a generator, and you -write it now, in this change — once it passes the cost test in `references/owning-generators.md` -(smaller than the code it replaces, generator counted; more instances expected; or drift -protection is the point). Do not hand-write the output (it drifts the day the model -changes and nothing notices), do not wait for MetaObjects to ship it, and do not ask -permission: a generator in this repo is ordinary source you own. - -**How — the shape is about 20 lines in every port.** A generator is a `name` plus a -function from the loaded model to a list of `{ path, content }` files: +## Need an output? Write the generator + +**When.** You need an output the model fully describes and no reference generator emits, or +none emits it the way this application needs: Zod schemas, DTOs or a client for a framework +nothing here ships, a service layer in the house style, a data dictionary, a search-index +mapping, test fixtures. Write it once it passes the cost test in +`references/owning-generators.md` (smaller than the code it replaces, generator counted; more +instances expected; or drift protection is the point). Hand-written output drifts the day the +model changes and nothing notices, and waiting for MetaObjects to ship it is not needed. + +**How.** A generator is a `name` plus a function from the loaded model to a list of +`{ path, content }` files: ```ts import { isAbstract, perEntity, type Generator } from "@metaobjectsdev/codegen-ts"; @@ -107,11 +130,10 @@ export function fieldListGenerator(): Generator { ``` **Start from the scaffold (TypeScript):** `meta generator new [--scope -entity|package|model]` writes a working, commented generator into `codegen/generators/` -and wires it into `metaobjects.config.ts`. `meta gen` runs it straight away. Then change -what it emits. +entity|package|model]` writes a working, commented generator into `codegen/generators/` and +wires it into `metaobjects.config.ts`. `meta gen` runs it straight away. -**Register it** — the one step per port: +**Register it**, the one step per port: | Port | Registration | Model helpers | |---|---|---| @@ -120,335 +142,252 @@ what it emits. | C# | `new Codegen.Generators.YourGenerator()` in `codegen/Generators.cs` (`dotnet meta init` writes it); `dotnet meta gen` / `verify --codegen` run that list | node accessors, `ValueObjectNames.ResolveFieldRef`, `CSharpNaming.RoutePath` | | Java / Kotlin | `` plus ``, from a module on the plugin's classpath; extend `FileEmittingGenerator` | `com.metaobjects.generator.ModelWalk` | -**Verify it** — nothing to register. `verify --codegen` (`mvn metaobjects:verify` on the -JVM) re-runs the same generator list and fails when committed output is stale. Typecheck -a TypeScript generator with `npx tsc -p tsconfig.codegen.json`: `meta gen` loads it -without typechecking, so a wrong accessor runs silently. - -**Read the model correctly — the rules that make a generator right:** - -- **Which objects.** The runner hands you every object — entities, value objects, - projections and abstract bases. Filter: abstract bases only contribute fields to what - `extends` them. To scope a generator that ships with the tool to some objects, use the - port's own idiom (a TypeScript `filter`, a C# `Include`, a Python `filter=` argument; the - table in `references/owning-generators.md`), never emit everything and delete files by name. -- **Resolving accessors, always (ADR-0039).** `fields()`, `attr()`, `isRequired`, - `resolvedIsArray()` see what a field or object inherits through `extends`; the `own*()` - forms and the raw `isArray` flag do not, and the output is silently wrong on any model - that uses inheritance. In Python `attr()` is the OWN read — use `model_walk` or - `attrs().get()`. On the JVM `getName()` is the fully-qualified name — use - `ModelWalk.name`. Full table: `references/owning-generators.md`. -- **Names from the model, resolved by the engine's rules.** An `@objectRef` resolves - package-locally through the port's helper (`objectRefTarget` and its equivalents), - never by matching a short name. A REST address is `servedPath` / `route_path` / - `RoutePath` / `ModelWalk.collectionSegment`, the same rule the reference routes use. -- **Any format.** `content` is written as given — no port formats it or adds a header. - Make it deterministic: the same model must give the same bytes, or verify reports drift. - -Every port's minimal generator (each run through gen, verify and a convicted model -change) and two worked examples to copy — JSON Schema and OpenAPI 3.1, examples and not a -product surface — are in the guide "Write your own generator": -. - -**Use a stock generator as shipped** when one already emits what you need: -`meta gen --list --probe` is the catalog, and each row says how to wire it with nothing -copied into the repo (an import line on TypeScript, a stable name on the other ports). An -upgrade is then how its fixes reach you. **Eject** when a reference generator is close and -you need to change what it emits: `meta eject ` copies it in. Do not eject a -generator you are not going to change, because an unmodified copy only duplicates the -reference and falls behind it. -**Hand-write** only what the model cannot express — business logic, calls to other -systems — and have it import the generated types. - -## What codegen does - -You run a `gen` step. The runner: - -1. Loads the project's metadata from wherever its configuration points (the same loader - the runtime uses): `sources` in `.metaobjects/config.json` (TypeScript, and C# when gen - names no ``), `metadata` in `metaobjects.config.yaml` (Python), the - plugin's `` (Java, Kotlin). `metaobjects/` is only the default. -2. Resolves output targets and precomputes shared render state. -3. Runs each configured **generator** — most emit one file per entity; some emit a - single shared file (a barrel, a DB-context, an app-config). -4. Decides whether it may overwrite a file, by a committed **hash manifest** - (`.metaobjects/.gen-state/.hashes.json`) on every port. If a file still hashes to what - the generator recorded writing, it is safe to overwrite; if it was edited, or there is - no record of it, the write is **refused by name**. TypeScript additionally - three-way-merges against a snapshot when one is present locally. **Commit the - manifest.** Java and Kotlin have used it since 8.1.0: there, a file with no record that - carries the bare **`GENERATED`** header token (not `@generated`) is adopted as generated - output, which is how the first run after upgrading from 8.0.x records everything. - - **A refusal FAILS the run — exit 1 on TypeScript, C# and Python** (Python and C# warned - and exited 0 until 1.0, so a `gen` wired into CI was green while codegen refused to - write). On Java and Kotlin a refusal is a warning and `mvn metaobjects:verify` is the - gate that fails. The one-time fix for a project that predates the committed manifest - is **`gen --baseline=adopt`**: it records the files you have as the baseline and writes - nothing, so there is finally a `.hashes.json` to commit — then `gen` again, and the - regeneration lands as its own diff. Adopting DECLARES those files to be generated - output, so an edit already inside one is part of the baseline and that regeneration - replaces it; commit before you run it. (TypeScript additionally has - `--baseline=fresh`: write fresh output now and discard the edits.) - - **Output nobody should edit: set `handEdits: overwrite` on its generator entry.** The - default, `keep`, refuses an edited file. `overwrite` replaces it with fresh output, names - it, and re-baselines it; `verify --codegen` then reports the edit as drift that `gen` - fixes. A file the manifest has no record of is refused either way. TypeScript - `{ ...entityFile(), handEdits: "overwrite" }`; Python `{ name: entity, handEdits: overwrite }` - in `metaobjects.config.yaml`; C# `new EntityGenerator().WithHandEdits(HandEdits.Overwrite)`; - Java and Kotlin `overwrite` on the ``. - - **A full `gen` deletes generated files it no longer emits** (a renamed or deleted object, - a page that moved package). Only files the manifest records, only when untouched, and - never on a run narrowed by `--generators` or an entity filter. An edited one is refused by - name, and `verify --codegen` says to delete it: regeneration cannot follow a rename, so - move the edits into the new file first if you want them. Details: - `docs/features/own-your-codegen.md`, "Files that are no longer generated". - - On every port *editing the content* is what takes ownership — that is what breaks the - hash — and deleting the header is just another edit. (Through Maven 8.0.x, Java and - Kotlin did the reverse: an edit was overwritten and only removing the `GENERATED` token - protected a file. Do not carry that habit forward.) - - (The header text differs per port and is not the write decision: TypeScript and Python - emit `@generated by …`, C# emits ``, Java and Kotlin emit `GENERATED`.) - -The output is normal idiomatic code in your language — you import it and use it -like any hand-written module. - -## The `@generated` header + hand-edit-preserving regen - -Every file a reference generator emits carries a `@generated` header (a generator you -write adds one only if it chooses to — the runner adds none, and JSON cannot hold one). -Treat any generated file this way: - -- **Never hand-edit a file with a `@generated` header for a change you want to - keep.** The next `gen` run overwrites it. If you need different output, change the - metadata, or change the generator that emits it. -- **This rule is about emitted output — it is not a rule about your generators.** A - generator you own carries no `@generated` header and is edited like any other source - file in your repo. See the next section before you conclude a shape is unreachable. -- **Hand-written regions are preserved by three-way merge.** Where the codegen - supports designated hand-editable regions, regeneration runs a three-way merge - (base → yours → newly-generated) so your edits survive a regen. Code review is - the backstop: a diff on a `@generated` file that wasn't produced by `gen` is a - smell. - -Practical rule: **pattern-derivable-from-metadata = regenerate; business logic = -hand-write in a non-generated file.** FK columns, CRUD, validator chains, -type-safe finders, `relations()` blocks — all derived, never hand-coded. What you -hand-write is what metadata genuinely can't express: regex from outside metadata and -domain logic. Most views are NOT irreducible — model them as an `object.projection` -and the view DDL is generated (see `references/choosing-layers.md`); a hand-written view -for a shape origins can express is drift the drift gate can't even see. A genuinely -*irreducible* view body (recursive CTE, window function, set op) isn't hand-written -loose either — it goes in the `source.rdb` **`@sql`** escape (#208, ADR-0043) so the -tool still registers, fingerprints, and drift-checks it. - -## Your generators are yours — editing one needs no permission - -A generator in your repo is your code, not a vendor artifact. ADR-0034 is -**scaffold-and-own**: the generators the scaffolded config wires are copied into your -repo at init, and every reference template's header says so in its own first line -("copy this into your repo … and own it", "now YOURS to change"). None carries a -`@generated` header. Editing one is ordinary work. - -**A standing rule not to change the MetaObjects repo is not a rule about your -generators.** They are different repositories, and you own yours outright. That -generalisation is the observed failure mode, not a hypothetical: an agent told not to -touch upstream quietly drops "edit the generator" from the moves available to it and -hand-writes the layer instead — the single outcome the rest of this skill exists to -prevent. If you are about to hand-write something data-shaped because the generated -shape is wrong, the generator is the file to open, and you do not need to ask first. - -**The order when generated output does not fit:** - -1. **The metadata**, if the model is wrong — wrong column type, missing relationship, - a join that should be a projection. Fix the spine first; it fixes every port at once. -2. **Your own generator**, if the model is right and the *emit* is wrong — naming, file - layout, imports, framework, signatures. -3. **Hand-write**, only for what metadata genuinely cannot express — and wire it to the - generated types. - -Hand-writing something the metadata already describes is step 3 used as step 1. - -**A defect in generated code is a defect in your generator.** When generated output does not -compile, has the wrong shape, or collides with your code, fix the generator that emitted it (or -the runtime file `eject` copied beside it) in the same change. Do not file an issue upstream, -pin an older release, or patch a clone of MetaObjects for it. What is legitimately upstream is -only what you cannot own: the loader and metamodel, the core runtime, the codegen engine, and -`meta migrate`. Per-port steps: `references/owning-generators.md`. - -**Wire a generator only for output you will consume.** An emitted file nobody imports still -reads as an invitation to adopt the surface you decided against. - -## Selecting generators — NOTHING is generated until you choose it - -**`meta init` wires no generators, and no port ships a default suite.** A fresh TypeScript -scaffold has `generators: []` and an empty `codegen/generators/`; a fresh C# scaffold -(`dotnet meta init`) has an empty `codegen/Generators.cs`; Java and Python have never had a -default set. In every port the project's own generator list — `generators` in -`metaobjects.config.ts`, `codegen/Generators.cs`, a target's `generators` in -`metaobjects.config.yaml`, or `` in the pom — is the COMPLETE list, -documentation included (ADR-0034 Amendment 9); `--generators` (Maven: a second -``) only narrows a run to entries already in it. Choosing what an application -needs is a judgment over its purpose and stack, and the tool's job is to make that choice -cheap and truthful, not to make it for you. - -Each generator has a **stable name** (kebab-case) that is the same in every port and -surfaces in diagnostics — reference generators by that name, never by inlining what -they emit. - -### The procedure - -1. **Read the app's purpose and stack.** What is it for; what does it already use. -2. **`meta gen --list --format json --probe`** — the catalog. Every generator with its - `layer`, `framework`, what it emits, what it requires, what it costs to install, - and — with `--probe`, which constructs each generator and dry-runs it against YOUR - model — how many files each would actually emit. -3. **Check the libraries before you choose generators.** The same catalog carries - `kind: "library"` rows — declared design MetaObjects ships, each with a `useWhen`. - If one matches a capability you are about to model, **opt in and adapt rather than - author**: you inherit its entities, its requirements, and the rulings recorded with - them. Layers are how much of it you take. The bare name is the CORE layer — the - model and its ledger, sourceless, so it adds **no tables and no generated code**; - `/db` is the separate opt-in that proposes the schema. Opt in with - `"libraries": ["iam", "iam/db"]` in `.metaobjects/config.json`. -4. **Choose by `layer`.** Satisfy every `requires`. Take what `wouldEmit > 0` says your +**Verify it.** Nothing to register: `verify --codegen` (`mvn metaobjects:verify` on the JVM) +re-runs the same generator list and fails when committed output is stale. Typecheck a +TypeScript generator with `npx tsc -p tsconfig.codegen.json`, because `meta gen` loads it +without typechecking and a wrong accessor runs silently. + +**Read the model correctly.** These are what make a generator right: + +- **Which objects.** The runner hands you every object: entities, value objects, projections + and abstract bases. Filter, because an abstract base only contributes fields to what + `extends` it. To scope a shipped generator to some objects use the port's own idiom (a + TypeScript `filter`, a C# `Include`, a Python `filter=` argument; the table is in + `references/owning-generators.md`), not emit-everything-then-delete. +- **Resolving accessors.** `fields()`, `attr()`, `isRequired` and `resolvedIsArray()` see what + a field or object inherits through `extends`; the `own*()` forms and the raw `isArray` flag + do not, so the output is silently wrong on any model that uses inheritance. In Python + `attr()` is the own read: use `model_walk` or `attrs().get()`. On the JVM `getName()` is the + fully-qualified name: use `ModelWalk.name`. Full table: `references/owning-generators.md`. +- **Names by the engine's rules.** An `@objectRef` resolves package-locally through the + port's helper (`objectRefTarget` and its equivalents), never by matching a short name. A + REST address is `servedPath` / `route_path` / `RoutePath` / + `ModelWalk.collectionSegment`, the same rule the reference routes use. +- **Any format, deterministic.** `content` is written as given; no port formats it or adds a + header. The same model must give the same bytes, or verify reports drift. + +Every port's minimal generator and two worked examples to copy (JSON Schema and OpenAPI 3.1) +are in "Write your own generator": +. +For those two documents themselves, the stock `contract-schema` and `openapi` generators emit +them from 1.2.1, run through the Node `meta` CLI on any port: +. + +## Selecting generators + +`meta init` wires no generators. A fresh TypeScript scaffold has `generators: []` and an empty +`codegen/generators/`; a fresh C# scaffold (`dotnet meta init`) has an empty +`codegen/Generators.cs`; Java and Python have never had a default set. In every port the +project's own list (`generators` in `metaobjects.config.ts`, `codegen/Generators.cs`, a +target's `generators` in `metaobjects.config.yaml`, or `` in the pom) is the +complete list, documentation included. `--generators` (Maven: a second ``) only +narrows a run to entries already in it. So a `gen` that writes nothing on a fresh project is +not broken. Each generator has a stable kebab-case name, the same in every port. + +Choosing what an application needs is a judgment over its purpose and stack. The catalog +makes that choice cheap: + +1. **`meta gen --list --format json --probe`.** Every generator with its `layer`, + `framework`, what it emits, what it requires and what it costs to install. `--probe` + constructs each generator and dry-runs it against your model, so `wouldEmit` is how many + files it would write here. +2. **Check the libraries first.** The catalog also carries `kind: "library"` rows: declared + design MetaObjects ships, each with a `useWhen`. If one matches a capability you are about + to model, opt in and adapt it: you inherit its entities, its requirements and the rulings + recorded with them. The bare name is the core layer, which is sourceless and so adds no + tables and no generated code; `/db` is the separate opt-in that proposes the schema. + Opt in with `"libraries": ["iam", "iam/db"]` in `.metaobjects/config.json`. A library row + carries `provides` and, under `--probe`, a `project` block: the layers selected, the tables + and requirements they added, which of your entities `extends` into it, and any generator it + implies that is not wired. +3. **Choose by `layer`.** Satisfy every `requires`, and take what `wouldEmit > 0` says your model is already asking for. - - Pick **ONE** framework on the `api` layer: `routes` and `routes-hono` are - alternatives, and wiring both silently produces two complete HTTP surfaces. - - Do **NOT** apply that rule to `client`. `@metaobjectsdev/tanstack` peers on - `react`, so a form generator plus the TanStack hook/grid generators is the - intended composition, not a conflict. -5. **Wire what you chose.** A generator you will run unchanged is wired from its package: - on TypeScript each catalog row carries `wire.import`, plus `install` and `configKeys`, - and you write the call from the generator's documented options; on the other ports you - select it by its stable name. Copy nothing. - For a generator whose output you need to change, - **`meta eject --format json`** copies each into `codegen/generators/` - (yours to edit), and reports the import line, the entry to add to `generators`, one - consolidated install command, and any config keys those generators read. On - TypeScript, a generator whose output calls an HTTP adapter (`routes`, `routes-hono`, - `entity`) also gets that adapter's source copied into `codegen/runtime/`, and each JSON - row lists those files under `runtime`. -6. **`meta gen`** — read its warnings, then typecheck. - -A library row also carries `provides` (what is in the box) and, under `--probe`, a -`project` block: which layers you selected, how many tables and requirements they -added here, which of your entities `extends` into it, and any generator the library -implies that you have not wired. - -### The six layers, and what picks them + - Pick **one** framework on the `api` layer: `routes` and `routes-hono` are alternatives, + and wiring both silently produces two complete HTTP surfaces. + - That rule does not apply to `client`. `@metaobjectsdev/tanstack` peers on `react`, so a + form generator plus the TanStack hook and grid generators is the intended composition. +4. **Wire what you chose.** A generator you run unchanged is wired from its package: on + TypeScript each catalog row carries `wire.import`, `install` and `configKeys`; on the + other ports you select it by its stable name. Nothing is copied. For a generator whose + output you need to change, `meta eject --format json` copies each into + `codegen/generators/` and reports the import line, the entry to add to `generators`, one + install command and the config keys it reads. On TypeScript a generator whose output + calls an HTTP adapter (`routes`, `routes-hono`, `entity`) also gets that adapter's source + in `codegen/runtime/`, listed under `runtime` in the JSON. +5. **`meta gen`**, read its warnings, then typecheck. | layer | what it is | chosen by | |---|---|---| | `model` | entity/DTO/value-object modules and the constants beside them | app shape | | `persistence` | how rows are read and written | app shape | +| `service` | one module per package that runs each operation in a transaction with the write rules (ADR-0067); its transport is on `api` | app shape | | `api` | the HTTP surface — pick one framework | app shape | | `client` | the browser tier | app shape | | `docs` | model pages, api reference, agent pages, requirement ledger — each its own generator entry, like any other | app shape | | `capability` | prompts, parsers, payloads, traces, test stubs | **`--probe`** | -At intent level: a **headless data service** is `model` + `persistence`; an **HTTP API** -adds `api` with one framework; an **admin UI** adds `client`. Members come from the live -catalog, never from a list in prose — a list here would go stale the day a generator is -added, and `--probe` cannot, because it runs the generators rather than describing them. +A headless data service is `model` + `persistence`; an HTTP API adds `api` with one +framework; an admin UI adds `client`. Take the members from the live catalog, not from a +list in prose, which goes stale when a generator is added. You do not choose inside +`capability` by reading labels: you declared a `template.prompt`, a `requirement.functional` +or a stored-proc source, and `--probe` reports the file count that follows. -`capability` looking like one large bucket is the point: you are not meant to choose -inside it by reading labels. You declared a `template.prompt`, or a -`requirement.functional`, or a stored-proc source — `--probe` reports the file count -that follows, for your model. +An abstract entity never emits instance or write artifacts, whatever is wired. A +dependency's metadata is load-only by default: codegen excludes nodes from a package a +dependency owns unless `scope.include` names that package +(`references/dependencies-and-shared-models.md`, which also covers publishing with +`sharedModelFile()`). -An abstract entity never emits instance/write artifacts regardless of what is wired. +## You don't have to generate everything -**A dependency's metadata is load-only by default:** codegen excludes nodes from a package a -dependency owns unless `scope.include` names that package literally. See -`references/dependencies-and-shared-models.md`, which also covers publishing with -`sharedModelFile()`. - -## You don't have to generate everything — pick your layers - -Codegen is à la carte. When the app's API does not match generated CRUD, **generate the data -layer and hand-write only the routes**, calling the generated queries — never abandon codegen -for the data access too. An entity's own columns plus a joined extra is an **entity read-view**, +Codegen is à la carte. When the app's API does not match generated CRUD, generate the data +layer and hand-write only the routes, calling the generated queries; do not abandon codegen +for the data access too. An entity's own columns plus a joined extra is an entity read-view, not a projection; derived or aggregate data is a projection whose generated query you call. Details and the adoption rules: `references/choosing-layers.md`. +## What a `gen` run does, and when it refuses to write + +The runner loads the metadata from wherever the project's configuration points (`sources` in +`.metaobjects/config.json` for TypeScript, and for C# when gen names no ``; +`metadata` in `metaobjects.config.yaml` for Python; the plugin's `` for +Java and Kotlin; `metaobjects/` is only the default), resolves output targets, and runs each +configured generator. Most emit one file per entity; some emit one shared file (a barrel, a +DB context). + +**Whether it may overwrite a file is decided by the committed hash manifest** +(`.metaobjects/.gen-state/.hashes/`), on every port. A file that still hashes to what the +generator recorded writing is safe to overwrite. A file that was edited, or that the +manifest has no record of, is refused by name. TypeScript also three-way merges against a +snapshot when one is present locally. Editing the content is what takes ownership of a file, +because that is what changes the hash; the header is not the write decision, and deleting it +is just another edit. (Java and Kotlin before 8.1.0 worked the other way round: an edit was +overwritten and only removing the `GENERATED` token protected a file. That no longer holds. +On those ports a file with no record that carries the bare `GENERATED` token is adopted as +generated output, which is how the first run after upgrading records everything.) + +- **A refusal fails the run**: exit 1 on TypeScript, C# and Python. On Java and Kotlin a + refusal is a warning and `mvn metaobjects:verify` is the gate that fails. +- **A project that predates the committed manifest** runs `gen --baseline=adopt` once: it + records the files you have as the baseline and writes nothing, so there is a `.hashes/` to + commit. Then `gen` again, and the regeneration lands as its own diff. Adopting declares + those files generated output, so an edit already inside one is replaced by that + regeneration: commit before you run it. (TypeScript also has `--baseline=fresh`: write + fresh output now and discard the edits.) +- **Output nobody should edit: `handEdits: overwrite` on its generator entry.** The default, + `keep`, refuses an edited file. `overwrite` replaces it with fresh output, names it and + re-baselines it, and `verify --codegen` reports the edit as drift that `gen` fixes. A file + the manifest has no record of is refused either way. TypeScript + `{ ...entityFile(), handEdits: "overwrite" }`; Python `{ name: entity, handEdits: overwrite }` + in `metaobjects.config.yaml`; C# `new EntityGenerator().WithHandEdits(HandEdits.Overwrite)`; + Java and Kotlin `overwrite` on the ``. +- **A full `gen` deletes generated files it no longer emits** (a renamed or deleted object): + only files the manifest records, only when untouched, and never on a run narrowed by + `--generators` or an entity filter. An edited one is refused by name and + `verify --codegen` says to delete it. Regeneration cannot follow a rename, so move the + edits into the new file first if you want them. +- **`gen` skips a run when nothing changed.** Every port computes a key from the loaded model + and everything the generators are built from; when it matches the last successful run and + every generated file still holds the bytes that run left, `gen` says so and writes + nothing. `--force` (Maven: `-Dmetaobjects.force=true`) renders anyway, and + `verify --codegen --full` renders and compares in a local run. A generator that reads + something the key does not cover declares it as an input or sets `cache: false`. + +The binary differs per server language (the Node `meta`, a language-native console tool, or +a build-plugin goal). A dry-run mode previews without writing, a watch mode re-runs on +metadata changes where supported, and entity names scope a run to those entities. + ## Two ways to author a generator A generator is **programmatic** (code that builds the output) or **declarative** (a Mustache -template plus a `scope` and an `outputPattern`). Both ship in every port. Use programmatic code -when the logic is involved; use a template when the shape is what you are iterating on, or you -want one output across languages. The per-port wiring is in -`references/template-or-code.md`. Whether a base/extension split or a write-if-absent -file exists is answered in `docs/features/codegen-concepts.md` §5-§7: MetaObjects ships one -hand-edit strategy, and no shipped generator emits either. +template plus a `scope` and an `outputPattern`). Both ship in every port. Use code when the +logic is involved; use a template when the shape is what you are iterating on, or you want +one output across languages. The per-port wiring is in `references/template-or-code.md`. +Whether a base/extension split or a write-if-absent file exists is answered in +`docs/features/codegen-concepts.md` §5-§7: MetaObjects ships one hand-edit strategy, and no +shipped generator emits either. ## Never hand-write a physical name -A table, column, schema or index name is declared in metadata. Every port can emit a per-object -names artifact (`.names.ts`, `Names.java`, …) — **but only when you wire the -`names` generator**, since no port generates it by default. Reference its constants from raw SQL, -migration scripts and external mappings; prefer the ORM's typed column handle where one exists. -Details: `references/physical-names.md`. +A table, column, schema or index name is declared in metadata. Every port can emit a +per-object names artifact (`.names.ts`, `Names.java`, …), but only when you +wire the `names` generator, since no port generates it by default. Reference its constants +from raw SQL, migration scripts and external mappings; prefer the ORM's typed column handle +where one exists. Details: `references/physical-names.md`. ## The JSON your API writes is a project setting Each port writes what its language's standard serializer writes: a C# decimal is a JSON -number, a Python one `str(Decimal)`. Identical output across ports is opt-in, through `wire` in -`.metaobjects/config.json` (`"decimals": "string"`, `"nullMembers": "omit"` or `"emit"`). Never -change one port to match another or to match a conformance corpus, and never hand-edit a -generated converter or annotation: change the setting and regenerate. Input rules hold in every -mode. Details and the per-port table: `references/wire-format.md`. +number, a Python one `str(Decimal)`. Identical output across ports is opt-in, through `wire` +in `.metaobjects/config.json` (`"decimals": "string"`, `"nullMembers": "omit"` or `"emit"`). +Do not change one port to match another or to match a conformance corpus, and do not +hand-edit a generated converter or annotation: change the setting and regenerate. Input +rules hold in every mode. Details and the per-port table: `references/wire-format.md`. ## Dialects -Generated DB schema/DDL targets a SQL **dialect**: - -- `postgres` — the default, fullest-featured. -- `sqlite` — supported; rejects non-default DB schemas. -- `d1` (Cloudflare D1) — **TypeScript-only**. It is SQLite at the SQL level; the - non-TS server ports have no analogue, so it never appears in their config. -- `mysql` — **TypeScript codegen and runtime only.** `meta migrate` does not own a MySQL - schema and refuses `--dialect mysql`; you keep the DDL yourself. - -Set the dialect once in the project's codegen config. Field subtypes map to the -dialect's column types deterministically (`field.string` + `@maxLength` → -`varchar(N)`, `field.currency` → integer, `field.uuid` → native `uuid` on -Postgres, `field.enum` → `varchar` + `CHECK`, etc.). - -Codegen only ever maps the **shapes you authored** — so author them right. If you -find the generator emitting the wrong column type, the fix is the field shape, not a -template hack. See the decision procedure in the **`metaobjects-authoring`** skill -(`references/choosing-a-shape.md`) for the ordered derive→`@dbColumnType`→subtype/ -`@kind`/attribute routing (ADR-0037) — e.g. arrays are `isArray: true` (never an -array column type) and a native UUID is `field.uuid` (not a string + `@dbColumnType`). -When you register custom vocabulary for a custom generator, the same ADR-0037 -procedure decides whether it's a subtype, a `@kind` variant, or an attribute. +Generated schema targets a SQL dialect, set once in the project's codegen config: + +- `postgres`: the default, fullest-featured. +- `sqlite`: supported; rejects non-default DB schemas. +- `d1` (Cloudflare D1): TypeScript only. It is SQLite at the SQL level. +- `mysql`: TypeScript codegen and runtime only. `meta migrate` does not own a MySQL schema + and refuses `--dialect mysql`; you keep the DDL yourself. + +Field subtypes map to the dialect's column types deterministically (`field.string` + +`@maxLength` → `varchar(N)`, `field.currency` → integer, `field.uuid` → native `uuid` on +Postgres, `field.enum` → `varchar` + `CHECK`). Codegen maps the shapes you authored, so when +a generator emits the wrong column type the fix is the field shape, not a template hack: the +`metaobjects-authoring` skill's `references/choosing-a-shape.md` has the decision procedure +(an array is `isArray: true`, never an array column type; a native UUID is `field.uuid`, not +a string plus `@dbColumnType`). The same procedure decides whether custom vocabulary for a +custom generator is a subtype, a `@kind` variant or an attribute; what it may say at all (what +a thing is, never the product, version or step the generator writes) is that skill's +`references/semantic-modelling.md`. That vocabulary is a +provider class listed once in the port's project configuration, so `gen`, `verify --codegen` +and the docs generators all load it (`metaobjects-authoring`, "Your own vocabulary"); a +generator reads the custom attribute through the resolving accessor like any other. ## Per-target output -Generated code can be routed to **multiple output directories/packages** so each -artifact lands with its runtime concern: the entity model in a database package, -routes in the API app, client hooks/forms/grids in the web app. Each generator can -declare which named target it writes to; same-target references stay relative, -cross-target references go through the target's configured import base. With no -targets configured, everything lands in a single output directory — output is -byte-identical to the single-directory case. Use multiple targets only when the -project's package boundaries justify it. +Generated code can be routed to several output directories or packages so each artifact +lands with its runtime concern: the entity model in a database package, routes in the API +app, client hooks, forms and grids in the web app. Each generator declares which named +target it writes to; same-target references stay relative and cross-target references go +through the target's configured import base. With no targets configured everything lands in +one output directory. Use several targets only when the project's package boundaries +justify it. + +**C#: one resolver names every property.** To spell a field's C# property differently (an +acronym, say), set `GenConfig.PropertyNaming` (`Func`). The entity +classes, the `AppDbContext`, the reverse finders, the routes, the filter map and the +credential stripping all read it, so they agree. A subclass hook +(`EntityGenerator.PropertyName`, `DbContextGenerator.PropertyName`) that disagrees with the +resolver is refused. -## Running gen +## Upgrading a project from 1.0 to 1.1 -The shape is always the same — a `gen` verb that loads metadata, renders, merges, -and writes — but the binary differs per server language (the Node `meta`, a -language-native console tool, or a build-plugin goal). A dry-run mode previews -without writing; a watch mode re-runs on metadata changes where supported. Pass -specific entity names to scope a run to those entities. +Read the upgrade guide, +https://github.com/metaobjectsdev/metaobjects/blob/v1.3.0/docs/features/migrations/upgrading-1.0-to-1.1.md, +before the first `gen`, for every port the project uses: the build can stay green while the +result is wrong. It lists the steps in order and every change that needs action. ---- - -For this project's codegen specifics, read the `references/.md` file for each server -language in this project's stack (only those are installed). Open the topic files in -`references/` only when the table at the top points you to one. +- Default column and table names are `snake_case` in every port (C#, Java, Kotlin's runtime + and Python used to default to the field names). A database whose columns are named like + its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or + regenerated code queries columns that do not exist. The per-port naming flags and + generator args are removed. +- Documentation is a generator in the project's list, and the docs commands are removed. C# + and Python also need a generator list (`dotnet meta init`; `metaobjects.config.yaml`). +- Upgrade to 1.1.2 or later. With no `wire` setting, each port writes its language's + standard JSON (C#, Java and Kotlin keep their 1.0.x decimals and null members). A project + whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": + "string", "nullMembers": "omit" }`; see `references/wire-format.md`. A fractional + validator `@min` or `@max` is refused (write an integer bound). +- **Resync the generators you own.** An ejected copy keeps the logic it was copied with, and + a plain `gen` does not refresh it. `meta eject --list` (TypeScript; + `metaobjects gen --list` in Python, which has no `eject --list`; `dotnet meta gen --list`; + `mvn metaobjects:eject -Dlist=true` in Java and Kotlin) reports each copy that differs + from the reference. `eject --force` takes the new reference for a copy you never + edited; a copy you edited is three-way merged. Steps for 1.0.x: + https://github.com/metaobjectsdev/metaobjects/blob/v1.3.0/docs/features/migrations/upgrading-within-1.0.md. diff --git a/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md b/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md index 3d0cdc8..8905088 100644 --- a/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md +++ b/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md @@ -41,10 +41,19 @@ replace those calls: an unmodified copy publishes the same bytes as the packaged generator. To publish through a package, point its `target` inside the package (an npm package's directory listed in `files`; a Python package's directory shipped as package data), run `meta gen`, then release the package as usual; consumers -declare an `npm` or `python` dependency on it. With no `version` option the +declare an `npm`, `python`, `maven` or `nuget` dependency on it. With no `version` option the manifest takes the nearest `package.json` version, else a `pyproject.toml` `[project]` version — pass `version` when neither is the package consumers install. -Only TypeScript can run it in Phase 1a. TypeScript, Python, Java, Kotlin (through -Java's loader and Maven plugin) and C# can *consume* a dependency, and only the -TypeScript toolchain can *publish* one. +TypeScript, Java, Kotlin and C# can *publish* with byte-identical output: the Java and Kotlin +`shared-model` generator runs through `mvn metaobjects:generate` (`SharedModelGenerator` / +`KotlinSharedModelGenerator`, args `name`, `include`, `exclude`, `files`, `version`; the version +defaults to the module ``); the C# one is `new SharedModelGenerator { ModelName, Include, +Files, OutDir }` in `codegen/Generators.cs` through `dotnet meta gen` (version from the project +``). Eject with `mvn metaobjects:eject -Dnames=shared-model -Dport=java|kotlin` or `dotnet +meta eject shared-model`. A JVM publisher ships the pair as the JAR's `metaobjects/` resources and a +C# publisher as the NuGet package's `metaobjects/` content; consumers declare +`{ "name": "x", "maven": "com.acme:model", "version": "1.0.0" }` or +`{ "name": "x", "nuget": "Acme.Model", "version": "1.0.0" }` (also `npm`/`python`/`path`). +TypeScript, Python, Java, Kotlin and C# *consume*; Python cannot publish. Node `meta deps sync` +remains the only writer of the lock and snapshot in every port. Full detail: `docs/features/metadata-dependencies.md`. diff --git a/.claude/skills/metaobjects-codegen/references/owning-generators.md b/.claude/skills/metaobjects-codegen/references/owning-generators.md index c78c097..6a3c67d 100644 --- a/.claude/skills/metaobjects-codegen/references/owning-generators.md +++ b/.claude/skills/metaobjects-codegen/references/owning-generators.md @@ -27,16 +27,17 @@ Then do **not**: - pin an older MetaObjects release, or wait for a newer one, to get past it; - branch, patch, or rebuild a clone of the MetaObjects repository. -The reference generators are starting points you take a copy of. They are +The reference generators emit real code, and you may take a copy of one. They are conformance-gated so the copy starts out correct — not so that each project's output becomes the library's problem. Once you run a generator in your build, what it emits for your model is yours, exactly as if you had written it. **What is legitimately upstream** is only what you cannot own: the **loader and metamodel** (valid metadata rejected, invalid metadata accepted, a wrong resolution), the -**core runtime** your app imports (the metadata-driven `ObjectManager`, prompt render, the -reply parser — not an HTTP adapter you ejected, which is yours), the **codegen engine -itself** (the runner, the three-way merge, `verify`), and **`meta migrate`**. The test is +**core contracts and runtime** your app imports (prompt render, the reply parser, the +store-neutral contracts — not an HTTP adapter you ejected, which is yours), the **codegen engine +itself** (the runner, the three-way merge, `verify`), and the **store-specific helpers you +cannot eject** (the `ObjectManager` drivers and `meta migrate`), which MetaObjects supports and fixes. The test is mechanical: if changing a generator — or a file eject copied beside it — fixes it, it is yours. diff --git a/.claude/skills/metaobjects-codegen/references/physical-names.md b/.claude/skills/metaobjects-codegen/references/physical-names.md index 83f8364..5be9c8b 100644 --- a/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are @@ -89,14 +89,26 @@ literally. **Java and Python generate no SQL at all**: their DTOs and models car names, and persistence is the repository interface/`Protocol` you implement. There the artifact exists *for your code*, which is the only place a physical name appears. -Two categories stay literal, deliberately, and the gate pins them as such rather than -exempting them: - -- a **flattened value-object column** (`@storage: flattened`) is a composite — - `_` — belonging to no single field of either object, - so there is no one constant to reference; -- a **write-through entity's replica view name**: the artifact holds the object's PRIMARY - source's name (its table), and a write-through entity has two physical names. +**A flattened value object's columns are constants of the OWNING object's artifact.** A +`@storage: flattened` field has no column of its own: each member of the value object is a +column of the owner's table, named by core naming (the field's `@flattenedColumnPrefix`, +else `_`, then the member's column). The artifact carries one constant per +member, and the field itself has none, because the table has no column of that name: + +| Port | Reads as | +|---|---| +| TypeScript | `ShipmentNames.fields.shipTo.members.street.column` | +| C# | `ShipmentNames.ShipToStreetColumn` | +| Java / Kotlin | `ShipmentNames.SHIP_TO_STREET_COLUMN` | +| Python | `SHIPMENT_SHIP_TO_STREET_COLUMN` | + +The column-by-field maps (`ColumnsByField`, `COLUMNS_BY_FIELD`) key these `shipTo.street`. +A member constant that would share its name with another constant (a field `shipToStreet` +beside a flattened `shipTo.street` with a custom prefix) is left out with a warning; rename +one to get it. The generated EF Core and Exposed bindings still spell these columns as +literals, because an owned copy of an older names generator does not emit the member +constants. Without the artifact, compute the name with core naming's +`resolveFlattenedColumnName` (or its port equivalent), never by concatenating. **But prefer a typed handle where one exists — this rule has a real limit.** If the ORM gives you a type-checked object for the same thing, use that. Replacing a Drizzle column diff --git a/.metaobjects/CLAUDE.md b/.claude/skills/metaobjects-codegen/references/principles.md similarity index 53% rename from .metaobjects/CLAUDE.md rename to .claude/skills/metaobjects-codegen/references/principles.md index 97d0722..1ef45c6 100644 --- a/.metaobjects/CLAUDE.md +++ b/.claude/skills/metaobjects-codegen/references/principles.md @@ -1,46 +1,24 @@ -# Working with MetaObjects in this project +# Standing principles -> Stack: typescript server, react client. -> -> Generated by MetaObjects (refresh: `meta init --refresh-docs`). Put project notes in your -> **root `CLAUDE.md`**, not here — this file is regenerated; see the note at the end before editing it. +The rules that hold in every MetaObjects project, whatever the stack and whatever the task. The +always-on file in `.metaobjects/` carries the short form; this page is the full text, with the +reasons. Read it when a rule there does not settle the case in front of you. -MetaObjects is a metadata standard: typed metadata (in `metaobjects/` unless the project -configures another directory) is the durable spine; generated code is the disposable -artifact. Regenerate with `npx meta gen`. +## Contents -## Read the generated reference before you touch a tier -`meta gen` writes four reference files under this project's docs target -(`targets.docs.outDir` in `metaobjects.config.ts`) when `generators` lists the generator -for each — `agentDocsFile()` for the three `agent/` pages, `apiDocsFile()` for the api -reference. There is no separate docs command: documentation is one more entry in the same -list every other generator is in. They are generated from THIS project's metadata, so they -describe what it actually is rather than what the framework does in general — and reading -the relevant one first is how you avoid inferring the answer from generated code, which is -the disposable half. - -- **`agent/schema.md`** — before touching persistence. Tables, columns, the field each - column came from, keys, foreign keys, constraints. -- **`api/AGENT-API.md`** — before calling generated code. The types, endpoints and filter - operators the generators actually emitted. -- **`agent/ui.md`** — before touching a form or a grid. The control, label, rules and - filterability per field, and each declared grid. -- **`agent/requirements.md`** — before adding a capability. What is already claimed, and - what was deliberately **retired** — an entry saying a capability must not be rebuilt is - the one thing you cannot learn from the code, because the code is gone. - -Not there? List the missing generator — and a `docs` target, if `targets` has none — in -`generators`, then run `meta gen`. +- Principles +- Authoring rules you must not violate ## Principles + - **Adopting onto existing code? Metadata FOLLOWS the code.** On a migration (existing working code / live DB), author metadata + tune codegen to *reproduce* what the code already is — native types (`field.uuid` when the code uses `UUID`, not `field.string`; and the type a JSON column's WRITER declares — `list[str]`, a dataclass, `dict[str, X]` — not an open jsonb bag), names, nullability — so regen changes as little existing code as possible. The only existing code that should change is the hand-written layer codegen replaces; ask when a modeling choice is ambiguous. (Greenfield: model-first, below.) -- Pattern-derivable from metadata = codegen, never hand-write — FKs, CRUD, validators, finders, and the database schema and migrations. The schema is a disposable, generated artifact: change the metadata and regenerate. Don't hand-write divergent SQL; where a stack owns its own migration files, GENERATE them — `meta migrate --migration-format flyway` emits the paired `V__`/`U__` files a Flyway runner expects, and leaves applying them to Flyway. The one exception is a schema this project deliberately owns outside MetaObjects (hand-written migrations by rule, or another team's database): when the root `CLAUDE.md` says so, follow it, and keep `meta verify --db` catching drift. +- Pattern-derivable from metadata = codegen, never hand-write — FKs, CRUD, validators, finders, and the database schema and migrations. The schema is generated output: change the metadata and regenerate. Don't hand-write divergent SQL; where a stack owns its own migration files, GENERATE them — `meta migrate --migration-format flyway` emits the paired `V__`/`U__` files a Flyway runner expects, and leaves applying them to Flyway. The one exception is a schema this project deliberately owns outside MetaObjects (hand-written migrations by rule, or another team's database): when the root `AGENTS.md` or `CLAUDE.md` says so, follow it, and keep `meta verify --db` catching drift. - **Once this project declares any `template.prompt`, every LLM prompt is one** — the text in the template, the data in a payload value object, rendered by the render engine. A structured reply is read through a response model (`@responseRef` and its generated extractor), never a regex or string search. This covers code that does not look like MetaObjects: a format string, text block, template literal or string builder sent to an LLM, and it covers every module, including test harnesses and scripts. Changing a prompt that is still hand-built means migrating it first (snapshot its current output and keep the rendered text byte-identical), not adding a line to it; the `metaobjects-prompts` skill has the steps. -- The **live database** is a derived artifact too — never hand-apply a schema change to a running DB (ad-hoc `psql`/console `ALTER`/`CREATE`/`DROP`), not even to preview a column or unblock a boot. Drive every schema change from the metadata, never ad-hoc: on the Node/TS-owned migrate stack that is `meta migrate` (metadata → DDL, ADR-0015); on a **Flyway**-owned JVM stack that is `meta migrate --migration-format flyway`, which emits the migration and deliberately refuses `--apply` because Flyway owns applying it. Hand-authoring a migration to match the generated schema is the LAST resort — for a runner MetaObjects has no writer for — never the default for Flyway. A hand-applied ad-hoc change drifts the live DB from the metadata + migration history and collides at the next migrate/boot ("column already exists") — a state no migration can reproduce. Run `meta verify --db ` after any DB-touching work to catch that drift early — the URL is required, and the bare form exits 2. +- The **live database** is a derived artifact too — never hand-apply a schema change to a running DB (ad-hoc `psql`/console `ALTER`/`CREATE`/`DROP`), not even to preview a column or unblock a boot. Drive every schema change from the metadata, never ad-hoc: with the reference migration helper that is `meta migrate` (metadata → DDL, ADR-0015); with a native tool (EF Core, Exposed, Alembic, sqlx) it is a migration written from the schema `meta schema` prints; on a **Flyway**-owned JVM stack that is `meta migrate --migration-format flyway`, which emits the migration and deliberately refuses `--apply` because Flyway owns applying it. Hand-authoring a migration to match the generated schema is the LAST resort — for a runner MetaObjects has no writer for — never the default for Flyway. A hand-applied ad-hoc change drifts the live DB from the metadata + migration history and collides at the next migrate/boot ("column already exists") — a state no migration can reproduce. Run `meta verify --db ` after any DB-touching work to catch that drift early — the URL is required, and the bare form exits 2. - **If this project declares `requirement.*` nodes, a commit that adds, changes or removes behaviour updates them in the same commit** (the claim, its `@status` and `@implementedBy`), or says in the commit message why not. `meta verify` checks that the links resolve, not that the ledger is current. - Never hand-edit generated **output** — change the metadata and regenerate. (That bounds the files codegen *emits*; it says nothing about the generator that emits them — next bullet.) What survives a regen DIFFERS BY TOOLCHAIN, so never rely on it: the Node/TS `meta gen` path three-way-merges, so an edit inside a generated file is preserved (and is refused rather than guessed at when it cannot tell yours from its own stale output); the JVM generators overwrite, and several Kotlin ones — including `.kt` — truncate unconditionally with no marker check. Put your own code in a subclass or a separate file, never in the generated one. - **Nothing is generated until you wire it — one generator list per port, documentation included.** No port ships a default generator suite, and there is no separate docs command or docs config block on any port: a docs page is one more entry in the same list as every other generator. The list lives in `generators` in `metaobjects.config.ts` (TypeScript; a fresh `meta init` writes `generators: []`), `codegen/Generators.cs` (C#, scaffolded by `dotnet meta init`), a target's `generators` in `metaobjects.config.yaml` (Python), or `` in the Maven plugin's `` (Java, Kotlin). `meta gen --list --probe` is the catalog — it runs every generator against your model and reports how many files each would emit — and each generator runs as shipped from its package: import it on the Node/TS path (the catalog row prints the line), select it by name on the others. `--generators ` (TypeScript, C#, Python; a second Maven `` of `generate`) NARROWS a run to entries the list already declares — it never adds one, and naming an undeclared entry is refused. Copy nothing you are not going to change. `meta eject ...` copies one into your repo when you need to change what it emits. -- **Need an output the model describes that nothing here emits? WRITE A GENERATOR — that is the primary path, not an escape hatch.** OpenAPI, JSON Schema, Zod, DTOs, a client, a service layer, docs: MetaObjects is the core (model, loader, `verify`, `migrate`, render, extract), and the generators on it are yours to write. A generator is a name plus a function from the model to `{ path, content }` files, about 20 lines; `verify --codegen` gates it with nothing to register. Read the model through the RESOLVING accessors (`fields()`, `attr()`, `resolvedIsArray()` — never `own*()`), skip abstract objects, and resolve `@objectRef` with the port's helper. On the Node/TS path, `meta generator new ` scaffolds a working one and wires it into `metaobjects.config.ts`; the `metaobjects-codegen` skill has every port's shape. Run a reference generator as shipped when it already emits what you want, and eject one only when it is close and you need to change it; never hand-write output the model fully describes. +- **Need an output the model describes that nothing here emits? WRITE A GENERATOR — that is the primary path, not an escape hatch.** Zod, DTOs, a client, a service layer, docs: MetaObjects is the core (model, loader, `verify`, `migrate`, render, extract), and the generators on it are yours to write. A generator is a name plus a function from the model to `{ path, content }` files, about 20 lines; `verify --codegen` gates it with nothing to register. Read the model through the RESOLVING accessors (`fields()`, `attr()`, `resolvedIsArray()` — never `own*()`), skip abstract objects, and resolve `@objectRef` with the port's helper. On the Node/TS path, `meta generator new ` scaffolds a working one and wires it into `metaobjects.config.ts`; the `metaobjects-codegen` skill has every port's shape. Run a reference generator as shipped when it already emits what you want, and eject one only when it is close and you need to change it; never hand-write output the model fully describes. - **Database, store or framework not built in? Work it out — that is a supported path, not a dead end.** MySQL is a `dialect`. MongoDB, DynamoDB, Cassandra, Neo4j or a remote API: model each record as a sourceless entity (`identity.primary`, no `source.*`, store settings in your own `@` property bag) and generate its data access with a repository generator you own. Express, NestJS, Next.js, Workers, Vue, Svelte: mount or retarget a reference generator, or write one. Never invent vocabulary for it and never hand-write the layer. The procedure is the `metaobjects-codegen` skill's `references/any-stack.md`. - **The generators are yours — editing one is ordinary work, not an escalation.** Your generator list, and any generator source in your repo (`codegen/generators/` on the Node/TS path), are your code: no `@generated` header, no upstream ownership, nothing to ask permission for. **A standing rule not to change the MetaObjects repo is not a rule about your generators** — that is a different repository, and generalising the first into the second is how an agent ends up hand-writing the exact layer it was told to generate. When generated output does not fit, in order: change the **metadata** if the model is wrong; else change **your own generator**; only then hand-write. Hand-writing what the metadata already describes is the last resort, not the first. Per-port specifics — including which ports have an eject command and which mean implementing a generator interface — are in the `metaobjects-codegen` skill. - **A defect in generated code is a defect in YOUR generator — fix it there and keep going.** Output that does not compile, has the wrong shape, or collides with your own code is fixed in the generator that emitted it: your ejected copy on the Node/TS path (eject it first if you import it from the package), your own generator class on the JVM (subclass the reference generator, or copy its source into a codegen module on the plugin's classpath), your ejected copy or your own generator on C# and Python. Do not file it upstream, do not wait for or pin a MetaObjects release, and never branch or patch the MetaObjects repository: the reference generators are helpers you can take a copy of at any time, not a guarantee to wait on. Upstream is only for what you cannot own — the loader and metamodel, the runtime packages, the codegen engine itself (runner, merge, `verify`), and `meta migrate`. The test: if changing a generator fixes it, it is yours. @@ -50,35 +28,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - **JVM:** serialize a MetaObject-backed instance (a `pojoAware`-flavor generated class, a runtime `ValueObject`, or any `MetaObjectAware` type) through the MetaObjects JSON layer — never hand-configure a Jackson/Gson mapper around the framework fields to make a default mapper cope. ## Authoring rules you must not violate -- **Search the vocabulary before concluding it cannot be expressed — `meta types `.** An unregistered TYPE or SUBTYPE fails the load in every command. An undeclared `@attr` is different: it fails `meta verify`, which loads strict, and NOT `meta gen`, which does not — so an invented attribute passes codegen silently and is caught by the drift gate rather than by the build. Either way inventing vocabulary is a failure you will hit, not a shortcut. Search names with `meta types `, names and descriptions with `--all` ("find it by what it does"), and one construct's valid `@attrs` with `meta types . --detail`; `--format json` returns the same answer as one machine-readable document, each attr with its `allowedValues`. Rows marked `[ts-only]` are TypeScript-only vocabulary the cross-port contract does not carry. It is the Node `meta` CLI and, like `meta migrate`, works whatever your backend — it reads the registry, so it needs no project. Ask for NEW vocabulary only once that search comes up empty. + +- **Search the vocabulary before concluding it cannot be expressed — `meta types `.** An unregistered TYPE or SUBTYPE fails the load in every command. An undeclared `@attr` is different: it fails `meta verify`, which loads strict, and NOT `meta gen`, which does not — so an invented attribute passes codegen silently and is caught by the drift gate rather than by the build. Either way inventing vocabulary is a failure you will hit, not a shortcut. Search names with `meta types `, names and descriptions with `--all` ("find it by what it does"), and one construct's valid `@attrs` with `meta types . --detail`; `--format json` returns the same answer as one machine-readable document, each attr with its `allowedValues`. Rows marked `[ts; pending elsewhere]` (or `[java; …]`) are cross-port vocabulary only that port implements so far: every port loads it, the others ignore it. `[-only]` (`[csharp-only]`; several ports: `[java+kotlin]`) marks vocabulary only those ports ever act on. It is the Node `meta` CLI and, like `meta migrate`, works whatever your backend — it reads the registry, so it needs no project. Ask for NEW vocabulary only once that search comes up empty. - Nodes are fused-key maps: `{".": { ... }}` (e.g. `{"field.string": {"name": "email"}}`) — never split the type and subtype into separate keys. - Attribute names are unique within a node; for multi-value use one array attr (`@values: [...]`). - An inline `@maxLength: 50` equals an `attr` child of the same name — never write both. - Package paths use `::` (`acme::common::id`). - -## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. - -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. - -**Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. - -## Going deeper (Claude Code) -For authoring, codegen, runtime/UI, prompts, verify, or adoption-audit work, use the -matching `metaobjects-*` skill — its body links the `references/.md` fragment -installed for this project's stack. Read only the skill your task needs, and inside it the -`SKILL.md` plus the reference file it points you to; the other `references/` files are topics -to open when they come up, not reading to do up front. A skill that `meta init` wrote during -the current session may not load by name until the next one; read -`.claude/skills//SKILL.md` directly. - -## Refreshing / customizing this generated context -This file and the `metaobjects-*` skills are **generated** by MetaObjects for this project's -stack (plain Markdown, no tools/hooks) — refresh with `meta init --refresh-docs`. Don't hand-edit -them expecting the edit to survive: a refresh leaves a file you've edited intact and writes the -new copy to `.new` (only `--force` overwrites in place — never `--force` a file with local -edits). For project-specific guidance, put it in your **root `CLAUDE.md`** (always-on concerns) or -copy a skill to a new name (skill-level overrides) — don't edit the generated originals in place. - -After a refresh, for each `.new`: diff it against ``, **keep the hand-edits and take -the upstream changes**, write the merged result back to ``, then delete `.new`. diff --git a/.claude/skills/metaobjects-codegen/references/template-or-code.md b/.claude/skills/metaobjects-codegen/references/template-or-code.md index a81e972..96097ce 100644 --- a/.claude/skills/metaobjects-codegen/references/template-or-code.md +++ b/.claude/skills/metaobjects-codegen/references/template-or-code.md @@ -8,7 +8,7 @@ are good at different things. | | Programmatic | Declarative template | |---|---|---| -| What you write | a `Generator` in the port's language, using its AST builder (ts-poet, KotlinPoet, …) | a `.mustache` file + `{ template, scope, outputPattern, format? }` | +| What you write | a `Generator` in the port's language, using its code writer (`JavaWriter`, `KotlinWriter`, …) | a `.mustache` file + `{ template, scope, outputPattern, format? }` | | Output shape | expressed in code | **is the file you are editing** | | Cross-language | per-port by construction | one template emits for any language — it renders against the neutral, byte-gated data dict | | Logic | any | what a template can express: sections, iteration, presence flags | @@ -24,8 +24,8 @@ here.** §5 (*Preserving hand edits*) states MetaObjects ships exactly one hand- no shipped generator on any port emits a generated-base + hand-owned-concrete pair, or a write-if-absent file; §6 names the `skip-existing` merge strategy `runGen` accepts for building that pair yourself, reachable only from a programmatic caller (no CLI flag selects -it); §7 (*Safety*) is the per-port write-decision mechanism behind "What codegen does" step 4 -above. +it); §7 (*Safety*) is the per-port write-decision mechanism behind "What a `gen` run does, +and when it refuses to write" in `SKILL.md`. **A template is not limited to documents.** It emits source as readily as docs — that is what the neutral data dict is for. diff --git a/.claude/skills/metaobjects-codegen/references/typescript-docs.md b/.claude/skills/metaobjects-codegen/references/typescript-docs.md index 35f595e..6285294 100644 --- a/.claude/skills/metaobjects-codegen/references/typescript-docs.md +++ b/.claude/skills/metaobjects-codegen/references/typescript-docs.md @@ -18,29 +18,28 @@ generate, docs included). Each factory is an ordinary entry in `generators`, fro | Factory | Registry name | Writes | |---|---|---| -| `docsFile()` | `docs` | the neutral model surface — one page per entity and per template (`.md`, `