From fff31a820848396bf5b8746162cd494a2f865ed0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 04:33:53 -0500 Subject: [PATCH 1/4] chore(scripts): raise the install-size budget by ruling, recorded in its history The install of @metaobjectsdev/cli measures 51.5 MB against a 51.0 MB budget: feature growth since #622, measured late because hosted CI does not run ts-slow. Ruling (Firstmate, 2026-11-22): raise to the measurement plus 0.2 MB and keep the declaration maps. check-install-size.mjs accepts a raise only when the newest history entry records it (from main's budget, to the new one, with a reason and a ruling), and it falls back to origin/main when there is no local main, so the never-rises rule no longer skips such a checkout. --- CHANGELOG.md | 8 ++++++++ scripts/check-install-size.mjs | 31 ++++++++++++++++++++++++------- scripts/install-size-budget.json | 14 ++++++++++++-- 3 files changed, 44 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 420429abf8..320851d5ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,14 @@ here.** ## [Unreleased] +- **The install-size budget rises to 51.7 MB, by ruling.** Installing `@metaobjectsdev/cli` now + measures 51.5 MB against a 51.0 MB budget. The growth since #622 (the service generator and the + 1.3.0 codegen and runtime work) was measured late because hosted CI does not run `ts-slow`. + Declaration maps stay, so go-to-definition still reaches the shipped source. + `scripts/check-install-size.mjs` now accepts a raise only when the newest `history` entry in + `scripts/install-size-budget.json` records it with its reason and ruling. It also reads + `origin/main` when a checkout has no local `main`; before this, such a checkout skipped the + never-rises rule entirely. - **codegen-ts: the service layer, part 1 (ADR-0067 layers 4 and 5).** Two new generators, neither scaffolded. `service` (the new `service` layer label, shared by every port's catalog) writes one module per metadata package: a function per derived list, get, create, update and delete of each diff --git a/scripts/check-install-size.mjs b/scripts/check-install-size.mjs index cb3e286da6..569f6ba8c3 100644 --- a/scripts/check-install-size.mjs +++ b/scripts/check-install-size.mjs @@ -18,6 +18,8 @@ // with --update. That is the ratchet: the budget has no way to rise. // 3. `budgetBytes` may not be higher than it is on `main`. Raising it to make a change pass // is the one edit this file exists to refuse; raise it only with a ruling that says why. +// A raise passes only when the newest `history` entry records it: `from` is main's budget, +// `to` is the new one, and it names the `reason` and the `ruling`. // 4. None of the packages in FORBIDDEN is in the tree (a fresh-install test: the install-time // guard in check-peer-ranges.ts reads manifests, this reads the result). // @@ -119,12 +121,23 @@ function installedNames(modules) { } function mainBudget() { - try { - const text = execFileSync("git", ["show", `main:${BUDGET_FILE}`], { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); - return JSON.parse(text).budgetBytes; - } catch { - return undefined; // no `main` here, or the file is new on this branch + // A worktree or a CI checkout may have no local `main`; the remote's is the same contract. + for (const ref of ["main", "origin/main"]) { + try { + const text = execFileSync("git", ["show", `${ref}:${BUDGET_FILE}`], { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); + return JSON.parse(text).budgetBytes; + } catch { + // try the next ref + } } + return undefined; // no `main` here, or the file is new on this branch +} + +/** The ruling that raised the budget from `from` to `to`: the newest history entry, when it records exactly that. */ +function rulingFor(budget, from, to) { + const last = Array.isArray(budget.history) ? budget.history[budget.history.length - 1] : undefined; + if (last === undefined || last.from !== from || last.to !== to) return undefined; + return typeof last.reason === "string" && last.reason !== "" && typeof last.ruling === "string" && last.ruling !== "" ? last : undefined; } function measure() { @@ -166,7 +179,7 @@ const budget = JSON.parse(readFileSync(BUDGET_PATH, "utf8")); const { bytes, rows, names, packed } = measure(); const mb = (n) => (n / MB).toFixed(1); -console.log(`install size: ${mb(bytes)} MB installing ${ENTRY} (${packed} workspace packages, ${names.length} top-level packages)`); +console.log(`install size: ${mb(bytes)} MB (${bytes} bytes) installing ${ENTRY} (${packed} workspace packages, ${names.length} top-level packages)`); for (const row of rows.slice(0, 8)) console.log(` ${mb(row.bytes).padStart(6)} MB ${row.name}`); const forbidden = Object.keys(FORBIDDEN).filter((name) => names.includes(name)); @@ -181,7 +194,11 @@ if (budget.platform !== platformKey()) { const onMain = mainBudget(); if (onMain !== undefined && budget.budgetBytes > onMain) { - fail(`the budget rose: ${BUDGET_FILE} says ${mb(budget.budgetBytes)} MB and main says ${mb(onMain)} MB. The budget only moves down.`); + const ruling = rulingFor(budget, onMain, budget.budgetBytes); + if (ruling === undefined) { + fail(`the budget rose: ${BUDGET_FILE} says ${mb(budget.budgetBytes)} MB and main says ${mb(onMain)} MB. The budget only moves down, unless the newest \`history\` entry records the raise ({ from: ${onMain}, to: ${budget.budgetBytes}, reason, ruling }).`); + } + console.log(`install-size budget: raised from ${mb(onMain)} MB to ${mb(budget.budgetBytes)} MB by ruling (${ruling.ruling}): ${ruling.reason}`); } if (bytes > budget.budgetBytes) { diff --git a/scripts/install-size-budget.json b/scripts/install-size-budget.json index 540e5e2222..5058d59e56 100644 --- a/scripts/install-size-budget.json +++ b/scripts/install-size-budget.json @@ -1,5 +1,15 @@ { "platform": "linux-x64", - "budgetBytes": 53470878, - "slackBytes": 2097152 + "budgetBytes": 54161931, + "slackBytes": 2097152, + "history": [ + { + "date": "2026-11-22", + "from": 53470878, + "to": 54161931, + "measuredBytes": 53952216, + "reason": "Feature growth since #622 (the service generator and the 1.3.0 codegen and runtime work), measured late because hosted CI does not run ts-slow. Declaration maps stay: they give go-to-definition into the shipped src. The margin over the measurement is 0.2 MB.", + "ruling": "Firstmate, 2026-11-22" + } + ] } From 5d18b7ef7e7e281d5d452c6a54778b01cc10e725 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 05:03:10 -0500 Subject: [PATCH 2/4] feat(codegen-ts): service part 2, ADR-0066 rules enforced by the generated service (L-TS-5) The service generator now writes a command per transition that derives one and a shell per declared command and query, each running ADR-0066 section 6's checks in one transaction: the row (404), the permission point (403 forbidden), the state (409 invalid_transition), the hand-written body, the guarded update (409 invalid_transition or transition_condition_failed) and the event hook. The generic update refuses a changed lifecycle field (409 state_managed). What an app writes attaches through generated interfaces passed to createService(deps): the policy, the operation bodies, optional hooks on the derived writes and the write-event hook. Any of them may refuse, which rolls the write back. The actor is an app-defined type parameter, passed as opts.actor and resolved by the Fastify transport's getActor(request). rules.lifecycle.create, rules.lifecycle.commands and rules.permissions.names: require now act on the generated side. New shared API tests (fixtures/api-contract-conformance/rules/, 17 scenarios with three settings variants) run on the TypeScript service lane in both layouts, and the service compile gate builds the rules model in every dialect. ADR-0066's "no effect yet" is removed, and ADR-0067, the business-rules and API-contract docs and the CHANGELOG say what the service now does. --- CHANGELOG.md | 39 +- docs/CONFORMANCE.md | 10 +- docs/features/api-contract.md | 12 + docs/features/business-rules.md | 80 ++- docs/ports/typescript.md | 7 +- fixtures/api-contract-conformance/README.md | 3 +- .../api-contract-conformance/rules/README.md | 77 +++ .../api-contract-conformance/rules/meta.json | 102 ++++ .../claimed-transition-has-no-command.yaml | 11 + .../create-starts-in-initial-state.yaml | 21 + .../declared-command-transitions.yaml | 32 ++ .../scenarios/declared-error-rolls-back.yaml | 30 + .../declared-permission-is-asked.yaml | 21 + .../scenarios/derived-command-forbidden.yaml | 32 ++ .../derived-command-moves-the-row.yaml | 23 + .../scenarios/event-refusal-rolls-back.yaml | 26 + .../scenarios/hook-refusal-rolls-back.yaml | 20 + .../rules/scenarios/invalid-transition.yaml | 19 + .../public-command-needs-no-actor.yaml | 18 + .../rules/scenarios/public-query.yaml | 12 + .../rules/scenarios/state-managed-update.yaml | 21 + .../transition-condition-failed.yaml | 21 + .../api-contract-conformance/rules/seed.json | 9 + .../commands-all/.metaobjects/config.json | 8 + .../claimed-transition-has-a-command.yaml | 21 + .../commands-none/.metaobjects/config.json | 8 + .../scenarios/no-derived-commands.yaml | 20 + .../create-any/.metaobjects/config.json | 8 + .../scenarios/create-in-any-state.yaml | 21 + fixtures/codegen-noop/rules/README.md | 6 + .../cli/test/unit/rules-inert.test.ts | 47 +- .../codegen-ts/src/generators/service-file.ts | 5 +- .../src/generators/service-routes-file.ts | 3 +- .../packages/codegen-ts/src/service-walk.ts | 236 +++++++- .../codegen-ts/src/templates/service-file.ts | 516 ++++++++++++++++-- .../codegen-ts/test/service-file.test.ts | 100 +++- .../api-contract-rules-generated-server.ts | 211 +++++++ .../integration-tests/src/load-metadata.ts | 5 +- .../packages/integration-tests/src/paths.ts | 3 + .../test/api-contract-rules.test.ts | 46 ++ .../test/service-compile.test.ts | 33 +- .../packages/runtime-ts/src/service/index.ts | 11 +- .../packages/runtime-ts/src/service/rules.ts | 307 +++++++++++ .../runtime-ts/test/service-rules.test.ts | 173 ++++++ ...usiness-rules-operations-and-lifecycles.md | 11 +- .../ADR-0067-layering-and-the-service-seam.md | 12 +- 46 files changed, 2343 insertions(+), 114 deletions(-) create mode 100644 fixtures/api-contract-conformance/rules/README.md create mode 100644 fixtures/api-contract-conformance/rules/meta.json create mode 100644 fixtures/api-contract-conformance/rules/scenarios/claimed-transition-has-no-command.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/create-starts-in-initial-state.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/declared-command-transitions.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/declared-error-rolls-back.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/declared-permission-is-asked.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/derived-command-forbidden.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/derived-command-moves-the-row.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/event-refusal-rolls-back.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/hook-refusal-rolls-back.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/invalid-transition.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/public-command-needs-no-actor.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/public-query.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/state-managed-update.yaml create mode 100644 fixtures/api-contract-conformance/rules/scenarios/transition-condition-failed.yaml create mode 100644 fixtures/api-contract-conformance/rules/seed.json create mode 100644 fixtures/api-contract-conformance/rules/settings/commands-all/.metaobjects/config.json create mode 100644 fixtures/api-contract-conformance/rules/settings/commands-all/scenarios/claimed-transition-has-a-command.yaml create mode 100644 fixtures/api-contract-conformance/rules/settings/commands-none/.metaobjects/config.json create mode 100644 fixtures/api-contract-conformance/rules/settings/commands-none/scenarios/no-derived-commands.yaml create mode 100644 fixtures/api-contract-conformance/rules/settings/create-any/.metaobjects/config.json create mode 100644 fixtures/api-contract-conformance/rules/settings/create-any/scenarios/create-in-any-state.yaml create mode 100644 server/typescript/packages/integration-tests/src/api-contract-rules-generated-server.ts create mode 100644 server/typescript/packages/integration-tests/test/api-contract-rules.test.ts create mode 100644 server/typescript/packages/runtime-ts/src/service/rules.ts create mode 100644 server/typescript/packages/runtime-ts/test/service-rules.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 320851d5ae..2e72f2dbb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,30 @@ here.** ## [Unreleased] +- **codegen-ts: the service layer, part 2 — the rules run (ADR-0066 §6, ADR-0067 §4 and §7).** The + `service` generator now writes a command per transition that derives one (`POST + /{id}/`) and a shell per declared command and query, at its binding or + derived path, and enforces ADR-0066's checks in order, in one transaction: the row (404), the + permission point (403 `forbidden`), the state (409 `invalid_transition`), the hand-written body, + the guarded update (409 `invalid_transition` or `transition_condition_failed`) and the event hook. + The generic update answers a changed lifecycle field 409 `state_managed`. What an app writes is + passed to `createService(deps)` through generated interfaces: `Policy`, `Bodies` + (a command returns the move to make or `"none"`, and `ctx.refuse` answers a declared error), + optional `Hooks` on the derived writes and `Events` told about every write. Any of + them may refuse, which rolls the write back. The actor is an app-defined type parameter, passed + as `opts.actor` and resolved by the Fastify transport's `getActor(request)`. Three settings now + act on the generated side: `rules.lifecycle.create` (`initial` fills an omitted state and refuses + another; `any` accepts any), `rules.lifecycle.commands` (which transitions get a command) and + `rules.permissions.names: require` (generation refuses a point with no `@permission`, naming the + derived one). A transport refuses two routes on one method and path. New shared API tests, + `fixtures/api-contract-conformance/rules/`, cover 403, the three 409 codes, a declared error, a + derived command, a declared command and query, a public operation and a hook's and the event + hook's refusal rolling back, with three settings variants; the TypeScript lane runs them in both + layouts, and the service compile gate builds the model in every dialect. `ServiceDeps`, the + service interface and the factory take the actor type `A` (default `unknown`), so existing calls + compile unchanged. `@metaobjectsdev/runtime-ts/service` gains the helpers they call + (`checkPermission`, `checkState`, `makeTransition`, `checkStateManaged`, `checkCreateState`, + `emitWrite`, `handlerContext`) and their types. - **The install-size budget rises to 51.7 MB, by ruling.** Installing `@metaobjectsdev/cli` now measures 51.5 MB against a 51.0 MB budget. The growth since #622 (the service generator and the 1.3.0 codegen and runtime work) was measured late because hosted CI does not run `ts-slow`. @@ -28,8 +52,8 @@ here.** shared corpus against the service behind its transport, in both layouts, and passes as the flat routes do; a compile gate builds the tier in every dialect. `@metaobjectsdev/runtime-ts` gains the `./service` and `./service/fastify` entries they import, and `meta eject` copies them. - Write-through, TPH, many-to-many, projections, reports, transitions and declared operations stay - on the flat generators for now: [docs/features/business-rules.md](docs/features/business-rules.md#the-service-layer-typescript). + Write-through, TPH, many-to-many, projections and reports stay on the flat generators for now: + [docs/features/business-rules.md](docs/features/business-rules.md#the-service-layer-typescript). - **runtime-ts: a list with no `limit` answers 50 rows (breaking).** A generated entity or projection list in a project that sets no `api.pagination` returned every matching row when the request carried no `limit`; it now answers the first 50, the default of every port. An explicit @@ -738,8 +762,8 @@ Each item below is described in full under Security, Added, Changed or Fixed; th `fixtures/rules-check-conformance/` corpus. - New settings in `.metaobjects/config.json`: `rules.permissions.names`, `rules.lifecycle.commands`, `rules.lifecycle.create` and `verify.lifecycle.unreachable`. - Absent, each behaves as before. `rules.lifecycle.create` is read and validated and has no - effect yet: the service shells that act on it are later work. + Absent, each behaves as before. The service generators act on `rules.lifecycle.create` and + `rules.lifecycle.commands` (TypeScript's first, see [Unreleased]). - A requirement's `@implementedBy` may name an operation (`Purchasing.decide`) or a transition (`PurchaseRequest.status.submit`). - The Rust port (ADR-0065) registers the same vocabulary and runs the same loader @@ -747,9 +771,10 @@ Each item below is described in full under Security, Added, Changed or Fixed; th the whole metamodel corpus (574 of 574, ledger empty). It reads and validates the new settings. It has no `verify`, so the rules gate does not run there. - Nothing is generated from the vocabulary yet: the enforcing service shells are later work - (ADR-0067: service generators an app chooses like any other, not a named set), and - `fixtures/codegen-noop/rules/` holds every generator to byte-identical output. + The flat generators generate nothing from the vocabulary: the enforcing shells are the service + generators (ADR-0067: generators an app chooses like any other, not a named set; TypeScript's + first, see [Unreleased]), and `fixtures/codegen-noop/rules/` holds every flat generator to + byte-identical output. A model that declares none of it sees no change. See `docs/features/business-rules.md`. ADR-0067 records the layering and service-seam design (a layer is a generator an app chooses; the actor is a type the app defines), and amends ADR-0045. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 3b6c0debc8..e1acbb9b21 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -36,7 +36,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`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/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` and `guarded-update` 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/) | 162 (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 + 21 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/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (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 + 21 list-query + 17 rules) | ✓ (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, and `rules/` until each port's 1.3.0 service 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) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | @@ -517,9 +517,9 @@ REAL, a MySQL `DECIMAL` keeps its scale, a MySQL `DATETIME` is the UTC wall cloc `report-relative-date` carries a per-engine seed (`seed-data-engine`). `op: relate` and the write ops stay Postgres-only. See [features/reporting.md](features/reporting.md#what-the-corpus-gates). -### `fixtures/api-contract-conformance/` (162) +### `fixtures/api-contract-conformance/` (179) -All 162 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port +All 179 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port REST API URL grammar + JSON wire format). Verifies every backend's emitted CRUD routes answer identically over HTTP — list / get / create / patch+put / delete, plus pagination (`limit`/`offset`), sort (`sort=field:dir`), the `withCount=1` @@ -546,7 +546,7 @@ canonical string, read exactly, filtered exactly and refused past its declared d in a calendar or clock spelling, and filtered and sorted as a span on every engine), `api-settings/` (8, the project's `api` block: `api.pagination`'s default page, `limit_too_large` cap and refused negative `limit`, an empty page for `limit=0`, and -`api.unknownFields: drop`), `list-query/` (21, the REST standard's list handling against a real store: search ignores case and `like` does not, `filter[or]`/`filter[and]`, the nesting cap, bare fields, a leading `%`, value formats, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript only until each port's 1.3.0 REST-standard work) and `report/` (37, +`api.unknownFields: drop`), `rules/` (17, ADR-0066 through a generated service: derived and declared commands, a query, permission points, the three 409 codes, a declared error and a refusal rolling back, under the default settings and three `rules.*` variants; generated lane, TypeScript only until each port's 1.3.0 service work), `list-query/` (21, the REST standard's list handling against a real store: search ignores case and `like` does not, `filter[or]`/`filter[and]`, the nesting cap, bare fields, a leading `%`, value formats, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals; generated lane, TypeScript only until each port's 1.3.0 REST-standard work) and `report/` (37, FR-044: a view-backed `object.report` is listed, filtered, sorted and paged on its derived fields, answers `POST` with 405 and mounts no `/{id}`; a `@spine` report keeps a row with no facts, and a measure with `@default` filters and sorts as its default). All 5 ports — TS, Java, @@ -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 68 + api-contract 162 + source-resolution 28 + scope 10 + ++ render 21 + persistence 68 + api-contract 179 + 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 diff --git a/docs/features/api-contract.md b/docs/features/api-contract.md index a1c0f89187..6521738391 100644 --- a/docs/features/api-contract.md +++ b/docs/features/api-contract.md @@ -87,6 +87,18 @@ every field. The TS mounts can restrict the update to one verb with |---|---|---| | `GET` | `//_meta` | Serves the loaded model's shape (entities, fields, types, validators, layouts) as JSON — a separate contract, see [`docs/features/metadata-api.md`](metadata-api.md) | +#### Operations and transitions (ADR-0066) + +A generated service (ADR-0067) adds the routes of a model's rules: `POST +///{id}/` for each transition that derives a command, and each +declared command or query at its `binding.rest` method and path or its derived one. They answer +four codes of their own: 403 `forbidden` (the policy refused), 409 `invalid_transition` (the row +is in no `@from` state), 409 `transition_condition_failed` (the `@condition` did not hold) and 409 +`state_managed` (a write named a lifecycle field). A declared business error is 409 with its code. +Each is `{ "error": "" }`. The rules are [business-rules.md](business-rules.md); the +`rules/` sub-corpus pins the answers, generated lane, TypeScript only until each port's 1.3.0 +service work. + #### The `` segment `` is the **entity name** `snake_case`d and then pluralized. One rule, the diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 83b614d7c6..1a2f39445e 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -24,11 +24,13 @@ guarded update a transition writes, `ObjectManager.guardedUpdate`, held to the s persistence scenario `guarded-update.yaml`. The service layer starts in TypeScript: `service` writes each package's derived list, get, create, update and delete, every write in one transaction with the declared write rules, behind a thin Fastify transport (`service-routes`) that answers the shared API -tests as the flat routes do (see [The service layer](#the-service-layer-typescript)). Transitions, -declared operations, the policy, the bodies and events interfaces, and the checks 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 +tests as the flat routes do (see [The service layer](#the-service-layer-typescript)). It also writes +a command per transition and a shell per declared command and query, and enforces at run time what +this page declares: the permission point, the state check, the guarded update, `state_managed` and +the declared errors, held to the shared API tests' `rules/` corpus. The other ports' services are +later 1.3.0 work. A lifecycle in a project that wires no service generator will be advised by +`verify` once that check lands; until then the flat routes enforce nothing and `verify` says +nothing about it. Every flat generator writes byte-identical code for a model with this vocabulary and the same model without it. The design is [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md). **Experimental.** This vocabulary, its loader rules, its `verify` checks and its settings may @@ -239,9 +241,9 @@ setting behaves as it does today. | Setting | Values | When absent | Effect | |---|---|---|---| -| `rules.permissions.names` | `derive`, `advise`, `require` | `derive` | `derive` accepts derived permission names. `advise` warns about each one. `require` fails `verify` on each one. | +| `rules.permissions.names` | `derive`, `advise`, `require` | `derive` | `derive` accepts derived permission names. `advise` warns about each one. `require` fails `verify` on each one, and the TypeScript service generator refuses to generate such a point, naming the permission it would derive. | | `rules.lifecycle.commands` | `unclaimed`, `all`, `none` | `unclaimed` | Which transitions derive a command of their own, and so are permission points: those no declared command claims, every one, or none. A command claims a transition for its target entity and every entity extending it. | -| `rules.lifecycle.create` | `initial`, `any` | `initial` | **No effect yet.** Whether a create may start a row in a state other than the initial one. It is read and validated, and nothing acts on it until the service shells land. | +| `rules.lifecycle.create` | `initial`, `any` | `initial` | Whether a create may start a row in a state other than the initial one. Under `initial` the generated service fills an omitted state with the initial one and answers a different one 409 `state_managed`; under `any` it accepts any state of the lifecycle. The TypeScript service acts on it; a port whose service has not landed has nothing to act on. | | `verify.lifecycle.unreachable` | `warn`, `error`, `off` | `warn` | The severity of the two reachability checks. `off` skips them. | ```json @@ -349,8 +351,9 @@ directory in either layout. - `/service/.ts`: one function per operation, `(deps, ...args, opts) => OpResult`. Each concrete entity with a writable table and a single-field key gets five: `list`, `get`, `create`, `update` and `delete`. -- `/service/index.ts`: `ServiceDeps` (the database), the `Service` interface, - `createService(deps)` that binds the operations to it, and each entity's wire mapper. +- `/service/index.ts`: `ServiceDeps` (the database, and the hand-written pieces below), + the `Service` interface, `createService(deps)` that binds the operations to it, and + each entity's wire mapper. Every write runs in one transaction, in ADR-0067's order: load the row under a row lock (`not_found` when there is none), validate the input and stamp what the model declares (ADR-0045: `@autoSet`, @@ -389,9 +392,64 @@ Both import the entity module (`entity`, for the table and the allowlists) and t `codegen/runtime/` as they do for the routes. The service lane of the shared API tests runs the corpus the flat routes pass against the service behind this transport, in both layouts. +### Transitions, declared operations and what you write by hand + +The service also writes what the rules on this page declare: + +- `/service/.ts` for each transition that derives a command (by + `rules.lifecycle.commands`), mounted at `POST /{id}/`. +- `/service/.ts` for each declared command and query, mounted at its + `binding.rest` method and path, or at the derived path (`/{id}/` when it + addresses a row, `/` when it does not; a query is a `GET`, a command a + `POST`). Two routes on one method and path are refused when the transport is generated. + +Each one runs ADR-0066 §6's checks in this order, in one transaction (a query in the read scope): +load the row (`not_found`), validate the input, the permission point (403 `forbidden`), the state +check (409 `invalid_transition`), the hand-written body, the guarded update (409 +`invalid_transition` or `transition_condition_failed` when it matches no row), and the event hook. +The generic update refuses a different value of a lifecycle field (409 `state_managed`) and lets +the same value through. Under `rules.lifecycle.create: initial` a create starts in the initial +state, so an omitted state is filled and another is `state_managed`. + +What you write is passed to `createService(deps)`; there is no base class to extend. +`index.ts` types each piece: + +| In `deps` | Type | What it is | +|---|---|---| +| `policy` | `Policy` | `allows(permission, actor, row, input, tx)`: a refusal is 403 `forbidden`. Required when the package has a permission point. `Permission` lists every name it is asked about. | +| `bodies` | `Bodies` | One per declared operation. A command with `@transitions` returns the move to make, or `"none"`; `ctx.refuse(code)` answers one of its `@errors` (409). Required when the package declares an operation. | +| `hooks` | `Hooks` | Optional `before`/`after` hooks on each derived create, update and delete. A before hook may return a replacement input. | +| `events` | `Events` | Optional `onWrite(event, ctx)`, told about every create, update, delete, transition and command, in its transaction, with the actor. An outbox, a history table or an audit log is written here. | + +Every hook, body and event runs in the write's transaction (`ctx.tx`), and any of them may refuse +with `ctx.refuse(code)`, which answers 409 with that code and rolls the whole write back. A code the +API contract reserves (`not_found`, `forbidden`, `validation`, ...) is not accepted. + +The actor is a type you define, `A`. A caller passes it per call as `opts.actor`, and the service +hands it to the policy, the bodies, the hooks and the event hook without looking inside it. The +Fastify transport takes a `getActor(request)` resolver of yours: + +```ts +const service = createPurchasingService({ + db, + policy: { allows: (permission, actor) => actor?.grants.includes(permission) ?? false }, + bodies: { + decide: (input, ctx) => (input.approve ? "approve" : "reject"), + requestTotals: async (ctx) => totalsOf(ctx.tx), + }, + events: { onWrite: (event, ctx) => writeAudit(ctx.tx, event) }, +}); +await app.register(purchasingServiceRoutes, { service, getActor: (req) => actorFromSession(req) }); +``` + +The shared API tests' `fixtures/api-contract-conformance/rules/` corpus runs a model with a +lifecycle, a declared command and query, permission points and declared errors against the +generated service, under the default settings and under `rules.lifecycle.create: any` and +`rules.lifecycle.commands: all` and `none`. Its README specifies the hand-written pieces, so every +port's lane implements the same ones. + Not covered yet, and still served by the flat generators: write-through entities, single-table (TPH) -hierarchies, many-to-many traversal, projections and reports. Transitions and declared operations -come with the policy, bodies and events interfaces. +hierarchies, many-to-many traversal, projections and reports. ## Requirements can claim operations and transitions diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index d02084c7f6..7495488af3 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -755,8 +755,11 @@ and give it its own `target` to put the layer in a package the transport and cli module per metadata package, under the package's directory in either layout: a file per operation in `/service/` (each entity's derived list, get, create, update and delete, every write in one transaction with the declared write rules) and `service/index.ts` with the `Service` -interface and `createService(deps)`. `serviceRoutesFile()` (stable name `service-routes`) -writes `/transport/fastify.ts`, the routes that call it. Both need `entity` and +interface and `createService(deps)`. A model with ADR-0066 rules also gets a file per +derived transition command and per declared command and query, each running the rules' checks +around a hand-written body; the policy, bodies, hooks and event hook are passed in `deps`. +`serviceRoutesFile()` (stable name `service-routes`) writes `/transport/fastify.ts`, the +routes that call it, with a `getActor(request)` option for the app's actor. Both need `entity` and `contract-types` in the same target. Neither is scaffolded; add them to `generators` or `meta eject` them. On SQLite the service needs an async Drizzle driver such as libsql (`Db` is `BaseSQLiteDatabase<"async", …>`). See [Business rules](../features/business-rules.md#the-service-layer-typescript). diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 96b2f880b2..7adc4c522e 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -57,7 +57,7 @@ fixtures/api-contract-conformance/ ``` Beside the 34 core scenarios above sit twelve **sub-corpora**, each a directory with its -own `meta.json`, `seed.json`, `scenarios/` and `README.md` (128 scenarios in all, 162 with the +own `meta.json`, `seed.json`, `scenarios/` and `README.md` (145 scenarios in all, 179 with the core): | Directory | Scenarios | Gates | Lanes | @@ -74,6 +74,7 @@ core): | `api-settings/` | 8 | the `api` block in the sub-corpus's own `.metaobjects/config.json`: `api.pagination` (default 2, max 4) — a list with no `limit` answers the default page, `offset` and `withCount=1` page past it, `limit` at the cap is served, one above it is `400 {"error": "limit_too_large", "maxLimit": 4}` and a negative one is `400 pagination.invalid_value`, while `limit=0` is an empty page — and `api.unknownFields: drop`, under which an undeclared body key is ignored rather than refused | generated only | | `list-query/` | 21 | the REST standard's list handling against a real store, over a 60-row seed: `?search` ignores case and `like` does not, `filter[or]` / `filter[and]`, the nesting cap, a bare field refused, a leading `%` refused, value formats refused, a default page of 50, paging past 50, and the `invalid_json`, `invalid_id`, `pagination.invalid_value` and `constraint_violation` refusals. The parse itself is pinned with no server by `fixtures/list-query-conformance/`. TypeScript only until each port's 1.3.0 REST-standard work | generated only | | `duration/` | 2 | `field.duration` is a canonical ISO-8601 span on the wire under `"wire": { "durations": "iso" }`: write, read, refuse, and filter and sort as a span on every engine. Also carries `schema.postgres.sql` / `schema.sqlite.sql` / `schema.mysql.sql` | generated only | +| `rules/` | 17 | ADR-0066 through a generated service: a derived transition command and its derived permission name, a declared `@permission`, 403 `forbidden`, the three 409 codes (`invalid_transition`, `transition_condition_failed`, `state_managed` on update and create), a declared command and its declared error, a `@public` command and query, a claimed transition with no command of its own, and a hook's and the event hook's refusal rolling the write back; `settings/` runs `rules.lifecycle.create: any` and `rules.lifecycle.commands: all` and `none` over the same model | generated only, TypeScript only until each port's 1.3.0 service work | `meta.json` declares a single canonical `Author` entity in the `acme::blog` package: diff --git a/fixtures/api-contract-conformance/rules/README.md b/fixtures/api-contract-conformance/rules/README.md new file mode 100644 index 0000000000..99b4c6b56c --- /dev/null +++ b/fixtures/api-contract-conformance/rules/README.md @@ -0,0 +1,77 @@ +# api-contract-conformance / rules + +Gates what a generated service does with ADR-0066's rules, over HTTP: the lifecycle, the derived +transition commands, a declared command and query, the permission points, the declared errors and +the refusals of a hook and of the event hook. The check order and the answers are ADR-0066 §6; the +hand-written pieces attach as ADR-0067 §4 and §7 describe. + +**Generated lane only, by design.** What is under test is whether a port's service GENERATOR emits +these shells. A hand-rolled reference server would answer every scenario by construction. + +## The model + +`meta.json`, package `acme::purchasing`: + +- `PurchaseRequest` (table `purchase_requests`): `id`, `title`, `amountCents`, `limitCents` and the + lifecycle field `status` (`draft`, `submitted`, `approved`, `rejected`, `cancelled`; initial + `draft`). Its transitions: + + | Transition | From | To | Permission | + |---|---|---|---| + | `submit` | `draft` | `submitted` | derived: `acme::purchasing.PurchaseRequest.submit` | + | `approve` | `submitted` | `approved` | derived; `@condition` amountCents <= coalesce(limitCents, 0) | + | `reject` | `submitted` | `rejected` | derived | + | `cancel` | `draft`, `submitted` | `cancelled` | `@public` | + | `reopen` | `rejected` | `draft` | declared: `purchasing.reopen` | + +- `AuditEntry` (table `audit_entries`): `id`, `kind`, `detail`. The event hook writes it. +- API `Purchasing`: + - `decide`, a command: input `DecisionInput` (`requestId` borrows the key, `approve`, `note`), + `@transitions` `approve` and `reject`, `@permission: purchasing.decide`, `@errors` + `note_required`, bound to `PUT /purchase-requests/{id}/decision`, answering the request. + - `requestTotals`, a `@public` query on `PurchaseRequest`, answering `RequestTotals` + (`count`, `totalCents`) at the derived path `GET /purchase_requests/requestTotals`. + +Routes mount under `/api`. `seed.json` holds requests 1 to 5, in states `draft`, `submitted`, +`submitted` (over its limit), `rejected` and `approved`. + +## The hand-written pieces every lane implements + +These are the app's code, not the generator's, and every port's lane writes the same ones: + +- **Actor.** From the request headers: `x-actor` is the actor's name (absent or empty: no actor), + `x-grants` a comma-separated list of the permission names it holds. +- **Policy.** Allows a permission exactly when the actor holds it by name. No actor is refused. +- **`decide` body.** When `approve` is false and `note` is absent or empty, refuse `note_required`. + Otherwise return `approve` when `approve` is true, else `reject`. +- **`requestTotals` body.** `count` is the number of purchase requests, `totalCents` the sum of + their `amountCents` (0 for none), read in the query's scope. +- **Hook.** After a purchase request is updated, refuse `title_refused` when its title is + `REFUSE`. +- **Event hook.** For every write: refuse `audit_unavailable` when the actor's name is + `no-audit`; otherwise insert an audit entry in the write's transaction, `kind` the event's kind + and `detail`: + - a transition: ` -> by `; + - a command that made no move: ` by `; + - a create, update or delete: ` by `. + +## Settings variants + +`scenarios/` runs under the default settings. Each `settings//` directory holds a +`.metaobjects/config.json` and its own `scenarios/`, run over the same `meta.json` and seed: + +| Variant | Setting | What it shows | +|---|---|---| +| `create-any` | `rules.lifecycle.create: any` | a create may start in any state | +| `commands-all` | `rules.lifecycle.commands: all` | a transition `decide` claims still gets its own command | +| `commands-none` | `rules.lifecycle.commands: none` | no transition gets a command; `decide` still moves | + +A 404 for a route that is not mounted is asserted on the status only: the body is the web +framework's own. + +## Port coverage + +| Port | Lane | +|---|---| +| TypeScript | `server/typescript/packages/integration-tests/test/api-contract-rules.test.ts`, both output layouts | +| C#, Java, Kotlin, Python | not yet: each port's service generator is its own 1.3.0 work | diff --git a/fixtures/api-contract-conformance/rules/meta.json b/fixtures/api-contract-conformance/rules/meta.json new file mode 100644 index 0000000000..1acfde5c14 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/meta.json @@ -0,0 +1,102 @@ +{ + "metadata.root": { + "package": "acme::purchasing", + "children": [ + { + "object.entity": { + "name": "PurchaseRequest", + "children": [ + { "source.rdb": { "@table": "purchase_requests" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } }, + { "field.string": { "name": "title", "@maxLength": 80, "@required": true } }, + { "field.long": { "name": "amountCents", "@required": true } }, + { "field.long": { "name": "limitCents" } }, + { + "field.enum": { + "name": "status", + "@values": ["draft", "submitted", "approved", "rejected", "cancelled"], + "@default": "draft", + "children": [ + { "transition.action": { "name": "submit", "@from": ["draft"], "@to": "submitted" } }, + { + "transition.action": { + "name": "approve", + "@from": ["submitted"], + "@to": "approved", + "@condition": { + "op": "lte", + "left": { "field": "amountCents" }, + "right": { "fn": "coalesce", "args": [{ "field": "limitCents" }, { "value": 0 }] } + } + } + }, + { "transition.action": { "name": "reject", "@from": ["submitted"], "@to": "rejected" } }, + { "transition.action": { "name": "cancel", "@from": ["draft", "submitted"], "@to": "cancelled", "@public": true } }, + { "transition.action": { "name": "reopen", "@from": ["rejected"], "@to": "draft", "@permission": "purchasing.reopen" } } + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "AuditEntry", + "children": [ + { "source.rdb": { "@table": "audit_entries" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } }, + { "field.string": { "name": "kind", "@maxLength": 20, "@required": true } }, + { "field.string": { "name": "detail", "@maxLength": 200, "@required": true } } + ] + } + }, + { + "object.value": { + "name": "DecisionInput", + "children": [ + { "field.long": { "name": "requestId", "extends": "PurchaseRequest.id" } }, + { "field.boolean": { "name": "approve", "@required": true } }, + { "field.string": { "name": "note", "@maxLength": 200 } } + ] + } + }, + { + "object.value": { + "name": "RequestTotals", + "children": [ + { "field.long": { "name": "count" } }, + { "field.long": { "name": "totalCents" } } + ] + } + }, + { + "api.operational": { + "name": "Purchasing", + "children": [ + { + "operation.command": { + "name": "decide", + "@inputRef": "DecisionInput", + "@outputRef": "PurchaseRequest", + "@transitions": ["approve", "reject"], + "@permission": "purchasing.decide", + "@errors": ["note_required"], + "children": [{ "binding.rest": { "@method": "PUT", "@path": "/purchase-requests/{id}/decision" } }] + } + }, + { + "operation.query": { + "name": "requestTotals", + "@objectRef": "PurchaseRequest", + "@outputRef": "RequestTotals", + "@public": true + } + } + ] + } + } + ] + } +} diff --git a/fixtures/api-contract-conformance/rules/scenarios/claimed-transition-has-no-command.yaml b/fixtures/api-contract-conformance/rules/scenarios/claimed-transition-has-no-command.yaml new file mode 100644 index 0000000000..17d1338456 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/claimed-transition-has-no-command.yaml @@ -0,0 +1,11 @@ +name: claimed-transition-has-no-command +description: > + Under the default `rules.lifecycle.commands: unclaimed`, a transition a declared command lists + in `@transitions` derives no command of its own: `approve` is reached only through `decide`. +requests: + - id: r1 + method: POST + path: /api/purchase_requests/2/approve + headers: { x-actor: "rita", x-grants: "acme::purchasing.PurchaseRequest.approve,purchasing.decide" } + expect: + status: 404 diff --git a/fixtures/api-contract-conformance/rules/scenarios/create-starts-in-initial-state.yaml b/fixtures/api-contract-conformance/rules/scenarios/create-starts-in-initial-state.yaml new file mode 100644 index 0000000000..58b5d9dc3b --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/create-starts-in-initial-state.yaml @@ -0,0 +1,21 @@ +name: create-starts-in-initial-state +description: > + Under the default `rules.lifecycle.create: initial`, a create starts the lifecycle in its + initial state (the enum's `@default`): omitted, the row is `draft`; naming another state is 409 + `state_managed`, and no row is written. +requests: + - id: r1 + method: POST + path: /api/purchase_requests + body: { title: "Phone", amountCents: 50000, status: "approved" } + expect: + status: 409 + body: { error: "state_managed" } + - id: r2 + method: POST + path: /api/purchase_requests + body: { title: "Phone", amountCents: 50000 } + expect: + status: 201 + body: + row: { id: 6, title: "Phone", status: "draft" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/declared-command-transitions.yaml b/fixtures/api-contract-conformance/rules/scenarios/declared-command-transitions.yaml new file mode 100644 index 0000000000..5258658696 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/declared-command-transitions.yaml @@ -0,0 +1,32 @@ +name: declared-command-transitions +description: > + A declared command bound to `PUT /purchase-requests/{id}/decision` takes its input with the key + from the path, asks for its declared permission, and its body picks the move. Approving request + 2 (amount 30000, limit 50000) moves it to `approved`, and the answer is the row as the command + left it. Rejecting request 3 with a note moves it to `rejected`. +requests: + - id: r1 + method: PUT + path: /api/purchase-requests/2/decision + headers: { x-actor: "rita", x-grants: "purchasing.decide" } + body: { approve: true } + expect: + status: 200 + body: + row: { id: 2, status: "approved" } + - id: r2 + method: PUT + path: /api/purchase-requests/3/decision + headers: { x-actor: "rita", x-grants: "purchasing.decide" } + body: { approve: false, note: "too large" } + expect: + status: 200 + body: + row: { id: 3, status: "rejected" } + - id: r3 + method: PUT + path: /api/purchase-requests/2/decision + body: { approve: true } + expect: + status: 403 + body: { error: "forbidden" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/declared-error-rolls-back.yaml b/fixtures/api-contract-conformance/rules/scenarios/declared-error-rolls-back.yaml new file mode 100644 index 0000000000..f8443411f6 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/declared-error-rolls-back.yaml @@ -0,0 +1,30 @@ +name: declared-error-rolls-back +description: > + A body refusing with one of its `@errors` is answered 409 with that code. The README's `decide` + body refuses a rejection without a note as `note_required`; the request keeps its state. A + command on a row in no state of its `@transitions`' `@from` is `invalid_transition` before the + body runs. +requests: + - id: r1 + method: PUT + path: /api/purchase-requests/2/decision + headers: { x-actor: "rita", x-grants: "purchasing.decide" } + body: { approve: false } + expect: + status: 409 + body: { error: "note_required" } + - id: r2 + method: GET + path: /api/purchase_requests/2 + expect: + status: 200 + body: + row: { id: 2, status: "submitted" } + - id: r3 + method: PUT + path: /api/purchase-requests/5/decision + headers: { x-actor: "rita", x-grants: "purchasing.decide" } + body: { approve: true } + expect: + status: 409 + body: { error: "invalid_transition" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/declared-permission-is-asked.yaml b/fixtures/api-contract-conformance/rules/scenarios/declared-permission-is-asked.yaml new file mode 100644 index 0000000000..feaef9a4cd --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/declared-permission-is-asked.yaml @@ -0,0 +1,21 @@ +name: declared-permission-is-asked +description: > + A transition that declares `@permission` asks for that name, not the derived one. `reopen` + declares `purchasing.reopen`: the derived name `acme::purchasing.PurchaseRequest.reopen` is not + enough, and the declared one moves the rejected request 4 back to `draft`. +requests: + - id: r1 + method: POST + path: /api/purchase_requests/4/reopen + headers: { x-actor: "ann", x-grants: "acme::purchasing.PurchaseRequest.reopen" } + expect: + status: 403 + body: { error: "forbidden" } + - id: r2 + method: POST + path: /api/purchase_requests/4/reopen + headers: { x-actor: "ann", x-grants: "purchasing.reopen" } + expect: + status: 200 + body: + row: { id: 4, status: "draft" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/derived-command-forbidden.yaml b/fixtures/api-contract-conformance/rules/scenarios/derived-command-forbidden.yaml new file mode 100644 index 0000000000..ca019c5916 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/derived-command-forbidden.yaml @@ -0,0 +1,32 @@ +name: derived-command-forbidden +description: > + The permission point is asked after the row is loaded and before anything is written. An actor + without the derived permission, or no actor at all, is answered 403 `forbidden`, and the row + keeps its state. A missing row is `not_found` before the policy is asked. +requests: + - id: r1 + method: POST + path: /api/purchase_requests/1/submit + headers: { x-actor: "bob", x-grants: "purchasing.decide" } + expect: + status: 403 + body: { error: "forbidden" } + - id: r2 + method: POST + path: /api/purchase_requests/1/submit + expect: + status: 403 + body: { error: "forbidden" } + - id: r3 + method: POST + path: /api/purchase_requests/99/submit + expect: + status: 404 + body: { error: "not_found" } + - id: r4 + method: GET + path: /api/purchase_requests/1 + expect: + status: 200 + body: + row: { id: 1, status: "draft" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/derived-command-moves-the-row.yaml b/fixtures/api-contract-conformance/rules/scenarios/derived-command-moves-the-row.yaml new file mode 100644 index 0000000000..ab7e3e9cf5 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/derived-command-moves-the-row.yaml @@ -0,0 +1,23 @@ +name: derived-command-moves-the-row +description: > + A transition no declared command claims derives a command, `POST /{id}/`, + whose permission point asks for the derived name `..`. Holding it, + the draft request 1 moves to `submitted`; the answer is the written row, and the event hook is + told about the move in the same transaction (one audit entry). +requests: + - id: r1 + method: POST + path: /api/purchase_requests/1/submit + headers: { x-actor: "ann", x-grants: "acme::purchasing.PurchaseRequest.submit" } + expect: + status: 200 + body: + row: { id: 1, title: "Laptop", status: "submitted" } + - id: r2 + method: GET + path: /api/audit_entries + expect: + status: 200 + body: + equals: + - { id: 1, kind: "transition", detail: "PurchaseRequest 1 submit draft->submitted by ann" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/event-refusal-rolls-back.yaml b/fixtures/api-contract-conformance/rules/scenarios/event-refusal-rolls-back.yaml new file mode 100644 index 0000000000..17c0f1a349 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/event-refusal-rolls-back.yaml @@ -0,0 +1,26 @@ +name: event-refusal-rolls-back +description: > + The event hook runs last, in the same transaction as the move. The README's event hook refuses + any write by the actor `no-audit` as `audit_unavailable`: the transition is answered 409 with + that code and undone, and no audit entry is kept. +requests: + - id: r1 + method: POST + path: /api/purchase_requests/1/submit + headers: { x-actor: "no-audit", x-grants: "acme::purchasing.PurchaseRequest.submit" } + expect: + status: 409 + body: { error: "audit_unavailable" } + - id: r2 + method: GET + path: /api/purchase_requests/1 + expect: + status: 200 + body: + row: { id: 1, status: "draft" } + - id: r3 + method: GET + path: /api/audit_entries + expect: + status: 200 + body: { length: 0 } diff --git a/fixtures/api-contract-conformance/rules/scenarios/hook-refusal-rolls-back.yaml b/fixtures/api-contract-conformance/rules/scenarios/hook-refusal-rolls-back.yaml new file mode 100644 index 0000000000..c2e9d787a0 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/hook-refusal-rolls-back.yaml @@ -0,0 +1,20 @@ +name: hook-refusal-rolls-back +description: > + A hook runs in the write's transaction, so its refusal undoes the write. The README's + `afterUpdatePurchaseRequest` hook refuses a title of `REFUSE` as `title_refused` after the row + is written: the answer is 409 with that code, and the row keeps its title. +requests: + - id: r1 + method: PATCH + path: /api/purchase_requests/1 + body: { title: "REFUSE" } + expect: + status: 409 + body: { error: "title_refused" } + - id: r2 + method: GET + path: /api/purchase_requests/1 + expect: + status: 200 + body: + row: { id: 1, title: "Laptop" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/invalid-transition.yaml b/fixtures/api-contract-conformance/rules/scenarios/invalid-transition.yaml new file mode 100644 index 0000000000..bfe74fe241 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/invalid-transition.yaml @@ -0,0 +1,19 @@ +name: invalid-transition +description: > + A move whose `@from` does not hold the row's state is answered 409 `invalid_transition`, after + the permission point: request 2 is already `submitted`, so `submit` is refused and nothing is + written (no audit entry). +requests: + - id: r1 + method: POST + path: /api/purchase_requests/2/submit + headers: { x-actor: "ann", x-grants: "acme::purchasing.PurchaseRequest.submit" } + expect: + status: 409 + body: { error: "invalid_transition" } + - id: r2 + method: GET + path: /api/audit_entries + expect: + status: 200 + body: { length: 0 } diff --git a/fixtures/api-contract-conformance/rules/scenarios/public-command-needs-no-actor.yaml b/fixtures/api-contract-conformance/rules/scenarios/public-command-needs-no-actor.yaml new file mode 100644 index 0000000000..6d21e2f252 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/public-command-needs-no-actor.yaml @@ -0,0 +1,18 @@ +name: public-command-needs-no-actor +description: > + A `@public` transition skips the policy: with no actor at all, `cancel` moves the submitted + request 2 to `cancelled`. Its `@from` lists two states, and a third is still refused. +requests: + - id: r1 + method: POST + path: /api/purchase_requests/2/cancel + expect: + status: 200 + body: + row: { id: 2, status: "cancelled" } + - id: r2 + method: POST + path: /api/purchase_requests/5/cancel + expect: + status: 409 + body: { error: "invalid_transition" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/public-query.yaml b/fixtures/api-contract-conformance/rules/scenarios/public-query.yaml new file mode 100644 index 0000000000..4036854fdd --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/public-query.yaml @@ -0,0 +1,12 @@ +name: public-query +description: > + A declared `@public` query answers its body's output with no actor, in the read scope. The + README's `requestTotals` body counts the requests and sums their amounts. +requests: + - id: r1 + method: GET + path: /api/purchase_requests/requestTotals + expect: + status: 200 + body: + equals: { count: 5, totalCents: 1105000 } diff --git a/fixtures/api-contract-conformance/rules/scenarios/state-managed-update.yaml b/fixtures/api-contract-conformance/rules/scenarios/state-managed-update.yaml new file mode 100644 index 0000000000..2a90fbed29 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/state-managed-update.yaml @@ -0,0 +1,21 @@ +name: state-managed-update +description: > + A lifecycle field is moved only by a transition. The generic update naming a different state is + 409 `state_managed` and writes nothing; naming the state the row already has is not a move, and + the rest of the update is written. +requests: + - id: r1 + method: PATCH + path: /api/purchase_requests/1 + body: { status: "approved", title: "Laptop Pro" } + expect: + status: 409 + body: { error: "state_managed" } + - id: r2 + method: PATCH + path: /api/purchase_requests/1 + body: { status: "draft", title: "Laptop Pro" } + expect: + status: 200 + body: + row: { id: 1, title: "Laptop Pro", status: "draft" } diff --git a/fixtures/api-contract-conformance/rules/scenarios/transition-condition-failed.yaml b/fixtures/api-contract-conformance/rules/scenarios/transition-condition-failed.yaml new file mode 100644 index 0000000000..0d6cf2da08 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/scenarios/transition-condition-failed.yaml @@ -0,0 +1,21 @@ +name: transition-condition-failed +description: > + The guarded update carries the transition's `@condition`. Request 3's amount (900000) is over + its limit (100000), so `approve` matches no row: the row is still in `@from`, so the answer is + 409 `transition_condition_failed`, and the row keeps its state. +requests: + - id: r1 + method: PUT + path: /api/purchase-requests/3/decision + headers: { x-actor: "rita", x-grants: "purchasing.decide" } + body: { approve: true } + expect: + status: 409 + body: { error: "transition_condition_failed" } + - id: r2 + method: GET + path: /api/purchase_requests/3 + expect: + status: 200 + body: + row: { id: 3, status: "submitted" } diff --git a/fixtures/api-contract-conformance/rules/seed.json b/fixtures/api-contract-conformance/rules/seed.json new file mode 100644 index 0000000000..4c03859fe1 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/seed.json @@ -0,0 +1,9 @@ +{ + "purchaseRequests": [ + { "id": 1, "title": "Laptop", "amountCents": 120000, "limitCents": 200000, "status": "draft" }, + { "id": 2, "title": "Desk", "amountCents": 30000, "limitCents": 50000, "status": "submitted" }, + { "id": 3, "title": "Server", "amountCents": 900000, "limitCents": 100000, "status": "submitted" }, + { "id": 4, "title": "Chair", "amountCents": 15000, "limitCents": null, "status": "rejected" }, + { "id": 5, "title": "Monitor", "amountCents": 40000, "limitCents": 50000, "status": "approved" } + ] +} diff --git a/fixtures/api-contract-conformance/rules/settings/commands-all/.metaobjects/config.json b/fixtures/api-contract-conformance/rules/settings/commands-all/.metaobjects/config.json new file mode 100644 index 0000000000..e7f4f4dd68 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/settings/commands-all/.metaobjects/config.json @@ -0,0 +1,8 @@ +{ + "schema_version": 1, + "rules": { + "lifecycle": { + "commands": "all" + } + } +} diff --git a/fixtures/api-contract-conformance/rules/settings/commands-all/scenarios/claimed-transition-has-a-command.yaml b/fixtures/api-contract-conformance/rules/settings/commands-all/scenarios/claimed-transition-has-a-command.yaml new file mode 100644 index 0000000000..10203e493e --- /dev/null +++ b/fixtures/api-contract-conformance/rules/settings/commands-all/scenarios/claimed-transition-has-a-command.yaml @@ -0,0 +1,21 @@ +name: claimed-transition-has-a-command +description: > + Under `rules.lifecycle.commands: all`, every transition derives a command, the ones a declared + command claims included: `approve` is reachable at `POST /purchase_requests/{id}/approve`, with + its derived permission and its `@condition`, as well as through `decide`. +requests: + - id: r1 + method: POST + path: /api/purchase_requests/2/approve + headers: { x-actor: "rita", x-grants: "acme::purchasing.PurchaseRequest.approve" } + expect: + status: 200 + body: + row: { id: 2, status: "approved" } + - id: r2 + method: POST + path: /api/purchase_requests/3/approve + headers: { x-actor: "rita", x-grants: "acme::purchasing.PurchaseRequest.approve" } + expect: + status: 409 + body: { error: "transition_condition_failed" } diff --git a/fixtures/api-contract-conformance/rules/settings/commands-none/.metaobjects/config.json b/fixtures/api-contract-conformance/rules/settings/commands-none/.metaobjects/config.json new file mode 100644 index 0000000000..680fd5829d --- /dev/null +++ b/fixtures/api-contract-conformance/rules/settings/commands-none/.metaobjects/config.json @@ -0,0 +1,8 @@ +{ + "schema_version": 1, + "rules": { + "lifecycle": { + "commands": "none" + } + } +} diff --git a/fixtures/api-contract-conformance/rules/settings/commands-none/scenarios/no-derived-commands.yaml b/fixtures/api-contract-conformance/rules/settings/commands-none/scenarios/no-derived-commands.yaml new file mode 100644 index 0000000000..b8d9ad9c06 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/settings/commands-none/scenarios/no-derived-commands.yaml @@ -0,0 +1,20 @@ +name: no-derived-commands +description: > + Under `rules.lifecycle.commands: none`, no transition derives a command: `submit` has no route. + A declared command still makes the moves it lists. +requests: + - id: r1 + method: POST + path: /api/purchase_requests/1/submit + headers: { x-actor: "ann", x-grants: "acme::purchasing.PurchaseRequest.submit" } + expect: + status: 404 + - id: r2 + method: PUT + path: /api/purchase-requests/2/decision + headers: { x-actor: "rita", x-grants: "purchasing.decide" } + body: { approve: true } + expect: + status: 200 + body: + row: { id: 2, status: "approved" } diff --git a/fixtures/api-contract-conformance/rules/settings/create-any/.metaobjects/config.json b/fixtures/api-contract-conformance/rules/settings/create-any/.metaobjects/config.json new file mode 100644 index 0000000000..98d499010f --- /dev/null +++ b/fixtures/api-contract-conformance/rules/settings/create-any/.metaobjects/config.json @@ -0,0 +1,8 @@ +{ + "schema_version": 1, + "rules": { + "lifecycle": { + "create": "any" + } + } +} diff --git a/fixtures/api-contract-conformance/rules/settings/create-any/scenarios/create-in-any-state.yaml b/fixtures/api-contract-conformance/rules/settings/create-any/scenarios/create-in-any-state.yaml new file mode 100644 index 0000000000..6146fef031 --- /dev/null +++ b/fixtures/api-contract-conformance/rules/settings/create-any/scenarios/create-in-any-state.yaml @@ -0,0 +1,21 @@ +name: create-in-any-state +description: > + Under `rules.lifecycle.create: any`, a create may name any state of the lifecycle: the row is + written `approved`. Omitted, the state is the column's default, the enum's `@default`. +requests: + - id: r1 + method: POST + path: /api/purchase_requests + body: { title: "Phone", amountCents: 50000, status: "approved" } + expect: + status: 201 + body: + row: { id: 6, title: "Phone", status: "approved" } + - id: r2 + method: POST + path: /api/purchase_requests + body: { title: "Tablet", amountCents: 20000 } + expect: + status: 201 + body: + row: { id: 7, status: "draft" } diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md index 7cd246688e..f7d6e8bca8 100644 --- a/fixtures/codegen-noop/rules/README.md +++ b/fixtures/codegen-noop/rules/README.md @@ -26,6 +26,12 @@ writes for `without/`. Today those are TypeScript's `rules-names`, which writes `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. +The service generators (ADR-0067 layers 4 and 5) are the enforcing shells, so they also CHANGE +files they write for `without/`: TypeScript's `service` adds a file per derived transition command +and per declared operation and changes the package index (its policy, bodies and interfaces) and +the lifecycle entity's create and update (which check its state), and `service-routes` changes the +transport (the new routes). The test pins both lists, and every other file stays byte-identical. + 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/server/typescript/packages/cli/test/unit/rules-inert.test.ts b/server/typescript/packages/cli/test/unit/rules-inert.test.ts index aa2d6f200b..7ea2388406 100644 --- a/server/typescript/packages/cli/test/unit/rules-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/rules-inert.test.ts @@ -101,6 +101,30 @@ const RULES_LAYER: Record = { ], }; +/** + * The ADR-0067 service generators: the enforcing shells, so the vocabulary is what they act on. + * Each pins the files the vocabulary ADDS (a command per derived transition, a shell per declared + * operation) and the files it CHANGES (the index's interfaces, the lifecycle entity's create and + * update, which check its state, and the transport's routes); every other file stays byte-identical. + */ +const SERVICE_LAYER: Record = { + service: { + // `approve` and `reject` are claimed by `decide`, so only `submit` derives a command. + added: [ + "src/generated/acme/purchasing/service/decide.ts", + "src/generated/acme/purchasing/service/openRequests.ts", + "src/generated/acme/purchasing/service/requestSummary.ts", + "src/generated/acme/purchasing/service/submitPurchaseRequest.ts", + ], + changed: [ + "src/generated/acme/purchasing/service/createPurchaseRequest.ts", + "src/generated/acme/purchasing/service/index.ts", + "src/generated/acme/purchasing/service/updatePurchaseRequest.ts", + ], + }, + "service-routes": { added: [], changed: ["src/generated/acme/purchasing/transport/fastify.ts"] }, +}; + let withRules: MetaRoot; let withoutRules: MetaRoot; @@ -119,7 +143,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 || name in RULES_LAYER) continue; + if (name === DOCS_SITE || name in RULES_LAYER || name in SERVICE_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()]); @@ -138,6 +162,17 @@ describe("ADR-0066 the business-rules vocabulary is inert in every generator and }); } + for (const [name, { added, changed }] of Object.entries(SERVICE_LAYER)) { + test(`service generator "${name}" adds and changes exactly the files the vocabulary reaches`, async () => { + const expected = await emit(withoutRules, [catalog[name]!.factory()]); + const actual = await emit(withRules, [catalog[name]!.factory()]); + expect(expected[""]).toBeUndefined(); + expect(Object.keys(expected).filter((p) => !(p in actual))).toEqual([]); + expect(Object.keys(actual).filter((p) => !(p in expected)).sort()).toEqual(added); + expect(Object.keys(expected).filter((p) => actual[p] !== expected[p]).sort()).toEqual(changed); + }); + } + 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()]); @@ -170,11 +205,17 @@ 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. A value module + // The rules layers add their own files beside the rest, and move none of them; the service + // layers add and change exactly the files their own tests pin. 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)); + const added = [...Object.values(RULES_LAYER).flat(), ...Object.values(SERVICE_LAYER).flatMap((l) => l.added)].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]; + // The service generators' changed files are pinned by their own tests above. + for (const p of Object.values(SERVICE_LAYER).flatMap((l) => l.changed)) { + delete actual[p]; + delete expected[p]; + } expect(actual).toEqual(expected); }); diff --git a/server/typescript/packages/codegen-ts/src/generators/service-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-file.ts index e11825e9d7..a81e1b8a87 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-file.ts @@ -7,7 +7,10 @@ import { renderServiceFiles } from "../templates/service-file.js"; * The service layer (ADR-0067 §1, layer 4): one module per metadata package, one file per * operation, and `createService(deps)`. Each covered entity gets its derived list, get, * create, update and delete; every write runs in one transaction with the declared write rules - * (ADR-0045). Hand-written code calls the service; a transport (`serviceRoutesFile()`) mounts it. + * (ADR-0045). Each transition that derives a command (`rules.lifecycle.commands`) and each declared + * command and query gets its shell, which runs ADR-0066 §6's checks around the hand-written body. + * The policy, bodies, hooks and event hook are passed in `deps`, through the interfaces the index + * declares. Hand-written code calls the service; a transport (`serviceRoutesFile()`) mounts it. * * SQLite needs an async Drizzle driver (libsql): the emitted `Db` type is `BaseSQLiteDatabase<"async", …>`, * so a sync driver (better-sqlite3, bun:sqlite) fails to type-check instead of failing at run time. diff --git a/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts index f04944688a..780bc6f402 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-routes-file.ts @@ -7,7 +7,8 @@ import { renderFastifyTransport } from "../templates/service-file.js"; * The thin Fastify transport of the service layer (ADR-0067 §1, layer 5): one file per metadata * package, `/transport/fastify.ts`, whose routes parse a request, call the package's * service and send what it answered. It holds no rules, and it imports the service module and - * the contract types only. The built-in twin of `src/reference/service-routes.ts`. + * the contract types only. Its `getActor(request)` option resolves who a request is for; two + * routes on one method and path are refused when it is generated. The built-in twin of `src/reference/service-routes.ts`. */ export interface ServiceRoutesFileOpts { /** Narrow which entities get routes. Keep it the same as the service generator's. */ diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 3cd73e5b53..4ff7a087ac 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -6,13 +6,48 @@ // adopter's. // // Covered: every concrete `object.entity` whose primary source is a writable `source.rdb`, keyed -// by a single-field primary identity. It gets the five derived operations: list, get, create, -// update and delete. Not covered yet: a write-through entity (reads through a replica view), a -// single-table (TPH) hierarchy, many-to-many traversal, projections and reports, and the -// transition commands and declared operations of ADR-0066 (later service work, which adds the -// policy, bodies and events interfaces). +// by a single-field primary identity. It gets the five derived operations (list, get, create, +// update and delete), a command per transition that derives one (ADR-0066 §2, under +// `rules.lifecycle.commands`), and the package's declared operations that act on a covered entity +// or on none. Not covered yet: a write-through entity (reads through a replica view), a +// single-table (TPH) hierarchy, many-to-many traversal, projections and reports. -import { IDENTITY_ATTR_FIELDS, isMetaObject, OBJECT_SUBTYPE_ENTITY, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import { + BINDING_ATTR_METHOD, + BINDING_ATTR_PATH, + IDENTITY_ATTR_FIELDS, + OBJECT_SUBTYPE_ENTITY, + OPERATION_ATTR_ERRORS, + OPERATION_ATTR_INPUT_REF, + OPERATION_ATTR_MANY, + OPERATION_ATTR_OUTPUT_REF, + OPERATION_ATTR_TRANSITIONS, + OPERATION_SUBTYPE_COMMAND, + TRANSITION_ATTR_CONDITION, + TYPE_BINDING, + TYPE_FIELD, + claimedTransitions, + commandPermission, + derivedCommandsOf, + effectivePackageOf, + entityLineage, + isMetaObject, + lifecyclesOf, + modelOperations, + needsPermissionName, + operationIsKeyed, + operationPermission, + operationTarget, + refTarget, + rulesSettingsOfModel, + topLevelNodeOf, + transitionFrom, + transitionTo, + type MetaData, + type MetaObject, + type RulesSettings, +} from "@metaobjectsdev/metadata"; +import { restPath } from "./templates/entity-ui-descriptor.js"; import { packageToPath } from "./import-path.js"; import { posix } from "node:path"; import { contractSpecifier } from "./contract-walk.js"; @@ -37,6 +72,32 @@ export const SERVICE_INDEX_FILE = "index.ts"; export const DERIVED_OPERATIONS = ["list", "get", "create", "update", "delete"] as const; export type DerivedOperation = (typeof DERIVED_OPERATIONS)[number]; +/** One move of a lifecycle (ADR-0066 §2), as the guarded update makes it. */ +export interface ServiceTransition { + readonly name: string; + /** The lifecycle's field. */ + readonly field: string; + readonly from: readonly string[]; + readonly to: string; + /** The `@condition` node (attr.expression), when the move has one. */ + readonly condition: unknown; +} + +/** One lifecycle of an entity: its field and its initial state (the enum's `@default`). */ +export interface ServiceLifecycle { + readonly field: string; + readonly initial: string | undefined; +} + +/** The command a transition derives on an entity (ADR-0066 §2): it takes the key and makes the move. */ +export interface ServiceTransitionCommand { + /** The service function: `` (`submitPurchaseRequest`). */ + readonly fn: string; + readonly transition: ServiceTransition; + /** The permission it asks the policy about; undefined when the transition is `@public`. */ + readonly permission: string | undefined; +} + /** One entity's service operations. */ export interface ServiceEntity { readonly obj: MetaObject; @@ -44,12 +105,50 @@ export interface ServiceEntity { readonly keyField: string; /** The function name of each derived operation (`listAuthors`, `getAuthor`, ...). */ readonly operations: Readonly>; + /** The entity's lifecycles: the generic write path may not move them (409 `state_managed`). */ + readonly lifecycles: readonly ServiceLifecycle[]; + /** The commands its transitions derive, in lifecycle order. */ + readonly commands: readonly ServiceTransitionCommand[]; +} + +/** A declared `operation.command` or `operation.query` (ADR-0066 §1). */ +export interface ServiceOperation { + /** The operation's name, which is its service function's. */ + readonly name: string; + readonly kind: "command" | "query"; + /** The covered entity it acts on, when it has one. */ + readonly target: ServiceEntity | undefined; + /** Whether it addresses one row of the target by key (ADR-0066 §3). */ + readonly keyed: boolean; + /** The `@inputRef` value object. */ + readonly input: MetaObject | undefined; + /** The input's field that borrows the target's key, when the operation is keyed by its input. */ + readonly inputKeyField: string | undefined; + /** The `@outputRef` object. */ + readonly output: MetaObject | undefined; + readonly many: boolean; + /** The moves a command may make (`@transitions`), resolved on the target. */ + readonly transitions: readonly ServiceTransition[]; + /** The business errors a command's body may return (`@errors`). */ + readonly errors: readonly string[]; + /** The permission it asks the policy about; undefined when it is `@public`. */ + readonly permission: string | undefined; + /** The REST method: `binding.rest @method`, else GET for a query and POST for a command. */ + readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; + /** The REST path in the Fastify form (`/purchase-requests/:id/decision`), before the API prefix. */ + readonly path: string; } /** One metadata package's service module. */ export interface ServicePackage { readonly package: string; readonly entities: readonly ServiceEntity[]; + /** The package's declared operations a service covers, in model order, once each. */ + readonly operations: readonly ServiceOperation[]; + /** Every permission a point of the package asks about, sorted, once each. */ + readonly permissions: readonly string[]; + /** The settings the model was loaded with (`rules.lifecycle.create` decides a create's states). */ + readonly settings: RulesSettings; } export interface ServiceWalkOpts { @@ -85,18 +184,129 @@ export function serviceOperationNames(obj: MetaObject): Readonly typeof x === "string") : typeof v === "string" ? [v] : []; +} + +/** A point that asks about a derived name is refused under `rules.permissions.names: require`. */ +function requireDeclared(settings: RulesSettings, node: MetaData, what: string, derived: string | undefined): void { + if (settings.permissionNames === "require" && needsPermissionName(node)) { + throw new Error( + `service: ${what} declares no @permission and is not @public, and rules.permissions.names is "require"; declare its permission (it would derive "${derived}")`, + ); + } +} + +function entityRules(obj: MetaObject, claimed: ReturnType, settings: RulesSettings) { + const lifecycles = lifecyclesOf(obj); + const fieldOf = new Map(); + for (const l of lifecycles) for (const t of l.transitions) fieldOf.set(t, l.field.name); + const commands = derivedCommandsOf(obj, claimed, settings).map((t) => { + requireDeclared(settings, t, `transition ${obj.name}.${fieldOf.get(t)}.${t.name}`, commandPermission(obj, t)); + return { + fn: `${toCamelCase(t.name)}${obj.name}`, + transition: transitionOf(t, fieldOf.get(t) ?? ""), + permission: commandPermission(obj, t), + }; + }); + return { lifecycles: lifecycles.map((l) => ({ field: l.field.name, initial: l.initial })), commands }; +} + +/** The input field that extends one of `target`'s key fields (the borrowed key, ADR-0066 §3). */ +function borrowedKeyField(input: MetaObject, target: MetaObject, keyField: string): string | undefined { + const lineage = entityLineage(target); + for (const f of input.children()) { + if (f.type !== TYPE_FIELD) continue; + const sup = f.superResolved; + if (sup?.name === keyField && sup.parent !== undefined && lineage.includes(sup.parent)) return f.name; + } + return undefined; +} + +function asObject(node: MetaData | undefined): MetaObject | undefined { + return node !== undefined && isMetaObject(node) ? node : undefined; +} + +function operationOf(op: MetaData, target: ServiceEntity | undefined, settings: RulesSettings): ServiceOperation { + const kind = op.subType === OPERATION_SUBTYPE_COMMAND ? "command" : "query"; + requireDeclared(settings, op, `operation ${op.name}`, operationPermission(op)); + const input = asObject(refTarget(op, OPERATION_ATTR_INPUT_REF)); + const keyed = target !== undefined && operationIsKeyed(op); + const lifecycles = target === undefined ? [] : lifecyclesOf(target.obj); + const names = new Set(kind === "command" ? stringsOf(op, OPERATION_ATTR_TRANSITIONS) : []); + const transitions = lifecycles.flatMap((l) => l.transitions.filter((t) => names.has(t.name)).map((t) => transitionOf(t, l.field.name))); + const binding = op.children().find((c) => c.type === TYPE_BINDING); + const declaredMethod = binding?.attr(BINDING_ATTR_METHOD); + const declaredPath = binding?.attr(BINDING_ATTR_PATH); + const method = (typeof declaredMethod === "string" ? declaredMethod : kind === "query" ? "GET" : "POST") as ServiceOperation["method"]; + const base = target === undefined ? "" : restPath(target.obj); + const path = typeof declaredPath === "string" + ? declaredPath.replace(/\{([^}]*)\}/g, ":$1") + : keyed ? `${base}/:${target!.keyField}/${op.name}` : `${base}/${op.name}`; + return { + name: op.name, + kind, + target, + keyed, + input, + inputKeyField: keyed && input !== undefined ? borrowedKeyField(input, target!.obj, target!.keyField) : undefined, + output: asObject(refTarget(op, OPERATION_ATTR_OUTPUT_REF)), + many: op.attr(OPERATION_ATTR_MANY) === true, + transitions, + errors: kind === "command" ? stringsOf(op, OPERATION_ATTR_ERRORS) : [], + permission: operationPermission(op), + method, + path, + }; +} + +/** + * The service modules of `root`, one per package that has a covered entity or a declared + * operation the service covers, sorted by package. + */ export function serviceModelOf(root: MetaData, opts: ServiceWalkOpts = {}): ServicePackage[] { const matches = opts.matches ?? (() => true); - const packages = new Map(); + const settings = rulesSettingsOfModel(root); + const claimed = claimedTransitions(root); + const packages = new Map(); + const bucket = (pkg: string) => { + let b = packages.get(pkg); + if (b === undefined) { b = { entities: [], operations: [] }; packages.set(pkg, b); } + return b; + }; + const covered = new Map(); for (const obj of root.children().filter(isMetaObject)) { if (!hasServiceOperations(obj) || !matches(obj)) continue; - const pkg = effectivePackage(obj) ?? ""; - const list = packages.get(pkg) ?? []; - packages.set(pkg, list); - list.push({ obj, keyField: serviceKeyField(obj)!, operations: serviceOperationNames(obj) }); + const e: ServiceEntity = { obj, keyField: serviceKeyField(obj)!, operations: serviceOperationNames(obj), ...entityRules(obj, claimed, settings) }; + covered.set(obj, e); + bucket(effectivePackage(obj) ?? "").entities.push(e); + } + // One operation declared identically by two APIs (a versioned API) is one operation (O6). An + // operation whose target the service does not cover (a single-table hierarchy, say) is left to + // later service work, as its entity is. + const seen = new Set(); + for (const op of modelOperations(root)) { + const targetNode = operationTarget(op); + const target = targetNode === undefined ? undefined : covered.get(targetNode); + if (targetNode !== undefined && target === undefined) continue; + const pkg = effectivePackageOf(topLevelNodeOf(op)); + const id = `${pkg}\u0000${op.name.toLowerCase()}`; + if (seen.has(id)) continue; + seen.add(id); + bucket(pkg).operations.push(operationOf(op, target, settings)); } - return [...packages.keys()].sort().map((pkg) => ({ package: pkg, entities: packages.get(pkg)! })); + return [...packages.keys()].sort().map((pkg) => { + const { entities, operations } = packages.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); + return { package: pkg, entities, operations, permissions: [...permissions].sort(), settings }; + }); } /** Where a file of package `pkg`'s service module goes, relative to the target's outDir. */ diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts index c277c0b8f2..d8898f4421 100644 --- a/server/typescript/packages/codegen-ts/src/templates/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -5,20 +5,25 @@ // // /service/.ts — one exported function: `(deps, ...args, opts) => OpResult` // /service/index.ts — `ServiceDeps`, the `Service` interface, `createService`, -// and each entity's wire mapper -// /transport/fastify.ts — the routes: parse, call the service, send what it answered +// the policy, bodies, hooks and events interfaces hand-written +// code implements, and each entity's wire mapper +// /transport/fastify.ts — the routes: parse, resolve the actor, call the service, send // // Every write operation runs in one transaction (a savepoint inside a caller's), in ADR-0067 §4's -// order: load the row under a row lock, validate and stamp the input (ADR-0045), write. A refusal -// rolls it back. Reads open no write transaction. The mechanics are `@metaobjectsdev/runtime-ts/service`; -// what runs, against which schema and table, is written here. +// order: load the row under a row lock, the before hook, validate and stamp the input (ADR-0045), +// the write (or the body, then the guarded update), the after hook, the event hook. A transition or +// a declared command checks in ADR-0066 §6's order: the row (404), the permission point (403), the +// state (409 `invalid_transition`), the body, the guarded update. A refusal anywhere rolls it all +// back. Reads open no write transaction and call no hooks. The mechanics are +// `@metaobjectsdev/runtime-ts/service`; what runs, against which schema and table, is written here. import type { MetaObject } from "@metaobjectsdev/metadata"; import { GENERATED_EDIT_NOTE, GENERATED_HEADER } from "../constants.js"; import { withExtIfRelative, type RenderContext } from "../render-context.js"; import { decimalColumnsLine, knownFieldsLine, paginationLine, restPath, writeDeniedColumnsLine } from "../api-surface.js"; import { dbTypeBlock } from "../dialect-module.js"; -import { contractObjectPath, contractSpecifier } from "../contract-walk.js"; +import { contractObjectPath, contractOperationsPath, contractSpecifier } from "../contract-walk.js"; +import { toPascalCase } from "../naming.js"; import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; import { @@ -30,7 +35,10 @@ import { serviceRoutesName, SERVICE_INDEX_FILE, type ServiceEntity, + type ServiceOperation, type ServicePackage, + type ServiceTransition, + type ServiceTransitionCommand, } from "../service-walk.js"; import { TsWriter, str } from "../writer/ts-writer.js"; @@ -87,8 +95,16 @@ export function renderServiceFiles(pkg: ServicePackage, ctx: RenderContext): Ser for (const e of pkg.entities) { for (const op of ["list", "get", "create", "update", "delete"] as const) { const path = servicePath(pkg.package, `${e.operations[op]}.ts`); - files.push({ path, content: renderOperation(op, e, path, ctx) }); + files.push({ path, content: renderOperation(op, e, path, ctx, pkg) }); } + for (const c of e.commands) { + const path = servicePath(pkg.package, `${c.fn}.ts`); + files.push({ path, content: renderTransitionCommand(c, e, path, ctx, pkg) }); + } + } + for (const op of pkg.operations) { + const path = servicePath(pkg.package, `${op.name}.ts`); + files.push({ path, content: renderDeclaredOperation(op, path, ctx, pkg) }); } const index = servicePath(pkg.package, SERVICE_INDEX_FILE); files.push({ path: index, content: renderServiceIndex(pkg, index, ctx) }); @@ -100,6 +116,7 @@ function renderOperation( e: ServiceEntity, path: string, ctx: RenderContext, + pkg: ServicePackage, ): string { const obj = e.obj; const name = obj.name; @@ -110,10 +127,11 @@ function renderOperation( const mods = modulesOf(path, obj, ctx); const table = w.use(ctx.collectionName(name), mods.entity); const row = w.useType(name, mods.contract); - const deps = w.useType("ServiceDeps", withExtIfRelative(`./${SERVICE_INDEX_FILE.replace(/\.ts$/, "")}`, ctx.extStyle)); - const opOptions = w.useType("OpOptions", runtime); + const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; + const opOptions = `${w.useType("OpOptions", runtime)}`; const opResult = w.useType("OpResult", runtime); const dialect = str(ctx.dialect); + const lifecycleFields = e.lifecycles.map((l) => l.field); const keyField = str(e.keyField); const id = "id: number | string"; @@ -129,7 +147,7 @@ function renderOperation( "query string parses to), checked against the allowlists; ordered by the key when it names no sort.", ); w.block( - `export async function ${fn}(deps: ${deps}, query: ${query} = {}, opts: ${opOptions} = {}): Promise<${opResult}<${listPage}<${row}>>> {`, + `export async function ${fn}(deps: ${deps}, query: ${query} = {}, opts: ${opOptions} = {}): Promise<${opResult}<${listPage}<${row}>>> {`, () => { w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { objectLiteral( @@ -151,7 +169,7 @@ function renderOperation( const keyCondition = w.use("keyCondition", runtime); const notFound = w.use("notFound", runtime); w.doc(`The ${name} row \`id\` names: \`not_found\` when there is none, \`invalid_id\` when \`id\` is no key.`); - w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { + w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { w.line(`const row = await ${readOne}(db, ${table}, ${keyCondition}(${table}, ${keyField}, id));`); w.line(`if (row === undefined) ${notFound}();`); @@ -173,13 +191,30 @@ function renderOperation( const schema = w.use(`${name}InsertSchema`, mods.contract); const input = w.useType(`${name}Create`, mods.contract); w.doc( - `Create a ${name}. In one transaction: validate the input and stamp what the model declares`, - "(ADR-0045), then insert it and answer the written row.", + `Create a ${name}. In one transaction: the before hook (it may replace the input or refuse),`, + "validate the input and stamp what the model declares (ADR-0045), insert it, the after hook", + "and the event hook; answer the written row.", ); - w.block(`export async function ${fn}(deps: ${deps}, input: ${input}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { + w.block(`export async function ${fn}(deps: ${deps}, input: ${input}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { - w.line(`const values = ${validateBody}(${schema}, input, writeRules);`); - w.line(`return (await ${insertRow}(tx, ${table}, values, ${dialect}, ${keyField})) as ${row};`); + w.line(`const ctx = ${w.use("handlerContext", runtime)}(tx, opts.actor);`); + w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(input, ctx)) ?? input;`); + w.line(`const values: Record = ${validateBody}(${schema}, given, writeRules);`); + if (e.lifecycles.length > 0) { + if (pkg.settings.lifecycleCreate === "initial") { + const initials = e.lifecycles.map((l) => `${l.field}: ${str(l.initial ?? "")}`).join(", "); + w.line(`// rules.lifecycle.create: "initial" — a create starts each lifecycle in its initial state.`); + w.line(`${w.use("checkCreateState", runtime)}(values, { ${initials} });`); + } else { + w.line(`// rules.lifecycle.create: "any" — a create may start a lifecycle in any of its states.`); + } + } + w.line(`const row = (await ${insertRow}(tx, ${table}, values, ${dialect}, ${keyField})) as ${row};`); + w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, ctx);`); + w.line( + `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "create", entity: ${str(name)}, key: row.${e.keyField}, row, actor: opts.actor, at: new Date() }, tx);`, + ); + w.line("return row;"); }, "});"); }); return w.toString(); @@ -192,21 +227,32 @@ function renderOperation( const patch = w.useType(`${name}Patch`, mods.contract); w.doc( `Update the ${name} row \`id\` names with \`patch\`. In one transaction: load the row under a row`, - "lock (`not_found` when there is none), validate the patch and stamp what the model declares", - "(ADR-0045), then write it and answer the written row. A patch with nothing to write answers the row.", + "lock (`not_found` when there is none), the before hook, validate the patch and stamp what the", + "model declares (ADR-0045), write it, the after hook and the event hook; answer the written row.", + "A patch with nothing to write answers the row and calls no after or event hook.", ); w.block( - `export async function ${fn}(deps: ${deps}, ${id}, patch: ${patch}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, + `export async function ${fn}(deps: ${deps}, ${id}, patch: ${patch}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); - w.line(`const current = await ${loadForWrite}(tx, ${table}, cond, ${dialect});`); + w.line(`const current = (await ${loadForWrite}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${notFound}();`); - w.line(`const data: Record = ${validateBody}(${schema}, patch, writeRules);`); - w.line(`if (Object.keys(data).length === 0) return current as ${row};`); - w.line(`const row = await ${updateRow}(tx, ${table}, data, cond, ${dialect});`); + w.line(`const ctx = ${w.use("handlerContext", runtime)}(tx, opts.actor);`); + w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(patch, current, ctx)) ?? patch;`); + w.line(`const data: Record = ${validateBody}(${schema}, given, writeRules);`); + if (lifecycleFields.length > 0) { + w.line("// A lifecycle moves only through its transitions (ADR-0066 §6 step 7)."); + w.line(`${w.use("checkStateManaged", runtime)}(data, current, ${JSON.stringify(lifecycleFields)});`); + } + w.line("if (Object.keys(data).length === 0) return current;"); + w.line(`const row = (await ${updateRow}(tx, ${table}, data, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (row === undefined) ${notFound}();`); - w.line(`return row as ${row};`); + w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, current, ctx);`); + w.line( + `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "update", entity: ${str(name)}, key: row.${e.keyField}, row, previous: current, actor: opts.actor, at: new Date() }, tx);`, + ); + w.line("return row;"); }, "});"); }, ); @@ -219,13 +265,231 @@ function renderOperation( const notFound = w.use("notFound", runtime); w.doc( `Delete the ${name} row \`id\` names. In one transaction: load it under a row lock (\`not_found\``, - "when there is none), then delete it.", + "when there is none), the before hook, the delete, the after hook and the event hook.", ); - w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}> {`, () => { + w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); - w.line(`if ((await ${loadForWrite}(tx, ${table}, cond, ${dialect})) === undefined) ${notFound}();`); + w.line(`const current = (await ${loadForWrite}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); + w.line(`if (current === undefined) ${notFound}();`); + w.line(`const ctx = ${w.use("handlerContext", runtime)}(tx, opts.actor);`); + w.line(`await deps.hooks?.before${toPascalCase(fn)}?.(current, ctx);`); w.line(`await ${deleteRows}(tx, ${table}, cond);`); + w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(current, ctx);`); + w.line( + `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "delete", entity: ${str(name)}, key: current.${e.keyField}, row: current, actor: opts.actor, at: new Date() }, tx);`, + ); + }, "});"); + }); + return w.toString(); +} + +/** The specifier of the package's service index, from a file in the same folder. */ +function indexSpecifier(ctx: RenderContext): string { + return withExtIfRelative(`./${SERVICE_INDEX_FILE.replace(/\.ts$/, "")}`, ctx.extStyle); +} + +/** The specifier of the package's operations contract (`operations.contract.ts`), from `path`. */ +function operationsSpecifier(path: string, pkg: ServicePackage, ctx: RenderContext): string { + return contractSpecifier(path, contractOperationsPath(pkg.package), ctx.extStyle); +} + +/** The move as the runtime's `TransitionSpec` literal. */ +function transitionLiteral(t: ServiceTransition): string { + const condition = t.condition === undefined ? "" : `, condition: ${JSON.stringify(t.condition)}`; + return `{ name: ${str(t.name)}, field: ${str(t.field)}, from: ${JSON.stringify(t.from)}, to: ${str(t.to)}${condition} }`; +} + +/** The type of a declared operation's input after validation: the contract's input schema's output. */ +function inputType(w: TsWriter, op: ServiceOperation, path: string, pkg: ServicePackage, ctx: RenderContext): string { + const z = w.useType("z", "zod"); + const schema = w.useType(`${toPascalCase(op.name)}InputSchema`, operationsSpecifier(path, pkg, ctx)); + return `${z}.output`; +} + +/** The type a caller passes as a declared operation's input: the contract's, less a key the path carries. */ +function callerInputType(w: TsWriter, op: ServiceOperation, path: string, pkg: ServicePackage, ctx: RenderContext): string { + const t = w.useType(`${toPascalCase(op.name)}Input`, operationsSpecifier(path, pkg, ctx)); + return op.inputKeyField === undefined ? t : `Omit<${t}, ${str(op.inputKeyField)}>`; +} + +/** What a declared operation answers: the target's row, the declared output, or nothing. */ +function outputType(w: TsWriter, op: ServiceOperation, path: string, pkg: ServicePackage, ctx: RenderContext): string { + if (outputIsTargetRow(op)) return w.useType(op.target!.obj.name, modulesOf(path, op.target!.obj, ctx).contract); + if (op.output !== undefined) return w.useType(`${toPascalCase(op.name)}Output`, operationsSpecifier(path, pkg, ctx)); + return op.kind === "query" ? "unknown" : "void"; +} + +/** A command whose `@outputRef` is its target answers the target's row as the command left it. */ +function outputIsTargetRow(op: ServiceOperation): boolean { + return op.kind === "command" && op.target !== undefined && op.output === op.target.obj; +} + +/** What a declared operation's body returns (ADR-0066 §6 step 4). */ +function outcomeType(op: ServiceOperation, output: string): string { + const moves = op.transitions.length === 0 ? undefined : [...op.transitions.map((t) => str(t.name)), str("none")].join(" | "); + const bodyOutput = op.kind === "query" || (op.output !== undefined && !outputIsTargetRow(op)) ? output : undefined; + if (moves !== undefined && bodyOutput !== undefined) return `{ readonly transition: ${moves}; readonly output: ${bodyOutput} }`; + return moves ?? bodyOutput ?? "void"; +} + +/** The parameters a declared operation takes, before `opts`, as `name: type` pairs. */ +function operationParams(w: TsWriter, op: ServiceOperation, path: string, pkg: ServicePackage, ctx: RenderContext): string[] { + const params: string[] = []; + if (op.keyed) params.push("id: number | string"); + if (op.input !== undefined) params.push(`input: ${callerInputType(w, op, path, pkg, ctx)}`); + if (op.kind === "query" && op.many) params.push(`query: ${w.useType("ListQueryInput", runtimeSpecifierFrom(path, "service", ctx))}`); + return params; +} + +/** The derived command of a transition (ADR-0066 §2): it takes the key and makes the move. */ +function renderTransitionCommand(c: ServiceTransitionCommand, e: ServiceEntity, path: string, ctx: RenderContext, pkg: ServicePackage): string { + const obj = e.obj; + const name = obj.name; + const t = c.transition; + const w = new TsWriter(); + header(w, `${name} (${obj.fqn()}) — transition ${t.field}.${t.name}, service operation ${c.fn} (ADR-0066 §2)`); + const runtime = runtimeSpecifierFrom(path, "service", ctx); + const mods = modulesOf(path, obj, ctx); + const table = w.use(ctx.collectionName(name), mods.entity); + const row = w.useType(name, mods.contract); + const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; + const opOptions = `${w.useType("OpOptions", runtime)}`; + const opResult = w.useType("OpResult", runtime); + const dialect = str(ctx.dialect); + const spec = w.useType("TransitionSpec", runtime); + w.doc(`\`${t.field}\`: ${t.from.join(", ")} → ${t.to}.`); + w.line(`const move: ${spec} = ${transitionLiteral(t)};`); + w.blank(); + w.doc( + `Make the ${name} row \`id\` names move \`${t.name}\`. In one transaction, in ADR-0066 §6's order: load it`, + "under a row lock (`not_found`), the permission point (`forbidden`), the state check", + "(`invalid_transition`), the guarded update (`invalid_transition` or", + "`transition_condition_failed` when it matches no row), the event hook. Answers the written row.", + ); + w.block(`export async function ${c.fn}(deps: ${deps}, id: number | string, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { + w.block(`return ${w.use("inWriteTransaction", runtime)}(deps.db, opts.tx, async (tx) => {`, () => { + w.line(`const cond = ${w.use("keyCondition", runtime)}(${table}, ${str(e.keyField)}, id);`); + w.line(`const current = (await ${w.use("loadForWrite", runtime)}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); + w.line(`if (current === undefined) ${w.use("notFound", runtime)}();`); + if (c.permission === undefined) w.line("// @public: the policy is not asked."); + else w.line(`await ${w.use("checkPermission", runtime)}(deps.policy, ${str(c.permission)}, opts.actor, current, undefined, tx);`); + w.line(`${w.use("checkState", runtime)}(current, [move]);`); + w.line(`const row = (await ${w.use("makeTransition", runtime)}(tx, ${table}, cond, move, ${dialect})) as ${row};`); + w.line( + `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "transition", entity: ${str(name)}, key: current.${e.keyField}, lifecycle: move.field, transition: move.name, from: String(current.${t.field}), to: move.to, operation: ${str(c.fn)}, actor: opts.actor, at: new Date() }, tx);`, + ); + w.line("return row;"); + }, "});"); + }); + return w.toString(); +} + +/** A declared command or query (ADR-0066 §1): the shell around its hand-written body. */ +function renderDeclaredOperation(op: ServiceOperation, path: string, ctx: RenderContext, pkg: ServicePackage): string { + if (op.transitions.length > 0 && !op.keyed) { + throw new Error(`service: command ${op.name} lists @transitions but addresses no row by key, so it has no row to move`); + } + const w = new TsWriter(); + header(w, `${pkg.package === "" ? "the model" : pkg.package} — ${op.kind} ${op.name}, a service operation (ADR-0066 §1)`); + const runtime = runtimeSpecifierFrom(path, "service", ctx); + const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; + const opOptions = `${w.useType("OpOptions", runtime)}`; + const opResult = w.useType("OpResult", runtime); + const dialect = str(ctx.dialect); + const target = op.target; + // The target's table and row type, imported only by an operation that reads or answers its row. + const usesRow = op.keyed || outputIsTargetRow(op); + const mods = target === undefined || !usesRow ? undefined : modulesOf(path, target.obj, ctx); + const table = mods === undefined ? undefined : w.use(ctx.collectionName(target!.obj.name), mods.entity); + const row = mods === undefined ? undefined : w.useType(target!.obj.name, mods.contract); + const output = outputType(w, op, path, pkg, ctx); + const params = [...operationParams(w, op, path, pkg, ctx), `opts: ${opOptions} = {}`]; + const command = op.kind === "command"; + + if (op.input !== undefined) { + w.doc("What the input may name: every other key is refused."); + objectLiteral(w, `const inputRules: ${w.useType("WriteBodyRules", runtime)} = `, [knownFieldsLine(op.input, "", ctx.loadedRoot)], ";"); + w.blank(); + } + if (op.transitions.length > 0) { + const spec = w.useType("TransitionSpec", runtime); + w.doc("The moves the command may make (`@transitions`)."); + w.block(`const moves: Record = {`, () => { + for (const t of op.transitions) w.line(`${t.name}: ${transitionLiteral(t)},`); + }, "};"); + w.blank(); + } + const steps = [ + ...(op.keyed ? [command ? "load the target row under a row lock (`not_found`)" : "read the target row (`not_found`)"] : []), + ...(op.input !== undefined ? ["validate the input"] : []), + op.permission === undefined ? "no permission point (it is `@public`)" : "the permission point (`forbidden`)", + ...(op.transitions.length > 0 ? ["the state check (`invalid_transition`)"] : []), + "the body", + ...(op.transitions.length > 0 ? ["the guarded update"] : []), + ...(command ? ["the event hook"] : []), + ]; + w.doc( + command + ? `\`${op.name}\` (command). In one transaction, in ADR-0066 §6's order:` + : `\`${op.name}\` (query). In the read scope, opening no write transaction:`, + `${steps.join(", ")}.`, + ); + w.block(`export async function ${op.name}(deps: ${deps}, ${params.join(", ")}): Promise<${opResult}<${output}>> {`, () => { + const scope = command ? w.use("inWriteTransaction", runtime) : w.use("inReadScope", runtime); + w.block(`return ${scope}(deps.db, opts.tx, async (tx) => {`, () => { + if (op.keyed) { + w.line(`const cond = ${w.use("keyCondition", runtime)}(${table}, ${str(target!.keyField)}, id);`); + const load = command + ? `await ${w.use("loadForWrite", runtime)}(tx, ${table}, cond, ${dialect})` + : `await ${w.use("readOne", runtime)}(tx, ${table}, cond)`; + w.line(`const current = (${load}) as ${row} | undefined;`); + w.line(`if (current === undefined) ${w.use("notFound", runtime)}();`); + } + let values = "undefined"; + if (op.input !== undefined) { + const schema = w.use(`${toPascalCase(op.name)}InputSchema`, operationsSpecifier(path, pkg, ctx)); + const given = op.inputKeyField === undefined ? "input" : `{ ...input, ${op.inputKeyField}: current.${target!.keyField} }`; + w.line(`const values: ${inputType(w, op, path, pkg, ctx)} = ${w.use("validateBody", runtime)}(${schema}, ${given}, inputRules);`); + values = "values"; + } + const rowArg = op.keyed ? "current" : "undefined"; + if (op.permission === undefined) w.line("// @public: the policy is not asked."); + else w.line(`await ${w.use("checkPermission", runtime)}(deps.policy, ${str(op.permission)}, opts.actor, ${rowArg}, ${values}, tx);`); + if (op.transitions.length > 0) w.line(`${w.use("checkState", runtime)}(current, Object.values(moves));`); + const bodyArgs = [ + ...(op.input !== undefined ? ["values"] : []), + ...(op.kind === "query" && op.many ? ["query"] : []), + op.keyed ? `{ ...${w.use("handlerContext", runtime)}(tx, opts.actor), row: current }` : `${w.use("handlerContext", runtime)}(tx, opts.actor)`, + ]; + const call = `await deps.bodies.${op.name}(${bodyArgs.join(", ")})`; + if (!command) { + w.line(`return ${call};`); + return; + } + w.line(`const outcome = ${call};`); + const emit = w.use("emitWrite", runtime); + const entity = target === undefined ? "undefined" : str(target.obj.name); + const key = op.keyed ? `current.${target!.keyField}` : "undefined"; + const commandEvent = `await ${emit}(deps.events, { kind: "command", operation: ${str(op.name)}, entity: ${entity}, key: ${key}, actor: opts.actor, at: new Date() }, tx);`; + if (op.transitions.length > 0) { + const both = op.output !== undefined && !outputIsTargetRow(op); + w.line(`const made = ${both ? "outcome.transition" : "outcome"};`); + w.block(`if (made === "none") {`, () => w.line(commandEvent)); + w.block(`if (made !== "none") {`, () => { + w.line("const move = moves[made]!;"); + w.line(`await ${w.use("makeTransition", runtime)}(tx, ${table}, cond, move, ${dialect});`); + w.line( + `await ${emit}(deps.events, { kind: "transition", entity: ${entity}, key: ${key}, lifecycle: move.field, transition: move.name, from: String(current[move.field as keyof typeof current]), to: move.to, operation: ${str(op.name)}, actor: opts.actor, at: new Date() }, tx);`, + ); + }); + if (outputIsTargetRow(op)) w.line(`return (await ${w.use("readOne", runtime)}(tx, ${table}, cond)) as ${row};`); + else if (both) w.line("return outcome.output;"); + return; + } + w.line(commandEvent); + if (outputIsTargetRow(op)) w.line(`return (await ${w.use("readOne", runtime)}(tx, ${table}, cond)) as ${row};`); + else if (op.output !== undefined) w.line("return outcome;"); }, "});"); }); return w.toString(); @@ -236,13 +500,13 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex const label = pkg.package === "" ? "the model's root package" : `package ${pkg.package}`; header(w, `${label} — service module (ADR-0067 layer 4)`); const runtime = runtimeSpecifierFrom(path, "service", ctx); - const opOptions = w.useType("OpOptions", runtime); + const opOptions = `${w.useType("OpOptions", runtime)}`; const opResult = w.useType("OpResult", runtime); const listPage = w.useType("ListPage", runtime); const query = w.useType("ListQueryInput", runtime); - const timestampWire = w.use("timestampWire", runtime); - const withWire = w.use("withWire", runtime); + const hookContext = `${w.useType("HookContext", runtime)}`; const type = serviceTypeName(pkg.package); + const stem = type.replace(/Service$/, ""); const { import: dbImport, alias: dbAlias } = dbTypeBlock(ctx.dialect, { asyncOnly: true }); // The dialect's Drizzle base type, the queries generator's, except that SQLite is async-only: @@ -250,11 +514,87 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex const dbModule = /from "([^"]+)"/.exec(dbImport)![1]!; for (const t of /import type \{ ([^}]+) \}/.exec(dbImport)![1]!.split(",").map((s) => s.trim())) w.useType(t, dbModule); w.line(dbAlias); + + const hasPolicy = pkg.permissions.length > 0; + const hasBodies = pkg.operations.length > 0; + if (hasPolicy) { + w.blank(); + w.doc("Every permission a point of the package asks the policy about (ADR-0066 §1)."); + w.line(`export type ${stem}Permission = ${pkg.permissions.map(str).join(" | ")};`); + w.blank(); + w.doc( + "The policy: whether the actor may pass a permission point, given the loaded row and the input.", + "Asked before anything is written; refusing answers 403 `forbidden`. Who holds a permission is data,", + "and what the policy decides is code: implement it, and pass it in `deps.policy`.", + ); + w.line(`export type ${stem}Policy = ${w.useType("Policy", runtime)}<${stem}Permission, A, Db>;`); + } + + w.blank(); + w.doc( + "Hooks on the derived writes, all optional: an absent hook does nothing. Each runs in the write's", + "transaction (`ctx.tx`); a before hook may return a replacement input, and any hook may refuse", + "(`ctx.refuse(code)`, 409), which rolls the whole write back.", + ); + w.block(`export interface ${stem}Hooks {`, () => { + for (const e of pkg.entities) { + const mods = modulesOf(path, e.obj, ctx); + const row = w.useType(e.obj.name, mods.contract); + const create = w.useType(`${e.obj.name}Create`, mods.contract); + const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const o = e.operations; + const P = (f: string) => toPascalCase(f); + w.line(`before${P(o.create)}?(input: ${create}, ctx: ${hookContext}): ${create} | void | Promise<${create} | void>;`); + w.line(`after${P(o.create)}?(row: ${row}, ctx: ${hookContext}): void | Promise;`); + w.line(`before${P(o.update)}?(patch: ${patch}, current: ${row}, ctx: ${hookContext}): ${patch} | void | Promise<${patch} | void>;`); + w.line(`after${P(o.update)}?(row: ${row}, previous: ${row}, ctx: ${hookContext}): void | Promise;`); + w.line(`before${P(o.delete)}?(current: ${row}, ctx: ${hookContext}): void | Promise;`); + w.line(`after${P(o.delete)}?(row: ${row}, ctx: ${hookContext}): void | Promise;`); + } + }); + + w.blank(); + w.doc( + "The write-event hook: told about every write, in its transaction, with the actor (ADR-0066 §7).", + "An outbox, a history table or an audit log is written here. Absent, nothing is told.", + ); + w.line(`export type ${stem}Events = ${w.useType("WriteEvents", runtime)};`); + + if (hasBodies) { + w.blank(); + w.doc( + "The hand-written bodies of the declared operations. The shell calls each inside its guarantee,", + "after the row, the input and the permission point are checked: a command's body in the write", + "transaction, a query's in the read scope. A command with `@transitions` returns the move to make", + "or `\"none\"`; `ctx.refuse(code)` answers one of its `@errors` (409) and rolls everything back.", + ); + w.block(`export interface ${stem}Bodies {`, () => { + for (const op of pkg.operations) { + const output = outputType(w, op, path, pkg, ctx); + const outcome = outcomeType(op, output); + const errors = op.errors.length === 0 ? "never" : w.useType(`${toPascalCase(op.name)}BusinessError`, operationsSpecifier(path, pkg, ctx)); + const bodyCtx = `${w.useType("BodyContext", runtime)}`; + const rowType = op.keyed ? w.useType(op.target!.obj.name, modulesOf(path, op.target!.obj, ctx).contract) : undefined; + const ctxType = rowType === undefined ? bodyCtx : `${bodyCtx} & { readonly row: ${rowType} }`; + const args = [ + ...(op.input !== undefined ? [`input: ${inputType(w, op, path, pkg, ctx)}`] : []), + ...(op.kind === "query" && op.many ? [`query: ${query}`] : []), + `ctx: ${ctxType}`, + ]; + w.line(`${op.name}(${args.join(", ")}): ${outcome} | Promise<${outcome}>;`); + } + }); + } + w.blank(); - w.doc("What the service needs from the composition root."); - w.block("export interface ServiceDeps {", () => { + w.doc("What the service needs from the composition root. `A` is the app's actor type (ADR-0067 §7)."); + w.block("export interface ServiceDeps {", () => { w.doc("The database every operation runs on. A caller may pass a transaction of its own per call (`opts.tx`)."); w.line("readonly db: Db;"); + if (hasPolicy) w.line(`readonly policy: ${stem}Policy;`); + if (hasBodies) w.line(`readonly bodies: ${stem}Bodies;`); + w.line(`readonly hooks?: ${stem}Hooks;`); + w.line(`readonly events?: ${stem}Events;`); }); const calls: string[] = []; @@ -263,7 +603,7 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex `The operations of ${label}. A transport, a job or an agent tool calls these; each answers an`, "`OpResult`, and a failure carries the status the REST contract gives its code.", ); - w.block(`export interface ${type} {`, () => { + w.block(`export interface ${type} {`, () => { for (const e of pkg.entities) { const mods = modulesOf(path, e.obj, ctx); const row = w.useType(e.obj.name, mods.contract); @@ -283,12 +623,24 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex `${o.update}: (id, patch, opts) => ${o.update}(deps, id, patch, opts),`, `${o.delete}: (id, opts) => ${o.delete}(deps, id, opts),`, ); + for (const c of e.commands) { + w.use(c.fn, withExtIfRelative(`./${c.fn}`, ctx.extStyle)); + w.line(`${c.fn}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + calls.push(`${c.fn}: (id, opts) => ${c.fn}(deps, id, opts),`); + } + } + for (const op of pkg.operations) { + w.use(op.name, withExtIfRelative(`./${op.name}`, ctx.extStyle)); + const params = operationParams(w, op, path, pkg, ctx); + const names = params.map((p) => p.slice(0, p.indexOf(":"))); + w.line(`${op.name}(${[...params, `opts?: ${opOptions}`].join(", ")}): Promise<${opResult}<${outputType(w, op, path, pkg, ctx)}>>;`); + calls.push(`${op.name}: (${[...names, "opts"].join(", ")}) => ${op.name}(deps, ${[...names, "opts"].join(", ")}),`); } }); w.blank(); w.doc(`Bind the operations of ${label} to \`deps\`.`); - w.block(`export function ${serviceFactoryName(pkg.package)}(deps: ServiceDeps): ${type} {`, () => { + w.block(`export function ${serviceFactoryName(pkg.package)}(deps: ServiceDeps): ${type} {`, () => { w.block("return {", () => { for (const c of calls) w.line(c); }, "};"); @@ -299,20 +651,44 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex const table = w.use(ctx.collectionName(e.obj.name), mods.entity); w.blank(); w.doc(`The wire form (ADR-0019) of a ${e.obj.name} row: what a transport sends.`); - objectLiteral(w, `export const ${wireMapperName(e.obj.name)} = ${withWire}(${timestampWire}(${table}), `, [decimalColumnsLine(e.obj, "", ctx.loadedRoot)], ");"); + objectLiteral(w, `export const ${wireMapperName(e.obj.name)} = ${w.use("withWire", runtime)}(${w.use("timestampWire", runtime)}(${table}), `, [decimalColumnsLine(e.obj, "", ctx.loadedRoot)], ");"); } return w.toString(); } -/** The thin Fastify transport of package `pkg`: parse, call the service, send what it answered. */ +/** One route the transport mounts: its method and Fastify path, before the API prefix. */ +interface MountedRoute { + readonly method: string; + readonly path: string; + readonly what: string; +} + +/** + * Refuse two routes on one method and path (placeholder names ignored): a declared binding on a + * derived CRUD route, or two derived paths that meet (ADR-0066 §5: the transport generator that + * mounts the routes refuses a collision the loader cannot see). + */ +function refuseRouteCollisions(routes: readonly MountedRoute[]): void { + const seen = new Map(); + for (const r of routes) { + const key = `${r.method} ${r.path.replace(/:[^/]+/g, ":")}`; + const prior = seen.get(key); + if (prior !== undefined) throw new Error(`service-routes: ${r.what} and ${prior} are both mounted on ${r.method} ${r.path}`); + seen.set(key, r.what); + } +} + +/** The thin Fastify transport of package `pkg`: parse, resolve the actor, call the service, send what it answered. */ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): ServiceFile { const path = fastifyTransportPath(pkg.package); const w = new TsWriter(); const label = pkg.package === "" ? "the model's root package" : `package ${pkg.package}`; header(w, `${label} — Fastify transport (ADR-0067 layer 5)`); const runtime = runtimeSpecifierFrom(path, "service-fastify", ctx); + const serviceRuntime = runtimeSpecifierFrom(path, "service", ctx); const serviceIndex = contractSpecifier(path, servicePath(pkg.package, SERVICE_INDEX_FILE), ctx.extStyle); const fastifyInstance = w.useType("FastifyInstance", "fastify"); + const fastifyRequest = w.useType("FastifyRequest", "fastify"); const send = w.use("sendOpResult", runtime); const handler = w.use("withContractErrorHandler", runtime); const parseQuery = w.use("parseListQueryString", runtime); @@ -320,18 +696,42 @@ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): const type = w.useType(serviceTypeName(pkg.package), serviceIndex); const routes = serviceRoutesName(pkg.package); - w.doc("What the routes need: the service they call."); - w.block(`export interface ${type}RoutesOptions {`, () => { - w.line(`readonly service: ${type};`); + const mounted: MountedRoute[] = []; + for (const e of pkg.entities) { + const base = restPath(e.obj); + const item = `${base}/:id`; + mounted.push( + { method: "GET", path: base, what: `${e.obj.name} list` }, + { method: "GET", path: item, what: `${e.obj.name} get` }, + { method: "POST", path: base, what: `${e.obj.name} create` }, + { method: "PATCH", path: item, what: `${e.obj.name} update` }, + { method: "PUT", path: item, what: `${e.obj.name} update` }, + { method: "DELETE", path: item, what: `${e.obj.name} delete` }, + ); + for (const c of e.commands) mounted.push({ method: "POST", path: `${item}/${c.transition.name}`, what: `transition ${e.obj.name}.${c.transition.name}` }); + } + for (const op of pkg.operations) mounted.push({ method: op.method, path: op.path, what: `operation ${op.name}` }); + refuseRouteCollisions(mounted); + + w.doc("What the routes need: the service they call, and who is calling."); + w.block(`export interface ${type}RoutesOptions {`, () => { + w.line(`readonly service: ${type};`); + w.doc( + "Who a request is for (ADR-0067 §7): the app's own resolver, from its own authentication. The", + "service never looks inside the actor; it hands it to the policy, the bodies, the hooks and the", + "event hook. Absent, every operation runs with no actor, which a policy may refuse.", + ); + w.line(`readonly getActor?: (request: ${fastifyRequest}) => A | undefined | Promise;`); }); w.blank(); w.doc( - `Mount the REST routes of ${label}. Each route parses the request, calls one operation of the`, - "service and sends what it answered; it holds no rules. Register it with the service:", - `\`app.register(${routes}, { service })\`.`, + `Mount the REST routes of ${label}. Each route parses the request, resolves the actor, calls one`, + "operation of the service and sends what it answered; it holds no rules. Register it with the", + `service: \`app.register(${routes}, { service, getActor })\`.`, ); - w.block(`export async function ${routes}(fastify: ${fastifyInstance}, opts: ${type}RoutesOptions): Promise {`, () => { + w.block(`export async function ${routes}(fastify: ${fastifyInstance}, opts: ${type}RoutesOptions): Promise {`, () => { w.line("const { service } = opts;"); + w.line(`const actorOf = async (req: ${fastifyRequest}): Promise<${w.useType("OpOptions", serviceRuntime)}> => ({ actor: (await opts.getActor?.(req)) as A | undefined });`); w.line(`const ro = ${handler}(undefined);`); const mount = (app: string) => { for (const e of pkg.entities) { @@ -344,20 +744,40 @@ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): const item = str(`${restPath(e.obj)}/:id`); const params = "{ Params: { id: string } }"; w.block(`${app}.get(${base}, ro, async (req, reply) => {`, () => { - w.line(`const result = await service.${o.list}(${parseQuery}(${rawQuery}(req.raw.url)));`); + w.line(`const result = await service.${o.list}(${parseQuery}(${rawQuery}(req.raw.url)), await actorOf(req));`); w.line( `return ${send}(reply, result, 200, (page) => (page.total === undefined ? page.rows.map(${toWire}) : { rows: page.rows.map(${toWire}), total: page.total }));`, ); }, "});"); - w.line(`${app}.get<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.get}(req.params.id), 200, ${toWire}));`); - w.line(`${app}.post(${base}, ro, async (req, reply) => ${send}(reply, await service.${o.create}(req.body as ${create}), 201, ${toWire}));`); + w.line(`${app}.get<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.get}(req.params.id, await actorOf(req)), 200, ${toWire}));`); + w.line(`${app}.post(${base}, ro, async (req, reply) => ${send}(reply, await service.${o.create}(req.body as ${create}, await actorOf(req)), 201, ${toWire}));`); w.line("// The update is reachable by PATCH and by PUT, as in every port."); for (const verb of ["patch", "put"]) { w.line( - `${app}.${verb}<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.update}(req.params.id, req.body as ${patch}), 200, ${toWire}));`, + `${app}.${verb}<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.update}(req.params.id, req.body as ${patch}, await actorOf(req)), 200, ${toWire}));`, ); } - w.line(`${app}.delete<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.delete}(req.params.id), 204));`); + w.line(`${app}.delete<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.delete}(req.params.id, await actorOf(req)), 204));`); + for (const c of e.commands) { + w.line( + `${app}.post<${params}>(${str(`${restPath(e.obj)}/:id/${c.transition.name}`)}, ro, async (req, reply) => ${send}(reply, await service.${c.fn}(req.params.id, await actorOf(req)), 200, ${toWire}));`, + ); + } + } + for (const op of pkg.operations) { + const key = op.keyed ? op.target!.keyField : undefined; + const generic = key === undefined ? "" : `<{ Params: { ${key}: string } }>`; + const fromGet = op.method === "GET" || op.method === "DELETE"; + const args = [ + ...(key === undefined ? [] : [`req.params.${key}`]), + ...(op.input !== undefined ? [`(${fromGet ? "req.query" : "req.body ?? {}"}) as never`] : []), + ...(op.kind === "query" && op.many ? [`${parseQuery}(${rawQuery}(req.raw.url))`] : []), + "await actorOf(req)", + ]; + const result = `await service.${op.name}(${args.join(", ")})`; + const wire = outputIsTargetRow(op) ? `, ${w.use(wireMapperName(op.target!.obj.name), serviceIndex)}` : ""; + const status = op.output === undefined && op.kind === "command" ? "204" : "200"; + w.line(`${app}.${op.method.toLowerCase()}${generic}(${str(op.path)}, ro, async (req, reply) => ${send}(reply, ${result}, ${status}${wire}));`); } }; if (ctx.apiPrefix) { diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts index 3c514a7238..c5ed73111d 100644 --- a/server/typescript/packages/codegen-ts/test/service-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -85,7 +85,7 @@ describe("service generators — what they write", () => { test("the flat layout keeps the package directory: two packages cannot both write service/index.ts", async () => { const root = await load("acme::shop", [entity("Order")]); const files = await gen(root, tier(), "flat"); - expect(files["acme/shop/service/index.ts"]).toContain("export function createShopService(deps: ServiceDeps): ShopService {"); + expect(files["acme/shop/service/index.ts"]).toContain("export function createShopService(deps: ServiceDeps): ShopService {"); // The entity module stays where the flat layout puts it, and the service reaches it. expect(files["acme/shop/service/createOrder.ts"]).toContain('from "../../../Order.js";'); }); @@ -151,3 +151,101 @@ describe("service walk — which entities get the derived operations", () => { for (const tph of ["Auth", "BridgeAuth", "CouponAuth", "PermitAuth", "ReferralAuth"]) expect(covered).not.toContain(tph); }); }); + +// ADR-0066 on the generated side: the lifecycle, the declared operations, the permission points +// and the three `rules.*` keys that change what is generated. Behaviour over HTTP is gated by the +// api-contract rules corpus (`integration-tests/test/api-contract-rules.test.ts`). +const order = (transitions: unknown[], extra: unknown[] = []) => + entity("Order", [ + { + "field.enum": { + name: "status", + "@values": ["open", "paid", "void"], + "@default": "open", + children: transitions, + }, + }, + ...extra, + ]); +const pay = { "transition.action": { name: "pay", "@from": ["open"], "@to": "paid" } }; +const voidIt = { "transition.action": { name: "void", "@from": ["open", "paid"], "@to": "void", "@public": true } }; +const api = (...ops: unknown[]) => ({ "api.operational": { name: "Shop", children: ops } }); +const settlement = { + "object.value": { + name: "Settlement", + children: [{ "field.long": { name: "orderId", extends: "Order.id" } }, { "field.string": { name: "reference", "@maxLength": 40 } }], + }, +}; +// Keyed by its input's borrowed key (`orderId` extends `Order.id`, ADR-0066 §3). +const settle = { + "operation.command": { name: "settle", "@inputRef": "Settlement", "@transitions": ["pay"], "@permission": "shop.settle" }, +}; + +async function withSettings(root: MetaRoot, settings: Partial): Promise { + root.rulesSettings = { ...root.rulesSettings, ...settings }; + return root; +} + +describe("service generators — lifecycles and declared operations (ADR-0066)", () => { + test("each unclaimed transition derives a command file and a route; a claimed one derives neither", async () => { + const root = await load("acme::shop", [order([pay, voidIt]), settlement, api(settle)]); + const files = await gen(root, tier()); + expect(servicePaths(files)).toContain("acme/shop/service/voidOrder.ts"); + expect(servicePaths(files)).toContain("acme/shop/service/settle.ts"); + // `pay` is claimed by `settle`, so under the default `unclaimed` it has no command of its own. + expect(servicePaths(files)).not.toContain("acme/shop/service/payOrder.ts"); + expect(files["acme/shop/transport/fastify.ts"]).toContain('"/orders/:id/void"'); + expect(files["acme/shop/transport/fastify.ts"]).not.toContain('"/orders/:id/pay"'); + // The derived permission name of a transition is `..`; `void` is public. + expect(files["acme/shop/service/index.ts"]).toContain('export type ShopPermission = "shop.settle";'); + }); + + test("rules.lifecycle.commands: all derives a command for a claimed transition too; none derives none", async () => { + const all = await gen(await withSettings(await load("acme::shop", [order([pay, voidIt]), settlement, api(settle)]), { lifecycleCommands: "all" }), tier()); + expect(servicePaths(all)).toContain("acme/shop/service/payOrder.ts"); + expect(all["acme/shop/service/payOrder.ts"]).toContain('"acme::shop.Order.pay"'); + const none = await gen(await withSettings(await load("acme::shop", [order([pay, voidIt]), settlement, api(settle)]), { lifecycleCommands: "none" }), tier()); + expect(servicePaths(none).filter((p) => /(pay|void)Order/.test(p))).toEqual([]); + expect(servicePaths(none)).toContain("acme/shop/service/settle.ts"); + }); + + test("rules.lifecycle.create: initial checks a create's state against the initial one; any does not", async () => { + const initial = await gen(await load("acme::shop", [order([pay])]), tier()); + expect(initial["acme/shop/service/createOrder.ts"]).toContain('checkCreateState(values, { status: "open" });'); + const any = await gen(await withSettings(await load("acme::shop", [order([pay])]), { lifecycleCreate: "any" }), tier()); + expect(any["acme/shop/service/createOrder.ts"]).not.toContain("checkCreateState("); + // A lifecycle field is moved only by a transition, under either setting. + expect(any["acme/shop/service/updateOrder.ts"]).toContain('checkStateManaged('); + }); + + test("rules.permissions.names: require refuses a point with no @permission, naming the name it would derive", async () => { + const root = await withSettings(await load("acme::shop", [order([pay])]), { permissionNames: "require" }); + await expect(gen(root, tier())).rejects.toThrow(/acme::shop\.Order\.pay/); + // A declared or public point passes. + const declared = await withSettings( + await load("acme::shop", [order([{ "transition.action": { name: "pay", "@from": ["open"], "@to": "paid", "@permission": "shop.pay" } }, voidIt])]), + { permissionNames: "require" }, + ); + expect(servicePaths(await gen(declared, tier()))).toContain("acme/shop/service/payOrder.ts"); + }); + + test("a declared binding on a derived route's method and path is refused by name", async () => { + const clash = { + "operation.query": { + name: "peek", + "@objectRef": "Order", + "@outputRef": "Order", + "@public": true, + children: [{ "binding.rest": { "@method": "GET", "@path": "/orders/{id}" } }], + }, + }; + const root = await load("acme::shop", [order([pay]), api(clash)]); + await expect(gen(root, tier())).rejects.toThrow(/operation peek and Order get are both mounted on GET/); + }); + + test("a command that lists @transitions but addresses no row by key is refused: it has no row to move", async () => { + const unkeyed = { "operation.command": { name: "settle", "@objectRef": "Order", "@transitions": ["pay"], "@permission": "shop.settle" } }; + const root = await load("acme::shop", [order([pay]), api(unkeyed)]); + await expect(gen(root, tier())).rejects.toThrow(/command settle lists @transitions but addresses no row by key/); + }); +}); diff --git a/server/typescript/packages/integration-tests/src/api-contract-rules-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-rules-generated-server.ts new file mode 100644 index 0000000000..b67b180275 --- /dev/null +++ b/server/typescript/packages/integration-tests/src/api-contract-rules-generated-server.ts @@ -0,0 +1,211 @@ +// api-contract-rules-generated-server.ts — boots the GENERATED service of the rules corpus +// (ADR-0066 lifecycles, declared operations and permission points; ADR-0067 layers 4 and 5) +// behind its emitted Fastify transport, and drives it against `fixtures/api-contract-conformance/rules/`. +// +// The shells are generated; what an app writes by hand is supplied here, exactly as the corpus +// README specifies it so every port's lane implements the same behaviour: the actor resolver, +// the policy, the two operation bodies, one hook and the event hook. Nothing here re-implements a +// rule the shell owns: the check order, the guarded update, `state_managed` and the rollback are +// all the emitted code's. + +import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; +import { contractTypes, entityFile, serviceFile, serviceRoutesFile } from "@metaobjectsdev/codegen-ts/generators"; +import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; +import { sql, type SQL } from "drizzle-orm"; +import type pg from "pg"; +import type { OutputLayout } from "./output-layout.ts"; +import { executeSql } from "./postgres-sql.ts"; +import { applyNearestNaming, loadMetadataFile } from "./load-metadata.ts"; + +export interface RulesSeed { + purchaseRequests: Array<{ id: number; title: string; amountCents: number; limitCents: number | null; status: string }>; +} + +export interface GeneratedRulesServerHandle { + baseUrl: string; + applySeed(seed: RulesSeed): Promise; + close(): Promise; +} + +/** The README's actor: a name and the permissions it holds, from two request headers. */ +interface Actor { + readonly name: string; + readonly grants: readonly string[]; +} + +/** The slice of a Drizzle node-postgres handle the hand-written code uses. */ +interface Sqlish { + execute(query: SQL): Promise<{ rows: Array> }>; +} + +/** The slice of the generated contexts the hand-written code uses. */ +interface Ctx { + readonly tx: unknown; + readonly actor: Actor | undefined; + refuse(code: string, details?: Record): never; +} + +type WriteEvent = { + kind: string; + entity?: string; + key?: unknown; + transition?: string; + from?: string; + to?: string; + operation?: string; + actor: Actor | undefined; +}; + +const exec = (tx: unknown, query: SQL) => (tx as Sqlish).execute(query); + +/** + * Generate the corpus's service and transport, and mount them. + * + * `configDir` is where the run's `.metaobjects/config.json` is looked up: the corpus directory + * for the default settings, or a `settings//` directory for a variant, which reuses the + * corpus's one model. + */ +export async function startGeneratedRulesServer( + connectionUri: string, + metaPath: string, + configDir: string, + outputLayout: OutputLayout = "flat", +): Promise { + const here = dirname(fileURLToPath(import.meta.url)); + const genTmpRoot = join(here, "..", ".gen-tmp"); + mkdirSync(genTmpRoot, { recursive: true }); + const tmp = mkdtempSync(join(genTmpRoot, "api-contract-rules-")); + + const root = applyNearestNaming(await loadMetadataFile(metaPath), configDir); + root.physicalNaming = DEFAULT_PHYSICAL_NAMING; + const lr = await runGen({ + config: defineConfig({ + outDir: tmp, + extStyle: "none", + outputLayout, + dbImport: "./db", + dialect: "postgres", + apiPrefix: "/api", + generators: [entityFile(), contractTypes(), serviceFile(), serviceRoutesFile()], + }), + metadata: root, + }); + if (lr.warnings.length > 0) throw new Error(`codegen produced warnings: ${lr.warnings.join("; ")}`); + + const bigintTypesImport = pathToFileURL(join(here, "pg-bigint-number-types.ts")).href; + writeFileSync( + join(tmp, "db.ts"), + ` +import { drizzle } from "drizzle-orm/node-postgres"; +import pg from "pg"; +import { bigintAsNumberTypes } from ${JSON.stringify(bigintTypesImport)}; +export const pool = new pg.Pool({ connectionString: ${JSON.stringify(connectionUri)}, types: bigintAsNumberTypes }); +export const db = drizzle(pool); +`, + "utf8", + ); + + // The schema `meta migrate` writes for the model: the enum's `@default` is the column DEFAULT, + // which a create under `rules.lifecycle.create: any` that omits the state relies on. + await executeSql( + connectionUri, + `CREATE TABLE IF NOT EXISTS "purchase_requests" ( + "id" bigserial PRIMARY KEY, + "title" varchar(80) NOT NULL, + "amount_cents" bigint NOT NULL, + "limit_cents" bigint, + "status" varchar(255) DEFAULT 'draft' + ); + CREATE TABLE IF NOT EXISTS "audit_entries" ( + "id" bigserial PRIMARY KEY, + "kind" varchar(20) NOT NULL, + "detail" varchar(200) NOT NULL + );`, + ); + + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const service = (await import(pathToFileURL(join(tmp, "acme/purchasing/service/index.ts")).href)) as { + createPurchasingService: (deps: unknown) => unknown; + }; + const transport = (await import(pathToFileURL(join(tmp, "acme/purchasing/transport/fastify.ts")).href)) as { + purchasingServiceRoutes: (f: FastifyInstance, opts: unknown) => Promise; + }; + + const deps = { + db: dbMod.db, + // Allowed exactly when the actor holds the permission by name. + policy: { allows: (permission: string, actor: Actor | undefined) => actor?.grants.includes(permission) ?? false }, + bodies: { + decide: (input: { approve: boolean; note?: string | null }, ctx: Ctx) => { + if (!input.approve && (input.note === undefined || input.note === null || input.note === "")) ctx.refuse("note_required"); + return input.approve ? "approve" : "reject"; + }, + requestTotals: async (ctx: Ctx) => { + const r = await exec( + ctx.tx, + sql`SELECT count(*)::bigint AS "count", coalesce(sum("amount_cents"), 0)::bigint AS "totalCents" FROM "purchase_requests"`, + ); + return { count: Number(r.rows[0]!["count"]), totalCents: Number(r.rows[0]!["totalCents"]) }; + }, + }, + hooks: { + // Runs after the row is written, so a refusal here proves the write is rolled back. + afterUpdatePurchaseRequest: (row: { title: string }, _previous: unknown, ctx: Ctx) => { + if (row.title === "REFUSE") ctx.refuse("title_refused"); + }, + }, + events: { + onWrite: async (event: WriteEvent, ctx: Ctx) => { + if (event.actor?.name === "no-audit") ctx.refuse("audit_unavailable"); + const detail = + event.kind === "transition" + ? `${event.entity} ${String(event.key)} ${event.transition} ${event.from}->${event.to} by ${event.actor?.name ?? "-"}` + : event.kind === "command" + ? `${event.operation} ${String(event.key)} by ${event.actor?.name ?? "-"}` + : `${event.entity} ${String(event.key)} by ${event.actor?.name ?? "-"}`; + await exec(ctx.tx, sql`INSERT INTO "audit_entries" ("kind", "detail") VALUES (${event.kind}, ${detail})`); + }, + }, + }; + + const getActor = (req: FastifyRequest): Actor | undefined => { + const name = req.headers["x-actor"]; + if (typeof name !== "string" || name === "") return undefined; + const grants = req.headers["x-grants"]; + return { name, grants: typeof grants === "string" && grants !== "" ? grants.split(",").map((g) => g.trim()) : [] }; + }; + + const fastify = Fastify(); + await fastify.register(transport.purchasingServiceRoutes, { service: service.createPurchasingService(deps), getActor }); + await fastify.ready(); + const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + + return { + baseUrl, + applySeed: async (seed: RulesSeed) => { + await executeSql(connectionUri, `TRUNCATE TABLE "purchase_requests", "audit_entries" RESTART IDENTITY;`); + for (const r of seed.purchaseRequests) { + await executeSql( + connectionUri, + `INSERT INTO "purchase_requests" ("id","title","amount_cents","limit_cents","status") VALUES (${r.id}, ${str(r.title)}, ${r.amountCents}, ${ + r.limitCents === null ? "NULL" : r.limitCents + }, ${str(r.status)})`, + ); + } + await executeSql(connectionUri, `SELECT setval(pg_get_serial_sequence('purchase_requests','id'), (SELECT MAX("id") FROM "purchase_requests"));`); + }, + close: async () => { + await fastify.close(); + await dbMod.pool.end(); + rmSync(tmp, { recursive: true, force: true }); + }, + }; +} + +function str(v: string): string { + return `'${v.replace(/'/g, "''")}'`; +} diff --git a/server/typescript/packages/integration-tests/src/load-metadata.ts b/server/typescript/packages/integration-tests/src/load-metadata.ts index d321f8d610..4798a5c82c 100644 --- a/server/typescript/packages/integration-tests/src/load-metadata.ts +++ b/server/typescript/packages/integration-tests/src/load-metadata.ts @@ -6,7 +6,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { pathToFileURL } from "node:url"; import { DEFAULT_WIRE_FORMAT, loadDirectory, loadString, loadUris, type MetaRoot, type WireFormat } from "@metaobjectsdev/metadata"; -import { ConfigSchema, apiPaginationFromConfig, apiUnknownFieldsFromConfig, enumDefaultsFromConfig, physicalNamingFromConfig, wireFormatFromConfig, type Config } from "@metaobjectsdev/sdk"; +import { ConfigSchema, apiPaginationFromConfig, apiUnknownFieldsFromConfig, enumDefaultsFromConfig, physicalNamingFromConfig, rulesSettingsFromConfig, wireFormatFromConfig, type Config } from "@metaobjectsdev/sdk"; /** * ADR-0058 — set `root`'s physical naming, wire format and enum defaults from the nearest `.metaobjects/config.json` at or @@ -29,6 +29,9 @@ export function applyNearestNaming(root: MetaRoot, startDir: string): MetaRoot { if (page !== undefined) root.apiPagination = page; const unknownFields = apiUnknownFieldsFromConfig(config); if (unknownFields !== undefined) root.apiUnknownFields = unknownFields; + // ADR-0066 §5's four settings: the service generator reads `rules.lifecycle.create` and + // `rules.lifecycle.commands` from the root, as a project-aware load sets them. + root.rulesSettings = rulesSettingsFromConfig(config); return root; } diff --git a/server/typescript/packages/integration-tests/src/paths.ts b/server/typescript/packages/integration-tests/src/paths.ts index 9164920c2b..16718a327c 100644 --- a/server/typescript/packages/integration-tests/src/paths.ts +++ b/server/typescript/packages/integration-tests/src/paths.ts @@ -54,6 +54,9 @@ export const API_CONTRACT_SECRET_FIELDS_TPH_SCENARIOS_DIR = resolve(API_CONTRACT // Enum @default applied on create subcorpus (GENERATED lane only, every port). export const API_CONTRACT_ENUM_DEFAULT_DIR = resolve(API_CONTRACT_DIR, "enum-default"); export const API_CONTRACT_ENUM_DEFAULT_SCENARIOS_DIR = resolve(API_CONTRACT_ENUM_DEFAULT_DIR, "scenarios"); +export const API_CONTRACT_RULES_DIR = resolve(API_CONTRACT_DIR, "rules"); +export const API_CONTRACT_RULES_SCENARIOS_DIR = resolve(API_CONTRACT_RULES_DIR, "scenarios"); +export const API_CONTRACT_RULES_SETTINGS_DIR = resolve(API_CONTRACT_RULES_DIR, "settings"); // `api` settings subcorpus (GENERATED lane only): `api.pagination` and `api.unknownFields: drop`. export const API_CONTRACT_API_SETTINGS_DIR = resolve(API_CONTRACT_DIR, "api-settings"); diff --git a/server/typescript/packages/integration-tests/test/api-contract-rules.test.ts b/server/typescript/packages/integration-tests/test/api-contract-rules.test.ts new file mode 100644 index 0000000000..629d76de54 --- /dev/null +++ b/server/typescript/packages/integration-tests/test/api-contract-rules.test.ts @@ -0,0 +1,46 @@ +// rules api-contract conformance (GENERATED service lane). +// +// Drives fixtures/api-contract-conformance/rules/ over HTTP against the GENERATED service of a +// model with a lifecycle, declared operations and permission points (ADR-0066), behind its +// emitted Fastify transport (ADR-0067 layers 4 and 5). The corpus's scenarios run under the +// default settings; each `settings//` directory runs its own scenarios with its own +// `.metaobjects/config.json` over the same model. Generated lane only — see the corpus README. +// One Postgres testcontainer per scenario (shared per file in the package layout). + +import { describe, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { API_CONTRACT_RULES_DIR, API_CONTRACT_RULES_SCENARIOS_DIR, API_CONTRACT_RULES_SETTINGS_DIR } from "../src/paths.ts"; +import { loadScenarios, runScenario } from "../src/api-contract-scenario.ts"; +import { OUTPUT_LAYOUTS, postgresFor } from "../src/output-layout.ts"; +import { startGeneratedRulesServer, type GeneratedRulesServerHandle, type RulesSeed } from "../src/api-contract-rules-generated-server.ts"; + +const SEED = JSON.parse(readFileSync(join(API_CONTRACT_RULES_DIR, "seed.json"), "utf8")) as RulesSeed; +const META_PATH = join(API_CONTRACT_RULES_DIR, "meta.json"); + +const runs: Array<{ label: string; configDir: string; scenariosDir: string }> = [ + { label: "default settings", configDir: API_CONTRACT_RULES_DIR, scenariosDir: API_CONTRACT_RULES_SCENARIOS_DIR }, + ...readdirSync(API_CONTRACT_RULES_SETTINGS_DIR) + .sort() + .map((v) => ({ label: `settings/${v}`, configDir: join(API_CONTRACT_RULES_SETTINGS_DIR, v), scenariosDir: join(API_CONTRACT_RULES_SETTINGS_DIR, v, "scenarios") })), +]; + +for (const layout of OUTPUT_LAYOUTS) describe(`api contract rules — GENERATED service lane [${layout}]`, () => { + const startDb = postgresFor(layout); + for (const run of runs) { + for (const scenario of loadScenarios(run.scenariosDir)) { + test(`${run.label}: ${scenario.name}`, async () => { + const pg = await startDb(); + let server: GeneratedRulesServerHandle | null = null; + try { + server = await startGeneratedRulesServer(pg.connectionUri, META_PATH, run.configDir, layout); + await server.applySeed(SEED); + await runScenario(scenario, server.baseUrl); + } finally { + if (server) await server.close(); + await pg.stop(); + } + }, { timeout: 60_000 }); + } + } +}); diff --git a/server/typescript/packages/integration-tests/test/service-compile.test.ts b/server/typescript/packages/integration-tests/test/service-compile.test.ts index 0108b715d8..8f3aa3fe41 100644 --- a/server/typescript/packages/integration-tests/test/service-compile.test.ts +++ b/server/typescript/packages/integration-tests/test/service-compile.test.ts @@ -1,4 +1,5 @@ -// The service tier's compile gate (ADR-0067 layers 4 and 5): the shared fitness corpus, generated +// The service tier's compile gate (ADR-0067 layers 4 and 5): the shared fitness corpus and the +// api-contract rules corpus, each generated // with the entity module, the contract types, the service and its Fastify transport, compiled with // the real compiler in both profiles, every dialect and both output layouts. // @@ -27,9 +28,13 @@ mkdirSync(GEN_TMP, { recursive: true }); const CORPUS = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "..", "fixtures", "persistence-conformance", "canonical", "meta.fitness.json"); -async function loadCorpus(): Promise { - const result = await loadUris([pathToFileURL(CORPUS).href]); - if (result.errors.length > 0) throw new Error(`${CORPUS} did not load: ${result.errors.map((e) => e.message).join("; ")}`); +// The rules corpus (ADR-0066): a lifecycle with conditions, derived and declared commands, a +// query, permission points and declared errors, which the fitness corpus does not carry. +const RULES = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "..", "fixtures", "api-contract-conformance", "rules", "meta.json"); + +async function loadCorpus(path: string = CORPUS): Promise { + const result = await loadUris([pathToFileURL(path).href]); + if (result.errors.length > 0) throw new Error(`${path} did not load: ${result.errors.map((e) => e.message).join("; ")}`); return result.root; } @@ -68,12 +73,22 @@ function emittedTs(dir: string): string[] { return out.sort(); } -describe("service compile gate — the shared fitness corpus", () => { +const CORPORA = [ + { label: "the shared fitness corpus", path: CORPUS, pkg: "fitness", present: ["fitness/service/createProgram.ts"] }, + { + label: "the rules corpus", + path: RULES, + pkg: "acme/purchasing", + present: ["acme/purchasing/service/submitPurchaseRequest.ts", "acme/purchasing/service/decide.ts", "acme/purchasing/service/requestTotals.ts"], + }, +] as const; + +for (const corpus of CORPORA) describe(`service compile gate — ${corpus.label}`, () => { for (const layout of ["flat", "package"] as const satisfies readonly OutputLayout[]) { for (const dialect of ["postgres", "sqlite", "mysql"] as const) { for (const [profile, options] of PROFILES) { test(`${layout} / ${dialect} [${profile}]: the service and its transport compile with zero diagnostics`, async () => { - const root = await loadCorpus(); + const root = await loadCorpus(corpus.path); const dir = mkdtempSync(join(GEN_TMP, `service-compile-${layout}-${dialect}-`)); try { await runGen({ @@ -91,9 +106,9 @@ describe("service compile gate — the shared fitness corpus", () => { const files = emittedTs(dir); const rel = files.map((f) => f.slice(dir.length + 1).split("\\").join("/")); // The tier is present by name, so the gate cannot pass on an empty service. - expect(rel).toContain("fitness/service/index.ts"); - expect(rel).toContain("fitness/service/createProgram.ts"); - expect(rel).toContain("fitness/transport/fastify.ts"); + expect(rel).toContain(`${corpus.pkg}/service/index.ts`); + for (const p of corpus.present) expect(rel).toContain(p); + expect(rel).toContain(`${corpus.pkg}/transport/fastify.ts`); writeFileSync(join(dir, "package.json"), JSON.stringify({ type: "module" })); const program = ts.createProgram(files, { ...options, noEmit: true }); const diagnostics = ts.getPreEmitDiagnostics(program).map((d) => { diff --git a/server/typescript/packages/runtime-ts/src/service/index.ts b/server/typescript/packages/runtime-ts/src/service/index.ts index 47953c1ab3..722638806c 100644 --- a/server/typescript/packages/runtime-ts/src/service/index.ts +++ b/server/typescript/packages/runtime-ts/src/service/index.ts @@ -27,6 +27,8 @@ export type { FilterAllowlist, SortAllowlist } from "../drizzle-fastify/filter-a // The wire mappers a generated service index builds its `ToWire` from: no framework in them. export { timestampWire } from "../timestamp-wire.js"; export { withWire } from "../wire-format.js"; +// The business-rules mechanics: permission point, state check, guarded update, hook contexts. +export * from "./rules.js"; // biome-ignore lint/suspicious/noExplicitAny: the adopter's Drizzle database, table or transaction type Drizzle = any; @@ -70,8 +72,13 @@ export function notFound(): never { refuse({ error: "not_found" }, 404); } -/** The options every operation takes. */ -export interface OpOptions { +/** The options every operation takes. `A` is the app's actor type (ADR-0067 §7). */ +export interface OpOptions { + /** + * Who the operation runs for. The shell never looks inside it: it passes it to the policy and to + * the hooks, bodies and event hook. A `@public` operation and the derived CRUD verbs run without one. + */ + readonly actor?: A | undefined; /** * A transaction the caller opened, for a job that runs several operations atomically. A write * runs in a savepoint inside it, so a refusal undoes this operation's writes and leaves the diff --git a/server/typescript/packages/runtime-ts/src/service/rules.ts b/server/typescript/packages/runtime-ts/src/service/rules.ts new file mode 100644 index 0000000000..d2874a44fc --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/service/rules.ts @@ -0,0 +1,307 @@ +// The business-rules mechanics a generated service shell calls (ADR-0066 §6, ADR-0067 §4 and §7): +// the permission point, the state check, the guarded update and its re-read, and the contexts a +// hand-written body, hook or event handler receives. +// +// The generated shell decides WHAT: which permission a point asks about, which states a move may +// start from, which condition guards it. This module is HOW, on Drizzle, in the order ADR-0066 §6 +// holds every shell to: +// +// 1. load the row: 404 `not_found` when it is absent (`loadForWrite`, ./index.ts); +// 2. the permission point: 403 `forbidden` when the policy refuses (`checkPermission`); +// 3. the row's state is in the `@from` of a move the operation may make: 409 `invalid_transition` +// (`checkState`); +// 4. the hand-written body, when the operation has one (generated); +// 5. the guarded update, re-read once when it matches no row: 409 `invalid_transition` or +// `transition_condition_failed`, or 404 when the row is gone (`makeTransition`); +// 6. all of it, and the event hook, in one transaction (`inWriteTransaction`). +// +// And a lifecycle field on the generic write path is the shell's to move: 409 `state_managed` +// (`checkStateManaged`). + +import { + BUSINESS_ERROR_CODE_PATTERN, + 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, + RESERVED_ERROR_CODES, + type ExprNode, +} from "@metaobjectsdev/metadata"; +import { and, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, or, sql, type SQL } from "drizzle-orm"; +import { supportsReturning, type SqlDialect } from "../sql-dialect.js"; +import { extractRowCount } from "../drizzle-fastify/util.js"; +// Called at run time only, so the cycle with ./index.ts (which re-exports this module) is harmless. +import { notFound, readOne, refuse, REFUSAL_STATUS, type ServiceErrorBody } from "./index.js"; + +// biome-ignore lint/suspicious/noExplicitAny: the adopter's Drizzle database, table or transaction +type Drizzle = any; + +/** The wire code of a policy refusal (ADR-0066 §6 step 2). */ +export const FORBIDDEN = "forbidden"; +/** The row's state is not one a move the operation may make starts from (§6 steps 3 and 5). */ +export const INVALID_TRANSITION = "invalid_transition"; +/** The state allows the move and its `@condition` does not hold (§6 step 5). */ +export const TRANSITION_CONDITION_FAILED = "transition_condition_failed"; +/** A lifecycle field written through the generic create or update path (§6 step 7). */ +export const STATE_MANAGED = "state_managed"; + +const RESERVED: ReadonlySet = new Set(RESERVED_ERROR_CODES); + +/** + * Refuse with a business code a body, hook or event handler chose: answered 409 with the code and + * the details, and the transaction rolls back. A code the shell or the API contract answers itself + * (ADR-0066 O5), or one that is not lower snake case, is a programming error, thrown as such, so a + * client never reads a business refusal as the shell's own. + */ +export function refuseBusiness(code: string, details: Readonly> = {}): never { + if (RESERVED.has(code) || !BUSINESS_ERROR_CODE_PATTERN.test(code)) { + throw new Error(`refuse("${code}"): a business refusal takes a lower snake case code the shell and the API contract do not answer themselves`); + } + refuse({ ...details, error: code } as ServiceErrorBody, REFUSAL_STATUS); +} + +/** What a hand-written hook or event handler receives beside its own arguments. */ +export interface HookContext { + /** The transaction the write runs in. What the handler writes on it commits or rolls back with it. */ + readonly tx: Tx; + /** The actor the operation was called for, passed through untouched (ADR-0067 §7). */ + readonly actor: A | undefined; + /** Refuse the operation with a business code: 409, and everything rolls back. */ + refuse(code: string, details?: Readonly>): never; +} + +/** What a hand-written operation body receives (ADR-0066 §6 step 4). `E` is the operation's `@errors`. */ +export interface BodyContext { + /** The transaction of a command, or the read scope of a query. */ + readonly tx: Tx; + readonly actor: A | undefined; + /** Refuse with one of the operation's declared errors: 409, and everything rolls back. */ + refuse(code: E, details?: Readonly>): never; +} + +/** The context of a hook, a body or an event handler running on `tx` for `actor`. */ +export function handlerContext(tx: Tx, actor: A | undefined): HookContext & BodyContext { + return { tx, actor, refuse: refuseBusiness }; +} + +/** One write the package's event hook is told about, inside the write's transaction (ADR-0066 §7). */ +export type WriteEvent = + | { readonly kind: "create"; readonly entity: string; readonly key: unknown; readonly row: unknown; readonly actor: A | undefined; readonly at: Date } + | { + readonly kind: "update"; + readonly entity: string; + readonly key: unknown; + readonly row: unknown; + readonly previous: unknown; + readonly actor: A | undefined; + readonly at: Date; + } + | { readonly kind: "delete"; readonly entity: string; readonly key: unknown; readonly row: unknown; readonly actor: A | undefined; readonly at: Date } + | { + readonly kind: "transition"; + readonly entity: string; + readonly key: unknown; + /** The lifecycle's field. */ + readonly lifecycle: string; + readonly transition: string; + readonly from: string; + readonly to: string; + /** The command that made it: the transition's own derived command, or a declared one. */ + readonly operation: string; + readonly actor: A | undefined; + readonly at: Date; + } + | { + readonly kind: "command"; + /** A declared command whose body made no move. */ + readonly operation: string; + readonly entity: string | undefined; + readonly key: unknown; + readonly actor: A | undefined; + readonly at: Date; + }; + +/** The package's write-event hook: an outbox, a history table or an audit log is written here. */ +export interface WriteEvents { + onWrite(event: WriteEvent, ctx: HookContext): void | Promise; +} + +/** Tell `events` (when the app supplied any) about `event`, on the write's transaction. */ +export async function emitWrite(events: WriteEvents | undefined, event: WriteEvent, tx: Tx): Promise { + if (events !== undefined) await events.onWrite(event, handlerContext(tx, event.actor)); +} + +/** A policy: whether `actor` may pass the permission point named `permission` (ADR-0066 §1). */ +export interface Policy

