From 9ad559a01882b9c605f63326c35c3ac82797e3ab Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:10:29 -0500 Subject: [PATCH 01/16] feat(codegen-ts,metadata): rules names generator (L-TS-1) rulesNamesFile() writes one rules.names.ts per metadata package that declares a lifecycle or an operation (ADR-0067 layer 0): each lifecycle's states, initial and terminal states and transitions, the commands derived from unclaimed transitions, the declared operations, the permissions they ask about and the business errors, as as-const values and literal unions. The names come from the derivations meta verify's rules gate checks, now shared in metadata (core/transition/commands.ts) and read by both the gate and the generator's engine walk (codegen-ts rules-walk.ts). The generator is ejectable, TypeScript-only for now, and silent for a model without the rules vocabulary. --- CHANGELOG.md | 11 + docs/features/business-rules.md | 51 +++- docs/ports/typescript.md | 11 + fixtures/codegen-noop/rules/README.md | 4 + .../generator-registry-conformance/README.md | 6 +- .../registry.json | 3 +- .../cli/src/lib/collection-load-options.ts | 3 +- .../packages/cli/src/lib/rules-check.ts | 88 +------ .../catalog-declarations-resolved.test.ts | 5 + .../packages/cli/test/eject-contract.test.ts | 2 + .../cli/test/eject-templates-contract.test.ts | 2 + .../cli/test/unit/rules-inert.test.ts | 21 +- .../packages/codegen-ts/src/engine-surface.ts | 1 + .../packages/codegen-ts/src/engine.ts | 1 + .../codegen-ts/src/generator-registry.ts | 12 + .../codegen-ts/src/generators/index.ts | 1 + .../src/generators/rules-names-file.ts | 47 ++++ .../codegen-ts/src/reference-templates.ts | 3 + .../codegen-ts/src/reference/rules-names.ts | 59 +++++ .../packages/codegen-ts/src/rules-walk.ts | 199 ++++++++++++++++ .../codegen-ts/src/templates/rules-names.ts | 97 ++++++++ .../test/generator-registry.test.ts | 1 + .../test/reference-byte-identical.test.ts | 5 + .../test/reference-templates.test.ts | 2 +- .../codegen-ts/test/rules-names.test.ts | 221 ++++++++++++++++++ .../metadata/src/core/transition/commands.ts | 131 +++++++++++ .../typescript/packages/metadata/src/index.ts | 18 +- .../packages/metadata/src/rules-settings.ts | 10 + .../packages/metadata/src/shared/meta-root.ts | 8 + server/typescript/packages/sdk/src/memory.ts | 11 +- 30 files changed, 946 insertions(+), 88 deletions(-) create mode 100644 server/typescript/packages/codegen-ts/src/generators/rules-names-file.ts create mode 100644 server/typescript/packages/codegen-ts/src/reference/rules-names.ts create mode 100644 server/typescript/packages/codegen-ts/src/rules-walk.ts create mode 100644 server/typescript/packages/codegen-ts/src/templates/rules-names.ts create mode 100644 server/typescript/packages/codegen-ts/test/rules-names.test.ts create mode 100644 server/typescript/packages/metadata/src/core/transition/commands.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 534327d4c4..69b1e0a192 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,17 @@ 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. +- **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`). - **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 diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index fc86d1cc4d..eefc889b79 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -14,9 +14,10 @@ The Rust port loads the vocabulary and runs the same loader rules, and its `veri same rules gate, held to `fixtures/rules-check-conformance/` ([Rust port](../ports/rust.md)). A requirement can claim an operation or a transition. The flat generators generate nothing from the vocabulary. The layer generators of ADR-0067 do, and an app adds them to its generator list as -it adds any generator. The first are C#'s `rules-names`, which writes the states, transitions, -permissions and error codes as constants, and `contract-types`, which writes each entity's create -and update records ([C# port](../ports/csharp.md)). The service shells that +it adds any generator. The first is `rules-names`, which writes the states, transitions, +permissions and error codes as constants, in TypeScript (see +[The names layer](#the-names-layer-typescript)) and C#; C# also ships `contract-types`, which writes +each entity's create and update records ([C# port](../ports/csharp.md)). The service shells that enforce these rules at run time are later work. A lifecycle in a project that wires none will be advised by `verify` once that check lands; today the flat routes enforce nothing and `verify` says nothing about it. Every flat generator writes byte-identical code for @@ -245,6 +246,50 @@ setting behaves as it does today. } ``` +## The names layer (TypeScript) + +`rulesNamesFile()` (stable name `rules-names`, ejectable like any reference generator) writes one +`rules.names.ts` per metadata package that declares a lifecycle or an operation, under the +package's directory (`acme/purchasing/rules.names.ts`) in either output layout. A package without +the vocabulary gets no file. Hand-written code (a command body, a policy, a grant table) imports +these instead of writing a state, a transition, a permission or an error code as a string, so a +rename in the model stops it compiling: + +```ts +export const PurchaseRequestStatusLifecycle = { + field: "status", + states: ["draft", "submitted", "approved", "rejected"], + initial: "draft", + terminal: ["approved", "rejected"], + transitions: { + submit: { from: ["draft"], to: "submitted" }, + approve: { from: ["submitted"], to: "approved" }, + reject: { from: ["submitted"], to: "rejected" }, + }, +} as const; +export type PurchaseRequestStatusState = (typeof PurchaseRequestStatusLifecycle.states)[number]; +export type PurchaseRequestStatusTransition = keyof typeof PurchaseRequestStatusLifecycle.transitions; + +export const PurchaseRequestCommands = { + submit: { lifecycle: "status", permission: "acme::purchasing.PurchaseRequest.submit" }, +} as const; + +export const Operations = { + decide: { kind: "command", permission: "purchasing.decide", transitions: ["approve", "reject"], errors: ["over_budget", "already_decided"] }, + openRequests: { kind: "query", public: true }, +} as const; + +export const Permissions = ["acme::purchasing.PurchaseRequest.submit", "purchasing.decide"] as const; +export type Permission = (typeof Permissions)[number]; +export const BusinessErrors = ["already_decided", "over_budget"] as const; +``` + +The file also carries `ShellErrors`, the codes the enforcing shell answers with on its own. What +is derived (the terminal states, which transitions get a command under `rules.lifecycle.commands`, +each derived permission name) comes from the same functions `verify`'s rules gate uses, so the +constant and a `verify` message name the same thing. The file ends in `.names.ts`, so +`meta verify --codegen` treats a hand edit in it as drift, as it does for `.names.ts`. + ## Requirements can claim operations and transitions A level 5 requirement's `implementedBy` can name an operation as `.`, or a diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 5340dfc039..7566158047 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -727,6 +727,17 @@ file and take `db` as an explicit first argument — useful directly in request handlers, tests, or any runtime where a module singleton doesn't fit (see the recipe above). +### `rules.names.ts` — the business-rules names, as constants + +`rulesNamesFile()` (stable name `rules-names`) is the first rules layer of ADR-0067. It writes one +`rules.names.ts` per metadata package that declares a lifecycle or an operation, under the +package's directory in either layout: each lifecycle's states, initial and terminal states and +transitions (`Lifecycle`, with `State` and `…Transition` unions), the +commands derived from unclaimed transitions (`Commands`), the declared `Operations`, every +`Permission` the package asks about and its `BusinessError` codes. It is not scaffolded; add it to +`generators` or `meta eject rules-names`. The derivations are the ones `meta verify`'s rules gate +checks. See [Business rules](../features/business-rules.md#the-names-layer-typescript). + ### Prove it works Boot the server: diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md index 4916b220b7..126446bf8e 100644 --- a/fixtures/codegen-noop/rules/README.md +++ b/fixtures/codegen-noop/rules/README.md @@ -20,6 +20,10 @@ the two models produce the same output everywhere: lists the `api`, `operation`, `binding` and `transition` nodes as well. Its other output is byte-identical, and its payload gains only lines of those four types. +The generators of the rules layers themselves (ADR-0067) are the other exception: reading this +vocabulary is their job. Each writes nothing for `without/` and only files of its own for +`with/`, so it adds files and moves none. Today that is TypeScript's `rules-names`. + A generator that started reading an operation or a transition by accident would emit something half-built; these tests are what notice: diff --git a/fixtures/generator-registry-conformance/README.md b/fixtures/generator-registry-conformance/README.md index d8df34d421..affeabd200 100644 --- a/fixtures/generator-registry-conformance/README.md +++ b/fixtures/generator-registry-conformance/README.md @@ -32,7 +32,7 @@ to make the choice cheap, and `layer` is the axis it is cheap along. | layer | members | chosen by | |---|---|---| -| `model` | entity, names, barrel, dto, value-object | app shape | +| `model` | entity, names, rules-names, barrel, dto, value-object | app shape | | `persistence` | queries, prisma-schema, db-context, repository, exposed-table, relations, stored-proc | app shape | | `api` | routes, routes-hono, filter-allowlist, validator, spring-config, contract-schema, openapi | app shape | | `client` | form, hooks, grid, grid-hook, client, commands | app shape | @@ -122,6 +122,10 @@ port that adopts either name adds itself to that entry's `ports`; the name is th shared like the others. (`payload` was one until ADR-0056 removed it: a value object's type now comes from the value-object generator, so the template tier declares none.) +One name is **TypeScript-only for now**: `rules-names`, the first rules layer of ADR-0067 (the +names of a package's lifecycle states, transitions, commands, operations, permissions and +business errors). Each other port adds itself to its `ports` with its own rules-layer work. + ## Changing the surface Adding, removing, or renaming a generator means editing **both** `registry.json` diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 3326538dd9..41c8d61e5c 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -109,7 +109,7 @@ "tier": "native", "layer": "model", "eject": "full", - "ports": ["csharp"] + "ports": ["typescript", "csharp"] }, "contract-types": { "concept": "Per-entity create and update records (ADR-0067 layer 1): the members a client sends to create a row and may change on update, with the entity's validation; the server-owned members (generated key, @autoSet stamp, readOnly and derived fields, TPH discriminator) are on neither, and the update record tells an omitted member from an explicit null.", @@ -428,6 +428,7 @@ "codegen-ts/src/render-engine/framework-provider.ts", "codegen-ts/src/requirement-walk.ts", "codegen-ts/src/routes-expose.ts", + "codegen-ts/src/rules-walk.ts", "codegen-ts/src/source-detect.ts", "codegen-ts/src/templates/entity-ui-descriptor.ts", "codegen-ts/src/templates/find-inbound.ts", diff --git a/server/typescript/packages/cli/src/lib/collection-load-options.ts b/server/typescript/packages/cli/src/lib/collection-load-options.ts index a0126169fe..e615403a9c 100644 --- a/server/typescript/packages/cli/src/lib/collection-load-options.ts +++ b/server/typescript/packages/cli/src/lib/collection-load-options.ts @@ -27,7 +27,7 @@ import type { Collection, LoadMemoryOptions } from "@metaobjectsdev/sdk"; */ export function collectionLoadOptions( collection: Collection, -): Required> { +): Required> { return { files: collection.files, fileIds: collection.fileIds, @@ -44,6 +44,7 @@ export function collectionLoadOptions( enumDefaults: collection.enumDefaults ?? DEFAULT_ENUM_DEFAULTS, apiPagination: collection.apiPagination, apiUnknownFields: collection.apiUnknownFields, + rulesSettings: collection.rulesSettings, // The collection's migrate settings (`migrate.conventions`, `migrate.checks`) are not load // options: they reach the expected-schema builds through `schemaBuildOptions`. }; diff --git a/server/typescript/packages/cli/src/lib/rules-check.ts b/server/typescript/packages/cli/src/lib/rules-check.ts index e039aea352..ee78704e35 100644 --- a/server/typescript/packages/cli/src/lib/rules-check.ts +++ b/server/typescript/packages/cli/src/lib/rules-check.ts @@ -36,21 +36,20 @@ // target: a command acting on an abstract base claims the inherited transition of each child. import { - TYPE_API, - TYPE_OBJECT, - TYPE_OPERATION, - OBJECT_SUBTYPE_ENTITY, OPERATION_ATTR_PERMISSION, OPERATION_ATTR_PUBLIC, - OPERATION_ATTR_TRANSITIONS, - OPERATION_SUBTYPE_COMMAND, PACKAGE_SEPARATOR, + claimedTransitions, + claimsOn, + commandEntities, + derivedPermissionName, + derivesCommand, effectivePackageOf, - entityLineage, entityTransitions, - lifecycleIsLive, lifecyclesOf, - operationTarget, + modelEntities, + modelOperations, + needsPermissionName, reachableStates, terminalStates, topLevelNodeOf, @@ -97,33 +96,11 @@ export function rulesAddress(node: MetaData): string { return pkg === "" ? parts.join(".") : `${pkg}${PACKAGE_SEPARATOR}${parts.join(".")}`; } -/** The permission name a node gets when it declares none, `.`: the path is - * `` for a declared operation and `.` for a transition's derived - * command, so two entities' transitions of one name ask about different permissions. */ -function derivedPermissionName(owner: MetaData, path: string): string { - const pkg = effectivePackageOf(topLevelNodeOf(owner)); - return pkg === "" ? path : `${pkg}.${path}`; -} - -function needsPermissionName(node: MetaData): boolean { - return node.attr(OPERATION_ATTR_PERMISSION) === undefined && node.attr(OPERATION_ATTR_PUBLIC) !== true; -} - -function entities(root: MetaData): MetaData[] { - return root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_ENTITY); -} - -function operations(root: MetaData): MetaData[] { - return root.children() - .filter((c) => c.type === TYPE_API) - .flatMap((api) => api.children().filter((c) => c.type === TYPE_OPERATION)); -} - /** Every lifecycle of the model, once per declaring field, in model order. */ function declaredLifecycles(root: MetaData): Lifecycle[] { const seen = new Set(); const out: Lifecycle[] = []; - for (const entity of entities(root)) { + for (const entity of modelEntities(root)) { for (const l of lifecyclesOf(entity)) { if (seen.has(l.field)) continue; seen.add(l.field); @@ -184,49 +161,6 @@ function checkLifecycle(l: Lifecycle, settings: RulesSettings, out: Diagnostic[] } } -/** One command's claim on a transition node, made for its target entity. */ -interface Claim { - readonly target: MetaData; - readonly op: MetaData; -} - -/** Each transition node the declared commands claim, with the claims on it in model order. */ -function claimedTransitions(root: MetaData): Map { - const claimed = new Map(); - for (const op of operations(root)) { - if (op.subType !== OPERATION_SUBTYPE_COMMAND) continue; - const target = operationTarget(op); - if (target === undefined) continue; - const raw = op.attr(OPERATION_ATTR_TRANSITIONS); - const names = new Set(Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : []); - for (const t of entityTransitions(target)) { - if (!names.has(t.name)) continue; - const claims = claimed.get(t) ?? []; - claims.push({ target, op }); - claimed.set(t, claims); - } - } - return claimed; -} - -/** The claims that cover transition `t` on `entity`: those made for the entity or an entity it extends. */ -function claimsOn(claimed: Map, entity: MetaData, t: MetaData): Claim[] { - const lineage = entityLineage(entity); - return (claimed.get(t) ?? []).filter((c) => lineage.includes(c.target)); -} - -/** Whether `t`, carried by `entity`, derives a command of its own under the setting. */ -function derivesCommand(claimed: Map, settings: RulesSettings, entity: MetaData, t: MetaData): boolean { - if (settings.lifecycleCommands === "none") return false; - if (settings.lifecycleCommands === "all") return true; - return claimsOn(claimed, entity, t).length === 0; -} - -/** The entities a transition can derive a command on: concrete, with a source. */ -function commandEntities(root: MetaData): MetaData[] { - return entities(root).filter((e) => !e.isAbstract && lifecycleIsLive(e)); -} - /** A transition's @permission or @public is read only by the command derived from it. One that * derives no command for any entity carrying it declares an attribute nothing reads. A transition * carried only by entities with no source is inert, not shadowed: it is not reported. */ @@ -284,7 +218,7 @@ function checkPermissionNames(root: MetaData, settings: RulesSettings, out: Diag } } - for (const op of operations(root)) { + for (const op of modelOperations(root)) { if (!needsPermissionName(op)) continue; out.push({ severity, @@ -300,7 +234,7 @@ function checkPermissionNames(root: MetaData, settings: RulesSettings, out: Diag /** The rules gate over a loaded model. */ export function checkRules(root: MetaData, settings: RulesSettings): RulesCheckResult { const lifecycles = declaredLifecycles(root); - const ops = operations(root); + const ops = modelOperations(root); if (lifecycles.length === 0 && ops.length === 0) return { diagnostics: [], summary: undefined }; const diagnostics: Diagnostic[] = []; diff --git a/server/typescript/packages/cli/test/catalog-declarations-resolved.test.ts b/server/typescript/packages/cli/test/catalog-declarations-resolved.test.ts index 1f1138a1d1..be0bb2facb 100644 --- a/server/typescript/packages/cli/test/catalog-declarations-resolved.test.ts +++ b/server/typescript/packages/cli/test/catalog-declarations-resolved.test.ts @@ -150,6 +150,10 @@ describe("catalog declarations are resolved against what the generators emit", ( // declares no report. Its files import nothing outside their own pair // (`requires: []`, no runtime packages), and the reference byte-identical // test runs it over the report corpus. + // rules-names writes `rules.names.ts` only for a package that declares a lifecycle or + // an operation (ADR-0066); this fixture declares neither. The file it + // writes imports nothing (`requires: []`, no runtime packages), and the + // inert test (rules-inert.test.ts) runs it over a model that declares them. const silent = [...emissions.entries()].filter(([, e]) => e.size === 0).map(([n]) => n).sort(); expect(silent).toEqual([ "agent-docs", @@ -161,6 +165,7 @@ describe("catalog declarations are resolved against what the generators emit", ( "render-helper", "report-export", "requirements", + "rules-names", "shared-model", "template", "trace-helper", diff --git a/server/typescript/packages/cli/test/eject-contract.test.ts b/server/typescript/packages/cli/test/eject-contract.test.ts index a2b26f79b2..c2f27914ad 100644 --- a/server/typescript/packages/cli/test/eject-contract.test.ts +++ b/server/typescript/packages/cli/test/eject-contract.test.ts @@ -341,6 +341,8 @@ const CORPORA: Corpus[] = [ // The grid tier is TypeScript-only, so its model is this port's own fixture. { label: "data-grid", files: [join(PACKAGES, "codegen-ts-tanstack", "test", "fixtures", "single-entity.json")] }, { label: "llm-call", files: inputs("conformance", "ai-trace-prompt-nested", "input") }, + // Lifecycles, a claimed and an unclaimed transition, and an API with a command and queries. + { label: "rules", files: [join(FIXTURES, "codegen-noop", "rules", "with", "meta.purchasing.json")] }, ]; /** diff --git a/server/typescript/packages/cli/test/eject-templates-contract.test.ts b/server/typescript/packages/cli/test/eject-templates-contract.test.ts index 2c43e3b4fe..f7c96b0252 100644 --- a/server/typescript/packages/cli/test/eject-templates-contract.test.ts +++ b/server/typescript/packages/cli/test/eject-templates-contract.test.ts @@ -287,6 +287,8 @@ const CORPORA: Corpus[] = [ // The grid tier is TypeScript-only, so its model is this port's own fixture. { label: "data-grid", files: [join(PACKAGES, "codegen-ts-tanstack", "test", "fixtures", "single-entity.json")] }, { label: "llm-call", files: inputs("conformance", "ai-trace-prompt-nested", "input") }, + // Lifecycles, a claimed and an unclaimed transition, and an API with a command and queries. + { label: "rules", files: [join(FIXTURES, "codegen-noop", "rules", "with", "meta.purchasing.json")] }, ]; /** The options a factory cannot be called without. `shared-model` publishes nothing until told what to include. */ diff --git a/server/typescript/packages/cli/test/unit/rules-inert.test.ts b/server/typescript/packages/cli/test/unit/rules-inert.test.ts index c72edbe1c2..9f21f09db7 100644 --- a/server/typescript/packages/cli/test/unit/rules-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/rules-inert.test.ts @@ -14,6 +14,10 @@ // node of the model in its data payload, so it lists the new nodes too. Its other output is // byte-identical, and the payload differs by exactly the `api`, `operation`, `binding` and // `transition` nodes. +// +// The generators of the rules layers themselves (ADR-0067) are the other exception: reading the +// vocabulary is what they are for. Each emits nothing for the model without it, and only files of +// its own for the model with it, so it adds files and moves none. import { describe, test, expect, beforeAll, afterAll } from "bun:test"; import { copyFileSync, mkdirSync, mkdtempSync, rmSync, readFileSync, readdirSync, statSync } from "node:fs"; @@ -86,6 +90,10 @@ async function emit(metadata: MetaRoot, generators: Generator[]): Promise = { + "rules-names": ["src/generated/acme/purchasing/rules.names.ts"], +}; let withRules: MetaRoot; let withoutRules: MetaRoot; @@ -105,7 +113,7 @@ describe("ADR-0066 the business-rules vocabulary is inert in every generator and const catalog = composeCatalog(); for (const [name, entry] of Object.entries(catalog)) { - if (name === DOCS_SITE) continue; + if (name === DOCS_SITE || name in RULES_LAYER) continue; test(`generator "${name}" emits the same files, byte for byte`, async () => { const expected = await emit(withoutRules, [entry.factory()]); const actual = await emit(withRules, [entry.factory()]); @@ -113,6 +121,13 @@ describe("ADR-0066 the business-rules vocabulary is inert in every generator and }); } + for (const [name, files] of Object.entries(RULES_LAYER)) { + test(`rules-layer generator "${name}" writes nothing without the vocabulary, and only its own files with it`, async () => { + expect(await emit(withoutRules, [catalog[name]!.factory()])).toEqual({}); + expect(Object.keys(await emit(withRules, [catalog[name]!.factory()])).sort()).toEqual(files); + }); + } + test("docs-site differs by exactly the new nodes in its data payload", async () => { const expected = await emit(withoutRules, [catalog[DOCS_SITE]!.factory()]); const actual = await emit(withRules, [catalog[DOCS_SITE]!.factory()]); @@ -145,6 +160,10 @@ describe("ADR-0066 the business-rules vocabulary is inert in every generator and const actual = await emit(withRules, runnable.map((f) => f())); expect(expected[""]).toBeUndefined(); expect(Object.keys(expected).length).toBeGreaterThan(10); + // The rules layers add their own files beside the rest, and move none of them. + const added = Object.values(RULES_LAYER).flat(); + expect(Object.keys(actual).filter((p) => !(p in expected)).sort()).toEqual([...added].sort()); + for (const p of added) delete actual[p]; expect(actual).toEqual(expected); }); diff --git a/server/typescript/packages/codegen-ts/src/engine-surface.ts b/server/typescript/packages/codegen-ts/src/engine-surface.ts index 1dbc8d9fe8..c3830ad380 100644 --- a/server/typescript/packages/codegen-ts/src/engine-surface.ts +++ b/server/typescript/packages/codegen-ts/src/engine-surface.ts @@ -66,6 +66,7 @@ export const ENGINE_MODULES: readonly string[] = [ "codegen-ts/src/render-engine/framework-provider.ts", "codegen-ts/src/requirement-walk.ts", "codegen-ts/src/routes-expose.ts", + "codegen-ts/src/rules-walk.ts", "codegen-ts/src/source-detect.ts", "codegen-ts/src/templates/entity-ui-descriptor.ts", "codegen-ts/src/templates/find-inbound.ts", diff --git a/server/typescript/packages/codegen-ts/src/engine.ts b/server/typescript/packages/codegen-ts/src/engine.ts index b8e6b0fa6a..22a7e13045 100644 --- a/server/typescript/packages/codegen-ts/src/engine.ts +++ b/server/typescript/packages/codegen-ts/src/engine.ts @@ -53,6 +53,7 @@ export * from "./render-context.js"; export * from "./render-engine/framework-provider.js"; export * from "./requirement-walk.js"; export * from "./routes-expose.js"; +export * from "./rules-walk.js"; export * from "./source-detect.js"; export * from "./templates/entity-ui-descriptor.js"; export * from "./templates/find-inbound.js"; diff --git a/server/typescript/packages/codegen-ts/src/generator-registry.ts b/server/typescript/packages/codegen-ts/src/generator-registry.ts index 66ff378e91..c32d1b21ac 100644 --- a/server/typescript/packages/codegen-ts/src/generator-registry.ts +++ b/server/typescript/packages/codegen-ts/src/generator-registry.ts @@ -36,6 +36,7 @@ import { callableFile, routesFileHono, namesFile, + rulesNamesFile, reportExport, promptRender, outputParser, @@ -213,6 +214,17 @@ export const generatorRegistry: Record = { options: "filter?, target?", ejectable: ejectable("names"), }, + "rules-names": { + name: "rules-names", + kind: "generator", + layer: "model", + description: "Per-package rules name constants: lifecycle states and transitions, derived commands, operations, permissions and business errors.", + tier: "native", + factory: () => rulesNamesFile(), + factoryExport: "rulesNamesFile", + options: "filter?, target?", + ejectable: ejectable("rules-names"), + }, barrel: { name: "barrel", kind: "generator", diff --git a/server/typescript/packages/codegen-ts/src/generators/index.ts b/server/typescript/packages/codegen-ts/src/generators/index.ts index 95c37d0e04..b704588c00 100644 --- a/server/typescript/packages/codegen-ts/src/generators/index.ts +++ b/server/typescript/packages/codegen-ts/src/generators/index.ts @@ -29,6 +29,7 @@ export { barrel, type BarrelOpts } from "./barrel.js"; export { callableFile, type CallableFileOpts } from "./callable-file.js"; export { routesFileHono, type RoutesFileHonoOpts } from "./routes-file-hono.js"; export { namesFile } from "./names-file.js"; +export { rulesNamesFile, type RulesNamesFileOpts } from "./rules-names-file.js"; export { reportExport, type ReportExportOpts } from "./report-export-file.js"; export { promptRender, type PromptRenderOpts } from "./prompt-render-file.js"; export { outputParser, type OutputParserOpts } from "./output-parser-file.js"; diff --git a/server/typescript/packages/codegen-ts/src/generators/rules-names-file.ts b/server/typescript/packages/codegen-ts/src/generators/rules-names-file.ts new file mode 100644 index 0000000000..f5465c714b --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/generators/rules-names-file.ts @@ -0,0 +1,47 @@ +import type { MetaData } from "@metaobjectsdev/metadata"; +import { isMetaObject, type MetaObject } from "@metaobjectsdev/metadata"; +import type { EmittedFile, GenContext, Generator } from "../generator.js"; +import { packageToPath } from "../import-path.js"; +import { NAMES_FILE_SUFFIX } from "../constants.js"; +import { rulesNamesOf } from "../rules-walk.js"; +import { renderRulesNames } from "../templates/rules-names.js"; + +/** + * `rules.names.ts`: the rules names of one metadata package (ADR-0067 §1, layer 0) — its + * lifecycles' states and transitions, its derived commands, its declared operations, and the + * permissions and business errors they name — as constants a hand-written body, policy or + * grant table imports instead of a string literal. + * + * The built-in twin of `src/reference/rules-names.ts` (ADR-0034 scaffold-and-own); the + * reference-byte-identical gate holds the two to the same output. + * + * A SEPARATE generator, never a branch inside an existing one: a model with no rules vocabulary + * gets no file from it, and no existing generator's output moves (`fixtures/codegen-noop/rules`). + */ +export interface RulesNamesFileOpts { + /** Narrow which entities' lifecycles and operations are written. ANDed with the generator's own + * gates, so it can only narrow; an operation with no target entity is always kept. */ + filter?: (entity: MetaObject) => boolean; + /** Named output target, as on every other generator. */ + target?: string; +} + +export function rulesNamesFile(opts?: RulesNamesFileOpts): Generator { + const generator: Generator = { + name: "rules-names", + generate: (ctx: GenContext): EmittedFile[] => { + const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj); + return rulesNamesOf(ctx.loadedRoot, { matches }).map((pkg) => { + // One file per PACKAGE, under the package's directory in either layout: under the flat + // layout two packages would otherwise both write `rules.names.ts`. The `.names.ts` + // suffix is what makes `meta verify --codegen` hold it fail-closed, like `.names.ts`. + const dir = packageToPath(pkg.package); + const file = `rules${NAMES_FILE_SUFFIX}`; + return { path: dir === "" ? file : `${dir}/${file}`, content: renderRulesNames(pkg) }; + }); + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/reference-templates.ts b/server/typescript/packages/codegen-ts/src/reference-templates.ts index 1a2d35e0fb..7af8889523 100644 --- a/server/typescript/packages/codegen-ts/src/reference-templates.ts +++ b/server/typescript/packages/codegen-ts/src/reference-templates.ts @@ -15,6 +15,9 @@ import { fileURLToPath } from "node:url"; /** Basenames (no extension) of the copyable reference generators shipped in `src/reference/`. */ export const REFERENCE_GENERATOR_NAMES = [ "entity", "queries", "routes", "routes-hono", "barrel", "names", + // The rules names (ADR-0067 layer 0): the file's shape is the adopter's, while the walk that + // derives states, commands and permission names stays engine, shared with `meta verify`. + "rules-names", // The report export (`?format=csv|json|xml` on a served report): which reports get a module, the // column list and the CSV/XML writers, handed over as one file. "report-export", diff --git a/server/typescript/packages/codegen-ts/src/reference/rules-names.ts b/server/typescript/packages/codegen-ts/src/reference/rules-names.ts new file mode 100644 index 0000000000..268e2f6eb8 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/reference/rules-names.ts @@ -0,0 +1,59 @@ +// REFERENCE TEMPLATE — copy this into your repo (e.g. codegen/generators/rules-names.ts) and own it. +// Then import it LOCALLY in metaobjects.config.ts: +// import { rulesNamesFile } from "./codegen/generators/rules-names.js"; +// +// RUNTIME: this file executes under whatever runs `meta gen`, and the published CLI's +// shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not +// reach for `Bun.*` globals here; use `node:` builtins instead. +// targets: the emit step. Replace `renderRulesNames` to change the file's SHAPE (flat +// `ORDER_STATUS_PLACED` constants, an enum per lifecycle); keep `rulesNamesOf` +// so the names come from the same derivation `meta verify`'s rules gate checks. +// use-when: hand-written code names a lifecycle state, a transition, a permission or a +// business error (a command body, a policy, a grant table) and you want a rename +// in the model to stop it compiling instead of leaving a stale string behind. +// emits: //rules.names.ts per metadata package that declares a +// lifecycle or an operation, in either output layout. A model with no rules +// vocabulary gets no file. +// customize: swap `renderRulesNames` for your own shape; keep `rulesNamesOf` as the one walk. +// composes-with: names.ts (the physical names of the same entities). Nothing else imports it. +// +// A SEPARATE generator, never a branch inside an existing one: a model with no rules vocabulary +// moves no existing generator's output (fixtures/codegen-noop/rules). +import { + NAMES_FILE_SUFFIX, + packageToPath, + rulesNamesOf, + type EmittedFile, + type GenContext, + type Generator, +} from "@metaobjectsdev/codegen-ts/engine"; +import { renderRulesNames } from "../templates/rules-names.js"; +import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; + +export interface RulesNamesFileOpts { + /** Narrow which entities' lifecycles and operations are written. ANDed with the generator's own + * gates, so it can only narrow; an operation with no target entity is always kept. */ + filter?: (entity: MetaObject) => boolean; + /** Named output target, as on every other generator. */ + target?: string; +} + +export function rulesNamesFile(opts?: RulesNamesFileOpts): Generator { + const generator: Generator = { + name: "rules-names", + generate: (ctx: GenContext): EmittedFile[] => { + const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj); + return rulesNamesOf(ctx.loadedRoot, { matches }).map((pkg) => { + // One file per PACKAGE, under the package's directory in either layout: under the flat + // layout two packages would otherwise both write `rules.names.ts`. The `.names.ts` + // suffix is what makes `meta verify --codegen` hold it fail-closed, like `.names.ts`. + const dir = packageToPath(pkg.package); + const file = `rules${NAMES_FILE_SUFFIX}`; + return { path: dir === "" ? file : `${dir}/${file}`, content: renderRulesNames(pkg) }; + }); + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/rules-walk.ts b/server/typescript/packages/codegen-ts/src/rules-walk.ts new file mode 100644 index 0000000000..f4fed2d59e --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/rules-walk.ts @@ -0,0 +1,199 @@ +// The rules names of a model, one record per metadata package (ADR-0067 §1, layer 0; ADR-0066). +// +// The names layer is the tether between the model and hand-written code: a body, a policy or a +// grant table that names a state, a transition, a permission or an error code through these +// constants stops compiling when the model renames it. This walk collects what the model DERIVES +// as well as what it declares, from the same functions `meta verify`'s rules gate uses +// (`@metaobjectsdev/metadata`: lifecyclesOf, derivedCommandsOf, operationPermission, +// commandPermission), so a generated constant and a verify message cannot name two different +// permissions. +// +// It is engine, not emit: `rulesNamesFile()` renders these records, and an ejected copy of its +// renderer keeps calling this walk, so what the model means stays packaged while the file's shape +// is the adopter's. + +import { + OPERATION_ATTR_ERRORS, + OPERATION_ATTR_TRANSITIONS, + OPERATION_SUBTYPE_COMMAND, + RESERVED_ERROR_CODES, + claimedTransitions, + commandPermission, + derivedCommandsOf, + effectivePackageOf, + isPublicPoint, + lifecyclesOf, + modelEntities, + modelOperations, + operationPermission, + operationTarget, + rulesSettingsOfModel, + terminalStates, + topLevelNodeOf, + transitionFrom, + transitionTo, + type MetaData, +} from "@metaobjectsdev/metadata"; + +/** The wire codes the enforcing shell answers on its own (ADR-0066 §6): the first five of the + * reserved codes. The rest of `RESERVED_ERROR_CODES` belongs to the API contract's transport. */ +export const SHELL_ERROR_CODES = RESERVED_ERROR_CODES.slice(0, 5) as readonly string[]; + +/** One transition of a lifecycle. */ +export interface RulesNamesTransition { + readonly name: string; + readonly from: readonly string[]; + readonly to: string | undefined; +} + +/** One lifecycle of an entity: an enum field with at least one transition. */ +export interface RulesNamesLifecycle { + /** The lifecycle's field. */ + readonly field: string; + readonly states: readonly string[]; + /** The enum's @default (the loader refuses a lifecycle without one). */ + readonly initial: string | undefined; + readonly terminal: readonly string[]; + readonly transitions: readonly RulesNamesTransition[]; +} + +/** A command derived from a transition (ADR-0066 §2): it takes the key and makes the transition. */ +export interface RulesNamesCommand { + /** The command's name, which is the transition's. */ + readonly name: string; + /** The field of the lifecycle the transition belongs to. */ + readonly lifecycle: string; + /** The permission it asks the policy about; undefined when the transition is `@public`. */ + readonly permission: string | undefined; +} + +/** An entity's lifecycles and derived commands. */ +export interface RulesNamesEntity { + readonly name: string; + readonly lifecycles: readonly RulesNamesLifecycle[]; + /** Empty for an abstract entity or one with no source, which derive no command. */ + readonly commands: readonly RulesNamesCommand[]; +} + +/** A declared operation. */ +export interface RulesNamesOperation { + readonly name: string; + readonly kind: "command" | "query"; + /** The permission it asks the policy about; undefined when it is `@public`. */ + readonly permission: string | undefined; + /** The transitions a command may make (`@transitions`). */ + readonly transitions: readonly string[]; + /** The business errors a command's body may return (`@errors`). */ + readonly errors: readonly string[]; +} + +/** The rules names of one metadata package. */ +export interface RulesNamesPackage { + /** The package (`acme::shop`), or `""` for a model with none. */ + readonly package: string; + /** Entities of the package with at least one lifecycle, in model order. */ + readonly entities: readonly RulesNamesEntity[]; + /** The package's declared operations, once each, in model order. */ + readonly operations: readonly RulesNamesOperation[]; + /** Every permission a point of the package asks about, sorted and once each. */ + readonly permissions: readonly string[]; + /** Every business error the package's commands declare, sorted and once each. */ + readonly errors: readonly string[]; +} + +export interface RulesNamesOpts { + /** Narrow which entities are walked (a generator's `filter`). An operation is kept when its + * target entity matches or it has none. */ + readonly matches?: (obj: MetaData) => boolean; +} + +function strings(node: MetaData, attr: string): string[] { + const v = node.attr(attr); + return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; +} + +function packageOf(node: MetaData): string { + return effectivePackageOf(topLevelNodeOf(node)); +} + +function entityNames(entity: MetaData, claimed: ReturnType, root: MetaData): RulesNamesEntity | undefined { + const lifecycles = lifecyclesOf(entity); + if (lifecycles.length === 0) return undefined; + const lifecycleOf = new Map(); + const out: RulesNamesLifecycle[] = lifecycles.map((l) => { + for (const t of l.transitions) lifecycleOf.set(t, l.field.name); + return { + field: l.field.name, + states: l.states, + initial: l.initial, + terminal: terminalStates(l), + transitions: l.transitions.map((t) => ({ name: t.name, from: transitionFrom(t), to: transitionTo(t) })), + }; + }); + const commands = derivedCommandsOf(entity, claimed, rulesSettingsOfModel(root)).map((t) => ({ + name: t.name, + lifecycle: lifecycleOf.get(t) ?? "", + permission: commandPermission(entity, t), + })); + return { name: entity.name, lifecycles: out, commands }; +} + +function operationNames(op: MetaData): RulesNamesOperation { + const kind = op.subType === OPERATION_SUBTYPE_COMMAND ? "command" : "query"; + return { + name: op.name, + kind, + permission: isPublicPoint(op) ? undefined : operationPermission(op), + transitions: kind === "command" ? strings(op, OPERATION_ATTR_TRANSITIONS) : [], + errors: kind === "command" ? strings(op, OPERATION_ATTR_ERRORS) : [], + }; +} + +/** + * The rules names of every package that declares a lifecycle or an operation, sorted by package. + * A package that declares neither has no record, so a model with no rules vocabulary yields `[]`. + */ +export function rulesNamesOf(root: MetaData, opts: RulesNamesOpts = {}): RulesNamesPackage[] { + const matches = opts.matches ?? (() => true); + const claimed = claimedTransitions(root); + const byPackage = new Map(); + const bucket = (pkg: string) => { + let b = byPackage.get(pkg); + if (b === undefined) { b = { entities: [], operations: [] }; byPackage.set(pkg, b); } + return b; + }; + + for (const entity of modelEntities(root)) { + if (!matches(entity)) continue; + const names = entityNames(entity, claimed, root); + if (names !== undefined) bucket(packageOf(entity)).entities.push(names); + } + + // One operation declared identically by two APIs (a versioned API) is one operation (O6), so + // it is listed once. + const seen = new Set(); + for (const op of modelOperations(root)) { + const target = operationTarget(op); + if (target !== undefined && !matches(target)) continue; + const pkg = packageOf(op); + const id = `${pkg}\u0000${op.name.toLowerCase()}`; + if (seen.has(id)) continue; + seen.add(id); + bucket(pkg).operations.push(operationNames(op)); + } + + return [...byPackage.keys()].sort().map((pkg) => { + const { entities, operations } = byPackage.get(pkg)!; + const permissions = new Set(); + for (const e of entities) for (const c of e.commands) if (c.permission !== undefined) permissions.add(c.permission); + for (const o of operations) if (o.permission !== undefined) permissions.add(o.permission); + const errors = new Set(operations.flatMap((o) => o.errors)); + return { + package: pkg, + entities, + operations, + permissions: [...permissions].sort(), + errors: [...errors].sort(), + }; + }); +} diff --git a/server/typescript/packages/codegen-ts/src/templates/rules-names.ts b/server/typescript/packages/codegen-ts/src/templates/rules-names.ts new file mode 100644 index 0000000000..db09b87401 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/templates/rules-names.ts @@ -0,0 +1,97 @@ +// The rules names file of one metadata package (ADR-0067 §1, layer 0): its lifecycles' +// states and transitions, its derived commands, its declared operations, the permissions they +// ask about and the business errors its commands declare, as `as const` values and the literal +// unions read off them. +// +// This is the emit step only. What the names ARE comes from `rulesNamesOf` (engine), which +// reads the same derivations `meta verify`'s rules gate checks; change the file's shape here +// and keep that walk, so a constant and a verify message never name two different things. + +import { GENERATED_EDIT_NOTE, GENERATED_HEADER } from "../constants.js"; +import { toPascalCase } from "../naming.js"; +import { SHELL_ERROR_CODES, type RulesNamesEntity, type RulesNamesPackage } from "../rules-walk.js"; +import { TsWriter, arr, key, props, str } from "../writer/ts-writer.js"; + +const strings = (values: readonly string[]) => arr(values.map(str)); + +/** `Lifecycle`: the constant one lifecycle is written to. */ +export function lifecycleConstName(entity: string, field: string): string { + return `${entity}${toPascalCase(field)}Lifecycle`; +} + +function writeEntity(w: TsWriter, e: RulesNamesEntity): void { + for (const l of e.lifecycles) { + const name = lifecycleConstName(e.name, l.field); + const stem = name.slice(0, -"Lifecycle".length); + w.blank().doc(`The lifecycle of ${e.name}.${l.field}: its states, initial and terminal states, and transitions.`); + w.block(`export const ${name} = {`, () => { + w.line(`field: ${str(l.field)},`); + w.line("states: ", strings(l.states), ","); + if (l.initial !== undefined) w.line(`initial: ${str(l.initial)},`); + w.line("terminal: ", strings(l.terminal), ","); + w.block("transitions: {", () => { + for (const t of l.transitions) { + const body = props().set("from", strings(t.from)); + if (t.to !== undefined) body.set("to", str(t.to)); + w.line(`${key(t.name)}: `, body, ","); + } + }, "},"); + }, "} as const;"); + w.line(`export type ${stem}State = (typeof ${name}.states)[number];`); + w.line(`export type ${stem}Transition = keyof typeof ${name}.transitions;`); + } + if (e.commands.length === 0) return; + w.blank().doc( + `The commands derived from ${e.name}'s transitions (ADR-0066 §2): each takes the key and makes`, + "its transition. `permission` is what the shell asks the policy; `public` means it asks nothing.", + ); + w.block(`export const ${e.name}Commands = {`, () => { + for (const c of e.commands) { + const body = props().set("lifecycle", str(c.lifecycle)); + if (c.permission === undefined) body.set("public", "true"); + else body.set("permission", str(c.permission)); + w.line(`${key(c.name)}: `, body, ","); + } + }, "} as const;"); + w.line(`export type ${e.name}Command = keyof typeof ${e.name}Commands;`); +} + +/** The text of one package's `rules.names.ts`. */ +export function renderRulesNames(pkg: RulesNamesPackage): string { + const w = new TsWriter(); + w.header( + `// ${GENERATED_HEADER} — ${GENERATED_EDIT_NOTE}`, + `// Source metadata: rules of ${pkg.package === "" ? "the model" : `package ${pkg.package}`}`, + ); + + w.doc("The wire codes the enforcing shell answers with on its own (ADR-0066 §6)."); + w.line("export const ShellErrors = ", strings(SHELL_ERROR_CODES), " as const;"); + w.line("export type ShellError = (typeof ShellErrors)[number];"); + + for (const e of pkg.entities) writeEntity(w, e); + + if (pkg.operations.length > 0) { + w.blank().doc("The package's declared operations, with the permission each asks about."); + w.block("export const Operations = {", () => { + for (const o of pkg.operations) { + const body = props().set("kind", str(o.kind)); + if (o.permission === undefined) body.set("public", "true"); + else body.set("permission", str(o.permission)); + if (o.transitions.length > 0) body.set("transitions", strings(o.transitions)); + if (o.errors.length > 0) body.set("errors", strings(o.errors)); + w.line(`${key(o.name)}: `, body, ","); + } + }, "} as const;"); + w.line("export type Operation = keyof typeof Operations;"); + } + + w.blank().doc("Every permission a point of this package asks about: what a grant table names."); + w.line("export const Permissions = ", strings(pkg.permissions), " as const;"); + w.line("export type Permission = (typeof Permissions)[number];"); + + w.blank().doc("The business errors this package's commands declare (`@errors`)."); + w.line("export const BusinessErrors = ", strings(pkg.errors), " as const;"); + w.line("export type BusinessError = (typeof BusinessErrors)[number];"); + + return w.toString(); +} diff --git a/server/typescript/packages/codegen-ts/test/generator-registry.test.ts b/server/typescript/packages/codegen-ts/test/generator-registry.test.ts index 8f3b86ef50..2f8412fdc5 100644 --- a/server/typescript/packages/codegen-ts/test/generator-registry.test.ts +++ b/server/typescript/packages/codegen-ts/test/generator-registry.test.ts @@ -22,6 +22,7 @@ const EXPECTED_NATIVE = [ "routes-hono", "barrel", "names", + "rules-names", "report-export", "prompt-render", "output-parser", diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index 940687c421..cda6517100 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -22,6 +22,8 @@ import { routesFile as refRoutes } from "../src/reference/routes.js"; import { routesFileHono as refRoutesHono } from "../src/reference/routes-hono.js"; import { barrel as refBarrel } from "../src/reference/barrel.js"; import { namesFile as refNames } from "../src/reference/names.js"; +import { rulesNamesFile as builtinRulesNames } from "../src/generators/rules-names-file.js"; +import { rulesNamesFile as refRulesNames } from "../src/reference/rules-names.js"; import { reportExport as builtinReportExport } from "../src/generators/report-export-file.js"; import { reportExport as refReportExport } from "../src/reference/report-export.js"; import { promptRender as builtinPromptRender } from "../src/generators/prompt-render-file.js"; @@ -178,6 +180,9 @@ const PAIRS: Record Generator; ref: () "routes-hono": { builtin: builtinRoutesHono, ref: () => refRoutesHono(PKG) }, barrel: { builtin: builtinBarrel, ref: refBarrel }, names: { builtin: builtinNames, ref: refNames }, + // Emits nothing over the entity-shaped fixtures (none declares a lifecycle or an operation); + // test/rules-names.test.ts runs both over a rules model. + "rules-names": { builtin: builtinRulesNames, ref: refRulesNames }, // Emits nothing over the entity-shaped fixtures (none declares a served report); the // describe after the route-composition one runs the pair, with the routes, over the report corpus. "report-export": { builtin: builtinReportExport, ref: refReportExport }, diff --git a/server/typescript/packages/codegen-ts/test/reference-templates.test.ts b/server/typescript/packages/codegen-ts/test/reference-templates.test.ts index 91a71cbcda..90653dd92d 100644 --- a/server/typescript/packages/codegen-ts/test/reference-templates.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-templates.test.ts @@ -13,7 +13,7 @@ import { join } from "node:path"; describe("reference-templates reader", () => { test("exposes the copyable generator names, entity first (reader sentinel)", () => { expect([...REFERENCE_GENERATOR_NAMES]).toEqual([ - "entity", "queries", "routes", "routes-hono", "barrel", "names", "report-export", + "entity", "queries", "routes", "routes-hono", "barrel", "names", "rules-names", "report-export", "prompt-render", "output-parser", "extractor", "output-prompt", "render-helper", "requirement-tests", "cube-model", "prisma-schema", "contract-schema", "openapi", "callable", "trace-helper", "shared-model", "docs", "api-docs", "requirements", "agent-docs", "metamodel-docs", diff --git a/server/typescript/packages/codegen-ts/test/rules-names.test.ts b/server/typescript/packages/codegen-ts/test/rules-names.test.ts new file mode 100644 index 0000000000..d806d4e795 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/rules-names.test.ts @@ -0,0 +1,221 @@ +// `rulesNamesFile()` — the rules names layer (ADR-0067 §1, layer 0) over the ADR-0066 vocabulary. +// +// The expected names come from ADR-0066's derivation rules, stated per test: the states are the +// enum's `@values`, the initial state its `@default`, a terminal state one no transition leaves; a +// transition a declared command claims derives no command (under the default `unclaimed`); an +// absent `@permission` derives `.` or `..`, and +// `@public` asks nothing. The compile tests hold the emitted unions to what a consumer may write. + +import { describe, test, expect, setDefaultTimeout } from "bun:test"; +import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; +import ts from "typescript"; +import { MetaDataLoader, InMemoryStringSource, type MetaRoot, type RulesSettings } from "@metaobjectsdev/metadata"; +import { rulesNamesFile } from "../src/generators/index.js"; +import type { GenContext } from "../src/generator.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; + +setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); + +const transition = (name: string, from: string[], to: string, extra: Record = {}) => + ({ "transition.action": { name, "@from": from, "@to": to, ...extra } }); + +/** One sourced entity with a three-transition lifecycle, and an API whose command claims two. */ +function purchasing(pkg = "acme::purchasing"): unknown { + return { + "metadata.root": { + package: pkg, + children: [ + { + "object.entity": { + name: "PurchaseRequest", + children: [ + { "source.rdb": { "@table": "purchase_requests" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + { + "field.enum": { + name: "status", + "@values": ["draft", "submitted", "approved", "rejected"], + "@default": "draft", + children: [ + transition("submit", ["draft"], "submitted"), + transition("withdraw", ["submitted"], "draft", { "@public": true }), + transition("approve", ["submitted"], "approved"), + transition("reject", ["submitted"], "rejected", { "@permission": "purchasing.review" }), + ], + }, + }, + ], + }, + }, + { "object.value": { name: "DecisionInput", children: [{ "field.long": { name: "requestId", extends: "PurchaseRequest.id" } }] } }, + { + "api.operational": { + name: "Purchasing", + children: [ + { + "operation.command": { + name: "decide", + "@inputRef": "DecisionInput", + "@objectRef": "PurchaseRequest", + "@transitions": ["approve", "reject"], + "@errors": ["over_budget", "already_decided"], + }, + }, + { "operation.query": { name: "openRequests", "@outputRef": "PurchaseRequest", "@many": true, "@public": true } }, + ], + }, + }, + ], + }, + }; +} + +async function load(...models: unknown[]): Promise { + const result = await new MetaDataLoader({ strict: true }).load( + models.map((m, i) => new InMemoryStringSource(JSON.stringify(m), { id: `rules-${i}.json` })), + ); + expect(result.errors.map((e) => e.message)).toEqual([]); + return result.root; +} + +async function emit(root: MetaRoot, settings?: RulesSettings): Promise> { + if (settings !== undefined) root.rulesSettings = settings; + const ctx = { + entities: root.objects(), + loadedRoot: root, + matches: () => true, + projectRoot: "/", + config: { outputLayout: "flat", outDir: "/", extStyle: "js", dbImport: "~/db", dialect: "postgres" }, + warn: () => {}, + } as unknown as GenContext; + const files = await rulesNamesFile().generate(ctx); + return Object.fromEntries(files.map((f) => [f.path, f.content])); +} + +const PATH = "acme/purchasing/rules.names.ts"; + +describe("rulesNamesFile — what one package's file names", () => { + test("a lifecycle's states, initial, terminal states and transitions", async () => { + const file = (await emit(await load(purchasing())))[PATH]!; + expect(file).toContain(`export const PurchaseRequestStatusLifecycle = { + field: "status", + states: ["draft", "submitted", "approved", "rejected"], + initial: "draft", + terminal: ["approved", "rejected"], + transitions: { + submit: { from: ["draft"], to: "submitted" }, + withdraw: { from: ["submitted"], to: "draft" }, + approve: { from: ["submitted"], to: "approved" }, + reject: { from: ["submitted"], to: "rejected" }, + }, +} as const;`); + }); + + test("only unclaimed transitions derive a command; @public asks nothing, an absent @permission derives one", async () => { + const file = (await emit(await load(purchasing())))[PATH]!; + expect(file).toContain(`export const PurchaseRequestCommands = { + submit: { lifecycle: "status", permission: "acme::purchasing.PurchaseRequest.submit" }, + withdraw: { lifecycle: "status", public: true }, +} as const;`); + }); + + test("operations, the permission list and the business errors", async () => { + const file = (await emit(await load(purchasing())))[PATH]!; + expect(file).toContain(` decide: { + kind: "command", + permission: "acme::purchasing.decide", + transitions: ["approve", "reject"], + errors: ["over_budget", "already_decided"], + }, + openRequests: { kind: "query", public: true },`); + // decide's own permission and submit's derived one; withdraw and openRequests are public, and + // the claimed reject's @permission is the command's to ask, not a point of its own. + expect(file).toContain(`export const Permissions = ["acme::purchasing.PurchaseRequest.submit", "acme::purchasing.decide"] as const;`); + expect(file).toContain(`export const BusinessErrors = ["already_decided", "over_budget"] as const;`); + }); + + test("rules.lifecycle.commands: all derives every transition's command, none derives no command", async () => { + const all = (await emit(await load(purchasing()), { permissionNames: "advise", lifecycleCommands: "all" } as RulesSettings))[PATH]!; + for (const t of ["submit", "withdraw", "approve", "reject"]) expect(all).toMatch(new RegExp(`^ ${t}: \\{ lifecycle: "status"`, "m")); + expect(all).toContain(`reject: { lifecycle: "status", permission: "purchasing.review" }`); + const none = (await emit(await load(purchasing()), { permissionNames: "advise", lifecycleCommands: "none" } as RulesSettings))[PATH]!; + expect(none).not.toContain("PurchaseRequestCommands"); + expect(none).toContain(`export const Permissions = ["acme::purchasing.decide"] as const;`); + }); + + test("an inherited lifecycle is each concrete subtype's, and only a sourced one derives commands", async () => { + const lifecycleField = { + "field.enum": { name: "status", "@values": ["draft", "submitted"], "@default": "draft", children: [transition("submit", ["draft"], "submitted")] }, + }; + const root = await load({ + "metadata.root": { + package: "acme::purchasing", + children: [ + { "object.entity": { name: "Request", abstract: true, children: [ + { "field.long": { name: "id" } }, { "identity.primary": { name: "pk", "@fields": ["id"] } }, lifecycleField, + ] } }, + { "object.entity": { name: "TravelRequest", extends: "Request", children: [{ "source.rdb": { "@table": "travel_requests" } }] } }, + ], + }, + }); + const file = (await emit(root))[PATH]!; + expect(file).toContain("export const RequestStatusLifecycle = {"); + expect(file).toContain("export const TravelRequestStatusLifecycle = {"); + expect(file).toContain(`export const TravelRequestCommands = { + submit: { lifecycle: "status", permission: "acme::purchasing.TravelRequest.submit" }, +} as const;`); + expect(file).not.toContain("export const RequestCommands"); + }); + + test("one file per package that declares rules, and none for a model without them", async () => { + const plain = { "metadata.root": { package: "acme::catalog", children: [{ "object.entity": { name: "Item", children: [ + { "source.rdb": { "@table": "items" } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }] } }; + expect(Object.keys(await emit(await load(plain)))).toEqual([]); + expect(Object.keys(await emit(await load(plain, purchasing())))).toEqual([PATH]); + }); +}); + +describe("rulesNamesFile — the file compiles and its unions are narrow", () => { + function diagnostics(files: Record): string[] { + const dir = makeScratchDir("rules-names-compile-"); + try { + for (const [name, content] of Object.entries(files)) writeFileSync(join(dir, name), content); + const program = ts.createProgram(Object.keys(files).map((f) => join(dir, f)), { + strict: true, noEmit: true, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, skipLibCheck: true, + }); + return ts.getPreEmitDiagnostics(program).map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")); + } finally { + removeTree(dir); + } + } + + test("a consumer naming real states, transitions, permissions and errors compiles", async () => { + const names = (await emit(await load(purchasing())))[PATH]!; + const consumer = `import type { PurchaseRequestStatusState, PurchaseRequestStatusTransition, Permission, BusinessError, Operation, PurchaseRequestCommand } from "./rules.names.js"; +const s: PurchaseRequestStatusState = "approved"; +const t: PurchaseRequestStatusTransition = "withdraw"; +const p: Permission = "acme::purchasing.decide"; +const e: BusinessError = "over_budget"; +const o: Operation = "openRequests"; +const c: PurchaseRequestCommand = "submit"; +export { s, t, p, e, o, c }; +`; + expect(diagnostics({ "rules.names.ts": names, "consumer.ts": consumer })).toEqual([]); + }); + + test("a renamed or misspelt name does not compile", async () => { + const names = (await emit(await load(purchasing())))[PATH]!; + const consumer = `import type { PurchaseRequestStatusState, Permission, PurchaseRequestCommand } from "./rules.names.js"; +const s: PurchaseRequestStatusState = "approve"; +const p: Permission = "purchasing.review"; +const c: PurchaseRequestCommand = "approve"; +export { s, p, c }; +`; + expect(diagnostics({ "rules.names.ts": names, "consumer.ts": consumer })).toHaveLength(3); + }); +}); diff --git a/server/typescript/packages/metadata/src/core/transition/commands.ts b/server/typescript/packages/metadata/src/core/transition/commands.ts new file mode 100644 index 0000000000..f1583cfa8a --- /dev/null +++ b/server/typescript/packages/metadata/src/core/transition/commands.ts @@ -0,0 +1,131 @@ +// Permission points and derived commands (ADR-0066 §1, §2), shared by `meta verify`'s rules gate +// and the generators that read the rules vocabulary. Like lifecycle.ts, everything here is +// DERIVED: which transitions get a command of their own, and the permission name each point +// asks the policy about when it declares none. Every port derives these the same way. +// +// A command claims a transition NODE for its target entity and every entity that extends the +// target: a command acting on an abstract base claims the inherited transition of each child. +// A derived command exists per concrete entity with a source (lifecycleIsLive), and the +// `rules.lifecycle.commands` setting decides which transitions derive one. + +import type { MetaData } from "../../shared/meta-data.js"; +import { TYPE_API, TYPE_OBJECT, TYPE_OPERATION } from "../../shared/base-types.js"; +import { OBJECT_SUBTYPE_ENTITY } from "../object/object-constants.js"; +import { effectivePackageOf, topLevelNodeOf } from "../../naming-refs.js"; +import { + OPERATION_ATTR_PERMISSION, + OPERATION_ATTR_PUBLIC, + OPERATION_ATTR_TRANSITIONS, + OPERATION_SUBTYPE_COMMAND, +} from "../api/api-constants.js"; +import type { RulesSettings } from "../../rules-settings.js"; +import { entityLineage, entityTransitions, lifecycleIsLive, operationTarget } from "./lifecycle.js"; + +/** The root's `object.entity` children, in model order. */ +export function modelEntities(root: MetaData): MetaData[] { + return root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_ENTITY); +} + +/** Every declared operation, across every `api.*` of the root, in model order. */ +export function modelOperations(root: MetaData): MetaData[] { + return root.children() + .filter((c) => c.type === TYPE_API) + .flatMap((api) => api.children().filter((c) => c.type === TYPE_OPERATION)); +} + +/** One command's claim on a transition node, made for its target entity. */ +export interface TransitionClaim { + readonly target: MetaData; + readonly op: MetaData; +} + +/** Each transition node the declared commands claim, with the claims on it in model order. */ +export function claimedTransitions(root: MetaData): Map { + const claimed = new Map(); + for (const op of modelOperations(root)) { + if (op.subType !== OPERATION_SUBTYPE_COMMAND) continue; + const target = operationTarget(op); + if (target === undefined) continue; + const raw = op.attr(OPERATION_ATTR_TRANSITIONS); + const names = new Set(Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : []); + for (const t of entityTransitions(target)) { + if (!names.has(t.name)) continue; + const claims = claimed.get(t) ?? []; + claims.push({ target, op }); + claimed.set(t, claims); + } + } + return claimed; +} + +/** The claims that cover transition `t` on `entity`: those made for the entity or an entity it extends. */ +export function claimsOn(claimed: Map, entity: MetaData, t: MetaData): TransitionClaim[] { + const lineage = entityLineage(entity); + return (claimed.get(t) ?? []).filter((c) => lineage.includes(c.target)); +} + +/** Whether `t`, carried by `entity`, derives a command of its own under the setting. */ +export function derivesCommand( + claimed: Map, + settings: Pick, + entity: MetaData, + t: MetaData, +): boolean { + if (settings.lifecycleCommands === "none") return false; + if (settings.lifecycleCommands === "all") return true; + return claimsOn(claimed, entity, t).length === 0; +} + +/** The entities a transition can derive a command on: concrete, with a source. */ +export function commandEntities(root: MetaData): MetaData[] { + return modelEntities(root).filter((e) => !e.isAbstract && lifecycleIsLive(e)); +} + +/** The transitions of `entity` that derive a command of their own, in lifecycle order. Empty for + * an abstract entity or one with no source: such an entity derives no command. */ +export function derivedCommandsOf( + entity: MetaData, + claimed: Map, + settings: Pick, +): MetaData[] { + if (entity.isAbstract || !lifecycleIsLive(entity)) return []; + return entityTransitions(entity).filter((t) => derivesCommand(claimed, settings, entity, t)); +} + +/** + * The permission name a point gets when it declares none, `.`: the path is + * `` for a declared operation and `.` for a transition's derived + * command, so two entities' transitions of one name ask about different permissions. With no + * package the prefix is dropped. + */ +export function derivedPermissionName(owner: MetaData, path: string): string { + const pkg = effectivePackageOf(topLevelNodeOf(owner)); + return pkg === "" ? path : `${pkg}.${path}`; +} + +/** Whether a point is `@public: true`: the shell calls no permission check for it. */ +export function isPublicPoint(node: MetaData): boolean { + return node.attr(OPERATION_ATTR_PUBLIC) === true; +} + +/** Whether a point declares neither `@permission` nor `@public: true`, so it asks about a derived name. */ +export function needsPermissionName(node: MetaData): boolean { + return node.attr(OPERATION_ATTR_PERMISSION) === undefined && !isPublicPoint(node); +} + +/** The permission a declared operation asks the policy about: its `@permission`, else the derived + * `.`. Undefined for a `@public` operation, which asks about none. */ +export function operationPermission(op: MetaData): string | undefined { + if (isPublicPoint(op)) return undefined; + const declared = op.attr(OPERATION_ATTR_PERMISSION); + return typeof declared === "string" ? declared : derivedPermissionName(op, op.name); +} + +/** The permission a transition's derived command on `entity` asks about: the transition's + * `@permission`, else the derived `..` with the concrete entity's + * package. Undefined for a `@public` transition. */ +export function commandPermission(entity: MetaData, t: MetaData): string | undefined { + if (isPublicPoint(t)) return undefined; + const declared = t.attr(OPERATION_ATTR_PERMISSION); + return typeof declared === "string" ? declared : derivedPermissionName(entity, `${entity.name}.${t.name}`); +} diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 9df5535b5f..1a3675230f 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -73,6 +73,22 @@ export { type Lifecycle, type DerivedTarget, } from "./core/transition/lifecycle.js"; +// ADR-0066 — permission points and derived commands, shared by verify and the rules generators. +export { + modelEntities, + modelOperations, + claimedTransitions, + claimsOn, + derivesCommand, + commandEntities, + derivedCommandsOf, + derivedPermissionName, + isPublicPoint, + needsPermissionName, + operationPermission, + commandPermission, + type TransitionClaim, +} from "./core/transition/commands.js"; export { isDerivedExpr, derivedExprFields, type DerivedExprNode } from "./core/reporting/derived-expr.js"; export { reportFrom, @@ -461,7 +477,7 @@ export type { WireFormat, WireDecimals, WireNullMembers, WireDurations } from ". // ADR-0066: the `rules` and `verify` blocks of .metaobjects/config.json. export { RULES_PERMISSION_NAMES, RULES_LIFECYCLE_CREATE, RULES_LIFECYCLE_COMMANDS, VERIFY_LIFECYCLE_UNREACHABLE, - DEFAULT_RULES_SETTINGS, rulesSettingsOf, + DEFAULT_RULES_SETTINGS, rulesSettingsOf, rulesSettingsOfModel, } from "./rules-settings.js"; export type { RulesSettings, RulesConfigBlocks, RulesPermissionNames, RulesLifecycleCreate, RulesLifecycleCommands, diff --git a/server/typescript/packages/metadata/src/rules-settings.ts b/server/typescript/packages/metadata/src/rules-settings.ts index c6091e06f2..b51734934e 100644 --- a/server/typescript/packages/metadata/src/rules-settings.ts +++ b/server/typescript/packages/metadata/src/rules-settings.ts @@ -54,6 +54,16 @@ export interface RulesConfigBlocks { } | undefined; } +/** + * The settings of the project a node was loaded for: the root's `rulesSettings`, which the + * project-aware load sets from `.metaobjects/config.json` (as it sets `naming` and `wire`). A tree + * loaded with no project has the defaults. Generators read this; `meta verify` reads the same + * settings from its collection. + */ +export function rulesSettingsOfModel(node: { root(): unknown }): RulesSettings { + return (node.root() as { rulesSettings?: RulesSettings | undefined }).rulesSettings ?? DEFAULT_RULES_SETTINGS; +} + /** The settings a config declares, each absent key at its default. */ export function rulesSettingsOf(cfg: RulesConfigBlocks): RulesSettings { return { diff --git a/server/typescript/packages/metadata/src/shared/meta-root.ts b/server/typescript/packages/metadata/src/shared/meta-root.ts index ed7b252a20..0f13a21c63 100644 --- a/server/typescript/packages/metadata/src/shared/meta-root.ts +++ b/server/typescript/packages/metadata/src/shared/meta-root.ts @@ -11,6 +11,7 @@ import { DEFAULT_PHYSICAL_NAMING, type PhysicalNaming } from "../naming.js"; import { DEFAULT_WIRE_FORMAT, type WireFormat } from "../wire.js"; import { DEFAULT_ENUM_DEFAULTS, type EnumDefaults } from "../enum-length.js"; import type { ApiPagination, UnknownFieldsMode } from "../api-pagination.js"; +import { DEFAULT_RULES_SETTINGS, type RulesSettings } from "../rules-settings.js"; import { PACKAGE_SEPARATOR } from "./structural.js"; import { lookupCanonical } from "../naming-refs.js"; @@ -48,6 +49,13 @@ export class MetaRoot extends MetaData { */ apiUnknownFields: UnknownFieldsMode | undefined = undefined; + /** + * The project's business-rules settings (`rules` and `verify.lifecycle` in + * `.metaobjects/config.json`, ADR-0066 §5), set by the project-aware load and read through + * `rulesSettingsOfModel`. A tree loaded with no project has the defaults. + */ + rulesSettings: RulesSettings = DEFAULT_RULES_SETTINGS; + /** Object entities defined at this root level. */ objects(): MetaObject[] { return this.cached("objects", () => diff --git a/server/typescript/packages/sdk/src/memory.ts b/server/typescript/packages/sdk/src/memory.ts index bb605a2809..a9c2baf8f9 100644 --- a/server/typescript/packages/sdk/src/memory.ts +++ b/server/typescript/packages/sdk/src/memory.ts @@ -19,6 +19,7 @@ import { type EnumDefaults, type ApiPagination, type UnknownFieldsMode, + type RulesSettings, } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; // FR-043 — a node-only subpath (it reaches the filesystem), which is why it is imported @@ -124,6 +125,8 @@ export interface LoadMemoryOptions { apiPagination?: ApiPagination | undefined; /** `api.unknownFields`; on the no-`files` arm the collection supplies it. */ apiUnknownFields?: UnknownFieldsMode | undefined; + /** The business-rules settings (`rules`, `verify.lifecycle`); on the no-`files` arm the collection supplies them. */ + rulesSettings?: RulesSettings | undefined; } /** Default provider bundle threaded by {@link loadMemory} when no options @@ -217,7 +220,7 @@ type RawLoad = Awaited>; /** The checks {@link loadMemory} makes after the loader, and the root they leave. */ function finishLoad(run: RawLoad): MetaRoot { - const { result, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, enumDefaults, apiPagination, apiUnknownFields } = run; + const { result, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, enumDefaults, apiPagination, apiUnknownFields, rulesSettings } = run; if (result.errors.length > 0) { const first = result.errors[0]!; @@ -240,6 +243,7 @@ function finishLoad(run: RawLoad): MetaRoot { if (enumDefaults !== undefined) result.root.enumDefaults = enumDefaults; if (apiPagination !== undefined) result.root.apiPagination = apiPagination; if (apiUnknownFields !== undefined) result.root.apiUnknownFields = apiUnknownFields; + if (rulesSettings !== undefined) result.root.rulesSettings = rulesSettings; return result.root; } @@ -329,6 +333,7 @@ async function loadCollectionRaw( enumDefaults: EnumDefaults | undefined; apiPagination: ApiPagination | undefined; apiUnknownFields: UnknownFieldsMode | undefined; + rulesSettings: RulesSettings | undefined; }> { const extra = options?.providers ?? []; let providers: readonly MetaDataTypeProvider[]; @@ -360,6 +365,7 @@ async function loadCollectionRaw( let enumDefaults: EnumDefaults | undefined = options?.enumDefaults; let apiPagination: ApiPagination | undefined = options?.apiPagination; let apiUnknownFields: UnknownFieldsMode | undefined = options?.apiUnknownFields; + let rulesSettings: RulesSettings | undefined = options?.rulesSettings; if (options?.files !== undefined) { paths = [...options.files]; fileIds = options.fileIds; @@ -383,6 +389,7 @@ async function loadCollectionRaw( enumDefaults ??= collection.enumDefaults; apiPagination ??= collection.apiPagination; apiUnknownFields ??= collection.apiUnknownFields; + rulesSettings ??= collection.rulesSettings; } const loader = new MetaDataLoader({ @@ -408,7 +415,7 @@ async function loadCollectionRaw( return id === undefined ? new FileSource(p) : new FileSource(p, { id }); }), ]); - return { result, registry, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, enumDefaults, apiPagination, apiUnknownFields }; + return { result, registry, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, enumDefaults, apiPagination, apiUnknownFields, rulesSettings }; } /** Every source file that contributed to a node, across the envelope variants that From f8ca9563414df2d04efceac648c43dc6034b5439 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:18:24 -0500 Subject: [PATCH 02/16] feat(runtime-ts,fixtures): the guarded update and its shared persistence scenario (L-TS-3) ObjectManager.guardedUpdate makes a lifecycle transition's write in one statement: UPDATE ... SET state = :to WHERE key = :id AND state IN (:from) [AND condition]. The condition grammar is attr.expression's CHECK subset, compiled to new not/compare/nullTest WhereClause kinds on all three bundled drivers; the in-memory driver follows SQL three-valued logic. fixtures/persistence-conformance/queries/guarded-update.yaml holds every store driver to it. TypeScript runs it; Java, Kotlin, C# and Python defer it to their own rules-layer rows. --- CHANGELOG.md | 12 ++ docs/CONFORMANCE.md | 2 +- docs/features/business-rules.md | 4 +- fixtures/persistence-conformance/README.md | 32 ++- .../queries/guarded-update.yaml | 187 ++++++++++++++++++ .../Runner/CorpusPaths.cs | 16 +- .../Runner/ScenarioLoader.cs | 3 + .../integration/kotlin/Scenarios.kt | 4 +- .../metaobjects/integration/Scenarios.java | 4 +- .../tests/integration/test_query_scenarios.py | 4 +- .../integration-tests/src/query-scenario.ts | 20 +- .../integration-tests/src/scenario.ts | 30 ++- .../packages/runtime-ts/src/condition.ts | 99 ++++++++++ .../runtime-ts/src/drivers/drizzle-driver.ts | 15 +- .../src/drivers/in-memory-driver.ts | 52 ++++- .../runtime-ts/src/drivers/kysely-driver.ts | 14 +- .../packages/runtime-ts/src/index.ts | 4 +- .../packages/runtime-ts/src/object-manager.ts | 50 ++++- .../runtime-ts/src/persistence-driver.ts | 18 +- .../packages/runtime-ts/src/query-builder.ts | 41 +++- .../runtime-ts/test/guarded-update.test.ts | 156 +++++++++++++++ ...usiness-rules-operations-and-lifecycles.md | 8 +- 22 files changed, 745 insertions(+), 30 deletions(-) create mode 100644 fixtures/persistence-conformance/queries/guarded-update.yaml create mode 100644 server/typescript/packages/runtime-ts/src/condition.ts create mode 100644 server/typescript/packages/runtime-ts/test/guarded-update.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 69b1e0a192..3acc2f33eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,6 +99,18 @@ here.** 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`). +- **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, 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 diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 7d8211268b..10db6ff306 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -35,7 +35,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/jinja-verify-conformance/`](../fixtures/jinja-verify-conformance/) (ADR-0061 — the payload check over a Jinja body) | 31 | ✓ | refuses Jinja | refuses, via Java | refuses Jinja | ✓ | | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | -| [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 67 (55 query + 12 migration) | all 67; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query; the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | +| [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015; `guarded-update` deferred to L-JV-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed; `guarded-update` deferred to L-KT-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (`guarded-update` deferred to L-CS-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000; `guarded-update` deferred to L-PY-2); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | | [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 161 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 20 list-query) | ✓ (Fastify reference + generated lane); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` is TypeScript-only until each port's 1.3.0 REST-standard work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | | [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index eefc889b79..894d4aa3c8 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -17,7 +17,9 @@ the vocabulary. The layer generators of ADR-0067 do, and an app adds them to its it adds any generator. The first is `rules-names`, which writes the states, transitions, permissions and error codes as constants, in TypeScript (see [The names layer](#the-names-layer-typescript)) and C#; C# also ships `contract-types`, which writes -each entity's create and update records ([C# port](../ports/csharp.md)). The service shells that +each entity's create and update records ([C# port](../ports/csharp.md)). The TypeScript runtime makes the +guarded update a transition writes, `ObjectManager.guardedUpdate`, held to the shared +persistence scenario `guarded-update.yaml`. The service shells that enforce these rules at run time are later work. A lifecycle in a project that wires none will be advised by `verify` once that check lands; today the flat routes enforce nothing and `verify` says nothing about it. Every flat generator writes byte-identical code for diff --git a/fixtures/persistence-conformance/README.md b/fixtures/persistence-conformance/README.md index 6413db7da1..809083ffb8 100644 --- a/fixtures/persistence-conformance/README.md +++ b/fixtures/persistence-conformance/README.md @@ -235,12 +235,13 @@ TS: `om.findMany(entityName, filter, opts)`). | field | type | notes | |------------|---------------------------------------------|-------| -| `op` | `list \| get \| count \| relate \| create \| update \| delete \| roundtrip`| required | +| `op` | `list \| get \| count \| relate \| create \| update \| delete \| roundtrip \| guardedUpdate`| required | | `entity` | string | metadata name (Program, ProgramStat, …) | -| `by` | `{ id: scalar }` | required for `op: get`, `op: relate`, `op: update`, `op: delete` (the record key) | +| `by` | `{ id: scalar }` | required for `op: get`, `op: relate`, `op: update`, `op: delete`, `op: guardedUpdate` (the record key) | | `data` | row object | required for `op: create` / `op: update` (the row payload to write) | | `relation` | string | required for `op: relate`; the relationship name to traverse | | `insert` | row (field → value) | required for `op: roundtrip`; the row to WRITE through the runtime | +| `guard` | `{ field, from, to, condition? }` | required for `op: guardedUpdate`; the state field, the states it may be in, the state written, and an optional `@condition` node | | `filter` | filter object (below) | optional; same vocabulary as Project D | | `sort` | `[{ field, dir }]` | optional; `dir` ∈ `asc | desc` | | `limit` | integer | optional | @@ -350,6 +351,33 @@ native-uuid-write. > normalize → assert, PK excluded), then run these scenarios green; do not > delete them. +### `op: guardedUpdate` — the lifecycle transition's write (ADR-0066 §6) + +`guardedUpdate` makes the one statement a transition writes, through the port's +runtime or generated data access: + +``` +UPDATE … SET = :to WHERE = :id AND IN (:from) [AND ] +``` + +`guard.from` and `guard.to` are member SYMBOLS of the state field, and +`guard.condition` is a node of the `@condition` grammar (attr.expression's CHECK +subset: `field`, `value`, the six comparisons, `isNull` / `isNotNull`, `and` / `or` +/ `not`, and `coalesce`) over the entity's FIELD names. Every symbol and every +literal compared with a field is stored in that field's column form, so an +int-backed enum (`AllTypes.intEnumVal`) is guarded and written as its integer. +`expect` is the **boolean** answer: `true` when a row matched the guard and was +moved, `false` when none did (a row in another state, a failing condition, a +missing row, or the second of two moves out of the same state). A false move +writes nothing; prove it with a follow-up `op: get` or `op: count`. + +`guarded-update.yaml` is the scenario. Every store driver is held to it, including +one an adopter writes: a NULL operand in a condition matches nothing, as SQL's +three-valued logic says. The TypeScript runner drives +`ObjectManager.guardedUpdate`, on every `PersistenceDriver`. C#, Java, Kotlin and +Python defer it by name, with the 1.3.0 row that builds each one's guarded update +(L-CS-2, L-JV-2, L-KT-2, L-PY-2), and run it once that lands. + ### `op: relate` — relationship traversal (M:N) `relate` traverses a relationship from a single source record (`by`) and returns diff --git a/fixtures/persistence-conformance/queries/guarded-update.yaml b/fixtures/persistence-conformance/queries/guarded-update.yaml new file mode 100644 index 0000000000..c51fcc2cac --- /dev/null +++ b/fixtures/persistence-conformance/queries/guarded-update.yaml @@ -0,0 +1,187 @@ +name: guarded-update +description: | + The guarded update (ADR-0066 §6 step 5, §8): the store-neutral write a lifecycle transition + makes. One statement sets the state field to `to` where the key matches, the state is one of + `from`, and the transition's `@condition` (when it has one) holds: + + UPDATE ... SET = :to WHERE = :id AND IN (:from) [AND ] + + `op: guardedUpdate` answers whether a row matched the guard (true or false), and a follow-up + `op: get` or `op: count` reads what was written. A guard that matches no row writes nothing: a + row in another state, a row whose condition fails, a missing row, and the second of two moves + out of the same state all answer false and leave the row as it was. + + `guard.condition` is a node of the `@condition` grammar (attr.expression's CHECK subset: fields, + literals, comparisons, null tests, and, or, not and coalesce), over the entity's FIELD names. A + literal compared with a field is written in the form that field's column stores, and so is each + `from` and `to` member: `AllTypes.intEnumVal` is an int-backed enum, so `DRAFT` is stored as 0 + and `PUBLISHED` as 5, while the wire value stays the member symbol. + + Every store driver is held to this, including one an adopter writes. The TypeScript runner + drives `ObjectManager.guardedUpdate`; each other port runs it with its own guarded update. +seed-data: | + INSERT INTO "programs" ("id", "title", "priceCents", "status", "created_ts") VALUES + (1, 'Draft A', 4999, 'DRAFT', '2026-05-01T10:00:00'), + (2, 'Free draft', 0, 'DRAFT', '2026-05-02T10:00:00'), + (3, 'Live', 1500, 'PUBLISHED', '2026-05-03T10:00:00'), + (4, 'Old', 100, 'ARCHIVED', '2026-05-04T10:00:00'); + INSERT INTO "all_types" ( + "id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", + "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "intEnumVal", "uuidVal", + "uriVal", "inetVal", "inet6Val", "settings" + ) VALUES + ( + '33333333-3333-4333-8333-333333333331', + 'small', 1, 2, 0.5, 0.5, 1.5, true, + '2020-01-01', '00:00:00', '2020-01-01T00:00:00', '2020-01-01T00:00:00Z', + 100, 'LOW', 0, '11111111-1111-4111-8111-111111111111', + 'urn:example:one', '10.0.0.1', 'fe80::1', '{}' + ), + ( + '33333333-3333-4333-8333-333333333332', + 'large', 9, 2, 0.5, 0.5, 1.5, false, + '2020-01-01', '00:00:00', '2020-01-01T00:00:00', '2020-01-01T00:00:00Z', + 100, 'HIGH', 0, '11111111-1111-4111-8111-111111111112', + 'urn:example:two', '10.0.0.2', 'fe80::2', '{}' + ); +queries: + # --- the state guard ----------------------------------------------------------------------- + - name: move-from-the-from-state + op: guardedUpdate + entity: Program + by: { id: 1 } + guard: { field: status, from: [DRAFT], to: PUBLISHED } + expect: true + + - name: the-move-is-written + op: get + entity: Program + by: { id: 1 } + expect: { id: "1", title: "Draft A", priceCents: "4999", status: "PUBLISHED", createdAt: "2026-05-01T10:00:00" } + + - name: the-second-move-out-of-the-same-state-matches-nothing + op: guardedUpdate + entity: Program + by: { id: 1 } + guard: { field: status, from: [DRAFT], to: ARCHIVED } + expect: false + + - name: the-row-keeps-the-first-move + op: get + entity: Program + by: { id: 1 } + expect: { id: "1", title: "Draft A", priceCents: "4999", status: "PUBLISHED", createdAt: "2026-05-01T10:00:00" } + + - name: any-of-several-from-states + op: guardedUpdate + entity: Program + by: { id: 3 } + guard: { field: status, from: [DRAFT, PUBLISHED], to: ARCHIVED } + expect: true + + - name: a-row-in-no-from-state-matches-nothing + op: guardedUpdate + entity: Program + by: { id: 4 } + guard: { field: status, from: [DRAFT, PUBLISHED], to: ARCHIVED } + expect: false + + - name: a-missing-row-matches-nothing + op: guardedUpdate + entity: Program + by: { id: 999 } + guard: { field: status, from: [DRAFT], to: PUBLISHED } + expect: false + + # --- the condition ------------------------------------------------------------------------- + - name: a-failing-condition-matches-nothing + op: guardedUpdate + entity: Program + by: { id: 2 } + guard: + field: status + from: [DRAFT] + to: PUBLISHED + condition: { op: gt, left: { field: priceCents }, right: { value: 0 } } + expect: false + + - name: the-row-stays-in-its-state + op: get + entity: Program + by: { id: 2 } + expect: { id: "2", title: "Free draft", priceCents: "0", status: "DRAFT", createdAt: "2026-05-02T10:00:00" } + + - name: or-and-not-in-a-condition + op: guardedUpdate + entity: Program + by: { id: 2 } + guard: + field: status + from: [DRAFT] + to: PUBLISHED + condition: + op: and + args: + - op: or + args: + - { op: gt, left: { field: priceCents }, right: { value: 0 } } + - { op: eq, left: { field: title }, right: { value: "Free draft" } } + - op: not + arg: { op: isNull, arg: { field: title } } + expect: true + + - name: only-the-guarded-rows-moved + op: count + entity: Program + filter: { status: { eq: PUBLISHED } } + expect: 2 + + # --- an int-backed state, a field compared with a field, and coalesce ------------------------ + - name: a-field-compared-with-a-field-fails + op: guardedUpdate + entity: AllTypes + by: { id: "33333333-3333-4333-8333-333333333332" } + guard: + field: intEnumVal + from: [DRAFT] + to: PUBLISHED + condition: { op: lte, left: { field: iVal }, right: { field: lVal } } + expect: false + + - name: a-field-compared-with-a-field-holds + op: guardedUpdate + entity: AllTypes + by: { id: "33333333-3333-4333-8333-333333333331" } + guard: + field: intEnumVal + from: [DRAFT] + to: PUBLISHED + condition: { op: lte, left: { field: iVal }, right: { field: lVal } } + expect: true + + - name: an-int-backed-state-is-compared-and-written-as-its-integer + op: count + entity: AllTypes + filter: { intEnumVal: { eq: PUBLISHED } } + expect: 1 + + - name: coalesce-and-an-enum-literal-in-a-condition + op: guardedUpdate + entity: AllTypes + by: { id: "33333333-3333-4333-8333-333333333332" } + guard: + field: intEnumVal + from: [DRAFT] + to: ARCHIVED + condition: + op: and + args: + - { op: eq, left: { fn: coalesce, args: [{ field: sVal }, { value: "none" }] }, right: { value: "large" } } + - { op: eq, left: { field: enumVal }, right: { value: HIGH } } + expect: true + + - name: the-other-row-kept-its-state + op: count + entity: AllTypes + filter: { intEnumVal: { eq: ARCHIVED } } + expect: 1 diff --git a/server/csharp/MetaObjects.IntegrationTests/Runner/CorpusPaths.cs b/server/csharp/MetaObjects.IntegrationTests/Runner/CorpusPaths.cs index 002cd94127..0e7362deb7 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Runner/CorpusPaths.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Runner/CorpusPaths.cs @@ -26,8 +26,20 @@ internal static class CorpusPaths public static IEnumerable ScenariosFor(ScenarioEngine engine) => Directory.EnumerateFiles(QueriesDir, "*.yaml", SearchOption.TopDirectoryOnly) .OrderBy(p => p, StringComparer.Ordinal) - .Where(p => ScenarioLoader.LoadQuery(p).RunsOn(engine)) - .Select(p => new object[] { p }); + .Select(p => (Path: p, Scenario: ScenarioLoader.LoadQuery(p))) + .Where(s => s.Scenario.RunsOn(engine) && !Deferred.ContainsKey(s.Scenario.Name)) + .Select(s => new object[] { s.Path }); + + /// + /// Scenarios this port defers on every engine, each with the port gap that blocks it. Every + /// other scenario under queries/ runs, so a new fixture auto-runs or auto-fails and a + /// deferral is a deliberate entry here. xUnit 2 has no runtime skip, so a deferred scenario + /// is left out of the member data rather than skipped. + /// + public static readonly IReadOnlyDictionary Deferred = new Dictionary + { + ["guarded-update"] = "op: guardedUpdate: the guarded update on the generated context is not built yet (1.3.0 row L-CS-2)", + }; /// /// The committed canonical Postgres schema artifact. TypeScript is the single diff --git a/server/csharp/MetaObjects.IntegrationTests/Runner/ScenarioLoader.cs b/server/csharp/MetaObjects.IntegrationTests/Runner/ScenarioLoader.cs index 0fb9c3edee..a0ea4919ae 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Runner/ScenarioLoader.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Runner/ScenarioLoader.cs @@ -160,6 +160,9 @@ private sealed class QuerySpecYaml // the authoring forms (a quoted decimal/uuid stays a string; a nested object is // a mapping). Mirrors the Expect capture rationale above. public YamlNode? Insert { get; set; } + // For op: guardedUpdate — the guard (field, from, to, condition). Loaded so the + // scenario file parses; the op itself is deferred (CorpusPaths.Deferred). + public YamlNode? Guard { get; set; } public YamlNode? Expect { get; set; } } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/Scenarios.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/Scenarios.kt index 61e2339c32..cb4c4870d9 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/Scenarios.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/Scenarios.kt @@ -12,7 +12,9 @@ object Scenarios { * blocks it. Every other scenario under `queries/` runs, so a new fixture auto-runs or * auto-fails, forcing a deliberate entry here. */ - val DEFERRED: Map = emptyMap() + val DEFERRED: Map = mapOf( + "guarded-update" to "op: guardedUpdate: the Kotlin guarded update is not built yet (1.3.0 row L-KT-2)", + ) data class SortSpec(val field: String, val dir: String) diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/Scenarios.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/Scenarios.java index 1ed666672b..305f074113 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/Scenarios.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/Scenarios.java @@ -15,7 +15,9 @@ private Scenarios() {} * blocks it. A runner aborts (skips) a listed scenario instead of failing it; every other * scenario under {@code queries/} runs, so a new fixture auto-runs or auto-fails. */ - public static final Map DEFERRED = Map.of(); + public static final Map DEFERRED = Map.of( + "guarded-update", + "op: guardedUpdate: the guarded update on OMDB is not built yet (1.3.0 row L-JV-2)"); public record SortSpec(String field, String dir) {} diff --git a/server/python/tests/integration/test_query_scenarios.py b/server/python/tests/integration/test_query_scenarios.py index 020ec1d78a..5b0fa7d7b9 100644 --- a/server/python/tests/integration/test_query_scenarios.py +++ b/server/python/tests/integration/test_query_scenarios.py @@ -32,7 +32,9 @@ # inject/scope/strip. FR-017 Tier-4: the Python runtime now ships TPH support # (ObjectManagerDb discriminator inject/scope/strip + runtime/tph.py), so the # ``tph-*`` scenarios run green and are no longer skipped. -EXPECTED_FAILURES: dict[str, str] = {} +EXPECTED_FAILURES: dict[str, str] = { + "guarded-update": "op: guardedUpdate: the Python guarded update is not built yet (1.3.0 row L-PY-2)", +} # The same, for one engine only: (engine, scenario name) -> reason. The Python runtime's # SQLite and MySQL dialects bind no list parameter (``runtime/dialect.py`` encode_param has diff --git a/server/typescript/packages/integration-tests/src/query-scenario.ts b/server/typescript/packages/integration-tests/src/query-scenario.ts index 4ab454afd2..8e70ba5168 100644 --- a/server/typescript/packages/integration-tests/src/query-scenario.ts +++ b/server/typescript/packages/integration-tests/src/query-scenario.ts @@ -15,7 +15,7 @@ import { ObjectManager, type Filter } from "@metaobjectsdev/runtime-ts"; import { kyselyDriver } from "@metaobjectsdev/runtime-ts/drivers"; import { - type MetaRoot, + type ExprNode, type MetaRoot, TYPE_OBJECT, TYPE_IDENTITY, TYPE_FIELD, FIELD_SUBTYPE_DECIMAL, IDENTITY_SUBTYPE_PRIMARY, IDENTITY_ATTR_FIELDS, } from "@metaobjectsdev/metadata"; @@ -121,7 +121,7 @@ const DECIMAL_CANONICAL_RE = /^-?(0|[1-9][0-9]*)(\.[0-9]*[1-9])?$/; * the canonical spelling the runtime owes the wire. */ function assertDecimalsTyped(scenarioPath: string, spec: QuerySpec, actual: unknown, root: MetaRoot, engine: string): void { - if (spec.op === "count" || spec.op === "delete" || actual === null || actual === undefined) return; + if (spec.op === "count" || spec.op === "delete" || spec.op === "guardedUpdate" || actual === null || actual === undefined) return; const rows = (Array.isArray(actual) ? actual : [actual]) as Record[]; const names = decimalFieldNames(root, spec.entity); if (names.length === 0) return; @@ -197,6 +197,18 @@ async function execute(om: ObjectManager, root: MetaRoot, spec: QuerySpec): Prom if (spec.op === "count") { return await om.count(spec.entity, filter); } + if (spec.op === "guardedUpdate") { + if (!spec.by) throw new Error(`${spec.name}: op:guardedUpdate requires 'by' (the record key)`); + if (!spec.guard) throw new Error(`${spec.name}: op:guardedUpdate requires 'guard'`); + const ids = Object.values(spec.by); + if (ids.length !== 1) throw new Error(`${spec.name}: op:guardedUpdate supports single-field 'by' only`); + const { field, from, to, condition } = spec.guard; + // Answers whether a row matched the guard; a follow-up get or count reads what was written. + const row = await om.guardedUpdate(spec.entity, ids[0], { + field, from, to, ...(condition === null ? {} : { condition: condition as ExprNode }), + }); + return row !== null; + } if (spec.op === "relate") { if (!spec.by) throw new Error(`${spec.name}: op:relate requires 'by' (the source record key)`); if (!spec.relation) throw new Error(`${spec.name}: op:relate requires 'relation'`); @@ -289,7 +301,7 @@ function canonicalizeExpected(expect: unknown, op: QuerySpec["op"]): string { return String(n); } // `delete` returns a boolean outcome (true = a row was deleted). - if (op === "delete") return String(expect === true); + if (op === "delete" || op === "guardedUpdate") return String(expect === true); // `relate` (M:N navigation) is a SET — order is not part of the contract, so // sort both sides for a deterministic, port-agnostic comparison. `list` keeps // its order (the scenario pins it via `sort:`). @@ -299,7 +311,7 @@ function canonicalizeExpected(expect: unknown, op: QuerySpec["op"]): string { function canonicalizeActual(actual: unknown, op: QuerySpec["op"]): string { if (op === "count") return String(actual); - if (op === "delete") return String(actual === true); + if (op === "delete" || op === "guardedUpdate") return String(actual === true); if (op === "relate") { const rows = (Array.isArray(actual) ? actual : actual == null ? [] : [actual]) as Record[]; return canonicalRowSet(rows.map(normalizeRow)); diff --git a/server/typescript/packages/integration-tests/src/scenario.ts b/server/typescript/packages/integration-tests/src/scenario.ts index 3cbd32a84a..17bc196613 100644 --- a/server/typescript/packages/integration-tests/src/scenario.ts +++ b/server/typescript/packages/integration-tests/src/scenario.ts @@ -60,9 +60,17 @@ export interface QueryScenario { readonly queries: ReadonlyArray; } +/** The guard of an `op: guardedUpdate`: state field, from-states, to-state, optional condition. */ +export interface GuardSpec { + readonly field: string; + readonly from: readonly string[]; + readonly to: string; + readonly condition: unknown; +} + export interface QuerySpec { readonly name: string; - readonly op: "list" | "get" | "count" | "relate" | "create" | "update" | "delete" | "roundtrip"; + readonly op: "list" | "get" | "count" | "relate" | "create" | "update" | "delete" | "roundtrip" | "guardedUpdate"; readonly entity: string; readonly by: Record | null; /** @@ -94,6 +102,13 @@ export interface QuerySpec { * object); `expect` is the wire-normalized read-back form. */ readonly insert: Record | null; + /** + * For `op: guardedUpdate` (ADR-0066 §6 step 5): the transition's write. `field` is the state + * field, `from` the states the row must be in, `to` the state written, and `condition` an + * optional `@condition` expression node over the entity's field names. Requires `by: { id }`; + * `expect` is whether a row matched the guard (true or false). + */ + readonly guard: GuardSpec | null; /** * Either `{ field: { op: value } }` (each top-level key is a field name) or * `{ and: [filter, filter, ...] }` (compose by AND). Mixed forms are @@ -175,6 +190,7 @@ export function loadQuery(yamlPath: string): QueryScenario { expectError: q["expect-error"] === true, relation: q.relation ?? null, insert: (q.insert as Record | undefined) ?? null, + guard: parseGuard(q.guard, yamlPath), filter: (q.filter as Record | undefined) ?? null, sort: q.sort ? q.sort.map((s) => ({ field: s.field ?? "", dir: (s.dir as "asc" | "desc") ?? "asc" })) @@ -188,6 +204,17 @@ export function loadQuery(yamlPath: string): QueryScenario { // ---------- helpers ---------- +function parseGuard(raw: unknown, path: string): GuardSpec | null { + if (raw === undefined || raw === null) return null; + const g = raw as Record; + const from = g["from"]; + if (typeof g["field"] !== "string" || typeof g["to"] !== "string" || !Array.isArray(from) || from.length === 0 + || !from.every((f) => typeof f === "string")) { + throw new Error(`${path}: 'guard' needs a string 'field', a non-empty string list 'from' and a string 'to'`); + } + return { field: g["field"], from: from as string[], to: g["to"], condition: g["condition"] ?? null }; +} + function listYaml(dir: string): string[] { return readdirSync(dir) .filter((f) => f.endsWith(".yaml")) @@ -249,6 +276,7 @@ interface QueryYaml { "expect-error"?: boolean; relation?: string; insert?: unknown; + guard?: unknown; filter?: unknown; sort?: { field?: string; dir?: string }[]; limit?: number; diff --git a/server/typescript/packages/runtime-ts/src/condition.ts b/server/typescript/packages/runtime-ts/src/condition.ts new file mode 100644 index 0000000000..79b374174a --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/condition.ts @@ -0,0 +1,99 @@ +// A transition's `@condition` (ADR-0066 §1) as a driver WhereClause, so the guarded update +// (§6 step 5) can AND it into the one statement that makes the move. +// +// The grammar is attr.expression's CHECK subset — fields, literals, the six comparisons, the null +// tests, and / or / not, and coalesce — the same subset `meta migrate` renders as a CHECK. A node +// outside it is refused here rather than dropped, because a guard that silently loses its +// condition makes a move the model forbids. +// +// A literal compared with a field is written in the form that field's column stores (an +// int-backed enum's member is its integer), exactly as a filter value is: `encode` is the +// caller's filter-value encoder, so the condition and a list filter cannot disagree. + +import { + EXPR_FN_COALESCE, + EXPR_OP_IS_NOT_NULL, + EXPR_OP_NOT, + FILTER_COMPOSE_AND, + FILTER_COMPOSE_OR, + FILTER_OP_EQ, + FILTER_OP_GT, + FILTER_OP_GTE, + FILTER_OP_IS_NULL, + FILTER_OP_LT, + FILTER_OP_LTE, + FILTER_OP_NE, + type ExprNode, +} from "@metaobjectsdev/metadata"; +import { MetadataError } from "./errors.js"; +import type { CompareOp, Operand, PrimitiveValue, WhereClause } from "./persistence-driver.js"; + +const COMPARE_OPS: ReadonlySet = new Set([ + FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, +] as CompareOp[]); + +type Node = Record; + +/** How a condition reaches the entity: its column for a field name, and a literal's stored form. */ +export interface ConditionContext { + /** The physical column of `field`, or undefined when the entity has no such field. */ + column(field: string): string | undefined; + /** `value` in the form `field`'s column stores it (the filter-value encoder). */ + encode(field: string, value: PrimitiveValue): PrimitiveValue; +} + +/** `node`, a `@condition` expression, as a WhereClause over the entity's columns. */ +export function compileCondition(node: ExprNode, ctx: ConditionContext): WhereClause { + const n = node as Node; + const op = n["op"]; + if (typeof op === "string" && COMPARE_OPS.has(op)) { + return { + kind: "compare", + op: op as CompareOp, + left: operand(n["left"], storedFieldOf(n["right"]), ctx), + right: operand(n["right"], storedFieldOf(n["left"]), ctx), + }; + } + if (op === FILTER_OP_IS_NULL || op === EXPR_OP_IS_NOT_NULL) { + return { kind: "nullTest", operand: operand(n["arg"], undefined, ctx), not: op === EXPR_OP_IS_NOT_NULL }; + } + if (op === EXPR_OP_NOT) return { kind: "not", clause: compileCondition(n["arg"] as ExprNode, ctx) }; + if (op === FILTER_COMPOSE_AND || op === FILTER_COMPOSE_OR) { + const clauses = (n["args"] as ExprNode[]).map((a) => compileCondition(a, ctx)); + return { kind: op === FILTER_COMPOSE_AND ? "and" : "or", clauses }; + } + throw new MetadataError(`@condition: ${JSON.stringify(node)} is not a condition the guarded update can apply`); +} + +/** One comparison operand; a literal takes the stored form of `partner`, the field it is compared with. */ +function operand(x: unknown, partner: string | undefined, ctx: ConditionContext): Operand { + const n = (x ?? {}) as Node; + if (typeof n["field"] === "string") { + const column = ctx.column(n["field"]); + if (column === undefined) throw new MetadataError(`@condition names "${n["field"]}", which is not a field of the entity`); + return { column }; + } + if ("value" in n) { + const v = n["value"] as PrimitiveValue | null; + return { value: v === null || partner === undefined ? v : ctx.encode(partner, v) }; + } + if (n["fn"] === EXPR_FN_COALESCE && Array.isArray(n["args"])) { + // The arguments of a coalesce share its type, so a literal among them takes the first field's form. + const own = storedFieldOf(n) ?? partner; + return { coalesce: (n["args"] as unknown[]).map((a) => operand(a, own, ctx)) }; + } + throw new MetadataError(`@condition: ${JSON.stringify(x)} is not an operand the guarded update can apply`); +} + +/** The field whose stored form a literal compared with `node` takes (migrate's CHECK renderer's rule). */ +function storedFieldOf(node: unknown): string | undefined { + const n = (node ?? {}) as Node; + if (typeof n["field"] === "string") return n["field"]; + if (n["fn"] === EXPR_FN_COALESCE && Array.isArray(n["args"])) { + for (const a of n["args"] as unknown[]) { + const f = storedFieldOf(a); + if (f !== undefined) return f; + } + } + return undefined; +} diff --git a/server/typescript/packages/runtime-ts/src/drivers/drizzle-driver.ts b/server/typescript/packages/runtime-ts/src/drivers/drizzle-driver.ts index ca005dba26..ec8a9c4197 100644 --- a/server/typescript/packages/runtime-ts/src/drivers/drizzle-driver.ts +++ b/server/typescript/packages/runtime-ts/src/drivers/drizzle-driver.ts @@ -24,6 +24,7 @@ import { inArray as drzInArray, isNull as drzIsNull, isNotNull as drzIsNotNull, + not as drzNot, asc as drzAsc, desc as drzDesc, count as drzCount, @@ -44,7 +45,7 @@ import type { UpdateManySpec, DeleteSpec, DeleteManySpec, - WhereClause, PrimitiveValue, + WhereClause, PrimitiveValue, CompareOp, Operand, Row, } from "../persistence-driver.js"; import { ConstraintViolationError } from "../errors.js"; @@ -429,6 +430,14 @@ function jsKeyedFromSelect(row: Row, _selectMap: Record): Row } +const DRIZZLE_COMPARE = { eq: "=", ne: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=" } as const satisfies Record; + +function drizzleOperand(o: Operand, cols: Map): SQL | AnyColumn { + if ("column" in o) return cols.get(o.column); + if ("value" in o) return sql`${o.value}`; + return sql`COALESCE(${sql.join(o.coalesce.map((x) => sql`${drizzleOperand(x, cols)}`), sql`, `)})`; +} + function buildExpression(w: WhereClause, cols: Map, dialect: "sqlite" | "postgres" | "mysql"): unknown { switch (w.kind) { case "eq": { @@ -471,6 +480,10 @@ function buildExpression(w: WhereClause, cols: Map, dialect: const parts = w.clauses.map((c) => buildExpression(c, cols, dialect)) as SQL[]; return drzOr(...parts); } + case "not": return drzNot(buildExpression(w.clause, cols, dialect) as SQL); + case "compare": + return sql`${drizzleOperand(w.left, cols)} ${sql.raw(DRIZZLE_COMPARE[w.op])} ${drizzleOperand(w.right, cols)}`; + case "nullTest": return sql`${drizzleOperand(w.operand, cols)} ${sql.raw(w.not ? "IS NOT NULL" : "IS NULL")}`; default: { const exhaustive: never = w; throw new Error(`Unhandled WhereClause kind: ${JSON.stringify(exhaustive)}`); diff --git a/server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts b/server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts index e07f20efb1..863cb5d633 100644 --- a/server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts +++ b/server/typescript/packages/runtime-ts/src/drivers/in-memory-driver.ts @@ -1,6 +1,6 @@ import type { PersistenceDriver, SelectSpec, CountSpec, InsertSpec, InsertManySpec, - UpdateSpec, UpdateManySpec, DeleteSpec, DeleteManySpec, WhereClause, Row, + UpdateSpec, UpdateManySpec, DeleteSpec, DeleteManySpec, WhereClause, Row, CompareOp, Operand, } from "../persistence-driver.js"; import { ConstraintViolationError } from "../errors.js"; import { parseDurationLiteral } from "../duration-wire.js"; @@ -196,6 +196,16 @@ function pkKey(row: Row, pkFields: string[]): string { function matchesWhere(row: Row, where?: WhereClause): boolean { if (!where) return true; + return truth(row, where) === true; +} + +/** + * SQL's three-valued truth of `where` on `row`: null is unknown. A comparison with a NULL operand + * is unknown, NOT keeps unknown unknown, AND is false if any part is false, OR true if any is + * true, and only a true row matches — so a negated guard condition never matches a NULL row, as + * on a real engine. The column-and-value kinds keep their historical two-valued answers. + */ +function truth(row: Row, where: WhereClause): boolean | null { switch (where.kind) { case "eq": return sameValue(row[where.column], where.value); @@ -222,10 +232,31 @@ function matchesWhere(row: Row, where?: WhereClause): boolean { const isNull = row[where.column] === null || row[where.column] === undefined; return where.not ? !isNull : isNull; } - case "and": - return where.clauses.every((c) => matchesWhere(row, c)); - case "or": - return where.clauses.some((c) => matchesWhere(row, c)); + case "and": { + const parts = where.clauses.map((c) => truth(row, c)); + return parts.includes(false) ? false : parts.includes(null) ? null : true; + } + case "or": { + const parts = where.clauses.map((c) => truth(row, c)); + return parts.includes(true) ? true : parts.includes(null) ? null : false; + } + case "not": { + const t = truth(row, where.clause); + return t === null ? null : !t; + } + case "compare": { + const a = operandValue(row, where.left); + const b = operandValue(row, where.right); + if (a === null || b === null) return null; + if (where.op === "eq") return sameValue(a, b); + if (where.op === "ne") return !sameValue(a, b); + const c = compareValues(a, b); + return where.op === "gt" ? c > 0 : where.op === "gte" ? c >= 0 : where.op === "lt" ? c < 0 : c <= 0; + } + case "nullTest": { + const isNull = operandValue(row, where.operand) === null; + return where.not ? !isNull : isNull; + } default: { const exhaustive: never = where; throw new Error(`Unhandled WhereClause kind: ${JSON.stringify(exhaustive)}`); @@ -233,6 +264,17 @@ function matchesWhere(row: Row, where?: WhereClause): boolean { } } +/** An operand's value on `row`; NULL (and an absent column) is null. */ +function operandValue(row: Row, o: Operand): unknown { + if ("column" in o) return row[o.column] ?? null; + if ("value" in o) return o.value; + for (const x of o.coalesce) { + const v = operandValue(row, x); + if (v !== null) return v; + } + return null; +} + // Sort order: nulls are larger than any value, as in the SQL drivers (ASC last, DESC first). function compareForSort(a: unknown, b: unknown): number { const aNull = a === null || a === undefined; diff --git a/server/typescript/packages/runtime-ts/src/drivers/kysely-driver.ts b/server/typescript/packages/runtime-ts/src/drivers/kysely-driver.ts index 2ab55c95be..79e7a210ef 100644 --- a/server/typescript/packages/runtime-ts/src/drivers/kysely-driver.ts +++ b/server/typescript/packages/runtime-ts/src/drivers/kysely-driver.ts @@ -1,7 +1,7 @@ import type { Kysely, ExpressionBuilder, SelectQueryBuilder, Expression, SqlBool } from "kysely"; import type { PersistenceDriver, SelectSpec, CountSpec, InsertSpec, InsertManySpec, - UpdateSpec, UpdateManySpec, DeleteSpec, DeleteManySpec, WhereClause, Row, + UpdateSpec, UpdateManySpec, DeleteSpec, DeleteManySpec, WhereClause, Row, CompareOp, Operand, } from "../persistence-driver.js"; import { ConstraintViolationError } from "../errors.js"; import { likePatternToGlob } from "../drizzle-fastify/list-query.js"; @@ -222,6 +222,9 @@ function buildExpression(eb: AnyExprBuilder, w: WhereClause, dialect: KyselyDial case "isNull": return w.not ? eb(w.column, "is not", null) : eb(w.column, "is", null); case "and": return eb.and(w.clauses.map((c: WhereClause) => buildExpression(eb, c, dialect))); case "or": return eb.or(w.clauses.map((c: WhereClause) => buildExpression(eb, c, dialect))); + case "not": return eb.not(buildExpression(eb, w.clause, dialect)); + case "compare": return eb(kyselyOperand(eb, w.left), KYSELY_COMPARE[w.op], kyselyOperand(eb, w.right)); + case "nullTest": return eb(kyselyOperand(eb, w.operand), w.not ? "is not" : "is", null); default: { const exhaustive: never = w; throw new Error(`Unhandled WhereClause kind: ${JSON.stringify(exhaustive)}`); @@ -229,6 +232,15 @@ function buildExpression(eb: AnyExprBuilder, w: WhereClause, dialect: KyselyDial } } +const KYSELY_COMPARE = { eq: "=", ne: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=" } as const satisfies Record; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function kyselyOperand(eb: AnyExprBuilder, o: Operand): any { + if ("column" in o) return eb.ref(o.column); + if ("value" in o) return eb.val(o.value); + return eb.fn("coalesce", o.coalesce.map((x) => kyselyOperand(eb, x))); +} + function applyOrderLimit( q: AnyQuery, orderBy: { column: string; direction: "asc" | "desc" }[] | undefined, diff --git a/server/typescript/packages/runtime-ts/src/index.ts b/server/typescript/packages/runtime-ts/src/index.ts index 19dc0b9eb7..17860b3392 100644 --- a/server/typescript/packages/runtime-ts/src/index.ts +++ b/server/typescript/packages/runtime-ts/src/index.ts @@ -3,12 +3,12 @@ export type { ObjectManagerOptions, ReadOpts, WriteOpts } from "./object-manager export type { PersistenceDriver, Dialect, Row, PrimitiveValue, - WhereClause, OrderBy, + WhereClause, OrderBy, CompareOp, Operand, SelectSpec, CountSpec, InsertSpec, InsertManySpec, UpdateSpec, UpdateManySpec, DeleteSpec, DeleteManySpec, } from "./persistence-driver.js"; -export type { Filter, FilterValue, QueryOpts } from "./query-builder.js"; +export type { Filter, FilterValue, QueryOpts, TransitionGuard } from "./query-builder.js"; export type { FieldViewSpec, EntityViewSpec } from "./view.js"; diff --git a/server/typescript/packages/runtime-ts/src/object-manager.ts b/server/typescript/packages/runtime-ts/src/object-manager.ts index 6e7f7d974b..12535b25a0 100644 --- a/server/typescript/packages/runtime-ts/src/object-manager.ts +++ b/server/typescript/packages/runtime-ts/src/object-manager.ts @@ -4,7 +4,7 @@ import { TYPE_OBJECT, TYPE_FIELD, OBJECT_SUBTYPE_REPORT, isMetaObject, isMetaRoot, isReadOnlySource, reportReadModel, - FIELD_SUBTYPE_INT, + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_ENUM, FIELD_ATTR_VALUES, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, } from "@metaobjectsdev/metadata"; import type { @@ -12,9 +12,9 @@ import type { InsertManySpec, UpdateManySpec, DeleteManySpec, } from "./persistence-driver.js"; import { - buildSelectSpec, buildCountSpec, buildInsertSpec, buildUpdateSpec, buildDeleteSpec, + buildSelectSpec, buildCountSpec, buildInsertSpec, buildUpdateSpec, buildDeleteSpec, buildGuardedUpdateSpec, resolvePkFields, compileFilter, primaryKeyColumns, tableTarget, - type Filter, type QueryOpts, type DiscriminatorScope, + type Filter, type QueryOpts, type DiscriminatorScope, type TransitionGuard, } from "./query-builder.js"; import { tphSubtypeOf, type TphSubtype } from "./tph.js"; import { @@ -249,6 +249,50 @@ export class ObjectManager { return this.toJsRow(entity, dbRow); } + /** + * The guarded update (ADR-0066 §6 step 5): move the row keyed `id` to `guard.to` in ONE + * statement, only when its `guard.field` is one of `guard.from` and `guard.condition` holds. + * Answers the row as written, or null when the guard matched nothing — a row in another state, + * a failing condition, a missing row, or the loser of two concurrent moves. Null is the + * shell's 409, never a not-found, so `ifMissing` does not apply. + */ + async guardedUpdate(entityName: string, id: unknown, guard: TransitionGuard, opts: Pick = {}): Promise { + const entity = this.requireIdentified(entityName, "update"); + const driver = opts.tx ?? this.driver; + if (guard.from.length === 0) { + throw new MetadataError(`guardedUpdate on ${entityName}.${guard.field}: 'from' names no state`, { entity: entityName }); + } + // ADR-0039: effective children — the state field may be inherited through extends. + const state = entity.children().find((c) => c.type === TYPE_FIELD && c.name === guard.field); + if (state === undefined) { + throw new MetadataError(`guardedUpdate on ${entityName}: no field '${guard.field}'`, { entity: entityName }); + } + if (state.subType === FIELD_SUBTYPE_ENUM) { + // A lifecycle's states are its enum's members; a symbol outside them is a broken guard, not + // a guard that happens to match nothing (an unmapped symbol would otherwise be written raw). + const members = state.attr(FIELD_ATTR_VALUES); + const known = new Set(Array.isArray(members) ? members.map(String) : []); + const stray = [...guard.from, guard.to].filter((s) => !known.has(s)); + if (stray.length > 0) { + throw new MetadataError( + `guardedUpdate on ${entityName}.${guard.field}: ${stray.map((s) => JSON.stringify(s)).join(", ")} is not a member of its @values`, + { entity: entityName }, + ); + } + } + const write = { [guard.field]: guard.to }; + const validation = runValidators(entity, write, { partial: true }); + if (!validation.ok) { + throw new ValidationError(formatValidationMessage(entityName, validation.errors), { entity: entityName, errors: validation.errors }); + } + const coerced = coerceRowOnWrite(entity, write, driver.dialect); + const spec = buildGuardedUpdateSpec( + entity, coerced, this.coerceIdArg(entity, id), guard, this.columnNamingStrategy, this.tphScope(entity), driver.dialect, + ); + const dbRow = await driver.update(spec); + return dbRow === null ? null : this.toJsRow(entity, dbRow); + } + async delete(entityName: string, id: unknown, opts: WriteOpts = {}): Promise { const entity = this.requireIdentified(entityName, "delete"); const driver = opts.tx ?? this.driver; diff --git a/server/typescript/packages/runtime-ts/src/persistence-driver.ts b/server/typescript/packages/runtime-ts/src/persistence-driver.ts index ad8ef08dc0..0dde43e4df 100644 --- a/server/typescript/packages/runtime-ts/src/persistence-driver.ts +++ b/server/typescript/packages/runtime-ts/src/persistence-driver.ts @@ -16,7 +16,23 @@ export type WhereClause = | { kind: "ilike"; column: string; pattern: string } | { kind: "isNull"; column: string; not: boolean } | { kind: "and"; clauses: WhereClause[] } - | { kind: "or"; clauses: WhereClause[] }; + | { kind: "or"; clauses: WhereClause[] } + /** SQL NOT: three-valued, so NOT of an unknown (a comparison with NULL) stays unknown and matches nothing. */ + | { kind: "not"; clause: WhereClause } + /** A comparison of two operands, either of which may be a column, a literal or a coalesce. A + * transition's `@condition` compiles to these (ADR-0066 §6); a NULL operand matches nothing. */ + | { kind: "compare"; op: CompareOp; left: Operand; right: Operand } + /** IS [NOT] NULL over any operand (a column alone is `isNull`). */ + | { kind: "nullTest"; operand: Operand; not: boolean }; + +/** The six comparisons a `compare` clause makes. */ +export type CompareOp = "eq" | "ne" | "gt" | "gte" | "lt" | "lte"; + +/** One side of a `compare`: a column, a bound literal, or the first non-null of several operands. */ +export type Operand = + | { column: string } + | { value: PrimitiveValue | null } + | { coalesce: Operand[] }; export interface OrderBy { column: string; diff --git a/server/typescript/packages/runtime-ts/src/query-builder.ts b/server/typescript/packages/runtime-ts/src/query-builder.ts index 7d412183d5..380acfc79d 100644 --- a/server/typescript/packages/runtime-ts/src/query-builder.ts +++ b/server/typescript/packages/runtime-ts/src/query-builder.ts @@ -1,4 +1,4 @@ -import type { ColumnNamingStrategy, MetaData } from "@metaobjectsdev/metadata"; +import type { ColumnNamingStrategy, ExprNode, MetaData } from "@metaobjectsdev/metadata"; import { TYPE_FIELD, TYPE_IDENTITY, IDENTITY_SUBTYPE_PRIMARY, @@ -12,6 +12,7 @@ import { } from "@metaobjectsdev/metadata"; import { MetadataError } from "./errors.js"; import { intValueMapOf } from "./type-coercer.js"; +import { compileCondition } from "./condition.js"; import type { Dialect, WhereClause, OrderBy, PrimitiveValue, Row, SelectSpec, InsertSpec, UpdateSpec, DeleteSpec, CountSpec, TableTarget, @@ -353,6 +354,44 @@ export function buildUpdateSpec( }; } +/** + * A lifecycle transition's write (ADR-0066 §6 step 5): set `field` to `to` where the key matches, + * `field` is one of `from`, and `condition` (the transition's `@condition`) holds. `from`, `to` and + * every condition literal are the member SYMBOLS; each is stored in its column's form. + */ +export interface TransitionGuard { + field: string; + from: readonly string[]; + to: string; + condition?: ExprNode; +} + +/** + * The one statement a guarded update makes: `UPDATE … SET = :to WHERE = :id AND + * IN (:from) [AND ]`, TPH-scoped like any by-id write. `values` is the coerced + * write of `{ [field]: to }`. No row back means the guard matched nothing. + */ +export function buildGuardedUpdateSpec( + entity: MetaData, values: Row, id: unknown, guard: TransitionGuard, + strategy: ColumnNamingStrategy = DEFAULT_COLUMN_NAMING_STRATEGY, + scope?: DiscriminatorScope, + dialect?: Dialect, +): UpdateSpec { + const base = buildUpdateSpec(entity, values, id, strategy, scope); + const state = getField(entity, guard.field); + const clauses: WhereClause[] = [ + base.where, + { kind: "in", column: resolveColumnName(state, strategy), values: guard.from.map((s) => encodeFilterValue(state, s, dialect)) }, + ]; + if (guard.condition !== undefined) { + clauses.push(compileCondition(guard.condition, { + column: (f) => resolveColumnName(getField(entity, f), strategy), + encode: (f, v) => encodeFilterValue(getField(entity, f), v, dialect), + })); + } + return { ...base, where: { kind: "and", clauses } }; +} + export function buildDeleteSpec( entity: MetaData, id: unknown, strategy: ColumnNamingStrategy = DEFAULT_COLUMN_NAMING_STRATEGY, diff --git a/server/typescript/packages/runtime-ts/test/guarded-update.test.ts b/server/typescript/packages/runtime-ts/test/guarded-update.test.ts new file mode 100644 index 0000000000..c3bfb5e9f4 --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/guarded-update.test.ts @@ -0,0 +1,156 @@ +// ObjectManager.guardedUpdate — the lifecycle transition's one-statement write (ADR-0066 §6 +// step 5), on every bundled PersistenceDriver. The expected answers are SQL's: a row moves only +// when its state is one of `from` and the condition is TRUE, and a comparison with NULL is +// unknown, so a NOT over it is unknown too and matches nothing. The in-memory driver is held to +// the same answers as the two SQL drivers, which is what makes it a usable test double for one. + +import { describe, test, expect } from "bun:test"; +import { Kysely, sql } from "kysely"; +import { LibsqlDialect } from "@libsql/kysely-libsql"; +import { createClient } from "@libsql/client"; +import { drizzle as drizzleLibsql } from "drizzle-orm/libsql"; +import { sqliteTable, integer, text } from "drizzle-orm/sqlite-core"; +import { MetaDataLoader, InMemoryStringSource, type ExprNode, type MetaRoot } from "@metaobjectsdev/metadata"; +import { ObjectManager } from "../src/index.js"; +import { inMemoryDriver, kyselyDriver, drizzleDriver } from "../src/drivers/index.js"; +import type { PersistenceDriver, Row } from "../src/persistence-driver.js"; + +// `state` is int-backed (open=0, done=5, closed=9), so every guard symbol must be stored as its +// integer; `kind` is string-backed. amount, cap and note are nullable. +const MODEL = { + "metadata.root": { + package: "acme::desk", + children: [{ + "object.entity": { + name: "Ticket", + children: [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + { "field.enum": { name: "state", "@values": ["open", "done", "closed"], "@intValueMap": { open: 0, done: 5, closed: 9 } } }, + { "field.enum": { name: "kind", "@values": ["bug", "task"] } }, + { "field.int": { name: "amount" } }, + { "field.int": { name: "cap" } }, + { "field.string": { name: "note" } }, + ], + }, + }], + }, +}; + +const DDL = `CREATE TABLE tickets (id INTEGER PRIMARY KEY, state INTEGER NOT NULL, kind TEXT NOT NULL, + amount INTEGER, cap INTEGER, note TEXT)`; + +const drzTickets = sqliteTable("tickets", { + id: integer("id").primaryKey(), + state: integer("state").notNull(), + kind: text("kind").notNull(), + amount: integer("amount"), + cap: integer("cap"), + note: text("note"), +}); + +const SEED: Row[] = [ + { id: 1, state: "open", kind: "bug", amount: 5, cap: 10, note: "hi" }, + { id: 2, state: "open", kind: "task", amount: 20, cap: 10, note: null }, + { id: 3, state: "open", kind: "bug", amount: null, cap: 10, note: null }, + { id: 4, state: "done", kind: "bug", amount: 1, cap: 1, note: "x" }, +]; + +async function loadRoot(): Promise { + const result = await new MetaDataLoader({ strict: true }).load([new InMemoryStringSource(JSON.stringify(MODEL), { id: "desk.json" })]); + expect(result.errors.map((e) => e.message)).toEqual([]); + return result.root; +} + +const DRIVERS: { name: string; build: () => Promise }[] = [ + { name: "inMemoryDriver", build: async () => inMemoryDriver({ pkFields: { tickets: ["id"] } }) }, + { + name: "kyselyDriver/sqlite", + build: async () => { + const db = new Kysely>({ dialect: new LibsqlDialect({ url: ":memory:" }) }); + await sql.raw(DDL).execute(db); + return kyselyDriver({ db, dialect: "sqlite" }); + }, + }, + { + name: "drizzleDriver/sqlite", + build: async () => { + const client = createClient({ url: ":memory:" }); + await client.execute(DDL); + return drizzleDriver({ db: drizzleLibsql(client), schema: { tickets: drzTickets }, dialect: "sqlite" }); + }, + }, +]; + +const gt = (field: string, value: number): ExprNode => ({ op: "gt", left: { field }, right: { value } }); + +for (const d of DRIVERS) { + describe(`guardedUpdate on ${d.name}`, () => { + async function seeded(): Promise { + const om = new ObjectManager({ metadata: await loadRoot(), driver: await d.build() }); + for (const row of SEED) await om.create("Ticket", row); + return om; + } + const stateOf = async (om: ObjectManager, id: number) => (await om.findById("Ticket", id))?.["state"]; + + test("moves a row in a from-state, and the second move out of that state matches nothing", async () => { + const om = await seeded(); + const moved = await om.guardedUpdate("Ticket", 1, { field: "state", from: ["open"], to: "done" }); + expect(moved?.["state"]).toBe("done"); + expect(await om.guardedUpdate("Ticket", 1, { field: "state", from: ["open"], to: "closed" })).toBeNull(); + expect(await stateOf(om, 1)).toBe("done"); + }); + + test("a row in no from-state, and a missing row, match nothing and nothing is written", async () => { + const om = await seeded(); + expect(await om.guardedUpdate("Ticket", 4, { field: "state", from: ["open"], to: "closed" })).toBeNull(); + expect(await om.guardedUpdate("Ticket", 99, { field: "state", from: ["open"], to: "closed" })).toBeNull(); + expect(await stateOf(om, 4)).toBe("done"); + expect((await om.guardedUpdate("Ticket", 4, { field: "state", from: ["open", "done"], to: "closed" }))?.["state"]).toBe("closed"); + }); + + test("a column compared with a column", async () => { + const om = await seeded(); + const withinCap: ExprNode = { op: "lte", left: { field: "amount" }, right: { field: "cap" } }; + expect(await om.guardedUpdate("Ticket", 2, { field: "state", from: ["open"], to: "done", condition: withinCap })).toBeNull(); + expect((await om.guardedUpdate("Ticket", 1, { field: "state", from: ["open"], to: "done", condition: withinCap }))?.["state"]).toBe("done"); + }); + + test("NOT over a comparison with NULL is unknown and matches nothing (SQL three-valued logic)", async () => { + const om = await seeded(); + // Ticket 3's amount is NULL: `amount > 10` is unknown, and so is NOT of it. + const notLarge: ExprNode = { op: "not", arg: gt("amount", 10) }; + expect(await om.guardedUpdate("Ticket", 3, { field: "state", from: ["open"], to: "done", condition: notLarge })).toBeNull(); + expect(await stateOf(om, 3)).toBe("open"); + expect((await om.guardedUpdate("Ticket", 1, { field: "state", from: ["open"], to: "done", condition: notLarge }))?.["state"]).toBe("done"); + }); + + test("null tests, coalesce, or, and literals compared with enum fields in their stored form", async () => { + const om = await seeded(); + const cond: ExprNode = { + op: "and", + args: [ + { op: "eq", left: { fn: "coalesce", args: [{ field: "note" }, { value: "none" }] }, right: { value: "none" } }, + { op: "or", args: [gt("amount", 100), { op: "isNotNull", arg: { field: "amount" } }] }, + { op: "ne", left: { field: "state" }, right: { value: "closed" } }, + { op: "eq", left: { field: "kind" }, right: { value: "task" } }, + ], + } as ExprNode; + expect((await om.guardedUpdate("Ticket", 2, { field: "state", from: ["open"], to: "closed", condition: cond }))?.["state"]).toBe("closed"); + // Ticket 3 fails `kind = task` and the null test; ticket 1 fails the coalesce. + expect(await om.guardedUpdate("Ticket", 3, { field: "state", from: ["open"], to: "closed", condition: cond })).toBeNull(); + expect(await om.guardedUpdate("Ticket", 1, { field: "state", from: ["open"], to: "closed", condition: cond })).toBeNull(); + expect(await om.count("Ticket", { state: "closed" })).toBe(1); + }); + + test("a condition outside the @condition grammar, and a to-state that is not a member, are refused", async () => { + const om = await seeded(); + const relative = { op: "gt", left: { field: "amount" }, right: { now: "-P1D" } } as unknown as ExprNode; + await expect(om.guardedUpdate("Ticket", 1, { field: "state", from: ["open"], to: "done", condition: relative })).rejects.toThrow(/not an operand/); + await expect(om.guardedUpdate("Ticket", 1, { field: "state", from: ["open"], to: "shipped" })).rejects.toThrow(); + await expect(om.guardedUpdate("Ticket", 1, { field: "state", from: [], to: "done" })).rejects.toThrow(/names no state/); + expect(await stateOf(om, 1)).toBe("open"); + }); + }); +} diff --git a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md index c420af8fa4..f6f9f45824 100644 --- a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md +++ b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md @@ -294,8 +294,12 @@ routes enforce nothing. This is what the shells are held to: **The guarded update is part of the store-neutral storage contract** (§8). Every store driver, including one an adopter writes, will be held to it by a persistence-conformance scenario. -That scenario does not exist yet: no file under `fixtures/persistence-conformance/` pins the -guarded update, so until it lands the contract is stated here, not yet implemented or gated. +That scenario is `fixtures/persistence-conformance/queries/guarded-update.yaml` (`op: +guardedUpdate`): the state guard, a failing condition, a missing row, the second of two moves, and +a condition with a field compared with a field, `not`, `coalesce` and an int-backed state. The +TypeScript runtime implements it as `ObjectManager.guardedUpdate` on every bundled +`PersistenceDriver` and runs the scenario; the C#, Java, Kotlin and Python runners defer it by name +until each port builds its own guarded update in 1.3.0. ### 7. Events and invariants in 1.3.0 From 406c048017acfb81a633cef7178f7b492d05e0b1 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 14:51:25 -0500 Subject: [PATCH 03/16] feat(codegen-ts): contract types generator (L-TS-2) contractTypes() writes ADR-0067's contract types layer: the shapes a caller and a service exchange, with no persistence mapping in them. Every module imports zod only. - .contract.ts: the read schema and type, the create and update schemas, and the typed create and patch inputs. - .contract.ts: the read shape. - The value modules those shapes reach, byte-identical to the entity generator's, so the two collapse into one file when both run. - /operations.contract.ts: each declared operation's input, output and business errors. - errors.contract.ts: the shell and contract wire codes, their HTTP statuses, and the error bodies. The field schemas come from the entity generator's own renderers, and the tests hold each entity's contract read type equal to the entity file's on postgres, sqlite and mysql. Two exceptions are named in the test: a TPH base, and a physical-only jsonb column. What it covers is the engine walk (contract-walk.ts), so the generator is ejectable. It is TypeScript-only for now, and it moves no existing generator's output. --- CHANGELOG.md | 9 + docs/features/business-rules.md | 48 ++- docs/ports/typescript.md | 11 + fixtures/codegen-noop/rules/README.md | 6 +- .../generator-registry-conformance/README.md | 4 +- .../registry.json | 5 +- .../cli/test/unit/rules-inert.test.ts | 23 +- .../packages/codegen-ts/src/contract-walk.ts | 200 +++++++++++++ .../packages/codegen-ts/src/engine-surface.ts | 1 + .../packages/codegen-ts/src/engine.ts | 1 + .../codegen-ts/src/generator-registry.ts | 14 + .../src/generators/contract-types-file.ts | 109 +++++++ .../codegen-ts/src/generators/index.ts | 1 + .../codegen-ts/src/reference-templates.ts | 3 + .../src/reference/contract-types.ts | 114 ++++++++ .../src/templates/contract-types.ts | 206 +++++++++++++ .../codegen-ts/test/contract-types.test.ts | 276 ++++++++++++++++++ .../test/generator-registry.test.ts | 1 + .../test/reference-byte-identical.test.ts | 3 + .../test/reference-templates.test.ts | 2 +- 20 files changed, 1023 insertions(+), 14 deletions(-) create mode 100644 server/typescript/packages/codegen-ts/src/contract-walk.ts create mode 100644 server/typescript/packages/codegen-ts/src/generators/contract-types-file.ts create mode 100644 server/typescript/packages/codegen-ts/src/reference/contract-types.ts create mode 100644 server/typescript/packages/codegen-ts/src/templates/contract-types.ts create mode 100644 server/typescript/packages/codegen-ts/test/contract-types.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3acc2f33eb..7308935ea4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,6 +99,15 @@ here.** 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. TypeScript only + for now. 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 diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 894d4aa3c8..a6c67805dc 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -16,8 +16,10 @@ A requirement can claim an operation or a transition. The flat generators genera the vocabulary. The layer generators of ADR-0067 do, and an app adds them to its generator list as it adds any generator. The first is `rules-names`, which writes the states, transitions, permissions and error codes as constants, in TypeScript (see -[The names layer](#the-names-layer-typescript)) and C#; C# also ships `contract-types`, which writes -each entity's create and update records ([C# port](../ports/csharp.md)). The TypeScript runtime makes the +[The names layer](#the-names-layer-typescript)) and C#. The second is `contract-types`: in +TypeScript it writes the shapes and errors an operation takes and returns (see +[The contract types layer](#the-contract-types-layer-typescript)), and in C# so far each +entity's create and update records ([C# port](../ports/csharp.md)). The TypeScript runtime makes the guarded update a transition writes, `ObjectManager.guardedUpdate`, held to the shared persistence scenario `guarded-update.yaml`. The service shells that enforce these rules at run time are later work. A lifecycle in a project @@ -292,6 +294,48 @@ each derived permission name) comes from the same functions `verify`'s rules gat constant and a `verify` message name the same thing. The file ends in `.names.ts`, so `meta verify --codegen` treats a hand edit in it as drift, as it does for `.names.ts`. +## The contract types layer (TypeScript) + +`contractTypes()` (stable name `contract-types`, ejectable) writes the shapes a caller and a +service exchange, with no persistence mapping in them, so a transport, a client or a job can import +them without the ORM. Each module imports `zod` and nothing else. Beside where the entity generator +writes `.ts`, it writes: + +- `.contract.ts` for each store-backed entity: the read schema and type (`Schema`, + ``, a row as the store returns it), the create and update schemas with their validation + (`InsertSchema`, `UpdateSchema`) and the typed `Create` and + `Patch`. A TPH subtype's read schema pins its discriminator, and a TPH base's read type + is the union of its subtypes'; +- `.contract.ts` for each projection: its read schema and type, and nothing a caller + sends; +- the value module of each value object those shapes or an operation reach, byte for byte the + entity generator's, so the two collapse into one file when both run; +- `/operations.contract.ts` for each package that declares operations, under the + package's directory in either layout; +- `errors.contract.ts` at the target root: the wire error bodies. + +For the example's `decide` command and its queries: + +```ts +/** `decide` (command). */ +export const DecideInputSchema = DecisionInputInsertSchema; +export type DecideInput = z.input; +export type DecideBusinessError = "over_budget" | "already_decided"; +export type DecideError = ErrorBody; + +/** `openRequests` (query). */ +export type OpenRequestsOutput = readonly RequestSummary[]; +export type OpenRequestsBusinessError = never; +export type OpenRequestsError = ErrorBody; +``` + +`errors.contract.ts` carries the shell's codes (`ShellErrorCodes`) and the API contract's +(`ContractErrorCodes`), the HTTP status of each fixed code (`ErrorStatus`), and the bodies: +`ErrorBody`, `ValidationErrorBody` with its `issues`, and `ConstraintViolationBody` with its +`constraint` kind (see [API contract](api-contract.md)). It gives no status for a business error a +command declares; that is the service shell's to answer. A key a derived command or a keyed query +takes is not here either: the service generator decides its parameters. + ## Requirements can claim operations and transitions A level 5 requirement's `implementedBy` can name an operation as `.`, or a diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 7566158047..231f3a33b2 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -738,6 +738,17 @@ commands derived from unclaimed transitions (`Commands`), the declared ` `generators` or `meta eject rules-names`. The derivations are the ones `meta verify`'s rules gate checks. See [Business rules](../features/business-rules.md#the-names-layer-typescript). +### `*.contract.ts` — the contract types, with no persistence mapping + +`contractTypes()` (stable name `contract-types`) is the second rules layer of ADR-0067. It writes +`.contract.ts` (read, create and update shapes, as Zod schemas and their types), +`.contract.ts` (the read shape), the value modules they reach (the entity generator's, +byte for byte), `/operations.contract.ts` per package that declares operations (each +operation's input, output and errors) and `errors.contract.ts` (the wire error bodies). Every module +imports `zod` only. It is not scaffolded; add it to `generators` or `meta eject contract-types`, +and give it its own `target` to put the layer in a package the transport and clients share. See +[Business rules](../features/business-rules.md#the-contract-types-layer-typescript). + ### Prove it works Boot the server: diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md index 126446bf8e..7cd246688e 100644 --- a/fixtures/codegen-noop/rules/README.md +++ b/fixtures/codegen-noop/rules/README.md @@ -21,8 +21,10 @@ the two models produce the same output everywhere: is byte-identical, and its payload gains only lines of those four types. The generators of the rules layers themselves (ADR-0067) are the other exception: reading this -vocabulary is their job. Each writes nothing for `without/` and only files of its own for -`with/`, so it adds files and moves none. Today that is TypeScript's `rules-names`. +vocabulary is their job. Each adds only files of its own for `with/`, and moves none of what it +writes for `without/`. Today those are TypeScript's `rules-names`, which writes nothing for +`without/`, and `contract-types`, whose entity contracts do not depend on the vocabulary and whose +operations module (and the value object only an operation reaches) does. A generator that started reading an operation or a transition by accident would emit something half-built; these tests are what notice: diff --git a/fixtures/generator-registry-conformance/README.md b/fixtures/generator-registry-conformance/README.md index affeabd200..9a8e7a6244 100644 --- a/fixtures/generator-registry-conformance/README.md +++ b/fixtures/generator-registry-conformance/README.md @@ -32,7 +32,7 @@ to make the choice cheap, and `layer` is the axis it is cheap along. | layer | members | chosen by | |---|---|---| -| `model` | entity, names, rules-names, barrel, dto, value-object | app shape | +| `model` | entity, names, rules-names, contract-types, barrel, dto, value-object | app shape | | `persistence` | queries, prisma-schema, db-context, repository, exposed-table, relations, stored-proc | app shape | | `api` | routes, routes-hono, filter-allowlist, validator, spring-config, contract-schema, openapi | app shape | | `client` | form, hooks, grid, grid-hook, client, commands | app shape | @@ -125,6 +125,8 @@ object's type now comes from the value-object generator, so the template tier de One name is **TypeScript-only for now**: `rules-names`, the first rules layer of ADR-0067 (the names of a package's lifecycle states, transitions, commands, operations, permissions and business errors). Each other port adds itself to its `ports` with its own rules-layer work. +So is `contract-types`, ADR-0067 layer 1 (the read, create and update shapes, the operations' +inputs and outputs, and the wire error bodies, with no persistence mapping), on the same terms. ## Changing the surface diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 41c8d61e5c..119a7a2ad8 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -112,11 +112,11 @@ "ports": ["typescript", "csharp"] }, "contract-types": { - "concept": "Per-entity create and update records (ADR-0067 layer 1): the members a client sends to create a row and may change on update, with the entity's validation; the server-owned members (generated key, @autoSet stamp, readOnly and derived fields, TPH discriminator) are on neither, and the update record tells an omitted member from an explicit null.", + "concept": "Contract types with no persistence mapping (ADR-0067 layer 1): each store-backed entity's read, create and update shapes, each projection's read shape, each declared operation's input, output and errors, and the wire error bodies. TypeScript writes the whole layer. C# so far writes each entity's create and update records, which leave out the server-owned members (generated key, @autoSet stamp, readOnly and derived fields, TPH discriminator) and tell an omitted member from an explicit null. The other ports add theirs with their rules-layer work.", "tier": "native", "layer": "model", "eject": "full", - "ports": ["csharp"] + "ports": ["typescript", "csharp"] }, "prompt-render": { "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other four ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", @@ -394,6 +394,7 @@ "codegen-ts/src/client-directive.ts", "codegen-ts/src/column-mapper.ts", "codegen-ts/src/constants.ts", + "codegen-ts/src/contract-walk.ts", "codegen-ts/src/dialect-module.ts", "codegen-ts/src/docs-paths.ts", "codegen-ts/src/docs-run.ts", diff --git a/server/typescript/packages/cli/test/unit/rules-inert.test.ts b/server/typescript/packages/cli/test/unit/rules-inert.test.ts index 9f21f09db7..aa2d6f200b 100644 --- a/server/typescript/packages/cli/test/unit/rules-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/rules-inert.test.ts @@ -90,9 +90,15 @@ async function emit(metadata: MetaRoot, generators: Generator[]): Promise = { "rules-names": ["src/generated/acme/purchasing/rules.names.ts"], + // Its entity contracts and error bodies do not depend on the vocabulary; the operations do, and + // so does the value object only an operation reaches. + "contract-types": [ + "src/generated/DecisionInput.ts", + "src/generated/acme/purchasing/operations.contract.ts", + ], }; let withRules: MetaRoot; @@ -122,9 +128,13 @@ describe("ADR-0066 the business-rules vocabulary is inert in every generator and } for (const [name, files] of Object.entries(RULES_LAYER)) { - test(`rules-layer generator "${name}" writes nothing without the vocabulary, and only its own files with it`, async () => { - expect(await emit(withoutRules, [catalog[name]!.factory()])).toEqual({}); - expect(Object.keys(await emit(withRules, [catalog[name]!.factory()])).sort()).toEqual(files); + test(`rules-layer generator "${name}" adds only its own files for the vocabulary, and moves none`, async () => { + const expected = await emit(withoutRules, [catalog[name]!.factory()]); + const actual = await emit(withRules, [catalog[name]!.factory()]); + expect(expected[""]).toBeUndefined(); + expect(Object.keys(actual).filter((p) => !(p in expected)).sort()).toEqual(files); + for (const p of files) delete actual[p]; + expect(actual).toEqual(expected); }); } @@ -160,8 +170,9 @@ describe("ADR-0066 the business-rules vocabulary is inert in every generator and const actual = await emit(withRules, runnable.map((f) => f())); expect(expected[""]).toBeUndefined(); expect(Object.keys(expected).length).toBeGreaterThan(10); - // The rules layers add their own files beside the rest, and move none of them. - const added = Object.values(RULES_LAYER).flat(); + // The rules layers add their own files beside the rest, and move none of them. A value module + // the contract layer writes for an operation is the entity generator's, already in both runs. + const added = Object.values(RULES_LAYER).flat().filter((p) => !(p in expected)); expect(Object.keys(actual).filter((p) => !(p in expected)).sort()).toEqual([...added].sort()); for (const p of added) delete actual[p]; expect(actual).toEqual(expected); diff --git a/server/typescript/packages/codegen-ts/src/contract-walk.ts b/server/typescript/packages/codegen-ts/src/contract-walk.ts new file mode 100644 index 0000000000..ccdacfa1e4 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/contract-walk.ts @@ -0,0 +1,200 @@ +// What the contract types layer covers (ADR-0067 §1, layer 1), for one model. +// +// Engine, not emit: `contractTypes()` renders these records, and an ejected copy of its renderer +// keeps calling this walk, so which objects carry a contract and how an operation's input and +// output resolve stays packaged while the files' shape is the adopter's. +// +// Covered: +// - every concrete `object.entity` backed by a store: read, create and update shapes; +// - every concrete `object.projection`: its read shape; +// - every `object.value` those shapes or an operation's `@inputRef` / `@outputRef` reach, as the +// value module the entity generator writes (byte for byte, so the two collapse in one run); +// - each package's declared operations: input, output and the errors they may answer. +// Not covered: reports (their read rows are the report generators'), abstract objects, and the +// key a derived command or a keyed query takes (the service generator decides its parameters). + +import { + FIELD_ATTR_OBJECT_REF, + FIELD_SUBTYPE_OBJECT, + OBJECT_SUBTYPE_ENTITY, + OBJECT_SUBTYPE_PROJECTION, + OBJECT_SUBTYPE_VALUE, + OPERATION_ATTR_ERRORS, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_MANY, + OPERATION_ATTR_OUTPUT_REF, + OPERATION_SUBTYPE_COMMAND, + RESERVED_ERROR_CODES, + TYPE_FIELD, + effectivePackageOf, + isMetaObject, + modelOperations, + operationTarget, + refTarget, + topLevelNodeOf, + type MetaData, + type MetaObject, +} from "@metaobjectsdev/metadata"; +import { relative as posixRelative } from "node:path/posix"; +import { SHELL_ERROR_CODES } from "./rules-walk.js"; +import { entityOutputPath, packageToPath, type OutputLayout } from "./import-path.js"; +import { withExtIfRelative, type ExtStyle } from "./render-context.js"; +import { effectivePackage } from "./docs-paths.js"; +import { hasAnyRdbSource } from "./source-detect.js"; +import { isAbstract } from "./instance-artifacts.js"; + +export { SHELL_ERROR_CODES }; + +/** The wire codes the REST contract's transport answers with: the reserved codes the shell does + * not (ADR-0066 O5). */ +export const CONTRACT_ERROR_CODES = RESERVED_ERROR_CODES.filter((c) => !SHELL_ERROR_CODES.includes(c)) as readonly string[]; + +/** One declared operation, with its `@inputRef` and `@outputRef` resolved. */ +export interface ContractOperation { + readonly name: string; + readonly kind: "command" | "query"; + /** The `@inputRef` value object, when declared. */ + readonly input: MetaObject | undefined; + /** The `@outputRef` entity, projection or value, when declared. */ + readonly output: MetaObject | undefined; + readonly many: boolean; + /** The business errors a command declares (`@errors`), in declaration order. */ + readonly errors: readonly string[]; +} + +/** One package's declared operations. */ +export interface ContractPackage { + /** The package (`acme::shop`), or `""` for a model with none. */ + readonly package: string; + readonly operations: readonly ContractOperation[]; +} + +/** The contract types of a model. */ +export interface ContractModel { + /** Entities and projections that get `.contract.ts`, in model order. */ + readonly objects: readonly MetaObject[]; + /** Value objects the contract reaches, in model order. */ + readonly values: readonly MetaObject[]; + /** Packages with at least one declared operation, sorted by package. */ + readonly packages: readonly ContractPackage[]; +} + +export interface ContractWalkOpts { + /** Narrow which objects are covered (a generator's `filter` and `--select`). An operation is + * kept when its target entity matches or it has none. */ + readonly matches?: (obj: MetaData) => boolean; +} + +function strings(node: MetaData, attr: string): string[] { + const v = node.attr(attr); + return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; +} + +function objectRef(node: MetaData, attr: string): MetaObject | undefined { + const target = refTarget(node, attr); + return target !== undefined && isMetaObject(target) ? target : undefined; +} + +/** Whether `obj` gets its own `.contract.ts`. */ +export function hasObjectContract(obj: MetaObject): boolean { + if (isAbstract(obj)) return false; + if (obj.subType === OBJECT_SUBTYPE_ENTITY) return hasAnyRdbSource(obj); + return obj.subType === OBJECT_SUBTYPE_PROJECTION; +} + +/** The value objects `obj`'s fields reference (`field.object @objectRef`), resolving. */ +function referencedValues(obj: MetaData): MetaObject[] { + const out: MetaObject[] = []; + for (const f of obj.children()) { + if (f.type !== TYPE_FIELD || f.subType !== FIELD_SUBTYPE_OBJECT) continue; + const target = objectRef(f, FIELD_ATTR_OBJECT_REF); + if (target !== undefined && target.subType === OBJECT_SUBTYPE_VALUE) out.push(target); + } + return out; +} + +/** The contract types of `root`: which objects get one, the values they reach, and the operations. */ +export function contractTypesOf(root: MetaData, opts: ContractWalkOpts = {}): ContractModel { + const matches = opts.matches ?? (() => true); + const all = root.children().filter(isMetaObject); + const objects = all.filter((o) => hasObjectContract(o) && matches(o)); + + const packages = new Map(); + // One operation declared identically by two APIs (a versioned API) is one operation (O6). + const seen = new Set(); + for (const op of modelOperations(root)) { + const target = operationTarget(op); + if (target !== undefined && !matches(target)) continue; + const pkg = effectivePackageOf(topLevelNodeOf(op)); + const id = `${pkg}\u0000${op.name.toLowerCase()}`; + if (seen.has(id)) continue; + seen.add(id); + const kind = op.subType === OPERATION_SUBTYPE_COMMAND ? "command" : "query"; + const ops = packages.get(pkg) ?? []; + packages.set(pkg, ops); + ops.push({ + name: op.name, + kind, + input: objectRef(op, OPERATION_ATTR_INPUT_REF), + output: objectRef(op, OPERATION_ATTR_OUTPUT_REF), + many: op.attr(OPERATION_ATTR_MANY) === true, + errors: kind === "command" ? strings(op, OPERATION_ATTR_ERRORS) : [], + }); + } + + // Every value a covered shape reaches, transitively, so a contract module never imports a value + // module the run did not write. + const reached = new Set(); + const queue: MetaData[] = [...objects]; + const reach = (v: MetaObject | undefined) => { + if (v === undefined || v.subType !== OBJECT_SUBTYPE_VALUE || reached.has(v)) return; + reached.add(v); + queue.push(v); + }; + for (const ops of packages.values()) { + for (const o of ops) { + reach(o.input); + reach(o.output); + } + } + while (queue.length > 0) for (const v of referencedValues(queue.shift()!)) reach(v); + + return { + objects, + values: all.filter((o) => reached.has(o)), + packages: [...packages.keys()].sort().map((pkg) => ({ package: pkg, operations: packages.get(pkg)! })), + }; +} + +/** The suffix of an object's contract module (`Order.contract.ts`). */ +export const CONTRACT_FILE_SUFFIX = ".contract.ts"; +/** The wire error module, at the target root. */ +export const CONTRACT_ERRORS_FILE = "errors.contract.ts"; +/** The operations module, one per package that declares operations. */ +export const CONTRACT_OPERATIONS_FILE = "operations.contract.ts"; + +/** Where `obj`'s contract module goes: beside where the entity generator writes `.ts`. */ +export function contractObjectPath(layout: OutputLayout, obj: MetaObject): string { + return entityOutputPath(layout, effectivePackage(obj), `${obj.name}${CONTRACT_FILE_SUFFIX}`); +} + +/** Where a value object's module goes: the entity generator's own path, so the two collapse. */ +export function contractValuePath(layout: OutputLayout, obj: MetaObject): string { + return entityOutputPath(layout, effectivePackage(obj), `${obj.name}.ts`); +} + +/** Where a package's operations module goes: under the package's directory in either layout, so + * two packages never both write it. */ +export function contractOperationsPath(pkg: string): string { + const dir = packageToPath(pkg); + return dir === "" ? CONTRACT_OPERATIONS_FILE : `${dir}/${CONTRACT_OPERATIONS_FILE}`; +} + +/** The module specifier from the file at `fromFile` to the module file `toFile`, both relative to + * the target's outDir. */ +export function contractSpecifier(fromFile: string, toFile: string, extStyle: ExtStyle): string { + const fromDir = fromFile.includes("/") ? fromFile.slice(0, fromFile.lastIndexOf("/")) : ""; + let rel = posixRelative(fromDir, toFile.replace(/\.ts$/, "")); + if (!rel.startsWith(".")) rel = `./${rel}`; + return withExtIfRelative(rel, extStyle); +} diff --git a/server/typescript/packages/codegen-ts/src/engine-surface.ts b/server/typescript/packages/codegen-ts/src/engine-surface.ts index c3830ad380..5b5b878b6f 100644 --- a/server/typescript/packages/codegen-ts/src/engine-surface.ts +++ b/server/typescript/packages/codegen-ts/src/engine-surface.ts @@ -31,6 +31,7 @@ export const ENGINE_MODULES: readonly string[] = [ "codegen-ts/src/client-directive.ts", "codegen-ts/src/column-mapper.ts", "codegen-ts/src/constants.ts", + "codegen-ts/src/contract-walk.ts", "codegen-ts/src/dialect-module.ts", "codegen-ts/src/docs-paths.ts", "codegen-ts/src/docs-run.ts", diff --git a/server/typescript/packages/codegen-ts/src/engine.ts b/server/typescript/packages/codegen-ts/src/engine.ts index 22a7e13045..84e5404fcc 100644 --- a/server/typescript/packages/codegen-ts/src/engine.ts +++ b/server/typescript/packages/codegen-ts/src/engine.ts @@ -54,6 +54,7 @@ export * from "./render-engine/framework-provider.js"; export * from "./requirement-walk.js"; export * from "./routes-expose.js"; export * from "./rules-walk.js"; +export * from "./contract-walk.js"; export * from "./source-detect.js"; export * from "./templates/entity-ui-descriptor.js"; export * from "./templates/find-inbound.js"; diff --git a/server/typescript/packages/codegen-ts/src/generator-registry.ts b/server/typescript/packages/codegen-ts/src/generator-registry.ts index c32d1b21ac..ae8aa44706 100644 --- a/server/typescript/packages/codegen-ts/src/generator-registry.ts +++ b/server/typescript/packages/codegen-ts/src/generator-registry.ts @@ -37,6 +37,7 @@ import { routesFileHono, namesFile, rulesNamesFile, + contractTypes, reportExport, promptRender, outputParser, @@ -225,6 +226,19 @@ export const generatorRegistry: Record = { options: "filter?, target?", ejectable: ejectable("rules-names"), }, + "contract-types": { + name: "contract-types", + kind: "generator", + layer: "model", + description: "Contract types with no persistence mapping: read, create and update shapes, operation inputs and outputs, and the wire error bodies.", + tier: "native", + factory: () => contractTypes(), + factoryExport: "contractTypes", + options: "filter?, target?", + requires: [], + runtimePeers: ["zod"], + ejectable: ejectable("contract-types"), + }, barrel: { name: "barrel", kind: "generator", diff --git a/server/typescript/packages/codegen-ts/src/generators/contract-types-file.ts b/server/typescript/packages/codegen-ts/src/generators/contract-types-file.ts new file mode 100644 index 0000000000..c4561fc316 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/generators/contract-types-file.ts @@ -0,0 +1,109 @@ +import { isMetaObject, OBJECT_SUBTYPE_VALUE, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { EmittedFile, GenContext, Generator } from "../generator.js"; +import { + CONTRACT_ERRORS_FILE, + contractObjectPath, + contractOperationsPath, + contractSpecifier, + contractTypesOf, + contractValuePath, + hasObjectContract, +} from "../contract-walk.js"; +import { DEFAULT_OUTPUT_LAYOUT } from "../import-path.js"; +import { claimModuleNames } from "../naming/name-claims.js"; +import { renderValueObjectFile } from "../templates/value-object-file.js"; +import { renderSharedEnumsFile, SHARED_ENUMS_BASENAME } from "../templates/enums-file.js"; +import { + renderErrorsContract, + renderObjectContract, + renderOperationsContract, + type ContractShapeRef, +} from "../templates/contract-types.js"; + +/** + * The contract types layer (ADR-0067 §1, layer 1): the shapes a caller and a service exchange, + * with no persistence mapping in them, so a transport, a client or a job can import them without + * the ORM. + * + * Writes, beside where the entity generator writes `.ts`: + * - `.contract.ts` — the read schema and type, the create and update schemas, the typed + * create and patch inputs; + * - `.contract.ts` — the read schema and type; + * - `.ts` for each value object the contract reaches — the entity generator's value + * module byte for byte, so when both run the two emissions collapse into one file; + * - `enums.ts` when a shared enum is materialized, likewise the entity generator's; + * - `errors.contract.ts` at the target root — the wire error bodies; + * - `/operations.contract.ts` per package that declares operations, in either layout. + * + * The built-in twin of `src/reference/contract-types.ts` (ADR-0034 scaffold-and-own); the + * reference-byte-identical gate holds the two to the same output. + * + * A SEPARATE generator, never a branch inside the entity generator: a project that does not list + * it sees no change (`fixtures/codegen-noop/rules`). + */ +export interface ContractTypesFileOpts { + /** Narrow which objects are covered. ANDed with the generator's own gates, so it can only + * narrow; an operation with no target entity is always kept. */ + filter?: (entity: MetaObject) => boolean; + /** Named output target, as on every other generator. */ + target?: string; +} + +export function contractTypes(opts?: ContractTypesFileOpts): Generator { + const generator: Generator = { + name: "contract-types", + generate: (ctx: GenContext): EmittedFile[] => { + const rc = ctx.renderContext; + if (!rc) throw new Error("contract-types: renderContext is required (provided by runGen)"); + const layout = ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; + const matches = (obj: MetaData): boolean => + isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const model = contractTypesOf(ctx.loadedRoot, { matches }); + const files: EmittedFile[] = []; + + for (const obj of model.objects) { + claimModuleNames(ctx, obj); + files.push({ path: contractObjectPath(layout, obj), content: renderObjectContract(obj, rc) }); + } + for (const v of model.values) { + claimModuleNames(ctx, v); + files.push({ path: contractValuePath(layout, v), content: renderValueObjectFile(v, rc.apiPrefix, rc) }); + } + + for (const pkg of model.packages) { + const path = contractOperationsPath(pkg.package); + // A value's module, or an object's contract module; an object with no contract of its + // own (a report) is left out rather than imported from a file this run did not write. + const shape = (obj: MetaObject | undefined, name: string): ContractShapeRef | undefined => { + if (obj === undefined) return undefined; + if (obj.subType === OBJECT_SUBTYPE_VALUE) return { name, from: contractSpecifier(path, contractValuePath(layout, obj), rc.extStyle) }; + if (!hasObjectContract(obj)) return undefined; + return { name, from: contractSpecifier(path, contractObjectPath(layout, obj), rc.extStyle) }; + }; + const operations = pkg.operations.map((o) => { + const input = o.input && shape(o.input, `${rc.valueObjectEmittedName(o.input)}InsertSchema`); + const output = o.output && shape(o.output, o.output.subType === OBJECT_SUBTYPE_VALUE ? rc.valueObjectEmittedName(o.output) : o.output.name); + return { + name: o.name, + kind: o.kind, + many: o.many, + errors: o.errors, + ...(input !== undefined ? { input } : {}), + ...(output !== undefined ? { output } : {}), + }; + }); + const errors = contractSpecifier(path, CONTRACT_ERRORS_FILE, rc.extStyle); + files.push({ path, content: renderOperationsContract(pkg.package, operations, errors) }); + } + + if (files.length === 0) return []; + files.push({ path: CONTRACT_ERRORS_FILE, content: renderErrorsContract() }); + const sharedEnums = renderSharedEnumsFile(ctx.loadedRoot, ctx.select !== undefined ? { select: ctx.select } : undefined); + if (sharedEnums !== null) files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); + return files; + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/generators/index.ts b/server/typescript/packages/codegen-ts/src/generators/index.ts index b704588c00..7e9f8647bb 100644 --- a/server/typescript/packages/codegen-ts/src/generators/index.ts +++ b/server/typescript/packages/codegen-ts/src/generators/index.ts @@ -30,6 +30,7 @@ export { callableFile, type CallableFileOpts } from "./callable-file.js"; export { routesFileHono, type RoutesFileHonoOpts } from "./routes-file-hono.js"; export { namesFile } from "./names-file.js"; export { rulesNamesFile, type RulesNamesFileOpts } from "./rules-names-file.js"; +export { contractTypes, type ContractTypesFileOpts } from "./contract-types-file.js"; export { reportExport, type ReportExportOpts } from "./report-export-file.js"; export { promptRender, type PromptRenderOpts } from "./prompt-render-file.js"; export { outputParser, type OutputParserOpts } from "./output-parser-file.js"; diff --git a/server/typescript/packages/codegen-ts/src/reference-templates.ts b/server/typescript/packages/codegen-ts/src/reference-templates.ts index 7af8889523..3c16567b32 100644 --- a/server/typescript/packages/codegen-ts/src/reference-templates.ts +++ b/server/typescript/packages/codegen-ts/src/reference-templates.ts @@ -18,6 +18,9 @@ export const REFERENCE_GENERATOR_NAMES = [ // The rules names (ADR-0067 layer 0): the file's shape is the adopter's, while the walk that // derives states, commands and permission names stays engine, shared with `meta verify`. "rules-names", + // The contract types (ADR-0067 layer 1): the modules' shape is the adopter's, while which objects, + // values and operations are covered stays the engine walk. + "contract-types", // The report export (`?format=csv|json|xml` on a served report): which reports get a module, the // column list and the CSV/XML writers, handed over as one file. "report-export", diff --git a/server/typescript/packages/codegen-ts/src/reference/contract-types.ts b/server/typescript/packages/codegen-ts/src/reference/contract-types.ts new file mode 100644 index 0000000000..205351b51b --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/reference/contract-types.ts @@ -0,0 +1,114 @@ +// REFERENCE TEMPLATE — copy this into your repo (e.g. codegen/generators/contract-types.ts) and own it. +// Then import it LOCALLY in metaobjects.config.ts: +// import { contractTypes } from "./codegen/generators/contract-types.js"; +// +// RUNTIME: this file executes under whatever runs `meta gen`, and the published CLI's +// shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not +// reach for `Bun.*` globals here; use `node:` builtins instead. +// targets: the emit step. Replace the renderers in `../templates/contract-types.js` to change +// a module's SHAPE (interfaces instead of Zod, one file per package); keep +// `contractTypesOf` so which objects, values and operations are covered stays the +// packaged walk. +// use-when: a transport, a client, a job or another service needs the shapes a service takes +// and returns, and the wire errors it answers with, without importing the ORM. +// emits: .contract.ts (read, create and update shapes), .contract.ts +// (read shape), the value modules they reach, enums.ts, errors.contract.ts at the +// target root, and /operations.contract.ts per package that declares +// operations. A model with no store-backed entity, projection or operation gets +// no file. +// customize: swap the renderers; route the layer to its own package with `target`. +// composes-with: entity.ts (its value modules and enums.ts are byte-identical, so the two collapse +// into one file in one run). Nothing else imports it yet. +// +// A SEPARATE generator, never a branch inside the entity generator: a project that does not list +// it sees no change (fixtures/codegen-noop/rules). +import { + CONTRACT_ERRORS_FILE, + DEFAULT_OUTPUT_LAYOUT, + claimModuleNames, + contractObjectPath, + contractOperationsPath, + contractSpecifier, + contractTypesOf, + contractValuePath, + hasObjectContract, + type EmittedFile, + type GenContext, + type Generator, +} from "@metaobjectsdev/codegen-ts/engine"; +import { renderValueObjectFile } from "../templates/value-object-file.js"; +import { renderSharedEnumsFile, SHARED_ENUMS_BASENAME } from "../templates/enums-file.js"; +import { + renderErrorsContract, + renderObjectContract, + renderOperationsContract, + type ContractShapeRef, +} from "../templates/contract-types.js"; +import { isMetaObject, OBJECT_SUBTYPE_VALUE, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; + +export interface ContractTypesFileOpts { + /** Narrow which objects are covered. ANDed with the generator's own gates, so it can only + * narrow; an operation with no target entity is always kept. */ + filter?: (entity: MetaObject) => boolean; + /** Named output target, as on every other generator. */ + target?: string; +} + +export function contractTypes(opts?: ContractTypesFileOpts): Generator { + const generator: Generator = { + name: "contract-types", + generate: (ctx: GenContext): EmittedFile[] => { + const rc = ctx.renderContext; + if (!rc) throw new Error("contract-types: renderContext is required (provided by runGen)"); + const layout = ctx.config.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; + const matches = (obj: MetaData): boolean => + isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const model = contractTypesOf(ctx.loadedRoot, { matches }); + const files: EmittedFile[] = []; + + for (const obj of model.objects) { + claimModuleNames(ctx, obj); + files.push({ path: contractObjectPath(layout, obj), content: renderObjectContract(obj, rc) }); + } + for (const v of model.values) { + claimModuleNames(ctx, v); + files.push({ path: contractValuePath(layout, v), content: renderValueObjectFile(v, rc.apiPrefix, rc) }); + } + + for (const pkg of model.packages) { + const path = contractOperationsPath(pkg.package); + // A value's module, or an object's contract module; an object with no contract of its + // own (a report) is left out rather than imported from a file this run did not write. + const shape = (obj: MetaObject | undefined, name: string): ContractShapeRef | undefined => { + if (obj === undefined) return undefined; + if (obj.subType === OBJECT_SUBTYPE_VALUE) return { name, from: contractSpecifier(path, contractValuePath(layout, obj), rc.extStyle) }; + if (!hasObjectContract(obj)) return undefined; + return { name, from: contractSpecifier(path, contractObjectPath(layout, obj), rc.extStyle) }; + }; + const operations = pkg.operations.map((o) => { + const input = o.input && shape(o.input, `${rc.valueObjectEmittedName(o.input)}InsertSchema`); + const output = o.output && shape(o.output, o.output.subType === OBJECT_SUBTYPE_VALUE ? rc.valueObjectEmittedName(o.output) : o.output.name); + return { + name: o.name, + kind: o.kind, + many: o.many, + errors: o.errors, + ...(input !== undefined ? { input } : {}), + ...(output !== undefined ? { output } : {}), + }; + }); + const errors = contractSpecifier(path, CONTRACT_ERRORS_FILE, rc.extStyle); + files.push({ path, content: renderOperationsContract(pkg.package, operations, errors) }); + } + + if (files.length === 0) return []; + files.push({ path: CONTRACT_ERRORS_FILE, content: renderErrorsContract() }); + const sharedEnums = renderSharedEnumsFile(ctx.loadedRoot, ctx.select !== undefined ? { select: ctx.select } : undefined); + if (sharedEnums !== null) files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: sharedEnums }); + return files; + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/templates/contract-types.ts b/server/typescript/packages/codegen-ts/src/templates/contract-types.ts new file mode 100644 index 0000000000..a1f8f76e9e --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/templates/contract-types.ts @@ -0,0 +1,206 @@ +// The contract types layer (ADR-0067 §1, layer 1): the shapes a caller and a service exchange, +// with no persistence mapping in them. Three kinds of module: +// +// - `.contract.ts` — an entity's read shape (interface), its create and update schemas +// with their validation, and the typed create and patch inputs; a projection's read shape; +// - `errors.contract.ts` — the wire error bodies of the REST contract and the enforcing shell; +// - `/operations.contract.ts` — each declared operation's input, output and errors. +// +// The field-level schemas are the ones the entity file already writes (`renderZodValidators`, +// `renderValueObjectInterface`), so the two can never validate one field two ways. + +import { CONTRACT_ERROR_CODES, CONTRACT_FILE_SUFFIX, SHELL_ERROR_CODES } from "../contract-walk.js"; +import { withExtIfRelative } from "../render-context.js"; +import { GENERATED_EDIT_NOTE, GENERATED_HEADER } from "../constants.js"; +import type { RenderContext } from "../render-context.js"; +import { toPascalCase } from "../naming.js"; +import { isProjection } from "../projection/projection-detector.js"; +import { renderEnumTypeAliases } from "./inferred-types.js"; +import { primaryIdentityFieldNames, renderTphSubtypeReadSchema, renderZodValidators } from "./zod-validators.js"; +import { tphConcreteSubtypes } from "./tph-discriminator.js"; +import { isTphSubtype } from "../tph.js"; +import { renderViewReadZodObject } from "./view-decl.js"; +import { valueObjectFieldImport } from "../import-path.js"; +import { effectivePackage } from "../docs-paths.js"; +import { TsWriter, arr, str } from "../writer/ts-writer.js"; +import { code, imp, joinCode, type Code } from "../poet.js"; +import type { MetaObject } from "@metaobjectsdev/metadata"; + +const strings = (values: readonly string[]) => arr(values.map(str)); +const union = (values: readonly string[]): string => values.map(str).join(" | "); + +/** + * The text of `.contract.ts`. An entity gets its three shapes: the read schema and type (a + * row as the store returns it: the key and every NOT NULL column present, a nullable one `null`), + * the create and update schemas with their validation, and the typed create and patch inputs. A + * projection gets its read schema and type. Every section is one the entity file already renders, + * printed the way the entity file is printed, so a field reads and validates the same in both. + */ +export function renderObjectContract(obj: MetaObject, ctx: RenderContext): string { + const z = imp("z@zod"); + const name = obj.name; + const pkg = effectivePackage(obj); + const subtypes = tphConcreteSubtypes(obj, ctx.loadedRoot); + let readDecl: Code; + if (subtypes.length > 0) { + // A TPH base: a row is one of its subtypes, told apart by the discriminator. + // A subtype shares its base's table, so it shares its base's package and directory. + const from = (s: MetaObject) => withExtIfRelative(`./${s.name}${CONTRACT_FILE_SUFFIX.replace(/\.ts$/, "")}`, ctx.extStyle); + const schemas = subtypes.map((s) => code`${imp(`${s.name}Schema@${from(s)}`)}`); + const types = subtypes.map((s) => code`${imp(`t:${s.name}@${from(s)}`)}`); + readDecl = code`export const ${name}Schema = ${z}.union([${joinCode(schemas, { on: ", " })}]); export type ${name} = ${joinCode(types, { on: " | " })};`; + } else if (isTphSubtype(obj)) { + // A TPH subtype: the discriminator pinned, and a column only some subtypes have nullable. + readDecl = code`${renderTphSubtypeReadSchema(obj, ctx)}export type ${name} = ${z}.infer;`; + } else { + const read = renderViewReadZodObject(obj.fields(), { + dialect: ctx.dialect, + columnNamingStrategy: ctx.columnNamingStrategy, + timestampMode: ctx.timestampMode, + voRef: (field, suffix, typeOnly) => valueObjectFieldImport(ctx, field, pkg, suffix, typeOnly), + pkFieldNames: new Set(primaryIdentityFieldNames(obj)), + }); + readDecl = code`export const ${name}Schema = ${read}; export type ${name} = ${z}.infer;`; + } + const aliases = renderEnumTypeAliases(obj, ctx) ?? code``; + // A projection is read-only: it has a read shape and nothing a caller sends. + const writes = isProjection(obj) ? code`` : renderZodValidators(obj, ctx); + const body = code`${readDecl}${aliases}${writes}`.toString(); + const w = new TsWriter(); + w.header( + `// ${GENERATED_HEADER} — ${GENERATED_EDIT_NOTE}`, + `// Source metadata: ${name} (${obj.fqn()}) — contract types, no persistence mapping`, + ); + w.text(body); + return w.toString(); +} + +/** The text of `errors.contract.ts`: the wire error bodies every route and shell answers with. */ +export function renderErrorsContract(): string { + const w = new TsWriter(); + w.header( + `// ${GENERATED_HEADER} — ${GENERATED_EDIT_NOTE}`, + "// Source metadata: the wire error contract (docs/features/api-contract.md, ADR-0066 §6)", + ); + + w.doc("The wire codes the enforcing shell answers with on its own (ADR-0066 §6)."); + w.line("export const ShellErrorCodes = ", strings(SHELL_ERROR_CODES), " as const;"); + w.line("export type ShellErrorCode = (typeof ShellErrorCodes)[number];"); + + w.blank().doc("The wire codes the REST contract's transport answers with (docs/features/api-contract.md)."); + w.line("export const ContractErrorCodes = ", strings(CONTRACT_ERROR_CODES), " as const;"); + w.line("export type ContractErrorCode = (typeof ContractErrorCodes)[number];"); + + w.blank().doc( + "The HTTP status of each fixed code. `constraint_violation` has none of its own: it is 409 for a", + "`unique` or `foreign_key` constraint and 400 for a `check` or `not_null` one.", + ); + w.block("export const ErrorStatus = {", () => { + for (const [code, status] of ERROR_STATUS) w.line(`${code}: ${status},`); + }, `} as const satisfies Record, number>;`); + + w.blank().doc("Every error body: a short code, and a human message that is not part of the contract."); + w.block("export interface ErrorBody {", () => { + w.line("readonly error: Code;"); + w.line("readonly message?: string;"); + }); + + w.blank().doc( + "One problem with a request body. `code` uses Zod's names; a client treats a code it does not know", + "as `custom`, and ignores keys it does not know.", + ); + w.block("export interface ValidationIssue {", () => { + w.line("readonly code: string;"); + w.line("readonly path: readonly (string | number)[];"); + w.line("readonly message: string;"); + }); + + w.blank().doc("400: the body failed its schema. Every issue is listed, not the first."); + w.block(`export interface ValidationErrorBody extends ErrorBody<${str("validation")}> {`, () => { + w.line("readonly issues: readonly ValidationIssue[];"); + }); + + w.blank().doc("The kind of constraint the database refused a write on. The body never names the SQL."); + w.line(`export type ConstraintKind = ${union(CONSTRAINT_KINDS)};`); + + w.blank().doc("409 (`unique`, `foreign_key`) or 400 (`check`, `not_null`): the database refused the write."); + w.block(`export interface ConstraintViolationBody extends ErrorBody<${str("constraint_violation")}> {`, () => { + w.line("readonly constraint: ConstraintKind;"); + }); + return w.toString(); +} + +const ERROR_STATUS: readonly (readonly [string, number])[] = [ + ["not_found", 404], + ["forbidden", 403], + ["invalid_transition", 409], + ["transition_condition_failed", 409], + ["state_managed", 409], + ["validation", 400], + ["invalid_json", 400], + ["invalid_id", 400], + ["method_not_allowed", 405], + ["internal", 500], +]; + +const CONSTRAINT_KINDS = ["unique", "foreign_key", "check", "not_null"] as const; + +/** A shape an operation takes or returns, and where its module is. */ +export interface ContractShapeRef { + /** The exported name to import: a value object's `InsertSchema`, or an object's read type. */ + readonly name: string; + /** The specifier of the module that exports it, relative to the operations file. */ + readonly from: string; +} + +/** One declared operation, as the operations file writes it. */ +export interface ContractOperationInput { + readonly name: string; + readonly kind: "command" | "query"; + /** The `@inputRef` value object's insert schema; absent when the operation declares none. */ + readonly input?: ContractShapeRef; + /** The `@outputRef` object's read type; absent when the operation declares none. */ + readonly output?: ContractShapeRef; + /** `@many`: the output is a list. */ + readonly many: boolean; + /** The business errors a command's body may return (`@errors`). */ + readonly errors: readonly string[]; +} + +/** The text of `/operations.contract.ts`. */ +export function renderOperationsContract( + pkg: string, + operations: readonly ContractOperationInput[], + errorsModule: string, +): string { + const w = new TsWriter(); + w.header( + `// ${GENERATED_HEADER} — ${GENERATED_EDIT_NOTE}`, + `// Source metadata: operations of ${pkg === "" ? "the model" : `package ${pkg}`} — inputs, outputs and errors`, + ); + const errorBody = w.useType("ErrorBody", errorsModule); + const shell = w.useType("ShellErrorCode", errorsModule); + const contract = w.useType("ContractErrorCode", errorsModule); + + let first = true; + for (const op of operations) { + if (!first) w.blank(); + first = false; + const stem = toPascalCase(op.name); + w.doc(`\`${op.name}\` (${op.kind}).`); + if (op.input !== undefined) { + const z = w.useType("z", "zod"); + const schema = w.use(op.input.name, op.input.from); + w.line(`export const ${stem}InputSchema = ${schema};`); + w.line(`export type ${stem}Input = ${z}.input;`); + } + if (op.output !== undefined) { + const out = w.useType(op.output.name, op.output.from); + w.line(`export type ${stem}Output = ${op.many ? `readonly ${out}[]` : out};`); + } + const business = op.errors.length === 0 ? "never" : union(op.errors); + w.line(`export type ${stem}BusinessError = ${business};`); + w.line(`export type ${stem}Error = ${errorBody}<${shell} | ${contract} | ${stem}BusinessError>;`); + } + return w.toString(); +} diff --git a/server/typescript/packages/codegen-ts/test/contract-types.test.ts b/server/typescript/packages/codegen-ts/test/contract-types.test.ts new file mode 100644 index 0000000000..3d9036bc27 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/contract-types.test.ts @@ -0,0 +1,276 @@ +// `contractTypes()` — the contract types layer (ADR-0067 §1, layer 1): the shapes a caller and a +// service exchange, with no persistence mapping in them. +// +// The oracles, stated per test: +// - the wire error codes are ADR-0066's list (O5 names every code a route answers itself: the +// shell's five in §6 and the API contract's six), and their statuses are §6's shell steps +// (404, 403, 409) and the error tables of docs/features/api-contract.md; +// - an operation's business errors are the fixture's `@errors`, its output a list when the +// fixture says `@many`, and its input the `@inputRef` value object's insert schema; +// - an entity's contract read type is the read type the entity generator already promises for +// the same object (the Drizzle select row, or the read schema's inferred type) — two modules +// that describe one row two ways are the defect this layer would add; +// - a projection is read-only (ADR-0028): it has a read shape and nothing a caller sends. +// The compile tests hold the emitted types to what a consumer may write, with the real compiler. + +import { describe, test, expect, setDefaultTimeout, beforeAll, afterAll } from "bun:test"; +import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; +import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import ts from "typescript"; +import { loadUris, type MetaRoot } from "@metaobjectsdev/metadata"; +import { contractTypes } from "../src/generators/index.js"; +import { entityFile } from "../src/generators/entity-file.js"; +import { runGen } from "../src/runner.js"; +import { defineConfig, type Dialect } from "../src/metaobjects-config.js"; +import type { OutputLayout } from "../src/import-path.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; +import type { Generator } from "../src/generator.js"; + +setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); + +const FIXTURES = join(import.meta.dir, "..", "..", "..", "..", "..", "fixtures"); +const RULES_MODEL = join(FIXTURES, "codegen-noop", "rules", "with", "meta.purchasing.json"); +const FITNESS_MODEL = join(FIXTURES, "persistence-conformance", "canonical", "meta.fitness.json"); + +/** ADR-0066 §6: the codes the enforcing shell answers with on its own. */ +const SHELL_CODES = ["not_found", "forbidden", "invalid_transition", "transition_condition_failed", "state_managed"]; +/** ADR-0066 O5: the API contract's own codes. */ +const CONTRACT_CODES = ["validation", "invalid_json", "invalid_id", "method_not_allowed", "constraint_violation", "internal"]; + +const scratch: string[] = []; +afterAll(() => { + for (const d of scratch) removeTree(d); +}); + +async function load(file: string): Promise { + const r = await loadUris([pathToFileURL(file).href]); + expect(r.errors.map((e) => e.message)).toEqual([]); + return r.root; +} + +/** A scratch project that resolves `zod`, and the entity file's own packages when asked, the way + * an adopter's would. The contract layer alone gets zod only, so a persistence import cannot + * compile. */ +function project(withDrizzle = false): string { + const dir = makeScratchDir("contract-types-"); + scratch.push(dir); + const require = createRequire(import.meta.url); + mkdirSync(join(dir, "node_modules"), { recursive: true }); + for (const pkg of withDrizzle ? ["zod", "drizzle-orm", "@metaobjectsdev/runtime-ts"] : ["zod"]) { + mkdirSync(dirname(join(dir, "node_modules", pkg)), { recursive: true }); + symlinkSync(dirname(require.resolve(`${pkg}/package.json`)), join(dir, "node_modules", pkg), "dir"); + } + writeFileSync(join(dir, "package.json"), JSON.stringify({ type: "module" })); + return dir; +} + +const OUT = "gen"; + +async function generate( + root: MetaRoot, + generators: Generator[], + opts: { layout?: OutputLayout; dialect?: Dialect; withDrizzle?: boolean } = {}, +): Promise<{ dir: string; out: string; files: Record }> { + const dir = project(opts.withDrizzle); + await runGen({ + config: defineConfig({ + outDir: OUT, + extStyle: "js", + dbImport: "~/db", + dialect: opts.dialect ?? "postgres", + outputLayout: opts.layout ?? "package", + generators, + }), + metadata: root, + projectRoot: dir, + }); + const out = join(dir, OUT); + const files: Record = {}; + const walk = (d: string) => { + for (const f of readdirSync(d)) { + const p = join(d, f); + if (statSync(p).isDirectory()) walk(p); + else if (p.endsWith(".ts")) files[p.slice(out.length + 1)] = readFileSync(p, "utf8"); + } + }; + if (existsSync(out)) walk(out); + return { dir, out, files }; +} + +/** Compile `files` (paths under `out`) plus `extra` (written beside them), strictest settings. */ +function compile(out: string, files: string[], extra: Record = {}): string[] { + for (const [name, text] of Object.entries(extra)) writeFileSync(join(out, name), text); + const program = ts.createProgram( + [...files, ...Object.keys(extra)].map((f) => join(out, f)), + { + strict: true, + noEmit: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + skipLibCheck: true, + verbatimModuleSyntax: true, + exactOptionalPropertyTypes: true, + noUncheckedIndexedAccess: true, + }, + ); + return ts.getPreEmitDiagnostics(program).map((d) => { + const where = d.file && d.start !== undefined ? `${d.file.fileName.slice(out.length + 1)}:${d.file.getLineAndCharacterOfPosition(d.start).line + 1}` : ""; + return `${where} ${ts.flattenDiagnosticMessageText(d.messageText, " ")}`; + }); +} + +const EQ = "type Eq = [A] extends [B] ? ([B] extends [A] ? true : false) : false;"; + +/** A specifier is a third-party or MetaObjects package the module imports. */ +const imported = (text: string): string[] => + [...text.matchAll(/^import .* from "([^".][^"]*)";$/gm)].map((m) => m[1]!).sort(); + +describe("contractTypes() over the rules model (package layout)", () => { + let gen: Awaited>; + beforeAll(async () => { + gen = await generate(await load(RULES_MODEL), [contractTypes()]); + }); + + test("writes the entity's and projection's contracts, the reached value, the operations and the error bodies", () => { + expect(Object.keys(gen.files).sort()).toEqual([ + "acme/purchasing/DecisionInput.ts", + "acme/purchasing/PurchaseRequest.contract.ts", + "acme/purchasing/RequestSummary.contract.ts", + "acme/purchasing/operations.contract.ts", + "errors.contract.ts", + ]); + }); + + test("imports no persistence: zod is the one package any module needs", () => { + for (const [path, text] of Object.entries(gen.files)) { + expect({ path, imports: imported(text).filter((s) => s !== "zod") }).toEqual({ path, imports: [] }); + } + }); + + test("a projection is read-only: a read schema and type, nothing a caller sends", async () => { + const m = await import(pathToFileURL(join(gen.out, "acme/purchasing/RequestSummary.contract.ts")).href); + expect(Object.keys(m).sort()).toEqual(["RequestSummarySchema"]); + // A view row carries every declared column; the key is never null. + expect(m.RequestSummarySchema.safeParse({ id: 1, title: null }).success).toBe(true); + expect(m.RequestSummarySchema.safeParse({ id: null, title: "x" }).success).toBe(false); + }); + + test("the wire codes and their statuses are the ADR-0066 and api-contract ones", async () => { + const m = await import(pathToFileURL(join(gen.out, "errors.contract.ts")).href); + expect([...m.ShellErrorCodes]).toEqual(SHELL_CODES); + expect([...m.ContractErrorCodes]).toEqual(CONTRACT_CODES); + expect(m.ErrorStatus).toEqual({ + not_found: 404, + forbidden: 403, + invalid_transition: 409, + transition_condition_failed: 409, + state_managed: 409, + validation: 400, + invalid_json: 400, + invalid_id: 400, + method_not_allowed: 405, + internal: 500, + }); + }); + + test("an operation's input schema is its @inputRef value's, and validates the value's fields", async () => { + const m = await import(pathToFileURL(join(gen.out, "acme/purchasing/operations.contract.ts")).href); + expect(m.DecideInputSchema.safeParse({ requestId: 7, comment: "within budget" }).success).toBe(true); + expect(m.DecideInputSchema.safeParse({ requestId: "seven" }).success).toBe(false); + }); + + test("the emitted types compile and say what the model declares", () => { + const check = `${EQ} +import type { ContractErrorCode, ShellErrorCode, ValidationErrorBody, ConstraintViolationBody } from "./errors.contract.js"; +import type * as Ops from "./acme/purchasing/operations.contract.js"; +import type { RequestSummary } from "./acme/purchasing/RequestSummary.contract.js"; +import type { PurchaseRequestCreate, PurchaseRequestPatch } from "./acme/purchasing/PurchaseRequest.contract.js"; +type Shell = ${SHELL_CODES.map((c) => JSON.stringify(c)).join(" | ")}; +type Contract = ${CONTRACT_CODES.map((c) => JSON.stringify(c)).join(" | ")}; +export const shell: Eq = true; +export const contract: Eq = true; +// @errors: [over_budget, already_decided] +export const business: Eq = true; +export const decideError: Eq = true; +// A query declares no @errors. +export const queryBusiness: Eq = true; +// openRequests is @many, requestSummary is not. +export const many: Eq = true; +export const one: Eq = true; +export const input: Ops.DecideInput = { requestId: 7, comment: "within budget" }; +export const create: PurchaseRequestCreate = { id: 1, title: "Desk", amountCents: 12000, status: "draft" }; +export const patch: PurchaseRequestPatch = { title: null }; +export const issue: ValidationErrorBody = { error: "validation", issues: [{ code: "invalid_type", path: ["title"], message: "Expected string" }] }; +export const conflict: ConstraintViolationBody = { error: "constraint_violation", constraint: "unique" }; +// @ts-expect-error a code the operation does not declare is not one of its errors +export const undeclared: Ops.DecideError = { error: "payment_declined" }; +// @ts-expect-error a value outside the lifecycle's states is not a status +export const badState: PurchaseRequestCreate = { id: 1, status: "archived" }; +`; + expect(compile(gen.out, Object.keys(gen.files), { "check.ts": check })).toEqual([]); + }); +}); + +describe("contractTypes() over the fitness corpus", () => { + let root: MetaRoot; + beforeAll(async () => { + root = await load(FITNESS_MODEL); + }); + + for (const layout of ["flat", "package"] as const) { + test(`compiles under the strictest settings, ${layout} layout, with no persistence import`, async () => { + const gen = await generate(root, [contractTypes()], { layout }); + expect(Object.keys(gen.files).length).toBeGreaterThan(20); + expect(compile(gen.out, Object.keys(gen.files))).toEqual([]); + for (const [path, text] of Object.entries(gen.files)) { + expect({ path, imports: imported(text).filter((s) => s !== "zod") }).toEqual({ path, imports: [] }); + } + }); + } + + // Two objects differ from the entity file's read type, both by intent: + // - `Auth`, a TPH base: the entity file unions its subtypes' INPUT interfaces, while the contract + // unions their read rows — what the entity file's own `parseAuth` returns at runtime; + // - `Asset`: `payload` is a `field.string` whose `@dbColumnType: jsonb` is physical only + // (ADR-0037 step 1), so Drizzle reads it as `unknown` and the contract keeps the declared string. + const DIFFERS = new Set(["Auth", "Asset"]); + + for (const dialect of ["postgres", "sqlite", "mysql"] as const) { + test(`beside the entity generator (${dialect}): value modules collapse, and every read type matches the entity file's`, async () => { + // The two generators write the same value modules and enums.ts; runGen refuses a path two + // generators write with different bytes, so finishing at all is the collapse check. + const gen = await generate(root, [entityFile({ allowlists: false }), contractTypes()], { layout: "flat", dialect, withDrizzle: true }); + const names = Object.keys(gen.files) + .map((p) => /^(.*)\.contract\.ts$/.exec(p)?.[1]) + .filter((n): n is string => n !== undefined && n !== "errors" && n !== "operations" && !DIFFERS.has(n)); + expect(names.length).toBeGreaterThan(20); + const lines = names.map((n) => { + // The entity file's read type: its read schema's when it declares one (a TPH subtype, a + // projection, a write-through entity), else the exported row type. + const row = gen.files[`${n}.ts`]!.includes(`export const ${n}Schema`) + ? `z.infer` + : `import("./${n}.js").${n}`; + return `export const ${n}Eq: Eq<${row}, import("./${n}.contract.js").${n}> = true;`; + }); + const check = [EQ, `import type { z } from "zod";`, ...lines].join("\n"); + expect(compile(gen.out, Object.keys(gen.files), { "check.ts": check })).toEqual([]); + }); + } +}); + +describe("contractTypes() is silent without anything to describe", () => { + test("a model of value objects only gets no file", async () => { + const dir = makeScratchDir("contract-types-model-"); + scratch.push(dir); + const file = join(dir, "meta.values.json"); + writeFileSync(file, JSON.stringify({ + "metadata.root": { package: "acme", children: [{ "object.value": { name: "Money", children: [{ "field.long": { name: "cents" } }] } }] }, + })); + const gen = await generate(await load(file), [contractTypes()]); + expect(gen.files).toEqual({}); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/generator-registry.test.ts b/server/typescript/packages/codegen-ts/test/generator-registry.test.ts index 2f8412fdc5..0fd585d713 100644 --- a/server/typescript/packages/codegen-ts/test/generator-registry.test.ts +++ b/server/typescript/packages/codegen-ts/test/generator-registry.test.ts @@ -23,6 +23,7 @@ const EXPECTED_NATIVE = [ "barrel", "names", "rules-names", + "contract-types", "report-export", "prompt-render", "output-parser", diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index cda6517100..7b64b2ca27 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -24,6 +24,8 @@ import { barrel as refBarrel } from "../src/reference/barrel.js"; import { namesFile as refNames } from "../src/reference/names.js"; import { rulesNamesFile as builtinRulesNames } from "../src/generators/rules-names-file.js"; import { rulesNamesFile as refRulesNames } from "../src/reference/rules-names.js"; +import { contractTypes as builtinContractTypes } from "../src/generators/contract-types-file.js"; +import { contractTypes as refContractTypes } from "../src/reference/contract-types.js"; import { reportExport as builtinReportExport } from "../src/generators/report-export-file.js"; import { reportExport as refReportExport } from "../src/reference/report-export.js"; import { promptRender as builtinPromptRender } from "../src/generators/prompt-render-file.js"; @@ -183,6 +185,7 @@ const PAIRS: Record Generator; ref: () // Emits nothing over the entity-shaped fixtures (none declares a lifecycle or an operation); // test/rules-names.test.ts runs both over a rules model. "rules-names": { builtin: builtinRulesNames, ref: refRulesNames }, + "contract-types": { builtin: builtinContractTypes, ref: refContractTypes }, // Emits nothing over the entity-shaped fixtures (none declares a served report); the // describe after the route-composition one runs the pair, with the routes, over the report corpus. "report-export": { builtin: builtinReportExport, ref: refReportExport }, diff --git a/server/typescript/packages/codegen-ts/test/reference-templates.test.ts b/server/typescript/packages/codegen-ts/test/reference-templates.test.ts index 90653dd92d..23d3f84b5d 100644 --- a/server/typescript/packages/codegen-ts/test/reference-templates.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-templates.test.ts @@ -13,7 +13,7 @@ import { join } from "node:path"; describe("reference-templates reader", () => { test("exposes the copyable generator names, entity first (reader sentinel)", () => { expect([...REFERENCE_GENERATOR_NAMES]).toEqual([ - "entity", "queries", "routes", "routes-hono", "barrel", "names", "rules-names", "report-export", + "entity", "queries", "routes", "routes-hono", "barrel", "names", "rules-names", "contract-types", "report-export", "prompt-render", "output-parser", "extractor", "output-prompt", "render-helper", "requirement-tests", "cube-model", "prisma-schema", "contract-schema", "openapi", "callable", "trace-helper", "shared-model", "docs", "api-docs", "requirements", "agent-docs", "metamodel-docs", From e294d001c629d614710794c0c97a4d041310360d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 18:04:38 -0500 Subject: [PATCH 04/16] docs(conformance): count the guarded-update scenario in the orphaned-fixtures sum L-TS-3 added a persistence scenario and moved the table's persistence row to 68, but the prose sum under "Orphaned fixtures" still said 67, which the site counts gate refuses. --- docs/CONFORMANCE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 10db6ff306..96fc2674e1 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -860,7 +860,7 @@ JSON and verify payload feeds it unchanged. ## Orphaned fixtures (tested but not yet documented) The fixtures in the nine corpora mapped above (metamodel 578 + yaml 19 + verify 45 -+ render 21 + persistence 67 + api-contract 161 + source-resolution 28 + scope 10 + ++ render 21 + persistence 68 + api-contract 161 + source-resolution 28 + scope 10 + dependency 47) each map to a feature doc, and so do the two requirement corpora, `rules-check-conformance`, `shared-model-conformance`, the `cube-model` corpus, `explorer-conformance` and `list-query-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider From 0f707d31e5548b6cf5afe2731e42b3d5712b0d9b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 21 Nov 2026 18:05:37 -0500 Subject: [PATCH 05/16] feat(sdk,cli): the static agent files built once for every port; Rust as a server language (G1) The assembler now also runs at build time, once per stack a port's own agent-docs command serves: each server language alone and Java with Kotlin, each with no client, React, React with TanStack or Angular (28 stacks). The result is committed at agent-context-shipped/: a manifest listing each stack's files by project path, and each distinct file once under files/, named by its content hash (101 files, about 1.1 MB). A port's package embeds the tree; its command finds the stack by id, pins the guide links to its release tag with one text replacement, and writes the files, so a C#, JVM, Python or Rust project needs no Node for them (1.3.0 design call 17, ADR-0033 Amendment 1). agent-context-shipped/README.md is the contract. - sdk: buildShippedAgentContext(), materializeShippedStack(), shippedStackId() and shippedTreeFiles(), and scripts/build-shipped-agent-context.ts (writes only changed bytes; --check exits 1 naming each stale file). - shipped.test.ts: the committed tree is byte-for-byte what the build writes; every stack, materialized as a port would, equals assemble() for it with the release ref; the shared agent-context-conformance goldens come out of the tree unchanged; an unshipped stack is refused, naming the shipped ones. - Rust: SERVER_LANGS gains rust; `--server rust` (alias rs) is accepted and a root Cargo.toml detects it; servers/rust.meta.json and templates/loops/rust.md give the cargo meta gen loop and the cargo meta verify step; a rust case joins fixtures/agent-context-conformance. Libraries now list Rust among their ports, and the manifest gate checks the copy Rust's build.rs embeds (server/rust/metaobjects/data/library). - The lane map routes agent-context-shipped/ to every lane. --- CHANGELOG.md | 14 + agent-context-shipped/README.md | 56 + .../files/0080df7715486e4c.md | 85 + .../files/0440a95faf89e271.md | 225 + .../files/063a909f9775df93.md | 106 + .../files/0ee567e8d039312d.md | 218 + .../files/0fe543fe1b3c9b3c.md | 244 + .../files/103a368daf29e749.md | 139 + .../files/10f8c588c3a14034.md | 106 + .../files/1217aab33469e7bd.md | 167 + .../files/123dcfb6c65640a0.md | 99 + .../files/124752f4316a72cc.md | 116 + .../files/13b9b0de13b23fab.md | 96 + .../files/14ca7edcbf971bef.md | 105 + .../files/1c25799a074fff7d.md | 275 + .../files/1e0fda1afdd26e1a.md | 74 + .../files/1e292839ec10ca12.md | 160 + .../files/1ed66f8d84192ee1.md | 88 + .../files/1fc0b42e73b64728.md | 106 + .../files/1ffb7e594a3532d3.md | 114 + .../files/20ec11b332e12322.md | 375 ++ .../files/260df9380fb2eb9d.md | 115 + .../files/2fe5f67ab529af0c.md | 67 + .../files/34d60341c7210314.md | 323 + .../files/378f755bb43b1e71.md | 73 + .../files/417c26a7097034e4.md | 115 + .../files/4244641a71a9c537.md | 69 + .../files/42b77a057282e309.md | 114 + .../files/4426fbef79f236fb.md | 134 + .../files/46659a758d40373b.md | 39 + .../files/490fa77b77d0a1cc.md | 115 + .../files/494853543fba1c5f.md | 264 + .../files/4d4d3378a83fb76e.md | 114 + .../files/4f6d18160c694c41.md | 10 + .../files/51b5c54862c75382.md | 193 + .../files/58d380101a100501.md | 59 + .../files/5a2f3bbdcf835d47.md | 53 + .../files/5b789ec72652dfa6.md | 167 + .../files/5df6f5793c17c564.md | 107 + .../files/608f89f60afad4b9.md | 42 + .../files/636d4309c12de5cb.md | 151 + .../files/651a126eaa501924.md | 154 + .../files/6554b044ac4e5c29.md | 116 + .../files/6935df5f6afbbf93.md | 116 + .../files/6afa98a9c7fd23f6.md | 65 + .../files/6b42cc8511e0eb7d.md | 115 + .../files/6e3f75ac9b8e8680.md | 335 + .../files/80606ed514438d51.md | 342 + .../files/83fa1bfb70e0da93.md | 179 + .../files/84b5d02029893745.md | 156 + .../files/86974256b798cf22.md | 477 ++ .../files/8a9c3f4a4119022a.md | 89 + .../files/8b16b974614265d4.md | 218 + .../files/8cd1bca8a659b6ef.md | 82 + .../files/91463562405e88cc.md | 171 + .../files/940c3d118c7ab1dc.md | 150 + .../files/969f739fa94d7a76.md | 500 ++ .../files/98f64001b169da91.md | 116 + .../files/9b23d9815903eeab.md | 112 + .../files/9fbf06132414b6be.md | 262 + .../files/a1b81119468f84a9.md | 337 + .../files/a431af761169a99d.md | 106 + .../files/a7fd4ec2565ab8c0.md | 40 + .../files/b28302f5febaea38.md | 102 + .../files/b3680649050a0d51.md | 102 + .../files/b70e863795b7a44f.md | 169 + .../files/b8371541b1d36c6b.md | 174 + .../files/be3b1226c6f00862.md | 116 + .../files/bf673961bd3ea6ea.md | 112 + .../files/bfe25e4bd2cf097d.md | 62 + .../files/c13bca93ec2f4d50.md | 106 + .../files/c1a4896ebda79dd9.md | 204 + .../files/c37f1e343d6e2832.md | 121 + .../files/c5b68292c9103dcc.md | 112 + .../files/c6dbd68483d196ea.md | 116 + .../files/c7994468651aa905.md | 165 + .../files/ca05e997cc76ca60.md | 134 + .../files/cb2bbe4cb7d06c55.md | 104 + .../files/ce8ecdef3b83fec0.md | 174 + .../files/cf1872a72588959a.md | 106 + .../files/cffbbf66c1dff86f.md | 116 + .../files/d3eaa47c0bbd9332.md | 326 + .../files/d3f2f83fe9835f64.md | 215 + .../files/d6bd70c9bf36eb46.md | 77 + .../files/db66e0e785a6cf50.md | 331 + .../files/dd80d926c56ea1e3.md | 36 + .../files/e1f6478444c1e120.md | 388 ++ .../files/e413f6fcd012b1f3.md | 403 ++ .../files/e5c6430567eecae4.md | 225 + .../files/e626029a53526f92.md | 378 ++ .../files/e899275df4b48c66.md | 187 + .../files/e985f8151935157d.md | 66 + .../files/eab139844783c8e7.md | 93 + .../files/f02832e4d7770c3c.md | 112 + .../files/f410d7096bb80685.md | 106 + .../files/f425eaf3566cf602.md | 96 + .../files/f578d3e76cb97c78.md | 96 + .../files/f745f2c1411ab2f0.md | 73 + .../files/f80806308b356cb6.md | 194 + .../files/fb3d3670ae387530.md | 60 + .../files/fda1a58ac1585828.md | 22 + .../files/fe7f8817bfc35bb5.md | 120 + agent-context-shipped/manifest.json | 5533 +++++++++++++++++ agent-context/README.md | 5 + agent-context/servers/rust.meta.json | 6 + agent-context/templates/loops/rust.md | 15 + docs/CONFORMANCE.md | 2 +- docs/features/cli.md | 11 +- .../.claude/skills/metaobjects-audit/SKILL.md | 331 + .../references/calibration.md | 40 + .../references/capability-checklist.md | 375 ++ .../references/drift-signatures.md | 67 + .../references/prompt-anti-patterns.md | 62 + .../references/requirements.md | 154 + .../references/surface-review-axes.md | 262 + .../references/vocabulary-hygiene.md | 102 + .../skills/metaobjects-authoring/SKILL.md | 500 ++ .../references/abstracts-and-overlay.md | 60 + .../references/adopting-existing-code.md | 73 + .../references/adopting-existing-models.md | 388 ++ .../references/choosing-a-shape.md | 204 + .../references/declaring-reports.md | 115 + .../references/identities-and-indexes.md | 89 + .../references/inheritance-tph.md | 39 + .../references/json-columns.md | 65 + .../references/metadata-dependencies.md | 42 + .../references/model-first-rationale.md | 22 + .../references/read-views-and-projections.md | 174 + .../references/relationships.md | 66 + .../references/reporting.md | 194 + .../references/requirements.md | 225 + .../references/sources.md | 99 + .../skills/metaobjects-codegen/SKILL.md | 477 ++ .../references/any-stack.md | 134 + .../references/choosing-layers.md | 82 + .../dependencies-and-shared-models.md | 59 + .../references/owning-generators.md | 187 + .../references/physical-names.md | 121 + .../references/principles.md | 36 + .../references/template-or-code.md | 73 + .../references/wire-format.md | 96 + .../skills/metaobjects-prompts/SKILL.md | 337 + .../skills/metaobjects-runtime-ui/SKILL.md | 225 + .../skills/metaobjects-verify/SKILL.md | 342 + .../references/migration.md | 323 + .../references/requirements.md | 218 + .../references/upgrading.md | 10 + .../rust/expected/.metaobjects/AGENTS.md | 102 + .../agent-context-conformance/rust/stack.json | 1 + scripts/ci-lane-map.txt | 1 + server/typescript/packages/cli/src/index.ts | 4 +- .../packages/cli/src/lib/detect-stack.ts | 1 + .../test/library-manifest-resolved.test.ts | 37 +- .../cli/test/unit/stack-values.test.ts | 6 + .../scripts/build-shipped-agent-context.ts | 55 + .../sdk/src/agent-context/assemble.ts | 2 +- .../packages/sdk/src/agent-context/index.ts | 1 + .../packages/sdk/src/agent-context/resolve.ts | 1 + .../packages/sdk/src/agent-context/shipped.ts | 174 + .../packages/sdk/src/agent-context/types.ts | 2 +- .../sdk/test/agent-context/resolve.test.ts | 4 + .../sdk/test/agent-context/shipped.test.ts | 146 + .../sdk/test/agent-context/types.test.ts | 2 +- ...ADR-0033-single-agent-context-assembler.md | 32 + 164 files changed, 28028 insertions(+), 12 deletions(-) create mode 100644 agent-context-shipped/README.md create mode 100644 agent-context-shipped/files/0080df7715486e4c.md create mode 100644 agent-context-shipped/files/0440a95faf89e271.md create mode 100644 agent-context-shipped/files/063a909f9775df93.md create mode 100644 agent-context-shipped/files/0ee567e8d039312d.md create mode 100644 agent-context-shipped/files/0fe543fe1b3c9b3c.md create mode 100644 agent-context-shipped/files/103a368daf29e749.md create mode 100644 agent-context-shipped/files/10f8c588c3a14034.md create mode 100644 agent-context-shipped/files/1217aab33469e7bd.md create mode 100644 agent-context-shipped/files/123dcfb6c65640a0.md create mode 100644 agent-context-shipped/files/124752f4316a72cc.md create mode 100644 agent-context-shipped/files/13b9b0de13b23fab.md create mode 100644 agent-context-shipped/files/14ca7edcbf971bef.md create mode 100644 agent-context-shipped/files/1c25799a074fff7d.md create mode 100644 agent-context-shipped/files/1e0fda1afdd26e1a.md create mode 100644 agent-context-shipped/files/1e292839ec10ca12.md create mode 100644 agent-context-shipped/files/1ed66f8d84192ee1.md create mode 100644 agent-context-shipped/files/1fc0b42e73b64728.md create mode 100644 agent-context-shipped/files/1ffb7e594a3532d3.md create mode 100644 agent-context-shipped/files/20ec11b332e12322.md create mode 100644 agent-context-shipped/files/260df9380fb2eb9d.md create mode 100644 agent-context-shipped/files/2fe5f67ab529af0c.md create mode 100644 agent-context-shipped/files/34d60341c7210314.md create mode 100644 agent-context-shipped/files/378f755bb43b1e71.md create mode 100644 agent-context-shipped/files/417c26a7097034e4.md create mode 100644 agent-context-shipped/files/4244641a71a9c537.md create mode 100644 agent-context-shipped/files/42b77a057282e309.md create mode 100644 agent-context-shipped/files/4426fbef79f236fb.md create mode 100644 agent-context-shipped/files/46659a758d40373b.md create mode 100644 agent-context-shipped/files/490fa77b77d0a1cc.md create mode 100644 agent-context-shipped/files/494853543fba1c5f.md create mode 100644 agent-context-shipped/files/4d4d3378a83fb76e.md create mode 100644 agent-context-shipped/files/4f6d18160c694c41.md create mode 100644 agent-context-shipped/files/51b5c54862c75382.md create mode 100644 agent-context-shipped/files/58d380101a100501.md create mode 100644 agent-context-shipped/files/5a2f3bbdcf835d47.md create mode 100644 agent-context-shipped/files/5b789ec72652dfa6.md create mode 100644 agent-context-shipped/files/5df6f5793c17c564.md create mode 100644 agent-context-shipped/files/608f89f60afad4b9.md create mode 100644 agent-context-shipped/files/636d4309c12de5cb.md create mode 100644 agent-context-shipped/files/651a126eaa501924.md create mode 100644 agent-context-shipped/files/6554b044ac4e5c29.md create mode 100644 agent-context-shipped/files/6935df5f6afbbf93.md create mode 100644 agent-context-shipped/files/6afa98a9c7fd23f6.md create mode 100644 agent-context-shipped/files/6b42cc8511e0eb7d.md create mode 100644 agent-context-shipped/files/6e3f75ac9b8e8680.md create mode 100644 agent-context-shipped/files/80606ed514438d51.md create mode 100644 agent-context-shipped/files/83fa1bfb70e0da93.md create mode 100644 agent-context-shipped/files/84b5d02029893745.md create mode 100644 agent-context-shipped/files/86974256b798cf22.md create mode 100644 agent-context-shipped/files/8a9c3f4a4119022a.md create mode 100644 agent-context-shipped/files/8b16b974614265d4.md create mode 100644 agent-context-shipped/files/8cd1bca8a659b6ef.md create mode 100644 agent-context-shipped/files/91463562405e88cc.md create mode 100644 agent-context-shipped/files/940c3d118c7ab1dc.md create mode 100644 agent-context-shipped/files/969f739fa94d7a76.md create mode 100644 agent-context-shipped/files/98f64001b169da91.md create mode 100644 agent-context-shipped/files/9b23d9815903eeab.md create mode 100644 agent-context-shipped/files/9fbf06132414b6be.md create mode 100644 agent-context-shipped/files/a1b81119468f84a9.md create mode 100644 agent-context-shipped/files/a431af761169a99d.md create mode 100644 agent-context-shipped/files/a7fd4ec2565ab8c0.md create mode 100644 agent-context-shipped/files/b28302f5febaea38.md create mode 100644 agent-context-shipped/files/b3680649050a0d51.md create mode 100644 agent-context-shipped/files/b70e863795b7a44f.md create mode 100644 agent-context-shipped/files/b8371541b1d36c6b.md create mode 100644 agent-context-shipped/files/be3b1226c6f00862.md create mode 100644 agent-context-shipped/files/bf673961bd3ea6ea.md create mode 100644 agent-context-shipped/files/bfe25e4bd2cf097d.md create mode 100644 agent-context-shipped/files/c13bca93ec2f4d50.md create mode 100644 agent-context-shipped/files/c1a4896ebda79dd9.md create mode 100644 agent-context-shipped/files/c37f1e343d6e2832.md create mode 100644 agent-context-shipped/files/c5b68292c9103dcc.md create mode 100644 agent-context-shipped/files/c6dbd68483d196ea.md create mode 100644 agent-context-shipped/files/c7994468651aa905.md create mode 100644 agent-context-shipped/files/ca05e997cc76ca60.md create mode 100644 agent-context-shipped/files/cb2bbe4cb7d06c55.md create mode 100644 agent-context-shipped/files/ce8ecdef3b83fec0.md create mode 100644 agent-context-shipped/files/cf1872a72588959a.md create mode 100644 agent-context-shipped/files/cffbbf66c1dff86f.md create mode 100644 agent-context-shipped/files/d3eaa47c0bbd9332.md create mode 100644 agent-context-shipped/files/d3f2f83fe9835f64.md create mode 100644 agent-context-shipped/files/d6bd70c9bf36eb46.md create mode 100644 agent-context-shipped/files/db66e0e785a6cf50.md create mode 100644 agent-context-shipped/files/dd80d926c56ea1e3.md create mode 100644 agent-context-shipped/files/e1f6478444c1e120.md create mode 100644 agent-context-shipped/files/e413f6fcd012b1f3.md create mode 100644 agent-context-shipped/files/e5c6430567eecae4.md create mode 100644 agent-context-shipped/files/e626029a53526f92.md create mode 100644 agent-context-shipped/files/e899275df4b48c66.md create mode 100644 agent-context-shipped/files/e985f8151935157d.md create mode 100644 agent-context-shipped/files/eab139844783c8e7.md create mode 100644 agent-context-shipped/files/f02832e4d7770c3c.md create mode 100644 agent-context-shipped/files/f410d7096bb80685.md create mode 100644 agent-context-shipped/files/f425eaf3566cf602.md create mode 100644 agent-context-shipped/files/f578d3e76cb97c78.md create mode 100644 agent-context-shipped/files/f745f2c1411ab2f0.md create mode 100644 agent-context-shipped/files/f80806308b356cb6.md create mode 100644 agent-context-shipped/files/fb3d3670ae387530.md create mode 100644 agent-context-shipped/files/fda1a58ac1585828.md create mode 100644 agent-context-shipped/files/fe7f8817bfc35bb5.md create mode 100644 agent-context-shipped/manifest.json create mode 100644 agent-context/servers/rust.meta.json create mode 100644 agent-context/templates/loops/rust.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/SKILL.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/prompt-anti-patterns.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/requirements.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/surface-review-axes.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/vocabulary-hygiene.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/SKILL.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/abstracts-and-overlay.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-code.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/choosing-a-shape.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/identities-and-indexes.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/json-columns.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/model-first-rationale.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/read-views-and-projections.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/relationships.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/reporting.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/requirements.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-authoring/references/sources.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/SKILL.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/references/any-stack.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/references/choosing-layers.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/references/owning-generators.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/references/physical-names.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/references/principles.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/references/template-or-code.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-codegen/references/wire-format.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-prompts/SKILL.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-runtime-ui/SKILL.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-verify/SKILL.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-verify/references/migration.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-verify/references/requirements.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-verify/references/upgrading.md create mode 100644 fixtures/agent-context-conformance/rust/expected/.metaobjects/AGENTS.md create mode 100644 fixtures/agent-context-conformance/rust/stack.json create mode 100644 server/typescript/packages/sdk/scripts/build-shipped-agent-context.ts create mode 100644 server/typescript/packages/sdk/src/agent-context/shipped.ts create mode 100644 server/typescript/packages/sdk/test/agent-context/shipped.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7308935ea4..fc77d4d4ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,20 @@ 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 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/063a909f9775df93.md b/agent-context-shipped/files/063a909f9775df93.md new file mode 100644 index 0000000000..150aa330bf --- /dev/null +++ b/agent-context-shipped/files/063a909f9775df93.md @@ -0,0 +1,106 @@ +# Working with MetaObjects in this project + +> Stack: kotlin server, react, tanstack 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 + +### Kotlin: generate with `mvn metaobjects:generate` + +1. **Config.** The `metaobjects-maven-plugin`'s `` in `pom.xml` is the generator + list, one `` each. Nothing is generated until it is listed. Which + classes to list (the Exposed and Spring tier, requirement tests, API docs) is in the + `metaobjects-codegen` skill's `references/kotlin.md`. +2. **Generate.** `mvn metaobjects:generate`. `mvn metaobjects:eject -Dnames= -Dport=kotlin` + copies a generator to change what it emits. Several Kotlin generators truncate their output + on every run, so never put your own code in a generated file. + +### 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# and Python 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 --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 `/