diff --git a/.claude/skills/releasing/SKILL.md b/.claude/skills/releasing/SKILL.md index ac13e8b153..826e14a148 100644 --- a/.claude/skills/releasing/SKILL.md +++ b/.claude/skills/releasing/SKILL.md @@ -82,7 +82,7 @@ the adopter's only signal. Bump with `node scripts/check-metamodel-version.mjs - ## Phase 1 — Decide scope + version The lockstep set = every package currently at the previous version (it is NOT a -fixed list; `ai-runtime` and the `client/web/packages/*` are in it). Enumerate it: +fixed list; the `client/web/packages/*` are in it, and the private `ai-runtime` and `conformance` are not). Enumerate it: ```bash for f in server/typescript/packages/*/package.json client/web/packages/*/package.json; do @@ -90,7 +90,7 @@ for f in server/typescript/packages/*/package.json client/web/packages/*/package done ``` -`forge` / `conformance` are `private` (never publish). Confirm each candidate is +`conformance` and `ai-runtime` are `private` (never publish). Confirm each candidate is actually on npm (`npm view dist-tags`). Patch bump unless a public API changed; this repo bumps the whole set in lockstep. diff --git a/.github/workflows/npm-dist-tag.yml b/.github/workflows/npm-dist-tag.yml index e1bb1c3dd6..8f5e4ce72d 100644 --- a/.github/workflows/npm-dist-tag.yml +++ b/.github/workflows/npm-dist-tag.yml @@ -68,8 +68,8 @@ jobs: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc trap 'rm -f ~/.npmrc' EXIT - # Fail on the credential, once, before touching 14 packages. Without this an - # auth problem arrives as fourteen identical per-package errors and looks like a + # Fail on the credential, once, before touching any package. Without this an + # auth problem arrives as one identical error per package and looks like a # registry-side refusal of the operation. npm whoami >/dev/null 2>&1 || { echo "::error::NPM_TOKEN does not authenticate"; exit 1; } diff --git a/AGENTS.md b/AGENTS.md index 9d37eb27e9..9f8cb0de8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,7 +51,7 @@ moved it (1.0.4 relaxed `@sourceRefField` onto `@cardinality: one` with a prose- manifest footprint, and was ruled a hold). `metamodelVersion` read **`1.1`** from 1.1.0 through 1.1.3 for the FR-044 reporting vocabulary and the requirements slice 1 (the first slice of two, covering existence gates and per-entity coverage). **It reads `1.2` from 1.1.4** through every published release since, for calendar-aligned relative report windows (`startOf` on a relative date). The merged tree claims **`1.3`** (`METAMODEL_VERSION` in every port) — main's 1.3.0 and the line's 1.2.4 both carry it, and neither is published. Per-release detail lives in **`CHANGELOG.md`** — it is the log, and this file does not duplicate it. -The npm surface is **14 `@metaobjectsdev/*` packages in full lockstep**; the two `angular` +The npm surface is **13 `@metaobjectsdev/*` packages in full lockstep** (`ai-runtime` left it in 1.3.0: its call loop is now written into the project by the `trace-helper` generator, ADR-0024 Amendment 2); the two `angular` packages are on their own `0.6.x` line and are **not published — source-only by decision** (ADR-0048). They build in-repo and stay off the registry until they meet that ADR's promotion bar. @@ -59,7 +59,7 @@ bar. **A lagging version number is INFORMATION, not drift.** Since `0.24.5` a registry publishes only when it has a changed product file, and when it does it adopts the shared `minor.patch` then current, skipping the numbers it sat out (operative table in `docs/RELEASING.md`; -the level vocabulary takes is ADR-0035 Amendment 5's feature test). Two carve-outs: the 14 +the level vocabulary takes is ADR-0035 Amendment 5's feature test). Two carve-outs: the 13 npm packages move atomically with each other, and a change to `expected-registry.json` / `metamodelVersion` still forces all four, at any release level, because that is the contract every port byte-matches. So PyPI at `0.25.0` while npm is at `0.25.2` says diff --git a/CHANGELOG.md b/CHANGELOG.md index 711f587bce..5e116617b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,36 @@ here.** ## [Unreleased] +- **codegen-ts: the trace helper's call loop is written into the project, and + `@metaobjectsdev/ai-runtime` is no longer published.** The `trace-helper` generator now writes + `llm-call.ts` (the `LlmClient` seam and `runLlmCall`) beside the `.trace.ts` modules, + and a `call` imports it from there, so generated trace code depends only on + `runtime-ts`, `render` and `metadata`. `ai-runtime` is `private` and leaves the publish set, + which is 13 packages; 1.2.3 stays on npm. Regenerate and drop the dependency: + [docs/features/migrations/ai-runtime-unpublished.md](docs/features/migrations/ai-runtime-unpublished.md) + (ADR-0024 Amendment 2). +- **codegen-ts: a trace helper whose response value object has a required field compiles.** It + cast the extracted record straight to the value object's interface, which `strict` TypeScript + refuses; it now casts through `unknown`, after checking that no required field was lost. +- **react: `` moves to `@metaobjectsdev/react/image-upload`, and `react-easy-crop` + becomes an optional peer (breaking).** `ImageUpload` and `cropToBlob` leave the package root + for the new subpath, and the generated form imports them from there, so a project with no + `view.image` field no longer installs the crop library at all. A project with one adds + `react-easy-crop` (`>=6.2.3 <7.0.0`) to its dependencies. The adapter provider stays on the + root. Regenerate, and move any hand-written import: + [docs/features/migrations/react-image-upload-subpath.md](docs/features/migrations/react-image-upload-subpath.md). +- **The empty `@metaobjectsdev/forge` package is removed.** It was private, exported nothing and + had no importer. The forge vocabulary (`decision`, `principle`, `convention`, `glossary`, + `failure` and the `@forge*` attributes) is unchanged: `@metaobjectsdev/sdk` ships it as + `forgeTypesProvider`, and `FORGE-METADATA.md` now says so. The "The TypeScript forge provider" + section of `docs/features/extending-with-providers.md` is removed; that doc no longer names it. +- **cli: `meta schema` prints the expected schema, read-only.** `meta schema --dialect + postgres|sqlite|d1` prints the `CREATE` statements `meta migrate` would write for an empty + database, views included; `--as json` prints the neutral JSON document instead, the format + `meta migrate` commits as its snapshot, now described in `docs/features/schema-snapshot-format.md`. + It builds the schema the way `meta migrate` does (conventions, `migrate.scope`, the dependency + exclusion) and reads no database and no snapshot, so a native migration tool can start from it. + The dialect defaults to `migrate.dialect`, then to the `dialect` in `metaobjects.config.ts`. - **Java: a standalone `{{! comment }}` line leaves no blank line.** mustache.java kept the line break after a standalone comment tag, so a Java render had one extra blank line where TypeScript, C# and Python had none. `Renderer` now strips standalone comment lines before mustache.java parses them. A diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 47e653636b..e92bca09df 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -38,7 +38,7 @@ As of 2026-10-28, every registry package has a single owner, the creator. | Registry | Packages | Owner today | How it is published | |---|---|---|---| -| npm | The 14 `@metaobjectsdev/*` packages: `ai-runtime`, `cli`, `codegen-ts`, `codegen-ts-react`, `codegen-ts-tanstack`, `docs-site`, `metadata`, `migrate-ts`, `react`, `render`, `runtime-ts`, `runtime-web`, `sdk`, `tanstack` | npm user `dougmealing`, the only owner of each package, in the `metaobjectsdev` npm organization | Locally, by the release script ([docs/RELEASING.md](docs/RELEASING.md)) | +| npm | The 13 `@metaobjectsdev/*` packages: `cli`, `codegen-ts`, `codegen-ts-react`, `codegen-ts-tanstack`, `docs-site`, `metadata`, `migrate-ts`, `react`, `render`, `runtime-ts`, `runtime-web`, `sdk`, `tanstack` | npm user `dougmealing`, the only owner of each package, in the `metaobjectsdev` npm organization | Locally, by the release script ([docs/RELEASING.md](docs/RELEASING.md)) | | Maven Central | The `com.metaobjects` namespace: the `metaobjects` parent POM and 14 modules (`metaobjects-metadata`, `-codegen-base`, `-codegen-mustache`, `-codegen-spring`, `-codegen-kotlin`, `-codegen-plantuml`, `-render`, `-metadata-ktx`, `-maven-plugin`, `-core-spring`, `-spring-boot-starter`, `-om`, `-omdb`, `-omdb-ktx`) | The creator's Sonatype Central Portal account, which holds the verified namespace; artifacts are signed with the creator's GPG key | Locally, with `mvn deploy` | | NuGet | `MetaObjects`, `MetaObjects.Render`, `MetaObjects.Codegen`, `MetaObjects.Cli` | nuget.org organization `metaobjects`, administered by the creator | Trusted Publishing from `.github/workflows/publish-csharp.yml` | | PyPI | `metaobjects` | PyPI user `dougmealing` (Owner) | Locally or from `.github/workflows/publish-python.yml` with an API token | diff --git a/agent-context-shipped/files/0fe543fe1b3c9b3c.md b/agent-context-shipped/files/01fcc1b45dff7950.md similarity index 95% rename from agent-context-shipped/files/0fe543fe1b3c9b3c.md rename to agent-context-shipped/files/01fcc1b45dff7950.md index 92b5d47980..ca32e33fea 100644 --- a/agent-context-shipped/files/0fe543fe1b3c9b3c.md +++ b/agent-context-shipped/files/01fcc1b45dff7950.md @@ -183,12 +183,13 @@ MetaObjects generates **no** provider/LLM-call layer and never will — the call commodity the ecosystem already solves, and a maintained vendor wrapper would just chase SDK churn (ADR-0024). You bring the caller; MetaObjects owns the typed render → parse → record. For the call step, plug the idiomatic library into the -one-method `LlmClient` seam from `@metaobjectsdev/ai-runtime`: +one-method `LlmClient` seam. The `trace-helper` generator writes it into your project, in +`llm-call.ts` beside the helpers (no package to install): ```ts import { generateText } from "ai"; // Vercel AI SDK — recommended import { anthropic } from "@ai-sdk/anthropic"; -import type { LlmClient } from "@metaobjectsdev/ai-runtime"; +import type { LlmClient } from "./generated/llm-call"; // where trace-helper wrote it export const llm: LlmClient = { async complete({ prompt, model, system }) { @@ -204,10 +205,10 @@ output, the de-facto TS standard. Single-provider apps can implement `complete` directly over `@anthropic-ai/sdk` / `openai`; heavy chains can use LangChain.js — the seam is one method either way. -With a client in hand, the generated `record` helper (the `trace-helper` -generator) and `@metaobjectsdev/ai-runtime`'s `callLlm` do render → call → **typed -trace persist** in one call, recording request/response as typed value objects in -your own DB. The parser above is the standalone receive side if you don't want the +With a client in hand, the generated `call` helper (the `trace-helper` +generator) does render → call → **typed trace persist** in one call, recording +request/response as typed value objects in your own DB; `record` persists a +call you made yourself. The parser above is the standalone receive side if you don't want the recorder. ## Drift gate diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index 2ad546ed52..b616f775dd 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -185,7 +185,7 @@ }, { "path": ".claude/skills/metaobjects-prompts/references/typescript.md", - "file": "0fe543fe1b3c9b3c.md" + "file": "01fcc1b45dff7950.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/SKILL.md", @@ -400,7 +400,7 @@ }, { "path": ".claude/skills/metaobjects-prompts/references/typescript.md", - "file": "0fe543fe1b3c9b3c.md" + "file": "01fcc1b45dff7950.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/SKILL.md", @@ -620,7 +620,7 @@ }, { "path": ".claude/skills/metaobjects-prompts/references/typescript.md", - "file": "0fe543fe1b3c9b3c.md" + "file": "01fcc1b45dff7950.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/SKILL.md", @@ -843,7 +843,7 @@ }, { "path": ".claude/skills/metaobjects-prompts/references/typescript.md", - "file": "0fe543fe1b3c9b3c.md" + "file": "01fcc1b45dff7950.md" }, { "path": ".claude/skills/metaobjects-runtime-ui/SKILL.md", diff --git a/agent-context/skills/metaobjects-prompts/references/typescript.md b/agent-context/skills/metaobjects-prompts/references/typescript.md index 92b5d47980..ca32e33fea 100644 --- a/agent-context/skills/metaobjects-prompts/references/typescript.md +++ b/agent-context/skills/metaobjects-prompts/references/typescript.md @@ -183,12 +183,13 @@ MetaObjects generates **no** provider/LLM-call layer and never will — the call commodity the ecosystem already solves, and a maintained vendor wrapper would just chase SDK churn (ADR-0024). You bring the caller; MetaObjects owns the typed render → parse → record. For the call step, plug the idiomatic library into the -one-method `LlmClient` seam from `@metaobjectsdev/ai-runtime`: +one-method `LlmClient` seam. The `trace-helper` generator writes it into your project, in +`llm-call.ts` beside the helpers (no package to install): ```ts import { generateText } from "ai"; // Vercel AI SDK — recommended import { anthropic } from "@ai-sdk/anthropic"; -import type { LlmClient } from "@metaobjectsdev/ai-runtime"; +import type { LlmClient } from "./generated/llm-call"; // where trace-helper wrote it export const llm: LlmClient = { async complete({ prompt, model, system }) { @@ -204,10 +205,10 @@ output, the de-facto TS standard. Single-provider apps can implement `complete` directly over `@anthropic-ai/sdk` / `openai`; heavy chains can use LangChain.js — the seam is one method either way. -With a client in hand, the generated `record` helper (the `trace-helper` -generator) and `@metaobjectsdev/ai-runtime`'s `callLlm` do render → call → **typed -trace persist** in one call, recording request/response as typed value objects in -your own DB. The parser above is the standalone receive side if you don't want the +With a client in hand, the generated `call` helper (the `trace-helper` +generator) does render → call → **typed trace persist** in one call, recording +request/response as typed value objects in your own DB; `record` persists a +call you made yourself. The parser above is the standalone receive side if you don't want the recorder. ## Drift gate diff --git a/bun.lock b/bun.lock index 8a5ac3b437..33d1ecc97b 100644 --- a/bun.lock +++ b/bun.lock @@ -46,7 +46,6 @@ "version": "1.3.0", "dependencies": { "@metaobjectsdev/runtime-web": "workspace:*", - "react-easy-crop": "^6.2.3", }, "devDependencies": { "@hookform/resolvers": "^3.10.0", @@ -57,6 +56,7 @@ "jsdom": "^29.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", + "react-easy-crop": "^6.2.3", "react-hook-form": "^7.54.0", "typescript": "^5.6.0", "zod": "^4.4.3", @@ -64,10 +64,12 @@ "peerDependencies": { "@hookform/resolvers": ">=3.0.0 <6.0.0", "react": ">=18.0.0 <20.0.0", + "react-easy-crop": ">=6.2.3 <7.0.0", "react-hook-form": ">=7.0.0 <8.0.0", "zod": ">=3.23.0 <5.0.0", }, "optionalPeers": [ + "react-easy-crop", "zod", ], }, @@ -319,19 +321,10 @@ "typescript": "^5.6.0", }, }, - "server/typescript/packages/forge": { - "name": "@metaobjectsdev/forge", - "version": "0.1.0", - "devDependencies": { - "bun-types": "latest", - "typescript": "^5.6.0", - }, - }, "server/typescript/packages/integration-tests": { "name": "@metaobjectsdev/integration-tests", "version": "0.0.0", "dependencies": { - "@metaobjectsdev/ai-runtime": "workspace:*", "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/migrate-ts": "workspace:*", @@ -774,8 +767,6 @@ "@metaobjectsdev/example-dynamic-grid": ["@metaobjectsdev/example-dynamic-grid@workspace:examples/dynamic-grid"], - "@metaobjectsdev/forge": ["@metaobjectsdev/forge@workspace:server/typescript/packages/forge"], - "@metaobjectsdev/integration-tests": ["@metaobjectsdev/integration-tests@workspace:server/typescript/packages/integration-tests"], "@metaobjectsdev/metadata": ["@metaobjectsdev/metadata@workspace:server/typescript/packages/metadata"], @@ -1604,6 +1595,8 @@ "@metaobjectsdev/docs-site/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "@metaobjectsdev/integration-tests/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], + "@metaobjectsdev/metadata/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], "@metaobjectsdev/migrate-ts/bun-types": ["bun-types@1.4.5", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-ECHn+9dhL3wv0G6u0+7dQvrnaimXiRDxxerYBmhTaLyJEEuvTPWk2Fye3XIf5Y++JIIiHKfQw4Z7V5D8KuiXbg=="], diff --git a/client/web/packages/react/package.json b/client/web/packages/react/package.json index 965ed9e38b..3863517015 100644 --- a/client/web/packages/react/package.json +++ b/client/web/packages/react/package.json @@ -11,6 +11,11 @@ "types": "./dist/index.d.ts", "default": "./dist/index.js" }, + "./image-upload": { + "bun": "./src/image-upload.tsx", + "types": "./dist/image-upload.d.ts", + "default": "./dist/image-upload.js" + }, "./form.css": "./form.css" }, "files": [ @@ -47,16 +52,19 @@ "access": "public" }, "dependencies": { - "@metaobjectsdev/runtime-web": "workspace:*", - "react-easy-crop": "^6.2.3" + "@metaobjectsdev/runtime-web": "workspace:*" }, "peerDependencies": { "@hookform/resolvers": ">=3.0.0 <6.0.0", "react": ">=18.0.0 <20.0.0", + "react-easy-crop": ">=6.2.3 <7.0.0", "react-hook-form": ">=7.0.0 <8.0.0", "zod": ">=3.23.0 <5.0.0" }, "peerDependenciesMeta": { + "react-easy-crop": { + "optional": true + }, "zod": { "optional": true } @@ -70,6 +78,7 @@ "jsdom": "^29.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", + "react-easy-crop": "^6.2.3", "react-hook-form": "^7.54.0", "typescript": "^5.6.0", "zod": "^4.4.3" diff --git a/client/web/packages/react/src/image-upload.tsx b/client/web/packages/react/src/image-upload.tsx index 3aed4b584c..312bef2487 100644 --- a/client/web/packages/react/src/image-upload.tsx +++ b/client/web/packages/react/src/image-upload.tsx @@ -1,3 +1,14 @@ +// `@metaobjectsdev/react/image-upload`: the upload-and-crop control, on its own subpath. +// This module IS that subpath (its name mirrors src/, which tsconfig.scripts.json relies on). +// +// `react-easy-crop` is an OPTIONAL peer. A bundler resolves the whole import graph before it +// tree-shakes, and a dynamic import() of a package that is not installed is fatal to webpack, +// Next.js, esbuild and Bun, so nothing reachable from the package root may import it (#287; +// test/browser-bundleable.test.ts holds every optional peer to that). A project with a +// `view.image` field installs react-easy-crop and imports from here; every other project +// installs nothing extra. The adapter contract stays on the root, because it imports nothing +// optional and an app wires it once for the whole tree. + import { lazy, Suspense, useCallback, useRef, useState } from "react"; import type { ChangeEvent, ReactElement } from "react"; import type { Area } from "react-easy-crop"; @@ -126,3 +137,5 @@ export function ImageUpload({ value, onChange, meta }: ImageUploadProps): ReactE ); } + +export { cropToBlob } from "./crop-to-blob.js"; diff --git a/client/web/packages/react/src/index.ts b/client/web/packages/react/src/index.ts index 6922991c43..96a819004f 100644 --- a/client/web/packages/react/src/index.ts +++ b/client/web/packages/react/src/index.ts @@ -9,10 +9,10 @@ export { type UseEntityFormReturn, } from "./use-entity-form.js"; export { CurrencyInput, type CurrencyInputProps } from "./currency-input.js"; -export { ImageUpload, type ImageUploadProps } from "./image-upload.js"; export { ImageUploadAdapterProvider, useImageUploadAdapter, type ImageUploadAdapterProviderProps, } from "./image-adapter-provider.js"; -export { cropToBlob } from "./crop-to-blob.js"; +// and cropToBlob live on the `@metaobjectsdev/react/image-upload` subpath, which +// needs the optional peer react-easy-crop (see src/image-upload.tsx). diff --git a/docs/README.md b/docs/README.md index 3512e81306..3b07199217 100644 --- a/docs/README.md +++ b/docs/README.md @@ -30,6 +30,7 @@ docs/ │ ├── templates-and-payloads.md │ ├── loaders.md │ ├── migrations-and-drift.md +│ ├── schema-snapshot-format.md # the expected schema as JSON: what `meta schema --as json` prints and migrate commits │ ├── migrations/ # per-version migration guides (start at upgrading-1.0-to-1.1.md for 1.0.x → 1.1) │ ├── api-contract.md # cross-port REST contract (the universal browser client speaks it) │ ├── abstracts-and-inheritance.md # abstract: true + extends: — author-side shape reuse diff --git a/docs/RELEASING-automation-proposal.md b/docs/RELEASING-automation-proposal.md index c020fa0fca..70eaed274c 100644 --- a/docs/RELEASING-automation-proposal.md +++ b/docs/RELEASING-automation-proposal.md @@ -23,7 +23,7 @@ there's no per-PR record of what is releasable. - Each PR adds a changeset file (`bunx changeset`) declaring bump level + human summary; a bot nags (non-blocking) if missing. - Configure a **`fixed` (lockstep) group** containing every publish candidate - so they bump together — matching today's lockstep. `forge` / `conformance` + so they bump together — matching today's lockstep. `conformance` / `ai-runtime` (private) and the independently-versioned `*-angular` packages stay out. - A GitHub Action maintains a **"Version Packages" PR** that consumes changesets → bumps versions + writes `CHANGELOG.md`. **Merging that PR is the approval gate.** diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 321e05c8e3..ee7a48897c 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -23,7 +23,7 @@ > permanent (`scripts/maven-coordinate.mjs` is the single derivation; every script imports it). > Concretely: npm `0.25.0` is Maven `7.25.0`, and npm `1.0.0` is Maven **`8.0.0`**. Do not type > a literal `7.` anywhere — at the 1.0 cut it asks Central for a version BELOW the last release. -> Two carve-outs: the **14 npm packages still move atomically with each other** (they +> Two carve-outs: the **13 npm packages still move atomically with each other** (they > cross-depend — that is intra-npm lockstep and it is unchanged), and a change to > `expected-registry.json` / `metamodelVersion` **forces all four**, because that is the > cross-port contract — whatever the release's level, so a vocabulary-adding PATCH publishes @@ -143,10 +143,14 @@ node scripts/publish-set.mjs --check # the set + its tier order, and the inva | 1 | `codegen-ts`, `runtime-ts`, `migrate-ts`, `sdk`, `docs-site`, `runtime-web` | | 2 | `codegen-ts-react`, `codegen-ts-tanstack`, `react` | | 3 | `tanstack` | -| 4 | `cli`, `ai-runtime` (leaves — nothing depends on them; publish last) | +| 4 | `cli` (the leaf — nothing depends on it; publish last) | -Publish in tier order so a dependent never lands before its dependency. **`forge` and -`conformance` are `private: true` and must never be published** (bun refuses them). +Publish in tier order so a dependent never lands before its dependency. **`conformance` +and `ai-runtime` are `private: true` and must never be published** (bun refuses them). +`ai-runtime` left the set in 1.3.0: the generated trace helper used to import it, and the +`trace-helper` generator now writes that call loop into the project instead +([ADR-0024](../spec/decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md) +Amendment 2). Its last published version is 1.2.3, and it stays on the registry. ## Golden rules (the non-obvious ones) @@ -493,7 +497,7 @@ diff explained. ## Procedure Run everything from the repo root unless noted. Bump the publish-candidate set only -(not the private root, not forge/conformance) — enumerate it (see "What gets published"). +(not the private root, not conformance/ai-runtime) — enumerate it (see "What gets published"). ### 0. Build fresh — the stale-`dist` trap `bun publish` does NOT rebuild, `dist/` is gitignored, and `main` points at `dist/`, diff --git a/docs/features/cli.md b/docs/features/cli.md index 3b4341f382..f8ba3a95e8 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -27,6 +27,7 @@ command surface splits in two: |---|---|---|---| | Project scaffold (`init`) | Node `meta` | `meta init` | TS projects; `--dialect sqlite\|postgres\|mysql\|d1` writes the codegen `dialect` in `metaobjects.config.ts` and, for sqlite, postgres and d1, `migrate.dialect` in `.metaobjects/config.json` (d1 is `--d1`; MySQL schema is not `meta migrate`'s). A new `.metaobjects/config.json` also carries `"api": { "pagination": { "defaultLimit": 50, "maxLimit": 1000 }, "unknownFields": "reject" }`, the generated list routes' page size and the refusal of undeclared write keys ([api-contract.md](api-contract.md)); for `--dialect sqlite` it also adds `@libsql/kysely-libsql` to the project's `dependencies`, the SQLite driver the CLI's optional peer names (run your package manager's install afterwards); `--force` over an existing config does not add it | | **Agent-context scaffold** (`agent-docs`) | **Node `meta`** | `npx meta agent-docs --server ` | **any backend** — single assembler (ADR-0033); non-Node CLIs redirect here | +| **Expected schema** (`schema`) | **Node `meta`** | `meta schema [--dialect ] [--as ddl\|json]` | **any backend** — read-only: prints the schema the metadata expects as DDL or as the neutral document ([schema-snapshot-format.md](schema-snapshot-format.md)); reads no database; writes nothing unless `--out` names a file | | **Schema migrate** | **Node `meta`** | `meta migrate` | **any backend** — schema is Node-only (ADR-0015) | | **Schema drift** (`verify --db`) | **Node `meta`** | `meta verify --db` | **any backend** — live-DB drift, Node-only | | **Codegen drift** (`verify --codegen`) | **Node `meta`** | `meta verify --codegen` | TS reference (ADR-0021 D2) — regen-to-temp + diff committed output | diff --git a/docs/features/extending-with-providers.md b/docs/features/extending-with-providers.md index 0445417247..65fe14a71c 100644 --- a/docs/features/extending-with-providers.md +++ b/docs/features/extending-with-providers.md @@ -504,26 +504,6 @@ The same file, loaded strictly without the provider, fails with `ERR_UNKNOWN_SUB order, in every port. A lax load accepts the unknown attributes but still refuses the unknown subtype. -### The TypeScript forge provider - -**`forgeTypesProvider` is TypeScript-only, and is no longer in any default -composition.** It was listed here as part of the default composition for "the TS / C# / -Python loaders"; in fact only TypeScript ever had it, and no C#, Python, Java or Kotlin -registry registers any `@forge*` attribute or `decision` / `principle` / `convention` / -`glossary` / `failure` type at all. Nor does `expected-registry.json`, the manifest all -five ports byte-match, so the cross-port gate never had jurisdiction over it — one -document had two verdicts, decided by which toolchain read it, and 1.0 would have frozen -that in. - -At the 1.0 cut it left `defaultLoadMemoryProviders` and `meta types`. It is still -exported and unchanged, as the chartered opt-in: - -```ts -const root = await loadMemory("./", { providers: [forgeTypesProvider] }); -``` - -A project taking it knows it has a surface the other four ports do not. - ## Stable error codes Composition surfaces these codes consistently across all ports (see diff --git a/docs/features/image-upload.md b/docs/features/image-upload.md index 14a32fd3e5..69e5450389 100644 --- a/docs/features/image-upload.md +++ b/docs/features/image-upload.md @@ -191,27 +191,40 @@ specificity so a host app's reset styles win, and resolves colors through `--mo-*` CSS custom properties with fallback hex values — themable with zero configuration, override any subset. -`react-easy-crop` is a **regular dependency of `@metaobjectsdev/react`, lazy-loaded -at runtime.** It is imported via `React.lazy` only when `` actually -renders the crop UI, so it lands in its own chunk and a consumer without a -`view.image` field never downloads it — but it IS installed for everyone, and -nothing needs to be added by hand. - -> It was an *optional peer* through `0.21.4`, which was a bug rather than a saving. -> `ImageUpload` is exported from the package root, so `image-upload.js` sits in -> every consumer's module graph, and bundlers resolve the whole graph before -> tree-shaking — a dynamic `import()` of a missing package is fatal to **webpack, -> Next.js (Turbopack and webpack), esbuild and Bun** alike (only Vite special-cases -> optional peers). So *any* consumer of the generated forms failed to build with a -> "can't resolve `react-easy-crop`" error naming a package they had never heard of, -> whether or not they authored an image field. Making it a real dependency fixes -> that for every bundler with nothing for the adopter to configure. +`` and `cropToBlob` live on their own subpath, +**`@metaobjectsdev/react/image-upload`**, and the crop library, `react-easy-crop`, is an +**optional peer** of `@metaobjectsdev/react` (`>=6.2.3 <7.0.0`). A project with a `view.image` +field installs it beside the package: + +```bash +npm install react-easy-crop +``` + +```tsx +import { ImageUpload } from "@metaobjectsdev/react/image-upload"; +import { ImageUploadAdapterProvider } from "@metaobjectsdev/react"; +``` + +The generated form imports `ImageUpload` from the subpath, and only when the entity has an image +field, so a project without one installs nothing extra and its bundle never reaches the crop +code. The adapter provider stays on the package root, because it imports nothing optional and an +app wires it once for the whole tree. Inside `` the crop UI is still loaded with +`React.lazy`, so it lands in its own chunk. + +> **Why a subpath, and not the root.** Through `0.21.4` `react-easy-crop` was an optional peer while +> `ImageUpload` was exported from the package root, so `image-upload.js` sat in every consumer's +> module graph. Bundlers resolve the whole graph before tree-shaking, and a dynamic `import()` of a +> missing package is fatal to **webpack, Next.js (Turbopack and webpack), esbuild and Bun** alike +> (only Vite special-cases optional peers). So every consumer of the generated forms failed to +> build, whether or not they authored an image field. From `0.21.5` to 1.2 it was a regular +> dependency instead, installed for everyone. Since 1.3.0 nothing reachable from the root imports +> it, which `test/browser-bundleable.test.ts` holds every optional peer to: the root must still +> bundle with the optional peer absent. > -> The cleaner long-term shape is a `@metaobjectsdev/react/image` subpath so the -> crop dependency is pulled in only by consumers who import it. That removes -> exports from the package root, which is breaking, so it belongs in a MINOR — and -> a MINOR would not reach the adopters whose builds are broken today, since -> `^0.21.x` will not resolve it. +> **Upgrading from 1.2.** Regenerate (`meta gen`): a form with an image field changes its +> `ImageUpload` import to the subpath. Code that imports `ImageUpload` or `cropToBlob` from +> `@metaobjectsdev/react` by hand moves to `@metaobjectsdev/react/image-upload`. If the project has +> an image field, add `react-easy-crop` to its dependencies; it is no longer installed for you. ## Storage & wire contract diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 2641337a7f..1c94fc8c46 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -57,6 +57,19 @@ dialect only; `meta migrate --dialect mysql` is refused with that explanation, a yours (`docs/recipes/mysql.md`). Output lands under the path configured in `metaobjects.config.ts` (typically `./migrations/__.sql`). +**`meta schema`** prints the expected schema without migrating anything: the `CREATE` +statements `meta migrate` would write for an empty database (`--as ddl`, the default), or the +neutral JSON document (`--as json`), the same format as the committed snapshot and described in +[schema-snapshot-format.md](schema-snapshot-format.md). It builds the schema as `meta migrate` +does, with the project's conventions, `migrate.scope`, the dependency exclusion and the +projection and report views, and reads no database and no snapshot. Use it to hand the schema +to a native migration tool, to review it, or to diff it between two commits. + +```bash +meta schema --dialect postgres > schema.sql +meta schema --dialect postgres --as json --out schema.json +``` + **`meta migrate apply-pending`** replays the committed migration files against `--db` in order, ledger-tracked (`_metaobjects_migrations`) and transactional — with **no diff and no metadata load**. For a project whose chain *builds* the schema, it is the diff --git a/docs/features/migrations/ai-runtime-unpublished.md b/docs/features/migrations/ai-runtime-unpublished.md new file mode 100644 index 0000000000..fad0ef3c86 --- /dev/null +++ b/docs/features/migrations/ai-runtime-unpublished.md @@ -0,0 +1,43 @@ +# Migration — the trace helper's call loop is generated; `@metaobjectsdev/ai-runtime` is unpublished (`1.3.0`) + +**TypeScript only; regenerate, then drop a dependency.** The generated `call` trace +helpers imported `runLlmCall` and the `LlmClient` seam from `@metaobjectsdev/ai-runtime`. From +1.3.0 the `trace-helper` generator writes that call loop into your project as `llm-call.ts`, +beside the `.trace.ts` modules, and the package is no longer published. Its last +version, 1.2.3, stays on npm, so nothing breaks until you choose to move. + +## What to change + +| Before | After | +|---|---| +| `@metaobjectsdev/ai-runtime` in `dependencies` | remove it, after regenerating | +| `import type { LlmClient } from "@metaobjectsdev/ai-runtime"` | `import type { LlmClient } from "/llm-call"` | +| `import { runLlmCall } from "@metaobjectsdev/ai-runtime"` | the same name from the generated `llm-call.ts` | + +Run `meta gen`. Each `.trace.ts` whose prompt carries `@textRef` changes one import, to +`./llm-call`, and `llm-call.ts` appears beside it. The `LlmClient` you wrote does not change: +the interface is the same. + +**An owned `trace-helper`** (`meta eject trace-helper`, 1.1 or later) keeps writing what your +copy writes, including the old import, so it keeps working against 1.2.3. To move, take a fresh +copy with `meta eject trace-helper --force` and re-apply your edits, or add the second file to +your copy: it is `renderLlmCallSupport()` written to `LLM_CALL_SUPPORT_FILE`, both exported +from `@metaobjectsdev/codegen-ts`. + +**`callLlm`, `CompositeRecorder` and the Langfuse and OpenTelemetry recorders** are not +generated. They stay in the repository under `server/typescript/packages/ai-runtime/` as +reference source; copy the ones you use into your project. + +## Also fixed + +A `.trace.ts` whose response value object has a required field did not compile under +`strict`: it cast the extracted record straight to the value object's interface, which +TypeScript refuses when the types do not overlap. It now casts through `unknown`, after the +helper has checked that no required field was lost or malformed. + +## Why + +Generated code should import nothing from MetaObjects beyond ordinary published packages, and +the call loop is code an adopter owns anyway: the client it calls is theirs. See +[ADR-0024](../../../spec/decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md), +Amendment 2. diff --git a/docs/features/migrations/react-image-upload-subpath.md b/docs/features/migrations/react-image-upload-subpath.md new file mode 100644 index 0000000000..b0f6c90b8c --- /dev/null +++ b/docs/features/migrations/react-image-upload-subpath.md @@ -0,0 +1,42 @@ +# Migration — `` moves to `@metaobjectsdev/react/image-upload` (`1.3.0`) + +**Breaking, TypeScript React only; the generated forms change on regen.** `ImageUpload` and +`cropToBlob` are no longer exported from the root of `@metaobjectsdev/react`. They live on the +subpath `@metaobjectsdev/react/image-upload`, and the crop library they need, `react-easy-crop`, +is now an optional peer instead of a dependency. A project with no `view.image` field installs +nothing extra and its bundle never reaches the crop code; a project with one installs +`react-easy-crop` itself. + +## What to change + +| Before | After | +|---|---| +| `import { ImageUpload } from "@metaobjectsdev/react"` | `import { ImageUpload } from "@metaobjectsdev/react/image-upload"` | +| `import { cropToBlob } from "@metaobjectsdev/react"` | `import { cropToBlob } from "@metaobjectsdev/react/image-upload"` | +| `react-easy-crop` arrived with `@metaobjectsdev/react` | add `react-easy-crop` (`>=6.2.3 <7.0.0`) to your dependencies, only if you render `` | + +`ImageUploadAdapterProvider`, `useImageUploadAdapter` and the `ImageUploadAdapter` contract do not +move: they import nothing optional. + +**Generated forms.** Run `meta gen`. A form whose entity has a `view.image` field changes one line, +its `ImageUpload` import. A form you ejected the `form` generator for (`meta eject form`) needs +the same one-line change in your copy, or a fresh `meta eject form --force`. + +A search that finds every hand-written site: `grep -rn "ImageUpload\|cropToBlob" --include=*.ts --include=*.tsx src` + +## What happens if you skip it + +- **An import from the root** fails to compile: the root no longer exports the name. +- **An image field without `react-easy-crop` installed** fails at bundle time, naming + `react-easy-crop`, on the subpath that needs it. Nothing reachable from the root imports it, so + a project without an image field is not affected. + +## Why + +Before 1.3.0 `react-easy-crop` was a regular dependency, installed for every React consumer +whether or not they had an image field. The earlier optional-peer form (through `0.21.4`) failed +because `ImageUpload` was on the root: bundlers resolve the whole graph before they tree-shake, +and a dynamic `import()` of a missing package is fatal to webpack, Next.js, esbuild and Bun. With +`ImageUpload` on its own subpath, the root holds no optional import, and +`client/web/packages/react/test/browser-bundleable.test.ts` keeps it that way for every optional +peer. See [image-upload.md](../image-upload.md). diff --git a/docs/features/schema-snapshot-format.md b/docs/features/schema-snapshot-format.md new file mode 100644 index 0000000000..f63eca6dc6 --- /dev/null +++ b/docs/features/schema-snapshot-format.md @@ -0,0 +1,152 @@ +# The schema snapshot format + +The expected schema is the store-neutral contract between a model and a database: the tables, +columns, keys, indexes, checks and views the metadata implies. This page describes how it is +written down as JSON. The same document is two things: + +- what `meta schema --as json` prints, the expected schema with nothing applied anywhere; +- what `meta migrate` commits as `.metaobjects/migrations/.schema..json`, the schema + the committed migration chain has reached. + +A native migration tool (EF Core, Flyway, Liquibase, Alembic, sqlx) or a port's own tooling can +read it to know what the model expects without running the Node engine. `meta migrate` is one +way to apply that schema, not the only one. + +The TypeScript definitions are the source: `SchemaSnapshot` and its descriptors in +`server/typescript/packages/migrate-ts/src/types.ts`, and the writer and reader in +`server/typescript/packages/migrate-ts/src/snapshot/serialize.ts` (`serializeSnapshot`, +`parseSnapshot`). + +## Producing it + +```bash +meta schema --dialect postgres --as json # print it +meta schema --dialect sqlite --as json --out schema.json +meta schema --dialect postgres # the same schema as CREATE statements +``` + +`meta schema` builds the expected schema exactly as `meta migrate` does: the project's schema +conventions (`migrate.conventions`), `migrate.scope` and the dependency exclusion, and the views +that projections and reports lower to. It reads no database and no snapshot, and writes nothing +unless `--out` is given. The DDL form is what `meta migrate` would create for an empty database. + +The dialect is `--dialect`, else `migrate.dialect` in `.metaobjects/config.json`, else `dialect` +in `metaobjects.config.ts`. The document is dialect-specific in its details (a view's body, a +check's expression, whether a table has a `schema`), so produce it for the dialect you deploy. +MySQL has no expected schema: MetaObjects does not own a MySQL schema. + +## The file + +```json +{ + "formatVersion": 4, + "snapshot": { + "tables": [ /* table descriptors */ ], + "views": [ /* view descriptors */ ], + "meta": { "sqliteVersion": "3.44.2" } + } +} +``` + +The writer makes it byte-stable, so a diff of two documents is a diff of the schemas: + +- object keys are sorted at every level, and the indentation is two spaces, with a trailing newline; +- `tables`, `views`, and each table's `columns`, `indexes`, `foreignKeys` and `checks` are sorted by `name`; +- an optional field that does not apply is left out, never written as `null`. + +`meta` is optional. It records facts about the database the snapshot was taken against +(today only `sqliteVersion`), so the expected schema `meta schema` prints never has it. + +## Table + +| Key | Type | Meaning | +|---|---|---| +| `name` | string | The table's physical name, after `naming` (ADR-0058) | +| `schema` | string, optional | The database schema. Absent on SQLite and D1; on Postgres absent means `public` | +| `columns` | column[] | See below | +| `primaryKey` | string[] | The primary key's column names, in key order; `[]` for none | +| `primaryKeyName` | string, optional | The key constraint's name, when the conventions name it something other than `_pkey` | +| `indexes` | index[] | See below | +| `foreignKeys` | foreign key[] | See below | +| `checks` | check[] | `{ name, expression }`: a named CHECK constraint and its boolean SQL | +| `description` | string, optional | From the entity's `@description`; a Postgres table comment | + +## Column + +| Key | Type | Meaning | +|---|---|---| +| `name` | string | The physical column name | +| `sqlType` | SQL type | The dialect-neutral type, below | +| `nullable` | boolean | Whether the column takes NULL | +| `default` | `{ kind, value }`, optional | `kind` is `literal` (a value) or `expr` (SQL such as `now()`) | +| `identity` | `"increment"` or `"uuid"`, optional | The key is generated by the database | +| `sequence` | `{ name?, start? }`, optional | An `increment` key's sequence, only as the model declares it (`@sequenceName`, `@sequenceStart`) | +| `description` | string, optional | From the field's `@description`; a Postgres column comment | + +### SQL type + +`sqlType` is a tagged object keyed by `kind`. The dialect renderers turn it into SQL, so the +same document describes the type on every dialect: + +| `kind` | Extra keys | Notes | +|---|---|---| +| `text` | `maxLength?`, `variant?` (`varchar` or `char`) | `variant` is an `@dbColumnType` spelling | +| `integer` | `bits` (32 or 64) | | +| `real` | | Double precision (`field.double`) | +| `real4` | | Single precision (`field.float`) | +| `numeric` | `precision?`, `scale?` | | +| `boolean`, `date`, `time`, `json`, `blob`, `uuid`, `inet`, `interval` | | `inet` and `interval` are native on Postgres | +| `timestamp` | `withTimezone` | | +| `array` | `element` (an SQL type) | A native array, such as `uuid[]` | + +## Index + +| Key | Type | Meaning | +|---|---|---| +| `name` | string | The index's database name | +| `columns` | string[] | Key columns in order; `[]` when `expr` is the key | +| `unique` | boolean | `identity.secondary` is unique, `index.lookup` is not (ADR-0040) | +| `orders` | (`asc` or `desc`)[], optional | Per-column direction; absent is all ascending | +| `where` | string, optional | A partial index's predicate | +| `expr` | string, optional | An expression index's key | +| `using` | string, optional | The access method (`gin`, `gist`, ...); absent is the default | +| `constraint` | `"unique"`, optional | The conventions want this key as a UNIQUE constraint rather than an index | +| `plainIndex` | `true`, optional | The conventions want this key as a plain unique index | + +## Foreign key + +| Key | Type | Meaning | +|---|---|---| +| `name` | string | The constraint name | +| `columns` | string[] | The referencing columns | +| `refTable` | string | The referenced table's physical name | +| `refColumns` | string[] | The referenced columns, positional to `columns` | +| `onDelete`, `onUpdate` | `cascade`, `set-null`, `restrict` or `no-action`, optional | From the relationship's `@onDelete` / `@onUpdate`; absent is the database default | + +## View + +| Key | Type | Meaning | +|---|---|---| +| `name` | string | The view's physical name (`@view`) | +| `schema` | string, optional | As for a table | +| `sql` | string, optional | The view body, the `SELECT` through its tail | +| `fingerprint` | string, optional | `metaobjects:v1:sha256:`, the body's hash, which `meta migrate` stamps in the view's comment | +| `dependsOn` | string[], optional | The tables the view reads | + +A snapshot `meta migrate` took from a database can also record a view's `dependents`, the +relations that depend on it. The expected schema never has them. + +## Versions + +`formatVersion` is bumped when a descriptor gains a field. A reader refuses a document newer than +it knows and upgrades an older one: + +- 2: tables gained `checks`. +- 3: views gained `fingerprint` and `dependents`. +- 4: a comment and a generated identity read back from a database are recorded, so absence means + none, not unknown. + +## See also + +- [Migrations and drift detection](migrations-and-drift.md) +- [The CLI](cli.md) diff --git a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json index b960c50d96..466526d6c0 100644 --- a/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json +++ b/examples/advanced-modeling/.metaobjects/.gen-state/.hashes/acme.learn.json @@ -45,7 +45,7 @@ "sourceNode": "acme::learn::Lesson" }, "src/generated/Program.form.tsx": { - "hash": "42056db5d322bb03e0fc00a197357061854d5a4fb3a304a2e8e04c8fc3689b6f", + "hash": "16c15c97549faffb320e0d10e8588d86751cf4580eda591d6b7ce0cf7ce42a02", "generatedBy": "form-file", "sourceNode": "acme::learn::Program" }, diff --git a/examples/advanced-modeling/src/generated/Program.form.tsx b/examples/advanced-modeling/src/generated/Program.form.tsx index a73475e10d..2f54551a7b 100644 --- a/examples/advanced-modeling/src/generated/Program.form.tsx +++ b/examples/advanced-modeling/src/generated/Program.form.tsx @@ -1,7 +1,7 @@ // @generated by @metaobjectsdev/codegen-ts — hand edits are kept by a three-way merge on regeneration; meta verify --codegen checks only the generated parts. // Source metadata: Program (Program) // Extend in your own module (e.g. Program.extra.tsx) — nothing imports it for you. -import { ImageUpload } from "@metaobjectsdev/react"; +import { ImageUpload } from "@metaobjectsdev/react/image-upload"; import { useFieldArray } from "react-hook-form"; import { Controller } from "react-hook-form"; import { Program, ProgramInsertSchema, ProgramUpdateSchema } from "./Program"; diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-prompts/references/typescript.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-prompts/references/typescript.md index 92b5d47980..ca32e33fea 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-prompts/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-prompts/references/typescript.md @@ -183,12 +183,13 @@ MetaObjects generates **no** provider/LLM-call layer and never will — the call commodity the ecosystem already solves, and a maintained vendor wrapper would just chase SDK churn (ADR-0024). You bring the caller; MetaObjects owns the typed render → parse → record. For the call step, plug the idiomatic library into the -one-method `LlmClient` seam from `@metaobjectsdev/ai-runtime`: +one-method `LlmClient` seam. The `trace-helper` generator writes it into your project, in +`llm-call.ts` beside the helpers (no package to install): ```ts import { generateText } from "ai"; // Vercel AI SDK — recommended import { anthropic } from "@ai-sdk/anthropic"; -import type { LlmClient } from "@metaobjectsdev/ai-runtime"; +import type { LlmClient } from "./generated/llm-call"; // where trace-helper wrote it export const llm: LlmClient = { async complete({ prompt, model, system }) { @@ -204,10 +205,10 @@ output, the de-facto TS standard. Single-provider apps can implement `complete` directly over `@anthropic-ai/sdk` / `openai`; heavy chains can use LangChain.js — the seam is one method either way. -With a client in hand, the generated `record` helper (the `trace-helper` -generator) and `@metaobjectsdev/ai-runtime`'s `callLlm` do render → call → **typed -trace persist** in one call, recording request/response as typed value objects in -your own DB. The parser above is the standalone receive side if you don't want the +With a client in hand, the generated `call` helper (the `trace-helper` +generator) does render → call → **typed trace persist** in one call, recording +request/response as typed value objects in your own DB; `record` persists a +call you made yourself. The parser above is the standalone receive side if you don't want the recorder. ## Drift gate diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index b5488748b9..055675a827 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -770,7 +770,7 @@ gate_ts_unit() { # codegen packages, sdk (which owns the agent-context conformance corpus), ai-runtime, # conformance and docs-site never ran in CI. That is how a red agent-context corpus # could reach `main` — and how this very lane's own new tests would have been ungated. - # ~2s for all seven. `forge` has no tests; `integration-tests` has its own ts-slow lane. + # ~2s for all seven. `integration-tests` has its own ts-slow lane. for p in metadata render runtime-ts \ codegen-ts-tanstack codegen-ts-react codegen-ts-angular \ sdk ai-runtime conformance docs-site; do diff --git a/scripts/finish-release.mjs b/scripts/finish-release.mjs index 5fb4529d37..9601c68904 100644 --- a/scripts/finish-release.mjs +++ b/scripts/finish-release.mjs @@ -201,7 +201,7 @@ if (wrong.length > 0) { const skipped = raw.startsWith("--") ? [] : raw.split(",").filter(Boolean); // npm can never sit out: `` IS the npm version — `release.mjs` writes it into - // all 14 package.json files — so a mismatch there always means the payload is stale. + // every package.json of the lockstep set — so a mismatch there always means the payload is stale. // Checked BEFORE the generic branch so the accurate message is reachable: it used to // fire only when an operator explicitly typed `npm`, which nobody does. if (wrong.some(([k]) => k === "npm")) { diff --git a/scripts/finish-release.test.ts b/scripts/finish-release.test.ts index 713bdfe6eb..3694233469 100644 --- a/scripts/finish-release.test.ts +++ b/scripts/finish-release.test.ts @@ -457,7 +457,7 @@ describe("finish-release gate 3: the payload states what shipped", () => { expect(r.out).toContain("pypi"); }); - // npm cannot sit out: `` IS the npm version, written into all 14 package.json + // npm cannot sit out: `` IS the npm version, written into every lockstep package.json // files by release.mjs. The accurate message used to fire only when an operator typed // `npm` explicitly, which nobody does, so the generic branch answered instead. test("an npm mismatch gets the npm-specific message, never an empty --sat-out", () => { diff --git a/scripts/publish-set.mjs b/scripts/publish-set.mjs index e67231ff28..b9426af76e 100755 --- a/scripts/publish-set.mjs +++ b/scripts/publish-set.mjs @@ -45,7 +45,7 @@ export const TIER_ORDER = [ "runtime-web", "codegen-ts-react", "codegen-ts-tanstack", "react", "tanstack", - "cli", "ai-runtime", + "cli", ]; /** Every workspace package: `{ dir, pkg, short }`, dir repo-relative. */ diff --git a/scripts/release-verify.mjs b/scripts/release-verify.mjs index 1bf5d1c7c6..d34fdc80b8 100644 --- a/scripts/release-verify.mjs +++ b/scripts/release-verify.mjs @@ -23,6 +23,7 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join, dirname } from "node:path"; import { homedir } from "node:os"; import { mavenVersion } from "./maven-coordinate.mjs"; +import { publishSet } from "./publish-set.mjs"; const args = process.argv.slice(2); const VERSION = args.find((a) => /^\d+\.\d+\.\d+(-rc\.\d+)?$/.test(a)); @@ -78,11 +79,9 @@ if (unknownRegistries.length) { process.exit(2); } -const NPM_PKGS = [ - "metadata", "render", "codegen-ts", "runtime-ts", "migrate-ts", "sdk", "docs-site", - "runtime-web", "codegen-ts-react", "codegen-ts-tanstack", "react", "tanstack", - "cli", "ai-runtime", -]; +// The npm set is the one the release published, read from scripts/publish-set.mjs, never a +// third list kept here: this one had to be edited by hand when ai-runtime left the set. +const NPM_PKGS = publishSet().set.map((p) => p.short); const NUGET_PKGS = ["metaobjects", "metaobjects.render", "metaobjects.codegen", "metaobjects.cli"]; const MVN_MODULES = ["metadata", "om", "omdb", "render", "codegen-spring", "codegen-kotlin", "metadata-ktx", "maven-plugin", "spring-boot-starter"]; diff --git a/scripts/release.mjs b/scripts/release.mjs index 4f82c5a30c..b53b0e77e5 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -7,7 +7,7 @@ // bun run release --preflight-only # run PHASE 0 and stop // // --preflight-only is NOT --dry-run. --dry-run still runs Phase 1, which writes the -// new version into all 14 package.json files, rebuilds, and regenerates bun.lock — +// new version into every package.json of the lockstep set, rebuilds, and regenerates bun.lock — // nothing reverts that, and this repo carries a scar from a corrupting version bump. // --preflight-only returns before any of it, so it is the safe way to exercise a // preflight change. diff --git a/server/typescript/README.md b/server/typescript/README.md index 593cfcdbca..22a20c2814 100644 --- a/server/typescript/README.md +++ b/server/typescript/README.md @@ -17,7 +17,6 @@ TypeScript implementation of the MetaObjects standard. | `@metaobjectsdev/migrate-ts` | Database migration tooling | | `@metaobjectsdev/sdk` | Programmatic SDK (memory, paths, workspace) | | `@metaobjectsdev/cli` | The `meta` CLI binary (`init`, `gen`, `migrate`) | -| `@metaobjectsdev/forge` | AI-collaboration capabilities (agent-docs, future MCP) | ## Getting started diff --git a/server/typescript/packages/ai-runtime/README.md b/server/typescript/packages/ai-runtime/README.md index 1fc9a35821..0e694f04fd 100644 --- a/server/typescript/packages/ai-runtime/README.md +++ b/server/typescript/packages/ai-runtime/README.md @@ -4,13 +4,15 @@ LLM call loop + typed-trace recorder adapters for MetaObjects — a provider-neu Part of the [MetaObjects](https://github.com/metaobjectsdev/metaobjects) monorepo. -## Install +## Not published since 1.3.0 -```bash -npm install @metaobjectsdev/ai-runtime -``` +This package is `private` and is no longer released. Its last published version, 1.2.3, stays +on npm. The generated `call` trace helpers used to import its call loop; since 1.3.0 +the `trace-helper` generator writes that loop into the project as `llm-call.ts`, so generated +code needs no package for it ([ADR-0024](../../../../spec/decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md) +Amendment 2). What remains here is reference source: copy what you need. -## What it provides +## What it holds - **`LlmClient`** — a provider-neutral seam you implement (or adapt) for your LLM vendor; no vendor SDK is bundled. - **`callLlm`** — the call bridge that invokes your client and records a typed trace of each call (request/response/cost). diff --git a/server/typescript/packages/ai-runtime/package.json b/server/typescript/packages/ai-runtime/package.json index 18705f92a7..6941e98001 100644 --- a/server/typescript/packages/ai-runtime/package.json +++ b/server/typescript/packages/ai-runtime/package.json @@ -1,6 +1,7 @@ { "name": "@metaobjectsdev/ai-runtime", "version": "1.3.0", + "private": true, "description": "LLM call loop + typed-trace recorder adapters for MetaObjects: provider-neutral LlmClient seam, callLlm bridge, Composite/Langfuse/OTel recorders.", "type": "module", "main": "./dist/index.js", @@ -51,9 +52,6 @@ "langfuse", "opentelemetry" ], - "publishConfig": { - "access": "public" - }, "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/render": "workspace:*", diff --git a/server/typescript/packages/cli/README.md b/server/typescript/packages/cli/README.md index 30328e7c5f..6666548d1b 100644 --- a/server/typescript/packages/cli/README.md +++ b/server/typescript/packages/cli/README.md @@ -196,6 +196,17 @@ Flags: **Requirements for D1:** `wrangler` >= 3 on PATH (`npm i -D wrangler`). +### `meta schema` + +Prints the expected schema the metadata implies, without touching a database: the `CREATE` statements `meta migrate` would write for an empty database (default), or the neutral JSON document with `--as json`. Built the same way as `meta migrate`; reads no database and no snapshot, and writes nothing unless `--out ` is given. Use it to hand the schema to a native migration tool. + +Flags: +- `--dialect postgres|sqlite|d1` — default: `migrate.dialect`, else the dialect in `metaobjects.config.ts` +- `--as ddl|json` — default `ddl` +- `--out ` — write to a file instead of stdout + +The JSON document is described in [schema-snapshot-format.md](../../../../docs/features/schema-snapshot-format.md). + ## Configuration Two config files, by design: diff --git a/server/typescript/packages/cli/src/commands/schema.ts b/server/typescript/packages/cli/src/commands/schema.ts new file mode 100644 index 0000000000..a36ba7ea28 --- /dev/null +++ b/server/typescript/packages/cli/src/commands/schema.ts @@ -0,0 +1,174 @@ +// `meta schema` (1.3.0 T3) — print the schema the metadata expects, read-only. +// +// The expected schema is the store-neutral contract (ADR-0015 Amendment 2: each language's +// native migration tool is first-class, the Node engine the reference helper). Until this +// command it existed only inside `meta migrate`, which reaches it by diffing against a +// committed snapshot or a live database. This prints it on its own, built by the SAME path +// migrate's offline generate takes — the project's conventions, `migrate.scope` and the +// dependency exclusion, the views codegen-ts lowers projections and reports to — and diffed +// against an EMPTY schema, so the DDL is exactly what `meta migrate` would create for a new +// database. Nothing is read from a database or a snapshot, and nothing is written unless +// `--out` names a file. + +import { writeFile } from "node:fs/promises"; +import { resolve as resolvePath } from "node:path"; +import { buildProjectionViews } from "@metaobjectsdev/codegen-ts"; +import type { MetaobjectsGenConfig } from "@metaobjectsdev/codegen-ts"; +import { + buildExpectedSchemaWithProvenance, + DIALECTS, + emit, + isFkTargetNotUniqueError, + isUnknownSchemaConventionsError, + planOffline, + serializeSnapshot, + type Dialect, +} from "@metaobjectsdev/migrate-ts"; +import { loadMemory, resolveCollection, resolveConfigDir } from "@metaobjectsdev/sdk"; +import { parseSchemaArgs } from "../lib/args.js"; +import { collectionLoadOptions } from "../lib/collection-load-options.js"; +import { resolveMigrateDefaults } from "../lib/config.js"; +import { describeError } from "../lib/error-text.js"; +import { reportLoadError } from "../lib/load-error.js"; +import { + configNotLoadedWarning, + loadMemoryOptionsFrom, + loadMetaobjectsConfig, + RemovedNamingConfigError, + resolveGenConfigDir, +} from "../lib/load-metaobjects-config.js"; +import { log } from "../lib/log.js"; +import { importedOption, migrateScopeMismatch } from "../lib/migrate-scope.js"; +import { schemaBuildOptions } from "../lib/schema-build-options.js"; + +const PREFIX = "schema"; + +function isDialect(value: string): value is Dialect { + return (DIALECTS as readonly string[]).includes(value); +} + +export async function schemaCommand(args: string[], cwd: string): Promise { + let flags; + try { + flags = parseSchemaArgs(args); + } catch (err) { + log.error(`${PREFIX}: ${describeError(err)}`); + return 2; + } + + // The same two roots `meta migrate` resolves (see migrateCommand): `.metaobjects/config.json` + // governs the metadata and `migrate.*`, the nearest `metaobjects.config.ts` the providers. + const metaRoot = await resolveConfigDir(cwd); + const genRoot = resolveGenConfigDir(cwd, metaRoot); + + let genConfig: MetaobjectsGenConfig | undefined; + let loadOptions: ReturnType = {}; + try { + genConfig = await loadMetaobjectsConfig(genRoot); + loadOptions = loadMemoryOptionsFrom(genConfig); + } catch (err) { + if (err instanceof RemovedNamingConfigError) { + log.error(err.message); + return 2; + } + const warning = configNotLoadedWarning(genRoot, err, PREFIX); + if (warning !== undefined) log.warn(warning); + } + + const dialectName = flags.dialect ?? (await resolveMigrateDefaults(metaRoot)).dialect ?? genConfig?.dialect; + if (dialectName === undefined) { + log.error( + `${PREFIX}: no dialect — pass --dialect ${DIALECTS.join("|")}, or set migrate.dialect in .metaobjects/config.json or dialect in metaobjects.config.ts`, + ); + return 2; + } + if (!isDialect(dialectName)) { + log.error( + `${PREFIX}: unknown dialect '${dialectName}' — expected one of ${DIALECTS.join(", ")} ` + + `(MetaObjects does not own a MySQL schema; the generated Drizzle tables describe it)`, + ); + return 2; + } + const dialect = dialectName; + + let collection; + let metadata; + try { + collection = await resolveCollection(metaRoot); + metadata = await loadMemory(collection.configDir, { ...collectionLoadOptions(collection), ...loadOptions }); + } catch (err) { + reportLoadError(log, `${PREFIX}: failed to load metadata`, err); + return 1; + } + + let schema; + try { + schema = schemaBuildOptions(collection, genConfig); + } catch (err) { + if (!isUnknownSchemaConventionsError(err)) throw err; + log.error(`${PREFIX}: ${err.message}`); + return 2; + } + + const views = buildProjectionViews(metadata, { dialect }); + // A migrate.scope that matches nothing is refused, as `meta migrate` refuses it, rather than + // printing an empty schema that reads as "this model declares no tables". + const mismatch = migrateScopeMismatch( + collection, + () => buildExpectedSchemaWithProvenance(metadata, { ...schema, dialect, views }).provenance, + ); + if (mismatch !== undefined) { + log.error(`${PREFIX}: ${mismatch}`); + return 2; + } + + let plan; + try { + plan = await planOffline({ + ...schema, + metadata, + dialect, + snapshot: { tables: [], views: [] }, + views, + ...(collection.inMigrateScope !== undefined ? { inScope: collection.inMigrateScope } : {}), + ...importedOption(collection), + }); + } catch (err) { + // A model the schema builder refuses (a duplicate physical name, a foreign key onto a + // non-unique target) is refused here exactly as `meta migrate` refuses it. + log.error(`${PREFIX}: ${describeError(err)}`); + if (isFkTargetNotUniqueError(err)) { + log.error( + `${PREFIX}: declare an identity.secondary on the target with exactly the referenced fields, ` + + `or set migrate.foreignKeyTargets to "warn" in .metaobjects/config.json`, + ); + } + return 1; + } + + // The governed side: under migrate.scope or a dependency, the objects this project does not + // govern are left out, as `meta migrate` leaves them out of the DDL it writes. + const text = flags.as === "json" + ? serializeSnapshot(plan.expected) + : ddl(emit(plan.diff.changes, { dialect, expectedSchema: plan.expected, actualSchema: { tables: [], views: [] } }).up); + + if (flags.out !== undefined) { + const outPath = resolvePath(cwd, flags.out); + try { + await writeFile(outPath, text, "utf8"); + } catch (err) { + log.error(`${PREFIX}: cannot write ${outPath} — ${describeError(err)}`); + return 1; + } + log.info(`meta schema — wrote ${outPath}`); + } else { + process.stdout.write(text); + } + return 0; +} + +/** The DDL, ending in exactly one newline (an empty model prints nothing). */ +function ddl(up: string): string { + const trimmed = up.trimEnd(); + return trimmed === "" ? "" : `${trimmed}\n`; +} diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts index d53e903a10..b5598b85c4 100644 --- a/server/typescript/packages/cli/src/index.ts +++ b/server/typescript/packages/cli/src/index.ts @@ -49,6 +49,7 @@ COMMANDS: verify Drift gate — subverbs: --templates / --db / --codegen / --deps (bare = --codegen --templates) upgrade Rewrite retired metadata vocabulary (previews; --apply writes) prompt-snapshot Snapshot rendered template.* output; --check gates drift + schema Print the expected schema: DDL for a dialect, or --as json for the neutral document migrate Diff metadata vs live DB; emit migration SQL files --version, -v, -V Print version --help, -h Print this help @@ -469,6 +470,30 @@ an identity.reference whose @fields names a field the object does not have (inherited and overlaid fields count as present), and a field name declared more than once in one object's children list. Both load with no error. Warnings only — it can never fail the build. Opt out with --no-field-lint or META_NO_FIELD_LINT=1. +`, + schema: `meta schema — print the schema the metadata expects, changing nothing + +USAGE: + meta schema [flags] + +Builds the expected schema exactly as 'meta migrate' does (the same conventions, +migrate.scope and dependency exclusions, and the views projections and reports +declare) and prints it. It reads no database and no snapshot, and writes nothing +unless --out is given. The expected schema is the contract: a native migration +tool (EF Core, Flyway, Liquibase, Alembic, sqlx) can take this output as its +starting point, and 'meta migrate' is one way to apply it, not the only one. + +FLAGS: + --dialect postgres | sqlite | d1 (default: migrate.dialect in + .metaobjects/config.json, else the dialect in + metaobjects.config.ts). The DDL and the column types in the + JSON document are both dialect-specific. + --as ddl (default) prints CREATE statements; json prints the + neutral document, the snapshot format 'meta migrate' + commits (formatVersion 4, + docs/features/schema-snapshot-format.md) + --out Write to a file instead of stdout + --help, -h Print this help `, export: `meta export — flatten loaded metadata to one canonical JSON artifact @@ -802,6 +827,10 @@ export async function run(argv: string[]): Promise { const { promptSnapshotCommand } = await import("./commands/prompt-snapshot.js"); return promptSnapshotCommand(rest, cwd); } + case "schema": { + const { schemaCommand } = await import("./commands/schema.js"); + return schemaCommand(rest, cwd); + } case "migrate": { const { migrateCommand } = await import("./commands/migrate.js"); return migrateCommand(rest, cwd, undefined, fmt); diff --git a/server/typescript/packages/cli/src/lib/args.ts b/server/typescript/packages/cli/src/lib/args.ts index 4aa391b5ad..03f030cc2d 100644 --- a/server/typescript/packages/cli/src/lib/args.ts +++ b/server/typescript/packages/cli/src/lib/args.ts @@ -237,6 +237,40 @@ export function parseExportArgs(argv: string[]): ExportFlags { }; } +// --------------------------------------------------------------------------- +// schema flags (1.3.0 T3) +// --------------------------------------------------------------------------- + +export interface SchemaFlags { + /** postgres | sqlite | d1; undefined takes `migrate.dialect` from `.metaobjects/config.json`. */ + dialect: string | undefined; + /** `ddl` (the default) or `json`, the neutral document in the snapshot format. */ + as: string; + out: string | undefined; +} + +/** The flag table `parseSchemaArgs` parses. Exported so the help text can be gated against it. */ +export const SCHEMA_OPTIONS = { + dialect: { type: "string" }, + as: { type: "string", default: "ddl" }, + out: { type: "string" }, +} as const; + +export const SCHEMA_OUTPUTS = ["ddl", "json"] as const; + +export function parseSchemaArgs(argv: string[]): SchemaFlags { + const { values } = parseCommandArgs("schema", { + args: argv, + options: SCHEMA_OPTIONS, + strict: true, + allowPositionals: false, + }); + if (!(SCHEMA_OUTPUTS as readonly string[]).includes(values.as)) { + throw new Error(`--as takes ${SCHEMA_OUTPUTS.join(" or ")}, not '${values.as}'`); + } + return { dialect: values.dialect, as: values.as, out: values.out }; +} + // --------------------------------------------------------------------------- // fmt flags (#304) // --------------------------------------------------------------------------- diff --git a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap index 735baf8e22..b835d5cc58 100644 --- a/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap +++ b/server/typescript/packages/cli/test/__snapshots__/cli.test.ts.snap @@ -27,6 +27,7 @@ COMMANDS: verify Drift gate — subverbs: --templates / --db / --codegen / --deps (bare = --codegen --templates) upgrade Rewrite retired metadata vocabulary (previews; --apply writes) prompt-snapshot Snapshot rendered template.* output; --check gates drift + schema Print the expected schema: DDL for a dialect, or --as json for the neutral document migrate Diff metadata vs live DB; emit migration SQL files --version, -v, -V Print version --help, -h Print this help diff --git a/server/typescript/packages/cli/test/help-lists-every-flag.test.ts b/server/typescript/packages/cli/test/help-lists-every-flag.test.ts index d1c7330340..be1acf525c 100644 --- a/server/typescript/packages/cli/test/help-lists-every-flag.test.ts +++ b/server/typescript/packages/cli/test/help-lists-every-flag.test.ts @@ -30,6 +30,7 @@ import { INIT_OPTIONS, MIGRATE_OPTIONS, PROMPT_SNAPSHOT_OPTIONS, + SCHEMA_OPTIONS, VERIFY_OPTIONS, } from "../src/lib/args.js"; import { COMMAND_HELP } from "../src/index.js"; @@ -54,6 +55,7 @@ const COMMANDS: ReadonlyArray ["verify", VERIFY_OPTIONS], ["prompt-snapshot", PROMPT_SNAPSHOT_OPTIONS], ["migrate", MIGRATE_OPTIONS], + ["schema", SCHEMA_OPTIONS], ["eject", EJECT_OPTIONS], ["deps", DEPS_OPTIONS], ["generator", GENERATOR_OPTIONS], diff --git a/server/typescript/packages/cli/test/integration/schema.test.ts b/server/typescript/packages/cli/test/integration/schema.test.ts new file mode 100644 index 0000000000..5607568695 --- /dev/null +++ b/server/typescript/packages/cli/test/integration/schema.test.ts @@ -0,0 +1,177 @@ +/** + * `meta schema` (1.3.0 T3): print the expected schema, read-only. + * + * The oracle is the migration engine, not the command's own output: the DDL `meta schema` + * prints is executed against an EMPTY real SQLite database, and then `meta migrate --db` + * introspects that database and diffs it against the metadata. If the DDL left anything out + * (a column, the foreign key, the projection's view) or added anything, migrate proposes a + * change and writes a migration file. A schema that is exactly the expected one gives + * "no changes" and no file. + */ +import { describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createClient } from "@libsql/client"; +import { parseSnapshot, SNAPSHOT_FORMAT_VERSION } from "@metaobjectsdev/migrate-ts"; +import { run } from "../../src/index.js"; +import { declareScope, scaffold } from "./support/scope-fixture.js"; + +const META = JSON.stringify({ + "metadata.root": { + package: "acme", + children: [ + { + "object.entity": { + name: "Author", + children: [ + { "source.rdb": { name: "src", "@table": "authors" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "name", "@required": true, "@maxLength": 80 } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ], + }, + }, + { + "object.entity": { + name: "Book", + children: [ + { "source.rdb": { name: "src", "@table": "books" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "title", "@required": true } }, + { "field.long": { name: "authorId", "@required": true } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + { "identity.reference": { name: "authorRef", "@fields": ["authorId"], "@references": "Author" } }, + ], + }, + }, + { + "object.projection": { + name: "BookView", + children: [ + { "source.rdb": { name: "src", "@kind": "view", "@view": "v_books" } }, + { "field.long": { name: "id", extends: "acme::Book.id" } }, + { "field.string": { name: "title", extends: "acme::Book.title" } }, + { "identity.primary": { name: "pk", extends: "acme::Book.pk" } }, + ], + }, + }, + ], + }, +}); + +function project(config?: Record): string { + const repo = mkdtempSync(join(tmpdir(), "meta-schema-")); + mkdirSync(join(repo, "metaobjects"), { recursive: true }); + writeFileSync(join(repo, "metaobjects", "meta.books.json"), META, "utf8"); + if (config !== undefined) { + mkdirSync(join(repo, ".metaobjects"), { recursive: true }); + writeFileSync(join(repo, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, ...config }), "utf8"); + } + return repo; +} + +/** Every path under `dir`, relative, so a test can prove a run wrote nothing. */ +function tree(dir: string): string[] { + return readdirSync(dir, { recursive: true, encoding: "utf8" }).sort(); +} + +describe("meta schema", () => { + test("the sqlite DDL builds exactly the schema meta migrate expects: tables, foreign key and view", async () => { + const repo = project(); + const out = join(repo, "schema.sql"); + const dbUrl = `file:${join(repo, "local.db")}`; + try { + expect(await run(["schema", "--cwd", repo, "--dialect", "sqlite", "--out", out])).toBe(0); + const sql = readFileSync(out, "utf8"); + + const client = createClient({ url: dbUrl }); + await client.executeMultiple(sql); + const objects = await client.execute("SELECT name, type FROM sqlite_master WHERE type IN ('table','view')"); + const fks = await client.execute("PRAGMA foreign_key_list(books)"); + client.close(); + const byName = new Map(objects.rows.map((r) => [String(r.name), String(r.type)])); + expect(byName.get("authors")).toBe("table"); + expect(byName.get("books")).toBe("table"); + expect(byName.get("v_books")).toBe("view"); + expect(fks.rows.map((r) => [String(r.table), String(r.from), String(r.to)])).toEqual([["authors", "author_id", "id"]]); + + // The engine's own introspect-and-diff finds nothing to do, so writes no migration. + expect(await run(["migrate", "--from-db", "--cwd", repo, "--db", dbUrl, "--dialect", "sqlite", "--slug", "probe"])).toBe(0); + const migrations = join(repo, ".metaobjects", "migrations"); + // Each migration is a directory holding up.sql and down.sql, so look all the way down. + const written = existsSync(migrations) ? tree(migrations).filter((f) => f.endsWith(".sql")) : []; + expect(written).toEqual([]); + } finally { + rmSync(repo, { recursive: true, force: true }); + } + }, 30000); + + test("--as json is the neutral snapshot document, stable across runs, naming the same objects", async () => { + const repo = project(); + try { + const a = join(repo, "a.json"); + const b = join(repo, "b.json"); + expect(await run(["schema", "--cwd", repo, "--dialect", "postgres", "--as", "json", "--out", a])).toBe(0); + expect(await run(["schema", "--cwd", repo, "--dialect", "postgres", "--as", "json", "--out", b])).toBe(0); + const text = readFileSync(a, "utf8"); + expect(readFileSync(b, "utf8")).toBe(text); + expect((JSON.parse(text) as { formatVersion: number }).formatVersion).toBe(SNAPSHOT_FORMAT_VERSION); + const snapshot = parseSnapshot(text); + expect(snapshot.tables.map((t) => t.name).sort()).toEqual(["authors", "books"]); + expect(snapshot.views.map((v) => v.name)).toEqual(["v_books"]); + expect(snapshot.tables.find((t) => t.name === "books")?.columns.map((c) => c.name).sort()) + .toEqual(["author_id", "id", "title"]); + } finally { + rmSync(repo, { recursive: true, force: true }); + } + }); + + test("is read-only: no snapshot, no migration, no file of any kind without --out", async () => { + const repo = project({ migrate: { dialect: "postgres" } }); + try { + const before = tree(repo); + const proc = Bun.spawnSync(["bun", join(import.meta.dirname, "../../bin/meta.ts"), "schema", "--cwd", repo]); + expect(proc.exitCode).toBe(0); + // The dialect came from migrate.dialect: Postgres DDL, not SQLite. + const stdout = proc.stdout.toString(); + expect(stdout).toContain('CREATE TABLE "books"'); + expect(stdout).toContain("GENERATED BY DEFAULT AS IDENTITY"); + expect(tree(repo)).toEqual(before); + } finally { + rmSync(repo, { recursive: true, force: true }); + } + }); + + test("leaves out what migrate.scope does not govern, as meta migrate does", async () => { + const { repo } = scaffold("meta-schema-scope-"); + try { + declareScope(repo, ["acme::platform::**"]); + const out = join(repo, "schema.sql"); + expect(await run(["schema", "--cwd", repo, "--dialect", "sqlite", "--out", out])).toBe(0); + const sql = readFileSync(out, "utf8"); + expect(sql).toContain('CREATE TABLE "jobs"'); + expect(sql).not.toContain('"matches"'); + } finally { + rmSync(repo, { recursive: true, force: true }); + } + }); + + test("refuses, exit 2, a scope that matches nothing, no dialect, mysql, and an unknown --as", async () => { + const { repo } = scaffold("meta-schema-refuse-"); + try { + declareScope(repo, ["nobody::**"]); + expect(await run(["schema", "--cwd", repo, "--dialect", "sqlite"])).toBe(2); + } finally { + rmSync(repo, { recursive: true, force: true }); + } + const bare = project(); + try { + expect(await run(["schema", "--cwd", bare])).toBe(2); + expect(await run(["schema", "--cwd", bare, "--dialect", "mysql"])).toBe(2); + expect(await run(["schema", "--cwd", bare, "--dialect", "sqlite", "--as", "yaml"])).toBe(2); + } finally { + rmSync(bare, { recursive: true, force: true }); + } + }); +}); diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts index 34db514518..a13d9f922e 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-foreign-files.test.ts @@ -21,7 +21,12 @@ * from a stranger's, so the old, conservative verdict stands — the same * fail-closed default the content branch uses. */ -import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { describe, test, expect, beforeEach, afterEach, setDefaultTimeout } from "bun:test"; + +// Each test drives several in-process `meta gen` / `meta verify` runs over a real tree, which +// is well inside a second on an idle machine and was overrunning Bun's 5 s default on a loaded +// one, failing a different test each run. The budget is for the whole sequence. +setDefaultTimeout(30_000); import { cpSync, mkdtempSync, diff --git a/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts b/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts index c3922c70b9..59bbe87b7f 100644 --- a/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts +++ b/server/typescript/packages/cli/test/integration/verify-codegen-hand-edits.test.ts @@ -15,7 +15,12 @@ * not — the split exists so this question is answerable on a machine that did not * generate the output. */ -import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { describe, test, expect, beforeEach, afterEach, setDefaultTimeout } from "bun:test"; + +// Each test drives several in-process `meta gen` / `meta verify` runs over a real tree, which +// is well inside a second on an idle machine and was overrunning Bun's 5 s default on a loaded +// one, failing a different test each run. The budget is for the whole sequence. +setDefaultTimeout(30_000); import { cpSync, mkdtempSync, diff --git a/server/typescript/packages/cli/test/schema-out.test.ts b/server/typescript/packages/cli/test/schema-out.test.ts new file mode 100644 index 0000000000..3601d97d42 --- /dev/null +++ b/server/typescript/packages/cli/test/schema-out.test.ts @@ -0,0 +1,55 @@ +/** + * `meta schema --out ` — a path that cannot be written is a clean CLI error + * (exit 1, message naming the path), not an unhandled ENOENT stack trace. The + * parent directory is not created silently. + */ +import { describe, test, expect, afterAll } from "bun:test"; +import { mkdtemp, rm, mkdir, writeFile, readFile, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { schemaCommand } from "../src/commands/schema.js"; + +const dirs: string[] = []; +afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); + +const MODEL = JSON.stringify({ + "metadata.root": { + package: "acme::platform", + children: [{ + "object.entity": { + name: "Job", + children: [ + { "source.rdb": { name: "src", "@table": "jobs" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ], + }, + }], + }, +}); + +async function project(): Promise { + const root = await mkdtemp(join(tmpdir(), "schema-out-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.platform.json"), MODEL, "utf8"); + await mkdir(join(root, ".metaobjects"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1 }), "utf8"); + return root; +} + +describe("meta schema --out", () => { + test("a missing parent directory exits 1 without creating it", async () => { + const root = await project(); + const code = await schemaCommand(["--dialect", "sqlite", "--out", "missing/expected.sql"], root); + expect(code).toBe(1); + await expect(stat(join(root, "missing"))).rejects.toThrow(); + }); + + test("a writable path receives the DDL and exits 0", async () => { + const root = await project(); + const code = await schemaCommand(["--dialect", "sqlite", "--out", "expected.sql"], root); + expect(code).toBe(0); + expect(await readFile(join(root, "expected.sql"), "utf8")).toContain("CREATE TABLE"); + }); +}); diff --git a/server/typescript/packages/codegen-ts-react/src/templates/form-file.ts b/server/typescript/packages/codegen-ts-react/src/templates/form-file.ts index d829a4f1db..67f89ed8fa 100644 --- a/server/typescript/packages/codegen-ts-react/src/templates/form-file.ts +++ b/server/typescript/packages/codegen-ts-react/src/templates/form-file.ts @@ -549,7 +549,7 @@ ${control} (f) => viewForContext(f, VIEW_CONTEXT_FORM)?.subType === VIEW_SUBTYPE_IMAGE, ); const imageImports = hasImage - ? `import { Controller } from "react-hook-form";\nimport { ImageUpload } from "@metaobjectsdev/react";\n` + ? `import { Controller } from "react-hook-form";\nimport { ImageUpload } from "@metaobjectsdev/react/image-upload";\n` : ""; const literalImports = code` diff --git a/server/typescript/packages/codegen-ts-react/test/form-image.test.ts b/server/typescript/packages/codegen-ts-react/test/form-image.test.ts index 425a896659..1cda8e8593 100644 --- a/server/typescript/packages/codegen-ts-react/test/form-image.test.ts +++ b/server/typescript/packages/codegen-ts-react/test/form-image.test.ts @@ -128,9 +128,9 @@ describe("form controls — view.image dispatch", () => { const { root, doc } = await loadModel(); const out = renderFormFile(doc, ctxFor(root)); expect(out).toContain('import { Controller } from "react-hook-form"'); - // Specifically the ImageUpload specifier, not just any "@metaobjectsdev/react" - // import — useEntityForm's import from the same package is unconditional. - expect(out).toContain('import { ImageUpload } from "@metaobjectsdev/react"'); + // The ImageUpload specifier, on its own subpath because react-easy-crop is an optional + // peer; useEntityForm still comes from the package root, unconditionally. + expect(out).toContain('import { ImageUpload } from "@metaobjectsdev/react/image-upload"'); expect(out).toMatch(/from "@metaobjectsdev\/react"/); }); diff --git a/server/typescript/packages/codegen-ts/src/generator-registry.ts b/server/typescript/packages/codegen-ts/src/generator-registry.ts index ae8aa44706..fa554036c0 100644 --- a/server/typescript/packages/codegen-ts/src/generator-registry.ts +++ b/server/typescript/packages/codegen-ts/src/generator-registry.ts @@ -549,17 +549,17 @@ export const generatorRegistry: Record = { kind: "generator", layer: "capability", description: - "Per-entity typed record/call trace helpers (extract + buildLlmCallRow + persist; LlmCallBase-derived entities only).", + "Per-entity typed record/call trace helpers (extract + buildLlmCallRow + persist; LlmCallBase-derived entities only), plus the llm-call.ts call loop they use.", tier: "native", factory: () => traceHelperFile(), factoryExport: "traceHelperFile", options: "outDir?, target?", // ADR-0056: typed by the request/response value objects' OWN interfaces (entityFile()). requires: ["entity"], - // What the emitted `.trace.ts` imports. `ai-runtime` is reached only by the - // `call` half, which every loadable prompt gets (a prompt requires @textRef). + // What the emitted `.trace.ts` imports. The `call` half's call loop is + // `llm-call.ts`, written into the project by this generator, not a package (ADR-0024 + // Amendment 2). runtimePackages: [ - "@metaobjectsdev/ai-runtime", "@metaobjectsdev/metadata", "@metaobjectsdev/render", "@metaobjectsdev/runtime-ts", diff --git a/server/typescript/packages/codegen-ts/src/generators/trace-helper-file.ts b/server/typescript/packages/codegen-ts/src/generators/trace-helper-file.ts index 91f9ecebf7..2bbd0ec33f 100644 --- a/server/typescript/packages/codegen-ts/src/generators/trace-helper-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/trace-helper-file.ts @@ -14,7 +14,10 @@ import { type Generator, type GeneratorFactory, perEntity } from "../generator.j import { TRACE_HELPER_STABLE_NAME, extendsTraceAnchor, + LLM_CALL_SUPPORT_FILE, + renderLlmCallSupport, renderTraceHelper, + traceHelperCallsLlm, traceAnchorNodes, } from "../templates/trace-helper.js"; @@ -39,7 +42,11 @@ export const traceHelperFile = function traceHelperFile(opts?: TraceHelperOpts): if (!extendsTraceAnchor(entity, anchors)) return []; const path = `${dirPrefix}${entity.name}.trace.ts`; const content = renderTraceHelper(entity, ctx, path); - return content === undefined ? [] : [{ path, content }]; + if (content === undefined) return []; + // A call imports the call loop from a module beside it. Every helper that + // needs it emits the same bytes at the same path, and the runner keeps one copy. + if (!traceHelperCallsLlm(entity)) return [{ path, content }]; + return [{ path, content }, { path: `${dirPrefix}${LLM_CALL_SUPPORT_FILE}`, content: renderLlmCallSupport() }]; }), }; if (opts?.target) { diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index 79f17f5cd5..efd39ccbd8 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -357,7 +357,14 @@ export { renderRenderHelper } from "./templates/render-helper.js"; // (src/reference/trace-helper.ts) chooses which files to emit and where; the module body // stays in these composers. export { renderCallableFile, isCallableEntity } from "./templates/callable-file.js"; -export { renderTraceHelper, traceAnchorNodes, extendsTraceAnchor } from "./templates/trace-helper.js"; +export { + renderTraceHelper, + traceAnchorNodes, + extendsTraceAnchor, + traceHelperCallsLlm, + renderLlmCallSupport, + LLM_CALL_SUPPORT_FILE, +} from "./templates/trace-helper.js"; // Template-driven codegen (rc.12). Factory + framework Provider for adopters // who want to wire their own templateGenerator instances. The default diff --git a/server/typescript/packages/codegen-ts/src/reference/trace-helper.ts b/server/typescript/packages/codegen-ts/src/reference/trace-helper.ts index 0bbdd523e4..7008bf2a1f 100644 --- a/server/typescript/packages/codegen-ts/src/reference/trace-helper.ts +++ b/server/typescript/packages/codegen-ts/src/reference/trace-helper.ts @@ -9,14 +9,16 @@ // targets: the `ai` library's LLM-call trace. The emitted module calls // `@metaobjectsdev/runtime-ts` (ObjectManager, the trace row builders), // `@metaobjectsdev/render` (extract, render) and, for a renderable prompt, -// `@metaobjectsdev/ai-runtime` (runLlmCall). +// the call loop in `llm-call.ts`, which this generator writes beside it. // use-when: an entity extends a library's trace anchor (the `ai` library's // `LlmCallBase`) and nests a `template.prompt` with @payloadRef and // @responseRef, and you want a typed `record` — plus `call` // when the prompt carries @textRef — instead of hand-wiring extract + // buildLlmCallRow + persist at every call site. // emits: /.trace.ts per concrete trace entity whose nested prompt -// names both value objects; nothing for an entity that does not. +// names both value objects; nothing for an entity that does not. Plus one +// /llm-call.ts (`runLlmCall`, the `LlmClient` seam) when any helper +// has a `call`. // customize: which entities get a helper (the two gates below), the output directory // (`outDir`) and the file name. The module BODY comes from // `renderTraceHelper`, which `meta eject` copies beside this file @@ -33,7 +35,10 @@ import type { MetaData } from "@metaobjectsdev/metadata"; import { perEntity, type Generator, type GeneratorFactory } from "@metaobjectsdev/codegen-ts/engine"; import { extendsTraceAnchor, + LLM_CALL_SUPPORT_FILE, + renderLlmCallSupport, renderTraceHelper, + traceHelperCallsLlm, traceAnchorNodes, } from "../templates/trace-helper.js"; @@ -58,7 +63,11 @@ export const traceHelperFile = function traceHelperFile(opts?: TraceHelperOpts): if (!extendsTraceAnchor(entity, anchors)) return []; const path = `${dirPrefix}${entity.name}.trace.ts`; const content = renderTraceHelper(entity, ctx, path); - return content === undefined ? [] : [{ path, content }]; + if (content === undefined) return []; + // A call imports the call loop from a module beside it. Every helper that + // needs it emits the same bytes at the same path, and the runner keeps one copy. + if (!traceHelperCallsLlm(entity)) return [{ path, content }]; + return [{ path, content }, { path: `${dirPrefix}${LLM_CALL_SUPPORT_FILE}`, content: renderLlmCallSupport() }]; }), }; if (opts?.target) { diff --git a/server/typescript/packages/codegen-ts/src/templates/trace-helper.ts b/server/typescript/packages/codegen-ts/src/templates/trace-helper.ts index 7005a106a5..47167502bb 100644 --- a/server/typescript/packages/codegen-ts/src/templates/trace-helper.ts +++ b/server/typescript/packages/codegen-ts/src/templates/trace-helper.ts @@ -37,6 +37,7 @@ import { valueObjectImport, valueObjectImportLines } from "./value-object-import import { GENERATED_HEADER, GENERATED_EDIT_NOTE } from "../constants.js"; import { toPascalCase } from "../naming.js"; import { tphDiscriminatorPin } from "../tph.js"; +import { withExt } from "../render-context.js"; /** The generator's stable name — the key a library manifest declares its anchor under. */ export const TRACE_HELPER_STABLE_NAME = "trace-helper"; @@ -92,6 +93,181 @@ export function extendsTraceAnchor(obj: MetaObject, anchors: readonly MetaData[] return false; } +/** The call-loop module the trace helpers import, without its extension. */ +export const LLM_CALL_SUPPORT_MODULE = "llm-call"; +/** Its file name, written in the same directory as the `.trace.ts` modules. */ +export const LLM_CALL_SUPPORT_FILE = `${LLM_CALL_SUPPORT_MODULE}.ts`; + +/** + * Whether `renderTraceHelper` writes a `call` for this entity, and so imports the + * call loop: its nested prompt carries @textRef. The generator writes + * {@link LLM_CALL_SUPPORT_FILE} beside the helper exactly when this holds. + */ +export function traceHelperCallsLlm(entity: MetaObject): boolean { + // ADR-0039: resolving — the prompt and its @textRef may be inherited through extends. + const prompt = entity.children().find( + (c) => c.type === TYPE_TEMPLATE && c.subType === TEMPLATE_SUBTYPE_PROMPT, + ); + return prompt !== undefined && typeof prompt.attr(TEMPLATE_ATTR_TEXT_REF) === "string"; +} + +/** + * The project's call loop: the provider-neutral `LlmClient` seam, the injectable clock, + * ids and cost function, and `runLlmCall`, which times the call, never throws, and + * returns the base trace input the helper persists. + * + * Until 1.3.0 this was `@metaobjectsdev/ai-runtime`, a package the generated helper + * depended on. It is the same code, written into the project instead (ADR-0024 + * Amendment 2): the provider call stays bring-your-own behind `LlmClient`, and the + * module is the project's to edit. Its one import is the trace row type from + * `@metaobjectsdev/runtime-ts`, which the helper imports anyway. + */ +export function renderLlmCallSupport(): string { + return [ + `// ${GENERATED_HEADER} — ${GENERATED_EDIT_NOTE}`, + `//`, + `// The LLM call loop behind the generated call trace helpers. The provider call is`, + `// yours: implement LlmClient over your LLM library and pass it in. Nothing here talks to a`, + `// provider, keeps a rate table or retries.`, + ``, + `import type { LlmCallInput } from "@metaobjectsdev/runtime-ts";`, + ``, + `export interface LlmRequest {`, + ` /** The rendered prompt text. */`, + ` prompt: string;`, + ` /** gen_ai.request.model */`, + ` model: string;`, + ` /** Optional system prompt text. */`, + ` system?: string;`, + ` /** Provider params: temperature, max_tokens, top_p, ... */`, + ` params?: Record;`, + `}`, + ``, + `export interface LlmUsage {`, + ` /** gen_ai.usage.input_tokens */`, + ` inputTokens?: number;`, + ` /** gen_ai.usage.output_tokens */`, + ` outputTokens?: number;`, + `}`, + ``, + `export interface LlmCompletion {`, + ` /** Raw completion text, which the helper extracts the response from. */`, + ` body: string;`, + ` usage?: LlmUsage;`, + ` /** gen_ai.response.model (may differ from the request's model). */`, + ` model?: string;`, + ` /** The full wire request, stored as llmRequest (falls back to the LlmRequest). */`, + ` request?: unknown;`, + ` /** gen_ai.response.finish_reasons */`, + ` finishReason?: string;`, + `}`, + ``, + `/** The single-method, provider-neutral call seam. */`, + `export interface LlmClient {`, + ` complete(req: LlmRequest): Promise;`, + `}`, + ``, + `/** Wall clock in ms since the epoch, injectable so tests are deterministic. */`, + `export interface Clock {`, + ` now(): number;`, + `}`, + ``, + `/** Span and trace id source, injectable so tests are deterministic. */`, + `export interface IdGen {`, + ` next(): string;`, + `}`, + ``, + `export const systemClock: Clock = { now: () => Date.now() };`, + ``, + `export const uuidIds: IdGen = { next: () => crypto.randomUUID() };`, + ``, + `/**`, + ` * Maps (model, usage) to a cost in integer USD minor units (cents), or null when unknown.`, + ` * No rate table ships: supply your own from your LLM library's usage and your rates.`, + ` */`, + `export type CostFn = (model: string, usage: LlmUsage | undefined) => number | null;`, + ``, + `export interface RunLlmCallInput {`, + ` /** Discriminator / call identity. */`, + ` callType: string;`, + ` /** The already-rendered request sent to the client. */`, + ` request: LlmRequest;`, + ` /** An existing trace to attach to; a new trace id is generated when absent. */`, + ` traceId?: string;`, + ` parentSpanId?: string;`, + ` sessionId?: string;`, + `}`, + ``, + `export interface RunLlmCallDeps {`, + ` client: LlmClient;`, + ` cost?: CostFn;`, + ` clock?: Clock;`, + ` ids?: IdGen;`, + `}`, + ``, + `export interface RunLlmCallResult {`, + ` /** The base trace input, ready to persist: envelope, raw I/O and status. */`, + ` input: LlmCallInput;`, + ` /** The provider completion, or undefined when the client threw. */`, + ` completion?: LlmCompletion;`, + `}`, + ``, + `/**`, + ` * Make the call: generate ids, time it, call the client (a throw becomes an error status,`, + ` * never a rethrow) and compute the cost. Persists nothing and extracts nothing; the`, + ` * generated call does both.`, + ` */`, + `export async function runLlmCall(input: RunLlmCallInput, deps: RunLlmCallDeps): Promise {`, + ` const clock = deps.clock ?? systemClock;`, + ` const ids = deps.ids ?? uuidIds;`, + ``, + ` const spanId = ids.next();`, + ` const traceId = input.traceId ?? ids.next();`, + ` const t0 = clock.now();`, + ` const startedAt = new Date(t0).toISOString();`, + ``, + ` let completion: LlmCompletion | undefined;`, + ` let status: "ok" | "error" = "ok";`, + ` let errorDetail: string | null = null;`, + ` try {`, + ` completion = await deps.client.complete(input.request);`, + ` } catch (err) {`, + ` status = "error";`, + ` errorDetail = err instanceof Error ? err.message : String(err);`, + ` }`, + ` const latencyMs = clock.now() - t0;`, + ``, + ` // exactOptionalPropertyTypes: assign an optional only when it is defined.`, + ` const recInput: LlmCallInput = {`, + ` spanId,`, + ` traceId,`, + ` callType: input.callType,`, + ` startedAt,`, + ` latencyMs,`, + ` requestModel: input.request.model,`, + ` llmRequest: completion?.request ?? input.request,`, + ` llmResponseText: completion?.body ?? "",`, + ` status,`, + ` errorDetail,`, + ` };`, + ` if (input.request.system !== undefined) recInput.system = input.request.system;`, + ` if (input.parentSpanId !== undefined) recInput.parentSpanId = input.parentSpanId;`, + ` if (input.sessionId !== undefined) recInput.sessionId = input.sessionId;`, + ` if (completion?.model !== undefined) recInput.responseModel = completion.model;`, + ` if (completion?.usage?.inputTokens !== undefined) recInput.inputTokens = completion.usage.inputTokens;`, + ` if (completion?.usage?.outputTokens !== undefined) recInput.outputTokens = completion.usage.outputTokens;`, + ` if (completion?.finishReason !== undefined) recInput.finishReason = completion.finishReason;`, + ` if (completion !== undefined && deps.cost !== undefined) {`, + ` const c = deps.cost(completion.model ?? input.request.model, completion.usage);`, + ` if (c !== null) recInput.costMinor = c;`, + ` }`, + ``, + ` return completion !== undefined ? { input: recInput, completion } : { input: recInput };`, + `}`, + ``, + ].join("\n"); +} + /** * Render the `.trace.ts` module for one trace entity, or `undefined` when the * entity carries nothing to type a helper by: no nested template.prompt, a prompt @@ -204,6 +380,9 @@ export function renderTraceHelper(entity: MetaObject, ctx: GenContext, outPath: ...valueObjectImportLines([requestImport, responseImport]), ]; if (renderable) { + // The call loop is the project's own module, written beside this one by the same + // generator (LLM_CALL_SUPPORT_FILE), so the helper imports nothing that is not an + // ordinary published package (ADR-0024 Amendment 2). importLines.push( `import {`, ` runLlmCall,`, @@ -214,7 +393,7 @@ export function renderTraceHelper(entity: MetaObject, ctx: GenContext, outPath: ` type CostFn,`, ` type Clock,`, ` type IdGen,`, - `} from "@metaobjectsdev/ai-runtime";`, + `} from "${withExt(`./${LLM_CALL_SUPPORT_MODULE}`, extStyle)}";`, ); } @@ -275,7 +454,7 @@ export function renderTraceHelper(entity: MetaObject, ctx: GenContext, outPath: ` const base = buildLlmCallRow(${recordBuildArg});`, ` const row = { ...base, voRequest: input.llmRequest, voResponse: failed ? null : outcome.data };`, ` await persistLlmCallRow(new LlmCallDbRecorder(om, "${entityName}"), row, opts?.redact ? { redact: opts.redact } : undefined);`, - ` return { status, errorDetail, voResponse: failed ? null : (outcome.data as ${responseType}) };`, + ` return { status, errorDetail, voResponse: failed ? null : (outcome.data as unknown as ${responseType}) };`, `}`, ``, ]; @@ -339,7 +518,7 @@ export function renderTraceHelper(entity: MetaObject, ctx: GenContext, outPath: ` status = "error";`, ` errorDetail = unusable;`, ` } else {`, - ` voResponse = outcome.data as ${responseType};`, + ` voResponse = outcome.data as unknown as ${responseType};`, ` }`, ` }`, ` const row = { ...buildLlmCallRow({ ...recInput, status, errorDetail }), voRequest: payload, voResponse };`, diff --git a/server/typescript/packages/codegen-ts/test/generators/trace-helper-anchor.test.ts b/server/typescript/packages/codegen-ts/test/generators/trace-helper-anchor.test.ts index af908c0cd2..b8849808e9 100644 --- a/server/typescript/packages/codegen-ts/test/generators/trace-helper-anchor.test.ts +++ b/server/typescript/packages/codegen-ts/test/generators/trace-helper-anchor.test.ts @@ -78,7 +78,8 @@ async function emitCount( ...(opts.libraries !== undefined ? { libraries: opts.libraries } : {}), warn: () => {}, } as GenContext; - return (await traceHelperFile().generate(ctx)).length; + // The helpers only: the llm-call.ts support module rides along with any renderable one. + return (await traceHelperFile().generate(ctx)).filter((f) => f.path.endsWith(".trace.ts")).length; } const AI = [libraryManifests()["ai"]!]; diff --git a/server/typescript/packages/codegen-ts/test/generators/trace-helper-response-format.test.ts b/server/typescript/packages/codegen-ts/test/generators/trace-helper-response-format.test.ts index fed4d1c0c7..c6854cecbb 100644 --- a/server/typescript/packages/codegen-ts/test/generators/trace-helper-response-format.test.ts +++ b/server/typescript/packages/codegen-ts/test/generators/trace-helper-response-format.test.ts @@ -74,8 +74,9 @@ function ctxFor(root: Awaited>): GenContext { async function emit(promptAttrs: Record): Promise { const root = await loadRoot(promptAttrs); const files = await traceHelperFile().generate(ctxFor(root)); - expect(files.length).toBe(1); - return files[0]!.content; + // One helper, plus the call loop its call imports (every prompt here has @textRef). + expect(files.map((f) => f.path).sort()).toEqual(["ApiCall.trace.ts", "llm-call.ts"].sort()); + return files.find((f) => f.path.endsWith(".trace.ts"))!.content; } describe("trace helper — the reply's syntax comes from @responseFormat (ADR-0053)", () => { diff --git a/server/typescript/packages/codegen-ts/test/trace-helper-llm-call.test.ts b/server/typescript/packages/codegen-ts/test/trace-helper-llm-call.test.ts new file mode 100644 index 0000000000..ba1b93a176 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/trace-helper-llm-call.test.ts @@ -0,0 +1,229 @@ +// The trace helper's call loop is written into the project (1.3.0 T10b, ADR-0024 Amendment 2). +// +// Until 1.3.0 the generated `call` imported `runLlmCall` and the `LlmClient` seam from +// `@metaobjectsdev/ai-runtime`, a package the project had to install. The `trace-helper` +// generator now writes the same loop as `llm-call.ts` beside the helpers, so generated code +// depends only on the ordinary published packages it already imported. +// +// Proven three ways, all against the generated tree: +// 1. it compiles with the real TypeScript compiler, and the program never reaches the +// ai-runtime package's files; +// 2. the generated `runLlmCall` behaves as ai-runtime's did — the expectations are the ones +// `ai-runtime/test/call-loop.test.ts` held that package to; +// 3. the generated `call` renders, calls, extracts and persists one typed row. + +import { describe, test, expect, setDefaultTimeout } from "bun:test"; +import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { join, sep } from "node:path"; +import ts from "typescript"; +import { MetaDataLoader, InMemoryStringSource, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; +import { librarySources } from "@metaobjectsdev/metadata/library"; +import { entityFile } from "../src/generators/entity-file.js"; +import { traceHelperFile } from "../src/generators/trace-helper-file.js"; +import { makeRenderContext } from "../src/render-context.js"; +import { buildPkMap } from "../src/pk-resolver.js"; +import { buildRelationMap } from "../src/relation-resolver.js"; +import type { EmittedFile, GenContext } from "../src/generator.js"; + +setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); + +const MODEL = { + "metadata.root": { + package: "app::ops", + children: [ + { "object.value": { name: "AskVO", children: [{ "field.string": { name: "question", "@required": true } }] } }, + { "object.value": { name: "AnswerVO", children: [{ "field.string": { name: "answer", "@required": true } }] } }, + { + "object.entity": { + name: "ApiCall", + extends: "metaobjects::ai::LlmCallBase", + children: [ + { "source.rdb": { "@table": "api_call", "@role": "primary" } }, + { "identity.primary": { name: "id", "@fields": ["traceId"] } }, + { + "template.prompt": { + name: "AskPrompt", + "@payloadRef": "AskVO", + "@responseRef": "AnswerVO", + "@textRef": "p/ask", + "@format": "text", + }, + }, + ], + }, + }, + ], + }, +}; + +async function loadModel(): Promise { + const res = await new MetaDataLoader().load([ + ...librarySources(["ai"]), + new InMemoryStringSource(JSON.stringify(MODEL), { id: "meta.json", format: "json" }), + ]); + expect(res.errors.map((e) => e.message)).toEqual([]); + return res.root; +} + +async function generate(root: MetaRoot, dir: string): Promise { + const renderContext = makeRenderContext({ + outputLayout: "flat", + dialect: "postgres", + loadedRoot: root, + outDir: dir, + dbImport: "./db", + pkMap: buildPkMap(root), + relationMap: buildRelationMap(root), + }); + const ctx = (g: { filter?: (e: MetaObject) => boolean }): GenContext => ({ + entities: root.objects(), + loadedRoot: root, + matches: (e) => g.filter?.(e) ?? true, + projectRoot: dir, + config: { outputLayout: "flat", outDir: dir, extStyle: "none", dbImport: "./db", dialect: "postgres" } as never, + renderContext, + warn: () => {}, + }); + const generators = [entityFile({ allowlists: false }), traceHelperFile()]; + return (await Promise.all(generators.map((g) => g.generate(ctx(g))))).flat(); +} + +/** Generate into a fresh directory beside this test (so the workspace packages resolve), run `body`, remove it. */ +async function withTree(body: (dir: string, root: MetaRoot, files: EmittedFile[]) => Promise): Promise { + const root = await loadModel(); + const dir = mkdtempSync(join(import.meta.dir, "tmp-trace-llm-call-")); + try { + const files = await generate(root, dir); + for (const f of files) writeFileSync(join(dir, f.path), f.content); + return await body(dir, root, files); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +/** The generated `runLlmCall`, typed loosely: the compile test above is what checks its types. */ +type RunLlmCall = ( + input: { callType: string; request: { prompt: string; model: string }; traceId?: string }, + deps: Record, +) => Promise<{ input: Record; completion?: { body: string } }>; + +describe("trace-helper writes its call loop into the project", () => { + test("the helper and llm-call.ts compile, and the program never reaches the ai-runtime package", async () => { + await withTree(async (dir, _root, files) => { + const paths = files.map((f) => f.path); + expect(paths).toContain("ApiCall.trace.ts"); + expect(paths).toContain("llm-call.ts"); + // A caller typed against the generated surface only. + writeFileSync( + join(dir, "caller.ts"), + [ + `import { callApiCall } from "./ApiCall.trace";`, + `import type { LlmClient, CostFn } from "./llm-call";`, + `declare const deps: Omit[1], "client" | "cost">;`, + `const client: LlmClient = { complete: async (req) => ({ body: req.prompt }) };`, + `const cost: CostFn = () => 1;`, + `export const run = () => callApiCall({ question: "why" }, { ...deps, client, cost });`, + ].join("\n"), + ); + const program = ts.createProgram( + [...paths, "caller.ts"].map((p) => join(dir, p)), + { + strict: true, + exactOptionalPropertyTypes: true, + noEmit: true, + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + skipLibCheck: true, + lib: ["lib.es2022.d.ts", "lib.dom.d.ts"], + }, + ); + const diagnostics = ts.getPreEmitDiagnostics(program).map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")); + expect(diagnostics).toEqual([]); + const aiRuntime = `${sep}ai-runtime${sep}`; + expect(program.getSourceFiles().map((f) => f.fileName).filter((f) => f.includes(aiRuntime))).toEqual([]); + }); + }); + + test("runLlmCall behaves as ai-runtime's did: ids, latency, cost, a supplied trace, a client that throws", async () => { + await withTree(async (dir) => { + const mod = (await import(join(dir, "llm-call.ts"))) as { runLlmCall: RunLlmCall }; + let t = 1000; + const clock = { now: () => (t += 500) }; + let n = 0; + const ids = { next: () => `id${++n}` }; + const client = { + async complete(req: { model: string }) { + return { body: `{"verdict":"ok"}`, model: req.model, usage: { inputTokens: 10, outputTokens: 20 } }; + }, + }; + + const ok = await mod.runLlmCall({ callType: "Verdict", request: { prompt: "P", model: "gpt-4o-mini" } }, { client, clock, ids, cost: () => 75 }); + expect(ok.input.spanId).toBe("id1"); + expect(ok.input.traceId).toBe("id2"); + expect(ok.input.latencyMs).toBe(500); + expect(ok.input.startedAt).toBe(new Date(1500).toISOString()); + expect(ok.input.status).toBe("ok"); + expect(ok.input.requestModel).toBe("gpt-4o-mini"); + expect(ok.input.inputTokens).toBe(10); + expect(ok.input.outputTokens).toBe(20); + expect(ok.input.costMinor).toBe(75); + expect(ok.input.llmResponseText).toBe(`{"verdict":"ok"}`); + expect(ok.completion?.body).toBe(`{"verdict":"ok"}`); + + const noCost = await mod.runLlmCall({ callType: "X", request: { prompt: "p", model: "m" } }, { client }); + expect("costMinor" in noCost.input).toBe(false); + + n = 0; + const kept = await mod.runLlmCall({ callType: "V", request: { prompt: "P", model: "m" }, traceId: "T-EXIST" }, { client, ids }); + expect(kept.input.traceId).toBe("T-EXIST"); + expect(kept.input.spanId).toBe("id1"); + + const thrown = await mod.runLlmCall( + { callType: "V", request: { prompt: "P", model: "m" } }, + { client: { complete: async () => { throw new Error("boom"); } } }, + ); + expect(thrown.input.status).toBe("error"); + expect(thrown.input.errorDetail).toContain("boom"); + expect(thrown.completion).toBeUndefined(); + }); + }); + + test("call renders the prompt, calls the client, and persists one typed row", async () => { + await withTree(async (dir, root) => { + const trace = (await import(join(dir, "ApiCall.trace.ts"))) as { + callApiCall: (payload: { question: string }, deps: Record) => Promise<{ status: string; errorDetail: string | null; voResponse: unknown }>; + }; + const created: Array<{ entity: string; row: Record }> = []; + const om = { create: async (entity: string, row: Record) => { created.push({ entity, row }); return row; } }; + const prompts: string[] = []; + const responseMo = root.findObject("app::ops::AnswerVO"); + expect(responseMo).toBeDefined(); + let n = 0; + const result = await trace.callApiCall( + { question: "why" }, + { + om, + responseMo, + client: { complete: async (req: { prompt: string }) => { prompts.push(req.prompt); return { body: `{"answer":"42"}` }; } }, + provider: { resolve: (ref: string) => (ref === "p/ask" ? "Q: {{question}}" : undefined) }, + model: "m", + ids: { next: () => `id${++n}` }, + cost: () => 3, + }, + ); + expect(prompts).toEqual(["Q: why"]); + expect(result).toEqual({ status: "ok", errorDetail: null, voResponse: { answer: "42" } }); + expect(created.length).toBe(1); + expect(created[0]!.entity).toBe("ApiCall"); + const row = created[0]!.row; + expect(row.callType).toBe("ApiCall"); + expect(row.spanId).toBe("id1"); + expect(row.traceId).toBe("id2"); + expect(row.costMinor).toBe(3); + expect(row.voRequest).toEqual({ question: "why" }); + expect(row.voResponse).toEqual({ answer: "42" }); + }); + }); +}); diff --git a/server/typescript/packages/forge/README.md b/server/typescript/packages/forge/README.md deleted file mode 100644 index 37b29b253c..0000000000 --- a/server/typescript/packages/forge/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# @metaobjectsdev/forge — private, incubating - -**Not published to npm. Not part of the public API. Do not depend on this.** - -This package is a reserved slot, not a shipped capability. `src/index.ts` exports -nothing today (`export {}`); the agent-docs generator that once lived here moved -to [`@metaobjectsdev/sdk`](../sdk/) (`@metaobjectsdev/sdk/agent-docs`), which is -where the AI-assistant context surfaces are generated from now. - -It is kept as the intended home for the AI-collaboration tier that has not been -built yet — the MCP server exposing declared prompts and tools (the one remaining -library-side piece of the prompt pillar, see [`spec/roadmap.md`](../../../../spec/roadmap.md)), -a Claude Code hooks installer, and `forge ingest` / `audit` / `serve` / `capture` -commands. The long-term plan is to carve that tier out to its own repository, so -nothing here should accumulate dependencies from the published packages. - -If you are looking for: - -- **AI-assistant context files** (`.metaobjects/AGENTS.md` and the `metaobjects-*` - skills) → `meta agent-docs`, implemented in - `@metaobjectsdev/sdk`. -- **Prompt construction** (declared payloads, deterministic render, drift checks) - → [`docs/features/templates-and-payloads.md`](../../../../docs/features/templates-and-payloads.md). diff --git a/server/typescript/packages/forge/package.json b/server/typescript/packages/forge/package.json deleted file mode 100644 index 8c80c0a77c..0000000000 --- a/server/typescript/packages/forge/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "@metaobjectsdev/forge", - "version": "0.1.0", - "private": true, - "type": "module", - "main": "./dist/index.js", - "types": "./src/index.ts", - "exports": { - ".": { - "bun": "./src/index.ts", - "types": "./src/index.ts", - "default": "./dist/index.js" - } - }, - "files": ["dist", "src"], - "scripts": { - "build": "tsc -p tsconfig.json", - "typecheck": "tsc -p tsconfig.typecheck.json" - }, - "devDependencies": { - "bun-types": "latest", - "typescript": "^5.6.0" - }, - "description": "AI-collaboration capabilities for the MetaObjects standard" -} diff --git a/server/typescript/packages/forge/src/index.ts b/server/typescript/packages/forge/src/index.ts deleted file mode 100644 index 13875b92c1..0000000000 --- a/server/typescript/packages/forge/src/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -// @metaobjectsdev/forge — AI-collaboration capabilities (unpublished, repo-internal). -// -// The agent-docs generator moved to @metaobjectsdev/sdk/agent-docs (H7a). This -// package is retained for the future MCP server, Claude Code hooks installer, -// and `forge ingest`/`audit`/`serve`/`capture` commands, and will carve out to -// a separate repo per the H1 polyglot design. It is NOT published to npm. -export {}; diff --git a/server/typescript/packages/forge/tsconfig.json b/server/typescript/packages/forge/tsconfig.json deleted file mode 100644 index a5c0be6a1a..0000000000 --- a/server/typescript/packages/forge/tsconfig.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "dist" - }, - "include": ["src/**/*"], - "exclude": ["test", "dist", "node_modules"] -} diff --git a/server/typescript/packages/forge/tsconfig.typecheck.json b/server/typescript/packages/forge/tsconfig.typecheck.json deleted file mode 100644 index 4d5d9bd870..0000000000 --- a/server/typescript/packages/forge/tsconfig.typecheck.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "noEmit": true, - "rootDir": "." - }, - "include": ["src/**/*", "test/**/*"], - "exclude": ["dist", "node_modules"] -} diff --git a/server/typescript/packages/integration-tests/package.json b/server/typescript/packages/integration-tests/package.json index 0a0a53eadf..ed5d398a69 100644 --- a/server/typescript/packages/integration-tests/package.json +++ b/server/typescript/packages/integration-tests/package.json @@ -2,7 +2,7 @@ "name": "@metaobjectsdev/integration-tests", "version": "0.0.0", "private": true, - "description": "Cross-language persistence conformance — TS runner against fixtures/persistence-conformance/. On-demand only (requires Docker).", + "description": "Cross-language persistence conformance \u2014 TS runner against fixtures/persistence-conformance/. On-demand only (requires Docker).", "type": "module", "scripts": { "test": "bun test", @@ -15,7 +15,6 @@ "oracle": "bun run src/oracle-cli.ts" }, "dependencies": { - "@metaobjectsdev/ai-runtime": "workspace:*", "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/migrate-ts": "workspace:*", diff --git a/server/typescript/packages/sdk/FORGE-METADATA.md b/server/typescript/packages/sdk/FORGE-METADATA.md index 1d7e15f3bb..c8b1d7501b 100644 --- a/server/typescript/packages/sdk/FORGE-METADATA.md +++ b/server/typescript/packages/sdk/FORGE-METADATA.md @@ -2,6 +2,12 @@ > **Note (2026-05-21):** This doc predates the H1 monorepo migration and the 2026-05-15 canonical-format change. Pending a deeper rewrite: the JSON examples below still use the OLD `{ "": { "subType": "..." } }` form (current canonical is fused-key `{ ".": {...} }`), and the `.meta/memory/` directory layout is now `.metaobjects/memory/`. The `@forge*` attribute names and the memory record types (`decision`, `principle`, `convention`, `glossary`, `failure`) are still accurate. See git history for full original wording. +> **Where this vocabulary lives.** `@metaobjectsdev/sdk` ships and registers it: `forgeTypesProvider` +> (`src/forge-types.ts`) for a provider list, `registerForgeTypes(registry)` for a registry you build +> yourself. "Forge" is only the name of the vocabulary and its `@forge*` prefix. The empty, private +> `@metaobjectsdev/forge` package that once reserved the name was removed in 1.3.0; nothing here +> depends on it. + This doc describes how `@metaobjectsdev/sdk` extends the [metaobjects metamodel](../metadata/METAMODEL.md) with provenance attributes and descriptive memory types. If you're authoring memory `.json` files for an SDK-driven project, read this *and* `METAMODEL.md`. > **For agentic assistants:** the metaobjects rules in METAMODEL.md apply unchanged here — attribute uniqueness, inline-vs-child equivalence, `extends`/overlay semantics, package paths. This doc only adds the memory-specific names. diff --git a/spec/decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md b/spec/decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md index c2df6d7e39..839b584a14 100644 --- a/spec/decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md +++ b/spec/decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md @@ -1,6 +1,6 @@ # ADR-0024 — AI-trace scope: the typed trace + recorder is the standard; the LLM caller is bring-your-own -**Status:** Accepted (2026-06-06); **amended 2026-06-07** — see Amendment below. +**Status:** Accepted (2026-06-06); **amended 2026-06-07** (the first amendment below) and **2026-11-21** (Amendment 2). **Deciders:** human (project owner) + Claude **Relates to:** ADR-0020 (codegen tiering — native per-port vs. language-neutral), ADR-0023 (strict metadata provenance), and the AI LLM-trace design docs (`docs/superpowers/specs/2026-06-02-ai-llm-call-trace-persistence-design.md`, `2026-06-05-ai-runtime-call-loop-and-recorders-design.md`, `2026-06-05-ai-trace-1c-shared-table-sti-design.md`). @@ -30,6 +30,37 @@ Everything else in this ADR stands: the typed-trace data model, the recorder sea and STI all remain. Only the derivation mechanism + the `preFreeze` hook are gone. (Shipped: Python `378db17f`, Java `7ce05527`, TS+C#+Kotlin `7d6552c7`.) +## Amendment 2 (2026-11-21) — the call glue is generated into the project; `ai-runtime` is no longer published + +The decision put the vendor-neutral call glue (`LlmClient`, `runLlmCall`, `callLlm`) in KEEP +and shipped it as the npm package `@metaobjectsdev/ai-runtime`, which the generated +`call` imported. That made a 120-line loop a dependency every adopter installed and a +package the project published in lockstep, for code an adopter is expected to own anyway: the +`LlmClient` it plugs in is theirs, and so is how a call is timed and costed. + +**Revised rule:** the call glue is still owned and kept, but it is **generated**, not +depended on. The `trace-helper` generator writes `llm-call.ts` beside the +`.trace.ts` modules whenever a helper has a `call`: the `LlmClient` seam, +the injectable `Clock`, `IdGen` and `CostFn`, and `runLlmCall`, with the same behaviour the +package had. Generated trace code therefore imports only the ordinary published packages it +already used (`runtime-ts`, `render`, `metadata`), which is what this project promises of +generated code. The module is the project's to edit, and `meta eject trace-helper` owns the +generator that writes it. + +`@metaobjectsdev/ai-runtime` is `private` from 1.3.0 and leaves the publish set +(`scripts/publish-set.mjs`). Its last published version, 1.2.3, stays on the registry for +projects that have not regenerated. The package stays in the repository as source: its +`callLlm`, `CompositeRecorder` and the optional Langfuse and OpenTelemetry recorders are small +and are reference code to copy, not a supported dependency. + +Nothing else changes. The provider call stays bring-your-own behind `LlmClient`, no rate table +ships, and the typed-trace data model and recorder seam are as above. The other ports were +never on this package: their call glue is per-port already (ADR-0020 Tier 1). + +Upgrading: regenerate. A project's `.trace.ts` now imports `./llm-call`, and the +project can drop `@metaobjectsdev/ai-runtime` from its dependencies. Code that imported +`LlmClient` or `runLlmCall` from the package imports them from the generated `llm-call.ts`. + ## Context The AI LLM-trace stack shipped TypeScript-first across four arcs (#1 shipped `LlmCallBase` metadata + loader `libraries` opt-in; #1b `@responseRef` + `deriveTraceFields` + `record`; #2/#3 `@metaobjectsdev/ai-runtime` = `LlmClient` seam + `callLlm` + `builtinCost` + Composite/Langfuse/OTel recorders + `AnthropicClient`/`OpenAIClient` + `call`; #1c shared-table STI via TPH). diff --git a/spec/roadmap.md b/spec/roadmap.md index 1963f1e518..373fb8151b 100644 --- a/spec/roadmap.md +++ b/spec/roadmap.md @@ -382,7 +382,7 @@ _(FR-032 was developed under the working number "FR-026" — see commit history; ### Active -- **AI LLM-call trace persistence — cross-port rollout.** A metaobjects-native typed-trace store: each LLM call is persisted in the adopter's own DB with request/response as **typed value objects** (the same payload projection the prompt pillar declares + drift-checks), the one thing blob-only observability tools (Langfuse/Helicone/OTel) structurally can't do. **Scope locked by [ADR-0024](decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md):** MetaObjects owns the typed trace + recorder seam + the vendor-NEUTRAL call glue; the provider call + pricing are **bring-your-own** (plug the stack's LLM library — Vercel AI SDK / LiteLLM / Spring AI — behind the one-method `LlmClient`). **Shipped in TypeScript** (the reference port): shipped `library/ai/llm-call.yaml` (`LlmCallBase`) + opt-in `libraries` loader; the recorder (`recordLlmCall`, never-throws, redaction seam) + `buildLlmCallRow` whose key set is gated == `LlmCallBase`'s fields; `deriveTraceFields` (typed `voRequest`/`voResponse` jsonb columns derived from a nested `template.prompt`'s `@payloadRef`/`@responseRef`); generated `record`/`call` (extract + persist base + typed in one row); `@metaobjectsdev/ai-runtime` (`LlmClient` seam, `runLlmCall`, `callLlm`, `CompositeRecorder` + optional `LangfuseRecorder`/`OtelRecorder` exporters); shared-table STI (`@discriminator`/`@discriminatorValue`, reuses FR-017 TPH). **Cross-port (P3) in progress, JVM first:** the Java metamodel slice shipped (`@responseRef` on `template.prompt` + `template.*` admitted as `object.entity` children + a `TS_PILOT_VOCAB` registry-manifest exclusion; `ai-trace-prompt-nested` + `ai-trace-sti` un-ledgered in Java). Remaining: the Java recording half (OMDB recorder + the `deriveTraceFields` loader pre-pass + `record` Spring codegen + a persistence round-trip), then Python → C# → Kotlin, then the **atomic carve-out close** (register `@responseRef` in every port + remove `TsPilotVocab` from all ports + add it to `expected-registry.json`). Phased plan: `docs/superpowers/plans/2026-06-06-ai-trace-descope-and-cross-port.md`. +- **AI LLM-call trace persistence — cross-port rollout.** A metaobjects-native typed-trace store: each LLM call is persisted in the adopter's own DB with request/response as **typed value objects** (the same payload projection the prompt pillar declares + drift-checks), the one thing blob-only observability tools (Langfuse/Helicone/OTel) structurally can't do. **Scope locked by [ADR-0024](decisions/ADR-0024-ai-trace-scope-and-llm-caller-boundary.md):** MetaObjects owns the typed trace + recorder seam + the vendor-NEUTRAL call glue; the provider call + pricing are **bring-your-own** (plug the stack's LLM library — Vercel AI SDK / LiteLLM / Spring AI — behind the one-method `LlmClient`). **Shipped in TypeScript** (the reference port): shipped `library/ai/llm-call.yaml` (`LlmCallBase`) + opt-in `libraries` loader; the recorder (`recordLlmCall`, never-throws, redaction seam) + `buildLlmCallRow` whose key set is gated == `LlmCallBase`'s fields; `deriveTraceFields` (typed `voRequest`/`voResponse` jsonb columns derived from a nested `template.prompt`'s `@payloadRef`/`@responseRef`); generated `record`/`call` (extract + persist base + typed in one row); the `LlmClient` seam and `runLlmCall` (shipped as `@metaobjectsdev/ai-runtime` through 1.2; since 1.3.0 written into the project as `llm-call.ts` by the `trace-helper` generator, ADR-0024 Amendment 2, with `callLlm`, `CompositeRecorder` and the Langfuse/OTel recorders kept as reference source); shared-table STI (`@discriminator`/`@discriminatorValue`, reuses FR-017 TPH). **Cross-port (P3) in progress, JVM first:** the Java metamodel slice shipped (`@responseRef` on `template.prompt` + `template.*` admitted as `object.entity` children + a `TS_PILOT_VOCAB` registry-manifest exclusion; `ai-trace-prompt-nested` + `ai-trace-sti` un-ledgered in Java). Remaining: the Java recording half (OMDB recorder + the `deriveTraceFields` loader pre-pass + `record` Spring codegen + a persistence round-trip), then Python → C# → Kotlin, then the **atomic carve-out close** (register `@responseRef` in every port + remove `TsPilotVocab` from all ports + add it to `expected-registry.json`). Phased plan: `docs/superpowers/plans/2026-06-06-ai-trace-descope-and-cross-port.md`. ### Planned diff --git a/tsconfig.scripts.json b/tsconfig.scripts.json index bde36e2df4..5017d91fd0 100644 --- a/tsconfig.scripts.json +++ b/tsconfig.scripts.json @@ -96,12 +96,6 @@ "@metaobjectsdev/docs-site/*": [ "./server/typescript/packages/docs-site/src/*" ], - "@metaobjectsdev/forge": [ - "./server/typescript/packages/forge/src/index.ts" - ], - "@metaobjectsdev/forge/*": [ - "./server/typescript/packages/forge/src/*" - ], "@metaobjectsdev/integration-tests": [ "./server/typescript/packages/integration-tests/src/index.ts" ],