{ + allows(permission: P, actor: A | undefined, row: unknown, input: unknown, tx: Tx): boolean | Promise; +} + +/** The permission point (ADR-0066 §6 step 2): 403 `forbidden` unless the policy allows it. */ +export async function checkPermission

( + policy: Policy, + permission: P, + actor: A | undefined, + row: unknown, + input: unknown, + tx: Tx, +): Promise { + if (!(await policy.allows(permission, actor, row, input, tx))) refuse({ error: FORBIDDEN }, 403); +} + +/** A move a lifecycle may make: its field, the states it starts from and the state it ends in. */ +export interface TransitionSpec { + readonly name: string; + /** The lifecycle's field, as the Drizzle table names its column. */ + readonly field: string; + readonly from: readonly string[]; + readonly to: string; + /** The `@condition`, an attr.expression CHECK-subset node over the entity's fields. */ + readonly condition?: ExprNode | undefined; +} + +/** Whether `row` is in a state `t` starts from. */ +export function inFromState(row: Readonly>, t: TransitionSpec): boolean { + return t.from.includes(String(row[t.field])); +} + +/** The state check (ADR-0066 §6 step 3): 409 `invalid_transition` unless one of `moves` starts from the row's state. */ +export function checkState(row: Readonly>, moves: readonly TransitionSpec[]): void { + if (!moves.some((t) => inFromState(row, t))) refuse({ error: INVALID_TRANSITION }, REFUSAL_STATUS); +} + +/** + * The guarded update (ADR-0066 §6 step 5), one statement: + * `UPDATE ... SET = :to WHERE AND IN (:from) [AND ]`. + * Answers the row as written. When it matches no row the row is read once more: gone is 404, + * another state is 409 `invalid_transition`, and the state it starts from with a condition that + * does not hold is 409 `transition_condition_failed`. + */ +export async function makeTransition( + tx: Drizzle, + table: Drizzle, + key: SQL, + t: TransitionSpec, + dialect: SqlDialect, +): Promise> { + const guards: SQL[] = [key, inArray(table[t.field], [...t.from])]; + if (t.condition !== undefined) guards.push(conditionSql(table, t.condition)); + const where = and(...guards)!; + const set = { [t.field]: t.to }; + let written: Record | undefined; + if (supportsReturning(dialect)) { + written = ((await tx.update(table).set(set).where(where).returning()) as Record[])[0]; + } else if (extractRowCount(await tx.update(table).set(set).where(where)) > 0) { + // MySQL: no RETURNING. mysql2 reports matched rows (FOUND_ROWS), so a self-transition counts. + written = await readOne(tx, table, key); + } + if (written !== undefined) return written; + const now = await readOne(tx, table, key); + if (now === undefined) notFound(); + refuse({ error: inFromState(now, t) ? TRANSITION_CONDITION_FAILED : INVALID_TRANSITION }, REFUSAL_STATUS); +} + +/** + * The generic write path may not move a lifecycle (ADR-0066 §6 step 7): a lifecycle field in + * `values` that differs from `current` is refused 409 `state_managed`, and one equal to it (a + * client echoing the read model) is dropped. On a create `current` holds the initial states when + * `rules.lifecycle.create` is `initial` (the default); under `any` the generator passes none. + */ +export function checkStateManaged(values: Record, current: Readonly>, fields: readonly string[]): void { + for (const f of fields) { + if (!(f in values) || values[f] === undefined) continue; + if (String(values[f]) !== String(current[f])) refuse({ error: STATE_MANAGED }, REFUSAL_STATUS); + delete values[f]; + } +} + +/** + * A create starts each lifecycle in its initial state under `rules.lifecycle.create: initial` + * (the default, ADR-0066 §5): a state the input names is refused 409 `state_managed` unless it is + * the initial one, and an omitted one is the initial one. Under `any` the generator skips this. + */ +export function checkCreateState(values: Record, initials: Readonly>): void { + for (const [f, initial] of Object.entries(initials)) { + if (values[f] === undefined || values[f] === null) values[f] = initial; + else if (String(values[f]) !== initial) refuse({ error: STATE_MANAGED }, REFUSAL_STATUS); + } +} + +type Node = Record; +type Operand = SQL | Drizzle; + +/** + * `node`, a `@condition` (attr.expression's CHECK subset: fields, literals, the six comparisons, + * the null tests, and / or / not, coalesce), as a Drizzle condition over `table`'s columns. A + * literal compared with a field is bound through that field's column, so it is written in the form + * the column stores (an int-backed enum's member is its integer). A node outside the subset is + * refused, never dropped: a guard that loses its condition makes a move the model forbids. + */ +export function conditionSql(table: Drizzle, node: ExprNode): SQL { + const n = node as Node; + const op = n["op"]; + if (typeof op === "string" && COMPARE.has(op)) { + const left = operand(table, n["left"], partnerColumn(table, n["right"])); + const right = operand(table, n["right"], partnerColumn(table, n["left"])); + return COMPARE.get(op)!(left, right); + } + if (op === FILTER_OP_IS_NULL) return isNull(operand(table, n["arg"], undefined)); + if (op === EXPR_OP_IS_NOT_NULL) return isNotNull(operand(table, n["arg"], undefined)); + if (op === EXPR_OP_NOT) return not(conditionSql(table, n["arg"] as ExprNode)); + if (op === FILTER_COMPOSE_AND || op === FILTER_COMPOSE_OR) { + const parts = (n["args"] as ExprNode[]).map((a) => conditionSql(table, a)); + return (op === FILTER_COMPOSE_AND ? and(...parts) : or(...parts))!; + } + throw new Error(`@condition: ${JSON.stringify(node)} is not a condition the guarded update can apply`); +} + +const COMPARE = new Map SQL>([ + [FILTER_OP_EQ, (l, r) => eq(l, r)], + [FILTER_OP_NE, (l, r) => ne(l, r)], + [FILTER_OP_GT, (l, r) => gt(l, r)], + [FILTER_OP_GTE, (l, r) => gte(l, r)], + [FILTER_OP_LT, (l, r) => lt(l, r)], + [FILTER_OP_LTE, (l, r) => lte(l, r)], +]); + +function column(table: Drizzle, field: string): Drizzle { + const c = table[field]; + if (c === undefined) throw new Error(`@condition names "${field}", which is not a column of the table`); + return c; +} + +/** The column a literal compared with `node` is bound through: `node`'s field, or a coalesce's first. */ +function partnerColumn(table: Drizzle, node: unknown): Drizzle | undefined { + const n = (node ?? {}) as Node; + if (typeof n["field"] === "string") return column(table, n["field"]); + if (n["fn"] === EXPR_FN_COALESCE && Array.isArray(n["args"])) { + for (const a of n["args"] as unknown[]) { + const c = partnerColumn(table, a); + if (c !== undefined) return c; + } + } + return undefined; +} + +function operand(table: Drizzle, x: unknown, partner: Drizzle | undefined): Operand { + const n = (x ?? {}) as Node; + if (typeof n["field"] === "string") return column(table, n["field"]); + if ("value" in n) { + const v = n["value"]; + return v === null ? sql`null` : partner === undefined ? sql.param(v) : sql.param(v, partner); + } + 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 = partnerColumn(table, n) ?? partner; + const args = (n["args"] as unknown[]).map((a) => operand(table, a, own)); + return sql`coalesce(${sql.join(args, sql`, `)})`; + } + throw new Error(`@condition: ${JSON.stringify(x)} is not an operand the guarded update can apply`); +} diff --git a/server/typescript/packages/runtime-ts/test/service-rules.test.ts b/server/typescript/packages/runtime-ts/test/service-rules.test.ts new file mode 100644 index 0000000000..f06be38c04 --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/service-rules.test.ts @@ -0,0 +1,173 @@ +// The business-rules mechanics a generated service shell calls (ADR-0066 §6): the permission +// point, the state check, the guarded update and its re-read, the state-managed refusal and the +// business refusal. libsql on a scratch file, as in service.test.ts. +import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { createClient, type Client } from "@libsql/client"; +import { drizzle } from "drizzle-orm/libsql"; +import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + checkCreateState, + checkPermission, + checkState, + checkStateManaged, + emitWrite, + inWriteTransaction, + keyCondition, + makeTransition, + refuseBusiness, + type OpResult, + type TransitionSpec, + type WriteEvent, +} from "../src/service/index.js"; + +const requests = sqliteTable("requests", { + id: integer("id").primaryKey(), + status: text("status").notNull(), + amount: integer("amount"), + limitAmount: integer("limit_amount"), +}); + +let dir: string; +let client: Client; +let db: ReturnType; + +beforeAll(async () => { + dir = mkdtempSync(join(process.env.DEV_SCRATCH ?? tmpdir(), "runtime-ts-service-rules-")); + client = createClient({ url: `file:${join(dir, "rules.db")}` }); + db = drizzle(client); + await client.execute("CREATE TABLE requests (id INTEGER PRIMARY KEY, status TEXT NOT NULL, amount INTEGER, limit_amount INTEGER)"); +}); + +afterAll(() => { + client.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +beforeEach(async () => { + await client.execute("DELETE FROM requests"); + await client.execute( + "INSERT INTO requests (id, status, amount, limit_amount) VALUES (1, 'submitted', 50, 100), (2, 'submitted', 500, 100), (3, 'draft', 50, NULL)", + ); +}); + +const status = async (id: number) => (await client.execute(`SELECT status FROM requests WHERE id = ${id}`)).rows[0]?.["status"]; + +function failed(r: OpResult): { status: number; error: Record } { + if (r.ok) throw new Error(`expected a failure, got ${JSON.stringify(r.value)}`); + return r; +} + +// approve: submitted → approved, when amount <= coalesce(limitAmount, 0) and not (amount is null). +const approve: TransitionSpec = { + name: "approve", + field: "status", + from: ["submitted"], + to: "approved", + condition: { + op: "and", + args: [ + { op: "lte", left: { field: "amount" }, right: { fn: "coalesce", args: [{ field: "limitAmount" }, { value: 0 }] } }, + { op: "not", arg: { op: "isNull", arg: { field: "amount" } } }, + ], + }, +}; + +const move = (id: number, t: TransitionSpec) => + inWriteTransaction(db, undefined, (tx) => makeTransition(tx, requests, keyCondition(requests, "id", id), t, "sqlite")); + +describe("makeTransition — the guarded update", () => { + test("a row in a from state whose condition holds moves, and the written row is answered", async () => { + const r = await move(1, approve); + expect(r).toEqual({ ok: true, value: { id: 1, status: "approved", amount: 50, limitAmount: 100 } }); + }); + + test("a failing condition is transition_condition_failed, and nothing is written", async () => { + expect(failed(await move(2, approve))).toEqual({ ok: false, status: 409, error: { error: "transition_condition_failed" } } as never); + expect(await status(2)).toBe("submitted"); + }); + + test("another state is invalid_transition", async () => { + expect(failed(await move(3, approve)).error).toEqual({ error: "invalid_transition" }); + }); + + test("the second of two moves out of one state is invalid_transition", async () => { + expect((await move(1, approve)).ok).toBe(true); + expect(failed(await move(1, approve)).error).toEqual({ error: "invalid_transition" }); + }); + + test("a missing row is not_found", async () => { + expect(failed(await move(9, approve)).status).toBe(404); + }); + + test("a self-transition matches its row", async () => { + const touch: TransitionSpec = { name: "touch", field: "status", from: ["submitted"], to: "submitted" }; + expect((await move(1, touch)).ok).toBe(true); + }); +}); + +describe("the checks before the move", () => { + test("checkState refuses a row no move starts from", async () => { + const r = await inWriteTransaction(db, undefined, async () => checkState({ status: "draft" }, [approve])); + expect(failed(r).error).toEqual({ error: "invalid_transition" }); + expect(() => checkState({ status: "submitted" }, [approve])).not.toThrow(); + }); + + test("checkPermission answers 403 forbidden when the policy refuses, with the name, actor, row and input", async () => { + const seen: unknown[] = []; + const policy = { allows: (p: string, a: unknown, row: unknown, input: unknown) => (seen.push([p, a, row, input]), a === "ok") }; + const r = await inWriteTransaction(db, undefined, (tx) => checkPermission(policy, "shop.approve", "no", { id: 1 }, { x: 1 }, tx)); + expect(failed(r)).toEqual({ ok: false, status: 403, error: { error: "forbidden" } } as never); + expect(seen).toEqual([["shop.approve", "no", { id: 1 }, { x: 1 }]]); + }); + + test("checkStateManaged refuses a moved lifecycle field and drops an echoed one", async () => { + const echoed: Record = { status: "draft", title: "t" }; + checkStateManaged(echoed, { status: "draft" }, ["status"]); + expect(echoed).toEqual({ title: "t" }); + const r = await inWriteTransaction(db, undefined, async () => checkStateManaged({ status: "approved" }, { status: "draft" }, ["status"])); + expect(failed(r).error).toEqual({ error: "state_managed" }); + }); +}); + +describe("refusals and events", () => { + test("a business refusal rolls back and answers 409 with its code and details", async () => { + const r = await inWriteTransaction(db, undefined, async (tx) => { + await makeTransition(tx, requests, keyCondition(requests, "id", 1), approve, "sqlite"); + refuseBusiness("over_budget", { limit: 100 }); + }); + expect(failed(r)).toEqual({ ok: false, status: 409, error: { limit: 100, error: "over_budget" } } as never); + expect(await status(1)).toBe("submitted"); + }); + + test("a reserved or malformed code is a programming error, not a refusal", () => { + expect(() => refuseBusiness("forbidden")).toThrow(/business refusal/); + expect(() => refuseBusiness("Over-Budget")).toThrow(/business refusal/); + }); + + test("an event handler runs on the write's transaction, and its refusal undoes the write", async () => { + const events = { + onWrite: (e: WriteEvent, ctx: { refuse(code: string): never }) => { + if (e.kind === "transition" && e.actor === "auditor-down") ctx.refuse("audit_unavailable"); + }, + }; + const r = await inWriteTransaction(db, undefined, async (tx) => { + await makeTransition(tx, requests, keyCondition(requests, "id", 1), approve, "sqlite"); + await emitWrite(events, { kind: "transition", entity: "Request", key: 1, lifecycle: "status", transition: "approve", from: "submitted", to: "approved", operation: "approveRequest", actor: "auditor-down", at: new Date() }, tx); + }); + expect(failed(r).error).toEqual({ error: "audit_unavailable" }); + expect(await status(1)).toBe("submitted"); + }); +}); + +describe("checkCreateState", () => { + test("an omitted state is the initial one, the initial one is kept, another is state_managed", async () => { + const omitted: Record = { title: "t" }; + checkCreateState(omitted, { status: "draft" }); + expect(omitted).toEqual({ title: "t", status: "draft" }); + const r = await inWriteTransaction(db, undefined, async () => checkCreateState({ status: "approved" }, { status: "draft" })); + expect(failed(r).error).toEqual({ error: "state_managed" }); + }); +}); 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 f19a503537..32c8031cd3 100644 --- a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md +++ b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md @@ -271,13 +271,16 @@ A model that declares no operation and no transition gets no rules diagnostics, line and no gate row. The settings `rules.permissions.names`, `rules.lifecycle.create`, `rules.lifecycle.commands` and `verify.lifecycle.unreachable` are read from `.metaobjects/config.json` by every port. When a key is absent, the setting takes today's -behaviour. `rules.lifecycle.create` is read and validated and has **no effect yet**: the shells -will be the first to act on it, and the documentation says so until they do. +behaviour. The service generators are what act on `rules.lifecycle.create` and +`rules.lifecycle.commands` (TypeScript first; the shared API tests' `rules/` corpus pins both), and +`verify` acts on the other two. ### 6. What the enforcing shell will guarantee, for every transition -The shells are later work: service generators that an app adds (ADR-0067). A project that declares -a lifecycle and wires no service generator will be told so by `verify`, as an advisory, once that check lands; today's flat +The shells are the service generators an app adds (ADR-0067). TypeScript's `service` generator is +the first, held to the shared API tests' `fixtures/api-contract-conformance/rules/` corpus; each +other port's lands in its own 1.3.0 service work. A project that declares a lifecycle and wires no +service generator will be told so by `verify`, as an advisory, once that check lands; the flat routes enforce nothing. This is what the shells are held to: 1. Load the row: 404 when it is absent. diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md index dce592f46c..c182df7e3f 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -148,11 +148,13 @@ These calls are recorded here: It is still not meant to be extended, and its generated header says so. - **ADR-0066's four settings stay** (`rules.permissions.names`, `rules.lifecycle.commands`, `rules.lifecycle.create` and `verify.lifecycle.unreachable`). They decide what the model derives, - which every port must agree on, so they are not generator options. The service generators read - `rules.lifecycle.commands` and `rules.lifecycle.create`; until they land, `rules.lifecycle.create` - is read and validated and has no effect (ADR-0066 §5). What reads each key: `rules.permissions.names` - and `verify.lifecycle.unreachable` are read by the `verify` rules gate today, and the service - generators will read `rules.lifecycle.commands` (the derived commands) and `rules.lifecycle.create`. + which every port must agree on, so they are not generator options. What reads each key: + `rules.permissions.names` and `verify.lifecycle.unreachable` are read by the `verify` rules gate, + and the service generators read `rules.lifecycle.commands` (the derived commands), + `rules.lifecycle.create` (whether a create may start outside the initial state) and + `rules.permissions.names` (`require` refuses to generate a point with no `@permission`). The + TypeScript service is the first to read them; a port's service that has not landed has nothing + to act on. ### 5. Choosing layers From b6da79f0e85df307c25a80b4f49fcb8531153826 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 05:21:07 -0500 Subject: [PATCH 3/4] no-mistakes(document): Sync service-layer docs with TS rules run --- .claude/rules/cross-language-porting.md | 2 +- docs/features/own-your-codegen.md | 2 +- .../ADR-0066-business-rules-operations-and-lifecycles.md | 8 +++++--- spec/decisions/ADR-0067-layering-and-the-service-seam.md | 7 ++++--- spec/decisions/README.md | 2 +- spec/roadmap.md | 2 +- 6 files changed, 13 insertions(+), 10 deletions(-) diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index 182197d49e..22bafb0241 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -26,7 +26,7 @@ Preserve the following contracts exactly across all language ports: - Relationship subtypes: `association`, `aggregation`, `composition`. Cardinality via `@cardinality: one|many`; target via `@objectRef`. **M:N (FR-018) slim vocabulary:** `@cardinality: "many"` + `@objectRef` (target) + `@through` (the junction/through entity — a third entity that MUST declare two `identity.reference` children, one per FK side). The relationship's FK fields are **derived** from those references (the `identity.reference` SSOT for FK direction), never restated. `@sourceRefField` (optional) disambiguates a *directed* self-join by naming the source-side FK field on the junction (the other reference is the target side); on a `@cardinality: one` relationship it instead names which of several `identity.reference` nodes onto the same target this relationship navigates, short-circuiting the unique-candidate/`@sourceRefField`/name-pairing ladder (#368, [ADR-0029](spec/decisions/ADR-0029-entity-child-extends-and-via-inference.md) Amendment 1) — an unresolvable 1:N reference set is `ERR_INVALID_RELATIONSHIP` at load. `@symmetric` (optional boolean) marks an *undirected* self-join (union-on-read) — valid only when `@objectRef` == the declaring entity, and mutually exclusive with `@sourceRefField`. The pre-FR-018 `@joinEntity`/`@joinFields` attrs are REMOVED. Validation errors: symmetric-on-hetero / symmetric+sourceRefField → `ERR_BAD_ATTR_VALUE`; junction-missing-two-references / sourceRefField-not-matching / M:N-attr-on-1:N / **junction-unpairable** → `ERR_INVALID_RELATIONSHIP`. **Unpairable means the junction declares its two references but neither resolves to the navigating entity, or neither to the `@objectRef` target** — declaring two references is NOT enough, and the loader now checks WHAT they point at (owner ruling 2026-09-20). It does so by running the real FK derivation and converting its failure, never a parallel re-implementation, so the loader and the derivation cannot drift; scope mirrors codegen's own iteration exactly — every CONCRETE, non-projection object crossed with its EFFECTIVE relationships, NOT deduped by declaration, because pairing is a property of the navigating entity and an inherited M:N can pair from one subtype and not another. Before the ruling this loaded clean and then diverged: TS and C# warned and emitted no traversal route (a silent 404), while Java, Kotlin and Python failed the build. Gated by `fixtures/conformance/error-relationship-m2m-junction-unpairable/`. - Index subtypes: `index.lookup` (non-unique retrieval index; uniqueness is encoded in the **type**: `identity.secondary` = unique alternate key, `index.lookup` = non-unique; `@unique` is REMOVED from `identity.secondary` — `ERR_UNKNOWN_ATTR` on any legacy `@unique`). RDB-physical escapes `@using`/`@expr`/`@where`/`@orders` are registered by the db provider on **both** `identity.secondary` and `index.lookup`. `index.fulltext` / `index.vector` / `index.spatial` are reserved on the subtype axis — documented, NOT registered (YAGNI + 1.0 vocab freeze). See [ADR-0040](spec/decisions/ADR-0040-index-type-and-secondary-key-purity.md). - Layout subtypes: `dataGrid` -- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#, and the TypeScript `service` and `service-routes` for derived CRUD so far). +- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service` and `service-routes` for derived CRUD, transitions, declared operations and the rules' checks). - Transition subtypes: `transition.action` (a child of `field.enum` on an `object.entity`: `@from`, `@to`, `@condition` in the validators' grammar, `@permission`, `@public`); `transition.base` is the abstract root and `transition.timed` is reserved, not registered. An enum with a transition IS a lifecycle — states, initial state (`@default`), terminal states and each unclaimed transition's command are derived, never declared (ADR-0066). A transition's `@from` lists enum members, not object references: every port's ref-bearing-attr check excludes `transition.*` nodes. A lifecycle belongs to the declaring entity and its `extends` descendants, NEVER to an entity whose field merely `extends` the lifecycle field (filter by the declaring field's owner); a command claims a transition NODE for its target and every entity extending it. Transition and operation names compare case-insensitively; operation names are unique per PACKAGE across its APIs, except one operation declared identically in two APIs (a versioned API). A lifecycle on an entity with no source loads and is inert (no derived command, no permission checks); the writable-source check applies once a source exists. A `@permission` is a dotted identifier path (a package prefix may use `::`); an absent one derives `.` for an operation and `..` for a transition's command. - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 9da8915093..be473af5d9 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -396,7 +396,7 @@ calls it copies the adapter's source too: | `routes` | `routes.ts` — the whole route composition (CRUD, read-only projections, M:N traversal, TPH per-subtype sets), not a call into the engine | `drizzle-fastify/*` (mounts, filter parser, list params, M:N and read-only mounts, error handler), `route-errors.ts`, `constraint-errors.ts`, `timestamp-wire.ts`, `decimal-wire.ts`, `duration-wire.ts`, `wire-format.ts`, `sql-dialect.ts`, `canonical-key.ts`, `errors.ts` | | `routes-hono` | `routes-hono.ts`, likewise self-contained | `hono/*`, plus the shared parser, allowlist, envelope and timestamp files it reaches | | `entity` | `entity.ts` | `drizzle-fastify/filter-allowlist.ts` — the `FilterAllowlist` / `SortAllowlist` types the entity module's allowlists are typed by | -| `service` | `service.ts` | `service/index.ts` — the store mechanics the generated service modules call (transaction, row lock, write-rule stamping) | +| `service` | `service.ts` | `service/index.ts` — the store mechanics the generated service modules call (transaction, row lock, write-rule stamping), and `service/rules.ts`, the business-rules mechanics it re-exports | | `service-routes` | `service-routes.ts` | `service/fastify.ts` — the request and reply helpers the generated Fastify transport imports | The ejected generators point their output at that copy 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 32c8031cd3..b99ce61ca8 100644 --- a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md +++ b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md @@ -12,9 +12,11 @@ every entity that extends it. ADR-0067 decides where the rules are enforced, and ADR-0045 to match. 1.3.0 ships the vocabulary, the loader rules and the `verify` checks. The generated service -shells that enforce the rules at run time (§6) are later work. Until they land, the flat generators -emit nothing from the vocabulary; the layer generators of ADR-0067 emit its names and contract -types. `fixtures/codegen-noop/rules/` holds the flat generators to that. +shells that enforce the rules at run time (§6) are the service generators of ADR-0067: TypeScript's +`service` generator enforces them; the other ports' service generators are later 1.3.0 work. The +flat generators emit nothing from the vocabulary; the layer generators of ADR-0067 emit its names, +contract types and, in TypeScript, the shells. `fixtures/codegen-noop/rules/` holds the flat +generators to that. **Experimental.** Decision 2 of the 1.3.0 design pass gives new vocabulary an experimental label until it is proven in use. Everything this ADR registers — `api.*`, `operation.*`, `binding.*`, diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md index c182df7e3f..2d1113f99d 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -19,9 +19,10 @@ Layer 0 and layer 1 are generated: `rules-names` and `contract-types` write in T writes its own names and create and update records. In TypeScript, layers 4 and 5 have started: `service` writes each package's derived list, get, create, update and delete in one transaction with the declared write rules, and `service-routes` the thin Fastify transport over it (the `service` -layer label of §5.6). Transitions, declared operations, the policy, bodies and events interfaces, -the other ports' shells and the per-package choice of generators are later work. ADR-0066's -vocabulary is inert at run time until they land. +layer label of §5.6). The same generators now write ADR-0066's transitions and declared operations, +with the policy, bodies, hooks and events interfaces, and enforce the rules at run time. The other +ports' shells and the per-package choice of generators are later work. ADR-0066's vocabulary is +inert at run time in any port whose service generator has not landed. **Experimental.** The vocabulary this design generates from is experimental (ADR-0066 Status, `docs/compatibility-policy.md`): it may change in a MINOR, including removals and renames, until diff --git a/spec/decisions/README.md b/spec/decisions/README.md index 3619dceddd..c77a80a50f 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -62,7 +62,7 @@ Write one when a decision is **cross-cutting** (affects more than one language p - [ADR-0063 — Generators own their layout; formatters are test oracles only](ADR-0063-generators-own-layout.md) — *Accepted* (a writer in each port lays generated text out and no formatter runs in generation; output aims for clean code, not parity with today's formatting; a syntax-tree ratchet holds generator source to it, with an allowlist that only shrinks) - [ADR-0064 — `gen` skips rendering when the loaded model and its generators are unchanged](ADR-0064-skip-codegen-when-nothing-changed.md) — *Accepted* (every port keys a run on the loaded model and its generator inputs, and a matching key with every generated file unchanged renders and writes nothing; the manifest is written once per run; a local `verify --codegen` may answer from the key; Amendment 1: the manifest is one file per model package) - [ADR-0065 — Rust is the sixth port](ADR-0065-rust-is-the-sixth-port.md) — *Accepted* (a Rust port under `server/rust/`, a full language of 1.3.0, crates ready to publish and not yet published; the command is `cargo meta`; no `migrate`, Jinja refused, generated code as one crate per MetaObjects package; gated by `registry-conformance` and the metamodel corpus with a shrink-only ledger. **Amendment 1**: `cargo meta init` / `gen` / `verify --codegen` / `eject`, an owned generator as a crate the project builds, the generated crate shape, and the `client` and `commands` generators, the second Rust-only by decision) -- [ADR-0066 — Business rules: operations, permission points and lifecycles](ADR-0066-business-rules-operations-and-lifecycles.md) — *Accepted* (registers `api.*`, `operation.*`, `binding.*` and `transition.*` in all five ports, experimental, with eleven loader errors and a rules gate in every `verify`; the lifecycle, its states and a transition's command are derived; `transition.timed` reserved; the enforcing shells are later work) +- [ADR-0066 — Business rules: operations, permission points and lifecycles](ADR-0066-business-rules-operations-and-lifecycles.md) — *Accepted* (registers `api.*`, `operation.*`, `binding.*` and `transition.*` in all five ports, experimental, with eleven loader errors and a rules gate in every `verify`; the lifecycle, its states and a transition's command are derived; `transition.timed` reserved; TypeScript's service generator enforces them; the other ports' services are later work) - [ADR-0067 — Generated code is layered, and hand-written code attaches at the service seam](ADR-0067-layering-and-the-service-seam.md) — *Accepted* (layers 0 to 6; a service module per metadata package whose surface is its operations; hand-written bodies, policy and event handling implement generated interfaces and are passed in, in every language; a layer is a generator an app chooses, per package, with no named sets; the actor is an app-defined type; amends ADR-0045) - [ADR-0068 — The list query is part of the cross-port REST contract](ADR-0068-list-query-cross-port-contract.md) — *Accepted* (`?search`, `filter[or]`/`filter[and]`, the nesting cap, the bare-field and leading-`%` refusals, the value-format check, the `in` cap and the invalid_json / invalid_id / pagination.invalid_value / constraint_violation responses are contract in every port; `fixtures/list-query-conformance/` and the api-contract `list-query/` sub-corpus are the authority; each port passes both before rc.4) diff --git a/spec/roadmap.md b/spec/roadmap.md index 373fb8151b..e996724a35 100644 --- a/spec/roadmap.md +++ b/spec/roadmap.md @@ -143,7 +143,7 @@ under **Shipped**; planned FRs under **Planned** + the **Release plan**. ✅ shi | FR-021 | api metadata + contract projections | 📋 | 1.3 | [#7](https://github.com/metaobjectsdev/metaobjects/issues/7) | | FR-022 | Contract emitters (JSON Schema/OpenAPI/protobuf) | 🔵 JSON Schema and OpenAPI 1.2.1 · protobuf 1.3 | 1.2.1 | [#8](https://github.com/metaobjectsdev/metaobjects/issues/8) | | FR-023 | Metadata dependencies (cross-repo sharing: generated shared-model artifact, `meta deps sync`, committed snapshot + lock, default exclusion of imported metadata, consumer extend/overlay across the boundary) | 🟢 Phase 1a (TS + Python) **shipped** per DESIGN §11, Java/Kotlin consume (Phase 2 S3) — the usage-aware breaking-change classifier and the packaged transports (`npm`/`python`/`maven`/`nuget`) in the Python, Java and C# check are deferred (§11.4); C# consumer shipped in Phase 2 S6 | 1.1 | [#9](https://github.com/metaobjectsdev/metaobjects/issues/9) | -| FR-024 | Entity surfaces (projection/value + declared API) | 🟢 taxonomy + B3/B4a/B4b/B5/B6 validation parity + projection codegen **shipped 5 ports (1.0)**; declared-API surface (`api.operational`/`operation`/`binding.rest`) **registered in 1.3.0** with lifecycles (`transition.action`), loader rules and a `verify` rules gate in all five ports (ADR-0066); the enforcing service shells are later work (ADR-0067) | 1.0 · 1.3 | [#10](https://github.com/metaobjectsdev/metaobjects/issues/10) | +| FR-024 | Entity surfaces (projection/value + declared API) | 🟢 taxonomy + B3/B4a/B4b/B5/B6 validation parity + projection codegen **shipped 5 ports (1.0)**; declared-API surface (`api.operational`/`operation`/`binding.rest`) **registered in 1.3.0** with lifecycles (`transition.action`), loader rules and a `verify` rules gate in all five ports (ADR-0066); TypeScript's service generator enforces them (ADR-0067); the other ports' services are later 1.3.0 work | 1.0 · 1.3 | [#10](https://github.com/metaobjectsdev/metaobjects/issues/10) | | FR-025 | Cross-port package-binding codegen config | 📋 | 1.1 | [#11](https://github.com/metaobjectsdev/metaobjects/issues/11) | | FR-026 | Forms completeness (edit forms + view parity) | 🟢 edit forms + view-kind control dispatch **shipped**; renderer parity / validator wiring / `layout.form` **deferred to a later 1.x** (not in 1.1.0) | 1.x (later) | [#12](https://github.com/metaobjectsdev/metaobjects/issues/12) | | FR-027 | DataGrid downloads (CSV/XLSX/PDF/TXT) | 📋 | 1.2 | [#13](https://github.com/metaobjectsdev/metaobjects/issues/13) | From 4c0497192ff20df7a4812efadaa424d4833372d5 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 05:23:17 -0500 Subject: [PATCH 4/4] no-mistakes(document): Reword TS service calibration in audit refs --- ...a516068ccf344f8.md => 9984405efdf695f3.md} | 7 +- ...de78e78a5c9b963.md => a41cb586bdd98720.md} | 2 +- agent-context-shipped/manifest.json | 112 +++++++++--------- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 7 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 7 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 7 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 7 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 7 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 7 +- .../references/calibration.md | 2 +- .../references/capability-checklist.md | 7 +- 17 files changed, 96 insertions(+), 88 deletions(-) rename agent-context-shipped/files/{0a516068ccf344f8.md => 9984405efdf695f3.md} (98%) rename agent-context-shipped/files/{2de78e78a5c9b963.md => a41cb586bdd98720.md} (87%) diff --git a/agent-context-shipped/files/0a516068ccf344f8.md b/agent-context-shipped/files/9984405efdf695f3.md similarity index 98% rename from agent-context-shipped/files/0a516068ccf344f8.md rename to agent-context-shipped/files/9984405efdf695f3.md index bc71a99054..345e4b9c92 100644 --- a/agent-context-shipped/files/0a516068ccf344f8.md +++ b/agent-context-shipped/files/9984405efdf695f3.md @@ -364,11 +364,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — registered, nothing generated yet:** the declared-API surface +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at - load and by `verify`, but no generator emits from them yet. Their absence is not an adopter - defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* diff --git a/agent-context-shipped/files/2de78e78a5c9b963.md b/agent-context-shipped/files/a41cb586bdd98720.md similarity index 87% rename from agent-context-shipped/files/2de78e78a5c9b963.md rename to agent-context-shipped/files/a41cb586bdd98720.md index 70ab55926b..48b411ee42 100644 --- a/agent-context-shipped/files/2de78e78a5c9b963.md +++ b/agent-context-shipped/files/a41cb586bdd98720.md @@ -34,7 +34,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index 8c6a5a8b5b..f4b44e8178 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -17,11 +17,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -232,11 +232,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -452,11 +452,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -675,11 +675,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -888,11 +888,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1079,11 +1079,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1275,11 +1275,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1474,11 +1474,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1663,11 +1663,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -1854,11 +1854,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2050,11 +2050,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2249,11 +2249,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -2438,11 +2438,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", @@ -2629,11 +2629,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", @@ -2825,11 +2825,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", @@ -3024,11 +3024,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/csharp.md", @@ -3213,11 +3213,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3404,11 +3404,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3600,11 +3600,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3799,11 +3799,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -3988,11 +3988,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4159,11 +4159,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4335,11 +4335,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4514,11 +4514,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4684,11 +4684,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -4896,11 +4896,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5113,11 +5113,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", @@ -5333,11 +5333,11 @@ }, { "path": ".claude/skills/metaobjects-audit/references/calibration.md", - "file": "2de78e78a5c9b963.md" + "file": "a41cb586bdd98720.md" }, { "path": ".claude/skills/metaobjects-audit/references/capability-checklist.md", - "file": "0a516068ccf344f8.md" + "file": "9984405efdf695f3.md" }, { "path": ".claude/skills/metaobjects-audit/references/drift-signatures.md", diff --git a/agent-context/skills/metaobjects-audit/references/calibration.md b/agent-context/skills/metaobjects-audit/references/calibration.md index 70ab55926b..48b411ee42 100644 --- a/agent-context/skills/metaobjects-audit/references/calibration.md +++ b/agent-context/skills/metaobjects-audit/references/calibration.md @@ -34,7 +34,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/agent-context/skills/metaobjects-audit/references/capability-checklist.md b/agent-context/skills/metaobjects-audit/references/capability-checklist.md index bc71a99054..345e4b9c92 100644 --- a/agent-context/skills/metaobjects-audit/references/capability-checklist.md +++ b/agent-context/skills/metaobjects-audit/references/capability-checklist.md @@ -364,11 +364,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — registered, nothing generated yet:** the declared-API surface +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at - load and by `verify`, but no generator emits from them yet. Their absence is not an adopter - defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md index 70ab55926b..48b411ee42 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -34,7 +34,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index bc71a99054..345e4b9c92 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -364,11 +364,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — registered, nothing generated yet:** the declared-API surface +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at - load and by `verify`, but no generator emits from them yet. Their absence is not an adopter - defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index 70ab55926b..48b411ee42 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -34,7 +34,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index bc71a99054..345e4b9c92 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -364,11 +364,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — registered, nothing generated yet:** the declared-API surface +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at - load and by `verify`, but no generator emits from them yet. Their absence is not an adopter - defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md index 70ab55926b..48b411ee42 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -34,7 +34,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index bc71a99054..345e4b9c92 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -364,11 +364,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — registered, nothing generated yet:** the declared-API surface +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at - load and by `verify`, but no generator emits from them yet. Their absence is not an adopter - defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md index 70ab55926b..48b411ee42 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -34,7 +34,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index bc71a99054..345e4b9c92 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -364,11 +364,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — registered, nothing generated yet:** the declared-API surface +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at - load and by `verify`, but no generator emits from them yet. Their absence is not an adopter - defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* diff --git a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md index 70ab55926b..48b411ee42 100644 --- a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -34,7 +34,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index bc71a99054..345e4b9c92 100644 --- a/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/rust/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -364,11 +364,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — registered, nothing generated yet:** the declared-API surface +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at - load and by `verify`, but no generator emits from them yet. Their absence is not an adopter - defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port* diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index 70ab55926b..48b411ee42 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -34,7 +34,7 @@ - **C#** has no ObjectManager runtime tier (EF Core is the runtime) — hand services over the generated `DbContext` are expected. - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. -- **CALIBRATION — registered, nothing generated yet** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`, but no generator emits from them yet. Their absence is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. +- **CALIBRATION — registered; generated by TypeScript only** — the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at load and by `verify`. TypeScript's service generator emits from them (transition commands, declared command and query shells, permission points); the other ports do not yet. Their absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. - **Include-only templates are not duplicates.** A prompt template whose body is only `{{> partial }}` includes is already the shared-partial fix the template-duplication check recommends. Identical stubs are the shape to want, never a byte-identical cluster to report (`references/prompt-anti-patterns.md`, template-text duplication). diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md index bc71a99054..345e4b9c92 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -364,11 +364,12 @@ to nothing, and does not check that each claimed node complies). `naming` block of `.metaobjects/config.json` (column and table rules, read by every port) and per-target output dirs: hunt these values hard-coded in multiple places instead of resolved from config. -- **CALIBRATION — registered, nothing generated yet:** the declared-API surface +- **CALIBRATION — registered; generated by TypeScript only:** the declared-API surface (`api.operational`, `operation.query`, `operation.command`, `binding.rest`) and lifecycles (`transition.action` under a `field.enum`) are registered since 1.3.0 (ADR-0066), checked at - load and by `verify`, but no generator emits from them yet. Their absence is not an adopter - defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in + load and by `verify`. TypeScript's service generator emits from them (transition commands, + declared command and query shells, permission points); the other ports do not yet. Their + absence in a non-TypeScript port is not an adopter defect; do NOT audit for them. MCP exposure of declared prompts/tools is planned and not in the registry. - **CALIBRATION — cross-port version skew is by design:** TS/C#/Python on the `0.x` line vs Java/Kotlin on the `7.x` Maven line is correct — **never flag it.** Flag only *intra-port*