From c2f0da72642899f352a76125b191930b78c53a7a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 20:09:05 -0500 Subject: [PATCH 01/35] fix(ci): start a local CI lane only when memory allows; the SQLite/D1 report corpus boots once per suite The gate's test step on PR 645 kept failing in ways that passed when re-run in the foreground. Two causes, both fixed here. 1. The C# 'Test host process crashed' and the SIGTERMed bun workers and rustc were earlyoom. The system journal shows it SIGTERMing the dotnet test host (2.6-3.4 GiB), bun workers and rustc while MemAvailable sat below 4%. scripts/ci-local.sh now holds a waiting lane until MemAvailable covers MO_CI_LANE_MIN_FREE_MB (default 8192) for it and for each lane started in the last 30 seconds. The first lane always starts, and 0 turns the check off. scripts/test-ci-lane-memory.sh (in the gates lane) pins the rule. 2. api-contract-report-sqlite.test.ts ran codegen and booted a server, Miniflare included on D1, for each of its 378 tests, and re-seeded D1 one statement per round trip. It took about 604s, so an agent with a 10-minute command cap was killed before it reported. It now generates and boots once per lane, layout and engine, and reseeds in one batch (D1 batch(), a bun:sqlite transaction). Runtime is about 46s, 378 pass. --- CHANGELOG.md | 9 ++++ CONTRIBUTING.md | 7 ++- scripts/ci-local.sh | 43 ++++++++++++++-- scripts/test-ci-lane-memory.sh | 48 ++++++++++++++++++ .../src/api-contract-report-sqlite-server.ts | 28 ++++++++--- .../test/api-contract-report-sqlite.test.ts | 50 ++++++++++--------- 6 files changed, 150 insertions(+), 35 deletions(-) create mode 100755 scripts/test-ci-lane-memory.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 440cceef2..42f246f01 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,15 @@ here.** ## [Unreleased] +- **Local CI starts a lane only when the machine has the memory for it.** `scripts/ci-local.sh` + holds a waiting lane until `MemAvailable` covers `MO_CI_LANE_MIN_FREE_MB` (default 8192) for + it and for each lane started in the last 30 seconds. The first lane always starts, and `0` + turns the check off. On a busy machine the parallel lanes had driven memory down to + earlyoom's limit, and its SIGTERMs read as a crashed C# test host, SIGTERMed bun workers and + a killed `rustc`, not as a memory problem. The SQLite and D1 report api-contract file now + generates and boots one server per suite and reseeds in one batch, so it runs in about 46 + seconds instead of about 10 minutes, which no longer outlasts a 10-minute command cap. + - **The deprecated-reference finding ends its sentence before naming the replacement.** It read `…Team: the league no longer tracks teams Replaced by acme::app::Club.`; it now reads `…tracks teams. Replaced by acme::app::Club.` A reason that already ends in `.`, `!` or `?` is left as written. - **C#: `dotnet meta verify` runs the three model authoring lints.** The overlay lint diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8e3bf9fd0..df341ced4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -144,7 +144,12 @@ a selection without running anything. The flagless run above is unchanged and is The full run does its tree-writing steps first (install, the drift gates, one workspace build), then runs the rest as parallel lanes: at most `MO_CI_JOBS` at once, default 8. Each lane's output prints as one block when the lane finishes, so lanes never interleave. The -summary gives every step's time, the slowest steps and each lane's wall time. `--quick` and +summary gives every step's time, the slowest steps and each lane's wall time. A waiting lane +starts only while the machine has `MO_CI_LANE_MIN_FREE_MB` of memory available (default +8192, plus as much again for each lane started in the last 30 seconds; `0` turns it off), so +a run on a busy machine queues its lanes. Without that check the run drove the machine down +to the out-of-memory killer, and a killed test host looked like a test crash. +`scripts/test-ci-lane-memory.sh` (in the `gates` lane) pins the rule. `--quick` and `--only` run serially. `MO_CI_PY_WORKERS` (default 8), `MO_CI_TS_WORKERS` (default 6) and `MO_CI_JVM_FORKS` (default 3) set the worker counts for pytest-xdist, the TypeScript integration suite and the TypeScript `codegen-ts` conformance suite, and the JVM diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 055675a82..30e3bac73 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -130,6 +130,11 @@ # ends, so output never interleaves. The summary lists every step with its time, the # slowest steps and each lane's wall time. Every step still runs and still fails the # run; only the order changes. --quick and --only run serially as before. +# A waiting lane also starts only while the machine has MO_CI_LANE_MIN_FREE_MB of memory +# available (MemAvailable, default 8192; 0 turns the check off), so the run never starts a +# lane into a machine that is already short. The first lane always starts. Without this a +# run on a busy machine drove memory to earlyoom's limit, and the SIGTERMs it sent showed +# up as a crashed C# test host and SIGTERMed bun workers, not as a memory problem. # Worker counts inside the runners: MO_CI_PY_WORKERS (pytest-xdist, default 8), # MO_CI_TS_WORKERS (bun test --parallel for the integration suite and the codegen-ts suite # in conformance: typescript, default 6) and @@ -199,6 +204,10 @@ MO_CI_JOBS="${MO_CI_JOBS:-8}" case "$MO_CI_JOBS" in ''|*[!0-9]*|0) echo "MO_CI_JOBS must be a positive integer (got '${MO_CI_JOBS}')" >&2; exit 2 ;; esac +MO_CI_LANE_MIN_FREE_MB="${MO_CI_LANE_MIN_FREE_MB:-8192}" +case "$MO_CI_LANE_MIN_FREE_MB" in + ''|*[!0-9]*) echo "MO_CI_LANE_MIN_FREE_MB must be a non-negative integer (got '${MO_CI_LANE_MIN_FREE_MB}')" >&2; exit 2 ;; +esac in_lane() { # in_lane
— true when the section is selected [ -z "$ONLY" ] && return 0 @@ -356,7 +365,8 @@ gate_uv_lock_version() { scripts/check-uv-lock-version.sh; } # itself the one thing nothing tested. That is the worst place in the tree for an unrun # test — a wrong answer here does not fail, it silently stops testing a port. gate_ci_port_selection() { - scripts/test-ci-affected-ports.sh && scripts/test-ci-ports-to-run.sh && scripts/test-ci-lane-selection.sh + scripts/test-ci-affected-ports.sh && scripts/test-ci-ports-to-run.sh && scripts/test-ci-lane-selection.sh \ + && scripts/test-ci-lane-memory.sh } # ── the no-magic-physical-names gate is wired in all five ports ─────────────── @@ -1293,9 +1303,27 @@ lane_start() { # lane_start LANE_PID[$1]=$! } +# mem_available_mb — MemAvailable in MiB, or nothing when it cannot be read (not Linux). +mem_available_mb() { awk '/^MemAvailable:/ { print int($2 / 1024); exit }' /proc/meminfo 2>/dev/null; } + +# lane_has_memory — true when another lane may start now. A lane started in +# the last LANE_WARMUP_S seconds has not grown into its memory yet, so each of those +# lanes holds one more MO_CI_LANE_MIN_FREE_MB in reserve; otherwise every lane would pass the +# check in the same second. The first lane always may start, so a machine that never has the +# headroom still runs every lane, one at a time. +LANE_WARMUP_S=30 +lane_has_memory() { + local avail + [ "$1" -eq 0 ] && return 0 + [ "$MO_CI_LANE_MIN_FREE_MB" -eq 0 ] && return 0 + avail="$(mem_available_mb)" + [ -z "$avail" ] && return 0 + [ "$avail" -ge $((MO_CI_LANE_MIN_FREE_MB * ($2 + 1))) ] +} + run_lanes() { - local max="$MO_CI_JOBS" n=${#LANE_NAMES[@]} i d ready running=0 left - local -a st=() + local max="$MO_CI_JOBS" n=${#LANE_NAMES[@]} i d ready running=0 left held=0 now recent t + local -a st=() started_at=() left=$n for ((i = 0; i < n; i++)); do st[i]=wait; done while [ "$left" -gt 0 ]; do @@ -1311,7 +1339,14 @@ run_lanes() { ready=1 for d in ${LANE_AFTER[i]//,/ }; do [ -e "$CI_TMP/lane-$d.done" ] || ready=0; done [ "$ready" -eq 1 ] || continue - lane_start "$i"; st[i]=run; running=$((running + 1)) + now="$(date +%s)"; recent=0 + for t in "${started_at[@]:-}"; do [ -n "$t" ] && [ $((now - t)) -lt "$LANE_WARMUP_S" ] && recent=$((recent + 1)); done + if ! lane_has_memory "$running" "$recent"; then + [ "$held" -eq 1 ] || echo " ▸ lane ${LANE_NAMES[i]} waits: less than ${MO_CI_LANE_MIN_FREE_MB} MiB of memory available" + held=1; break + fi + held=0 + lane_start "$i"; st[i]=run; running=$((running + 1)); started_at+=("$now") echo " ▸ lane ${LANE_NAMES[i]} started${LANE_AFTER[i]:+ (after ${LANE_AFTER[i]})}" done [ "$left" -gt 0 ] && sleep 1 diff --git a/scripts/test-ci-lane-memory.sh b/scripts/test-ci-lane-memory.sh new file mode 100755 index 000000000..5abe019a3 --- /dev/null +++ b/scripts/test-ci-lane-memory.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Test of the lane scheduler's memory admission in scripts/ci-local.sh (lane_has_memory). +# +# A waiting lane starts only while MemAvailable covers MO_CI_LANE_MIN_FREE_MB for it and for +# each lane started in the last LANE_WARMUP_S seconds. Without that, a parallel run on a busy +# machine drove memory down to earlyoom's limit, and earlyoom's SIGTERMs surfaced as a crashed +# C# test host and SIGTERMed bun workers instead of as a memory problem. +# +# The functions are read out of ci-local.sh itself, so this tests the shipped code. The +# script cannot be sourced whole because it runs CI. MemAvailable is stubbed, so the result +# does not depend on the machine running the test. Nothing here starts a lane. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 + +fails=0 +check() { # check "" "" "" + if [ "$2" != "$1" ]; then + echo "FAIL: $3 -> '$2' (expected '$1')" >&2; fails=$((fails+1)) + else + echo "ok: $3 -> '$2'" + fi +} + +defs="$(sed -n '/^LANE_WARMUP_S=/p; /^lane_has_memory() {/,/^}/p' scripts/ci-local.sh)" +[ -n "$defs" ] || { echo "FAIL: lane_has_memory not found in scripts/ci-local.sh" >&2; exit 1; } +eval "$defs" + +AVAIL="" +mem_available_mb() { echo "$AVAIL"; } +admit() { # admit + MO_CI_LANE_MIN_FREE_MB="$1"; AVAIL="$2" + if lane_has_memory "$3" "$4"; then echo start; else echo wait; fi +} + +check start "$(admit 8192 1000 0 3)" "the first lane starts even with no headroom (no deadlock)" +check start "$(admit 8192 9000 1 0)" "enough for one more lane" +check wait "$(admit 8192 7000 1 0)" "below the threshold: the lane waits" +check wait "$(admit 8192 20000 2 2)" "two lanes still warming up hold 8 GiB each in reserve" +check start "$(admit 8192 24576 2 2)" "enough for the new lane and both warming lanes" +check start "$(admit 0 100 5 5)" "MO_CI_LANE_MIN_FREE_MB=0 turns the check off" +check start "$(admit 8192 '' 4 4)" "unreadable MemAvailable (not Linux) never blocks" + +# The scheduler must consult it, or the function is dead code that this test keeps green. +check 1 "$(sed -n '/^run_lanes() {/,/^}/p' scripts/ci-local.sh | grep -c 'lane_has_memory "$running" "$recent"')" \ + "run_lanes gates each lane start on lane_has_memory" + +if [ "$fails" -gt 0 ]; then echo "$fails check(s) failed" >&2; exit 1; fi +echo "lane memory admission: all checks passed" diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts index 44686ebb4..ef7083983 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts @@ -31,6 +31,8 @@ export type SqliteReportEngine = "sqlite" | "d1"; /** What the server needs of an engine: run one statement, and close. */ interface EngineClient { run(sql: string, params?: unknown[]): Promise; + /** Run several statements in order as one unit: on D1, one `batch()` round trip instead of one per statement. */ + runAll(statements: ReadonlyArray<{ sql: string; params: unknown[] }>): Promise; close(): Promise; } @@ -184,14 +186,17 @@ export async function startSqliteReportServer( baseUrl, applySeed: async (seed: ReportSeed) => { // Children before parents on the way out; the seed's file order (parents first) on the way in. - for (const t of [...BASE_TABLES].reverse()) await client.run(`DELETE FROM "${t.name}"`); - for (const r of seedInserts(root, seed)) { - await client.run( - `INSERT INTO "${r.table}" (${r.columns.map((c) => `"${c}"`).join(",")}) ` + + // One batch: a test reseeds before it runs, and on D1 each statement sent alone is a round + // trip into Miniflare, which made the reseed most of the file's run time. + await client.runAll([ + ...[...BASE_TABLES].reverse().map((t) => ({ sql: `DELETE FROM "${t.name}"`, params: [] })), + ...seedInserts(root, seed).map((r) => ({ + sql: + `INSERT INTO "${r.table}" (${r.columns.map((c) => `"${c}"`).join(",")}) ` + `VALUES (${r.columns.map(() => "?").join(",")})`, - r.values, - ); - } + params: r.values, + })), + ]); }, close: async () => { await served.close(); @@ -221,6 +226,10 @@ export const db = drizzle((globalThis as Record)[${JSON.stringify run: async (sql, params = []) => { await local.d1.prepare(sql).bind(...params).all(); }, + runAll: async (statements) => { + if (statements.length === 0) return; + await local.d1.batch(statements.map((st) => local.d1.prepare(st.sql).bind(...st.params))); + }, close: async () => { delete (globalThis as Record)[key]; await local.dispose(); @@ -236,6 +245,11 @@ export const db = drizzle(client); const mod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { client: import("bun:sqlite").Database }; return { run: async (sql, params = []) => { mod.client.run(sql, params as never); }, + runAll: async (statements) => { + mod.client.transaction(() => { + for (const st of statements) mod.client.run(st.sql, st.params as never); + })(); + }, close: async () => { mod.client.close(); }, }; } diff --git a/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts b/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts index d18fba2dd..ed02ea98e 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts @@ -14,7 +14,7 @@ // 2. the shared scenarios: every scenario the Postgres lane runs also passes here, so // filtering, sorting and paging a decimal measure behave the same on both engines. -import { describe, expect, test } from "bun:test"; +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { API_LANES, laneLabel, type ApiLane } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; @@ -27,27 +27,29 @@ import { startSqliteReportServer, type SqliteReportEngine, type SqliteReportServ const SEED = JSON.parse(readFileSync(join(API_CONTRACT_REPORT_DIR, "seed.json"), "utf8")) as ReportSeed; const META_PATH = join(API_CONTRACT_REPORT_DIR, "meta.json"); -// Every test boots its own server; on D1 that is a Miniflare (workerd) process. Under the default -// parallel lane load (8 lanes) that start-up alone can pass bun's 5000ms default, so these -// server-backed tests get the same headroom as the other server-backed integration tests. +// Generation and the server boot happen ONCE per lane, layout and engine, not once per test. +// On D1 the boot is a Miniflare (workerd) process, and at one boot per test the file took about +// ten minutes, which a command cap (an agent harness's or a gate's) kills before it reports. A +// report is read-only, so every test here only reads or is refused (405) a write; it reseeds +// before it runs, so a shared server cannot carry state from one test into the next. +// The boot itself still gets the headroom the other server-backed integration tests get. const SERVER_TEST_TIMEOUT_MS = 120_000; const ENGINES: readonly SqliteReportEngine[] = ["sqlite", "d1"]; -async function withServer( - engine: SqliteReportEngine, - layout: OutputLayout, - lane: ApiLane, - fn: (server: SqliteReportServerHandle) => Promise, - seed: ReportSeed = SEED, -): Promise { - const server = await startSqliteReportServer(META_PATH, engine, layout, lane); - try { +function sharedServer(engine: SqliteReportEngine, layout: OutputLayout, lane: ApiLane) { + let server: SqliteReportServerHandle | undefined; + beforeAll(async () => { + server = await startSqliteReportServer(META_PATH, engine, layout, lane); + }, SERVER_TEST_TIMEOUT_MS); + afterAll(async () => { + await server?.close(); + }); + return async (fn: (server: SqliteReportServerHandle) => Promise, seed: ReportSeed = SEED): Promise => { + if (server === undefined) throw new Error("the report server did not start"); await server.applySeed(seed); await fn(server); - } finally { - await server.close(); - } + }; } async function getJson(server: SqliteReportServerHandle, path: string): Promise { @@ -56,11 +58,13 @@ async function getJson(server: SqliteReportServerHandle, path: string): Promise< return res.json(); } -// D1 starts a Miniflare (workerd) process per test and emits the same routes as SQLite (only the +// D1 starts a Miniflare (workerd) process per suite and emits the same routes as SQLite (only the // db module differs), so the package layout runs on SQLite alone. for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract report (FR-044) — ${laneLabel(lane)} on ${engine === "d1" ? "Cloudflare D1 (local)" : "SQLite"} [${layout}]`, () => { + const withServer = sharedServer(engine, layout, lane); + test("a ratio is a JSON string, as it is on Postgres, and the integers around it stay numbers", async () => { - await withServer(engine, layout, lane, async (server) => { + await withServer(async (server) => { const rows = (await getJson(server, "/api/invoice_totals")) as Array>; expect(rows.length).toBe(1); const row = rows[0]!; @@ -72,7 +76,7 @@ for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const en }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a ratio is a string in the withCount envelope too", async () => { - await withServer(engine, layout, lane, async (server) => { + await withServer(async (server) => { const body = (await getJson(server, "/api/invoice_totals?withCount=1")) as { rows: Array>; total: number; }; @@ -82,14 +86,14 @@ for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const en }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a ratio over zero rows is null, not the string 'null' or 0", async () => { - await withServer(engine, layout, lane, async (server) => { + await withServer(async (server) => { const rows = (await getJson(server, "/api/invoice_totals")) as Array>; expect(rows).toEqual([{ invoices: 0, totalCents: null, paidShare: null }]); }, { invoices: [] }); }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a report with no decimal field is untouched: every value keeps its type", async () => { - await withServer(engine, layout, lane, async (server) => { + await withServer(async (server) => { expect(await getJson(server, "/api/invoice_status_totals?sort=status:asc")).toEqual( SEED.reports!["InvoiceStatusTotals"], ); @@ -103,7 +107,7 @@ for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const en }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("the filter and the sort on a ratio still compare numerically after the wire change", async () => { - await withServer(engine, layout, lane, async (server) => { + await withServer(async (server) => { const hit = async (path: string): Promise => ((await getJson(server, path)) as unknown[]).length; expect(await hit("/api/invoice_totals?filter[paidShare][gt]=0.3")).toBe(1); expect(await hit("/api/invoice_totals?filter[paidShare][gt]=0.5")).toBe(0); @@ -116,7 +120,7 @@ for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const en for (const scenario of loadScenarios(API_CONTRACT_REPORT_SCENARIOS_DIR)) { test(`shared scenario: ${scenario.name}`, async () => { - await withServer(engine, layout, lane, (server) => runScenario(scenario, server.baseUrl)); + await withServer((server) => runScenario(scenario, server.baseUrl)); }, { timeout: SERVER_TEST_TIMEOUT_MS }); } }); From e1a6230c336d1477e7e618013484179611aef14c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 20:48:06 -0500 Subject: [PATCH 02/35] fix(docs-site): build the explorer on custom top-level vocabulary Top-level nodes of different types sharing a package and a name made buildExplorer throw a duplicate-id error. The object now keeps the plain :: id and each other node is qualified by its type, as a nested sibling already was; a model with no collision keeps its ids. A requirement whose id took a qualifier still matches its ledger row. The site wrote pages only for objects and templates, so a requirement claiming a node of another type failed the link check. Every other top-level type now gets a generic page (explorer-node.html.mustache), listed on its package page and in search. --- CHANGELOG.md | 13 ++++ docs/features/explorer-data.md | 2 +- docs/features/explorer-site.md | 6 +- .../packages/docs-site/src/explorer/build.ts | 43 +++++++++-- .../docs-site/src/explorer/index-model.ts | 7 +- .../packages/docs-site/src/explorer/pages.ts | 71 +++++++++++++++++-- .../packages/docs-site/src/explorer/site.ts | 8 +++ .../packages/docs-site/src/scaffold.ts | 1 + .../templates/explorer-node.html.mustache | 28 ++++++++ .../docs-site/test/explorer-build.test.ts | 34 ++++++++- .../docs-site/test/explorer-site.test.ts | 36 ++++++++++ .../test/fixture/custom-vocabulary.ts | 61 ++++++++++++++++ 12 files changed, 296 insertions(+), 14 deletions(-) create mode 100644 server/typescript/packages/docs-site/templates/explorer-node.html.mustache create mode 100644 server/typescript/packages/docs-site/test/fixture/custom-vocabulary.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 440cceef2..318a56a96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,19 @@ here.** ## [Unreleased] +- **The model explorer builds on a project with its own top-level vocabulary.** Two top-level + nodes of different types sharing a package and a name (an entity `Lead` and a page `Lead`) + made `buildExplorer` throw `two nodes share the id`. The object now keeps the plain + `::` id and each other node adds its type, `acme::crm::Lead[page.list]`, as a + nested sibling already did; a model with no such collision gets the same ids as before. A + requirement whose id took a qualifier still takes its ledger row. +- **Every top-level node gets an explorer page.** The site wrote pages only for objects and + templates, so a requirement claiming a node of another type, such as an application's + `capability.module`, failed the site's own link check. Every other top-level type now gets a + generic page (`explorer-node.html.mustache`, which `meta eject docs-site` copies): its + attributes, linked where they name a node, its members, the requirements claiming it, what + references it and what was generated from it. Package pages and search list these nodes too. + - **The deprecated-reference finding ends its sentence before naming the replacement.** It read `…Team: the league no longer tracks teams Replaced by acme::app::Club.`; it now reads `…tracks teams. Replaced by acme::app::Club.` A reason that already ends in `.`, `!` or `?` is left as written. - **C#: `dotnet meta verify` runs the three model authoring lints.** The overlay lint diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index d96ac9d1d..09051e8a2 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -139,7 +139,7 @@ each node nested inside one (field, identity, source, view, index, nested requir | Field | Meaning | | --- | --- | -| `id` | A top-level node's id is `::`. A nested node's id is its parent's id followed by `.`, for example `acme::shop::Order.total`. A nested requirement's id equals its ledger row's `qualifiedPath`. A nested node with no name gets `#` in place of `.`. When siblings of different types share a name, the first one in the effective JSON keeps `.`, because that is the node a dotted `@implementedBy` reference such as `Order.id` resolves to. Each later one adds its type, for example `acme::shop::AuditEntry.id[identity.primary]`. | +| `id` | A top-level node's id is `::`. When top-level nodes of different types share a package and a name (an entity `Lead` and an application's page `Lead`), the object keeps `::`, because every model reference names an object; if none is an object, the first one in the effective JSON keeps it. Each other one adds its type, for example `acme::crm::Lead[page.list]`. A model with no such collision gets no qualified top-level id. A nested node's id is its parent's id followed by `.`, for example `acme::shop::Order.total`. A nested requirement's id equals its ledger row's `qualifiedPath`. A nested node with no name gets `#` in place of `.`. When siblings of different types share a name, the first one in the effective JSON keeps `.`, because that is the node a dotted `@implementedBy` reference such as `Order.id` resolves to. Each later one adds its type, for example `acme::shop::AuditEntry.id[identity.primary]`. | | `type`, `subType`, `name`, `package` | As in the model. `package` is the package of the top-level ancestor. | | `parent` | The id of the node it is nested in. A top-level node has no `parent`. | | `order` | Its position among its siblings in the effective tree, from 0: the declaration order, which the id sort does not keep. | diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index c221b8645..626b1fc57 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -87,6 +87,7 @@ docsSiteFile({ assetBase: "/vendor/npm" }) | Model map | `map.html` | Every top-level node and the edges between them. Open a slice (a package, a requirement subtree, a prompt), colour by kind, API, claims, capability or status, and hide or show value objects and nodes outside the slice. The URL keeps the choice (`?slice=&colour=&focus=`) | | Object | `model//.html` | Why it exists (the requirements that claim it), its fields, inherited ones marked, relationships, indexes, a one-hop mini-map, its routes and the files generated from it. A projection shows its read model and each field's origin; a report shows where its rows come from, its dimensions and its measures | | Prompt | `model//.html` | The payload and reply types, the template text with each variable marked, and which payload fields the text never uses | +| Any other node | `model//.html` | A generic page for every other top-level type, including vocabulary an application registers itself (a `capability.module`, a `page.list`): its attributes, each one linked when it names a node, its members, the requirements that claim it, what references it and the files generated from it | | Features, qualities | `requirements/features.html`, `requirements/qualities.html` | The requirement tree, one card per entry | | Requirement | `requirements//.html` | Its status, what it claims, the entries below it with their roll-up, what the gate found, its authoring advisories apart, and links to its slice of the map and its trace | | Matrix | `matrix.html` | Requirements against stored entities and prompts. An empty column is a node nothing claims | @@ -95,7 +96,10 @@ docsSiteFile({ assetBase: "/vendor/npm" }) | Gaps | `gaps.html` | The gate's findings and coverage warnings, the authoring lint's advisories (listed apart, never as a verdict), undecided gaps as the gate counts them (a roll-up parent of outstanding work is left out), and the checks this explorer adds: planned entries with live work below, prompts nothing claims, fields named like a reference with no `identity.reference`, payload fields the text never uses | An object named `index` gets `index.node.html`, so it never takes its package's index page, -and a model with no package puts its pages under `model/-root/`. +and a model with no package puts its pages under `model/-root/`. A node whose id carries its +type (because a node of another type has the same name in its package, see +[explorer-data.md](explorer-data.md)) carries it in its file name too: the page `Lead` beside +the entity `Lead` is `Lead.page-list.html`. Every page works at phone width: the navigation scrolls, the tiles stack in two columns, and wide tables scroll inside their card. diff --git a/server/typescript/packages/docs-site/src/explorer/build.ts b/server/typescript/packages/docs-site/src/explorer/build.ts index 817e1f93f..899dbc15e 100644 --- a/server/typescript/packages/docs-site/src/explorer/build.ts +++ b/server/typescript/packages/docs-site/src/explorer/build.ts @@ -37,6 +37,7 @@ import { TYPE_FIELD, TYPE_IDENTITY, TYPE_METADATA, + TYPE_OBJECT, TYPE_RELATIONSHIP, TYPE_REQUIREMENT, TYPE_SUBTYPE_SEPARATOR, @@ -124,6 +125,8 @@ interface Walked { body: Record; /** The id of the top-level node this one sits under (itself, at the top). */ owner: string; + /** The id as a dotted path names it, before any type qualifier: what `verify` prints. */ + path: string; } function walkModel(model: unknown): Walked[] { @@ -134,6 +137,23 @@ function walkModel(model: unknown): Walked[] { const rootPkg = typeof root[RESERVED_KEY_PACKAGE] === "string" ? (root[RESERVED_KEY_PACKAGE] as string) : ""; const out: Walked[] = []; const seen = new Set(); + const topLevel = rawChildren(root); + const topPlainId = (child: RawChild): string => { + const name = typeof child.body[RESERVED_KEY_NAME] === "string" ? (child.body[RESERVED_KEY_NAME] as string) : ""; + const own = child.body[RESERVED_KEY_PACKAGE]; + const pkg = typeof own === "string" ? own : rootPkg; + return pkg === "" ? name : `${pkg}${PACKAGE_SEPARATOR}${name}`; + }; + // Top-level nodes of different types may share a package and a name (an entity `Lead` and + // an application's page `Lead`). One of them keeps the plain id: the object, since every + // reference in the model (`@objectRef`, `@payloadRef`, `extends`) names an object, else the + // first declared. Each other one is qualified by its type, as a nested sibling is. + const plainHolder = new Map(); + for (const child of topLevel) { + const id = topPlainId(child); + const held = plainHolder.get(id); + if (held === undefined || (held.type !== TYPE_OBJECT && child.type === TYPE_OBJECT)) plainHolder.set(id, child); + } const visit = (child: RawChild, index: number, parent: Walked | undefined): void => { const name = typeof child.body[RESERVED_KEY_NAME] === "string" ? (child.body[RESERVED_KEY_NAME] as string) : ""; @@ -142,13 +162,15 @@ function walkModel(model: unknown): Walked[] { if (parent === undefined) { const own = child.body[RESERVED_KEY_PACKAGE]; pkg = typeof own === "string" ? own : rootPkg; - id = pkg === "" ? name : `${pkg}${PACKAGE_SEPARATOR}${name}`; + id = topPlainId(child); + const holder = plainHolder.get(id); + if (name !== "" && holder !== child && holder?.type !== child.type) id = qualified(id, child); } else { pkg = parent.node.package; id = name === "" ? `${parent.node.id}#${index}` : `${parent.node.id}${CHILD_REF_SEPARATOR}${name}`; // The first sibling of a name keeps the plain id: it is the one a dotted reference // resolves to. A later sibling of another type sharing the name is qualified by type. - if (name !== "" && seen.has(id)) id = `${id}[${child.type}${TYPE_SUBTYPE_SEPARATOR}${child.subType}]`; + if (name !== "" && seen.has(id)) id = qualified(id, child); } if (seen.has(id)) { throw new Error(`explorer: two nodes share the id "${id}" — the model names two siblings alike`); @@ -168,15 +190,22 @@ function walkModel(model: unknown): Walked[] { ...(child.body[RESERVED_KEY_IS_ARRAY] === true ? { isArray: true as const } : {}), attrs: attrsOf(child.body), }; - const walked: Walked = { node, body: child.body, owner: parent === undefined ? id : parent.owner }; + const path = + parent === undefined ? topPlainId(child) : name === "" ? `${parent.path}#${index}` : `${parent.path}${CHILD_REF_SEPARATOR}${name}`; + const walked: Walked = { node, body: child.body, owner: parent === undefined ? id : parent.owner, path }; out.push(walked); rawChildren(child.body).forEach((c, i) => visit(c, i, walked)); }; - rawChildren(root).forEach((c, i) => visit(c, i, undefined)); + topLevel.forEach((c, i) => visit(c, i, undefined)); return out; } +/** A plain id qualified by the node's type: `[.]`. */ +function qualified(id: string, child: RawChild): string { + return `${id}[${child.type}${TYPE_SUBTYPE_SEPARATOR}${child.subType}]`; +} + /** A canonical reference spells a root-level target `::Name`; the node's id is `Name`. */ function nodeIdOf(ref: string): string { return ref.startsWith(PACKAGE_SEPARATOR) ? ref.slice(PACKAGE_SEPARATOR.length) : ref; @@ -260,10 +289,14 @@ function asLink(v: unknown): { ref: string; resolves: boolean; target?: string } function ledgerFrom(verify: unknown, byId: Map, edges: ExplorerEdge[]): ExplorerLedger | undefined { if (!isRecord(verify) || !Array.isArray(verify.requirementLedger)) return undefined; + // A ledger row names its requirement by dotted path; the node's id differs only when a + // same-named node of another type took the plain id. + const reqByPath = new Map(); + for (const w of byId.values()) if (w.node.type === TYPE_REQUIREMENT) reqByPath.set(w.path, w.node.id); const rows: ExplorerLedgerRow[] = []; for (const raw of verify.requirementLedger) { if (!isRecord(raw) || typeof raw.qualifiedPath !== "string" || typeof raw.path !== "string") continue; - const node = raw.qualifiedPath; + const node = reqByPath.get(raw.qualifiedPath) ?? raw.qualifiedPath; const implementedBy = asLinks(raw.implementedBy); const supersededBy = asLink(raw.supersededBy); const diagnostics = Array.isArray(raw.diagnostics) diff --git a/server/typescript/packages/docs-site/src/explorer/index-model.ts b/server/typescript/packages/docs-site/src/explorer/index-model.ts index 6b1014a83..4d90576dc 100644 --- a/server/typescript/packages/docs-site/src/explorer/index-model.ts +++ b/server/typescript/packages/docs-site/src/explorer/index-model.ts @@ -87,6 +87,9 @@ export class ExplorerIndex { readonly objects: ExplorerNode[] = []; /** Top-level template nodes (prompt, output, …), by id. */ readonly templates: ExplorerNode[] = []; + /** Top-level nodes of every other type but requirement: vocabulary an application or a + * provider pack registered (a `capability.module`, a `page.list`), each on a generic page. */ + readonly others: ExplorerNode[] = []; /** Every requirement, in document order (the ledger's order when there is one). */ readonly requirements: ReqEntry[] = []; readonly reqById = new Map(); @@ -111,6 +114,7 @@ export class ExplorerIndex { if (n.parent !== undefined) continue; if (n.type === TYPE_OBJECT) this.objects.push(n); else if (n.type === TYPE_TEMPLATE) this.templates.push(n); + else if (n.type !== TYPE_REQUIREMENT) this.others.push(n); } this.packages = [...new Set(doc.nodes.filter((n) => n.parent === undefined).map((n) => n.package))].sort(byCodeUnit); this.indexRequirements(); @@ -209,8 +213,9 @@ export class ExplorerIndex { } /** The kind a page and the map name a top-level node by. */ - kindOf(n: ExplorerNode): "entity" | "value" | "projection" | "report" | "prompt" | "template" | "object" { + kindOf(n: ExplorerNode): "entity" | "value" | "projection" | "report" | "prompt" | "template" | "object" | "other" { if (n.type === TYPE_TEMPLATE) return n.subType === TEMPLATE_SUBTYPE_PROMPT ? "prompt" : "template"; + if (n.type !== TYPE_OBJECT) return "other"; if (n.subType === OBJECT_SUBTYPE_ENTITY) return "entity"; if (n.subType === OBJECT_SUBTYPE_VALUE) return "value"; if (n.subType === OBJECT_SUBTYPE_PROJECTION) return "projection"; diff --git a/server/typescript/packages/docs-site/src/explorer/pages.ts b/server/typescript/packages/docs-site/src/explorer/pages.ts index 684729f76..9b8fd055b 100644 --- a/server/typescript/packages/docs-site/src/explorer/pages.ts +++ b/server/typescript/packages/docs-site/src/explorer/pages.ts @@ -18,6 +18,7 @@ import { FIELD_ATTR_VALUES, FIELD_SUBTYPE_ENUM, IDENTITY_ATTR_FIELDS, + PACKAGE_SEPARATOR, IDENTITY_REFERENCE_ATTR_REFERENCES, OBJECT_REPORT_ATTR_DIMENSIONS, OBJECT_REPORT_ATTR_FILTER, @@ -148,8 +149,12 @@ export class Pages { // ─── Addresses ─────────────────────────────────────────────────────────────── + /** A top-level node's page. A node whose id is qualified by its type (another type holds + * the plain id) carries the type in its file name too, so the two never share a page. */ objectPage(n: ExplorerNode): string { - return `model/${pkgDir(n.package)}/${pageStem(n.name)}.html`; + const qualifier = `[${n.type}.${n.subType}]`; + const typed = n.parent === undefined && n.id.endsWith(qualifier) ? `.${n.type}-${n.subType}` : ""; + return `model/${pkgDir(n.package)}/${pageStem(n.name)}${typed}.html`; } packagePage(pkg: string): string { @@ -181,7 +186,9 @@ export class Pages { const page = this.objectPage(owner); if (ownerId === id) return page; const member = this.memberOf(ownerId, id); - return member !== undefined && ANCHORED_TYPES.has(member.type) ? `${page}#${memberAnchor(member)}` : page; + if (member === undefined) return page; + // A generic page lists every member, so each one has a row to land on. + return ANCHORED_TYPES.has(member.type) || this.ix.kindOf(owner) === "other" ? `${page}#${memberAnchor(member)}` : page; } /** The direct child of `ownerId` that `id` sits in (or is). */ @@ -295,10 +302,10 @@ export class Pages { } private packageCard(from: string, pkg: string): Record { - const members = [...this.ix.objects, ...this.ix.templates].filter((n) => n.package === pkg); + const members = [...this.ix.objects, ...this.ix.templates, ...this.ix.others].filter((n) => n.package === pkg); const kinds = new Map(); for (const m of members) kinds.set(this.ix.kindOf(m), (kinds.get(this.ix.kindOf(m)) ?? 0) + 1); - const order = ["entity", "value", "projection", "report", "prompt", "template", "object"]; + const order = ["entity", "value", "projection", "report", "prompt", "template", "object", "other"]; const kindLine = order.filter((k) => kinds.has(k)).map((k) => `● ${kinds.get(k)} ${plural(k, kinds.get(k) ?? 0)}`).join(" · "); const shown = members.slice(0, 12); return { @@ -561,6 +568,60 @@ export class Pages { return [...groups.keys()].sort(byCodeUnit).map((g) => ({ generator: esc(g), files: (groups.get(g) ?? []).map((p) => esc(p)) })); } + // ─── Generic node page: any other top-level type ───────────────────────────── + + /** The page of a top-level node the explorer has no specific screen for: what the model + * states about it (attributes, members), why it exists, what points at it, what was + * generated from it. Every value comes off the node; nothing is interpreted. */ + node(n: ExplorerNode): Record { + const ix = this.ix; + const from = this.objectPage(n); + const kindLabel = `${n.type}.${n.subType}`; + const whyRows = this.whyRows(from, n); + const attrs = this.attrRows(from, n); + const refBy = [...new Set(ix.doc.edges.filter((e) => e.to === n.id || ix.ownerOf(e.to) === n.id).map((e) => ix.ownerOf(e.from)).filter((id) => id !== n.id))] + .sort(byCodeUnit) + .map((id) => this.link(from, id)); + return { + id: esc(n.id), + name: esc(n.name), + kindLabel: esc(kindLabel), + crumbsHtml: `Model › ${esc(n.package === "" ? "(no package)" : n.package)} › ${esc(kindLabel)}`, + isAbstract: n.abstract === true, + description: this.description(n), + extendsHtml: n.extends !== undefined ? this.link(from, n.extends) : "", + attrs, + hasAttrs: attrs.length > 0, + members: ix.children(n.id).map((c) => ({ + anchor: esc(memberAnchor(c)), + kind: esc(`${c.type}.${c.subType}`), + nameHtml: ix.reqById.has(c.id) ? this.link(from, c.id) : esc(c.name === "" ? `#${c.order}` : c.name), + attrsHtml: this.attrRows(from, c).map((a) => `@${a.name} ${a.valueHtml}`).join("
"), + below: ix.children(c.id).length, + })), + hasMembers: ix.children(n.id).length > 0, + whyRows, + hasWhy: whyRows.length > 0, + whyEmptyHtml: this.whyEmpty(n), + referencedByHtml: refBy.join(", "), + generated: this.generatedGroups(n.id), + hasGenerated: ix.generated(n.id).length > 0, + generatedNote: ix.doc.generated === undefined ? "No generation manifest was read." : "Nothing generated is traced to it.", + }; + } + + /** A node's attributes, sorted, each value linked when it names a node. */ + private attrRows(from: string, n: ExplorerNode): { name: string; valueHtml: string }[] { + return Object.keys(n.attrs) + .sort(byCodeUnit) + .map((k) => { + const v = n.attrs[k]; + const target = typeof v === "string" ? (v.startsWith(PACKAGE_SEPARATOR) ? v.slice(PACKAGE_SEPARATOR.length) : v) : undefined; + const linked = target !== undefined && this.ix.byId.has(target) && this.pageOf(target) !== undefined; + return { name: esc(k), valueHtml: linked ? this.link(from, target) : `${esc(fmt(v))}` }; + }); + } + // ─── S4: Prompt (and other template) page ──────────────────────────────────── prompt(n: ExplorerNode, text: string | undefined): Record { @@ -897,7 +958,7 @@ export class Pages { packageIndex(pkg: string): Record { const ix = this.ix; const from = this.packagePage(pkg); - const rows = [...ix.objects, ...ix.templates].filter((n) => n.package === pkg).map((n) => { + const rows = [...ix.objects, ...ix.templates, ...ix.others].filter((n) => n.package === pkg).map((n) => { const s = ix.storage(n.id); const st = ix.claimStatus(n.id); return { diff --git a/server/typescript/packages/docs-site/src/explorer/site.ts b/server/typescript/packages/docs-site/src/explorer/site.ts index ca6782e70..e3530c905 100644 --- a/server/typescript/packages/docs-site/src/explorer/site.ts +++ b/server/typescript/packages/docs-site/src/explorer/site.ts @@ -7,6 +7,9 @@ // map.html S2 the model map (slices, colour-by) // model//.html S3 an object page (entity, value, projection, report) // S4 a prompt page (and any other template) +// a generic page for any other top-level type +// model//.-.html the same, for a node whose name another +// type's node holds in its package // requirements/{features,qualities}.html S5 // requirements//.html S6 // matrix.html, trace.html, gaps.html, api.html, prompts.html, model/index.html, model//index.html @@ -193,6 +196,7 @@ export function generateExplorerSite(opts: ExplorerSiteOptions): ExplorerSiteRes } for (const n of ix.objects) page("explorer-object.html.mustache", pagesModel.objectPage(n), "map", n.name, pagesModel.object(n), true); for (const t of ix.templates) page("explorer-prompt.html.mustache", pagesModel.objectPage(t), "prompts", t.name, pagesModel.prompt(t, opts.texts?.get(t.id))); + for (const n of ix.others) page("explorer-node.html.mustache", pagesModel.objectPage(n), "map", n.name, pagesModel.node(n)); for (const r of ix.requirements) page("explorer-requirement.html.mustache", pagesModel.reqPage(r), "requirements", pagesModel.reqLabel(r), pagesModel.requirement(r)); for (const a of EXPLORER_ASSET_NAMES) write(`assets/${a}`, loadFrom(BUNDLED_ASSETS, a, opts.assetsDir)); @@ -261,6 +265,10 @@ function graphData(ix: ExplorerIndex, p: Pages): Record { search.push({ t: `${n.name}.${f.name}`, s: `field.${f.subType}`, h: p.pageOf(f.id) ?? p.objectPage(n), k: `${n.name}.${f.name} ${f.id}`.toLowerCase() }); } } + for (const n of ix.others) { + const desc = typeof n.attrs[DOC_ATTR_DESCRIPTION] === "string" ? (n.attrs[DOC_ATTR_DESCRIPTION] as string) : ""; + search.push({ t: n.name, s: `${n.type}.${n.subType}${n.package !== "" ? ` · ${n.package}` : ""}`, h: p.objectPage(n), k: `${n.name} ${n.id} ${desc}`.toLowerCase() }); + } for (const r of ix.requirements) { search.push({ t: p.reqLabel(r), diff --git a/server/typescript/packages/docs-site/src/scaffold.ts b/server/typescript/packages/docs-site/src/scaffold.ts index 972dbbf20..5f0e68fa5 100644 --- a/server/typescript/packages/docs-site/src/scaffold.ts +++ b/server/typescript/packages/docs-site/src/scaffold.ts @@ -26,6 +26,7 @@ export const EXPLORER_TEMPLATE_NAMES: readonly string[] = [ "explorer-overview.html.mustache", "explorer-map.html.mustache", "explorer-object.html.mustache", + "explorer-node.html.mustache", "explorer-prompt.html.mustache", "explorer-prompts.html.mustache", "explorer-requirements.html.mustache", diff --git a/server/typescript/packages/docs-site/templates/explorer-node.html.mustache b/server/typescript/packages/docs-site/templates/explorer-node.html.mustache new file mode 100644 index 000000000..d2d8941b0 --- /dev/null +++ b/server/typescript/packages/docs-site/templates/explorer-node.html.mustache @@ -0,0 +1,28 @@ +
{{{crumbsHtml}}}
+

