@metaobjectsdev/sdk 0.5.0-rc.3 → 0.6.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- export declare const AGENT_DOCS_BODY = "# Meta Forge \u2014 agent reference\n\nThis file is scaffolded by `meta init` and lives alongside your `metaobjects/` records. It teaches AI coding assistants (Claude Code, Codex, etc.) how to read and modify MetaObjects metadata correctly. Refresh after CLI updates with `meta init --refresh-docs`.\n\n## Five working principles (read first)\n\nThese shape every interaction with a metaobjects-driven project. Follow them when you author metadata, write hand-coded business logic, or review someone else's work.\n\n### 1. If it's pattern-derivable from metadata, generate it. Never hand-write boilerplate.\n\nThe metaobjects raison d'\u00EAtre is that anything the metadata fully describes \u2014 schemas, FK references, basic CRUD, query helpers, Zod validators, route handlers, RHF rules, form fields \u2014 should be produced by codegen, not hand-typed. If you find yourself hand-writing something the metadata already knows about, stop and use the generated artifact.\n\nThe first version of the trainer website's database layer had hand-written Drizzle schemas, Zod schemas, and CRUD endpoints. Every one of those is now generated. The hand-written code that remains is real business logic (Stripe webhooks, Loops integration, custom auth flows) \u2014 things the generator genuinely cannot derive.\n\nWhen you're about to add a new field or entity: edit `metaobjects/*.json` and re-run `meta gen`. Don't reach for the generated file directly.\n\n### 2. Use the generated constants. Never use magic strings that touch metadata.\n\nAfter `meta gen`, each entity file exports a rich metadata-constants block. Each non-dollar-prefixed key is a per-field object that carries everything a consumer might need (name, label, view, html input type, placeholder, RHF validation rules):\n\n```ts\nexport const Subscriber = {\n $entity: \"Subscriber\", // entity name string\n $table: \"subscribers\", // SQL table name\n $path: \"/subscribers\", // REST resource path\n\n email: {\n name: \"email\", // field name string (use for filters, register())\n label: \"Email Address\", // humanized fallback or @label override\n view: \"text\", // MetaView subtype\n htmlType: \"email\", // optional; maps view \u2192 HTML <input type=>\n placeholder: \"you@example.com\", // optional; only when @placeholder is set on the view\n helpText: \"We never share this.\", // optional; only when @helpText is set\n rules: { // optional; derived from validator children\n required: \"Email is required\",\n maxLength: { value: 255, message: \"Too long\" },\n pattern: { value: /.../, message: \"Invalid email\" },\n },\n },\n firstName: { name: \"firstName\", label: \"First Name\", view: \"text\", htmlType: \"text\", rules: { required: \"First Name is required\" } },\n // ...\n} as const;\n```\n\n**Use them everywhere \u2014 in both generated AND hand-written code:**\n\n```tsx\n// \u2717 Don't:\n<input name=\"email\" type=\"email\" placeholder=\"Email\" />\n\n// \u2713 Do:\n<input\n type={Subscriber.email.htmlType}\n name={Subscriber.email.name}\n placeholder={Subscriber.email.placeholder}\n aria-label={Subscriber.email.label}\n/>\n```\n\nRename a field in `metaobjects/` and re-gen \u2014 TypeScript catches every stale reference.\n\n**Special case \u2014 Drizzle column access:** when you're already inside Drizzle's typed builder, just use the column properties directly. Drizzle's table-const types are themselves derived from metadata, so `weeks.programId` is already TS-safe:\n\n```ts\n// \u2713 Use Drizzle's typed accessor directly \u2014 no constants needed here:\ndb.select().from(weeks).where(eq(weeks.programId, X))\n\n// \u2717 Don't do this \u2014 it's redundant indirection:\ndb.select().from(weeks).where(eq(weeks[Week.programId.name], X))\n```\n\nUse the constants when you need a STRING (filter object keys, registration arguments, REST paths, labels). Use Drizzle properties directly when the type system already does the work.\n\n### 3. Forms: spread `form.input.<field>` from useEntityForm. One line per input.\n\nFor React forms, use `useEntityForm` from `@metaobjectsdev/react`. It returns the standard React Hook Form surface plus a pre-bound `.input` accessor \u2014 one entry per field, ready to spread onto an `<input>`:\n\n```tsx\nimport { useEntityForm } from '@metaobjectsdev/react';\nimport { Subscriber, SubscriberInsertSchema } from './generated/Subscriber';\n\nconst form = useEntityForm(Subscriber, SubscriberInsertSchema);\n\n<label>{Subscriber.email.label}</label>\n<input {...form.input.email} /> // \u2190 type, placeholder, name, rules, aria-label all spread automatically\n```\n\nFor non-`<input>` controls (textarea, select), the `type` attr is omitted from `form.input.X` \u2014 pick the right element yourself.\n\nThe same Zod schema (`SubscriberInsertSchema`) validates on the server (in Fastify routes) and on the client (via the resolver). One schema, two surfaces, zero drift.\n\n### 4. Routes: use the generated `<Entity>.routes.ts` for stock CRUD. Hand-write only what's custom.\n\n`meta gen` emits a per-entity routes file that mounts the 5 standard verbs via `mountCrudRoutes` from `@metaobjectsdev/runtime-ts/drizzle-fastify`. The runtime is plain Drizzle + Zod \u2014 no extra ORM.\n\nFor custom flows (Stripe webhooks, side effects, auth-gated actions), hand-write the route \u2014 but import the entity constants + generated Zod schema. The boilerplate (CRUD, validation, 404 mapping, pagination) lives in the helper; your hand-written code is just the business logic.\n\n**Auth pattern:** install a plugin-level Fastify `preHandler` hook at the top of your route plugin. The hook applies to every route registered after it \u2014 both hand-written handlers AND metaobjects-generated routes via the `routeOptions` field. Beats sprinkling `if (!auth(...)) return;` at the top of every handler.\n\n### 5. Hand-coded code is always available, but coexists with generated code.\n\nGenerated code does the boilerplate. Hand-coded code does the business logic. They live in the same project, the same package, sometimes the same file. The hand-coded code consumes the generated constants and generated Zod schemas \u2014 it never duplicates schema, never hard-codes paths, never declares its own validators that metadata could declare.\n\nConcrete pattern from the trainer website:\n- Generated `Subscriber.routes.ts` registers GET / GET-by-id / POST / PATCH / DELETE on `/api/subscribers`.\n- Hand-written `apps/api/src/routes/subscribers.ts` keeps `POST /subscribe` \u2014 the custom endpoint with the Loops side-effect.\n- Both registered with `fastify.register()`. Both validate via `SubscriberInsertSchema`. Both use `Subscriber.email.name` / etc. Neither knows the other exists.\n\n## Metaobjects metamodel \u2014 quick rules\n\nThe format used by `metaobjects/*.json` is **metaobjects metadata**, a cross-language standard. Eight base types:\n\n| Type | Purpose |\n|---|---|\n| `metadata` | Root document wrapper |\n| `object` | An entity (table/record) |\n| `field` | A property on an object |\n| `attr` | Named scalar/array decoration on any parent |\n| `validator` | A validation rule |\n| `view` | A UI control kind |\n| `identity` | A primary/secondary key |\n| `relationship` | An association between objects |\n\n### Two most-violated rules\n\n1. **Attribute uniqueness.** Within a single parent metadata node, all attribute names must be unique. You cannot have two `attr` children both named `alternative`. For multi-value, use a single `stringarray` attr: `\"@alternatives\": [\"a\", \"b\", \"c\"]`.\n\n2. **Inline `@<name>` and `attr` child are the same thing.** `\"@maxLength\": 50` is shorthand for `{\"attr\": {\"name\": \"maxLength\", \"subType\": \"int\", \"value\": \"50\"}}`. The parser converts inline form into attr children. Don't use both forms for the same attribute name on the same parent.\n\n### Object subtypes (v0.3)\n\n- `base` \u2014 abstract template (no runtime semantics)\n- `entity` \u2014 persistent record; should have a primary identity\n- `value` \u2014 value-object; equality by content; must NOT have a primary identity\n\nJava-runtime strategies (pojo / map / proxy) belong on `@javaRuntime`, not in `subType`.\n\n### Reserved structural keys (NOT attributes)\n\n`name`, `subType`, `package`, `extends`, `isAbstract`, `children`, `merge`, `value`.\n\nThe v0.2 keys (`super`, `overlay`, `override`, `isInterface`, `implements`) are **gone**. The current parser will reject them. Use:\n- `extends:` instead of `super:` for the supertype reference\n- `merge: true` instead of `overlay: true` / `override: true` for in-place modification\n- `@isAbstract: true` instead of `isInterface: true` (multiple inheritance is not supported)\n\n### Package paths and inheritance\n\n- Package segments separated by `::` \u2014 `acme::common::id`\n- Relative references in `extends:` \u2014 `..::common::id` means \"go up to parent package, descend into `common::id`\"\n- Cross-file resolution works as long as all files are passed to Loader (or live in the same `metaobjects/` directory)\n\n### Two special intercepted attrs (parser-routed)\n\n- `@isArray` \u2192 marks a field as a collection\n- `@isAbstract` \u2192 marks a node as abstract (inheritable but not instantiable)\n\n## Validators \u2014 two layers\n\nValidators can attach in two places, and they compose:\n\n**Field-level validators** describe what makes the *stored value* valid. They survive across UI, API, batch import, manual SQL \u2014 anywhere data enters the system. The generated Zod `<Entity>InsertSchema` encodes these.\n\n```json\n{\"field\": {\"name\": \"email\", \"subType\": \"string\",\n \"children\": [\n {\"validator\": {\"subType\": \"required\"}},\n {\"validator\": {\"subType\": \"regex\", \"@pattern\": \"^[^@]+@[^@]+\\\\.[^@]+$\"}}\n ]\n}}\n```\n\n**View-level validators** describe what makes user *input* valid in a specific UI surface \u2014 possibly stricter, possibly with different messages, possibly format-specific. They run client-side in generated forms. They do NOT necessarily reject the stored value if it's already in the DB.\n\n```json\n{\"field\": {\"name\": \"phone\", \"subType\": \"string\",\n \"children\": [\n {\"validator\": {\"subType\": \"regex\", \"@pattern\": \"^\\\\+?[0-9]+$\"}},\n {\"view\": {\"subType\": \"text-input\", \"@label\": \"Phone\",\n \"children\": [\n {\"validator\": {\"subType\": \"length\", \"@min\": 7, \"@max\": 20,\n \"@message\": \"Phone must be 7-20 digits\"}}\n ]\n }}\n ]\n}}\n```\n\nRule of thumb: rules that protect data integrity \u2192 field. Rules that improve input UX \u2192 view.\n\n## metaobjects.config.ts \u2014 generator wiring (project root)\n\n`meta gen` reads `metaobjects.config.ts` at the project root. This is where you declare which generators run and their options. It is TypeScript, type-checked, and imported via `jiti` at run time.\n\n```ts\nimport { defineConfig } from \"@metaobjectsdev/cli\";\nimport {\n entityFile, queriesFile, routesFile, /* formFile, */ barrel,\n} from \"@metaobjectsdev/codegen-ts/generators\";\n\nexport default defineConfig({\n outDir: \"packages/database/src/generated\",\n extStyle: \"none\",\n dbImport: \"../index\",\n dialect: \"sqlite\",\n generators: [\n entityFile(),\n queriesFile(),\n routesFile(),\n // formFile(), // opt-in: emits stock React forms per entity\n barrel(),\n ],\n});\n```\n\n3rd-party generator example: `import { tanstackQuery } from \"@metaobjectsdev/codegen-ts-tanstack\"; // then add tanstackQuery({ ... }) to the generators array`\n\nFilters live on the generator entry: `routesFile({ filter: e => e.name !== \"AuditLog\" })`\n\n`.metaobjects/config.json` is unchanged \u2014 it still holds static project state (schema_version, pending_in_git, confidence_thresholds). Generator wiring belongs in `metaobjects.config.ts` so TypeScript can type-check the imports.\n\n## Generated hooks + grids (TanStack)\n\nWhen `tanstackQuery()` is in your `metaobjects.config.ts`, every entity gets `<Entity>.hooks.ts` with a query-key factory + `useEntity`, `useEntities`, `useCreate`, `useUpdate`, `useDelete` hooks. When `tanstackGrid()` is in the config, entities with a `layout[dataGrid]` child also get `<Entity>.columns.tsx`.\n\n```tsx\nimport { usePrograms, useCreateProgram } from \"@your-pkg/database/generated/Program.hooks\";\nimport { programDefaultColumns, programDefaultGrid } from \"@your-pkg/database/generated/Program.columns\";\nimport { EntityGrid } from \"@metaobjectsdev/tanstack\";\n\nconst { data, isLoading } = usePrograms();\nconst create = useCreateProgram({ onSuccess: () => navigate(\"/programs\") });\n\n<EntityGrid\n columns={programDefaultColumns}\n grid={programDefaultGrid}\n data={data ?? []}\n isLoading={isLoading}\n onRowClick={(row) => navigate(`/admin/programs/${row.id}`)}\n/>\n```\n\n**Provider setup.** Wrap your app with `<EntityFetcherProvider value={fetcher}>` (supplies the HTTP fetcher to all generated hooks). For an admin subtree with different auth, wrap a second time inside: `<EntityFetcherProvider value={adminFetch}>...</EntityFetcherProvider>` overrides the outer one.\n\n**Metadata layer \u2014 grid definition:**\n\n```jsonc\n{ \"layout\": {\n \"subType\": \"dataGrid\",\n \"name\": \"default\",\n \"@pageSize\": 25,\n \"@defaultSortField\": \"createdAt\",\n \"@defaultSortOrder\": \"desc\",\n \"@filterable\": true,\n \"@columns\": [\"email\", \"firstName\", \"subscribed\", \"createdAt\"]\n}}\n```\n\nThe `@columns` attr is a flat string array listing fields to display. Per-column rendering comes from each field's own `view` subtype (the same one that drives forms); sortability comes from the field's `@sortable` attr; width belongs in app CSS. There are no nested per-column children \u2014 just `@columns`.\n\n**Cell renderers.** Field rendering inside grids comes from each field's own `view` subtype (the same one that drives forms). Override defaults app-wide with `<CellRendererProvider value={{ currency: ({ getValue }) => <Money value={getValue()} /> }}>`.\n\n**Per-entity opt-out.** `@emitTanstack: false` on an entity skips both hooks and columns.\n\n## Filtering generated lists\n\nMark filterable fields in metadata with `@filterable: true`:\n\n```jsonc\n{ \"field\": { \"name\": \"email\", \"subType\": \"string\", \"@filterable\": true } }\n```\n\nThe generated `useSubscribers(filter)` hook accepts a typed filter:\n\n```tsx\nconst { data } = useSubscribers({\n email: { like: \"%@example.com\" },\n subscribed: true,\n sort: \"createdAt:desc\",\n limit: 25,\n});\n```\n\nURL sent: `/subscribers?filter[email][like]=%25@example.com&filter[subscribed]=true&sort=createdAt:desc&limit=25`\n\n**Operators by field subtype:**\n- String: `eq, ne, in, like, isNull`\n- Number/date: `eq, ne, gt, gte, lt, lte, in, isNull`\n- Boolean: `eq, isNull`\n\nIllegal combinations like `useSubscribers({ subscribed: { gte: true } })` fail to compile (booleans don't support `gte`).\n\n**Per-grid preset filter** via layout `@filter`:\n\n```jsonc\n{ \"layout\": { \"subType\": \"dataGrid\", \"name\": \"active\",\n \"@filter\": { \"subscribed\": true },\n \"@columns\": [\"email\", \"firstName\", \"subscribed\"] }}\n```\n\nGenerates `subscriberActiveFilter` const consumable in pages. Compose with ad-hoc filters via object spread.\n\n## Projections (read models with joined/aggregated columns)\n\nWhen a list needs computed columns (counts, sums, joined fields), create a **projection** \u2014 an entity that extends a base entity but reads from a SQL view:\n\n```json\n// metaobjects/meta.commerce.json (inline with Program)\n{\n \"object\": {\n \"name\": \"ProgramSummary\",\n \"subType\": \"entity\",\n \"extends\": \"Program\",\n \"children\": [\n { \"source\": { \"subType\": \"dbView\", \"@name\": \"v_program_summary\" } },\n { \"field\": { \"name\": \"weekCount\", \"subType\": \"int\", \"children\": [\n { \"origin\": { \"subType\": \"aggregate\",\n \"@agg\": \"count\", \"@of\": \"Week.id\", \"@via\": \"Program.weeks\" }}\n ]}},\n { \"identity\": { \"subType\": \"primary\", \"@fields\": \"id\" } }\n ]\n }\n}\n```\n\n`meta gen` produces a read-only `useProgramSummaries(filter)` hook, a SQL view DDL in the migration, and a read-only GET-only route.\n\n**Aggregate vocabulary**: `count`, `sum`, `avg`, `min`, `max`.\n\n**Multi-level via paths** are supported: `@via: \"Program.weeks.workouts\"` builds a 2-level JOIN tree.\n\n**For pages that need a full nested tree** (e.g., Program \u2192 Weeks \u2192 Workouts \u2192 Exercises), use 4 entity hooks with Project D's filter syntax for batched lookups (no projection needed \u2014 flat hooks + client-side stitching is enough):\n\n```tsx\nconst { data: weeks } = useWeeks({ programId, sort: \"weekNumber:asc\" });\nconst weekIds = weeks?.map((w) => w.id) ?? [];\nconst { data: workouts } = useWorkouts(\n weekIds.length ? { weekId: { in: weekIds } } : undefined,\n);\n```\n\n## Currency fields\n\nDeclare a money field with `subType: \"currency\"`:\n\n```json\n{ \"field\": { \"name\": \"priceCents\", \"subType\": \"currency\", \"@currency\": \"USD\" } }\n```\n\nStorage stays as integer minor units (cents for USD). The generated `<Entity>` constants block carries `view`, `currency`, `locale` so admin grids auto-format prices.\n\n**Imports \u2014 use sub-paths in browser code:**\n\n```tsx\nimport { formatCurrency } from \"@metaobjectsdev/runtime-web\";\nimport { CurrencyInput } from \"@metaobjectsdev/react\";\n```\n\n**Display:**\n\n```tsx\n<span>{formatCurrency(program.priceCents)}</span> // $15.00\n<span>{formatCurrency(p.amountCents, \"EUR\", \"de-DE\")}</span> // 15,00 \u20AC\n```\n\n**Form input:**\n\n```tsx\n<CurrencyInput value={priceCents} onChange={setPriceCents} currency=\"USD\" />\n```\n\nUser types `15.99` \u2192 component emits `1599` to `onChange` on blur. Wire format is always integer cents.\n\n**Locale override** via a `view[currency]` child:\n\n```json\n{ \"field\": { \"name\": \"priceCents\", \"subType\": \"currency\", \"@currency\": \"EUR\",\n \"children\": [{ \"view\": { \"subType\": \"currency\", \"@locale\": \"de-DE\" } }]\n}}\n```\n\nCurrency code lives on the field; locale lives on the view.\n\n## Generated artifacts \u2014 what `meta gen` produces\n\nAfter `meta gen`, you get one barrel + per-entity files in your configured `outDir` (default `packages/database/src/generated/`):\n\n| File | What's in it | When to touch by hand |\n|---|---|---|\n| `<Entity>.ts` | Drizzle table, relations(), inferred types, Zod insert/update schemas, and the rich `<Entity>` constants block (per-field objects with name, label, view, htmlType, rules, etc.) | Never. Regenerate. |\n| `<Entity>.queries.ts` | Typed query helpers (`findUserById`, `listUsers`, `createUser`, ...) using prepared statements | Never. Regenerate. |\n| `<Entity>.routes.ts` | Fastify CRUD plugin delegating to `mountCrudRoutes` from `@metaobjectsdev/runtime-ts/drizzle-fastify` (5 verbs, Zod validation, 404/204 mapping, Drizzle-direct under the hood) | Never. Regenerate. |\n| `<Entity>.form.tsx` | React form using `useEntityForm` + the entity constants. **OPT-IN at project level:** add `formFile()` to `generators` in `metaobjects.config.ts`. Opt out per-entity via `@emitForm: false`. | Never. Regenerate. |\n| `index.ts` | Barrel re-exporting every entity file | Never. Regenerate. |\n\nFor business logic the generator doesn't cover, create a SIBLING file: `<Entity>.extra.ts` for query/route helpers, or any file you like in your apps directory. Import the constants from the generated `<Entity>.ts`.\n\n### Stock route mounting\n\n```ts\nimport { subscriberRoutes } from \"@your-pkg/database/generated/Subscriber.routes\";\nfastify.register(subscriberRoutes, { prefix: \"/api\" });\n```\n\nThat mounts: `GET /api/subscribers`, `GET /api/subscribers/:id`, `POST /api/subscribers`, `PATCH /api/subscribers/:id`, `DELETE /api/subscribers/:id`. Pagination via `?limit=` & `?offset=`. Validation via the generated Zod schemas. Drizzle calls under the hood.\n\n### Mixing custom routes alongside generated\n\n```ts\nimport { db, subscribers } from \"@your-pkg/database\";\nimport { Subscriber, SubscriberInsertSchema } from \"@your-pkg/database/generated/Subscriber\";\nimport { eq } from \"drizzle-orm\";\n\nfastify.post(\"/subscribe\", async (req, reply) => {\n // Generated Zod schema validates the body \u2014 same schema the API route uses.\n const parsed = SubscriberInsertSchema.safeParse(req.body);\n if (!parsed.success) return reply.code(400).send({ issues: parsed.error.issues });\n\n // Drizzle's typed accessors are already TS-safe; no need for indirection.\n const existing = await db.select().from(subscribers).where(eq(subscribers.email, parsed.data.email)).get();\n if (existing) return reply.code(409).send({ error: \"Already subscribed\" });\n\n const [row] = await db.insert(subscribers).values(parsed.data).returning();\n // ... your business logic (analytics, Loops/Mailchimp, navigation, etc.)\n return reply.code(201).send(row);\n});\n```\n\nThe fact that every metadata-derived value flows from `Subscriber` / `SubscriberInsertSchema` / the typed `subscribers` table is what makes rename-the-field-in-metadata-and-regen safe.\n\n### Hand-written form using `useEntityForm`\n\n```tsx\nimport { useEntityForm } from '@metaobjectsdev/react';\nimport { Subscriber, SubscriberInsertSchema, type Subscriber as Row } from './generated/Subscriber';\n\nexport function SubscribeForm() {\n const form = useEntityForm(Subscriber, SubscriberInsertSchema);\n const { handleSubmit, formState: { errors } } = form;\n\n return (\n <form onSubmit={handleSubmit(/* your onSubmit */)} className=\"your-design-system\">\n <label>{Subscriber.email.label}</label>\n <input {...form.input.email} />\n {errors.email && <span>{errors.email.message}</span>}\n\n <label>{Subscriber.firstName.label}</label>\n <input {...form.input.firstName} />\n {errors.firstName && <span>{errors.firstName.message}</span>}\n\n <button type=\"submit\">Subscribe</button>\n </form>\n );\n}\n```\n\nSpread `form.input.<field>` \u2014 it carries name, type, placeholder, rules, aria-label automatically. No magic strings.\n\n## Meta Forge additions\n\n### `@forge*` attribute namespace\n\nProvenance and confidence concerns expressed as inline attributes on any metadata child. Names use camelCase (no separator).\n\nMost common:\n- `@forgeConfidence` (double 0..1) \u2014 confidence the record is correct\n- `@forgeSource` (string) \u2014 `human` | `claude` | `ts-ast` | `drizzle` | ...\n- `@forgePrimaryLocation` (string) \u2014 file path for an entity\n- `@forgeRationale` (string, decision only) \u2014 why this decision\n- `@forgeAlternatives` (stringarray, decision only) \u2014 alternatives considered\n\nFull inventory in `packages/sdk/FORGE-METADATA.md`.\n\n### New top-level types\n\nRegistered by `@metaobjectsdev/sdk` into the TypeRegistry:\n\n| Type | Purpose |\n|---|---|\n| `decision` | Architectural or design decision |\n| `principle` | Design principle (advisory/enforced) |\n| `convention` | Coding/structural convention |\n| `glossary` | Domain-term definition |\n| `failure` | Recorded failure mode |\n\nThese coexist with `object` children in the same package files. `meta gen` and `meta migrate` only consume `object`; the descriptive types are context for AI tooling and don't drive codegen.\n\n## File layout\n\n```\nmetaobjects/\n\u251C\u2500\u2500 meta.common.json shared base fields/validators (optional)\n\u251C\u2500\u2500 meta.<domain>.json your entity packages(s)\n\u2514\u2500\u2500 _pending/<pkg>.json proposed packages awaiting review\n\n.metaobjects/\n\u251C\u2500\u2500 config.json static project state\n\u251C\u2500\u2500 migrations/ written by meta migrate\n\u2514\u2500\u2500 .gen-state/ codegen merge base (gitignored)\n\nmetaobjects.config.ts generator wiring (committed)\n```\n\n## Worked example\n\n```json\n{\n \"metadata\": {\n \"package\": \"myapp\",\n \"children\": [\n {\n \"object\": {\n \"name\": \"User\",\n \"subType\": \"entity\",\n \"@forgeConfidence\": 0.95,\n \"@forgeSource\": \"human\",\n \"@forgePrimaryLocation\": \"src/db/users.schema.ts\",\n \"children\": [\n {\"field\": {\"name\": \"id\", \"extends\": \"..::common::id\"}},\n {\"field\": {\"name\": \"email\", \"subType\": \"string\",\n \"@dbColumn\": \"email_address\",\n \"children\": [{\"validator\": {\"subType\": \"required\"}}]\n }},\n {\"identity\": {\"name\": \"pk\", \"subType\": \"primary\", \"@fields\": [\"id\"], \"@generation\": \"increment\"}}\n ]\n }\n },\n {\n \"decision\": {\n \"name\": \"useTanstackQuery\",\n \"subType\": \"global\",\n \"@forgeConfidence\": 0.9,\n \"@forgeSource\": \"human\",\n \"@forgeRationale\": \"Real-time invalidation matters for live game state.\",\n \"@forgeAlternatives\": [\"swr\", \"redux-toolkit-query\"]\n }\n }\n ]\n }\n}\n```\n\n## Authoring guidance\n\n| Situation | Action |\n|---|---|\n| Adding a field to an existing entity | Edit the `object`'s `children`; append a `field` node, then `meta gen` |\n| New entity in an existing domain | Append an `object` to the appropriate package file, then `meta gen` |\n| Renaming an entity or field | Edit the metadata, regenerate; TS will surface every stale consumer of the constants |\n| New REST resource | Already done \u2014 `meta gen` produced `<Entity>.routes.ts`. Just `fastify.register(...)` it |\n| Custom business logic (Stripe webhook, side-effects, auth flows) | Hand-write a route/handler that imports the generated constants + `om()` |\n| Architectural choice affecting how entities are built | Add a `decision` with `@forgeRationale` + `@forgeAlternatives` |\n| Coding convention | Add a `convention` with `@forgePatternDescription` + `@forgeAppliesTo` |\n| Domain term | Add a `glossary` entry with `@forgeTerm` + `@forgeDefinition` |\n\n## Deeper references\n\n- `packages/metadata/METAMODEL.md` \u2014 full metamodel reference\n- `packages/sdk/FORGE-METADATA.md` \u2014 full `@forge*` inventory + MetaObjects layout details\n- `docs/strategy/2026-05-12-v0.3-ai-first-metadata-loading.md` \u2014 current strategy (v0.3 vocab, packages, AI-first loading)\n";
1
+ export declare const AGENT_DOCS_BODY = "# Meta Forge \u2014 agent reference\n\nThis file is scaffolded by `meta init` and lives alongside your `metaobjects/` records. It teaches AI coding assistants (Claude Code, Codex, etc.) how to read and modify MetaObjects metadata correctly. Refresh after CLI updates with `meta init --refresh-docs`.\n\n## Five working principles (read first)\n\nThese shape every interaction with a metaobjects-driven project. Follow them when you author metadata, write hand-coded business logic, or review someone else's work.\n\n### 1. If it's pattern-derivable from metadata, generate it. Never hand-write boilerplate.\n\nThe metaobjects raison d'\u00EAtre is that anything the metadata fully describes \u2014 schemas, FK references, basic CRUD, query helpers, Zod validators, route handlers, RHF rules, form fields \u2014 should be produced by codegen, not hand-typed. If you find yourself hand-writing something the metadata already knows about, stop and use the generated artifact.\n\nThe first version of the trainer website's database layer had hand-written Drizzle schemas, Zod schemas, and CRUD endpoints. Every one of those is now generated. The hand-written code that remains is real business logic (Stripe webhooks, Loops integration, custom auth flows) \u2014 things the generator genuinely cannot derive.\n\nWhen you're about to add a new field or entity: edit `metaobjects/*.json` and re-run `meta gen`. Don't reach for the generated file directly.\n\n### 2. Use the generated constants. Never use magic strings that touch metadata.\n\nAfter `meta gen`, each entity file exports a rich metadata-constants block. Each non-dollar-prefixed key is a per-field object that carries everything a consumer might need (name, label, view, html input type, placeholder, RHF validation rules):\n\n```ts\nexport const Subscriber = {\n $entity: \"Subscriber\", // entity name string\n $table: \"subscribers\", // SQL table name\n $path: \"/subscribers\", // REST resource path\n\n email: {\n name: \"email\", // field name string (use for filters, register())\n label: \"Email Address\", // humanized fallback or @label override\n view: \"text\", // MetaView subtype\n htmlType: \"email\", // optional; maps view \u2192 HTML <input type=>\n placeholder: \"you@example.com\", // optional; only when @placeholder is set on the view\n helpText: \"We never share this.\", // optional; only when @helpText is set\n rules: { // optional; derived from validator children\n required: \"Email is required\",\n maxLength: { value: 255, message: \"Too long\" },\n pattern: { value: /.../, message: \"Invalid email\" },\n },\n },\n firstName: { name: \"firstName\", label: \"First Name\", view: \"text\", htmlType: \"text\", rules: { required: \"First Name is required\" } },\n // ...\n} as const;\n```\n\n**Use them everywhere \u2014 in both generated AND hand-written code:**\n\n```tsx\n// \u2717 Don't:\n<input name=\"email\" type=\"email\" placeholder=\"Email\" />\n\n// \u2713 Do:\n<input\n type={Subscriber.email.htmlType}\n name={Subscriber.email.name}\n placeholder={Subscriber.email.placeholder}\n aria-label={Subscriber.email.label}\n/>\n```\n\nRename a field in `metaobjects/` and re-gen \u2014 TypeScript catches every stale reference.\n\n**Special case \u2014 Drizzle column access:** when you're already inside Drizzle's typed builder, just use the column properties directly. Drizzle's table-const types are themselves derived from metadata, so `weeks.programId` is already TS-safe:\n\n```ts\n// \u2713 Use Drizzle's typed accessor directly \u2014 no constants needed here:\ndb.select().from(weeks).where(eq(weeks.programId, X))\n\n// \u2717 Don't do this \u2014 it's redundant indirection:\ndb.select().from(weeks).where(eq(weeks[Week.programId.name], X))\n```\n\nUse the constants when you need a STRING (filter object keys, registration arguments, REST paths, labels). Use Drizzle properties directly when the type system already does the work.\n\n### 3. Forms: spread `form.input.<field>` from useEntityForm. One line per input.\n\nFor React forms, use `useEntityForm` from `@metaobjectsdev/react`. It returns the standard React Hook Form surface plus a pre-bound `.input` accessor \u2014 one entry per field, ready to spread onto an `<input>`:\n\n```tsx\nimport { useEntityForm } from '@metaobjectsdev/react';\nimport { Subscriber, SubscriberInsertSchema } from './generated/Subscriber';\n\nconst form = useEntityForm(Subscriber, SubscriberInsertSchema);\n\n<label>{Subscriber.email.label}</label>\n<input {...form.input.email} /> // \u2190 type, placeholder, name, rules, aria-label all spread automatically\n```\n\nFor non-`<input>` controls (textarea, select), the `type` attr is omitted from `form.input.X` \u2014 pick the right element yourself.\n\nThe same Zod schema (`SubscriberInsertSchema`) validates on the server (in Fastify routes) and on the client (via the resolver). One schema, two surfaces, zero drift.\n\n### 4. Routes: use the generated `<Entity>.routes.ts` for stock CRUD. Hand-write only what's custom.\n\n`meta gen` emits a per-entity routes file that mounts the 5 standard verbs via `mountCrudRoutes` from `@metaobjectsdev/runtime-ts/drizzle-fastify`. The runtime is plain Drizzle + Zod \u2014 no extra ORM.\n\nFor custom flows (Stripe webhooks, side effects, auth-gated actions), hand-write the route \u2014 but import the entity constants + generated Zod schema. The boilerplate (CRUD, validation, 404 mapping, pagination) lives in the helper; your hand-written code is just the business logic.\n\n**Auth pattern:** install a plugin-level Fastify `preHandler` hook at the top of your route plugin. The hook applies to every route registered after it \u2014 both hand-written handlers AND metaobjects-generated routes via the `routeOptions` field. Beats sprinkling `if (!auth(...)) return;` at the top of every handler.\n\n### 5. Hand-coded code is always available, but coexists with generated code.\n\nGenerated code does the boilerplate. Hand-coded code does the business logic. They live in the same project, the same package, sometimes the same file. The hand-coded code consumes the generated constants and generated Zod schemas \u2014 it never duplicates schema, never hard-codes paths, never declares its own validators that metadata could declare.\n\nConcrete pattern from the trainer website:\n- Generated `Subscriber.routes.ts` registers GET / GET-by-id / POST / PATCH / DELETE on `/api/subscribers`.\n- Hand-written `apps/api/src/routes/subscribers.ts` keeps `POST /subscribe` \u2014 the custom endpoint with the Loops side-effect.\n- Both registered with `fastify.register()`. Both validate via `SubscriberInsertSchema`. Both use `Subscriber.email.name` / etc. Neither knows the other exists.\n\n## Metaobjects metamodel \u2014 quick rules\n\nThe format used by `metaobjects/*.json` is **metaobjects metadata**, a cross-language standard. Eight base types:\n\n| Type | Purpose |\n|---|---|\n| `metadata` | Root document wrapper |\n| `object` | An entity (table/record) |\n| `field` | A property on an object |\n| `attr` | Named scalar/array decoration on any parent |\n| `validator` | A validation rule |\n| `view` | A UI control kind |\n| `identity` | A primary/secondary key |\n| `relationship` | An association between objects |\n\n### Two most-violated rules\n\n1. **Attribute uniqueness.** Within a single parent metadata node, all attribute names must be unique. You cannot have two `attr` children both named `alternative`. For multi-value, use a single `stringarray` attr: `\"@alternatives\": [\"a\", \"b\", \"c\"]`.\n\n2. **Inline `@<name>` and `attr` child are the same thing.** `\"@maxLength\": 50` is shorthand for `{\"attr\": {\"name\": \"maxLength\", \"subType\": \"int\", \"value\": \"50\"}}`. The parser converts inline form into attr children. Don't use both forms for the same attribute name on the same parent.\n\n### Object subtypes (v0.3)\n\n- `base` \u2014 abstract template (no runtime semantics)\n- `entity` \u2014 persistent record; should have a primary identity\n- `value` \u2014 value-object; equality by content; must NOT have a primary identity\n\nJava-runtime strategies (pojo / map / proxy) belong on `@javaRuntime`, not in `subType`.\n\n### Reserved structural keys (NOT attributes)\n\n`name`, `subType`, `package`, `extends`, `isAbstract`, `children`, `merge`, `value`.\n\nThe v0.2 keys (`super`, `overlay`, `override`, `isInterface`, `implements`) are **gone**. The current parser will reject them. Use:\n- `extends:` instead of `super:` for the supertype reference\n- `merge: true` instead of `overlay: true` / `override: true` for in-place modification\n- `@isAbstract: true` instead of `isInterface: true` (multiple inheritance is not supported)\n\n### Package paths and inheritance\n\n- Package segments separated by `::` \u2014 `acme::common::id`\n- Relative references in `extends:` \u2014 `..::common::id` means \"go up to parent package, descend into `common::id`\"\n- Cross-file resolution works as long as all files are passed to Loader (or live in the same `metaobjects/` directory)\n\n### Two special intercepted attrs (parser-routed)\n\n- `@isArray` \u2192 marks a field as a collection\n- `@isAbstract` \u2192 marks a node as abstract (inheritable but not instantiable)\n\n## Validators \u2014 two layers\n\nValidators can attach in two places, and they compose:\n\n**Field-level validators** describe what makes the *stored value* valid. They survive across UI, API, batch import, manual SQL \u2014 anywhere data enters the system. The generated Zod `<Entity>InsertSchema` encodes these.\n\n```json\n{\"field\": {\"name\": \"email\", \"subType\": \"string\",\n \"children\": [\n {\"validator\": {\"subType\": \"required\"}},\n {\"validator\": {\"subType\": \"regex\", \"@pattern\": \"^[^@]+@[^@]+\\\\.[^@]+$\"}}\n ]\n}}\n```\n\n**View-level validators** describe what makes user *input* valid in a specific UI surface \u2014 possibly stricter, possibly with different messages, possibly format-specific. They run client-side in generated forms. They do NOT necessarily reject the stored value if it's already in the DB.\n\n```json\n{\"field\": {\"name\": \"phone\", \"subType\": \"string\",\n \"children\": [\n {\"validator\": {\"subType\": \"regex\", \"@pattern\": \"^\\\\+?[0-9]+$\"}},\n {\"view\": {\"subType\": \"text-input\", \"@label\": \"Phone\",\n \"children\": [\n {\"validator\": {\"subType\": \"length\", \"@min\": 7, \"@max\": 20,\n \"@message\": \"Phone must be 7-20 digits\"}}\n ]\n }}\n ]\n}}\n```\n\nRule of thumb: rules that protect data integrity \u2192 field. Rules that improve input UX \u2192 view.\n\n## metaobjects.config.ts \u2014 generator wiring (project root)\n\n`meta gen` reads `metaobjects.config.ts` at the project root. This is where you declare which generators run and their options. It is TypeScript, type-checked, and imported via `jiti` at run time.\n\n```ts\nimport { defineConfig } from \"@metaobjectsdev/cli\";\nimport {\n entityFile, queriesFile, routesFile, /* formFile, */ barrel,\n} from \"@metaobjectsdev/codegen-ts/generators\";\n\nexport default defineConfig({\n outDir: \"packages/database/src/generated\",\n extStyle: \"none\",\n dbImport: \"../index\",\n dialect: \"sqlite\",\n generators: [\n entityFile(),\n queriesFile(),\n routesFile(),\n // formFile(), // opt-in: emits stock React forms per entity\n barrel(),\n ],\n});\n```\n\n3rd-party generator example: `import { tanstackQuery } from \"@metaobjectsdev/codegen-ts-tanstack\"; // then add tanstackQuery({ ... }) to the generators array`\n\nFilters live on the generator entry: `routesFile({ filter: e => e.name !== \"AuditLog\" })`\n\n`.metaobjects/config.json` is unchanged \u2014 it still holds static project state (schema_version, pending_in_git, confidence_thresholds). Generator wiring belongs in `metaobjects.config.ts` so TypeScript can type-check the imports.\n\n## Generated hooks + grids (TanStack)\n\nWhen `tanstackQuery()` is in your `metaobjects.config.ts`, every entity gets `<Entity>.hooks.ts` with a query-key factory + `useEntity`, `useEntities`, `useCreate`, `useUpdate`, `useDelete` hooks. When `tanstackGrid()` is in the config, entities with a `layout[dataGrid]` child also get `<Entity>.columns.tsx`.\n\n```tsx\nimport { usePrograms, useCreateProgram } from \"@your-pkg/database/generated/Program.hooks\";\nimport { programDefaultColumns, programDefaultGrid } from \"@your-pkg/database/generated/Program.columns\";\nimport { EntityGrid } from \"@metaobjectsdev/tanstack\";\n\nconst { data, isLoading } = usePrograms();\nconst create = useCreateProgram({ onSuccess: () => navigate(\"/programs\") });\n\n<EntityGrid\n columns={programDefaultColumns}\n grid={programDefaultGrid}\n data={data ?? []}\n isLoading={isLoading}\n onRowClick={(row) => navigate(`/admin/programs/${row.id}`)}\n/>\n```\n\n**Provider setup.** Wrap your app with `<EntityFetcherProvider value={fetcher}>` (supplies the HTTP fetcher to all generated hooks). For an admin subtree with different auth, wrap a second time inside: `<EntityFetcherProvider value={adminFetch}>...</EntityFetcherProvider>` overrides the outer one.\n\n**Metadata layer \u2014 grid definition:**\n\n```jsonc\n{ \"layout\": {\n \"subType\": \"dataGrid\",\n \"name\": \"default\",\n \"@pageSize\": 25,\n \"@defaultSortField\": \"createdAt\",\n \"@defaultSortOrder\": \"desc\",\n \"@filterable\": true,\n \"@columns\": [\"email\", \"firstName\", \"subscribed\", \"createdAt\"]\n}}\n```\n\nThe `@columns` attr is a flat string array listing fields to display. Per-column rendering comes from each field's own `view` subtype (the same one that drives forms); sortability comes from the field's `@sortable` attr; width belongs in app CSS. There are no nested per-column children \u2014 just `@columns`.\n\n**Cell renderers.** Field rendering inside grids comes from each field's own `view` subtype (the same one that drives forms). Override defaults app-wide with `<CellRendererProvider value={{ currency: ({ getValue }) => <Money value={getValue()} /> }}>`.\n\n**Per-entity opt-out.** `@emitTanstack: false` on an entity skips both hooks and columns.\n\n## Filtering generated lists\n\nMark filterable fields in metadata with `@filterable: true`:\n\n```jsonc\n{ \"field\": { \"name\": \"email\", \"subType\": \"string\", \"@filterable\": true } }\n```\n\nThe generated `useSubscribers(filter)` hook accepts a typed filter:\n\n```tsx\nconst { data } = useSubscribers({\n email: { like: \"%@example.com\" },\n subscribed: true,\n sort: \"createdAt:desc\",\n limit: 25,\n});\n```\n\nURL sent: `/subscribers?filter[email][like]=%25@example.com&filter[subscribed]=true&sort=createdAt:desc&limit=25`\n\n**Operators by field subtype:**\n- String: `eq, ne, in, like, isNull`\n- Number/date: `eq, ne, gt, gte, lt, lte, in, isNull`\n- Boolean: `eq, isNull`\n\nIllegal combinations like `useSubscribers({ subscribed: { gte: true } })` fail to compile (booleans don't support `gte`).\n\n**Per-grid preset filter** via layout `@filter`:\n\n```jsonc\n{ \"layout\": { \"subType\": \"dataGrid\", \"name\": \"active\",\n \"@filter\": { \"subscribed\": true },\n \"@columns\": [\"email\", \"firstName\", \"subscribed\"] }}\n```\n\nGenerates `subscriberActiveFilter` const consumable in pages. Compose with ad-hoc filters via object spread.\n\n## Projections (read models with joined/aggregated columns)\n\nWhen a list needs computed columns (counts, sums, joined fields), create a **projection** \u2014 an entity that extends a base entity but reads from a SQL view:\n\n```json\n// metaobjects/meta.commerce.json (inline with Program)\n{\n \"object\": {\n \"name\": \"ProgramSummary\",\n \"subType\": \"entity\",\n \"extends\": \"Program\",\n \"children\": [\n { \"source\": { \"subType\": \"rdb\", \"@kind\": \"view\", \"@table\": \"v_program_summary\" } },\n { \"field\": { \"name\": \"weekCount\", \"subType\": \"int\", \"children\": [\n { \"origin\": { \"subType\": \"aggregate\",\n \"@agg\": \"count\", \"@of\": \"Week.id\", \"@via\": \"Program.weeks\" }}\n ]}},\n { \"identity\": { \"subType\": \"primary\", \"@fields\": \"id\" } }\n ]\n }\n}\n```\n\n`meta gen` produces a read-only `useProgramSummaries(filter)` hook, a SQL view DDL in the migration, and a read-only GET-only route.\n\n**Aggregate vocabulary**: `count`, `sum`, `avg`, `min`, `max`.\n\n**Multi-level via paths** are supported: `@via: \"Program.weeks.workouts\"` builds a 2-level JOIN tree.\n\n**For pages that need a full nested tree** (e.g., Program \u2192 Weeks \u2192 Workouts \u2192 Exercises), use 4 entity hooks with Project D's filter syntax for batched lookups (no projection needed \u2014 flat hooks + client-side stitching is enough):\n\n```tsx\nconst { data: weeks } = useWeeks({ programId, sort: \"weekNumber:asc\" });\nconst weekIds = weeks?.map((w) => w.id) ?? [];\nconst { data: workouts } = useWorkouts(\n weekIds.length ? { weekId: { in: weekIds } } : undefined,\n);\n```\n\n## Currency fields\n\nDeclare a money field with `subType: \"currency\"`:\n\n```json\n{ \"field\": { \"name\": \"priceCents\", \"subType\": \"currency\", \"@currency\": \"USD\" } }\n```\n\nStorage stays as integer minor units (cents for USD). The generated `<Entity>` constants block carries `view`, `currency`, `locale` so admin grids auto-format prices.\n\n**Imports \u2014 use sub-paths in browser code:**\n\n```tsx\nimport { formatCurrency } from \"@metaobjectsdev/runtime-web\";\nimport { CurrencyInput } from \"@metaobjectsdev/react\";\n```\n\n**Display:**\n\n```tsx\n<span>{formatCurrency(program.priceCents)}</span> // $15.00\n<span>{formatCurrency(p.amountCents, \"EUR\", \"de-DE\")}</span> // 15,00 \u20AC\n```\n\n**Form input:**\n\n```tsx\n<CurrencyInput value={priceCents} onChange={setPriceCents} currency=\"USD\" />\n```\n\nUser types `15.99` \u2192 component emits `1599` to `onChange` on blur. Wire format is always integer cents.\n\n**Locale override** via a `view[currency]` child:\n\n```json\n{ \"field\": { \"name\": \"priceCents\", \"subType\": \"currency\", \"@currency\": \"EUR\",\n \"children\": [{ \"view\": { \"subType\": \"currency\", \"@locale\": \"de-DE\" } }]\n}}\n```\n\nCurrency code lives on the field; locale lives on the view.\n\n## Generated artifacts \u2014 what `meta gen` produces\n\nAfter `meta gen`, you get one barrel + per-entity files in your configured `outDir` (default `packages/database/src/generated/`):\n\n| File | What's in it | When to touch by hand |\n|---|---|---|\n| `<Entity>.ts` | Drizzle table, relations(), inferred types, Zod insert/update schemas, and the rich `<Entity>` constants block (per-field objects with name, label, view, htmlType, rules, etc.) | Never. Regenerate. |\n| `<Entity>.queries.ts` | Typed query helpers (`findUserById`, `listUsers`, `createUser`, ...) using prepared statements | Never. Regenerate. |\n| `<Entity>.routes.ts` | Fastify CRUD plugin delegating to `mountCrudRoutes` from `@metaobjectsdev/runtime-ts/drizzle-fastify` (5 verbs, Zod validation, 404/204 mapping, Drizzle-direct under the hood) | Never. Regenerate. |\n| `<Entity>.form.tsx` | React form using `useEntityForm` + the entity constants. **OPT-IN at project level:** add `formFile()` to `generators` in `metaobjects.config.ts`. Opt out per-entity via `@emitForm: false`. | Never. Regenerate. |\n| `index.ts` | Barrel re-exporting every entity file | Never. Regenerate. |\n\nFor business logic the generator doesn't cover, create a SIBLING file: `<Entity>.extra.ts` for query/route helpers, or any file you like in your apps directory. Import the constants from the generated `<Entity>.ts`.\n\n### Stock route mounting\n\n```ts\nimport { subscriberRoutes } from \"@your-pkg/database/generated/Subscriber.routes\";\nfastify.register(subscriberRoutes, { prefix: \"/api\" });\n```\n\nThat mounts: `GET /api/subscribers`, `GET /api/subscribers/:id`, `POST /api/subscribers`, `PATCH /api/subscribers/:id`, `DELETE /api/subscribers/:id`. Pagination via `?limit=` & `?offset=`. Validation via the generated Zod schemas. Drizzle calls under the hood.\n\n### Mixing custom routes alongside generated\n\n```ts\nimport { db, subscribers } from \"@your-pkg/database\";\nimport { Subscriber, SubscriberInsertSchema } from \"@your-pkg/database/generated/Subscriber\";\nimport { eq } from \"drizzle-orm\";\n\nfastify.post(\"/subscribe\", async (req, reply) => {\n // Generated Zod schema validates the body \u2014 same schema the API route uses.\n const parsed = SubscriberInsertSchema.safeParse(req.body);\n if (!parsed.success) return reply.code(400).send({ issues: parsed.error.issues });\n\n // Drizzle's typed accessors are already TS-safe; no need for indirection.\n const existing = await db.select().from(subscribers).where(eq(subscribers.email, parsed.data.email)).get();\n if (existing) return reply.code(409).send({ error: \"Already subscribed\" });\n\n const [row] = await db.insert(subscribers).values(parsed.data).returning();\n // ... your business logic (analytics, Loops/Mailchimp, navigation, etc.)\n return reply.code(201).send(row);\n});\n```\n\nThe fact that every metadata-derived value flows from `Subscriber` / `SubscriberInsertSchema` / the typed `subscribers` table is what makes rename-the-field-in-metadata-and-regen safe.\n\n### Hand-written form using `useEntityForm`\n\n```tsx\nimport { useEntityForm } from '@metaobjectsdev/react';\nimport { Subscriber, SubscriberInsertSchema, type Subscriber as Row } from './generated/Subscriber';\n\nexport function SubscribeForm() {\n const form = useEntityForm(Subscriber, SubscriberInsertSchema);\n const { handleSubmit, formState: { errors } } = form;\n\n return (\n <form onSubmit={handleSubmit(/* your onSubmit */)} className=\"your-design-system\">\n <label>{Subscriber.email.label}</label>\n <input {...form.input.email} />\n {errors.email && <span>{errors.email.message}</span>}\n\n <label>{Subscriber.firstName.label}</label>\n <input {...form.input.firstName} />\n {errors.firstName && <span>{errors.firstName.message}</span>}\n\n <button type=\"submit\">Subscribe</button>\n </form>\n );\n}\n```\n\nSpread `form.input.<field>` \u2014 it carries name, type, placeholder, rules, aria-label automatically. No magic strings.\n\n## Meta Forge additions\n\n### `@forge*` attribute namespace\n\nProvenance and confidence concerns expressed as inline attributes on any metadata child. Names use camelCase (no separator).\n\nMost common:\n- `@forgeConfidence` (double 0..1) \u2014 confidence the record is correct\n- `@forgeSource` (string) \u2014 `human` | `claude` | `ts-ast` | `drizzle` | ...\n- `@forgePrimaryLocation` (string) \u2014 file path for an entity\n- `@forgeRationale` (string, decision only) \u2014 why this decision\n- `@forgeAlternatives` (stringarray, decision only) \u2014 alternatives considered\n\nFull inventory in `packages/sdk/FORGE-METADATA.md`.\n\n### New top-level types\n\nRegistered by `@metaobjectsdev/sdk` into the TypeRegistry:\n\n| Type | Purpose |\n|---|---|\n| `decision` | Architectural or design decision |\n| `principle` | Design principle (advisory/enforced) |\n| `convention` | Coding/structural convention |\n| `glossary` | Domain-term definition |\n| `failure` | Recorded failure mode |\n\nThese coexist with `object` children in the same package files. `meta gen` and `meta migrate` only consume `object`; the descriptive types are context for AI tooling and don't drive codegen.\n\n## File layout\n\n```\nmetaobjects/\n\u251C\u2500\u2500 meta.common.json shared base fields/validators (optional)\n\u251C\u2500\u2500 meta.<domain>.json your entity packages(s)\n\u2514\u2500\u2500 _pending/<pkg>.json proposed packages awaiting review\n\n.metaobjects/\n\u251C\u2500\u2500 config.json static project state\n\u251C\u2500\u2500 migrations/ written by meta migrate\n\u2514\u2500\u2500 .gen-state/ codegen merge base (gitignored)\n\nmetaobjects.config.ts generator wiring (committed)\n```\n\n## Worked example\n\n```json\n{\n \"metadata\": {\n \"package\": \"myapp\",\n \"children\": [\n {\n \"object\": {\n \"name\": \"User\",\n \"subType\": \"entity\",\n \"@forgeConfidence\": 0.95,\n \"@forgeSource\": \"human\",\n \"@forgePrimaryLocation\": \"src/db/users.schema.ts\",\n \"children\": [\n {\"field\": {\"name\": \"id\", \"extends\": \"..::common::id\"}},\n {\"field\": {\"name\": \"email\", \"subType\": \"string\",\n \"@column\": \"email_address\",\n \"children\": [{\"validator\": {\"subType\": \"required\"}}]\n }},\n {\"identity\": {\"name\": \"pk\", \"subType\": \"primary\", \"@fields\": [\"id\"], \"@generation\": \"increment\"}}\n ]\n }\n },\n {\n \"decision\": {\n \"name\": \"useTanstackQuery\",\n \"subType\": \"global\",\n \"@forgeConfidence\": 0.9,\n \"@forgeSource\": \"human\",\n \"@forgeRationale\": \"Real-time invalidation matters for live game state.\",\n \"@forgeAlternatives\": [\"swr\", \"redux-toolkit-query\"]\n }\n }\n ]\n }\n}\n```\n\n## Authoring guidance\n\n| Situation | Action |\n|---|---|\n| Adding a field to an existing entity | Edit the `object`'s `children`; append a `field` node, then `meta gen` |\n| New entity in an existing domain | Append an `object` to the appropriate package file, then `meta gen` |\n| Renaming an entity or field | Edit the metadata, regenerate; TS will surface every stale consumer of the constants |\n| New REST resource | Already done \u2014 `meta gen` produced `<Entity>.routes.ts`. Just `fastify.register(...)` it |\n| Custom business logic (Stripe webhook, side-effects, auth flows) | Hand-write a route/handler that imports the generated constants + `om()` |\n| Architectural choice affecting how entities are built | Add a `decision` with `@forgeRationale` + `@forgeAlternatives` |\n| Coding convention | Add a `convention` with `@forgePatternDescription` + `@forgeAppliesTo` |\n| Domain term | Add a `glossary` entry with `@forgeTerm` + `@forgeDefinition` |\n\n## Deeper references\n\n- `packages/metadata/METAMODEL.md` \u2014 full metamodel reference\n- `packages/sdk/FORGE-METADATA.md` \u2014 full `@forge*` inventory + MetaObjects layout details\n- `docs/strategy/2026-05-12-v0.3-ai-first-metadata-loading.md` \u2014 current strategy (v0.3 vocab, packages, AI-first loading)\n";
2
2
  //# sourceMappingURL=body.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"body.d.ts","sourceRoot":"","sources":["../../src/agent-docs/body.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,eAAe,qr0BAgjB3B,CAAC"}
