diff --git a/.claude/skills/metaobjects-audit/references/capability-checklist.md b/.claude/skills/metaobjects-audit/references/capability-checklist.md index 39d9a51..e145d1c 100644 --- a/.claude/skills/metaobjects-audit/references/capability-checklist.md +++ b/.claude/skills/metaobjects-audit/references/capability-checklist.md @@ -198,8 +198,10 @@ soft-delete / status / type view it models. and are NOT in the cross-port registry — `view.text`, `view.textarea`, `view.date`, `view.month`, `view.hotlink`, `view.image`, `view.dropdown`, `view.radio`, `view.checkbox`, `view.number`, `view.password`, `view.hidden`, `view.web`. Every port LOADS them, so shared metadata that - carries them is valid in a backend port; nothing outside TS/web reads them. **Audit these - only for TS adopters.** Only + carries them is valid in a backend port. The one exception is `view.password`: every port's generated + routes read it as a credential, so it is never returned and never written (see + "Credentials and excluded fields" in `docs/features/api-contract.md`). + Audit the other widgets only for TS adopters. Only `view.base` / `view.currency` are cross-port-gated. ## Template — `template.*` (prompt pillar) diff --git a/.claude/skills/metaobjects-audit/references/typescript.md b/.claude/skills/metaobjects-audit/references/typescript.md index 8c8df46..3fc9924 100644 --- a/.claude/skills/metaobjects-audit/references/typescript.md +++ b/.claude/skills/metaobjects-audit/references/typescript.md @@ -41,7 +41,7 @@ meta gen # render → 3-way merge → write (overwrites @ meta gen --dry-run # preview without writing meta gen Author Post # scope to named entities meta verify --codegen # regenerate to temp, diff vs committed output -meta verify --templates # check {{field}} refs vs payload VO (bare `meta verify` default) +meta verify --templates # check {{field}} refs vs payload VO (a bare `meta verify` runs this and `--codegen`) meta verify --db # schema drift — live DB vs metadata (requires DB connection) meta verify --codegen --templates --db # all three drift checks in one pass ``` @@ -199,4 +199,4 @@ TypeScript is the reference implementation — it ships the full feature set: - Output-parser codegen: **complete** (`outputParser()` generator; `parse*`/`safeParse*`/`extract*` emitted as `.response.ts` per **responding `template.prompt`** — one carrying `@responseRef`; ADR-0052). - ObjectManager: **complete** (`@metaobjectsdev/runtime-ts`; `kyselyDriver` / `inMemoryDriver`). - Schema migrate / `meta verify --db`: **complete** (TS owns the shared migrate engine — ADR-0015). -- D1 dialect: **TS-only by design** — `dialect: "d1"` in `metaobjects.config.ts` targets Cloudflare D1 via the Wrangler CLI layout. Do NOT recommend porting D1 support to other languages. +- D1 dialect: **TS-only by design** — `migrate.dialect: "d1"` (and `meta migrate --dialect d1`) targets Cloudflare D1 via the Wrangler CLI layout; codegen's `dialect` in `metaobjects.config.ts` is `"sqlite"` for D1 and `"d1"` there is refused. Do NOT recommend porting D1 support to other languages. diff --git a/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md b/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md index 4da7390..2574655 100644 --- a/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md +++ b/.claude/skills/metaobjects-authoring/references/metadata-dependencies.md @@ -7,7 +7,16 @@ build on a shared model.** A project may declare `dependencies` in `.metaobjects/config.json` and `meta deps sync` a publisher's metadata into a committed snapshot — that snapshot loads BEFORE your own files, so a foreign abstract resolves via `extends` and a foreign node re-opens via `overlay: true` -exactly like a local one. Two rules are specific to that boundary: +exactly like a local one. A dependency names one transport: `path` (a directory +relative to the directory holding `.metaobjects/`), `npm` (an installed npm +package, e.g. `{ "name": "acme-model", "npm": "@acme/model", "dir": "metaobjects" }`) +or `python` (an installed Python package by its import name, e.g. +`{ "name": "acme-model", "python": "acme_model", "dir": "metaobjects" }`). For +`npm`/`python`, install the package with the project's package manager first; +`meta deps sync` locates it, copies its shared model into the snapshot, and says +what to install when it is missing. Prefer the package transport over a `path` into +someone else's checkout when the publisher releases a package. Two rules are +specific to that boundary: - **Say `overlay: true` on every amendment to a node you don't own.** Within one project the parser merges a same-`(type, package::name)` redeclaration whether diff --git a/.claude/skills/metaobjects-codegen/SKILL.md b/.claude/skills/metaobjects-codegen/SKILL.md index 02eea05..f57fad8 100644 --- a/.claude/skills/metaobjects-codegen/SKILL.md +++ b/.claude/skills/metaobjects-codegen/SKILL.md @@ -44,13 +44,14 @@ exact config, generator names and commands for this project; read it. The other | `references/dependencies-and-shared-models.md` | the project consumes or publishes metadata across projects | | `references/typescript-document-store.md` | a TypeScript project on MongoDB, or any store MetaObjects does not manage, wanting a tested repository generator | | `references/typescript-mysql.md` | a TypeScript project on a MySQL database | +| `references/typescript-prisma.md` | a TypeScript project that keeps Prisma as its ORM | | `references/typescript-retargeting.md` | a TypeScript project on a framework other than Fastify, Hono or React | | `references/typescript-templates.md` | declarative Mustache template-codegen in a TypeScript project | | `references/typescript-docs.md` | the docs generators (`docsFile`, `apiDocsFile`, `agentDocsFile`, `requirementsFile`, `metamodelDocsFile`, `docsSiteFile`) in a TypeScript project | ## Upgrading a project from 1.0 to 1.1 -Read the one upgrade guide, https://github.com/metaobjectsdev/metaobjects/blob/v1.1.4/docs/features/migrations/upgrading-1.0-to-1.1.md, before the first `gen`, for every +Read the one upgrade guide, https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-1.0-to-1.1.md, before the first `gen`, for every port the project uses; the build can stay green while the result is wrong. It lists the steps in order and every change that needs action. @@ -71,7 +72,7 @@ in order and every change that needs action. `eject --list`; `dotnet meta gen --list`; `mvn metaobjects:eject -Dlist=true` in Java and Kotlin) reports each copy that differs from the reference; `eject --force` takes the new reference for a copy you never edited, and a copy you - edited is three-way merged instead. Steps for 1.0.x: https://github.com/metaobjectsdev/metaobjects/blob/v1.1.4/docs/features/migrations/upgrading-within-1.0.md. + edited is three-way merged instead. Steps for 1.0.x: https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-within-1.0.md. ## Need an output? Write the generator — this is the primary path @@ -147,7 +148,7 @@ without typechecking, so a wrong accessor runs silently. Every port's minimal generator (each run through gen, verify and a convicted model change) and two worked examples to copy — JSON Schema and OpenAPI 3.1, examples and not a product surface — are in the guide "Write your own generator": -. +. **Use a stock generator as shipped** when one already emits what you need: `meta gen --list --probe` is the catalog, and each row says how to wire it with nothing diff --git a/.claude/skills/metaobjects-codegen/references/any-stack.md b/.claude/skills/metaobjects-codegen/references/any-stack.md index 57f1c96..91f568f 100644 --- a/.claude/skills/metaobjects-codegen/references/any-stack.md +++ b/.claude/skills/metaobjects-codegen/references/any-stack.md @@ -34,7 +34,7 @@ reference generators target React and TanStack. Anything else is this page. | Layer | Always available | When your target is not built in | |---|---|---| | **model** — types, create/PATCH validation, filter and sort allowlists | yes, in every port, for every store | — | -| **persistence** — how rows are read and written | Postgres, SQLite, D1; MySQL (TypeScript, Java) | §3 | +| **persistence** — how rows are read and written | Postgres, SQLite, D1; MySQL (TypeScript, Java); a Prisma schema (TypeScript) | §3 | | **api** — the HTTP surface | Fastify, Hono | §4 | | **client** — hooks, forms, grids | React, TanStack | §5 | @@ -52,6 +52,12 @@ the column-type table and the behaviour differences are in `typescript-mysql.md` OMDB's `MySQLDriver` reads and writes MySQL; the generated DTOs and controllers are dialect-neutral. +**Prisma as the ORM (TypeScript).** Set `orm: "prisma"` and wire `prismaSchemaFile()`. The +model then writes `schema.prisma` (Postgres, MySQL, SQLite) beside Zod schemas and types, and +Prisma runs the database. `meta verify --codegen` and `--db` gate it. Setup, the mapping and +what it refuses are in `typescript-prisma.md`. Any other ORM (TypeORM, Sequelize, MikroORM) is +a generator you write: the Prisma one is a model to copy (`meta eject prisma-schema`). + **A SQL database that speaks another dialect's protocol.** Use that dialect: CockroachDB, Neon, Supabase, AlloyDB and Aurora PostgreSQL are `postgres`; Turso and libSQL are `sqlite` (or `d1` on Cloudflare); MariaDB and PlanetScale are `mysql`. Test the generated queries diff --git a/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md b/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md index 1417e31..3d0cdc8 100644 --- a/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md +++ b/.claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md @@ -38,8 +38,13 @@ artifact is a contract whose bytes a cross-port corpus pins and whose hash consumers verify, so everything a consumer checks stays in the package, in the two functions the copy calls (`buildSharedModel`, `renderSharedModelFiles`). Do not replace those calls: an unmodified copy publishes the same bytes as the packaged -generator. Only TypeScript can run it in Phase 1a. **Phase 1a is TypeScript and Python -only, full stop** — TypeScript and Python are the only two ports that can -*consume* a dependency at all today, and only the TypeScript toolchain can -*publish* one; Java, Kotlin, and C# do not read `dependencies` yet (Phase 2). +generator. To publish through a package, point its `target` inside the package +(an npm package's directory listed in `files`; a Python package's directory shipped +as package data), run `meta gen`, then release the package as usual; consumers +declare an `npm` or `python` dependency on it. With no `version` option the +manifest takes the nearest `package.json` version, else a `pyproject.toml` +`[project]` version — pass `version` when neither is the package consumers install. +Only TypeScript can run it in Phase 1a. TypeScript, Python, Java, Kotlin (through +Java's loader and Maven plugin) and C# can *consume* a dependency, and only the +TypeScript toolchain can *publish* one. Full detail: `docs/features/metadata-dependencies.md`. diff --git a/.claude/skills/metaobjects-codegen/references/typescript-docs.md b/.claude/skills/metaobjects-codegen/references/typescript-docs.md index fa51941..35f595e 100644 --- a/.claude/skills/metaobjects-codegen/references/typescript-docs.md +++ b/.claude/skills/metaobjects-codegen/references/typescript-docs.md @@ -54,7 +54,7 @@ directory each port's `verify --codegen` reports the other ports' pages as drift name (`meta gen --list` prints them); it never adds one, and naming an entry the config does not declare is refused. A config still carrying a 1.0 `docs: { ... }` block fails `meta gen` and `meta verify --codegen` before writing anything, naming the block. Full -before/after and the flag-to-option table: , +before/after and the flag-to-option table: , section "TypeScript". **An owned docs generator goes in `generators`, like any other owned copy.** `meta eject diff --git a/.claude/skills/metaobjects-codegen/references/typescript-prisma.md b/.claude/skills/metaobjects-codegen/references/typescript-prisma.md new file mode 100644 index 0000000..4ec7d2f --- /dev/null +++ b/.claude/skills/metaobjects-codegen/references/typescript-prisma.md @@ -0,0 +1,160 @@ +# Prisma on TypeScript + +> Part of the `metaobjects-codegen` skill's TypeScript reference. Read it when the app keeps +> Prisma as its ORM. + +Under `orm: "prisma"`, `meta gen` writes `schema.prisma` from the model, along with Zod schemas +and types that have no Drizzle code. Prisma still creates the tables (`prisma db push` or +`prisma migrate`) and runs the queries. `meta verify --codegen` fails when someone edits +`schema.prisma` or it is out of date. `meta verify --db` fails when the database Prisma created +differs from the model (Postgres and SQLite). Do not hand-write a Prisma model for a table the +MetaObjects model declares. + +## Contents +- TypeScript setup +- The workflow +- How the model maps +- What it refuses +- SQLite and MySQL +- Eject it + +## TypeScript setup + +```ts +// metaobjects.config.ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { prismaSchemaFile } from "@metaobjectsdev/codegen-ts/generators"; + +export default defineConfig({ + orm: "prisma", + dialect: "postgres", // "postgres" | "mysql" | "sqlite": picks the Prisma provider + outDir: "src/generated", // Zod schemas and types + targets: { prisma: { outDir: "prisma" } }, + generators: ["entity", prismaSchemaFile({ target: "prisma" })], +}); +``` + +`orm: "prisma"` does two things: + +- **Every target defaults to `runtime: false`.** The `entity` generator then writes Zod schemas + and types with no `drizzle-orm` import. A target that sets `runtime: true` is refused. +- **Generators that write Drizzle code are refused** by name: `queries`, `routes`, + `routes-hono` and `callable`. Your routes call the Prisma Client instead. `meta gen` exits + with `orm: "prisma" refuses "queries", …` and makes no changes. + +The default `orm` is `"drizzle"`, and it changes nothing. + +Prisma 7 reads the connection URL from `prisma.config.ts`, not from the schema: + +```ts +// prisma.config.ts +import { defineConfig } from "prisma/config"; +export default defineConfig({ schema: "prisma/schema.prisma", datasource: { url: process.env.DATABASE_URL! } }); +``` + +The generated schema names the `prisma-client` generator, writing to `prisma/generated`. To +choose your own generator and datasource blocks, pass `header` as a string. Pass +`header: false` for a multi-file schema (`prisma/schema/`) whose blocks live in a file you own. +Other options: + +- `provider` overrides the provider that `dialect` picks. +- `fileName` renames the file (default `schema.prisma`). +- `filter` narrows which objects get a model. +- `checks: "omit"` drops the CHECK file. + +## The workflow + +```bash +meta gen # writes prisma/schema.prisma (+ schema.checks.sql) +npx prisma db push # or: npx prisma migrate dev +npx prisma db execute --file prisma/schema.checks.sql +npx prisma generate # the Prisma Client, as usual +meta verify --codegen --db "$DATABASE_URL" # in CI: fails on an edited schema or a drifted database +``` + +To change a field, edit the model and run `meta gen`. **Do not edit `schema.prisma` by hand.** +The generator overwrites hand edits instead of merging them. Prisma treats the whole file as +the schema, so a merged edit would change the database without the model knowing. +`meta verify --codegen` fails on the edit until you run `meta gen` again. `prisma format` +leaves the file unchanged, so formatting it does not count as an edit. + +A Prisma schema cannot declare a CHECK constraint, so the constraints the model implies go in +`schema.checks.sql`. These are enum membership checks plus the `@min`/`@max` and length +validators. Apply the file after every `db push` or migration. On Postgres the file drops each +constraint before adding it, so you can apply it more than once. On MySQL it only adds them, +so apply it once, when you create the table. When a check changes, drop the old one in a Prisma +migration. When the model has no checks left, `meta gen` deletes the file. + +With `prisma migrate`, keep the Prisma migration chain: `meta gen` changes `schema.prisma`, and +`prisma migrate dev` writes the SQL. To make the checks part of the chain, put the contents of +`schema.checks.sql` into a migration (`prisma migrate dev --create-only`, then add the SQL). + +## How the model maps + +The schema is built from the same expected schema that `meta migrate` writes and +`meta verify --db` compares against. A database that Prisma creates from it therefore passes +the gate. + +| Model | Prisma | +|---|---| +| object with a writable `source.rdb` | `model ` with `@@map("")` when the names differ | +| field | a scalar field with `@map("")` when the names differ; `?` when the field is not `@required` | +| `field.string @maxLength` | `String @db.VarChar(n)` (Postgres, MySQL) | +| `field.int` / `field.long` / `field.currency` | `Int` / `BigInt` / `BigInt` | +| `field.double` / `field.float` | `Float` / `Float @db.Real` (Postgres) | +| `field.decimal` | `Decimal @db.Decimal(p, s)` | +| `field.boolean` | `Boolean` | +| `field.timestamp` / `field.date` / `field.time` | `DateTime` with `@db.Timestamptz`/`@db.Timestamp`, `@db.Date`, `@db.Time` (Postgres); `String` on SQLite, where the column holds ISO text | +| `field.uuid` | `String @db.Uuid` (Postgres), `@db.VarChar(36)` (MySQL) | +| `field.enum` | `String` plus a CHECK in `schema.checks.sql` (not a Prisma `enum`, so the column matches `meta migrate`'s) | +| `field.object`, `field.map`, `@storage: jsonb` | `Json` | +| `field.object @storage: flattened` | one field per field of the value object, `` with `@map("_")` | +| `isArray` scalar | a list (`String[]`) on Postgres; `Json` on MySQL; `String` holding JSON text on SQLite | +| `identity.primary` | `@id` or `@@id([...])`; `@generation: increment` is `@default(autoincrement())`; `@generation: uuid` is `gen_random_uuid()` on Postgres, `uuid()` elsewhere | +| `@default` | `@default(...)` for a literal; `"now"` and other expressions are `dbgenerated(...)`, so the default text matches what `verify --db` expects (a MySQL `DateTime` takes `now()`) | +| `identity.secondary` | `@unique` or `@@unique` (the index name in `map:`) | +| `index.lookup` | `@@index` (`@orders` becomes `sort: Desc`) | +| `identity.reference` | a relation field on both models, with `fields`, `references`, `onDelete`, `onUpdate` and the constraint name in `map:` | +| `@schema` on `source.rdb` | `@@schema("")` and the datasource's `schemas` list (Postgres) | + +## What it refuses + +The generator stops with an error code rather than write a schema that would push a database +the model does not describe. Each message names the object or index, says why, and says what +to change. + +| Code | When | What to do | +|---|---|---| +| `ERR_PRISMA_READ_ONLY_SOURCE` | an object declares a view that `meta migrate` creates and `meta verify --db` expects (a projection, a write-through entity's read view, or a served report) | create the view in a Prisma migration and mark its read `source.rdb` `@unmanaged: true`, or leave the object out with `filter` | +| `ERR_PRISMA_UNSUPPORTED_INDEX` | an index has `@expr` or `@where`, or a `@using` method other than `btree` or, on Postgres, `hash`, `gin`, `gist`, `brin` or `spgist` | create it in a Prisma migration, or drop the attribute | +| `ERR_PRISMA_UNSUPPORTED_SCHEMA` | a `source.rdb` declares `@schema` and the provider is not `postgresql`, where Prisma has no `@@schema` | remove the `@schema`, or use the `postgresql` provider | +| `ERR_PRISMA_UNSUPPORTED_CHECK` | the provider is SQLite and the model implies a CHECK | pass `checks: "omit"` | +| `ERR_PRISMA_NO_PRIMARY_KEY` | a table has no primary key | declare an `identity.primary` | +| `ERR_PRISMA_UNMAPPABLE_RELATION` | a foreign key points at a table with no model, at a non-unique key, or at a column of another type | include the table, reference a key, or match the subtype | +| `ERR_PRISMA_NAME_COLLISION` | two objects, or two fields, would get the same Prisma name | rename one, or narrow `filter` | +| `ERR_PRISMA_UNSUPPORTED_PROVIDER` | the dialect or `provider` is not `postgresql`, `mysql` or `sqlite` | pass `provider` | + +A model with projections, write-through read views or served reports therefore needs one of +those two fixes before the generator runs. A stored procedure, table function or materialized +view is not refused: `meta migrate` does not create it, so neither does Prisma. Read the view's rows with Prisma's `$queryRaw`, and validate them with the +generated Zod schema. + +## SQLite and MySQL + +- **SQLite** cannot add a CHECK to an existing table. Pass `checks: "omit"`. `meta verify --db` + then reports each missing CHECK as an `add-check` row and nothing else. Only the Zod schemas + enforce those rules. Timestamps, dates and times are `String` in the Prisma Client, because the + column holds ISO text, as it does under `meta migrate`. +- **MySQL** gets the enum CHECKs only. The other checks are written in Postgres SQL. The schema + matches the column types in the MySQL recipe, but `meta verify --db` does not support MySQL, + so on MySQL the drift gate is `verify --codegen` alone. + +## Eject it + +```bash +meta eject prisma-schema +``` + +This copies the generator to `codegen/generators/prisma-schema.ts`, and the mapping and +renderers to `codegen/templates/prisma/`. To change a type mapping, edit your copy. A mapping +that no longer matches the expected schema makes `meta verify --db` report drift. diff --git a/.claude/skills/metaobjects-codegen/references/typescript.md b/.claude/skills/metaobjects-codegen/references/typescript.md index 6db44b8..0765faf 100644 --- a/.claude/skills/metaobjects-codegen/references/typescript.md +++ b/.claude/skills/metaobjects-codegen/references/typescript.md @@ -15,8 +15,9 @@ packages. Codegen runs through the Node `meta` CLI (`@metaobjectsdev/cli`, binar - Field subtype → column mapping Topic files beside this one, to open when they come up: -`typescript-mysql.md` (a MySQL database), `typescript-document-store.md` (MongoDB or any -store MetaObjects does not manage, with a tested repository generator), +`typescript-mysql.md` (a MySQL database), `typescript-prisma.md` (Prisma as the ORM), +`typescript-document-store.md` (MongoDB or any store MetaObjects does not manage, with a +tested repository generator), `typescript-retargeting.md` (a framework other than Fastify, Hono or React), `typescript-templates.md` (declarative Mustache template-codegen) and `typescript-docs.md` (the docs generators). The procedure for any unsupported stack is `any-stack.md`. @@ -85,6 +86,7 @@ import { tanstackQuery, tanstackGrid } from "@metaobjectsdev/codegen-ts-tanstack export default defineConfig({ outDir: "src/generated", dialect: "postgres", // "postgres" | "sqlite" | "d1" | "mysql" (mysql: codegen + runtime; migrate does not own it) + // orm: "prisma", // keep Prisma: contract-only targets + prismaSchemaFile(); see `typescript-prisma.md` extStyle: "js", // "js" (default) for Node ESM / plain tsc; "none" for a bundler-resolution toolchain — see `owning-generators.md` "Your framework isn't the default" apiPrefix: "/api", // flows to routes AND client fetch URLs timestampMode: "string", // "string" (default, ISO-8601 wire contract) | "date" (Drizzle native Date) diff --git a/.claude/skills/metaobjects-prompts/SKILL.md b/.claude/skills/metaobjects-prompts/SKILL.md index 011c28d..37377ba 100644 --- a/.claude/skills/metaobjects-prompts/SKILL.md +++ b/.claude/skills/metaobjects-prompts/SKILL.md @@ -166,7 +166,8 @@ drift at build time instead of letting a prompt silently degrade. `@textRef` is a 2-layer logical reference `group/source` (folder/file, table/key, collection/document). The prompt text itself **never lives in metadata** — at runtime a configured **provider** resolves the reference to the -actual Mustache text: +actual template text (Mustache in every port; Python and TypeScript also accept Jinja, see +below): - a filesystem provider (L1 = folder, L2 = file) — the dev default: `lobby/welcome` → `/lobby/welcome.mustache`. It is `FilesystemProvider` in every @@ -181,6 +182,18 @@ actual Mustache text: Locale, A/B, dynamic, and evolutionary prompt variants all live behind the provider seam without touching metadata. +**Jinja bodies (Python and TypeScript only, ADR-0061).** A body may be a Jinja file — +`lobby/welcome.jinja` (or `.j2` / `.jinja2`) — instead of `welcome.mustache`; the +`@textRef` does not change, and the metadata never names an engine. Python renders it with +jinja2 (the `metaobjects[jinja]` extra), TypeScript with nunjucks. The same `verify` gate +checks it against the payload, walking the parsed template, and reports what it cannot +settle statically (`user[key]`, a computed include name) as `ERR_TEMPLATE_NOT_STATIC`. Java, +Kotlin and C# refuse a Jinja body with `ERR_TEMPLATE_ENGINE_UNSUPPORTED`, so a model that +must render in those ports keeps Mustache. Prefer Mustache for new templates: it is the +cross-port engine, and its logic-less shape is what pushes conditionals into the payload +(next sections). Jinja is for adopting existing Jinja templates without rewriting them; per +port reference files say how. + ## `render()` is deterministic + byte-stable Rendering is a pure function: `(payload VO, resolved text) → string`. Same inputs, @@ -244,7 +257,8 @@ against each value of the dimension and snapshot every variant. ## `verify` fails the build on prompt-drift For every template, the verify step resolves the text, parses each `{{...}}` -reference, and checks it exists on the payload VO. If the text references +reference (Mustache, or a Jinja body in Python and TypeScript), and checks it exists on the +payload VO. If the text references `{{authorName}}` but the payload only has `displayName`, **the build fails.** This is the prompt-vs-payload drift gate — run it in CI. It walks both `template.prompt` and `template.output` nodes the same way (both RENDER; only the direction of what comes diff --git a/.claude/skills/metaobjects-prompts/references/typescript.md b/.claude/skills/metaobjects-prompts/references/typescript.md index 89de514..92b5d47 100644 --- a/.claude/skills/metaobjects-prompts/references/typescript.md +++ b/.claude/skills/metaobjects-prompts/references/typescript.md @@ -219,6 +219,18 @@ error in every port. The emitted parser imports `zod`; it's usually already a dependency (Drizzle / `runtime-ts` lean on it), else `npm i zod`. +**Jinja bodies (ADR-0061).** A body may be `/.jinja` (or `.j2`, `.jinja2`) +instead of `.mustache`; `@textRef` does not change. `@metaobjectsdev/render` renders it with +nunjucks (a dependency of the package, nothing to install) and `meta verify` checks it the same +way, walking the parsed template; it names the `.jinja` file and line on a drift. +`FilesystemProvider.engineOf(ref)` reports the engine of the file it found; for an +`InMemoryProvider` pass `new InMemoryProvider(map, { engine: "jinja" })`, or pass +`engine: "jinja"` to `render` / `verify`. A generated `render()` helper over a Jinja body +passes `engine: "jinja"`, so it renders as Jinja through any runtime provider, and the +runtime check runs on it as on a Mustache body. What the check cannot settle statically is +`ERR_TEMPLATE_NOT_STATIC`. nunjucks treats an empty list as true (jinja2 does not), so test a +list with `{% if items | length %}` when the same template must render in Python. + ## See which fields a template consumes List `docsFile()` in `generators` and run `meta gen` to emit the model surface to the diff --git a/.claude/skills/metaobjects-verify/SKILL.md b/.claude/skills/metaobjects-verify/SKILL.md index bfaf943..54ffb46 100644 --- a/.claude/skills/metaobjects-verify/SKILL.md +++ b/.claude/skills/metaobjects-verify/SKILL.md @@ -92,15 +92,16 @@ JSON. A pass that did not run reports `status: "skipped"` and why, so an empty l always means "found nothing", never "never looked"; what the payload does not carry is named in its own `notRepresented[]`. -**A bare `verify` is a partial check, not the full gate.** The Node/C# default runs -only `--templates`; Java/Python's bare default runs only `--codegen` — either way, -paired with the advisory anti-pattern pass above, never all three subverbs. Treat a -bare run as a smoke test: the real done-check is running the subverbs your project -uses explicitly — `verify --codegen`, and, where a DB exists, `verify --db `. -The Node `meta verify` ends every run, bare or not, with a `not run:` line naming -each gate it skipped and the flag that selects it; on a model with no templates a -bare run checks nothing but the requirement ledger and still exits 0, so never -wire a bare `meta verify` into CI as the whole gate. +**A bare `verify` runs the code gates, not the database gate.** In every port a bare +run covers codegen drift (stale generated code), prompt-template drift and the +requirement ledger, paired with the advisory anti-pattern pass above. `verify --db +`, `--deps` and `--replay` stay opt-in (`--db` is Node `meta` only). A bare run +skips a gate it has no configuration for and says so in one line: Node `meta` with +no `metaobjects.config.ts`, Python with no `metaobjects.config.yaml`, `dotnet meta` +with no `--out ` or `codegen/Generators.cs`, Maven with no `templateRoot`. The +Node `meta verify` ends every run, bare or not, with a `not run:` line naming each +gate it skipped and the flag that selects it; read it, because a skipped gate is a +gate that did not guard the build. ## Requirements are checked on every run diff --git a/.metaobjects/.agent-context.json b/.metaobjects/.agent-context.json index 661055c..ee51d53 100644 --- a/.metaobjects/.agent-context.json +++ b/.metaobjects/.agent-context.json @@ -1,7 +1,7 @@ { "version": 1, - "generatedBy": "1.1.4", - "contentHash": "3f1c4a6aebabee748d00a596b75c71069d0dd8163f2398ec01b33b58a1355b8c", + "generatedBy": "1.2.0", + "contentHash": "995da2b47b86f6bfb22cf3ee410a02e0e01455989c1bb483bf2fb90c9370be90", "servers": [ "typescript" ], @@ -11,11 +11,11 @@ "files": { ".claude/skills/metaobjects-audit/SKILL.md": "84cc2119968dfbe3a66077030fa66d3cb3210ff3076a75430b4befa923649ded", ".claude/skills/metaobjects-audit/references/calibration.md": "254ca3b4f5846e5b8fa05266d074de0e4603b28d0a415da8a944e9f881c5d983", - ".claude/skills/metaobjects-audit/references/capability-checklist.md": "811d4c4dde135310457886acb8707c0c602dfac43a47860012d81f16b2131297", + ".claude/skills/metaobjects-audit/references/capability-checklist.md": "245962c0b471dac3e2c0d786aa7d6c0a8cb08ecc1b00e8b822322a3b1a8fbdc8", ".claude/skills/metaobjects-audit/references/drift-signatures.md": "6927eab4a99c8c50597f0bb62547a1dd1b33ae720519be9708663d2179970761", ".claude/skills/metaobjects-audit/references/prompt-anti-patterns.md": "3d74e5bd93e401a8fca5aa6282039a5fb6f27fbe245956843e7883f6c3a226f7", ".claude/skills/metaobjects-audit/references/surface-review-axes.md": "4ae96f1dcd2bf08c2c84dfa2b07eaafaa52f89a8ec524006bc8e41c8a1f4024c", - ".claude/skills/metaobjects-audit/references/typescript.md": "23ba8c75ebf4f28bf1f775c3e5ac28d041f6b59de4c54de191c84f8714f7d227", + ".claude/skills/metaobjects-audit/references/typescript.md": "0c80e15300f984105ad60ed0b7e7a3d1daf480b5b68353bfaac7cff0ba2b8296", ".claude/skills/metaobjects-audit/references/vocabulary-hygiene.md": "ba78f1568b213d1c49ae4d620c5a7830b3af0ee16896cc929949c9db64611834", ".claude/skills/metaobjects-authoring/SKILL.md": "83dd1ba908b67daaa5ab3cca0e959ba738fb55c2cf2a0b18cbbbfd222b279c0b", ".claude/skills/metaobjects-authoring/references/abstracts-and-overlay.md": "fb3d3670ae38753029f351fe9a3fe0225160c7117d5ea851edceb7b19ce8f4ac", @@ -25,34 +25,35 @@ ".claude/skills/metaobjects-authoring/references/identities-and-indexes.md": "c6b34446ae6d2de5264e8e18b3fb6a7f058bb79d342d74a6af6a5ae2f4fe5904", ".claude/skills/metaobjects-authoring/references/inheritance-tph.md": "42ba2a0fe47b9c180bdbbf83a1e19dc995bfa9c884fa821d448c26ff4e2b4c81", ".claude/skills/metaobjects-authoring/references/json-columns.md": "6afa98a9c7fd23f6698c916f6e608188f5cc45a612b598f24064ce6f2cc41d88", - ".claude/skills/metaobjects-authoring/references/metadata-dependencies.md": "460a5aaafcad64a7fea1dfb167aa30f48820c0b5fb3d9ab2fcc235e533672373", + ".claude/skills/metaobjects-authoring/references/metadata-dependencies.md": "bab9ed12bd7774f1c736f927bff96e1cb700a2301e701242d852d98aac8cc2aa", ".claude/skills/metaobjects-authoring/references/model-first-rationale.md": "fda1a58ac1585828110d1d2a8cb186bef4eefc7b36e056a416d9702f75abbe13", ".claude/skills/metaobjects-authoring/references/read-views-and-projections.md": "97f11f7f11f9dad47ab00163fb717f89ab5e0f106bfbbd24c114e8a229f8697a", ".claude/skills/metaobjects-authoring/references/relationships.md": "e985f8151935157dcc1e19bea096fd2adf9904c0779688a79eb108e652df9919", ".claude/skills/metaobjects-authoring/references/reporting.md": "4cbb1c1986a5e8f2c1d086d0edfe0a3b9c2ca290f2a7b405181de92613a1f906", ".claude/skills/metaobjects-authoring/references/sources.md": "4d989cc0f24fd81cc7751defc54e165c3b53a11a074a3b4141b6de3d0465c721", - ".claude/skills/metaobjects-codegen/SKILL.md": "c29946bc64c6c8792020372ed5c0bb3749269fe785bed5bcb22c472536caf5db", - ".claude/skills/metaobjects-codegen/references/any-stack.md": "ed93d18ba04e96a155efdf1eda646146fd0536293480560bd6b4fce87a2fdc62", + ".claude/skills/metaobjects-codegen/SKILL.md": "b1f676bbdd272e4f33f918f65c820204287064706896659d012fb893053c1192", + ".claude/skills/metaobjects-codegen/references/any-stack.md": "4426fbef79f236fb7d33a457fc15f1ab070ab4e705913971533df506f14ec163", ".claude/skills/metaobjects-codegen/references/choosing-layers.md": "8cd1bca8a659b6efc35e31b3dfbe2c5da75f418445a6f1a5eef48fb266faf640", - ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md": "7776d68b052ac8603f67241a64fedca1c1ba56e58bbfb2dc9bf5c8b39352a133", + ".claude/skills/metaobjects-codegen/references/dependencies-and-shared-models.md": "c7a76bc1e0c3ef3394187df6b67a7a019d3e6e69eae282615f2e0c604ae3be86", ".claude/skills/metaobjects-codegen/references/owning-generators.md": "73f727084a09b1ce6d69b861f60844082dc74d9a059f93414162c7f41253a65e", ".claude/skills/metaobjects-codegen/references/physical-names.md": "e36469fe8a7a32fa1518def9a832fef7465511b3342c4629f14680252b92b65d", ".claude/skills/metaobjects-codegen/references/template-or-code.md": "f745f2c1411ab2f09009f88a4c5c68c0012946b2eeb17559ab1ad40b10af0d71", - ".claude/skills/metaobjects-codegen/references/typescript-docs.md": "ec072e6077e0ffffc4fb0850088311d62aa2434892c8afdb118c1901ddac96d9", + ".claude/skills/metaobjects-codegen/references/typescript-docs.md": "05f8eb56bfcab14bf0f131af36e78c11e5b69e92d6fb06933a6853ac161282a4", ".claude/skills/metaobjects-codegen/references/typescript-document-store.md": "cd51977a8606eb6d7e690c66ae8fea9eadb6e734c32724e4f2a57e2193433068", ".claude/skills/metaobjects-codegen/references/typescript-mysql.md": "103a368daf29e749c53649511b5309a4d685281d11ad76af2e8a5ff17b5c412a", + ".claude/skills/metaobjects-codegen/references/typescript-prisma.md": "1e292839ec10ca121ead9a4639856a86f5689dd73dddd00f98e55131e57ed1ce", ".claude/skills/metaobjects-codegen/references/typescript-retargeting.md": "6935df5f6afbbf93b391577f0d2e296e56ae9ef7ccef647fffca3dd58073a472", ".claude/skills/metaobjects-codegen/references/typescript-templates.md": "5a2f3bbdcf835d47b522c31fda6427cc8d6dda76099102997d9eeb75a9d4c38c", - ".claude/skills/metaobjects-codegen/references/typescript.md": "8fcd616c676824aeaa1d462d01fe2bb5399d06d78064ba7cc3c64f33e75feacc", + ".claude/skills/metaobjects-codegen/references/typescript.md": "6dbe76f0fb78d3ba4d25535e19631b7a2bc4df6cf404d1b7c90ac0db5a47bfae", ".claude/skills/metaobjects-codegen/references/wire-format.md": "6658fb34c62294e488884ed0954b0c311690193564f82a99b6693d887c8aec3f", - ".claude/skills/metaobjects-prompts/SKILL.md": "fd9b0bef42289dcd5baf7f3008c65883bcf050fcb94116ed281aa03235bd6608", - ".claude/skills/metaobjects-prompts/references/typescript.md": "d6dbeae2c61c4b0de29fa2469079dfaf8ca67cec8b8cb4cec88868e075605670", + ".claude/skills/metaobjects-prompts/SKILL.md": "a1b81119468f84a94a3293d85c3b2d3298b6c4819c5ab9da3ccdd89442e384a5", + ".claude/skills/metaobjects-prompts/references/typescript.md": "0fe543fe1b3c9b3cb86f06bb361deecacb64c4d519f07da498418278663cd7e3", ".claude/skills/metaobjects-runtime-ui/SKILL.md": "636330ce42428c382f248a2a5720b4bf43ee2508d0eae8ca8757be7fb0227b86", ".claude/skills/metaobjects-runtime-ui/references/react.md": "1ed66f8d84192ee1ebe89d8e92b9ff1ce7ad4dc5c4963d3858a2ceea057b6ea8", ".claude/skills/metaobjects-runtime-ui/references/typescript.md": "494853543fba1c5f01c1469d2512b92821a5986e57b7bf737bc68583ed354061", - ".claude/skills/metaobjects-verify/SKILL.md": "cc0705960d97920840583fbc21bf7fdb3238997d550766e0b95393bf84a1b6a3", + ".claude/skills/metaobjects-verify/SKILL.md": "ea4d8e1a2b98bedd5bf0880ee1189a355e430255fb19f263281c79b00e66652c", ".claude/skills/metaobjects-verify/references/migration.md": "37d24154a7e09e271612e98f835b7d24954fac9b3613ec975db1e65d27b55e92", - ".metaobjects/AGENTS.md": "b75331ccb693b1ee543b7c94a6a3f2bdaaf48e4c608a8ea35c4493d0e3ba9fac", - ".metaobjects/CLAUDE.md": "b75331ccb693b1ee543b7c94a6a3f2bdaaf48e4c608a8ea35c4493d0e3ba9fac" + ".metaobjects/AGENTS.md": "3ee120a69db7a2d82d306ded4bfc2388fd9557efc88db09d1fe688d165cac4bb", + ".metaobjects/CLAUDE.md": "3ee120a69db7a2d82d306ded4bfc2388fd9557efc88db09d1fe688d165cac4bb" } } diff --git a/.metaobjects/.gen-state/.hashes.json b/.metaobjects/.gen-state/.hashes.json index 194c8cd..1b2f9c4 100644 --- a/.metaobjects/.gen-state/.hashes.json +++ b/.metaobjects/.gen-state/.hashes.json @@ -2,7 +2,7 @@ "docs/generated/site/assets/search-index.json": "9f35b6b37ecaf0aa5cd1936fe7a898974298fdf00ce092724591d406303844ea", "docs/generated/site/assets/site.css": "cdc91339b922cc181e6013c5f244c310acf279dca8cdf1725d77497fcef9d6df", "docs/generated/site/assets/site.js": "af542bdd4896fcd8b5f9a39a459a7882c30c1f4494a2e4e08696e2dfc62074a9", - "docs/generated/site/coverage.html": "0a0cc419962e0c2058d34f8763cc8fcc9b8435280a741e32a1d23d0f1535767e", + "docs/generated/site/coverage.html": "dd3b109b9c7712a0ac6c8ba4095c47fcb498ef378568730860f77038de28a67d", "docs/generated/site/enums.html": "8416152afda75ad45fbd2e563b3b58516e04533ac207a4d6ed18b3a7049b8e4d", "docs/generated/site/index.html": "5690bad02c8b9bc024e3de51ca194cf266b99a50dadeb6333b18a6c29a602bdb", "docs/generated/site/wizardsofodd/Council.html": "d03a7fed07409414bc25c96fdf309ab50c842859f5e1b93a9558d6fb3b18e2e7", @@ -33,8 +33,8 @@ "docs/generated/site/wizardsofodd/dominoSystem.html": "74b01c86e563a80ff5654cdff2f4882fee49220d28fa650c1b8f0ee3febd92e6", "docs/generated/site/wizardsofodd/dominoUser.html": "ff08aca56b674dcf527eb258c0edf599eef32e8bff6df5b433c551b5f6fee0e1", "docs/generated/site/wizardsofodd/doneFrame.html": "b1eb34b8980b475fdbf1a8ecbf312ee3d19a9be04b3c6aea744b99dbd45891d1", - "docs/generated/site/wizardsofodd/emitVerdict.html": "89c3a1cf38d5aa1ec3f59411726e51e931e83f49a29aa80e5dc1568cde1031cf", - "docs/generated/site/wizardsofodd/emitWizardTake.html": "2eed650f7131c35eabb0b4c2eaca62076be96201bd869b72adf08b61d2d8b704", + "docs/generated/site/wizardsofodd/emitVerdict.html": "6c24684d1220249c843d8beef775abc164bfa154068be62e899a690d7aaf54e9", + "docs/generated/site/wizardsofodd/emitWizardTake.html": "99fd216494b9d34cd4623ff2358673d51e39f504042b98dfca8685ed63b0f442", "docs/generated/site/wizardsofodd/errorFrame.html": "8a041eb1bc1511dcbf421a480cec54f571daa4aa9c9cd1fe9dd78bae4421a0c3", "docs/generated/site/wizardsofodd/fabulaSystem.html": "972d9cf1762bcb256bfb9a911535485098a05dba730d4c45ca06df12b2bb2e76", "docs/generated/site/wizardsofodd/fabulaUser.html": "3f56d7340ead4b348a5e107612061b292b98bb86649df4cb1c0c69245346ab8f", @@ -57,26 +57,26 @@ "docs/generated/site/wizardsofodd/vexilSystem.html": "1eb4e49aef208f88ab2f49c8132dd2524278c50fa4fc9ce50a999186a92fe3d6", "docs/generated/site/wizardsofodd/vexilUser.html": "268ef47f0e488e16a0498bdfb92f55ad01555e656b8d59f890461410c94a1ec2", "docs/generated/site/wizardsofodd/wizardFrame.html": "4dda9a3fa0d798df0caf5a2803c02a9998927c65c46b70cbc7828cc6c5c6ddfc", - "src/db/generated/Council.lineage.ts": "b6e962840c41f963de3dceb9443e2de0ed80c62aed393a261924ac9c64b1f47d", + "src/db/generated/Council.lineage.ts": "e4ae19ec9ac89efbb06fe3e4d703230f41473f4ac6da4f6b6d54495ee6ece6e4", "src/db/generated/Council.names.ts": "7639829ce25c2652fd3cb43b8a8715a524436ac589e76f4a50ab4167a71e1e3d", - "src/db/generated/Council.queries.ts": "32e7dde8387ee6fc750e09c70b4725d570def791180ae66e19fa28543bd48942", - "src/db/generated/Council.ts": "27c8f4eb87273c27605f44c076df451d0435056090ff8e7fd8e979db9890bf7c", + "src/db/generated/Council.queries.ts": "7f16bd599e682f1f9fff6320bf14d2939aea13607146e3d4b9e014f6cf0b70ec", + "src/db/generated/Council.ts": "2a3281018980f57536c913dbd1c3b380a55bb887b3d25aca390ab48dfc78a656", "src/db/generated/CouncilFramePayload.ts": "e874aab4391ec529fe9752bea1161ae79c37f1790f1c91ccd15c79758dc59153", "src/db/generated/CouncilRequest.ts": "63b023fc6ff0fffbfd82a492ee8d596bde8add808ebfbbafa48165f291e19ad6", - "src/db/generated/CouncilTurn.lineage.ts": "8b1eea473344ff2113c94464f528a9f683aa306971f87feaff3f36ad7c6a08f4", + "src/db/generated/CouncilTurn.lineage.ts": "9cea15ac464301230739aacfd780dad653887d5f733816df408cc124cd39837e", "src/db/generated/CouncilTurn.names.ts": "dce73f3e62ba305d1101ab21ee9467a61cf89fb9c4779998b4649b8a4de46b55", - "src/db/generated/CouncilTurn.ts": "d0f16cb134036e634c4c7a103566e733e10989a2ec1fb40b4966bcfff688c572", + "src/db/generated/CouncilTurn.ts": "54612b61a4c0f41b0cf0fc1f1bfa270d13f6f07e927bc7f4cda53e5aad34ac53", "src/db/generated/Dissent.ts": "62dc434107da66d2538870468264e5ea5c5359c4ab83021a7165235db5d086df", "src/db/generated/DoneFramePayload.ts": "41d587bfb531edbb29ca7fd68feba89678d879e4fde36d1f377bfbaf25699b3b", "src/db/generated/ErrorFramePayload.ts": "f036b7d8e2b9bcc45daeb52e74acafcd874f4ed0cfcaafe134579e228eb6e9c8", "src/db/generated/RivalLens.ts": "d9d333f1fe5887b19515d89d775c1280ea825e9b999427fda348583ec3760125", "src/db/generated/RosterLens.ts": "b9ddecda801bb906efa25d1ecabcd20f3638e12d64c6cd8a46ee54f67c38bf56", - "src/db/generated/SharedCouncil.lineage.ts": "66eede9515d9ec1f380bebcb356c8ec4e4a809ada2f1d742b1c1b1ced84b4e3c", + "src/db/generated/SharedCouncil.lineage.ts": "9917d67c2bcff0ef9409827334ca3ae0fcd44ad15cb26f3a86fb288b26adf4e0", "src/db/generated/SharedCouncil.ts": "1541c8defa5826394a0411f220be3af6ab1722bc69a95ce0a6a7a047cbe0fa57", - "src/db/generated/SharedTurn.lineage.ts": "d11511ee0b3715ac3cdcad64d3b52eef482d73a853eded8f30957b7847c8de12", + "src/db/generated/SharedTurn.lineage.ts": "5e673bb83d5dc805664ff4b33db36a6bf7bd04b377f10413f1ff383db04cbe48", "src/db/generated/SharedTurn.ts": "65cb8944ae422f6e676e586d398afe0ffdc79f15578c2d97ad6e339874107425", "src/db/generated/SourceLens.ts": "36f865d7eed7d4422ebb1b52ab13c7b7fe42761de4c7dc1283e34b255e920ce4", - "src/db/generated/TurnLens.lineage.ts": "22fb0b7a6b9a01ae0b119899e1d013ae55975cb8d22efe8d72f3c40b49a15c18", + "src/db/generated/TurnLens.lineage.ts": "9712aa0f05ce648dceb60e9176b7f8d8c0983d0c2b86b344975b09d159166095", "src/db/generated/TurnLens.ts": "fb70ef7c8ef67ad036ee313e3336950fdedd46133d7df29f5974d813465157cf", "src/db/generated/VerdictFramePayload.ts": "b46de701da77068605db31077df9282edec376a8c289845752a378ee721874a5", "src/db/generated/VerdictOutput.ts": "115ab80a192c5efbe24f22105a7a778d47628031e28fb3a2b715dc98939e2dc9", @@ -88,11 +88,11 @@ "src/db/generated/WizardSystemPayload.ts": "1a83b4efb6f51c42beffb6a4d31815937a813d1ab6ee83da619a0b10385a6e30", "src/db/generated/WizardUserPayload.ts": "619c9c9c95c4fb397378897e8c1bdfdf1b7d422e7ea14865a3cd43c22b151d29", "src/db/generated/enums.ts": "813c6e9fc5b198c67d67338d9daeb38fcb492e5af97a97ff9d3abbfaad3cf4af", - "src/db/generated/index.ts": "c154e4dc7e74c5e0783982bb21a1bf567dfe80a92ed3d9dde6afd9ee135d7c8d", - "src/llm/generated/toolcalls.ts": "51779866fcc6dd751ab89f42880e532d4ae63588cdb0391cd88f9dac196ae96b", - "src/personas/generated/registry.ts": "1389f50d593cc3bded2dc61bc66acc57b791f6e33d4564017ef4f5f6324e7019", - "src/personas/generated/wizards.ts": "45c28aea4862cf75651f00581c8a19c2507b14a72651e89df622a83b72a88ce9", + "src/db/generated/index.ts": "866c08b1059a28f80043e24fe2cda8e71646bd96ed4f8b2d2fc53dbb2c7bc414", + "src/llm/generated/toolcalls.ts": "103788cb92e05530dba233dffc0a26db9cf13d93cf1313b054441fc6520005a7", + "src/personas/generated/registry.ts": "79457b454b1e5d16347c019dfee1b2af23af41e5d6b6e66a9d306d9c4ba25a75", + "src/personas/generated/wizards.ts": "e26d118ebcbd1197a6217e5a376f39e5f0a52b0493120d6ec22da975a5492b3a", "src/render/generated/prompts.ts": "773274d07c04940087f8f6d987b983638e32d5d8a1289a14941f067f1b5a636e", - "src/render/generated/templates.ts": "7511ae43e21c4d6f938783af98d04c218322e96358fb0e2d1f1b74a2ead4f7c8", - "src/web/generated/council-frames.ts": "6691c8b8cbcefe6738660dfac994c459c18f7217a3e2deebcf0b8b64d5613966" + "src/render/generated/templates.ts": "b6f280dab37d79718562c16765459be20dfab4fe8ba1fbc3bd24161ce34d411c", + "src/web/generated/council-frames.ts": "8fe37793729bff1319d7fe1eeb71512f126b1440551ba06a93fdd72a9713472a" } diff --git a/.metaobjects/AGENTS.md b/.metaobjects/AGENTS.md index 27f60cf..97d0722 100644 --- a/.metaobjects/AGENTS.md +++ b/.metaobjects/AGENTS.md @@ -59,9 +59,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has ## Keep all MetaObjects ports in sync MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/v1.1.4/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. -**Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/v1.1.4/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. +**Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. ## Going deeper (Claude Code) For authoring, codegen, runtime/UI, prompts, verify, or adoption-audit work, use the diff --git a/.metaobjects/CLAUDE.md b/.metaobjects/CLAUDE.md index 27f60cf..97d0722 100644 --- a/.metaobjects/CLAUDE.md +++ b/.metaobjects/CLAUDE.md @@ -59,9 +59,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has ## Keep all MetaObjects ports in sync MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/v1.1.4/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. -**Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/v1.1.4/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. +**Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/v1.2.0/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. ## Going deeper (Claude Code) For authoring, codegen, runtime/UI, prompts, verify, or adoption-audit work, use the diff --git a/CLAUDE.md b/CLAUDE.md index 8976631..f7679a4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,11 +21,11 @@ protocol, with a build-time drift gate. See [`README.md`](README.md) and | Runtime | **Cloudflare Workers** (one Worker serves static assets + `/api/*`) | | Framework | [Hono](https://hono.dev/) | | Frontend | React 18 SPA (Vite) for the home route; pure-SSR React for `/c/:slug` share routes | -| LLM | Anthropic Claude API (`claude-sonnet-4-6` by default) | +| LLM | Anthropic Claude API (`claude-sonnet-4-6`, declared as `@model` on each `template.toolcall`) | | Persistence | Cloudflare D1 + Drizzle, schema + queries driven by MetaObjects codegen (ADR-0002) | | Rate limit / bot gate | Workers KV + Cloudflare Turnstile | | Search (optional, Lorekeeper's RAG) | a self-hosted SearXNG behind Cloudflare Access, via the `SEARCH_URL` secret; degrades gracefully if unset | -| Metadata / codegen | `@metaobjectsdev/*@1.1.4` — loader, `meta gen` (codegen), `meta verify` (drift gate) | +| Metadata / codegen | `@metaobjectsdev/*@1.2.0` — loader, `meta gen` (codegen), `meta verify` (drift gate) | | Tests | Vitest via `@cloudflare/vitest-pool-workers` + jsdom | ## Layout @@ -40,7 +40,7 @@ metaobjects/ the metadata SPINE (typed, durable) data/ instance data OUTSIDE the spine (loadMemory() treats metaobjects/ as metadata) wizards/*.yaml the 10 wizard personas templates/ external Mustache prompt text (wizards/, verdict/) -codegen/generators/ OWNED entity/queries/barrel generators (ADR-0034 scaffold-and-own) +codegen/generators/ OWNED composition-loaders generator (Council + its ordered turns) src/ index.ts Hono Worker: council SSE endpoint, Env, Turnstile + rate-limit gates council/ orchestrator.ts (convene) · prompts.ts (compose generated handles) diff --git a/README.md b/README.md index 90006a6..452c45f 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,11 @@ disposable artifact. This app is a working proof: **one spine → many outputs, | Metadata (`metaobjects/`, `data/`) | Generator | Generated artifact | Consumed by | |---|---|---|---| -| `object.entity` (Council, CouncilTurn) — `source.rdb`, identity, `field.enum`, `field.object`, `relationship.composition` | `entityFile` / `queriesFile` | Drizzle D1 tables + Zod + typed finders + the `findCouncilWithTurns` aggregate read (`src/db/generated/`) | `src/db/queries.ts`, share routes | +| `object.entity` (Council, CouncilTurn) — `source.rdb`, identity, `field.enum`, `field.object`, `relationship.composition` | `entityFile` (shipped) / `compositionLoaders` (owned) | Drizzle D1 tables + Zod + the `findCouncilWithTurns` aggregate read (`src/db/generated/`) | `src/db/queries.ts`, share routes | | field-level `extends: .` lineage | `lineageMappers` (custom) | typed copies between `WizardOutput` and its descendants, and the public `SharedCouncil` view of a council row (`src/db/generated/*.lineage.ts`) | persistence, share page + JSON, prompt payloads | | `object.value` payloads + `template.prompt` | `promptRender` | typed render handles (`src/render/generated/prompts.ts`) | `src/council/prompts.ts` | | Mustache text (`data/templates/`) | `mustacheTemplates` (custom) | inlined template map + its `templateProvider` (`.../templates.ts`) | every render call | -| `template.toolcall` | `structuredCompletion` (custom) | Anthropic `tool_use` wrappers + retry/fallback ladder (`src/llm/generated/toolcalls.ts`) | orchestrator | +| `template.toolcall` (with `@model`, `@maxTokens`) | `structuredCompletion` (custom) | Anthropic `tool_use` wrappers carrying the model id and token budget + retry/fallback ladder (`src/llm/generated/toolcalls.ts`) | orchestrator | | `template.streamFrame` (a **project-local subtype**) | `sseFrames` (custom) | `CouncilFrame` discriminated union + `encodeCouncilFrame` / `toCouncilFrame` (`src/web/generated/council-frames.ts`) | orchestrator, Worker **and** React reducer | | Wizard instance data (`data/wizards/`) | `wizardData` + `wizardRegistry` (custom) | typed roster + render registry (`src/personas/generated/`) | orchestrator + gallery | @@ -132,7 +132,7 @@ Portraits/background are AI-generated (local SDXL) and covered by the repo licen ``` metaobjects/ the metadata spine (entities, value-objects, prompts, toolcalls, sse-frames) data/ instance data OUTSIDE the metadata: wizard YAML + Mustache prompt text -codegen/ owned generators (entity/queries/barrel — ADR-0034 scaffold-and-own) +codegen/ owned composition-loaders generator (entity, barrel and names run as shipped) src/codegen/ custom generators + the project provider src/**/generated/ generated code (drift-gated; never hand-edited) src/ the Worker: council orchestrator, D1 layer, LLM calls, React SPA, SSR share pages diff --git a/codegen/generators/barrel.ts b/codegen/generators/barrel.ts deleted file mode 100644 index 4d0d943..0000000 --- a/codegen/generators/barrel.ts +++ /dev/null @@ -1,73 +0,0 @@ -// REFERENCE TEMPLATE — copy this into your repo (e.g. codegen/generators/barrel.ts) and own it. -// Then import it LOCALLY in metaobjects.config.ts instead of from the package: -// import { barrel } from "./codegen/generators/barrel.js"; -// -// RUNTIME: this file executes under whatever runs `meta gen`, and the published CLI's -// shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not -// reach for `Bun.*` globals here; they are undefined and take the whole run down with -// `Bun is not defined`. Use `node:` builtins instead. -// targets: nothing framework-specific — it re-exports whatever the other generators -// emitted. `extStyle` decides whether the re-export specifiers carry a -// `.js` extension. -// use-when: you want a single `index.ts` re-exporting every generated entity module. -// emits: /index.ts with one `export * from "./"` per entity, alphabetical. -// customize: the export form (star vs named), ordering, grouping by package, what to include/exclude. -// composes-with: entity.ts (this re-exports the files entity.ts emits). -// -// Everything below imports ONLY from `@metaobjectsdev/codegen-ts` (the stable engine). -// The composition (`renderBarrel`) is inlined here so you own it — change it freely. - -import { - oncePerRun, - type Generator, - type GeneratorFactory, - type ExtStyle, - type ResolvedTarget, - barrelModuleSpecifier, - formatTs, - GENERATED_HEADER, -} from "@metaobjectsdev/codegen-ts"; - -interface BarrelEntry { - name: string; - package: string | undefined; -} - -// --- composition (OWNED) — the barrel file body. Customize freely. --- -function renderBarrel( - entries: BarrelEntry[], - extStyle: ExtStyle, - selfTarget: ResolvedTarget, - entityModuleTarget: ResolvedTarget, -): string { - const sorted = [...entries].sort((a, b) => a.name.localeCompare(b.name)); - const exports = sorted - .map((e) => `export * from ${JSON.stringify(barrelModuleSpecifier(selfTarget, entityModuleTarget, e.package, e.name, extStyle))};`) - .join("\n"); - return `// ${GENERATED_HEADER} — DO NOT EDIT.\n${exports}\n`; -} - -export interface BarrelOpts { - target?: string; -} - -export const barrel = function barrel(opts?: BarrelOpts): Generator { - const generator: Generator = { - name: "barrel", - generate: oncePerRun(async (entities, ctx) => ({ - path: "index.ts", - content: await formatTs( - renderBarrel( - entities.map((e) => ({ name: ctx.renderContext!.valueObjectEmittedName(e), package: e.package })), - ctx.renderContext!.extStyle, - ctx.renderContext!.selfTarget, - ctx.renderContext!.entityModuleTarget, - ), - ), - })), - }; - if (opts?.target) { - generator.target = opts.target; - } - return generator; -} as GeneratorFactory; diff --git a/codegen/generators/composition-loaders.ts b/codegen/generators/composition-loaders.ts new file mode 100644 index 0000000..16fbc56 --- /dev/null +++ b/codegen/generators/composition-loaders.ts @@ -0,0 +1,172 @@ +// OWNED generator: aggregate loaders for `relationship.composition`. +// +// Why this is custom: no shipped generator emits it. The stock `queries` generator +// (`queriesFile` from @metaobjectsdev/codegen-ts/generators) writes findById, list, +// create, update and deleteById for every stored entity, plus reverse FK finders, and +// takes no option to drop verbs or to load a composition. This app reads exactly one +// thing through generated code (a council with its ordered turns, src/handlers/share.ts) +// and writes bespoke, status-guarded updates by hand over the generated tables +// (src/db/queries.ts). Wiring the stock generator would emit eight helpers nothing +// calls, and its create/update parse input this app's writes never did. +// +// It used to be an ejected copy of the reference `queries` generator trimmed to reads. +// This replaces that copy: everything except the composition loader is the engine's own +// primitives (`renderFindByIdFn`, `dbTypeBlock`, the shared header), so the copy no +// longer falls behind the reference line by line. +// +// emits: .queries.ts for each stored object that composes a collection of parts +// (`relationship.composition`, cardinality many): findById and +// findWith, the root row plus its parts ordered by the rest of the +// part's primary key. +import { code, imp, joinCode, type Code } from "@metaobjectsdev/codegen-ts"; +import { + isMetaObject, + resolveObjectRef, + RELATIONSHIP_SUBTYPE_COMPOSITION, + type MetaObject, +} from "@metaobjectsdev/metadata"; +import { + perEntity, + type Generator, + type RenderContext, + dbTypeBlock, + effectivePackage, + entityModuleSpecifier, + entityOutputPath, + formatTs, + GENERATED_EDIT_NOTE, + GENERATED_HEADER, + getPkInfo, + hasAnyRdbSource, + renderFindByIdFn, + reverseFksFor, + sidecarLine, +} from "@metaobjectsdev/codegen-ts"; + +interface CompositionPart { + /** The relationship name: the parts' key in the aggregate (e.g. `turns`). */ + relName: string; + child: MetaObject; + /** The child's Drizzle table variable (e.g. `councilTurns`). */ + childTable: string; + /** The child's FK field that references the root (e.g. `councilId`). */ + fkField: string; + /** The child's primary-key fields after the FK, in order (e.g. [`ordinal`]). */ + orderFields: string[]; +} + +function compositionPartsOf(obj: MetaObject, ctx: RenderContext): CompositionPart[] { + const parts: CompositionPart[] = []; + for (const rel of obj.relationships()) { + if (rel.subType !== RELATIONSHIP_SUBTYPE_COMPOSITION || rel.cardinality !== "many") continue; + const { node: child } = resolveObjectRef( + ctx.loadedRoot, + rel.objectRef ?? "", + obj.package ?? obj.fileDefaultPackage ?? "", + ); + if (!child || !isMetaObject(child)) { + throw new Error(`composition-loaders: ${obj.name}.${rel.name} composes unknown object "${rel.objectRef}"`); + } + const fk = reverseFksFor(child).find((f) => f.targetEntity === obj.name); + if (!fk) { + throw new Error( + `composition-loaders: ${obj.name}.${rel.name} composes ${child.name}, which has no identity.reference to ${obj.name}`, + ); + } + const pkFields = child.primaryIdentity()?.fields ?? []; + parts.push({ + relName: rel.name, + child, + childTable: ctx.collectionName(child.name), + fkField: fk.fkField, + orderFields: pkFields.filter((f) => f !== fk.fkField), + }); + } + return parts; +} + +function moduleOf(obj: MetaObject, ctx: RenderContext): string { + return JSON.stringify( + entityModuleSpecifier(ctx.selfTarget, ctx.entityModuleTarget, effectivePackage(obj), obj.name, ctx.extStyle), + ); +} + +function renderLoader(obj: MetaObject, part: CompositionPart, ctx: RenderContext): Code { + const entityName = obj.name; + const parentVar = entityName.charAt(0).toLowerCase() + entityName.slice(1); + const relPascal = part.relName.charAt(0).toUpperCase() + part.relName.slice(1); + const aggregate = `${entityName}With${relPascal}`; + const { fieldName: pkField, tsType: pkType } = getPkInfo(obj, ctx); + const eqSym = imp("eq@drizzle-orm"); + const ascSym = imp("asc@drizzle-orm"); + const orderBy = part.orderFields.map((f) => code`${ascSym}(${part.childTable}.${f})`); + return code` +/** A ${entityName} with the ${part.child.name} rows it owns (relationship.composition \`${part.relName}\`). */ +export interface ${aggregate} { + ${parentVar}: ${entityName}; + ${part.relName}: ${part.child.name}[]; +} + +/** Load a ${entityName} and its \`${part.relName}\` (ordered by ${part.orderFields.join(", ") || "storage order"}); null when absent. */ +export async function find${aggregate}(db: Db, ${pkField}: ${pkType}): Promise<${aggregate} | null> { + const ${parentVar} = await find${entityName}ById(db, ${pkField}); + if (!${parentVar}) return null; + const ${part.relName} = await db + .select() + .from(${part.childTable}) + .where(${eqSym}(${part.childTable}.${part.fkField}, ${pkField}))${orderBy.length > 0 ? code` + .orderBy(${joinCode(orderBy, { on: ", " })})` : ""}; + return { ${parentVar}, ${part.relName} }; +} +`; +} + +function renderFile(obj: MetaObject, ctx: RenderContext): string { + const { import: dbTypeImport, alias: dbTypeAlias } = dbTypeBlock(ctx.dialect); + const sections: Code[] = [ + code` +${dbTypeImport} +${dbTypeAlias} + +import { ${ctx.collectionName(obj.name)}, type ${obj.name} } from ${moduleOf(obj, ctx)}; +`, + renderFindByIdFn(obj, ctx), + ...compositionPartsOf(obj, ctx).flatMap((part) => [ + code` +import { ${part.childTable}, type ${part.child.name} } from ${moduleOf(part.child, ctx)}; +`, + renderLoader(obj, part, ctx), + ]), + ]; + const header = + `// ${GENERATED_HEADER} — ${GENERATED_EDIT_NOTE}\n` + + `// Source metadata: ${obj.name} (${obj.fqn()})\n` + + sidecarLine(`${obj.name}.extra.ts`); + return header + joinCode(sections, { on: "\n" }).toString(); +} + +/** A stored object that owns at least one many-part composition. */ +function isCompositionRoot(obj: MetaObject): boolean { + return ( + hasAnyRdbSource(obj) && + obj.relationships().some((rel) => rel.subType === RELATIONSHIP_SUBTYPE_COMPOSITION && rel.cardinality === "many") + ); +} + +export function compositionLoaders(): Generator { + return { + name: "composition-loaders", + filter: isCompositionRoot, + // Sole producer of *.queries.ts: an object that stops being a root loses its file. + orphanPolicy: { owns: (relPath) => relPath.endsWith(".queries.ts") }, + generate: perEntity(async (entity, ctx) => { + if (!ctx.renderContext) { + throw new Error("composition-loaders: renderContext is required (provided by runGen)"); + } + return { + path: entityOutputPath(ctx.config.outputLayout ?? "flat", entity.package, `${entity.name}.queries.ts`), + content: await formatTs(renderFile(entity, ctx.renderContext)), + }; + }), + }; +} diff --git a/codegen/generators/entity.ts b/codegen/generators/entity.ts deleted file mode 100644 index d8fa4e3..0000000 --- a/codegen/generators/entity.ts +++ /dev/null @@ -1,192 +0,0 @@ -// REFERENCE TEMPLATE — copy this into your repo (e.g. codegen/generators/entity.ts) and own it. -// Then import it LOCALLY in metaobjects.config.ts: -// import { entityFile } from "./codegen/generators/entity.js"; -// -// RUNTIME: this file executes under whatever runs `meta gen`, and the published CLI's -// shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not -// reach for `Bun.*` globals here; they are undefined and take the whole run down with -// `Bun is not defined`. Use `node:` builtins instead. -// targets: Drizzle ORM + Zod. The emitted module is a Drizzle table plus Zod -// insert/update schemas; the column mapping follows `dialect`. On the -// default (vanilla) path, replace the `renderDrizzleSchema` / -// `renderZodValidators` calls to target a different ORM or validator — the -// metadata walk that feeds them is ORM-neutral. (The `isWriteThrough` -// branch calls `renderEntityFile` instead — a narrow #214 read-view case, -// not the default.) -// use-when: ALWAYS — this is the entity-module generator. It owns the shape of each -// generated .ts (the Drizzle table, Zod schemas, inferred types, -// constants, filter allowlists). Start here and adapt the assembly. -// emits: /.ts per concrete object — and the shared-enums module once. -// Dispatches: abstract/value → interface + Zod; projection → read-only view decl; -// write-through entity → full Drizzle table path. -// customize: reorder/drop sections in `sections` below; change the header; swap a sub-renderer -// for your own (each render* is an engine primitive you call). To deeply own one -// section (e.g. the Drizzle emit), copy/replace that sub-render call with your code. -// composes-with: queries.ts, routes.ts, barrel.ts (they import the files this emits). -// -// The composition (`renderEntity`) is the relocated body of the built-in entity composer — -// byte-identical to start, now YOURS to change. It imports only public engine primitives. - -// ts-poet combinators come from the engine package, NOT a bare "ts-poet" import: the -// Code sections composed here must share ONE ts-poet instance with the render* -// primitives below, or (with a globally-installed / linked CLI, where the project and -// the CLI resolve ts-poet to different physical copies) every section renders -// standalone with its own duplicate import header. -import { joinCode, type Code } from "@metaobjectsdev/codegen-ts"; -import type { MetaObject } from "@metaobjectsdev/metadata"; -import { - perEntity, - type EmittedFile, - type GenContext, - type Generator, - type GeneratorFactory, - type RenderContext, - // sub-renderers (engine primitives) — the LEGO blocks this composition assembles: - renderDrizzleSchema, - renderInferredTypes, - renderEnumTypeAliases, - renderZodValidators, - renderEntityConstants, - renderFilterAllowlist, - renderSortAllowlist, - renderFilterType, - renderTphDiscriminatorUnion, - isTphDiscriminatorBase, - renderProjectionDecl, - renderValueObjectFile, - renderSharedEnumsFile, - SHARED_ENUMS_BASENAME, - // predicates + helpers: - isProjection, - isWriteThrough, - isAbstract, - hasWritableRdbSource, - isTphSubtype, - // engine composer — used for the delegated write-through variant: - renderEntityFile, - // engine plumbing: - formatTs, - entityOutputPath, - namesRef, - namesConstArg, - GENERATED_HEADER, -} from "@metaobjectsdev/codegen-ts"; - -export interface RenderEntityOpts { - readonly allowlists?: boolean; -} - -// --- composition (OWNED) — assembles one .ts. Change this to change the output. --- -function renderEntity(entity: MetaObject, ctx: RenderContext, opts?: RenderEntityOpts): string { - const runtime = ctx.selfTarget.runtime; - const allowlists = runtime ? (opts?.allowlists ?? true) : false; - - // Abstract → shape only (interface + Zod), never a table. - if (isAbstract(entity)) { - return renderValueObjectFile(entity, ctx.apiPrefix, ctx); - } - // Projection → read-only view declaration + read schema. - if (isProjection(entity)) { - // §A6/§B2 — same `namesRef` pair renderDrizzleSchema builds, so the projection's view - // name + per-field dbCol reference the exact constant the names artifact exports - // (undefined when the artifact is not in this run). `namesRef`'s `{ resolved, symbol }` - // return is exactly the shape `ProjectionDeclOpts.names` wants. - return renderProjectionDecl(entity, ctx.loadedRoot, { - columnNamingStrategy: ctx.columnNamingStrategy, - dialect: ctx.dialect, - apiPrefix: ctx.apiPrefix, - timestampMode: ctx.timestampMode, - allowlists, - ctx, - includeViewDecl: runtime, - names: namesRef(entity, ctx), - }); - } - // Value-only / contract target → interface + Zod, no Drizzle table. - // - // A TPH subtype (FR-017) routes here too. It INHERITS the discriminator base's writable - // source.rdb through `extends`, so `hasWritableRdbSource` is true for it under the - // ADR-0039 resolving read — but the base owns the single shared table. Without the - // isTphSubtype clause this template fell through to the vanilla path and emitted a - // SECOND Drizzle table bound to the base's physical name, carrying only the subtype's - // own columns. - if (!runtime || !hasWritableRdbSource(entity) || isTphSubtype(entity)) { - return renderValueObjectFile(entity, ctx.apiPrefix, ctx); - } - // #214 — a write-through entity read-view (writable table + a read-only replica view + - // derived origin.* fields) needs the hybrid file (table + `.existing()` view decl + a - // z.infer read type carrying the derived fields). Delegate to the engine composer rather - // than duplicate that branch here (mirrors the projection delegation above). - if (isWriteThrough(entity)) { - return renderEntityFile(entity, ctx, { allowlists }); - } - - // Vanilla entity → the full Drizzle table file. Reorder/drop sections freely. - const enumAliases = renderEnumTypeAliases(entity, ctx); - const tphBlock = renderTphDiscriminatorUnion(entity, ctx.loadedRoot); - const tphBase = tphBlock !== null && isTphDiscriminatorBase(entity, ctx.loadedRoot); - // §A6/§B2 — same `namesRef` pair renderDrizzleSchema (and the projection branch above) - // build, so the descriptor's $table references the exact constant the names artifact - // exports (undefined when the artifact is not in this run). - const constantsNames = namesRef(entity, ctx); - const sections: Code[] = [ - renderDrizzleSchema(entity, ctx), - renderInferredTypes(entity, tphBase, ctx), - ...(enumAliases !== null ? [enumAliases] : []), - renderZodValidators(entity, ctx), - renderEntityConstants(entity, ctx.apiPrefix, namesConstArg(constantsNames)), - ...(allowlists ? [renderFilterAllowlist(entity, undefined, ctx), renderSortAllowlist(entity)] : []), - renderFilterType(entity), - ...(tphBlock !== null ? [tphBlock] : []), - ]; - - const body = joinCode(sections, { on: "\n" }).toString(); - const header = - `// ${GENERATED_HEADER} — DO NOT EDIT.\n` + - `// Source metadata: ${entity.name} (${entity.fqn()})\n` + - `// Customize via ${entity.name}.extra.ts in this directory.\n`; - return header + body; -} - -export interface EntityFileOpts { - filter?: (entity: MetaObject) => boolean; - target?: string; - allowlists?: boolean; -} - -export const entityFile = function entityFile(opts?: EntityFileOpts): Generator { - const allowlists = opts?.allowlists ?? true; - const perEntityEmit = perEntity(async (entity, ctx) => { - if (!ctx.renderContext) { - throw new Error("entity-file: renderContext is required (provided by runGen)"); - } - if (isAbstract(entity) && !ctx.renderContext.emitAbstractShapes) { - return []; - } - return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", entity.package, `${entity.name}.ts`), - content: await formatTs(renderEntity(entity, ctx.renderContext, { allowlists })), - }; - }); - - const generator: Generator = { - name: "entity-file", - emitsEntityModule: true, - generate: async (ctx: GenContext): Promise => { - const files = await perEntityEmit(ctx); - // FR-019: emit the shared-enums module once per run (null → no file). - const sharedEnums = renderSharedEnumsFile(ctx.loadedRoot); - if (sharedEnums !== null) { - files.push({ path: `${SHARED_ENUMS_BASENAME}.ts`, content: await formatTs(sharedEnums) }); - } - return files; - }, - }; - if (opts?.filter) { - generator.filter = opts.filter; - } - if (opts?.target) { - generator.target = opts.target; - } - return generator; -} as GeneratorFactory; diff --git a/codegen/generators/queries.ts b/codegen/generators/queries.ts deleted file mode 100644 index 1cc4efb..0000000 --- a/codegen/generators/queries.ts +++ /dev/null @@ -1,291 +0,0 @@ -// REFERENCE TEMPLATE — copy this into your repo (e.g. codegen/generators/queries.ts) and own it. -// Then import it LOCALLY in metaobjects.config.ts: -// import { queriesFile } from "./codegen/generators/queries.js"; -// -// RUNTIME: this file executes under whatever runs `meta gen`, and the published CLI's -// shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not -// reach for `Bun.*` globals here; they are undefined and take the whole run down with -// `Bun is not defined`. Use `node:` builtins instead. -// targets: Drizzle. Emitted helpers take `db` as a PARAMETER rather than importing -// a module singleton, so they compose with any caller that already holds a -// connection — including a server-rendered component. Swap the -// `renderFn` primitives (findById/list/create/update/deleteById) and -// the inline `Db` type block above them to emit for another query builder. -// use-when: you want generated typed finders over Drizzle. Drop it if you hand-write -// all of your data access. -// THIS COPY: trimmed to the READS this app makes (a worked example of the "drop verbs" -// customization). This app's writes are bespoke — hand-rolled inserts and -// updates in src/db/queries.ts over these generated row types — the same -// stance as the deliberately-absent routes generator (see -// metaobjects.config.ts). So create/update/delete, and the #203 -// insertPreserving escape hatch that attaches to create, are all dropped. -// The stock create/update also PARSE their input against the insert/update -// schema, which this app's writes never did — adopting them would start -// rejecting rows written today. `list` is dropped too (nothing pages), and -// a composition PART (CouncilTurn) gets no file of its own: it is read -// through its aggregate root's findWith loader (added below). -// emits: /.queries.ts per source-backed object (any source.rdb kind, -// incl. read-only projections) — skipped for sourceless objects (incl. every -// object.value, source-less by value purity) and TPH subtypes (#248 R2). -// customize: the vanilla CRUD assembly below is OWNED — reorder, drop verbs (e.g. no delete), -// change the Db type alias, add your own finders. The renderFn primitives emit -// each block; call your own instead to change a verb's body. -// composes-with: entity.ts (imports the table + InsertSchema it emits). -// -// NOTE: the advanced TPH-base + projection variants delegate to the engine's composer -// (`renderQueriesFile`) — they're rarely customized. To own those too, copy their branches -// out of the package source. The vanilla path here is byte-identical to the built-in. - -// ts-poet combinators come from the engine package, NOT a bare "ts-poet" import: the -// Code sections composed here must share ONE ts-poet instance with the render* -// primitives below, or (with a globally-installed / linked CLI, where the project and -// the CLI resolve ts-poet to different physical copies) every section renders -// standalone with its own duplicate import header. -import { code, imp, joinCode, type Code } from "@metaobjectsdev/codegen-ts"; -import { - isMetaObject, - resolveObjectRef, - RELATIONSHIP_SUBTYPE_COMPOSITION, - type MetaObject, -} from "@metaobjectsdev/metadata"; -import { - perEntity, - type Generator, - type GeneratorFactory, - type RenderContext, - entityModuleSpecifier, - renderFindByIdFn, - renderReverseFinderFns, - reverseFksFor, - getPkInfo, - isTphDiscriminatorBase, - isProjection, - isWriteThrough, - isTphSubtype, - hasAnyRdbSource, - renderQueriesFile, // engine composer — used for the delegated variants - formatTs, - entityOutputPath, - GENERATED_HEADER, -} from "@metaobjectsdev/codegen-ts"; - -// --- composition (OWNED for the common case) --- -function renderQueries(obj: MetaObject, ctx: RenderContext): string { - // Advanced variants delegate to the engine (byte-identical). Own them by copying their source. - // #214 — a write-through entity read-view (reads → replica view, writes → table) delegates - // too; owning it inline would duplicate the hybrid read/write routing. - if (isTphDiscriminatorBase(obj, ctx.loadedRoot) || isProjection(obj) || isWriteThrough(obj)) { - return renderQueriesFile(obj, ctx); - } - - const entityName = obj.name; - const entityFileName = entityModuleSpecifier( - ctx.selfTarget, - ctx.entityModuleTarget, - obj.package, - entityName, - ctx.extStyle, - ); - const varName = ctx.collectionName(entityName); - - // `db` is parameter-passed into every finder (ADR-0008). Emit the dialect-correct - // Drizzle type alias so signatures typecheck without the consumer constructing one. - // Keep EVERY type argument as open as Drizzle's own constraint allows — a `Db` this - // alias cannot name is a helper nobody can call, and uncompilable generated code looks - // exactly like unused generated code from outside. Both the driver axis (base classes, - // not `NodePgDatabase` / `<"async">`) and the schema axis (`Record`, - // Drizzle's own `TFullSchema extends …` bound, NOT its `Record` default) - // have been re-pinned once already; do not narrow either again. A schema-carrying - // `drizzle(client, { schema })` must assign, and so must a schema-less `drizzle(client)`. - const dbTypeImport = - ctx.dialect === "postgres" - ? `import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core";` - : `import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core";`; - const dbTypeAlias = - ctx.dialect === "postgres" - ? `type Db = PgDatabase>;` - : `type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>;`; - - const literalImports = code` -${dbTypeImport} -${dbTypeAlias} - -import { ${varName}, type ${entityName} } from ${JSON.stringify(entityFileName)}; -`; - - const sections: Code[] = [ - literalImports, - renderFindByIdFn(obj, ctx), - ]; - - // ADR-0038 — reverse-relationship navigation as explicit FK finders. One - // findBy (+ batched …In) per FK this entity holds. OWNED: - // drop this loop if you don't want reverse finders. - for (const fk of reverseFksFor(obj)) { - sections.push(renderReverseFinderFns(obj, fk, ctx)); - } - - // OWNED addition — one aggregate loader per composition this entity owns - // (`relationship.composition` with cardinality many): the parent row plus its - // parts, keyed by the relationship's name. See renderCompositionLoader. - for (const part of compositionPartsOf(obj, ctx)) { - const partModule = entityModuleSpecifier( - ctx.selfTarget, - ctx.entityModuleTarget, - part.child.package, - part.child.name, - ctx.extStyle, - ); - sections.push(code` -import { ${part.childTable}, type ${part.child.name} } from ${JSON.stringify(partModule)}; -`); - sections.push(renderCompositionLoader(obj, part, ctx)); - } - - const body = joinCode(sections, { on: "\n" }).toString(); - const header = - `// ${GENERATED_HEADER} — DO NOT EDIT.\n` + - `// Source metadata: ${entityName} (${obj.fqn()})\n` + - `// Customize via ${entityName}.extra.ts in this directory (additional queries, custom logic).\n`; - return header + body; -} - -// --- OWNED: composition aggregate loaders --------------------------------- -// A `relationship.composition` with cardinality many says the parent OWNS a -// collection of child rows (cascade on delete). The loader reads the parent by -// id and its parts through the child's reference identity back to the parent, -// ordered by the rest of the child's primary key — for a part keyed -// (parentId, ordinal) that is the part's position within its parent. -interface CompositionPart { - /** The relationship name — the parts' key in the aggregate (e.g. `turns`). */ - relName: string; - child: MetaObject; - /** The child's Drizzle table variable (e.g. `councilTurns`). */ - childTable: string; - /** The child's FK field that references the parent (e.g. `councilId`). */ - fkField: string; - /** The child's primary-key fields after the FK, in order (e.g. [`ordinal`]). */ - orderFields: string[]; -} - -function compositionPartsOf(obj: MetaObject, ctx: RenderContext): CompositionPart[] { - const parts: CompositionPart[] = []; - for (const rel of obj.relationships()) { - if (rel.subType !== RELATIONSHIP_SUBTYPE_COMPOSITION || rel.cardinality !== "many") continue; - const { node: child } = resolveObjectRef( - ctx.loadedRoot, - rel.objectRef ?? "", - obj.package ?? obj.fileDefaultPackage ?? "", - ); - if (!child || !isMetaObject(child)) { - throw new Error(`queries-file: ${obj.name}.${rel.name} composes unknown object "${rel.objectRef}"`); - } - const fk = reverseFksFor(child).find((f) => f.targetEntity === obj.name); - if (!fk) { - throw new Error( - `queries-file: ${obj.name}.${rel.name} composes ${child.name}, which has no identity.reference to ${obj.name}`, - ); - } - const pkFields = child.primaryIdentity()?.fields ?? []; - parts.push({ - relName: rel.name, - child, - childTable: ctx.collectionName(child.name), - fkField: fk.fkField, - orderFields: pkFields.filter((f) => f !== fk.fkField), - }); - } - return parts; -} - -function renderCompositionLoader(obj: MetaObject, part: CompositionPart, ctx: RenderContext): Code { - const entityName = obj.name; - const parentVar = entityName.charAt(0).toLowerCase() + entityName.slice(1); - const relPascal = part.relName.charAt(0).toUpperCase() + part.relName.slice(1); - const aggregate = `${entityName}With${relPascal}`; - const { fieldName: pkField, tsType: pkType } = getPkInfo(obj, ctx); - const eqSym = imp("eq@drizzle-orm"); - const ascSym = imp("asc@drizzle-orm"); - const orderBy = part.orderFields.map((f) => code`${ascSym}(${part.childTable}.${f})`); - return code` -/** A ${entityName} with the ${part.child.name} rows it owns (relationship.composition \`${part.relName}\`). */ -export interface ${aggregate} { - ${parentVar}: ${entityName}; - ${part.relName}: ${part.child.name}[]; -} - -/** Load a ${entityName} and its \`${part.relName}\` (ordered by ${part.orderFields.join(", ") || "storage order"}); null when absent. */ -export async function find${aggregate}(db: Db, ${pkField}: ${pkType}): Promise<${aggregate} | null> { - const ${parentVar} = await find${entityName}ById(db, ${pkField}); - if (!${parentVar}) return null; - const ${part.relName} = await db - .select() - .from(${part.childTable}) - .where(${eqSym}(${part.childTable}.${part.fkField}, ${pkField}))${orderBy.length > 0 ? code` - .orderBy(${joinCode(orderBy, { on: ", " })})` : ""}; - return { ${parentVar}, ${part.relName} }; -} -`; -} - -export interface QueriesFileOpts { - filter?: (entity: MetaObject) => boolean; - target?: string; -} - -// #248 R2: persistability derives from declared/inherited source, never subtype. -// An object with no source.rdb (of ANY kind) isn't backed by any store — the -// rendered queries module would emit findById/updateById/deleteById against -// Drizzle table/schema exports the entity file never emits for it (value -// objects are subsumed here too: value purity bans sources on them, so no -// loadable value ever has hasAnyRdbSource === true). TPH subtypes emit no -// standalone queries file either — their per-subtype CRUD helpers live in the -// discriminator base's queries file (which targets the single shared table). -const skipNonQueryable = (e: MetaObject): boolean => - hasAnyRdbSource(e) && !isTphSubtype(e) && !isCompositionPart(e); - -// OWNED: an entity another entity composes (`relationship.composition`, cardinality -// many) is a PART of that aggregate — it is loaded through the root's -// findWith, so a standalone queries file for it would only be dead -// code (and the stock findById on a composite key matches on its first column only). -function isCompositionPart(e: MetaObject): boolean { - const root = e.root(); - return root.children().some( - (owner) => - isMetaObject(owner) && - owner !== e && - owner.relationships().some((rel) => { - if (rel.subType !== RELATIONSHIP_SUBTYPE_COMPOSITION || rel.cardinality !== "many") return false; - const { node } = resolveObjectRef(root, rel.objectRef ?? "", owner.package ?? owner.fileDefaultPackage ?? ""); - return node === e; - }), - ); -} - -export const queriesFile = function queriesFile(opts?: QueriesFileOpts): Generator { - const userFilter = opts?.filter; - const filter: (e: MetaObject) => boolean = userFilter - ? (e) => skipNonQueryable(e) && userFilter(e) - : skipNonQueryable; - - const generator: Generator = { - name: "queries-file", - filter, - // Sole producer of *.queries.ts: when an entity stops getting one (e.g. it - // becomes a composition part), the run removes the untouched old file. - orphanPolicy: { owns: (relPath) => relPath.endsWith(".queries.ts") }, - generate: perEntity(async (entity, ctx) => { - if (!ctx.renderContext) { - throw new Error("queries-file: renderContext is required (provided by runGen)"); - } - return { - path: entityOutputPath(ctx.config.outputLayout ?? "flat", entity.package, `${entity.name}.queries.ts`), - content: await formatTs(renderQueries(entity, ctx.renderContext)), - }; - }), - }; - if (opts?.target) { - generator.target = opts.target; - } - return generator; -} as GeneratorFactory; diff --git a/docs/architecture.md b/docs/architecture.md index 3689666..cba21df 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -36,7 +36,7 @@ A single Cloudflare Worker handles everything: │ RATE_LIMIT KVNamespace │ │ DB D1Database (councils + council_turns) │ │ Vars: │ - │ MODEL, MAX_QUESTIONS_PER_DAY, GLOBAL_MAX_PER_DAY, │ + │ MAX_QUESTIONS_PER_DAY, GLOBAL_MAX_PER_DAY, │ │ KILL_SWITCH, SEARCH_URL │ │ Secrets: │ │ ANTHROPIC_API_KEY │ @@ -79,7 +79,8 @@ A single Cloudflare Worker handles everything: - Build user message (`buildWizardMessages`): the question + each prior wizard's reply (so wizards can react to each other) + the shared sources block (so any wizard can cite real URLs, not just Lorekeeper). - - Call `complete()` against Anthropic. Per-wizard try/catch: on success, + - Call `callEmitWizardTake()` (generated from the `emitWizardTake` toolcall, which + declares the model id and `max_tokens`) against Anthropic. Per-wizard try/catch: on success, emit `event: wizard` SSE frame and push the turn into `prior`; on throw, emit `event: error` with an in-character "lost in thought" message and skip pushing. diff --git a/docs/how-metaobjects-is-used.md b/docs/how-metaobjects-is-used.md index 2af0bcc..d1ca4fe 100644 --- a/docs/how-metaobjects-is-used.md +++ b/docs/how-metaobjects-is-used.md @@ -27,8 +27,9 @@ field `extends` the shared abstract enum `wizardStance` ([`abstracts/meta-stance-enums.yaml`](../metaobjects/abstracts/meta-stance-enums.yaml)) — declared once, reused by `WizardOutput`, `TurnLens`, and `CouncilTurn`. From that one spine: -- `entityFile`/`queriesFile` emit `src/db/generated/WizardOutput.ts` (Zod) and, for the - *entities* that persist these fields, Drizzle tables + typed finders. Because several fields +- `entityFile` emits `src/db/generated/WizardOutput.ts` (Zod) and, for the + *entities* that persist these fields, Drizzle tables; the owned `compositionLoaders` emits the + typed council read. Because several fields share `wizardStance`, codegen also emits a single `src/db/generated/enums.ts` the entities reference — the de-duplication carries through to the generated code. - `promptRender` emits a typed render payload + handles in `src/render/generated/prompts.ts`. @@ -131,10 +132,34 @@ Reference projects that admit friction are believed. Real things this project hi - **Generated writes validate.** The stock `create`/`update` query verbs parse their input with the insert/update schema. This app's writes don't, so adopting the verbs would start rejecting rows written today (a client-supplied visitor cookie longer than `visitorId`'s 64 chars, for - example). The owned queries generator keeps reads only. + example). So no `queriesFile()` is wired: the one generated read is the composition loader + (below), and the writes are hand-written Drizzle over the generated tables and enum constants. - **A nested-value-object FQN codegen bug** in an earlier `@metaobjectsdev/codegen-ts` surfaced from this project and was fixed upstream (the `promptRender` FQN handling in 0.15.18). +## Owned generators: why each one exists + +The entity modules, the barrel, the `Names` constants, the prompt render handles and the +docs site run as shipped from `@metaobjectsdev/codegen-ts/generators`; the project keeps no copy of +them. Until MetaObjects 1.2.0 it carried ejected copies of `entity`, `barrel` and `queries`; the +first two had no edits of their own (only an older header) and are gone. Each generator the project +still owns emits something no shipped generator does (`meta gen --list --probe` is the catalog it +was checked against), and says so in its header: + +| Generator | Emits | Why no shipped generator covers it | +|---|---|---| +| `compositionLoaders` (`codegen/generators/`) | `Council.queries.ts`: `findCouncilById` + `findCouncilWithTurns` | stock `queries` emits full CRUD for every entity, has no verb filter and no composition loader | +| `structuredCompletion` | `toolcalls.ts`: forced `tool_use` wrappers with the toolcall's `@model` and `@maxTokens`, retry and fallback | nothing shipped reads `template.toolcall`; the shipped LLM generators parse a `template.prompt` text reply | +| `sseFrames` | `council-frames.ts` | `template.streamFrame` is project-local vocabulary | +| `lineageMappers` | `*.lineage.ts` copies along field `extends` | no shipped generator maps between related objects | +| `mustacheTemplates` | `templates.ts`, the template text inlined for a Worker | shipped render handles resolve text through a provider at runtime | +| `wizardData`, `wizardRegistry` | the typed roster and its render registry | they read instance data under `data/`, which shipped generators never read | + +The cost test the audit applies (authored lines against emitted lines) fails for most of these: +they are larger than what they emit. They stay because the point is drift protection, not +line count: each turns a metadata or data change into a regenerated, drift-gated file instead of +a hand edit in several places. + ## Pointers - [`metaobjects.config.ts`](../metaobjects.config.ts) — the generator wiring + targets. diff --git a/metaobjects.config.ts b/metaobjects.config.ts index 19b2f90..43e107e 100644 --- a/metaobjects.config.ts +++ b/metaobjects.config.ts @@ -1,27 +1,13 @@ import { defineConfig } from "@metaobjectsdev/cli"; -// ADR-0034 scaffold-and-own: entityFile / queriesFile / barrel are OWNED local -// copies (scaffolded from @metaobjectsdev/codegen-ts/src/reference/*). We import -// them from ./codegen/generators, not the package — 1.0 REMOVED those four -// (entity/queries/routes/barrel) from `@metaobjectsdev/codegen-ts/generators` -// entirely; they were @deprecated on 0.24/0.25 and there is no longer an export -// to fall back to (ADR-0035 A3, 1.0-readiness G2). Owning the copy means the -// generated shape is ours to change and can never drift out from under us. -import { entityFile } from "./codegen/generators/entity"; -import { queriesFile } from "./codegen/generators/queries"; -import { barrel } from "./codegen/generators/barrel"; -// The /generators subpath STAYS, and everything still exported from it is -// supported public API — the removal was scoped by NAME, not by path. Two axes -// get confused here, so state both: -// - ownable? `meta eject --list` names all nine, INCLUDING `names` and -// `routes-hono`. Having an ownable reference copy is not the same -// as being removed from the package. -// - removed? only entity / queries / routes / barrel. -// So `promptRender` (upstream-owned render engine, no ownable copy) and -// `namesFile` (a stock generator that DOES have an ownable copy, and is still -// exported) are both correctly imported from the package here. Don't cargo-cult -// "own everything" — own a copy when you intend to change its emit; this project -// changed entity/queries/barrel and has no reason to fork the names artifact. -import { docsSiteFile, namesFile, promptRender } from "@metaobjectsdev/codegen-ts/generators"; +// The entity modules, the barrel, the Names constants and the prompt render +// handles are the SHIPPED generators, imported as-is: this project changes nothing +// they emit, so it owns no copy of them (an unchanged owned copy only falls behind +// the reference; `meta eject --list` reports any it finds). +import { barrel, docsSiteFile, entityFile, namesFile, promptRender } from "@metaobjectsdev/codegen-ts/generators"; +// Owned generators: each emits something no shipped generator does, and its header +// says what and why. codegen/generators/ holds the one for the persistence target; +// src/codegen/ holds the ones for prompts, personas, tool calls and SSE frames. +import { compositionLoaders } from "./codegen/generators/composition-loaders"; import { mustacheTemplates } from "./src/codegen/mustache-templates-generator"; import { wizardData } from "./src/codegen/wizard-data-generator"; import { wizardRegistry } from "./src/codegen/wizard-registry-generator"; @@ -61,8 +47,8 @@ export default defineConfig({ importBase: "../../db/generated", dialect: "sqlite", // No `dbImport`: since 0.24.3 it is demanded at the point of USE — by a generator - // that actually emits `import { db } from …`. This project's OWNED queries generator - // takes `db` as an explicit parameter (see src/db/generated/*.queries.ts) and the + // that actually emits `import { db } from …`. This project's composition loaders + // take `db` as an explicit parameter (see src/db/generated/*.queries.ts) and the // Worker builds its client per request, so nothing here ever reads it. Earlier // versions demanded it from the model, which is why a placeholder used to sit here. // Pin extensionless relative imports. This project compiles under `moduleResolution: @@ -91,7 +77,10 @@ export default defineConfig({ }, generators: [ entityFile(), - queriesFile(), + // The only generated read: findWith for a composition (Council + its + // turns). No `queriesFile()`: this app's writes are hand-written, status-guarded + // Drizzle updates (src/db/queries.ts), so stock CRUD helpers would go unused. + compositionLoaders(), // Names — the physical table/column names as importable constants, so a // name is spelled ONCE per run and every other reader points at it (1.0 §A1/§A5). // OPT-IN on TypeScript: `generators: [...]` IS the complete suite here, exactly diff --git a/metaobjects/toolcalls/meta-toolcall-emit-verdict.yaml b/metaobjects/toolcalls/meta-toolcall-emit-verdict.yaml index fb87aaf..c9c0de3 100644 --- a/metaobjects/toolcalls/meta-toolcall-emit-verdict.yaml +++ b/metaobjects/toolcalls/meta-toolcall-emit-verdict.yaml @@ -16,6 +16,9 @@ metadata: name: emitVerdict toolName: emit_verdict payloadRef: VerdictOutput + # The request the generated wrapper sends: model id and max_tokens. + model: claude-sonnet-4-6 + maxTokens: 1024 retryReminder: |- Your previous response was not a valid tool call. Call the named tool with an input matching its JSON schema. Do not include any text outside the tool call. children: diff --git a/metaobjects/toolcalls/meta-toolcall-emit-wizard-take.yaml b/metaobjects/toolcalls/meta-toolcall-emit-wizard-take.yaml index b448394..e1e25c9 100644 --- a/metaobjects/toolcalls/meta-toolcall-emit-wizard-take.yaml +++ b/metaobjects/toolcalls/meta-toolcall-emit-wizard-take.yaml @@ -16,5 +16,8 @@ metadata: name: emitWizardTake toolName: emit_wizard_take payloadRef: WizardOutput + # The request the generated wrapper sends: model id and max_tokens. + model: claude-sonnet-4-6 + maxTokens: 1024 retryReminder: |- Your previous response was not a valid tool call. Call the named tool with an input matching its JSON schema. Do not include any text outside the tool call. diff --git a/package-lock.json b/package-lock.json index 8bd897e..9ba5dda 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,11 +7,11 @@ "name": "wizardsofodd", "hasInstallScript": true, "dependencies": { - "@metaobjectsdev/cli": "1.1.4", - "@metaobjectsdev/codegen-ts": "1.1.4", - "@metaobjectsdev/render": "1.1.4", - "@metaobjectsdev/runtime-ts": "1.1.4", - "@metaobjectsdev/sdk": "1.1.4", + "@metaobjectsdev/cli": "1.2.0", + "@metaobjectsdev/codegen-ts": "1.2.0", + "@metaobjectsdev/render": "1.2.0", + "@metaobjectsdev/runtime-ts": "1.2.0", + "@metaobjectsdev/sdk": "1.2.0", "drizzle-orm": "^0.45.2", "drizzle-zod": "^0.8.3", "hono": "^4.13.7", @@ -24,7 +24,7 @@ "devDependencies": { "@cloudflare/vitest-pool-workers": "^0.22.0", "@cloudflare/workers-types": "^5.20260820.1", - "@metaobjectsdev/metadata": "1.1.4", + "@metaobjectsdev/metadata": "1.2.0", "@testing-library/react": "^16.3.2", "@types/node": "^26.3.0", "@types/react": "^18.3.29", @@ -387,9 +387,9 @@ } }, "node_modules/@biomejs/biome": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.6.3.tgz", - "integrity": "sha512-va/0xPku7wnfzv+D8Zpdm5uKiGJWiV8neqoEPnRjvNQQwhl4tVXS4fETs4H0CCB2rGeqJ4cu9y4iOZOnOYKAUA==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.6.7.tgz", + "integrity": "sha512-2bT1FE6FvZZgPLFw4BjcDyRwG8Ry9zYla4X+Lw8oj2SxvqiXHiYkkEpjcrsWQrik6iYHygAa/D67YxLbVz9P1Q==", "license": "MIT OR Apache-2.0", "peer": true, "bin": { @@ -403,22 +403,22 @@ "url": "https://opencollective.com/biome" }, "optionalDependencies": { - "@biomejs/cli-android-arm64": "2.6.3", - "@biomejs/cli-android-x64": "2.6.3", - "@biomejs/cli-darwin-arm64": "2.6.3", - "@biomejs/cli-darwin-x64": "2.6.3", - "@biomejs/cli-linux-arm64": "2.6.3", - "@biomejs/cli-linux-arm64-musl": "2.6.3", - "@biomejs/cli-linux-x64": "2.6.3", - "@biomejs/cli-linux-x64-musl": "2.6.3", - "@biomejs/cli-win32-arm64": "2.6.3", - "@biomejs/cli-win32-x64": "2.6.3" + "@biomejs/cli-android-arm64": "2.6.7", + "@biomejs/cli-android-x64": "2.6.7", + "@biomejs/cli-darwin-arm64": "2.6.7", + "@biomejs/cli-darwin-x64": "2.6.7", + "@biomejs/cli-linux-arm64": "2.6.7", + "@biomejs/cli-linux-arm64-musl": "2.6.7", + "@biomejs/cli-linux-x64": "2.6.7", + "@biomejs/cli-linux-x64-musl": "2.6.7", + "@biomejs/cli-win32-arm64": "2.6.7", + "@biomejs/cli-win32-x64": "2.6.7" } }, "node_modules/@biomejs/cli-android-arm64": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-android-arm64/-/cli-android-arm64-2.6.3.tgz", - "integrity": "sha512-5JD7QQDEHxdeEb4sftEHG+lsuUyu8Cob/hVLqRELbgGlFl68Rldv/PPi2k4dRjERZ/EItJ3O6Xmv8lqsEtUBiw==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-arm64/-/cli-android-arm64-2.6.7.tgz", + "integrity": "sha512-f4fyRTl+rW6QZp+iHdZrKAKptG/xmIDijTnxWhpC1Hnzr8yvjaBm/aJ98JiMv5mMx7jL1MOu4+zwmQUzfcoKBg==", "cpu": [ "arm64" ], @@ -433,9 +433,9 @@ } }, "node_modules/@biomejs/cli-android-x64": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-android-x64/-/cli-android-x64-2.6.3.tgz", - "integrity": "sha512-70WOGKCgpT+Uqg6LFdTLqefV54/DypdZg+LnBQDO6AWvkgXO+9xhVClajQyDsIHYjnXMtI1pRO5sP+zMXlS/bw==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-x64/-/cli-android-x64-2.6.7.tgz", + "integrity": "sha512-eUdeN+mh2bwen+By1feKzpFkFGAfLG3Pxi6tbwpzMvePBwFGMd4mnE6gaxDRMiWJ1eMuc+Xhtg3ErbLLbtL5wQ==", "cpu": [ "x64" ], @@ -450,9 +450,9 @@ } }, "node_modules/@biomejs/cli-darwin-arm64": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.6.3.tgz", - "integrity": "sha512-ezf+XEKeyJ2yYlBhrzyEEHLvfRYrhtNKc6maLzR/WcAcBccb4RVDeFxsymjBve2LO0bpIMRUAiS90D4bUBRT0A==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.6.7.tgz", + "integrity": "sha512-GewLcsnCsVblgnWYw5QRz5ydy9xphCtlFP37TpLKarezqwZMrH2qxrYblhY6DPOir4gnKyaqDnS/xZWIGVjaKw==", "cpu": [ "arm64" ], @@ -467,9 +467,9 @@ } }, "node_modules/@biomejs/cli-darwin-x64": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.6.3.tgz", - "integrity": "sha512-Lg2tFdg4elJo+7i707PpLMs6N1hATVt4kqDo6MD/q/VnPs8rsKReKXsz1TA5GNdfRVAQNJ5GRiyK2EwNptK+MA==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.6.7.tgz", + "integrity": "sha512-AMPl+Q+bHjRcNUBn8gwBl+dJAnKRUWGZ7ZiJo2U8tQtdpqJ32OqvIg4cwTH+xv0jrcNVkUSE69nj57zsHZ1WBA==", "cpu": [ "x64" ], @@ -484,9 +484,9 @@ } }, "node_modules/@biomejs/cli-linux-arm64": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.6.3.tgz", - "integrity": "sha512-8Stcvq98n1gs9VyLKuaWrnsd8kbXE2nKDAHtuLHGSYdGyNWN5JIIm5a28xdnmgdKzKHmiDgYyATetkEv7+zGow==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.6.7.tgz", + "integrity": "sha512-Qa2edxQClKn17y1ASWkOOuT96K2si1nTLiPbXMOMilNJ79eNsa1as1kaSbgxOXy1kRUENw76sp4pAddneq3l8Q==", "cpu": [ "arm64" ], @@ -504,9 +504,9 @@ } }, "node_modules/@biomejs/cli-linux-arm64-musl": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.6.3.tgz", - "integrity": "sha512-dYU70A89OFHzakQPE9VOPbE60JNcQt4mtxvUGQl+EgTkGtqCFxLD2RUn1SbiMu8Mu5xFscS1bfYDpoasaUrqNA==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.6.7.tgz", + "integrity": "sha512-BIA7qVO1O15D2wVKxLTcvEWszgOqJVZRUhlksg1KQ9N0VtYCbvknV1vyjFiSrzuBT57+z59gbzhYQCinw9lRSQ==", "cpu": [ "arm64" ], @@ -524,9 +524,9 @@ } }, "node_modules/@biomejs/cli-linux-x64": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.6.3.tgz", - "integrity": "sha512-CShmx0bO6BngywT3minv8K1xsQX1ig1vsBqYTLnmDY3mBiDYHlaLRIsdHoM1pEU9dV3BN5a0uiH0IGDtYh9TWA==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.6.7.tgz", + "integrity": "sha512-VpHQ33CPNYrlIn0vyDdRS1KUlS3AiM17FiyEE2gwU000NwzyY4MgjzVHEv2KrmMb5D9Ksm3gFkwg+IOx/ULJNQ==", "cpu": [ "x64" ], @@ -544,9 +544,9 @@ } }, "node_modules/@biomejs/cli-linux-x64-musl": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.6.3.tgz", - "integrity": "sha512-j6eFjUcWSphmgVTbrobEMA0wdbfNHKrGi8hRsFkc17jeS1n7nHwFACxp6jWqe9sxQqyFAeyOgt2/1bOGVcbATA==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.6.7.tgz", + "integrity": "sha512-+AOQyCsPR4nH5L4Hjzp8T0iaHm4UxY3unjL/KUJKc/8ziLnbkbmL3adtWmQW5ERB1zi6LRA1fsjaSuf/xGnLaQ==", "cpu": [ "x64" ], @@ -564,9 +564,9 @@ } }, "node_modules/@biomejs/cli-win32-arm64": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.6.3.tgz", - "integrity": "sha512-00SthDxBPwNiT7IL/mOneif6fiEU1PXK875zhr+InpeZjovY1mF5tCuDhXo1Hh0GYyiKHKzLbItzn58SAyLhJQ==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.6.7.tgz", + "integrity": "sha512-2nLivZfgcGMIXP/bI8w1FZP5JE2MetP+XZInyMQ7SvJBKlDoGrm/nRjN7uUi9dOaaSlpbRWkHSfb7PqcQR3nXg==", "cpu": [ "arm64" ], @@ -581,9 +581,9 @@ } }, "node_modules/@biomejs/cli-win32-x64": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.6.3.tgz", - "integrity": "sha512-GhtOPphBWlnCepqpNk/w5eGN5oGRCzL20EbAkL1XCIpyboeVC9R642noyT43l8LSenGS4qz9IL8sKPfwY37V/Q==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.6.7.tgz", + "integrity": "sha512-uYfH+n+IAtVz3lh7m6JxdjxfJ3WCvAJDE3spHIUbU955V42oKymlhiQiu92fAhXZb7KOjvRcrfImySQbc1MFFg==", "cpu": [ "x64" ], @@ -2283,23 +2283,23 @@ } }, "node_modules/@metaobjectsdev/cli": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/cli/-/cli-1.1.4.tgz", - "integrity": "sha512-IjaQzFfPXdMu55Dm24ntK+CAqsOt43dT96nolCZyAzIZaXf5vIy8Fn1U8Ue4bVTtsJubVAbvpgBqpp08QxMdrA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/cli/-/cli-1.2.0.tgz", + "integrity": "sha512-nthlJc4orqbwEKUn+JHnFRaXD97I0qmdCeTZERLhYnw/Rxkkhj5Y0ZpmoYh4NcZWei5db7xwG26ktVdRKYFo8Q==", "license": "Apache-2.0", "dependencies": { "@biomejs/js-api": "^0.7.0", "@biomejs/wasm-nodejs": "^1.9.4", "@libsql/kysely-libsql": "^0.4.0", - "@metaobjectsdev/codegen-ts": "1.1.4", - "@metaobjectsdev/codegen-ts-react": "1.1.4", - "@metaobjectsdev/codegen-ts-tanstack": "1.1.4", - "@metaobjectsdev/docs-site": "1.1.4", - "@metaobjectsdev/metadata": "1.1.4", - "@metaobjectsdev/migrate-ts": "1.1.4", - "@metaobjectsdev/render": "1.1.4", - "@metaobjectsdev/runtime-ts": "1.1.4", - "@metaobjectsdev/sdk": "1.1.4", + "@metaobjectsdev/codegen-ts": "1.2.0", + "@metaobjectsdev/codegen-ts-react": "1.2.0", + "@metaobjectsdev/codegen-ts-tanstack": "1.2.0", + "@metaobjectsdev/docs-site": "1.2.0", + "@metaobjectsdev/metadata": "1.2.0", + "@metaobjectsdev/migrate-ts": "1.2.0", + "@metaobjectsdev/render": "1.2.0", + "@metaobjectsdev/runtime-ts": "1.2.0", + "@metaobjectsdev/sdk": "1.2.0", "@toon-format/toon": "^2.3.0", "jiti": "^2.4.0" }, @@ -2317,16 +2317,17 @@ } }, "node_modules/@metaobjectsdev/codegen-ts": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/codegen-ts/-/codegen-ts-1.1.4.tgz", - "integrity": "sha512-IPJFNndnQqafOKWbJxDNDGYi8t+aqh8e6bisVeDIW8QCb3U5qZW9ZR5ZBJ1sJ05VkoKD4+MCJBdkJvbUyjkudA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/codegen-ts/-/codegen-ts-1.2.0.tgz", + "integrity": "sha512-Rt5WDY09S+DIGMHMhCUWwXHRvwDbLlmk8zy1UWGlI5UCxt4nBjMqO4H3Icp7gAJnwrVSdcUhN62zYc8HxnVGmg==", "license": "Apache-2.0", "dependencies": { "@biomejs/js-api": "^0.7.0", "@biomejs/wasm-nodejs": "^1.9.4", - "@metaobjectsdev/docs-site": "1.1.4", - "@metaobjectsdev/metadata": "1.1.4", - "@metaobjectsdev/render": "1.1.4", + "@metaobjectsdev/docs-site": "1.2.0", + "@metaobjectsdev/metadata": "1.2.0", + "@metaobjectsdev/migrate-ts": "1.2.0", + "@metaobjectsdev/render": "1.2.0", "@toon-format/toon": "^2.3.0", "ts-poet": "^6.10.0" }, @@ -2336,13 +2337,13 @@ } }, "node_modules/@metaobjectsdev/codegen-ts-react": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/codegen-ts-react/-/codegen-ts-react-1.1.4.tgz", - "integrity": "sha512-4gqj+rlUc2JyEMvBb1scaO9sHmS0WbWEyDYY736n1XoqO2FCmDjPjTYYbXIjMvm9pGzqk8+6xvZZtLjrdvEE2w==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/codegen-ts-react/-/codegen-ts-react-1.2.0.tgz", + "integrity": "sha512-2/RY4uTYQJP6tANuOeYjw9+sJgwvUNB3by6PlqXscWMvAUk+RqXPkB5s5JxU3q39kWatAIVabQhDYQwQtpcZNw==", "license": "Apache-2.0", "dependencies": { - "@metaobjectsdev/codegen-ts": "1.1.4", - "@metaobjectsdev/metadata": "1.1.4", + "@metaobjectsdev/codegen-ts": "1.2.0", + "@metaobjectsdev/metadata": "1.2.0", "ts-poet": "^6.10.0" }, "peerDependencies": { @@ -2350,13 +2351,13 @@ } }, "node_modules/@metaobjectsdev/codegen-ts-tanstack": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/codegen-ts-tanstack/-/codegen-ts-tanstack-1.1.4.tgz", - "integrity": "sha512-s5bxukvFjm1bHZISa4skUXXdp1z36gaeatLmic8uU+FbZqnmonTegvQu3WiF5StNeC7VrHF7lrXv8bBVqHWlOg==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/codegen-ts-tanstack/-/codegen-ts-tanstack-1.2.0.tgz", + "integrity": "sha512-KOIXvsTlsyPWJDFEhgCmCMM8TYZj0lvMB8namb2vhNkaFlySpHLOYBGjhl/fYEjUoM77XVJ64X4ecmWojojmaQ==", "license": "Apache-2.0", "dependencies": { - "@metaobjectsdev/codegen-ts": "1.1.4", - "@metaobjectsdev/metadata": "1.1.4", + "@metaobjectsdev/codegen-ts": "1.2.0", + "@metaobjectsdev/metadata": "1.2.0", "ts-poet": "^6.10.0" }, "peerDependencies": { @@ -2364,33 +2365,33 @@ } }, "node_modules/@metaobjectsdev/docs-site": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/docs-site/-/docs-site-1.1.4.tgz", - "integrity": "sha512-JvGPopyxojtXe5/RvowBoBQCuST302gvezHa2qOSJgtn7n27l1sRp3YzqjirXD/Cj026fKe7J2Usl0NGjkvJvA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/docs-site/-/docs-site-1.2.0.tgz", + "integrity": "sha512-+CX2OjtqY12Ob/JkBtPjk4Gq1ggvuLlJ8RFD9jVZZP+oIRUnNVVfUQNTE5Q6aPbY7aIR9VfOU86NsgVLeYRO4g==", "license": "Apache-2.0", "dependencies": { - "@metaobjectsdev/metadata": "1.1.4", - "@metaobjectsdev/render": "1.1.4", + "@metaobjectsdev/metadata": "1.2.0", + "@metaobjectsdev/render": "1.2.0", "yaml": "^2.9.0" } }, "node_modules/@metaobjectsdev/metadata": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/metadata/-/metadata-1.1.4.tgz", - "integrity": "sha512-ph2k7wysVX8G5YHoYwYGxqNDVaItw/Ynw+CXCQM4KfxgS6Z+7zecmcfgTHRt36wCTlTMuDdkMHkSGFb1tsYC5g==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/metadata/-/metadata-1.2.0.tgz", + "integrity": "sha512-4lU3s48yjSx1JwX9UkFa71Un9vxPr6cEtI5IWjo9rSNZdwGg/NmEb66Cw1MzfZhe9n/ZtvJLhxY02jzb1CnaNA==", "license": "Apache-2.0", "dependencies": { "yaml": "^2.9.0" } }, "node_modules/@metaobjectsdev/migrate-ts": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/migrate-ts/-/migrate-ts-1.1.4.tgz", - "integrity": "sha512-aXzzHZuY0B4ftNfBJFpbr6SMVFZDDF6eJNn9qdf7b6GnxzPjo7k2oAuvGuEwxrOpuASzpmWUWdUJmfmm6e500A==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/migrate-ts/-/migrate-ts-1.2.0.tgz", + "integrity": "sha512-jHb3DZjpTOFOyiIeZMC308giAGmvDiPr7lKgQW2JaahA2qqf3nGfCwsgsJSVq4LhjNpweBgS4hxrFXhnf1O7BA==", "license": "Apache-2.0", "dependencies": { "@iarna/toml": "^2.2.5", - "@metaobjectsdev/metadata": "1.1.4" + "@metaobjectsdev/metadata": "1.2.0" }, "peerDependencies": { "@electric-sql/pglite": ">=0.3.0 <0.6.0", @@ -2407,22 +2408,23 @@ } }, "node_modules/@metaobjectsdev/render": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/render/-/render-1.1.4.tgz", - "integrity": "sha512-MCYIP6/GcGyzoBEOQ3/sro/21j6ZMlIgozY0tEDEcCJK8i0CNnaJUyNIvtZHJhayZY4jWQ6o1JQe55WH0wqo9Q==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/render/-/render-1.2.0.tgz", + "integrity": "sha512-8LzWpb5e/jg1Ozk9th+u36O7t/wuCKMH+IGUMeBy/Adx5Z2Ap5lNg+ecWwNcD5UVTF42PV9ZJkqIJsCb9PYinw==", "license": "Apache-2.0", "dependencies": { - "mustache": "^4.2.0" + "mustache": "^4.2.0", + "nunjucks": "^3.2.4" } }, "node_modules/@metaobjectsdev/runtime-ts": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/runtime-ts/-/runtime-ts-1.1.4.tgz", - "integrity": "sha512-VCt7Ji8FMD/if10DnmKh/APgftyXFODLyc5DqBNnauEUvcn68w5REVdPhJyFzrU3r1+nEdI/hzSF4mdIjFGPVQ==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/runtime-ts/-/runtime-ts-1.2.0.tgz", + "integrity": "sha512-g6LoefcxybPa/1Iu+94xSm4iKk4N5U2Hv6tc73jt3GFO0GrhtyhCo2GyLOD4DtoaDnpywrY2pfBroVPj0Br6QQ==", "license": "Apache-2.0", "dependencies": { - "@metaobjectsdev/metadata": "1.1.4", - "@metaobjectsdev/render": "1.1.4", + "@metaobjectsdev/metadata": "1.2.0", + "@metaobjectsdev/render": "1.2.0", "qs": "^6.13.0" }, "peerDependencies": { @@ -2451,12 +2453,13 @@ } }, "node_modules/@metaobjectsdev/sdk": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@metaobjectsdev/sdk/-/sdk-1.1.4.tgz", - "integrity": "sha512-0WpluC7KW8JlpzdRVei9bJ0MqORTJ7vko/8cx/GGmdyGwp9s8G3F19tuIYatkbwUdxLvMm1GZXKTzy9UD0ofIw==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@metaobjectsdev/sdk/-/sdk-1.2.0.tgz", + "integrity": "sha512-icDDCWKk6Zt3IVMUV5M2hylkvi8xf7P9LZ4XkNdO091/r4ucxJug41JciEO8RdPEbQrIPsSH6QNXjxC4TEaY+Q==", "license": "Apache-2.0", "dependencies": { - "@metaobjectsdev/metadata": "1.1.4", + "@metaobjectsdev/metadata": "1.2.0", + "yaml": "^2.9.0", "zod": "^4.6.6" } }, @@ -3240,6 +3243,12 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/a-sync-waterfall": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/a-sync-waterfall/-/a-sync-waterfall-1.0.1.tgz", + "integrity": "sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA==", + "license": "MIT" + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -3276,6 +3285,12 @@ "dequal": "^2.0.3" } }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", + "license": "MIT" + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -3417,6 +3432,15 @@ "dev": true, "license": "MIT" }, + "node_modules/commander": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz", + "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -4044,9 +4068,9 @@ } }, "node_modules/js-base64": { - "version": "3.9.5", - "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.9.5.tgz", - "integrity": "sha512-u0CFDUca8BbBRkMkF/fDcuoLCx9nTNbXdVtbjVnBqySA9E221u0uYKbACiYGOEk1heY69qM4caeX3OwjSyxevw==", + "version": "3.9.6", + "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-3.9.6.tgz", + "integrity": "sha512-LjkzbLtU6Lx6fjXMYGEACEB7rdtqZtxkBe9aS1ZpDNUyWgUivw3yBEIhQ37OVygJYRt+C+9e9fVT8PpFzH2Hww==", "license": "BSD-3-Clause" }, "node_modules/js-tokens": { @@ -4935,6 +4959,31 @@ "node": ">=18" } }, + "node_modules/nunjucks": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-3.2.4.tgz", + "integrity": "sha512-26XRV6BhkgK0VOxfbU5cQI+ICFUtMLixv1noZn1tGU38kQH5A5nmmbk/O45xdyBhD1esk47nKrY0mvQpZIhRjQ==", + "license": "BSD-2-Clause", + "dependencies": { + "a-sync-waterfall": "^1.0.0", + "asap": "^2.0.3", + "commander": "^5.1.0" + }, + "bin": { + "nunjucks-precompile": "bin/precompile" + }, + "engines": { + "node": ">= 6.9.0" + }, + "peerDependencies": { + "chokidar": "^3.3.0" + }, + "peerDependenciesMeta": { + "chokidar": { + "optional": true + } + } + }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -5067,9 +5116,9 @@ } }, "node_modules/qs": { - "version": "6.17.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.0.tgz", - "integrity": "sha512-5LK5BZ2XDHMvcUJaf0CQ5HL3aVgKbpklvByC7qLSxYkfE8COEEbJg5xCHWCTqzqi0Gs4Jn5Mv5v3R38W6edscA==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", diff --git a/package.json b/package.json index cfb3c5c..2d7c78a 100644 --- a/package.json +++ b/package.json @@ -26,11 +26,11 @@ "demo:drift": "meta verify --templates --codegen --prompts data/templates" }, "dependencies": { - "@metaobjectsdev/cli": "1.1.4", - "@metaobjectsdev/codegen-ts": "1.1.4", - "@metaobjectsdev/render": "1.1.4", - "@metaobjectsdev/runtime-ts": "1.1.4", - "@metaobjectsdev/sdk": "1.1.4", + "@metaobjectsdev/cli": "1.2.0", + "@metaobjectsdev/codegen-ts": "1.2.0", + "@metaobjectsdev/render": "1.2.0", + "@metaobjectsdev/runtime-ts": "1.2.0", + "@metaobjectsdev/sdk": "1.2.0", "drizzle-orm": "^0.45.2", "drizzle-zod": "^0.8.3", "hono": "^4.13.7", @@ -43,7 +43,7 @@ "devDependencies": { "@cloudflare/vitest-pool-workers": "^0.22.0", "@cloudflare/workers-types": "^5.20260820.1", - "@metaobjectsdev/metadata": "1.1.4", + "@metaobjectsdev/metadata": "1.2.0", "@testing-library/react": "^16.3.2", "@types/node": "^26.3.0", "@types/react": "^18.3.29", diff --git a/src/codegen/lineage-mappers-generator.ts b/src/codegen/lineage-mappers-generator.ts index b7af176..13aa06f 100644 --- a/src/codegen/lineage-mappers-generator.ts +++ b/src/codegen/lineage-mappers-generator.ts @@ -1,6 +1,10 @@ // Custom MO codegen Generator: emits src/db/generated/.lineage.ts — typed // mappers between an object and another object whose fields DESCEND from it. // +// Why custom: no shipped generator emits field-lineage mappers. The shipped +// entity module gives each object its own type and Zod schemas, but nothing +// copies values between objects related by field `extends`. +// // Source of truth: field-level lineage in the metadata. A target field descends // from a source field when it // - `extends: .`, directly or further up its chain (e.g. @@ -33,7 +37,7 @@ // reverse mapper that misses a required source field) fails generation with the reason. import type { Generator, EmittedFile, GenContext } from "@metaobjectsdev/codegen-ts"; -import { formatTs, oncePerRun } from "@metaobjectsdev/codegen-ts"; +import { formatTs, oncePerRun, GENERATED_EDIT_NOTE } from "@metaobjectsdev/codegen-ts"; import { isMetaField, isMetaObject, isMetaRoot, type MetaField, type MetaObject } from "@metaobjectsdev/metadata"; export interface LineageMapperSpec { @@ -230,7 +234,7 @@ export const lineageMappers = (specs: readonly LineageMapperSpec[]): Generator = .map(([module, names]) => `import type { ${[...names].sort().join(", ")} } from "./${module}";`) .join("\n"); - const content = `// @generated by @metaobjectsdev/codegen-ts (via lineage-mappers) — DO NOT EDIT. + const content = `// @generated by @metaobjectsdev/codegen-ts (via lineage-mappers) — ${GENERATED_EDIT_NOTE} // AUTO-GENERATED — re-run \`npm run gen:db\`. // Source of truth: the \`extends\` lineage of ${target.name}'s fields (metaobjects/). diff --git a/src/codegen/mustache-templates-generator.ts b/src/codegen/mustache-templates-generator.ts index f57fecf..e177e8b 100644 --- a/src/codegen/mustache-templates-generator.ts +++ b/src/codegen/mustache-templates-generator.ts @@ -5,6 +5,10 @@ // `group/source`. The .mustache files on disk are the edit-time source of // truth; the emitted module is the runtime source of truth. // +// Why custom: the shipped render generators (prompt-render, render-helper) emit +// handles that RESOLVE a template ref through a provider at runtime; none of them +// inlines the template text, and a Worker has no filesystem to read it from. +// // Folded from the former scripts/build-templates.ts into a Generator so the // whole generated surface runs under one `meta gen` and is covered by the // `meta verify --codegen` drift gate — a hand-run build step outside `meta gen` @@ -23,7 +27,7 @@ import { readdirSync, readFileSync, statSync } from "node:fs"; import { join, relative, sep } from "node:path"; import type { Generator, EmittedFile } from "@metaobjectsdev/codegen-ts"; -import { oncePerRun } from "@metaobjectsdev/codegen-ts"; +import { oncePerRun, GENERATED_EDIT_NOTE } from "@metaobjectsdev/codegen-ts"; const TEMPLATES_DIR = "data/templates"; @@ -49,7 +53,7 @@ export const mustacheTemplates = (): Generator => ({ entries[ref] = readFileSync(f, "utf8"); } - const content = `// @generated by @metaobjectsdev/codegen-ts (via mustache-templates) — DO NOT EDIT. + const content = `// @generated by @metaobjectsdev/codegen-ts (via mustache-templates) — ${GENERATED_EDIT_NOTE} // AUTO-GENERATED — re-run \`npm run gen:db\`. // Source of truth: data/templates/**/*.mustache diff --git a/src/codegen/sse-frames-generator.ts b/src/codegen/sse-frames-generator.ts index 16bf5fd..ea94c63 100644 --- a/src/codegen/sse-frames-generator.ts +++ b/src/codegen/sse-frames-generator.ts @@ -4,6 +4,9 @@ // encodeCouncilFrame (Worker, emit side) and isCouncilFrameEvent / // toCouncilFrame (client, decode side). // +// Why custom: template.streamFrame is a project-local subtype, so no shipped +// generator knows it. +// // Source of truth: every `template.streamFrame` node in the loaded MetaRoot. // The template.streamFrame subtype is registered by wizardsofoddProvider // (src/codegen/wizardsofodd-provider.ts), wired in metaobjects.config.ts @@ -23,7 +26,7 @@ // exhaustiveness check all update on the next `npm run gen:db`. import type { Generator, EmittedFile, GenContext } from "@metaobjectsdev/codegen-ts"; -import { oncePerRun } from "@metaobjectsdev/codegen-ts"; +import { oncePerRun, GENERATED_EDIT_NOTE } from "@metaobjectsdev/codegen-ts"; import { stripPackage, TYPE_TEMPLATE, @@ -105,7 +108,7 @@ export const sseFrames = (): Generator => ({ ) .join("\n"); - const header = `// @generated by @metaobjectsdev/codegen-ts (via sse-frames) — DO NOT EDIT. + const header = `// @generated by @metaobjectsdev/codegen-ts (via sse-frames) — ${GENERATED_EDIT_NOTE} // AUTO-GENERATED — re-run \`npm run gen:db\`. // Source of truth: every template.streamFrame node under metaobjects/. // diff --git a/src/codegen/structured-completion-generator.ts b/src/codegen/structured-completion-generator.ts index 6361f29..99df385 100644 --- a/src/codegen/structured-completion-generator.ts +++ b/src/codegen/structured-completion-generator.ts @@ -2,12 +2,20 @@ // wrappers around `completeStructured` that bake in the try → retry-with- // stricter-reminder → optional-fallback ladder. // +// Why custom: no shipped generator reads template.toolcall. The shipped LLM +// generators (extractor, output-parser, output-prompt) work from a template.prompt's +// @responseRef and parse a text reply; this app's replies are forced tool_use +// blocks validated against the payload's Zod schema, and nothing shipped emits the +// call itself, its retry ladder or its fallback. +// // Source of truth: every `template.toolcall` node in the loaded MetaRoot. // template.toolcall is a core MO subtype; wizardsofoddProvider EXTENDS it with the -// Anthropic @retryReminder attr (src/codegen/wizardsofodd-provider.ts), wired in +// Anthropic @retryReminder attr and @model (src/codegen/wizardsofodd-provider.ts), wired in // metaobjects.config.ts via the providers: [...] field. Each toolcall node carries: // @toolName wire tool name surfaced to Anthropic // @payloadRef value-object whose Insert Zod schema is the runtime tool schema +// @model model id sent as the request's `model` (project provider) +// @maxTokens token budget sent as the request's `max_tokens` (core attr) // @retryReminder reminder appended on retry when the initial call fails // @fallback (optional) canned payload returned on double-failure // @@ -22,13 +30,15 @@ // edits, no new prompt constants, no copy-pasted retry ladder. import type { Generator, EmittedFile, GenContext } from "@metaobjectsdev/codegen-ts"; -import { oncePerRun } from "@metaobjectsdev/codegen-ts"; +import { oncePerRun, GENERATED_EDIT_NOTE } from "@metaobjectsdev/codegen-ts"; import { stripPackage, TYPE_TEMPLATE, TEMPLATE_SUBTYPE_TOOLCALL, TEMPLATE_ATTR_TOOL_NAME, TEMPLATE_ATTR_PAYLOAD_REF, + TEMPLATE_ATTR_MODEL, + TEMPLATE_ATTR_MAX_TOKENS, } from "@metaobjectsdev/metadata"; // The Anthropic-flavored attrs live on the project provider; read them through // the SAME constants it registers them under (no declared-vs-read drift). @@ -43,6 +53,10 @@ interface ToolcallSpec { payloadRef: string; /** Appended to the system prompt on retry when the initial call fails. */ retryReminder: string; + /** Target model id (@model, registered on template.toolcall by the project provider). */ + model: string; + /** Token budget for the structured response (core @maxTokens). */ + maxTokens: number; /** * Optional canned payload returned on double-failure instead of rethrowing. * When present, must satisfy the payloadRef's type at runtime — embedded as @@ -63,6 +77,8 @@ function discoverToolcalls(ctx: GenContext): ToolcallSpec[] { const payloadRef = child.attr(TEMPLATE_ATTR_PAYLOAD_REF); const retryReminder = child.attr(TEMPLATE_ATTR_RETRY_REMINDER); const fallback = child.attr(TEMPLATE_ATTR_FALLBACK); + const model = child.attr(TEMPLATE_ATTR_MODEL); + const maxTokens = child.attr(TEMPLATE_ATTR_MAX_TOKENS); if (typeof toolName !== "string" || !toolName) { throw new Error(`structured-completion: template.toolcall "${child.name}" is missing required @toolName`); } @@ -72,6 +88,12 @@ function discoverToolcalls(ctx: GenContext): ToolcallSpec[] { if (typeof retryReminder !== "string" || !retryReminder) { throw new Error(`structured-completion: template.toolcall "${child.name}" is missing required @retryReminder`); } + if (typeof model !== "string" || !model) { + throw new Error(`structured-completion: template.toolcall "${child.name}" is missing required @model`); + } + if (typeof maxTokens !== "number" || !Number.isInteger(maxTokens) || maxTokens <= 0) { + throw new Error(`structured-completion: template.toolcall "${child.name}" is missing required @maxTokens (a positive integer)`); + } specs.push({ name: child.name, toolName, @@ -79,6 +101,8 @@ function discoverToolcalls(ctx: GenContext): ToolcallSpec[] { // strip the package for the local TS type + import path. payloadRef: stripPackage(payloadRef), retryReminder, + model, + maxTokens, ...(fallback !== undefined ? { fallback: fallback as Record } : {}), }); } @@ -111,6 +135,8 @@ function emitToolcallFunction(spec: ToolcallSpec): string { // Strip a leading "Emit" if the YAML name already starts that way (e.g. // "emitWizardTake" → callEmitWizardTake, not callEmitEmitWizardTake). const reminderConst = `${screamingSnake(spec.name)}_REMINDER`; + const modelConst = `${screamingSnake(spec.name)}_MODEL`; + const maxTokensConst = `${screamingSnake(spec.name)}_MAX_TOKENS`; const payload = spec.payloadRef; const schemaImport = `${payload}InsertSchema`; const hasFallback = spec.fallback !== undefined; @@ -121,6 +147,8 @@ function emitToolcallFunction(spec: ToolcallSpec): string { messages: p.messages, toolName: ${JSON.stringify(spec.toolName)}, toolSchema: ${schemaImport}, + model: ${modelConst}, + maxTokens: ${maxTokensConst}, ...optional, });`; @@ -130,6 +158,8 @@ function emitToolcallFunction(spec: ToolcallSpec): string { messages: p.messages, toolName: ${JSON.stringify(spec.toolName)}, toolSchema: ${schemaImport}, + model: ${modelConst}, + maxTokens: ${maxTokensConst}, ...optional, });`; @@ -164,7 +194,9 @@ ${retryBlock} ? `\nconst ${fallbackConst}: ${payload} = ${indentJsonAsTsLiteral(spec.fallback, 0)};\n` : ""; - return `const ${reminderConst} = + return `const ${modelConst} = ${JSON.stringify(spec.model)}; +const ${maxTokensConst} = ${spec.maxTokens}; +const ${reminderConst} = ${JSON.stringify(spec.retryReminder)}; ${fallbackDecl} export async function ${fnName}(p: ToolcallParams): Promise<${payload}> { @@ -193,12 +225,13 @@ export const structuredCompletion = (): Generator => ({ const functions = specs.map(emitToolcallFunction).join("\n"); - const header = `// @generated by @metaobjectsdev/codegen-ts (via structured-completion) — DO NOT EDIT. + const header = `// @generated by @metaobjectsdev/codegen-ts (via structured-completion) — ${GENERATED_EDIT_NOTE} // AUTO-GENERATED — re-run \`npm run gen:db\`. // Source of truth: every template.toolcall node under metaobjects/. // // Each callEmit(params) wrapper calls completeStructured with the -// configured tool name + payload schema. On a MALFORMED first response the +// configured tool name, payload schema, model id and max_tokens (@model and +// @maxTokens on the template.toolcall). On a MALFORMED first response the // wrapper retries ONCE with a stricter reminder appended to the system // prompt. If the YAML declares a \`fallback\`, malformed double-failure returns // the canned payload; otherwise it rethrows. Transport/API errors (rate limit, @@ -214,7 +247,6 @@ export interface ToolcallParams { system: string | SystemBlock[]; messages: AnthropicMessage[]; fetchImpl?: typeof fetch; - model?: string; } /** @@ -232,10 +264,9 @@ function withReminder(system: string | SystemBlock[], reminder: string): string * Strip undefined optional keys so exactOptionalPropertyTypes-style strictness * in completeStructured does not see an explicit \`undefined\` and complain. */ -function pickOptional(p: ToolcallParams): { fetchImpl?: typeof fetch; model?: string } { - const o: { fetchImpl?: typeof fetch; model?: string } = {}; +function pickOptional(p: ToolcallParams): { fetchImpl?: typeof fetch } { + const o: { fetchImpl?: typeof fetch } = {}; if (p.fetchImpl !== undefined) o.fetchImpl = p.fetchImpl; - if (p.model !== undefined) o.model = p.model; return o; } diff --git a/src/codegen/wizard-data-generator.ts b/src/codegen/wizard-data-generator.ts index d2bbbc0..ec0b49b 100644 --- a/src/codegen/wizard-data-generator.ts +++ b/src/codegen/wizard-data-generator.ts @@ -2,6 +2,9 @@ // the codegen'd Wizard Insert schema, and emits src/personas/generated/wizards.ts // as a sorted, typed WIZARDS const array. // +// Why custom: shipped generators read metadata only; these are instance records +// under data/, which no shipped generator reads or validates. +// // Folded from the former scripts/build-wizard-data.ts into a Generator so wizard // instance data is produced under one `meta gen` and covered by the drift gate. // Validating against WizardInsertSchema (the codegen'd Zod for the Wizard entity) @@ -31,7 +34,7 @@ import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { parse as parseYaml } from "yaml"; import type { Generator, EmittedFile } from "@metaobjectsdev/codegen-ts"; -import { oncePerRun } from "@metaobjectsdev/codegen-ts"; +import { oncePerRun, GENERATED_EDIT_NOTE } from "@metaobjectsdev/codegen-ts"; import type { Wizard } from "../db/generated/Wizard"; const WIZARDS_DIR = "data/wizards"; @@ -63,7 +66,7 @@ export const wizardData = (): Generator => ({ target: "personas", generate: oncePerRun(async (): Promise => { const wizards = await loadWizards(); - const content = `// @generated by @metaobjectsdev/codegen-ts (via wizard-data) — DO NOT EDIT. + const content = `// @generated by @metaobjectsdev/codegen-ts (via wizard-data) — ${GENERATED_EDIT_NOTE} // AUTO-GENERATED — re-run \`npm run gen:db\`. // Source of truth: data/wizards/*.yaml diff --git a/src/codegen/wizard-registry-generator.ts b/src/codegen/wizard-registry-generator.ts index 191b846..4b09a42 100644 --- a/src/codegen/wizard-registry-generator.ts +++ b/src/codegen/wizard-registry-generator.ts @@ -1,6 +1,9 @@ // Custom MO codegen Generator: emits src/personas/generated/registry.ts pairing // each wizard instance file with its codegen'd render handles. // +// Why custom: it joins instance data (data/wizards/) to the prompt-render handles, +// a pairing no shipped generator knows about. +// // Discovery: a "wizard" is identified by a corresponding data/wizards/.yaml // instance file. For each, the registry imports renderSystem + renderUser // from the prompt-render codegen output. @@ -12,7 +15,7 @@ import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { parse as parseYaml } from "yaml"; import type { Generator, EmittedFile } from "@metaobjectsdev/codegen-ts"; -import { oncePerRun } from "@metaobjectsdev/codegen-ts"; +import { oncePerRun, GENERATED_EDIT_NOTE } from "@metaobjectsdev/codegen-ts"; import { TYPE_TEMPLATE, TEMPLATE_SUBTYPE_PROMPT } from "@metaobjectsdev/metadata"; // data/wizards is read relative to cwd (not ctx.projectRoot): `meta verify --codegen` @@ -100,7 +103,7 @@ export const wizardRegistry = (): Generator => ({ ) .join("\n"); - const content = `// @generated by @metaobjectsdev/codegen-ts (via wizard-registry) — DO NOT EDIT. + const content = `// @generated by @metaobjectsdev/codegen-ts (via wizard-registry) — ${GENERATED_EDIT_NOTE} // AUTO-GENERATED — re-run \`npm run gen:db\`. // Source of truth: data/wizards/*.yaml + metaobjects/prompts/*.yaml. diff --git a/src/codegen/wizardsofodd-provider.ts b/src/codegen/wizardsofodd-provider.ts index 0e04692..cf89dfd 100644 --- a/src/codegen/wizardsofodd-provider.ts +++ b/src/codegen/wizardsofodd-provider.ts @@ -1,4 +1,4 @@ -// Project-local MetaDataTypeProvider: adds an Anthropic-specific attr to the core +// Project-local MetaDataTypeProvider: adds two attrs to the core // `template.toolcall` subtype AND registers a project-specific // `template.streamFrame` subtype. // @@ -9,6 +9,11 @@ // cleanly. Future OpenAI / Mistral / MCP consumers would add their own vendor // attrs the same way via registry.extend. // +// It also adds @model, the target model id. Core declares @model on template.prompt +// (the LLM overlay, peer of @maxTokens) but not on template.toolcall, which carries +// @maxTokens only. Here the toolcall is what makes the request, so the model it +// targets is declared beside its token budget, under the same core attr name. +// // @fallback (the canned payload returned on double-failure) is NOT a first-class // attr. Under strict metadata provenance (ADR-0023) an undeclared @-attr fails // load with ERR_UNKNOWN_ATTR, so the toolcall YAML carries the fallback on the @@ -34,6 +39,7 @@ import { ATTR_SUBTYPE_STRING, TEMPLATE_SUBTYPE_TOOLCALL, TEMPLATE_ATTR_PAYLOAD_REF, + TEMPLATE_ATTR_MODEL, MetaTemplate, TypeId, } from "@metaobjectsdev/metadata"; @@ -52,7 +58,7 @@ export const wizardsofoddProvider: MetaDataTypeProvider = { id: "wizardsofodd-anthropic-toolcall", dependencies: ["metaobjects-core-types"], description: - "Extends core template.toolcall with an Anthropic-flavored wire attr (@retryReminder); registers the project-local template.streamFrame subtype.", + "Extends core template.toolcall with an Anthropic-flavored wire attr (@retryReminder) and the target model id (@model); registers the project-local template.streamFrame subtype.", registerTypes(registry) { registry.extend(TYPE_TEMPLATE, TEMPLATE_SUBTYPE_TOOLCALL, { attributes: [ @@ -63,6 +69,13 @@ export const wizardsofoddProvider: MetaDataTypeProvider = { description: "Anthropic-specific: reminder string appended to the system prompt on retry when the initial tool_use call fails to parse.", }, + { + name: TEMPLATE_ATTR_MODEL, + valueType: ATTR_SUBTYPE_STRING, + required: false, + description: + "Target model id for this tool call (LLM-specific). Same name and meaning as core @model on template.prompt.", + }, ], }); diff --git a/src/council/orchestrator.ts b/src/council/orchestrator.ts index feb7835..daad4e5 100644 --- a/src/council/orchestrator.ts +++ b/src/council/orchestrator.ts @@ -39,12 +39,10 @@ export interface ConveneParams { search?: SearchFn; /** Test seam — forwarded to `completeStructured`. */ fetchImpl?: typeof fetch; - /** Optional model override; defaults to the value baked into `completeStructured`. */ - model?: string; } export async function* convene(params: ConveneParams): AsyncGenerator { - const { question, search, apiKey, fetchImpl, model } = params; + const { question, search, apiKey, fetchImpl } = params; const registry = params.registry ?? WIZARD_REGISTRY; const all = registry.map((e) => e.wizard); const prior: PriorTurn[] = []; @@ -91,7 +89,7 @@ export async function* convene(params: ConveneParams): AsyncGenerator { const { visitorId, setCookie } = gate; const apiKey = c.env.ANTHROPIC_API_KEY; - const model = c.env.MODEL || "claude-sonnet-4-6"; const db = getDb(c.env); const slug = await insertCouncil(db, { visitorId, question }); @@ -179,7 +177,7 @@ app.post("/api/council", async (c) => { }); let ordinal = 0; const registry = selectRegistry(WIZARD_REGISTRY, wizardIds); - for await (const frame of convene({ question, apiKey, model, search: searchClient, registry })) { + for await (const frame of convene({ question, apiKey, search: searchClient, registry })) { // Persist first, then forward the same frame to the client. if (frame.event === COUNCIL_EVENTS.wizard) { await recordWizardTurn(db, slug, { ordinal: ++ordinal, ...frame.data }); diff --git a/src/llm/anthropic.ts b/src/llm/anthropic.ts index 1992184..320a20d 100644 --- a/src/llm/anthropic.ts +++ b/src/llm/anthropic.ts @@ -43,48 +43,18 @@ export type SystemBlock = { cache_control?: { type: "ephemeral" }; }; -export interface CompleteParams { +const API_URL = "https://api.anthropic.com/v1/messages"; + +export interface CompleteStructuredParams { apiKey: string; system: string | SystemBlock[]; messages: AnthropicMessage[]; - model?: string; - maxTokens?: number; + /** Model id. No default here: the generated toolcall wrappers pass the toolcall's @model. */ + model: string; + /** max_tokens. No default here: the generated toolcall wrappers pass the toolcall's @maxTokens. */ + maxTokens: number; /** injectable for tests; defaults to global fetch */ fetchImpl?: typeof fetch; -} - -const API_URL = "https://api.anthropic.com/v1/messages"; - -export async function complete(params: CompleteParams): Promise { - const doFetch = params.fetchImpl ?? fetch; - const res = await doFetch(API_URL, { - method: "POST", - headers: { - "x-api-key": params.apiKey, - "anthropic-version": "2023-06-01", - "content-type": "application/json", - }, - body: JSON.stringify({ - model: params.model ?? "claude-sonnet-4-6", - max_tokens: params.maxTokens ?? 400, - system: params.system, - messages: params.messages, - }), - }); - - if (!res.ok) { - const detail = await res.text().catch(() => ""); - throw new AnthropicTransportError(`Anthropic API error ${res.status} ${res.statusText}: ${detail.slice(0, 200)}`, res.status); - } - - const data = (await res.json()) as { content?: Array<{ type: string; text?: string }> }; - return (data.content ?? []) - .filter((b) => b.type === "text" && typeof b.text === "string") - .map((b) => b.text as string) - .join(""); -} - -export interface CompleteStructuredParams extends CompleteParams { /** Tool name; Anthropic emits a tool_use block with this name. */ toolName: string; /** Tool description shown to the model (kept short — the schema does the heavy lifting). */ @@ -104,8 +74,8 @@ export async function completeStructured(params: CompleteStructuredParams) "content-type": "application/json", }, body: JSON.stringify({ - model: params.model ?? "claude-sonnet-4-6", - max_tokens: params.maxTokens ?? 1024, + model: params.model, + max_tokens: params.maxTokens, system: params.system, messages: params.messages, tools: [{ diff --git a/src/llm/generated/toolcalls.ts b/src/llm/generated/toolcalls.ts index bba5da7..edf0d2f 100644 --- a/src/llm/generated/toolcalls.ts +++ b/src/llm/generated/toolcalls.ts @@ -1,9 +1,10 @@ -// @generated by @metaobjectsdev/codegen-ts (via structured-completion) — DO NOT EDIT. +// @generated by @metaobjectsdev/codegen-ts (via structured-completion) — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // AUTO-GENERATED — re-run `npm run gen:db`. // Source of truth: every template.toolcall node under metaobjects/. // // Each callEmit(params) wrapper calls completeStructured with the -// configured tool name + payload schema. On a MALFORMED first response the +// configured tool name, payload schema, model id and max_tokens (@model and +// @maxTokens on the template.toolcall). On a MALFORMED first response the // wrapper retries ONCE with a stricter reminder appended to the system // prompt. If the YAML declares a `fallback`, malformed double-failure returns // the canned payload; otherwise it rethrows. Transport/API errors (rate limit, @@ -20,7 +21,6 @@ export interface ToolcallParams { system: string | SystemBlock[]; messages: AnthropicMessage[]; fetchImpl?: typeof fetch; - model?: string; } /** @@ -38,13 +38,14 @@ function withReminder(system: string | SystemBlock[], reminder: string): string * Strip undefined optional keys so exactOptionalPropertyTypes-style strictness * in completeStructured does not see an explicit `undefined` and complain. */ -function pickOptional(p: ToolcallParams): { fetchImpl?: typeof fetch; model?: string } { - const o: { fetchImpl?: typeof fetch; model?: string } = {}; +function pickOptional(p: ToolcallParams): { fetchImpl?: typeof fetch } { + const o: { fetchImpl?: typeof fetch } = {}; if (p.fetchImpl !== undefined) o.fetchImpl = p.fetchImpl; - if (p.model !== undefined) o.model = p.model; return o; } +const EMIT_VERDICT_MODEL = "claude-sonnet-4-6"; +const EMIT_VERDICT_MAX_TOKENS = 1024; const EMIT_VERDICT_REMINDER = "Your previous response was not a valid tool call. Call the named tool with an input matching its JSON schema. Do not include any text outside the tool call."; @@ -68,6 +69,8 @@ export async function callEmitVerdict(p: ToolcallParams): Promise messages: p.messages, toolName: "emit_verdict", toolSchema: VerdictOutputInsertSchema, + model: EMIT_VERDICT_MODEL, + maxTokens: EMIT_VERDICT_MAX_TOKENS, ...optional, }); } catch (err) { @@ -82,6 +85,8 @@ export async function callEmitVerdict(p: ToolcallParams): Promise messages: p.messages, toolName: "emit_verdict", toolSchema: VerdictOutputInsertSchema, + model: EMIT_VERDICT_MODEL, + maxTokens: EMIT_VERDICT_MAX_TOKENS, ...optional, }); } catch (retryErr) { @@ -91,6 +96,8 @@ export async function callEmitVerdict(p: ToolcallParams): Promise } } +const EMIT_WIZARD_TAKE_MODEL = "claude-sonnet-4-6"; +const EMIT_WIZARD_TAKE_MAX_TOKENS = 1024; const EMIT_WIZARD_TAKE_REMINDER = "Your previous response was not a valid tool call. Call the named tool with an input matching its JSON schema. Do not include any text outside the tool call."; @@ -103,6 +110,8 @@ export async function callEmitWizardTake(p: ToolcallParams): Promise { - captured.body = JSON.parse(init.body as string); - captured.headers = init.headers; - return new Response( - JSON.stringify({ content: [{ type: "text", text: "hello from the tower" }] }), - { status: 200, headers: { "content-type": "application/json" } }, - ); - }; -} - -describe("complete", () => { - it("posts to the Messages API and returns joined text", async () => { - const captured: { body?: any; headers?: any } = {}; - const text = await complete({ - apiKey: "sk-test", - model: "claude-sonnet-4-6", - system: "be a wizard", - messages: [{ role: "user", content: "hi" }], - maxTokens: 256, - fetchImpl: fakeFetch(captured) as unknown as typeof fetch, - }); - - expect(text).toBe("hello from the tower"); - expect(captured.body.model).toBe("claude-sonnet-4-6"); - expect(captured.body.system).toBe("be a wizard"); - expect(captured.body.max_tokens).toBe(256); - expect(captured.body.messages).toEqual([{ role: "user", content: "hi" }]); - expect((captured.headers as Record)["x-api-key"]).toBe("sk-test"); - expect((captured.headers as Record)["anthropic-version"]).toBe("2023-06-01"); - }); - - it("throws on non-200 with status in message", async () => { - const badFetch = async () => - new Response("nope", { status: 429, statusText: "Too Many Requests" }); - await expect( - complete({ - apiKey: "sk-test", - system: "s", - messages: [{ role: "user", content: "x" }], - fetchImpl: badFetch as unknown as typeof fetch, - }), - ).rejects.toThrow(/429/); - }); - - it("applies default model and max_tokens when omitted", async () => { - const captured: { body?: any } = {}; - await complete({ - apiKey: "sk-test", - system: "s", - messages: [{ role: "user", content: "x" }], - fetchImpl: (async (_url: string, init: RequestInit) => { - captured.body = JSON.parse(init.body as string); - return new Response(JSON.stringify({ content: [{ type: "text", text: "ok" }] }), { status: 200 }); - }) as unknown as typeof fetch, - }); - expect(captured.body.model).toBe("claude-sonnet-4-6"); - expect(captured.body.max_tokens).toBe(400); - }); - - it("joins only text blocks and skips non-text blocks", async () => { - const fetchImpl = (async () => - new Response( - JSON.stringify({ - content: [ - { type: "text", text: "foo" }, - { type: "tool_use", id: "t1", name: "x", input: {} }, - { type: "text", text: "bar" }, - ], - }), - { status: 200 }, - )) as unknown as typeof fetch; - const text = await complete({ - apiKey: "sk-test", - system: "s", - messages: [{ role: "user", content: "x" }], - fetchImpl, - }); - expect(text).toBe("foobar"); - }); - - it("passes system through verbatim when given a SystemBlock[] (enables cache_control)", async () => { - const captured: { body?: any } = {}; - const blocks = [{ type: "text" as const, text: "be a wizard", cache_control: { type: "ephemeral" as const } }]; - await complete({ - apiKey: "sk-test", - system: blocks, - messages: [{ role: "user", content: "hi" }], - fetchImpl: (async (_url: string, init: RequestInit) => { - captured.body = JSON.parse(init.body as string); - return new Response(JSON.stringify({ content: [{ type: "text", text: "ok" }] }), { status: 200 }); - }) as unknown as typeof fetch, - }); - expect(captured.body.system).toEqual(blocks); - }); -}); +import { completeStructured } from "../src/llm/anthropic"; describe("completeStructured", () => { const schema = z.object({ @@ -124,11 +27,60 @@ describe("completeStructured", () => { messages: [{ role: "user", content: "u" }], toolName: "emit_take", toolSchema: schema, + model: "claude-sonnet-4-6", + maxTokens: 1024, fetchImpl, }); expect(got).toEqual({ stance: "a", note: "hi" }); }); + it("posts the given model, max_tokens, system and messages to the Messages API", async () => { + const captured: { body?: string; headers?: Record } = {}; + const blocks = [{ type: "text" as const, text: "be a wizard", cache_control: { type: "ephemeral" as const } }]; + const fetchImpl: typeof fetch = (async (_url: string, init: RequestInit) => { + captured.body = init.body as string; + captured.headers = init.headers as Record; + return new Response( + JSON.stringify({ content: [{ type: "tool_use", name: "t", input: { stance: "a", note: "n" } }] }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }) as unknown as typeof fetch; + await completeStructured({ + apiKey: "sk-test", + system: blocks, + messages: [{ role: "user", content: "hi" }], + toolName: "t", + toolSchema: schema, + model: "claude-sonnet-4-6", + maxTokens: 256, + fetchImpl, + }); + const body = JSON.parse(captured.body!); + expect(body.model).toBe("claude-sonnet-4-6"); + expect(body.max_tokens).toBe(256); + expect(body.system).toEqual(blocks); + expect(body.messages).toEqual([{ role: "user", content: "hi" }]); + expect(captured.headers?.["x-api-key"]).toBe("sk-test"); + expect(captured.headers?.["anthropic-version"]).toBe("2023-06-01"); + }); + + it("throws on non-200 with status in message", async () => { + const badFetch = (async () => + new Response("nope", { status: 429, statusText: "Too Many Requests" })) as unknown as typeof fetch; + await expect( + completeStructured({ + apiKey: "sk-test", + system: "s", + messages: [{ role: "user", content: "x" }], + toolName: "t", + toolSchema: schema, + model: "claude-sonnet-4-6", + maxTokens: 1024, + fetchImpl: badFetch, + }), + ).rejects.toThrow(/429/); + }); + it("sends tool_choice forcing the named tool", async () => { const captured: { body?: string } = {}; const fetchImpl: typeof fetch = (async (_url: string, init: RequestInit) => { @@ -144,6 +96,8 @@ describe("completeStructured", () => { messages: [{ role: "user", content: "u" }], toolName: "t", toolSchema: schema, + model: "claude-sonnet-4-6", + maxTokens: 1024, fetchImpl, }); const body = JSON.parse(captured.body!); @@ -164,6 +118,8 @@ describe("completeStructured", () => { messages: [{ role: "user", content: "u" }], toolName: "t", toolSchema: schema, + model: "claude-sonnet-4-6", + maxTokens: 1024, fetchImpl, }), ).rejects.toThrow(/no tool_use block/i); @@ -180,6 +136,8 @@ describe("completeStructured", () => { messages: [{ role: "user", content: "u" }], toolName: "t", toolSchema: schema, + model: "claude-sonnet-4-6", + maxTokens: 1024, fetchImpl, }), ).rejects.toThrow(/validation/i); diff --git a/test/codegen/structured-completion-generator.test.ts b/test/codegen/structured-completion-generator.test.ts new file mode 100644 index 0000000..2a53fb9 --- /dev/null +++ b/test/codegen/structured-completion-generator.test.ts @@ -0,0 +1,61 @@ +import { describe, it, expect } from "vitest"; +import type { GenContext } from "@metaobjectsdev/codegen-ts"; +import { MetaDataLoader, composeRegistry, coreProviders, isMetaObject } from "@metaobjectsdev/metadata"; +import { structuredCompletion } from "../../src/codegen/structured-completion-generator"; +import { wizardsofoddProvider } from "../../src/codegen/wizardsofodd-provider"; + +// The structured-completion generator, run against a small in-memory model. The model +// id and the token budget of each tool call are metadata (@model, @maxTokens on the +// template.toolcall), so the generated wrapper is where they reach the HTTP client. +function model(toolcallAttrs: string): string { + return ` +metadata: + package: demo + children: + - object.value: + name: Answer + children: + - field.string: + name: text + required: true + - template.toolcall: + name: emitAnswer + toolName: emit_answer + payloadRef: Answer + retryReminder: Call the tool. +${toolcallAttrs} +`; +} + +async function generate(src: string) { + const registry = composeRegistry([...coreProviders, wizardsofoddProvider]); + const { root, errors } = await MetaDataLoader.fromString(src, "yaml", { registry, strict: true }); + expect(errors).toEqual([]); + const ctx: GenContext = { + entities: root.children().filter(isMetaObject), + loadedRoot: root, + matches: () => true, + config: { outDir: "generated", extStyle: "none", dbImport: "./db", dialect: "sqlite" }, + warn: () => {}, + }; + return structuredCompletion().generate(ctx); +} + +describe("structuredCompletion generator", () => { + it("passes the toolcall's @model and @maxTokens to every completeStructured call", async () => { + const [file] = await generate(model(" model: claude-test-model\n maxTokens: 777")); + expect(file?.content).toContain('const EMIT_ANSWER_MODEL = "claude-test-model";'); + expect(file?.content).toContain("const EMIT_ANSWER_MAX_TOKENS = 777;"); + // Both the first call and the reminder retry. + expect(file?.content.match(/model: EMIT_ANSWER_MODEL,/g)).toHaveLength(2); + expect(file?.content.match(/maxTokens: EMIT_ANSWER_MAX_TOKENS,/g)).toHaveLength(2); + }); + + it("refuses a toolcall that declares no @model", async () => { + await expect(generate(model(" maxTokens: 777"))).rejects.toThrow(/emitAnswer.*@model/); + }); + + it("refuses a toolcall that declares no @maxTokens", async () => { + await expect(generate(model(" model: claude-test-model"))).rejects.toThrow(/emitAnswer.*@maxTokens/); + }); +}); diff --git a/test/structured-output.test.ts b/test/structured-output.test.ts index e45da49..4127d43 100644 --- a/test/structured-output.test.ts +++ b/test/structured-output.test.ts @@ -130,3 +130,28 @@ describe("structured outputs — retry/fallback contract", () => { expect(verdictCalls).toBe(2); // initial + 1 retry }); }); + +describe("structured outputs — model and token budget come from the metadata", () => { + // metaobjects/toolcalls/*.yaml declare @model and @maxTokens on each template.toolcall; + // the generated wrappers pass them to the HTTP client, which holds no default of its own. + it("every tool call sends the toolcall's declared model and max_tokens", async () => { + const sent: Array<{ tool: string; model: unknown; maxTokens: unknown }> = []; + const fetchImpl: typeof fetch = async (_url, init) => { + const body = JSON.parse(((init?.body ?? "{}") as string)); + const tool = body.tools[0].name as string; + sent.push({ tool, model: body.model, maxTokens: body.max_tokens }); + return r(tool === "emit_wizard_take" ? VALID_TAKE_RESPONSE : VALID_VERDICT_RESPONSE); + }; + for await (const _e of convene({ + question: "q?", + apiKey: "test-key", + fetchImpl, + registry: WIZARD_REGISTRY.slice(0, 1), + })) { /* drain */ } + expect(sent.map((s) => s.tool)).toEqual(["emit_wizard_take", "emit_verdict"]); + for (const s of sent) { + expect(s.model).toBe("claude-sonnet-4-6"); + expect(s.maxTokens).toBe(1024); + } + }); +}); diff --git a/wrangler.jsonc b/wrangler.jsonc index 8724469..da61fae 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -10,7 +10,6 @@ "run_worker_first": ["/api/*", "/c/*"] }, "vars": { - "MODEL": "claude-sonnet-4-6", "MAX_QUESTIONS_PER_DAY": "5", "GLOBAL_MAX_PER_DAY": "200", "IP_MAX_PER_DAY": "10",