{{{name}}} {{#isAbstract}}abstract{{/isAbstract}}

+ +{{#description}}
{{{description}}}
{{/description}} +
{{{kindLabel}}}{{#extendsHtml}} · extends {{{extendsHtml}}}{{/extendsHtml}}
+
+
+

Why it exists

+ {{#hasWhy}}
+ {{#whyRows}} + {{/whyRows}}
CapabilityRequirementLevelStatusOn
{{{capabilityHtml}}}{{{reqHtml}}}
{{{statement}}}
{{{levelHtml}}}{{{statusHtml}}}{{{onHtml}}}
{{/hasWhy}} + {{^hasWhy}}
{{{whyEmptyHtml}}}
{{/hasWhy}} + {{#hasAttrs}}

Attributes

+
{{#attrs}}{{/attrs}}
@{{{name}}}{{{valueHtml}}}
{{/hasAttrs}} + {{#hasMembers}}

Members

+
+ {{#members}} + {{/members}}
NameTypeAttributes
{{{nameHtml}}}{{#below}} +{{below}}{{/below}}{{{kind}}}{{{attrsHtml}}}
{{/hasMembers}} +
+ +
diff --git a/server/typescript/packages/docs-site/test/explorer-build.test.ts b/server/typescript/packages/docs-site/test/explorer-build.test.ts index 7f0fc1f0f..2a2eaef27 100644 --- a/server/typescript/packages/docs-site/test/explorer-build.test.ts +++ b/server/typescript/packages/docs-site/test/explorer-build.test.ts @@ -5,6 +5,7 @@ import { describe, test, expect } from "bun:test"; import { readFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { buildExplorer, serializeExplorer, type ExplorerJson } from "../src/index.js"; +import { CUSTOM_VOCABULARY_MODEL, CUSTOM_VOCABULARY_VERIFY } from "./fixture/custom-vocabulary.js"; const FIXTURE = resolve(import.meta.dir, "../../../../../fixtures/explorer-conformance/shop"); const text = (name: string): string => readFileSync(join(FIXTURE, name), "utf8"); @@ -102,7 +103,38 @@ describe("buildExplorer", () => { expect(nodes.get("acme::shop::AuditEntry.id[identity.primary]")?.type).toBe("identity"); }); - test("rejects two top-level nodes sharing an id", () => { + test("a top-level node of another type sharing an object's name gets a type-qualified id; the object keeps the plain one", () => { + // The page is declared first: the object keeps the plain id anyway, since references name objects. + const built = buildExplorer({ model: CUSTOM_VOCABULARY_MODEL, verify: CUSTOM_VOCABULARY_VERIFY }); + const nodes = new Map(built.nodes.map((n) => [n.id, n])); + expect(nodes.get("acme::crm::Lead")?.type).toBe("object"); + expect(nodes.get("acme::crm::Lead.email")?.type).toBe("field"); + expect(nodes.get("acme::crm::Lead[page.list]")?.type).toBe("page"); + expect(nodes.get("acme::crm::Lead[page.list].leads")?.parent).toBe("acme::crm::Lead[page.list]"); + expect(built.edges).toContainEqual({ kind: "implementedBy", from: "acme::tax::Tax", to: "acme::tax::tax" }); + }); + + test("a model with no collision keeps every top-level id plain", () => { + for (const n of build().nodes) if (n.parent === undefined) expect(n.id).not.toContain("["); + }); + + test("a requirement whose id is qualified still takes its ledger row", () => { + const model = { + "metadata.root": { + package: "p", + children: [ + { "object.entity": { name: "Billing" } }, + { "requirement.functional": { name: "Billing", "@status": "live", children: [{ "requirement.functional": { name: "Invoices", "@status": "live" } }] } }, + ], + }, + }; + const row = (path: string): unknown => ({ path, package: "p", qualifiedPath: `p::${path}`, subType: "functional", status: "live", digest: "", implementedBy: [{ ref: "Billing", resolves: true, target: "p::Billing" }], diagnostics: [], verdict: "clean" }); + const built = buildExplorer({ model, verify: { requirementLedger: [row("Billing"), row("Billing.Invoices")] } }); + expect(built.ledger?.rows.map((r) => r.node)).toEqual(["p::Billing[requirement.functional]", "p::Billing[requirement.functional].Invoices"]); + expect(built.edges).toContainEqual({ kind: "implementedBy", from: "p::Billing[requirement.functional]", to: "p::Billing" }); + }); + + test("rejects two top-level nodes of one type sharing an id", () => { const model = { "metadata.root": { package: "p", diff --git a/server/typescript/packages/docs-site/test/explorer-site.test.ts b/server/typescript/packages/docs-site/test/explorer-site.test.ts index 56dade146..f535596b8 100644 --- a/server/typescript/packages/docs-site/test/explorer-site.test.ts +++ b/server/typescript/packages/docs-site/test/explorer-site.test.ts @@ -14,6 +14,7 @@ import { readPromptTexts, type ExplorerJson, } from "../src/index.js"; +import { CUSTOM_VOCABULARY_MODEL, CUSTOM_VOCABULARY_VERIFY } from "./fixture/custom-vocabulary.js"; const REPO = resolve(import.meta.dir, "../../../../.."); const SHOP = join(REPO, "fixtures/explorer-conformance/shop"); @@ -210,6 +211,41 @@ describe("explorer site over the fitness model", async () => { }); }); +describe("explorer site over application-owned vocabulary", () => { + const build = (): { pages: string[]; page: (p: string) => string } => { + const out = scratch(); + const r = generateExplorerSite({ explorer: buildExplorer({ model: CUSTOM_VOCABULARY_MODEL, verify: CUSTOM_VOCABULARY_VERIFY }), outDir: out, title: "Acme" }); + return { pages: r.pages, page: (p) => readFileSync(join(out, p), "utf8") }; + }; + + test("every top-level node gets a page, and the site passes its own link check", () => { + const { pages } = build(); + expect(pages).toContain("model/acme/crm/Lead.html"); + expect(pages).toContain("model/acme/crm/Lead.page-list.html"); + expect(pages).toContain("model/acme/tax/tax.html"); + }); + + test("a custom type's generic page shows its kind, attributes, members and the requirement claiming it", () => { + const { page } = build(); + const tax = page("model/acme/tax/tax.html"); + expect(tax).toContain("capability.module"); + expect(tax).toContain("Sales tax."); + expect(tax).toContain("The software computes sales tax."); + const list = page("model/acme/crm/Lead.page-list.html"); + expect(list).toContain("page.list"); + expect(list).toContain(`id="m-block-leads"`); + // An attribute naming a node links to that node's page. + expect(list).toContain(`href="../../../model/acme/crm/Lead.html"`); + }); + + test("the package page lists the custom nodes beside the objects", () => { + const { page } = build(); + const crm = page("model/acme/crm/index.html"); + expect(crm).toContain(`href="../../../model/acme/crm/Lead.html"`); + expect(crm).toContain(`href="../../../model/acme/crm/Lead.page-list.html"`); + }); +}); + describe("explorer site page paths", () => { const model = (pkg: string | undefined, children: unknown[]): unknown => ({ "metadata.root": { ...(pkg !== undefined ? { package: pkg } : {}), children }, diff --git a/server/typescript/packages/docs-site/test/fixture/custom-vocabulary.ts b/server/typescript/packages/docs-site/test/fixture/custom-vocabulary.ts new file mode 100644 index 000000000..c743c088e --- /dev/null +++ b/server/typescript/packages/docs-site/test/fixture/custom-vocabulary.ts @@ -0,0 +1,61 @@ +// A model with application-owned top-level vocabulary, as an adopter with its own providers +// exports it: an entity and a page of a custom type sharing a package and a name, and a +// requirement claiming a node of a custom type. Both shapes broke the explorer: the first +// threw on a duplicate id, the second left a link with no page behind it. +// +// The explorer reads canonical JSON and never the loader, so the custom types (`page.list`, +// `capability.module`) need no provider here. + +export const CUSTOM_VOCABULARY_MODEL = { + "metadata.root": { + children: [ + { + "page.list": { + name: "Lead", + package: "acme::crm", + "@entity": "acme::crm::Lead", + children: [{ "block.table": { name: "leads", "@entity": "acme::crm::Lead" } }], + }, + }, + { + "object.entity": { + name: "Lead", + package: "acme::crm", + "@description": "A prospective customer.", + children: [ + { "field.long": { name: "id" } }, + { "field.string": { name: "email" } }, + ], + }, + }, + { "capability.module": { name: "tax", package: "acme::tax", "@description": "Sales tax." } }, + { + "requirement.functional": { + name: "Tax", + package: "acme::tax", + "@level": 1, + "@status": "live", + "@statement": "The software computes sales tax.", + "@implementedBy": ["acme::tax::tax"], + }, + }, + ], + }, +}; + +export const CUSTOM_VOCABULARY_VERIFY = { + requirementLedger: [ + { + path: "Tax", + package: "acme::tax", + qualifiedPath: "acme::tax::Tax", + subType: "functional", + level: 1, + status: "live", + digest: "", + implementedBy: [{ ref: "acme::tax::tax", resolves: true, target: "acme::tax::tax" }], + diagnostics: [], + verdict: "clean", + }, + ], +}; From 651cb75df8b6f12334df11b74e82e94db63c2d73 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 21:02:36 -0500 Subject: [PATCH 03/35] build(release): changelog entries as per-change fragments in changelog.d/ Every PR added its entry at the top of CHANGELOG.md's [Unreleased], so any two PRs in flight edited the same lines and conflicted as each other landed. A PR now adds one file under changelog.d/ instead; release.mjs folds the fragments into [Unreleased] (file-name order) and deletes them before promoting, so a release still ships one CHANGELOG.md. - scripts/lib/changelog-fragments.mjs: read, validate and assemble - scripts/changelog-fragments.mjs: --check | --preview | --assemble - gates lane: 'changelog fragments' step (shape check + assembly tests) - lane map: changelog.d/* selects no test lane, like CHANGELOG.md - RELEASING, CONTRIBUTING, PR template and the releasing skill point at changelog.d/README.md, which carries the entry conventions --- .claude/skills/releasing/SKILL.md | 2 +- .github/PULL_REQUEST_TEMPLATE.md | 1 + CONTRIBUTING.md | 7 ++- changelog.d/README.md | 38 ++++++++++++ docs/RELEASING-docs-checklist.md | 2 +- docs/RELEASING.md | 9 +++ scripts/changelog-fragments.mjs | 45 +++++++++++++++ scripts/ci-lane-map.txt | 1 + scripts/ci-local.sh | 5 ++ scripts/eject-release-gate.test.ts | 2 +- scripts/lib/changelog-fragments.mjs | 86 ++++++++++++++++++++++++++++ scripts/release.mjs | 27 +++++++-- scripts/test-changelog-fragments.mjs | 60 +++++++++++++++++++ scripts/test-ci-lane-selection.sh | 1 + tsconfig.scripts.json | 1 + 15 files changed, 277 insertions(+), 10 deletions(-) create mode 100644 changelog.d/README.md create mode 100644 scripts/changelog-fragments.mjs create mode 100644 scripts/lib/changelog-fragments.mjs create mode 100644 scripts/test-changelog-fragments.mjs diff --git a/.claude/skills/releasing/SKILL.md b/.claude/skills/releasing/SKILL.md index 826e14a14..b298a752e 100644 --- a/.claude/skills/releasing/SKILL.md +++ b/.claude/skills/releasing/SKILL.md @@ -39,7 +39,7 @@ Do not bump or publish anything until every check is green. Print each result. | **CI green on the exact release SHA** | `gh run list --branch main --limit 5`; `gh pr checks <#>` | all required checks `pass` on `HEAD` — not "passed sometime" | | Published vs local version | `npm view @metaobjectsdev/cli dist-tags.latest`; compare to `package.json` | you know current `latest` and the target bump | | **Target version is free** | `npm view @metaobjectsdev/cli@ version` (a 404 = free); `git tag -l v` | the target version is NOT already published or tagged (npm versions are permanent — a taken version can never be reused) | -| CHANGELOG ready | `sed -n '1,20p' CHANGELOG.md` | an entry exists or you will add one (see Phase 8) | +| CHANGELOG ready | `sed -n '1,20p' CHANGELOG.md`; `ls changelog.d/` | an entry or a fragment exists, or you will add one (see Phase 8). `release.mjs` assembles the `changelog.d/` fragments into `[Unreleased]`; `node scripts/changelog-fragments.mjs --assemble` does it by hand | | **`metamodelVersion` moved if the metamodel did** | `node scripts/check-metamodel-version.mjs` | exit 0. It diffs `expected-registry.json` against the last release tag and fails if the vocabulary changed without the version moving. Read its PROSE warning too — a rule can change with no machine-readable footprint (#210 changed only a `rules` string). Fix with `--set `; detail with `--explain`. | | **You CAN publish** | `npm whoami` | prints your username (see the note under this table) | diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 84b5c52d7..27fc1392e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -11,6 +11,7 @@ - [ ] Named constants used for metamodel strings; no `any` (TS) - [ ] **Public-repo hygiene:** no private/other-project names, personal info, or absolute local paths — in code, docs, fixtures, **or commit messages** - [ ] Docs updated if behavior/CLI changed +- [ ] User-visible change: a changelog fragment added under `changelog.d/` (not an edit to `CHANGELOG.md`; see `changelog.d/README.md`) ## Notes for reviewers diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8e3bf9fd0..76ca1d05a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,8 +36,11 @@ conformance corpora. This guide covers how to propose changes. unit and conformance tests of the ports your change touches (`pr-ci.yml`); the docker integration suites run on release tags and on manual dispatch — see the *Local CI* section below. -4. Open a **pull request** against `main` and fill out the PR template. -5. A maintainer reviews the change and the checks on the pull request before merge. Who can +4. If users would notice the change, add a changelog entry as a new file under + [`changelog.d/`](changelog.d/README.md). Do not edit `CHANGELOG.md` directly: the release + folds the fragments into it. +5. Open a **pull request** against `main` and fill out the PR template. +6. A maintainer reviews the change and the checks on the pull request before merge. Who can approve what, and which changes need a core maintainer, is in [GOVERNANCE.md](GOVERNANCE.md#how-decisions-are-made). diff --git a/changelog.d/README.md b/changelog.d/README.md new file mode 100644 index 000000000..27079bcd2 --- /dev/null +++ b/changelog.d/README.md @@ -0,0 +1,38 @@ +# Changelog fragments + +Do not edit the `## [Unreleased]` section of `CHANGELOG.md` in a pull request. Add **one new file +here per change** instead. Every PR that edits the top of `[Unreleased]` touches the same lines, +so two PRs in flight conflict as soon as one lands. Two PRs that each add their own file do not. + +At release time `scripts/release.mjs` puts every fragment at the top of `[Unreleased]`, in +file-name order, and deletes the files. The release commit then holds one `CHANGELOG.md`, as +before. To fold them in by hand, for example to prepare a release section ahead of the cut, run +`node scripts/changelog-fragments.mjs --assemble`. `--preview` prints the result without writing +anything. + +## Format + +- **Name:** `.md`, using lower-case letters, digits, `.`, `_` and `-` only, for example + `csharp-verify-model-lints.md`. Pick a name no other open PR is likely to use: the change's + subject, not `fix.md`. +- **Content:** the entry exactly as it would read under `[Unreleased]`. That is one top-level + `- ` bullet, with continuation lines and any further paragraphs or nested bullets indented two + spaces. Put one change in each file and no `#` heading lines. `scripts/ci-local.sh --only gates` + checks this (the `changelog fragments` step). + +```markdown +- **codegen-ts: the finder name follows the field's column.** A field whose `@column` + differs from its name now gets `findBy`. Generated-output change — regenerate to + pick it up; three-way merge preserves hand edits. +``` + +The entry conventions in [docs/RELEASING.md](../docs/RELEASING.md) apply to a fragment as they +apply to the CHANGELOG: + +- A change to generated output carries the phrase **"Generated-output change — regenerate to pick it + up; three-way merge preserves hand edits."** +- A change that moves `metamodelVersion` says that it moved, and to what. +- Upgrade notes go in the same bullet, as an indented paragraph that starts `Upgrading:`. The + release author moves them under the release's `### Upgrading` heading when writing the section. + +Fragments are for unreleased work only. A released section of `CHANGELOG.md` is edited in place. diff --git a/docs/RELEASING-docs-checklist.md b/docs/RELEASING-docs-checklist.md index dbf94aab9..dbd39b4a4 100644 --- a/docs/RELEASING-docs-checklist.md +++ b/docs/RELEASING-docs-checklist.md @@ -19,7 +19,7 @@ by exactly one release. ## A. This repo — `metaobjectsdev/metaobjects` - [ ] `README.md` — per-port version rows (npm + Maven Central). -- [ ] `CHANGELOG.md` — add the release entry. +- [ ] `CHANGELOG.md` — add the release entry (the `changelog.d/` fragments are folded in by `release.mjs`, or by `node scripts/changelog-fragments.mjs --assemble`). - [ ] `CLAUDE.md` — the `## Status` section (version line + "_Last refreshed_" date). - [ ] `docs/llms/llms.txt` — the "Shipping at `` … and `` …" line, the `## Implementations (npm … / Maven Central …)` header, the per-port version diff --git a/docs/RELEASING.md b/docs/RELEASING.md index ee7a48897..9bbe9e1d0 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -437,6 +437,15 @@ unexplained `meta gen` diff after `npm update`; the changelog flag + the planned gen-state engine-version stamp (see the tracking issue) are how you keep every such diff explained. +**Entries arrive as fragments.** A pull request does not edit `CHANGELOG.md`. It adds one file +per change under `changelog.d/`, in the format given in +[`changelog.d/README.md`](../changelog.d/README.md), so that parallel PRs never edit the same +lines. The conventions above apply to a fragment as they do to a CHANGELOG entry. +`scripts/release.mjs` places every fragment at the top of `## [Unreleased]` and deletes the +files before it promotes that section. To write a release section by hand ahead of the cut, run +`node scripts/changelog-fragments.mjs --assemble` first, so the entries you are arranging are in +`CHANGELOG.md`. The release then still ships one changelog. + ## Prerequisites - The JS/TS **workspace root is the repo root** (`/package.json`), globbing diff --git a/scripts/changelog-fragments.mjs b/scripts/changelog-fragments.mjs new file mode 100644 index 000000000..20d984ff1 --- /dev/null +++ b/scripts/changelog-fragments.mjs @@ -0,0 +1,45 @@ +#!/usr/bin/env node +// Changelog fragments (changelog.d/): check them, preview them, or fold them into CHANGELOG.md. +// +// node scripts/changelog-fragments.mjs --check # every fragment is well-formed (gates lane) +// node scripts/changelog-fragments.mjs --preview # print CHANGELOG.md as assembly would write it +// node scripts/changelog-fragments.mjs --assemble # write it, and delete the fragments +// +// `scripts/release.mjs` assembles on its own; run --assemble by hand when preparing a release +// section ahead of the cut, so the entries are in CHANGELOG.md before you edit it. +// The format and why it exists: scripts/lib/changelog-fragments.mjs, changelog.d/README.md. + +import { readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { FRAGMENT_DIR, assembleChangelog, fragmentProblems, readFragments } from "./lib/changelog-fragments.mjs"; + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); +const DIR = join(ROOT, FRAGMENT_DIR); +const CHANGELOG = join(ROOT, "CHANGELOG.md"); +const mode = process.argv[2]; + +const fragments = readFragments(DIR); +const problems = fragments.flatMap((f) => fragmentProblems(f.name, f.text)); +if (problems.length > 0) { + console.error(`${FRAGMENT_DIR}/ has malformed fragments (format: ${FRAGMENT_DIR}/README.md):`); + for (const p of problems) console.error(` ${p}`); + process.exit(1); +} + +if (mode === "--check") { + console.log(`ok: ${fragments.length} changelog fragment(s) well-formed`); +} else if (mode === "--preview") { + process.stdout.write(assembleChangelog(readFileSync(CHANGELOG, "utf8"), fragments)); +} else if (mode === "--assemble") { + if (fragments.length === 0) { + console.log(`no fragments in ${FRAGMENT_DIR}/ — CHANGELOG.md unchanged`); + } else { + writeFileSync(CHANGELOG, assembleChangelog(readFileSync(CHANGELOG, "utf8"), fragments)); + for (const f of fragments) rmSync(join(DIR, f.name)); + console.log(`assembled ${fragments.length} fragment(s) into CHANGELOG.md [Unreleased] and removed them`); + } +} else { + console.error("usage: node scripts/changelog-fragments.mjs --check | --preview | --assemble"); + process.exit(2); +} diff --git a/scripts/ci-lane-map.txt b/scripts/ci-lane-map.txt index f9ee7acc2..34c288050 100644 --- a/scripts/ci-lane-map.txt +++ b/scripts/ci-lane-map.txt @@ -52,6 +52,7 @@ agent-context-shipped/* | ALL | the static agent files every port's pa docs/* | ALL | port tests read it: Java walks every page for blocks and reads docs/ports, TypeScript and Python read the recipes and docs/features pages, so a page edit is not prose-only README.md | NONE | root prose; the gates lane checks its claims, examples and test references CHANGELOG.md | NONE | root prose, same gates +changelog.d/* | NONE | changelog fragments, assembled into CHANGELOG.md at release; the gates lane checks their shape CONTRIBUTING.md | NONE | root prose, same gates AGENTS.md | NONE | root prose, same gates CLAUDE.md | NONE | root prose, same gates diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 055675a82..dfa297cd1 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -319,6 +319,10 @@ gate_publish_intent() { scripts/check-publish-intent.sh; } # could see it. Both paths now read scripts/publish-set.mjs, which also asserts the # set is tier-ordered and closed over its own sibling deps. Offline (manifests only). gate_publish_set() { node scripts/publish-set.mjs --check && node scripts/test-publish-set.mjs; } +# Changelog entries are one file per change under changelog.d/, folded into CHANGELOG.md by +# release.mjs, so parallel PRs do not conflict on the top of [Unreleased]. This checks each +# fragment has the shape assembly expects, and tests the assembly itself. +gate_changelog_fragments() { node scripts/changelog-fragments.mjs --check && node scripts/test-changelog-fragments.mjs; } # ── no root script may be another root script's lifecycle hook ─────────────── # npm and bun both run `pre` before ``, with no per-script opt-out. So @@ -1335,6 +1339,7 @@ run_gates_offline() { if want gates; then step "uv.lock version parity" gate_uv_lock_version; fi if want gates; then step "publish-intent parity" gate_publish_intent; fi if want gates; then step "publish-set parity" gate_publish_set; fi + if want gates; then step "changelog fragments" gate_changelog_fragments; fi if want gates; then step "no committed pre-release version" gate_no_prerelease_versions; fi if want gates; then step "script-name hook collisions" gate_script_name_hooks; fi if want gates; then step "ci lane selection" gate_ci_port_selection; fi diff --git a/scripts/eject-release-gate.test.ts b/scripts/eject-release-gate.test.ts index 90f45b093..19fd66e5a 100644 --- a/scripts/eject-release-gate.test.ts +++ b/scripts/eject-release-gate.test.ts @@ -104,7 +104,7 @@ describe("eject release gate — the command and its wiring", () => { // check after it is the branch check, so a fixture on another branch tells the two apart: // a refused version stops before "not on main", and an allowed one reaches it. test("release.mjs asks the gate first in its preflight, and stops on a refusal", () => { - const RELEASE_SCRIPTS = ["release.mjs", "lib/changelog-promote.mjs", "lib/release-branch.mjs", "publish-set.mjs", "maven-coordinate.mjs"]; + const RELEASE_SCRIPTS = ["release.mjs", "lib/changelog-promote.mjs", "lib/changelog-fragments.mjs", "lib/release-branch.mjs", "publish-set.mjs", "maven-coordinate.mjs"]; const onBranch = (pending: (typeof ENTRY)[]) => { const root = repoWith(JSON.stringify(manifest(pending)), RELEASE_SCRIPTS); const git = (...args: string[]) => spawnSync("git", ["-C", root, ...args], { encoding: "utf8" }); diff --git a/scripts/lib/changelog-fragments.mjs b/scripts/lib/changelog-fragments.mjs new file mode 100644 index 000000000..aca9114fe --- /dev/null +++ b/scripts/lib/changelog-fragments.mjs @@ -0,0 +1,86 @@ +// Changelog fragments: one file per change under `changelog.d/`, folded into CHANGELOG.md at +// release time. +// +// Why: every PR used to add its entry at the top of `## [Unreleased]`, so any two PRs in +// flight edited the same lines and the second to land went conflicting — on 2026-11-22 one +// lane PR conflicted three times in an afternoon, once mid-gate. A PR that adds its own new +// file cannot conflict with another PR that adds a different one. +// +// A fragment is `changelog.d/.md` holding exactly the text the entry would have had +// under `## [Unreleased]`: one top-level `- ` bullet, continuation lines indented. Assembly +// puts the fragments, in file-name order, at the top of `## [Unreleased]` and deletes them, +// so CHANGELOG.md is still the one changelog a release ships. `changelog.d/README.md` is the +// format's documentation and is never assembled. + +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +export const FRAGMENT_DIR = "changelog.d"; +const README = "README.md"; +const NAME = /^[a-z0-9][a-z0-9._-]*\.md$/; +const UNRELEASED = "## [Unreleased]\n"; + +/** + * The fragment file names in `dir`, sorted, README excluded. A missing dir has none. + * @param {string} dir + * @returns {string[]} + */ +export function fragmentNames(dir) { + let entries; + try { + entries = readdirSync(dir, { withFileTypes: true }); + } catch (e) { + if (/** @type {NodeJS.ErrnoException} */ (e).code === "ENOENT") return []; + throw e; + } + return entries.filter((e) => e.isFile() && e.name !== README).map((e) => e.name).sort(); +} + +/** + * Every fragment in `dir` as `{ name, text }`, sorted by name. + * @param {string} dir + * @returns {{ name: string, text: string }[]} + */ +export function readFragments(dir) { + return fragmentNames(dir).map((name) => ({ name, text: readFileSync(join(dir, name), "utf8") })); +} + +/** + * What is wrong with one fragment, as messages naming it. Empty when it is well-formed. + * @param {string} name the file name + * @param {string} text its contents + * @returns {string[]} + */ +export function fragmentProblems(name, text) { + const problems = []; + if (!NAME.test(name)) { + problems.push(`${name}: name must be lower-case letters, digits, '.', '_' or '-', ending in .md`); + } + const body = text.replace(/\s+$/, ""); + if (body === "") return [...problems, `${name}: is empty`]; + if (!body.startsWith("- ")) problems.push(`${name}: must start with a '- ' bullet, as an [Unreleased] entry does`); + const lines = body.split("\n"); + if (lines.some((l) => /^#/.test(l))) { + problems.push(`${name}: must not contain a '#' heading line — it would split the CHANGELOG section it lands in`); + } + if (lines.slice(1).some((l) => l.startsWith("- "))) { + problems.push(`${name}: holds more than one top-level bullet — one change per fragment`); + } + return problems; +} + +/** + * CHANGELOG.md with the fragments at the top of `## [Unreleased]`, in the order given. + * @param {string} changelog the CHANGELOG.md text + * @param {{ name: string, text: string }[]} fragments + * @returns {string} + */ +export function assembleChangelog(changelog, fragments) { + if (fragments.length === 0) return changelog; + const at = changelog.indexOf(UNRELEASED); + if (at === -1) throw new Error("CHANGELOG.md has no '## [Unreleased]' heading to assemble fragments under"); + const head = changelog.slice(0, at + UNRELEASED.length); + const rest = changelog.slice(at + UNRELEASED.length).replace(/^\n+/, ""); + const entries = fragments.map((f) => f.text.replace(/\s+$/, "")).join("\n\n"); + return `${head}\n${entries}\n\n${rest}`; +} diff --git a/scripts/release.mjs b/scripts/release.mjs index b53b0e77e..90c3f42fb 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -24,11 +24,12 @@ // refuses an already-taken version/tag. import { execSync } from "node:child_process"; -import { readFileSync, writeFileSync, mkdtempSync, mkdirSync, existsSync } from "node:fs"; +import { readFileSync, writeFileSync, mkdtempSync, mkdirSync, existsSync, rmSync } from "node:fs"; import { join, dirname } from "node:path"; import { tmpdir, homedir } from "node:os"; import { fileURLToPath } from "node:url"; import { promoteChangelog } from "./lib/changelog-promote.mjs"; +import { FRAGMENT_DIR, assembleChangelog, fragmentProblems, readFragments } from "./lib/changelog-fragments.mjs"; import { createInterface } from "node:readline/promises"; import { publishSet } from "./publish-set.mjs"; import { mavenVersion } from "./maven-coordinate.mjs"; @@ -94,10 +95,15 @@ const unmergedRefusal = unmergedMaintenanceRefusal(VERSION, maintenanceBranches, (b) => Number(out(`git rev-list --count HEAD..origin/${b}`))); if (unmergedRefusal !== null) die(unmergedRefusal); -// Clean tree, except the CHANGELOG (we promote its [Unreleased] section) and untracked noise. +// Clean tree, except the CHANGELOG and its fragments (we assemble the fragments into it and +// promote its [Unreleased] section, so an aborted run leaves both changed) and untracked noise. const dirty = out("git status --porcelain").split("\n") - .filter((l) => l && !l.startsWith("??") && !l.endsWith("CHANGELOG.md")); -if (dirty.length) die(`uncommitted changes:\n${dirty.join("\n")}\n(commit or stash first; CHANGELOG is allowed)`); + .filter((l) => l && !l.startsWith("??") && !l.endsWith("CHANGELOG.md") && !l.slice(3).startsWith(`${FRAGMENT_DIR}/`)); +if (dirty.length) die(`uncommitted changes:\n${dirty.join("\n")}\n(commit or stash first; CHANGELOG and ${FRAGMENT_DIR}/ are allowed)`); + +// Malformed changelog fragments would be folded into the release notes as they are. +const fragmentErrors = readFragments(FRAGMENT_DIR).flatMap((f) => fragmentProblems(f.name, f.text)); +if (fragmentErrors.length) die(`malformed changelog fragments (${FRAGMENT_DIR}/README.md):\n${fragmentErrors.join("\n")}`); if (out(`git tag -l v${VERSION}`)) die(`tag v${VERSION} already exists`); @@ -232,6 +238,17 @@ const bad = Object.entries(pj.dependencies || {}).filter(([k, v]) => k.startsWit if (bad.length) die(`packed cli pins stale/workspace sibling deps: ${JSON.stringify(bad)}`); ok(`packed deps verified: all @metaobjectsdev/* pinned to ${VERSION}`); +// --- fold changelog.d/ fragments into [Unreleased], then promote it -------------- +// One file per change (scripts/lib/changelog-fragments.mjs) keeps parallel PRs from +// conflicting in CHANGELOG.md; here they become ordinary [Unreleased] entries and the files +// go, so the release commit carries one CHANGELOG and an empty changelog.d/. +const fragments = readFragments(FRAGMENT_DIR); +if (fragments.length) { + writeFileSync("CHANGELOG.md", assembleChangelog(readFileSync("CHANGELOG.md", "utf8"), fragments)); + for (const f of fragments) rmSync(join(FRAGMENT_DIR, f.name)); + ok(`${fragments.length} changelog fragment(s) assembled into [Unreleased]`); +} + // --- promote CHANGELOG [Unreleased] → [VERSION], or date a prepared [VERSION] ---- // The rule and its cases live in scripts/lib/changelog-promote.mjs (tested by // scripts/test-changelog-promote.mjs): a section prepared ahead of the cut carries the date it @@ -275,7 +292,7 @@ if (!YES) { } // --- commit the release --------------------------------------------------- -sh("git add server/typescript/packages/*/package.json client/web/packages/*/package.json bun.lock CHANGELOG.md examples/showcase/site-payload.json"); +sh(`git add -A server/typescript/packages/*/package.json client/web/packages/*/package.json bun.lock CHANGELOG.md ${FRAGMENT_DIR} examples/showcase/site-payload.json`); sh(`git commit -q -m "chore(release): @metaobjectsdev TypeScript packages ${VERSION}"`); ok("committed"); diff --git a/scripts/test-changelog-fragments.mjs b/scripts/test-changelog-fragments.mjs new file mode 100644 index 000000000..b19405ef4 --- /dev/null +++ b/scripts/test-changelog-fragments.mjs @@ -0,0 +1,60 @@ +#!/usr/bin/env node +// Tests for scripts/lib/changelog-fragments.mjs. +// +// node scripts/test-changelog-fragments.mjs + +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { assembleChangelog, fragmentNames, fragmentProblems, readFragments } from "./lib/changelog-fragments.mjs"; + +let fails = 0; +const check = (cond, label) => (cond ? console.log(`ok: ${label}`) : (console.error(`FAIL: ${label}`), fails++)); + +const LOG = "# Changelog\n\n## [Unreleased]\n\n- an entry already here\n\n## [1.2.3] — 2026-11-15\n\n- old\n"; +const A = { name: "a-fix.md", text: "- **A fix.** It reads\n two lines.\n" }; +const B = { name: "b-feature.md", text: "- **A feature.**\n\n With a second paragraph.\n\n" }; + +let r = assembleChangelog(LOG, [A, B]); +check( + r === "# Changelog\n\n## [Unreleased]\n\n- **A fix.** It reads\n two lines.\n\n- **A feature.**\n\n With a second paragraph.\n\n- an entry already here\n\n## [1.2.3] — 2026-11-15\n\n- old\n", + "fragments land at the top of [Unreleased], in order, one blank line apart, above the existing entries", +); +check(assembleChangelog(LOG, []) === LOG, "no fragments leaves the CHANGELOG byte-identical"); + +const empty = "# Changelog\n\n## [Unreleased]\n\n## [1.3.0] — unreleased\n\n- prepared\n"; +r = assembleChangelog(empty, [A]); +check(r.includes("## [Unreleased]\n\n- **A fix.** It reads\n two lines.\n\n## [1.3.0] — unreleased"), "an empty [Unreleased] above a prepared section gains the entry, and the section below is untouched"); + +let threw = false; +try { assembleChangelog("# Changelog\n", [A]); } catch { threw = true; } +check(threw, "a CHANGELOG with no [Unreleased] heading refuses rather than dropping fragments"); + +check(fragmentProblems(A.name, A.text).length === 0, "a one-bullet fragment is well-formed"); +check(fragmentProblems(B.name, B.text).length === 0, "a fragment with an indented second paragraph is well-formed"); +check(fragmentProblems("x.md", " \n").some((p) => p.includes("empty")), "an empty fragment is refused"); +check(fragmentProblems("x.md", "A sentence.\n").some((p) => p.includes("bullet")), "a fragment that is not a bullet is refused"); +check(fragmentProblems("x.md", "- one\n- two\n").some((p) => p.includes("one change")), "two top-level bullets are refused"); +check(fragmentProblems("x.md", "- one\n - nested\n").length === 0, "a nested bullet is allowed"); +check(fragmentProblems("x.md", "- one\n### Fixed\n").some((p) => p.includes("heading")), "a heading line is refused"); +check(fragmentProblems("Bad Name.md", "- ok\n").some((p) => p.includes("name")), "a name with capitals or spaces is refused"); +check(fragmentProblems("x.txt", "- ok\n").some((p) => p.includes("name")), "a name not ending in .md is refused"); + +const dir = mkdtempSync(join(process.env.DEV_SCRATCH || tmpdir(), "changelog-fragments-")); +try { + check(fragmentNames(join(dir, "absent")).length === 0, "a missing changelog.d/ has no fragments"); + writeFileSync(join(dir, "README.md"), "# not an entry\n"); + writeFileSync(join(dir, "b.md"), "- b\n"); + writeFileSync(join(dir, "a.md"), "- a\n"); + mkdirSync(join(dir, "sub")); + const read = readFragments(dir); + check(read.map((f) => f.name).join(",") === "a.md,b.md", "fragments are read in name order, README and directories skipped"); +} finally { + rmSync(dir, { recursive: true, force: true }); +} + +if (fails > 0) { + console.error(`\n${fails} check(s) failed`); + process.exit(1); +} +console.log("\nall checks passed"); diff --git a/scripts/test-ci-lane-selection.sh b/scripts/test-ci-lane-selection.sh index b1f26ab55..22abe9f58 100755 --- a/scripts/test-ci-lane-selection.sh +++ b/scripts/test-ci-lane-selection.sh @@ -49,6 +49,7 @@ check "$ALL" "$(lanes docs/features/cli.md)" check "$ALL" "$(lanes docs/ports/java.md)" "the java port doc is read by a java test" check "$ALL" "$(lanes examples/foo/README.md)" "markdown outside the named root files is unmapped" check "" "$(lanes README.md CHANGELOG.md CONTRIBUTING.md)" "root prose only: no test lane, the gates lane checks it" +check "" "$(lanes changelog.d/some-fix.md)" "a changelog fragment is prose: no test lane" check "python" "$(lanes server/python/README.md)" "a port's own markdown still selects the port" check "" "$(lanes)" "empty diff: no test lane" diff --git a/tsconfig.scripts.json b/tsconfig.scripts.json index 5017d91fd..09f80295d 100644 --- a/tsconfig.scripts.json +++ b/tsconfig.scripts.json @@ -143,6 +143,7 @@ "scripts/maven-coordinate.mjs", "scripts/eject-release-gate.mjs", "scripts/lib/changelog-promote.mjs", + "scripts/lib/changelog-fragments.mjs", "scripts/lib/release-branch.mjs", "scripts/check-release-tag.mjs" ] From 4431b87e94471841a109a7e041cde76594dea314 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 21:08:22 -0500 Subject: [PATCH 04/35] =?UTF-8?q?feat(cli):=20meta=20verify=20advises=20on?= =?UTF-8?q?=20a=20lifecycle=20no=20service=20generator=20enforces=20(ADR-0?= =?UTF-8?q?067=20=C2=A76)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A concrete entity with a source and a lifecycle, in a project whose generators list no service generator covering it (by stable name, or a serviceFile() whose filter keeps it), is named in verify's advisory tier as rule "unenforced-lifecycle". Never an exit code. Part of L-TS-7; the init flag, docs and gen --list follow. --- .../packages/cli/src/commands/verify.ts | 24 +++ .../packages/cli/src/lib/advisory.ts | 22 +++ .../src/lib/unenforced-lifecycle-advisory.ts | 79 ++++++++++ .../test/verify-unenforced-lifecycle.test.ts | 139 ++++++++++++++++++ 4 files changed, 264 insertions(+) create mode 100644 server/typescript/packages/cli/src/lib/unenforced-lifecycle-advisory.ts create mode 100644 server/typescript/packages/cli/test/verify-unenforced-lifecycle.test.ts diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index a0b2a3dc6..5a78d1926 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -23,11 +23,13 @@ import { unindexedFkRows, warnAdvisory, referentialActionConflictRows, + unenforcedLifecycleRows, advisoryHelpLines, } from "../lib/advisory.js"; import { scanForUnprovenancedLibraryPrefix } from "../lib/library-prefix-advisory.js"; import { scanForUnindexedForeignKeys, summarizeUnindexedFks, type UnindexedFkFinding } from "../lib/fk-index-advisory.js"; import { scanForReferentialActionConflicts, type ReferentialActionConflictFinding } from "../lib/referential-action-advisory.js"; +import { scanForUnenforcedLifecycles, type GeneratorEntry, type UnenforcedLifecycleFinding } from "../lib/unenforced-lifecycle-advisory.js"; import { warnIfAgentContextMissesRequirements, warnIfAgentContextStale } from "../lib/agent-context-staleness.js"; import { warnIfManifestIgnored } from "../lib/manifest-ignored-check.js"; import { scanSourceForAntiPatterns } from "../lib/anti-patterns.js"; @@ -1166,6 +1168,20 @@ export async function verifyCommand( // advisory only — a model the schema builder refuses is migrate's to report. } + // ADR-0067 §6 — a lifecycle in a project whose generators include no service for that + // entity: the flat routes enforce nothing. Only with a loaded config, since the generator + // list is what it reads; a project without one (a non-TypeScript port's) has its own list. + let unenforcedLifecycles: UnenforcedLifecycleFinding[] = []; + try { + if (forgeConfig !== undefined) { + unenforcedLifecycles = scanForUnenforcedLifecycles( + root, forgeConfig.generators as readonly GeneratorEntry[], { skip: collection.imported }, + ); + } + } catch { + // advisory only — never breaks verify. + } + const unindexedFkSummary = summarizeUnindexedFks(unindexedFks); antiPatternSection = ranSection([ ...antiPatternRows(findings), @@ -1174,6 +1190,7 @@ export async function verifyCommand( ...libraryPrefixRows(libraryPrefix), ...unindexedFkRows(unindexedFkSummary === undefined ? [] : [unindexedFkSummary]), ...referentialActionConflictRows(actionConflicts), + ...unenforcedLifecycleRows(unenforcedLifecycles), ]); if (findings.length > 0) { log.warn( @@ -1210,6 +1227,13 @@ export async function verifyCommand( ); warnAdvisory(actionConflicts.map((f) => ` ${f.message}`), flags.limit, { structured }); } + if (unenforcedLifecycles.length > 0) { + log.warn( + `meta verify — ${unenforcedLifecycles.length} entit(ies) declare a lifecycle no service generator ` + + `enforces (advisory — does not fail the build):`, + ); + warnAdvisory(unenforcedLifecycles.map((f) => ` ${f.message}`), flags.limit, { structured }); + } if (libraryPrefix.length > 0) { log.warn( `meta verify — ${libraryPrefix.length} node(s) declared under "metaobjects::" with ` + diff --git a/server/typescript/packages/cli/src/lib/advisory.ts b/server/typescript/packages/cli/src/lib/advisory.ts index da5166758..4164670ce 100644 --- a/server/typescript/packages/cli/src/lib/advisory.ts +++ b/server/typescript/packages/cli/src/lib/advisory.ts @@ -115,6 +115,7 @@ export const RULE_REMOVED_PROP_PREFIX = "removed-prop:"; export const RULE_LIBRARY_PREFIX = "library-prefix-unprovenanced"; export const RULE_UNINDEXED_FK = "unindexed-foreign-key"; export const RULE_REFERENTIAL_ACTION_CONFLICT = "overridden-referential-action"; +export const RULE_UNENFORCED_LIFECYCLE = "unenforced-lifecycle"; /** The next-step line for `n` rows of one advisory kind, each naming what the rows are. */ const ADVISORY_HELP: ReadonlyArray<{ matches: (rule: string) => boolean; line: (n: number) => string }> = [ @@ -128,6 +129,11 @@ const ADVISORY_HELP: ReadonlyArray<{ matches: (rule: string) => boolean; line: ( line: (n) => `${n} foreign key(s) whose two sides disagree on the referential action — see antiPatterns.rows[] (rule "${RULE_REFERENTIAL_ACTION_CONFLICT}")`, }, + { + matches: (r) => r === RULE_UNENFORCED_LIFECYCLE, + line: (n) => + `${n} entit(ies) with a lifecycle no service generator enforces — see antiPatterns.rows[] (rule "${RULE_UNENFORCED_LIFECYCLE}")`, + }, { matches: (r) => r === RULE_MISSING_BASE_URL, line: (n) => @@ -246,6 +252,22 @@ export function unindexedFkRows( })); } +/** + * Lifecycles no service generator enforces, in the same row shape. `construct` is the entity's + * FQN; there is no line, for the same reason as {@link unindexedFkRows}. + */ +export function unenforcedLifecycleRows( + findings: readonly { file: string; construct: string; message: string }[], +): AdvisoryFindingRow[] { + return findings.map((f) => ({ + file: f.file, + line: 0, + rule: RULE_UNENFORCED_LIFECYCLE, + construct: f.construct, + message: f.message, + })); +} + /** * Relationships on both sides of one FK that disagree on its referential action, in the * same row shape. `construct` is `.` — the FK, where the fix goes. diff --git a/server/typescript/packages/cli/src/lib/unenforced-lifecycle-advisory.ts b/server/typescript/packages/cli/src/lib/unenforced-lifecycle-advisory.ts new file mode 100644 index 000000000..b163e61c8 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/unenforced-lifecycle-advisory.ts @@ -0,0 +1,79 @@ +// A lifecycle no generated code enforces (ADR-0067 §6). +// +// An enum with a transition is a lifecycle: the model says a row moves from state to state +// only by its transitions, and a command per transition asks the policy first (ADR-0066). The +// layer that enforces that is the service (`serviceFile()`, stable name `service`). The flat +// routes generators write no rules at all, by decision: a project that asked for nothing sees +// no change in their output. So a project that declares a lifecycle and wires no service +// generator for that entity has rules nothing checks: an update can set the state field to any +// member, and no permission is asked. +// +// Advisory, never a gate: the project may enforce the lifecycle in code of its own, or not +// serve the entity at all. This names each such entity and the generator that would enforce it. +// It reads the project's `generators` list, so it is TypeScript's own: each port's list lives in +// its own build configuration (ADR-0067 §5). + +import type { MetaData } from "@metaobjectsdev/metadata"; +import { commandEntities, lifecyclesOf } from "@metaobjectsdev/metadata"; + +/** The stable name of the generator that enforces a lifecycle (and of its ejected copy). */ +export const SERVICE_GENERATOR_NAME = "service"; + +/** One `generators` entry as the config declares it: a stable name, or a generator object. */ +export type GeneratorEntry = string | { name: string; filter?: (entity: MetaData) => boolean }; + +export interface UnenforcedLifecycleFinding { + /** The metadata file declaring the entity ("" when the loader recorded none). */ + file: string; + /** The entity's FQN. */ + construct: string; + message: string; +} + +export interface UnenforcedLifecycleOptions { + /** Skip an entity by FQN: imported (dependency) metadata is not the adopter's to fix. */ + skip?: (fqn: string) => boolean; +} + +/** True when some entry is the service generator and its own filter keeps `entity`. */ +function serviceCovers(generators: readonly GeneratorEntry[], entity: MetaData): boolean { + return generators.some((g) => + typeof g === "string" + ? g === SERVICE_GENERATOR_NAME + : g.name === SERVICE_GENERATOR_NAME && (g.filter?.(entity) ?? true), + ); +} + +/** + * Every concrete entity with a source and a lifecycle that no listed service generator covers. + * An entity with no source is inert (it derives no command), so it is not named. + */ +export function scanForUnenforcedLifecycles( + root: MetaData, + generators: readonly GeneratorEntry[], + opts: UnenforcedLifecycleOptions = {}, +): UnenforcedLifecycleFinding[] { + const out: UnenforcedLifecycleFinding[] = []; + for (const entity of commandEntities(root)) { + const lifecycles = lifecyclesOf(entity); + if (lifecycles.length === 0) continue; + const fqn = entity.resolutionKey(); + if (opts.skip?.(fqn) === true) continue; + const files = "files" in entity.source ? entity.source.files : []; + // A node a shipped library contributed is the library's design, not the adopter's. + if (files.some((f) => f.startsWith("library:"))) continue; + if (serviceCovers(generators, entity)) continue; + const fields = lifecycles.map((l) => `"${l.field.name}"`).join(", "); + out.push({ + file: files[0] ?? "", + construct: fqn, + message: + `${fqn} declares a lifecycle on ${fields}, and no service generator covers it, so nothing ` + + `generated enforces its transitions or asks its permissions: the flat routes write the field ` + + `like any other. Add serviceFile() (stable name "service") with contractTypes() and a ` + + `transport (serviceRoutesFile() or serviceRoutesHonoFile()) to \`generators\`, or enforce ` + + `the lifecycle in code of your own and ignore this.`, + }); + } + return out; +} diff --git a/server/typescript/packages/cli/test/verify-unenforced-lifecycle.test.ts b/server/typescript/packages/cli/test/verify-unenforced-lifecycle.test.ts new file mode 100644 index 000000000..b039adc3e --- /dev/null +++ b/server/typescript/packages/cli/test/verify-unenforced-lifecycle.test.ts @@ -0,0 +1,139 @@ +/** + * `meta verify` — a lifecycle no service generator enforces (ADR-0067 §6). + * + * The flat routes generators write no rules, by decision, so a project that declares a lifecycle + * and lists no service generator for that entity has transitions and permissions nothing checks. + * `verify` names each such entity in its advisory tier and never fails the build on it. + */ +import { describe, test, expect, afterAll } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { InMemoryStringSource, MetaDataLoader, type MetaData } from "@metaobjectsdev/metadata"; +import { verifyCommand } from "../src/commands/verify.js"; +import { scanForUnenforcedLifecycles } from "../src/lib/unenforced-lifecycle-advisory.js"; + +const SCRATCH = process.env.DEV_SCRATCH ?? tmpdir(); +const dirs: string[] = []; +afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); }); + +const order = (extra: Record = {}): Record => ({ + "object.entity": { name: "Order", ...extra, children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + { "field.enum": { name: "status", "@values": ["draft", "placed"], "@default": "draft", children: [ + { "transition.action": { name: "place", "@from": ["draft"], "@to": "placed" } }, + ] } }, + ] }, +}); + +/** A second entity with a lifecycle and no source: inert, so never named. */ +const SOURCELESS = { + "object.entity": { name: "Draft", children: [ + { "field.long": { name: "id" } }, + { "field.enum": { name: "state", "@values": ["open", "shut"], "@default": "open", children: [ + { "transition.action": { name: "shut", "@from": ["open"], "@to": "shut" } }, + ] } }, + ] }, +}; + +const MODEL = JSON.stringify({ "metadata.root": { package: "acme::shop", children: [order(), SOURCELESS] } }); + +function project(generators: string): string { + const root = mkdtempSync(join(SCRATCH, "verify-lifecycle-")); + dirs.push(root); + mkdirSync(join(root, "metaobjects"), { recursive: true }); + writeFileSync(join(root, "metaobjects", "meta.shop.json"), MODEL, "utf8"); + writeFileSync( + join(root, "metaobjects.config.ts"), + `import { defineConfig } from "@metaobjectsdev/codegen-ts"; +export default defineConfig({ + outDir: ${JSON.stringify(join(root, "generated"))}, + dialect: "sqlite", + extStyle: "none", + generators: ${generators}, +}); +`, + ); + return root; +} + +async function capture(fn: () => Promise): Promise<{ code: number; out: string }> { + const lines: string[] = []; + const log = console.log; + const err = console.error; + console.log = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + console.error = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + try { + return { code: await fn(), out: lines.join("\n") }; + } finally { + console.log = log; + console.error = err; + } +} + +async function loadModel(doc: unknown): Promise { + const r = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + if (r.errors.length > 0) throw new Error(r.errors.map((e) => e.message).join("\n")); + return r.root; +} + +async function loaded(): Promise { + return loadModel(JSON.parse(MODEL)); +} + +describe("a lifecycle no service generator enforces (advisory)", () => { + test("verify names the entity when the generators include no service, and passes", async () => { + const root = project(`[]`); + const { code, out } = await capture(() => verifyCommand(["--templates"], root)); + expect(code).toBe(0); + expect(out).toContain("1 entit(ies) declare a lifecycle no service generator enforces"); + expect(out).toContain(`acme::shop::Order declares a lifecycle on "status"`); + expect(out).not.toContain("acme::shop::Draft"); + }); + + test("a listed service generator silences it", async () => { + const root = project(`["service"]`); + const { code, out } = await capture(() => verifyCommand(["--templates"], root)); + expect(code).toBe(0); + expect(out).not.toContain("no service generator enforces"); + }); + + test("the structured payload carries one row keyed to the entity", async () => { + const root = project(`[]`); + const lines: string[] = []; + const log = console.log; + const err = console.error; + console.log = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + console.error = () => {}; + try { + expect(await verifyCommand(["--templates"], root, undefined, "json")).toBe(0); + } finally { + console.log = log; + console.error = err; + } + const payload = JSON.parse(lines.join("\n")) as { antiPatterns: { rows: { rule: string; construct: string }[] } }; + const rows = payload.antiPatterns.rows.filter((r) => r.rule === "unenforced-lifecycle"); + expect(rows.map((r) => r.construct)).toEqual(["acme::shop::Order"]); + }); + + test("a service generator whose filter drops the entity does not cover it", async () => { + const root = await loaded(); + const keep = (keepIt: boolean) => [{ name: "service", filter: () => keepIt }]; + expect(scanForUnenforcedLifecycles(root, keep(false)).map((f) => f.construct)).toEqual(["acme::shop::Order"]); + expect(scanForUnenforcedLifecycles(root, keep(true))).toEqual([]); + expect(scanForUnenforcedLifecycles(root, [{ name: "routes" }]).map((f) => f.construct)).toEqual(["acme::shop::Order"]); + }); + + test("a model with no lifecycle has nothing to name", async () => { + const root = await loadModel({ "metadata.root": { package: "acme::shop", children: [ + { "object.entity": { name: "Plain", children: [ + { "source.rdb": { "@table": "plain" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + ] } }); + expect(scanForUnenforcedLifecycles(root, [])).toEqual([]); + }); +}); From 9bd64c35355dd19c296bf1a1676aa323efaff88b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 21:36:18 -0500 Subject: [PATCH 05/35] =?UTF-8?q?feat(cli):=20meta=20init=20--with-service?= =?UTF-8?q?s=20wires=20the=20recommended=20service=20list=20(ADR-0067=20?= =?UTF-8?q?=C2=A78)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit init still writes an empty generator list. --with-services writes entityFile(), rulesNamesFile(), contractTypes(), serviceFile() and serviceRoutesFile() instead (serviceFile({ interactiveTransactions: false }) on D1), read from the generator registry, and prints the install set their output needs. On an existing config it leaves the file alone and says what to add. meta gen --list names the same list once under the catalog. ADR-0066/0067, business-rules.md, cli.md and the CHANGELOG now describe the shipped unenforced-lifecycle advisory instead of "once that check lands". Completes L-TS-7. --- CHANGELOG.md | 9 +++ docs/features/business-rules.md | 14 +++- docs/features/cli.md | 2 +- .../packages/cli/src/commands/init.ts | 73 +++++++++++++++---- server/typescript/packages/cli/src/index.ts | 3 + .../typescript/packages/cli/src/lib/args.ts | 3 + .../packages/cli/src/lib/catalog-listing.ts | 10 +++ .../cli/src/lib/recommended-services.ts | 48 ++++++++++++ .../packages/cli/test/catalog-listing.test.ts | 17 ++++- .../typescript/packages/cli/test/cli.test.ts | 6 +- .../typescript/packages/cli/test/init.test.ts | 51 +++++++++++++ ...usiness-rules-operations-and-lifecycles.md | 4 +- .../ADR-0067-layering-and-the-service-seam.md | 10 ++- 13 files changed, 225 insertions(+), 25 deletions(-) create mode 100644 server/typescript/packages/cli/src/lib/recommended-services.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 440cceef2..5ea8f58aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,15 @@ here.** ## [Unreleased] +- **cli: `meta init --with-services` and the `unenforced-lifecycle` advisory (ADR-0067 §6, §8).** + `init` still writes an empty generator list; `--with-services` writes the recommended service list + instead (`entityFile()`, `rulesNamesFile()`, `contractTypes()`, `serviceFile()`, + `serviceRoutesFile()`, with `serviceFile({ interactiveTransactions: false })` on `--d1`) and names + the packages their output needs. `meta gen --list` names the same list under the catalog. + `meta verify` now advises, without changing the exit code, when a concrete entity with a source + declares a lifecycle and no listed service generator covers it: the flat routes do not enforce + it. + - **The deprecated-reference finding ends its sentence before naming the replacement.** It read `…Team: the league no longer tracks teams Replaced by acme::app::Club.`; it now reads `…tracks teams. Replaced by acme::app::Club.` A reason that already ends in `.`, `!` or `?` is left as written. - **C#: `dotnet meta verify` runs the three model authoring lints.** The overlay lint diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index d4c511964..a1d3effcd 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -28,9 +28,9 @@ declared write rules, behind a thin Fastify transport (`service-routes`) or Hono [The service layer](#the-service-layer-typescript)). It also writes a command per transition and a shell per declared command and query, and enforces at run time what this page declares: the permission point, the state check, the guarded update, `state_managed` and the declared errors, held to the shared API tests' `rules/` corpus. The other ports' services are -later 1.3.0 work. A lifecycle in a project that wires no service generator will be advised by -`verify` once that check lands; until then the flat routes enforce nothing and `verify` says -nothing about it. Every flat generator writes byte-identical code for +later 1.3.0 work. A lifecycle in a project that wires no service generator covering it is +named by Node `meta verify` as an advisory (rule `unenforced-lifecycle`, never an exit code); the +flat routes enforce nothing. Every flat generator writes byte-identical code for a model with this vocabulary and the same model without it. The design is [ADR-0066](../../spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md). **Experimental.** This vocabulary, its loader rules, its `verify` checks and its settings may @@ -404,6 +404,14 @@ await withWriteTransaction(db, async (tx) => { }); ``` +A new project gets the recommended list with `meta init --with-services`: `entityFile()`, +`rulesNamesFile()`, `contractTypes()`, `serviceFile()` and `serviceRoutesFile()` (on `--d1`, the +service is `serviceFile({ interactiveTransactions: false })`), and init prints what their output +needs installed. It is a list, not a mode: swap `serviceRoutesFile()` for `serviceRoutesHonoFile()`, +or narrow `serviceFile()` with its `filter`, as with any generator. In a project that declares a +lifecycle and wires no service generator covering it, `meta verify` advises that nothing generated +enforces it (rule `unenforced-lifecycle`); the flat routes write the lifecycle field like any other. + Both import the entity module (`entity`, for the table and the allowlists) and the contract types (`contract-types`), written to the same target, and `@metaobjectsdev/runtime-ts`'s `service` and `service/fastify` (or `service/hono`) entries; `meta eject service`, `meta eject service-routes` and diff --git a/docs/features/cli.md b/docs/features/cli.md index 5e08e4201..5215eaa13 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -25,7 +25,7 @@ command surface splits in two: | Capability | Tool | Invocation | Notes | |---|---|---|---| -| 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 | +| 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. `--with-services` wires the recommended service list ([business-rules.md](business-rules.md#the-service-layer-typescript)) instead of the empty one, and `--with-docs` the two docs generators | | **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) | diff --git a/server/typescript/packages/cli/src/commands/init.ts b/server/typescript/packages/cli/src/commands/init.ts index 42aa92e59..42f69ecc6 100644 --- a/server/typescript/packages/cli/src/commands/init.ts +++ b/server/typescript/packages/cli/src/commands/init.ts @@ -16,7 +16,14 @@ import { currentContentHash } from "../lib/agent-context-staleness.js"; import { findWranglerConfig, parseWranglerConfig } from "@metaobjectsdev/migrate-ts"; import { DEFAULT_DOCS_DIR } from "@metaobjectsdev/codegen-ts"; import { describeError } from "../lib/error-text.js"; -import { ownPeerRange } from "../lib/install-set.js"; +import { installSetFor, ownPeerRange } from "../lib/install-set.js"; +import { + RECOMMENDED_SERVICE_GENERATORS, + RECOMMENDED_SERVICE_IMPORT, + recommendedServiceCalls, + recommendedServiceEntries, + recommendedServiceListText, +} from "../lib/recommended-services.js"; import { declaredDependencyNames, type PackageManifest } from "../lib/package-manifest.js"; import { SUBTYPE_ROOT, TYPE_METADATA, TYPE_SUBTYPE_SEPARATOR } from "@metaobjectsdev/metadata/constants"; import { docsRefForVersion } from "@metaobjectsdev/metadata"; @@ -120,17 +127,24 @@ function codegenDialectOf(dialect: InitDialect): CodegenDialect { return dialect === "d1" ? "sqlite" : dialect; } -function buildMetaobjectsConfigBody(dialect: CodegenDialect = "sqlite", withDocs = false): string { - const docsImport = withDocs - ? `import { docsFile, apiDocsFile } from "@metaobjectsdev/codegen-ts/generators";\n` - : ""; +function buildMetaobjectsConfigBody(dialect: InitDialect = "sqlite", withDocs = false, withServices = false): string { + // --with-services: the recommended service list (ADR-0067 §5.1, §8). D1 holds no transaction + // across application code, so its service is generated without one. + const serviceCalls = withServices ? recommendedServiceCalls({ interactiveTransactions: dialect !== "d1" }) : []; + const factories = [ + ...(withServices ? recommendedServiceEntries().map((e) => e.factoryExport) : []), + ...(withDocs ? ["docsFile", "apiDocsFile"] : []), + ]; + const generatorsImport = + factories.length > 0 ? `import { ${factories.join(", ")} } from "${RECOMMENDED_SERVICE_IMPORT}";\n` : ""; const docsTarget = withDocs ? ` targets: { docs: { outDir: "${DEFAULT_DOCS_DIR}" } },\n` : ""; - const generators = withDocs ? "[docsFile(), apiDocsFile()]" : "[]"; + const calls = [...serviceCalls, ...(withDocs ? ["docsFile()", "apiDocsFile()"] : [])]; + const generators = `[${calls.join(", ")}]`; return `import { defineConfig } from "@metaobjectsdev/cli"; -${docsImport} +${generatorsImport} export default defineConfig({ outDir: "${SCAFFOLD_OUT_DIR}", - dialect: "${dialect}", + dialect: "${codegenDialectOf(dialect)}", // One directory per metadata package (acme::commerce -> acme/commerce/), so two objects // with one name in two packages are two files. barrel() still exports every name from one // module, so with a barrel listed that pair is ERR_NAME_COLLISION. Omit it for the flat layout. @@ -147,6 +161,10 @@ export default defineConfig({ // // meta gen --list --probe // + // The service layers (one transaction per write, the declared rules enforced, a thin transport) + // are a recommended list of their own: \`meta init --with-services\` writes it, or add + // ${recommendedServiceListText()}. + // // Documentation is chosen the same way (docsFile(), apiDocsFile(), agentDocsFile()), with // a docs target beside \`generators\`: targets: { docs: { outDir: "${DEFAULT_DOCS_DIR}" } }, // @@ -238,6 +256,12 @@ export interface InitOptions { * is a generator like any other; this only chooses the two that need no further setup. */ withDocs?: boolean; + /** + * Wire the recommended service list (ADR-0067 §5.1, §8): `entityFile()`, `rulesNamesFile()`, + * `contractTypes()`, `serviceFile()` and `serviceRoutesFile()`. On D1 the service is generated + * with `interactiveTransactions: false`. Without the flag the list stays empty. + */ + withServices?: boolean; } export interface InitResult { @@ -822,13 +846,33 @@ export async function init(opts: InitOptions): Promise { // Scaffold metaobjects.config.ts at the project root. Never overwrite if it exists. const forgeConfigPath = join(opts.cwd, "metaobjects.config.ts"); if (!(await fileExists(forgeConfigPath))) { - await writeFile(forgeConfigPath, buildMetaobjectsConfigBody(codegenDialectOf(resolveInitDialect(opts)), opts.withDocs === true), "utf8"); - result.created.push("metaobjects.config.ts"); - } else if (opts.withDocs === true) { - result.warnings.push( - "--with-docs: metaobjects.config.ts already exists and was left alone. To write the docs, add " + - "`docsFile()` and `apiDocsFile()` from @metaobjectsdev/codegen-ts/generators to its `generators` list.", + await writeFile( + forgeConfigPath, + buildMetaobjectsConfigBody(resolveInitDialect(opts), opts.withDocs === true, opts.withServices === true), + "utf8", ); + result.created.push("metaobjects.config.ts"); + if (opts.withServices === true) { + // The flag wires generators whose output imports runtime packages; say what to install now, + // the way `meta eject` does, rather than at the first failing compile. + result.warnings.push( + `--with-services: wired ${RECOMMENDED_SERVICE_GENERATORS.join(", ")}. Their output needs: ` + + installSetFor(recommendedServiceEntries()).command, + ); + } + } else { + if (opts.withDocs === true) { + result.warnings.push( + "--with-docs: metaobjects.config.ts already exists and was left alone. To write the docs, add " + + "`docsFile()` and `apiDocsFile()` from @metaobjectsdev/codegen-ts/generators to its `generators` list.", + ); + } + if (opts.withServices === true) { + result.warnings.push( + "--with-services: metaobjects.config.ts already exists and was left alone. To generate the service " + + `layers, add ${recommendedServiceListText()} to its \`generators\` list.`, + ); + } } // Scaffold a minimal root .gitignore ONLY when the project has none — never @@ -1088,6 +1132,7 @@ export async function initCommand(args: string[], cwd: string): Promise docsOnly: flags.docsOnly, configOnly: flags.configOnly, withDocs: flags.withDocs, + withServices: flags.withServices, }); if (result.alreadyInitialized) { diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts index b5598b85c..49620fedf 100644 --- a/server/typescript/packages/cli/src/index.ts +++ b/server/typescript/packages/cli/src/index.ts @@ -574,6 +574,9 @@ FLAGS: metadata sources for the Node CLI from a Maven- or pip-rooted project --with-docs Wire docsFile() and apiDocsFile() and a docs target in the scaffolded config, so the first \`meta gen\` writes documentation + --with-services Wire the recommended service list (entityFile(), rulesNamesFile(), + contractTypes(), serviceFile(), serviceRoutesFile()) instead of an + empty one: one transaction per write, the declared rules enforced --help, -h Print this help `, "agent-docs": `meta agent-docs — scaffold the agent-context (.metaobjects/AGENTS.md + the metaobjects-* skills) diff --git a/server/typescript/packages/cli/src/lib/args.ts b/server/typescript/packages/cli/src/lib/args.ts index 03f030cc2..b619cc6a3 100644 --- a/server/typescript/packages/cli/src/lib/args.ts +++ b/server/typescript/packages/cli/src/lib/args.ts @@ -23,6 +23,7 @@ export interface InitFlags { docsOnly: boolean; configOnly: boolean; withDocs: boolean; + withServices: boolean; } /** The flag table `parseInitArgs` parses. Exported so the help text can be gated against it. */ @@ -41,6 +42,7 @@ export const INIT_OPTIONS = { "docs-only": { type: "boolean", default: false }, "config-only": { type: "boolean", default: false }, "with-docs": { type: "boolean", default: false }, + "with-services": { type: "boolean", default: false }, } as const; export function parseInitArgs(argv: string[]): InitFlags { @@ -65,6 +67,7 @@ export function parseInitArgs(argv: string[]): InitFlags { docsOnly: !!values["docs-only"], configOnly: !!values["config-only"], withDocs: !!values["with-docs"], + withServices: !!values["with-services"], }; } diff --git a/server/typescript/packages/cli/src/lib/catalog-listing.ts b/server/typescript/packages/cli/src/lib/catalog-listing.ts index df1f0e496..1fdc89f28 100644 --- a/server/typescript/packages/cli/src/lib/catalog-listing.ts +++ b/server/typescript/packages/cli/src/lib/catalog-listing.ts @@ -36,6 +36,7 @@ import { type LibraryCatalogRow, type LibraryProjectContext, } from "./library-listing.js"; import { installSetFor } from "./install-set.js"; +import { RECOMMENDED_SERVICE_GENERATORS } from "./recommended-services.js"; import { RUNTIME_ENTRIES, resolveRuntimePackage, runtimeClosure, runtimeCopyStatus, runtimeInstall, type RuntimeCopyRow, @@ -508,6 +509,14 @@ export const REFERENCE_HELPER_NOTE: readonly string[] = [ "references/any-stack.md has the procedure. MySQL is `dialect: \"mysql\"`.", ]; +/** + * The footer line naming the recommended service list (ADR-0067 §5.1): a list, not a mode, so it + * is said once here rather than as a mark on five rows. + */ +export const RECOMMENDED_SERVICE_NOTE = + `Service layers, recommended together: ${RECOMMENDED_SERVICE_GENERATORS.join(", ")}. ` + + "`meta init --with-services` wires them in a new project."; + /** The footer line explaining the `package-only` row mark. */ export const PACKAGE_ONLY_NOTE = "package-only = no reference template ships for it, so `meta eject` cannot copy it. " + @@ -588,6 +597,7 @@ export function renderCatalogText(rows: CatalogRow[], probed: boolean): string { lines.push("`generators: [...]`. To change what one emits, `meta eject ` copies it into"); lines.push("codegen/generators/ and prints the import to swap in, the entry to wire, and what to install."); if (generators.some((r) => !r.source.ejectable)) lines.push(PACKAGE_ONLY_NOTE); + if (generators.some((r) => r.layer === "service")) lines.push(RECOMMENDED_SERVICE_NOTE); if (!probed) { lines.push("Add --probe to see how many files each would emit for YOUR model."); } diff --git a/server/typescript/packages/cli/src/lib/recommended-services.ts b/server/typescript/packages/cli/src/lib/recommended-services.ts new file mode 100644 index 000000000..236928f57 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/recommended-services.ts @@ -0,0 +1,48 @@ +// recommended-services.ts — the one list MetaObjects recommends for the TypeScript service layers +// (ADR-0067 §5.1): the names, the contract types, data access, the service and its transport. +// +// It is documentation and what `meta init --with-services` writes (§8), never a mode: an app adds, +// removes, configures or replaces an entry the way it does any other. Defined once here, so the +// scaffold and the catalog's text view name the same list; each import is read from the shared +// generator registry rather than restated. + +import { getGenerator, type GeneratorRegistryEntry } from "@metaobjectsdev/codegen-ts"; + +/** The stable names, in the order the scaffold lists them. */ +export const RECOMMENDED_SERVICE_GENERATORS = [ + "entity", + "rules-names", + "contract-types", + "service", + "service-routes", +] as const; + +/** Where every recommended factory is imported from. */ +export const RECOMMENDED_SERVICE_IMPORT = "@metaobjectsdev/codegen-ts/generators"; + +/** The registry entries of the recommended list; throws if one is missing (a registry rename). */ +export function recommendedServiceEntries(): GeneratorRegistryEntry[] { + return RECOMMENDED_SERVICE_GENERATORS.map((name) => { + const entry = getGenerator(name); + if (entry === undefined) throw new Error(`recommended service generator "${name}" is not in the generator registry`); + return entry; + }); +} + +/** + * The factory calls the scaffold writes. Cloudflare D1 holds no transaction across application + * code (ADR-0067 §4), so on D1 the service is generated without one. + */ +export function recommendedServiceCalls(opts: { interactiveTransactions: boolean }): string[] { + return recommendedServiceEntries().map((e) => + e.name === "service" && !opts.interactiveTransactions + ? `${e.factoryExport}({ interactiveTransactions: false })` + : `${e.factoryExport}()`, + ); +} + +/** The list as prose, for a comment or a message: "entityFile(), …, and serviceRoutesFile()". */ +export function recommendedServiceListText(): string { + const calls = recommendedServiceEntries().map((e) => `${e.factoryExport}()`); + return `${calls.slice(0, -1).join(", ")} and ${calls[calls.length - 1]}`; +} diff --git a/server/typescript/packages/cli/test/catalog-listing.test.ts b/server/typescript/packages/cli/test/catalog-listing.test.ts index 8098b5533..838f520eb 100644 --- a/server/typescript/packages/cli/test/catalog-listing.test.ts +++ b/server/typescript/packages/cli/test/catalog-listing.test.ts @@ -14,10 +14,11 @@ import type { MetaobjectsGenConfig } from "@metaobjectsdev/codegen-ts"; import { genCommand } from "../src/commands/gen.js"; import { ejectGenerator } from "../src/commands/eject.js"; import { - buildCatalogListing, wiredGeneratorNames, ownedGeneratorNames, renderCatalogText, + buildCatalogListing, wiredGeneratorNames, ownedGeneratorNames, renderCatalogText, RECOMMENDED_SERVICE_NOTE, type GeneratorCatalogRow, type LibraryCatalogRow, } from "../src/lib/catalog-listing.js"; import { composeCatalog } from "../src/lib/catalog.js"; +import { RECOMMENDED_SERVICE_GENERATORS } from "../src/lib/recommended-services.js"; const FIXTURE = join(import.meta.dir, "fixtures", "catalog-probe"); @@ -105,6 +106,20 @@ describe("meta gen --list — the catalog", () => { } }); + test("the text view names the recommended service list once, and every name in it is a catalog row", async () => { + const tmp = mkdtempSync(join(tmpdir(), "meta-catalog-")); + try { + expect(await genCommand(["--list"], tmp, "text")).toBe(0); + const text = logged.join("\n"); + expect(text.split(RECOMMENDED_SERVICE_NOTE).length - 1).toBe(1); + expect(text).toContain("meta init --with-services"); + const catalog = composeCatalog(); + for (const name of RECOMMENDED_SERVICE_GENERATORS) expect(catalog[name], name).toBeDefined(); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } + }); + test("needs no project at all — an empty directory is not an error", async () => { const tmp = mkdtempSync(join(tmpdir(), "meta-catalog-")); try { diff --git a/server/typescript/packages/cli/test/cli.test.ts b/server/typescript/packages/cli/test/cli.test.ts index 968f235eb..74f2ca82c 100644 --- a/server/typescript/packages/cli/test/cli.test.ts +++ b/server/typescript/packages/cli/test/cli.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; // wireRoot defaults TRUE (root-wiring is on by default so the scaffolded always-on actually loads; --no-wire-root opts out). -const defaultInitFlags = { force: false, quiet: false, printOnly: false, refreshDocs: false, d1: false, dialect: undefined, servers: [], clients: [], noSkills: false, wireRoot: true, docsOnly: false, configOnly: false, withDocs: false, skillsDir: undefined }; +const defaultInitFlags = { force: false, quiet: false, printOnly: false, refreshDocs: false, d1: false, dialect: undefined, servers: [], clients: [], noSkills: false, wireRoot: true, docsOnly: false, configOnly: false, withDocs: false, withServices: false, skillsDir: undefined }; describe("parseInitArgs", () => { test("default flags (wireRoot on by default, others off)", () => { @@ -33,6 +33,10 @@ describe("parseInitArgs", () => { test("--with-docs toggles withDocs", () => { expect(parseInitArgs(["--with-docs"])).toEqual({ ...defaultInitFlags, withDocs: true }); }); + + test("--with-services toggles withServices", () => { + expect(parseInitArgs(["--with-services"])).toEqual({ ...defaultInitFlags, withServices: true }); + }); test("--config-only toggles configOnly", () => { expect(parseInitArgs(["--config-only"])).toEqual({ ...defaultInitFlags, configOnly: true }); }); diff --git a/server/typescript/packages/cli/test/init.test.ts b/server/typescript/packages/cli/test/init.test.ts index 48bcc9a0a..df334e24a 100644 --- a/server/typescript/packages/cli/test/init.test.ts +++ b/server/typescript/packages/cli/test/init.test.ts @@ -292,6 +292,57 @@ describe("init() — the owned-codegen tier is empty on purpose", () => { } }); + test("--with-services wires the recommended service list, and still copies no generator", async () => { + const result = await init({ cwd, withServices: true }); + const configSrc = readFileSync(join(cwd, "metaobjects.config.ts"), "utf8"); + expect(configSrc).toContain( + 'import { entityFile, rulesNamesFile, contractTypes, serviceFile, serviceRoutesFile } from "@metaobjectsdev/codegen-ts/generators";', + ); + expect(configSrc).toContain("generators: [entityFile(), rulesNamesFile(), contractTypes(), serviceFile(), serviceRoutesFile()]"); + expect(readdirSync(join(cwd, "codegen", "generators"))).toEqual([]); + // What the wired output needs is said at init, not at the first failing compile. + const said = result.warnings.join("\n"); + expect(said).toContain("--with-services"); + for (const pkg of ["@metaobjectsdev/runtime-ts", "drizzle-orm", "zod", "fastify"]) expect(said).toContain(pkg); + }); + + test("--with-services on D1 generates the service without an interactive transaction", async () => { + await init({ cwd, withServices: true, d1: true }); + const configSrc = readFileSync(join(cwd, "metaobjects.config.ts"), "utf8"); + expect(configSrc).toContain("serviceFile({ interactiveTransactions: false })"); + expect(configSrc).toContain('dialect: "sqlite"'); + }); + + test("--with-services and --with-docs together share one import and one list", async () => { + await init({ cwd, withServices: true, withDocs: true }); + const configSrc = readFileSync(join(cwd, "metaobjects.config.ts"), "utf8"); + expect(configSrc.match(/^import .* from "@metaobjectsdev\/codegen-ts\/generators";$/gm)?.length).toBe(1); + expect(configSrc).toContain("serviceRoutesFile(), docsFile(), apiDocsFile()]"); + }); + + test("--with-services on a project that already has a config leaves it alone and says what to add", async () => { + writeFileSync(join(cwd, "metaobjects.config.ts"), "export default {};\n", "utf8"); + const result = await init({ cwd, withServices: true }); + expect(readFileSync(join(cwd, "metaobjects.config.ts"), "utf8")).toBe("export default {};\n"); + expect(result.warnings.join("\n")).toContain("serviceFile()"); + }); + + test("--with-services writes the service and its transport on the first `meta gen`", async () => { + const dir = mkGenProjectDir("with-services-"); + try { + await init({ cwd: dir, withServices: true, quiet: true }); + mkdirSync(join(dir, "metaobjects"), { recursive: true }); + writeFileSync(join(dir, "metaobjects", "meta.probe.json"), PROBE_ENTITY, "utf8"); + const { genCommand } = await import("../src/commands/gen.js"); + expect(await genCommand([], dir)).toBe(0); + const written = (readdirSync(dir, { recursive: true }) as string[]).filter((f) => !f.includes(".metaobjects/") && !f.includes("node_modules/")); + expect(written.some((f) => f.endsWith("/service/index.ts"))).toBe(true); + expect(written.some((f) => f.endsWith("/transport/fastify.ts"))).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + test("--print-only forecasts the same: the tier, not files in it", async () => { const result = await init({ cwd, printOnly: true }); expect(result.created).toContain("codegen/generators"); diff --git a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md index 170103bd3..64124cdb8 100644 --- a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md +++ b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md @@ -282,8 +282,8 @@ behaviour. The service generators are what act on `rules.lifecycle.create` and The shells are the service generators an app adds (ADR-0067). TypeScript's `service` generator is the first, held to the shared API tests' `fixtures/api-contract-conformance/rules/` corpus; each other port's lands in its own 1.3.0 service work. A project that declares a lifecycle and wires no -service generator will be told so by `verify`, as an advisory, once that check lands; the flat -routes enforce nothing. This is what the shells are held to: +service generator covering it is told so by `verify`, as an advisory (Node `meta verify` emits it +as rule `unenforced-lifecycle`); the flat routes enforce nothing. This is what the shells are held to: 1. Load the row: 404 when it is absent. 2. Validate the operation's `@inputRef` input, when it has one (400 `validation`), then call the diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md index b435e1f4d..7ffce6ca3 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -217,8 +217,9 @@ The shell sits in layer 4, and only there: queue consumer or an agent tool that calls the service gets the same checks as an HTTP request. Today's flat generators have no service layer. A project that declares a lifecycle and wires no -service generator will be advised by `verify` that the lifecycle is not enforced, once that check -lands (it is not yet emitted); the flat routes enforce nothing. (This replaces the first version of this section, which promised the +service generator covering it is advised by `verify` (rule `unenforced-lifecycle`, never an exit +code) that the lifecycle is not enforced; the flat routes enforce nothing. Node `meta verify` emits +it today, the first port with a service generator. (This replaces the first version of this section, which promised the guarded update and the `state_managed` refusal in the flat routes. That would have changed the output of five routes generators for projects that asked for nothing.) @@ -261,7 +262,10 @@ permission model, and the model names where a decision is needed, never what the `meta init`, `dotnet meta init` and `metaobjects init` keep writing an **empty** generator list (ADR-0034 Amendment 2), with a comment naming the usual generators. One opt-in flag, on the -pattern of the existing `--with-docs`, wires the recommended list of §5 instead. Rust's +pattern of the existing `--with-docs`, wires the recommended list of §5 instead (TypeScript: +`meta init --with-services`, writing `entityFile()`, `rulesNamesFile()`, `contractTypes()`, +`serviceFile()` and `serviceRoutesFile()`, with `serviceFile({ interactiveTransactions: false })` on +D1; `meta gen --list` names the same list under the catalog). Rust's `init` writes the project's list the same way. Java and Kotlin have no `init`: the documentation carries the recommended pom `` block. From f8ef5856c711e6641c350860f6380f9679e36c7a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 21:39:05 -0500 Subject: [PATCH 06/35] feat(codegen-ts,fixtures): pin the rows the docs pages and the docs site share (D0a) The 1.3.0 docs-page design pass, done against the docs design: the pages G0 pinned are built from rows the docs site reuses, so no fact is pinned twice in two shapes. - fixtures/docs-page-conformance pins expected/rows/ under each case's page data: rows/requirements.json (the RequirementRow ledger rows both requirements pages are built from) and rows/schema.json (the model-only schema rows: tables, columns, foreign keys, views and declaredBy, every dialect fact left out). - codegen-ts exports schemaRows() (the expected schema projected onto those rows) and schemaInputFromRows() (the page builder's input rebuilt from rows alone). The runner rebuilds the model-only page data from rows/schema.json, so it provably needs nothing a port without the expected schema lacks. - cli/test/docs-page-shapes.test.ts holds the requirement rows equal to what the explorer graph holds (requirement node attributes plus the verify ledger row) and the schema rows to a subset of meta schema --as json, the storage lens's input. - README, codegen-data-shapes.md, CONFORMANCE.md and the CHANGELOG say so. No page changes a byte. --- CHANGELOG.md | 7 + docs/CONFORMANCE.md | 3 +- docs/features/codegen-data-shapes.md | 6 + fixtures/docs-page-conformance/README.md | 16 ++ .../expected/rows/requirements.json | 104 +++++++++++++ .../expected/rows/schema.json | 50 +++++++ .../expected/rows/requirements.json | 15 ++ .../schema-model/expected/rows/schema.json | 78 ++++++++++ .../expected/rows/schema.json | 30 ++++ .../cli/test/docs-page-conformance.test.ts | 11 ++ .../cli/test/docs-page-shapes.test.ts | 140 ++++++++++++++++++ .../src/generators/agent-schema-rows.ts | 126 ++++++++++++++++ .../packages/codegen-ts/src/index.ts | 12 ++ 13 files changed, 597 insertions(+), 1 deletion(-) create mode 100644 fixtures/docs-page-conformance/cases/ledger-and-claims/expected/rows/requirements.json create mode 100644 fixtures/docs-page-conformance/cases/ledger-and-claims/expected/rows/schema.json create mode 100644 fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/rows/requirements.json create mode 100644 fixtures/docs-page-conformance/cases/schema-model/expected/rows/schema.json create mode 100644 fixtures/docs-page-conformance/cases/schema-report-view/expected/rows/schema.json create mode 100644 server/typescript/packages/cli/test/docs-page-shapes.test.ts create mode 100644 server/typescript/packages/codegen-ts/src/generators/agent-schema-rows.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 440cceef2..4a88c224c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,13 @@ here.** ## [Unreleased] +- **The docs pages and the docs site share one row shape.** `fixtures/docs-page-conformance/` + now also pins, under `expected/rows/`, the rows each page is built from: the requirement + ledger rows and the model-only schema rows. The schema rows are a subset of `meta schema + --as json`, and the requirement rows are what the explorer graph already holds, so the site + reuses them instead of pinning a second shape. codegen-ts exports `schemaRows()` and + `schemaInputFromRows()`. No page changes a byte. + - **The deprecated-reference finding ends its sentence before naming the replacement.** It read `…Team: the league no longer tracks teams Replaced by acme::app::Club.`; it now reads `…tracks teams. Replaced by acme::app::Club.` A reason that already ends in `.`, `!` or `?` is left as written. - **C#: `dotnet meta verify` runs the three model authoring lints.** The overlay lint diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index e0f346a4e..de77f7998 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -783,7 +783,8 @@ All 4 cases → [features/requirements.md](features/requirements.md) (the docume surfaces) and [features/templates-and-payloads.md](features/templates-and-payloads.md) (the shared templates). Each case is a model under `input/` and, under `expected/`, every page it yields (`requirements.md`, `requirements.toon`, `agent/requirements.md`, the model-only -`agent/schema.md`) plus the data each page's shared template is fed. The TypeScript +`agent/schema.md`) plus the data each page's shared template is fed and, under `rows/`, the +ledger and model-only schema rows that data is built from (the shapes the docs site reuses). The TypeScript builders are the source of the expected bytes. The corpus README writes down what a non-TypeScript schema page contains and what it leaves out. diff --git a/docs/features/codegen-data-shapes.md b/docs/features/codegen-data-shapes.md index b872de7ba..e817b1539 100644 --- a/docs/features/codegen-data-shapes.md +++ b/docs/features/codegen-data-shapes.md @@ -81,6 +81,12 @@ lines, and `templates/requirements/*.mustache` and `templates/agent/*.mustache` (the other ports' status is in [CONFORMANCE.md](../CONFORMANCE.md)), and its README states what the model-only schema page (`physical: false`, the page a port without the expected schema writes) leaves out. +The corpus also pins the rows those builders start from (`expected/rows/`): `RequirementRow[]` +(`requirementRows`) for both requirements pages, and `SchemaRows` (`schemaRows`, a subset of the +`meta schema --as json` shape) for the model-only schema page. These are the rows the docs site +reads too: the requirement rows are what the explorer graph holds, and the schema rows are part +of the storage lens's input. One shape serves the pages and the site, so it is not pinned twice. + ### Neutral structural shapes → `EntityTemplateData` / `PackageTemplateData` / `ModelTemplateData` The declarative template scopes (`scope: "perEntity" | "perPackage" | "perModel"` diff --git a/fixtures/docs-page-conformance/README.md b/fixtures/docs-page-conformance/README.md index d4912f0cb..916d1ea23 100644 --- a/fixtures/docs-page-conformance/README.md +++ b/fixtures/docs-page-conformance/README.md @@ -27,6 +27,22 @@ has two checks: (compare as JSON values). 2. **Page.** Rendering the template with that data produces `expected/` byte for byte. +Under the page data sits one more layer, `expected/rows/`, the rows each builder starts from: + +| Rows | What they are | The same shape as | +|---|---|---| +| `rows/requirements.json` | One row per requirement in the ledger, in declaration order: `path`, `depth`, `title`, `subType`, `level`, `status`, `disposition`, `trackedBy`, `statement`, `counterexample`, `description`, `implementedBy` (as written), `claimedConcerns` (the `type.subType` of each target that resolves). Both requirements pages are built from these. | What the docs site's explorer graph holds: the requirement node's attributes plus its verify ledger row | +| `rows/schema.json` | The model-only schema: tables (name, schema, description, primary key, columns with `nullable`, `identity` and `description`, foreign keys as columns → table and columns), views (name, schema), and `declaredBy` (each table or view → the declaring object). | A subset of `meta schema --as json` (the `serializeSnapshot` format), the storage lens's input | + +These rows are how the 1.3.0 docs-page design pass (D0a) settles the shapes: the docs site +reuses the rows rather than pinning a second shape for the same facts, so a later site lens is +built over these rows, not a new extraction. A port checks its rows first (compare as JSON +values), then its page data, then the bytes. The model-only page data follows from the rows +and the model alone; the TypeScript runner proves it by rebuilding the page from +`rows/schema.json` (`schemaInputFromRows`). `cli/test/docs-page-shapes.test.ts` holds the +requirement rows equal to the explorer graph's (on `fixtures/explorer-conformance/shop/`) and +the schema rows to a subset of `meta schema`'s output. + A page the case does not list is a page the port must NOT write: a model with no `requirement.*` node gets neither requirements page, and a model with no table and no view gets no schema page. diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/rows/requirements.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/rows/requirements.json new file mode 100644 index 000000000..1ffe64a0d --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/rows/requirements.json @@ -0,0 +1,104 @@ +[ + { + "path": "Storefront", + "depth": 0, + "subType": "functional", + "level": 1, + "status": "live", + "trackedBy": [], + "statement": "The storefront solution", + "counterexample": "Nothing can be sold", + "implementedBy": [], + "claimedConcerns": [] + }, + { + "path": "Storefront.OrderService", + "depth": 1, + "title": "Order service", + "subType": "functional", + "level": 3, + "status": "live", + "trackedBy": [], + "statement": "Every placed order is recorded before payment is attempted", + "counterexample": "A payment attempted against an order that was never stored", + "description": "Recording first is what lets a failed payment be retried.\n\n# Why first\n\nA payment with no order is a refund nobody can trace.", + "implementedBy": [], + "claimedConcerns": [] + }, + { + "path": "Storefront.OrderService.OrderRecord", + "depth": 2, + "title": "What an order must hold", + "subType": "functional", + "level": 4, + "status": "live", + "trackedBy": [], + "statement": "An order records what was bought, for how much, and when: placed | paid", + "counterexample": "An order row that cannot say who placed it", + "implementedBy": [ + "acme::shop::Order", + "acme::shop::Order.placedAt" + ], + "claimedConcerns": [ + "object.entity", + "field.timestamp" + ] + }, + { + "path": "Storefront.OrderService.OrderRecord.TranscribableReference", + "depth": 3, + "subType": "functional", + "level": 5, + "status": "live", + "trackedBy": [], + "statement": "An order carries a reference a customer can read\ndown a phone line", + "counterexample": "A reference that is a raw uuid", + "implementedBy": [ + "acme::shop::Order.reference" + ], + "claimedConcerns": [ + "field.string" + ] + }, + { + "path": "Storefront.OrderService.OrderRecord.OrderExpiry", + "depth": 3, + "subType": "functional", + "level": 5, + "status": "planned", + "trackedBy": [ + "acme/shop#412" + ], + "statement": "An unpaid order carries the instant it stops being reservable", + "counterexample": "Stock held indefinitely against an order nobody paid for", + "implementedBy": [], + "claimedConcerns": [] + }, + { + "path": "MoneyIsExactMinorUnits", + "depth": 0, + "subType": "architectural", + "status": "live", + "trackedBy": [], + "statement": "Monetary amounts are stored as exact integer minor units, never as floating point", + "counterexample": "A cent that disappears when a total is split three ways", + "implementedBy": [ + "acme::shop::Invoice" + ], + "claimedConcerns": [ + "object.entity" + ] + }, + { + "path": "GuestCheckout", + "depth": 0, + "subType": "functional", + "level": 4, + "status": "retired", + "trackedBy": [], + "statement": "A visitor can check out without an account", + "counterexample": "An order with no way to reach the person who placed it", + "implementedBy": [], + "claimedConcerns": [] + } +] diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/rows/schema.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/rows/schema.json new file mode 100644 index 000000000..bacb8c6ed --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/rows/schema.json @@ -0,0 +1,50 @@ +{ + "tables": [ + { + "name": "invoices", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "nullable": false, + "identity": "increment" + }, + { + "name": "total_cents", + "nullable": false + } + ], + "foreignKeys": [] + }, + { + "name": "orders", + "description": "A customer's order, from cart to fulfilment.", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "nullable": false + }, + { + "name": "reference", + "nullable": false, + "description": "The code a customer reads down a phone line." + }, + { + "name": "placed_at", + "nullable": false + } + ], + "foreignKeys": [] + } + ], + "views": [], + "declaredBy": { + "invoices": "acme::shop::Invoice", + "orders": "acme::shop::Order" + } +} diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/rows/requirements.json b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/rows/requirements.json new file mode 100644 index 000000000..b4b2bd773 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/rows/requirements.json @@ -0,0 +1,15 @@ +[ + { + "path": "ExportsAreResumable", + "depth": 0, + "subType": "functional", + "level": 4, + "status": "planned", + "disposition": "deferred", + "trackedBy": [], + "statement": "true", + "counterexample": "A 2 GB export that restarts from zero after a dropped connection", + "implementedBy": [], + "claimedConcerns": [] + } +] diff --git a/fixtures/docs-page-conformance/cases/schema-model/expected/rows/schema.json b/fixtures/docs-page-conformance/cases/schema-model/expected/rows/schema.json new file mode 100644 index 000000000..4efc560c0 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/schema-model/expected/rows/schema.json @@ -0,0 +1,78 @@ +{ + "tables": [ + { + "name": "owners", + "description": "A person or company that owns vehicles.", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "nullable": false, + "identity": "increment" + }, + { + "name": "name", + "nullable": false, + "description": "The legal name, as registered." + }, + { + "name": "tier", + "nullable": true + }, + { + "name": "rating", + "nullable": true + } + ], + "foreignKeys": [] + }, + { + "name": "vehicles", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "nullable": false, + "identity": "increment" + }, + { + "name": "kind", + "nullable": false + }, + { + "name": "owner_id", + "nullable": true + }, + { + "name": "doors", + "nullable": true + } + ], + "foreignKeys": [ + { + "columns": [ + "owner_id" + ], + "refTable": "owners", + "refColumns": [ + "id" + ] + } + ] + } + ], + "views": [ + { + "name": "v_owner_summary" + } + ], + "declaredBy": { + "owners": "acme::fleet::Owner", + "v_owner_summary": "acme::fleet::OwnerSummary", + "vehicles": "acme::fleet::Vehicle" + } +} diff --git a/fixtures/docs-page-conformance/cases/schema-report-view/expected/rows/schema.json b/fixtures/docs-page-conformance/cases/schema-report-view/expected/rows/schema.json new file mode 100644 index 000000000..ced7da7e2 --- /dev/null +++ b/fixtures/docs-page-conformance/cases/schema-report-view/expected/rows/schema.json @@ -0,0 +1,30 @@ +{ + "tables": [ + { + "name": "invoices", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "nullable": false + }, + { + "name": "status", + "nullable": false + } + ], + "foreignKeys": [] + } + ], + "views": [ + { + "name": "v_status_totals" + } + ], + "declaredBy": { + "invoices": "acme::billing::Invoice", + "v_status_totals": "acme::billing::StatusTotals" + } +} diff --git a/server/typescript/packages/cli/test/docs-page-conformance.test.ts b/server/typescript/packages/cli/test/docs-page-conformance.test.ts index a8130a159..60cc6ec3e 100644 --- a/server/typescript/packages/cli/test/docs-page-conformance.test.ts +++ b/server/typescript/packages/cli/test/docs-page-conformance.test.ts @@ -6,6 +6,8 @@ // runner fails the moment they disagree. Every other port runs the same cases against its // own builders and the same templates. `expected/data/` pins what each template is FED, so a // port can tell a builder defect (wrong data) from a render defect (right data, wrong bytes). +// `expected/rows/` pins the layer below that (D0a): the ledger rows and the model-only schema +// rows each page is built from, in the shapes the docs site reads too. // // The schema page pinned here is the MODEL-ONLY one (`physical: false`): the page a port // without the expected schema writes. TypeScript builds its input from the expected schema @@ -31,6 +33,8 @@ import { requirementRows, requirementsLedgerData, requirementsToonData, + schemaInputFromRows, + schemaRows, } from "@metaobjectsdev/codegen-ts"; import { buildAgentSchemaInput } from "../src/lib/agent-schema.js"; @@ -57,6 +61,8 @@ async function outputsOf(root: MetaRoot): Promise> { out.set("requirements.toon", renderRequirementsToon(rows)); out.set("data/requirements.md.json", json(requirementsLedgerData(rows))); out.set("data/requirements.toon.json", json(requirementsToonData(rows))); + // The rows layer (D0a): what both requirements pages, and the docs site, are built from. + out.set("rows/requirements.json", json(rows)); } const agentRequirements = agentRequirementsPageData(root); if (agentRequirements !== undefined) { @@ -78,6 +84,11 @@ async function outputsOf(root: MetaRoot): Promise> { if (data !== undefined) { out.set("agent/schema.md", renderAgentSchemaPage(root, schema, naming, { physical: false })); out.set("data/agent-schema.md.json", json(data)); + // The rows layer (D0a). The page data must follow from the rows and the model alone: + // that is all a port without the expected schema has. + const rowsLayer = schemaRows(schema); + out.set("rows/schema.json", json(rowsLayer)); + expect(agentSchemaPageData(root, schemaInputFromRows(rowsLayer), naming, { physical: false })).toEqual(data); } } return out; diff --git a/server/typescript/packages/cli/test/docs-page-shapes.test.ts b/server/typescript/packages/cli/test/docs-page-shapes.test.ts new file mode 100644 index 000000000..0f9454637 --- /dev/null +++ b/server/typescript/packages/cli/test/docs-page-shapes.test.ts @@ -0,0 +1,140 @@ +// The docs pages and the docs site share one row shape (1.3.0 D0a). +// +// `fixtures/docs-page-conformance/` pins a ROWS layer under each page's data: the requirement +// ledger rows, and the model-only schema rows. The docs-design ruling is that the site reuses +// those rows rather than pinning a second shape for the same facts. This file holds that to +// the two sources the site actually reads: +// +// - the requirement rows are what the explorer graph (`explorer.json`: the requirement nodes +// and the verify ledger) already holds, field for field; +// - the schema rows are a literal subset of `meta schema --as json` (the `serializeSnapshot` +// format), the storage lens's input. + +import { describe, expect, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { InMemoryStringSource, MetaDataLoader } from "@metaobjectsdev/metadata"; +import type { MetaRoot } from "@metaobjectsdev/metadata"; +import { requirementRows, type RequirementRow, type SchemaRows } from "@metaobjectsdev/codegen-ts"; +import { buildExplorer, type ExplorerJson } from "@metaobjectsdev/docs-site"; +import { resolveSchemaConventions, serializeSnapshot } from "@metaobjectsdev/migrate-ts"; +import { buildAgentSchemaInput } from "../src/lib/agent-schema.js"; + +const FIXTURES = resolve(import.meta.dir, "../../../../../fixtures"); +const CORPUS = join(FIXTURES, "docs-page-conformance/cases"); +const SHOP = join(FIXTURES, "explorer-conformance/shop"); + +async function load(files: { id: string; text: string }[]): Promise { + const res = await new MetaDataLoader().load( + files.map((f) => new InMemoryStringSource(f.text, { id: f.id, format: "json" })), + ); + expect(res.errors).toEqual([]); + return res.root; +} + +function metaFiles(dir: string): { id: string; text: string }[] { + return readdirSync(dir) + .filter((f) => /^meta\..*\.json$/.test(f)) + .sort() + .map((f) => ({ id: f, text: readFileSync(join(dir, f), "utf8") })); +} + +const str = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined); + +/** The requirement rows as the docs site would read them off the explorer graph. */ +function rowsFromGraph(doc: ExplorerJson): RequirementRow[] { + const nodes = new Map(doc.nodes.map((n) => [n.id, n])); + return (doc.ledger?.rows ?? []).map((row) => { + const attrs = nodes.get(row.node)?.attrs ?? {}; + const trackedBy = attrs["trackedBy"]; + const concerns = row.implementedBy + .filter((l) => l.resolves && l.target !== undefined) + .map((l) => nodes.get(l.target as string)) + .filter((n) => n !== undefined) + .map((n) => `${n.type}.${n.subType}`); + return { + path: row.path, + depth: row.path.split(".").length - 1, + title: str(attrs["title"]), + subType: row.subType, + level: row.level, + status: row.status, + disposition: row.disposition, + trackedBy: Array.isArray(trackedBy) ? (trackedBy as string[]) : [], + statement: str(attrs["statement"]), + counterexample: str(attrs["counterexample"]), + description: str(attrs["description"]), + implementedBy: row.implementedBy.map((l) => l.ref), + claimedConcerns: [...new Set(concerns)], + }; + }); +} + +/** True when every key of `part` is in `whole` with an equal value (arrays: element-wise). */ +function isSubset(part: unknown, whole: unknown): boolean { + if (Array.isArray(part)) { + return Array.isArray(whole) && part.length === whole.length && part.every((p, i) => isSubset(p, whole[i])); + } + if (typeof part === "object" && part !== null) { + if (typeof whole !== "object" || whole === null || Array.isArray(whole)) return false; + const w = whole as Record; + return Object.entries(part).every(([k, v]) => k in w && isSubset(v, w[k])); + } + return part === whole; +} + +const byName = (list: readonly T[]): Map => new Map(list.map((x) => [x.name, x])); + +describe("docs page rows are the docs site's rows", () => { + test("requirement rows equal what the explorer graph holds (explorer-conformance/shop)", async () => { + const root = await load(metaFiles(join(SHOP, "project/metaobjects"))); + const doc = buildExplorer({ + model: JSON.parse(readFileSync(join(SHOP, "effective.json"), "utf8")), + verify: JSON.parse(readFileSync(join(SHOP, "verify.json"), "utf8")), + }); + const fromModel = requirementRows(root); + expect(fromModel.length).toBeGreaterThan(0); + // JSON round trip: absent keys and `undefined` values compare the same, as they do on disk. + expect(JSON.parse(JSON.stringify(rowsFromGraph(doc)))).toEqual(JSON.parse(JSON.stringify(fromModel))); + }); + + const cases = readdirSync(CORPUS, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort(); + for (const name of cases) { + const pinned = join(CORPUS, name, "expected/rows/schema.json"); + let rows: SchemaRows | undefined; + try { + rows = JSON.parse(readFileSync(pinned, "utf8")) as SchemaRows; + } catch { + continue; // a case with no schema page pins no schema rows + } + test(`${name}: the schema rows are a subset of meta schema --as json`, async () => { + const root = await load(metaFiles(join(CORPUS, name, "input"))); + const schema = buildAgentSchemaInput(root, "postgres", () => {}, { + conventions: resolveSchemaConventions(undefined), + skipRedundantChecks: false, + foreignKeyIndexes: false, + foreignKeyTargets: "refuse", + }); + expect(schema).toBeDefined(); + const file = JSON.parse( + serializeSnapshot({ tables: [...(schema?.tables ?? [])], views: [...(schema?.views ?? [])] } as never), + ) as { snapshot: { tables: { name: string; columns: { name: string }[]; foreignKeys: unknown[] }[]; views: { name: string }[] } }; + const tables = byName(file.snapshot.tables); + for (const t of rows?.tables ?? []) { + const whole = tables.get(t.name); + expect({ table: t.name, found: whole !== undefined }).toEqual({ table: t.name, found: true }); + const { columns, foreignKeys, ...rest } = t; + expect({ table: t.name, ok: isSubset(rest, whole) }).toEqual({ table: t.name, ok: true }); + const cols = byName(whole?.columns ?? []); + for (const c of columns) expect({ column: `${t.name}.${c.name}`, ok: isSubset(c, cols.get(c.name)) }).toEqual({ column: `${t.name}.${c.name}`, ok: true }); + // A foreign key is matched by its key, not its (dialect) constraint name. + for (const fk of foreignKeys) { + expect({ fk: `${t.name}:${fk.columns.join(",")}`, ok: (whole?.foreignKeys ?? []).some((w) => isSubset(fk, w)) }) + .toEqual({ fk: `${t.name}:${fk.columns.join(",")}`, ok: true }); + } + } + const views = byName(file.snapshot.views); + for (const v of rows?.views ?? []) expect({ view: v.name, ok: isSubset(v, views.get(v.name)) }).toEqual({ view: v.name, ok: true }); + }); + } +}); diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-schema-rows.ts b/server/typescript/packages/codegen-ts/src/generators/agent-schema-rows.ts new file mode 100644 index 000000000..ab0cdd943 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/generators/agent-schema-rows.ts @@ -0,0 +1,126 @@ +// The ROWS layer of the model-only `agent/schema.md`: the tables and views the page describes, +// in the shape the expected schema already has, with every dialect fact left out. +// +// WHY A ROWS LAYER (1.3.0 D0a). The pages are builder → pinned page data → shared template +// (ruling 2a). Page data is finished Markdown cells, which is right for the template and wrong +// for anything else that wants the same facts: the docs site's storage lens draws the same +// tables as HTML and an ERD. So the corpus pins one layer BELOW the page data too, and that +// layer is a literal subset of what `meta schema --as json` prints (the `serializeSnapshot` +// format), not a second shape. A port without the expected schema builds these rows from the +// model with its own naming helpers; TypeScript projects them from the expected schema; the +// docs site reads the same fields from `meta schema`. One shape, three readers. +// +// What is left out is exactly what the model cannot know: SQL types and defaults, indexes, +// checks, foreign-key constraint names and referential actions (design call 17). + +import type { AgentSchemaInput, SchemaColumnLike, SchemaTableLike } from "./agent-schema-input.js"; + +/** One column: the snapshot's own field names, the model-derivable ones only. */ +export interface SchemaRowColumn { + readonly name: string; + readonly nullable: boolean; + readonly identity?: "increment" | "uuid"; + readonly description?: string; +} + +/** One foreign key, without its constraint name or referential actions. */ +export interface SchemaRowForeignKey { + readonly columns: readonly string[]; + readonly refTable: string; + readonly refColumns: readonly string[]; +} + +export interface SchemaRowTable { + readonly name: string; + readonly schema?: string; + readonly description?: string; + readonly primaryKey: readonly string[]; + readonly columns: readonly SchemaRowColumn[]; + readonly foreignKeys: readonly SchemaRowForeignKey[]; +} + +export interface SchemaRowView { + readonly name: string; + readonly schema?: string; +} + +/** What a port's model-only schema builder produces before it lays out a single cell. */ +export interface SchemaRows { + /** Tables and views sorted by name, as the snapshot file sorts them; a table's columns and + * foreign keys in declaration order, as the page lists them. */ + readonly tables: readonly SchemaRowTable[]; + readonly views: readonly SchemaRowView[]; + /** `.` (or `` with no schema) → the declaring object's FQN. */ + readonly declaredBy: Readonly>; +} + +const byName = (a: T, b: T): number => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0); + +/** The key `declaredBy` uses: what a page heading prints, without the backticks. */ +export function schemaRowKey(obj: { readonly name: string; readonly schema?: string | undefined }): string { + return obj.schema === undefined ? obj.name : `${obj.schema}.${obj.name}`; +} + +function columnRow(c: SchemaColumnLike): SchemaRowColumn { + return { + name: c.name, + nullable: c.nullable, + ...(c.identity !== undefined && { identity: c.identity }), + ...(c.description !== undefined && c.description !== "" && { description: c.description }), + }; +} + +function tableRow(t: SchemaTableLike): SchemaRowTable { + return { + name: t.name, + ...(t.schema !== undefined && { schema: t.schema }), + ...(t.description !== undefined && t.description !== "" && { description: t.description }), + primaryKey: [...t.primaryKey], + // Declaration order, as the expected schema holds it: the page lists columns in it. + columns: t.columns.map(columnRow), + foreignKeys: t.foreignKeys.map((fk) => ({ columns: [...fk.columns], refTable: fk.refTable, refColumns: [...fk.refColumns] })), + }; +} + +/** Project the expected schema onto the rows a model-only page is built from. */ +export function schemaRows(input: AgentSchemaInput): SchemaRows { + const declaredBy: Record = {}; + const note = (obj: { name: string; schema?: string | undefined }): void => { + const fqn = input.provenance.get(input.qualify(obj)); + if (fqn !== undefined) declaredBy[schemaRowKey(obj)] = fqn; + }; + const tables = [...input.tables].sort(byName); + const views = [...input.views].sort(byName); + for (const t of tables) note(t); + for (const v of views) note(v); + return { + tables: tables.map(tableRow), + views: views.map((v) => ({ name: v.name, ...(v.schema !== undefined && { schema: v.schema }) })), + declaredBy: Object.fromEntries(Object.keys(declaredBy).sort().map((k) => [k, declaredBy[k] as string])), + }; +} + +/** + * The page builder's input rebuilt from rows alone: what a port without the expected schema + * hands `agentSchemaPageData` with `physical: false`. It carries no dialect, no index, no + * check and no constraint name, and asking it for a SQL type throws, so a model-only page that + * reached for a dialect fact fails loudly instead of printing one. + */ +export function schemaInputFromRows(rows: SchemaRows): AgentSchemaInput { + return { + dialect: "", + tables: rows.tables.map((t) => ({ + ...t, + columns: t.columns.map((c) => ({ ...c })), + indexes: [], + checks: [], + foreignKeys: t.foreignKeys.map((fk) => ({ ...fk, name: "" })), + })), + views: rows.views.map((v) => ({ ...v })), + provenance: new Map(Object.entries(rows.declaredBy)), + qualify: schemaRowKey, + columnType: () => { + throw new Error("a model-only schema page has no SQL type to print"); + }, + }; +} diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index efd39ccbd..fb69bc337 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -450,6 +450,18 @@ export { type AgentSchemaPageData, type AgentSchemaPageOptions, } from "./generators/agent-schema-page.js"; +// The rows layer beneath the model-only schema page (1.3.0 D0a): a subset of the +// `meta schema --as json` shape, pinned by the docs-page corpus and shared with the docs site. +export { + schemaRows, + schemaInputFromRows, + schemaRowKey, + type SchemaRows, + type SchemaRowTable, + type SchemaRowColumn, + type SchemaRowForeignKey, + type SchemaRowView, +} from "./generators/agent-schema-rows.js"; export type { RequirementTestsOpts, RequirementTestRenderer, From 7aaddb95b6d6514c5ad890c7f3e0a1f67875e1aa Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 22:02:16 -0500 Subject: [PATCH 07/35] feat(python,fixtures): requirements and agent docs pages from the shared templates (G-PY-1) Python gains the requirements generator (requirements.md, requirements.toon) and the agent-docs generator (agent/requirements.md and the model-only agent/schema.md; agent/ui.md stays TypeScript-only). Both render the shared Mustache templates from the data model pinned by fixtures/docs-page-conformance/, held by a pytest runner that checks rows, page data, then bytes. - Templates are bundled in the package (render/bundled_templates), synced by scripts/sync-doc-templates.sh and held by the doc-template drift gate; a same-named template under the project's templates directory overrides a page. - Registered as neutral/docs/ejectable; registry.json ports now list python. - The Python Mustache engine treats a truthy scalar section as the context so {{.}} names it. --- CHANGELOG.md | 10 + docs/CONFORMANCE.md | 8 +- docs/ports/python.md | 1 + fixtures/docs-page-conformance/README.md | 6 +- .../registry.json | 4 +- scripts/ci-local.sh | 3 +- scripts/sync-doc-templates.sh | 15 + .../metaobjects/codegen/generator_registry.py | 30 + .../generators/agent_docs_generator.py | 78 +++ .../generators/requirements_generator.py | 68 +++ .../codegen/runtime/docs_requirements.py | 348 ++++++++++++ .../codegen/runtime/docs_schema.py | 522 ++++++++++++++++++ .../agent/requirements.md.mustache | 34 ++ .../agent/schema.md.mustache | 118 ++++ .../requirements/requirements.md.mustache | 27 + .../requirements/requirements.toon.mustache | 2 + .../src/metaobjects/render/doc_pages.py | 62 +++ .../python/src/metaobjects/render/renderer.py | 11 +- .../python/tests/codegen/test_cli_registry.py | 4 +- .../conformance/test_docs_page_conformance.py | 149 +++++ .../test_generator_registry_conformance.py | 11 +- server/python/tests/test_reporting_inert.py | 8 +- 22 files changed, 1499 insertions(+), 20 deletions(-) create mode 100644 server/python/src/metaobjects/codegen/generators/agent_docs_generator.py create mode 100644 server/python/src/metaobjects/codegen/generators/requirements_generator.py create mode 100644 server/python/src/metaobjects/codegen/runtime/docs_requirements.py create mode 100644 server/python/src/metaobjects/codegen/runtime/docs_schema.py create mode 100644 server/python/src/metaobjects/render/bundled_templates/agent/requirements.md.mustache create mode 100644 server/python/src/metaobjects/render/bundled_templates/agent/schema.md.mustache create mode 100644 server/python/src/metaobjects/render/bundled_templates/requirements/requirements.md.mustache create mode 100644 server/python/src/metaobjects/render/bundled_templates/requirements/requirements.toon.mustache create mode 100644 server/python/src/metaobjects/render/doc_pages.py create mode 100644 server/python/tests/conformance/test_docs_page_conformance.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a88c224c..8939106c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,16 @@ here.** ## [Unreleased] +- **Python: the `requirements` and `agent-docs` generators.** `metaobjects gen` can now write + `requirements.md`, `requirements.toon`, `agent/requirements.md` and the model-only + `agent/schema.md` (`agent/ui.md` stays TypeScript-only). They render the shared Mustache + templates from the pinned data model, held to `fixtures/docs-page-conformance/`; the templates + are bundled in the package (`scripts/sync-doc-templates.sh` copies them, the doc-template drift + gate checks the copy) and a same-named template under the project's templates directory + overrides a page. Both are ejectable. The Python Mustache engine now treats a string-valued + section as the context (`{{#statement}}{{{.}}}{{/statement}}`), as the spec and the TypeScript + engine do. + - **The docs pages and the docs site share one row shape.** `fixtures/docs-page-conformance/` now also pins, under `expected/rows/`, the rows each page is built from: the requirement ledger rows and the model-only schema rows. The schema rows are a subset of `meta schema diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index de77f7998..2e3a2a000 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -53,7 +53,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | | [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) | 6 | ✓ (the emitter is TS-owned) | — | — | — | — | | [`fixtures/list-query-conformance/`](../fixtures/list-query-conformance/) (how a list route reads its query string: filter tree, search, sort, page, or the named 400) | 95 cases | ✓ (reference; the source of the expected answers) | planned (R-JV) | planned (R-KT) | planned (R-CS) | planned (R-PY) | -| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirements pages and the model-only schema page: each page's data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | planned | planned (through Java) | planned | planned | +| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirements pages and the model-only schema page: each page's data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | planned | planned (through Java) | ✓ | planned | | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) | 1 | ✓ (docs emit is TS-owned) | — | — | — | — | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | @@ -788,8 +788,10 @@ ledger and model-only schema rows that data is built from (the shapes the docs s builders are the source of the expected bytes. The corpus README writes down what a non-TypeScript schema page contains and what it leaves out. -**Held to it:** `server/typescript/packages/cli/test/docs-page-conformance.test.ts`. The -other ports' page generators are planned. +**Held to it:** `server/typescript/packages/cli/test/docs-page-conformance.test.ts` and +`server/python/tests/conformance/test_docs_page_conformance.py` (rows, page data, then bytes; +the Python builders derive the schema rows from the model with the port's own naming helpers). +The C#, Java (Kotlin through Java) and Rust page generators are planned. ### `fixtures/requirement-test-identity-conformance/` (27 cases) diff --git a/docs/ports/python.md b/docs/ports/python.md index 6e1d4413a..4fc3123a3 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -1085,6 +1085,7 @@ definitions, and import lines are stable. | Migrations | TS-only by design (ADR-0015) — no Python `migrate` command; consume the canonical `schema.postgres.sql` | | Drift verify | Yes — template / payload drift (`metaobjects verify`); `verify --codegen` regenerates the config's list and diffs each target's `outDir` | | API reference docs | Yes — `api-docs` in a target's `generators`, options in the top-level `apiDocs` block (`apiSubDir`, `projectName`, `modelBaseUrl`); `metaobjects docs` was removed in 1.1.0 ([migration](../features/migrations/docs-are-generators.md#python)) | +| Requirements and agent pages | Yes — `requirements` (`requirements.md`, `requirements.toon`) and `agent-docs` (`agent/requirements.md` and the model-only `agent/schema.md`: no SQL types, defaults, indexes or checks; `agent/ui.md` is TypeScript-only) in a target's `generators`, rendered from the shared templates bundled in the package; a same-named file under the project's templates directory overrides a page; both ejectable | | Requirement gate + requirement tests | Yes (`metaobjects verify`, on every run; `requirement-tests` emits pytest and is ejectable) | | Business-rules gate (ADR-0066, experimental) | Yes (`metaobjects verify`, on every run; see [business rules](../features/business-rules.md)) | | Runtime metadata | Yes (`metaobjects.runtime.ObjectManagerDb` — DB-API 2 drivers: Postgres via pg8000/psycopg, `SqliteDriver` over the standard library's `sqlite3`, `MySqlDriver` over PyMySQL with the `mysql` extra) + loader API + render engine | diff --git a/fixtures/docs-page-conformance/README.md b/fixtures/docs-page-conformance/README.md index 916d1ea23..529191cca 100644 --- a/fixtures/docs-page-conformance/README.md +++ b/fixtures/docs-page-conformance/README.md @@ -94,5 +94,7 @@ written from the expected schema, carries those; `agent/ui.md` stays a TypeScrip - TypeScript: `server/typescript/packages/cli/test/docs-page-conformance.test.ts`. Regenerate with `UPDATE_DOCS_PAGE_FIXTURES=1 bun test test/docs-page-conformance.test.ts` from that package, and review the diff: it is the cross-port contract. -- C#, Java (Kotlin through Java), Python and Rust: their page generators are planned and - will run every case. +- Python: `server/python/tests/conformance/test_docs_page_conformance.py` (rows, page data, + then the bytes the `requirements` and `agent-docs` generators write). +- C#, Java (Kotlin through Java) and Rust: their page generators are planned and will run + every case. diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 0a0f36569..60e26433c 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -335,7 +335,7 @@ "layer": "docs", "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9). A project that declares no requirement.* node gets no file.", "eject": "full", - "ports": ["typescript"] + "ports": ["typescript", "python"] }, "agent-docs": { "concept": "Pages written for a coding agent working in the project: the schema, the UI surface and the requirements.", @@ -343,7 +343,7 @@ "layer": "docs", "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9).", "eject": "full", - "ports": ["typescript"] + "ports": ["typescript", "python"] }, "metamodel-docs": { "concept": "The reference of the built-in metamodel: every type, subtype and attribute the build registers, by provider.", diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 055675a82..e88e8a5db 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -996,7 +996,8 @@ gate_doc_template_drift() { bash scripts/sync-doc-templates.sh \ && git diff --exit-code -- \ server/typescript/packages/codegen-ts/templates \ - server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts + server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts \ + server/python/src/metaobjects/render/bundled_templates } gate_embedded_library_drift() { bun run scripts/generate-embedded-library.ts \ diff --git a/scripts/sync-doc-templates.sh b/scripts/sync-doc-templates.sh index a7e4faba4..4d0acb610 100755 --- a/scripts/sync-doc-templates.sh +++ b/scripts/sync-doc-templates.sh @@ -34,6 +34,11 @@ DEST_ROOTS=( "${REPO_ROOT}/server/typescript/packages/codegen-ts/templates" ) +# Consumers that bundle only some groups: the Python port ships the requirements and agent +# pages (its docs generators), not the TypeScript-only docs and api templates. +PYTHON_DEST_ROOT="${REPO_ROOT}/server/python/src/metaobjects/render/bundled_templates" +PYTHON_GROUPS=(requirements agent) + for group in "${TEMPLATE_GROUPS[@]}"; do src_dir="${REPO_ROOT}/templates/${group}" if [[ ! -d "${src_dir}" ]]; then @@ -58,6 +63,16 @@ for group in "${TEMPLATE_GROUPS[@]}"; do echo "synced: ${src} -> ${dest}/$(basename "${src}")" done done + + for py_group in "${PYTHON_GROUPS[@]}"; do + if [[ "${py_group}" == "${group}" ]]; then + mkdir -p "${PYTHON_DEST_ROOT}/${group}" + for src in "${src_files[@]}"; do + cp "${src}" "${PYTHON_DEST_ROOT}/${group}/$(basename "${src}")" + echo "synced: ${src} -> ${PYTHON_DEST_ROOT}/${group}/$(basename "${src}")" + done + fi + done done # Regenerate the embedded-string TS module so the framework doc templates also diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index 9cd7bb60b..763cff471 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -28,6 +28,7 @@ from metaobjects.codegen.generator import Generator from metaobjects.codegen.project_config import DEFAULT_REQUIREMENT_WITNESS_MODULE, ApiDocsConfig +from metaobjects.codegen.generators.agent_docs_generator import agent_docs_generator from metaobjects.codegen.generators.api_docs_generator import api_docs_generator from metaobjects.codegen.generators.entity_model import entity_model, model_import_closure from metaobjects.codegen.generators.extractor_generator import extractor_generator @@ -45,6 +46,7 @@ render_helper_generator, ) from metaobjects.codegen.generators.report_export_generator import report_export_generator +from metaobjects.codegen.generators.requirements_generator import requirements_generator from metaobjects.codegen.generators.requirement_tests_generator import ( requirement_tests_generator, ) @@ -341,6 +343,10 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: "api_docs_paths", ) +#: The requirements pages' builders (rows, page data, TOON cells) and the model-only schema page's. +_DOCS_REQUIREMENTS = "docs_requirements" +_DOCS_SCHEMA = "docs_schema" + #: Stable name -> GeneratorEntry. The 12 native generators whose manifest `ports` #: include `python` (ADR-0021 D3). Set equality, tier AND layer are conformance-tested #: against the manifest. @@ -514,6 +520,30 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: source=api_docs_generator, runtime=_API_DOCS_RUNTIME + _SHARED_PREDICATES + (_M2M_CODEGEN,), ), + "requirements": GeneratorEntry( + name="requirements", + description=( + "The requirement ledger as documentation: requirements.md for people and " + "requirements.toon for tools (shared Mustache templates). No requirement.* node, no file." + ), + tier="neutral", + layer="docs", + factory=requirements_generator, + source=requirements_generator, + runtime=(_DOCS_REQUIREMENTS,), + ), + "agent-docs": GeneratorEntry( + name="agent-docs", + description=( + "Pages written for a coding agent: agent/requirements.md and the model-only " + "agent/schema.md (agent/ui.md stays TypeScript-only)." + ), + tier="neutral", + layer="docs", + factory=agent_docs_generator, + source=agent_docs_generator, + runtime=(_DOCS_REQUIREMENTS, _DOCS_SCHEMA), + ), } diff --git a/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py b/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py new file mode 100644 index 000000000..00f18fc4d --- /dev/null +++ b/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py @@ -0,0 +1,78 @@ +"""``agent-docs`` — pages written for a coding agent working in the project. + +In Python this writes two pages under ``agent/``: ``agent/requirements.md`` (the node index, the +statements and the embedded ledger, read before adding a capability) and ``agent/schema.md`` +(the MODEL-ONLY schema page: the tables, columns, keys, views, relationships and enums the model +declares, read before touching persistence; no SQL type, default, index, check or constraint +name, which only the TypeScript page, written from the expected schema, carries). +``agent/ui.md`` stays TypeScript-only: Python generates no client UI to describe. + +Each page is a shared Mustache template (``templates/agent/`` and ``templates/requirements/``, +bundled with the package) fed the data the builders in ``codegen/runtime/docs_requirements.py`` +and ``codegen/runtime/docs_schema.py`` compute from the loaded model, pinned by +``fixtures/docs-page-conformance/``. A page with nothing to describe is no file. A project +overrides a page by dropping a same-named template under its templates directory. +""" +from __future__ import annotations + +from typing import Any + +from metaobjects.codegen.generator import EmittedFile, GenContext, Generator +from metaobjects.render.doc_pages import doc_provider, end_with_one_newline, render_doc_page +from metaobjects.render.verify import Provider + +from ..runtime.docs_requirements import ( + AGENT_REQUIREMENTS_PAGE_REF, + REQUIREMENTS_PAGE_REF, + agent_requirements_page_data, +) +from ..runtime.docs_schema import AGENT_SCHEMA_PAGE_REF, agent_schema_page_data, schema_rows + +DEFAULT_AGENT_DIR = "agent" + + +class AgentDocsGenerator: + """Writes ``agent/schema.md`` and ``agent/requirements.md`` for the run's loaded model.""" + + name = "agent-docs" + + def __init__( + self, + sub_dir: str = DEFAULT_AGENT_DIR, + template_root: str | None = None, + provider: Provider | None = None, + ) -> None: + self._dir = sub_dir.rstrip("/") + self._provider = provider if provider is not None else doc_provider(template_root) + self.template_root = template_root + + def generate(self, ctx: GenContext) -> list[EmittedFile]: + if ctx.loaded_root is None: + return [] + root = ctx.loaded_root + files: list[EmittedFile] = [] + + schema_data = agent_schema_page_data(root, schema_rows(root)) + if schema_data is not None: + path = f"{self._dir}/schema.md" + page = render_doc_page(AGENT_SCHEMA_PAGE_REF, schema_data, self._provider, path) + files.append(EmittedFile(path=path, content=end_with_one_newline(page))) + + def render_ledger(data: dict[str, Any]) -> str: + return render_doc_page(REQUIREMENTS_PAGE_REF, data, self._provider, "requirements.md") + + requirements = agent_requirements_page_data(root, ctx.in_ledger, render_ledger) + if requirements is not None: + path = f"{self._dir}/requirements.md" + files.append( + EmittedFile( + path=path, + content=render_doc_page(AGENT_REQUIREMENTS_PAGE_REF, requirements, self._provider, path), + ) + ) + return files + + +def agent_docs_generator(ctx: Any) -> Generator: + """The registry's ``source=``, and so the symbol an ejected copy is wired by.""" + return AgentDocsGenerator(template_root=getattr(ctx, "template_root", None)) diff --git a/server/python/src/metaobjects/codegen/generators/requirements_generator.py b/server/python/src/metaobjects/codegen/generators/requirements_generator.py new file mode 100644 index 000000000..9275af91c --- /dev/null +++ b/server/python/src/metaobjects/codegen/generators/requirements_generator.py @@ -0,0 +1,68 @@ +"""``requirements`` — the requirement ledger as documentation: ``requirements.md`` for people and +``requirements.toon`` for tools. + +An ordinary entry in a target's ``generators`` (the ``docs`` target by convention), run by +``metaobjects gen``. A model declaring no ``requirement.*`` node gets no file. + +Each page is the shared Mustache template (``templates/requirements/``, bundled with the +package) fed the data the builder in ``codegen/runtime/docs_requirements.py`` computes; the +rows and the data are pinned by ``fixtures/docs-page-conformance/``. A project overrides a page +by dropping a same-named template under its templates directory. The generator reads the loaded +model and nothing else. +""" +from __future__ import annotations + +from typing import Any + +from metaobjects.codegen.generator import EmittedFile, GenContext, Generator +from metaobjects.render.doc_pages import doc_provider, render_doc_page +from metaobjects.render.verify import Provider + +from ..runtime.docs_requirements import ( + REQUIREMENTS_PAGE_REF, + REQUIREMENTS_TOON_REF, + requirement_rows, + requirements_ledger_data, + requirements_toon_data, +) + +MARKDOWN_FILENAME = "requirements.md" +TOON_FILENAME = "requirements.toon" + + +class RequirementsGenerator: + """Writes ``requirements.md`` and ``requirements.toon`` for the run's loaded model.""" + + name = "requirements" + + def __init__(self, template_root: str | None = None, provider: Provider | None = None) -> None: + self._provider = provider if provider is not None else doc_provider(template_root) + #: A project's templates directory is part of the run's skip key (``cli.py`` hashes it). + self.template_root = template_root + + def generate(self, ctx: GenContext) -> list[EmittedFile]: + if ctx.loaded_root is None: + return [] + rows = requirement_rows(ctx.loaded_root, ctx.in_ledger) + if not rows: + return [] + return [ + EmittedFile( + path=MARKDOWN_FILENAME, + content=render_doc_page( + REQUIREMENTS_PAGE_REF, requirements_ledger_data(rows), self._provider, MARKDOWN_FILENAME + ), + ), + EmittedFile( + path=TOON_FILENAME, + content=render_doc_page( + REQUIREMENTS_TOON_REF, requirements_toon_data(rows), self._provider, TOON_FILENAME + ), + ), + ] + + +def requirements_generator(ctx: Any) -> Generator: + """The registry's ``source=``, and so the symbol an ejected copy is wired by. It takes the + build context and reads the templates directory the run resolved.""" + return RequirementsGenerator(template_root=getattr(ctx, "template_root", None)) diff --git a/server/python/src/metaobjects/codegen/runtime/docs_requirements.py b/server/python/src/metaobjects/codegen/runtime/docs_requirements.py new file mode 100644 index 000000000..5de30b3bd --- /dev/null +++ b/server/python/src/metaobjects/codegen/runtime/docs_requirements.py @@ -0,0 +1,348 @@ +"""The requirements pages' builders: the ledger rows and the page data of ``requirements.md``, +``requirements.toon`` and ``agent/requirements.md``. + +Mirrors the TypeScript ``requirements-view.ts``, ``requirements-markdown.ts``, +``requirements-toon.ts`` and ``agent-requirements-page.ts``. Every page is a shared Mustache +template (``templates/requirements/`` and ``templates/agent/``) fed the data built here; the +builder makes every decision (heading depth, which title survives, the fact bar, the +demotion of the embedded ledger, every table cell, TOON quoting) and the template only lays +the lines out. The rows and the data are pinned by ``fixtures/docs-page-conformance/``. + +Rows and page data are plain dicts, so they compare as JSON values against the corpus. A +value the TypeScript leaves ``undefined`` is an ABSENT key here, as it is in the JSON. + +``notes`` is deliberately not a row field: ``documentation.json`` charters it internal-only, +and a renderer cannot leak a field the projection never carries. +""" +from __future__ import annotations + +import re +from typing import Any, Callable + +from metaobjects.codegen.requirement_walk import walk_requirements +from metaobjects.documentation.doc_constants import DOC_ATTR_DESCRIPTION, DOC_ATTR_TITLE +from metaobjects.meta.core.requirement.requirement_constants import ( + REQUIREMENT_ATTR_COUNTEREXAMPLE, + REQUIREMENT_ATTR_STATEMENT, +) +from metaobjects.meta.meta_data import MetaData + +#: The shared template refs (``/``, resolved by a provider). +REQUIREMENTS_PAGE_REF = "requirements/requirements.md" +REQUIREMENTS_TOON_REF = "requirements/requirements.toon" +AGENT_REQUIREMENTS_PAGE_REF = "agent/requirements.md" + +#: The marker the pinned page data carries. It is part of the shared contract (the corpus +#: pins it byte for byte in the page data and the pages), so every port writes this exact line. +GENERATED_MARKER = "" + +#: The TOON row's columns. ORDER is the wire contract. +REQUIREMENTS_TOON_FIELDS = ("path", "subType", "level", "status", "disposition", "claims", "statement") + +# --- ordering ------------------------------------------------------------------------- + +#: ICU root collation's order of the ASCII punctuation, which sorts before digits, which sort +#: before letters (what ``String.prototype.localeCompare`` gives the TypeScript builders). +_PUNCTUATION_ORDER = "_-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$" + + +def _collation_key(text: str) -> tuple[list[tuple[int, int | str]], list[int]]: + """An approximation of ICU root collation (the order ``localeCompare`` gives): space, then + punctuation, digits, letters (case-insensitive) at the first level; at a tie lowercase + sorts before uppercase. Enough for names, addresses and physical table names.""" + primary: list[tuple[int, int | str]] = [] + tertiary: list[int] = [] + for ch in text: + if ch == " ": + primary.append((0, 0)) + elif ch in _PUNCTUATION_ORDER: + primary.append((1, _PUNCTUATION_ORDER.index(ch))) + elif ch.isdigit(): + primary.append((2, ch)) + else: + primary.append((3, ch.casefold())) + tertiary.append(1 if ch.isupper() else 0) + return primary, tertiary + + +def locale_sorted(items: list[Any], key: Callable[[Any], str]) -> list[Any]: + """*items* sorted the way ``localeCompare`` sorts their *key* (stable).""" + return sorted(items, key=lambda item: _collation_key(key(item))) + + +# --- rows ----------------------------------------------------------------------------- + + +def _string_attr(node: MetaData, name: str) -> str | None: + """A resolving string attr; "declared but empty" is absent.""" + raw = node.get_meta_attr(name) + return raw if isinstance(raw, str) and raw != "" else None + + +def requirement_rows( + root: MetaData, in_ledger: Callable[[str], bool] | None = None +) -> list[dict[str, Any]]: + """Every ``requirement.*`` node in the project's ledger, nested ones included, as render-ready + rows in declaration order. Projects over :func:`walk_requirements`, never re-walks. ``[]`` for a + model declaring none, which is what lets the surface write nothing.""" + rows: list[dict[str, Any]] = [] + for walked in walk_requirements(root, in_ledger): + node, view = walked.node, walked.view + row: dict[str, Any] = {"path": view.path, "depth": view.path.count(".")} + title = _string_attr(node, DOC_ATTR_TITLE) + if title is not None: + row["title"] = title + row["subType"] = view.sub_type + if view.level is not None: + row["level"] = view.level + if view.status is not None: + row["status"] = view.status + disposition = node.disposition() + if disposition is not None: + row["disposition"] = disposition + row["trackedBy"] = list(node.tracked_by()) + for key, attr in ( + ("statement", REQUIREMENT_ATTR_STATEMENT), + ("counterexample", REQUIREMENT_ATTR_COUNTEREXAMPLE), + ("description", DOC_ATTR_DESCRIPTION), + ): + value = _string_attr(node, attr) + if value is not None: + row[key] = value + row["implementedBy"] = list(node.implemented_by()) + row["claimedConcerns"] = list(dict.fromkeys(t.concern for t in walked.targets)) + rows.append(row) + return rows + + +# --- requirements.md ------------------------------------------------------------------ + + +def _heading(depth: int) -> str: + """``##`` for a root-level requirement, deepening with nesting; ``#`` is the page title.""" + return "#" * min(depth + 2, 6) + + +def _normalize(text: str) -> str: + return re.sub(r"[^a-z0-9]", "", text.lower()) + + +def _title_restates_leaf(path: str, title: str) -> bool: + """True when the title says nothing the path's LEAF segment does not already say.""" + return _normalize(path[path.rfind(".") + 1 :]) == _normalize(title) + + +def _heading_line(row: dict[str, Any]) -> str: + title = re.sub(r"\s+", " ", row.get("title", "")).strip() + label = "" if title == "" or _title_restates_leaf(row["path"], title) else f" — {title}" + return f"{_heading(row['depth'])} {row['path']}{label}" + + +def _facts(row: dict[str, Any]) -> str: + parts = [f"`{row['subType']}`"] + if "level" in row: + parts.append(f"**L{row['level']}**") + if "status" in row: + parts.append(f"status: `{row['status']}`") + if "disposition" in row: + parts.append(f"disposition: `{row['disposition']}`") + if row["trackedBy"]: + parts.append(f"tracked: {', '.join(row['trackedBy'])}") + return " · ".join(parts) + + +def _demote(text: str) -> str: + """One extra ``#`` on every line that starts a heading, capped at h6.""" + return re.sub( + r"^(#{1,6}) ", lambda m: "#" * min(len(m.group(1)) + 1, 6) + " ", text, flags=re.MULTILINE + ) + + +def _entry(row: dict[str, Any], embedded: bool) -> dict[str, Any]: + line: Callable[[str], str] = _demote if embedded else (lambda text: text) + entry: dict[str, Any] = {"heading": line(_heading_line(row)), "facts": line(_facts(row))} + if "statement" in row: + entry["statement"] = line(row["statement"]) + if "counterexample" in row: + entry["counterexample"] = line(f"**Counterexample:** {row['counterexample']}") + if "description" in row: + entry["description"] = line(row["description"]) + if row["implementedBy"]: + refs = ", ".join(f"`{c}`" for c in row["implementedBy"]) + entry["implementedBy"] = line(f"**Implemented by:** {refs}") + return entry + + +def requirements_ledger_data(rows: list[dict[str, Any]], embedded: bool = False) -> dict[str, Any]: + """What ``requirements/requirements.md.mustache`` renders. ``embedded`` is the ledger as a + section of a larger page: no ``# Requirements`` title, every heading one level down.""" + return { + "embedded": embedded, + "count": len(rows), + "plural": "" if len(rows) == 1 else "s", + "entries": [_entry(r, embedded) for r in rows], + } + + +# --- requirements.toon ---------------------------------------------------------------- + +_NUMERIC_LIKE = re.compile(r"-?[0-9]+(?:\.[0-9]+)?(?:e[+-]?[0-9]+)?", re.IGNORECASE) +_LEADING_ZERO = re.compile(r"0[0-9]+") +_TOON_UNSAFE = re.compile(r'[:"\\\[\]{},\x00-\x1f]') + + +def toon_cell(value: str | int) -> str: + """One cell as TOON writes it in a comma-delimited row: a number bare, a string bare when + safe and quoted (with TOON's escapes) when it is empty, padded, numeric- or literal-looking, + or carries a delimiter, a colon, a quote, a bracket, a leading ``-`` or a control character.""" + if isinstance(value, int): + return str(value) + safe = ( + value != "" + and value == value.strip() + and value not in ("true", "false", "null") + and not _NUMERIC_LIKE.fullmatch(value) + and not _LEADING_ZERO.fullmatch(value) + and not _TOON_UNSAFE.search(value) + and not value.startswith("-") + ) + if safe: + return value + out = ['"'] + for ch in value: + if ch == "\\": + out.append("\\\\") + elif ch == '"': + out.append('\\"') + elif ch == "\n": + out.append("\\n") + elif ch == "\r": + out.append("\\r") + elif ch == "\t": + out.append("\\t") + elif ord(ch) < 0x20: + out.append(f"\\u{ord(ch):04x}") + else: + out.append(ch) + out.append('"') + return "".join(out) + + +def requirements_toon_data(rows: list[dict[str, Any]]) -> dict[str, Any]: + """What ``requirements/requirements.toon.mustache`` renders: every cell a finished literal.""" + return { + "count": len(rows), + "fields": "{" + ",".join(REQUIREMENTS_TOON_FIELDS) + "}", + "rows": [ + { + "line": ",".join( + toon_cell(cell) + for cell in ( + r["path"], + r["subType"], + r.get("level", ""), + r.get("status", ""), + r.get("disposition", ""), + " ".join(r["implementedBy"]), + r.get("statement", ""), + ) + ) + } + for r in rows + ], + } + + +# --- agent/requirements.md ------------------------------------------------------------ + + +def _node_address(node: MetaData) -> str: + """The ROOT-level node's resolution key, then the child-name path down to *node*. A claimed + field has a bare name, so the owner is part of the address.""" + segments: list[str] = [] + cur: MetaData | None = node + while cur is not None: + parent = cur.parent + if parent is None or parent.parent is None: + segments.append(cur.resolution_key()) + break + segments.append(cur.name) + cur = parent + return ".".join(reversed(segments)) + + +def build_node_index( + root: MetaData, in_ledger: Callable[[str], bool] | None = None +) -> list[dict[str, Any]]: + """Invert the walk: claimed node -> the requirements that claim it, sorted by address.""" + by_address: dict[str, dict[str, Any]] = {} + for walked in walk_requirements(root, in_ledger): + statement = walked.node.get_meta_attr(REQUIREMENT_ATTR_STATEMENT) + for target in walked.targets: + address = _node_address(target.node) + entry = by_address.setdefault( + address, {"address": address, "concern": target.concern, "claims": []} + ) + entry["claims"].append( + { + "path": walked.view.path, + "subType": walked.view.sub_type, + "level": walked.view.level, + "status": walked.view.status, + "statement": statement if isinstance(statement, str) and statement != "" else None, + } + ) + return locale_sorted(list(by_address.values()), lambda e: e["address"]) + + +def md_cell(text: str) -> str: + return text.replace("|", "\\|") + + +def one_line(text: str) -> str: + """Collapse to one line: a newline would end the table row.""" + return re.sub(r"\s+", " ", text).strip() + + +def agent_requirements_page_data( + root: MetaData, + in_ledger: Callable[[str], bool] | None, + render_ledger: Callable[[dict[str, Any]], str], +) -> dict[str, Any] | None: + """The data ``agent/requirements.md.mustache`` renders, or ``None`` for a model declaring no + requirements (no page). *render_ledger* renders the ``requirements`` template from ledger + data, so the embedded ledger is that page's own template and cannot disagree with it.""" + rows = requirement_rows(root, in_ledger) + if not rows: + return None + index = build_node_index(root, in_ledger) + stated: dict[str, dict[str, str]] = {} + for entry in index: + for c in entry["claims"]: + if c["statement"] is not None: + stated[c["path"]] = {"subType": c["subType"], "statement": c["statement"]} + statements = [ + {"path": path, "subType": info["subType"], "statement": md_cell(one_line(info["statement"]))} + for path, info in locale_sorted(list(stated.items()), lambda kv: kv[0]) + ] + + def claims_cell(entry: dict[str, Any]) -> str: + cells = [] + for c in entry["claims"]: + level = "" if c["level"] is None else f" L{c['level']}" + status = "" if c["status"] is None else f" ({c['status']})" + cells.append(f"`{c['path']}`{level}{status}") + return "
".join(cells) + + return { + "generatedMarker": GENERATED_MARKER, + "hasNodeIndex": len(index) > 0, + "nodeIndex": [ + {"address": e["address"], "concern": e["concern"], "claims": claims_cell(e)} for e in index + ], + "hasStatements": len(statements) > 0, + "statements": statements, + # The embedded ledger drops its own H1, demotes every heading one level, and loses its + # trailing line breaks (the agent template supplies the page's last one). + "ledger": render_ledger(requirements_ledger_data(rows, embedded=True)).rstrip("\n"), + } diff --git a/server/python/src/metaobjects/codegen/runtime/docs_schema.py b/server/python/src/metaobjects/codegen/runtime/docs_schema.py new file mode 100644 index 000000000..76311c5ef --- /dev/null +++ b/server/python/src/metaobjects/codegen/runtime/docs_schema.py @@ -0,0 +1,522 @@ +"""The MODEL-ONLY ``agent/schema.md``: the rows layer and the page data, built from the model. + +Mirrors the TypeScript ``agent-schema-rows.ts`` and ``agent-schema-page.ts`` (the +``physical: false`` page). TypeScript builds its rows from the expected schema; a port +without it builds them from the model with its own naming helpers (design call 17 of +``fixtures/docs-page-conformance/``): a table per concrete object whose primary source is a +writable table (abstract bases, sourceless values and ``@unmanaged`` tables have none; a TPH +subtype shares its base's table and adds its own columns after the base's, nullable), a view +per object whose primary source is a view. The page carries no SQL type, default, index, +check, constraint name or referential action: the model cannot know them. + +Rows and page data are plain dicts so they compare as JSON values against the corpus. +""" +from __future__ import annotations + +import re +from typing import Any + +from metaobjects.codegen.instance_artifacts import is_abstract +from metaobjects.codegen.model_walk import is_required +from .docs_requirements import GENERATED_MARKER, locale_sorted +from metaobjects.codegen.type_map import effective_enum_values +from metaobjects.documentation.doc_constants import DOC_ATTR_DESCRIPTION +from metaobjects.meta.core.field import field_constants as fc +from metaobjects.meta.core.field.meta_field import MetaField +from metaobjects.meta.core.identity.identity_constants import ( + GENERATION_INCREMENT, + GENERATION_UUID, + IDENTITY_ATTR_FIELDS, + IDENTITY_ATTR_GENERATION, + IDENTITY_REFERENCE_ATTR_ENFORCE, + IDENTITY_REFERENCE_ATTR_REFERENCES, + IDENTITY_SUBTYPE_REFERENCE, +) +from metaobjects.meta.core.object.meta_object import MetaObject +from metaobjects.meta.core.object.object_constants import ( + OBJECT_ATTR_DISCRIMINATOR, + OBJECT_ATTR_DISCRIMINATOR_VALUE, + OBJECT_SUBTYPE_REPORT, +) +from metaobjects.meta.core.relationship.relationship_constants import ( + CARDINALITY_MANY, + CARDINALITY_ONE, + RELATIONSHIP_ATTR_CARDINALITY, + RELATIONSHIP_ATTR_OBJECT_REF, + RELATIONSHIP_ATTR_ON_DELETE, + RELATIONSHIP_ATTR_THROUGH, +) +from metaobjects.meta.meta_data import MetaData +from metaobjects.meta.persistence.origin import origin_constants as oc +from metaobjects.meta.persistence.source.meta_source import MetaSource +from metaobjects.naming import ( + apply_column_naming_strategy, + naming_rules_of, + resolve_column_name, + resolve_flattened_column_name, +) +from metaobjects.naming_refs import ref_target, split_child_tail +from metaobjects.shared.base_types import TYPE_IDENTITY, TYPE_ORIGIN, TYPE_RELATIONSHIP +from metaobjects.source_resolution import primary_rdb_source + +AGENT_SCHEMA_PAGE_REF = "agent/schema.md" + +_SOURCE_KIND_VIEW = "view" + + +def is_report(obj: MetaObject) -> bool: + return obj.sub_type == OBJECT_SUBTYPE_REPORT + + +# --- the model, as rows --------------------------------------------------------------- + + +def row_key(name: str, schema: str | None) -> str: + """The key ``declaredBy`` uses: what a page heading prints, without the backticks.""" + return name if schema is None else f"{schema}.{name}" + + +def _objects(root: MetaData) -> list[MetaObject]: + return [c for c in root.children() if isinstance(c, MetaObject)] + + +def _description(node: MetaData) -> str | None: + v = node.get_meta_attr(DOC_ATTR_DESCRIPTION) + return v if isinstance(v, str) and v != "" else None + + +def _discriminator_base(entity: MetaData) -> MetaData | None: + """The ``@discriminator``-bearing ANCESTOR of *entity*, or ``None``.""" + ancestor = entity.super_data + while ancestor is not None: + # ADR-0039 sanctioned own: explicit super-resolution walk, each ancestor's own attr. + if ancestor.attr(OBJECT_ATTR_DISCRIMINATOR) is not None: + return ancestor + ancestor = ancestor.super_data + return None + + +def _is_tph_subtype(entity: MetaData) -> bool: + return ( + entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) is not None + and _discriminator_base(entity) is not None + ) + + +def _tph_concrete_subtypes(base: MetaObject, objects: list[MetaObject]) -> list[MetaObject]: + if base.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is None: + return [] + return [ + o + for o in objects + if not is_abstract(o) + and o.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) is not None + and _discriminator_base(o) is base + ] + + +def _identity_fields(identity: MetaData) -> list[str]: + v = identity.get_meta_attr(IDENTITY_ATTR_FIELDS) + if isinstance(v, str): + return [s.strip() for s in v.split(",") if s.strip()] + return [str(x) for x in v] if isinstance(v, (list, tuple)) else [] + + +def _find_field(obj: MetaObject, name: str) -> MetaField | None: + return obj.find_field(name) + + +def _column_row(field: MetaData, is_pk: bool, generation: str | None, name: str) -> dict[str, Any]: + col: dict[str, Any] = {"name": name, "nullable": not is_pk and not is_required(field)} + if is_pk and generation in (GENERATION_INCREMENT, GENERATION_UUID): + col["identity"] = generation + description = _description(field) + if description is not None: + col["description"] = description + return col + + +def _flattened(field: MetaField) -> bool: + return ( + field.sub_type == fc.FIELD_SUBTYPE_OBJECT + and field.get_meta_attr(fc.FIELD_ATTR_STORAGE) == fc.STORAGE_FLATTENED + ) + + +def _field_columns(field: MetaField, is_pk: bool, generation: str | None) -> list[dict[str, Any]]: + if _flattened(field): + target = ref_target(field, fc.FIELD_ATTR_OBJECT_REF) + if not isinstance(target, MetaObject): + return [] + return [ + _column_row(nested, False, None, resolve_flattened_column_name(field, nested)) + for nested in target.fields() + ] + return [_column_row(field, is_pk, generation, resolve_column_name(field))] + + +def _target_columns(ref: MetaData, target: MetaObject) -> list[str]: + """The referenced key's columns: an explicit dotted tail on ``@references``, else the + target's primary identity (its first field), else ``id``.""" + raw = ref.get_meta_attr(IDENTITY_REFERENCE_ATTR_REFERENCES) + tail = split_child_tail(raw)[1] if isinstance(raw, str) else "" + explicit = [s.strip() for s in tail.lstrip(".").split(",") if s.strip()] + if explicit: + names = explicit + else: + identity = target.primary_identity() + pk = _identity_fields(identity) if identity is not None else [] + names = [pk[0] if pk else "id"] + out = [] + for name in names: + f = _find_field(target, name) + out.append(resolve_column_name(f) if f is not None else apply_column_naming_strategy(name, naming_rules_of(target).columns)) + return out + + +def _foreign_keys( + entity: MetaObject, objects: list[MetaObject], table_of: dict[str, str] +) -> list[dict[str, Any]]: + refs: list[tuple[MetaObject, MetaData]] = [ + (entity, c) for c in entity.children() if c.type == TYPE_IDENTITY and c.sub_type == IDENTITY_SUBTYPE_REFERENCE + ] + if entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is not None: + base_names = {r.name for _h, r in refs} + for sub in _tph_concrete_subtypes(entity, objects): + for c in sub.children(): + if c.type == TYPE_IDENTITY and c.sub_type == IDENTITY_SUBTYPE_REFERENCE and c.name not in base_names: + refs.append((sub, c)) + fks: list[dict[str, Any]] = [] + for holder, ref in refs: + if ref.get_meta_attr(IDENTITY_REFERENCE_ATTR_ENFORCE) is False: + continue # a logical-only reference is no constraint + target = ref_target(ref, IDENTITY_REFERENCE_ATTR_REFERENCES) + if not isinstance(target, MetaObject): + continue + ref_table = table_of.get(target.resolution_key()) + if not ref_table: + continue + names = _identity_fields(ref) + if not names: + continue + columns = [] + for name in names: + f = _find_field(holder, name) + columns.append(resolve_column_name(f) if f is not None else apply_column_naming_strategy(name, naming_rules_of(holder).columns)) + fk = {"columns": columns, "refTable": ref_table, "refColumns": _target_columns(ref, target)} + if fk not in fks: # two subtypes may declare the same column: one constraint + fks.append(fk) + return fks + + +def _primary(entity: MetaObject) -> MetaSource | None: + return primary_rdb_source(entity) + + +def schema_rows(root: MetaData) -> dict[str, Any]: + """The rows layer of the model-only schema page: tables and views sorted by name (code + points, as the snapshot file sorts them), a table's columns and keys in declaration order, + and ``declaredBy`` (each table or view -> the declaring object).""" + objects = _objects(root) + # Pass 1: which objects own a table, and which are only an FK target. + entities: list[tuple[MetaObject, MetaSource]] = [] + target_only: list[tuple[MetaObject, MetaSource]] = [] + tph_members: list[tuple[MetaObject, MetaData]] = [] + for obj in objects: + base = _discriminator_base(obj) + if base is not None and (is_abstract(obj) or _is_tph_subtype(obj)): + tph_members.append((obj, base)) + continue + if is_abstract(obj): + continue + if not any(isinstance(c, MetaSource) and c.is_writable() for c in obj.children()): + continue + source = _primary(obj) + if source is None: + continue + # ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. + own = next((c for c in obj.own_children() if isinstance(c, MetaSource) and c.is_writable()), None) + if own is not None and own.is_unmanaged(): + target_only.append((obj, source)) + continue + entities.append((obj, source)) + table_of: dict[str, str] = {o.resolution_key(): s.physical_name() for o, s in [*entities, *target_only]} + for member, base in tph_members: + name = table_of.get(base.resolution_key()) + if name is not None and member.resolution_key() not in table_of: + table_of[member.resolution_key()] = name + + tables: list[dict[str, Any]] = [] + declared: dict[str, str] = {} + for entity, source in entities: + identity = entity.primary_identity() + pk_names = _identity_fields(identity) if identity is not None else [] + generation = identity.get_meta_attr(IDENTITY_ATTR_GENERATION) if identity is not None else None + generation = generation if isinstance(generation, str) else None + primary_key = [] + for name in pk_names: + f = _find_field(entity, name) + primary_key.append(resolve_column_name(f) if f is not None else apply_column_naming_strategy(name, naming_rules_of(entity).columns)) + columns: list[dict[str, Any]] = [] + for field in entity.fields(): + if field.is_derived(): + continue + columns.extend(_field_columns(field, field.name in pk_names, generation if field.name in pk_names else None)) + if entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is not None: + existing = {c["name"] for c in columns} + base_fields = {f.name for f in entity.fields()} + for sub in _tph_concrete_subtypes(entity, objects): + for field in sub.fields(): + if field.name in base_fields or field.is_derived(): + continue + col = _column_row(field, False, None, resolve_column_name(field)) + if col["name"] in existing: + continue + col["nullable"] = True # a row of any other subtype stores NULL here + columns.append(col) + existing.add(col["name"]) + table: dict[str, Any] = {"name": source.physical_name()} + schema = source.schema() + if schema is not None: + table["schema"] = schema + description = _description(entity) + if description is not None: + table["description"] = description + table["primaryKey"] = primary_key + table["columns"] = columns + table["foreignKeys"] = _foreign_keys(entity, objects, table_of) + tables.append(table) + declared[row_key(table["name"], schema)] = entity.resolution_key() + + views: list[dict[str, Any]] = [] + for obj in objects: + if is_abstract(obj): + continue + source = _primary(obj) + if source is None or source.effective_kind() != _SOURCE_KIND_VIEW: + continue + view: dict[str, Any] = {"name": source.physical_name()} + schema = source.schema() + if schema is not None: + view["schema"] = schema + key = row_key(view["name"], schema) + if key in declared: + continue + views.append(view) + declared[key] = obj.resolution_key() + + tables.sort(key=lambda t: t["name"]) + views.sort(key=lambda v: v["name"]) + return {"tables": tables, "views": views, "declaredBy": dict(sorted(declared.items()))} + + +# --- the page, from rows and the model ------------------------------------------------ + + +def _md_cell_free(text: str) -> str: + return re.sub(r"\s+", " ", text).strip() + + +def _cols(names: list[str]) -> str: + return "—" if not names else ", ".join(f"`{c}`" for c in names) + + +def _key_cell(table: dict[str, Any], column: dict[str, Any]) -> str: + roles: list[str] = [] + if column["name"] in table["primaryKey"]: + roles.append("PK (composite)" if len(table["primaryKey"]) > 1 else "PK") + fk = next((f for f in table["foreignKeys"] if column["name"] in f["columns"]), None) + if fk is not None: + roles.append(f"FK → `{fk['refTable']}`") + return " · ".join(roles) + + +def _lineage_of(field: MetaField) -> str | None: + # ADR-0039 sanctioned own: an origin.* NEVER inherits. + origin = next((c for c in field.own_children() if c.type == TYPE_ORIGIN), None) + if origin is None: + return None + + def text(name: str) -> str | None: + v = origin.authored_attr(name) + return v if isinstance(v, str) and v != "" else None + + sub = origin.sub_type + if sub == oc.ORIGIN_SUBTYPE_PASSTHROUGH: + src, via = text(oc.ORIGIN_ATTR_FROM), text(oc.ORIGIN_ATTR_VIA) + return f"passthrough from `{src or '?'}`" + ("" if via is None else f" via `{via}`") + if sub == oc.ORIGIN_SUBTYPE_AGGREGATE: + agg = text(oc.ORIGIN_ATTR_AGG) or "?" + of, via = text(oc.ORIGIN_ATTR_OF), text(oc.ORIGIN_ATTR_VIA) + return f"`{agg}`" + ("" if of is None else f" of `{of}`") + ("" if via is None else f" via `{via}`") + if sub == oc.ORIGIN_SUBTYPE_FIRST: + of, via, order = text(oc.ORIGIN_ATTR_OF), text(oc.ORIGIN_ATTR_VIA), text(oc.ORIGIN_ATTR_ORDER_BY) + return ( + "first" + + ("" if of is None else f" `{of}`") + + ("" if via is None else f" via `{via}`") + + ("" if order is None else f" ordered by `{order}`") + ) + if sub == oc.ORIGIN_SUBTYPE_COMPUTED: + return "computed from a declared `@expr`" + return f"`origin.{sub}`" + + +def _cardinality_phrase(cardinality: object, through: object) -> str: + if cardinality == CARDINALITY_MANY: + return "many-to-many" if isinstance(through, str) and through != "" else "one-to-many" + if cardinality == CARDINALITY_ONE: + return "many-to-one" + return "cardinality not declared" + + +def _relationship_lines(objects: list[MetaObject]) -> list[str]: + out: list[str] = [] + for obj in objects: + for rel in (c for c in obj.children() if c.type == TYPE_RELATIONSHIP): + cardinality = rel.get_meta_attr(RELATIONSHIP_ATTR_CARDINALITY) + target = rel.authored_attr(RELATIONSHIP_ATTR_OBJECT_REF) + through = rel.authored_attr(RELATIONSHIP_ATTR_THROUGH) + on_delete = rel.get_meta_attr(RELATIONSHIP_ATTR_ON_DELETE) + parts = [f"`{obj.resolution_key()}.{rel.name}`", f"`{rel.sub_type}`"] + parts.append(f"{_cardinality_phrase(cardinality, through)} → `{target if target is not None else '?'}`") + if isinstance(through, str) and through != "": + parts.append(f"through `{through}`") + if isinstance(on_delete, str) and on_delete != "": + parts.append(f"on delete `{on_delete}`") + out.append(" · ".join(parts)) + return out + + +def _enum_rows(objects: list[MetaObject]) -> list[dict[str, str]]: + rows: list[dict[str, str]] = [] + for obj in objects: + for field in obj.fields(): + if field.sub_type != fc.FIELD_SUBTYPE_ENUM: + continue + members = effective_enum_values(field) + if not members: + continue + int_map = field.get_meta_attr(fc.FIELD_ATTR_INT_VALUE_MAP) + if isinstance(int_map, dict): + storage = "int-backed (" + ", ".join(f"{m}={int_map[m]}" for m in members) + ")" + else: + storage = "string-backed" + rows.append( + { + "field": f"{obj.resolution_key()}.{field.name}", + "members": ", ".join(f"`{m}`" for m in members), + "storage": storage, + } + ) + return rows + + +def agent_schema_page_data(root: MetaData, rows: dict[str, Any]) -> dict[str, Any] | None: + """The data ``agent/schema.md.mustache`` renders (``physical: false``), built from the rows + and the model alone. ``None`` when there is no table and no view: no page.""" + if not rows["tables"] and not rows["views"]: + return None + objects = _objects(root) + table_keys = {row_key(t["name"], t.get("schema")) for t in rows["tables"]} + view_keys = {row_key(v["name"], v.get("schema")) for v in rows["views"]} + + table_backed: list[MetaObject] = [] + declared_by: dict[str, dict[str, tuple[str, str]]] = {} + view_lineage: dict[str, list[dict[str, str]]] = {} + report_views: set[str] = set() + for obj in objects: + source = _primary(obj) + if source is None: + continue + key = row_key(source.physical_name(), source.schema()) + is_table = key in table_keys + if not is_table and key not in view_keys: + continue + # An abstract base that declares the source its concrete child inherits resolves to + # that child's table: it is in the schema but is no table-backed object. + if is_table and not is_abstract(obj): + table_backed.append(obj) + if not is_table and is_report(obj): + report_views.add(key) + mapping = declared_by.setdefault(key, {}) + lineage: list[dict[str, str]] = [] + for field in obj.fields(): + column = resolve_column_name(field) + # A TPH base and its subtypes share one table: first writer wins. + if column not in mapping: + mapping[column] = (field.name, f"{field.type}.{field.sub_type}") + text = _lineage_of(field) + if text is not None: + lineage.append({"column": column, "text": text}) + if lineage: + view_lineage[key] = lineage + + relationships = _relationship_lines(objects) + enums = _enum_rows(table_backed) + any_description = any( + t.get("description", "") != "" or any(c.get("description", "") != "" for c in t["columns"]) + for t in rows["tables"] + ) + + tables = [] + for table in locale_sorted(rows["tables"], lambda t: t["name"]): + key = row_key(table["name"], table.get("schema")) + mapping = declared_by.get(key, {}) + described = [c for c in table["columns"] if c.get("description", "") != ""] + fks = [f"{_cols(f['columns'])} → `{f['refTable']}`({_cols(f['refColumns'])})" for f in table["foreignKeys"]] + entry: dict[str, Any] = {"heading": f"`{key}`"} + if key in rows["declaredBy"]: + entry["tableDeclaredBy"] = rows["declaredBy"][key] + if table.get("description", "") != "": + entry["tableDescription"] = _md_cell_free(table["description"]) + entry["columns"] = [ + { + "name": c["name"], + "fieldCell": f"`{mapping[c['name']][0]}`" if c["name"] in mapping else "", + "declaredCell": f"`{mapping[c['name']][1]}`" if c["name"] in mapping else "", + "sqlTypeCell": "", + "nullCell": "yes" if c["nullable"] else "no", + "defaultCell": "", + "keyCell": _key_cell(table, c), + } + for c in table["columns"] + ] + entry.update( + hasDescribed=len(described) > 0, + described=[{"name": c["name"], "text": _md_cell_free(c["description"])} for c in described], + hasIndexes=False, + indexes=[], + hasForeignKeys=len(fks) > 0, + foreignKeys=fks, + hasChecks=False, + checks=[], + ) + tables.append(entry) + + views = [] + for view in locale_sorted(rows["views"], lambda v: v["name"]): + key = row_key(view["name"], view.get("schema")) + lineage = view_lineage.get(key, []) + entry = {"heading": f"`{key}`"} + if key in rows["declaredBy"]: + entry["viewDeclaredBy"] = rows["declaredBy"][key] + entry["hasLineage"] = len(lineage) > 0 + entry["lineage"] = lineage + views.append(entry) + + return { + "generatedMarker": GENERATED_MARKER, + "physical": False, + "dialect": "", + "descriptionNudge": not any_description and len(rows["tables"]) > 0, + "hasTables": len(tables) > 0, + "tables": tables, + "hasViews": len(views) > 0, + "hasReportView": any(row_key(v["name"], v.get("schema")) in report_views for v in rows["views"]), + "views": views, + "hasRelationships": len(relationships) > 0, + "relationships": relationships, + "hasEnums": len(enums) > 0, + "enums": enums, + } diff --git a/server/python/src/metaobjects/render/bundled_templates/agent/requirements.md.mustache b/server/python/src/metaobjects/render/bundled_templates/agent/requirements.md.mustache new file mode 100644 index 000000000..cb7cba06c --- /dev/null +++ b/server/python/src/metaobjects/render/bundled_templates/agent/requirements.md.mustache @@ -0,0 +1,34 @@ +{{{generatedMarker}}} + +# Requirements + +Read this before adding a capability, and before extending anything that looks like it already does what you were asked for. + +- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild. +- The **node index** below answers *"does anything claim the thing I am about to change?"*. Match the literal FQN. +- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet. + +## Node index + +{{#hasNodeIndex}} +| Node | Kind | Claimed by | +|---|---|---| +{{#nodeIndex}} +| `{{{address}}}` | `{{{concern}}}` | {{{claims}}} | +{{/nodeIndex}} +{{#hasStatements}} + +### What those requirements say + +{{#statements}} +- `{{{path}}}` (`{{{subType}}}`) — {{{statement}}} +{{/statements}} +{{/hasStatements}} +{{/hasNodeIndex}} +{{^hasNodeIndex}} +No requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which. +{{/hasNodeIndex}} + +## The ledger + +{{{ledger}}} diff --git a/server/python/src/metaobjects/render/bundled_templates/agent/schema.md.mustache b/server/python/src/metaobjects/render/bundled_templates/agent/schema.md.mustache new file mode 100644 index 000000000..3c3da61ea --- /dev/null +++ b/server/python/src/metaobjects/render/bundled_templates/agent/schema.md.mustache @@ -0,0 +1,118 @@ +{{{generatedMarker}}} + +# Schema + +{{#physical}} +The physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column. +{{/physical}} +{{^physical}} +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. +{{/physical}} + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +{{#descriptionNudge}} +> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text `meta migrate` emits as a `COMMENT ON`, so it lands in the database too. + +{{/descriptionNudge}} +{{#hasTables}} +## Tables + +{{#tables}} +### {{{heading}}} + +{{#tableDeclaredBy}} +Declared by `{{{.}}}`. +{{/tableDeclaredBy}} +{{#tableDescription}} + +> {{{.}}} +{{/tableDescription}} + +{{#physical}} +| Column | Field | Declared | SQL type | Null | Default | Key | +|---|---|---|---|---|---|---| +{{/physical}} +{{^physical}} +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +{{/physical}} +{{#columns}} +| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} | +{{/columns}} +{{#hasDescribed}} + +{{#described}} +- `{{{name}}}` — {{{text}}} +{{/described}} +{{/hasDescribed}} +{{#hasIndexes}} + +**Indexes** + +{{#indexes}} +- {{{.}}} +{{/indexes}} +{{/hasIndexes}} +{{#hasForeignKeys}} + +**Foreign keys** + +{{#foreignKeys}} +- {{{.}}} +{{/foreignKeys}} +{{/hasForeignKeys}} +{{#hasChecks}} + +**Checks** + +{{#checks}} +- {{{.}}} +{{/checks}} +{{/hasChecks}} + +{{/tables}} +{{/hasTables}} +{{#hasViews}} +## Views + +A view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see. + +{{#views}} +### {{{heading}}} + +{{#viewDeclaredBy}} +Declared by `{{{.}}}`. +{{/viewDeclaredBy}} +{{#hasLineage}} + +| Column | Lineage | +|---|---| +{{#lineage}} +| `{{{column}}}` | {{{text}}} | +{{/lineage}} +{{/hasLineage}} + +{{/views}} +{{/hasViews}} +{{#hasRelationships}} +## Relationships + +{{#relationships}} +- {{{.}}} +{{/relationships}} + +{{/hasRelationships}} +{{#hasEnums}} +## Enums + +Members are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}} + +| Field | Members | Storage | +|---|---|---| +{{#enums}} +| `{{{field}}}` | {{{members}}} | {{{storage}}} | +{{/enums}} +{{/hasEnums}} diff --git a/server/python/src/metaobjects/render/bundled_templates/requirements/requirements.md.mustache b/server/python/src/metaobjects/render/bundled_templates/requirements/requirements.md.mustache new file mode 100644 index 000000000..a20009447 --- /dev/null +++ b/server/python/src/metaobjects/render/bundled_templates/requirements/requirements.md.mustache @@ -0,0 +1,27 @@ +{{^embedded}} +# Requirements + +{{/embedded}} +{{{count}}} declared requirement{{{plural}}}, in declaration order. +{{#entries}} + +{{{heading}}} + +{{{facts}}} +{{#statement}} + +{{{.}}} +{{/statement}} +{{#counterexample}} + +{{{.}}} +{{/counterexample}} +{{#description}} + +{{{.}}} +{{/description}} +{{#implementedBy}} + +{{{.}}} +{{/implementedBy}} +{{/entries}} diff --git a/server/python/src/metaobjects/render/bundled_templates/requirements/requirements.toon.mustache b/server/python/src/metaobjects/render/bundled_templates/requirements/requirements.toon.mustache new file mode 100644 index 000000000..cae64ef89 --- /dev/null +++ b/server/python/src/metaobjects/render/bundled_templates/requirements/requirements.toon.mustache @@ -0,0 +1,2 @@ +requirements[{{{count}}}]{{{fields}}}:{{#rows}} + {{{line}}}{{/rows}} \ No newline at end of file diff --git a/server/python/src/metaobjects/render/doc_pages.py b/server/python/src/metaobjects/render/doc_pages.py new file mode 100644 index 000000000..39d2e3533 --- /dev/null +++ b/server/python/src/metaobjects/render/doc_pages.py @@ -0,0 +1,62 @@ +"""Rendering a docs page from a shared Mustache template (``templates//.mustache``). + +The documentation generators (``requirements``, ``agent-docs``) feed a template the data a +builder computed. The templates ship with the package (``bundled_templates/``, a byte copy of +the repo-root ``templates/`` that ``scripts/sync-doc-templates.sh`` maintains and the +``doc-template drift`` gate holds), and a project overrides a page by dropping a same-named +file under its own templates directory. +""" +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from metaobjects.render import escapers +from metaobjects.render.filesystem_provider import FilesystemProvider +from metaobjects.render.renderer import RenderError, RenderRequest, render +from metaobjects.render.verify import Provider + +#: The directory the bundled copy of the shared doc templates lives in. +BUNDLED_TEMPLATES_DIR = Path(__file__).resolve().parent / "bundled_templates" + + +class LayeredProvider: + """The project's templates first, the bundled ones behind them.""" + + def __init__(self, *providers: FilesystemProvider) -> None: + self._providers = providers + + def resolve(self, ref: str | None) -> str | None: + for p in self._providers: + found = p.resolve(ref) + if found is not None: + return found + return None + + def engine_of(self, ref: str) -> str | None: + for p in self._providers: + if p.resolve(ref) is not None: + return p.engine_of(ref) + return None + + +def doc_provider(template_root: str | Path | None = None) -> Provider: + """The provider doc pages resolve from: *template_root* (a project's templates directory) + overrides a bundled page of the same ref.""" + layers = [FilesystemProvider(BUNDLED_TEMPLATES_DIR)] + if template_root: + layers.insert(0, FilesystemProvider(template_root)) + return LayeredProvider(*layers) + + +def end_with_one_newline(page: str) -> str: + """A page ends on exactly one line break, whichever section came last.""" + return page.rstrip("\n") + "\n" + + +def render_doc_page(ref: str, payload: Any, provider: Provider, path: str) -> str: + """Render one Markdown docs page; an engine error names the page ref and the output path.""" + try: + return render(RenderRequest(ref=ref, payload=payload, provider=provider, format=escapers.FORMAT_MARKDOWN)) + except RenderError as err: + raise RenderError(f"docs-file: failed rendering '{ref}' for '{path}': {err}") from err diff --git a/server/python/src/metaobjects/render/renderer.py b/server/python/src/metaobjects/render/renderer.py index a230dcf9b..e929f6bd1 100644 --- a/server/python/src/metaobjects/render/renderer.py +++ b/server/python/src/metaobjects/render/renderer.py @@ -361,8 +361,15 @@ def _emit( finally: stack.pop() else: - # truthy scalar — render body once in current context - _emit(tok.children, stack, out, format_) + # Truthy scalar: render the body once with the scalar as the context, so the + # implicit iterator `{{.}}` names it (a string-valued section, as in the spec). + # A name lookup skips a non-mapping context, so the body still sees the + # enclosing mappings exactly as before. + stack.append(value) + try: + _emit(tok.children, stack, out, format_) + finally: + stack.pop() def _resolve(path: str, stack: list[Any]) -> Any: diff --git a/server/python/tests/codegen/test_cli_registry.py b/server/python/tests/codegen/test_cli_registry.py index 92a67c892..31538589e 100644 --- a/server/python/tests/codegen/test_cli_registry.py +++ b/server/python/tests/codegen/test_cli_registry.py @@ -40,8 +40,8 @@ def test_gen_list_prints_all_and_exits_zero(capsys, tmp_path: Path) -> None: # Every registered stable name appears in the listing. for name in GENERATOR_REGISTRY: assert name in out, f"--list omitted {name!r}" - # Exactly the 14 registered names (ADR-0056 removed `payload`; FR-023 added `shared-model`) - assert len(GENERATOR_REGISTRY) == 14 + # Exactly the 16 registered names (`requirements` and `agent-docs` joined in G-PY-1; ADR-0056 removed `payload`; FR-023 added `shared-model`) + assert len(GENERATOR_REGISTRY) == 16 assert "payload" not in GENERATOR_REGISTRY # A template-tier generator says it needs the entity generator's models. assert "output-parser — " in out diff --git a/server/python/tests/conformance/test_docs_page_conformance.py b/server/python/tests/conformance/test_docs_page_conformance.py new file mode 100644 index 000000000..3d8289860 --- /dev/null +++ b/server/python/tests/conformance/test_docs_page_conformance.py @@ -0,0 +1,149 @@ +"""Cross-port docs-page corpus: fixtures/docs-page-conformance/. + +The requirements page, the agent requirements page and the MODEL-ONLY agent schema page are +shared Mustache templates fed data a per-port builder computes. TypeScript is the source of +the expected bytes; this runner holds the Python builders to them in three layers, so a +failure says where it is: the ROWS each builder starts from (JSON value equality), the PAGE +DATA each template is fed (JSON value equality), then the BYTES. The SET of pages is pinned +too: a page the case does not list must not be written. +""" +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from metaobjects import MetaDataLoader +from metaobjects.codegen.generator import GenContext +from metaobjects.codegen.generators.agent_docs_generator import AgentDocsGenerator +from metaobjects.codegen.generators.requirements_generator import RequirementsGenerator +from metaobjects.codegen.runtime.docs_requirements import ( + REQUIREMENTS_PAGE_REF, + REQUIREMENTS_TOON_REF, + agent_requirements_page_data, + requirement_rows, + requirements_ledger_data, + requirements_toon_data, + toon_cell, +) +from metaobjects.codegen.runtime.docs_schema import agent_schema_page_data, schema_rows +from metaobjects.render.doc_pages import doc_provider, render_doc_page + + +def _corpus() -> Path: + here = Path(__file__).resolve() + for parent in here.parents: + candidate = parent / "fixtures" / "docs-page-conformance" / "cases" + if candidate.is_dir(): + return candidate + raise RuntimeError("could not locate fixtures/docs-page-conformance") + + +CORPUS = _corpus() +CASES = sorted(p.name for p in CORPUS.iterdir() if p.is_dir()) + + +def _load(case: str): + from metaobjects.loader.sources import FileSource + + files = sorted((CORPUS / case / "input").glob("meta.*.json")) + result = MetaDataLoader(strict=True).load([FileSource(p) for p in files]) + assert not result.errors, result.errors + return result.root + + +def _expected(case: str) -> dict[str, str]: + base = CORPUS / case / "expected" + return {p.relative_to(base).as_posix(): p.read_text(encoding="utf-8") for p in base.rglob("*") if p.is_file()} + + +def _json(expected: dict[str, str], path: str) -> Any: + return json.loads(expected[path]) + + +def _ctx(root) -> GenContext: + from metaobjects.codegen.config import GenConfig + + return GenContext(entities=[], loaded_root=root, matches=lambda _e: True, config=GenConfig(out_dir="out"), warn=lambda _m: None) + + +def test_the_corpus_is_not_empty() -> None: + assert CASES + + +@pytest.mark.parametrize("case", CASES) +def test_rows_data_and_bytes(case: str) -> None: + root = _load(case) + expected = _expected(case) + provider = doc_provider() + + rows = requirement_rows(root) + if rows: + assert rows == _json(expected, "rows/requirements.json"), "requirement rows" + assert requirements_ledger_data(rows) == _json(expected, "data/requirements.md.json") + assert requirements_toon_data(rows) == _json(expected, "data/requirements.toon.json") + assert ( + render_doc_page(REQUIREMENTS_PAGE_REF, requirements_ledger_data(rows), provider, "requirements.md") + == expected["requirements.md"] + ) + assert ( + render_doc_page(REQUIREMENTS_TOON_REF, requirements_toon_data(rows), provider, "requirements.toon") + == expected["requirements.toon"] + ) + + def ledger(data: dict[str, Any]) -> str: + return render_doc_page(REQUIREMENTS_PAGE_REF, data, provider, "requirements.md") + + agent = agent_requirements_page_data(root, None, ledger) + if agent is not None: + assert agent == _json(expected, "data/agent-requirements.md.json"), "agent requirements data" + + srows = schema_rows(root) + data = agent_schema_page_data(root, srows) + if data is not None: + assert srows == _json(expected, "rows/schema.json"), "schema rows" + assert data == _json(expected, "data/agent-schema.md.json"), "schema page data" + + # The generators write exactly the pinned pages, byte for byte (the set is pinned too). + ctx = _ctx(root) + written = {f.path: f.content for f in RequirementsGenerator().generate(ctx)} + written.update({f.path: f.content for f in AgentDocsGenerator().generate(ctx)}) + pages = {k: v for k, v in expected.items() if not k.startswith(("data/", "rows/"))} + assert sorted(written) == sorted(pages) + for path, content in pages.items(): + assert written[path] == content, path + + +@pytest.mark.parametrize( + ("value", "cell"), + [ + (4, "4"), + ("plain words", "plain words"), + ("", '""'), + ("true", '"true"'), + ("12", '"12"'), + ("007", '"007"'), + ("a, b", '"a, b"'), + ("a: b", '"a: b"'), + ("-x", '"-x"'), + (" padded", '" padded"'), + ("line\nbreak", '"line\\nbreak"'), + ("tab\there", '"tab\\there"'), + ("bell\x07", '"bell\\u0007"'), + ('q"uote', '"q\\"uote"'), + ], +) +def test_toon_cell_quoting(value: str | int, cell: str) -> None: + assert toon_cell(value) == cell + + +def test_a_project_template_overrides_the_bundled_page(tmp_path: Path) -> None: + root = _load("ledger-unclaimed") + override = tmp_path / "requirements" + override.mkdir() + (override / "requirements.toon.mustache").write_text("custom {{{count}}}", encoding="utf-8") + files = {f.path: f.content for f in RequirementsGenerator(template_root=str(tmp_path)).generate(_ctx(root))} + assert files["requirements.toon"] == "custom 1" + assert files["requirements.md"].startswith("# Requirements") diff --git a/server/python/tests/conformance/test_generator_registry_conformance.py b/server/python/tests/conformance/test_generator_registry_conformance.py index e612f2c18..3067995e1 100644 --- a/server/python/tests/conformance/test_generator_registry_conformance.py +++ b/server/python/tests/conformance/test_generator_registry_conformance.py @@ -109,11 +109,12 @@ def test_every_manifest_entry_declares_one_of_the_seven_layers() -> None: ) -def test_registry_python_slice_is_all_native() -> None: - # The Python slice of the manifest is entirely tier: native. - assert all(e.tier == "native" for e in GENERATOR_REGISTRY.values()), ( - "Every Python registry entry must be tier 'native'; found: " - + ", ".join(f"{k}={v.tier}" for k, v in GENERATOR_REGISTRY.items() if v.tier != "native") +def test_registry_python_slice_tiers_are_native_or_neutral() -> None: + # The Python slice is native, plus the neutral docs generators (requirements, agent-docs). + # Each entry's tier is held to the manifest by test_registry_tiers_agree_with_manifest. + assert all(e.tier in ("native", "neutral") for e in GENERATOR_REGISTRY.values()), ( + "Every Python registry entry must be tier 'native' or 'neutral'; found: " + + ", ".join(f"{k}={v.tier}" for k, v in GENERATOR_REGISTRY.items() if v.tier not in ("native", "neutral")) ) diff --git a/server/python/tests/test_reporting_inert.py b/server/python/tests/test_reporting_inert.py index 88d042f7e..8067ac413 100644 --- a/server/python/tests/test_reporting_inert.py +++ b/server/python/tests/test_reporting_inert.py @@ -59,12 +59,14 @@ def _code_generators() -> list[GeneratorEntry]: - """Every registered generator but ``api-docs``. Since 1.1.0 ``gen`` runs ``api-docs`` like + """Every registered generator but the docs layer. Since 1.1.0 ``gen`` runs ``api-docs`` like any other entry; its pages document the model, so a served report changes the index and the agent page as well as adding its own. That is held to its own test, :func:`test_api_docs_gain_only_the_served_report`, which compares those two pages modulo - the report; the tests here pin what the vocabulary does to generated code.""" - return [e for e in list_generators() if e.name != "api-docs"] + the report; the tests here pin what the vocabulary does to generated code. The + ``requirements`` and ``agent-docs`` pages document the model the same way (the schema page + lists a report's view), and are held by ``tests/conformance/test_docs_page_conformance.py``.""" + return [e for e in list_generators() if e.layer != "docs"] def _load(variant: str): From ea137f0c8a8e240caa63a258ae3533919cc76842 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 22:18:17 -0500 Subject: [PATCH 08/35] feat(python): metaobjects agent-docs writes the shipped agent files itself (G-PY-2) The command no longer prints a redirect to the Node CLI. It copies one stack of the shipped agent files (.metaobjects/AGENTS.md and the metaobjects-* skills) out of a committed copy of agent-context-shipped/ inside the wheel, pins guide links to the release tag (a prerelease keeps main), and matches the TypeScript scaffolder's re-run rules: unchanged files and manifest are not rewritten, hand-edited files get .new, untouched orphans are pruned. Flags: --server, --client (default python), --out, --no-wire-root. The wheel carries the copy (no build hook; hatch_build.py removed). The gates lane and tests/unit/test_agent_docs.py fail when it drifts; scripts/sync-python-agent-context.sh refreshes it. --- CHANGELOG.md | 10 + docs/RELEASING.md | 11 +- docs/features/cli.md | 16 +- scripts/ci-local.sh | 5 + scripts/sync-python-agent-context.sh | 12 + server/python/README.md | 13 +- server/python/hatch_build.py | 15 - server/python/pyproject.toml | 10 +- .../metaobjects/agent_context/agent_docs.py | 153 + .../src/metaobjects/agent_context/scaffold.py | 92 +- .../src/metaobjects/agent_context/shipped.py | 123 + .../shipped/files/0080df7715486e4c.md | 85 + .../shipped/files/01fcc1b45dff7950.md | 245 + .../shipped/files/0440a95faf89e271.md | 225 + .../shipped/files/0b3cd53eedd718e2.md | 96 + .../shipped/files/0de6aba8a666dd9d.md | 115 + .../shipped/files/0ee567e8d039312d.md | 218 + .../shipped/files/10563ac017ebf8fb.md | 105 + .../shipped/files/123dcfb6c65640a0.md | 99 + .../shipped/files/15057721b9d06e77.md | 114 + .../shipped/files/15ee1bc0f67e8e01.md | 116 + .../shipped/files/1bba4aff747882dd.md | 106 + .../shipped/files/1c25799a074fff7d.md | 275 + .../shipped/files/1d4442064bb430d5.md | 106 + .../shipped/files/1e0fda1afdd26e1a.md | 74 + .../shipped/files/1e292839ec10ca12.md | 160 + .../shipped/files/1ed66f8d84192ee1.md | 88 + .../shipped/files/22c4d86c67650ab0.md | 168 + .../shipped/files/250eaeca5c4d1c38.md | 102 + .../shipped/files/2ded112f119f825b.md | 116 + .../shipped/files/2fe5f67ab529af0c.md | 67 + .../shipped/files/34d60341c7210314.md | 323 + .../shipped/files/378f755bb43b1e71.md | 73 + .../shipped/files/38afc85e1f586918.md | 112 + .../shipped/files/4244641a71a9c537.md | 69 + .../shipped/files/4426fbef79f236fb.md | 134 + .../shipped/files/46659a758d40373b.md | 39 + .../shipped/files/494853543fba1c5f.md | 264 + .../shipped/files/4f6d18160c694c41.md | 10 + .../shipped/files/51b5c54862c75382.md | 193 + .../shipped/files/58d380101a100501.md | 59 + .../shipped/files/5a2f3bbdcf835d47.md | 53 + .../shipped/files/5bf46c119eb2f22b.md | 114 + .../shipped/files/5d83d3b0cfa8b1d3.md | 106 + .../shipped/files/608f89f60afad4b9.md | 42 + .../shipped/files/60bc04713b62baba.md | 106 + .../shipped/files/61d8a218ffd3b20c.md | 116 + .../shipped/files/636d4309c12de5cb.md | 151 + .../shipped/files/651a126eaa501924.md | 154 + .../shipped/files/6935df5f6afbbf93.md | 116 + .../shipped/files/6afa98a9c7fd23f6.md | 65 + .../shipped/files/6b42cc8511e0eb7d.md | 115 + .../shipped/files/6e3f75ac9b8e8680.md | 335 + .../shipped/files/7ecd2af92a967b5e.md | 106 + .../shipped/files/80606ed514438d51.md | 342 + .../shipped/files/83fa1bfb70e0da93.md | 179 + .../shipped/files/84b5d02029893745.md | 156 + .../shipped/files/8a9c3f4a4119022a.md | 89 + .../shipped/files/8bc54bbb493091cd.md | 112 + .../shipped/files/8c2f34607e5f23fa.md | 170 + .../shipped/files/8cd1bca8a659b6ef.md | 82 + .../shipped/files/940c3d118c7ab1dc.md | 150 + .../shipped/files/969f739fa94d7a76.md | 500 ++ .../shipped/files/98558523cbdb9e82.md | 107 + .../shipped/files/9984405efdf695f3.md | 378 ++ .../shipped/files/9a4c5782dabd6c6e.md | 172 + .../shipped/files/9fbf06132414b6be.md | 262 + .../shipped/files/a1b81119468f84a9.md | 337 + .../shipped/files/a1e428980be88708.md | 112 + .../shipped/files/a3b90af6984e5058.md | 106 + .../shipped/files/a41cb586bdd98720.md | 42 + .../shipped/files/b28302f5febaea38.md | 102 + .../shipped/files/b55c2620ee7609d3.md | 140 + .../shipped/files/b8371541b1d36c6b.md | 174 + .../shipped/files/bc46fc3358130871.md | 104 + .../shipped/files/bfe25e4bd2cf097d.md | 62 + .../shipped/files/c1a4896ebda79dd9.md | 204 + .../shipped/files/c37f1e343d6e2832.md | 121 + .../shipped/files/c5b68292c9103dcc.md | 112 + .../shipped/files/c7994468651aa905.md | 165 + .../shipped/files/c99d78077736fd2d.md | 478 ++ .../shipped/files/ca05e997cc76ca60.md | 134 + .../shipped/files/ce8ecdef3b83fec0.md | 174 + .../shipped/files/d07ddba3c9a84355.md | 96 + .../shipped/files/d3eaa47c0bbd9332.md | 326 + .../shipped/files/d3f2f83fe9835f64.md | 215 + .../shipped/files/d6bd70c9bf36eb46.md | 77 + .../shipped/files/d8bac77e560c9b70.md | 116 + .../shipped/files/db66e0e785a6cf50.md | 331 + .../shipped/files/dd80d926c56ea1e3.md | 36 + .../shipped/files/e1054bf83aaaa224.md | 116 + .../shipped/files/e1f6478444c1e120.md | 388 ++ .../shipped/files/e413f6fcd012b1f3.md | 403 ++ .../shipped/files/e5c6430567eecae4.md | 225 + .../shipped/files/e626029a53526f92.md | 378 ++ .../shipped/files/e899275df4b48c66.md | 187 + .../shipped/files/e985f8151935157d.md | 66 + .../shipped/files/eaadb644cb1f809e.md | 218 + .../shipped/files/eab139844783c8e7.md | 93 + .../shipped/files/eb35a94b8d48d17d.md | 114 + .../shipped/files/ed5ffcac71d3cf75.md | 115 + .../shipped/files/f425eaf3566cf602.md | 96 + .../shipped/files/f4a1f275fa640c0f.md | 116 + .../shipped/files/f4c144c093105bb1.md | 115 + .../shipped/files/f53bebd852a41ec3.md | 168 + .../shipped/files/f745f2c1411ab2f0.md | 73 + .../shipped/files/f80806308b356cb6.md | 194 + .../shipped/files/fb3d3670ae387530.md | 60 + .../shipped/files/fd0c7ac49fc2b38d.md | 106 + .../shipped/files/fda1a58ac1585828.md | 22 + .../shipped/files/fe7f8817bfc35bb5.md | 120 + .../agent_context/shipped/manifest.json | 5533 +++++++++++++++++ server/python/src/metaobjects/cli.py | 44 +- .../python/tests/codegen/test_cli_surface.py | 32 - .../unit/test_agent_context_staleness.py | 4 +- server/python/tests/unit/test_agent_docs.py | 189 + 116 files changed, 21545 insertions(+), 88 deletions(-) create mode 100755 scripts/sync-python-agent-context.sh delete mode 100644 server/python/hatch_build.py create mode 100644 server/python/src/metaobjects/agent_context/agent_docs.py create mode 100644 server/python/src/metaobjects/agent_context/shipped.py create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/0080df7715486e4c.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/01fcc1b45dff7950.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/0440a95faf89e271.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/0b3cd53eedd718e2.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/0de6aba8a666dd9d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/0ee567e8d039312d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/10563ac017ebf8fb.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/123dcfb6c65640a0.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/15057721b9d06e77.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/15ee1bc0f67e8e01.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/1bba4aff747882dd.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/1c25799a074fff7d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/1d4442064bb430d5.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/1e0fda1afdd26e1a.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/1e292839ec10ca12.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/1ed66f8d84192ee1.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/22c4d86c67650ab0.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/250eaeca5c4d1c38.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/2ded112f119f825b.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/2fe5f67ab529af0c.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/34d60341c7210314.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/378f755bb43b1e71.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/38afc85e1f586918.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/4244641a71a9c537.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/4426fbef79f236fb.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/46659a758d40373b.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/494853543fba1c5f.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/4f6d18160c694c41.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/51b5c54862c75382.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/58d380101a100501.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/5a2f3bbdcf835d47.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/5bf46c119eb2f22b.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/5d83d3b0cfa8b1d3.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/608f89f60afad4b9.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/60bc04713b62baba.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/61d8a218ffd3b20c.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/636d4309c12de5cb.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/651a126eaa501924.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/6935df5f6afbbf93.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/6afa98a9c7fd23f6.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/6b42cc8511e0eb7d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/6e3f75ac9b8e8680.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/7ecd2af92a967b5e.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/80606ed514438d51.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/83fa1bfb70e0da93.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/84b5d02029893745.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/8a9c3f4a4119022a.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/8bc54bbb493091cd.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/8c2f34607e5f23fa.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/8cd1bca8a659b6ef.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/940c3d118c7ab1dc.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/969f739fa94d7a76.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/98558523cbdb9e82.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/9984405efdf695f3.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/9a4c5782dabd6c6e.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/9fbf06132414b6be.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/a1b81119468f84a9.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/a1e428980be88708.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/a3b90af6984e5058.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/a41cb586bdd98720.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/b28302f5febaea38.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/b55c2620ee7609d3.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/b8371541b1d36c6b.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/bc46fc3358130871.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/bfe25e4bd2cf097d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/c1a4896ebda79dd9.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/c37f1e343d6e2832.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/c5b68292c9103dcc.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/c7994468651aa905.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/c99d78077736fd2d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/ca05e997cc76ca60.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/ce8ecdef3b83fec0.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/d07ddba3c9a84355.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/d3eaa47c0bbd9332.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/d3f2f83fe9835f64.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/d6bd70c9bf36eb46.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/d8bac77e560c9b70.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/db66e0e785a6cf50.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/dd80d926c56ea1e3.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/e1054bf83aaaa224.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/e1f6478444c1e120.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/e413f6fcd012b1f3.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/e5c6430567eecae4.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/e626029a53526f92.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/e899275df4b48c66.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/e985f8151935157d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/eaadb644cb1f809e.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/eab139844783c8e7.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/eb35a94b8d48d17d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/ed5ffcac71d3cf75.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/f425eaf3566cf602.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/f4a1f275fa640c0f.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/f4c144c093105bb1.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/f53bebd852a41ec3.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/f745f2c1411ab2f0.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/f80806308b356cb6.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/fb3d3670ae387530.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/fd0c7ac49fc2b38d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/fda1a58ac1585828.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/fe7f8817bfc35bb5.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/manifest.json create mode 100644 server/python/tests/unit/test_agent_docs.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 440cceef2..2679f2f29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,16 @@ here.** ## [Unreleased] +- **Python: `metaobjects agent-docs` writes the shipped agent files itself, with no Node.** It used to + print a redirect to `npx meta agent-docs --server python` and exit 1. It now copies + `.metaobjects/AGENTS.md` and the `metaobjects-*` skills for the stack (`--server`, `--client`, + default `python`; `--out`; `--no-wire-root`) out of a copy of `agent-context-shipped/` that the + wheel carries, pins the guide links to the release tag (a prerelease keeps `main`), and matches + `npx meta agent-docs` byte for byte for the same stack. A re-run writes nothing for an unchanged + file, parks fresh text at `.new` beside a hand-edited one, and rewrites the sidecar manifest + only when it changed. `--skills-dir` and `--no-skills` remain Node-CLI flags. The `gates` lane + fails when the copy drifts (`scripts/sync-python-agent-context.sh` refreshes it). + - **The deprecated-reference finding ends its sentence before naming the replacement.** It read `…Team: the league no longer tracks teams Replaced by acme::app::Club.`; it now reads `…tracks teams. Replaced by acme::app::Club.` A reason that already ends in `.`, `!` or `?` is left as written. - **C#: `dotnet meta verify` runs the three model authoring lints.** The overlay lint diff --git a/docs/RELEASING.md b/docs/RELEASING.md index ee7a48897..a318852e8 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -881,9 +881,10 @@ Project `metaobjects` → **Settings → Publishing → Add a new GitHub publish 2. **Bump the version in `pyproject.toml`** (`[project].version`). 3. **The wheel is pure-Python/universal** (`py3-none-any`) — one wheel serves every platform. - (No agent-context content is vendored into the wheel anymore — scaffolding moved to the - Node `meta agent-docs` CLI, so `hatch_build.py` is a no-op. Don't re-add a - `force-include` of `../../agent-context`.) + (The wheel carries the shipped agent files as a committed copy of `agent-context-shipped/` + under `src/metaobjects/agent_context/shipped/`, so `metaobjects agent-docs` needs no Node. + Refresh it with `scripts/sync-python-agent-context.sh`; the `gates` lane and a Python test + fail when it is stale. There is no build hook and no `force-include` of `../../agent-context`.) ## Procedure @@ -1011,8 +1012,8 @@ shipped agent-context tree (and the docs ref its links are pinned to) into the m TypeScript check compares that hash: a context whose content differs from what this CLI ships nudges even at an equal version, and one whose content is identical is silent at any version. A manifest written before 1.1.0 has no hash and falls back to the version rule above. The C#, -Python and JVM checks keep the version rule, because they ship no agent-context content to hash: -`meta agent-docs` (npm) is the one scaffolder. A context stamped at that port's own version is +Python and JVM checks keep the version rule: each stamps its own release into the manifest it +writes, and no port but TypeScript hashes the tree. A context stamped at that port's own version is the context that release documents, so the version rule is the right answer there. ## Public-repo hygiene diff --git a/docs/features/cli.md b/docs/features/cli.md index 5e08e4201..42022ad99 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -26,7 +26,7 @@ command surface splits in two: | Capability | Tool | Invocation | Notes | |---|---|---|---| | 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 | +| **Agent-context scaffold** (`agent-docs`) | **Node `meta`** | `npx meta agent-docs --server ` | **any backend** — single assembler (ADR-0033); the Python CLI writes the same files itself (`metaobjects agent-docs`, no Node); the C# and Java/Kotlin CLIs still 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 | @@ -925,10 +925,16 @@ and Java with Kotlin, each with no client, React, React with TanStack or Angular committed at `agent-context-shipped/` (a manifest and each distinct file once), and a port's package embeds it so its command can copy one stack out with no Node on the path. `agent-context-shipped/README.md` is the contract that command follows, and the sdk's -`shipped.test.ts` fails when the tree is stale. Until each port's command lands, the stubs -below still redirect to the Node CLI. - -The C#, Java/Kotlin, and Python CLIs keep a **non-executing `agent-docs` pointer +`shipped.test.ts` fails when the tree is stale. **Python's command has landed**: +`metaobjects agent-docs [--server ]... [--client ]... [--out ] [--no-wire-root]` +copies one stack out of a committed copy of the tree inside the wheel (refreshed by +`scripts/sync-python-agent-context.sh`, gated for drift), pins the guide links to the release +tag, and keeps the Node CLI's re-run rules: an identical file is not rewritten, a hand-edited +file gets the fresh text beside it as `.new`, and the `.metaobjects/.agent-context.json` +manifest is rewritten only when its text changed. `--skills-dir` and `--no-skills` stay with +the Node CLI. Until the other ports' commands land, their stubs below still redirect. + +The C# and Java/Kotlin CLIs keep a **non-executing `agent-docs` pointer stub** that prints `agent-context scaffolding moved to the meta CLI — run: npx meta agent-docs --server ` to stderr and exits non-zero. The **live staleness check** in `gen`/`verify` stays per-port (it only *reads* the scaffold to nudge when it drifts); diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 055675a82..44876affc 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -998,6 +998,10 @@ gate_doc_template_drift() { server/typescript/packages/codegen-ts/templates \ server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts } +# The Python wheel's copy of the shipped agent files must equal the repo-root tree. +gate_python_agent_context_drift() { + diff -r -x README.md agent-context-shipped server/python/src/metaobjects/agent_context/shipped +} gate_embedded_library_drift() { bun run scripts/generate-embedded-library.ts \ && git diff --exit-code -- server/typescript/packages/metadata/src/library/embedded-library.generated.ts @@ -1345,6 +1349,7 @@ run_gates_offline() { if want gates; then step "positioning claims" gate_positioning_claims; fi if want gates; then step "hosted assess prompt builds" gate_assess_prompt; fi if want gates; then step "migration guides vs registry" gate_migration_guides; fi + if want gates; then step "python agent-context copy" gate_python_agent_context_drift; fi } # Every gate below runs bun over workspace TypeScript, and on a FRESH CI checkout there is # no node_modules — so a bare `@metaobjectsdev/*` specifier either fails to resolve (what diff --git a/scripts/sync-python-agent-context.sh b/scripts/sync-python-agent-context.sh new file mode 100755 index 000000000..0ce664430 --- /dev/null +++ b/scripts/sync-python-agent-context.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Refresh the Python package's committed copy of the shipped agent files from the repo-root +# tree (agent-context-shipped/, built by TypeScript). The wheel carries the copy, so +# `metaobjects agent-docs` needs no Node. Run after rebuilding the tree; the `gates` lane and +# a Python test fail when the copy is stale. +set -euo pipefail +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +src="$root/agent-context-shipped" +dst="$root/server/python/src/metaobjects/agent_context/shipped" +mkdir -p "$dst" +# --delete drops stored files a rebuild renamed away; the README stays at the root only. +rsync -a --delete --exclude README.md "$src/" "$dst/" diff --git a/server/python/README.md b/server/python/README.md index 1fdb287fe..39b30bca0 100644 --- a/server/python/README.md +++ b/server/python/README.md @@ -70,16 +70,17 @@ wins. See [the upgrade guide](../../docs/features/migrations/upgrading-1.0-to-1. ## AI assistant context -To scaffold MetaObjects context files (`.metaobjects/AGENTS.md` and the `metaobjects-*` skills) -into your project so your AI assistant understands how to author metadata and run codegen, use -the Node `meta` CLI. The skills go to `.claude/skills/` unless you pass `--skills-dir` (for -example `.agents/skills` for assistants that read that directory): +To write MetaObjects context files (`.metaobjects/AGENTS.md` and the `metaobjects-*` skills) +into your project so your AI assistant understands how to author metadata and run codegen: ```bash -npx meta agent-docs --server python +metaobjects agent-docs # the python stack +metaobjects agent-docs --client react # add --server/--client for the rest of your stack ``` -(Running `metaobjects agent-docs` in the Python CLI prints this redirect and exits.) +The files ship inside the wheel, so no Node is needed. The skills go to `.claude/skills/`; a +different skills directory (`--skills-dir`) is the Node CLI's (`npx meta agent-docs`). A re-run +rewrites only what changed, and parks fresh text at `.new` beside a file you edited. ## Links diff --git a/server/python/hatch_build.py b/server/python/hatch_build.py deleted file mode 100644 index e9b1478fc..000000000 --- a/server/python/hatch_build.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Build hook — no-op. - -The ``agent-context/`` content tree vendoring into ``_content/`` has been removed: -agent-context scaffolding is now owned by the Node ``meta agent-docs`` CLI. This -file is kept as a no-op to avoid breaking any build tooling that references it. -""" - -from __future__ import annotations - -from hatchling.builders.hooks.plugin.interface import BuildHookInterface - - -class CustomBuildHook(BuildHookInterface): - def initialize(self, version: str, build_data: dict) -> None: - pass # Nothing to vendor — scaffolding moved to the Node meta CLI. diff --git a/server/python/pyproject.toml b/server/python/pyproject.toml index cdc34b93f..ccf855c06 100644 --- a/server/python/pyproject.toml +++ b/server/python/pyproject.toml @@ -89,11 +89,11 @@ build-backend = "hatchling.build" packages = ["src/metaobjects"] exclude = ["**/KNOWN_GAPS.md"] -# No agent-context ships in this package. `metaobjects agent-docs` redirects to the Node -# scaffolder (`npx meta agent-docs --server python`), which owns that content, so the wheel -# and sdist carry none of it and an agent-context/ edit never makes PyPI publish. -# hatch_build.py is a deliberate no-op, kept only so tooling that names the hook does not break. -[tool.hatch.build.hooks.custom] +# The shipped agent files (`metaobjects agent-docs`) are a COMMITTED copy of the repo-root +# agent-context-shipped/ tree under src/metaobjects/agent_context/shipped/, so the default +# package inclusion above puts them in the wheel and sdist and the command needs no Node. +# scripts/sync-python-agent-context.sh refreshes the copy; a gate and +# tests/unit/test_agent_docs.py fail when it drifts. No build hook is involved. [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/server/python/src/metaobjects/agent_context/agent_docs.py b/server/python/src/metaobjects/agent_context/agent_docs.py new file mode 100644 index 000000000..8e32dc747 --- /dev/null +++ b/server/python/src/metaobjects/agent_context/agent_docs.py @@ -0,0 +1,153 @@ +"""``metaobjects agent-docs``: write the shipped agent files into a project, with no Node. + +Mirrors ``meta agent-docs`` for the flags a Python project uses: the stack comes from +``--server``/``--client``, else the stack the last run recorded in the sidecar manifest, +else ``python``. A re-run writes nothing for a file that is already right, parks fresh +text at ``.new`` beside a hand-edited file, deletes only orphans it wrote and nobody +touched, and rewrites the manifest only when its text changed. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from .scaffold import ( + AGENT_CONTEXT_MANIFEST_PATH, + Manifest, + installed_metaobjects_version, + plan_scaffold, +) +from .shipped import ( + ShippedContextError, + canonical_stack, + docs_ref_for_version, + load_shipped, + materialize, +) + +#: Server language of a project that names none and has no earlier manifest. +DEFAULT_SERVER = "python" +ROOT_IMPORT_LINE = "@.metaobjects/AGENTS.md" +ROOT_IMPORT_BLOCK = ( + "Read `.metaobjects/AGENTS.md` before changing this project's metadata, generated code " + f"or schema.\n{ROOT_IMPORT_LINE}\n" +) +_NEW_ROOT_BODY = f"# Project memory\n\n{ROOT_IMPORT_BLOCK}" + + +def _read(root: Path, rel: str) -> str | None: + p = root / rel + if not p.is_file(): + return None + with p.open(encoding="utf-8", newline="") as fh: # newline="": compare the bytes on disk + return fh.read() + + +def _write(root: Path, rel: str, text: str) -> None: + p = root / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_bytes(text.encode("utf-8")) + + +def _prior_manifest(root: Path) -> Manifest | None: + text = _read(root, AGENT_CONTEXT_MANIFEST_PATH) + if text is None: + return None + try: + data = json.loads(text) + except ValueError: + return None + return Manifest.from_json(data) if isinstance(data, dict) else None + + +def _wire_root(root: Path, created: list[str], notes: list[str], refresh: bool) -> None: + claude, agents = root / "CLAUDE.md", root / "AGENTS.md" + if not claude.exists() and not agents.exists(): + for name in ("AGENTS.md", "CLAUDE.md"): + _write(root, name, _NEW_ROOT_BODY) + created.append(f"{name} (created with MetaObjects @import)") + return + if claude.exists() and not agents.exists(): + if not refresh: + _write(root, "AGENTS.md", _NEW_ROOT_BODY) + created.append("AGENTS.md (created with MetaObjects @import)") + else: + notes.append( + "no root AGENTS.md: assistants other than Claude Code will not load " + ".metaobjects/AGENTS.md; add a root AGENTS.md containing @.metaobjects/AGENTS.md" + ) + for name in ("CLAUDE.md", "AGENTS.md"): + if not (root / name).exists(): + continue + body = _read(root, name) or "" + if ROOT_IMPORT_LINE in body: + continue + _write(root, name, body.rstrip("\n") + "\n\n" + ROOT_IMPORT_BLOCK) + notes.append(f"wired {ROOT_IMPORT_LINE} into {name} so the MetaObjects context loads") + + +def run_agent_docs( + *, + servers: list[str], + clients: list[str], + out: Path, + wire_root: bool = True, + version: str | None = None, +) -> tuple[list[str], list[str]]: + """Write the stack's files under ``out``; return ``(created paths, notes)``. + + Raises :class:`ShippedContextError` for an unknown stack value or stack. + """ + version = installed_metaobjects_version() if version is None else version + servers, clients = canonical_stack(servers, clients) + prior = _prior_manifest(out) + if not servers and not clients: + # No flags: reuse the recorded stack, so a refresh keeps it without repeating them. + if prior is not None and (prior.servers or prior.clients): + servers, clients = list(prior.servers), list(prior.clients) + else: + servers = [DEFAULT_SERVER] + tree = load_shipped() + assembled = materialize(tree, servers, clients, docs_ref_for_version(version)) + decision = plan_scaffold( + assembled=assembled, + prior=prior, + read_current=lambda p: _read(out, p), + generated_by=version, + servers=servers, + clients=clients, + ) + created: list[str] = [] + notes: list[str] = [] + for path, text in decision.writes: + _write(out, path, text) + created.append(path) + for path, text in decision.conflicts: + _write(out, path + ".new", text) + created.append(path + ".new") + notes.append(f"{path} appears hand-edited; refreshed version written to {path}.new") + assert decision.manifest is not None + manifest_text = json.dumps(decision.manifest.to_json(), indent=2, ensure_ascii=False) + "\n" + if _read(out, AGENT_CONTEXT_MANIFEST_PATH) != manifest_text: + _write(out, AGENT_CONTEXT_MANIFEST_PATH, manifest_text) + created.append(AGENT_CONTEXT_MANIFEST_PATH) + for orphan in decision.prunes: + (out / orphan).unlink() + # Drop a skill directory this just emptied, never the skills directory itself. + parent = (out / orphan).parent + skills = out / str(tree.manifest["skillsDir"]) + while parent != skills and parent != out and parent.is_dir() and not any(parent.iterdir()): + parent.rmdir() + parent = parent.parent + for orphan in decision.removed: + notes.append( + f"{orphan} is no longer part of this stack but appears hand-edited, so it was " + "kept; delete it yourself once you have salvaged anything you want from it." + ) + if wire_root: + _wire_root(out, created, notes, refresh=prior is not None) + return created, notes + + +__all__ = ["DEFAULT_SERVER", "ShippedContextError", "run_agent_docs"] diff --git a/server/python/src/metaobjects/agent_context/scaffold.py b/server/python/src/metaobjects/agent_context/scaffold.py index 04ae849d4..f57cb5deb 100644 --- a/server/python/src/metaobjects/agent_context/scaffold.py +++ b/server/python/src/metaobjects/agent_context/scaffold.py @@ -1,23 +1,30 @@ -"""Sidecar manifest + staleness nudge for the agent-context scaffolder. - -The assembly path (assemble / plan_scaffold / ScaffoldDecision) has been removed — -that work is now owned by the Node ``meta agent-docs`` CLI. This module retains -only the staleness-nudge machinery (``agent_context_staleness``, ``Manifest``, -``AGENT_CONTEXT_MANIFEST_PATH``, ``installed_metaobjects_version``) which is used -by ``gen``/``verify`` to detect when the scaffolded agent context predates the -installed MetaObjects version. +"""Sidecar manifest, write plan and staleness nudge for the agent-context scaffolder. + +The files themselves are the shipped tree embedded in this package (see ``shipped.py``); +this module owns what is written around them: the sidecar manifest that records what was +written (``Manifest``), the decision of what a re-run may overwrite (``plan_scaffold``, +the same predicate as the TypeScript scaffolder), and the staleness nudge +(``agent_context_staleness``) that ``gen``/``verify`` use to detect an agent context that +predates the installed MetaObjects version. """ from __future__ import annotations +import hashlib import re -from dataclasses import dataclass +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field from importlib.metadata import PackageNotFoundError, version as _pkg_version #: Consumer-relative path of the sidecar manifest that tracks scaffolded files. AGENT_CONTEXT_MANIFEST_PATH = ".metaobjects/.agent-context.json" +def hash_contents(text: str) -> str: + """sha256 hex of a file's text, as the TypeScript scaffolder records it.""" + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + def installed_metaobjects_version() -> str: """The installed ``metaobjects`` distribution version, or ``"0.0.0"`` if absent. @@ -77,6 +84,73 @@ def from_json(data: dict[str, object]) -> "Manifest": ) +@dataclass +class ScaffoldDecision: + """What a (re-)scaffold does, decided before anything is written.""" + + #: ``(path, contents)`` to write at their own path: new, or unmodified since the last scaffold. + writes: list[tuple[str, str]] = field(default_factory=list) + #: ``(path, contents)`` of hand-edited files: the fresh text goes to ``.new``. + conflicts: list[tuple[str, str]] = field(default_factory=list) + #: the manifest to persist after writing. + manifest: Manifest | None = None + #: orphans this tool wrote and nobody touched: safe to delete. + prunes: list[str] = field(default_factory=list) + #: orphans that are hand-edited: reported, never deleted. + removed: list[str] = field(default_factory=list) + + +def plan_scaffold( + *, + assembled: Mapping[str, str], + prior: Manifest | None, + read_current: Callable[[str], str | None], + generated_by: str, + servers: list[str], + clients: list[str], +) -> ScaffoldDecision: + """Decide what to write. Pure: disk access goes through ``read_current``. + + A file is safe to overwrite iff it is absent, or its on-disk hash still equals the + hash the prior manifest recorded (nobody hand-edited it). The manifest records what + was WRITTEN, never merely produced: a declined path keeps its prior hash, so reverting + the hand edit lets the next refresh see an unmodified file. + """ + decision = ScaffoldDecision() + files: dict[str, str] = {} + for path, contents in assembled.items(): + current = read_current(path) + if current is None: + files[path] = hash_contents(contents) + decision.writes.append((path, contents)) + continue + if current == contents: # already these bytes: nothing to write, true hash recorded + files[path] = hash_contents(contents) + continue + prior_hash = prior.files.get(path) if prior is not None else None + if prior_hash is not None and hash_contents(current) == prior_hash: + files[path] = hash_contents(contents) + decision.writes.append((path, contents)) + else: + if prior_hash is not None: + files[path] = prior_hash + decision.conflicts.append((path, contents)) + for path in prior.files if prior is not None else {}: + if path in assembled: + continue + current = read_current(path) + if current is None: + continue + if prior is not None and hash_contents(current) == prior.files[path]: + decision.prunes.append(path) + else: + decision.removed.append(path) + decision.manifest = Manifest( + version=1, servers=servers, clients=clients, files=files, generated_by=generated_by + ) + return decision + + # The sentinel a port stamps when it cannot resolve its own installed version. _UNRESOLVED_VERSION = "0.0.0" diff --git a/server/python/src/metaobjects/agent_context/shipped.py b/server/python/src/metaobjects/agent_context/shipped.py new file mode 100644 index 000000000..36e88e922 --- /dev/null +++ b/server/python/src/metaobjects/agent_context/shipped.py @@ -0,0 +1,123 @@ +"""The shipped agent files, copied out of the tree embedded in this package. + +``shipped/`` is a committed copy of the repo-root ``agent-context-shipped/`` tree, which +TypeScript builds (``agent-context-shipped/README.md`` is the contract). Everything here is +the three steps that README gives a port: find the stack, pin the guide links to the +release tag, write each file at its path. No Node is involved. +""" + +from __future__ import annotations + +import json +import re +from collections.abc import Iterable +from dataclasses import dataclass +from importlib import resources +from importlib.resources.abc import Traversable + +#: The manifest shape this port understands. +SHIPPED_SCHEMA = 1 +#: Canonical order of server languages and clients inside a stack id. +SERVER_LANGS = ("typescript", "java", "kotlin", "csharp", "python", "rust") +CLIENT_FRAMEWORKS = ("react", "tanstack", "angular") +#: The ref a prerelease or an unresolvable version keeps. +DOCS_DEFAULT_REF = "main" + +_SERVER_ALIASES = { + "node": "typescript", "nodejs": "typescript", "ts": "typescript", + "c#": "csharp", "dotnet": "csharp", "py": "python", "rs": "rust", +} +_CLIENT_ALIASES = {"reactjs": "react", "react-query": "tanstack"} +_RELEASE_VERSION = re.compile(r"^\d+\.\d+\.\d+$") + + +class ShippedContextError(Exception): + """The shipped tree cannot serve the request (unknown stack, unknown schema, bad flag).""" + + +@dataclass(frozen=True) +class ShippedTree: + manifest: dict[str, object] + root: Traversable + + def stack_entry(self, stack_id: str) -> dict[str, object] | None: + for entry in self.manifest["stacks"]: # type: ignore[attr-defined] + if entry["id"] == stack_id: + return entry # type: ignore[no-any-return] + return None + + def stack_ids(self) -> list[str]: + return [str(e["id"]) for e in self.manifest["stacks"]] # type: ignore[attr-defined] + + +def load_shipped() -> ShippedTree: + """Read the embedded tree's manifest; refuse a schema this port does not know.""" + root = resources.files("metaobjects.agent_context") / "shipped" + manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8")) + if manifest.get("schema") != SHIPPED_SCHEMA: + raise ShippedContextError( + f"agent-context: unknown shipped manifest schema {manifest.get('schema')!r} " + f"(this metaobjects understands {SHIPPED_SCHEMA}); upgrade metaobjects" + ) + return ShippedTree(manifest=manifest, root=root) + + +def docs_ref_for_version(version: str) -> str: + """``v`` for a release, ``main`` for a prerelease, ``0.0.0`` or non-version text.""" + v = version.strip() + return f"v{v}" if _RELEASE_VERSION.match(v) and v != "0.0.0" else DOCS_DEFAULT_REF + + +def _canonical(raw: str, valid: Iterable[str], aliases: dict[str, str]) -> str | None: + v = raw.strip().lower() + return v if v in tuple(valid) else aliases.get(v) + + +def canonical_stack(servers: list[str], clients: list[str]) -> tuple[list[str], list[str]]: + """Canonicalize ``--server``/``--client`` values; refuse one that names nothing known.""" + bad: list[str] = [] + out_servers: list[str] = [] + out_clients: list[str] = [] + for s in servers: + c = _canonical(s, SERVER_LANGS, _SERVER_ALIASES) + if c is None: + bad.append(f"--server {s} (known: {', '.join(SERVER_LANGS)})") + else: + out_servers.append(c) + for s in clients: + c = _canonical(s, CLIENT_FRAMEWORKS, _CLIENT_ALIASES) + if c is None: + bad.append(f"--client {s} (known: {', '.join(CLIENT_FRAMEWORKS)})") + else: + out_clients.append(c) + if bad: + raise ShippedContextError("unknown stack value: " + "; ".join(bad)) + return out_servers, out_clients + + +def shipped_stack_id(servers: list[str], clients: list[str]) -> str: + """Server languages then clients, each in canonical order, joined by ``-``.""" + return "-".join( + [s for s in SERVER_LANGS if s in servers] + [c for c in CLIENT_FRAMEWORKS if c in clients] + ) + + +def materialize( + tree: ShippedTree, servers: list[str], clients: list[str], docs_ref: str +) -> dict[str, str]: + """The stack's files, ``{path: contents}``, with every guide link pinned to ``docs_ref``.""" + stack_id = shipped_stack_id(servers, clients) + entry = tree.stack_entry(stack_id) + if entry is None: + raise ShippedContextError( + f'no shipped agent files for the stack "{stack_id}" ' + f"(shipped: {', '.join(tree.stack_ids())})" + ) + prefix = str(tree.manifest["docsLinkPrefix"]) + src = f"{prefix}{tree.manifest['docsRef']}/" + dst = f"{prefix}{docs_ref}/" + out: dict[str, str] = {} + for f in entry["files"]: # type: ignore[attr-defined] + text = (tree.root / "files" / f["file"]).read_text(encoding="utf-8") + out[f["path"]] = text.replace(src, dst) + return out diff --git a/server/python/src/metaobjects/agent_context/shipped/files/0080df7715486e4c.md b/server/python/src/metaobjects/agent_context/shipped/files/0080df7715486e4c.md new file mode 100644 index 000000000..45896849c --- /dev/null +++ b/server/python/src/metaobjects/agent_context/shipped/files/0080df7715486e4c.md @@ -0,0 +1,85 @@ +# Your own vocabulary in C# — a provider + +> Part of the `metaobjects-authoring` skill, "Your own vocabulary". Read it when the project +> needs a subtype or an attribute the core does not ship, and its C# tools load the metadata. + +A provider is a public class implementing `IMetaDataTypeProvider`, with a public parameterless +constructor: an `Id`, the provider ids it depends on, and a `RegisterTypes(registry)` body that +calls `Register` (a new subtype) and `Extend` (attributes on an existing one). Put it in its +own class library that references the `MetaObjects` package at the version your `dotnet meta` +tool runs. This one registers `layout.picker` and adds `@searchable` and `@valueLabels` to +`field.string`: + +```csharp +// vocabulary/AcmeVocabularyProvider.cs (vocabulary/Acme.Vocabulary.csproj: net8.0 class +// library with ) +using MetaObjects; +using MetaObjects.Meta; +using MetaObjects.Shared; + +namespace Acme.Vocabulary; + +public sealed class AcmeVocabularyProvider : IMetaDataTypeProvider +{ + public string Id => "acme-vocabulary"; + public IReadOnlyList Dependencies => ["metaobjects-core-types"]; + + public void RegisterTypes(TypeRegistry registry) + { + // A new subtype, with its own attribute (an own attribute may be required). + registry.Register(new TypeDefinition( + typeId: new TypeId("layout", "picker"), + description: "A picker over the owning object.", + childRules: [new ChildRule(BaseTypes.TYPE_ATTR, Structural.CHILD_RULE_WILDCARD, Structural.CHILD_RULE_WILDCARD)], + factory: (typeId, name) => new MetaLayout(typeId, name), + attributes: [new AttrSchema("displayField", "string", Required: false)])); + + // Attributes on a type another provider owns: always optional. + registry.Extend("field", "string", attributes: + [ + new AttrSchema("searchable", "boolean", Required: false), + new AttrSchema("valueLabels", "string", Required: false, IsArray: true), + ]); + } +} +``` + +Wire it once, in `.metaobjects/config.json`. `assembly` is the BUILT dll, relative to the +directory holding `.metaobjects/`; `type` is the provider's full type name: + +```json +{ + "schema_version": 1, + "csharp": { + "providers": [ + { "assembly": "vocabulary/bin/Debug/net8.0/Acme.Vocabulary.dll", "type": "Acme.Vocabulary.AcmeVocabularyProvider" } + ] + } +} +``` + +Build the vocabulary first (`dotnet build vocabulary`); a missing dll is refused with the path +and that instruction. Then `dotnet meta gen` and `verify --codegen` (through the project's +`codegen/` runner), `dotnet meta verify` (templates, requirements, field lint) and +`dotnet meta fmt` all compose the core providers plus this one. The `codegen/` project may +also reference the vocabulary project directly; the already-loaded assembly is reused. + +An application host that loads the model itself composes the registry in code: + +```csharp +var registry = Provider.ComposeRegistry([.. CoreTypes.LibraryProviders, new AcmeVocabularyProvider()]); +var load = MetaDataLoader.FromDirectory("metaobjects", registry, strict: true); +``` + +The metadata uses it like core vocabulary: + + +```json +{ "field.string": { "name": "name", "@searchable": true } } +{ "layout.picker": { "name": "contactPicker", "@displayField": "name" } } +``` + +Without the provider the same file fails `dotnet meta verify` with `ERR_UNKNOWN_SUBTYPE` on +`layout.picker` and `ERR_UNKNOWN_ATTR` on `@searchable`. If another port's tools load this +metadata too, that port needs its own copy of the provider (same id, same vocabulary). Each port's `verify` loads strict, so a clean run there proves that port's copy is complete. +Full contract: `docs/features/extending-with-providers.md`. diff --git a/server/python/src/metaobjects/agent_context/shipped/files/01fcc1b45dff7950.md b/server/python/src/metaobjects/agent_context/shipped/files/01fcc1b45dff7950.md new file mode 100644 index 000000000..ca32e33fe --- /dev/null +++ b/server/python/src/metaobjects/agent_context/shipped/files/01fcc1b45dff7950.md @@ -0,0 +1,245 @@ +# TypeScript parser-on-receipt + +For every RESPONDING `template.prompt` in your metadata — one declaring +`@responseRef` — the `outputParser()` generator (from +`@metaobjectsdev/codegen-ts/generators`) emits a **typed parser** that validates a +model's reply against that shape. ADR-0052: the tier binds `@responseRef`, never +`@payloadRef` (which types the request the prompt renders outbound), and a +`template.output` gets no parser at all. This is the receive side; codegen emits **no** +provider/LLM-call layer — you compose the call yourself. + +## Contents +- Wire the generator +- What it emits +- The response-format prompt fragment (FR-010) +- The three-step consumer pattern +- Recommended LLM caller (bring-your-own) +- Drift gate +- See which fields a template consumes + +## Wire the generator + +```ts +// metaobjects.config.ts +import { defineConfig } from "@metaobjectsdev/cli"; +// `meta init` wires nothing (ADR-0034 Amendment 2). Each generator is imported from the +// package to run it as shipped. The parser's reply type is the @responseRef value +// object's own interface, which `entity` emits, so `entity` has to be in the run. +// (On a 1.0.x install the first three have no package export: `meta eject entity queries +// barrel` and import them from ./codegen/generators/ instead.) +// +// Any of these can be OWNED instead: `meta eject prompt-render output-parser` copies them +// into ./codegen/generators/ and prints the local import to swap in. Either way the +// render and parse ENGINES they call stay in the package. +import { + entityFile, queriesFile, barrel, promptRender, outputParser, +} from "@metaobjectsdev/codegen-ts/generators"; + +export default defineConfig({ + outDir: "src/generated", + generators: [ + entityFile(), queriesFile(), barrel(), + promptRender(), // render() per template.prompt (the send side) + outputParser(), // parse*/safeParse* per responding template.prompt (the receive side) + ], +}); +``` + +`outputParser({ outDir: "src/generated/outputs", target: "default" })` are the +options. + +## What it emits + +Per responding `template.prompt` (say named `NpcReview`, `@responseRef: +"NpcResponse"`), `meta gen` writes `NpcReview.response.ts` with a Zod schema + a dual +API, named after the TEMPLATE. The strict tier is JSON-only — an `@responseFormat: xml` +reply gets the tolerant `extract` and no `parse`/`safeParse`: + +```ts +import { z } from "zod"; +import type { NpcResponse } from "./NpcResponse.js"; // the value object's own interface (entityFile) + +const NpcReviewSchema = z.object({ + name: z.string(), + level: z.number().int(), + role: z.enum(["tank", "healer", "dps"]), // field.enum → its declared members + notes: z.string().optional(), // not @required → .optional() +}); + +export type NpcReviewValidationError = z.ZodError; + +/** Throws ZodError on bad input. */ +export function parseNpcReview(text: string): NpcResponse { /* ... */ } + +/** Result-style; never throws. */ +export function safeParseNpcReview(text: string): + | { success: true; data: NpcResponse } + | { success: false; error: NpcReviewValidationError } { /* ... */ } +``` + +The dual API mirrors Zod's idiomatic shape: `parse*` throws a `ZodError`, +`safeParse*` returns a discriminated union. Both return the `@responseRef` value +object's OWN interface — the one `entityFile()` declares in `NpcResponse.ts` (ADR-0056) +— so the parser declares no type of its own. `parse*` / `safeParse*` expect the reply to +BE the JSON document; a raw chat reply — `Sure!` followed by a fenced JSON block — fails +them with `invalid JSON: Unexpected token 'S'…`. For a raw reply the same file exports the +tolerant tier: + +```ts +import { extractLenientNpcReviewWithLoader } from "./generated/NpcReview.response.js"; +import { MetaDataLoader } from "@metaobjectsdev/metadata"; +import { orThrow } from "@metaobjectsdev/render"; + +const { root } = await MetaDataLoader.fromDirectory("./metaobjects"); // load once at startup +const result = extractLenientNpcReviewWithLoader(root, reply); // strips prose + fences +result.report; // per field: recovered / defaulted / lost / malformed +const npc = orThrow(result); // opt-in: throws ExtractError if a @required field was lost +``` + +It reads the live metadata, so it takes a loaded `MetaRoot`; there is no text-only +`extractLenientNpcReview(text)`. A bad reply never throws — it is classified in `report` +and `data` holds what was recovered (every field of the `Extracted` mirror is +nullable). It throws only when `root` does not declare the response value object, which is +a setup error. + +Wiring the `extractor` generator as well adds `.extractor.ts` with two more entry +points over the same call: `extract(root, text)` returns the strict response type and +throws when a `@required` field is lost or malformed, and `extractLenient(root, text)` +re-exports the tolerant call above. `extractLenientWithLoader` itself is exported +only from `.response.ts`. + +Field-type → Zod mapping: `field.string` → `z.string()`; `field.int`/`long`/`currency` +→ `z.number().int()`; `field.double`/`float` → `z.number()`; `field.boolean` → +`z.boolean()`; `field.enum` → `z.enum([...])` over its declared `@values`; +`field.uuid` → `z.string().uuid()`; `field.decimal` and the temporal subtypes → +`z.string()` (their JSON wire form); `field.object` (with `@objectRef`) → a nested +`z.object({...})`; `isArray: true` → wrapped in `z.array(...)`; a field that is not +`@required` → `.optional()`. Only a subtype outside that set, or a self-referencing +`@objectRef`, falls through to `z.unknown()`. + +## The response-format prompt fragment (FR-010) + +For every responding `template.prompt`, the `outputPrompt()` generator (same import +path, `@metaobjectsdev/codegen-ts/generators`) emits a +`.responseFormat.ts` exporting `renderFormat(overrides?)` — +backed by the render engine's `renderOutputFormat()`. This is the "produce your +answer like this" fragment you splice into the prompt text so the model returns the +shape the parser above expects: + +```ts +// metaobjects.config.ts — the same entity trio as above, plus outputPrompt +import { + entityFile, queriesFile, barrel, promptRender, outputParser, outputPrompt, +} from "@metaobjectsdev/codegen-ts/generators"; + +export default defineConfig({ + outDir: "src/generated", + generators: [ + entityFile(), queriesFile(), barrel(), + promptRender(), outputParser(), outputPrompt(), + ], +}); +``` + +`@promptStyle` on the `template.prompt` (`guide` default / `inline` / `exampleOnly`) +controls the fragment's presentation: `guide` is a prose field list + example +skeleton, `inline` is one skeleton with inline placeholders/enum choices, +`exampleOnly` is just the filled skeleton. Guidance is never emitted as comments — +models ignore them. Skipped for `template.output` and for any prompt whose +`@responseRef` doesn't resolve — the same skip contract as `outputParser()`. There is NO +format gate: the old `@format ∈ {json,xml}` test read the syntax of the outbound BODY to +decide whether to describe the REPLY. `@responseFormat` selects which syntax the fragment +teaches. The baked spec's root name matches the response shape, so the fragment and the +parser's `extract()` agree on the same root. + +## The three-step consumer pattern + +Render the prompt → call your LLM client (provider-agnostic; nothing is generated +here) → parse the response with the generated parser: + +```ts +// Node-only subpath: the package ROOT stays browser-safe, so the filesystem provider +// lives on `@metaobjectsdev/render/providers`. `lobby/welcome` → ./prompts/lobby/welcome.mustache. +import { FilesystemProvider } from "@metaobjectsdev/render/providers"; +import { renderNpcReview } from "./generated/prompts"; +import { parseNpcReview, safeParseNpcReview } from "./generated/NpcReview.response"; + +const textProvider = new FilesystemProvider("./prompts"); +const promptText = renderNpcReview(payload, textProvider); +const llmResponse = await myLlmProvider.call(promptText); // YOUR code — no generated provider + +// Throwing path: +const npc = parseNpcReview(llmResponse); + +// Result-style: +const r = safeParseNpcReview(llmResponse); +if (!r.success) log.warn("malformed LLM payload", r.error); +else handle(r.data); +``` + +## Recommended LLM caller (bring-your-own) + +MetaObjects generates **no** provider/LLM-call layer and never will — the call is a +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. 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 "./generated/llm-call"; // where trace-helper wrote it + +export const llm: LlmClient = { + async complete({ prompt, model, system }) { + const { text } = await generateText({ model: anthropic(model), system, prompt }); + return { body: text }; // also map usage/model/finishReason from the result → cost + token columns + }, +}; +``` + +**Recommended: the Vercel AI SDK (`ai`)** — provider-agnostic (`generateText` / +`generateObject` over Anthropic / OpenAI / Google / …), first-class structured +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 `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 + +`meta verify` walks every template's `@payloadRef` resolution and fails the build +(exit 1) if a reference can't be resolved. A `@responseRef` that does not resolve to a +value-object (or sourceless projection) is caught one layer earlier — it is a LOAD +error in every port. The emitted parser imports `zod`; +it's usually already a dependency (Drizzle / `runtime-ts` lean on it), else +`npm i zod`. + +**Jinja bodies (ADR-0061).** A body may be `/.jinja` (or `.j2`, `.jinja2`) +instead of `.mustache`; `@textRef` does not change. `@metaobjectsdev/render` renders it with +nunjucks (a dependency of the package, nothing to install) and `meta verify` checks it the same +way, walking the parsed template; it names the `.jinja` file and line on a drift. +`FilesystemProvider.engineOf(ref)` reports the engine of the file it found; for an +`InMemoryProvider` pass `new InMemoryProvider(map, { engine: "jinja" })`, or pass +`engine: "jinja"` to `render` / `verify`. A generated `render()` helper over a Jinja body +passes `engine: "jinja"`, so it renders as Jinja through any runtime provider, and the +runtime check runs on it as on a Mustache body. What the check cannot settle statically is +`ERR_TEMPLATE_NOT_STATIC`. nunjucks treats an empty list as true (jinja2 does not), so test a +list with `{% if items | length %}` when the same template must render in Python. + +## See which fields a template consumes + +List `docsFile()` in `generators` and run `meta gen` to emit the model surface to the +`docs` target — one page per `template.*` at `/