diff --git a/AGENTS.md b/AGENTS.md index beb954aed3..9d37eb27e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,7 +76,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. **Cross-port conformance corpora** (every port runs the shared corpus): - Metamodel: `fixtures/conformance/` (578 fixtures; 45 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. -- Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) +- Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. - YAML / verify corpora green across the ports that ship those layers. - **Codegen-compile gate** (all five ports; a GATE, not a corpus — it has no fixtures of its own and no row in the matrix). Every corpus above gates BEHAVIOUR; none asks whether the emitted code BUILDS, which is how four "generated code does not compile" defects shipped in 1.0.4 with the whole matrix green — `gen` exits 0 in all four cases and the adopter's build is the first thing that disagrees. Each port generates from `fixtures/persistence-conformance/canonical/meta.fitness.json` (reused deliberately: a second kitchen sink would drift from the one the other corpora already maintain) and compiles the emitted tree with its real compiler — `ts.createProgram` / Roslyn / `javac` / `KotlinCompilation` / (Python, having no static compiler) importing the generated package plus `ruff` F821. **Every port excludes its framework-bound route tier** (TS `routesFile`, C# `RoutesGenerator`, Java `SpringControllerGenerator`, Kotlin `KotlinSpringControllerGenerator`): those imports are not on an in-memory compile's classpath and stubbing them drowns the signal, so that tier is proven by the api-contract integration lane instead. One cross-port rule, not four local concessions. Found 5 further real defects on first run. Boundary detail: `docs/CONFORMANCE.md` → "Split coverage". diff --git a/CHANGELOG.md b/CHANGELOG.md index e2c9f54863..711f587bce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -111,6 +111,53 @@ here.** because a newer MetaObjects may have written it, but each one is now named once on standard error with the known keys, in the words TypeScript uses. A key inside a block C# owns (`csharp`, `naming`, `wire` and the rest) is refused as before. +- **sdk: the static agent files, built once for every port (ADR-0033 Amendment 1).** The + assembler now also runs at build time, once per stack a port's own command serves: each server + language alone and Java with Kotlin, each with no client, React, React with TanStack or + Angular. The result is committed at `agent-context-shipped/` (a manifest plus each distinct file + once, by content hash), for each port's package to embed and its `agent-docs` command to copy, + so a non-TypeScript project gets its agent files with no Node. `agent-context-shipped/README.md` + is the contract; `buildShippedAgentContext()` and `materializeShippedStack()` are exported, and + `shipped.test.ts` fails when the tree is stale or a stack differs from what `meta agent-docs` + writes. The ports' own commands land in their own rows; until then they still redirect. +- **sdk, cli: Rust is an agent-context server language.** `--server rust` (alias `rs`) is + accepted, and a `Cargo.toml` at the project root is detected as Rust. A Rust project's + always-on file gives the `cargo meta gen` loop and the `cargo meta verify` step, and a `rust` + case joins `fixtures/agent-context-conformance`. Libraries list Rust among their ports, checked + against the copy the Rust crate embeds. +- **codegen-ts: the rules names layer (ADR-0067 layer 0).** A new generator, `rules-names` + (`rulesNamesFile()`, ejectable), writes one `rules.names.ts` per metadata package that declares + a lifecycle or an operation: each lifecycle's states, initial and terminal states and + transitions, the commands derived from unclaimed transitions, the declared operations, every + permission the package asks about and the business errors its commands declare, as `as const` + values with literal-union types. The derivations move into `@metaobjectsdev/metadata` + (`derivedCommandsOf`, `operationPermission`, `commandPermission`, `claimedTransitions`, ...), and + `meta verify`'s rules gate now calls the same functions, so a constant and a verify message + cannot disagree. The loaded root carries the `rules` settings (`rulesSettings`). C# ships its own + `rules-names`; the other ports add theirs with their rules-layer work. No existing generator's output + moves (`fixtures/codegen-noop/rules`). +- **codegen-ts: the contract types layer (ADR-0067 layer 1).** A new generator, `contract-types` + (`contractTypes()`, ejectable), writes the shapes a caller and a service exchange with no + persistence mapping: `.contract.ts` (the read schema and type, the create and update + schemas, the typed create and patch), `.contract.ts` (the read shape), the value + modules they reach, `/operations.contract.ts` (each declared operation's input, output + and errors) and `errors.contract.ts` (the wire codes, their statuses and the error bodies). Each + module imports `zod` only. The field schemas are the entity generator's own renderers, and an + entity's contract read type is held equal to the entity file's on every dialect. C# writes the create and + update records with its own `contract-types`. No existing generator's output moves. +- **runtime-ts: the guarded update (ADR-0066 §6 step 5), and the shared scenario that holds every + store driver to it.** `ObjectManager.guardedUpdate(entity, id, { field, from, to, condition? })` + makes a lifecycle transition's write in one statement — `UPDATE … SET = :to WHERE + = :id AND IN (:from) [AND ]`, TPH-scoped — and answers the row, or `null` + when the guard matched nothing. The `@condition` (attr.expression's CHECK subset) compiles to + the driver contract, which gains three `WhereClause` kinds: `compare` (two operands, each a + column, a literal or a `coalesce`), `nullTest` over any operand, and `not`. A driver an adopter + wrote must handle them; the bundled Kysely, Drizzle and in-memory drivers do, the in-memory one + with SQL's three-valued logic. Guard symbols must be members of the state enum, and each symbol + and condition literal is stored in its column's form (an int-backed enum as its integer). The + persistence corpus gains `op: guardedUpdate` and `queries/guarded-update.yaml`; TypeScript runs + it on Postgres and MySQL, and C#, Java, Kotlin and Python defer it by name until each builds its + own. - **The REST standard's list handling is part of the cross-port contract.** `?search`, `filter[or]` / `filter[and]`, the nesting cap, the bare-field and leading-`%` refusals, the filter-value format check, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and @@ -126,6 +173,14 @@ here.** TypeScript passes both. The other ports take them on in their 1.3.0 REST-standard work. The decision is [ADR-0068](spec/decisions/ADR-0068-list-query-cross-port-contract.md). A scenario can now send a body that is not JSON with `rawBody`. +- **openapi: the document describes `?search`, `filter[or]` and `filter[and]`.** A list whose row + has a text field the search matches takes a `search` parameter naming those fields, and a list + with any filter takes the two combinators as `deepObject` parameters whose description gives the + grammar and the nesting cap. Item `GET`, `PATCH`, `PUT` and `DELETE` now list the `400 invalid_id` answer the routes + already gave. A project that wires `openApiFile()` sees `openapi.json` change on the next + `meta gen`; the contract corpus goldens move with it. A new contract case, `list-query`, documents + the list-query model, and the list-query lane now holds every exchange to it as the other + generated lanes do; the check no longer exempts `search` and the combinators. - **Java: the Spring controller generator writes through the code writer (ADR-0063).** `SpringControllerGenerator` writes through `SpringJavaWriter`, a `JavaWriter` that adds the two layouts Spring source uses and a block does not: a continuation line (two indents deeper) and an diff --git a/README.md b/README.md index 9f4ae50f8f..73c784fced 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ MetaObjects has two layers, and only the first is a promise | | Core — guaranteed | Helpers — yours | |---|---|---| -| **What** | The contracts and the conformance kits: the metamodel, loader, canonical format and registry; the store-neutral contracts (the expected schema, and the guarded update once its persistence-conformance scenario lands, ADR-0066 §6); the drift gates (`meta verify`); prompt render and the reply parser | Store-specific code (SQL writers, introspectors, drivers such as the `ObjectManager` drivers and the `meta migrate` writer, mappings) and every generator that writes code into your repo — the ones you write for the outputs you need, and the routes, controllers, ORM wiring, DTOs, forms, grids and hooks MetaObjects ships | +| **What** | The contracts and the conformance kits: the metamodel, loader, canonical format and registry; the store-neutral contracts (the expected schema, and the guarded update, which a persistence-conformance scenario holds every store driver to, ADR-0066 §6); the drift gates (`meta verify`); prompt render and the reply parser | Store-specific code (SQL writers, introspectors, drivers such as the `ObjectManager` drivers and the `meta migrate` writer, mappings) and every generator that writes code into your repo — the ones you write for the outputs you need, and the routes, controllers, ORM wiring, DTOs, forms, grids and hooks MetaObjects ships | | **Promise** | Conformance-gated, the same behaviour in every port that ships it, covered by the [compatibility policy](docs/compatibility-policy.md) | Supported helpers that compile and pass their reference fixtures, with the same capabilities in every port unless a ruling says otherwise. The code they generate is real code: run it as shipped, extend it through hooks, or copy it with `meta eject` and own it | | **A defect is** | A MetaObjects bug, fixed in a release | A bug in the reference, fixed there; your copy is yours | diff --git a/agent-context-shipped/README.md b/agent-context-shipped/README.md new file mode 100644 index 0000000000..3b9cb07462 --- /dev/null +++ b/agent-context-shipped/README.md @@ -0,0 +1,56 @@ +# The shipped agent files + +The always-on `.metaobjects/AGENTS.md` and the `metaobjects-*` skills, assembled once at build +time for every stack a port's own `agent-docs` command serves. Every non-TypeScript port embeds +this directory in its package and copies one stack out of it, so a project gets its agent files +with no Node on the path ([ADR-0033](../spec/decisions/ADR-0033-single-agent-context-assembler.md), +Amendment 1). + +Everything here but this README is built. Do not edit it by hand: change `agent-context/` and +rebuild. + +```bash +bun server/typescript/packages/sdk/scripts/build-shipped-agent-context.ts # rebuild +bun server/typescript/packages/sdk/scripts/build-shipped-agent-context.ts --check # exit 1 when stale +``` + +`server/typescript/packages/sdk/test/agent-context/shipped.test.ts` fails when the tree is stale. + +## Layout + +``` +manifest.json the stacks, and the files each one writes +files/.md each distinct file once, named by its content hash +``` + +`manifest.json`: + +| Key | Meaning | +|---|---| +| `schema` | The manifest's shape, `1`. Refuse a manifest whose schema you do not know. | +| `docsRef` | The git ref every guide link in the files is pinned to (`main`). | +| `docsLinkPrefix` | What comes before the ref in a guide link: the repository's `.../blob/`. | +| `skillsDir` | The directory every skill's path starts with (`.claude/skills`). | +| `stacks` | One entry per stack: `id`, `servers`, `clients`, and `files`, each a `path` (relative to the project root) and the `file` under `files/` it copies. | + +The stacks are every server language alone (`typescript`, `java`, `kotlin`, `csharp`, `python`, +`rust`) and Java with Kotlin together (one Maven goal serves both), each with every client +choice: none, `react`, `react` with `tanstack`, and `angular`. + +## What a port's command does + +1. **Find the stack.** Its id is the server languages, then the clients, each in this order and + joined by `-`: servers `typescript, java, kotlin, csharp, python, rust`; clients + `react, tanstack, angular`. So `--server kotlin --server java --client tanstack --client react` + is `java-kotlin-react-tanstack`. Refuse a stack with no entry, and name the ids that exist. +2. **Pin the links.** In every file, replace each `docsLinkPrefix + docsRef + "/"` with + `docsLinkPrefix + + "/"`, where `` is the release tag: `v` and the release's + npm-line version, so 1.3.0 is `v1.3.0` (Maven's 8.3.0 is also `v1.3.0`: its major is the npm + major plus 7). A prerelease, or a version the port cannot resolve, has no tag and keeps + `main`, so its files are written unchanged. That is a plain text replacement, with nothing + else to know (`docsRefForVersion` and `pinDocsRefs` in `@metaobjectsdev/metadata` are the + reference). +3. **Write each file** at its `path` under the project root, and nothing else. + +The result is byte-identical to what `npx meta agent-docs` writes for the same stack, which +`shipped.test.ts` checks for every stack here. diff --git a/agent-context-shipped/files/0080df7715486e4c.md b/agent-context-shipped/files/0080df7715486e4c.md new file mode 100644 index 0000000000..45896849cf --- /dev/null +++ b/agent-context-shipped/files/0080df7715486e4c.md @@ -0,0 +1,85 @@ +# Your own vocabulary in C# — 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 C# tools load the metadata. + +A provider is a public class implementing `IMetaDataTypeProvider`, with a public parameterless +constructor: 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). Put it in its +own class library that references the `MetaObjects` package at the version your `dotnet meta` +tool runs. This one registers `layout.picker` and adds `@searchable` and `@valueLabels` to +`field.string`: + +```csharp +// vocabulary/AcmeVocabularyProvider.cs (vocabulary/Acme.Vocabulary.csproj: net8.0 class +// library with ) +using MetaObjects; +using MetaObjects.Meta; +using MetaObjects.Shared; + +namespace Acme.Vocabulary; + +public sealed class AcmeVocabularyProvider : IMetaDataTypeProvider +{ + public string Id => "acme-vocabulary"; + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + // A new subtype, with its own attribute (an own attribute may be required). + registry.Register(new TypeDefinition( + typeId: new TypeId("layout", "picker"), + description: "A picker over the owning object.", + childRules: [new ChildRule(BaseTypes.TYPE_ATTR, Structural.CHILD_RULE_WILDCARD, Structural.CHILD_RULE_WILDCARD)], + factory: (typeId, name) => new MetaLayout(typeId, name), + attributes: [new AttrSchema("displayField", "string", Required: false)])); + + // Attributes on a type another provider owns: always optional. + registry.Extend("field", "string", attributes: + [ + new AttrSchema("searchable", "boolean", Required: false), + new AttrSchema("valueLabels", "string", Required: false, IsArray: true), + ]); + } +} +``` + +Wire it once, in `.metaobjects/config.json`. `assembly` is the BUILT dll, relative to the +directory holding `.metaobjects/`; `type` is the provider's full type name: + +```json +{ + "schema_version": 1, + "csharp": { + "providers": [ + { "assembly": "vocabulary/bin/Debug/net8.0/Acme.Vocabulary.dll", "type": "Acme.Vocabulary.AcmeVocabularyProvider" } + ] + } +} +``` + +Build the vocabulary first (`dotnet build vocabulary`); a missing dll is refused with the path +and that instruction. Then `dotnet meta gen` and `verify --codegen` (through the project's +`codegen/` runner), `dotnet meta verify` (templates, requirements, field lint) and +`dotnet meta fmt` all compose the core providers plus this one. The `codegen/` project may +also reference the vocabulary project directly; the already-loaded assembly is reused. + +An application host that loads the model itself composes the registry in code: + +```csharp +var registry = Provider.ComposeRegistry([.. CoreTypes.LibraryProviders, new AcmeVocabularyProvider()]); +var load = MetaDataLoader.FromDirectory("metaobjects", registry, strict: true); +``` + +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 `dotnet 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/agent-context-shipped/files/0440a95faf89e271.md b/agent-context-shipped/files/0440a95faf89e271.md new file mode 100644 index 0000000000..6f0302b540 --- /dev/null +++ b/agent-context-shipped/files/0440a95faf89e271.md @@ -0,0 +1,225 @@ +--- +name: metaobjects-runtime-ui +description: Use when wiring MetaObjects generated code into an app — runtime queries/CRUD, REST routes, and the web client (forms, grids, filters). +--- + +# Wiring MetaObjects runtime + web client + +This skill is the procedure for putting generated code to work: querying/persisting +through the runtime tier, serving the REST contract, and consuming it from the +universal web client. It is port-agnostic — the cross-cutting contracts are here; +the server- and client-specific imports/types live in reference fragments (see +the table below). + +## Reference files — open the ones for your stack + +Only the files for the servers and clients in this project's stack are installed. Read your +server language's file and your client framework's file before wiring anything. + +| File | Open it when | +|---|---| +| `references/typescript.md`, `references/java.md`, `references/kotlin.md`, `references/csharp.md`, `references/python.md` | the project's server language is that one: the runtime and REST specifics | +| `references/react.md` | the web client is React | +| `references/tanstack.md` | the web client uses TanStack Query or Table (grids, hooks, filters) | + +## The runtime return-type contract + +A port's runtime returns **native in-process language types**, never wire strings. +Query the runtime and you get back the language's natural type for each field: + +- `field.decimal` → the language's exact-decimal type (`BigDecimal` / `decimal` / + `Decimal`). Decimal is **lossless end-to-end** — no float round-tripping. +- temporal fields → native date/instant types. +- `field.object` (jsonb) → a native map/object. +- **TypeScript is the documented outlier: `field.decimal` is a `string`** in the + TS runtime (JS has no native exact decimal), preserving precision as text. + +Wire canonicalization (integer minor units for currency, ISO-8601 strings for +temporals, canonical hex for UUID) is applied only at the **serialization +boundary** — when a row leaves over HTTP — never inside the runtime query path. So: +compute with native types in-process; the HTTP layer handles wire encoding. + +## Generated repo / query helpers take the context as a parameter + +Generated finders and CRUD helpers **do not** reach for a module-level `db` +singleton. They take the persistence context (connection / session / data-access +handle) as an explicit **parameter**. You own the connection's lifecycle and pass +it in: + +``` +const rows = await findPostsForAuthor(db, authorId); // db is passed, not imported +``` + +This keeps generated code free of global state, makes it testable, and lets one +process talk to multiple databases (multi-tenant, read-replica). Construct/own the +context in your app; thread it through every generated call. + +## Physical names come from the generated names artifact, never a literal + +The runtime tier is where the code codegen leaves to you gets written — a repository +implementation, a raw query, a migration script, a log line — and that is where a table +or column name gets respelled. Don't. A physical name is declared **once**, in metadata +(`@table` / `@view` / `@column` / `@schema`), and every port emits a per-object names +artifact carrying it: `ProgramNames.fields.createdAt.column` on TypeScript, +`ProgramNames.CreatedAtColumn` on C#, `ProgramNames.CREATED_AT_COLUMN` on the JVM, +`PROGRAM_CREATED_AT_COLUMN` on Python. Reference it. `@column` is free-form — +`callPurpose` may live in `purpose_code` — so deriving a column from the field name is a +guess that fails silently, and a literal is a second spelling of a fact the metadata +owns: rename the column in metadata and the constant follows, the literal does not, and +nothing tells you. + +**Prefer a typed handle where one exists.** A Drizzle column object, an Exposed `Column`, +an EF Core property is type-checked against the schema; swapping it for a string constant +trades a compile error for a runtime one. The constants are for the places with no +handle: raw SQL, a string-keyed query builder, and a hand-written repository on a port +whose generated model carries no persistence binding at all (Java, Python). Your server +reference names the handle and the artifact for this stack. + +**First check the artifact exists — it is opt-in on EVERY port, and an existing project +almost certainly has none.** Every port's generator list is now the COMPLETE list: C# and +Python dropped their default suites (ADR-0034 Amendment 2), TypeScript's `generators: []` +starts empty, and the JVM's `` never had a default. Upgrading the package +never edits a config that was written earlier, so `names` arrives only when someone wires +it. Look for `.names.ts` / `Names` in the generated output before you +write `ProgramNames.fields.x.column` against it; if it is not there, wiring the generator +is the first step and the `metaobjects-codegen` skill says how. Writing raw SQL +with literal names because "there is no constant" is the loop this closes. + +## The REST contract + +Generated (or hand-written) routes speak one cross-port HTTP contract so the same +universal web client serves any backend language. One part of the path grammar — +the `` collection segment — is a known cross-port divergence (below); +the verbs, filters, sort/pagination, and wire format are uniform. + +### URL grammar + +`apiPrefix` (default `/api`, set in project config) flows to both the server routes +and the client fetch URLs. + +The `` collection segment is the **entity name `snake_case`d and then +pluralized** — one rule, identical in all five ports, and derived from the NAME, +never from the physical `@table`: + +| Name | Segment | Rule | +|---|---|---| +| `Author` | `authors` | a single regular word takes `s` | +| `PostCategory` | `post_categories` | multi-word: the capitals carry the word boundary | +| `Address` | `addresses` | ending `s`/`x`/`z`/`ch`/`sh` takes `es` | +| `Category` | `categories` | consonant + `y` becomes `ies` | +| `Day` | `days` | a VOWEL before the `y` does not | +| `HTTPServer` | `http_servers` | a run of capitals stays together until the final one that begins a word | + +An `object.projection` uses the same rule, so `OrderSummary` is at +`/order_summaries` either way. The generated web-client hooks and grids build +their fetch URLs from the TypeScript `$path`, and every backend now mounts that +same spelling, so a React/TanStack client works against any port's server. +A view-backed `object.report` has a generated list route at the same rule and, in +TypeScript, a generated list hook named `use` + the plural of the report's name +(`useMemberUtilizations` for `MemberUtilization`; `useList` only when the plural is +the name itself, as in `useSeriesList`); it has no grid, form or detail hook. + +**This is a change, and it was a breaking one.** Each port used to spell the +segment differently and they agreed only on single regular words — which was +every collection base in the corpus, so all five lanes were green while +`OrderSummary` was served at four different URLs: `/order_summaries` (TS entity), +`/order-summaries` (TS projection), `/ordersummaries` (C#) and `/ordersummarys` +(Java, Kotlin, Python). A project whose entity names are all single regular words +saw nothing move. Any multi-word or irregular-plural name had its collection URL +renamed, and clients had to follow. + +The rule is gated, not just documented: `fixtures/api-contract-conformance/m2m/` +declares `PostCategory` — multi-word AND ending consonant+`y`, so it separates +every spelling the ports used to produce — and asserts both retired spellings +404, on each port's reference AND generated lane. The JVM ports share one +implementation (`RouteNaming` in `codegen-base`); the acronym case is pinned by +unit test in each port, since no corpus entity carries one. + +| Verb | Path | Purpose | +|---|---|---| +| `GET` | `//?filter[...][...]=...&sort=...&limit=N&offset=N&withCount=1` | List | +| `GET` | `///:id` | Get by id | +| `POST` | `//` | Create (201) | +| `PATCH` | `///:id` | Update (partial) | +| `PUT` | `///:id` | Update (replace) — optional | +| `DELETE` | `///:id` | Delete (204) | + +### Filter operators by field subtype + +Filters use a bracketed qs: `filter[][]=`. A bare +`filter[]=` is sugar for `eq`. The operator set is **gated by field +subtype** via the generated `FilterAllowlist` — an unsupported operator for +a field → HTTP 400. + +| Operator | Strings | Numbers / Dates | Booleans | +|---|---|---|---| +| `eq`, `ne`, `isNull` | yes | yes | `eq` + `isNull` only | +| `in`, `like` | yes | `in` only | – | +| `gt`, `gte`, `lt`, `lte` | – | yes | – | + +These nine (`eq` `ne` `gt` `gte` `lt` `lte` `in` `like` `isNull`) are the whole +closed set — every port implements these and only these. + +### Sort + pagination + +- `sort=:asc|desc` — single sort key; the field must be in + `SortAllowlist`. +- `limit=N` / `offset=N` — page size + offset, identical across every endpoint. +- `withCount=1` — switches the list response from `[...]` to + `{ rows: [...], total: N }` (grids always send it). + +### Wire format + +JSON bodies (`application/json; charset=utf-8`). Single-row responses (`GET /:id`, +`POST`, `PATCH`, `PUT`) have **no envelope** — the body is the row. Type encodings: + +| Field type | JSON | Notes | +|---|---|---| +| `field.string` / `field.uuid` / `field.enum` | string | UUID is canonical hex `8-4-4-4-12` | +| `field.int` / `field.long` / `field.double` | number | `long` may be string on overflow (per-port) | +| `field.boolean` | boolean | | +| `field.date` | string | ISO 8601 `YYYY-MM-DD` | +| `field.timestamp` | string | ISO 8601 with timezone | +| `field.currency` | **integer minor units** | cents/yen; float arithmetic forbidden; server never formats | +| `field.object` | object | per the sub-object schema | + +The currency invariant is load-bearing: integer minor units on the wire, always. +Formatting happens client-side with locale-aware code. + +Errors: non-2xx returns `{ "error": "", "message"?: "..." }`. 400 for +validation/filter-parser errors, 404 for not-found (`{ "error": "not_found" }`), +5xx implementation-defined. Treat any 4xx as user-facing, any 5xx as retryable. + +## The EntityFetcher browser contract + +The web client never calls `fetch` directly. Every generated hook delegates to a +single `EntityFetcher` you supply once at the app root: + +```ts +export type EntityFetcher = (path: string, init?: RequestInit) => Promise; +``` + +Your fetcher resolves the `path` (always starting with `apiPrefix`) to a full URL, +attaches auth (cookie / bearer / API key) per your policy, parses the JSON, and +throws on non-2xx (the hooks rely on the throw for error state). Provide it via the +fetcher-provider at the tree root; every generated hook reads it from context. The +generated grid and form components, filter-qs serializer, and cell renderers all +sit on top of this one seam. + +## Grids are opt-in per entity + +Read/CRUD hooks are generated for **every** entity. Grids are the exception: +wherever your stack generates them (the TanStack client today), an entity produces +grid artifacts only when it declares a `layout.dataGrid` child. So wiring the grid +generator and seeing no grid files is expected metadata, not a broken build — the +run says so in its `meta gen` warnings. Opt an entity in with: + +```jsonc +{ "layout.dataGrid": { "name": "default", "@columns": ["name", "email"] } } +``` + +Generated grid components are fully **controlled** — they need row-count and +sort/pagination/filter state on top of the column definitions — so pair the columns +generator with the grid-**hook** generator, which generates that state plumbing +instead of leaving you to hand-write it. Your client's reference fragment has the +generator names and a rendered example. diff --git a/agent-context-shipped/files/0a516068ccf344f8.md b/agent-context-shipped/files/0a516068ccf344f8.md new file mode 100644 index 0000000000..bc71a99054 --- /dev/null +++ b/agent-context-shipped/files/0a516068ccf344f8.md @@ -0,0 +1,377 @@ +# MetaObjects capability checklist (registry-grounded) + +The **exhaustive** list of every modelable MetaObjects capability, each with its one-line +audit hunt: *"find a hand-written shape the metadata already describes."* Every +`type.subtype` and every `@`-prefixed attribute named here is verbatim from the cross-port vocabulary in +`fixtures/registry-conformance/expected-registry.json` (the +`agent-context-capability-grounding.test.ts` guard fails the build if a line claims a token +the registry lacks). Work this checklist on every axis so coverage is exhaustive; respect +the **inline calibration flags** so a per-port gap is never scored as the adopter's fault. + +How to use a line: the capability is what the metamodel can express; the hunt is the +hand-written second-source-of-truth that should have been derived from it. Found one → +classify it (using the classification scheme in `SKILL.md`) and route the cutover to the right sibling skill. + +--- + +## Contents +- Object — `object.*` +- Field — `field.*` +- Source — `source.rdb` +- Relationship — `relationship.*` +- Identity — `identity.*` +- Index — `index.*` (non-unique retrieval) +- Origin — `origin.*` (derived fields — on projections AND entity read-views) +- Validator — `validator.*` +- View / Layout — `view.*`, `layout.*` +- Template — `template.*` (prompt pillar) +- Attr — `attr.*` +- Requirement — `requirement.*` (capability ledger) +- Common documentation attrs (any node) +- Cross-cutting + +## Object — `object.*` + +- **`object.entity`** (`@discriminator` / `@discriminatorValue` for STI/TPH) — hunt + hand-written entity classes, DTOs, and repositories whose field list duplicates a modeled + entity; hand-rolled single-table-inheritance / type-discriminator switches that + `@discriminator`+`@discriminatorValue` already model. +- **`object.value`** — hunt hand-authored request / command / payload value objects (no + identity, no source) that restate a modeled `value` shape. +- **`object.projection`** — hunt hand-written read-model DTOs and the SQL views behind them + that a derived read-only projection (extends + origin-derived fields) already describes. +- **`object.base`** — abstract base; hunt copy-pasted shared field blocks that should be an + abstract base + `extends` (see cross-cutting). + +## Field — `field.*` + +- **`field.string`** (`@maxLength`) — hunt hand-validated string-length checks the field + models. +- **`field.int` / `field.long` / `field.double` / `field.float`** — hunt ad-hoc numeric + columns / parsing the subtype already types. +- **`field.decimal`** (`@precision` / `@scale`) — hunt money or quantity stored as `float`/ + `double` (lossy); the decimal subtype carries exact precision/scale. +- **`field.boolean`** — hunt int-or-string flags standing in for a boolean. +- **`field.currency`** (`@currency`, + `view.currency` `@locale`) — hunt money as float, + hand `*100` / `/100` minor-unit math, or server-side `Intl.NumberFormat`; storage is + integer minor units, formatting is client-side. +- **`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. 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`) + already drives. +- **`field.map`** (`@valueType`) — hunt ad-hoc open-keyed key/value bags stuffed into a jsonb + column by hand. +- **Common field attrs** — `@column` (hand column-name mapping), `@default` (hand default + assignment), `@required` (hand presence checks), `@unique` (hand uniqueness), + `@mutability` (hand write-guards: `readOnly` for a column the DB/replication owns, + `writeOnce` for one set at create and never changed — hunt hand-written + "cannot be modified after creation" checks), `@filterable` / `@sortable` + (hand filter/sort allowlists), + `@dbColumnType` (hand native-type override), `@example` / `@instruction` (hand prompt + hints), `@xmlText` (hand XML-text mapping). The `@db.indexed` attr suppresses the + *`@filterable`-without-index* Loader warning (you assert the column is indexed by other + means); it is a dotted attr name but canonical JSON still authors it WITH the sigil: + `"@db.indexed": true`. +- **CALIBRATION — cut subtypes:** `field.byte`, `field.short`, `field.class` are + non-functional removed stubs. **Do NOT audit for them and never recommend them.** + +## Source — `source.rdb` + +- **`source.rdb`** (`@table`, `@schema`) — hunt hard-coded physical table/schema names that + diverge from the default naming the source models, AND any physical table/column/schema + name spelled as a literal outside its declaration — raw SQL, a hand-written repository, a + migration script, a body-to-column map (drift signature 11). Every port emits a per-object + names artifact from the declaration, so a literal is a second source of truth even when it + agrees with the naming strategy today. A typed ORM handle in its place is correct. **Check + the artifact is emitted at all before scoring the literals: on every port the selection IS + the complete list, documentation included — `generators: [...]` in `metaobjects.config.ts` + (TypeScript), `codegen/Generators.cs` (C#), a target's `generators` in + `metaobjects.config.yaml` (Python), `` in the pom (Java, Kotlin) — + so an existing project emits none and the un-wired generator is the finding FIRST** (no port + ships a default suite; ADR-0034 Amendments 2 and 9). **This entry is the physical-name INSTANCE of signature 11.** The rule that + generates the rest — and the reason an enum member compared as a bare string is NOT one — is + the Cross-cutting entry below. +- **`@kind` = `view` / `materializedView`** — hunt hand-written SQL views where an authored + read-only source belongs. Apply the **view-necessity test** (`drift-signatures.md`, signature 8): a + hand-written `CREATE VIEW` (or read-only SQL mirroring a read model) is a CODEGEN CANDIDATE when + its shape is expressible via `origin.passthrough` / `origin.aggregate` / + `origin.computed` / `origin.first` + `extends`. Route by shape: an entity's OWN columns plus an + extra (`SELECT o.*, …`) → an **entity read-view** (#214: a `@role: replica` view beside the + writable `table`); a subset / renamed / row-filtered exposure → an `object.projection` (row-scope + with an object-level `@filter`, #207) — so `meta migrate` emits the view DDL. A genuinely + irreducible body (recursive CTE, window function, set op) belongs in the `source.rdb` `@sql` + escape (#208), not a hand migration. Only an *undeclared* view is invisible to `meta verify --db`, + so this is audit-only. +- **`@kind` = `storedProc` / `tableFunction`** (`@parameterRef`) — hunt hand-called procs / + table functions that a modeled callable source with `@parameterRef` already describes. +- **`@sql`** (read-only `@kind` only; mutually exclusive with `@unmanaged`) — a hand-written SQL + body the tool REGISTERS, fingerprints, and drift-checks but never authors or parses (#208, + ADR-0043). The **escape valve for a genuinely irreducible view** origins can't express (recursive + CTE, window function, set op): carry the body here rather than in a hand-edited migration where it + goes accidentally unmanaged. Forbids `origin.*` children (two sources of truth); adopt a + pre-existing view with `meta migrate --allow adopt-view`. Hunt a hand-written irreducible + `CREATE VIEW` in a migration / `.sql` that should be carried in `@sql`. +- **`@unmanaged`** (any `@kind` incl. `table`; mutually exclusive with `@sql`) — marks a DB object + whose DDL is owned entirely elsewhere (Flyway / a hand-migration). `meta migrate` never creates, + drops, or drift-checks it; `verify --db` reports it as external (declared). Hunt an + externally-owned table/view the metadata silently omits instead of declaring `@unmanaged: true`. +- **`@role` = `primary`** (multi-source write-through) — hunt manual CQRS / write-through + wiring; exactly one `primary` source per object models it. +- **`source.base`** — abstract source base (no audit target of its own). + +## Relationship — `relationship.*` + +- **1:N / N:1** (`@cardinality`, `@objectRef`) — hunt hand-written FK joins and type-unsafe + finders the cardinality + target reference already model. +- **M:N** (`@through`) — hunt hand junction-table queries where `@through` + the junction's + two `identity.reference` children generate the traversal. +- **Self-join** (`@symmetric`, `@sourceRefField`) — hunt hand-coded self-join / graph queries + that an undirected (`@symmetric`) or directed (`@sourceRefField`) self-relationship models. +- **Referential actions** (`@onDelete`, `@onUpdate`) — hunt app-code cascade/null-out logic + the relationship's referential actions express. +- **`relationship.association` / `relationship.aggregation` / `relationship.composition`** — + hunt ownership/lifecycle semantics (delete-with-parent, shared vs owned) coded by hand + instead of by the relationship subtype. +- **`relationship.base`** — abstract base. + +## Identity — `identity.*` + +- **`identity.primary`** (`@generation`) — hunt hand-assigned primary keys / ID generation + the primary identity's `@generation` strategy models. +- **`identity.secondary`** (keys off `@fields` XOR `@expr` — exactly one, never both; physical + escapes `@using`/`@where`/`@orders`) — a UNIQUE alternate key (uniqueness is the type — the + legacy `@unique` attr was removed from it, and the same XOR rule as `index.lookup` applies here + because ADR-0040 puts uniqueness in the TYPE: a secondary identity IS a unique index); + hunt hand-rolled unique constraints or raw-SQL partial/functional unique indexes it models. +- **`identity.reference`** (`@references`, `@enforce`) — hunt hand-written FK constraints / + reference enforcement the reference identity already declares. + +## Index — `index.*` (non-unique retrieval) + +- **`index.lookup`** (keys off `@fields` XOR `@expr` — exactly one, never both; physical escapes `@using`/`@where`/`@orders`) — + a NON-unique retrieval index (uniqueness is what distinguishes it from `identity.secondary`); + hunt hand-created lookup / recency indexes (`CREATE INDEX …`) it models. + +## Origin — `origin.*` (derived fields — on projections AND entity read-views) + +- **`origin.aggregate`** (`@agg`, `@of`, `@via`, `@filter`) — `@agg`: `count`/`sum`/`avg`/`min`/`max` + (numeric reduces over `@of`), `any`/`all` (predicate quantifiers over `@filter`; `@of` forbidden), + `collect` (array rollup of `@of` into an `isArray` field; `@distinct`/`@orderBy` collect-only). + Any aggregate may be row-scoped with `@filter`. Hunt hand `COUNT`/`SUM`/`AVG`/`EXISTS`/`array_agg` + subqueries or in-app rollups a derived aggregate field models. +- **`origin.passthrough`** (`@from`, `@via`, `@convert`) — hunt denormalized-by-hand copied fields + that a passthrough origin pulls across a relationship. +- **`origin.computed`** (`@expr` — a closed `attr.expression` grammar) — hunt a hand-computed derived + scalar (a formula over other fields) a computed origin models. +- **`origin.first`** (`@of`, `@via`, `@orderBy`, `@filter`; `@orderBy` REQUIRED) — hunt a hand + argmax-style "one related row's column" projection — a `DISTINCT ON … ORDER BY` or correlated + `ORDER BY … LIMIT 1` — a first origin models (nullable). +- **`origin.base`** — abstract base. + +Distinct from the per-aggregate `@filter` above, an **object-level `@filter` on +`object.projection`** (#207) row-scopes the WHOLE view (outer `WHERE`) — hunt a hand-written +soft-delete / status / type view it models. + +## Validator — `validator.*` + +- **`validator.required` / `validator.length` / `validator.numeric` / `validator.array` / + `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.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). +- **`validator.base`** — abstract base. + +## View / Layout — `view.*`, `layout.*` + +- **`view.currency`** (`@locale`) — hunt hand-passed currency locale / `Intl.NumberFormat` + options the currency view models. **Cross-port-gated** (with `view.base`). +- **`layout.dataGrid`** (`@columns`, `@defaultSortField`, `@defaultSortOrder`, `@pageSize`) — + hunt hand-written grid column definitions + data hooks a data-grid layout generates. +- **CALIBRATION — TS/web-only:** the `view.*` widget subtypes are consumed only by TS/web + and are NOT in the cross-port registry — `view.text`, `view.textarea`, `view.date`, + `view.month`, `view.hotlink`, `view.image`, `view.dropdown`, `view.radio`, `view.checkbox`, + `view.number`, `view.password`, `view.hidden`, `view.web`. Every port LOADS them, so shared metadata that + carries them is valid in a backend port. The one exception is `view.password`: every port's generated + routes read it as a credential, so it is never returned and never written (see + "Credentials and excluded fields" in `docs/features/api-contract.md`). + Audit the other widgets only for TS adopters. Only + `view.base` / `view.currency` are cross-port-gated. + +## Template — `template.*` (prompt pillar) + +**A template subtype's axis is DIRECTION** (ADR-0052): `template.prompt` owns everything about +talking to a model — both the request and the reply — while `template.output` renders an +artifact for a person or a file and generates **no parser**. + +- **`template.prompt`** (`@payloadRef`, `@textRef`, `@responseRef`, `@responseFormat`, + `@promptStyle`, `@requiredSlots`, `@requiredTags`, `@maxTokens`, `@maxChars`, `@format`, + `@model`) — hunt prompt strings assembled inline in services, payloads built ad-hoc, + token/char budgets enforced by hand, and **hand-written parse-on-receipt**: a prompt + declaring `@responseRef` owns the inbound half, so the strict parser, the tolerant + `extract` mapper and the FR-010 output-format fragment are all generated from it. + (`@promptStyle` — the FR-010 output-format presentation, `guide` / `inline` / + `exampleOnly` — is on `template.prompt` ONLY; authoring it on `template.output` fails load + with `ERR_UNKNOWN_ATTR`.) +- **`template.output`** (`@kind` = `document` | `email`; `@textRef`, `@subjectRef`, + `@htmlBodyRef`, `@textBodyRef`, `@payloadRef`, `@format`, `@maxChars`, `@requiredTags`) — + **outbound only.** Hunt hand-built document/email rendering the output template + generated + render helper cover. It parses nothing: a parser here would be reading back text the system + just rendered and sent. +- **`template.toolcall`** (`@toolName`, `@payloadRef`, `@maxTokens`) — hunt hand-declared LLM + tool schemas a modeled tool call describes. +- **`template.base`** — abstract base. + +## Attr — `attr.*` + +- **`attr.properties`** — the sanctioned author key/value escape hatch; hunt ad-hoc metadata + stuffed into code comments / side-maps that could instead ride the properties bag. +- **`attr.filter`** — hunt hand-maintained preset filter definitions a modeled filter attr + holds. +- **`attr.class`** — binding facet (`field.class` binding); hunt hand-wired type-binding + facets. (`attr.base`, `attr.string`, `attr.int`, `attr.long`, `attr.double`, `attr.boolean` + are the value-type primitives behind typed attrs — not direct audit targets.) +- **Custom-provider extension point** (`attr.properties` is the one-off escape hatch; + `template.toolcall` is the historical register→extend precedent) — hunt a *recurring, + closed* variant set hand-coded as parallel modules (channels / providers / export targets) + that a project-registered subtype with a closed variant discriminator + a small owned + generator would own. Apply the ADR-0037 ordered test before proposing; advisory (VOCAB + CANDIDATE); see `vocabulary-hygiene.md` "New-vocabulary OPPORTUNITY". + +## Requirement — `requirement.*` (capability ledger) + +The only axis here whose hunt is not "hand-written code the metadata describes" but +**hand-written PROSE that claims something about the code and nothing checks.** Two +subtypes with opposite polarity: `requirement.functional` is checked for existence (`meta verify` +warns when nothing implements it, and fails when a node it names is gone); +`requirement.architectural` is checked for universality (`meta verify` fails a live policy applied +to nothing, and does not check that each claimed node complies). + +- `requirement.functional` — `@statement`, `@status`, `@level`, `@counterexample` — hunt a + `CAPABILITIES.md`, a features table in a README, a `docs/status/` tree, or a spreadsheet + that lists what the system does and how done each item is. Prose goes stale silently; a + declared requirement is a node the loader resolves and `meta verify` reports on. +- `requirement.architectural` — `@statement`, `@status`, `@counterexample`, optional `@level` — + hunt a conventions doc, a lint rule with no enforcement, or an ADR whose ruling is + restated in review comments ("we always do X"). `@level` is optional here on purpose: + absent keeps the flat object-independent form, present opts into a taxonomy. +- `@implementedBy` — hunt the mapping from "capability" to "the code that provides it" + living only in someone's head, a wiki table, or a comment. This is the load-bearing + attribute: it is a REFERENCE the loader resolves, so a rename or deletion that + invalidates the claim is caught, where prose would not be. + - **L4 binds an object; L5 binds one MEMBER of it, as a dotted `pkg::Owner.member` path.** + Mismatches are errors at both levels (`ERR_REQUIREMENT_L5_NOT_MEMBER` / + `ERR_REQUIREMENT_L4_NOT_OBJECT`) and the fix is to move the entry to the other level, + not to change the ref. Reach for L5 for a rule about ONE column — the kind currently + recorded only as a comment above a field. +- `@disposition` (`accepted` / `deferred`) + `@trackedBy` — hunt a known-and-tolerated gap + recorded as a TODO, or a ticket number in a comment. **ABSENT disposition means UNDECIDED**, + which is the point: a gap nobody has ruled on reads differently from one deliberately + accepted. +- **The doc slots behave differently on this node type** — do not audit them by the generic + rule below. `title` is CHARTERED here (a requirement's `name` is an identifier, so the label + lives in `title`) and is **rendered** by `meta gen`'s `requirementsFile()`, heading each + entry after its dotted path; `summary` is INERT (nothing reads it, and `@statement` is already the required + one-liner) and `meta verify` warns on one. So an absent `summary` is correct, a populated + one is the finding, and a populated `title` is correct. +- **CALIBRATION — entirely opt-in and warning-only where it counts.** A project declaring no + `requirement.*` nodes sees no diagnostics at all, and object coverage ("entities claimed + by nothing") ships as a WARNING deliberately — a real estate carrying one requirement will + report most of itself unclaimed on day one. Do NOT score an absent ledger as a defect; + score the hand-written prose it would replace. + +## Common documentation attrs (any node) + +- `@description`, `@title`, `@summary`, `@notes`, `@deprecated`, `@replacedBy`, `@seeAlso`, + `@aliases` — hunt weak/absent generated docs and deprecation tracked only in code comments; + these doc attrs flow into JSDoc / XML-doc / Postgres `COMMENT` / Mermaid doc-gen, and + `@deprecated` / `@replacedBy` model lifecycle the codebase tracks by hand. (`@notes` is the + internal-only rationale slot — never emitted to user-facing doc-gen.) + +## Cross-cutting + +- **Open JSON bag vs a shape the readers already know (drift signature 12).** `field.string` + + `@dbColumnType: jsonb` is the SANCTIONED untyped-column escape hatch (emits `unknown`, + gated by `fixtures/api-contract-conformance/jsonb/`) — never a finding on sight. It is a + finding only when the code knows the shape. **Check the WRITER first** — the function writing + the column declares the type (`related_memory_ids: list[str]`, `vector_scores: list[float]`, a + serialized DTO); a reader-only hunt under-counts badly, because raw-SQL JSON paths are the + rarest way to consume jsonb. Reader tells second: fixed-key `->>'key'` reads, casts, typed + parsing (`model_validate` / `readValue` / `decodeFromString`), a hand validator. **Commonest + sub-case, and mechanical: a writer typed `list[str]` / `string[]` / `List` means the base + subtype + `isArray: true`, never an object and never an open bag** — a plural name plus a typed + collection is the whole test. A `*Json` suffix is a second free tell. Remedy ladder by the writer's + type: `list[X]` → base subtype + `isArray`; `dict[str, X]` with a known X → **`field.map` + + `@objectRef`** (emits `.$type>()` / `z.record`); a serialized DTO → `object.value` + + `field.object @objectRef @storage: jsonb`; only `dict[str, Any]` with no key-pinning readers stays + open. Every typed rung yields a TYPED HANDLE — Drizzle `.$type()` + Zod, a Pydantic model, a + typed Exposed jsonb codec — never a JSON string the consumer casts. Remedy: an `object.value` + + `field.object` `@objectRef` `@storage: jsonb` — the column stays jsonb. Not a finding for a + pass-through bag, a third-party/LLM raw response, or an array of scalars (`isArray`). + +- **A metadata-derived value spelled a second time (drift signature 11 — one rule, not two halves).** + A literal in non-generated code or config that must EQUAL a value the metadata declares or a + generator derives is a second spelling. The constants to reference: `Names` (physical + table / schema / column / index names) on all five ports; on TypeScript also the entity module's + `$entity` / `$table` / `$path` and per-field `name` / `label` / `view` / `htmlType` / `rules` / + `options`, with the browser-safe `.meta.ts` twin, whose docblock says to use them INSTEAD + of magic strings — the other four ports answer that surface with a generated typed handle + (Pydantic attribute, EF property, Exposed `Column`), already the gold standard. **Hunt VALUE-first** + — grep the non-generated tree, config included, for the values those artifacts carry, and trace each + hit to its consumer — and **score only a site regeneration would not break.** Resolved references + (typed handles, property access, typed filter keys, enum members narrowed by the generated union — + 332 literals, 0 findings on one estate) and values the metadata does not own (a page route or link — + 11 apparent hits, 0 real; the `/api` deployment prefix, which is `baseUrl` and deliberately not a + constant) are exempt as consequences of that rule, not as a list. Raw SQL, the API resource path and + the hand-built form are the three commonest shapes, never the set; a GraphQL field, a queue topic, a + cache key or a `COPY` header scores by the same rule. Procedure, the emitted-vs-adopted ratio and the + deferral rule: `drift-signatures.md` signature 11. + +- **`extends`** (any depth, cross-package `::`) — hunt copy-pasted base-entity field blocks + that should be an abstract base inherited via `extends` (the inheritance mechanism; + `origin.*` never inherits). +- **Filter + sort + pagination REST layer** — hunt hand-written query parsing, `LIMIT`/ + `OFFSET` pagination, total-count queries, and filter/sort handling the generated CRUD layer + (9 filter operators `eq/ne/gt/gte/lt/lte/in/like/isNull` + sort + `?limit=N&offset=N` + count) + already provides. + - **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.** The richer list surface (`?search=`, explicit + `filter[or][N]` / `filter[and][N]` combinators, leading-wildcard gating; ADR-0068) passes in + TypeScript 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 + that generated file). **Python** + still hand-wires the FastAPI router around a generated `APIRouter` (relationship / + 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 + `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 — registered, nothing generated yet:** 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`, but no generator emits from them yet. Their absence 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 + `devDependencies`). Trust the port docs + `meta gen --list`, not stale upstream prose + (e.g. the out-of-date "hand-write the Spring controller" note — controllers ARE generated). diff --git a/agent-context-shipped/files/0b3cd53eedd718e2.md b/agent-context-shipped/files/0b3cd53eedd718e2.md new file mode 100644 index 0000000000..066fdb050c --- /dev/null +++ b/agent-context-shipped/files/0b3cd53eedd718e2.md @@ -0,0 +1,96 @@ +# Working with MetaObjects in this project + +> Stack: java server, no client. +> +> Generated by MetaObjects (refresh: `meta init --refresh-docs`). Put project notes in your +> root `AGENTS.md` or `CLAUDE.md`, not here: this file is regenerated. + +The metadata (`metaobjects/` unless `.metaobjects/config.json` says otherwise) is the source of +truth. Code, schema and migrations are generated from it and are disposable. + +## Start here: the whole loop, in order + +### Java: generate with `mvn metaobjects:generate` + +1. **Config.** The `metaobjects-maven-plugin`'s `` in `pom.xml` is the generator + list, one `` each, under `` pointing at the metadata. + Nothing is generated until it is listed; the build names any generator a listed one needs. + Which classes to list (the Spring REST tier, requirement tests, API docs) is in the + `metaobjects-codegen` skill's `references/java.md`. +2. **Generate.** `mvn metaobjects:generate`. `mvn metaobjects:eject -Dnames= -Dport=java` + copies a generator to change what it emits. + +### Schema (every stack: the Node `meta` CLI owns it, so Java, Kotlin, C#, Python and Rust projects need Node too) + +Never hand-write DDL, and never `ALTER` a live database by hand. + +- First migration (needs a reachable, empty database): + `npx meta migrate --from-db --db --dialect --slug init` writes + `.metaobjects/migrations/-init/up.sql` and `down.sql`. +- At boot or deploy: `npx meta migrate apply-pending --db `. +- A later change: edit the metadata, regenerate, then + `npx meta migrate --dialect --slug ` (offline, from the committed snapshot). + A renamed field needs `--rename-column .=` (an object: + `--rename-table =`) to keep its data. A destructive change is refused until you + allow its kind by name: `--allow drop-check` for a changed enum, `--allow drop-column` only + when the data should go. + +### Requirements, when the metadata declares `requirement.*` nodes + +A commit that changes behaviour updates them in the same commit: `@status: live` once a claim +is built (never before), a new node for new behaviour. + +### Before you call it done + +- `mvn metaobjects:verify` (the generated code and the requirements). +- `npx meta verify --db ` (the live schema matches the metadata). + +Commit the metadata, the generated code, `.metaobjects/migrations/` and +`.metaobjects/.gen-state/.hashes/`. + +## Calling the generated REST API + +When the project serves the generated routes (any port): + +- Filter as `?filter[][]=`: `?filter[status][eq]=active`, never + `?status=active` (TypeScript refuses that with 400; the other ports ignore it). Operators: `eq`, `ne`, `isNull` (`true`/`false`), `in` (comma list, at most 100), `like` + (case-sensitive, `%` and `_`), `gt`, `gte`, `lt`, `lte`. Filters AND; only `@filterable` + fields filter. +- `?sort=:asc|desc`, `?limit=N&offset=N`; `withCount=1` returns `{"rows", "total"}`. + Always send `limit`: without it the project's `api.pagination.defaultLimit` applies, or with + none set TypeScript and C# return every row, the other ports 50; above `maxLimit` is 400. +- `PUT` is the same partial update as `PATCH`. Send only declared fields: an undeclared key is + 400 `unknown_fields` (unless `api.unknownFields` is `drop`). +- Errors are `{"error": ""}`: 400 for validation (`issues` lists each problem) and for + a bad filter or sort (`invalid_filter_field`, `_op`, `_value`, `invalid_sort`, each naming + `field`), 404 `not_found`, 409 for a unique or foreign-key conflict. + +## Rules + +- What the metadata describes is generated, never hand-written (tables, types, validators, + foreign keys, schema, migrations). Hand-write only what it cannot describe, on top. +- Never hand-edit generated output: change the metadata and regenerate. Output wrong for you, or + broken? Fix the generator: eject it and it is yours, no permission needed, nothing to wait on. +- Never spell a table or column name as a string; use the generated table or names constants. +- Wire a generator only for output you will import. +- An LLM prompt in a project that declares `template.prompt` is a declared template + (`metaobjects-prompts`); a grouped total or report view is an `object.report` + (`metaobjects-authoring`). Open the skill before writing either by hand. +- Never invent metadata vocabulary. Search it: `npx meta types `, and + `npx meta types . --detail` for one construct's valid attributes. +- Metadata nodes are fused-key maps, `{"field.string": {"name": "email"}}`. Attribute names are + unique within a node, and package paths use `::`. + +## Going deeper + +The loop above needs no skill. For less common work load a `metaobjects-*` skill by name, or open +`.claude/skills//SKILL.md` if your assistant does not load skills: `metaobjects-authoring` +(unusual shapes, reports, adopting existing code), `metaobjects-codegen` (owning or writing a +generator), `metaobjects-runtime-ui` (REST routes, the web client), `metaobjects-prompts` (LLM +prompts), `metaobjects-verify` (migration edge cases, drift, upgrades), `metaobjects-audit` (an +adoption review). Each names the one reference page to open. + +`meta init --refresh-docs` regenerates this file and the skills, so keep project guidance in +the root `AGENTS.md` or `CLAUDE.md` (or copy a skill to a new name). A refresh never overwrites a +file you edited; it writes `.new` beside it, which you merge into `` and delete. +Never `--force` a refresh over local edits. diff --git a/agent-context-shipped/files/0de6aba8a666dd9d.md b/agent-context-shipped/files/0de6aba8a666dd9d.md new file mode 100644 index 0000000000..930c6e8ab7 --- /dev/null +++ b/agent-context-shipped/files/0de6aba8a666dd9d.md @@ -0,0 +1,115 @@ +# Working with MetaObjects in this project + +> Stack: python server, react client. +> +> Generated by MetaObjects (refresh: `meta init --refresh-docs`). Put project notes in your +> root `AGENTS.md` or `CLAUDE.md`, not here: this file is regenerated. + +The metadata (`metaobjects/` unless `.metaobjects/config.json` says otherwise) is the source of +truth. Code, schema and migrations are generated from it and are disposable. + +## Start here: the whole loop, in order + +### Python: generate with `metaobjects gen` + +1. **Config.** `metaobjects.config.yaml` names each target's `outDir` and its generators. Nothing + is generated until it is listed: + + ```yaml + targets: + app: + outDir: generated + generators: [entity, names] # Pydantic models + physical-name constants + ``` + + `routes` and `filter-allowlist` add FastAPI routers over a repository `Protocol` you + implement; `requirement-tests` writes one pytest file per package of requirements; + `api-docs` writes `api/python/AGENT-API.md`. `metaobjects gen --list` is the catalog. + Install what the output imports: `pip install "pydantic[email]>=2" fastapi`. +2. **Generate.** `metaobjects gen`. `metaobjects eject ` copies a generator into the repo + to change what it emits. + +### Web client: generated by the Node `npx meta gen` + +The client tiers are generators in `metaobjects.config.ts`, whatever the backend: `formFile()` +from `@metaobjectsdev/codegen-ts-react`, `tanstackQuery()` and `tanstackGrid()` from +`@metaobjectsdev/codegen-ts-tanstack`, with the runtime packages `@metaobjectsdev/react` and +`@metaobjectsdev/tanstack`. Wrap the app in ``: +`baseUrl` is where the server mounts its routes, and leaving it out drops that prefix from every +hook without an error. The `metaobjects-runtime-ui` skill has the detail. + +### Schema (every stack: the Node `meta` CLI owns it, so Java, Kotlin, C#, Python and Rust projects need Node too) + +Never hand-write DDL, and never `ALTER` a live database by hand. + +- First migration (needs a reachable, empty database): + `npx meta migrate --from-db --db --dialect --slug init` writes + `.metaobjects/migrations/-init/up.sql` and `down.sql`. +- At boot or deploy: `npx meta migrate apply-pending --db `. +- A later change: edit the metadata, regenerate, then + `npx meta migrate --dialect --slug ` (offline, from the committed snapshot). + A renamed field needs `--rename-column
.=` (an object: + `--rename-table =`) to keep its data. A destructive change is refused until you + allow its kind by name: `--allow drop-check` for a changed enum, `--allow drop-column` only + when the data should go. + +### Requirements, when the metadata declares `requirement.*` nodes + +A commit that changes behaviour updates them in the same commit: `@status: live` once a claim +is built (never before), a new node for new behaviour. + +### Before you call it done + +- `metaobjects verify` (the generated code and the requirements; `--codegen` is its default). +- `npx meta verify --codegen` (the generated web client). +- `npx meta verify --db ` (the live schema matches the metadata). + +Commit the metadata, the generated code, `.metaobjects/migrations/` and +`.metaobjects/.gen-state/.hashes/`. + +## Calling the generated REST API + +When the project serves the generated routes (any port): + +- Filter as `?filter[][]=`: `?filter[status][eq]=active`, never + `?status=active` (TypeScript refuses that with 400; the other ports ignore it). Operators: `eq`, `ne`, `isNull` (`true`/`false`), `in` (comma list, at most 100), `like` + (case-sensitive, `%` and `_`), `gt`, `gte`, `lt`, `lte`. Filters AND; only `@filterable` + fields filter. +- `?sort=:asc|desc`, `?limit=N&offset=N`; `withCount=1` returns `{"rows", "total"}`. + Always send `limit`: without it the project's `api.pagination.defaultLimit` applies, or with + none set TypeScript and C# return every row, the other ports 50; above `maxLimit` is 400. +- `PUT` is the same partial update as `PATCH`. Send only declared fields: an undeclared key is + 400 `unknown_fields` (unless `api.unknownFields` is `drop`). +- Errors are `{"error": ""}`: 400 for validation (`issues` lists each problem) and for + a bad filter or sort (`invalid_filter_field`, `_op`, `_value`, `invalid_sort`, each naming + `field`), 404 `not_found`, 409 for a unique or foreign-key conflict. + +## Rules + +- What the metadata describes is generated, never hand-written (tables, types, validators, + foreign keys, schema, migrations). Hand-write only what it cannot describe, on top. +- Never hand-edit generated output: change the metadata and regenerate. Output wrong for you, or + broken? Fix the generator: eject it and it is yours, no permission needed, nothing to wait on. +- Never spell a table or column name as a string; use the generated table or names constants. +- Wire a generator only for output you will import. +- An LLM prompt in a project that declares `template.prompt` is a declared template + (`metaobjects-prompts`); a grouped total or report view is an `object.report` + (`metaobjects-authoring`). Open the skill before writing either by hand. +- Never invent metadata vocabulary. Search it: `npx meta types `, and + `npx meta types . --detail` for one construct's valid attributes. +- Metadata nodes are fused-key maps, `{"field.string": {"name": "email"}}`. Attribute names are + unique within a node, and package paths use `::`. + +## Going deeper + +The loop above needs no skill. For less common work load a `metaobjects-*` skill by name, or open +`.claude/skills//SKILL.md` if your assistant does not load skills: `metaobjects-authoring` +(unusual shapes, reports, adopting existing code), `metaobjects-codegen` (owning or writing a +generator), `metaobjects-runtime-ui` (REST routes, the web client), `metaobjects-prompts` (LLM +prompts), `metaobjects-verify` (migration edge cases, drift, upgrades), `metaobjects-audit` (an +adoption review). Each names the one reference page to open. + +`meta init --refresh-docs` regenerates this file and the skills, so keep project guidance in +the root `AGENTS.md` or `CLAUDE.md` (or copy a skill to a new name). A refresh never overwrites a +file you edited; it writes `.new` beside it, which you merge into `` and delete. +Never `--force` a refresh over local edits. diff --git a/agent-context-shipped/files/0ee567e8d039312d.md b/agent-context-shipped/files/0ee567e8d039312d.md new file mode 100644 index 0000000000..e859076180 --- /dev/null +++ b/agent-context-shipped/files/0ee567e8d039312d.md @@ -0,0 +1,218 @@ +# Requirements — what `meta verify` checks + +This project declares `requirement.*` nodes, so `verify` checks them. **There is no +subverb**: requirements are metadata, so they are checked on *every* `meta verify` run. + +## Contents +- Which command runs the gate +- The split, and why it matters when you read a failure +- A load failure on RETIRED vocabulary — run `meta upgrade`, do not hand-sweep +- The status asymmetry — the one that surprises people +- Exit codes +- The strict switch — `--require-implementers` +- Keeping the ledger current +- The error codes, and the fix for each +- The authoring lint — a second section, never an error +- `verify` does not look at your tests +- What a green run does NOT prove + +## Which command runs the gate + +Every port's `verify` runs the same gate, with the same codes, severities and message +text (a shared corpus pins them). Run the one for the project's server language: + +| port | command | +|---|---| +| TypeScript | `meta verify` | +| Python | `metaobjects verify` | +| Java, Kotlin | `mvn metaobjects:verify` (one goal for both) | +| C# | `dotnet meta verify` | + +The gate is core: it is not a generator and cannot be ejected or replaced. What differs +by port is the **authoring lint** further down this page, which only the Node `meta verify` +prints. This page writes `meta verify` throughout; read it as the port's own command. + +## The split, and why it matters when you read a failure + +| | owns | +|---|---| +| **loader** | `@status` enum, required attrs, child rules, levels — unconditional | +| **`verify`** | `@implementedBy` resolution — **severity depends on `@status`** | + +A typo'd `@status` fails the **load** ("failed to load metadata"), before verify runs. If you +see that, no other diagnostic in the run is trustworthy — fix it first and re-run. + +## A load failure on RETIRED vocabulary — run `meta upgrade`, do not hand-sweep + +`@status` is not the only way the load fails before any of this runs. **0.24.0** retired +`@violation` (→ `@counterexample`) and `@verifiedBy`; **0.24.1** made an index key `@fields` +**XOR** `@expr`, so a node declaring both is now `ERR_INVALID_INDEX`. **0.24.2 reversed half +of the 0.24.0 cut**: `abandoned` and `superseded` become **`@status: retired`**, and +`@supersededBy` is registered again — this time as a reference the loader resolves. There is no deprecation shim for any of them — +the registry is sealed (ADR-0023), so a legacy document does not load at all and every check on +this page is unreachable until it does. + +``` +meta upgrade # previews every rewrite; writes nothing +meta upgrade --apply # makes them +``` + +It rewrites from the same table the loader's error text is generated from, so the fix you are +told about and the edit the tool makes cannot drift apart. It fixes only what has one correct +answer and **refuses the rest, exiting non-zero** — a partial migration can never be recorded +as finished by CI. Two refusals are expected on a real ledger and both are yours to decide: + +- **`@status: abandoned` / `superseded` are no longer refused** — they rewrite to `retired`, + and the same run drops the `@implementedBy` that a retired entry may not carry. This was the + canonical judgement case in 0.24.0; FR-039 made it determinate. +- **`origin.collection`.** Retired to `origin.aggregate @agg: collect`; the attribute sets + differ, so the tool will not guess. + +`@fields` beside `@expr` **is** rewritten, and the survivor is not a coin toss: that pair loaded +before 0.24.1 with `@fields` silently discarded, so the index already in your database is the +expression one. `upgrade` drops `@fields` — which reproduces the object that exists and emits no +DDL change. Do not hand-pick the other survivor; that invents a new index and migrates live data. + +## The status asymmetry — the one that surprises people + +The **same** unresolved `@implementedBy` reference is: + +- an **error** on `live` / `partial` — the model moved and the requirement is stale; +- **allowed** on `planned` — those nodes do not exist YET. That is + the entry doing its job, not drift. + +So on a `planned` entry a dangling reference is the entry doing its job, not drift — do not +"fix" it by deleting the reference, or you delete the plan. + +## Exit codes + +| situation | exit | +|---|---| +| clean tree, or no `requirement.*` nodes at all | 0 | +| dangling `@implementedBy` on `live`/`partial` | 1 | +| the same reference on `planned` | 0 | +| `@implementedBy` above the L4 link floor | 1 | +| live `requirement.architectural` claimed by nothing | 1 | +| an entity no requirement claims | 0 (warning) | +| a `live`/`partial` functional requirement nothing implements | 0 (warning); **1 under the strict switch** | + +## The strict switch — `--require-implementers` + +`WARN_REQUIREMENT_NOTHING_IMPLEMENTS` (a `live` or `partial` functional requirement where +neither it nor anything nested under it names a node) is a warning by default. A project +whose ledger has caught up with its links can make it fail the build: + +| port | flag | environment | +|---|---|---| +| TypeScript | `meta verify --require-implementers` | `META_REQUIRE_IMPLEMENTERS=1` | +| Python | `metaobjects verify --require-implementers` | `META_REQUIRE_IMPLEMENTERS=1` | +| Java, Kotlin | `mvn metaobjects:verify -Dmeta.verify.requireImplementers=true` | `META_REQUIRE_IMPLEMENTERS=1` | +| C# | `dotnet meta verify … --require-implementers` | `META_REQUIRE_IMPLEMENTERS=1` | + +It raises that one finding to an error and **keeps its code**. Every other warning stays a +warning. If CI went red on this code, check whether the switch is set before treating it +as a new defect: the fix is to add the `@implementedBy` link (or drop the entry to +`planned`), not to unset the switch. + +Once the ledger is clean, set the switch where the project already runs `verify`: its verify +script, CI job or pre-push hook. Until then a stale `live` claim is only a warning that +nobody reads. + +## Keeping the ledger current + +`verify` proves the ledger's links resolve, not that the ledger is current. A commit that +adds, changes or removes behaviour updates the ledger in the same commit: the new or changed +claim, its `@status` and its `@implementedBy`. If the commit should not touch the ledger, the +commit message says why. + +## The error codes, and the fix for each + +Match on the stable `code`, never the message text (ADR-0009). The runtime messages already +name the remedy; this table exists so you can act on one without re-deriving the rule. + +| code | what it means | fix | +|---|---|---| +| `ERR_REQUIREMENT_DANGLING_REF` | an `@implementedBy` ref does not resolve in the loaded model, on a status that requires live nodes | the model moved and the claim is stale — repoint the ref, or change the status if the capability really went away. **Check the ref is not merely unloaded**: a source missing from `sources` makes a live node look deleted. | +| `ERR_REQUIREMENT_L5_NOT_MEMBER` | an L5 entry's ref names an OBJECT | move the entry to **L4**, or repoint to a member as `pkg::Owner.member`. Moving the level is usually right — the ref is usually what you meant. | +| `ERR_REQUIREMENT_L4_NOT_OBJECT` | an L4 entry's ref names a MEMBER | the symmetric case — move the entry to **L5**, or repoint at the owning object. | +| `ERR_REQUIREMENT_LINK_ABOVE_FLOOR` | `@implementedBy` on an L1–L3 node | L1–L3 are problem-domain altitude and never reference the model. Push the claim down to the L4/L5 child that actually carries it. | +| `ERR_REQUIREMENT_ARCH_NO_IMPLEMENTERS` | a `live`/`partial` `requirement.architectural` that nothing implements | a policy declared and applied to nothing. Claim the nodes it governs, or drop it to `planned` — which is exempt, because it is not applied yet by definition. | +| `ERR_REQUIREMENT_LEVEL_NESTING` | a node's `@level` disagrees with the level of the parent it nests under | nesting IS the hierarchy. Move the node to the right parent rather than editing the level to match where it happens to sit. | +| `ERR_REQUIREMENT_BAD_LEVEL` | `@level` is not an integer inside the allowed range | levels are L1–L5 and nothing else. | +| `ERR_REQUIREMENT_RETIRED_HAS_IMPLEMENTORS` | a `@status: retired` entry declares `@implementedBy` | a retired capability has no implementation by definition. Delete the attribute and put what used to implement it in `notes`; if the nodes are still there, the capability is `live` or `partial`, not retired. | +| `ERR_REQUIREMENT_SUPERSEDED_BY_NOT_RETIRED` | `@supersededBy` on a status other than `retired` | it names what REPLACED a withdrawn capability, so on a live one there is nothing for it to say. | +| `ERR_MISSING_REQUIRED_ATTR` | a required attr is absent | `@statement`, `@status` and `@counterexample` are required on both subtypes; `@level` is required on `functional` and optional on `architectural`. | +| `ERR_BAD_ATTR_VALUE` | a closed-enum attr has an unknown value | `@status` and `@disposition` are enforced by the LOADER, so a typo fails the load in every port rather than passing in some. | + +**A note on the L4/L5 pair.** They are enforced at the same site and fail for opposite +reasons, so reading only the code you hit can send you the wrong way. The question is not +"is this ref valid?" — usually it is — but "does the LEVEL match the shape of the ref?" + +## The authoring lint — a second section, never an error + +The Node `meta verify` also prints an **authoring lint** under its own heading, after the +gate's own warnings. It is TypeScript-only: `metaobjects verify`, `mvn metaobjects:verify` +and `dotnet meta verify` run the gate above and never print these codes, so on those ports +a clean run says nothing about them. + +``` +meta verify — requirements: 6 authoring warning(s) (advisory — does not fail the build): +``` + +Read it as a different claim from everything above. The gate says the ledger **disagrees with +the model**; the lint says it agrees but **records less than its author thinks**. Every finding +is a warning and none can change the exit code, so a lint-only run is a passing run. + +| code | what it means | fix | +|---|---|---| +| `WARN_REQUIREMENT_NAME_NOT_ADDRESSABLE` | the `name` holds a character that breaks the dotted path or the generated stub filename | rename it. A `.` is the common one and the worst: `Orders.Recorded` and `Orders` containing `Recorded` produce the **same** path, so the address stops identifying one node. | +| `WARN_REQUIREMENT_NAME_READS_AS_PROSE` | the `name` is a sentence | the name is an address — make it an identifier and put the prose in `@statement`. | +| `WARN_REQUIREMENT_NAME_RESTATES_STATEMENT` | `name` and `@statement` say the same thing | the claim is written twice. Keep `@statement` (every surface reads it) and shorten the name. | +| `WARN_REQUIREMENT_PROSE_EMPTY` | `@statement` or `@counterexample` is present but blank | the loader requires the attr to EXIST, never to say anything. Write the sentence, or delete the entry. | +| `WARN_REQUIREMENT_PROSE_DUPLICATED` | `description` repeats `@statement` (whole, or as its opening sentence), or `@counterexample` does | `@statement` is already the description. `description` holds the SCOPE; drop it entirely if the scope is obvious. | +| `WARN_REQUIREMENT_INERT_DOC_SLOT` | `summary` is set on a requirement | `@statement` is already the required one-line sentence, so a summary can only repeat it, and nothing reads it. Delete it. (`title` is NOT flagged — it is chartered as the entry's label.) | +| `WARN_REQUIREMENT_TITLE_IS_AN_ID` | `title` holds a catalogue or ticket id | a title is a noun phrase and an id is not a name. **Split** it — the id to `@trackedBy`, the phrase stays the title. Do not move the whole string; that throws the label away. | + +Findings from both sections are addressed by the requirement's **dotted path**, never its +bare name — two branches of a ledger may reuse a name, so a bare one can be ambiguous. + +Mute the lint with `--no-requirement-lint` or `META_NO_REQUIREMENT_LINT=1`. That silences the +advisory half **only** — the gate above still runs and can still exit 1. + +Two deliberate silences. The lint reports only **exact** repeats, never a paraphrase — a +similarity threshold on prose produces findings you can argue with. And it never judges +whether a statement is true or a counterexample sufficient; those are the judgements the +ledger exists to record. + +## `verify` does not look at your tests + +It used to. `@verifiedBy` asked you to name a test, and `verify` checked that the **name** +occurred somewhere in your test sources. That is existence evidence, never proof — an audit of +one real 19-name ledger opened every named test and found **4 that did not verify their +claim**: one matched a comment, one a dependency-injection key, one a real test of a +*different* claim, and one a test of the entry's output where the claim was about its source +text. `verify` reported zero errors throughout. The author picks the string, so the cheapest +way to satisfy the check is to find any name that already exists. + +The attribute is retired. Tying a requirement to a test is the job of a generator that emits +the test **from** the requirement, so the link is structural rather than a name someone chose. +Every port ships one, `requirement-tests` (see the codegen skill's reference for the +project's language). `verify` still never reads test results: the codegen drift gate +(`verify --codegen`) proves the generated tests match the ledger, a live test with nothing +behind it fails in the project's own test run, and a generated test that passes proves its +witness ran, not that the witness tests the claim. + +## What a green run does NOT prove + +It proves **referential integrity**: statuses parse, levels are in range, links sit at or +below the floor, references resolve. + +It cannot prove a status is **true**, or that a node genuinely implements the requirement +claiming it. No test can. That judgement is yours. + +Coverage is also narrower than the name suggests: it is checked at **entity grain only** — +`object.value` and `object.projection` are exempt, and fields, views, validators and +identities are never required to be claimed. Green means "every entity is claimed by +something", not "every node is described". + +Full reference: the repo's `spec/capability-ledger.md`. diff --git a/agent-context-shipped/files/0fe543fe1b3c9b3c.md b/agent-context-shipped/files/0fe543fe1b3c9b3c.md new file mode 100644 index 0000000000..92b5d47980 --- /dev/null +++ b/agent-context-shipped/files/0fe543fe1b3c9b3c.md @@ -0,0 +1,244 @@ +# TypeScript parser-on-receipt + +For every RESPONDING `template.prompt` in your metadata — one declaring +`@responseRef` — the `outputParser()` generator (from +`@metaobjectsdev/codegen-ts/generators`) emits a **typed parser** that validates a +model's reply against that shape. ADR-0052: the tier binds `@responseRef`, never +`@payloadRef` (which types the request the prompt renders outbound), and a +`template.output` gets no parser at all. This is the receive side; codegen emits **no** +provider/LLM-call layer — you compose the call yourself. + +## Contents +- Wire the generator +- What it emits +- The response-format prompt fragment (FR-010) +- The three-step consumer pattern +- Recommended LLM caller (bring-your-own) +- Drift gate +- See which fields a template consumes + +## Wire the generator + +```ts +// metaobjects.config.ts +import { defineConfig } from "@metaobjectsdev/cli"; +// `meta init` wires nothing (ADR-0034 Amendment 2). Each generator is imported from the +// package to run it as shipped. The parser's reply type is the @responseRef value +// object's own interface, which `entity` emits, so `entity` has to be in the run. +// (On a 1.0.x install the first three have no package export: `meta eject entity queries +// barrel` and import them from ./codegen/generators/ instead.) +// +// Any of these can be OWNED instead: `meta eject prompt-render output-parser` copies them +// into ./codegen/generators/ and prints the local import to swap in. Either way the +// render and parse ENGINES they call stay in the package. +import { + entityFile, queriesFile, barrel, promptRender, outputParser, +} from "@metaobjectsdev/codegen-ts/generators"; + +export default defineConfig({ + outDir: "src/generated", + generators: [ + entityFile(), queriesFile(), barrel(), + promptRender(), // render() per template.prompt (the send side) + outputParser(), // parse*/safeParse* per responding template.prompt (the receive side) + ], +}); +``` + +`outputParser({ outDir: "src/generated/outputs", target: "default" })` are the +options. + +## What it emits + +Per responding `template.prompt` (say named `NpcReview`, `@responseRef: +"NpcResponse"`), `meta gen` writes `NpcReview.response.ts` with a Zod schema + a dual +API, named after the TEMPLATE. The strict tier is JSON-only — an `@responseFormat: xml` +reply gets the tolerant `extract` and no `parse`/`safeParse`: + +```ts +import { z } from "zod"; +import type { NpcResponse } from "./NpcResponse.js"; // the value object's own interface (entityFile) + +const NpcReviewSchema = z.object({ + name: z.string(), + level: z.number().int(), + role: z.enum(["tank", "healer", "dps"]), // field.enum → its declared members + notes: z.string().optional(), // not @required → .optional() +}); + +export type NpcReviewValidationError = z.ZodError; + +/** Throws ZodError on bad input. */ +export function parseNpcReview(text: string): NpcResponse { /* ... */ } + +/** Result-style; never throws. */ +export function safeParseNpcReview(text: string): + | { success: true; data: NpcResponse } + | { success: false; error: NpcReviewValidationError } { /* ... */ } +``` + +The dual API mirrors Zod's idiomatic shape: `parse*` throws a `ZodError`, +`safeParse*` returns a discriminated union. Both return the `@responseRef` value +object's OWN interface — the one `entityFile()` declares in `NpcResponse.ts` (ADR-0056) +— so the parser declares no type of its own. `parse*` / `safeParse*` expect the reply to +BE the JSON document; a raw chat reply — `Sure!` followed by a fenced JSON block — fails +them with `invalid JSON: Unexpected token 'S'…`. For a raw reply the same file exports the +tolerant tier: + +```ts +import { extractLenientNpcReviewWithLoader } from "./generated/NpcReview.response.js"; +import { MetaDataLoader } from "@metaobjectsdev/metadata"; +import { orThrow } from "@metaobjectsdev/render"; + +const { root } = await MetaDataLoader.fromDirectory("./metaobjects"); // load once at startup +const result = extractLenientNpcReviewWithLoader(root, reply); // strips prose + fences +result.report; // per field: recovered / defaulted / lost / malformed +const npc = orThrow(result); // opt-in: throws ExtractError if a @required field was lost +``` + +It reads the live metadata, so it takes a loaded `MetaRoot`; there is no text-only +`extractLenientNpcReview(text)`. A bad reply never throws — it is classified in `report` +and `data` holds what was recovered (every field of the `Extracted` mirror is +nullable). It throws only when `root` does not declare the response value object, which is +a setup error. + +Wiring the `extractor` generator as well adds `.extractor.ts` with two more entry +points over the same call: `extract(root, text)` returns the strict response type and +throws when a `@required` field is lost or malformed, and `extractLenient(root, text)` +re-exports the tolerant call above. `extractLenientWithLoader` itself is exported +only from `.response.ts`. + +Field-type → Zod mapping: `field.string` → `z.string()`; `field.int`/`long`/`currency` +→ `z.number().int()`; `field.double`/`float` → `z.number()`; `field.boolean` → +`z.boolean()`; `field.enum` → `z.enum([...])` over its declared `@values`; +`field.uuid` → `z.string().uuid()`; `field.decimal` and the temporal subtypes → +`z.string()` (their JSON wire form); `field.object` (with `@objectRef`) → a nested +`z.object({...})`; `isArray: true` → wrapped in `z.array(...)`; a field that is not +`@required` → `.optional()`. Only a subtype outside that set, or a self-referencing +`@objectRef`, falls through to `z.unknown()`. + +## The response-format prompt fragment (FR-010) + +For every responding `template.prompt`, the `outputPrompt()` generator (same import +path, `@metaobjectsdev/codegen-ts/generators`) emits a +`.responseFormat.ts` exporting `renderFormat(overrides?)` — +backed by the render engine's `renderOutputFormat()`. This is the "produce your +answer like this" fragment you splice into the prompt text so the model returns the +shape the parser above expects: + +```ts +// metaobjects.config.ts — the same entity trio as above, plus outputPrompt +import { + entityFile, queriesFile, barrel, promptRender, outputParser, outputPrompt, +} from "@metaobjectsdev/codegen-ts/generators"; + +export default defineConfig({ + outDir: "src/generated", + generators: [ + entityFile(), queriesFile(), barrel(), + promptRender(), outputParser(), outputPrompt(), + ], +}); +``` + +`@promptStyle` on the `template.prompt` (`guide` default / `inline` / `exampleOnly`) +controls the fragment's presentation: `guide` is a prose field list + example +skeleton, `inline` is one skeleton with inline placeholders/enum choices, +`exampleOnly` is just the filled skeleton. Guidance is never emitted as comments — +models ignore them. Skipped for `template.output` and for any prompt whose +`@responseRef` doesn't resolve — the same skip contract as `outputParser()`. There is NO +format gate: the old `@format ∈ {json,xml}` test read the syntax of the outbound BODY to +decide whether to describe the REPLY. `@responseFormat` selects which syntax the fragment +teaches. The baked spec's root name matches the response shape, so the fragment and the +parser's `extract()` agree on the same root. + +## The three-step consumer pattern + +Render the prompt → call your LLM client (provider-agnostic; nothing is generated +here) → parse the response with the generated parser: + +```ts +// Node-only subpath: the package ROOT stays browser-safe, so the filesystem provider +// lives on `@metaobjectsdev/render/providers`. `lobby/welcome` → ./prompts/lobby/welcome.mustache. +import { FilesystemProvider } from "@metaobjectsdev/render/providers"; +import { renderNpcReview } from "./generated/prompts"; +import { parseNpcReview, safeParseNpcReview } from "./generated/NpcReview.response"; + +const textProvider = new FilesystemProvider("./prompts"); +const promptText = renderNpcReview(payload, textProvider); +const llmResponse = await myLlmProvider.call(promptText); // YOUR code — no generated provider + +// Throwing path: +const npc = parseNpcReview(llmResponse); + +// Result-style: +const r = safeParseNpcReview(llmResponse); +if (!r.success) log.warn("malformed LLM payload", r.error); +else handle(r.data); +``` + +## Recommended LLM caller (bring-your-own) + +MetaObjects generates **no** provider/LLM-call layer and never will — the call is a +commodity the ecosystem already solves, and a maintained vendor wrapper would just +chase SDK churn (ADR-0024). You bring the caller; MetaObjects owns the typed +render → parse → record. For the call step, plug the idiomatic library into the +one-method `LlmClient` seam from `@metaobjectsdev/ai-runtime`: + +```ts +import { generateText } from "ai"; // Vercel AI SDK — recommended +import { anthropic } from "@ai-sdk/anthropic"; +import type { LlmClient } from "@metaobjectsdev/ai-runtime"; + +export const llm: LlmClient = { + async complete({ prompt, model, system }) { + const { text } = await generateText({ model: anthropic(model), system, prompt }); + return { body: text }; // also map usage/model/finishReason from the result → cost + token columns + }, +}; +``` + +**Recommended: the Vercel AI SDK (`ai`)** — provider-agnostic (`generateText` / +`generateObject` over Anthropic / OpenAI / Google / …), first-class structured +output, the de-facto TS standard. Single-provider apps can implement `complete` +directly over `@anthropic-ai/sdk` / `openai`; heavy chains can use LangChain.js — +the seam is one method either way. + +With a client in hand, the generated `record` helper (the `trace-helper` +generator) and `@metaobjectsdev/ai-runtime`'s `callLlm` do render → call → **typed +trace persist** in one call, recording request/response as typed value objects in +your own DB. The parser above is the standalone receive side if you don't want the +recorder. + +## Drift gate + +`meta verify` walks every template's `@payloadRef` resolution and fails the build +(exit 1) if a reference can't be resolved. A `@responseRef` that does not resolve to a +value-object (or sourceless projection) is caught one layer earlier — it is a LOAD +error in every port. The emitted parser imports `zod`; +it's usually already a dependency (Drizzle / `runtime-ts` lean on it), else +`npm i zod`. + +**Jinja bodies (ADR-0061).** A body may be `/.jinja` (or `.j2`, `.jinja2`) +instead of `.mustache`; `@textRef` does not change. `@metaobjectsdev/render` renders it with +nunjucks (a dependency of the package, nothing to install) and `meta verify` checks it the same +way, walking the parsed template; it names the `.jinja` file and line on a drift. +`FilesystemProvider.engineOf(ref)` reports the engine of the file it found; for an +`InMemoryProvider` pass `new InMemoryProvider(map, { engine: "jinja" })`, or pass +`engine: "jinja"` to `render` / `verify`. A generated `render()` helper over a Jinja body +passes `engine: "jinja"`, so it renders as Jinja through any runtime provider, and the +runtime check runs on it as on a Mustache body. What the check cannot settle statically is +`ERR_TEMPLATE_NOT_STATIC`. nunjucks treats an empty list as true (jinja2 does not), so test a +list with `{% if items | length %}` when the same template must render in Python. + +## See which fields a template consumes + +List `docsFile()` in `generators` and run `meta gen` to emit the model surface to the +`docs` target — one page per `template.*` at `/