1
+ {"version":3,"file":"body.d.ts","sourceRoot":"","sources":["../../src/agent-docs/body.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,eAAe,ss0BAgjB3B,CAAC"}
@@ -313,7 +313,7 @@ When a list needs computed columns (counts, sums, joined fields), create a **pro
313
313
  "subType": "entity",
314
314
  "extends": "Program",
315
315
  "children": [
316
- { "source": { "subType": "dbView", "@name": "v_program_summary" } },
316
+ { "source": { "subType": "rdb", "@kind": "view", "@table": "v_program_summary" } },
317
317
  { "field": { "name": "weekCount", "subType": "int", "children": [
318
318
  { "origin": { "subType": "aggregate",
319
319
  "@agg": "count", "@of": "Week.id", "@via": "Program.weeks" }}
@@ -519,7 +519,7 @@ metaobjects.config.ts generator wiring (committed)
519
519
  "children": [
520
520
  {"field": {"name": "id", "extends": "..::common::id"}},
521
521
  {"field": {"name": "email", "subType": "string",
522
- "@dbColumn": "email_address",
522
+ "@column": "email_address",
523
523
  "children": [{"validator": {"subType": "required"}}]
524
524
  }},
525
525
  {"identity": {"name": "pk", "subType": "primary", "@fields": ["id"], "@generation": "increment"}}
package/dist/config.d.ts CHANGED
@@ -41,19 +41,47 @@ export declare const ConfigSchema: z.ZodObject<{
41
41
  migrate: z.ZodOptional<z.ZodObject<{
42
42
  outDir: z.ZodOptional<z.ZodString>;
43
43
  databaseUrl: z.ZodOptional<z.ZodString>;
44
- dialect: z.ZodOptional<z.ZodEnum<["sqlite", "postgres"]>>;
44
+ dialect: z.ZodOptional<z.ZodEnum<["sqlite", "postgres", "d1"]>>;
45
45
  onAmbiguous: z.ZodOptional<z.ZodEnum<["abort", "rename", "drop-add"]>>;
46
46
  allow: z.ZodOptional<z.ZodArray<z.ZodEnum<["drop-column", "drop-table", "type-change", "drop-index", "drop-fk", "nullable-to-not-null"]>, "many">>;
47
+ d1: z.ZodOptional<z.ZodObject<{
48
+ binding: z.ZodOptional<z.ZodString>;
49
+ remote: z.ZodOptional<z.ZodBoolean>;
50
+ autoApply: z.ZodOptional<z.ZodBoolean>;
51
+ wranglerConfigPath: z.ZodOptional<z.ZodString>;
52
+ }, "strip", z.ZodTypeAny, {
53
+ binding?: string | undefined;
54
+ remote?: boolean | undefined;
55
+ autoApply?: boolean | undefined;
56
+ wranglerConfigPath?: string | undefined;
57
+ }, {
58
+ binding?: string | undefined;
59
+ remote?: boolean | undefined;
60
+ autoApply?: boolean | undefined;
61
+ wranglerConfigPath?: string | undefined;
62
+ }>>;
47
63
  }, "strip", z.ZodTypeAny, {
64
+ d1?: {
65
+ binding?: string | undefined;
66
+ remote?: boolean | undefined;
67
+ autoApply?: boolean | undefined;
68
+ wranglerConfigPath?: string | undefined;
69
+ } | undefined;
48
70
  outDir?: string | undefined;
49
71
  databaseUrl?: string | undefined;
50
- dialect?: "sqlite" | "postgres" | undefined;
72
+ dialect?: "sqlite" | "postgres" | "d1" | undefined;
51
73
  onAmbiguous?: "abort" | "rename" | "drop-add" | undefined;
52
74
  allow?: ("drop-column" | "drop-table" | "type-change" | "drop-index" | "drop-fk" | "nullable-to-not-null")[] | undefined;
53
75
  }, {
76
+ d1?: {
77
+ binding?: string | undefined;
78
+ remote?: boolean | undefined;
79
+ autoApply?: boolean | undefined;
80
+ wranglerConfigPath?: string | undefined;
81
+ } | undefined;
54
82
  outDir?: string | undefined;
55
83
  databaseUrl?: string | undefined;
56
- dialect?: "sqlite" | "postgres" | undefined;
84
+ dialect?: "sqlite" | "postgres" | "d1" | undefined;
57
85
  onAmbiguous?: "abort" | "rename" | "drop-add" | undefined;
58
86
  allow?: ("drop-column" | "drop-table" | "type-change" | "drop-index" | "drop-fk" | "nullable-to-not-null")[] | undefined;
59
87
  }>>;
@@ -75,9 +103,15 @@ export declare const ConfigSchema: z.ZodObject<{
75
103
  metaignore?: string | undefined;
76
104
  };
77
105
  migrate?: {
106
+ d1?: {
107
+ binding?: string | undefined;
108
+ remote?: boolean | undefined;
109
+ autoApply?: boolean | undefined;
110
+ wranglerConfigPath?: string | undefined;
111
+ } | undefined;
78
112
  outDir?: string | undefined;
79
113
  databaseUrl?: string | undefined;
80
- dialect?: "sqlite" | "postgres" | undefined;
114
+ dialect?: "sqlite" | "postgres" | "d1" | undefined;
81
115
  onAmbiguous?: "abort" | "rename" | "drop-add" | undefined;
82
116
  allow?: ("drop-column" | "drop-table" | "type-change" | "drop-index" | "drop-fk" | "nullable-to-not-null")[] | undefined;
83
117
  } | undefined;
@@ -99,9 +133,15 @@ export declare const ConfigSchema: z.ZodObject<{
99
133
  metaignore?: string | undefined;
100
134
  } | undefined;
101
135
  migrate?: {
136
+ d1?: {
137
+ binding?: string | undefined;
138
+ remote?: boolean | undefined;
139
+ autoApply?: boolean | undefined;
140
+ wranglerConfigPath?: string | undefined;
141
+ } | undefined;
102
142
  outDir?: string | undefined;
103
143
  databaseUrl?: string | undefined;
104
- dialect?: "sqlite" | "postgres" | undefined;
144
+ dialect?: "sqlite" | "postgres" | "d1" | undefined;
105
145
  onAmbiguous?: "abort" | "rename" | "drop-add" | undefined;
106
146
  allow?: ("drop-column" | "drop-table" | "type-change" | "drop-index" | "drop-fk" | "nullable-to-not-null")[] | undefined;
107
147
  } | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/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
  import { z } from "zod";
2
2
  import { readFile, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
- const DialectEnum = z.enum(["sqlite", "postgres"]);
4
+ const DialectEnum = z.enum(["sqlite", "postgres", "d1"]);
5
5
  const OnAmbiguousEnum = z.enum(["abort", "rename", "drop-add"]);
6
6
  const AllowTokenEnum = z.enum([
7
7
  "drop-column",
@@ -11,12 +11,19 @@ const AllowTokenEnum = z.enum([
11
11
  "drop-fk",
12
12
  "nullable-to-not-null",
13
13
  ]);
14
+ const D1Block = z.object({
15
+ binding: z.string(),
16
+ remote: z.boolean(),
17
+ autoApply: z.boolean(),
18
+ wranglerConfigPath: z.string(),
19
+ }).partial();
14
20
  const MigrateBlock = z.object({
15
21
  outDir: z.string(),
16
22
  databaseUrl: z.string(),
17
23
  dialect: DialectEnum,
18
24
  onAmbiguous: OnAmbiguousEnum,
19
25
  allow: z.array(AllowTokenEnum),
26
+ d1: D1Block,
20
27
  }).partial();
21
28
  export const ConfigSchema = z.object({
22
29
  schema_version: z.literal(1),
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC;AAEnD,MAAM,eAAe,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC;AAEhE,MAAM,cAAc,GAAG,CAAC,CAAC,IAAI,CAAC;IAC5B,aAAa;IACb,YAAY;IACZ,aAAa;IACb,YAAY;IACZ,SAAS;IACT,sBAAsB;CACvB,CAAC,CAAC;AAEH,MAAM,YAA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AC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,EACtC,MAAM,CACP,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metaobjectsdev/sdk",
3
- "version": "0.5.0-rc.3",
3
+ "version": "0.6.0-rc.1",
4
4
  "description": "Workspace helpers and agent-docs utilities for MetaObjects projects.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -38,7 +38,7 @@
38
38
  "access": "public"
39
39
  },
40
40
  "dependencies": {
41
- "@metaobjectsdev/metadata": "0.5.0-rc.3",
41
+ "@metaobjectsdev/metadata": "0.6.0-rc.1",
42
42
  "zod": "^3.23.0"
43
43
  },
44
44
  "devDependencies": {
@@ -313,7 +313,7 @@ When a list needs computed columns (counts, sums, joined fields), create a **pro
313
313
  "subType": "entity",
314
314
  "extends": "Program",
315
315
  "children": [
316
- { "source": { "subType": "dbView", "@name": "v_program_summary" } },
316
+ { "source": { "subType": "rdb", "@kind": "view", "@table": "v_program_summary" } },
317
317
  { "field": { "name": "weekCount", "subType": "int", "children": [
318
318
  { "origin": { "subType": "aggregate",
319
319
  "@agg": "count", "@of": "Week.id", "@via": "Program.weeks" }}
@@ -519,7 +519,7 @@ metaobjects.config.ts generator wiring (committed)
519
519
  "children": [
520
520
  {"field": {"name": "id", "extends": "..::common::id"}},
521
521
  {"field": {"name": "email", "subType": "string",
522
- "@dbColumn": "email_address",
522
+ "@column": "email_address",
523
523
  "children": [{"validator": {"subType": "required"}}]
524
524
  }},
525
525
  {"identity": {"name": "pk", "subType": "primary", "@fields": ["id"], "@generation": "increment"}}
package/src/config.ts CHANGED
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { readFile, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
 
5
- const DialectEnum = z.enum(["sqlite", "postgres"]);
5
+ const DialectEnum = z.enum(["sqlite", "postgres", "d1"]);
6
6
 
7
7
  const OnAmbiguousEnum = z.enum(["abort", "rename", "drop-add"]);
8
8
 
@@ -15,12 +15,20 @@ const AllowTokenEnum = z.enum([
15
15
  "nullable-to-not-null",
16
16
  ]);
17
17
 
18
+ const D1Block = z.object({
19
+ binding: z.string(),
20
+ remote: z.boolean(),
21
+ autoApply: z.boolean(),
22
+ wranglerConfigPath: z.string(),
23
+ }).partial();
24
+
18
25
  const MigrateBlock = z.object({
19
26
  outDir: z.string(),
20
27
  databaseUrl: z.string(),
21
28
  dialect: DialectEnum,
22
29
  onAmbiguous: OnAmbiguousEnum,
23
30
  allow: z.array(AllowTokenEnum),
31
+ d1: D1Block,
24
32
  }).partial();
25
33
 
26
34
  export const ConfigSchema = z.object({