Skip to content

Latest commit

 

History

History
167 lines (140 loc) · 11.5 KB

how-metaobjects-is-used.md

File metadata and controls

167 lines (140 loc) · 11.5 KB

How MetaObjects is used here

A guided tour of the metadata spine for a curious engineer. architecture.md is the app doc; this is the MetaObjects doc. Everything below is grounded in real files.

The one idea

Typed metadata under metaobjects/ is the durable spine. Every generated file under src/**/generated/ is disposable output — regenerated by npm run gen:db (meta gen) and diffed by npm run demo:drift (meta verify). You never hand-edit generated code; you change the metadata and regenerate.

Two object kinds matter (ADR-0028):

  • object.entity — owns data: has identity + a source.rdb, so it becomes a DB table. Only Council and CouncilTurn are entities here.
  • object.value — a pure shape with no identity and no source: an interface + Zod schema, never a table. Everything else (WizardOutput, TurnLens, the prompt payloads, …) is a value object — the in-memory shapes for prompts, LLM I/O, and projections. storage: jsonb is a column attribute, so it's meaningful on an entity field and inert on a value object.

One field, followed to every surface

Take WizardOutput (the structured thing each wizard emits) declared in metaobjects/meta-wizard-output.yaml. Its stance field extends the shared abstract enum wizardStance (abstracts/meta-stance-enums.yaml) — declared once, reused by WizardOutput, TurnLens, and CouncilTurn. From that one spine:

  • 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.
  • structuredCompletion (a custom generator) reads the template.toolcall that names WizardOutput as its payloadRef and emits callEmitWizardTake in src/llm/generated/toolcalls.ts — a wrapper whose runtime tool schema is the Zod WizardOutputInsertSchema.
  • sseFrames (custom) emits the wizard arm of the CouncilFrame union in src/web/generated/council-frames.ts, carrying a WizardOutput. The orchestrator yields these frames, the Worker encodes them with encodeCouncilFrame, and the client narrows them with toCouncilFrame.
  • lineageMappers (custom) emits the copies between WizardOutput and the objects whose fields extends it: CouncilTurn.lineage.ts (persist a take, rehydrate it) and TurnLens.lineage.ts (project a prior take into the next prompt). A field added to all three can no longer be dropped by a hand-written copy. The same generator builds the public SharedCouncil view that GET /c/:slug.json serves: its declared fields are the exposure, so visitorId stays private and a new Council column stays hidden until someone adds it to SharedCouncil on purpose. That spec sets nullForAbsent, so every declared key is always served and a NULL column arrives as null. The turns in that response go through SharedTurn the same way, so councilId, ordinal and the deprecated round column stay private. Council.lineage.ts stores a VerdictOutput on the council's verdict columns (each extends the VerdictOutput field it holds) and reads it back, as null until the council completes.

Rename a field on WizardOutput, or on the WizardUserPayload that the prompts bind, and the drift gate fails across all of it at once — the money shot in the README.

The prompt pillar, end to end

  1. Payload — a object.value payload (e.g. WizardUserPayload) declares exactly what a prompt may reference. Payload bloat becomes a reviewable diff.
  2. Declaration — a template.prompt (metaobjects/prompts/) binds a payload to external text via textRef; the text lives in data/templates/ Mustache, outside metaobjects/ (so loadMemory() doesn't try to parse it as metadata).
  3. Render — promptRender generates a typed render<Name> handle. mustacheTemplates (custom) inlines the .mustache files into src/render/generated/templates.ts so the Worker — which has no filesystem — can resolve them via an InMemoryProvider.
  4. Compose — src/council/prompts.ts is the seam where the generated handles meet hand-written composition. A byte-equivalence snapshot test pins the rendered output.
  5. Tool call — template.toolcall + structuredCompletion generate callEmitWizardTake / callEmitVerdict: try → retry-with-stricter-reminder → optional typed fallback.
  6. Persist / display — the lineage mappers copy the take onto its D1 columns and back; the SSR share page (src/render/share-page.tsx) loads the council with the generated findCouncilWithTurns (from Council's turns composition).

meta verify --templates checks that every {{var}} in a template is on its declared payload — so a renamed payload field can't silently degrade a prompt.

Extending the metamodel (it's a standard, not a framework)

src/codegen/wizardsofodd-provider.ts registers this project's own vocabulary, strict-provenance-clean (ADR-0023):

  • template.streamFrame — a brand-new project-local subtype (MetaObjects core has no SSE concept). It pairs an @eventName with a @payloadRef; sseFrames walks these nodes.
  • @retryReminder on core template.toolcall — a vendor attr added to a core subtype via registry.extend. The structured fallback payload rides the registered attr.properties bag (an undeclared @fallback would fail load under strict provenance — ERR_UNKNOWN_ATTR).

The custom generators (sseFrames, structuredCompletion, wizardRegistry, lineageMappers, plus mustacheTemplates + wizardData) implement the same Generator interface as the built-ins, each writing under a target outDir so the drift gate covers their output.

The drift gate

  • npm run gen:db (meta gen) regenerates everything to the committed locations.
  • npm run demo:drift (meta verify --templates --codegen --prompts data/templates) checks template drift ({{var}} ↔ payload) and codegen drift (regenerate to a temp dir, diff the committed output).
  • CI (.github/workflows/meta-verify.yml) runs that exact command on every PR — CI and local are byte-identical.

Friction log — what didn't work, honestly

Reference projects that admit friction are believed. Real things this project hit:

  • The drift gate had a blind spot. Four generated files were written outside the drift-checked directories via ../../ path escapes, so a breaking wire-format change (@eventName: wizard → wizardTake) passed demo:drift clean. Fixed by declaring per-target output dirs and putting every generator on a target — now the diff walks the whole surface.
  • The official meta-verify-action only runs --templates. It has no --codegen input, so it would miss codegen drift. CI runs npm run demo:drift directly instead, so the gate is complete.
  • Abstract-attr hoisting doesn't work for every subtype. field.enum shares its values via an abstract + extends (see the stance enums), but template.prompt requires @textRef as an own attr — the loader's required-attr check is own-only — so an abstract template.prompt that omits textRef fails to load. The prompt declarations were consolidated into two files but keep their per-node payloadRef/format.
  • Lineage through a concrete enum loses the shared enum module. CouncilTurn.stance could say extends: WizardOutput.stance, but an enum that extends a concrete field gets its own inlined enum instead of the shared enums.ts one. So enum fields keep extending the abstract (wizardStance), and lineageMappers also pairs same-named fields that share an abstract.
  • Lineage carries validators, and validators carry DB constraints. Linking Council's verdict columns to VerdictOutput with extends pulls in confidence's 0–1 validator, which meta verify --db reads as a new CHECK constraint on councils.verdict_confidence. That kept the columns hand-mapped until migration 0007 (written by meta migrate --dialect d1) rebuilt councils with the CHECK; they are now linked and mapped by the generated Council.lineage.ts.
  • 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). 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 <Entity>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