diff --git a/AGENTS.md b/AGENTS.md index 4c07da5621..863dda487f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (584 fixtures; 48 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (584 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python byte-identical; C# and Rust each carry a `KnownDrift` render ledger, recorded in `docs/CONFORMANCE.md`. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/agent-context-shipped/files/5497499d5dddc2cc.md b/agent-context-shipped/files/5497499d5dddc2cc.md new file mode 100644 index 0000000000..bf233c2a66 --- /dev/null +++ b/agent-context-shipped/files/5497499d5dddc2cc.md @@ -0,0 +1,7 @@ +## Pages generated for this project + +The project's `gen` command writes these from the metadata (they are regenerated output, like the +code). Read the one for a tier before you change that tier: + +{{pageList}} + diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index dd3daf5969..ca50485056 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -3,6 +3,7 @@ "docsRef": "main", "docsLinkPrefix": "https://github.com/metaobjectsdev/metaobjects/blob/", "skillsDir": ".claude/skills", + "agentPagesTemplate": "5497499d5dddc2cc.md", "stacks": [ { "id": "typescript", diff --git a/agent-context/templates/agent-pages.md.mustache b/agent-context/templates/agent-pages.md.mustache new file mode 100644 index 0000000000..bf233c2a66 --- /dev/null +++ b/agent-context/templates/agent-pages.md.mustache @@ -0,0 +1,7 @@ +## Pages generated for this project + +The project's `gen` command writes these from the metadata (they are regenerated output, like the +code). Read the one for a tier before you change that tier: + +{{pageList}} + diff --git a/changelog.d/agent-pages-every-port.md b/changelog.d/agent-pages-every-port.md new file mode 100644 index 0000000000..69dc1ebe58 --- /dev/null +++ b/changelog.d/agent-pages-every-port.md @@ -0,0 +1,32 @@ +- **The agent pages in every port, from the docs view.** `requirements.toon`, + `agent/requirements.md` and the model-only `agent/schema.md` are now written by C#, Java, + Kotlin, Python, Rust and TypeScript alike: each port's `requirements` and `agent-docs` + generators build the page data from its own docs view and render the shared + `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what + `fixtures/docs-page-conformance/` pins. A TypeScript project with no dialect now gets the + model-only `agent/schema.md` too (it used to get no schema page); with a dialect it keeps the + physical page. `agent/schema.md` documents the project's own storage in every port: a + dependency's object that `scope.include` does not name is left out of its tables, views, + relationships and enums (Rust loads no dependency, and leaves out a reference node). The + TypeScript physical page used to list an imported table too. `agent/ui.md` stays + TypeScript's. Rust has no requirement ledger of its own yet, so its pages list every + requirement the view carries, an uninherited import's included. + + The docs view gains a `storage` section (`docs/features/docs-view.md`): every table and view + the model stores into, its columns (names from the port's naming helpers, each linked to its + field), keys and foreign keys. The physical facts (SQL types, defaults, indexes, checks, + constraint names and actions) are `null` outside a TypeScript run with a dialect, which fills + them. `explorer.json` carries the new key in every port. + + **Retired: the human `requirements.md` page.** The `requirements` generator writes only + `requirements.toon`; people read the ledger in the explorer (`docs-site`), and agents read it + embedded in `agent/requirements.md`. Upgrading: the next `gen` no longer writes + `requirements.md`; delete the committed copy (and its `.hashes/` entry goes with the run). + + **The always-on agent file points at the agent pages, only when they exist.** `meta init` + (and `--refresh-docs`), `meta agent-docs` (which the C# and Java commands hand off to) and + Python's `metaobjects agent-docs` now add a "Pages + generated for this project" section to `.metaobjects/AGENTS.md`, naming each agent page the + project's last `gen` wrote (read from the committed `.metaobjects/.gen-state/.hashes/`) and + when to read it. A project that wires none of them gets the file unchanged. Refresh the agent + files after wiring `agent-docs`, `api-docs` or `requirements` for the first time. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 2ae59a0255..83a2d1a6e8 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,6 +1,6 @@ # Conformance coverage -The MetaObjects standard ships **48 shared conformance corpora** under +The MetaObjects standard ships **49 shared conformance corpora** under [`fixtures/`](../fixtures/). Every port runs every corpus that is *applicable to it* and asserts the same expected behaviour against the same fixtures. **This page is the inverse index**: fixture → feature doc + per-port pass status, and it is the @@ -54,8 +54,9 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | — | | [`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/agent-pages-pointer/`](../fixtures/agent-pages-pointer/) (the always-on agent file names the agent pages the last `gen` wrote, from the committed `.hashes/`) | 3 cases | ✓ (reference) | — (`metaobjects:agent-docs` runs the Node CLI) | — | — (`dotnet meta agent-docs` runs the Node CLI) | ✓ | — (no agent-context scaffold) | | [`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) | ✓ (`ListQueryConformanceTests`) | planned (R-PY) | ✓ (`list_query_conformance.rs`, the parser `meta_http` ships) | -| [`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 (G-RS-1) | +| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirement pages and the model-only schema page, built from the docs view: each page's rows, data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | ✓ (`DocsPageConformanceTest`) | ✓ (through Java: the Kotlin generators call the JVM page builder) | ✓ | ✓ | ✓ (rows from the view; no requirement ledger, RS-V2) | | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) (the vocabulary reference pages: each page's data and bytes, shared `templates/metamodel/`) | 1 (23 pages) | ✓ (reference; the source of the expected bytes) | ✓ (`MetamodelDocsCorpusTest`) | ✓ (through Java's builder and emitter) | ✓ (`MetamodelDocsTests`) | ✓ (`test_metamodel_docs_conformance.py`) | ✓ (`tests/metamodel_docs.rs`) | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | — (no `fmt`) | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | — | @@ -108,7 +109,7 @@ the contracts and the conformance corpora this repository runs against every por `jinja-render-conformance/` and `jinja-verify-conformance/` (the Jinja engine and its payload check, Python and TypeScript only, ADR-0061), `persistence-conformance/` (runtime reads and writes, and the migration scenarios of - the TypeScript reference helper), `agent-context-conformance/`, `metamodel-docs/`, `fmt-conformance/` + the TypeScript reference helper), `agent-context-conformance/`, `agent-pages-pointer/`, `metamodel-docs/`, `fmt-conformance/` (the canonical serializer, surfaced per-file — ADR-0034's "canonical format" is core), `field-lint-conformance/` (the advisory field lint every port's `verify` prints), `model-lint-conformance/` (the advisory overlay, node-name and deprecated-reference lints), @@ -833,16 +834,32 @@ REST-standard work lands, and each port's change flips its own entry. The decisi All 4 cases → [features/requirements.md](features/requirements.md) (the documentation 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 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. - -**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. +yields (`requirements.toon`, `agent/requirements.md`, the model-only `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). Every builder reads the docs view +alone, its `storage` section included, so no port walks the model for a page. The TypeScript +builders are the source of the expected bytes. The human `requirements.md` page is retired: the +explorer shows the ledger. The corpus README writes down what a model-only schema page contains +and what it leaves out. + +**Held to it, in every port** (rows, page data, then bytes, and the set of files written): +`server/typescript/packages/cli/test/docs-page-conformance.test.ts`, +`server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs`, +`server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java` +(Kotlin's generators call the same JVM page builder), +`server/python/tests/conformance/test_docs_page_conformance.py` and +`server/rust/metaobjects-codegen/tests/docs_page_conformance.rs`. Rust has no requirement ledger +of its own (RS-V2), so its pages list every requirement the view carries. + +### `fixtures/agent-pages-pointer/` (3 cases) + +All 3 cases → [features/cli.md](features/cli.md#agent-context-scaffold). Each case is a project +root and the section the always-on `.metaobjects/AGENTS.md` gains above `## Rules`: the agent +pages the committed `.metaobjects/.gen-state/.hashes/` record, in a fixed order, and nothing at +all when none is recorded. **Held to it:** +`server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts` and +`server/python/tests/unit/test_agent_docs.py`, the two ports that write the always-on file. C# +and Java hand `agent-docs` to the Node CLI, and Rust scaffolds no agent context. ### `fixtures/requirement-test-identity-conformance/` (27 cases) diff --git a/docs/features/cli.md b/docs/features/cli.md index c222826160..e70dcb5e27 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -365,7 +365,7 @@ documentation never lands in the code's output directory by default. |---|---|---| | `docs` | `docsFile()` | The NEUTRAL per-entity + per-template pages plus a README index, with the ER diagrams. Makes no language assumption at all (ADR-0020). | | `api-docs` | `apiDocsFile()` | The generated SDK reference under `api/` — types, endpoints, filter operators — plus `AGENT-API.md`, its condensed agent form. | -| `requirements` | `requirementsFile()` | The declared ledger, as `requirements.md` + `requirements.toon`; nothing for a model with no `requirement.*` node. | +| `requirements` | `requirementsFile()` | The declared ledger, as `requirements.toon` (people read it in the explorer, `docs-site`); nothing for a model with no `requirement.*` node. | | `agent-docs` | `agentDocsFile()` | Three pages an agent reads BEFORE touching a tier (below), under `agent/`. | | `metamodel-docs` | `metamodelDocsFile()` | The reference of the BUILT-IN metamodel (every registered type, subtype and attribute), not your model, under `metamodel/`. Its rendered form is published at . | | `docs-site` | `docsSiteFile()` | The HTML site under `site/`: the model explorer by default ([explorer-site.md](explorer-site.md)), the earlier site with `site: "classic"`; `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` for you to change. | @@ -408,19 +408,20 @@ Two properties worth knowing: **Every page is derived from a builder that already exists**, and none has a derivation of its own. The schema page reads the expected-schema snapshot `meta migrate` diffs and emits -from; the UI page reads the same descriptor emitted as the `` const that -`useEntityForm` consumes at runtime; the requirements page reads the same walk the ledger -surface and the generated test stubs are built on. A page an agent is told to trust has to +from (with no dialect, it is the model-only page every port writes, read off the docs view's +`storage` section); the UI page reads the same descriptor emitted as the `` const that +`useEntityForm` consumes at runtime; the requirements page reads the docs view's requirements, as the ledger surface does in every +port. A page an agent is told to trust has to be true, and this is the only way to keep three more of them true. **An empty page is no file.** Each renders nothing when its tier has nothing to describe — -no physical schema, no generated UI, no ledger — so a project sees only the pages it has +no table or view, no generated UI, no ledger — so a project sees only the pages it has content for, and one with none sees no `agent/` directory at all. Physical names, the dialect and view dispatch all come from `metaobjects.config.ts`, which `meta gen` always has. The neutral model pages make no use of them and stay neutral. `agent/schema.md` asks the same guard `meta gen` does — a model that emits database code must declare a `dialect`, and -`DEFAULT_DIALECT` is inert — so the page is skipped, with the runner's own message, exactly +`DEFAULT_DIALECT` is inert — so the physical page is skipped, with the runner's own message, exactly when `meta gen` would refuse the model, and also when the expected schema cannot be built at all (a primary-key move, a duplicate physical name: conditions `meta migrate` reports properly, and docs must not be the command that fails on them). @@ -942,6 +943,17 @@ file gets the fresh text beside it as `.new`, and the `.metaobjects/.agent 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 always-on file points at the agent pages only when they are wired.** When the project's +committed `.metaobjects/.gen-state/.hashes/` record an agent page the last `gen` wrote +(`agent/schema.md`, `agent/ui.md`, `agent/requirements.md`, `AGENT-API.md`, `requirements.toon`), +both `meta agent-docs` and Python's `metaobjects agent-docs` add a section above `## Rules` in +`.metaobjects/AGENTS.md` that names each one by its path. With none recorded the file is exactly +as shipped, so it never sends an agent to a page that does not exist. It recognises the pages +by those default paths only: an `agent-docs` run with a custom `subDir` (`llm/schema.md`) writes +pages the section does not name, so they get no line rather than a wrong one, and a project whose +only agent pages are such gets no section. The section's template is the shipped manifest's +`agentPagesTemplate`, and `fixtures/agent-pages-pointer/` gates it. + 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** diff --git a/docs/features/docs-view.md b/docs/features/docs-view.md index 0c8695d2bf..9a36bcd1a5 100644 --- a/docs/features/docs-view.md +++ b/docs/features/docs-view.md @@ -126,6 +126,7 @@ interface DocsView { requirements: DocsViewRequirement[]; advisories: DocsViewAdvisory[]; slices: DocsViewSlice[]; + storage: DocsViewStorage; } ``` @@ -264,6 +265,39 @@ Named node sets a map view opens on, all derived, each `{ id, kind, anchor, node - `prompt:`: one per template. It holds the template and what its own attributes reference (its payload and reply). +### `storage` + +Where the model's objects are stored, as names: what the model-only `agent/schema.md` page is +built from in every port (`fixtures/docs-page-conformance/`). + +```ts +interface DocsViewStorage { + physical: boolean; // true only when TypeScript filled the physical facts below + dialect: string; // the dialect they are for, or "" + tables: DocsViewTable[]; // sorted by name + views: DocsViewStoredView[]; // sorted by name +} +``` + +- **A table** is `{ name, schema, declaredBy, objects, description, primaryKey, columns, + foreignKeys, indexes, checks }`: one per concrete object whose primary source is a writable, + managed table. A TPH subtype shares its base's table and adds its columns there, nullable; + an `@unmanaged` table is only a foreign-key target. `declaredBy` links the declaring object, + `objects` every concrete object stored there. +- **A column** is `{ name, field, nullable, identity, description, sqlType, default }`. `field` + links the field's member row (first writer wins on a shared table); `nullable` is false for a + primary-key column and a required field; `identity` is the increment kind of a generated key. +- **A foreign key** is `{ columns, refTable, refColumns, name, onDelete, onUpdate }`, from each + `identity.reference` (one with `@enforce: false` is left out). +- **A view** is `{ name, schema, declaredBy, objects, columns }`, a column being `{ name, field }`; + the lineage is read from the linked field's `origin.*` member. + +Table, view and column names come from each port's own naming helpers (`naming` in +`.metaobjects/config.json`). The physical facts (`sqlType`, `default`, `indexes`, `checks`, a +foreign key's `name` and actions) are `null` in every port. The TypeScript `docs-site` run fills +them from the expected schema `meta migrate` diffs against when the project has a dialect, and +sets `physical` and `dialect`; the committed cases are built without one. + ## Verified by - [`fixtures/explorer-conformance/`](../../fixtures/explorer-conformance/): each case's diff --git a/docs/features/metadata-dependencies.md b/docs/features/metadata-dependencies.md index c2bd6f0308..47f2e46caf 100644 --- a/docs/features/metadata-dependencies.md +++ b/docs/features/metadata-dependencies.md @@ -407,7 +407,7 @@ A dependency published with `requirements: true` carries its requirements, and t with its model: an overlay of one resolves, and `meta verify` can see it. By default they stay the **publisher's** ledger, not yours. The requirement gate does not check, count, summarise or lint them, the `requirement-tests` generator writes no test for them, and the -requirements pages (`requirementsFile()`, the agent docs' `requirements.md`, an entity page's +requirements pages (`requirementsFile()`'s `requirements.toon`, the agent docs' `agent/requirements.md`, an entity page's "Required by") do not list them. That is the same default as an imported entity's code generation, for the same reason: you did not declare them. diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 940b074fb1..3eb02b36b8 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -290,7 +290,7 @@ it yourself. |---|---|---| | `docs` | which objects and templates get a page, where a page lands, which page template renders, the whole overview page (`renderIndexPage`) | the page payloads (`buildEntityDocData`, `buildTemplateDocData`) and the ER diagram (`renderMermaidErBlock`) | | `api-docs` | which units get a page, where a page lands, whether the index and the agent form (`AGENT-API.md`) are written | the model of the generated API (`buildApiModelForRun`, which also reads the run: layout, `apiPrefix`, whether Hono routes are wired) and its renderers (`renderEntityApiPage`, `renderApiIndex`, `renderAgentApi`) | -| `requirements` | which files the ledger becomes and where they land (`requirements.md`, `requirements.toon`); a project with no `requirement.*` node gets none | the two page builders (`requirements-markdown`, `requirements-toon`) and the projection they read (`requirements-view`) | +| `requirements` | where the ledger lands (`requirements.toon`); a project with no `requirement.*` node gets none | the page builder (`requirements-toon`) and the rows it reads off the docs view (`requirements-view`, `docs-view-pages`) | | `agent-docs` | which of the three pages are written and where | the three page builders (`agent-schema-page`, which also walks the model for the column-to-field map, lineage, relationships and enums; `agent-ui-page`; `agent-requirements-page`) | | `metamodel-docs` | which pages are written and where they land | the page render call (`renderDocPage`); each page's data comes from `coreMetamodelDocsPages` in `@metaobjectsdev/metadata`, which is core, and its layout from the shared `metamodel/*.mustache` templates | @@ -299,8 +299,8 @@ package. To change the wording of a model page you need no eject: put a file of name in your project (`templates/docs/entity-page.md.mustache` or `template-page.md.mustache`), or point `docsFile({ templates })` at another directory; it wins over the packaged one. The requirements and agent pages work the same way: -`templates/requirements/requirements.md.mustache` and `requirements.toon.mustache` -(`requirementsFile({ templates })`), and `templates/agent/schema.md.mustache` and +`templates/requirements/requirements.toon.mustache` (`requirementsFile({ templates })`), and +`templates/agent/schema.md.mustache` and `requirements.md.mustache` (`agentDocsFile({ templates })`; its embedded ledger is the `requirements/requirements.md` template). The templates and the data they are fed are pinned in `fixtures/docs-page-conformance/`; which ports run that corpus is in [CONFORMANCE.md](../CONFORMANCE.md). diff --git a/docs/features/requirements.md b/docs/features/requirements.md index ab7198d178..e59a605ac8 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -262,9 +262,11 @@ describes **the revival**, which is the thing a future reader is about to propos governs nothing. **One honest limit.** 19 of 40 is under half, and the guardrail only fires if something routes -an agent to the ledger. The requirement ledger (`requirementsFile()`) and the agent pages -(`agentDocsFile()`) carry retired entries; if -your agents never read it, restoring the entry buys you a coin flip. Point at it. +an agent to the ledger. The requirement ledger (`requirementsFile()`'s `requirements.toon`), +the explorer (`docs-site`) and the agent pages (`agentDocsFile()`) carry retired entries, in +every port; if your agents never read them, restoring the entry buys you a coin flip. Point at +them: once a `gen` has written the agent pages, the always-on `.metaobjects/AGENTS.md` that +`meta init --refresh-docs` (or your port's agent-docs command) writes names each one. > **`@verifiedBy` was retired in `0.24.0`, and `verify` no longer looks at your tests.** It asked > you to name a test and then checked only that the **name** occurred somewhere in the test diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 85ffaded4c..e7c92876ad 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -365,6 +365,18 @@ reference (`metamodel/INDEX.md`, `providers.md`, `types/.md`) from the s `templates/metamodel/` Mustache set; a `metamodel/.mustache` under its `TemplateRoot` overrides a shipped page. +**The agent pages.** The `requirements` generator writes `requirements.toon`, and `agent-docs` +writes `agent/requirements.md` and the model-only `agent/schema.md` (tables, columns, keys, +views, relationships and enums, named by this port's naming helpers). Both build their data from +the docs view (`MetaObjects.DocsView`, its `storage` section for the schema) and render the +shared `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what +`fixtures/docs-page-conformance/` pins (`DocsPageConformanceTests`). A `/.mustache` +under `TemplateRoot` overrides a shipped page. `agent-docs`'s `SubDir` is the directory the pages +land in, `agent` by default (`"llm"` writes `llm/schema.md`; `""` writes at the root), as in every +port. `agent/ui.md` and the physical schema (SQL types, +defaults, indexes) stay TypeScript's. The always-on agent file comes from the Node CLI +(`npx meta agent-docs`), which names these pages once a `gen` has written them. + **Generators write through a code writer.** `MetaObjects.Codegen.Writer.CsWriter` is where a generator's layout lives (ADR-0063): it owns the indent, the braces, the `using` lines and the blank lines, so a generator states what the file says and not how many spaces it takes. Every diff --git a/docs/ports/java.md b/docs/ports/java.md index 00045c54f2..9c610ad074 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -469,6 +469,8 @@ name in every port. | `api-docs` | `JavaApiDocsGenerator` | `metaobjects-codegen-spring` | The Java SDK api reference: one page per entity, value object, projection, served report and template, an index and `AGENT-API.md`, under `/`. A `` entry like any other, run by `metaobjects:generate` and checked by `metaobjects:verify`. Args: `outputDir` (required; give it generated files only, since `verify` compares the whole tree), `apiSubDir` (default `api/java`), `layout` (`flat`, the default, or `package`), `projectName` (the agent page's header label, default `project`) and `modelBaseUrl` (absolute base for the links to the model pages; with none set the pages carry no `Model / metadata` link, since nothing writes a page for it to point at). The `metaobjects:docs` goal was removed in 8.1.0 ([migration](../features/migrations/docs-are-generators.md#java-and-kotlin)). Ejectable: the copy takes the page IR, the builder, the renderer, the page paths and the page templates with it. | | `plantuml` | `PlantUMLGenerator` | `metaobjects-codegen-plantuml` | One PlantUML class diagram of the object model (`outputDir`, `outputFilename`; `showAttrs`, `showFields`, `showAbstracts`, `drawKeys`, `drawRefs` choose what is drawn). Ejectable: the copy takes `PlantUMLWriter` with it. | | `metamodel-docs` | `MetamodelDocsGenerator` | `metaobjects-codegen-base` | The reference of the built-in metamodel as Markdown: `INDEX.md`, `providers.md` and one `types/.md` per type family, rendered from the shared `templates/metamodel/` Mustache set over the build's own registry, so every port writes the same pages. Args: `outputDir` (required, generated files only), `subDir` (default `metamodel`; empty writes at the root) and `metamodelTemplateDir` (a directory holding `metamodel/.mustache` that win over the packaged ones; a same-path resource earlier on the classpath does too). Reads no model objects. Ejectable: the page data and templates stay in the package. | +| `requirements` | `RequirementsGenerator` | `metaobjects-codegen-base` | The requirement ledger as `requirements.toon`, for tools, rendered from the shared `templates/requirements/` Mustache page over the model's docs view, so every port writes the same bytes (`fixtures/docs-page-conformance/`). People read the ledger in the explorer (`docs-site`); no port writes a human `requirements.md`. Args: `outputDir` (required, generated files only), `subDir` (default empty: the root) and `templateDir` (a directory holding `requirements/.mustache` that win over the packaged ones). No `requirement.*` node, no file. Ejectable: the page data and templates stay in the package. | +| `agent-docs` | `AgentDocsGenerator` | `metaobjects-codegen-base` | Pages written for a coding agent, from the shared `templates/agent/` Mustache pages over the docs view: `agent/requirements.md` (the node index and the ledger) and the model-only `agent/schema.md` (tables, views, relationships and enums, without the SQL types, defaults, indexes and checks only the TypeScript migration engine knows). `agent/ui.md` stays a TypeScript page. Byte-identical to the TypeScript pages (`fixtures/docs-page-conformance/`). Args: `outputDir` (required, generated files only), `subDir` (the directory the pages land in, default `agent`; `llm` writes `llm/schema.md`, empty writes at the root, as in every port) and `templateDir` (`agent/.mustache` and `requirements/.mustache` overrides). The schema page says to change the schema with `meta migrate` when `.metaobjects/config.json` sets `migrate.dialect`. No requirement, no requirement page; no table and no view, no schema page. Ejectable. | | `docs-site` | `DocsSiteGenerator` | `metaobjects-codegen-base` | The model explorer, with no Node: under `/` (default `site`) it writes the explorer app (`index.html` and `assets/`, the same bytes in every port), `explorer.json` (the docs view, built from the model this run loaded; byte-identical to TypeScript's for the same inputs, gated by `fixtures/explorer-conformance/`), `explorer-model.js` and `explorer-stamp.js`. Each object lists the files generated for it (`generatedBy`, `sourceNode`): this execution's, and what the committed hash manifest records for the module's other ``s. The execution builds the site after every other generator it runs, so `metaobjects:verify` renders the lists the write run wrote. Args: `outputDir` (required), `subDir`, `title` (default: the module directory's name), `stamp` (footer text, default none), `prompts` (a directory of prompt `.mustache` sources beside the metadata and `templates/`), `verifyFile` (a `verify --format json` payload from the Node CLI, for the requirement verdicts; without it the requirement tree shows claims but no verdicts), `routesFile` (the routes the application mounts, `[{ node, method, path }]` with `node` a resolution key; without it no node lists routes) and `genStateDir` (default `.metaobjects/.gen-state`; read only when the generator runs outside `metaobjects:generate` and `metaobjects:verify`). An owned theme under `codegen/docs-site/` (`assets/explorer.css`, `assets/explorer.js`, `templates/explorer-*.mustache`) wins over the packaged one. Not ejectable: the builder is engine, the theme is what you own. The page-per-screen static export and the classic site stay TypeScript's. | | `html-docs` | `MetaDataHtmlDocumentationGenerator` | `metaobjects-codegen-base` | One HTML page describing the registered metamodel types (`outputDir`, `outputFilename`). It reads the type registry, not your model, so it documents the vocabulary your build loads, providers included. Ejectable: the copy takes `MetaDataHtmlDocumentationWriter` with it. | | `ai-docs` | `MetaDataAIDocumentationGenerator` | `metaobjects-codegen-base` | The same type reference as JSON, laid out for an AI reader (`outputDir`, `outputFilename`). Ejectable: the copy takes `MetaDataAIDocumentationWriter` with it. | diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index bff8fd2c9b..7928a0d67c 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -164,7 +164,7 @@ Every generator lays its output out with `KotlinWriter` The layout ratchet (`KotlinLayoutRatchetTest`) fails a generator that types its own line breaks or indentation, or imports KotlinPoet; its shrink-only allowlist of unconverted emitters is empty. -The 20 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): +The 22 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | Generator | Output | Per | |---|---|---| @@ -187,6 +187,8 @@ The 20 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | `KotlinSharedModelGenerator` | `.metaobjects.json` and `metaobjects.pkg.json` — the FR-023 shared-model artifact and manifest a consumer's `meta deps sync` reads. See [Publishing a shared model](#publishing-a-shared-model-shared-model) | once per project (`include` selects the nodes) | | `KotlinApiDocsGenerator` | The Kotlin SDK api reference, under `/`: `.md` per entity, value object, projection, served report and template, a `README.md` index and `AGENT-API.md`. A `` entry like any other, run by `metaobjects:generate` and checked by `metaobjects:verify`. Args: `outputDir` (required, generated files only), `apiSubDir` (default `api/kotlin`), `layout` (`flat` or `package`), `projectName` and `modelBaseUrl`, as for the Java `api-docs` (with no `modelBaseUrl` the pages carry no `Model / metadata` link). The `metaobjects:docs` goal was removed in 8.1.0 ([migration](../features/migrations/docs-are-generators.md#java-and-kotlin)). Ejectable, with the page model, builder, renderer and path math | the whole model, once | | `KotlinMetamodelDocsGenerator` | The reference of the built-in metamodel, under `/`: `INDEX.md`, `providers.md` and one `types/.md` per type family, rendered from the shared `templates/metamodel/` Mustache set over the build's own registry, so every port writes the same pages. Args: `outputDir` (required, generated files only), `subDir` (default `metamodel`; empty writes at the root) and `metamodelTemplateDir` (a directory holding `metamodel/.mustache` that win over the packaged ones). Reads no model objects. Ejectable | once per project | +| `KotlinRequirementsGenerator` | The requirement ledger as `requirements.toon` under `/`, rendered by the JVM page builder from the shared `templates/requirements/` page over the docs view, the same bytes as every port (`fixtures/docs-page-conformance/`). Args: `outputDir` (required), `subDir` (default empty) and `templateDir`. No `requirement.*` node, no file. Ejectable | once per project | +| `KotlinAgentDocsGenerator` | `agent/requirements.md` and the model-only `agent/schema.md` for a coding agent, from the shared `templates/agent/` pages over the docs view (the JVM page builder; `agent/ui.md` stays TypeScript). Args: `outputDir` (required), `subDir` (the directory the pages land in, default `agent`; `llm` writes `llm/schema.md`, empty writes at the root) and `templateDir`. No requirement, no requirement page; no table and no view, no schema page. Ejectable | once per project | | `DocsSiteGenerator` (`docs-site`) | The model explorer, with no Node: the JVM `DocsSiteGenerator` itself, so Kotlin and Java write the same bytes. Under `/` (default `site`): the explorer app, `explorer.json` (the docs view of the loaded model, byte-identical to TypeScript's, gated by `fixtures/explorer-conformance/`), `explorer-model.js` and `explorer-stamp.js`, with each object's generated files from this execution (built after every other generator it runs) and from the committed hash manifest for the module's other executions. Args as in [the Java table](java.md#generators). Not ejectable: an owned theme under `codegen/docs-site/` wins over the packaged one | once per project | Maven wiring. The plugin bundles `metaobjects-codegen-kotlin`, so it is not a dependency of your @@ -319,7 +321,7 @@ copies `KotlinSharedModelGenerator.kt` into a `codegen/` module under your packa ### Declarative template-codegen (`TemplateScopeGenerator`) -The 20 generators above are not the ceiling. When you need a shape +The 22 generators above are not the ceiling. When you need a shape none of them emits, Kotlin has **both** authoring paths — and which to reach for is a real decision (tradeoff table: [`codegen-concepts.md` §3](../features/codegen-concepts.md)). diff --git a/docs/ports/python.md b/docs/ports/python.md index 1400063391..6e584dcc11 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -1086,9 +1086,10 @@ definitions, and import lines are stable. | Migrations | Your own tool (Alembic, say) handed `meta schema`, or the Node reference helper (ADR-0015, Amendment 2) — no Python `migrate` command; the canonical `schema.postgres.sql` is the expected schema | | 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 | +| Requirements and agent pages | Yes — `requirements` (`requirements.toon`; the human `requirements.md` page is retired, the explorer replaces it) and `agent-docs` (`agent/requirements.md`, which embeds the ledger, 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`, each rendered from the shared templates bundled in the package over the docs view (`build_docs_view`, including its `storage` section of tables and views named by this port's naming helpers; gated by `fixtures/docs-page-conformance/`); a same-named file under the project's templates directory overrides a page; both ejectable | | Metamodel reference | Yes — `metamodel-docs` in a target's `generators` (`INDEX.md`, `providers.md` and `types/.md` under `metamodel/`; option `subDir`), rendered from the shared templates bundled in the package over the port's own registry manifest and embedded provider definitions; reads no model objects; a same-named file under the project's templates directory overrides a page; ejectable | | Model explorer | Yes, with no Node — `docs-site` in a target's `generators`: under `/` (default `site`) it writes the explorer app (`index.html` and `assets/`, the same bytes in every port, shipped as package data), `explorer.json` (the docs view, built from the model the run loaded by `metaobjects.docs_view.build_docs_view`; byte-identical to TypeScript's for the same inputs, gated by `fixtures/explorer-conformance/`), `explorer-model.js` and `explorer-stamp.js`. Each object lists the files generated for it (`generatedBy`, `sourceNode`): the run's own, laid over what the committed hash manifest records. The runner runs it after every other generator, so a write run and `verify --codegen` list the same files. Options: `subDir`, `title` (default: the project directory's name), `stamp` (footer text, default none), `prompts` (a directory of prompt `.mustache` sources beside the metadata and `templates/`), `verifyFile` (a `verify --format json` payload from the Node CLI, for the requirement verdicts), `routesFile` (the routes the application mounts, `[{ node, method, path }]`, `node` a resolution key). An owned theme under `codegen/docs-site/` (`assets/explorer.css`, `assets/explorer.js`, `templates/explorer-*.mustache`) wins over the packaged one. Not ejectable: the builder is engine, the theme is what you own. The page-per-screen static export and the classic site stay TypeScript's | +| Always-on pointer | Yes — `metaobjects agent-docs` inserts a section above `## Rules` in `.metaobjects/AGENTS.md` naming the agent pages (`agent/schema.md`, `agent/requirements.md`, `requirements.toon`, ...) that the project's committed `.metaobjects/.gen-state/.hashes/` record; no recorded page, no change (`fixtures/agent-pages-pointer/`) | | Docs view endpoint | `META_DOCS_ROUTE_PATH` (`/_meta/docs`), `meta_docs_json(root, routes=None)` and `meta_docs(root, routes=None)` in `metaobjects` (like `/_meta`, a framework-free helper, not a mount): the body is the docs view of the loaded model alone, byte-identical to every other port's (`fixtures/explorer-conformance/model-alone/`); `meta_docs` builds it once with a strong `ETag` and `matches(if_none_match)` for the `304`. Contract: [metadata-api.md](../features/metadata-api.md#the-docs-view-endpoint-get-_metadocs) | | 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)) | diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 2dd78f4e7e..933bde7ade 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -37,7 +37,7 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Report shapes | `metaobjects::report_shape::report_shape` derives an `object.report`'s fields (FR-044 Table B, with Table C's `required`): each dimension and measure, its subtype, and the `@of` field it takes its type from. It byte-matches `fixtures/persistence-conformance/report-shapes.json`, as every port does. | | Docs view | `metaobjects::docs_view::build` builds the port-neutral docs view (`docs/features/docs-view.md`) from the loaded model, with the requirement ledger, the generated files and the routes when it is given them. It byte-matches `fixtures/explorer-conformance/`, as every port does. | | Metadata routes | `metaobjects::meta_endpoint` holds the bodies of `GET /_meta` (`meta_json`) and `GET /_meta/docs` (`docs`, with its ETag and the `If-None-Match` check), framework-free, for the host to mount ([Metadata API](../features/metadata-api.md#rust--axum)). | -| Code generation (`cargo meta`) | The run engine, thirteen generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`, and two opt-in docs generators: `metamodel-docs`, the metamodel reference pages rendered from the shared Mustache set, and `docs-site`, the model explorer), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | +| Code generation (`cargo meta`) | The run engine, fifteen generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`, and four opt-in docs generators: `metamodel-docs`, the metamodel reference pages rendered from the shared Mustache set, `requirements` and `agent-docs`, the requirement and agent pages read off the docs view, and `docs-site`, the model explorer), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | ## The command: `cargo meta` @@ -70,8 +70,8 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log The generators a project runs are the list in `metaobjects.config.json` at the project root, the way the other ports choose theirs (`metaobjects.config.ts`, `codegen/Generators.cs`, the pom, `metaobjects.config.yaml`). `cargo meta init` writes every shipped generator but the opt-in -ones: the transport, `service-routes`, which `cargo meta init --transport` adds, and the two docs -generators, `metamodel-docs` and `docs-site`, which you add by name. Delete a line to stop running +ones: the transport, `service-routes`, which `cargo meta init --transport` adds, and the four docs +generators, `metamodel-docs`, `requirements`, `agent-docs` and `docs-site`, which you add by name. Delete a line to stop running one, and no eject is needed: ```json @@ -81,10 +81,10 @@ one, and no eject is needed: The file takes that one key: a layer is only a generator, so there are no layer settings. An entry is a name, or `{"name": "", "options": {...}}` for a generator that takes options; the generator's `configure` reads them and refuses a key it does not know (`ERR_UNKNOWN_GENERATOR_OPTION`, -naming the options it takes). Of the shipped generators only the two docs generators take options -(`metamodel-docs` takes `subDir`; `docs-site` takes the six in [its section](#docs-site-the-model-explorer)), so +naming the options it takes). Of the shipped generators only the docs generators take options +(`metamodel-docs` and `agent-docs` take `subDir`; `docs-site` takes the six in [its section](#docs-site-the-model-explorer)), so any other option fails the run, also a run `--generators` narrows to other generators. A project with -no such file runs every generator but `service-routes`, `metamodel-docs` and `docs-site`, which run +no such file runs every generator but `service-routes` and the four docs generators, which run only when they are listed: an HTTP server is a choice the project makes, not a default, and so are the metamodel reference pages and the model explorer. A generator that leaves the list has its files removed on the next `gen` (a file somebody edited is refused by name instead), and the run fails, naming the @@ -487,6 +487,26 @@ An entity whose source has a read-only view beside its table (`source.rdb @kind: role) is written to the table and read back through the view, so the fields that view derives (`origin.*`) are in every answer, a write's included. +### `requirements` and `agent-docs`: the requirement and agent pages + +`requirements` writes the requirement ledger as `requirements.toon`, for tools; `agent-docs` writes +`agent/requirements.md` (the node index and the embedded ledger) and the model-only `agent/schema.md` +(tables, views, relationships and enums, without the SQL types, defaults, indexes and checks only the +TypeScript migration engine knows; a reference node's table, view and relationships are left out, +as another run's to generate). Both read the docs view alone and render the shared +`templates/requirements/` and `templates/agent/` Mustache pages, so the bytes are every port's +(`fixtures/docs-page-conformance/`, run by `tests/docs_page_conformance.rs`). A same-path file under +the project's `templates/` wins. No `requirement.*` node, no requirement page; no table and no view, +no schema page. The schema page says to change the schema with `meta migrate` when +`.metaobjects/config.json` sets `migrate.dialect`. Nobody reads a human `requirements.md` any more: +the explorer shows the ledger. `agent/ui.md` stays a TypeScript page. + +What is absent here: this port has no requirement ledger of its own (no `requirements.inherit` +collection and no requirement gate in `cargo meta verify`, the RS-V2 work), so the pages list every +requirement the view carries, an imported package's included, where a port with the ledger lists +only those the collection counts. The project has no always-on agent file to point at the pages +either: `cargo meta` scaffolds no agent context. + ### `docs-site`: the model explorer The model explorer ([Explorer site](../features/explorer-site.md)), written with no Node: the diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 84198022c1..2f6dbbbdb6 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -8,7 +8,7 @@ }, "counts": { "fixtures": 584, - "corpora": 48, + "corpora": 49, "baseTypes": 21 }, "snippets": { diff --git a/fixtures/agent-pages-pointer/README.md b/fixtures/agent-pages-pointer/README.md new file mode 100644 index 0000000000..ef08545f2b --- /dev/null +++ b/fixtures/agent-pages-pointer/README.md @@ -0,0 +1,25 @@ +# agent-pages-pointer + +The always-on agent file (`.metaobjects/AGENTS.md`) points at the pages the project's `gen` +writes for a coding agent (`agent/schema.md`, `agent/ui.md`, `agent/requirements.md`, +`AGENT-API.md`, `requirements.toon`) only when the project's last `gen` wrote one. Every port that scaffolds the +always-on file reads what was written from the committed `.metaobjects/.gen-state/.hashes/` +(one JSON file per package, keyed by project-relative path; a value is a hash or an object +carrying one), renders the section from the template the shipped manifest names +(`agentPagesTemplate`, from `agent-context/templates/agent-pages.md.mustache`), and inserts it +above the file's `## Rules` heading. + +The pages are recognised by those default paths only (a path that is one, or ends in `/` plus +one). An `agent-docs` run with a custom `subDir` writes `llm/schema.md`, which the section does not +name: it gets no line, never a wrong one, and with no other agent page there is no section. +Knowing which generator wrote a path would need the hashes to record it, which they do not. + +Each case is a project root. `expected-section.md` is the rendered section: empty when no page +is wired, which leaves the always-on file exactly as shipped. + +- `no-hashes`: no `.hashes/` directory at all. +- `none`: hashes record generated code and per-object pages, but no agent page. +- `wired`: four agent pages over two hashes files in the two value shapes, plus a near miss + (`schema.md.orig`) that is not one. Pages list in the fixed page order, then by path. + +The reference is `server/typescript/packages/sdk/src/agent-context/agent-pages.ts`. diff --git a/fixtures/agent-pages-pointer/cases/no-hashes/.keep b/fixtures/agent-pages-pointer/cases/no-hashes/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/fixtures/agent-pages-pointer/cases/no-hashes/expected-section.md b/fixtures/agent-pages-pointer/cases/no-hashes/expected-section.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/fixtures/agent-pages-pointer/cases/none/.metaobjects/.gen-state/.hashes/shop.json b/fixtures/agent-pages-pointer/cases/none/.metaobjects/.gen-state/.hashes/shop.json new file mode 100644 index 0000000000..4d0d37d055 --- /dev/null +++ b/fixtures/agent-pages-pointer/cases/none/.metaobjects/.gen-state/.hashes/shop.json @@ -0,0 +1,4 @@ +{ + "src/generated/shop/Order.ts": "0000000000000000000000000000000000000000000000000000000000000000", + "docs/shop/Order.md": "1111111111111111111111111111111111111111111111111111111111111111" +} diff --git a/fixtures/agent-pages-pointer/cases/none/expected-section.md b/fixtures/agent-pages-pointer/cases/none/expected-section.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/.root.json b/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/.root.json new file mode 100644 index 0000000000..f019e1ea55 --- /dev/null +++ b/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/.root.json @@ -0,0 +1,6 @@ +{ + "docs/requirements.toon": "2222222222222222222222222222222222222222222222222222222222222222", + "docs/agent/requirements.md": "3333333333333333333333333333333333333333333333333333333333333333", + "docs/agent/schema.md": "4444444444444444444444444444444444444444444444444444444444444444", + "docs/agent/schema.md.orig": "5555555555555555555555555555555555555555555555555555555555555555" +} diff --git a/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/shop.json b/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/shop.json new file mode 100644 index 0000000000..5c5640c622 --- /dev/null +++ b/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/shop.json @@ -0,0 +1,12 @@ +{ + "docs/api/AGENT-API.md": { + "hash": "6666666666666666666666666666666666666666666666666666666666666666", + "generatedBy": "api-docs", + "sourceNode": "shop" + }, + "generated/shop/src/order.rs": { + "hash": "7777777777777777777777777777777777777777777777777777777777777777", + "generatedBy": "entity", + "sourceNode": "shop::Order" + } +} diff --git a/fixtures/agent-pages-pointer/cases/wired/expected-section.md b/fixtures/agent-pages-pointer/cases/wired/expected-section.md new file mode 100644 index 0000000000..fe46f1c2b4 --- /dev/null +++ b/fixtures/agent-pages-pointer/cases/wired/expected-section.md @@ -0,0 +1,10 @@ +## Pages generated for this project + +The project's `gen` command writes these from the metadata (they are regenerated output, like the +code). Read the one for a tier before you change that tier: + +- `docs/agent/schema.md`: before you touch persistence: tables, columns, keys and views. +- `docs/agent/requirements.md`: before you add or change a capability. +- `docs/api/AGENT-API.md`: before you call or change the generated API. +- `docs/requirements.toon`: the requirement ledger, in the form a tool reads. + diff --git a/fixtures/docs-page-conformance/README.md b/fixtures/docs-page-conformance/README.md index 909040d206..920417a69b 100644 --- a/fixtures/docs-page-conformance/README.md +++ b/fixtures/docs-page-conformance/README.md @@ -1,8 +1,14 @@ # docs-page-conformance -The shared corpus for the documentation pages every port writes from the requirement -ledger and the model: `requirements.md`, `requirements.toon`, `agent/requirements.md` and -the **model-only** `agent/schema.md`. +The shared corpus for the documentation pages every port writes from its docs view +(`docs/features/docs-view.md`): `requirements.toon`, `agent/requirements.md` and the +**model-only** `agent/schema.md`. Each port's builders read the view and nothing else: the +requirement rows from its `requirements`, the node index from each requirement's resolved +`implementedBy`, and the schema from its `storage` section plus the members of the nodes it +links (reference: `server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts`). + +The human `requirements.md` page was retired in 1.3.0: people read the ledger in the explorer +(`docs-site`). Its template stays, as the ledger `agent/requirements.md` embeds. **The TypeScript generators are the source of the expected bytes.** A port that disagrees with a case is wrong, not the case. @@ -13,7 +19,7 @@ Every page is a shared Mustache template fed the data a builder computes: | Page | Template (canonical copy) | Data | |---|---|---| -| `requirements.md` | `templates/requirements/requirements.md.mustache` | `data/requirements.md.json` | +| the ledger inside `agent/requirements.md` | `templates/requirements/requirements.md.mustache`, embedded form | `data/ledger.md.json` | | `requirements.toon` | `templates/requirements/requirements.toon.mustache` | `data/requirements.toon.json` | | `agent/requirements.md` | `templates/agent/requirements.md.mustache` | `data/agent-requirements.md.json` | | `agent/schema.md` | `templates/agent/schema.md.mustache` | `data/agent-schema.md.json` | @@ -26,6 +32,7 @@ has two checks: 1. **Builder.** The port's builder, run on `input/`, produces `expected/data/.json` (compare as JSON values). 2. **Page.** Rendering the template with that data produces `expected/` byte for byte. + (The embedded ledger has no page of its own; it is checked inside `agent/requirements.md`.) Under the page data sits one more layer, `expected/rows/`, the rows each builder starts from: @@ -34,30 +41,30 @@ Under the page data sits one more layer, `expected/rows/`, the rows each builder | `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 +Both are read off the docs view: `rows/requirements.json` from its `requirements` +(`requirementRowsFromView`), `rows/schema.json` from its `storage` (`schemaRowsFromView`). A +port checks its rows first (compare as JSON values), then its page data, then the bytes. The +TypeScript runner also holds the view-built rows and page equal to the ones it builds from the +expected schema (`schemaRows`, `agentSchemaPageData` with `physical: false`), so the model-only +page is the physical page less its physical facts. `cli/test/docs-page-shapes.test.ts` holds the requirement rows equal to the docs view'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. +gets no schema page. Every case builds its view with no verify ledger, manifest or routes. Two rules a port must keep. `agent/requirements.md` carries the ledger as its `ledger` value: the `requirements.md` template rendered in its `embedded` form (no `# Requirements` title, every heading one level down, capped at h6), with its trailing line breaks removed. The TOON page ends without a line break; the other pages end with exactly one. -## What a non-TypeScript schema page contains (design call 17) +## What the model-only schema page contains (design call 17) -A port without the expected schema builds the schema page from the model with its own -naming helpers. TypeScript writes the same page with `physical: false`: it builds its input -from the expected schema and then leaves out every fact only that schema knows. The page -contains: +Every port builds this page from its docs view's `storage` section, whose table and column +names come from the port's own naming helpers. TypeScript writes it the same way when the +project has no dialect, and with a dialect writes the physical page from the expected schema +instead. The page contains: - **Tables**: one per object whose primary source is a table in the schema (abstract bases and sourceless values have none; a TPH subtype shares its base's table and adds its own @@ -80,6 +87,11 @@ It leaves out the dialect facts: the SQL type and default columns, indexes (and them), foreign-key constraint names and referential actions. Only the TypeScript page, written from the expected schema, carries those; `agent/ui.md` stays a TypeScript page. +It also leaves out what is not the project's own storage: a dependency's object that +`scope.include` does not name (in Rust, which loads no dependency, a reference node) gives the +page no table, view, relationship or enum, in the physical TypeScript page too. These cases load +no dependency; each port's dependency-import test holds that rule. + One project setting reaches the page: `hasMigrate` is true when the project's `.metaobjects/config.json` sets `migrate.dialect` (it chose `meta migrate`, the reference migration helper). The page then says to change the schema with `meta migrate`; otherwise with @@ -100,7 +112,9 @@ the project's own migration tool, from the schema `meta schema` prints. A case s - 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. -- 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. +- Python: `server/python/tests/conformance/test_docs_page_conformance.py`. +- C#: `server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs`. +- Java and Kotlin: `server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java` (the Kotlin generators call the same JVM page builder). +- Rust: `server/rust/metaobjects-codegen/tests/docs_page_conformance.rs`. + +Each checks rows, page data, then the bytes its `requirements` and `agent-docs` generators write. diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/ledger.md.json similarity index 79% rename from fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json rename to fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/ledger.md.json index 2e53f21d77..ade04705f3 100644 --- a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/ledger.md.json @@ -1,50 +1,50 @@ { - "embedded": false, + "embedded": true, "count": 7, "plural": "s", "entries": [ { - "heading": "## Storefront", + "heading": "### Storefront", "facts": "`functional` · **L1** · status: `live`", "statement": "The storefront solution", "counterexample": "**Counterexample:** Nothing can be sold" }, { - "heading": "### Storefront.OrderService", + "heading": "#### Storefront.OrderService", "facts": "`functional` · **L3** · status: `live`", "statement": "Every placed order is recorded before payment is attempted", "counterexample": "**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." + "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." }, { - "heading": "#### Storefront.OrderService.OrderRecord — What an order must hold", + "heading": "##### Storefront.OrderService.OrderRecord — What an order must hold", "facts": "`functional` · **L4** · status: `live`", "statement": "An order records what was bought, for how much, and when: placed | paid", "counterexample": "**Counterexample:** An order row that cannot say who placed it", "implementedBy": "**Implemented by:** `acme::shop::Order`, `acme::shop::Order.placedAt`" }, { - "heading": "##### Storefront.OrderService.OrderRecord.TranscribableReference", + "heading": "###### Storefront.OrderService.OrderRecord.TranscribableReference", "facts": "`functional` · **L5** · status: `live`", "statement": "An order carries a reference a customer can read\ndown a phone line", "counterexample": "**Counterexample:** A reference that is a raw uuid", "implementedBy": "**Implemented by:** `acme::shop::Order.reference`" }, { - "heading": "##### Storefront.OrderService.OrderRecord.OrderExpiry", + "heading": "###### Storefront.OrderService.OrderRecord.OrderExpiry", "facts": "`functional` · **L5** · status: `planned` · tracked: acme/shop#412", "statement": "An unpaid order carries the instant it stops being reservable", "counterexample": "**Counterexample:** Stock held indefinitely against an order nobody paid for" }, { - "heading": "## MoneyIsExactMinorUnits", + "heading": "### MoneyIsExactMinorUnits", "facts": "`architectural` · status: `live`", "statement": "Monetary amounts are stored as exact integer minor units, never as floating point", "counterexample": "**Counterexample:** A cent that disappears when a total is split three ways", "implementedBy": "**Implemented by:** `acme::shop::Invoice`" }, { - "heading": "## GuestCheckout", + "heading": "### GuestCheckout", "facts": "`functional` · **L4** · status: `retired`", "statement": "A visitor can check out without an account", "counterexample": "**Counterexample:** An order with no way to reach the person who placed it" diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md deleted file mode 100644 index 799e1ed6b7..0000000000 --- a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md +++ /dev/null @@ -1,72 +0,0 @@ -# Requirements - -7 declared requirements, in declaration order. - -## Storefront - -`functional` · **L1** · status: `live` - -The storefront solution - -**Counterexample:** Nothing can be sold - -### Storefront.OrderService - -`functional` · **L3** · status: `live` - -Every placed order is recorded before payment is attempted - -**Counterexample:** A payment attempted against an order that was never stored - -Recording first is what lets a failed payment be retried. - -# Why first - -A payment with no order is a refund nobody can trace. - -#### Storefront.OrderService.OrderRecord — What an order must hold - -`functional` · **L4** · status: `live` - -An order records what was bought, for how much, and when: placed | paid - -**Counterexample:** An order row that cannot say who placed it - -**Implemented by:** `acme::shop::Order`, `acme::shop::Order.placedAt` - -##### Storefront.OrderService.OrderRecord.TranscribableReference - -`functional` · **L5** · status: `live` - -An order carries a reference a customer can read -down a phone line - -**Counterexample:** A reference that is a raw uuid - -**Implemented by:** `acme::shop::Order.reference` - -##### Storefront.OrderService.OrderRecord.OrderExpiry - -`functional` · **L5** · status: `planned` · tracked: acme/shop#412 - -An unpaid order carries the instant it stops being reservable - -**Counterexample:** Stock held indefinitely against an order nobody paid for - -## MoneyIsExactMinorUnits - -`architectural` · status: `live` - -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 - -**Implemented by:** `acme::shop::Invoice` - -## GuestCheckout - -`functional` · **L4** · status: `retired` - -A visitor can check out without an account - -**Counterexample:** An order with no way to reach the person who placed it diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/ledger.md.json similarity index 82% rename from fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json rename to fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/ledger.md.json index 9764aa2e2e..0b0c4db57c 100644 --- a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/ledger.md.json @@ -1,10 +1,10 @@ { - "embedded": false, + "embedded": true, "count": 1, "plural": "", "entries": [ { - "heading": "## ExportsAreResumable", + "heading": "### ExportsAreResumable", "facts": "`functional` · **L4** · status: `planned` · disposition: `deferred`", "statement": "true", "counterexample": "**Counterexample:** A 2 GB export that restarts from zero after a dropped connection" diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md deleted file mode 100644 index eec567a3ae..0000000000 --- a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md +++ /dev/null @@ -1,11 +0,0 @@ -# Requirements - -1 declared requirement, in declaration order. - -## ExportsAreResumable - -`functional` · **L4** · status: `planned` · disposition: `deferred` - -true - -**Counterexample:** A 2 GB export that restarts from zero after a dropped connection diff --git a/fixtures/explorer-conformance/crm/expected.json b/fixtures/explorer-conformance/crm/expected.json index 21e857bf28..0fa73a3f0f 100644 --- a/fixtures/explorer-conformance/crm/expected.json +++ b/fixtures/explorer-conformance/crm/expected.json @@ -2229,5 +2229,173 @@ "acme::tax::tax" ] } - ] + ], + "storage": { + "physical": false, + "dialect": "", + "tables": [ + { + "name": "accounts", + "schema": "", + "declaredBy": { + "label": "Account", + "id": "acme::crm::Account", + "path": "model/acme/crm/Account.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Account", + "id": "acme::crm::Account", + "path": "model/acme/crm/Account.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Account.id", + "id": "acme::crm::Account.id", + "path": "model/acme/crm/Account.html#m-id", + "kind": "field.long", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "name", + "field": { + "label": "Account.name", + "id": "acme::crm::Account.name", + "path": "model/acme/crm/Account.html#m-name", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [], + "indexes": null, + "checks": null + }, + { + "name": "leads", + "schema": "", + "declaredBy": { + "label": "Lead", + "id": "acme::crm::Lead", + "path": "model/acme/crm/Lead.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Lead", + "id": "acme::crm::Lead", + "path": "model/acme/crm/Lead.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "A prospective customer.", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "score", + "field": { + "label": "Lead.score", + "id": "acme::crm::Lead.score", + "path": "model/acme/crm/Lead.html#m-score", + "kind": "field.long", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "id", + "field": { + "label": "Lead.id", + "id": "acme::crm::Lead.id", + "path": "model/acme/crm/Lead.html#m-id", + "kind": "field.long", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "email", + "field": { + "label": "Lead.email", + "id": "acme::crm::Lead.email", + "path": "model/acme/crm/Lead.html#m-email", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "account_id", + "field": { + "label": "Lead.accountId", + "id": "acme::crm::Lead.accountId", + "path": "model/acme/crm/Lead.html#m-accountId", + "kind": "field.long", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [ + { + "columns": [ + "account_id" + ], + "refTable": "accounts", + "refColumns": [ + "id" + ], + "name": null, + "onDelete": null, + "onUpdate": null + } + ], + "indexes": null, + "checks": null + } + ], + "views": [] + } } diff --git a/fixtures/explorer-conformance/model-alone/expected.json b/fixtures/explorer-conformance/model-alone/expected.json index 84ff4ef38a..d9c9265bcd 100644 --- a/fixtures/explorer-conformance/model-alone/expected.json +++ b/fixtures/explorer-conformance/model-alone/expected.json @@ -702,5 +702,158 @@ "acme::library::Book" ] } - ] + ], + "storage": { + "physical": false, + "dialect": "", + "tables": [ + { + "name": "authors", + "schema": "", + "declaredBy": { + "label": "Author", + "id": "acme::library::Author", + "path": "model/acme/library/Author.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Author", + "id": "acme::library::Author", + "path": "model/acme/library/Author.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Author.id", + "id": "acme::library::Author.id", + "path": "model/acme/library/Author.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "name", + "field": { + "label": "Author.name", + "id": "acme::library::Author.name", + "path": "model/acme/library/Author.html#m-name", + "kind": "field.string", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [], + "indexes": null, + "checks": null + }, + { + "name": "books", + "schema": "", + "declaredBy": { + "label": "Book", + "id": "acme::library::Book", + "path": "model/acme/library/Book.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Book", + "id": "acme::library::Book", + "path": "model/acme/library/Book.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Book.id", + "id": "acme::library::Book.id", + "path": "model/acme/library/Book.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "title", + "field": { + "label": "Book.title", + "id": "acme::library::Book.title", + "path": "model/acme/library/Book.html#m-title", + "kind": "field.string", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "author_id", + "field": { + "label": "Book.authorId", + "id": "acme::library::Book.authorId", + "path": "model/acme/library/Book.html#m-authorId", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [ + { + "columns": [ + "author_id" + ], + "refTable": "authors", + "refColumns": [ + "id" + ], + "name": null, + "onDelete": null, + "onUpdate": null + } + ], + "indexes": null, + "checks": null + } + ], + "views": [] + } } diff --git a/fixtures/explorer-conformance/shop/expected.json b/fixtures/explorer-conformance/shop/expected.json index 6c055ef32b..e2120e111b 100644 --- a/fixtures/explorer-conformance/shop/expected.json +++ b/fixtures/explorer-conformance/shop/expected.json @@ -3277,5 +3277,307 @@ "acme::shop::Shop.Checkout.Orders.Recorded.Quotable" ] } - ] + ], + "storage": { + "physical": false, + "dialect": "", + "tables": [ + { + "name": "audit_entries", + "schema": "", + "declaredBy": { + "label": "AuditEntry", + "id": "acme::shop::AuditEntry", + "path": "model/acme/shop/AuditEntry.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "AuditEntry", + "id": "acme::shop::AuditEntry", + "path": "model/acme/shop/AuditEntry.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "AuditEntry.id", + "id": "acme::shop::AuditEntry.id", + "path": "model/acme/shop/AuditEntry.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "message", + "field": { + "label": "AuditEntry.message", + "id": "acme::shop::AuditEntry.message", + "path": "model/acme/shop/AuditEntry.html#m-message", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [], + "indexes": null, + "checks": null + }, + { + "name": "customers", + "schema": "", + "declaredBy": { + "label": "Customer", + "id": "acme::shop::Customer", + "path": "model/acme/shop/Customer.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Customer", + "id": "acme::shop::Customer", + "path": "model/acme/shop/Customer.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Customer.id", + "id": "acme::shop::Customer.id", + "path": "model/acme/shop/Customer.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "created_at", + "field": { + "label": "Customer.createdAt", + "id": "acme::shop::Customer.createdAt", + "path": "model/acme/shop/Customer.html#m-createdAt", + "kind": "field.timestamp", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "name", + "field": { + "label": "Customer.name", + "id": "acme::shop::Customer.name", + "path": "model/acme/shop/Customer.html#m-name", + "kind": "field.string", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "email", + "field": { + "label": "Customer.email", + "id": "acme::shop::Customer.email", + "path": "model/acme/shop/Customer.html#m-email", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "shipping_address", + "field": { + "label": "Customer.shippingAddress", + "id": "acme::shop::Customer.shippingAddress", + "path": "model/acme/shop/Customer.html#m-shippingAddress", + "kind": "field.object", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [], + "indexes": null, + "checks": null + }, + { + "name": "orders", + "schema": "", + "declaredBy": { + "label": "Order", + "id": "acme::shop::Order", + "path": "model/acme/shop/Order.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Order", + "id": "acme::shop::Order", + "path": "model/acme/shop/Order.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Order.id", + "id": "acme::shop::Order.id", + "path": "model/acme/shop/Order.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "created_at", + "field": { + "label": "Order.createdAt", + "id": "acme::shop::Order.createdAt", + "path": "model/acme/shop/Order.html#m-createdAt", + "kind": "field.timestamp", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "customer_id", + "field": { + "label": "Order.customerId", + "id": "acme::shop::Order.customerId", + "path": "model/acme/shop/Order.html#m-customerId", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "reference", + "field": { + "label": "Order.reference", + "id": "acme::shop::Order.reference", + "path": "model/acme/shop/Order.html#m-reference", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "total", + "field": { + "label": "Order.total", + "id": "acme::shop::Order.total", + "path": "model/acme/shop/Order.html#m-total", + "kind": "field.decimal", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "state", + "field": { + "label": "Order.state", + "id": "acme::shop::Order.state", + "path": "model/acme/shop/Order.html#m-state", + "kind": "field.enum", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [ + { + "columns": [ + "customer_id" + ], + "refTable": "customers", + "refColumns": [ + "id" + ], + "name": null, + "onDelete": null, + "onUpdate": null + } + ], + "indexes": null, + "checks": null + } + ], + "views": [] + } } diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 60ddd95c80..9aaaeaaa9e 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -330,20 +330,20 @@ "ports": ["typescript"] }, "requirements": { - "concept": "The requirement ledger as documentation: requirements.md for people and requirements.toon for tools.", + "concept": "The requirement ledger as requirements.toon, for tools; people read it in the explorer (docs-site).", "tier": "neutral", "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.", + "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9). A project that declares no requirement.* node gets no file. Every port renders the shared templates/requirements/ Mustache page over its docs view, gated by fixtures/docs-page-conformance/; the human requirements.md page was retired in 1.3.0.", "eject": "full", - "ports": ["typescript", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "agent-docs": { "concept": "Pages written for a coding agent working in the project: the schema, the UI surface and the requirements.", "tier": "neutral", "layer": "docs", - "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9).", + "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9). Every port renders agent/requirements.md and the model-only agent/schema.md from the shared templates/agent/ Mustache pages over its docs view, gated by fixtures/docs-page-conformance/; agent/ui.md and the physical schema (SQL types, defaults, indexes) are TypeScript's.", "eject": "full", - "ports": ["typescript", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "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 84a880812c..817784948d 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -1110,8 +1110,14 @@ gate_doc_template_drift() { server/typescript/packages/codegen-ts/templates server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts server/python/src/metaobjects/render/bundled_templates + server/csharp/MetaObjects.Codegen/Templates/requirements + server/csharp/MetaObjects.Codegen/Templates/agent server/csharp/MetaObjects.Codegen/Templates/metamodel + server/java/codegen-base/src/main/resources/metaobjects/templates/requirements + server/java/codegen-base/src/main/resources/metaobjects/templates/agent server/java/codegen-base/src/main/resources/metaobjects/templates/metamodel + server/rust/metaobjects-codegen/templates/requirements + server/rust/metaobjects-codegen/templates/agent server/rust/metaobjects-codegen/templates/metamodel ) bash scripts/sync-doc-templates.sh || return 1 diff --git a/scripts/sync-doc-templates.sh b/scripts/sync-doc-templates.sh index a215f6c1c2..90070ad31a 100755 --- a/scripts/sync-doc-templates.sh +++ b/scripts/sync-doc-templates.sh @@ -39,13 +39,16 @@ DEST_ROOTS=( PYTHON_DEST_ROOT="${REPO_ROOT}/server/python/src/metaobjects/render/bundled_templates" PYTHON_GROUPS=(requirements agent metamodel) -# The metamodel reference pages (the metamodel-docs generator) render in every port, so -# the metamodel group also ships in the C#, JVM (Java and Kotlin) and Rust packages. The -# group carries one data file beside its templates, provider-descriptions.json. -METAMODEL_EXTRA_DESTS=( - "${REPO_ROOT}/server/csharp/MetaObjects.Codegen/Templates/metamodel" - "${REPO_ROOT}/server/java/codegen-base/src/main/resources/metaobjects/templates/metamodel" - "${REPO_ROOT}/server/rust/metaobjects-codegen/templates/metamodel" +# The metamodel reference pages (the metamodel-docs generator) and the agent pages +# (requirements.toon, agent/requirements.md, the model-only agent/schema.md) render in every +# port, so those groups also ship in the C#, JVM (Java and Kotlin) and Rust packages, each +# under /. The metamodel group carries one data file beside its templates, +# provider-descriptions.json. +PORT_GROUPS=(requirements agent metamodel) +PORT_DEST_ROOTS=( + "${REPO_ROOT}/server/csharp/MetaObjects.Codegen/Templates" + "${REPO_ROOT}/server/java/codegen-base/src/main/resources/metaobjects/templates" + "${REPO_ROOT}/server/rust/metaobjects-codegen/templates" ) for group in "${TEMPLATE_GROUPS[@]}"; do @@ -74,15 +77,18 @@ for group in "${TEMPLATE_GROUPS[@]}"; do done done - if [[ "${group}" == "metamodel" ]]; then - for dest in "${METAMODEL_EXTRA_DESTS[@]}"; do - mkdir -p "${dest}" - for src in "${src_files[@]}"; do - cp "${src}" "${dest}/$(basename "${src}")" - echo "synced: ${src} -> ${dest}/$(basename "${src}")" + for port_group in "${PORT_GROUPS[@]}"; do + if [[ "${port_group}" == "${group}" ]]; then + for dest_root in "${PORT_DEST_ROOTS[@]}"; do + dest="${dest_root}/${group}" + mkdir -p "${dest}" + for src in "${src_files[@]}"; do + cp "${src}" "${dest}/$(basename "${src}")" + echo "synced: ${src} -> ${dest}/$(basename "${src}")" + done done - done - fi + fi + done for py_group in "${PYTHON_GROUPS[@]}"; do if [[ "${py_group}" == "${group}" ]]; then diff --git a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs index e6a4389706..1a1f29c73e 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs @@ -47,7 +47,7 @@ public void ListHeader_says_generators_are_owned_via_eject() public void ListLines_prints_all_generators_with_stable_names_and_descriptions() { var lines = GenCommand.ListLines(_tmp); - Assert.Equal(20, lines.Count); + Assert.Equal(22, lines.Count); foreach (var name in new[] { "entity", "db-context", "routes", "output-parser", "extractor", @@ -66,6 +66,8 @@ public void ListLines_prints_all_generators_with_stable_names_and_descriptions() // ADR-0025 — the api reference, an ordinary entry since ADR-0034 Amendment 9. "api-docs", "metamodel-docs", + "requirements", + "agent-docs", // The model explorer, written with no Node. "docs-site", // The @expr indexes the EF model cannot carry, as SQL. diff --git a/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs new file mode 100644 index 0000000000..f9c1705d1f --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs @@ -0,0 +1,122 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.Codegen.Docs; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +/// +/// fixtures/docs-page-conformance/ — the requirement pages and the model-only schema page, one case +/// at a time. In order: the rows each builder reads off the docs view (rows/), the page data (data/), +/// then the bytes the requirements and agent-docs generators write; and the case expects +/// no file this port does not produce, nor the reverse. TypeScript is the source of the expected bytes. +/// +public sealed class DocsPageConformanceTests +{ + private static string Corpus => Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "docs-page-conformance", "cases"); + + public static IEnumerable Cases() => + Directory.GetDirectories(Corpus).OrderBy(d => d, StringComparer.Ordinal).Select(d => new object[] { Path.GetFileName(d) }); + + private static MetaRoot Load(string inputDir) + { + var sources = Directory.GetFiles(inputDir, "meta.*.json").OrderBy(f => f, StringComparer.Ordinal) + .Select(f => (IMetaDataSource)new InMemoryStringSource(File.ReadAllText(f), id: Path.GetFileName(f))).ToList(); + var load = new MetaDataLoader().Load(sources); + Assert.Empty(load.Errors.Select(e => e.Code + ": " + e.Message)); + return load.Root; + } + + /// The case chose a meta migrate dialect: its config sets migrate.dialect. + private static string? Dialect(string inputDir) + { + var path = Path.Combine(inputDir, ".metaobjects", "config.json"); + if (!File.Exists(path)) return null; + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + return doc.RootElement.TryGetProperty("migrate", out var m) && m.TryGetProperty("dialect", out var d) ? d.GetString() : null; + } + + private static JsonNode? Json(object? data) => JsonSerializer.SerializeToNode(data); + + private static void AssertJson(string file, JsonNode? expected, JsonNode? actual) => + Assert.True(JsonNode.DeepEquals(expected, actual), $"{file} differs.\nexpected: {expected?.ToJsonString()}\nactual: {actual?.ToJsonString()}"); + + private static Dictionary ExpectedFiles(string dir, Func pick) => + Directory.Exists(dir) + ? Directory.GetFiles(dir, "*", SearchOption.AllDirectories) + .Select(f => Path.GetRelativePath(dir, f).Replace('\\', '/')).Where(pick) + .ToDictionary(f => f, f => File.ReadAllText(Path.Combine(dir, f)), StringComparer.Ordinal) + : []; + + [Fact] + public void The_corpus_is_not_empty() => Assert.NotEmpty(Cases()); + + [Theory] + [MemberData(nameof(Cases))] + public void Case_rows_data_and_bytes_equal_the_expected_files(string name) + { + string caseDir = Path.Combine(Corpus, name); + string input = Path.Combine(caseDir, "input"); + string expectedDir = Path.Combine(caseDir, "expected"); + var root = Load(input); + string? dialect = Dialect(input); + var view = DocsView.Build(root); + + // 1. The rows. + var rows = DocsViewPages.RequirementRows(view); + var expectedRows = ExpectedFiles(expectedDir, f => f.StartsWith("rows/", StringComparison.Ordinal)); + Assert.Equal(rows.Count > 0, expectedRows.ContainsKey("rows/requirements.json")); + if (rows.Count > 0) + AssertJson("rows/requirements.json", JsonNode.Parse(expectedRows["rows/requirements.json"]), Json(rows.Select(r => r.ToData()).ToList())); + var schemaRows = DocsViewPages.SchemaRows(view); + bool hasSchema = DocsViewPages.AgentSchemaData(view, dialect is not null) is not null; + Assert.Equal(hasSchema, expectedRows.ContainsKey("rows/schema.json")); + if (hasSchema) AssertJson("rows/schema.json", JsonNode.Parse(expectedRows["rows/schema.json"]), Json(schemaRows)); + + // 2. The page data. + var expectedData = ExpectedFiles(expectedDir, f => f.StartsWith("data/", StringComparison.Ordinal)); + var data = DocsViewPages.PageData(view, dialect is not null).ToList(); + Assert.Equal(expectedData.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(), + data.Select(d => "data/" + d.File).OrderBy(k => k, StringComparer.Ordinal).ToList()); + foreach (var (file, page) in data) + AssertJson("data/" + file, JsonNode.Parse(expectedData["data/" + file]), Json(page)); + + // 3. The bytes, through the generators. + var ctx = new GenContext + { + Entities = root.Objects(), + Root = root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme", Dialect = dialect }, + }; + var written = new RequirementsGenerator().Generate(ctx).Concat(new AgentDocsGenerator().Generate(ctx)) + .ToDictionary(f => f.Path, f => f.Content, StringComparer.Ordinal); + var expectedPages = ExpectedFiles(expectedDir, f => !f.StartsWith("rows/", StringComparison.Ordinal) && !f.StartsWith("data/", StringComparison.Ordinal)); + Assert.Equal(expectedPages.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(), written.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList()); + foreach (var (path, content) in expectedPages) + Assert.True(content == written[path], $"bytes differ for {path}"); + } + + // SubDir names the directory the agent pages land in, in place of agent/, as TypeScript's + // agentDocsFile({ subDir }), Python's sub_dir and Rust's subDir do: "llm" writes llm/schema.md, + // never llm/agent/schema.md. + [Fact] + public void SubDirReplacesTheAgentDirectory() + { + string input = Path.Combine(Corpus, "ledger-and-claims", "input"); + var root = Load(input); + var ctx = new GenContext + { + Entities = root.Objects(), + Root = root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme", Dialect = Dialect(input) }, + }; + var expected = new AgentDocsGenerator().Generate(ctx) + .Select(f => "llm/" + f.Path["agent/".Length..]).OrderBy(p => p, StringComparer.Ordinal).ToList(); + Assert.NotEmpty(expected); + Assert.Equal(expected, new AgentDocsGenerator { SubDir = "llm" }.Generate(ctx) + .Select(f => f.Path).OrderBy(p => p, StringComparer.Ordinal).ToList()); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs index ff42a522b5..adc6705c69 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs @@ -182,10 +182,10 @@ public void The_model_script_matches_TypeScript() var view = (JsonObject)JsonNode.Parse(File.ReadAllText( Path.Combine(RepoRoot(), "fixtures", "explorer-conformance", "model-alone", "expected.json")))!; var m = ExplorerModelScript.Of("T \u2028", "f", new Dictionary { ["b"] = "2", ["a"] = "1" }, null, view); - Assert.Equal("8ae24964eac47e67", m.Stamp); - Assert.Equal(10014, m.Script.Length); - Assert.Equal("3ae42a3977b053c76481fd1d5e7ca83f5f84fc1902608dbaec21bfe2cdc3019e", + Assert.Equal("950cb20a9b1bc1ca", m.Stamp); + Assert.Equal(12216, m.Script.Length); + Assert.Equal("a6a2e3094c558ab1823ebb782fa3f22747b13c2912f4be673a1a5d23c584c2e1", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(m.Script))).ToLowerInvariant()); - Assert.Equal("window.MO_STAMP = \"8ae24964eac47e67\";\n", ExplorerModelScript.StampScript(m.Stamp)); + Assert.Equal("window.MO_STAMP = \"950cb20a9b1bc1ca\";\n", ExplorerModelScript.StampScript(m.Stamp)); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs index f0e87c32f2..34b718a9ab 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs @@ -38,6 +38,9 @@ public sealed class GeneratorRegistryTests "api-docs", // The metamodel reference — the shared Mustache set over this port's registry. "metamodel-docs", + // The shared requirements / agent Mustache pages over the docs view. + "requirements", + "agent-docs", ]; [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs index fa6e6ba675..0e823b47a9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs @@ -398,10 +398,11 @@ private static readonly (string Literal, string ShouldUse, Reach Reach, string W /// render-helper needs a --template-root and template is a /// primitive with no default walk; neither can emit here. docs-site writes the model /// explorer's data, which shows each field's physical column as documentation: it is data the - /// page displays, not code that could reference a constant. + /// page displays, not code that could reference a constant. agent-docs is the same + /// case: its agent/schema.md names every table and column for an agent to read. /// private static readonly IReadOnlyList GeneratorNames = - [.. GeneratorRegistry.Entries.Keys.Where(n => n is not ("render-helper" or "template" or "shared-model" or "docs-site"))]; + [.. GeneratorRegistry.Entries.Keys.Where(n => n is not ("render-helper" or "template" or "shared-model" or "docs-site" or "agent-docs"))]; /// Run the generator suite over the fixture. private static IReadOnlyList Generate() diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs index da7a9a1cb5..70b660a737 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs @@ -132,6 +132,10 @@ private static readonly (string Generator, string File)[] ReportFiles = /// The index and the agent page, which gain lines for a served report and lose none. private static readonly string[] ApiDocsSharedPages = ["api/csharp/README.md", "api/csharp/AGENT-API.md"]; + private const string AgentDocsGeneratorName = "agent-docs"; + /// The model-only schema page, which gains the served report's view and loses no line. + private const string AgentSchemaPage = "agent/schema.md"; + // Every derived field is filterable: a count and a sum of a currency take the ordered band. private const string ExpectedAllowlist = """ @@ -283,7 +287,8 @@ private static void AssertSameExceptTheReportRow( Assert.Equal(ExpectedDbContextLines, AddedLines(content, actual[path])); continue; } - if (ApiDocsSharedPages.Contains(path) && selection.Contains(ApiDocsGeneratorName)) + if ((ApiDocsSharedPages.Contains(path) && selection.Contains(ApiDocsGeneratorName)) + || (path == AgentSchemaPage && selection.Contains(AgentDocsGeneratorName))) { var added = AddedLines(content, actual[path]); Assert.NotEmpty(added); @@ -374,11 +379,12 @@ public void A_report_reaches_no_tier_but_its_row_its_mapping_its_allowlist_and_i Assert.DoesNotContain(files.Keys, k => k.Contains(sourceless, StringComparison.Ordinal)); Assert.DoesNotContain(files.Values, c => c.Contains(sourceless, StringComparison.Ordinal)); } - // Outside those three, the DbContext and the api reference, no generated file mentions the report. + // Outside those three, the DbContext, the api reference and the schema page (its view), no + // generated file mentions the report. var mentions = files.Where(f => f.Value.Contains("StoreTotals", StringComparison.Ordinal)) .Select(f => f.Key).OrderBy(k => k, StringComparer.Ordinal).ToList(); Assert.Equal( - ((string[])[DbContextFile, RowFile, AllowlistFile, RoutesFile, ExportModuleFile, ApiDocsReportPage, .. ApiDocsSharedPages]) + ((string[])[DbContextFile, RowFile, AllowlistFile, RoutesFile, ExportModuleFile, ApiDocsReportPage, AgentSchemaPage, .. ApiDocsSharedPages]) .OrderBy(k => k, StringComparer.Ordinal).ToList(), mentions); } diff --git a/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs b/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs new file mode 100644 index 0000000000..fa63fb7a8e --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs @@ -0,0 +1,598 @@ +// The agent pages, built from the docs view (docs/features/docs-view.md). +// +// `requirements.toon`, `agent/requirements.md` and the model-only `agent/schema.md` are shared +// Mustache templates (templates/requirements/, templates/agent/) every port renders. The view is +// the one input every port builds the same bytes of, so the rows each page starts from are read +// off the view and nothing else: the requirement rows from `requirements`, the node index from +// each requirement's resolved `implementedBy`, and the schema from `storage` plus the members of +// the nodes it links. This file is the C# port of TypeScript's docs-view-pages.ts, +// requirements-toon.ts, requirements-markdown.ts and agent-requirements-page.ts; the cross-port +// corpus is fixtures/docs-page-conformance/. +// +// The builders return plain dictionaries and lists: that is the payload the render engine takes, +// and what the corpus pins as JSON. + +using System.Text; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using MetaObjects.Render; + +namespace MetaObjects.Codegen.Docs; + +/// One requirement of the ledger, as the pages read it (expected/rows/requirements.json). +public sealed record RequirementRow( + string Path, int Depth, string? Title, string SubType, long? Level, string? Status, string? Disposition, + IReadOnlyList TrackedBy, string? Statement, string? Counterexample, string? Description, + IReadOnlyList ImplementedBy, IReadOnlyList ClaimedConcerns) +{ + /// The row as the corpus pins it: an absent optional value is an absent key. + public Dictionary ToData() + { + var d = new Dictionary { ["path"] = Path, ["depth"] = Depth }; + if (Title is not null) d["title"] = Title; + d["subType"] = SubType; + if (Level is not null) d["level"] = Level; + if (Status is not null) d["status"] = Status; + if (Disposition is not null) d["disposition"] = Disposition; + d["trackedBy"] = TrackedBy.Cast().ToList(); + if (Statement is not null) d["statement"] = Statement; + if (Counterexample is not null) d["counterexample"] = Counterexample; + if (Description is not null) d["description"] = Description; + d["implementedBy"] = ImplementedBy.Cast().ToList(); + d["claimedConcerns"] = ClaimedConcerns.Cast().ToList(); + return d; + } +} + +/// One page the docs-view builders make: where it is written, its template and its data. +public sealed record DocViewPage(string Path, string Group, string Template, Dictionary Data); + +public static class DocsViewPages +{ + /// The marker on the first line of every agent page. The same bytes in every port: the + /// page data is pinned by the corpus. + public const string AgentPageMarker = ""; + + public const string RequirementsToonPath = "requirements.toon"; + public const string AgentRequirementsPath = "agent/requirements.md"; + public const string AgentSchemaPath = "agent/schema.md"; + + private const string ToonTemplate = "requirements.toon"; + private const string LedgerTemplate = "requirements.md"; + private const string AgentRequirementsTemplate = "requirements.md"; + private const string AgentSchemaTemplate = "schema.md"; + + // ---- JSON helpers ----------------------------------------------------------------- + + private static string Str(JsonNode? n) => n is JsonValue v && v.TryGetValue(out var s) ? s : ""; + + private static string? Opt(JsonNode? n) => Str(n) is { Length: > 0 } s ? s : null; + + private static JsonArray Arr(JsonNode? n) => n as JsonArray ?? []; + + private static JsonObject Obj(JsonNode? n) => n as JsonObject ?? []; + + private static bool Bool(JsonNode? n) => n is JsonValue v && v.TryGetValue(out var b) && b; + + private static long? Num(JsonNode? n) + { + if (n is not JsonValue v) return null; + if (v.TryGetValue(out var l)) return l; + if (v.TryGetValue(out var d)) return (long)d; + return null; + } + + private static IEnumerable Objs(JsonNode? n) => Arr(n).OfType(); + + // ---- requirements ----------------------------------------------------------------- + + /// The requirement rows of the view, in document order. is the + /// collection's ledger predicate over a requirement's qualified address: a dependency's + /// requirement the project did not inherit is left out. + public static List RequirementRows(JsonObject view, Func? inLedger = null) => + Objs(view["requirements"]) + .Where(r => inLedger is null || inLedger(Qualified(r))) + .Select(r => + { + var claims = Objs(r["implementedBy"]).ToList(); + return new RequirementRow( + Str(r["address"]), (int)(Num(r["depth"]) ?? 0), Opt(r["title"]), Str(r["subType"]), Num(r["level"]), + Opt(r["status"]), Opt(r["disposition"]), + Arr(r["trackedBy"]).Select(Str).ToList(), + Opt(r["statement"]), Opt(r["counterexample"]), Opt(r["description"]), + claims.Select(l => Str(l["ref"])).ToList(), + claims.Where(l => Bool(l["resolves"])).Select(l => Str(Obj(l["target"])["kind"])).Distinct(StringComparer.Ordinal).ToList()); + }).ToList(); + + private static string Qualified(JsonObject requirement) + { + string package = Str(requirement["package"]); + string address = Str(requirement["address"]); + return package.Length == 0 ? address : package + "::" + address; + } + + private sealed record NodeClaim(string Path, string SubType, long? Level, string? Status, string? Statement); + + private sealed record NodeEntry(string Address, string Concern, List Claims); + + /// Claimed node to the requirements that claim it, sorted by the node's id. A claim that + /// does not resolve is left out, as verify is what reports it. + private static List NodeIndex(JsonObject view, Func? inLedger) + { + var by = new Dictionary(StringComparer.Ordinal); + foreach (var r in Objs(view["requirements"])) + { + if (inLedger is not null && !inLedger(Qualified(r))) continue; + foreach (var link in Objs(r["implementedBy"])) + { + if (!Bool(link["resolves"])) continue; + var target = Obj(link["target"]); + string id = Str(target["id"]); + if (!by.TryGetValue(id, out var entry)) by[id] = entry = new NodeEntry(id, Str(target["kind"]), []); + entry.Claims.Add(new NodeClaim(Str(r["address"]), Str(r["subType"]), Num(r["level"]), Opt(r["status"]), Opt(r["statement"]))); + } + } + return by.Values.OrderBy(e => e.Address, StringComparer.Ordinal).ToList(); + } + + // ---- requirements.md (the ledger) --------------------------------------------------- + + /// One extra # on every line that starts a heading, capped at h6. + private static string Demote(string text) => + Regex.Replace(text, "^(#{1,6}) ", m => new string('#', Math.Min(m.Groups[1].Length + 1, 6)) + " ", RegexOptions.Multiline); + + private static string Heading(int depth) => new('#', Math.Min(depth + 2, 6)); + + private static string Collapse(string text) => Regex.Replace(text, @"\s+", " ").Trim(); + + private static string Normalize(string s) => Regex.Replace(s.ToLowerInvariant(), "[^a-z0-9]", ""); + + private static bool TitleRestatesLeaf(string path, string title) => + Normalize(path[(path.LastIndexOf('.') + 1)..]) == Normalize(title); + + private static string HeadingLine(RequirementRow r) + { + string? title = r.Title is null ? null : Collapse(r.Title); + string label = title is null || title.Length == 0 || TitleRestatesLeaf(r.Path, title) ? "" : $" — {title}"; + return $"{Heading(r.Depth)} {r.Path}{label}"; + } + + private static string Facts(RequirementRow r) + { + var parts = new List { $"`{r.SubType}`" }; + if (r.Level is { } level) parts.Add($"**L{level}**"); + if (r.Status is not null) parts.Add($"status: `{r.Status}`"); + if (r.Disposition is not null) parts.Add($"disposition: `{r.Disposition}`"); + if (r.TrackedBy.Count > 0) parts.Add($"tracked: {string.Join(", ", r.TrackedBy)}"); + return string.Join(" · ", parts); + } + + /// What requirements/requirements.md.mustache renders. is the + /// ledger as a section of a larger page: no Requirements title, every heading one level down. + public static Dictionary LedgerData(IReadOnlyList rows, bool embedded) + { + string Line(string text) => embedded ? Demote(text) : text; + return new() + { + ["embedded"] = embedded, + ["count"] = rows.Count, + ["plural"] = rows.Count == 1 ? "" : "s", + ["entries"] = rows.Select(r => + { + var e = new Dictionary { ["heading"] = Line(HeadingLine(r)), ["facts"] = Line(Facts(r)) }; + if (r.Statement is not null) e["statement"] = Line(r.Statement); + if (r.Counterexample is not null) e["counterexample"] = Line($"**Counterexample:** {r.Counterexample}"); + if (r.Description is not null) e["description"] = Line(r.Description); + if (r.ImplementedBy.Count > 0) + e["implementedBy"] = Line($"**Implemented by:** {string.Join(", ", r.ImplementedBy.Select(c => $"`{c}`"))}"); + return (object?)e; + }).ToList(), + }; + } + + // ---- requirements.toon -------------------------------------------------------------- + + private static readonly string[] ToonFields = ["path", "subType", "level", "status", "disposition", "claims", "statement"]; + + private static readonly Regex NumericLike = new(@"^-?[0-9]+(\.[0-9]+)?(e[+-]?[0-9]+)?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private static readonly Regex LeadingZero = new("^0[0-9]+$"); + private static readonly Regex ToonUnsafe = new(@"[:""\\\[\]{},\x00-\x1f]"); + + /// 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. + public static string ToonCell(string value) + { + bool safe = value.Length > 0 && value == value.Trim() + && value is not ("true" or "false" or "null") + && !NumericLike.IsMatch(value) && !LeadingZero.IsMatch(value) + && !ToonUnsafe.IsMatch(value) && !value.StartsWith('-'); + if (safe) return value; + var sb = new StringBuilder("\""); + foreach (char ch in value) + { + switch (ch) + { + case '\\': sb.Append("\\\\"); break; + case '"': sb.Append("\\\""); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + case < ' ': sb.Append("\\u").Append(((int)ch).ToString("x4")); break; + default: sb.Append(ch); break; + } + } + return sb.Append('"').ToString(); + } + + /// What requirements/requirements.toon.mustache renders: every cell a finished literal. + public static Dictionary ToonData(IReadOnlyList rows) => new() + { + ["count"] = rows.Count, + ["fields"] = "{" + string.Join(",", ToonFields) + "}", + ["rows"] = rows.Select(r => (object?)new Dictionary + { + ["line"] = string.Join(",", new[] + { + ToonCell(r.Path), + ToonCell(r.SubType), + r.Level is { } l ? l.ToString() : ToonCell(""), + ToonCell(r.Status ?? ""), + ToonCell(r.Disposition ?? ""), + ToonCell(string.Join(" ", r.ImplementedBy)), + ToonCell(r.Statement ?? ""), + }), + }).ToList(), + }; + + // ---- agent/requirements.md ---------------------------------------------------------- + + private static string MdCell(string text) => text.Replace("|", "\\|"); + + /// What agent/requirements.md.mustache renders. is the ledger + /// page's own template rendered in its embedded form, trailing line breaks removed. Null for a + /// model declaring no requirements, which gets no page. + public static Dictionary? AgentRequirementsData( + JsonObject view, string ledger, Func? inLedger = null) + { + var rows = RequirementRows(view, inLedger); + if (rows.Count == 0) return null; + var index = NodeIndex(view, inLedger); + var stated = new Dictionary(StringComparer.Ordinal); + foreach (var entry in index) + foreach (var c in entry.Claims) + if (c.Statement is not null) stated[c.Path] = (c.SubType, c.Statement); + var statements = stated.OrderBy(kv => kv.Key, StringComparer.Ordinal) + .Select(kv => (object?)new Dictionary + { + ["path"] = kv.Key, ["subType"] = kv.Value.SubType, ["statement"] = MdCell(Collapse(kv.Value.Statement)), + }).ToList(); + return new() + { + ["generatedMarker"] = AgentPageMarker, + ["hasNodeIndex"] = index.Count > 0, + ["nodeIndex"] = index.Select(e => (object?)new Dictionary + { + ["address"] = e.Address, + ["concern"] = e.Concern, + ["claims"] = string.Join("
", e.Claims.Select(c => + $"`{c.Path}`{(c.Level is { } l ? $" L{l}" : "")}{(c.Status is not null ? $" ({c.Status})" : "")}")), + }).ToList(), + ["hasStatements"] = statements.Count > 0, + ["statements"] = statements, + ["ledger"] = ledger.TrimEnd('\n'), + }; + } + + // ---- agent/schema.md ---------------------------------------------------------------- + + private static string StorageKey(string name, string schema) => schema.Length == 0 ? name : $"{schema}.{name}"; + + /// The model-only rows layer of the schema page, read off the view's storage + /// (expected/rows/schema.json). + public static Dictionary SchemaRows(JsonObject view) + { + var storage = Obj(view["storage"]); + var declared = new List<(string Key, string Id)>(); + var tables = Objs(storage["tables"]).Select(t => + { + declared.Add((StorageKey(Str(t["name"]), Str(t["schema"])), Str(Obj(t["declaredBy"])["id"]))); + var row = new Dictionary { ["name"] = Str(t["name"]) }; + if (Opt(t["schema"]) is { } schema) row["schema"] = schema; + if (Opt(t["description"]) is { } description) row["description"] = description; + row["primaryKey"] = Arr(t["primaryKey"]).Select(n => (object?)Str(n)).ToList(); + row["columns"] = Objs(t["columns"]).Select(c => + { + var col = new Dictionary { ["name"] = Str(c["name"]), ["nullable"] = Bool(c["nullable"]) }; + if (Opt(c["identity"]) is { } identity) col["identity"] = identity; + if (Opt(c["description"]) is { } d) col["description"] = d; + return (object?)col; + }).ToList(); + row["foreignKeys"] = Objs(t["foreignKeys"]).Select(f => (object?)new Dictionary + { + ["columns"] = Arr(f["columns"]).Select(n => (object?)Str(n)).ToList(), + ["refTable"] = Str(f["refTable"]), + ["refColumns"] = Arr(f["refColumns"]).Select(n => (object?)Str(n)).ToList(), + }).ToList(); + return (object?)row; + }).ToList(); + var views = Objs(storage["views"]).Select(v => + { + declared.Add((StorageKey(Str(v["name"]), Str(v["schema"])), Str(Obj(v["declaredBy"])["id"]))); + var row = new Dictionary { ["name"] = Str(v["name"]) }; + if (Opt(v["schema"]) is { } schema) row["schema"] = schema; + return (object?)row; + }).ToList(); + var declaredBy = new Dictionary(); + foreach (var (key, id) in declared.OrderBy(d => d.Key, StringComparer.Ordinal)) declaredBy[key] = id; + return new() { ["tables"] = tables, ["views"] = views, ["declaredBy"] = declaredBy }; + } + + private static Dictionary MembersById(JsonObject view) + { + var map = new Dictionary(StringComparer.Ordinal); + void Visit(JsonObject m) + { + map[Str(m["id"])] = m; + foreach (var g in Objs(m["memberGroups"])) foreach (var c in Objs(g["members"])) Visit(c); + } + foreach (var n in Objs(view["nodes"])) + foreach (var g in Objs(n["memberGroups"])) foreach (var m in Objs(g["members"])) Visit(m); + return map; + } + + private static List DirectMembers(JsonObject owner, string type) => + Objs(owner["memberGroups"]).FirstOrDefault(g => Str(g["type"]) == type) is { } g ? Objs(g["members"]).ToList() : []; + + private static JsonObject? Attr(JsonObject owner, string name) => Objs(owner["attrs"]).FirstOrDefault(a => Str(a["name"]) == name); + + private static JsonNode? AttrValue(JsonObject owner, string name) => Attr(owner, name)?["value"]; + + /// A string attribute as a page prints it: a resolved reference by its link's label, + /// anything else as its text. + private static string? AttrText(JsonObject owner, string name) + { + if (Attr(owner, name) is not { } a || a["value"] is not JsonValue v || !v.TryGetValue(out var value)) return null; + var link = Arr(a["values"]).FirstOrDefault() is JsonObject first ? first["link"] as JsonObject : null; + string text = link is not null && !Bool(link["unresolved"]) ? Str(link["label"]) : value; + return text.Length == 0 ? null : text; + } + + private static string Cols(IEnumerable names) + { + var list = names.ToList(); + return list.Count == 0 ? "—" : string.Join(", ", list.Select(c => $"`{c}`")); + } + + private static string KeyCell(JsonObject table, string column) + { + var pk = Arr(table["primaryKey"]).Select(Str).ToList(); + var roles = new List(); + if (pk.Contains(column)) roles.Add(pk.Count > 1 ? "PK (composite)" : "PK"); + var fk = Objs(table["foreignKeys"]).FirstOrDefault(f => Arr(f["columns"]).Select(Str).Contains(column)); + if (fk is not null) roles.Add($"FK → `{Str(fk["refTable"])}`"); + return string.Join(" · ", roles); + } + + private static string? LineageOf(JsonObject? field) + { + var origin = field is null ? null : DirectMembers(field, "origin").FirstOrDefault(); + if (origin is null) return null; + string? T(string name) => AttrText(origin, name); + string Via() => T("via") is { } via ? $" via `{via}`" : ""; + switch (Str(origin["subType"])) + { + case "passthrough": return $"passthrough from `{T("from") ?? "?"}`" + Via(); + case "aggregate": return $"`{T("agg") ?? "?"}`" + (T("of") is { } of ? $" of `{of}`" : "") + Via(); + case "first": + return "first" + (T("of") is { } o ? $" `{o}`" : "") + Via() + (T("orderBy") is { } ob ? $" ordered by `{ob}`" : ""); + case "computed": return "computed from a declared `@expr`"; + default: return $"`origin.{Str(origin["subType"])}`"; + } + } + + private static string CardinalityPhrase(string? cardinality, string? through) => cardinality switch + { + "many" => through is not null ? "many-to-many" : "one-to-many", + "one" => "many-to-one", + _ => "cardinality not declared", + }; + + private static string JsText(JsonNode? n) => + n is JsonValue v && v.TryGetValue(out var s) ? s : n?.ToJsonString() ?? "undefined"; + + /// The data agent/schema.md.mustache renders for the model-only page, built from the + /// view alone. : the project chose a meta migrate dialect + /// (migrate.dialect in .metaobjects/config.json). Null when the model declares no table + /// and no view: no page. + public static Dictionary? AgentSchemaData(JsonObject view, bool hasMigrate, Func? inScope = null) + { + var storage = Obj(view["storage"]); + // A dependency's node the project did not take into scope is not the project's schema. + bool Scoped(string id) => inScope is null || inScope(id); + var tables = Objs(storage["tables"]).Where(t => Scoped(Str(Obj(t["declaredBy"])["id"]))).ToList(); + var views = Objs(storage["views"]).Where(v => Scoped(Str(Obj(v["declaredBy"])["id"]))).ToList(); + if (tables.Count == 0 && views.Count == 0) return null; + var members = MembersById(view); + string FieldName(string id) => members.TryGetValue(id, out var m) ? Str(m["name"]) : ""; + + var tableData = tables.Select(t => + { + var columns = Objs(t["columns"]).ToList(); + var described = columns.Where(c => Str(c["description"]).Length > 0).ToList(); + var fks = Objs(t["foreignKeys"]).Select(f => + $"{Cols(Arr(f["columns"]).Select(Str))} → `{Str(f["refTable"])}`({Cols(Arr(f["refColumns"]).Select(Str))})").ToList(); + var d = new Dictionary + { + ["heading"] = $"`{StorageKey(Str(t["name"]), Str(t["schema"]))}`", + ["tableDeclaredBy"] = Str(Obj(t["declaredBy"])["id"]), + }; + if (Str(t["description"]).Length > 0) d["tableDescription"] = Collapse(Str(t["description"])); + d["columns"] = columns.Select(c => + { + var field = c["field"] as JsonObject; + return (object?)new Dictionary + { + ["name"] = Str(c["name"]), + ["fieldCell"] = field is null ? "" : $"`{FieldName(Str(field["id"]))}`", + ["declaredCell"] = field is null ? "" : $"`{Str(field["kind"])}`", + ["sqlTypeCell"] = "", + ["nullCell"] = Bool(c["nullable"]) ? "yes" : "no", + ["defaultCell"] = "", + ["keyCell"] = KeyCell(t, Str(c["name"])), + }; + }).ToList(); + d["hasDescribed"] = described.Count > 0; + d["described"] = described.Select(c => (object?)new Dictionary + { ["name"] = Str(c["name"]), ["text"] = Collapse(Str(c["description"])) }).ToList(); + d["hasIndexes"] = false; + d["indexes"] = new List(); + d["hasForeignKeys"] = fks.Count > 0; + d["foreignKeys"] = fks.Cast().ToList(); + d["hasChecks"] = false; + d["checks"] = new List(); + return (object?)d; + }).ToList(); + + var viewData = views.Select(v => + { + var lineage = Objs(v["columns"]).SelectMany(c => + { + string? text = LineageOf(c["field"] is JsonObject f && members.TryGetValue(Str(f["id"]), out var m) ? m : null); + return text is null ? [] : new[] { (object?)new Dictionary { ["column"] = Str(c["name"]), ["text"] = text } }; + }).ToList(); + return (object?)new Dictionary + { + ["heading"] = $"`{StorageKey(Str(v["name"]), Str(v["schema"]))}`", + ["viewDeclaredBy"] = Str(Obj(v["declaredBy"])["id"]), + ["hasLineage"] = lineage.Count > 0, + ["lineage"] = lineage, + }; + }).ToList(); + + // Every relationship as written, in declaration order of its object. + var byOrder = Objs(view["nodes"]).OrderBy(n => Num(n["order"]) ?? 0).ToList(); + var relationships = new List(); + foreach (var n in byOrder) + { + if (Str(n["type"]) != "object" || !Scoped(Str(n["id"]))) continue; + foreach (var rel in DirectMembers(n, "relationship")) + { + string? through = AttrText(rel, "through"); + string? onDelete = AttrText(rel, "onDelete"); + var parts = new List + { + $"`{Str(n["id"])}.{Str(rel["name"])}`", + $"`{Str(rel["subType"])}`", + $"{CardinalityPhrase(AttrValue(rel, "cardinality") is JsonValue c && c.TryGetValue(out var cs) ? cs : null, through)} → `{AttrText(rel, "objectRef") ?? "?"}`", + }; + if (through is not null) parts.Add($"through `{through}`"); + if (onDelete is not null) parts.Add($"on delete `{onDelete}`"); + relationships.Add(string.Join(" · ", parts)); + } + } + + // Every enum field of a table-backed object, in declaration order of its object. + var tableBacked = new HashSet(tables.SelectMany(t => Objs(t["objects"]).Select(o => Str(o["id"]))), StringComparer.Ordinal); + var enums = new List(); + foreach (var n in byOrder) + { + if (!tableBacked.Contains(Str(n["id"]))) continue; + foreach (var f in DirectMembers(n, "field")) + { + if (Str(f["subType"]) != "enum") continue; + var list = AttrValue(f, "values") is JsonArray values ? values.Select(JsText).ToList() : []; + if (list.Count == 0) continue; + string storageKind = AttrValue(f, "intValueMap") is JsonObject map + ? $"int-backed ({string.Join(", ", list.Select(m => $"{m}={(map.TryGetPropertyValue(m, out var v) ? JsText(v) : "undefined")}"))})" + : "string-backed"; + enums.Add(new Dictionary + { + ["field"] = $"{Str(n["id"])}.{Str(f["name"])}", + ["members"] = string.Join(", ", list.Select(m => $"`{m}`")), + ["storage"] = storageKind, + }); + } + } + + bool anyDescription = tables.Any(t => Str(t["description"]).Length > 0 || Objs(t["columns"]).Any(c => Str(c["description"]).Length > 0)); + return new() + { + ["generatedMarker"] = AgentPageMarker, + ["physical"] = false, + ["dialect"] = "", + ["hasMigrate"] = hasMigrate, + ["descriptionNudge"] = !anyDescription && tables.Count > 0, + ["hasTables"] = tableData.Count > 0, + ["tables"] = tableData, + ["hasViews"] = viewData.Count > 0, + ["hasReportView"] = views.Any(v => Objs(v["objects"]).Any(o => Str(o["kind"]) == "object.report")), + ["views"] = viewData, + ["hasRelationships"] = relationships.Count > 0, + ["relationships"] = relationships, + ["hasEnums"] = enums.Count > 0, + ["enums"] = enums, + }; + } + + // ---- templates and rendering --------------------------------------------------------- + + private const string ResourcePrefix = "MetaObjects.Codegen.Templates."; + + /// The text of templates/<group>/<page>.mustache: the project's own copy + /// under when there is one, else the one shipped in the package. + public static string Template(string group, string page, string? templateRoot) + { + string file = page + ".mustache"; + if (templateRoot is { Length: > 0 } root && System.IO.Path.Combine(root, group, file) is var path && File.Exists(path)) + return File.ReadAllText(path); + using var stream = typeof(IGenerator).Assembly.GetManifestResourceStream($"{ResourcePrefix}{group}.{file}") + ?? throw new InvalidOperationException($"embedded template missing: {ResourcePrefix}{group}.{file}"); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); + } + + private static string RenderTemplate(string text, object data) => + Renderer.Render(new RenderRequest + { + Template = text, + Payload = data, + Provider = new InMemoryProvider(new Dictionary()), + Format = Escapers.FORMAT_TEXT, + }); + + /// Every page of the view, in the order they are written: requirements.toon, + /// agent/requirements.md and agent/schema.md. A page the model gives no content for + /// is not in the list. and pick the + /// requirements and the agent-docs generator's pages. + public static IEnumerable<(string Path, string Content)> Render( + JsonObject view, bool hasMigrate, string? templateRoot, Func? inLedger, + bool includeRequirements, bool includeAgent, Func? inScope = null) + { + var rows = RequirementRows(view, inLedger); + if (includeRequirements && rows.Count > 0) + yield return (RequirementsToonPath, RenderTemplate(Template("requirements", ToonTemplate, templateRoot), ToonData(rows))); + if (!includeAgent) yield break; + var data = rows.Count == 0 ? null : AgentRequirementsData( + view, RenderTemplate(Template("requirements", LedgerTemplate, templateRoot), LedgerData(rows, embedded: true)), inLedger); + if (data is not null) + yield return (AgentRequirementsPath, RenderTemplate(Template("agent", AgentRequirementsTemplate, templateRoot), data)); + if (AgentSchemaData(view, hasMigrate, inScope) is { } schema) + yield return (AgentSchemaPath, RenderTemplate(Template("agent", AgentSchemaTemplate, templateRoot), schema).TrimEnd('\n') + "\n"); + } + + /// The page data the corpus pins, by its file name under expected/data/. + public static IEnumerable<(string File, Dictionary Data)> PageData(JsonObject view, bool hasMigrate, Func? inLedger = null) + { + var rows = RequirementRows(view, inLedger); + if (rows.Count > 0) + { + yield return ("requirements.toon.json", ToonData(rows)); + yield return ("ledger.md.json", LedgerData(rows, embedded: true)); + } + var data = rows.Count == 0 ? null : AgentRequirementsData( + view, RenderTemplate(Template("requirements", LedgerTemplate, null), LedgerData(rows, embedded: true)), inLedger); + if (data is not null) yield return ("agent-requirements.md.json", data); + if (AgentSchemaData(view, hasMigrate) is { } schema) yield return ("agent-schema.md.json", schema); + } +} diff --git a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs index 79d331c560..28e0836b78 100644 --- a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs +++ b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs @@ -328,6 +328,32 @@ private static IGenerator RenderHelper(GeneratorBuildContext ctx) => Note = "Reads no model objects. A project's metamodel/.mustache under the template root overrides the shipped template.", SourceFileName = "MetamodelDocsGenerator.cs", }, + // The requirement ledger as requirements.toon: the shared templates/requirements/ Mustache page over the docs view. + ["requirements"] = new() + { + Name = "requirements", + Description = "The requirement ledger as requirements.toon, for tools; people read it in the explorer (docs-site).", + Tier = GeneratorTier.Neutral, + Layer = GeneratorLayer.Docs, + Factory = ctx => new RequirementsGenerator { TemplateRoot = ctx.TemplateRoot }, + Options = "OutDir, SubDir (default \"\"), TemplateRoot (init properties on the entry in codegen/Generators.cs)", + Note = "A model that declares no requirement.* node gets no file. A project's requirements/requirements.toon.mustache under the template root overrides the shipped template.", + SourceFileName = "RequirementsGenerator.cs", + Companions = ["Docs/DocsViewPages.cs"], + }, + // The pages for a coding agent: agent/requirements.md and the model-only agent/schema.md, over the docs view. + ["agent-docs"] = new() + { + Name = "agent-docs", + Description = "Pages written for a coding agent working in the project: the model-only schema and the requirements (agent/ui.md and the physical schema are TypeScript's).", + Tier = GeneratorTier.Neutral, + Layer = GeneratorLayer.Docs, + Factory = ctx => new AgentDocsGenerator { TemplateRoot = ctx.TemplateRoot }, + Options = "OutDir, SubDir (default \"agent\"; \"\" writes at the root), TemplateRoot (init properties on the entry in codegen/Generators.cs)", + Note = "A model with no requirement gets no requirements page, and one with no table and no view gets no schema page. A project's agent/.mustache under the template root overrides the shipped template.", + SourceFileName = "AgentDocsGenerator.cs", + Companions = ["Docs/DocsViewPages.cs"], + }, // The model explorer over the docs view (no Node). Exempt from eject (registry.json): the site // builder is engine; a project owns the explorer's theme and page templates under codegen/docs-site/. ["docs-site"] = new() diff --git a/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs new file mode 100644 index 0000000000..6ac039295d --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs @@ -0,0 +1,51 @@ +// agent-docs — the pages written for a coding agent working in the project: agent/requirements.md +// (the node index and the embedded ledger) and the model-only agent/schema.md (tables, columns, +// keys, views, relationships and enums, named by this port's own naming helpers). The shared +// templates/agent/ Mustache pages rendered over the docs view this port builds from the loaded model +// (MetaObjects.DocsView), the page data built by Docs/DocsViewPages.cs and held to the same bytes by +// fixtures/docs-page-conformance/. agent/ui.md and the physical schema (SQL types, defaults, indexes) +// stay TypeScript's. +// +// An ordinary entry in codegen/Generators.cs (ADR-0034 Amendment 9). A model with no requirement +// gets no requirements page; a model with no table and no view gets no schema page. A project's own +// `agent/.mustache` (and `requirements/requirements.md.mustache`, the ledger it embeds) under +// TemplateRoot wins over the shipped template. + +using MetaObjects.Codegen.Docs; +using MetaObjects.Meta; + +namespace MetaObjects.Codegen.Generators; + +public sealed class AgentDocsGenerator : IGenerator +{ + public string Name => "agent-docs"; + + /// The docs output root the pages are written under; null writes under the run's --out. + public string? OutDir { get; init; } + + /// The directory under the pages land in, in place of agent; "" writes them at its root. + public string SubDir { get; init; } = DefaultSubDir; + + /// Where the pages land when the entry names no . + public const string DefaultSubDir = "agent"; + + /// A project template directory: agent/<page>.mustache there overrides the shipped one. + public string? TemplateRoot { get; init; } + + public bool WholeModel => true; + + public IEnumerable Generate(GenContext ctx) + { + var imports = ctx.Root.ImportScope; + var view = DocsView.Build(ctx.Root); + // The project chose `meta migrate` (migrate.dialect in .metaobjects/config.json). + bool hasMigrate = !string.IsNullOrEmpty(ctx.Config.Dialect); + // An object a dependency brought and the project did not take into scope is left out of the schema. + var inScope = ctx.Root.Objects().Where(ctx.Root.InScope).Select(o => o.ResolutionKey()).ToHashSet(StringComparer.Ordinal); + string prefix = SubDir.Trim('/') is { Length: > 0 } sub ? sub + "/" : ""; + foreach (var (path, content) in DocsViewPages.Render( + view, hasMigrate, TemplateRoot, fqn => imports?.InLedger(fqn) ?? true, + includeRequirements: false, includeAgent: true, inScope.Contains)) + yield return new EmittedFile(prefix + Path.GetFileName(path), content) { WholeModel = true }; + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/RequirementsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RequirementsGenerator.cs new file mode 100644 index 0000000000..b81b4b8924 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/RequirementsGenerator.cs @@ -0,0 +1,40 @@ +// requirements — the requirement ledger as requirements.toon, for tools; people read it in the +// explorer (docs-site). The shared templates/requirements/ Mustache page rendered over the docs view +// this port builds from the loaded model (MetaObjects.DocsView), the page data built by +// Docs/DocsViewPages.cs and held to the same bytes by fixtures/docs-page-conformance/. +// +// An ordinary entry in codegen/Generators.cs, run by `dotnet meta gen` (ADR-0034 Amendment 9). A +// model that declares no requirement.* node gets no file. A project's own +// `requirements/requirements.toon.mustache` under TemplateRoot wins over the shipped template. + +using MetaObjects.Codegen.Docs; +using MetaObjects.Meta; + +namespace MetaObjects.Codegen.Generators; + +public sealed class RequirementsGenerator : IGenerator +{ + public string Name => "requirements"; + + /// The docs output root the page is written under; null writes under the run's --out. + public string? OutDir { get; init; } + + /// Where under the page lands; "" writes it at its root. + public string SubDir { get; init; } = ""; + + /// A project template directory: requirements/requirements.toon.mustache there overrides the shipped one. + public string? TemplateRoot { get; init; } + + public bool WholeModel => true; + + public IEnumerable Generate(GenContext ctx) + { + var imports = ctx.Root.ImportScope; + var view = DocsView.Build(ctx.Root); + string prefix = SubDir.TrimEnd('/') is { Length: > 0 } sub ? sub + "/" : ""; + foreach (var (path, content) in DocsViewPages.Render( + view, hasMigrate: false, TemplateRoot, fqn => imports?.InLedger(fqn) ?? true, + includeRequirements: true, includeAgent: false)) + yield return new EmittedFile(prefix + path, content) { WholeModel = true }; + } +} diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index 10664c0b39..5e10083319 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -55,6 +55,8 @@ + + @@ -64,6 +66,7 @@ + @@ -78,6 +81,8 @@ + + "; + + public static final String REQUIREMENTS_TOON_REF = "requirements/requirements.toon"; + public static final String REQUIREMENTS_LEDGER_REF = "requirements/requirements.md"; + public static final String AGENT_REQUIREMENTS_REF = "agent/requirements.md"; + public static final String AGENT_SCHEMA_REF = "agent/schema.md"; + + private static final String NO_VALUE = "—"; + private static final String TYPE_OBJECT = "object"; + private static final String TYPE_FIELD = "field"; + private static final String TYPE_ORIGIN = "origin"; + private static final String TYPE_RELATIONSHIP = "relationship"; + private static final String KIND_REPORT = "object.report"; + private static final String SUBTYPE_ENUM = "enum"; + + private DocsViewPages() { + } + + // ---- json reads -------------------------------------------------------------------- + + private static String str(JsonObject o, String key) { + JsonElement e = o.get(key); + return e == null || e.isJsonNull() || !e.isJsonPrimitive() ? "" : e.getAsString(); + } + + private static JsonArray arr(JsonObject o, String key) { + JsonElement e = o.get(key); + return e != null && e.isJsonArray() ? e.getAsJsonArray() : new JsonArray(); + } + + private static List objects(JsonArray a) { + List out = new ArrayList<>(); + for (JsonElement e : a) if (e.isJsonObject()) out.add(e.getAsJsonObject()); + return out; + } + + private static boolean has(JsonObject o, String key) { + JsonElement e = o.get(key); + return e != null && !e.isJsonNull(); + } + + private static String opt(String s) { + return s.isEmpty() ? null : s; + } + + // ---- requirements ------------------------------------------------------------------ + + /** One requirement row of the view, in document order, as the rows layer pins it. */ + public static List> requirementRows(JsonObject view, Predicate inLedger) { + List> rows = new ArrayList<>(); + for (JsonObject r : objects(arr(view, "requirements"))) { + if (inLedger != null && !inLedger.test(str(r, "qualifiedPath"))) continue; + Map row = new LinkedHashMap<>(); + row.put("path", str(r, "address")); + row.put("depth", r.get("depth").getAsInt()); + if (opt(str(r, "title")) != null) row.put("title", str(r, "title")); + row.put("subType", str(r, "subType")); + if (has(r, "level")) row.put("level", r.get("level").getAsInt()); + for (String k : new String[]{"status", "disposition"}) if (opt(str(r, k)) != null) row.put(k, str(r, k)); + List tracked = new ArrayList<>(); + for (JsonElement t : arr(r, "trackedBy")) tracked.add(t.getAsString()); + row.put("trackedBy", tracked); + for (String k : new String[]{"statement", "counterexample", "description"}) { + if (opt(str(r, k)) != null) row.put(k, str(r, k)); + } + List refs = new ArrayList<>(); + Set concerns = new LinkedHashSet<>(); + for (JsonObject l : objects(arr(r, "implementedBy"))) { + refs.add(str(l, "ref")); + if (l.get("resolves").getAsBoolean()) concerns.add(str(l.getAsJsonObject("target"), "kind")); + } + row.put("implementedBy", refs); + row.put("claimedConcerns", new ArrayList<>(concerns)); + rows.add(row); + } + return rows; + } + + @SuppressWarnings("unchecked") + private static List list(Object o) { + return (List) o; + } + + private static String heading(int depth) { + return "#".repeat(Math.min(depth + 2, 6)); + } + + private static String normalize(String s) { + return s.toLowerCase(java.util.Locale.ROOT).replaceAll("[^a-z0-9]", ""); + } + + private static final Pattern WS = Pattern.compile("(?U)\\s+"); + + private static String oneLine(String text) { + return WS.matcher(text).replaceAll(" ").strip(); + } + + private static String headingLine(Map r) { + String path = (String) r.get("path"); + String title = r.containsKey("title") ? oneLine((String) r.get("title")) : ""; + boolean restates = normalize(path.substring(path.lastIndexOf('.') + 1)).equals(normalize(title)); + String label = title.isEmpty() || restates ? "" : " — " + title; + return heading((Integer) r.get("depth")) + " " + path + label; + } + + private static String facts(Map r) { + List parts = new ArrayList<>(); + parts.add("`" + r.get("subType") + "`"); + if (r.containsKey("level")) parts.add("**L" + r.get("level") + "**"); + if (r.containsKey("status")) parts.add("status: `" + r.get("status") + "`"); + if (r.containsKey("disposition")) parts.add("disposition: `" + r.get("disposition") + "`"); + List tracked = list(r.get("trackedBy")); + if (!tracked.isEmpty()) parts.add("tracked: " + String.join(", ", tracked)); + return String.join(" · ", parts); + } + + private static final Pattern HEADING_LINE = Pattern.compile("(?m)^(#{1,6}) "); + + /** One extra {@code #} on every line that starts a heading, capped at h6. */ + private static String demote(String text) { + return HEADING_LINE.matcher(text).replaceAll(m -> + java.util.regex.Matcher.quoteReplacement("#".repeat(Math.min(m.group(1).length() + 1, 6)) + " ")); + } + + private static Map entryOf(Map r, boolean embedded) { + Function line = embedded ? DocsViewPages::demote : s -> s; + Map e = new LinkedHashMap<>(); + e.put("heading", line.apply(headingLine(r))); + e.put("facts", line.apply(facts(r))); + if (r.containsKey("statement")) e.put("statement", line.apply((String) r.get("statement"))); + if (r.containsKey("counterexample")) e.put("counterexample", line.apply("**Counterexample:** " + r.get("counterexample"))); + if (r.containsKey("description")) e.put("description", line.apply((String) r.get("description"))); + List impl = list(r.get("implementedBy")); + if (!impl.isEmpty()) { + List quoted = new ArrayList<>(); + for (String c : impl) quoted.add("`" + c + "`"); + e.put("implementedBy", line.apply("**Implemented by:** " + String.join(", ", quoted))); + } + return e; + } + + /** The data {@code requirements/requirements.md.mustache} renders, for a non-empty ledger. */ + public static Map requirementsLedgerData(List> rows, boolean embedded) { + Map d = new LinkedHashMap<>(); + d.put("embedded", embedded); + d.put("count", rows.size()); + d.put("plural", rows.size() == 1 ? "" : "s"); + List> entries = new ArrayList<>(); + for (Map r : rows) entries.add(entryOf(r, embedded)); + d.put("entries", entries); + return d; + } + + // ---- requirements.toon --------------------------------------------------------------- + + private static final List TOON_FIELDS = + List.of("path", "subType", "level", "status", "disposition", "claims", "statement"); + private static final Pattern NUMERIC_LIKE = Pattern.compile("-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?"); + private static final Pattern LEADING_ZERO = Pattern.compile("0[0-9]+"); + private static final Pattern TOON_UNSAFE = Pattern.compile("[:\"\\\\\\[\\]{},\\x00-\\x1f]"); + + /** 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 {@code -} or a control character. */ + public static String toonCell(Object value) { + if (value instanceof Integer) return value.toString(); + String s = (String) value; + boolean safe = !s.isEmpty() && s.equals(s.strip()) + && !s.equals("true") && !s.equals("false") && !s.equals("null") + && !NUMERIC_LIKE.matcher(s).matches() && !LEADING_ZERO.matcher(s).matches() + && !TOON_UNSAFE.matcher(s).find() && !s.startsWith("-"); + if (safe) return s; + StringBuilder out = new StringBuilder("\""); + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + switch (ch) { + case '\\' -> out.append("\\\\"); + case '"' -> out.append("\\\""); + case '\n' -> out.append("\\n"); + case '\r' -> out.append("\\r"); + case '\t' -> out.append("\\t"); + default -> { + if (ch < 0x20) out.append(String.format("\\u%04x", (int) ch)); + else out.append(ch); + } + } + } + return out.append('"').toString(); + } + + /** The data {@code requirements/requirements.toon.mustache} renders: every cell a finished literal. */ + public static Map requirementsToonData(List> rows) { + Map d = new LinkedHashMap<>(); + d.put("count", rows.size()); + d.put("fields", "{" + String.join(",", TOON_FIELDS) + "}"); + List> out = new ArrayList<>(); + for (Map r : rows) { + List cells = new ArrayList<>(); + cells.add(toonCell(r.get("path"))); + cells.add(toonCell(r.get("subType"))); + cells.add(toonCell(r.containsKey("level") ? r.get("level") : "")); + cells.add(toonCell(r.getOrDefault("status", ""))); + cells.add(toonCell(r.getOrDefault("disposition", ""))); + cells.add(toonCell(String.join(" ", list(r.get("implementedBy"))))); + cells.add(toonCell(r.getOrDefault("statement", ""))); + Map row = new LinkedHashMap<>(); + row.put("line", String.join(",", cells)); + out.add(row); + } + d.put("rows", out); + return d; + } + + // ---- agent/requirements.md ----------------------------------------------------------- + + private record Claim(String path, String subType, Integer level, String status, String statement) {} + + /** Claimed node to the requirements that claim it, sorted by the node's id. A claim that does + * not resolve is left out, as {@code meta verify} is what reports it. */ + private static List>> nodeIndex(JsonObject view, Predicate inLedger) { + Map head = new TreeMap<>(); + Map> claims = new TreeMap<>(); + for (JsonObject r : objects(arr(view, "requirements"))) { + if (inLedger != null && !inLedger.test(str(r, "qualifiedPath"))) continue; + for (JsonObject link : objects(arr(r, "implementedBy"))) { + if (!link.get("resolves").getAsBoolean()) continue; + JsonObject target = link.getAsJsonObject("target"); + String id = str(target, "id"); + head.putIfAbsent(id, new String[]{id, str(target, "kind")}); + claims.computeIfAbsent(id, k -> new ArrayList<>()).add(new Claim( + str(r, "address"), str(r, "subType"), has(r, "level") ? r.get("level").getAsInt() : null, + opt(str(r, "status")), opt(str(r, "statement")))); + } + } + List>> out = new ArrayList<>(); + for (Map.Entry e : head.entrySet()) out.add(Map.entry(e.getValue(), claims.get(e.getKey()))); + return out; + } + + /** The data {@code agent/requirements.md.mustache} renders; null for a model declaring no + * requirements, which gets no page. {@code renderLedger} renders the ledger template from its data. */ + public static Map agentRequirementsPageData( + JsonObject view, Predicate inLedger, Function, String> renderLedger) { + List> rows = requirementRows(view, inLedger); + if (rows.isEmpty()) return null; + List>> index = nodeIndex(view, inLedger); + Map stated = new TreeMap<>(); + for (Map.Entry> e : index) { + for (Claim c : e.getValue()) if (c.statement() != null) stated.put(c.path(), c); + } + List> statements = new ArrayList<>(); + for (Map.Entry e : stated.entrySet()) { + Map s = new LinkedHashMap<>(); + s.put("path", e.getKey()); + s.put("subType", e.getValue().subType()); + s.put("statement", oneLine(e.getValue().statement()).replace("|", "\\|")); + statements.add(s); + } + List> nodes = new ArrayList<>(); + for (Map.Entry> e : index) { + List cells = new ArrayList<>(); + for (Claim c : e.getValue()) { + String level = c.level() == null ? "" : " L" + c.level(); + String status = c.status() == null ? "" : " (" + c.status() + ")"; + cells.add("`" + c.path() + "`" + level + status); + } + Map n = new LinkedHashMap<>(); + n.put("address", e.getKey()[0]); + n.put("concern", e.getKey()[1]); + n.put("claims", String.join("
", cells)); + nodes.add(n); + } + Map d = new LinkedHashMap<>(); + d.put("generatedMarker", AGENT_PAGE_MARKER); + d.put("hasNodeIndex", !index.isEmpty()); + d.put("nodeIndex", nodes); + d.put("hasStatements", !statements.isEmpty()); + d.put("statements", statements); + d.put("ledger", stripTrailingNewlines(renderLedger.apply(requirementsLedgerData(rows, true)))); + return d; + } + + public static String stripTrailingNewlines(String s) { + int end = s.length(); + while (end > 0 && s.charAt(end - 1) == '\n') end--; + return s.substring(0, end); + } + + /** The text ending with exactly one of its own line breaks; text that ends without one is returned as is. */ + public static String keepOneTrailingNewline(String s) { + int end = s.length(); + while (end > 1 && s.charAt(end - 1) == '\n' && s.charAt(end - 2) == '\n') end--; + return s.substring(0, end); + } + + // ---- schema ------------------------------------------------------------------------ + + private static String storageKey(String name, String schema) { + return schema.isEmpty() ? name : schema + "." + name; + } + + private static List strings(JsonArray a) { + List out = new ArrayList<>(); + for (JsonElement e : a) out.add(e.getAsString()); + return out; + } + + /** The rows layer of the schema page, read off the view's storage ({@code expected/rows/schema.json}). */ + public static Map schemaRows(JsonObject view) { + JsonObject storage = view.getAsJsonObject("storage"); + Map declared = new TreeMap<>(); + List> tables = new ArrayList<>(); + for (JsonObject t : objects(arr(storage, "tables"))) { + declared.put(storageKey(str(t, "name"), str(t, "schema")), str(t.getAsJsonObject("declaredBy"), "id")); + Map row = new LinkedHashMap<>(); + row.put("name", str(t, "name")); + if (!str(t, "schema").isEmpty()) row.put("schema", str(t, "schema")); + if (!str(t, "description").isEmpty()) row.put("description", str(t, "description")); + row.put("primaryKey", strings(arr(t, "primaryKey"))); + List> columns = new ArrayList<>(); + for (JsonObject c : objects(arr(t, "columns"))) { + Map col = new LinkedHashMap<>(); + col.put("name", str(c, "name")); + col.put("nullable", c.get("nullable").getAsBoolean()); + if (!str(c, "identity").isEmpty()) col.put("identity", str(c, "identity")); + if (!str(c, "description").isEmpty()) col.put("description", str(c, "description")); + columns.add(col); + } + row.put("columns", columns); + List> fks = new ArrayList<>(); + for (JsonObject f : objects(arr(t, "foreignKeys"))) { + Map fk = new LinkedHashMap<>(); + fk.put("columns", strings(arr(f, "columns"))); + fk.put("refTable", str(f, "refTable")); + fk.put("refColumns", strings(arr(f, "refColumns"))); + fks.add(fk); + } + row.put("foreignKeys", fks); + tables.add(row); + } + List> views = new ArrayList<>(); + for (JsonObject v : objects(arr(storage, "views"))) { + declared.put(storageKey(str(v, "name"), str(v, "schema")), str(v.getAsJsonObject("declaredBy"), "id")); + Map row = new LinkedHashMap<>(); + row.put("name", str(v, "name")); + if (!str(v, "schema").isEmpty()) row.put("schema", str(v, "schema")); + views.add(row); + } + Map out = new LinkedHashMap<>(); + out.put("tables", tables); + out.put("views", views); + out.put("declaredBy", new LinkedHashMap<>(declared)); + return out; + } + + /** Every member of every node, by id. */ + private static Map membersById(JsonObject view) { + Map out = new LinkedHashMap<>(); + for (JsonObject n : objects(arr(view, "nodes"))) for (JsonObject g : objects(arr(n, "memberGroups"))) { + for (JsonObject m : objects(arr(g, "members"))) visit(m, out); + } + return out; + } + + private static void visit(JsonObject m, Map out) { + out.put(str(m, "id"), m); + for (JsonObject g : objects(arr(m, "memberGroups"))) for (JsonObject c : objects(arr(g, "members"))) visit(c, out); + } + + private static List directMembers(JsonObject n, String type) { + for (JsonObject g : objects(arr(n, "memberGroups"))) if (type.equals(str(g, "type"))) return objects(arr(g, "members")); + return List.of(); + } + + private static JsonObject attr(JsonObject owner, String name) { + for (JsonObject a : objects(arr(owner, "attrs"))) if (name.equals(str(a, "name"))) return a; + return null; + } + + private static JsonElement attrValue(JsonObject owner, String name) { + JsonObject a = attr(owner, name); + return a == null || !a.has("value") ? null : a.get("value"); + } + + /** A string attribute as a page prints it: a resolved reference by its link's label, anything else as its text. */ + private static String attrText(JsonObject owner, String name) { + JsonObject a = attr(owner, name); + if (a == null || !a.has("value") || !a.get("value").isJsonPrimitive() || !a.get("value").getAsJsonPrimitive().isString()) return null; + String text = a.get("value").getAsString(); + JsonArray values = arr(a, "values"); + if (values.size() > 0 && values.get(0).isJsonObject()) { + JsonElement link = values.get(0).getAsJsonObject().get("link"); + if (link != null && link.isJsonObject() && !link.getAsJsonObject().get("unresolved").getAsBoolean()) { + text = str(link.getAsJsonObject(), "label"); + } + } + return text.isEmpty() ? null : text; + } + + private static String cols(List names) { + if (names.isEmpty()) return NO_VALUE; + List q = new ArrayList<>(); + for (String c : names) q.add("`" + c + "`"); + return String.join(", ", q); + } + + private static String keyCell(JsonObject table, String column) { + List pk = strings(arr(table, "primaryKey")); + List roles = new ArrayList<>(); + if (pk.contains(column)) roles.add(pk.size() > 1 ? "PK (composite)" : "PK"); + for (JsonObject f : objects(arr(table, "foreignKeys"))) { + if (strings(arr(f, "columns")).contains(column)) { + roles.add("FK → `" + str(f, "refTable") + "`"); + break; + } + } + return String.join(" · ", roles); + } + + /** The lineage text of a view column, from its field's {@code origin.*} member. */ + private static String lineageOf(JsonObject field) { + if (field == null) return null; + List origins = directMembers(field, TYPE_ORIGIN); + if (origins.isEmpty()) return null; + JsonObject origin = origins.get(0); + String via = attrText(origin, "via"); + String of = attrText(origin, "of"); + String viaPart = via == null ? "" : " via `" + via + "`"; + switch (str(origin, "subType")) { + case "passthrough": { + String from = attrText(origin, "from"); + return "passthrough from `" + (from == null ? "?" : from) + "`" + viaPart; + } + case "aggregate": { + String agg = attrText(origin, "agg"); + return "`" + (agg == null ? "?" : agg) + "`" + (of == null ? "" : " of `" + of + "`") + viaPart; + } + case "first": { + String orderBy = attrText(origin, "orderBy"); + return "first" + (of == null ? "" : " `" + of + "`") + viaPart + + (orderBy == null ? "" : " ordered by `" + orderBy + "`"); + } + case "computed": + return "computed from a declared `@expr`"; + default: + return "`origin." + str(origin, "subType") + "`"; + } + } + + private static String cardinalityPhrase(JsonElement cardinality, String through) { + String c = cardinality != null && cardinality.isJsonPrimitive() ? cardinality.getAsString() : null; + if ("many".equals(c)) return through != null ? "many-to-many" : "one-to-many"; + if ("one".equals(c)) return "many-to-one"; + return "cardinality not declared"; + } + + /** + * The data {@code agent/schema.md.mustache} renders for the model-only page, built from the view + * alone. {@code hasMigrate}: the project chose a {@code meta migrate} dialect. Null when the model + * declares no table and no view: no page. {@code inScope} keeps only the objects that are the + * project's own (null keeps every object): a dependency's object is not the project's schema. + */ + public static Map agentSchemaPageData(JsonObject view, boolean hasMigrate, Predicate inScope) { + JsonObject storage = view.getAsJsonObject("storage"); + Predicate scoped = inScope == null ? id -> true : inScope; + List tables = new ArrayList<>(); + for (JsonObject t : objects(arr(storage, "tables"))) if (scoped.test(str(t.getAsJsonObject("declaredBy"), "id"))) tables.add(t); + List views = new ArrayList<>(); + for (JsonObject v : objects(arr(storage, "views"))) if (scoped.test(str(v.getAsJsonObject("declaredBy"), "id"))) views.add(v); + if (tables.isEmpty() && views.isEmpty()) return null; + Map members = membersById(view); + List byOrder = new ArrayList<>(objects(arr(view, "nodes"))); + byOrder.sort(Comparator.comparingInt(n -> n.get("order").getAsInt())); + + List> tableData = new ArrayList<>(); + for (JsonObject t : tables) { + List columns = objects(arr(t, "columns")); + List described = new ArrayList<>(); + for (JsonObject c : columns) if (!str(c, "description").isEmpty()) described.add(c); + List fks = new ArrayList<>(); + for (JsonObject f : objects(arr(t, "foreignKeys"))) { + fks.add(cols(strings(arr(f, "columns"))) + " → `" + str(f, "refTable") + "`(" + cols(strings(arr(f, "refColumns"))) + ")"); + } + Map td = new LinkedHashMap<>(); + td.put("heading", "`" + storageKey(str(t, "name"), str(t, "schema")) + "`"); + td.put("tableDeclaredBy", str(t.getAsJsonObject("declaredBy"), "id")); + if (!str(t, "description").isEmpty()) td.put("tableDescription", oneLine(str(t, "description"))); + List> cd = new ArrayList<>(); + for (JsonObject c : columns) { + JsonObject field = has(c, "field") ? c.getAsJsonObject("field") : null; + Map col = new LinkedHashMap<>(); + col.put("name", str(c, "name")); + col.put("fieldCell", field == null ? "" : "`" + (members.containsKey(str(field, "id")) ? str(members.get(str(field, "id")), "name") : "") + "`"); + col.put("declaredCell", field == null ? "" : "`" + str(field, "kind") + "`"); + col.put("sqlTypeCell", ""); + col.put("nullCell", c.get("nullable").getAsBoolean() ? "yes" : "no"); + col.put("defaultCell", ""); + col.put("keyCell", keyCell(t, str(c, "name"))); + cd.add(col); + } + td.put("columns", cd); + td.put("hasDescribed", !described.isEmpty()); + List> dd = new ArrayList<>(); + for (JsonObject c : described) { + Map d = new LinkedHashMap<>(); + d.put("name", str(c, "name")); + d.put("text", oneLine(str(c, "description"))); + dd.add(d); + } + td.put("described", dd); + td.put("hasIndexes", false); + td.put("indexes", new ArrayList<>()); + td.put("hasForeignKeys", !fks.isEmpty()); + td.put("foreignKeys", fks); + td.put("hasChecks", false); + td.put("checks", new ArrayList<>()); + tableData.add(td); + } + + List> viewData = new ArrayList<>(); + for (JsonObject v : views) { + List> lineage = new ArrayList<>(); + for (JsonObject c : objects(arr(v, "columns"))) { + JsonObject field = has(c, "field") ? members.get(str(c.getAsJsonObject("field"), "id")) : null; + String text = lineageOf(field); + if (text == null) continue; + Map l = new LinkedHashMap<>(); + l.put("column", str(c, "name")); + l.put("text", text); + lineage.add(l); + } + Map vd = new LinkedHashMap<>(); + vd.put("heading", "`" + storageKey(str(v, "name"), str(v, "schema")) + "`"); + vd.put("viewDeclaredBy", str(v.getAsJsonObject("declaredBy"), "id")); + vd.put("hasLineage", !lineage.isEmpty()); + vd.put("lineage", lineage); + viewData.add(vd); + } + + // Every relationship as written, in declaration order of its object. + List relationships = new ArrayList<>(); + for (JsonObject n : byOrder) { + if (!TYPE_OBJECT.equals(str(n, "type")) || !scoped.test(str(n, "id"))) continue; + for (JsonObject rel : directMembers(n, TYPE_RELATIONSHIP)) { + String through = attrText(rel, "through"); + String onDelete = attrText(rel, "onDelete"); + String objectRef = attrText(rel, "objectRef"); + List parts = new ArrayList<>(); + parts.add("`" + str(n, "id") + "." + str(rel, "name") + "`"); + parts.add("`" + str(rel, "subType") + "`"); + parts.add(cardinalityPhrase(attrValue(rel, "cardinality"), through) + " → `" + (objectRef == null ? "?" : objectRef) + "`"); + if (through != null) parts.add("through `" + through + "`"); + if (onDelete != null) parts.add("on delete `" + onDelete + "`"); + relationships.add(String.join(" · ", parts)); + } + } + + // Every enum field of a table-backed object, in declaration order of its object. + Set tableBacked = new LinkedHashSet<>(); + for (JsonObject t : tables) for (JsonObject o : objects(arr(t, "objects"))) tableBacked.add(str(o, "id")); + List> enums = new ArrayList<>(); + for (JsonObject n : byOrder) { + if (!tableBacked.contains(str(n, "id"))) continue; + for (JsonObject f : directMembers(n, TYPE_FIELD)) { + if (!SUBTYPE_ENUM.equals(str(f, "subType"))) continue; + JsonElement values = attrValue(f, "values"); + List list = new ArrayList<>(); + if (values != null && values.isJsonArray()) for (JsonElement v : values.getAsJsonArray()) list.add(jsString(v)); + if (list.isEmpty()) continue; + JsonElement intMap = attrValue(f, "intValueMap"); + String storageText; + if (intMap != null && intMap.isJsonObject()) { + List pairs = new ArrayList<>(); + for (String m : list) { + JsonElement v = intMap.getAsJsonObject().get(m); + pairs.add(m + "=" + (v == null ? "undefined" : jsString(v))); + } + storageText = "int-backed (" + String.join(", ", pairs) + ")"; + } else { + storageText = "string-backed"; + } + List quoted = new ArrayList<>(); + for (String m : list) quoted.add("`" + m + "`"); + Map e = new LinkedHashMap<>(); + e.put("field", str(n, "id") + "." + str(f, "name")); + e.put("members", String.join(", ", quoted)); + e.put("storage", storageText); + enums.add(e); + } + } + + boolean anyDescription = false; + for (JsonObject t : tables) { + if (!str(t, "description").isEmpty()) anyDescription = true; + for (JsonObject c : objects(arr(t, "columns"))) if (!str(c, "description").isEmpty()) anyDescription = true; + } + boolean reportView = false; + for (JsonObject v : views) for (JsonObject o : objects(arr(v, "objects"))) if (KIND_REPORT.equals(str(o, "kind"))) reportView = true; + + Map d = new LinkedHashMap<>(); + d.put("generatedMarker", AGENT_PAGE_MARKER); + d.put("physical", false); + d.put("dialect", ""); + d.put("hasMigrate", hasMigrate); + d.put("descriptionNudge", !anyDescription && !tables.isEmpty()); + d.put("hasTables", !tableData.isEmpty()); + d.put("tables", tableData); + d.put("hasViews", !viewData.isEmpty()); + d.put("hasReportView", reportView); + d.put("views", viewData); + d.put("hasRelationships", !relationships.isEmpty()); + d.put("relationships", relationships); + d.put("hasEnums", !enums.isEmpty()); + d.put("enums", enums); + return d; + } + + /** {@code String(v)} of a JSON scalar as JavaScript prints it. */ + private static String jsString(JsonElement v) { + if (v.isJsonPrimitive()) { + JsonPrimitive p = v.getAsJsonPrimitive(); + return p.getAsString(); + } + return v.toString(); + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java new file mode 100644 index 0000000000..ee30218b92 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java @@ -0,0 +1,64 @@ +package com.metaobjects.generator; + +// Eject note (ADR-0034 Amendment 8): `mvn metaobjects:eject -Dnames=agent-docs` copies this file. +// What there is to emit (the page data) and the templates stay in com.metaobjects.docs.pages and on the +// classpath, so the copy can change where the pages go and how they are laid out, and a project that wants +// other page text puts a same-path template earlier on the classpath or names a `templateDir`. +import com.google.gson.JsonObject; +import com.metaobjects.config.MigrateSettings; +import com.metaobjects.config.SourceResolver; +import com.metaobjects.docs.pages.DocsPagesEmitter; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.generator.FileEmittingGenerator; +import com.metaobjects.loader.MetaDataLoader; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * {@code agent-docs}: pages written for a coding agent working in the project, rendered from the + * shared {@code templates/agent/} Mustache pages over the model's docs view: {@code agent/requirements.md} + * (the node index and the ledger) and the model-only {@code agent/schema.md} (tables, views, + * relationships and enums, without the SQL types, defaults, indexes and checks the model cannot know). + * {@code agent/ui.md} stays a TypeScript page. No requirement, no requirement page; no table and no + * view, no schema page. + * + *

Args: {@code outputDir} (required), {@code subDir} (the directory under it the pages land in, + * default {@code agent}; empty writes them at its root) and {@code templateDir} (a directory holding + * {@code agent/.mustache} and {@code requirements/.mustache} overrides). The schema page says to change the schema with + * {@code meta migrate} when the project's {@code .metaobjects/config.json} sets {@code migrate.dialect}. + * Give it an {@code outputDir} that holds generated files only.

+ */ +public class AgentDocsGenerator extends FileEmittingGenerator { + + /** Arg: the directory under {@code outputDir} the pages land in, in place of {@code agent}. */ + public static final String ARG_SUB_DIR = "subDir"; + + /** Arg: a directory holding {@code agent/.mustache} that win over the packaged templates. */ + public static final String ARG_TEMPLATE_DIR = "templateDir"; + + @Override + protected List generate(MetaDataLoader loader) { + String subDir = getArg(ARG_SUB_DIR, DocsPagesEmitter.DEFAULT_AGENT_DIR); + Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; + JsonObject view = DocsView.build(loader.getRoot()); + List files = new ArrayList<>(); + for (Map.Entry page : DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, + DocsPagesEmitter.inLedger(loader), DocsPagesEmitter.inScope(loader)).entrySet()) { + files.add(new EmittedFile(page.getKey(), page.getValue())); + } + return files; + } + + /** The project chose a {@code meta migrate} dialect: its config sets {@code migrate.dialect}. */ + private static boolean choseMigrateDialect(MetaDataLoader loader) { + MigrateSettings settings = MigrateSettings.of(loader.getRoot()); + if (settings.getDialect() != null) return true; + if (loader.getSourceURIs() == null) return false; + Optional found = SourceResolver.discoverMigrateSettings(loader.getSourceURIs()); + return found.isPresent() && found.get().getDialect() != null; + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java new file mode 100644 index 0000000000..5aa79ee1ed --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java @@ -0,0 +1,47 @@ +package com.metaobjects.generator; + +// Eject note (ADR-0034 Amendment 8): `mvn metaobjects:eject -Dnames=requirements` copies this file. +// What there is to emit (the page data) and the template stay in com.metaobjects.docs.pages and on the +// classpath, so the copy can change where the page goes and how it is laid out, and a project that wants +// other page text puts a same-path template earlier on the classpath or names a `templateDir`. +import com.google.gson.JsonObject; +import com.metaobjects.docs.pages.DocsPagesEmitter; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.generator.FileEmittingGenerator; +import com.metaobjects.loader.MetaDataLoader; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * {@code requirements}: the requirement ledger as {@code requirements.toon}, for tools, rendered from + * the shared {@code templates/requirements/} Mustache page over the model's docs view. People read the + * ledger in the explorer ({@code docs-site}). A model that declares no {@code requirement.*} node + * gets no file. + * + *

Args: {@code outputDir} (required), {@code subDir} (where under it the page lands, default empty: + * the root) and {@code templateDir} (a directory holding {@code requirements/.mustache} + * overrides). Give it an {@code outputDir} that holds generated files only.

+ */ +public class RequirementsGenerator extends FileEmittingGenerator { + + /** Arg: where under {@code outputDir} the page lands. */ + public static final String ARG_SUB_DIR = "subDir"; + + /** Arg: a directory holding {@code requirements/.mustache} that win over the packaged templates. */ + public static final String ARG_TEMPLATE_DIR = "templateDir"; + + @Override + protected List generate(MetaDataLoader loader) { + String subDir = getArg(ARG_SUB_DIR, ""); + Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; + JsonObject view = DocsView.build(loader.getRoot()); + List files = new ArrayList<>(); + for (Map.Entry page : DocsPagesEmitter.requirementsPages(view, subDir, templateDir, DocsPagesEmitter.inLedger(loader)).entrySet()) { + files.add(new EmittedFile(page.getKey(), page.getValue())); + } + return files; + } +} diff --git a/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/requirements.md.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/requirements.md.mustache new file mode 100644 index 0000000000..cb7cba06cb --- /dev/null +++ b/server/java/codegen-base/src/main/resources/metaobjects/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/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache new file mode 100644 index 0000000000..ad91a93c2f --- /dev/null +++ b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache @@ -0,0 +1,123 @@ +{{{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. +{{#hasMigrate}} +- 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. +{{/hasMigrate}} +{{^hasMigrate}} +- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +{{/hasMigrate}} +- `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 {{#hasMigrate}}`meta migrate`{{/hasMigrate}}{{^hasMigrate}}`meta schema`{{/hasMigrate}} 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/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.md.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.md.mustache new file mode 100644 index 0000000000..a200094478 --- /dev/null +++ b/server/java/codegen-base/src/main/resources/metaobjects/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/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.toon.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.toon.mustache new file mode 100644 index 0000000000..cae64ef896 --- /dev/null +++ b/server/java/codegen-base/src/main/resources/metaobjects/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/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java index 7bf774c180..2109e20b5e 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java @@ -62,10 +62,10 @@ public void modelScriptIsTypeScriptsBytes() throws Exception { Map.of("explorer-head.mustache", ""), expectedView("shop")); // explorerModelScript({ title: "Shop 
", footer: "v1", texts, templates, view }) // in @metaobjectsdev/docs-site, over the same shop view, gives this stamp and these bytes. - assertEquals("05b57283a47416e2", m.stamp()); - assertEquals(50657, m.script().length()); - assertEquals("02f2d4321101c0ab9fa9e22db542ff8f71f1e952748e8f894d388bd43feeb6bc", sha256(m.script())); - assertEquals("window.MO_STAMP = \"05b57283a47416e2\";\n", ExplorerSite.stampScript(m.stamp())); + assertEquals("33fd741544d5a480", m.stamp()); + assertEquals(55371, m.script().length()); + assertEquals("c649aa99ef4c570149d6ce06f102738524db766915829a889b39f884af061070", sha256(m.script())); + assertEquals("window.MO_STAMP = \"33fd741544d5a480\";\n", ExplorerSite.stampScript(m.stamp())); } @Test diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java new file mode 100644 index 0000000000..fd350feb3d --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java @@ -0,0 +1,151 @@ +package com.metaobjects.docs.pages; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.loader.DirectorySource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import org.junit.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * The docs page corpus ({@code fixtures/docs-page-conformance/}): for each case the model in + * {@code input/} is loaded, its docs view is built with no verify ledger, manifest or routes, and + * the builders over that view must reproduce, in order, the rows ({@code expected/rows/}), the page + * data ({@code expected/data/}) and the page bytes, over exactly the expected file set. The + * TypeScript generators are the source of the expected bytes. + */ +public class DocsPageConformanceTest { + + private static final Gson GSON = new Gson(); + + private static Path corpus() { + for (Path p = Path.of("").toAbsolutePath(); p != null; p = p.getParent()) { + Path c = p.resolve("fixtures/docs-page-conformance/cases"); + if (Files.isDirectory(c)) return c; + } + throw new IllegalStateException("fixtures/docs-page-conformance/cases not found above " + Path.of("").toAbsolutePath()); + } + + private static JsonObject viewOf(Path input, String name) { + LoaderOptions opts = LoaderOptions.create(false, false, true); + MetaDataLoader loader = new MetaDataLoader(opts, MetaDataLoader.SUBTYPE_MANUAL, "docs_page_" + name.replace('-', '_')); + loader.init(); + // Top level only: the case's .metaobjects/config.json is project state, not metadata. + loader.load(new DirectorySource(input, new DirectorySource.Options().setRecurse(false)).expandToList()); + assertTrue(name + ": expected a clean strict load, got: " + loader.getErrors(), loader.getErrors().isEmpty()); + return DocsView.build(loader.getRoot()); + } + + /** The case chose a {@code meta migrate} dialect: its config sets {@code migrate.dialect}. */ + private static boolean choseMigrateDialect(Path input) throws IOException { + Path config = input.resolve(".metaobjects/config.json"); + if (!Files.isRegularFile(config)) return false; + JsonObject root = JsonParser.parseString(Files.readString(config, StandardCharsets.UTF_8)).getAsJsonObject(); + return root.has("migrate") && root.getAsJsonObject("migrate").has("dialect"); + } + + private static Map expectedOf(Path dir) throws IOException { + Map out = new TreeMap<>(); + if (!Files.isDirectory(dir)) return out; + try (Stream s = Files.walk(dir)) { + for (Path p : s.filter(Files::isRegularFile).toList()) { + out.put(dir.relativize(p).toString().replace('\\', '/'), Files.readString(p, StandardCharsets.UTF_8)); + } + } + return out; + } + + private static void assertJson(String what, String expected, Object actual) { + assertEquals(what, JsonParser.parseString(expected), GSON.toJsonTree(actual)); + } + + private static List cases() throws IOException { + List out = new ArrayList<>(); + try (Stream s = Files.list(corpus())) { + s.filter(Files::isDirectory).map(p -> p.getFileName().toString()).sorted().forEach(out::add); + } + return out; + } + + @Test + public void everyCaseReproducesRowsDataAndBytes() throws IOException { + List names = cases(); + assertTrue("the corpus is not empty", !names.isEmpty()); + for (String name : names) { + Path caseDir = corpus().resolve(name); + Path input = caseDir.resolve("input"); + JsonObject view = viewOf(input, name); + boolean migrate = choseMigrateDialect(input); + Map expected = expectedOf(caseDir.resolve("expected")); + + Map actual = new TreeMap<>(); + // 1. rows, 2. page data + List> rows = DocsViewPages.requirementRows(view, null); + if (!rows.isEmpty()) { + assertJson(name + " rows/requirements.json", expected.get("rows/requirements.json"), rows); + assertJson(name + " data/ledger.md.json", expected.get("data/ledger.md.json"), DocsViewPages.requirementsLedgerData(rows, true)); + assertJson(name + " data/requirements.toon.json", expected.get("data/requirements.toon.json"), DocsViewPages.requirementsToonData(rows)); + actual.put("rows/requirements.json", ""); + actual.put("data/ledger.md.json", ""); + actual.put("data/requirements.toon.json", ""); + } + Map agentRequirements = DocsViewPages.agentRequirementsPageData(view, null, ledger -> ""); + if (agentRequirements != null) { + // The ledger is the rendered embedded template; compare the data through the real renderer. + Map pages = DocsPagesEmitter.agentPages(view, migrate, DocsPagesEmitter.DEFAULT_AGENT_DIR, null, null, null); + actual.put("data/agent-requirements.md.json", ""); + assertTrue(name + ": agent/requirements.md written", pages.containsKey("agent/requirements.md")); + } + Map schema = DocsViewPages.agentSchemaPageData(view, migrate, null); + if (schema != null) { + assertJson(name + " rows/schema.json", expected.get("rows/schema.json"), DocsViewPages.schemaRows(view)); + assertJson(name + " data/agent-schema.md.json", expected.get("data/agent-schema.md.json"), schema); + actual.put("rows/schema.json", ""); + actual.put("data/agent-schema.md.json", ""); + } + + // 3. bytes + Map pages = new TreeMap<>(); + pages.putAll(DocsPagesEmitter.requirementsPages(view, "", null, null)); + pages.putAll(DocsPagesEmitter.agentPages(view, migrate, DocsPagesEmitter.DEFAULT_AGENT_DIR, null, null, null)); + actual.putAll(pages); + + // The agent requirements data carries the rendered ledger: check it against the pinned data too. + if (agentRequirements != null) { + Map real = DocsViewPages.agentRequirementsPageData(view, null, + ledger -> renderLedger(ledger)); + assertJson(name + " data/agent-requirements.md.json", expected.get("data/agent-requirements.md.json"), real); + } + + // the SET of files is pinned too: a file one side writes and the other does not is drift + assertEquals(name + ": file set", new TreeSet<>(expected.keySet()), new TreeSet<>(actual.keySet())); + for (Map.Entry page : pages.entrySet()) { + assertEquals(name + ": " + page.getKey(), expected.get(page.getKey()), page.getValue()); + } + } + } + + private static String renderLedger(Map ledgerData) { + return new com.metaobjects.render.Renderer().render(new com.metaobjects.render.RenderRequest( + null, DocsViewPages.REQUIREMENTS_LEDGER_REF, ledgerData, + com.metaobjects.docs.metamodel.MetamodelDocsEmitter.provider(null, DocsPageConformanceTest.class.getClassLoader()), + com.metaobjects.render.Escapers.FORMAT_MARKDOWN, null, null)); + } +} diff --git a/server/java/codegen-kotlin/pom.xml b/server/java/codegen-kotlin/pom.xml index 353e269bc3..548a7b8d2e 100644 --- a/server/java/codegen-kotlin/pom.xml +++ b/server/java/codegen-kotlin/pom.xml @@ -258,6 +258,8 @@ KotlinReportExportGenerator.kt KotlinSharedModelGenerator.kt KotlinMetamodelDocsGenerator.kt + KotlinRequirementsGenerator.kt + KotlinAgentDocsGenerator.kt KotlinEnumEmitter.kt diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistry.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistry.kt index a217768522..3bd9859e25 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistry.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistry.kt @@ -313,6 +313,24 @@ val GENERATOR_REGISTRY: Map = linkedMapOf( factory = ::KotlinMetamodelDocsGenerator, ejectResourcePath = ejectPath("KotlinMetamodelDocsGenerator"), ), + "requirements" to GeneratorInfo( + name = "requirements", + description = "The requirement ledger as requirements.toon, for tools (a shared Mustache template over " + + "the docs view); people read it in the explorer (docs-site). No requirement.* node, no file.", + tier = GeneratorTier.NEUTRAL, + layer = GeneratorLayer.DOCS, + factory = ::KotlinRequirementsGenerator, + ejectResourcePath = ejectPath("KotlinRequirementsGenerator"), + ), + "agent-docs" to GeneratorInfo( + name = "agent-docs", + description = "Pages written for a coding agent: agent/requirements.md and the model-only agent/schema.md " + + "(shared Mustache templates over the docs view; agent/ui.md stays TypeScript-only).", + tier = GeneratorTier.NEUTRAL, + layer = GeneratorLayer.DOCS, + factory = ::KotlinAgentDocsGenerator, + ejectResourcePath = ejectPath("KotlinAgentDocsGenerator"), + ), // Exempt from eject (registry.json): the site builder is engine, and the site is language-neutral, // so Kotlin runs the JVM DocsSiteGenerator itself and writes the same bytes as Java. "docs-site" to GeneratorInfo( diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt new file mode 100644 index 0000000000..2f41db76da --- /dev/null +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt @@ -0,0 +1,51 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.config.MigrateSettings +import com.metaobjects.config.SourceResolver +import com.metaobjects.docs.pages.DocsPagesEmitter +import com.metaobjects.docsview.DocsView +import com.metaobjects.generator.FileEmittingGenerator +import com.metaobjects.generator.FileEmittingGenerator.EmittedFile +import com.metaobjects.loader.MetaDataLoader +import java.nio.file.Path + +/** + * `agent-docs`: pages written for a coding agent working in the project, rendered from the shared + * `templates/agent/` Mustache pages over the model's docs view: `agent/requirements.md` (the node index and + * the ledger) and the model-only `agent/schema.md`. The Kotlin sibling of the JVM `AgentDocsGenerator`: the + * pages are language-neutral, so both write identical bytes. `agent/ui.md` stays a TypeScript page. No + * requirement, no requirement page; no table and no view, no schema page. + * + * This file decides where the pages go; what there is to emit (the page data) and the templates stay in the + * package, so a copy (`mvn metaobjects:eject`) can lay the pages out differently, and a project that wants + * other page text puts a same-path template earlier on the classpath or names a `templateDir`. The schema + * page says to change the schema with `meta migrate` when the project's `.metaobjects/config.json` sets + * `migrate.dialect`. + * + * Args: `outputDir` (required), `subDir` (the directory under it the pages land in, default `agent`; empty + * writes them at its root) and `templateDir` (a directory holding `agent/.mustache` and `requirements/.mustache` overrides). + */ +open class KotlinAgentDocsGenerator : FileEmittingGenerator() { + + override fun generate(loader: MetaDataLoader): List { + val subDir = getArg(ARG_SUB_DIR, DocsPagesEmitter.DEFAULT_AGENT_DIR) + val templateDir: Path? = if (hasArg(ARG_TEMPLATE_DIR)) Path.of(getArg(ARG_TEMPLATE_DIR)) else null + val view = DocsView.build(loader.root) + return DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, + DocsPagesEmitter.inLedger(loader), DocsPagesEmitter.inScope(loader)) + .map { (path, content) -> EmittedFile(path, content) } + } + + /** The project chose a `meta migrate` dialect: its config sets `migrate.dialect`. */ + private fun choseMigrateDialect(loader: MetaDataLoader): Boolean { + if (MigrateSettings.of(loader.root).dialect != null) return true + val uris = loader.sourceURIs ?: return false + val found = SourceResolver.discoverMigrateSettings(uris) + return found.isPresent && found.get().dialect != null + } + + companion object { + const val ARG_SUB_DIR = "subDir" + const val ARG_TEMPLATE_DIR = "templateDir" + } +} diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt new file mode 100644 index 0000000000..30a8996dd7 --- /dev/null +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt @@ -0,0 +1,36 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.docs.pages.DocsPagesEmitter +import com.metaobjects.docsview.DocsView +import com.metaobjects.generator.FileEmittingGenerator +import com.metaobjects.generator.FileEmittingGenerator.EmittedFile +import com.metaobjects.loader.MetaDataLoader +import java.nio.file.Path + +/** + * `requirements`: the requirement ledger as `requirements.toon`, for tools, rendered from the shared + * `templates/requirements/` Mustache page over the model's docs view. The Kotlin sibling of the JVM + * `RequirementsGenerator`: the page is language-neutral, so both write identical bytes. People read the + * ledger in the explorer (`docs-site`). A model that declares no `requirement.*` node gets no file. + * + * This file decides where the page goes; what there is to emit (the page data) and the template stay in + * the package, so a copy (`mvn metaobjects:eject`) can lay the page out differently, and a project that + * wants other page text puts a same-path template earlier on the classpath or names a `templateDir`. + * + * Args: `outputDir` (required), `subDir` (where under it the page lands, default empty: the root) and + * `templateDir` (a directory holding `requirements/.mustache` overrides). + */ +open class KotlinRequirementsGenerator : FileEmittingGenerator() { + + override fun generate(loader: MetaDataLoader): List { + val subDir = getArg(ARG_SUB_DIR, "") + val templateDir: Path? = if (hasArg(ARG_TEMPLATE_DIR)) Path.of(getArg(ARG_TEMPLATE_DIR)) else null + val view = DocsView.build(loader.root) + return DocsPagesEmitter.requirementsPages(view, subDir, templateDir, DocsPagesEmitter.inLedger(loader)).map { (path, content) -> EmittedFile(path, content) } + } + + companion object { + const val ARG_SUB_DIR = "subDir" + const val ARG_TEMPLATE_DIR = "templateDir" + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDependencyImportExclusionTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDependencyImportExclusionTest.kt index b888c8161b..6a75328763 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDependencyImportExclusionTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDependencyImportExclusionTest.kt @@ -69,7 +69,7 @@ class KotlinDependencyImportExclusionTest { KotlinEntityGenerator(), KotlinExposedTableGenerator(), KotlinRelationsGenerator(), KotlinRepositoryGenerator(), KotlinNamesGenerator(), KotlinFilterAllowlistGenerator(), KotlinSpringControllerGenerator(), KotlinReportExportGenerator(), - KotlinStoredProcGenerator(), KotlinExtractorGenerator(), + KotlinStoredProcGenerator(), KotlinExtractorGenerator(), KotlinAgentDocsGenerator(), ) GeneratedFileWriter.beginRun().use { run -> for (gen in generators) { @@ -81,6 +81,14 @@ class KotlinDependencyImportExclusionTest { val files = Files.walk(outDir).use { s -> s.filter { Files.isRegularFile(it) }.toList() } assertTrue(files.any { it.fileName.toString().startsWith("Order") }, "the project's own Order must still generate: $files") + // agent/schema.md documents the project's own storage: the local Order, never an imported table. + val schema = outDir.resolve("agent/schema.md") + assertTrue(Files.isRegularFile(schema), "agent-docs writes the project's schema page: $files") + val schemaBody = Files.readString(schema) + assertTrue("app::Order" in schemaBody, "agent/schema.md names the local Order") + for (imported in listOf("Customer", "Address", "Audited", "acme::common")) { + assertFalse(imported in schemaBody, "agent/schema.md names the imported $imported") + } for (f in files) { val rel = outDir.relativize(f).toString() assertFalse("acme" in rel || "Customer" in rel || "Address" in rel, diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt new file mode 100644 index 0000000000..495e47a860 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt @@ -0,0 +1,167 @@ +package com.metaobjects.generator.kotlin + +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.metaobjects.config.SourceResolver +import com.metaobjects.generator.util.GeneratedFileWriter +import com.metaobjects.loader.FileSource +import com.metaobjects.loader.LoaderOptions +import com.metaobjects.loader.MetaDataLoader +import com.metaobjects.loader.MetaDataSource +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The Kotlin `requirements` and `agent-docs` generators list the project's own ledger: its own + * requirements, and a dependency's only when `requirements.inherit` names that dependency's package. + * The projects and the ledger each must list (`expectLedger`) are the shared + * `fixtures/dependency-conformance` cases every port's loader is held to. A requirement in the + * dependency's artifact that the case's ledger does not hold must appear on neither page. + */ +class KotlinRequirementPagesLedgerTest { + + private val scratch = mutableListOf() + + @AfterTest + fun cleanUp() { + scratch.forEach { it.toFile().deleteRecursively() } + scratch.clear() + } + + private fun tempDir(prefix: String): Path = Files.createTempDirectory(prefix).also { scratch.add(it) } + + private fun corpus(): Path { + var dir: Path? = Paths.get("").toAbsolutePath() + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.parent + return dir!!.resolve("fixtures/dependency-conformance") + } + + private fun case(name: String): JsonObject = + JsonParser.parseString(Files.readString(corpus().resolve("cases.json"))) + .asJsonObject.getAsJsonArray("cases") + .map { it.asJsonObject }.first { it["name"].asString == name } + + private fun write(p: Path, bytes: ByteArray) { + Files.createDirectories(p.parent) + Files.write(p, bytes) + } + + /** Every requirement a case's metadata declares, keyed `::`, with its statement. */ + private fun declaredStatements(case: JsonObject): Map { + val docs = case.getAsJsonObject("tree").entrySet().map { JsonParser.parseString(it.value.asString) } + + case.getAsJsonObject("treeFiles").entrySet().map { + JsonParser.parseString(Files.readString(corpus().resolve(it.value.asString))) + } + val out = mutableMapOf() + fun walk(node: JsonElement, pkg: String?, path: String?) { + if (!node.isJsonObject) return + for ((key, value) in node.asJsonObject.entrySet()) { + if (!value.isJsonObject) continue + val body = value.asJsonObject + val ownPkg = body["package"]?.asString ?: pkg + var childPath = path + if (key.startsWith("requirement.")) { + childPath = if (path == null) body["name"].asString else "$path.${body["name"].asString}" + out["$ownPkg::$childPath"] = body["@statement"].asString + } + body.getAsJsonArray("children")?.forEach { walk(it, ownPkg, childPath) } + } + } + docs.forEach { walk(it, null, null) } + return out + } + + private fun load(case: JsonObject): MetaDataLoader { + val project = tempDir("kreq-ledger-project-") + for ((k, v) in case.getAsJsonObject("tree").entrySet()) write(project.resolve(k), v.asString.toByteArray()) + for ((k, v) in case.getAsJsonObject("treeFiles").entrySet()) { + write(project.resolve(k), Files.readAllBytes(corpus().resolve(v.asString))) + } + write(project.resolve(".metaobjects/config.json"), case.getAsJsonObject("config").toString().toByteArray()) + write(project.resolve(".metaobjects/deps.lock.json"), case.getAsJsonObject("lock").toString().toByteArray()) + + val collection = SourceResolver.resolveCollectionWithDependencies(project) + val deps = collection.dependencies() + val sources = ArrayList(deps.sources()) + collection.ownFiles().forEach { sources.add(FileSource(it)) } + val loader = MetaDataLoader(LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "kreq-ledger") + loader.init() + loader.setDependencies(deps) + loader.load(sources) + return loader + } + + /** The two pages that list requirements, by path; a page the run did not write is absent. */ + private fun pages(loader: MetaDataLoader): Map { + val out = tempDir("kreq-ledger-out-") + GeneratedFileWriter.beginRun().use { run -> + for (gen in listOf(KotlinRequirementsGenerator(), KotlinAgentDocsGenerator())) { + run.attributeTo(gen.javaClass.simpleName) + gen.setArgs(mapOf("outputDir" to out.toString())).execute(loader) + } + } + return listOf("requirements.toon", "agent/requirements.md") + .filter { Files.isRegularFile(out.resolve(it)) } + .associateWith { Files.readString(out.resolve(it)) } + } + + private fun assertPagesListTheLedger(caseName: String) { + val case = case(caseName) + val ledger = case.getAsJsonObject("expectLedger").keySet() + val declared = declaredStatements(case) + assertTrue(declared.keys.containsAll(ledger), "$caseName: the corpus ledger names an undeclared requirement") + val pages = pages(load(case)) + + if (ledger.isEmpty()) { + assertTrue(pages.isEmpty(), "$caseName: an empty ledger writes no requirement page, got ${pages.keys}") + return + } + assertTrue(pages.keys == setOf("requirements.toon", "agent/requirements.md"), "$caseName: ${pages.keys}") + for ((page, text) in pages) { + for ((fqn, statement) in declared) { + if (fqn in ledger) { + assertTrue(statement in text, "$caseName: $page omits the ledger's $fqn") + } else { + assertFalse(statement in text, "$caseName: $page lists $fqn, which the ledger does not hold") + } + } + } + } + + @Test fun `an uninherited dependency's requirements stay off the pages beside the project's own`() = + assertPagesListTheLedger("an-own-requirement-beside-an-uninherited-dependency-ledger-is-the-whole-ledger") + + @Test fun `requirements inherit naming the dependency's package brings its requirements onto the pages`() = + assertPagesListTheLedger("requirements-inherit-naming-the-package-takes-on-its-ledger") + + @Test fun `a wildcard inherit lists no dependency requirement`() = + assertPagesListTheLedger("a-wildcard-inherit-does-not-name-a-package") + + @Test fun `a scope include naming the dependency lists none of its requirements`() = + assertPagesListTheLedger("a-scope-include-naming-the-package-does-not-inherit-its-requirements") + + /** + * `subDir` names the directory the agent pages land in, in place of `agent`, as the TypeScript + * `agentDocsFile({ subDir })`, Python `AgentDocsGenerator(sub_dir=...)` and Rust `agent-docs` + * options do: `llm` writes `llm/schema.md`, never `llm/agent/schema.md`. + */ + @Test fun `subDir replaces the agent directory`() { + val loader = load(case("an-own-requirement-beside-an-uninherited-dependency-ledger-is-the-whole-ledger")) + val out = tempDir("kreq-ledger-subdir-") + GeneratedFileWriter.beginRun().use { run -> + val gen = KotlinAgentDocsGenerator() + run.attributeTo(gen.javaClass.simpleName) + gen.setArgs(mapOf("outputDir" to out.toString(), "subDir" to "llm")).execute(loader) + } + val written = Files.walk(out).use { s -> + s.filter { Files.isRegularFile(it) }.map { out.relativize(it).toString().replace('\\', '/') }.toList().toSet() + } + assertTrue(written == setOf("llm/requirements.md", "llm/schema.md"), "written: $written") + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ReportingInertTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ReportingInertTest.kt index 2dc1fa0bbf..dd2e999afb 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ReportingInertTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ReportingInertTest.kt @@ -113,7 +113,7 @@ class ReportingInertTest { } /** - * Every generator that writes code. `api-docs` writes the api reference, not code, and is + * Every generator that writes code. `agent-docs` writes pages, held to its own test below. `api-docs` writes the api reference, not code, and is * held to the same inertness by [api docs gain exactly the view-backed report's page], which * compares its pages unit by unit. */ @@ -121,7 +121,25 @@ class ReportingInertTest { // which a bare in-memory model does not have. Its bytes are gated by the shared-model corpus. // docs-site documents every node, so it is held to its own line (DocsSiteInert), below. private val codeGenerators get() = GENERATOR_REGISTRY.values.filter { - it.name != "api-docs" && it.name != "shared-model" && it.name != DocsSiteInert.GENERATOR + it.name != "api-docs" && it.name != "agent-docs" && it.name != "shared-model" && it.name != DocsSiteInert.GENERATOR + } + + @Test + fun `agent docs list the view-backed report's view and no sourceless report`() { + // agent-docs writes pages, not code: its schema page lists every table and view, so the served + // report's view is one more entry there, and nothing else moves. + val info = GENERATOR_REGISTRY.getValue("agent-docs") + val without = emit("without", listOf(info)) + val with = emit("with", listOf(info)) + assertEquals(without.keys, with.keys) + val schema = "agent/schema.md" + assertTrue("StoreTotals" in with.getValue(schema), "the served report is not on the schema page") + assertFalse("StoreTotals" in without.getValue(schema), "the schema page names the report without it") + for (report in SOURCELESS_REPORTS) { + assertFalse(with.any { (path, text) -> report in path || report in text }, "$report is on an agent page") + } + val differing = without.keys.filter { it != schema && without[it] != with[it] } + assertTrue(differing.isEmpty(), "$differing differ once reporting nodes are declared") } @Test diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java index 8fd278bd95..2a9ccde4d4 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java @@ -12,7 +12,9 @@ import com.metaobjects.generator.apidocs.JavaApiModelBuilder; import com.metaobjects.generator.apidocs.JavaFieldShapes; import com.metaobjects.generator.apidocs.UnitExample; +import com.metaobjects.generator.AgentDocsGenerator; import com.metaobjects.generator.MetamodelDocsGenerator; +import com.metaobjects.generator.RequirementsGenerator; import com.metaobjects.generator.direct.metadata.ai.MetaDataAIDocumentationGenerator; import com.metaobjects.generator.direct.metadata.ai.MetaDataAIDocumentationWriter; import com.metaobjects.generator.direct.metadata.file.json.MetaDataFileJsonSchemaGenerator; @@ -497,6 +499,14 @@ Tier.NATIVE, Layer.DOCS, ejectPath(JavaApiDocsGenerator.class), List.of(), null, + "by provider, rendered from the shared templates/metamodel/ Mustache set " + "(INDEX.md, providers.md, one types/.md per type family). Reads no model objects.", Tier.NEUTRAL, Layer.DOCS, ejectPath(MetamodelDocsGenerator.class)); + register(m, "requirements", RequirementsGenerator.class.getName(), + "The requirement ledger as requirements.toon, for tools (a shared Mustache template over " + + "the docs view); people read it in the explorer (docs-site). No requirement.* node, no file.", + Tier.NEUTRAL, Layer.DOCS, ejectPath(RequirementsGenerator.class)); + register(m, "agent-docs", AgentDocsGenerator.class.getName(), + "Pages written for a coding agent: agent/requirements.md and the model-only agent/schema.md " + + "(shared Mustache templates over the docs view; agent/ui.md stays TypeScript-only).", + Tier.NEUTRAL, Layer.DOCS, ejectPath(AgentDocsGenerator.class)); // Exempt from eject (registry.json): the site builder is engine; what a project changes is the // explorer's theme, which it owns under codegen/docs-site/ and this generator reads from there. register(m, "docs-site", DocsSiteGenerator.class.getName(), diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/DependencyImportExclusionTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/DependencyImportExclusionTest.java index 107fcaca80..dfc8c10780 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/DependencyImportExclusionTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/DependencyImportExclusionTest.java @@ -4,6 +4,7 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.metaobjects.config.DependencySet; +import com.metaobjects.generator.AgentDocsGenerator; import com.metaobjects.generator.Generator; import com.metaobjects.generator.direct.object.javacode.ExtractorCodeGenerator; import com.metaobjects.generator.direct.object.javacode.JavaObjectCodeGenerator; @@ -102,7 +103,7 @@ public void noGeneratorEmitsForAnImportedNode() throws Exception { new SpringNamesGenerator(), new SpringControllerGenerator(), new SpringReportExportGenerator(), new LlmTraceHelperGenerator(), new SpringOutputParserGenerator(), new SpringOutputPromptGenerator(), - new SpringRenderHelperGenerator()); + new SpringRenderHelperGenerator(), new AgentDocsGenerator()); try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { for (Generator gen : generators) { run.attributeTo(gen.getClass().getSimpleName()); @@ -118,6 +119,14 @@ public void noGeneratorEmitsForAnImportedNode() throws Exception { } assertTrue("the project's own Order must still generate: " + files, files.stream().anyMatch(p -> p.getFileName().toString().startsWith("Order"))); + // agent/schema.md documents the project's own storage: the local Order, never an imported table. + Path schema = outDir.resolve("agent/schema.md"); + assertTrue("agent-docs writes the project's schema page: " + files, Files.isRegularFile(schema)); + String schemaBody = Files.readString(schema, StandardCharsets.UTF_8); + assertTrue("agent/schema.md names the local Order", schemaBody.contains("app::Order")); + for (String imported : List.of("Customer", "Address", "Audited", "acme::common")) { + assertFalse("agent/schema.md names the imported " + imported, schemaBody.contains(imported)); + } for (Path f : files) { String rel = outDir.relativize(f).toString(); assertFalse("a file was emitted for an imported node: " + rel, diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReportingInertTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReportingInertTest.java index 3d4966c6cb..d47c5b3189 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReportingInertTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReportingInertTest.java @@ -83,11 +83,13 @@ public class ReportingInertTest extends SharedRegistryTestBase { /** * The files that LIST every unit rather than describe one, by generator stable name: the api - * reference's index and agent page. They differ between the two models by the served report's + * reference's index and agent page, and the agent schema page. They differ between the two models by the served report's * entry, so each is checked to name it and then left out of the byte comparison. */ private static final Map> UNIT_LISTINGS = Map.of( - "api-docs", List.of("api/java/README.md", "api/java/AGENT-API.md")); + "api-docs", List.of("api/java/README.md", "api/java/AGENT-API.md"), + // The agent schema page lists every table and view, and the served report reads one. + "agent-docs", List.of("agent/schema.md")); private static Path model(String variant) { return SpringTestFixtures.findCorpusRoot().getParent() diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratorWritePathTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratorWritePathTest.java index cd6a275700..a3d121c8e6 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratorWritePathTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratorWritePathTest.java @@ -140,7 +140,8 @@ private Map args(Entry e, Path outDir) { /** Generators keyed off model nodes the fitness corpus does not declare, so they write nothing over it. */ private static final List NO_INPUT_IN_CORPUS = - List.of("java-trace-helper", "java-requirement-tests", "kotlin-stored-proc", "kotlin-requirement-tests"); + List.of("java-trace-helper", "java-requirement-tests", "java-requirements", "kotlin-stored-proc", "kotlin-requirements", + "kotlin-requirement-tests"); /** What each run wrote: the files left on disk, and the paths the writer was asked for. */ private record Result(Map disk, Set emitted) {} diff --git a/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java index f7841a89cd..a902e99f5d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java +++ b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java @@ -606,6 +606,12 @@ JsonObject run(JsonElement verifyIn, JsonElement manifest, JsonElement routesIn) view.add("requirements", array(reqs)); view.add("advisories", advisories); view.add("slices", slices(nodes, reqs)); + view.add("storage", DocsViewStorage.build(root, DocsView::children, md -> linkTo(md, md.getName()), (owner, field) -> { + Walked top = canonical.get(owner); + if (top == null) return null; + for (Walked c : top.children) if (c.md == field) return link(c); + return null; + })); return view; } @@ -818,7 +824,7 @@ private static String plainOf(MetaData md) { return pkg.isEmpty() ? nameOf(md) : pkg + PKG + nameOf(md); } - private static boolean isAbstract(MetaData md) { + static boolean isAbstract(MetaData md) { // ADR-0039: own — @isAbstract is a declaration-layer marker, never inherited. return md.hasMetaAttr(MetaData.ATTR_IS_ABSTRACT, false) && Boolean.TRUE.equals(md.getMetaAttr(MetaData.ATTR_IS_ABSTRACT, false).getValue()); diff --git a/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewStorage.java b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewStorage.java new file mode 100644 index 0000000000..7b2b3875c3 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewStorage.java @@ -0,0 +1,446 @@ +package com.metaobjects.docsview; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.metaobjects.MetaData; +import com.metaobjects.database.ColumnNaming; +import com.metaobjects.database.PhysicalNaming; +import com.metaobjects.documentation.DocumentationConstants; +import com.metaobjects.field.MetaField; +import com.metaobjects.field.ObjectField; +import com.metaobjects.identity.MetaIdentity; +import com.metaobjects.identity.ReferenceIdentity; +import com.metaobjects.loader.References; +import com.metaobjects.object.MetaObject; +import com.metaobjects.origin.MetaOrigin; +import com.metaobjects.source.MetaSource; +import com.metaobjects.source.SourceResolution; +import com.metaobjects.validator.MetaValidator; +import com.metaobjects.validator.RequiredValidator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * The docs view's {@code storage} section: the tables and views the model declares, named by this + * port's own naming helpers ({@code docs/features/docs-view.md}, "storage"). The Java port of + * TypeScript's {@code buildStorage} ({@code docs-view/storage.ts}), held to the same bytes by + * {@code fixtures/explorer-conformance/}. + * + *

MODEL-ONLY: a table per concrete object whose primary source is a writable, managed table + * (abstract bases and sourceless values 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 physical facts (SQL type, default, indexes, checks, constraint names, referential actions) + * are {@code null} here; only the TypeScript run fills them.

+ */ +final class DocsViewStorage { + + private DocsViewStorage() {} + + /** A column as the walk finds it, before its field link is attached. */ + private record RawColumn(String name, boolean nullable, String identity, String description) { + RawColumn withNullable(boolean n) { + return new RawColumn(name, n, identity, description); + } + } + + private record Mapped(MetaObject owner, MetaData field) {} + + /** + * @param children the effective structural children of a node (the walk's own accessor) + * @param node the link to a top-level node + * @param member the link to a field as a member of its top-level owner, or null + */ + static JsonObject build(MetaData root, + Function> children, + Function node, + BiFunction member) { + return new Run(children, node, member).build(root); + } + + private static final class Run { + final Function> kids; + final Function node; + final BiFunction member; + + Run(Function> kids, Function node, + BiFunction member) { + this.kids = kids; + this.node = node; + this.member = member; + } + + // ---- model reads ------------------------------------------------------------- + + List fieldsOf(MetaObject obj) { + List out = new ArrayList<>(); + for (MetaData c : kids.apply(obj)) if (c instanceof MetaField f) out.add(f); + return out; + } + + static String description(MetaData md) { + if (!md.hasMetaAttr(DocumentationConstants.DOC_ATTR_DESCRIPTION)) return ""; + Object v = md.getMetaAttr(DocumentationConstants.DOC_ATTR_DESCRIPTION).getValue(); + return v instanceof String s ? s : ""; + } + + static String schemaOf(MetaSource source) { + String s = source.getSchema(); + return s == null ? "" : s; + } + + static boolean isRequired(MetaData field) { + // ADR-0039: resolving, since @required and validator.required may be inherited via extends. + if (field.hasMetaAttr(MetaField.ATTR_REQUIRED) + && Boolean.TRUE.equals(field.getMetaAttr(MetaField.ATTR_REQUIRED).getValue())) return true; + for (MetaData c : field.getChildren(MetaData.class, true)) { + if (MetaValidator.TYPE_VALIDATOR.equals(c.getType()) + && RequiredValidator.SUBTYPE_REQUIRED.equals(c.getSubType())) return true; + } + return false; + } + + static boolean isDerived(MetaData field) { + // ADR-0039 own (category 4): origin.* never inherits (ADR-0029). + return !field.getChildren(MetaOrigin.class, false).isEmpty(); + } + + static boolean isAbstract(MetaData md) { + return DocsView.isAbstract(md); + } + + static boolean hasAttr(MetaData md, String name) { + return md.hasMetaAttr(name); + } + + /** The {@code @discriminator}-bearing ANCESTOR of {@code entity}, or null. */ + static MetaData discriminatorBase(MetaData entity) { + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + for (MetaData a = entity.hasSuperData() ? entity.getSuperData() : null; + a != null && seen.add(a); a = a.hasSuperData() ? a.getSuperData() : null) { + // ADR-0039 sanctioned own: an explicit super-resolution walk reads each ancestor's own attr. + if (a.hasMetaAttr(MetaObject.ATTR_DISCRIMINATOR, false)) return a; + } + return null; + } + + static boolean isTphSubtype(MetaData entity) { + return hasAttr(entity, MetaObject.ATTR_DISCRIMINATOR_VALUE) && discriminatorBase(entity) != null; + } + + static List tphConcreteSubtypes(MetaObject base, List objects) { + List out = new ArrayList<>(); + if (!hasAttr(base, MetaObject.ATTR_DISCRIMINATOR)) return out; + for (MetaObject o : objects) { + if (!isAbstract(o) && hasAttr(o, MetaObject.ATTR_DISCRIMINATOR_VALUE) && discriminatorBase(o) == base) out.add(o); + } + return out; + } + + static List identityFields(MetaIdentity identity) { + List out = new ArrayList<>(); + for (String s : identity.getFields()) { + String t = s.trim(); + if (!t.isEmpty()) out.add(t); + } + return out; + } + + static String columnOf(MetaObject obj, String name) { + MetaField f = obj.findMetaField(name).orElse(null); + return f != null ? ColumnNaming.resolve(f) : ColumnNaming.apply(name, PhysicalNaming.of(obj).columns()); + } + + static boolean isFlattened(MetaField field) { + return ObjectField.SUBTYPE_OBJECT.equals(field.getSubType()) + && hasAttr(field, MetaField.ATTR_STORAGE) + && ObjectField.STORAGE_FLATTENED.equals(field.getMetaAttr(MetaField.ATTR_STORAGE).getValue()); + } + + static RawColumn rawColumn(MetaData field, boolean isPk, String generation, String name) { + String identity = isPk && (MetaIdentity.GENERATION_INCREMENT.equals(generation) + || MetaIdentity.GENERATION_UUID.equals(generation)) ? generation : ""; + return new RawColumn(name, !isPk && !isRequired(field), identity, description(field)); + } + + List fieldColumns(MetaField field, boolean isPk, String generation) { + if (isFlattened(field)) { + MetaObject target = References.refTarget(field, MetaField.ATTR_OBJECT_REF); + List out = new ArrayList<>(); + if (target == null) return out; + for (MetaField nested : fieldsOf(target)) { + out.add(rawColumn(nested, false, "", ColumnNaming.resolveFlattened(field, nested))); + } + return out; + } + return List.of(rawColumn(field, isPk, generation, ColumnNaming.resolve(field))); + } + + /** The referenced key's columns: an explicit dotted tail on {@code @references}, else the + * target's primary identity (its first field), else {@code id}. */ + static List targetColumns(MetaData ref, MetaObject target) { + String tail = ""; + if (ref.hasMetaAttr(ReferenceIdentity.ATTR_REFERENCES)) { + Object raw = ref.getMetaAttr(ReferenceIdentity.ATTR_REFERENCES).getValue(); + if (raw instanceof String s) tail = References.splitChildTail(s).tail(); + } + List names = new ArrayList<>(); + for (String s : (tail.startsWith(".") ? tail.substring(1) : tail).split(",")) { + String t = s.trim(); + if (!t.isEmpty()) names.add(t); + } + if (names.isEmpty()) { + MetaIdentity identity = target.getPrimaryIdentity(); + List pk = identity != null ? identityFields(identity) : List.of(); + names = List.of(pk.isEmpty() ? "id" : pk.get(0)); + } + List out = new ArrayList<>(); + for (String n : names) out.add(columnOf(target, n)); + return out; + } + + static boolean isRef(MetaData c) { + return MetaIdentity.TYPE_IDENTITY.equals(c.getType()) && ReferenceIdentity.SUBTYPE_REFERENCE.equals(c.getSubType()); + } + + JsonArray foreignKeys(MetaObject entity, List objects, Map tableOf) { + List> refs = new ArrayList<>(); + for (MetaData c : entity.getChildren(MetaData.class, true)) if (isRef(c)) refs.add(Map.entry(entity, c)); + if (hasAttr(entity, MetaObject.ATTR_DISCRIMINATOR)) { + Set baseNames = new HashSet<>(); + for (Map.Entry e : refs) baseNames.add(e.getValue().getName()); + for (MetaObject sub : tphConcreteSubtypes(entity, objects)) { + for (MetaData c : sub.getChildren(MetaData.class, true)) { + if (isRef(c) && !baseNames.contains(c.getName())) refs.add(Map.entry(sub, c)); + } + } + } + JsonArray fks = new JsonArray(); + Set seen = new HashSet<>(); + for (Map.Entry e : refs) { + MetaObject holder = e.getKey(); + MetaData ref = e.getValue(); + // A logical-only reference is no constraint. + if (ref.hasMetaAttr(ReferenceIdentity.ATTR_ENFORCE) + && Boolean.FALSE.equals(ref.getMetaAttr(ReferenceIdentity.ATTR_ENFORCE).getValue())) continue; + MetaObject target = References.refTarget(ref, ReferenceIdentity.ATTR_REFERENCES); + if (target == null) continue; + String refTable = tableOf.get(target); + if (refTable == null || refTable.isEmpty()) continue; + List names = identityFields((MetaIdentity) ref); + if (names.isEmpty()) continue; + List columns = new ArrayList<>(); + for (String n : names) columns.add(columnOf(holder, n)); + List refColumns = targetColumns(ref, target); + // Two subtypes may declare the same column: one constraint. + String sig = refTable + "\0" + String.join("\0", columns) + "\1" + String.join("\0", refColumns); + if (!seen.add(sig)) continue; + JsonObject fk = new JsonObject(); + fk.add("columns", strings(columns)); + fk.addProperty("refTable", refTable); + fk.add("refColumns", strings(refColumns)); + fk.add("name", JsonNull.INSTANCE); + fk.add("onDelete", JsonNull.INSTANCE); + fk.add("onUpdate", JsonNull.INSTANCE); + fks.add(fk); + } + return fks; + } + + static String key(String name, String schema) { + return schema.isEmpty() ? name : schema + "." + name; + } + + static JsonArray strings(List items) { + JsonArray a = new JsonArray(); + for (String s : items) a.add(s); + return a; + } + + // ---- the section ------------------------------------------------------------- + + JsonObject build(MetaData root) { + List objects = new ArrayList<>(); + for (MetaData c : kids.apply(root)) if (c instanceof MetaObject o) objects.add(o); + + // Pass 1: which objects own a table, and which are only a foreign-key target. + List> entities = new ArrayList<>(); + List> targetOnly = new ArrayList<>(); + List> tphMembers = new ArrayList<>(); + for (MetaObject obj : objects) { + MetaData base = discriminatorBase(obj); + if (base != null && (isAbstract(obj) || isTphSubtype(obj))) { + tphMembers.add(Map.entry(obj, base)); + continue; + } + if (isAbstract(obj)) continue; + boolean writable = false; + for (MetaSource s : obj.getSources(true)) if (s.isWritable()) writable = true; + if (!writable) continue; + MetaSource source = SourceResolution.primaryRdbSource(obj); + if (source == null) continue; + // ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. + MetaSource own = null; + for (MetaSource s : obj.getSources(false)) { + if (s.isWritable()) { own = s; break; } + } + if (own != null && own.isUnmanaged()) { + targetOnly.add(Map.entry(obj, source)); + continue; + } + entities.add(Map.entry(obj, source)); + } + Map tableOf = new IdentityHashMap<>(); + for (Map.Entry e : entities) tableOf.put(e.getKey(), e.getValue().getPhysicalName()); + for (Map.Entry e : targetOnly) tableOf.put(e.getKey(), e.getValue().getPhysicalName()); + for (Map.Entry m : tphMembers) { + String name = tableOf.get(m.getValue()); + if (name != null && !tableOf.containsKey(m.getKey())) tableOf.put(m.getKey(), name); + } + + // Every object at each storage key, in declaration order. + Map> atKey = new LinkedHashMap<>(); + for (MetaObject obj : objects) { + MetaSource source = SourceResolution.primaryRdbSource(obj); + if (source == null) continue; + atKey.computeIfAbsent(key(source.getPhysicalName(), schemaOf(source)), k -> new ArrayList<>()).add(obj); + } + + List tables = new ArrayList<>(); + Set keys = new HashSet<>(); + for (Map.Entry e : entities) { + MetaObject entity = e.getKey(); + MetaSource source = e.getValue(); + MetaIdentity identity = entity.getPrimaryIdentity(); + List pkNames = identity != null ? identityFields(identity) : List.of(); + String generation = ""; + if (identity != null && identity.hasMetaAttr(MetaIdentity.ATTR_GENERATION) + && identity.getMetaAttr(MetaIdentity.ATTR_GENERATION).getValue() instanceof String g) generation = g; + List raw = new ArrayList<>(); + for (MetaField field : fieldsOf(entity)) { + if (isDerived(field)) continue; + boolean isPk = pkNames.contains(field.getName()); + raw.addAll(fieldColumns(field, isPk, isPk ? generation : "")); + } + if (hasAttr(entity, MetaObject.ATTR_DISCRIMINATOR)) { + Set existing = new HashSet<>(); + for (RawColumn c : raw) existing.add(c.name()); + Set baseFields = new HashSet<>(); + for (MetaField f : fieldsOf(entity)) baseFields.add(f.getName()); + for (MetaObject sub : tphConcreteSubtypes(entity, objects)) { + for (MetaField field : fieldsOf(sub)) { + if (baseFields.contains(field.getName()) || isDerived(field)) continue; + RawColumn col = rawColumn(field, false, "", ColumnNaming.resolve(field)); + if (existing.contains(col.name())) continue; + // A row of any other subtype stores NULL here. + raw.add(col.withNullable(true)); + existing.add(col.name()); + } + } + } + String schema = schemaOf(source); + String k = key(source.getPhysicalName(), schema); + Map mapping = fieldMap(atKey.get(k)); + JsonArray columns = new JsonArray(); + for (RawColumn c : raw) { + Mapped m = mapping.get(c.name()); + JsonObject col = new JsonObject(); + col.addProperty("name", c.name()); + col.add("field", m == null ? JsonNull.INSTANCE : orNull(member.apply(m.owner(), m.field()))); + col.addProperty("nullable", c.nullable()); + col.addProperty("identity", c.identity()); + col.addProperty("description", c.description()); + col.add("sqlType", JsonNull.INSTANCE); + col.add("default", JsonNull.INSTANCE); + columns.add(col); + } + List pk = new ArrayList<>(); + for (String n : pkNames) pk.add(columnOf(entity, n)); + JsonObject table = new JsonObject(); + table.addProperty("name", source.getPhysicalName()); + table.addProperty("schema", schema); + table.add("declaredBy", node.apply(entity)); + table.add("objects", concreteLinks(atKey.get(k))); + table.addProperty("description", description(entity)); + table.add("primaryKey", strings(pk)); + table.add("columns", columns); + table.add("foreignKeys", foreignKeys(entity, objects, tableOf)); + table.add("indexes", JsonNull.INSTANCE); + table.add("checks", JsonNull.INSTANCE); + tables.add(table); + keys.add(k); + } + + List views = new ArrayList<>(); + for (MetaObject obj : objects) { + if (isAbstract(obj)) continue; + MetaSource source = SourceResolution.primaryRdbSource(obj); + if (source == null || !MetaSource.KIND_VIEW.equals(source.getEffectiveKind())) continue; + String schema = schemaOf(source); + String k = key(source.getPhysicalName(), schema); + if (!keys.add(k)) continue; + JsonArray columns = new JsonArray(); + for (Map.Entry c : fieldMap(atKey.get(k)).entrySet()) { + JsonObject col = new JsonObject(); + col.addProperty("name", c.getKey()); + col.add("field", orNull(member.apply(c.getValue().owner(), c.getValue().field()))); + columns.add(col); + } + JsonObject view = new JsonObject(); + view.addProperty("name", source.getPhysicalName()); + view.addProperty("schema", schema); + view.add("declaredBy", node.apply(obj)); + view.add("objects", concreteLinks(atKey.get(k))); + view.add("columns", columns); + views.add(view); + } + + tables.sort((a, b) -> a.get("name").getAsString().compareTo(b.get("name").getAsString())); + views.sort((a, b) -> a.get("name").getAsString().compareTo(b.get("name").getAsString())); + JsonObject storage = new JsonObject(); + storage.addProperty("physical", false); + storage.addProperty("dialect", ""); + storage.add("tables", array(tables)); + storage.add("views", array(views)); + return storage; + } + + /** The column to declaring field map of a storage key (first writer wins on a shared table). */ + Map fieldMap(List atKey) { + Map map = new LinkedHashMap<>(); + if (atKey == null) return map; + for (MetaObject obj : atKey) { + for (MetaField field : fieldsOf(obj)) { + map.putIfAbsent(ColumnNaming.resolve(field), new Mapped(obj, field)); + } + } + return map; + } + + JsonArray concreteLinks(List atKey) { + JsonArray out = new JsonArray(); + if (atKey != null) for (MetaObject o : atKey) if (!isAbstract(o)) out.add(node.apply(o)); + return out; + } + + static JsonElement orNull(JsonObject o) { + return o == null ? JsonNull.INSTANCE : o; + } + + static JsonArray array(List items) { + JsonArray a = new JsonArray(); + for (JsonObject o : items) a.add(o); + return a; + } + } +} diff --git a/server/python/src/metaobjects/agent_context/agent_docs.py b/server/python/src/metaobjects/agent_context/agent_docs.py index 7551c11ad8..36f9b80752 100644 --- a/server/python/src/metaobjects/agent_context/agent_docs.py +++ b/server/python/src/metaobjects/agent_context/agent_docs.py @@ -14,6 +14,12 @@ from metaobjects.config.neutral_config import chose_migrate_dialect +from .agent_pages import ( + ALWAYS_ON_PATH, + render_agent_pages_section, + wired_agent_pages, + with_agent_pages_section, +) from .scaffold import ( AGENT_CONTEXT_MANIFEST_PATH, Manifest, @@ -123,6 +129,11 @@ def run_agent_docs( # Read from the project config on every run, as TypeScript does at init and refresh. migration = chose_migrate_dialect(out) assembled = materialize(tree, servers, clients, docs_ref_for_version(version), migration) + if ALWAYS_ON_PATH in assembled: + # The always-on file points at the agent pages only when the project's last `gen` wrote one. + template = (tree.root / "files" / str(tree.manifest["agentPagesTemplate"])).read_text(encoding="utf-8") + section = render_agent_pages_section(template, wired_agent_pages(out)) + assembled[ALWAYS_ON_PATH] = with_agent_pages_section(assembled[ALWAYS_ON_PATH], section) decision = plan_scaffold( assembled=assembled, prior=prior, diff --git a/server/python/src/metaobjects/agent_context/agent_pages.py b/server/python/src/metaobjects/agent_context/agent_pages.py new file mode 100644 index 0000000000..a7ee816384 --- /dev/null +++ b/server/python/src/metaobjects/agent_context/agent_pages.py @@ -0,0 +1,77 @@ +"""The always-on file's pointer at the pages ``metaobjects gen`` writes for a coding agent. + +The Python side of TypeScript's ``agent-pages.ts``; ``fixtures/agent-pages-pointer/`` pins both. +The pointer is there only when the pages are: what is wired is read off the committed +``.metaobjects/.gen-state/.hashes/`` (one file per package, keyed by the project-relative path of +every file a run wrote), so a project that wires no agent-pages generator is never told to read a +file that does not exist. The section's template is the stored file the shipped manifest names +(``agentPagesTemplate``). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +#: The file the section is inserted into, relative to the project root. +ALWAYS_ON_PATH = ".metaobjects/AGENTS.md" +#: The heading the section is inserted above: the always-on file's rules. +AGENT_PAGES_ANCHOR = "\n## Rules\n" + +#: Each agent page, by the path it ends with, and when to read it. In the order they are listed. +AGENT_PAGES: tuple[tuple[str, str], ...] = ( + ("agent/schema.md", "before you touch persistence: tables, columns, keys and views"), + ("agent/ui.md", "before you touch a form or a grid"), + ("agent/requirements.md", "before you add or change a capability"), + ("AGENT-API.md", "before you call or change the generated API"), + ("requirements.toon", "the requirement ledger, in the form a tool reads"), +) + +_HASHES_DIR = Path(".metaobjects") / ".gen-state" / ".hashes" + + +def _page_index(path: str) -> int: + for i, (suffix, _when) in enumerate(AGENT_PAGES): + if path == suffix or path.endswith("/" + suffix): + return i + return -1 + + +def wired_agent_pages(root: Path) -> list[str]: + """The agent pages the project's last ``gen`` wrote, as project-relative paths, in page + order and then by path. Empty when nothing records one.""" + directory = root / _HASHES_DIR + if not directory.is_dir(): + return [] + found: set[str] = set() + for entry in sorted(directory.iterdir(), key=lambda p: p.name): + if not entry.name.endswith(".json"): + continue + try: + parsed = json.loads(entry.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue # an unreadable hashes file is `gen`'s to report, not this pointer's + if isinstance(parsed, dict): + found.update(path for path in parsed if _page_index(path) >= 0) + return sorted(found, key=lambda p: (_page_index(p), p.encode("utf-16-be"))) + + +def render_agent_pages_section(template: str, pages: list[str]) -> str: + """The section for *pages*, from *template*; ``""`` when there are none.""" + if not pages: + return "" + lines = "\n".join(f"- `{p}`: {AGENT_PAGES[_page_index(p)][1]}." for p in pages) + return template.replace("{{pageList}}", lines) + + +def with_agent_pages_section(always_on: str, section: str) -> str: + """*always_on* with *section* inserted above its rules; unchanged for an empty section.""" + if section == "": + return always_on + at = always_on.find(AGENT_PAGES_ANCHOR) + if at < 0: + raise ValueError( + f'agent-context: the always-on file has no "{AGENT_PAGES_ANCHOR.strip()}" heading ' + "to place the agent pages above" + ) + return always_on[: at + 1] + section + always_on[at + 1 :] diff --git a/server/python/src/metaobjects/agent_context/shipped/files/5497499d5dddc2cc.md b/server/python/src/metaobjects/agent_context/shipped/files/5497499d5dddc2cc.md new file mode 100644 index 0000000000..bf233c2a66 --- /dev/null +++ b/server/python/src/metaobjects/agent_context/shipped/files/5497499d5dddc2cc.md @@ -0,0 +1,7 @@ +## Pages generated for this project + +The project's `gen` command writes these from the metadata (they are regenerated output, like the +code). Read the one for a tier before you change that tier: + +{{pageList}} + diff --git a/server/python/src/metaobjects/agent_context/shipped/manifest.json b/server/python/src/metaobjects/agent_context/shipped/manifest.json index dd3daf5969..ca50485056 100644 --- a/server/python/src/metaobjects/agent_context/shipped/manifest.json +++ b/server/python/src/metaobjects/agent_context/shipped/manifest.json @@ -3,6 +3,7 @@ "docsRef": "main", "docsLinkPrefix": "https://github.com/metaobjectsdev/metaobjects/blob/", "skillsDir": ".claude/skills", + "agentPagesTemplate": "5497499d5dddc2cc.md", "stacks": [ { "id": "typescript", diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index 90eec55aee..fb8aa97fe2 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -44,6 +44,11 @@ class GenContext: #: (``Collection.in_ledger``)? A dependency's requirement the project did not inherit #: gets no generated test. ``None``: every loaded requirement is the project's. in_ledger: Callable[[str], bool] | None = None + #: FR-023 — is the object at this resolution key the project's own to generate + #: (``run_gen``'s ``select``, normally ``Collection.in_scope``)? A whole-model page built + #: from the docs view reads it to leave a dependency's objects out. ``None``: every + #: loaded object is the project's. + in_scope: Callable[[str], bool] | None = None #: The run's one claim registry : a generator claims each module it emits in #: its generated package directory, and a second claimant is refused with #: ``ERR_NAME_COLLISION``. ``run_gen`` shares one across every generator of the run. diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index ef5fdb6a95..0cde31d118 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -527,8 +527,8 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: "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." + "The requirement ledger as requirements.toon, for tools (a shared Mustache template over " + "the docs view); people read it in the explorer (docs-site). No requirement.* node, no file." ), tier="neutral", layer="docs", diff --git a/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py b/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py index 327b6e4999..11cbfbe758 100644 --- a/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py +++ b/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py @@ -9,7 +9,7 @@ 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 +and ``codegen/runtime/docs_schema.py`` read off the docs view, 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. """ @@ -19,6 +19,7 @@ from metaobjects.codegen.generator import EmittedFile, GenContext, Generator from metaobjects.config.neutral_config import chose_migrate_dialect +from metaobjects.docs_view import build_docs_view from metaobjects.render.doc_pages import doc_provider, end_with_one_newline, render_doc_page from metaobjects.render.verify import Provider @@ -30,7 +31,6 @@ from ..runtime.docs_schema import ( AGENT_SCHEMA_PAGE_REF, agent_schema_page_data, - schema_rows, ) DEFAULT_AGENT_DIR = "agent" @@ -54,12 +54,12 @@ def __init__( def generate(self, ctx: GenContext) -> list[EmittedFile]: if ctx.loaded_root is None: return [] - root = ctx.loaded_root + view = build_docs_view(ctx.loaded_root) files: list[EmittedFile] = [] # `.metaobjects/config.json` is already part of the run's skip key (cli `_skip_identity`). has_migrate = chose_migrate_dialect(ctx.config.project_root) - schema_data = agent_schema_page_data(root, schema_rows(root), has_migrate) + schema_data = agent_schema_page_data(view, has_migrate, ctx.in_scope) 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) @@ -68,7 +68,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: 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) + requirements = agent_requirements_page_data(view, ctx.in_ledger, render_ledger) if requirements is not None: path = f"{self._dir}/requirements.md" files.append( diff --git a/server/python/src/metaobjects/codegen/generators/requirements_generator.py b/server/python/src/metaobjects/codegen/generators/requirements_generator.py index 9275af91cc..2645860da5 100644 --- a/server/python/src/metaobjects/codegen/generators/requirements_generator.py +++ b/server/python/src/metaobjects/codegen/generators/requirements_generator.py @@ -1,37 +1,35 @@ -"""``requirements`` — the requirement ledger as documentation: ``requirements.md`` for people and -``requirements.toon`` for tools. +"""``requirements`` — the requirement ledger as ``requirements.toon``, for tools. People read it in +the explorer (``docs-site``); the human ``requirements.md`` page is retired. 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. +package) fed the data the builder in ``codegen/runtime/docs_requirements.py`` reads off the docs +view; 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.docs_view import build_docs_view 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.""" + """Writes ``requirements.toon`` for the run's loaded model.""" name = "requirements" @@ -43,16 +41,10 @@ def __init__(self, template_root: str | None = None, provider: Provider | None = def generate(self, ctx: GenContext) -> list[EmittedFile]: if ctx.loaded_root is None: return [] - rows = requirement_rows(ctx.loaded_root, ctx.in_ledger) + rows = requirement_rows(build_docs_view(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( diff --git a/server/python/src/metaobjects/codegen/runner.py b/server/python/src/metaobjects/codegen/runner.py index b7e8794795..dcff866f35 100644 --- a/server/python/src/metaobjects/codegen/runner.py +++ b/server/python/src/metaobjects/codegen/runner.py @@ -252,6 +252,7 @@ def is_selected(o: MetaObject) -> bool: warn=_warn_collector(gen.name, result.warnings), generators=tuple(g.name for g in generators), in_ledger=in_ledger, + in_scope=select, claims=claims, selected=is_selected if narrowed else None, run_provenance=( diff --git a/server/python/src/metaobjects/codegen/runtime/docs_requirements.py b/server/python/src/metaobjects/codegen/runtime/docs_requirements.py index 9720ad4573..ea24cdecc4 100644 --- a/server/python/src/metaobjects/codegen/runtime/docs_requirements.py +++ b/server/python/src/metaobjects/codegen/runtime/docs_requirements.py @@ -1,8 +1,9 @@ -"""The requirements pages' builders: the ledger rows and the page data of ``requirements.md``, -``requirements.toon`` and ``agent/requirements.md``. +"""The requirements pages' builders: the ledger rows and the page data of ``requirements.toon`` +and ``agent/requirements.md`` (with its embedded ledger), all read off the docs view. -Mirrors the TypeScript ``requirements-view.ts``, ``requirements-markdown.ts``, -``requirements-toon.ts`` and ``agent-requirements-page.ts``. Every page is a shared Mustache +Mirrors the TypeScript ``docs-view-pages.ts``, ``requirements-markdown.ts``, +``requirements-toon.ts`` and ``agent-requirements-page.ts``. The human ``requirements.md`` page is +retired: its template renders only as the ledger embedded in ``agent/requirements.md``. 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 @@ -19,13 +20,6 @@ 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" @@ -42,44 +36,37 @@ # --- 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 _opt(text: Any) -> str | None: + """A view string as a row value: "" is absent.""" + return text if isinstance(text, str) and text != "" else None def requirement_rows( - root: MetaData, in_ledger: Callable[[str], bool] | None = None + view: dict[str, Any], 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.""" + """Every requirement of the docs view in the project's ledger, nested ones included, as + render-ready rows in document order. ``in_ledger`` is the collection's ledger predicate: a + dependency's requirement the project did not inherit is left out. ``[]`` 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)) + for r in view["requirements"]: + if in_ledger is not None and not in_ledger(r["qualifiedPath"]): + continue + row: dict[str, Any] = {"path": r["address"], "depth": r["depth"]} + if _opt(r["title"]) is not None: + row["title"] = r["title"] + row["subType"] = r["subType"] + if r["level"] is not None: + row["level"] = r["level"] + for key in ("status", "disposition"): + if _opt(r[key]) is not None: + row[key] = r[key] + row["trackedBy"] = list(r["trackedBy"]) + for key in ("statement", "counterexample", "description"): + if _opt(r[key]) is not None: + row[key] = r[key] + row["implementedBy"] = [lk["ref"] for lk in r["implementedBy"]] + row["claimedConcerns"] = list(dict.fromkeys(lk["target"]["kind"] for lk in r["implementedBy"] if lk["resolves"])) rows.append(row) return rows @@ -225,43 +212,33 @@ def requirements_toon_data(rows: list[dict[str, Any]]) -> dict[str, Any]: # --- 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 + view: dict[str, Any], in_ledger: Callable[[str], bool] | None = None ) -> list[dict[str, Any]]: - """Invert the walk: claimed node -> the requirements that claim it, sorted by address.""" + """Invert the view's resolved ``implementedBy``: claimed node -> the requirements that claim + it, sorted by the node's id. A claim that does not resolve is left out (``meta verify`` + reports it).""" 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) + for r in view["requirements"]: + if in_ledger is not None and not in_ledger(r["qualifiedPath"]): + continue + for link in r["implementedBy"]: + if not link["resolves"]: + continue + target = link["target"] entry = by_address.setdefault( - address, {"address": address, "concern": target.concern, "claims": []} + target["id"], {"address": target["id"], "concern": target["kind"], "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, + "path": r["address"], + "subType": r["subType"], + "level": r["level"], + "status": _opt(r["status"]), + "statement": _opt(r["statement"]), } ) - return sorted(by_address.values(), key=lambda e: e["address"]) + return sorted(by_address.values(), key=lambda e: e["address"].encode("utf-16-be")) def md_cell(text: str) -> str: @@ -274,17 +251,17 @@ def one_line(text: str) -> str: def agent_requirements_page_data( - root: MetaData, + view: dict[str, Any], 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) + rows = requirement_rows(view, in_ledger) if not rows: return None - index = build_node_index(root, in_ledger) + index = build_node_index(view, in_ledger) stated: dict[str, dict[str, str]] = {} for entry in index: for c in entry["claims"]: diff --git a/server/python/src/metaobjects/codegen/runtime/docs_schema.py b/server/python/src/metaobjects/codegen/runtime/docs_schema.py index 5657bdf4d3..8f593d8920 100644 --- a/server/python/src/metaobjects/codegen/runtime/docs_schema.py +++ b/server/python/src/metaobjects/codegen/runtime/docs_schema.py @@ -1,316 +1,80 @@ -"""The MODEL-ONLY ``agent/schema.md``: the rows layer and the page data, built from the model. +"""The MODEL-ONLY ``agent/schema.md``: the rows layer and the page data, read off the docs view. -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. +Mirrors the TypeScript ``docs-view-pages.ts`` (``schemaRowsFromView`` and +``agentSchemaPageDataFromView``, the ``physical: false`` page). The docs view's ``storage`` +section (``metaobjects.docs_view_storage``) holds the tables and views the model declares, +named by this port's own naming helpers (design call 17 of ``fixtures/docs-page-conformance/``); +the relationships and enums are read from the members of the nodes it links. 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 typing import Any, Callable -from metaobjects.codegen.instance_artifacts import is_abstract -from metaobjects.codegen.model_walk import is_required from .docs_requirements import GENERATED_MARKER -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" +_TYPE_OBJECT = "object" +_TYPE_FIELD = "field" +_TYPE_ORIGIN = "origin" +_TYPE_RELATIONSHIP = "relationship" +_KIND_REPORT = "object.report" +_SUBTYPE_ENUM = "enum" +Json = dict[str, Any] -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: +def row_key(name: str, schema: str) -> 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 name if schema == "" else f"{schema}.{name}" + + +# --- the rows layer, read off the view's storage --------------------------------------- + + +def schema_rows(view: Json) -> Json: + """The rows layer of the model-only schema page: tables and views as the view's storage + lists them (sorted by name), a table's columns and keys in declaration order, and + ``declaredBy`` (each table or view -> the declaring object).""" + storage = view["storage"] + declared: list[tuple[str, str]] = [] + tables: list[Json] = [] + for t in storage["tables"]: + declared.append((row_key(t["name"], t["schema"]), t["declaredBy"]["id"])) + table: Json = {"name": t["name"]} + if t["schema"] != "": + table["schema"] = t["schema"] + if t["description"] != "": + table["description"] = t["description"] + table["primaryKey"] = t["primaryKey"] + table["columns"] = [ + { + "name": c["name"], + "nullable": c["nullable"], + **({"identity": c["identity"]} if c["identity"] != "" else {}), + **({"description": c["description"]} if c["description"] != "" else {}), + } + for c in t["columns"] + ] + table["foreignKeys"] = [ + {"columns": f["columns"], "refTable": f["refTable"], "refColumns": f["refColumns"]} + for f in t["foreignKeys"] ] - 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[Json] = [] + for v in storage["views"]: + declared.append((row_key(v["name"], v["schema"]), v["declaredBy"]["id"])) + views.append({"name": v["name"], **({"schema": v["schema"]} if v["schema"] != "" else {})}) + declared.sort(key=lambda kv: kv[0].encode("utf-16-be")) + return {"tables": tables, "views": views, "declaredBy": dict(declared)} - 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 ------------------------------------------------ +# --- the page, from the view ---------------------------------------------------------- def _md_cell_free(text: str) -> str: @@ -321,169 +85,124 @@ 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: +def _key_cell(table: Json, column: str) -> str: roles: list[str] = [] - if column["name"] in table["primaryKey"]: + if column 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) + fk = next((f for f in table["foreignKeys"] if column 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: +def _members_by_id(view: Json) -> dict[str, Json]: + """Every member of every node, by id.""" + out: dict[str, Json] = {} + + def visit(m: Json) -> None: + out[m["id"]] = m + for g in m["memberGroups"]: + for c in g["members"]: + visit(c) + + for n in view["nodes"]: + for g in n["memberGroups"]: + for m in g["members"]: + visit(m) + return out + + +def _direct_members(n: Json, type_: str) -> list[Json]: + return next((g["members"] for g in n["memberGroups"] if g["type"] == type_), []) + + +def _attr_value(attrs: list[Json], name: str) -> Any: + return next((a["value"] for a in attrs if a["name"] == name), None) + + +def _attr_text(attrs: list[Json], name: str) -> str | None: + """A string attribute as a page prints it: a resolved reference by its link's label (what + the author wrote, relative to the model: ``Owner.name``), anything else as its text.""" + a = next((x for x in attrs if x["name"] == name), None) + if a is None or not isinstance(a["value"], str): return None + first = a["values"][0] if a["values"] else None + link = first.get("link") if first is not None else None + text = link["label"] if link is not None and not link["unresolved"] else a["value"] + return None if text == "" else text - 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: + +def _lineage_of(field: Json | None) -> str | None: + """The lineage text of a view column, from its field's ``origin.*`` member.""" + origins = [] if field is None else _direct_members(field, _TYPE_ORIGIN) + if not origins: + return None + origin = origins[0] + + def t(name: str) -> str | None: + return _attr_text(origin["attrs"], name) + + sub = origin["subType"] + via = t("via") + via_part = "" if via is None else f" via `{via}`" + if sub == "passthrough": + return f"passthrough from `{t('from') or '?'}`" + via_part + if sub == "aggregate": + of = t("of") + return f"`{t('agg') or '?'}`" + ("" if of is None else f" of `{of}`") + via_part + if sub == "first": + of, order = t("of"), t("orderBy") + return "first" + ("" if of is None else f" `{of}`") + via_part + ("" if order is None else f" ordered by `{order}`") + if sub == "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: +def _cardinality_phrase(cardinality: Any, through: str | None) -> str: + if cardinality == "many": + return "many-to-many" if through is not None else "one-to-many" + if 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], has_migrate: bool = False -) -> dict[str, Any] | None: - """The data ``agent/schema.md.mustache`` renders (``physical: false``), built from the rows - and the model alone. ``has_migrate``: the project chose a ``meta migrate`` dialect - (``metaobjects.config.neutral_config.chose_migrate_dialect``). ``None`` when there is no table and no view: no page.""" - if not rows["tables"] and not rows["views"]: + view: Json, has_migrate: bool = False, in_scope: Callable[[str], bool] | None = None +) -> Json | None: + """The data ``agent/schema.md.mustache`` renders (``physical: false``), built from the docs + view alone. ``has_migrate``: the project chose a ``meta migrate`` dialect + (``metaobjects.config.neutral_config.chose_migrate_dialect``). ``None`` when the model + declares no table and no view: no page. ``in_scope`` keeps only the project's own objects + (``None`` keeps every object): a dependency's object is not the project's schema.""" + + def scoped(node_id: str) -> bool: + return in_scope is None or in_scope(node_id) + + tables = [t for t in view["storage"]["tables"] if scoped(t["declaredBy"]["id"])] + views = [v for v in view["storage"]["views"] if scoped(v["declaredBy"]["id"])] + if not tables and not 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 sorted(rows["tables"], key=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"]) + members = _members_by_id(view) + by_order = sorted(view["nodes"], key=lambda n: n["order"]) + + table_data: list[Json] = [] + for t in tables: + described = [c for c in t["columns"] if c["description"] != ""] + fks = [f"{_cols(f['columns'])} → `{f['refTable']}`({_cols(f['refColumns'])})" for f in t["foreignKeys"]] + entry: Json = {"heading": f"`{row_key(t['name'], t['schema'])}`", "tableDeclaredBy": t["declaredBy"]["id"]} + if t["description"] != "": + entry["tableDescription"] = _md_cell_free(t["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 "", + "fieldCell": "" if c["field"] is None else f"`{members[c['field']['id']]['name']}`", + "declaredCell": "" if c["field"] is None else f"`{c['field']['kind']}`", "sqlTypeCell": "", "nullCell": "yes" if c["nullable"] else "no", "defaultCell": "", - "keyCell": _key_cell(table, c), + "keyCell": _key_cell(t, c["name"]), } - for c in table["columns"] + for c in t["columns"] ] entry.update( hasDescribed=len(described) > 0, @@ -495,30 +214,75 @@ def agent_schema_page_data( hasChecks=False, checks=[], ) - tables.append(entry) - - views = [] - for view in sorted(rows["views"], key=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) + table_data.append(entry) + + view_data: list[Json] = [] + for v in views: + lineage: list[Json] = [] + for c in v["columns"]: + text = _lineage_of(None if c["field"] is None else members.get(c["field"]["id"])) + if text is not None: + lineage.append({"column": c["name"], "text": text}) + view_data.append({ + "heading": f"`{row_key(v['name'], v['schema'])}`", + "viewDeclaredBy": v["declaredBy"]["id"], + "hasLineage": len(lineage) > 0, + "lineage": lineage, + }) + + # Every relationship as written, in declaration order of its object. + relationships: list[str] = [] + for n in by_order: + if n["type"] != _TYPE_OBJECT or not scoped(n["id"]): + continue + for rel in _direct_members(n, _TYPE_RELATIONSHIP): + through = _attr_text(rel["attrs"], "through") + on_delete = _attr_text(rel["attrs"], "onDelete") + target = _attr_text(rel["attrs"], "objectRef") + parts = [f"`{n['id']}.{rel['name']}`", f"`{rel['subType']}`"] + parts.append(f"{_cardinality_phrase(_attr_value(rel['attrs'], 'cardinality'), through)} → `{target if target is not None else '?'}`") + if through is not None: + parts.append(f"through `{through}`") + if on_delete is not None: + parts.append(f"on delete `{on_delete}`") + relationships.append(" · ".join(parts)) + + # Every enum field of a table-backed object, in declaration order of its object. + table_backed = {o["id"] for t in tables for o in t["objects"]} + enums: list[Json] = [] + for n in by_order: + if n["id"] not in table_backed: + continue + for f in _direct_members(n, _TYPE_FIELD): + if f["subType"] != _SUBTYPE_ENUM: + continue + values = _attr_value(f["attrs"], "values") + names = [str(x) for x in values] if isinstance(values, list) else [] + if not names: + continue + int_map = _attr_value(f["attrs"], "intValueMap") + if isinstance(int_map, dict): + storage = "int-backed (" + ", ".join(f"{m}={int_map.get(m)}" for m in names) + ")" + else: + storage = "string-backed" + enums.append({ + "field": f"{n['id']}.{f['name']}", + "members": ", ".join(f"`{m}`" for m in names), + "storage": storage, + }) + any_description = any(t["description"] != "" or any(c["description"] != "" for c in t["columns"]) for t in tables) return { "generatedMarker": GENERATED_MARKER, "physical": False, "dialect": "", - "descriptionNudge": not any_description and len(rows["tables"]) > 0, + "descriptionNudge": not any_description and len(tables) > 0, "hasMigrate": has_migrate, - "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, + "hasTables": len(table_data) > 0, + "tables": table_data, + "hasViews": len(view_data) > 0, + "hasReportView": any(o["kind"] == _KIND_REPORT for v in views for o in v["objects"]), + "views": view_data, "hasRelationships": len(relationships) > 0, "relationships": relationships, "hasEnums": len(enums) > 0, diff --git a/server/python/src/metaobjects/docs_view.py b/server/python/src/metaobjects/docs_view.py index f3909fe8f9..2f3c75d4d0 100644 --- a/server/python/src/metaobjects/docs_view.py +++ b/server/python/src/metaobjects/docs_view.py @@ -35,6 +35,7 @@ from .requirement_check import effective_package from .naming_refs import effective_package_of, is_ref_bearing_attr, split_child_tail from .documentation.doc_constants import DOC_ATTR_DESCRIPTION, DOC_ATTR_SUMMARY, DOC_ATTR_TITLE +from .docs_view_storage import build_storage from .serializer_json import _normalize from .shared.base_types import TYPE_FIELD, TYPE_OBJECT, TYPE_REQUIREMENT, TYPE_TEMPLATE from .shared.separators import PACKAGE_SEP @@ -761,9 +762,17 @@ def num(k: str) -> int | float | None: "requirements": requirements, "advisories": advisories, "slices": _slices_of(b, nodes, requirements), + "storage": build_storage(root, lambda md: b.link_to(md, md.name), lambda owner, field: _member_link(b, owner, field)), } +def _member_link(b: _Builder, owner: MetaData, field: MetaData) -> Json | None: + """The link to *field* as a member of the top-level *owner*: its own row of an inherited one.""" + top = b.canonical.get(id(owner)) + row = None if top is None else next((c for c in top.children if c.md is field), None) + return None if row is None else b.link(row) + + def _slices_of(b: _Builder, nodes: list[Json], requirements: list[Json]) -> list[Json]: slices: list[Json] = [] diff --git a/server/python/src/metaobjects/docs_view_storage.py b/server/python/src/metaobjects/docs_view_storage.py new file mode 100644 index 0000000000..eefdd26b75 --- /dev/null +++ b/server/python/src/metaobjects/docs_view_storage.py @@ -0,0 +1,327 @@ +"""The docs view's ``storage`` section: the tables and views the model declares, named by the +port's own naming helpers (``docs/features/docs-view.md``, "storage"). + +The Python port of TypeScript's ``storage.ts`` (``@metaobjectsdev/metadata``), held to the +same bytes by ``fixtures/explorer-conformance/``. MODEL-ONLY: a table per concrete object +whose primary source is a writable, managed 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 +physical facts (SQL type, default, indexes, checks, constraint names, referential actions) +are ``None`` here and ``physical`` is false: only the TypeScript run fills them. +""" +from __future__ import annotations + +from typing import Any, Callable + +from .codegen.model_walk import is_required +from .documentation.doc_constants import DOC_ATTR_DESCRIPTION +from .meta.core.field import field_constants as fc +from .meta.core.field.meta_field import MetaField +from .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 .meta.core.object.meta_object import MetaObject +from .meta.core.object.object_constants import OBJECT_ATTR_DISCRIMINATOR, OBJECT_ATTR_DISCRIMINATOR_VALUE +from .meta.meta_data import MetaData +from .meta.persistence.source.meta_source import MetaSource +from .naming import ( + apply_column_naming_strategy, + naming_rules_of, + resolve_column_name, + resolve_flattened_column_name, +) +from .naming_refs import ref_target, split_child_tail +from .shared.base_types import TYPE_IDENTITY +from .source_resolution import primary_rdb_source + +Json = dict[str, Any] + +_SOURCE_KIND_VIEW = "view" + + +def _cu(s: str) -> bytes: + return s.encode("utf-16-be") + + +def _description(node: MetaData) -> str: + v = node.get_meta_attr(DOC_ATTR_DESCRIPTION) + return v if isinstance(v, str) else "" + + +def _schema_of(source: MetaSource) -> str: + v = source.schema() + return v if isinstance(v, str) else "" + + +def _is_abstract(obj: MetaObject) -> bool: + return obj.is_abstract is True + + +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: an explicit super-resolution walk reads 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 _column_of(obj: MetaObject, name: str) -> str: + f = obj.find_field(name) + return resolve_column_name(f) if f is not None else apply_column_naming_strategy(name, naming_rules_of(obj).columns) + + +def _is_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 _raw_column(field: MetaData, is_pk: bool, generation: str, name: str) -> Json: + return { + "name": name, + "nullable": not is_pk and not is_required(field), + "identity": generation if is_pk and generation in (GENERATION_INCREMENT, GENERATION_UUID) else "", + "description": _description(field), + } + + +def _field_columns(field: MetaField, is_pk: bool, generation: str) -> list[Json]: + if _is_flattened(field): + target = ref_target(field, fc.FIELD_ATTR_OBJECT_REF) + if not isinstance(target, MetaObject): + return [] + return [ + _raw_column(nested, False, "", resolve_flattened_column_name(field, nested)) + for nested in target.fields() + ] + return [_raw_column(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 "" + names = [s.strip() for s in tail.lstrip(".").split(",") if s.strip()] + if not names: + identity = target.primary_identity() + pk = _identity_fields(identity) if identity is not None else [] + names = [pk[0] if pk else "id"] + return [_column_of(target, n) for n in names] + + +def _is_ref(c: MetaData) -> bool: + return c.type == TYPE_IDENTITY and c.sub_type == IDENTITY_SUBTYPE_REFERENCE + + +def _foreign_keys(entity: MetaObject, objects: list[MetaObject], table_of: dict[int, str]) -> list[Json]: + refs: list[tuple[MetaObject, MetaData]] = [(entity, c) for c in entity.children() if _is_ref(c)] + 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 _is_ref(c) and c.name not in base_names: + refs.append((sub, c)) + fks: list[Json] = [] + 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(id(target)) + if not ref_table: + continue + names = _identity_fields(ref) + if not names: + continue + fk: Json = { + "columns": [_column_of(holder, n) for n in names], + "refTable": ref_table, + "refColumns": _target_columns(ref, target), + "name": None, + "onDelete": None, + "onUpdate": None, + } + if fk not in fks: # two subtypes may declare the same column: one constraint + fks.append(fk) + return fks + + +def _key(name: str, schema: str) -> str: + return name if schema == "" else f"{schema}.{name}" + + +def build_storage( + root: MetaData, + node: Callable[[MetaData], Json], + member: Callable[[MetaData, MetaData], Json | None], +) -> Json: + """The storage section of the docs view for the top-level nodes of *root*, in declaration + order. *node* is a top-level node's link; *member* the link to a field as a member of its + top-level owner (its own row of an inherited one), or ``None``.""" + objects = [c for c in root.children() if isinstance(c, MetaObject)] + + # Pass 1: which objects own a table, and which are only a foreign-key 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_rdb_source(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[int, str] = {id(o): s.physical_name() for o, s in [*entities, *target_only]} + for m, base in tph_members: + name = table_of.get(id(base)) + if name is not None and id(m) not in table_of: + table_of[id(m)] = name + + # Every object at each storage key, in declaration order: the column -> declaring field map + # (first writer wins on a shared table) and the objects a page lists. + at_key: dict[str, list[MetaObject]] = {} + for obj in objects: + source = primary_rdb_source(obj) + if source is None: + continue + at_key.setdefault(_key(source.physical_name(), _schema_of(source)), []).append(obj) + + def field_of(k: str) -> dict[str, tuple[MetaObject, MetaField]]: + mapping: dict[str, tuple[MetaObject, MetaField]] = {} + for obj in at_key.get(k, []): + for field in obj.fields(): + column = resolve_column_name(field) + if column not in mapping: + mapping[column] = (obj, field) + return mapping + + def objects_at(k: str) -> list[Json]: + return [node(o) for o in at_key.get(k, []) if not _is_abstract(o)] + + tables: list[Json] = [] + keys: set[str] = set() + for entity, source in entities: + identity = entity.primary_identity() + pk_names = _identity_fields(identity) if identity is not None else [] + gen = identity.get_meta_attr(IDENTITY_ATTR_GENERATION) if identity is not None else None + generation = gen if isinstance(gen, str) else "" + raw: list[Json] = [] + for field in entity.fields(): + if field.is_derived(): + continue + is_pk = field.name in pk_names + raw.extend(_field_columns(field, is_pk, generation if is_pk else "")) + if entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is not None: + existing = {c["name"] for c in raw} + 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 = _raw_column(field, False, "", resolve_column_name(field)) + if col["name"] in existing: + continue + col["nullable"] = True # a row of any other subtype stores NULL here + raw.append(col) + existing.add(col["name"]) + schema = _schema_of(source) + k = _key(source.physical_name(), schema) + mapping = field_of(k) + columns: list[Json] = [] + for c in raw: + m = mapping.get(c["name"]) + columns.append({ + "name": c["name"], + "field": None if m is None else member(m[0], m[1]), + "nullable": c["nullable"], + "identity": c["identity"], + "description": c["description"], + "sqlType": None, + "default": None, + }) + tables.append({ + "name": source.physical_name(), + "schema": schema, + "declaredBy": node(entity), + "objects": objects_at(k), + "description": _description(entity), + "primaryKey": [_column_of(entity, n) for n in pk_names], + "columns": columns, + "foreignKeys": _foreign_keys(entity, objects, table_of), + "indexes": None, + "checks": None, + }) + keys.add(k) + + views: list[Json] = [] + for obj in objects: + if _is_abstract(obj): + continue + source = primary_rdb_source(obj) + if source is None or source.effective_kind() != _SOURCE_KIND_VIEW: + continue + schema = _schema_of(source) + k = _key(source.physical_name(), schema) + if k in keys: + continue + keys.add(k) + views.append({ + "name": source.physical_name(), + "schema": schema, + "declaredBy": node(obj), + "objects": objects_at(k), + "columns": [{"name": name, "field": member(m[0], m[1])} for name, m in field_of(k).items()], + }) + + tables.sort(key=lambda t: _cu(t["name"])) + views.sort(key=lambda v: _cu(v["name"])) + return {"physical": False, "dialect": "", "tables": tables, "views": views} diff --git a/server/python/tests/codegen/test_cli_dependencies.py b/server/python/tests/codegen/test_cli_dependencies.py index b0b0d75c3f..0a6939425d 100644 --- a/server/python/tests/codegen/test_cli_dependencies.py +++ b/server/python/tests/codegen/test_cli_dependencies.py @@ -55,6 +55,7 @@ def _consumer( *, scope_include: list[str] | None = None, target_entities: list[str] | None = None, + generators: str = "names", ) -> Path: """A consumer project: APP + SNAP + CONFIG_REF + LOCK_V1, with one `metaobjects.config.yaml` target (`generators: [names]`).""" @@ -82,7 +83,7 @@ def _consumer( "targets:\n" " main:\n" " outDir: gen\n" - f" generators: [names]{entities_line}\n" + f" generators: [{generators}]{entities_line}\n" ) return tmp_path / "metaobjects.config.yaml" @@ -95,6 +96,17 @@ def test_gen_excludes_the_dependencys_entities_by_default(tmp_path: Path) -> Non assert not (tmp_path / "gen" / "customer_names.py").exists() +def test_agent_schema_page_leaves_the_dependencys_objects_out(tmp_path: Path) -> None: + # agent/schema.md documents the project's own storage: the local Order, never an import. + cfg = _consumer(tmp_path, generators="agent-docs") + rc = main(["gen", "--config", str(cfg)]) + assert rc == 0 + schema = (tmp_path / "gen" / "agent" / "schema.md").read_text() + assert "app::Order" in schema + for imported in ("Customer", "Address", "Audited", "acme::common"): + assert imported not in schema, imported + + def test_gen_scope_include_naming_the_package_opts_it_in(tmp_path: Path) -> None: cfg = _consumer(tmp_path, scope_include=["acme::common::**"]) rc = main(["gen", "--config", str(cfg)]) diff --git a/server/python/tests/codegen/test_docs_site_generator.py b/server/python/tests/codegen/test_docs_site_generator.py index 13494a8447..eeaecb2900 100644 --- a/server/python/tests/codegen/test_docs_site_generator.py +++ b/server/python/tests/codegen/test_docs_site_generator.py @@ -50,10 +50,10 @@ def test_model_script_is_typescripts_bytes() -> None: script, stamp = explorer_model_script( "Shop ", "v1", {"b": "B\n", "a": "A é"}, {"explorer-head.mustache": ""}, expected_view("shop") ) - assert stamp == "2600a8bb3cb5d29d" - assert len(script) == 50657 - assert hashlib.sha256(script.encode("utf-8")).hexdigest() == "87643095df7b9c679871c21420f8a3ae71128ba60f71f97b2b8bc99dfc482cfb" - assert explorer_stamp_script(stamp) == 'window.MO_STAMP = "2600a8bb3cb5d29d";\n' + assert stamp == "d4fdee1b6a14ff03" + assert len(script) == 55371 + assert hashlib.sha256(script.encode("utf-8")).hexdigest() == "c3359765dc5274a1837ec945a9faa3eba528f7bd885080e6c983f06ab6694b5b" + assert explorer_stamp_script(stamp) == 'window.MO_STAMP = "d4fdee1b6a14ff03";\n' def test_app_files_are_the_canonical_copy() -> None: diff --git a/server/python/tests/conformance/test_docs_page_conformance.py b/server/python/tests/conformance/test_docs_page_conformance.py index 1c6c369497..93162e72cb 100644 --- a/server/python/tests/conformance/test_docs_page_conformance.py +++ b/server/python/tests/conformance/test_docs_page_conformance.py @@ -1,9 +1,9 @@ """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 +The requirements TOON page, the agent requirements page and the MODEL-ONLY agent schema page are +shared Mustache templates fed data a per-port builder reads off the docs view. 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 reads off the view (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. """ @@ -20,6 +20,7 @@ from metaobjects.codegen.generators.agent_docs_generator import AgentDocsGenerator from metaobjects.codegen.generators.requirements_generator import RequirementsGenerator from metaobjects.codegen.runtime.docs_requirements import ( + AGENT_REQUIREMENTS_PAGE_REF, REQUIREMENTS_PAGE_REF, REQUIREMENTS_TOON_REF, agent_requirements_page_data, @@ -28,9 +29,10 @@ requirements_toon_data, toon_cell, ) -from metaobjects.codegen.runtime.docs_schema import agent_schema_page_data, schema_rows +from metaobjects.codegen.runtime.docs_schema import AGENT_SCHEMA_PAGE_REF, agent_schema_page_data, schema_rows from metaobjects.config.neutral_config import chose_migrate_dialect -from metaobjects.render.doc_pages import doc_provider, render_doc_page +from metaobjects.docs_view import build_docs_view +from metaobjects.render.doc_pages import doc_provider, end_with_one_newline, render_doc_page def _corpus() -> Path: @@ -76,45 +78,49 @@ def test_the_corpus_is_not_empty() -> None: @pytest.mark.parametrize("case", CASES) -def test_rows_data_and_bytes(case: str) -> None: +def test_view_rows_data_and_bytes(case: str) -> None: root = _load(case) expected = _expected(case) provider = doc_provider() + has_migrate = chose_migrate_dialect(CORPUS / case / "input") + # Every page starts from the docs view; the layers are checked in order: rows, data, bytes. + view = build_docs_view(root) - rows = requirement_rows(root) + def ledger(data: dict[str, Any]) -> str: + return render_doc_page(REQUIREMENTS_PAGE_REF, data, provider, "requirements.md") + + produced: dict[str, str] = {} + rows = requirement_rows(view) if rows: assert rows == _json(expected, "rows/requirements.json"), "requirement rows" - assert requirements_ledger_data(rows) == _json(expected, "data/requirements.md.json") + assert requirements_ledger_data(rows, embedded=True) == _json(expected, "data/ledger.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"] + produced["requirements.toon"] = render_doc_page( + REQUIREMENTS_TOON_REF, requirements_toon_data(rows), provider, "requirements.toon" ) - 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) + agent = agent_requirements_page_data(view, 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, chose_migrate_dialect(CORPUS / case / "input")) + produced["agent/requirements.md"] = render_doc_page( + AGENT_REQUIREMENTS_PAGE_REF, agent, provider, "agent/requirements.md" + ) + data = agent_schema_page_data(view, has_migrate) if data is not None: - assert srows == _json(expected, "rows/schema.json"), "schema rows" + assert schema_rows(view) == _json(expected, "rows/schema.json"), "schema rows" assert data == _json(expected, "data/agent-schema.md.json"), "schema page data" + produced["agent/schema.md"] = end_with_one_newline( + render_doc_page(AGENT_SCHEMA_PAGE_REF, data, provider, "agent/schema.md") + ) # The generators write exactly the pinned pages, byte for byte (the set is pinned too). ctx = _ctx(root, CORPUS / case / "input") 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(produced) == sorted(pages) assert sorted(written) == sorted(pages) for path, content in pages.items(): + assert produced[path] == content, path assert written[path] == content, path @@ -148,4 +154,4 @@ def test_a_project_template_overrides_the_bundled_page(tmp_path: Path) -> None: (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, CORPUS / "ledger-unclaimed" / "input"))} assert files["requirements.toon"] == "custom 1" - assert files["requirements.md"].startswith("# Requirements") + assert "requirements.md" not in files diff --git a/server/python/tests/unit/test_agent_docs.py b/server/python/tests/unit/test_agent_docs.py index 39b4284fdd..466def9d21 100644 --- a/server/python/tests/unit/test_agent_docs.py +++ b/server/python/tests/unit/test_agent_docs.py @@ -206,3 +206,37 @@ def test_command_writes_into_out_and_refuses_an_unknown_stack( assert main(["agent-docs", "--server", "python", "--client", "tanstack", "--out", str(tmp_path / "no")]) == 2 assert "python-react-tanstack" in capsys.readouterr().err assert not (tmp_path / "no").exists() + + +# --- the always-on pointer at the agent pages (fixtures/agent-pages-pointer/) --------------- + +POINTER_CASES = REPO_ROOT / "fixtures/agent-pages-pointer/cases" + + +def _pages_template() -> str: + tree = load_shipped() + return (tree.root / "files" / str(tree.manifest["agentPagesTemplate"])).read_text(encoding="utf-8") + + +@pytest.mark.parametrize("case", sorted(p.name for p in POINTER_CASES.iterdir() if p.is_dir())) +def test_agent_pages_section_matches_the_corpus(case: str) -> None: + from metaobjects.agent_context.agent_pages import render_agent_pages_section, wired_agent_pages + + expected = (POINTER_CASES / case / "expected-section.md").read_text(encoding="utf-8") + assert render_agent_pages_section(_pages_template(), wired_agent_pages(POINTER_CASES / case)) == expected + + +def test_the_pointer_lands_above_the_rules_and_an_empty_section_changes_nothing(tmp_path: Path) -> None: + import shutil + + plain = tmp_path / "plain" + plain.mkdir() + run_agent_docs(servers=["python"], clients=[], out=plain, version=RELEASE) + wired = tmp_path / "wired" + shutil.copytree(POINTER_CASES / "wired" / ".metaobjects", wired / ".metaobjects") + run_agent_docs(servers=["python"], clients=[], out=wired, version=RELEASE) + before = (plain / ".metaobjects/AGENTS.md").read_text(encoding="utf-8") + after = (wired / ".metaobjects/AGENTS.md").read_text(encoding="utf-8") + section = (POINTER_CASES / "wired" / "expected-section.md").read_text(encoding="utf-8") + at = before.index("\n## Rules\n") + 1 + assert after == before[:at] + section + before[at:] diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 4ea4c4c6ca..be3f03cc8a 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -96,7 +96,7 @@ OPTIONS (everywhere): GENERATORS: a project chooses what runs in metaobjects.config.json, `{ \"generators\": [..] }`, by name. Edit the list; no eject is needed. With no such file every generator runs but the opt-in ones: the transport (service-routes), which `init --transport` lists, and the docs -generators (metamodel-docs, docs-site), which run only when listed. +generators (metamodel-docs, requirements, agent-docs, docs-site), which run only when listed. ENTITY names limit `gen` to the crates that contain them plus the crates those depend on. Such a run never skips, never stores the skip key and never removes a file. diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index 2293061043..fcf105c1e6 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -278,7 +278,7 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl "{out}" ); assert_eq!(out.matches("[configured]").count(), 10, "{out}"); - assert_eq!(out.matches("[not configured]").count(), 3, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 5, "{out}"); assert!( out.contains("(layer: docs) [not configured] [package-only]"), "docs-site is listed as package-only: {out}" @@ -295,7 +295,7 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl ); let out = ok(&p.run(&["meta", "gen", "--list"])); assert!(out.contains("runs: entity\n"), "{out}"); - assert_eq!(out.matches("[not configured]").count(), 12, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 14, "{out}"); } #[test] @@ -598,7 +598,7 @@ fn eject_copies_the_generator_never_overwrites_and_undo_takes_back_only_identica assert_eq!(r.status.code(), Some(2)); assert!( text(&r.stderr).contains( - "unknown or non-ejectable generator(s): nope; ejectable: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt, metamodel-docs" + "unknown or non-ejectable generator(s): nope; ejectable: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt, metamodel-docs, requirements, agent-docs" ), "{}", text(&r.stderr) diff --git a/server/rust/metaobjects-codegen/src/agent_docs.rs b/server/rust/metaobjects-codegen/src/agent_docs.rs new file mode 100644 index 0000000000..8d84512c75 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/agent_docs.rs @@ -0,0 +1,127 @@ +//! The `agent-docs` generator: pages written for a coding agent working in the project. +//! +//! In Rust it 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. +//! +//! Each page is a shared Mustache template (`templates/agent/`, `templates/requirements/`) +//! fed the data the docs page builders read off the docs view, pinned by +//! `fixtures/docs-page-conformance/`. A page with nothing to describe is no file. A project's +//! own same-named template wins over the shipped one. + +use metaobjects_codegen::generator::{ + EmittedFile, GenContext, GenError, Generator, Options, unknown_options, +}; +use metaobjects_codegen::plan::{ + DocsTemplates, agent_requirements_page, agent_schema_page, has_migrate, view_of, +}; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; + +const DEFAULT_DIR: &str = "agent"; +const OPTION_SUB_DIR: &str = "subDir"; +const ERR_AGENT_DOCS: &str = "ERR_AGENT_DOCS"; +/// What the pages read besides the model: the templates, and `migrate.dialect` of the config. +const INPUTS: [&str; 3] = [ + "templates/agent", + "templates/requirements", + ".metaobjects/config.json", +]; + +/// The agent-docs generator. +#[derive(Debug, Clone, Copy, Default)] +pub struct AgentDocsGenerator; + +/// The generator as a project configured it (`{"name": "agent-docs", "options": {"subDir": ""}}`). +#[derive(Debug, Clone)] +pub struct ConfiguredAgentDocs { + dir: String, +} + +impl Generator for AgentDocsGenerator { + fn name(&self) -> &str { + "agent-docs" + } + + fn identity(&self) -> String { + format!("agent-docs:{FORMAT}:{DEFAULT_DIR}") + } + + fn extra_inputs(&self) -> Vec { + INPUTS.iter().map(ToString::to_string).collect() + } + + fn configure(&self, options: &Options) -> Result, GenError> { + if options.keys().any(|k| k != OPTION_SUB_DIR) { + return Err(unknown_options(self.name(), options, &[OPTION_SUB_DIR])); + } + let dir = match options.get(OPTION_SUB_DIR) { + None => DEFAULT_DIR.to_string(), + Some(serde_json::Value::String(s)) => s.trim_matches('/').to_string(), + Some(other) => { + return Err(GenError::new( + ERR_AGENT_DOCS, + format!( + "the generator agent-docs takes \"{OPTION_SUB_DIR}\" as a string, got {other}" + ), + )); + } + }; + Ok(Box::new(ConfiguredAgentDocs { dir })) + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + pages_under(DEFAULT_DIR, ctx) + } +} + +impl Generator for ConfiguredAgentDocs { + fn name(&self) -> &str { + "agent-docs" + } + + fn identity(&self) -> String { + format!("agent-docs:{FORMAT}:{}", self.dir) + } + + fn extra_inputs(&self) -> Vec { + INPUTS.iter().map(ToString::to_string).collect() + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + pages_under(&self.dir, ctx) + } +} + +/// Every page that has something to describe, under `dir` of the output (`""` for its root). +fn pages_under(dir: &str, ctx: &GenContext<'_>) -> Result, GenError> { + let at = |name: &str| { + if dir.is_empty() { + name.to_string() + } else { + format!("{dir}/{name}") + } + }; + let view = view_of(ctx); + let templates = DocsTemplates::new(ctx); + let mut files = Vec::new(); + let path = at("schema.md"); + if let Some(page) = agent_schema_page( + &view, + has_migrate(ctx), + ctx.reference_nodes, + &templates, + &path, + )? { + files.push(EmittedFile::new(path, page)); + } + let path = at("requirements.md"); + if let Some(page) = agent_requirements_page(&view, &templates, &path)? { + files.push(EmittedFile::new(path, page)); + } + Ok(files) +} diff --git a/server/rust/metaobjects-codegen/src/docs_pages.rs b/server/rust/metaobjects-codegen/src/docs_pages.rs new file mode 100644 index 0000000000..394bc2736f --- /dev/null +++ b/server/rust/metaobjects-codegen/src/docs_pages.rs @@ -0,0 +1,959 @@ +//! The documentation pages written from the docs view: `requirements.toon`, +//! `agent/requirements.md` (with the ledger it embeds) and the model-only `agent/schema.md`. +//! +//! The port of TypeScript's `docs-view-pages.ts`, `requirements-markdown.ts`, +//! `requirements-toon.ts` and `agent-requirements-page.ts`, over the view +//! ([`metaobjects::docs_view::build`]) and nothing else: the requirement rows come from its +//! `requirements`, the node index from each requirement's resolved `implementedBy`, and the +//! schema from its `storage` plus the members of the nodes it links. Every page is a shared +//! Mustache template (`templates/requirements/`, `templates/agent/`, embedded in +//! [`crate::metamodel_templates`]) 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. Rows and data are +//! pinned by `fixtures/docs-page-conformance/`. +//! +//! Rust holds no requirement ledger of its own (the resolved gate is not ported), so the rows are +//! every `requirement.*` node of the model, and a dependency's requirement the project did not +//! inherit is not left out. + +use std::collections::{BTreeSet, HashMap}; + +use metaobjects::docs_view; +use metaobjects::naming::NamingRegistry; +use metaobjects_render::{Body, Provider, RenderRequest, render}; +use serde_json::{Map, Value, json}; + +use crate::generator::{GenContext, GenError}; +use crate::metamodel_templates::shipped_template; + +/// The shared templates, by ref. +pub const REQUIREMENTS_PAGE_REF: &str = "requirements/requirements.md"; +pub const REQUIREMENTS_TOON_REF: &str = "requirements/requirements.toon"; +pub const AGENT_REQUIREMENTS_PAGE_REF: &str = "agent/requirements.md"; +pub const AGENT_SCHEMA_PAGE_REF: &str = "agent/schema.md"; + +/// The marker on the first line of every agent page. It is part of the shared contract: the +/// corpus pins it byte for byte. +pub const GENERATED_MARKER: &str = + ""; + +const REQUIREMENTS_TOON_FIELDS: [&str; 7] = [ + "path", + "subType", + "level", + "status", + "disposition", + "claims", + "statement", +]; + +fn s<'a>(v: &'a Value, key: &str) -> &'a str { + v.get(key).and_then(Value::as_str).unwrap_or_default() +} + +fn arr<'a>(v: &'a Value, key: &str) -> &'a [Value] { + v.get(key) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} + +/// JavaScript's string order: by UTF-16 code unit. +fn by_code_unit(a: &str, b: &str) -> std::cmp::Ordering { + a.encode_utf16().cmp(b.encode_utf16()) +} + +/// `text.replace(/\s+/g, " ").trim()`. +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +fn md_cell(text: &str) -> String { + text.replace('|', "\\|") +} + +// ---- rows ----------------------------------------------------------------------------- + +/// A view string as a row value: "" is absent. +fn put_opt(row: &mut Map, key: &str, text: &str) { + if !text.is_empty() { + row.insert(key.to_string(), Value::String(text.to_string())); + } +} + +/// Every requirement of the view, nested ones included, as render-ready rows in document +/// order. An empty list for a model declaring none, which is what lets the surface write +/// nothing. A value the TypeScript leaves `undefined` is an ABSENT key here. +pub fn requirement_rows(view: &Value) -> Vec { + arr(view, "requirements") + .iter() + .map(|r| { + let mut row = Map::new(); + row.insert("path".into(), json!(s(r, "address"))); + row.insert("depth".into(), r["depth"].clone()); + put_opt(&mut row, "title", s(r, "title")); + row.insert("subType".into(), json!(s(r, "subType"))); + if !r["level"].is_null() { + row.insert("level".into(), r["level"].clone()); + } + put_opt(&mut row, "status", s(r, "status")); + put_opt(&mut row, "disposition", s(r, "disposition")); + row.insert("trackedBy".into(), r["trackedBy"].clone()); + put_opt(&mut row, "statement", s(r, "statement")); + put_opt(&mut row, "counterexample", s(r, "counterexample")); + put_opt(&mut row, "description", s(r, "description")); + let claims = arr(r, "implementedBy"); + row.insert( + "implementedBy".into(), + Value::Array(claims.iter().map(|l| json!(s(l, "ref"))).collect()), + ); + let mut concerns: Vec<&str> = Vec::new(); + for l in claims.iter().filter(|l| l["resolves"] == Value::Bool(true)) { + let kind = s(&l["target"], "kind"); + if !concerns.contains(&kind) { + concerns.push(kind); + } + } + row.insert("claimedConcerns".into(), json!(concerns)); + Value::Object(row) + }) + .collect() +} + +// ---- requirements.md (the ledger) ----------------------------------------------------- + +/// `##` for a root-level requirement, deepening with nesting; `#` is the page title. +fn heading(depth: u64) -> String { + "#".repeat(usize::try_from(depth + 2).unwrap_or(6).min(6)) +} + +fn normalize_name(text: &str) -> String { + text.to_lowercase() + .chars() + .filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + .collect() +} + +/// True when the title says nothing the path's LEAF segment does not already say. +fn title_restates_leaf(path: &str, title: &str) -> bool { + let leaf = path.rfind('.').map_or(path, |i| &path[i + 1..]); + normalize_name(leaf) == normalize_name(title) +} + +fn heading_line(row: &Value) -> String { + let title = one_line(s(row, "title")); + let path = s(row, "path"); + let label = if title.is_empty() || title_restates_leaf(path, &title) { + String::new() + } else { + format!(" \u{2014} {title}") + }; + format!( + "{} {path}{label}", + heading(row["depth"].as_u64().unwrap_or(0)) + ) +} + +fn facts(row: &Value) -> String { + let mut parts = vec![format!("`{}`", s(row, "subType"))]; + if let Some(level) = row.get("level") { + parts.push(format!("**L{}**", metaobjects::json::js_display(level))); + } + if let Some(status) = row.get("status").and_then(Value::as_str) { + parts.push(format!("status: `{status}`")); + } + if let Some(d) = row.get("disposition").and_then(Value::as_str) { + parts.push(format!("disposition: `{d}`")); + } + let tracked: Vec<&str> = arr(row, "trackedBy") + .iter() + .filter_map(Value::as_str) + .collect(); + if !tracked.is_empty() { + parts.push(format!("tracked: {}", tracked.join(", "))); + } + parts.join(" \u{b7} ") +} + +/// One extra `#` on every line that starts a heading, capped at h6. +fn demote(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 4); + let mut at_line_start = true; + let mut rest = text; + while !rest.is_empty() { + if at_line_start { + let hashes = rest.bytes().take_while(|&b| b == b'#').count(); + if (1..=6).contains(&hashes) && rest[hashes..].starts_with(' ') { + out.push_str(&"#".repeat((hashes + 1).min(6))); + rest = &rest[hashes..]; + } + } + let Some(c) = rest.chars().next() else { break }; + out.push(c); + // The line terminators of a JavaScript multiline `^`. + at_line_start = matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'); + rest = &rest[c.len_utf8()..]; + } + out +} + +fn entry_of(row: &Value, embedded: bool) -> Value { + let line = |t: String| if embedded { demote(&t) } else { t }; + let mut entry = Map::new(); + entry.insert("heading".into(), json!(line(heading_line(row)))); + entry.insert("facts".into(), json!(line(facts(row)))); + if let Some(t) = row.get("statement").and_then(Value::as_str) { + entry.insert("statement".into(), json!(line(t.to_string()))); + } + if let Some(t) = row.get("counterexample").and_then(Value::as_str) { + entry.insert( + "counterexample".into(), + json!(line(format!("**Counterexample:** {t}"))), + ); + } + if let Some(t) = row.get("description").and_then(Value::as_str) { + entry.insert("description".into(), json!(line(t.to_string()))); + } + let refs: Vec = arr(row, "implementedBy") + .iter() + .filter_map(Value::as_str) + .map(|c| format!("`{c}`")) + .collect(); + if !refs.is_empty() { + entry.insert( + "implementedBy".into(), + json!(line(format!("**Implemented by:** {}", refs.join(", ")))), + ); + } + Value::Object(entry) +} + +/// 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. +pub fn requirements_ledger_data(rows: &[Value], embedded: bool) -> Value { + json!({ + "embedded": embedded, + "count": rows.len(), + "plural": if rows.len() == 1 { "" } else { "s" }, + "entries": rows.iter().map(|r| entry_of(r, embedded)).collect::>(), + }) +} + +// ---- requirements.toon ---------------------------------------------------------------- + +/// One cell as TOON writes it inside a comma-delimited row: a number bare, a string bare when +/// it is safe and quoted (with TOON's escapes) when it is not. +fn toon_cell(value: &Value) -> String { + let Value::String(text) = value else { + return metaobjects::json::js_display(value); + }; + if toon_is_safe(text) { + return text.clone(); + } + let mut out = String::from("\""); + for ch in text.chars() { + match ch { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// `-?[0-9]+(\.[0-9]+)?(e[+-]?[0-9]+)?`, case-insensitively, over the whole text. +fn numeric_like(text: &str) -> bool { + let b = text.as_bytes(); + let mut i = usize::from(b.first() == Some(&b'-')); + let digits = |i: &mut usize| { + let start = *i; + while *i < b.len() && b[*i].is_ascii_digit() { + *i += 1; + } + *i > start + }; + if !digits(&mut i) { + return false; + } + if b.get(i) == Some(&b'.') { + i += 1; + if !digits(&mut i) { + return false; + } + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + if !digits(&mut i) { + return false; + } + } + i == b.len() +} + +/// All digits with a leading zero (`007`): a TOON reader would take it for a number. +fn leading_zero_digits(text: &str) -> bool { + text.starts_with('0') && text.bytes().all(|b| b.is_ascii_digit()) +} + +fn toon_is_safe(text: &str) -> bool { + !text.is_empty() + && text.trim() == text + && !matches!(text, "true" | "false" | "null") + && !numeric_like(text) + && !leading_zero_digits(text) + && !text.starts_with('-') + && !text.chars().any(|c| { + matches!(c, ':' | '"' | '\\' | '[' | ']' | '{' | '}' | ',') || (c as u32) < 0x20 + }) +} + +/// What `requirements/requirements.toon.mustache` renders: every cell a finished literal. +pub fn requirements_toon_data(rows: &[Value]) -> Value { + let lines: Vec = rows + .iter() + .map(|r| { + let text = |key: &str| json!(r.get(key).and_then(Value::as_str).unwrap_or_default()); + let claims: Vec<&str> = arr(r, "implementedBy") + .iter() + .filter_map(Value::as_str) + .collect(); + let cells = [ + json!(s(r, "path")), + json!(s(r, "subType")), + r.get("level").cloned().unwrap_or_else(|| json!("")), + text("status"), + text("disposition"), + json!(claims.join(" ")), + text("statement"), + ]; + let line: Vec = cells.iter().map(toon_cell).collect(); + json!({ "line": line.join(",") }) + }) + .collect(); + json!({ + "count": rows.len(), + "fields": format!("{{{}}}", REQUIREMENTS_TOON_FIELDS.join(",")), + "rows": lines, + }) +} + +// ---- agent/requirements.md ------------------------------------------------------------ + +/// Claimed node to the requirements that claim it, sorted by the node's id. A claim that does +/// not resolve is left out (`meta verify` reports it). +fn node_index(view: &Value) -> Vec<(String, String, Vec)> { + let mut by_address: Vec<(String, String, Vec)> = Vec::new(); + let mut at: HashMap = HashMap::new(); + for r in arr(view, "requirements") { + for link in arr(r, "implementedBy") { + if link["resolves"] != Value::Bool(true) { + continue; + } + let target = &link["target"]; + let id = s(target, "id").to_string(); + let i = *at.entry(id.clone()).or_insert_with(|| { + by_address.push((id, s(target, "kind").to_string(), Vec::new())); + by_address.len() - 1 + }); + by_address[i].2.push(json!({ + "path": s(r, "address"), + "subType": s(r, "subType"), + "level": r["level"], + "status": s(r, "status"), + "statement": s(r, "statement"), + })); + } + } + by_address.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + by_address +} + +/// 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. +pub fn agent_requirements_page_data( + view: &Value, + render_ledger: impl Fn(&Value) -> Result, +) -> Result, E> { + let rows = requirement_rows(view); + if rows.is_empty() { + return Ok(None); + } + let index = node_index(view); + // The statements ride below the table: they are prose, and they repeat across nodes a + // shared architectural entry claims. + let mut stated: Vec<(String, String, String)> = Vec::new(); + for (_, _, claims) in &index { + for c in claims { + let statement = s(c, "statement"); + if statement.is_empty() { + continue; + } + let path = s(c, "path").to_string(); + let entry = ( + path.clone(), + s(c, "subType").to_string(), + statement.to_string(), + ); + match stated.iter_mut().find(|e| e.0 == path) { + Some(e) => *e = entry, + None => stated.push(entry), + } + } + } + stated.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + let statements: Vec = stated + .iter() + .map(|(path, sub_type, statement)| { + json!({ "path": path, "subType": sub_type, "statement": md_cell(&one_line(statement)) }) + }) + .collect(); + let node_index: Vec = index + .iter() + .map(|(address, concern, claims)| { + let cells: Vec = claims + .iter() + .map(|c| { + let level = c["level"] + .as_i64() + .map_or(String::new(), |l| format!(" L{l}")); + let status = match s(c, "status") { + "" => String::new(), + st => format!(" ({st})"), + }; + format!("`{}`{level}{status}", s(c, "path")) + }) + .collect(); + json!({ "address": address, "concern": concern, "claims": cells.join("
") }) + }) + .collect(); + let ledger = render_ledger(&requirements_ledger_data(&rows, true))?; + Ok(Some(json!({ + "generatedMarker": GENERATED_MARKER, + "hasNodeIndex": !node_index.is_empty(), + "nodeIndex": node_index, + "hasStatements": !statements.is_empty(), + "statements": statements, + "ledger": ledger.trim_end_matches('\n'), + }))) +} + +// ---- schema --------------------------------------------------------------------------- + +fn storage_key(name: &str, schema: &str) -> String { + if schema.is_empty() { + name.to_string() + } else { + format!("{schema}.{name}") + } +} + +/// The rows layer of the schema page, read off the view's storage: the shape `meta schema --as +/// json` prints, less its physical facts. +pub fn schema_rows(view: &Value) -> Value { + let storage = &view["storage"]; + let mut declared: Vec<(String, String)> = Vec::new(); + let mut tables = Vec::new(); + for t in arr(storage, "tables") { + declared.push(( + storage_key(s(t, "name"), s(t, "schema")), + s(&t["declaredBy"], "id").to_string(), + )); + let mut row = Map::new(); + row.insert("name".into(), json!(s(t, "name"))); + put_opt(&mut row, "schema", s(t, "schema")); + put_opt(&mut row, "description", s(t, "description")); + row.insert("primaryKey".into(), t["primaryKey"].clone()); + let columns: Vec = arr(t, "columns") + .iter() + .map(|c| { + let mut col = Map::new(); + col.insert("name".into(), json!(s(c, "name"))); + col.insert("nullable".into(), c["nullable"].clone()); + put_opt(&mut col, "identity", s(c, "identity")); + put_opt(&mut col, "description", s(c, "description")); + Value::Object(col) + }) + .collect(); + row.insert("columns".into(), Value::Array(columns)); + let fks: Vec = arr(t, "foreignKeys") + .iter() + .map(|f| json!({ "columns": f["columns"], "refTable": f["refTable"], "refColumns": f["refColumns"] })) + .collect(); + row.insert("foreignKeys".into(), Value::Array(fks)); + tables.push(Value::Object(row)); + } + let mut views = Vec::new(); + for v in arr(storage, "views") { + declared.push(( + storage_key(s(v, "name"), s(v, "schema")), + s(&v["declaredBy"], "id").to_string(), + )); + let mut row = Map::new(); + row.insert("name".into(), json!(s(v, "name"))); + put_opt(&mut row, "schema", s(v, "schema")); + views.push(Value::Object(row)); + } + declared.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + json!({ + "tables": tables, + "views": views, + "declaredBy": declared.into_iter().map(|(k, v)| (k, Value::String(v))).collect::>(), + }) +} + +/// Every member of every node, by id. +fn members_by_id(view: &Value) -> HashMap<&str, &Value> { + fn visit<'a>(m: &'a Value, out: &mut HashMap<&'a str, &'a Value>) { + out.insert(s(m, "id"), m); + for g in arr(m, "memberGroups") { + for c in arr(g, "members") { + visit(c, out); + } + } + } + let mut out = HashMap::new(); + for n in arr(view, "nodes") { + for g in arr(n, "memberGroups") { + for m in arr(g, "members") { + visit(m, &mut out); + } + } + } + out +} + +fn direct_members<'a>(n: &'a Value, type_name: &str) -> &'a [Value] { + arr(n, "memberGroups") + .iter() + .find(|g| s(g, "type") == type_name) + .map_or(&[], |g| arr(g, "members")) +} + +fn attr_value<'a>(attrs: &'a [Value], name: &str) -> Option<&'a Value> { + attrs + .iter() + .find(|a| s(a, "name") == name) + .map(|a| &a["value"]) +} + +/// A string attribute as a page prints it: a resolved reference by its link's label (what the +/// author wrote, relative to the model), anything else as its text. +fn attr_text(attrs: &[Value], name: &str) -> Option { + let a = attrs.iter().find(|a| s(a, "name") == name)?; + let value = a["value"].as_str()?; + let link = arr(a, "values").first().map(|v| &v["link"]); + let text = match link { + Some(l) if l.is_object() && l["unresolved"] != Value::Bool(true) => s(l, "label"), + _ => value, + }; + (!text.is_empty()).then(|| text.to_string()) +} + +fn cols(names: &[Value]) -> String { + if names.is_empty() { + return "\u{2014}".to_string(); + } + names + .iter() + .map(|c| format!("`{}`", c.as_str().unwrap_or_default())) + .collect::>() + .join(", ") +} + +fn key_cell(table: &Value, column: &str) -> String { + let pk = arr(table, "primaryKey"); + let mut roles: Vec = Vec::new(); + if pk.iter().any(|c| c.as_str() == Some(column)) { + roles.push(if pk.len() > 1 { "PK (composite)" } else { "PK" }.to_string()); + } + if let Some(fk) = arr(table, "foreignKeys") + .iter() + .find(|f| arr(f, "columns").iter().any(|c| c.as_str() == Some(column))) + { + roles.push(format!("FK \u{2192} `{}`", s(fk, "refTable"))); + } + roles.join(" \u{b7} ") +} + +/// The lineage text of a view column, from its field's `origin.*` member. +fn lineage_of(field: Option<&Value>) -> Option { + let origin = direct_members(field?, "origin").first()?; + let attrs = arr(origin, "attrs"); + let t = |name: &str| attr_text(attrs, name); + let via = |t: &dyn Fn(&str) -> Option| { + t("via").map_or(String::new(), |v| format!(" via `{v}`")) + }; + Some(match s(origin, "subType") { + "passthrough" => format!( + "passthrough from `{}`{}", + t("from").unwrap_or_else(|| "?".into()), + via(&t) + ), + "aggregate" => format!( + "`{}`{}{}", + t("agg").unwrap_or_else(|| "?".into()), + t("of").map_or(String::new(), |v| format!(" of `{v}`")), + via(&t) + ), + "first" => format!( + "first{}{}{}", + t("of").map_or(String::new(), |v| format!(" `{v}`")), + via(&t), + t("orderBy").map_or(String::new(), |v| format!(" ordered by `{v}`")) + ), + "computed" => "computed from a declared `@expr`".to_string(), + other => format!("`origin.{other}`"), + }) +} + +fn cardinality_phrase(cardinality: Option<&Value>, through: bool) -> &'static str { + match cardinality.and_then(Value::as_str) { + Some("many") if through => "many-to-many", + Some("many") => "one-to-many", + Some("one") => "many-to-one", + _ => "cardinality not declared", + } +} + +/// The data `agent/schema.md.mustache` renders for the model-only page, built from the view +/// alone. `has_migrate`: the project chose a `meta migrate` dialect (`migrate.dialect` in +/// `.metaobjects/config.json`). `None` when the model declares no table and no view: no page. +/// `not_own` names the objects that are another run's to generate (the run's reference nodes): +/// they are not the project's schema, so the page leaves them out. +pub fn agent_schema_page_data( + view: &Value, + has_migrate: bool, + not_own: &BTreeSet, +) -> Option { + let storage = &view["storage"]; + let own = |v: &&Value| !not_own.contains(s(&v["declaredBy"], "id")); + let tables: Vec<&Value> = arr(storage, "tables").iter().filter(own).collect(); + let views: Vec<&Value> = arr(storage, "views").iter().filter(own).collect(); + if tables.is_empty() && views.is_empty() { + return None; + } + let members = members_by_id(view); + let mut by_order: Vec<&Value> = arr(view, "nodes").iter().collect(); + by_order.sort_by_key(|n| n["order"].as_u64().unwrap_or(0)); + + let table_data: Vec = tables + .iter() + .map(|t| { + let k = storage_key(s(t, "name"), s(t, "schema")); + let described: Vec<&Value> = arr(t, "columns") + .iter() + .filter(|c| !s(c, "description").is_empty()) + .collect(); + let fks: Vec = arr(t, "foreignKeys") + .iter() + .map(|f| { + format!( + "{} \u{2192} `{}`({})", + cols(arr(f, "columns")), + s(f, "refTable"), + cols(arr(f, "refColumns")) + ) + }) + .collect(); + let columns: Vec = arr(t, "columns") + .iter() + .map(|c| { + let field = &c["field"]; + let (field_cell, declared_cell) = if field.is_null() { + (String::new(), String::new()) + } else { + let name = members.get(s(field, "id")).map_or("", |m| s(m, "name")); + (format!("`{name}`"), format!("`{}`", s(field, "kind"))) + }; + json!({ + "name": s(c, "name"), + "fieldCell": field_cell, + "declaredCell": declared_cell, + "sqlTypeCell": "", + "nullCell": if c["nullable"] == Value::Bool(true) { "yes" } else { "no" }, + "defaultCell": "", + "keyCell": key_cell(t, s(c, "name")), + }) + }) + .collect(); + let mut row = Map::new(); + row.insert("heading".into(), json!(format!("`{k}`"))); + row.insert("tableDeclaredBy".into(), json!(s(&t["declaredBy"], "id"))); + if !s(t, "description").is_empty() { + row.insert("tableDescription".into(), json!(one_line(s(t, "description")))); + } + row.insert("columns".into(), Value::Array(columns)); + row.insert("hasDescribed".into(), json!(!described.is_empty())); + row.insert( + "described".into(), + Value::Array( + described + .iter() + .map(|c| json!({ "name": s(c, "name"), "text": one_line(s(c, "description")) })) + .collect(), + ), + ); + row.insert("hasIndexes".into(), json!(false)); + row.insert("indexes".into(), json!([])); + row.insert("hasForeignKeys".into(), json!(!fks.is_empty())); + row.insert("foreignKeys".into(), json!(fks)); + row.insert("hasChecks".into(), json!(false)); + row.insert("checks".into(), json!([])); + Value::Object(row) + }) + .collect(); + + let view_data: Vec = views + .iter() + .map(|v| { + let lineage: Vec = arr(v, "columns") + .iter() + .filter_map(|c| { + let field = (!c["field"].is_null()) + .then(|| members.get(s(&c["field"], "id")).copied()) + .flatten(); + lineage_of(field).map(|text| json!({ "column": s(c, "name"), "text": text })) + }) + .collect(); + json!({ + "heading": format!("`{}`", storage_key(s(v, "name"), s(v, "schema"))), + "viewDeclaredBy": s(&v["declaredBy"], "id"), + "hasLineage": !lineage.is_empty(), + "lineage": lineage, + }) + }) + .collect(); + + // Every relationship as written, in declaration order of its object. + let mut relationships: Vec = Vec::new(); + for n in &by_order { + if s(n, "type") != "object" || not_own.contains(s(n, "id")) { + continue; + } + for rel in direct_members(n, "relationship") { + let attrs = arr(rel, "attrs"); + let through = attr_text(attrs, "through"); + let mut parts = vec![ + format!("`{}.{}`", s(n, "id"), s(rel, "name")), + format!("`{}`", s(rel, "subType")), + format!( + "{} \u{2192} `{}`", + cardinality_phrase(attr_value(attrs, "cardinality"), through.is_some()), + attr_text(attrs, "objectRef").unwrap_or_else(|| "?".into()) + ), + ]; + if let Some(t) = &through { + parts.push(format!("through `{t}`")); + } + if let Some(d) = attr_text(attrs, "onDelete") { + parts.push(format!("on delete `{d}`")); + } + relationships.push(parts.join(" \u{b7} ")); + } + } + + // Every enum field of a table-backed object, in declaration order of its object. + let table_backed: Vec<&str> = tables + .iter() + .flat_map(|t| arr(t, "objects").iter().map(|o| s(o, "id"))) + .collect(); + let mut enums: Vec = Vec::new(); + for n in &by_order { + if !table_backed.contains(&s(n, "id")) { + continue; + } + for f in direct_members(n, "field") { + if s(f, "subType") != "enum" { + continue; + } + let attrs = arr(f, "attrs"); + let list: Vec = match attr_value(attrs, "values") { + Some(Value::Array(items)) => { + items.iter().map(metaobjects::json::js_display).collect() + } + _ => Vec::new(), + }; + if list.is_empty() { + continue; + } + let storage = match attr_value(attrs, "intValueMap") { + Some(Value::Object(map)) => format!( + "int-backed ({})", + list.iter() + .map(|m| format!( + "{m}={}", + map.get(m) + .map_or("undefined".to_string(), metaobjects::json::js_display) + )) + .collect::>() + .join(", ") + ), + _ => "string-backed".to_string(), + }; + enums.push(json!({ + "field": format!("{}.{}", s(n, "id"), s(f, "name")), + "members": list.iter().map(|m| format!("`{m}`")).collect::>().join(", "), + "storage": storage, + })); + } + } + + let any_description = tables.iter().any(|t| { + !s(t, "description").is_empty() + || arr(t, "columns") + .iter() + .any(|c| !s(c, "description").is_empty()) + }); + Some(json!({ + "generatedMarker": GENERATED_MARKER, + "physical": false, + "dialect": "", + "hasMigrate": has_migrate, + "descriptionNudge": !any_description && !tables.is_empty(), + "hasTables": !table_data.is_empty(), + "tables": table_data, + "hasViews": !view_data.is_empty(), + "hasReportView": views.iter().any(|v| arr(v, "objects").iter().any(|o| s(o, "kind") == "object.report")), + "views": view_data, + "hasRelationships": !relationships.is_empty(), + "relationships": relationships, + "hasEnums": !enums.is_empty(), + "enums": enums, + })) +} + +/// A page ends with exactly one of its own line breaks (the templates end with one, so a page +/// always has one to keep); a page that ends without a break is returned as is. +pub fn end_with_one_newline(page: &str) -> String { + let body = page.trim_end_matches('\n').len(); + let keep = if body < page.len() { body + 1 } else { body }; + page[..keep].to_string() +} + +// ---- running the pages ---------------------------------------------------------------- + +/// Where a project's own templates live, from the project root. A same-named +/// `templates/.mustache` wins over the shipped one. +pub const TEMPLATE_DIR: &str = "templates"; +/// The failure of the docs page generators. +pub const ERR_DOC_PAGE: &str = "ERR_DOC_PAGE"; + +/// Resolves a template ref: the project's `templates/.mustache` if it has one, else the +/// shipped text. +pub struct DocsTemplates { + project_templates: std::path::PathBuf, +} + +impl DocsTemplates { + pub fn new(ctx: &GenContext<'_>) -> Self { + Self { + project_templates: ctx.collection.config_dir.join(TEMPLATE_DIR), + } + } +} + +impl Provider for DocsTemplates { + fn resolve(&self, reference: &str) -> Option { + std::fs::read_to_string(self.project_templates.join(format!("{reference}.mustache"))) + .ok() + .or_else(|| shipped_template(reference).map(str::to_string)) + } +} + +/// The docs view of the run's model, with the project's physical naming and no build inputs +/// (no verify ledger, generated files or routes): the input every page is built from. +pub fn view_of(ctx: &GenContext<'_>) -> Value { + docs_view::build_with_naming( + ctx.tree, + ctx.root, + None, + None, + None, + &NamingRegistry::builtin(), + &ctx.collection.physical_naming, + ) +} + +/// Whether the project chose a `meta migrate` dialect (`migrate.dialect`). +pub fn has_migrate(ctx: &GenContext<'_>) -> bool { + ctx.collection + .config + .migrate + .as_ref() + .is_some_and(|m| m.dialect.is_some()) +} + +/// Render one page from a template ref, naming the page when the template fails. +pub fn render_doc_page( + reference: &str, + data: &Value, + templates: &DocsTemplates, + path: &str, +) -> Result { + let request = RenderRequest::new(Body::Ref(reference), data, templates).format("markdown"); + render(&request).map_err(|e| { + GenError::new( + ERR_DOC_PAGE, + format!("failed rendering '{reference}' for '{path}': {e}"), + ) + }) +} + +/// `requirements.toon`: the ledger for tools. `None` for a model declaring no requirement. +pub fn requirements_toon_page( + view: &Value, + templates: &DocsTemplates, +) -> Result, GenError> { + let rows = requirement_rows(view); + if rows.is_empty() { + return Ok(None); + } + render_doc_page( + REQUIREMENTS_TOON_REF, + &requirements_toon_data(&rows), + templates, + "requirements.toon", + ) + .map(Some) +} + +/// `agent/requirements.md`. `None` for a model declaring no requirement. +pub fn agent_requirements_page( + view: &Value, + templates: &DocsTemplates, + path: &str, +) -> Result, GenError> { + let ledger = + |data: &Value| render_doc_page(REQUIREMENTS_PAGE_REF, data, templates, "requirements.md"); + match agent_requirements_page_data(view, ledger)? { + Some(data) => { + render_doc_page(AGENT_REQUIREMENTS_PAGE_REF, &data, templates, path).map(Some) + } + None => Ok(None), + } +} + +/// The model-only `agent/schema.md`. `None` for a model with no table and no view. +pub fn agent_schema_page( + view: &Value, + has_migrate: bool, + not_own: &BTreeSet, + templates: &DocsTemplates, + path: &str, +) -> Result, GenError> { + match agent_schema_page_data(view, has_migrate, not_own) { + Some(data) => { + let page = render_doc_page(AGENT_SCHEMA_PAGE_REF, &data, templates, path)?; + Ok(Some(end_with_one_newline(&page))) + } + None => Ok(None), + } +} diff --git a/server/rust/metaobjects-codegen/src/docs_site.rs b/server/rust/metaobjects-codegen/src/docs_site.rs index 5f7d6e160d..6bdd8935df 100644 --- a/server/rust/metaobjects-codegen/src/docs_site.rs +++ b/server/rust/metaobjects-codegen/src/docs_site.rs @@ -243,12 +243,14 @@ impl Generator for DocsSite { } }; let manifest = files.map(|f| Value::Object(f.clone())); - let view = docs_view::build( + let view = docs_view::build_with_naming( ctx.tree, ctx.root, verify.as_ref(), manifest.as_ref(), routes.as_ref(), + &metaobjects::naming::NamingRegistry::builtin(), + &ctx.collection.physical_naming, ); let owned = project.join(OWNED_DOCS_SITE_DIR); let title = self.title.clone().unwrap_or_else(|| { diff --git a/server/rust/metaobjects-codegen/src/eject.rs b/server/rust/metaobjects-codegen/src/eject.rs index 259161acbc..af0affb8b2 100644 --- a/server/rust/metaobjects-codegen/src/eject.rs +++ b/server/rust/metaobjects-codegen/src/eject.rs @@ -251,6 +251,33 @@ pub const REFERENCES: &[Reference] = &[ (reads no model; templates/metamodel/ in the project wins)", source: include_str!("metamodel_docs.rs"), }, + Reference { + name: "requirements", + tier: "neutral", + opt_in: true, + package_only: false, + layer: "docs", + module: "requirements_docs", + type_name: "RequirementsGenerator", + needs: &[], + summary: "the requirement ledger as requirements.toon, for tools, read off the docs \ + view (templates/requirements/ in the project wins)", + source: include_str!("requirements_docs.rs"), + }, + Reference { + name: "agent-docs", + tier: "neutral", + opt_in: true, + package_only: false, + layer: "docs", + module: "agent_docs", + type_name: "AgentDocsGenerator", + needs: &[], + summary: "pages for a coding agent: agent/requirements.md (node index and ledger) and \ + the model-only agent/schema.md, read off the docs view (templates/agent/ in \ + the project wins; agent/ui.md stays TypeScript)", + source: include_str!("agent_docs.rs"), + }, Reference { name: "docs-site", tier: "neutral", diff --git a/server/rust/metaobjects-codegen/src/generator_list.rs b/server/rust/metaobjects-codegen/src/generator_list.rs index 9723b5fbe1..38cc9f64ca 100644 --- a/server/rust/metaobjects-codegen/src/generator_list.rs +++ b/server/rust/metaobjects-codegen/src/generator_list.rs @@ -14,7 +14,7 @@ //! ignored. Of the shipped generators only `metamodel-docs` takes one (`subDir`). The list carries no layer or set settings, //! because a layer is only a generator. A project with no such file runs every generator its host //! offers but the opt-in ones (the `service-routes` transport, which brings a web framework into -//! the build, and `metamodel-docs`, which writes reference pages no project asked for), which is +//! the build, and the docs generators `metamodel-docs`, `requirements` and `agent-docs`, which write pages no project asked for), which is //! what a project did before the file existed. A list may leave a generator //! out; generated files of a generator that left the list are swept like those of any //! generator that stops emitting them (an edited one is refused by name). @@ -246,12 +246,14 @@ mod tests { assert_eq!(all.len(), without_transport.len() + 1); assert_eq!(without_transport, names(&parse(&scaffold(false)).unwrap())); assert!(check(&all, &shipped_names()).is_ok()); - for docs in ["metamodel-docs", "docs-site"] { + for docs in ["metamodel-docs", "requirements", "agent-docs", "docs-site"] { assert!(!all.iter().any(|n| n == docs), "{docs}"); } assert!( !runs_unlisted("service-routes") && !runs_unlisted("metamodel-docs") + && !runs_unlisted("requirements") + && !runs_unlisted("agent-docs") && !runs_unlisted("docs-site") && runs_unlisted("entity") ); @@ -316,7 +318,7 @@ mod tests { let e = check(&s(&["entity", "nope"]), &available).unwrap_err(); assert!( e.contains("\"nope\"") - && e.contains("available: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt, metamodel-docs"), + && e.contains("available: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt, metamodel-docs, requirements, agent-docs"), "{e}" ); let e = check(&s(&["client"]), &available).unwrap_err(); diff --git a/server/rust/metaobjects-codegen/src/lib.rs b/server/rust/metaobjects-codegen/src/lib.rs index 5d4b11d5e6..0923f5db4d 100644 --- a/server/rust/metaobjects-codegen/src/lib.rs +++ b/server/rust/metaobjects-codegen/src/lib.rs @@ -18,9 +18,11 @@ // compiles here and as a project's owned copy (`cargo meta eject`). extern crate self as metaobjects_codegen; +pub mod agent_docs; pub mod client; pub mod commands; pub mod contract_types; +pub mod docs_pages; pub mod docs_site; pub mod eject; pub mod emitted; @@ -41,12 +43,14 @@ pub mod plan; pub mod project; pub mod render_helper; pub mod repository; +pub mod requirements_docs; pub mod rules_names; pub mod service; pub mod service_routes; pub mod sha256; pub mod writer; +pub use agent_docs::AgentDocsGenerator; pub use client::ClientGenerator; pub use commands::CommandsGenerator; pub use contract_types::ContractTypesGenerator; @@ -65,6 +69,7 @@ pub use output_parser::OutputParserGenerator; pub use output_prompt::OutputPromptGenerator; pub use render_helper::{RenderHelperGenerator, TemplateCheck, check_templates}; pub use repository::RepositoryGenerator; +pub use requirements_docs::RequirementsGenerator; pub use rules_names::RulesNamesGenerator; pub use service::ServiceGenerator; pub use service_routes::ServiceRoutesGenerator; @@ -84,6 +89,8 @@ pub fn shipped_generators() -> Vec> { Box::new(OutputParserGenerator), Box::new(OutputPromptGenerator), Box::new(MetamodelDocsGenerator), + Box::new(RequirementsGenerator), + Box::new(AgentDocsGenerator), Box::new(DocsSiteGenerator), ] } diff --git a/server/rust/metaobjects-codegen/src/metamodel_templates.rs b/server/rust/metaobjects-codegen/src/metamodel_templates.rs index 516a6bf401..b0500b0c9e 100644 --- a/server/rust/metaobjects-codegen/src/metamodel_templates.rs +++ b/server/rust/metaobjects-codegen/src/metamodel_templates.rs @@ -1,4 +1,4 @@ -//! The shipped templates of the `metamodel-docs` generator: the shared `templates/metamodel/` +//! The shipped templates of the `metamodel-docs`, `requirements` and `agent-docs` generators: the shared `templates/metamodel/` //! Mustache set every port renders, synced into this crate by `scripts/sync-doc-templates.sh` //! and embedded here, so an ejected copy of the generator (which cannot `include_str!` them //! from its own directory) reads them through [`shipped_template`]. @@ -8,6 +8,11 @@ use std::collections::BTreeMap; const INDEX: &str = include_str!("../templates/metamodel/index.md.mustache"); const PROVIDERS: &str = include_str!("../templates/metamodel/providers.md.mustache"); const TYPE_PAGE: &str = include_str!("../templates/metamodel/type-page.md.mustache"); +const REQUIREMENTS_MD: &str = include_str!("../templates/requirements/requirements.md.mustache"); +const REQUIREMENTS_TOON: &str = + include_str!("../templates/requirements/requirements.toon.mustache"); +const AGENT_REQUIREMENTS: &str = include_str!("../templates/agent/requirements.md.mustache"); +const AGENT_SCHEMA: &str = include_str!("../templates/agent/schema.md.mustache"); const PROVIDER_DESCRIPTIONS: &str = include_str!("../templates/metamodel/provider-descriptions.json"); @@ -17,6 +22,10 @@ pub fn shipped_template(reference: &str) -> Option<&'static str> { "metamodel/index.md" => Some(INDEX), "metamodel/providers.md" => Some(PROVIDERS), "metamodel/type-page.md" => Some(TYPE_PAGE), + "requirements/requirements.md" => Some(REQUIREMENTS_MD), + "requirements/requirements.toon" => Some(REQUIREMENTS_TOON), + "agent/requirements.md" => Some(AGENT_REQUIREMENTS), + "agent/schema.md" => Some(AGENT_SCHEMA), _ => None, } } diff --git a/server/rust/metaobjects-codegen/src/plan.rs b/server/rust/metaobjects-codegen/src/plan.rs index f85acbcb2d..250e416ce7 100644 --- a/server/rust/metaobjects-codegen/src/plan.rs +++ b/server/rust/metaobjects-codegen/src/plan.rs @@ -2103,3 +2103,10 @@ fn strongly_connected(adjacency: &[Vec]) -> Vec { // The shipped Mustache templates of the `metamodel-docs` generator, reached through the // engine surface so an owned copy of that generator reads them without a path into this crate. pub use crate::metamodel_templates::{shipped_provider_descriptions, shipped_template}; + +// The docs page builders of the `requirements` and `agent-docs` generators (rows, page data and +// the rendered pages, read off the docs view), reached through the same surface. +pub use crate::docs_pages::{ + DocsTemplates, agent_requirements_page, agent_schema_page, has_migrate, requirements_toon_page, + view_of, +}; diff --git a/server/rust/metaobjects-codegen/src/requirements_docs.rs b/server/rust/metaobjects-codegen/src/requirements_docs.rs new file mode 100644 index 0000000000..5a8bf9e2a0 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/requirements_docs.rs @@ -0,0 +1,45 @@ +//! The `requirements` generator: the requirement ledger as `requirements.toon`, for tools. +//! People read the ledger in the explorer (`docs-site`); the human `requirements.md` page is +//! retired. +//! +//! The page is the shared `templates/requirements/requirements.toon.mustache`, rendered over +//! the rows read off the docs view (`metaobjects_codegen::plan`'s docs page builders). A model +//! declaring no `requirement.*` node gets no file. A project's own +//! `templates/requirements/requirements.toon.mustache` wins over the shipped one. + +use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError, Generator}; +use metaobjects_codegen::plan::{DocsTemplates, requirements_toon_page, view_of}; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; + +/// Where a project's own templates live, from the project root. +const TEMPLATE_DIR: &str = "templates/requirements"; +const TOON_FILE: &str = "requirements.toon"; + +/// The requirements generator. +#[derive(Debug, Clone, Copy, Default)] +pub struct RequirementsGenerator; + +impl Generator for RequirementsGenerator { + fn name(&self) -> &str { + "requirements" + } + + fn identity(&self) -> String { + format!("requirements:{FORMAT}") + } + + fn extra_inputs(&self) -> Vec { + vec![TEMPLATE_DIR.to_string()] + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + let templates = DocsTemplates::new(ctx); + let page = requirements_toon_page(&view_of(ctx), &templates)?; + Ok(page + .map(|text| EmittedFile::new(TOON_FILE, text)) + .into_iter() + .collect()) + } +} diff --git a/server/rust/metaobjects-codegen/templates/agent/requirements.md.mustache b/server/rust/metaobjects-codegen/templates/agent/requirements.md.mustache new file mode 100644 index 0000000000..cb7cba06cb --- /dev/null +++ b/server/rust/metaobjects-codegen/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/rust/metaobjects-codegen/templates/agent/schema.md.mustache b/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache new file mode 100644 index 0000000000..ad91a93c2f --- /dev/null +++ b/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache @@ -0,0 +1,123 @@ +{{{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. +{{#hasMigrate}} +- 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. +{{/hasMigrate}} +{{^hasMigrate}} +- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +{{/hasMigrate}} +- `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 {{#hasMigrate}}`meta migrate`{{/hasMigrate}}{{^hasMigrate}}`meta schema`{{/hasMigrate}} 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/rust/metaobjects-codegen/templates/requirements/requirements.md.mustache b/server/rust/metaobjects-codegen/templates/requirements/requirements.md.mustache new file mode 100644 index 0000000000..a200094478 --- /dev/null +++ b/server/rust/metaobjects-codegen/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/rust/metaobjects-codegen/templates/requirements/requirements.toon.mustache b/server/rust/metaobjects-codegen/templates/requirements/requirements.toon.mustache new file mode 100644 index 0000000000..cae64ef896 --- /dev/null +++ b/server/rust/metaobjects-codegen/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/rust/metaobjects-codegen/tests/common/mod.rs b/server/rust/metaobjects-codegen/tests/common/mod.rs index 38f28dedf3..ca8c49825c 100644 --- a/server/rust/metaobjects-codegen/tests/common/mod.rs +++ b/server/rust/metaobjects-codegen/tests/common/mod.rs @@ -180,13 +180,19 @@ pub fn cargo(dir: &Path, args: &[&str]) -> std::process::Output { .expect("cargo runs") } -/// The shipped generators that write crates: every one but the two docs generators, -/// `metamodel-docs` and `docs-site`, whose pages are not a crate. Each is held to its own corpus -/// (`tests/metamodel_docs.rs`, `tests/docs_site.rs`). +/// The shipped generators that write crates: every one but the docs generators, +/// `metamodel-docs`, `requirements`, `agent-docs` and `docs-site`, whose pages are not a crate. +/// Each is held to its own corpus (`tests/metamodel_docs.rs`, `tests/docs_page_conformance.rs`, +/// `tests/docs_site.rs`). pub fn crate_generators() -> Vec> { shipped_generators() .into_iter() - .filter(|g| !matches!(g.name(), "metamodel-docs" | "docs-site")) + .filter(|g| { + !matches!( + g.name(), + "metamodel-docs" | "requirements" | "agent-docs" | "docs-site" + ) + }) .collect() } diff --git a/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs b/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs new file mode 100644 index 0000000000..ba7aeecd0b --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs @@ -0,0 +1,181 @@ +//! The docs page corpus (`fixtures/docs-page-conformance/`): the pages every port writes from +//! its docs view, `requirements.toon`, `agent/requirements.md` and the model-only +//! `agent/schema.md`. Per case, in order: the rows the builders read off the view, the page data, +//! then the bytes the `requirements` and `agent-docs` generators write through the engine. The +//! set of pages is pinned too: a page the case does not list must not be written. + +mod common; + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use metaobjects::docs_view; +use metaobjects::loader::Loader; +use metaobjects::providers::{compose_registry, core_providers}; +use metaobjects_codegen::docs_pages::{ + REQUIREMENTS_PAGE_REF, agent_requirements_page_data, agent_schema_page_data, requirement_rows, + requirements_ledger_data, requirements_toon_data, schema_rows, +}; +use metaobjects_codegen::plan::shipped_template; +use metaobjects_codegen::render::{Body, Provider, RenderRequest, render}; +use serde_json::Value; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/docs-page-conformance/cases") +} + +struct Shipped; +impl Provider for Shipped { + fn resolve(&self, reference: &str) -> Option { + shipped_template(reference).map(str::to_string) + } +} + +fn walk(dir: &Path, prefix: &str, out: &mut BTreeMap) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.map(Result::unwrap) { + let name = entry.file_name().to_string_lossy().to_string(); + if entry.path().is_dir() { + walk(&entry.path(), &format!("{prefix}{name}/"), out); + } else { + out.insert( + format!("{prefix}{name}"), + std::fs::read_to_string(entry.path()).unwrap(), + ); + } + } +} + +fn meta_files(input: &Path) -> Vec<(String, String)> { + let mut files: Vec<(String, String)> = std::fs::read_dir(input) + .unwrap() + .map(Result::unwrap) + .map(|e| e.file_name().to_string_lossy().to_string()) + .filter(|n| n.starts_with("meta.") && n.ends_with(".json")) + .map(|n| (n.clone(), std::fs::read_to_string(input.join(&n)).unwrap())) + .collect(); + files.sort(); + files +} + +fn json(text: &str) -> Value { + serde_json::from_str(text).unwrap() +} + +fn view_of_case(input: &Path) -> Value { + let mut registry = compose_registry(&core_providers()).unwrap(); + registry.seal(); + let loaded = Loader::new(®istry) + .strict(true) + .load_sources(&meta_files(input)); + assert!(loaded.errors.is_empty(), "{:?}", loaded.errors); + docs_view::build(&loaded.tree, loaded.root, None, None, None) +} + +fn page(reference: &str, data: &Value) -> String { + render(&RenderRequest::new(Body::Ref(reference), data, &Shipped).format("markdown")).unwrap() +} + +/// The rows and the page data, by path under `expected/`, as the builders make them. +fn built(view: &Value, has_migrate: bool) -> BTreeMap { + let mut out = BTreeMap::new(); + let rows = requirement_rows(view); + if !rows.is_empty() { + out.insert("rows/requirements.json".into(), Value::Array(rows.clone())); + out.insert( + "data/ledger.md.json".into(), + requirements_ledger_data(&rows, true), + ); + out.insert( + "data/requirements.toon.json".into(), + requirements_toon_data(&rows), + ); + } + let ledger = |d: &Value| Ok::<_, String>(page(REQUIREMENTS_PAGE_REF, d)); + if let Some(d) = agent_requirements_page_data(view, ledger).unwrap() { + out.insert("data/agent-requirements.md.json".into(), d); + } + if let Some(d) = agent_schema_page_data(view, has_migrate, &Default::default()) { + out.insert("data/agent-schema.md.json".into(), d); + out.insert("rows/schema.json".into(), schema_rows(view)); + } + out +} + +#[test] +fn every_case_reproduces_its_rows_data_and_pages() { + let mut cases: Vec = std::fs::read_dir(corpus()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.is_dir()) + .collect(); + cases.sort(); + assert!(cases.len() >= 4, "the corpus has its cases: {cases:?}"); + let mut failures = Vec::new(); + for case in &cases { + let name = case.file_name().unwrap().to_string_lossy().to_string(); + let input = case.join("input"); + let config = std::fs::read_to_string(input.join(".metaobjects/config.json")).ok(); + let has_migrate = config + .as_deref() + .is_some_and(|c| json(c)["migrate"]["dialect"].is_string()); + let mut expected = BTreeMap::new(); + walk(&case.join("expected"), "", &mut expected); + + // 1 and 2: rows, then page data, as JSON values. + let view = view_of_case(&input); + let built = built(&view, has_migrate); + for (path, value) in &built { + match expected.get(path) { + Some(text) if json(text) == *value => {} + Some(_) => failures.push(format!("{name}: {path} differs")), + None => failures.push(format!("{name}: {path} is built but not expected")), + } + } + for path in expected.keys().filter(|p| p.ends_with(".json")) { + if !built.contains_key(path) { + failures.push(format!("{name}: {path} is expected but not built")); + } + } + + // 3: the bytes the generators write, through the engine. + let p = common::Scratch::project("docs-page", &[]); + for (file, text) in meta_files(&input) { + p.write(&format!("metaobjects/{file}"), &text); + } + if let Some(c) = &config { + // The corpus config carries only the setting a case sets; this port's config reader + // also wants the `schema_version` every real config has. + let mut c = json(c); + c["schema_version"] = 1.into(); + p.write(".metaobjects/config.json", &c.to_string()); + } + p.write( + "metaobjects.config.json", + r#"{ "generators": ["requirements", "agent-docs"] }"#, + ); + let mut opts = metaobjects_codegen::RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + metaobjects_codegen::run(&opts, &metaobjects_codegen::shipped_generators()) + .unwrap_or_else(|e| panic!("{name}: gen failed: {e}")); + let mut written = BTreeMap::new(); + walk(&p.path().join("generated"), "", &mut written); + let pages: BTreeMap<&String, &String> = expected + .iter() + .filter(|(k, _)| !k.starts_with("data/") && !k.starts_with("rows/")) + .collect(); + let got: Vec<&String> = written.keys().collect(); + let want: Vec<&String> = pages.keys().copied().collect(); + if got != want { + failures.push(format!("{name}: pages written {got:?}, expected {want:?}")); + } + for (path, text) in pages { + if written.get(path) != Some(text) { + failures.push(format!("{name}: {path} bytes differ")); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/server/rust/metaobjects-codegen/tests/docs_site.rs b/server/rust/metaobjects-codegen/tests/docs_site.rs index 74ff678152..20fdc780ba 100644 --- a/server/rust/metaobjects-codegen/tests/docs_site.rs +++ b/server/rust/metaobjects-codegen/tests/docs_site.rs @@ -49,14 +49,14 @@ fn the_model_script_is_typescripts_bytes() { // The title carries U+2028, which JSON.stringify leaves unescaped. // explorerModelScript({ title: "Shop \u2028", footer: "v1", texts, templates, view }) in // @metaobjectsdev/docs-site, over the same shop view, gives this stamp and these bytes. - assert_eq!(stamp, "05b57283a47416e2"); + assert_eq!(stamp, "33fd741544d5a480"); assert_eq!( sha256_hex(script.as_bytes()), - "02f2d4321101c0ab9fa9e22db542ff8f71f1e952748e8f894d388bd43feeb6bc" + "c649aa99ef4c570149d6ce06f102738524db766915829a889b39f884af061070" ); assert_eq!( metaobjects::docs_view::stamp_script(&stamp), - "window.MO_STAMP = \"05b57283a47416e2\";\n" + "window.MO_STAMP = \"33fd741544d5a480\";\n" ); } diff --git a/server/rust/metaobjects-codegen/tests/reference_nodes.rs b/server/rust/metaobjects-codegen/tests/reference_nodes.rs index 4d64896b9c..88fc44ab51 100644 --- a/server/rust/metaobjects-codegen/tests/reference_nodes.rs +++ b/server/rust/metaobjects-codegen/tests/reference_nodes.rs @@ -6,7 +6,7 @@ mod common; use common::Scratch; use metaobjects_codegen::generator::GenContext; use metaobjects_codegen::project::load_project; -use metaobjects_codegen::{EntityGenerator, Generator}; +use metaobjects_codegen::{AgentDocsGenerator, EntityGenerator, Generator}; const CONFIG: &str = r#"{ "schema_version": 1, "sources": [ { "path": "model" }, { "path": "replies", "reference": true } ] }"#; @@ -61,3 +61,55 @@ fn a_reference_node_is_loaded_and_not_generated() { "the reference value object is not emitted:\n{all}" ); } + +const OWN_TABLES: &str = r#"{ "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } } +] } }"#; + +const REPLY_TABLES: &str = r#"{ "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Archive", "children": [ + { "source.rdb": { "@table": "archives" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } } +] } }"#; + +#[test] +fn the_agent_schema_page_leaves_a_reference_node_out() { + // agent/schema.md documents the project's own storage; a reference node is another run's. + let project = Scratch::project( + "reference-schema", + &[ + (".metaobjects/config.json", CONFIG), + ("model/meta.own.json", OWN_TABLES), + ("replies/meta.replies.json", REPLY_TABLES), + ], + ); + let loaded = load_project(project.path(), None, false).expect("the model loads clean"); + let ctx = GenContext { + tree: &loaded.result.tree, + root: loaded.result.root, + entities: &[], + collection: &loaded.collection, + reference_nodes: &loaded.reference_nodes, + generated_files: None, + }; + let files = AgentDocsGenerator.generate(&ctx).expect("generates"); + let schema = files + .iter() + .find(|f| f.path == "agent/schema.md") + .expect("agent-docs writes the schema page"); + assert!( + schema.content.contains("acme::Ticket"), + "the project's own table is listed" + ); + assert!( + !schema.content.contains("Archive") && !schema.content.contains("archives"), + "the reference node's table is not listed:\n{}", + schema.content + ); +} diff --git a/server/rust/metaobjects/src/docs_view.rs b/server/rust/metaobjects/src/docs_view.rs index e8e90b5578..624902c4b5 100644 --- a/server/rust/metaobjects/src/docs_view.rs +++ b/server/rust/metaobjects/src/docs_view.rs @@ -20,6 +20,7 @@ use serde_json::{Map, Value, json}; use crate::json::{js_quote, to_js_compact, to_js_pretty}; use crate::loader::{is_ref_bearing_attr, reference_targets, split_child_tail}; +use crate::naming::{NamingRegistry, PhysicalNaming}; use crate::node::{NodeId, PACKAGE_SEP, Tree}; use crate::parser::TYPE_OBJECT; use crate::serializer::normalize; @@ -113,9 +114,33 @@ pub fn build( manifest: Option<&Value>, routes: Option<&Value>, ) -> Value { - Build::new(tree, root).run(verify, manifest, routes) + build_with_naming( + tree, + root, + verify, + manifest, + routes, + &NamingRegistry::builtin(), + &PhysicalNaming::default(), + ) +} + +/// [`build`] with the project's physical naming (the `naming` block of +/// `.metaobjects/config.json`), which names the tables and columns of the `storage` section. +pub fn build_with_naming( + tree: &Tree, + root: NodeId, + verify: Option<&Value>, + manifest: Option<&Value>, + routes: Option<&Value>, + registry: &NamingRegistry, + naming: &PhysicalNaming, +) -> Value { + Build::new(tree, root, registry, naming).run(verify, manifest, routes) } +mod storage; + // ---- the walk ------------------------------------------------------------------------------ /// A node as walked: where it sits, and the ids and pages it gets. Indexes are into @@ -149,6 +174,8 @@ struct Ledger { } struct Build<'t> { + registry: &'t NamingRegistry, + naming: &'t PhysicalNaming, tree: &'t Tree, root: NodeId, objects: ObjectIndex, @@ -161,8 +188,15 @@ struct Build<'t> { } impl<'t> Build<'t> { - fn new(tree: &'t Tree, root: NodeId) -> Self { + fn new( + tree: &'t Tree, + root: NodeId, + registry: &'t NamingRegistry, + naming: &'t PhysicalNaming, + ) -> Self { let mut b = Self { + registry, + naming, tree, root, objects: ObjectIndex::build(tree, root), @@ -886,6 +920,7 @@ impl<'t> Build<'t> { "requirements": reqs, "advisories": advisories, "slices": slices, + "storage": self.storage(), }) } diff --git a/server/rust/metaobjects/src/docs_view/storage.rs b/server/rust/metaobjects/src/docs_view/storage.rs new file mode 100644 index 0000000000..20aa81f312 --- /dev/null +++ b/server/rust/metaobjects/src/docs_view/storage.rs @@ -0,0 +1,583 @@ +//! The docs view's `storage` section: the tables and views the model declares, named by the +//! port's own naming helpers (`docs/features/docs-view.md`, "storage"). +//! +//! Model-only, as TypeScript's `buildStorage` (`docs-view/storage.ts`) is when it has no +//! expected schema: a table per concrete object whose primary source is a writable, managed +//! table (abstract bases and sourceless values 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 physical facts (SQL type, default, indexes, checks, constraint names, +//! referential actions) are `null` here: only the TypeScript run fills them. + +use std::cmp::Ordering; +use std::collections::{HashMap, HashSet}; + +use serde_json::{Value, json}; + +use super::{ATTR_DESCRIPTION, Build, DOT, TYPE_FIELD, str_attr}; +use crate::loader::split_child_tail; +use crate::naming::{ + NamingCtx, primary_rdb_source, resolve_column_name, resolve_flattened_column_name, + source_effective_kind, source_is_read_only, source_physical_name, +}; +use crate::node::NodeId; +use crate::parser::TYPE_OBJECT; + +const TYPE_IDENTITY: &str = "identity"; +const TYPE_ORIGIN: &str = "origin"; +const TYPE_VALIDATOR: &str = "validator"; +const TYPE_SOURCE: &str = "source"; +const SUBTYPE_PRIMARY: &str = "primary"; +const SUBTYPE_REFERENCE: &str = "reference"; +const SUBTYPE_REQUIRED: &str = "required"; +const SUBTYPE_OBJECT: &str = "object"; +const KIND_VIEW: &str = "view"; +const ATTR_DISCRIMINATOR: &str = "discriminator"; +const ATTR_DISCRIMINATOR_VALUE: &str = "discriminatorValue"; +const ATTR_OBJECT_REF: &str = "objectRef"; +const ATTR_REQUIRED: &str = "required"; +const ATTR_STORAGE: &str = "storage"; +const ATTR_SCHEMA: &str = "schema"; +const ATTR_UNMANAGED: &str = "unmanaged"; +const ATTR_FIELDS: &str = "fields"; +const ATTR_GENERATION: &str = "generation"; +const ATTR_ENFORCE: &str = "enforce"; +const ATTR_REFERENCES: &str = "references"; +const STORAGE_FLATTENED: &str = "flattened"; +const GENERATION_INCREMENT: &str = "increment"; +const GENERATION_UUID: &str = "uuid"; + +/// A column before its field is linked. +struct RawColumn { + name: String, + nullable: bool, + identity: String, + description: String, +} + +/// The field behind a column: its owner object and the field node. +type Mapping = (NodeId, NodeId); + +/// A foreign key, before it is written as JSON. +#[derive(PartialEq, Eq)] +struct Fk { + columns: Vec, + ref_table: String, + ref_columns: Vec, +} + +/// JavaScript's string order: by UTF-16 code unit. +fn by_code_unit(a: &str, b: &str) -> Ordering { + a.encode_utf16().cmp(b.encode_utf16()) +} + +fn key(name: &str, schema: &str) -> String { + if schema.is_empty() { + name.to_string() + } else { + format!("{schema}.{name}") + } +} + +impl Build<'_> { + fn ctx(&self) -> NamingCtx<'_> { + NamingCtx::new(self.registry, self.naming) + } + + fn column_name(&self, field: NodeId) -> String { + resolve_column_name(self.tree, field, &self.ctx()) + .unwrap_or_else(|_| self.tree.node(field).name.clone()) + } + + /// The column of the object's field `name`, or `name` through the column strategy. + fn column_of(&self, obj: NodeId, name: &str) -> String { + match self.find_field(obj, name) { + Some(f) => self.column_name(f), + None => self + .registry + .apply_column_naming_strategy(name, &self.naming.columns) + .unwrap_or_else(|_| name.to_string()), + } + } + + fn fields_of(&self, obj: NodeId) -> Vec { + self.tree + .children(obj) + .iter() + .copied() + .filter(|&c| self.tree.node(c).type_name == TYPE_FIELD) + .collect() + } + + fn find_field(&self, obj: NodeId, name: &str) -> Option { + self.fields_of(obj) + .into_iter() + .find(|&f| self.tree.node(f).name == name) + } + + fn is_required(&self, field: NodeId) -> bool { + // ADR-0039: resolving. @required and validator.required may be inherited via extends. + if self.tree.attr(field, ATTR_REQUIRED) == Some(&Value::Bool(true)) { + return true; + } + self.tree.children(field).iter().any(|&c| { + let n = self.tree.node(c); + n.type_name == TYPE_VALIDATOR && n.sub_type == SUBTYPE_REQUIRED + }) + } + + fn is_derived(&self, field: NodeId) -> bool { + // ADR-0039 own (category 4): origin.* never inherits (ADR-0029). + self.tree + .own_children(field) + .iter() + .any(|&c| self.tree.node(c).type_name == TYPE_ORIGIN) + } + + /// The `@discriminator`-bearing ANCESTOR of `entity`. + fn discriminator_base(&self, entity: NodeId) -> Option { + let mut seen = vec![entity]; + let mut cur = self.tree.node(entity).super_node; + while let Some(a) = cur { + if seen.contains(&a) { + break; + } + seen.push(a); + // ADR-0039 sanctioned own: an explicit super-resolution walk reads each ancestor's + // own attr. + if self + .tree + .own_attr(a, ATTR_DISCRIMINATOR) + .is_some_and(|x| !x.value.is_null()) + { + return Some(a); + } + cur = self.tree.node(a).super_node; + } + None + } + + fn is_tph_subtype(&self, entity: NodeId) -> bool { + self.tree.attr(entity, ATTR_DISCRIMINATOR_VALUE).is_some() + && self.discriminator_base(entity).is_some() + } + + fn tph_concrete_subtypes(&self, base: NodeId, objects: &[NodeId]) -> Vec { + if self.tree.attr(base, ATTR_DISCRIMINATOR).is_none() { + return Vec::new(); + } + objects + .iter() + .copied() + .filter(|&o| { + !super::is_abstract(self.tree, o) + && self.tree.attr(o, ATTR_DISCRIMINATOR_VALUE).is_some() + && self.discriminator_base(o) == Some(base) + }) + .collect() + } + + fn identity_fields(&self, identity: NodeId) -> Vec { + match self.tree.attr(identity, ATTR_FIELDS) { + Some(Value::String(s)) => s + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(), + Some(Value::Array(items)) => items.iter().map(crate::json::js_display).collect(), + _ => Vec::new(), + } + } + + fn primary_identity(&self, obj: NodeId) -> Option { + self.tree.children(obj).iter().copied().find(|&c| { + let n = self.tree.node(c); + n.type_name == TYPE_IDENTITY && n.sub_type == SUBTYPE_PRIMARY + }) + } + + fn is_flattened(&self, field: NodeId) -> bool { + self.tree.node(field).sub_type == SUBTYPE_OBJECT + && self.tree.attr(field, ATTR_STORAGE).and_then(Value::as_str) + == Some(STORAGE_FLATTENED) + } + + /// The object a reference attribute resolved to (`refTarget`): none for a list value. + fn ref_target(&self, n: NodeId, attr: &str) -> Option { + if !matches!(self.tree.attr(n, attr), Some(Value::String(_))) { + return None; + } + let target = self.declaring_targets(n, attr).first().copied().flatten()?; + (self.tree.node(target).type_name == TYPE_OBJECT).then_some(target) + } + + fn raw_column(&self, field: NodeId, is_pk: bool, generation: &str, name: String) -> RawColumn { + RawColumn { + name, + nullable: !is_pk && !self.is_required(field), + identity: if is_pk + && (generation == GENERATION_INCREMENT || generation == GENERATION_UUID) + { + generation.to_string() + } else { + String::new() + }, + description: str_attr(self.tree, field, ATTR_DESCRIPTION), + } + } + + fn field_columns(&self, field: NodeId, is_pk: bool, generation: &str) -> Vec { + if self.is_flattened(field) { + let Some(target) = self.ref_target(field, ATTR_OBJECT_REF) else { + return Vec::new(); + }; + return self + .fields_of(target) + .into_iter() + .map(|nested| { + let name = resolve_flattened_column_name(self.tree, field, nested, &self.ctx()) + .unwrap_or_else(|_| self.tree.node(nested).name.clone()); + self.raw_column(nested, false, "", name) + }) + .collect(); + } + vec![self.raw_column(field, is_pk, generation, self.column_name(field))] + } + + /// The referenced key's columns: an explicit dotted tail on `@references`, else the + /// target's primary identity (its first field), else `id`. + fn target_columns(&self, reference: NodeId, target: NodeId) -> Vec { + let tail = match self.tree.attr(reference, ATTR_REFERENCES) { + Some(Value::String(raw)) => split_child_tail(raw).1.to_string(), + _ => String::new(), + }; + let tail = tail.strip_prefix(DOT).unwrap_or(&tail); + let mut names: Vec = tail + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(); + if names.is_empty() { + let pk = self + .primary_identity(target) + .map(|i| self.identity_fields(i)) + .unwrap_or_default(); + names = vec![pk.into_iter().next().unwrap_or_else(|| "id".to_string())]; + } + names.iter().map(|n| self.column_of(target, n)).collect() + } + + fn foreign_keys( + &self, + entity: NodeId, + objects: &[NodeId], + table_of: &HashMap, + ) -> Vec { + let is_ref = |c: NodeId| { + let n = self.tree.node(c); + n.type_name == TYPE_IDENTITY && n.sub_type == SUBTYPE_REFERENCE + }; + let mut refs: Vec<(NodeId, NodeId)> = self + .tree + .children(entity) + .iter() + .copied() + .filter(|&c| is_ref(c)) + .map(|c| (entity, c)) + .collect(); + if self.tree.attr(entity, ATTR_DISCRIMINATOR).is_some() { + let base_names: HashSet = refs + .iter() + .map(|&(_, r)| self.tree.node(r).name.clone()) + .collect(); + for sub in self.tph_concrete_subtypes(entity, objects) { + for &c in self.tree.children(sub).iter() { + if is_ref(c) && !base_names.contains(&self.tree.node(c).name) { + refs.push((sub, c)); + } + } + } + } + let mut fks: Vec = Vec::new(); + for (holder, reference) in refs { + // A logical-only reference is no constraint. + if self.tree.attr(reference, ATTR_ENFORCE) == Some(&Value::Bool(false)) { + continue; + } + let Some(target) = self.ref_target(reference, ATTR_REFERENCES) else { + continue; + }; + let Some(ref_table) = table_of.get(&target).filter(|t| !t.is_empty()) else { + continue; + }; + let names = self.identity_fields(reference); + if names.is_empty() { + continue; + } + let fk = Fk { + columns: names.iter().map(|n| self.column_of(holder, n)).collect(), + ref_table: ref_table.clone(), + ref_columns: self.target_columns(reference, target), + }; + // Two subtypes may declare the same column: one constraint. + if !fks.contains(&fk) { + fks.push(fk); + } + } + fks + } + + /// The link to `field` as a member of the top-level `owner`: its own row of an inherited + /// one, or null. + fn member_link(&self, owner: NodeId, field: NodeId) -> Value { + let row = self.canonical.get(&owner).and_then(|&top| { + self.walked[top] + .children + .iter() + .copied() + .find(|&c| self.walked[c].node == field) + }); + row.map_or(Value::Null, |w| self.link(w)) + } + + fn object_link(&self, obj: NodeId) -> Value { + self.link_to(Some(obj), &self.tree.node(obj).name) + } + + fn schema_of(&self, source: NodeId) -> String { + str_attr(self.tree, source, ATTR_SCHEMA) + } + + pub(super) fn storage(&self) -> Value { + let tree = self.tree; + let ctx = self.ctx(); + let objects: Vec = tree + .children(self.root) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_OBJECT) + .collect(); + let primary = |o: NodeId| primary_rdb_source(tree, o, &ctx).ok().flatten(); + let name_of = |s: NodeId| source_physical_name(tree, s, &ctx).unwrap_or_default(); + + // Pass 1: which objects own a table, and which are only a foreign-key target. + let mut entities: Vec<(NodeId, NodeId)> = Vec::new(); + let mut target_only: Vec<(NodeId, NodeId)> = Vec::new(); + let mut tph_members: Vec<(NodeId, NodeId)> = Vec::new(); + let is_writable_source = + |c: NodeId| tree.node(c).type_name == TYPE_SOURCE && !source_is_read_only(tree, c); + for &obj in &objects { + let base = self.discriminator_base(obj); + if let Some(base) = base + && (super::is_abstract(tree, obj) || self.is_tph_subtype(obj)) + { + tph_members.push((obj, base)); + continue; + } + if super::is_abstract(tree, obj) { + continue; + } + if !tree.children(obj).iter().any(|&c| is_writable_source(c)) { + continue; + } + let Some(source) = primary(obj) else { + continue; + }; + // ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. + let own = tree + .own_children(obj) + .iter() + .copied() + .find(|&c| is_writable_source(c)); + if own.is_some_and(|o| tree.attr(o, ATTR_UNMANAGED) == Some(&Value::Bool(true))) { + target_only.push((obj, source)); + continue; + } + entities.push((obj, source)); + } + let mut table_of: HashMap = entities + .iter() + .chain(target_only.iter()) + .map(|&(o, s)| (o, name_of(s))) + .collect(); + for &(member, base) in &tph_members { + if let Some(name) = table_of.get(&base).cloned() + && !table_of.contains_key(&member) + { + table_of.insert(member, name); + } + } + + // Every object at each storage key, in declaration order. + let mut at_key: HashMap> = HashMap::new(); + for &obj in &objects { + if let Some(source) = primary(obj) { + at_key + .entry(key(&name_of(source), &self.schema_of(source))) + .or_default() + .push(obj); + } + } + // The column to declaring field map: the first writer wins on a shared table. + let field_of = |k: &str| -> Vec<(String, Mapping)> { + let mut out: Vec<(String, Mapping)> = Vec::new(); + let mut seen: HashSet = HashSet::new(); + for &obj in at_key.get(k).into_iter().flatten() { + for field in self.fields_of(obj) { + let column = self.column_name(field); + if seen.insert(column.clone()) { + out.push((column, (obj, field))); + } + } + } + out + }; + let concrete_links = |k: &str| -> Vec { + at_key + .get(k) + .into_iter() + .flatten() + .filter(|&&o| !super::is_abstract(tree, o)) + .map(|&o| self.object_link(o)) + .collect() + }; + + let mut tables: Vec<(String, Value)> = Vec::new(); + let mut keys: HashSet = HashSet::new(); + for &(entity, source) in &entities { + let identity = self.primary_identity(entity); + let pk_names = identity + .map(|i| self.identity_fields(i)) + .unwrap_or_default(); + let generation = identity + .and_then(|i| tree.attr(i, ATTR_GENERATION)) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let mut raw: Vec = Vec::new(); + for field in self.fields_of(entity) { + if self.is_derived(field) { + continue; + } + let is_pk = pk_names.contains(&tree.node(field).name); + raw.extend(self.field_columns(field, is_pk, if is_pk { &generation } else { "" })); + } + if tree.attr(entity, ATTR_DISCRIMINATOR).is_some() { + let mut existing: HashSet = raw.iter().map(|c| c.name.clone()).collect(); + let base_fields: HashSet = self + .fields_of(entity) + .iter() + .map(|&f| tree.node(f).name.clone()) + .collect(); + for sub in self.tph_concrete_subtypes(entity, &objects) { + for field in self.fields_of(sub) { + if base_fields.contains(&tree.node(field).name) || self.is_derived(field) { + continue; + } + let mut col = self.raw_column(field, false, "", self.column_name(field)); + if existing.contains(&col.name) { + continue; + } + // A row of any other subtype stores NULL here. + col.nullable = true; + existing.insert(col.name.clone()); + raw.push(col); + } + } + } + let schema = self.schema_of(source); + let name = name_of(source); + let k = key(&name, &schema); + let mapping: HashMap = field_of(&k).into_iter().collect(); + let columns: Vec = raw + .iter() + .map(|c| { + json!({ + "name": c.name, + "field": mapping + .get(&c.name) + .map_or(Value::Null, |&(o, f)| self.member_link(o, f)), + "nullable": c.nullable, + "identity": c.identity, + "description": c.description, + "sqlType": Value::Null, + "default": Value::Null, + }) + }) + .collect(); + let fks: Vec = self + .foreign_keys(entity, &objects, &table_of) + .into_iter() + .map(|f| { + json!({ + "columns": f.columns, + "refTable": f.ref_table, + "refColumns": f.ref_columns, + "name": Value::Null, + "onDelete": Value::Null, + "onUpdate": Value::Null, + }) + }) + .collect(); + tables.push(( + name.clone(), + json!({ + "name": name, + "schema": schema, + "declaredBy": self.object_link(entity), + "objects": concrete_links(&k), + "description": str_attr(tree, entity, ATTR_DESCRIPTION), + "primaryKey": pk_names.iter().map(|n| self.column_of(entity, n)).collect::>(), + "columns": columns, + "foreignKeys": fks, + "indexes": Value::Null, + "checks": Value::Null, + }), + )); + keys.insert(k); + } + + let mut views: Vec<(String, Value)> = Vec::new(); + for &obj in &objects { + if super::is_abstract(tree, obj) { + continue; + } + let Some(source) = primary(obj) else { + continue; + }; + if source_effective_kind(tree, source) != KIND_VIEW { + continue; + } + let schema = self.schema_of(source); + let name = name_of(source); + let k = key(&name, &schema); + if !keys.insert(k.clone()) { + continue; + } + let columns: Vec = field_of(&k) + .into_iter() + .map(|(n, (o, f))| json!({ "name": n, "field": self.member_link(o, f) })) + .collect(); + views.push(( + name.clone(), + json!({ + "name": name, + "schema": schema, + "declaredBy": self.object_link(obj), + "objects": concrete_links(&k), + "columns": columns, + }), + )); + } + + tables.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + views.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + json!({ + "physical": false, + "dialect": "", + "tables": tables.into_iter().map(|t| t.1).collect::>(), + "views": views.into_iter().map(|t| t.1).collect::>(), + }) + } +} diff --git a/server/rust/metaobjects/tests/docs_view_conformance.rs b/server/rust/metaobjects/tests/docs_view_conformance.rs index 420731e69d..f38623a369 100644 --- a/server/rust/metaobjects/tests/docs_view_conformance.rs +++ b/server/rust/metaobjects/tests/docs_view_conformance.rs @@ -112,8 +112,8 @@ fn the_docs_route_serves_the_model_alone_view() { std::fs::read_to_string(dir.join("expected.json")).unwrap() ); // metaDocsEtag(body) in @metaobjectsdev/runtime-ts over the same bytes. - assert_eq!(d.etag, "\"4c8c-0068e2ba\""); - assert!(d.matches(Some("\"4c8c-0068e2ba\""))); + assert_eq!(d.etag, "\"5c90-d00d12d4\""); + assert!(d.matches(Some("\"5c90-d00d12d4\""))); assert_eq!(META_DOCS_ROUTE_PATH, format!("{META_ROUTE_PATH}/docs")); assert!(meta_json(&loaded.tree, loaded.root).starts_with('{')); } diff --git a/server/typescript/packages/cli/src/commands/init.ts b/server/typescript/packages/cli/src/commands/init.ts index d9a235a221..a8ba852c08 100644 --- a/server/typescript/packages/cli/src/commands/init.ts +++ b/server/typescript/packages/cli/src/commands/init.ts @@ -5,6 +5,7 @@ import { INIT_DEFAULT_LIMIT, INIT_MAX_LIMIT, UNKNOWN_FIELDS_REJECT } from "@meta import { DEFAULT_CONFIG, ConfigSchema, saveConfig, PACKAGE_MANIFEST_FILE, DEFAULT_METADATA_DIR, DEFAULT_METAOBJECTS_DIR, DEPS_DIR, LOCK_FILE } from "@metaobjectsdev/sdk"; import { assemble, resolveAgentContextRoot, planScaffold, + ALWAYS_ON_PATH, AGENT_PAGES_TEMPLATE, renderAgentPagesSection, wiredAgentPages, withAgentPagesSection, AGENT_CONTEXT_MANIFEST_PATH, DEFAULT_SKILLS_DIR, normalizeSkillsDir, type Manifest, type Stack, } from "@metaobjectsdev/sdk/agent-context"; import { assertKnownStackValues, resolveStack } from "../lib/detect-stack.js"; @@ -423,7 +424,14 @@ async function writeAgentContext(opts: InitOptions, result: InitResult): Promise // An explicit --skills-dir wins; otherwise the directory this project chose last time, so a // refresh never quietly moves the skills back to the default. const skillsDir = normalizeSkillsDir(opts.skillsDir ?? prior?.skillsDir ?? DEFAULT_SKILLS_DIR); - let assembled = assemble({ contentRoot: resolveAgentContextRoot(), stack, docsRef: docsRefForVersion(cliVersion()), skillsDir }); + const contentRoot = resolveAgentContextRoot(); + let assembled = assemble({ contentRoot, stack, docsRef: docsRefForVersion(cliVersion()), skillsDir }); + // The always-on file points at the agent pages only when the project's last `gen` wrote one. + const pagesSection = renderAgentPagesSection( + readFileSyncWrap(join(contentRoot, "templates", AGENT_PAGES_TEMPLATE), "utf8"), + wiredAgentPages(opts.cwd), + ); + assembled = assembled.map((f) => (f.path === ALWAYS_ON_PATH ? { ...f, contents: withAgentPagesSection(f.contents, pagesSection) } : f)); if (opts.noSkills) assembled = assembled.filter((f) => !f.path.startsWith(`${skillsDir}/`)); const generatedBy = cliVersion(); 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 1f22fa8aa1..5ce3191327 100644 --- a/server/typescript/packages/cli/test/docs-page-conformance.test.ts +++ b/server/typescript/packages/cli/test/docs-page-conformance.test.ts @@ -20,21 +20,24 @@ import { describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; -import { InMemoryStringSource, MetaDataLoader, physicalNamingOf } from "@metaobjectsdev/metadata"; +import { buildDocsView, InMemoryStringSource, MetaDataLoader, physicalNamingOf } from "@metaobjectsdev/metadata"; import type { MetaRoot } from "@metaobjectsdev/metadata"; import { resolveSchemaConventions } from "@metaobjectsdev/migrate-ts"; import { agentRequirementsPageData, agentSchemaPageData, + agentSchemaPageDataFromView, renderAgentRequirementsPage, renderAgentSchemaPage, - renderRequirementsMarkdown, renderRequirementsToon, requirementRows, + requirementRowsFromView, requirementsLedgerData, requirementsToonData, schemaInputFromRows, schemaRows, + schemaRowsFromView, + renderAgentSchemaPageFromView, } from "@metaobjectsdev/codegen-ts"; import { buildAgentSchemaInput } from "../src/lib/agent-schema.js"; @@ -55,11 +58,14 @@ async function outputsOf(root: MetaRoot, migrate: boolean): Promise(); const json = (v: unknown): string => `${JSON.stringify(v, null, 2)}\n`; - const rows = requirementRows(root); + // Every page starts from the docs view: the rows each port reads off its own view. + const view = buildDocsView({ root }); + const rows = requirementRowsFromView(view); + expect(requirementRows(root)).toEqual(rows); if (rows.length > 0) { - out.set("requirements.md", renderRequirementsMarkdown(rows)); out.set("requirements.toon", renderRequirementsToon(rows)); - out.set("data/requirements.md.json", json(requirementsLedgerData(rows))); + // The ledger agent/requirements.md embeds: the requirements template in its embedded form. + out.set("data/ledger.md.json", json(requirementsLedgerData(rows, { embedded: true }))); 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)); @@ -82,15 +88,21 @@ async function outputsOf(root: MetaRoot, migrate: boolean): Promise { } }); + // agent/schema.md documents the project's own storage: the local Order, never an import. + test("(a2) agent/schema.md names no imported node", async () => { + const root = setupRepo({ agentDocs: true }); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + const schema = readFileSync(join(root, "docs", "agent", "schema.md"), "utf8"); + expect(schema).toContain("app::Order"); + for (const imported of ["Customer", "customers", "Address", "acme::common"]) { + expect(schema).not.toContain(imported); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + test("(c) naming an excluded import positionally refuses with exit 2", async () => { const root = setupRepo(); try { diff --git a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts index fdfba074e6..200f369513 100644 --- a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts @@ -189,6 +189,8 @@ const BARREL = `${OUT}/index.ts`; /** The agent UI page, which `agent-docs` writes when the run also wires the client tier. It * is one page for the whole model, so a served report adds its section to it. */ const AGENT_UI_PAGE = `${OUT}/agent/ui.md`; +/** The model-only schema page (no dialect in this run): a served report adds its view. */ +const AGENT_SCHEMA_PAGE = `${OUT}/agent/schema.md`; /** The OpenAPI document, one for the whole model, so a served report adds to it. */ const OPENAPI_DOC = `${OUT}/openapi.json`; /** The client UI generators that emit NOTHING for a report: a report has a list hook and no @@ -408,7 +410,7 @@ describe("FR-044 a sourceless report is inert; a served report emits exactly its expect(expected[""]).toBeUndefined(); expect(actual[""]).toBeUndefined(); expect(Object.keys(expected).length).toBeGreaterThan(10); - expectOnlyAdds(expected, actual, Object.values(ADDED_FOR_WITH).flat(), [AGENT_UI_PAGE, OPENAPI_DOC, ...Object.values(SERVICE_GROWS).flat()]); + expectOnlyAdds(expected, actual, Object.values(ADDED_FOR_WITH).flat(), [AGENT_UI_PAGE, AGENT_SCHEMA_PAGE, OPENAPI_DOC, ...Object.values(SERVICE_GROWS).flat()]); // The agent UI page moves by the served report's section alone: every line it had is // still there, in order, and the section names the report. const before = expected[AGENT_UI_PAGE]!.split("\n"); @@ -418,6 +420,10 @@ describe("FR-044 a sourceless report is inert; a served report emits exactly its expect(kept).toBe(before.length); expect(after.filter((l) => !before.includes(l)).join("\n")).toContain("StoreTotals"); for (const name of SOURCELESS_REPORTS) expect(actual[AGENT_UI_PAGE]).not.toContain(name); + // The schema page gains the served report's view, and nothing names a sourceless one. + expect(actual[AGENT_SCHEMA_PAGE]).toContain("`v_store_totals`"); + expect(expected[AGENT_SCHEMA_PAGE]).not.toContain("v_store_totals"); + for (const name of SOURCELESS_REPORTS) expect(actual[AGENT_SCHEMA_PAGE]).not.toContain(name); // In the full suite the barrel re-exports the report's modules. expect(actual[BARREL]).toContain("StoreTotals"); expect(expected[BARREL]).not.toContain("StoreTotals"); diff --git a/server/typescript/packages/codegen-ts/src/docs-run.ts b/server/typescript/packages/codegen-ts/src/docs-run.ts index a26558191f..36ba82fbf6 100644 --- a/server/typescript/packages/codegen-ts/src/docs-run.ts +++ b/server/typescript/packages/codegen-ts/src/docs-run.ts @@ -64,9 +64,10 @@ export function docsRunFacts( } /** - * Memoize a schema builder so it runs at most once per run, and only when a generator asks: - * a run that lists no `agentDocsFile()` never builds a schema, and never prints the reasons - * one could not be built. + * Memoize a schema builder so it runs at most once per run, on first demand. `agentDocsFile()` + * and every generator that builds the docs view (`docsSiteFile()`, a view-scoped template) ask, + * so a run with a dialect and any one of them may build the schema and print the reasons one + * could not be built. A run that lists none of them never builds it. */ export function onceAgentSchema( build: () => AgentSchemaInput | undefined, diff --git a/server/typescript/packages/codegen-ts/src/docs-view-run.ts b/server/typescript/packages/codegen-ts/src/docs-view-run.ts index 9c82b32384..2937f3caf9 100644 --- a/server/typescript/packages/codegen-ts/src/docs-view-run.ts +++ b/server/typescript/packages/codegen-ts/src/docs-view-run.ts @@ -6,6 +6,7 @@ import { buildDocsView, type DocsView } from "@metaobjectsdev/metadata"; import type { GenContext } from "./generator.js"; import { buildApiModelForRun } from "./generators/api-model.js"; +import { withPhysicalStorage } from "./generators/docs-view-pages.js"; /** A route the run mounts, keyed by its node's resolution key: the docs view's `routes` input. */ interface RunRoute { @@ -50,10 +51,14 @@ export function runDocsView(ctx: GenContext, who: string): DocsView { // No route at all means this run recorded none (no routes generator, or REST off), which the // view says as such; an empty list would claim the run mounted nothing. const routes = runRoutes(ctx); - return buildDocsView({ + const view = buildDocsView({ root: ctx.loadedRoot, ...(ledger !== undefined && { verify: ledger }), ...(runFiles !== undefined && { manifest }), ...(routes.length > 0 && { routes }), }); + // The storage section's physical facts come from the expected schema, which only a run with + // a dialect has; without one they stay null, as in every other port. + const schema = ctx.docs?.agentSchema?.(); + return schema === undefined ? view : withPhysicalStorage(view, schema); } diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts index 5988cf8dc4..e5ad1c0e77 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts @@ -17,11 +17,12 @@ // schema ← the expected-schema snapshot `meta migrate` diffs and emits from // (injected; see agent-schema-input.ts for why codegen-ts refuses to // compute it) + `resolveObjectNames`, the field→column resolver the -// names artifact and the DDL already share +// names artifact and the DDL already share; with no dialect, the +// model-only page every port writes, read off the docs view // ui ← `buildEntityUiDescriptor`, the same derivation emitted as the // `` const that `useEntityForm` reads at runtime -// requirements ← `walkRequirements` + `requirementRows`, the same walk the ledger -// surface and the generated test stubs are built on +// requirements ← the docs view's requirement rows and resolved `implementedBy`, the +// same view every port's page builders read // // RUN-DEPENDENT, like the api reference. Physical names, the dialect and view dispatch all // depend on the gen config, which `meta gen` reads before it builds the schema. @@ -29,7 +30,7 @@ // different contract, not a relaxation of that one. // // AN EMPTY PAGE IS NO FILE. Each renderer returns "" when its tier has nothing to -// describe — no physical schema, no UI, no ledger — and an empty render emits nothing. +// describe — no table and no view, no UI, no ledger — and an empty render emits nothing. // That is what makes the surface safe to leave on: a headless project with no ledger sees // no `agent/` directory rather than three pages of headings. // @@ -40,6 +41,8 @@ import { physicalNamingGuideUrl } from "@metaobjectsdev/metadata/release-docs"; import { physicalNamingOf, physicalNamingRemovedMessage } from "@metaobjectsdev/metadata"; import type { EmittedFile, Generator, GeneratorFactory } from "../generator.js"; import { renderAgentSchemaPage } from "./agent-schema-page.js"; +import { renderAgentSchemaPageFromView } from "./docs-view-pages.js"; +import { buildDocsView } from "@metaobjectsdev/metadata"; import { renderAgentUiPage } from "./agent-ui-page.js"; import { renderAgentRequirementsPage } from "./agent-requirements-page.js"; import type { AgentSchemaInput } from "./agent-schema-input.js"; @@ -57,8 +60,8 @@ export interface AgentDocsFileOpts { /** * The physical schema, with its resolvers injected by whoever owns them. Default: the one * `meta gen` builds with the project's dialect and column naming (`ctx.docs.agentSchema`). - * ABSENT both ways is a supported state: a project with no physical schema gets no schema - * page rather than a page of unknowns. + * ABSENT both ways (no dialect), the page is the model-only one every port writes, built + * from the docs view. */ schema?: AgentSchemaInput; /** Directory whose `templates/agent/{schema,requirements}.md.mustache` (and @@ -93,8 +96,15 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G // ---- schema.md // The model walk (column → declaring field, view lineage, relationships, enums) is // the page builder's; this passes it the model, the schema and the naming. - if (schemaInput !== undefined) { - const content = renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }); + { + // With no expected schema (no dialect, so no `meta migrate` either), the model-only + // page every port writes, read off the docs view. + const content = schemaInput !== undefined + ? renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { + provider, + ...(ctx.select !== undefined && { inScope: ctx.select }), + }) + : renderAgentSchemaPageFromView(buildDocsView({ root: ctx.loadedRoot }), false, provider, ctx.select); if (content !== "") files.push({ path: `${dir}/schema.md`, content }); } diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts b/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts index 12a0c92921..4070e2ff54 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts @@ -8,22 +8,23 @@ // it, which for this repository's own ledger is 175 rows. // // So this page carries the same index PLUS a NODE index: every claimed node → the -// requirements claiming it, at every grain. It is an inversion of `walkRequirements`, not -// a second walk — the same resolution, read the other way, so the two indexes cannot -// disagree about what resolves. +// requirements claiming it, at every grain. It is the docs view's resolved `implementedBy` +// read the other way (`nodeIndexFromView`), so the two indexes cannot disagree about what +// resolves, and every port builds it from the same view. // // LITERAL FQNs ON EVERY LINE, deliberately and even where it is repetitive. An agent // retrieving over a long context finds a node by matching the token it is holding; a row // that says "the field above" is unreachable to it. This is also why the node index is // FLAT rather than nested under its owning object. // -// A CLAIM THAT DOES NOT RESOLVE IS OMITTED, silently, exactly as `walkRequirements` omits -// it. Resolution severity depends on `@status` and belongs to `meta verify`; a docs page +// A CLAIM THAT DOES NOT RESOLVE IS OMITTED, silently, exactly as the view marks it +// unresolved. Resolution severity depends on `@status` and belongs to `meta verify`; a docs page // that rendered a dangling reference as though it pointed somewhere would be asserting // the opposite of what the gate says. // // THE LEDGER IS EMBEDDED BELOW THE INDEX, and that duplication is deliberate rather than -// an oversight — the same content also lives at `requirements.md` when that surface is on. +// an oversight: this page is the one Markdown copy of the ledger (people read it in the +// explorer, the docs site). // The node index alone would omit exactly the entries the mechanism is MEASURED on: a // `retired` capability may carry no `@implementedBy` at all (FR-039 forbids it), so it // resolves to no node and appears in no node index. The one controlled finding behind this @@ -38,79 +39,18 @@ // `requirements` page's own template rendered in its embedded form, so the two cannot // disagree. -import { REQUIREMENT_ATTR_STATEMENT } from "@metaobjectsdev/metadata"; +import { buildDocsView } from "@metaobjectsdev/metadata"; import type { MetaData } from "@metaobjectsdev/metadata"; import type { Provider } from "@metaobjectsdev/render"; import { compareCodeUnits } from "../code-unit-order.js"; -import { GENERATED_HEADER } from "../constants.js"; -import { concernOf, walkRequirements } from "../requirement-walk.js"; import { frameworkTemplatesProvider } from "../render-engine/framework-provider.js"; import { renderDocPage } from "../render-engine/doc-page.js"; -import { requirementRows } from "./requirements-view.js"; +import { AGENT_PAGE_MARKER, nodeIndexFromView, requirementRowsFromView } from "./docs-view-pages.js"; import { renderRequirementsMarkdown } from "./requirements-markdown.js"; /** The shared template of `agent/requirements.md`. */ export const AGENT_REQUIREMENTS_PAGE_REF = "agent/requirements.md"; -const GENERATED_MARKER = ``; - -/** - * The address of any claimed node: the ROOT node's `resolutionKey()` (which carries the - * effective package), then the child-name path down to it. - * - * Built by walking parents rather than read off the node, because only a root-level node - * has a resolution key — a claimed FIELD has a bare name, and `Subscriber.status` and - * `Order.status` would collide in this index if the owner were dropped. - */ -function nodeAddress(node: MetaData): string { - const segments: string[] = []; - let cur: MetaData | undefined = node; - while (cur !== undefined) { - const parent: MetaData | undefined = cur.parent; - // The last node with a parent is the root-level one; the metadata ROOT itself has no - // name worth printing, so the walk stops when the next step would leave the model. - if (parent === undefined || parent.parent === undefined) { - segments.push(cur.resolutionKey()); - break; - } - segments.push(cur.name); - cur = parent; - } - return segments.reverse().join("."); -} - -interface NodeIndexEntry { - readonly address: string; - readonly concern: string; - readonly claims: { path: string; subType: string; level: number | undefined; status: string | undefined; statement: string | undefined }[]; -} - -/** Invert the walk: claimed node → the requirements that claim it. */ -export function buildNodeIndex( - root: MetaData, - inLedger?: (fqn: string) => boolean, -): NodeIndexEntry[] { - const byAddress = new Map(); - for (const walked of walkRequirements(root, inLedger)) { - const statement = walked.node.attr(REQUIREMENT_ATTR_STATEMENT); - for (const target of walked.targets) { - const address = nodeAddress(target.node); - let entry = byAddress.get(address); - if (entry === undefined) { - entry = { address, concern: concernOf(target.node), claims: [] }; - byAddress.set(address, entry); - } - entry.claims.push({ - path: walked.view.path, - subType: walked.view.subType, - level: walked.view.level, - status: walked.view.status, - statement: typeof statement === "string" && statement !== "" ? statement : undefined, - }); - } - } - return [...byAddress.values()].sort((a, b) => compareCodeUnits(a.address, b.address)); -} function mdCell(text: string): string { return text.replace(/\|/g, "\\|"); @@ -143,10 +83,11 @@ export function agentRequirementsPageData( inLedger?: (fqn: string) => boolean, provider?: Provider, ): AgentRequirementsPageData | undefined { - const rows = requirementRows(root, inLedger); + const view = buildDocsView({ root }); + const rows = requirementRowsFromView(view, inLedger); if (rows.length === 0) return undefined; - const index = buildNodeIndex(root, inLedger); + const index = nodeIndexFromView(view, inLedger); // The statements ride below the table: they are prose, they repeat across nodes a // shared architectural entry claims, and putting one in a cell forces the table wide. const stated = new Map(); @@ -159,7 +100,7 @@ export function agentRequirementsPageData( .sort((a, b) => compareCodeUnits(a[0], b[0])) .map(([path, { subType, statement }]) => ({ path, subType, statement: mdCell(oneLine(statement)) })); return { - generatedMarker: GENERATED_MARKER, + generatedMarker: AGENT_PAGE_MARKER, hasNodeIndex: index.length > 0, nodeIndex: index.map((entry) => ({ address: entry.address, diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts b/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts index 2d4ef08eb6..74aa612863 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts @@ -359,8 +359,14 @@ interface ModelFacts { readonly enums: readonly AgentSchemaEnumRow[]; } -function modelFacts(root: MetaRoot, schema: AgentSchemaInput, columnNamingStrategy: ColumnNamingStrategy): ModelFacts { - const objects = root.objects(); +function modelFacts( + root: MetaRoot, + schema: AgentSchemaInput, + columnNamingStrategy: ColumnNamingStrategy, + inScope: ((fqn: string) => boolean) | undefined, +): ModelFacts { + // A dependency's object the project did not take into scope is not the project's schema. + const objects = root.objects().filter((o) => inScope === undefined || inScope(o.resolutionKey())); // The qualified names the snapshot actually holds. An object whose physical name is not // one of these contributes nothing to the physical schema (an abstract base, a sourceless // value, an `@unmanaged` object) and must not appear on a page describing it — @@ -471,6 +477,9 @@ export interface AgentSchemaPageOptions { readonly physical?: boolean; /** Where the template is resolved. Default: the package's own templates. */ readonly provider?: Provider; + /** Keeps only the project's own objects (the run's `ctx.select`); a table or view a + * dependency's object declares is left out. Default: every object. */ + readonly inScope?: (fqn: string) => boolean; } /** @@ -481,11 +490,18 @@ export function agentSchemaPageData( root: MetaRoot, input: AgentSchemaInput, columnNamingStrategy: ColumnNamingStrategy, - opts?: { readonly physical?: boolean }, + opts?: { readonly physical?: boolean; readonly inScope?: (fqn: string) => boolean }, ): AgentSchemaPageData | undefined { - if (input.tables.length === 0 && input.views.length === 0) return undefined; + const inScope = opts?.inScope; + const own = (t: { name: string; schema?: string | undefined }): boolean => { + const fqn = input.provenance.get(input.qualify(t)); + return inScope === undefined || fqn === undefined || inScope(fqn); + }; + const ownTables = input.tables.filter(own); + const ownViews = input.views.filter(own); + if (ownTables.length === 0 && ownViews.length === 0) return undefined; const physical = opts?.physical !== false; - const facts = modelFacts(root, input, columnNamingStrategy); + const facts = modelFacts(root, input, columnNamingStrategy, inScope); // The semantics nudge. A schema page carrying business meaning beside the columns is // worth more to a reader working from it than any format choice this page could make — @@ -493,18 +509,18 @@ export function agentSchemaPageData( // snapshot already threads here to emit `COMMENT ON`. A model declaring none renders a // page of names with nothing to disambiguate them, and says so, because silently // omitting the highest-value content teaches an adopter that it does not exist. - const anyDescription = input.tables.some( + const anyDescription = ownTables.some( (t) => (t.description !== undefined && t.description !== "") || t.columns.some((c) => c.description !== undefined && c.description !== ""), ); - const tables = [...input.tables] + const tables = [...ownTables] .sort((a, b) => compareCodeUnits(a.name, b.name)) .map((table) => { const key = input.qualify(table); return tableOf(table, input, physical, input.provenance.get(key), facts.declaredBy.get(key) ?? new Map()); }); - const views = [...input.views] + const views = [...ownViews] .sort((a, b) => compareCodeUnits(a.name, b.name)) .map((view): AgentSchemaView => { const key = input.qualify(view); @@ -522,13 +538,13 @@ export function agentSchemaPageData( physical, dialect: physical ? input.dialect : "", hasMigrate: input.migrate, - descriptionNudge: !anyDescription && input.tables.length > 0, + descriptionNudge: !anyDescription && ownTables.length > 0, hasTables: tables.length > 0, tables, hasViews: views.length > 0, // A model with no report view must render exactly what it rendered before FR-044 // (no-churn: `meta verify --codegen` would flag drift after an upgrade otherwise). - hasReportView: input.views.some((v) => facts.reportViews.has(input.qualify(v))), + hasReportView: ownViews.some((v) => facts.reportViews.has(input.qualify(v))), views, hasRelationships: facts.relationships.length > 0, relationships: facts.relationships, diff --git a/server/typescript/packages/codegen-ts/src/generators/api-docs-file.ts b/server/typescript/packages/codegen-ts/src/generators/api-docs-file.ts index 50f3af220c..4051722f19 100644 --- a/server/typescript/packages/codegen-ts/src/generators/api-docs-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/api-docs-file.ts @@ -17,13 +17,12 @@ // this port's generators emit. Like every generator it runs when the project lists it, and // only then (ADR-0034 Amendment 9). // -// THE POINTER IS NO LONGER DEFERRED. This header used to record "surfacing the agent form -// (AGENT-API.md) to a coding agent via a pointer from the installed `.metaobjects/` -// context" as an agent-context-coordination follow-up. It was deferred, no roadmap item -// tracked it, and for as long as that held, the page existed and nothing routed an agent -// to it. `agent-context/templates/always-on.md.mustache` now names this file and the three -// `agent/` pages, and says when to read each. If you rename or move this artifact, that -// template is the other half. +// THE POINTER. The always-on file `meta init` writes (`.metaobjects/AGENTS.md`) names this file +// and the `agent/` pages, and says when to read each, but only once a `gen` has written them: +// `sdk/src/agent-context/agent-pages.ts` reads the committed `.gen-state/.hashes/` and inserts +// the section (`agent-context/templates/agent-pages.md.mustache`) above the rules, so a project +// that does not wire this generator is never sent to a file that is not there. If you rename +// this artifact, `AGENT_PAGES` there is the other half. import type { MetaObject } from "@metaobjectsdev/metadata"; import type { Generator, GeneratorFactory, EmittedFile } from "../generator.js"; diff --git a/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts b/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts new file mode 100644 index 0000000000..9fa89ea467 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts @@ -0,0 +1,400 @@ +// The agent pages, built from the docs view (docs/features/docs-view.md). +// +// `requirements.toon`, `agent/requirements.md` and the model-only `agent/schema.md` are shared +// Mustache templates every port renders. The view is the one input every port builds the same +// bytes of, so the rows each page starts from are read off the view and nothing else: the +// requirement rows from `requirements`, the node index from each requirement's resolved +// `implementedBy`, and the schema from `storage` plus the members of the nodes it links. A +// port's builders are therefore ports of THIS file, over its own view; the cross-port corpus +// is fixtures/docs-page-conformance/. + +import type { + DocsView, + DocsViewAttr, + DocsViewMember, + DocsViewNode, + DocsViewTable, +} from "@metaobjectsdev/metadata"; +import { compareCodeUnits } from "../code-unit-order.js"; +import { GENERATED_HEADER } from "../constants.js"; +import type { Provider } from "@metaobjectsdev/render"; +import type { AgentSchemaInput } from "./agent-schema-input.js"; +import { requirementLedgerKey } from "../requirement-walk.js"; +import { frameworkTemplatesProvider } from "../render-engine/framework-provider.js"; +import { renderDocPage } from "../render-engine/doc-page.js"; +import type { RequirementRow } from "./requirements-view.js"; + +/** The marker on the first line of every agent page. */ +export const AGENT_PAGE_MARKER = ``; + +const opt = (s: string): string | undefined => (s === "" ? undefined : s); + +// ---- requirements ----------------------------------------------------------------------- + +/** + * The requirement rows of the view, in document order. `inLedger` is the collection's ledger + * predicate: a dependency's requirement the project did not inherit is left out. + */ +export function requirementRowsFromView(view: DocsView, inLedger?: (fqn: string) => boolean): RequirementRow[] { + return view.requirements + .filter((r) => inLedger === undefined || inLedger(requirementLedgerKey({ package: r.package, path: r.address }))) + .map((r) => ({ + path: r.address, + depth: r.depth, + title: opt(r.title), + subType: r.subType, + level: r.level ?? undefined, + status: opt(r.status), + disposition: opt(r.disposition), + trackedBy: r.trackedBy, + statement: opt(r.statement), + counterexample: opt(r.counterexample), + description: opt(r.description), + implementedBy: r.implementedBy.map((l) => l.ref), + claimedConcerns: [...new Set(r.implementedBy.filter((l) => l.resolves).map((l) => l.target.kind))], + })); +} + +export interface NodeIndexClaim { + readonly path: string; + readonly subType: string; + readonly level: number | undefined; + readonly status: string | undefined; + readonly statement: string | undefined; +} + +export interface NodeIndexEntry { + readonly address: string; + readonly concern: string; + readonly claims: NodeIndexClaim[]; +} + +/** Claimed node → the requirements that claim it, sorted by the node's id. A claim that does + * not resolve is left out, as `meta verify` is what reports it. */ +export function nodeIndexFromView(view: DocsView, inLedger?: (fqn: string) => boolean): NodeIndexEntry[] { + const byAddress = new Map(); + for (const r of view.requirements) { + if (inLedger !== undefined && !inLedger(requirementLedgerKey({ package: r.package, path: r.address }))) continue; + for (const link of r.implementedBy) { + if (!link.resolves) continue; + let entry = byAddress.get(link.target.id); + if (entry === undefined) { + entry = { address: link.target.id, concern: link.target.kind, claims: [] }; + byAddress.set(link.target.id, entry); + } + entry.claims.push({ + path: r.address, + subType: r.subType, + level: r.level ?? undefined, + status: opt(r.status), + statement: opt(r.statement), + }); + } + } + return [...byAddress.values()].sort((a, b) => compareCodeUnits(a.address, b.address)); +} + +// ---- schema ------------------------------------------------------------------------------- + +/** One table of the model-only rows layer (`expected/rows/schema.json`). */ +export interface SchemaRowsTable { + name: string; + schema?: string; + description?: string; + primaryKey: string[]; + columns: { name: string; nullable: boolean; identity?: string; description?: string }[]; + foreignKeys: { columns: string[]; refTable: string; refColumns: string[] }[]; +} + +export interface SchemaRowsLayer { + tables: SchemaRowsTable[]; + views: { name: string; schema?: string }[]; + declaredBy: Record; +} + +function storageKey(name: string, schema: string): string { + return schema === "" ? name : `${schema}.${name}`; +} + +/** The rows layer of the schema page, read off the view's storage: the shape + * `meta schema --as json` prints, less its physical facts. */ +export function schemaRowsFromView(view: DocsView): SchemaRowsLayer { + const declared: [string, string][] = []; + const tables = view.storage.tables.map((t) => { + declared.push([storageKey(t.name, t.schema), t.declaredBy.id]); + return { + name: t.name, + ...(t.schema !== "" && { schema: t.schema }), + ...(t.description !== "" && { description: t.description }), + primaryKey: t.primaryKey, + columns: t.columns.map((c) => ({ + name: c.name, + nullable: c.nullable, + ...(c.identity !== "" && { identity: c.identity }), + ...(c.description !== "" && { description: c.description }), + })), + foreignKeys: t.foreignKeys.map((f) => ({ columns: f.columns, refTable: f.refTable, refColumns: f.refColumns })), + }; + }); + const views = view.storage.views.map((v) => { + declared.push([storageKey(v.name, v.schema), v.declaredBy.id]); + return { name: v.name, ...(v.schema !== "" && { schema: v.schema }) }; + }); + declared.sort((a, b) => compareCodeUnits(a[0], b[0])); + return { tables, views, declaredBy: Object.fromEntries(declared) }; +} + +/** What `agent/schema.md.mustache` renders. `physical` is false: the model-only page. */ +export interface AgentSchemaViewPageData { + generatedMarker: string; + physical: false; + dialect: ""; + hasMigrate: boolean; + descriptionNudge: boolean; + hasTables: boolean; + tables: Record[]; + hasViews: boolean; + hasReportView: boolean; + views: Record[]; + hasRelationships: boolean; + relationships: string[]; + hasEnums: boolean; + enums: { field: string; members: string; storage: string }[]; +} + +const TYPE_OBJECT = "object"; +const TYPE_FIELD = "field"; +const TYPE_ORIGIN = "origin"; +const TYPE_RELATIONSHIP = "relationship"; +const KIND_REPORT = "object.report"; +const SUBTYPE_ENUM = "enum"; + +/** Every member of every node, by id. */ +function membersById(view: DocsView): Map { + const out = new Map(); + const visit = (m: DocsViewMember): void => { + out.set(m.id, m); + for (const g of m.memberGroups) g.members.forEach(visit); + }; + for (const n of view.nodes) for (const g of n.memberGroups) g.members.forEach(visit); + return out; +} + +function directMembers(n: DocsViewNode | DocsViewMember, type: string): DocsViewMember[] { + return n.memberGroups.find((g) => g.type === type)?.members ?? []; +} + +function attrValue(attrs: readonly DocsViewAttr[], name: string): unknown { + return attrs.find((a) => a.name === name)?.value; +} + +/** A string attribute as a page prints it: a resolved reference by its link's label (what the + * author wrote, relative to the model: `Owner.name`), anything else as its text. */ +function attrText(attrs: readonly DocsViewAttr[], name: string): string | undefined { + const a = attrs.find((x) => x.name === name); + if (a === undefined || typeof a.value !== "string") return undefined; + const first = a.values[0]; + const text = first?.link != null && !first.link.unresolved ? first.link.label : a.value; + return text === "" ? undefined : text; +} + +const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim(); +const cols = (names: readonly string[]): string => (names.length === 0 ? "—" : names.map((c) => `\`${c}\``).join(", ")); + +function keyCell(table: DocsViewTable, column: string): string { + const roles: string[] = []; + if (table.primaryKey.includes(column)) roles.push(table.primaryKey.length > 1 ? "PK (composite)" : "PK"); + const fk = table.foreignKeys.find((f) => f.columns.includes(column)); + if (fk !== undefined) roles.push(`FK → \`${fk.refTable}\``); + return roles.join(" · "); +} + +/** The lineage text of a view column, from its field's `origin.*` member. */ +function lineageOf(field: DocsViewMember | undefined): string | undefined { + const origin = field === undefined ? undefined : directMembers(field, TYPE_ORIGIN)[0]; + if (origin === undefined) return undefined; + const t = (name: string): string | undefined => attrText(origin.attrs, name); + switch (origin.subType) { + case "passthrough": + return `passthrough from \`${t("from") ?? "?"}\`` + (t("via") === undefined ? "" : ` via \`${t("via")}\``); + case "aggregate": + return `\`${t("agg") ?? "?"}\`` + (t("of") === undefined ? "" : ` of \`${t("of")}\``) + (t("via") === undefined ? "" : ` via \`${t("via")}\``); + case "first": + return "first" + (t("of") === undefined ? "" : ` \`${t("of")}\``) + (t("via") === undefined ? "" : ` via \`${t("via")}\``) + (t("orderBy") === undefined ? "" : ` ordered by \`${t("orderBy")}\``); + case "computed": + return "computed from a declared `@expr`"; + default: + return `\`origin.${origin.subType}\``; + } +} + +function cardinalityPhrase(cardinality: unknown, through: string | undefined): string { + if (cardinality === "many") return through !== undefined ? "many-to-many" : "one-to-many"; + if (cardinality === "one") return "many-to-one"; + return "cardinality not declared"; +} + +/** + * The data `agent/schema.md.mustache` renders for the model-only page, built from the view + * alone. `hasMigrate`: the project chose a `meta migrate` dialect (`migrate.dialect` in + * `.metaobjects/config.json`). Undefined when the model declares no table and no view: no page. + * `inScope` keeps only the project's own objects (the run's `ctx.select`; undefined keeps every + * object): a dependency's object is not the project's schema. + */ +export function agentSchemaPageDataFromView( + view: DocsView, + hasMigrate: boolean, + inScope?: (fqn: string) => boolean, +): AgentSchemaViewPageData | undefined { + const scoped = (id: string): boolean => inScope === undefined || inScope(id); + const tables = view.storage.tables.filter((t) => scoped(t.declaredBy.id)); + const views = view.storage.views.filter((v) => scoped(v.declaredBy.id)); + if (tables.length === 0 && views.length === 0) return undefined; + const members = membersById(view); + const byOrder = [...view.nodes].sort((a, b) => a.order - b.order); + + const tableData = tables.map((t) => { + const k = storageKey(t.name, t.schema); + const described = t.columns.filter((c) => c.description !== ""); + const fks = t.foreignKeys.map((f) => `${cols(f.columns)} → \`${f.refTable}\`(${cols(f.refColumns)})`); + const fieldName = (id: string): string => members.get(id)?.name ?? ""; + return { + heading: `\`${k}\``, + tableDeclaredBy: t.declaredBy.id, + ...(t.description !== "" && { tableDescription: oneLine(t.description) }), + columns: t.columns.map((c) => ({ + name: c.name, + fieldCell: c.field === null ? "" : `\`${fieldName(c.field.id)}\``, + declaredCell: c.field === null ? "" : `\`${c.field.kind}\``, + sqlTypeCell: "", + nullCell: c.nullable ? "yes" : "no", + defaultCell: "", + keyCell: keyCell(t, c.name), + })), + hasDescribed: described.length > 0, + described: described.map((c) => ({ name: c.name, text: oneLine(c.description) })), + hasIndexes: false, + indexes: [], + hasForeignKeys: fks.length > 0, + foreignKeys: fks, + hasChecks: false, + checks: [], + }; + }); + + const viewData = views.map((v) => { + const lineage = v.columns.flatMap((c) => { + const text = lineageOf(c.field === null ? undefined : members.get(c.field.id)); + return text === undefined ? [] : [{ column: c.name, text }]; + }); + return { + heading: `\`${storageKey(v.name, v.schema)}\``, + viewDeclaredBy: v.declaredBy.id, + hasLineage: lineage.length > 0, + lineage, + }; + }); + + // Every relationship as written, in declaration order of its object. + const relationships: string[] = []; + for (const n of byOrder) { + if (n.type !== TYPE_OBJECT || !scoped(n.id)) continue; + for (const rel of directMembers(n, TYPE_RELATIONSHIP)) { + const through = attrText(rel.attrs, "through"); + const onDelete = attrText(rel.attrs, "onDelete"); + const parts = [`\`${n.id}.${rel.name}\``, `\`${rel.subType}\``]; + parts.push(`${cardinalityPhrase(attrValue(rel.attrs, "cardinality"), through)} → \`${attrText(rel.attrs, "objectRef") ?? "?"}\``); + if (through !== undefined) parts.push(`through \`${through}\``); + if (onDelete !== undefined) parts.push(`on delete \`${onDelete}\``); + relationships.push(parts.join(" · ")); + } + } + + // Every enum field of a table-backed object, in declaration order of its object. + const tableBacked = new Set(tables.flatMap((t) => t.objects.map((o) => o.id))); + const enums: AgentSchemaViewPageData["enums"] = []; + for (const n of byOrder) { + if (!tableBacked.has(n.id)) continue; + for (const f of directMembers(n, TYPE_FIELD)) { + if (f.subType !== SUBTYPE_ENUM) continue; + const values = attrValue(f.attrs, "values"); + const list = Array.isArray(values) ? values.map(String) : []; + if (list.length === 0) continue; + const intMap = attrValue(f.attrs, "intValueMap"); + const storage = + typeof intMap === "object" && intMap !== null && !Array.isArray(intMap) + ? `int-backed (${list.map((m) => `${m}=${String((intMap as Record)[m])}`).join(", ")})` + : "string-backed"; + enums.push({ field: `${n.id}.${f.name}`, members: list.map((m) => `\`${m}\``).join(", "), storage }); + } + } + + const anyDescription = tables.some((t) => t.description !== "" || t.columns.some((c) => c.description !== "")); + return { + generatedMarker: AGENT_PAGE_MARKER, + physical: false, + dialect: "", + hasMigrate, + descriptionNudge: !anyDescription && tables.length > 0, + hasTables: tableData.length > 0, + tables: tableData, + hasViews: viewData.length > 0, + hasReportView: views.some((v) => v.objects.some((o) => o.kind === KIND_REPORT)), + views: viewData, + hasRelationships: relationships.length > 0, + relationships, + hasEnums: enums.length > 0, + enums, + }; +} + +/** The model-only `agent/schema.md`, rendered from the view; "" when the model declares no + * table and no view. The page ends with exactly one line break. */ +export function renderAgentSchemaPageFromView( + view: DocsView, + hasMigrate: boolean, + provider?: Provider, + inScope?: (fqn: string) => boolean, +): string { + const data = agentSchemaPageDataFromView(view, hasMigrate, inScope); + if (data === undefined) return ""; + const page = renderDocPage("agent/schema.md", data, provider ?? frameworkTemplatesProvider, "agent/schema.md"); + // Keep one of the page's own trailing breaks (the template ends with one). + return page.replace(/(\n)\n+$/, "$1"); +} + +/** + * The view with its storage section's physical facts filled from the expected schema `meta + * migrate` diffs against (SQL types, defaults, indexes, checks, constraint names, referential + * actions). Only the TypeScript toolchain has that schema; a table it does not describe keeps + * its nulls. The view is returned, changed in place. + */ +export function withPhysicalStorage(view: DocsView, schema: AgentSchemaInput): DocsView { + const storage = view.storage; + storage.physical = true; + storage.dialect = schema.dialect; + for (const table of storage.tables) { + const match = + schema.tables.find((t) => t.name === table.name && (t.schema ?? "") === table.schema) ?? + (table.schema === "" ? schema.tables.find((t) => t.name === table.name) : undefined); + if (match === undefined) continue; + for (const column of table.columns) { + const c = match.columns.find((x) => x.name === column.name); + if (c === undefined) continue; + column.sqlType = schema.columnType(c); + column.default = c.default?.value ?? null; + } + for (const fk of table.foreignKeys) { + const f = match.foreignKeys.find( + (x) => x.refTable === fk.refTable && x.columns.join("\0") === fk.columns.join("\0"), + ); + if (f === undefined) continue; + fk.name = f.name; + fk.onDelete = f.onDelete ?? null; + fk.onUpdate = f.onUpdate ?? null; + } + table.indexes = match.indexes.map((i) => ({ name: i.name, columns: [...i.columns], unique: i.unique })); + table.checks = match.checks.map((c) => ({ name: c.name, expression: c.expression })); + } + return view; +} diff --git a/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts b/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts index 6843d0366d..7d24a246bb 100644 --- a/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts @@ -13,9 +13,9 @@ // AN EMPTY LEDGER EMITS ZERO FILES, not an empty page, so a project without a ledger that // lists this generator gets nothing rather than a page saying there is nothing. // -// BOTH FILES, UNCONDITIONALLY — deliberately not behind an option: a drift gate wants the -// machine-readable artifact committed regardless of who ran it or from what kind of -// terminal. +// ONE FILE, the machine-readable `requirements.toon` with its declared row count. The +// human page `requirements.md` is retired: people read the ledger in the explorer (the +// `docs-site` generator), and agents read it embedded in `agent/requirements.md`. import { type EmittedFile, @@ -23,14 +23,11 @@ import { type GeneratorFactory, oncePerRun, } from "../generator.js"; -import { renderRequirementsMarkdown } from "./requirements-markdown.js"; import { renderRequirementsToon } from "./requirements-toon.js"; import { requirementRows } from "./requirements-view.js"; import { DOCS_TARGET_NAME } from "../docs-run.js"; import { docsTemplateRoot, projectProvider } from "../render-engine/framework-provider.js"; -/** The human-facing index. */ -const MARKDOWN_FILENAME = "requirements.md"; /** The machine-facing artifact — see requirements-toon.ts for why TOON. */ const TOON_FILENAME = "requirements.toon"; @@ -39,8 +36,8 @@ export interface RequirementsFileOpts { outDir?: string; /** Named output target. Default `"docs"`, which `targets` must declare. */ target?: string; - /** Directory whose `templates/requirements/requirements.{md,toon}.mustache` override the - * shipped pages, relative to the project. Default: the project's own `templates/`. */ + /** Directory whose `templates/requirements/requirements.toon.mustache` overrides the + * shipped page, relative to the project. Default: the project's own `templates/`. */ templates?: string; } @@ -61,7 +58,6 @@ export const requirementsFile = function requirementsFile( const provider = projectProvider(docsTemplateRoot(ctx, opts?.templates)); const files: EmittedFile[] = [ - { path: `${dirPrefix}${MARKDOWN_FILENAME}`, content: renderRequirementsMarkdown(rows, { provider }) }, { path: `${dirPrefix}${TOON_FILENAME}`, content: renderRequirementsToon(rows, provider) }, ]; return files; diff --git a/server/typescript/packages/codegen-ts/src/generators/requirements-view.ts b/server/typescript/packages/codegen-ts/src/generators/requirements-view.ts index 0929a206cf..312da1033e 100644 --- a/server/typescript/packages/codegen-ts/src/generators/requirements-view.ts +++ b/server/typescript/packages/codegen-ts/src/generators/requirements-view.ts @@ -4,12 +4,10 @@ // // Design: docs/superpowers/specs/2026-08-21-requirements-doc-surface-design.md // -// PROJECTS OVER `walkRequirements()`, NEVER RE-WALKS. That walk already resolves the -// depth-first traversal, the dotted `path` (hierarchy IS nesting), and the -// `@implementedBy` targets, and it is what `requirementTests()` is built on. Sharing it -// means the doc view and the generated stubs agree about what the ledger contains by -// construction; two walks kept in step by hand is exactly the drift this surface exists -// to remove. +// READ OFF THE DOCS VIEW, NEVER RE-WALKED. The view's `requirements` already hold the +// depth-first order, the dotted address (hierarchy IS nesting) and each `@implementedBy` +// as written and as resolved, through the resolver the requirement gate uses; every port +// builds the same view, so every port's pages start from the same rows. // // `notes` IS DELIBERATELY ABSENT FROM THIS TYPE, not merely unread. `documentation.json` // charters it internal-only, never emitted to a user-facing doc surface, and the @@ -17,19 +15,12 @@ // cannot leak a field the projection never carries — which is a stronger guarantee than // asking every renderer to remember. // -// RESOLVING ACCESSORS ONLY (ADR-0039). Every read below goes through MetaRequirement's -// resolving accessors or the resolving `attr()`, so a requirement that `extends` an -// abstract parent inherits its `@level` / `@status` / statement rather than projecting -// them as undefined. No `own*()` call belongs in this file. +// The view reads effective attributes (ADR-0039), so a requirement that `extends` an +// abstract parent carries its inherited `@level` / `@status` / statement. -import { - DOC_ATTR_DESCRIPTION, - DOC_ATTR_TITLE, - REQUIREMENT_ATTR_STATEMENT, - REQUIREMENT_ATTR_COUNTEREXAMPLE, -} from "@metaobjectsdev/metadata"; +import { buildDocsView } from "@metaobjectsdev/metadata"; import type { MetaData } from "@metaobjectsdev/metadata"; -import { walkRequirements } from "../requirement-walk.js"; +import { requirementRowsFromView } from "./docs-view-pages.js"; /** One requirement, projected for rendering. Ordered depth-first, declaration order. */ export interface RequirementRow { @@ -62,20 +53,11 @@ export interface RequirementRow { readonly claimedConcerns: readonly string[]; } -/** Reads a resolving string attr, normalising "declared but empty" to undefined so a - * renderer has one absent-case to handle rather than two. */ -function stringAttr(node: MetaData, name: string): string | undefined { - // `attr()` is the RESOLVING accessor in TypeScript (ADR-0039). Note the cross-port - // naming inversion this repo records: Python's `attr()` is own-only, TS's resolves. - const raw = node.attr(name); - if (typeof raw !== "string") return undefined; - return raw.length > 0 ? raw : undefined; -} - /** * Project every `requirement.*` node in the project's ledger — nested ones included — into - * render-ready rows. `inLedger` is the collection's ledger predicate, as `walkRequirements` - * reads it: a dependency's requirement the project did not inherit is not listed. + * render-ready rows, read off the docs view (`requirementRowsFromView`), which every port + * builds alike. `inLedger` is the collection's ledger predicate: a dependency's requirement + * the project did not inherit is not listed. * * Returns `[]` for a model declaring no requirements, which is what lets the surface * emit NOTHING rather than an empty page, and is in turn what makes turning the surface @@ -85,24 +67,5 @@ export function requirementRows( root: MetaData, inLedger?: (fqn: string) => boolean, ): RequirementRow[] { - return walkRequirements(root, inLedger).map((walked) => { - const { node, view, targets } = walked; - return { - path: view.path, - // Derived rather than threaded: a separately-tracked depth could drift from the - // path that renders beside it, and there is only one right answer. - depth: view.path.split(".").length - 1, - title: stringAttr(node, DOC_ATTR_TITLE), - subType: view.subType, - level: view.level, - status: view.status, - disposition: node.disposition(), - trackedBy: node.trackedBy(), - statement: stringAttr(node, REQUIREMENT_ATTR_STATEMENT), - counterexample: stringAttr(node, REQUIREMENT_ATTR_COUNTEREXAMPLE), - description: stringAttr(node, DOC_ATTR_DESCRIPTION), - implementedBy: node.implementedBy(), - claimedConcerns: [...new Set(targets.map((t) => t.concern))], - }; - }); + return requirementRowsFromView(buildDocsView({ root }), inLedger); } diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index 12d10972d2..be199360a7 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -461,6 +461,21 @@ export { type AgentSchemaPageData, type AgentSchemaPageOptions, } from "./generators/agent-schema-page.js"; +// The agent pages' rows, read off the docs view: what every port's builders are ports of. +export { + AGENT_PAGE_MARKER, + agentSchemaPageDataFromView, + renderAgentSchemaPageFromView, + withPhysicalStorage, + nodeIndexFromView, + requirementRowsFromView, + schemaRowsFromView, + type AgentSchemaViewPageData, + type NodeIndexClaim, + type NodeIndexEntry, + type SchemaRowsLayer, + type SchemaRowsTable, +} from "./generators/docs-view-pages.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 { diff --git a/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts b/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts index e4426ee83c..cd39b6c897 100644 --- a/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts +++ b/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts @@ -56,6 +56,8 @@ import { DOCS_TARGET_NAME, } from "@metaobjectsdev/codegen-ts/engine"; import { renderAgentSchemaPage } from "../generators/agent-schema-page.js"; +import { renderAgentSchemaPageFromView } from "../generators/docs-view-pages.js"; +import { buildDocsView } from "@metaobjectsdev/metadata"; import { renderAgentUiPage } from "../generators/agent-ui-page.js"; import { renderAgentRequirementsPage } from "../generators/agent-requirements-page.js"; @@ -69,8 +71,8 @@ export interface AgentDocsFileOpts { target?: string; /** * The physical schema, with its resolvers injected by whoever owns them. Default: the one - * `meta gen` builds (`ctx.docs.agentSchema`). ABSENT both ways is a supported state: a - * project with no physical schema gets no schema page rather than a page of unknowns. + * `meta gen` builds (`ctx.docs.agentSchema`). ABSENT both ways (no dialect), the page is the + * model-only one every port writes, built from the docs view. */ schema?: AgentSchemaInput; /** Directory whose `templates/agent/{schema,requirements}.md.mustache` (and @@ -105,8 +107,15 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G // ---- schema.md // The model walk (column → declaring field, view lineage, relationships, enums) is // the page builder's; this passes it the model, the schema and the naming. - if (schemaInput !== undefined) { - const content = renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }); + { + // With no expected schema (no dialect, so no `meta migrate` either), the model-only + // page every port writes, read off the docs view. + const content = schemaInput !== undefined + ? renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { + provider, + ...(ctx.select !== undefined && { inScope: ctx.select }), + }) + : renderAgentSchemaPageFromView(buildDocsView({ root: ctx.loadedRoot }), false, provider, ctx.select); if (content !== "") files.push({ path: `${dir}/schema.md`, content }); } diff --git a/server/typescript/packages/codegen-ts/src/reference/requirements.ts b/server/typescript/packages/codegen-ts/src/reference/requirements.ts index a3e80ce948..2e8a3d436e 100644 --- a/server/typescript/packages/codegen-ts/src/reference/requirements.ts +++ b/server/typescript/packages/codegen-ts/src/reference/requirements.ts @@ -6,19 +6,18 @@ // shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not // reach for `Bun.*` globals here; they are undefined and take the whole run down with // `Bun is not defined`. Use `node:` builtins instead. -// targets: Markdown for people and TOON for tools. Neither imports anything. +// targets: TOON for tools. It imports nothing. // use-when: you want to change how the requirement ledger is written as documentation: // which files, where they land, or what they hold. The packaged // `requirementsFile()` writes them without this file; eject it only to // change them. -// emits: into the `docs` target: requirements.md, the human index, and -// requirements.toon, the machine-readable form a drift gate can commit. A -// project that declares no `requirement.*` node gets neither file. -// customize: the file names, the output directory (`outDir`), and whether both forms are -// written (`generate`). The two renderers and the projection they read -// (`requirements-markdown`, `requirements-toon`, `requirements-view`) are -// copied beside it into codegen/templates/. -// composes-with: agent-docs (its `requirements.md` page is built from the same projection). +// emits: into the `docs` target: requirements.toon, the machine-readable ledger a +// drift gate can commit. People read the ledger in the explorer (`docs-site`). +// A project that declares no `requirement.*` node gets no file. +// customize: the file name, the output directory (`outDir`) and what is written +// (`generate`). The renderer and the rows it reads (`requirements-toon`, +// `requirements-view`, `docs-view-pages`) are copied beside it. +// composes-with: agent-docs (its `agent/requirements.md` page is built from the same rows). // // HOW IT RUNS. Like every generator: list it in `generators` in metaobjects.config.ts, with // a `docs` target declared, and `meta gen` writes the files (`meta verify --codegen` checks @@ -30,8 +29,8 @@ // // METADATA ALONE: this generator reads `ctx.loadedRoot` and NOTHING else (a page template // under the project's `templates/requirements/` shapes the layout and adds no fact). An EMPTY LEDGER -// EMITS ZERO FILES, not an empty page. BOTH FILES, UNCONDITIONALLY: a drift gate wants the -// machine-readable artifact committed regardless of who ran it. +// EMITS ZERO FILES, not an empty page. The file is written unconditionally: a drift gate wants +// the machine-readable artifact committed regardless of who ran it. import { docsTemplateRoot, @@ -42,12 +41,9 @@ import { type GeneratorFactory, DOCS_TARGET_NAME, } from "@metaobjectsdev/codegen-ts/engine"; -import { renderRequirementsMarkdown } from "../generators/requirements-markdown.js"; import { renderRequirementsToon } from "../generators/requirements-toon.js"; import { requirementRows } from "../generators/requirements-view.js"; -/** The human-facing index. */ -const MARKDOWN_FILENAME = "requirements.md"; /** The machine-facing artifact — see requirements-toon.ts for why TOON. */ const TOON_FILENAME = "requirements.toon"; @@ -56,8 +52,8 @@ export interface RequirementsFileOpts { outDir?: string; /** Named output target. Default `"docs"`, which `targets` must declare. */ target?: string; - /** Directory whose `templates/requirements/requirements.{md,toon}.mustache` override the - * shipped pages, relative to the project. Default: the project's own `templates/`. */ + /** Directory whose `templates/requirements/requirements.toon.mustache` overrides the + * shipped page, relative to the project. Default: the project's own `templates/`. */ templates?: string; } @@ -78,7 +74,6 @@ export const requirementsFile = function requirementsFile( const provider = projectProvider(docsTemplateRoot(ctx, opts?.templates)); const files: EmittedFile[] = [ - { path: `${dirPrefix}${MARKDOWN_FILENAME}`, content: renderRequirementsMarkdown(rows, { provider }) }, { path: `${dirPrefix}${TOON_FILENAME}`, content: renderRequirementsToon(rows, provider) }, ]; return files; diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index 1b1f3a27d3..0caa37f097 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -162,7 +162,8 @@ export interface RunGenOpts { * Builds the physical schema `agent/schema.md` describes, with the project's dialect and * column naming. codegen-ts cannot build it (the schema builder is `migrate-ts`'s), so the * caller that can supplies it; the runner calls it at most once, and only when a generator - * asks (`ctx.docs.agentSchema`). Absent: `agentDocsFile()` writes no schema page. + * asks (`ctx.docs.agentSchema`). Absent: `agentDocsFile()` writes the model-only + * `agent/schema.md` built from the docs view, and the view's physical storage facts stay null. */ agentSchema?: () => AgentSchemaInput | undefined; /** Threaded onto `GenContext.schemaSettings`; see there. */ diff --git a/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts b/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts index 14bfffbdd4..fa8e88c400 100644 --- a/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts +++ b/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts @@ -389,9 +389,11 @@ describe("agent/schema.md", () => { expect(page).not.toContain("ALTER TABLE"); }); - test("emits NO schema page when no schema is supplied", async () => { + test("emits the model-only schema page when no schema is supplied", async () => { const files = await emit(await load(MODEL)); - expect(files.has("agent/schema.md")).toBe(false); + const page = files.get("agent/schema.md") ?? ""; + // Built from the docs view, as every port writes it: no SQL type, no physical facts. + expect(page).toContain("The tables, columns and keys this model declares."); // The other two still emit — a missing dialect must not take the whole surface down. expect(files.has("agent/ui.md")).toBe(true); expect(files.has("agent/requirements.md")).toBe(true); diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index 57e51f4af8..b47ea121f8 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -1551,8 +1551,8 @@ describe("ADR-0034 Amendments 8 and 9 — the requirements and agent-docs refere const a = await run(root, builtinRequirements()); const b = await run(root, refRequirements()); expect(b).toEqual(a); - // A ledger writes both forms; no ledger writes none — and the copy keeps that. - expect(paths(a)).toEqual(corpus.ledger ? ["requirements.md", "requirements.toon"] : []); + // A ledger writes the TOON; no ledger writes none — and the copy keeps that. + expect(paths(a)).toEqual(corpus.ledger ? ["requirements.toon"] : []); // The options an owned copy keeps: a directory and a target. expect(await run(root, refRequirements({ outDir: "ledger/" }))).toEqual( await run(root, builtinRequirements({ outDir: "ledger/" })), diff --git a/server/typescript/packages/codegen-ts/test/requirements-file-generator.test.ts b/server/typescript/packages/codegen-ts/test/requirements-file-generator.test.ts index 2217772c83..cf8f250a88 100644 --- a/server/typescript/packages/codegen-ts/test/requirements-file-generator.test.ts +++ b/server/typescript/packages/codegen-ts/test/requirements-file-generator.test.ts @@ -94,19 +94,10 @@ async function ctxFor(model: unknown): Promise { } describe("requirementsFile()", () => { - test("emits BOTH artifacts for a project with a ledger", async () => { + // The human requirements.md page is retired (1.3.0): people read the ledger in the explorer. + test("emits requirements.toon, and only that, for a project with a ledger", async () => { const files = await requirementsFile().generate(await ctxFor(WITH_LEDGER)); - expect(files.map((f) => f.path).sort()).toEqual([ - "requirements.md", - "requirements.toon", - ]); - }); - - test("the markdown carries the ledger's nesting", async () => { - const files = await requirementsFile().generate(await ctxFor(WITH_LEDGER)); - const md = files.find((f) => f.path === "requirements.md")?.content ?? ""; - expect(md).toContain("## checkout"); - expect(md).toContain("### checkout.capture"); + expect(files.map((f) => f.path)).toEqual(["requirements.toon"]); }); test("the TOON declares the row count", async () => { @@ -124,9 +115,6 @@ describe("requirementsFile()", () => { test("honours an outDir prefix without changing the filenames", async () => { const files = await requirementsFile({ outDir: "ledger" }).generate(await ctxFor(WITH_LEDGER)); - expect(files.map((f) => f.path).sort()).toEqual([ - "ledger/requirements.md", - "ledger/requirements.toon", - ]); + expect(files.map((f) => f.path)).toEqual(["ledger/requirements.toon"]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/run-gen.test.ts b/server/typescript/packages/codegen-ts/test/run-gen.test.ts index dfe1915cfb..74e33d39b8 100644 --- a/server/typescript/packages/codegen-ts/test/run-gen.test.ts +++ b/server/typescript/packages/codegen-ts/test/run-gen.test.ts @@ -20,6 +20,7 @@ import { barrel } from "../src/generators/barrel.js"; import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import { routesFile } from "../src/generators/routes-file.js"; +import { agentDocsFile } from "../src/generators/agent-docs-file.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -384,6 +385,33 @@ describe("runGen — scope", () => { expect(barrelContent).not.toContain("User"); }); + test("the model-only agent/schema.md documents the in-scope objects only", async () => { + const loader = new MetaDataLoader(); + const result = await loader.load([new FileSource(join(FIXTURE_DIR, "two-entities-fk.json"))]); + expect(result.errors).toEqual([]); + + // No `agentSchema` is handed to the run, so the page is the model-only one read off the + // docs view. An object outside the run's scope (a dependency's, in `meta gen`) is not the + // project's schema: its table and its heading stay off the page. + await runGen({ + config: defineConfig({ + outDir: tmp, + extStyle: "none", + dbImport: "~/server/db", + outputLayout: "flat" as const, dialect: "postgres", + targets: { docs: { outDir: join(tmp, "docs") } }, + generators: [agentDocsFile()], + }), + metadata: result.root, + scope: (fqn) => fqn === "demo::Post", + }); + + const schema = readFileSync(join(tmp, "docs", "agent", "schema.md"), "utf-8"); + expect(schema).toContain("Declared by `demo::Post`"); + expect(schema).not.toContain("Declared by `demo::User`"); + expect(schema).not.toContain("### `users`"); + }); + test("no scope option produces byte-identical output to an always-matching scope predicate", async () => { const loader = new MetaDataLoader(); const result = await loader.load([new FileSource(join(FIXTURE_DIR, "two-entities-fk.json"))]); diff --git a/server/typescript/packages/metadata/src/docs-view/build.ts b/server/typescript/packages/metadata/src/docs-view/build.ts index 5749839b53..279101b16d 100644 --- a/server/typescript/packages/metadata/src/docs-view/build.ts +++ b/server/typescript/packages/metadata/src/docs-view/build.ts @@ -56,6 +56,7 @@ import { type DocsViewSlice, type DocsViewStatusCount, } from "./types.js"; +import { buildStorage } from "./storage.js"; export interface DocsViewInput { /** The loaded, resolved model. */ @@ -660,6 +661,14 @@ export function buildDocsView(input: DocsViewInput): DocsView { requirements, advisories, slices: slicesOf(b, nodes, requirements), + storage: buildStorage(b.root, { + node: (md) => b.linkTo(md, md.name), + member: (owner, field) => { + const top = b.canonical.get(owner); + const row = top?.children.find((c) => c.md === field); + return row === undefined ? null : b.link(row); + }, + }), }; } diff --git a/server/typescript/packages/metadata/src/docs-view/storage.ts b/server/typescript/packages/metadata/src/docs-view/storage.ts new file mode 100644 index 0000000000..fcdfdcc781 --- /dev/null +++ b/server/typescript/packages/metadata/src/docs-view/storage.ts @@ -0,0 +1,334 @@ +// The docs view's `storage` section: the tables and views the model declares, named by the +// port's own naming helpers (docs/features/docs-view.md, "storage"). +// +// MODEL-ONLY, like the schema page a port without the expected schema writes (design call 17 +// of fixtures/docs-page-conformance/): a table per concrete object whose primary source is a +// writable, managed table (abstract bases and sourceless values 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 physical facts (SQL type, default, indexes, +// checks, constraint names, referential actions) are `null` here; the TypeScript run fills +// them from the expected schema when it has one (codegen-ts `withPhysicalStorage`). + +import type { MetaData } from "../shared/meta-data.js"; +import type { MetaObject } from "../core/object/meta-object.js"; +import type { MetaField } from "../core/field/meta-field.js"; +import type { MetaSource } from "../persistence/source/meta-source.js"; +import { isMetaObject, isMetaSource } from "../shared/node-guards.js"; +import { TYPE_IDENTITY, TYPE_ORIGIN, TYPE_VALIDATOR } from "../shared/base-types.js"; +import { DOC_ATTR_DESCRIPTION } from "../core/documentation/doc-constants.js"; +import { OBJECT_ATTR_DISCRIMINATOR, OBJECT_ATTR_DISCRIMINATOR_VALUE } from "../core/object/object-constants.js"; +import { + FIELD_ATTR_OBJECT_REF, + FIELD_ATTR_REQUIRED, + FIELD_ATTR_STORAGE, + FIELD_SUBTYPE_OBJECT, + STORAGE_FLATTENED, +} from "../core/field/field-constants.js"; +import { + GENERATION_INCREMENT, + GENERATION_UUID, + IDENTITY_ATTR_FIELDS, + IDENTITY_ATTR_GENERATION, + IDENTITY_REFERENCE_ATTR_ENFORCE, + IDENTITY_REFERENCE_ATTR_REFERENCES, + IDENTITY_SUBTYPE_REFERENCE, +} from "../core/identity/identity-constants.js"; +import { VALIDATOR_SUBTYPE_REQUIRED } from "../core/validator/validator-constants.js"; +import { SOURCE_ATTR_SCHEMA, SOURCE_KIND_VIEW } from "../persistence/source/source-constants.js"; +import { + applyColumnNamingStrategy, + physicalNamingOf, + primaryRdbSource, + resolveColumnName, + resolveFlattenedColumnName, +} from "../naming.js"; +import { refTarget, splitChildTail } from "../naming-refs.js"; +import type { + DocsViewColumn, + DocsViewForeignKey, + DocsViewLink, + DocsViewStorage, + DocsViewStoredView, + DocsViewTable, + DocsViewViewColumn, +} from "./types.js"; + +/** Links into the view, from the builder that owns the walk. */ +export interface StorageLinks { + /** The top-level node's link. */ + node(md: MetaData): DocsViewLink; + /** The link to `field` as a member of the top-level `owner` (its own row of an inherited one). */ + member(owner: MetaData, field: MetaData): DocsViewLink | null; +} + +const byCodeUnit = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0); + +function description(node: MetaData): string { + const v = node.attr(DOC_ATTR_DESCRIPTION); + return typeof v === "string" ? v : ""; +} + +function schemaOf(source: MetaSource): string { + const v = source.attr(SOURCE_ATTR_SCHEMA); + return typeof v === "string" ? v : ""; +} + +function isRequired(field: MetaData): boolean { + // ADR-0039: resolving — @required and validator.required may be inherited via extends. + if (field.attr(FIELD_ATTR_REQUIRED) === true) return true; + return field.children().some((c) => c.type === TYPE_VALIDATOR && c.subType === VALIDATOR_SUBTYPE_REQUIRED); +} + +function isDerived(field: MetaData): boolean { + // ADR-0039 own (category 4): origin.* never inherits (ADR-0029). + return field.ownChildren().some((c) => c.type === TYPE_ORIGIN); +} + +/** The `@discriminator`-bearing ANCESTOR of `entity`, or undefined. */ +function discriminatorBase(entity: MetaData): MetaData | undefined { + for (let a = entity.superData; a !== undefined; a = a.superData) { + // ADR-0039 sanctioned own: an explicit super-resolution walk reads each ancestor's own attr. + if (a.ownAttr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) return a; + } + return undefined; +} + +function isTphSubtype(entity: MetaData): boolean { + return entity.attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) !== undefined && discriminatorBase(entity) !== undefined; +} + +function tphConcreteSubtypes(base: MetaObject, objects: readonly MetaObject[]): MetaObject[] { + if (base.attr(OBJECT_ATTR_DISCRIMINATOR) === undefined) return []; + return objects.filter( + (o) => !o.isAbstract && o.attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) !== undefined && discriminatorBase(o) === base, + ); +} + +function identityFields(identity: MetaData): string[] { + const v = identity.attr(IDENTITY_ATTR_FIELDS); + if (typeof v === "string") return v.split(",").map((s) => s.trim()).filter((s) => s !== ""); + return Array.isArray(v) ? v.map(String) : []; +} + +function columnOf(obj: MetaObject, name: string): string { + const f = obj.findField(name); + return f !== undefined ? resolveColumnName(f) : applyColumnNamingStrategy(name, physicalNamingOf(obj).columns); +} + +function isFlattened(field: MetaField): boolean { + return field.subType === FIELD_SUBTYPE_OBJECT && field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED; +} + +interface RawColumn { + name: string; + nullable: boolean; + identity: string; + description: string; +} + +function rawColumn(field: MetaData, isPk: boolean, generation: string, name: string): RawColumn { + return { + name, + nullable: !isPk && !isRequired(field), + identity: isPk && (generation === GENERATION_INCREMENT || generation === GENERATION_UUID) ? generation : "", + description: description(field), + }; +} + +function fieldColumns(field: MetaField, isPk: boolean, generation: string): RawColumn[] { + if (isFlattened(field)) { + const target = refTarget(field, FIELD_ATTR_OBJECT_REF); + if (!isMetaObject(target)) return []; + return target.fields().map((nested) => rawColumn(nested, false, "", resolveFlattenedColumnName(field, nested))); + } + return [rawColumn(field, isPk, generation, resolveColumnName(field))]; +} + +/** The referenced key's columns: an explicit dotted tail on `@references`, else the target's + * primary identity (its first field), else `id`. */ +function targetColumns(ref: MetaData, target: MetaObject): string[] { + const raw = ref.attr(IDENTITY_REFERENCE_ATTR_REFERENCES); + const tail = typeof raw === "string" ? splitChildTail(raw).tail : ""; + const explicit = tail.replace(/^\./, "").split(",").map((s) => s.trim()).filter((s) => s !== ""); + let names = explicit; + if (names.length === 0) { + const identity = target.primaryIdentity(); + const pk = identity !== undefined ? identityFields(identity) : []; + names = [pk[0] ?? "id"]; + } + return names.map((n) => columnOf(target, n)); +} + +function foreignKeys(entity: MetaObject, objects: readonly MetaObject[], tableOf: Map): DocsViewForeignKey[] { + const isRef = (c: MetaData): boolean => c.type === TYPE_IDENTITY && c.subType === IDENTITY_SUBTYPE_REFERENCE; + const refs: [MetaObject, MetaData][] = entity.children().filter(isRef).map((c) => [entity, c]); + if (entity.attr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) { + const baseNames = new Set(refs.map(([, r]) => r.name)); + for (const sub of tphConcreteSubtypes(entity, objects)) { + for (const c of sub.children()) if (isRef(c) && !baseNames.has(c.name)) refs.push([sub, c]); + } + } + const fks: DocsViewForeignKey[] = []; + for (const [holder, ref] of refs) { + if (ref.attr(IDENTITY_REFERENCE_ATTR_ENFORCE) === false) continue; // a logical-only reference is no constraint + const target = refTarget(ref, IDENTITY_REFERENCE_ATTR_REFERENCES); + if (!isMetaObject(target)) continue; + const refTable = tableOf.get(target); + if (refTable === undefined || refTable === "") continue; + const names = identityFields(ref); + if (names.length === 0) continue; + const fk: DocsViewForeignKey = { + columns: names.map((n) => columnOf(holder, n)), + refTable, + refColumns: targetColumns(ref, target), + name: null, + onDelete: null, + onUpdate: null, + }; + // Two subtypes may declare the same column: one constraint. + const same = (a: DocsViewForeignKey): boolean => + a.refTable === fk.refTable && a.columns.join("\0") === fk.columns.join("\0") && a.refColumns.join("\0") === fk.refColumns.join("\0"); + if (!fks.some(same)) fks.push(fk); + } + return fks; +} + +function key(name: string, schema: string): string { + return schema === "" ? name : `${schema}.${name}`; +} + +/** The storage section of the docs view for the top-level nodes of `root`, in declaration order. */ +export function buildStorage(root: MetaData, links: StorageLinks): DocsViewStorage { + const objects = root.children().filter(isMetaObject); + + // Pass 1: which objects own a table, and which are only a foreign-key target. + const entities: [MetaObject, MetaSource][] = []; + const targetOnly: [MetaObject, MetaSource][] = []; + const tphMembers: [MetaObject, MetaData][] = []; + for (const obj of objects) { + const base = discriminatorBase(obj); + if (base !== undefined && (obj.isAbstract || isTphSubtype(obj))) { + tphMembers.push([obj, base]); + continue; + } + if (obj.isAbstract) continue; + if (!obj.children().some((c) => isMetaSource(c) && c.isWritable())) continue; + const source = primaryRdbSource(obj); + if (source === undefined) continue; + // ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. + const own = obj.ownChildren().find((c): c is MetaSource => isMetaSource(c) && c.isWritable()); + if (own !== undefined && own.isUnmanaged) { + targetOnly.push([obj, source]); + continue; + } + entities.push([obj, source]); + } + const tableOf = new Map([...entities, ...targetOnly].map(([o, s]) => [o, s.physicalName] as const)); + for (const [member, base] of tphMembers) { + const name = tableOf.get(base); + if (name !== undefined && !tableOf.has(member)) tableOf.set(member, name); + } + + // Every object at each storage key, in declaration order: the column → declaring field map + // (first writer wins on a shared table) and the objects a page lists. + const atKey = new Map(); + for (const obj of objects) { + const source = primaryRdbSource(obj); + if (source === undefined) continue; + const k = key(source.physicalName, schemaOf(source)); + atKey.set(k, [...(atKey.get(k) ?? []), obj]); + } + const fieldOf = (k: string): Map => { + const map = new Map(); + for (const obj of atKey.get(k) ?? []) { + for (const field of obj.fields()) { + const column = resolveColumnName(field); + if (!map.has(column)) map.set(column, { owner: obj, field }); + } + } + return map; + }; + + const tables: DocsViewTable[] = []; + const keys = new Set(); + for (const [entity, source] of entities) { + const identity = entity.primaryIdentity(); + const pkNames = identity !== undefined ? identityFields(identity) : []; + const gen = identity?.attr(IDENTITY_ATTR_GENERATION); + const generation = typeof gen === "string" ? gen : ""; + const raw: RawColumn[] = []; + for (const field of entity.fields()) { + if (isDerived(field)) continue; + const isPk = pkNames.includes(field.name); + raw.push(...fieldColumns(field, isPk, isPk ? generation : "")); + } + if (entity.attr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) { + const existing = new Set(raw.map((c) => c.name)); + const baseFields = new Set(entity.fields().map((f) => f.name)); + for (const sub of tphConcreteSubtypes(entity, objects)) { + for (const field of sub.fields()) { + if (baseFields.has(field.name) || isDerived(field)) continue; + const col = rawColumn(field, false, "", resolveColumnName(field)); + if (existing.has(col.name)) continue; + col.nullable = true; // a row of any other subtype stores NULL here + raw.push(col); + existing.add(col.name); + } + } + } + const schema = schemaOf(source); + const k = key(source.physicalName, schema); + const mapping = fieldOf(k); + const columns: DocsViewColumn[] = raw.map((c) => { + const m = mapping.get(c.name); + return { + name: c.name, + field: m === undefined ? null : links.member(m.owner, m.field), + nullable: c.nullable, + identity: c.identity, + description: c.description, + sqlType: null, + default: null, + }; + }); + tables.push({ + name: source.physicalName, + schema, + declaredBy: links.node(entity), + objects: (atKey.get(k) ?? []).filter((o) => !o.isAbstract).map((o) => links.node(o)), + description: description(entity), + primaryKey: pkNames.map((n) => columnOf(entity, n)), + columns, + foreignKeys: foreignKeys(entity, objects, tableOf), + indexes: null, + checks: null, + }); + keys.add(k); + } + + const views: DocsViewStoredView[] = []; + for (const obj of objects) { + if (obj.isAbstract) continue; + const source = primaryRdbSource(obj); + if (source === undefined || source.effectiveKind !== SOURCE_KIND_VIEW) continue; + const schema = schemaOf(source); + const k = key(source.physicalName, schema); + if (keys.has(k)) continue; + keys.add(k); + const columns: DocsViewViewColumn[] = [...fieldOf(k).entries()].map(([name, m]) => ({ + name, + field: links.member(m.owner, m.field), + })); + views.push({ + name: source.physicalName, + schema, + declaredBy: links.node(obj), + objects: (atKey.get(k) ?? []).filter((o) => !o.isAbstract).map((o) => links.node(o)), + columns, + }); + } + + tables.sort((a, b) => byCodeUnit(a.name, b.name)); + views.sort((a, b) => byCodeUnit(a.name, b.name)); + return { physical: false, dialect: "", tables, views }; +} diff --git a/server/typescript/packages/metadata/src/docs-view/types.ts b/server/typescript/packages/metadata/src/docs-view/types.ts index 1909a9658e..c7d6f6caa6 100644 --- a/server/typescript/packages/metadata/src/docs-view/types.ts +++ b/server/typescript/packages/metadata/src/docs-view/types.ts @@ -286,6 +286,93 @@ export interface DocsViewSlice { nodes: string[]; } +/** A column of a table the model declares. */ +export interface DocsViewColumn { + name: string; + /** The field that declares it (the first writer on a shared table; its `kind` is the + * declared `field.`); null for a column no field names by itself (a member of a + * flattened value object). */ + field: DocsViewLink | null; + nullable: boolean; + /** `increment` or `uuid` on a generated primary-key column; "" otherwise. */ + identity: string; + description: string; + /** Physical: the dialect's SQL type. Null unless `storage.physical`. */ + sqlType: string | null; + /** Physical: the column default as SQL. Null unless `storage.physical` (and when none). */ + default: string | null; +} + +export interface DocsViewForeignKey { + columns: string[]; + refTable: string; + refColumns: string[]; + /** Physical: the constraint name. Null unless `storage.physical`. */ + name: string | null; + /** Physical: the referential actions. Null unless `storage.physical` (and when none). */ + onDelete: string | null; + onUpdate: string | null; +} + +/** Physical: an index on a table. */ +export interface DocsViewIndex { + name: string; + columns: string[]; + unique: boolean; +} + +/** Physical: a check constraint on a table. */ +export interface DocsViewCheck { + name: string; + expression: string; +} + +export interface DocsViewTable { + name: string; + /** The `@schema` as declared; "" without one. */ + schema: string; + /** The object whose source declares the table. */ + declaredBy: DocsViewLink; + /** Every concrete object stored in it (the declaring one and its TPH subtypes), in + * declaration order. */ + objects: DocsViewLink[]; + description: string; + /** Column names. */ + primaryKey: string[]; + /** In declaration order; a TPH subtype's own columns follow its base's. */ + columns: DocsViewColumn[]; + foreignKeys: DocsViewForeignKey[]; + /** Physical. Null unless `storage.physical`. */ + indexes: DocsViewIndex[] | null; + checks: DocsViewCheck[] | null; +} + +export interface DocsViewViewColumn { + name: string; + /** The field that declares it (the first writer). */ + field: DocsViewLink | null; +} + +export interface DocsViewStoredView { + name: string; + schema: string; + declaredBy: DocsViewLink; + objects: DocsViewLink[]; + columns: DocsViewViewColumn[]; +} + +/** The tables and views the model declares, named by the port's naming helpers. */ +export interface DocsViewStorage { + /** The physical facts are filled: the TypeScript run had the expected schema. */ + physical: boolean; + /** The dialect of those facts; "" unless `physical`. */ + dialect: string; + /** Sorted by name. */ + tables: DocsViewTable[]; + /** Sorted by name. */ + views: DocsViewStoredView[]; +} + export interface DocsView { format: typeof DOCS_VIEW_FORMAT; sources: DocsViewSources; @@ -296,4 +383,5 @@ export interface DocsView { requirements: DocsViewRequirement[]; advisories: DocsViewAdvisory[]; slices: DocsViewSlice[]; + storage: DocsViewStorage; } diff --git a/server/typescript/packages/sdk/src/agent-context/agent-pages.ts b/server/typescript/packages/sdk/src/agent-context/agent-pages.ts new file mode 100644 index 0000000000..366eab14f3 --- /dev/null +++ b/server/typescript/packages/sdk/src/agent-context/agent-pages.ts @@ -0,0 +1,66 @@ +// The always-on file's pointer at the pages `meta gen` writes for a coding agent. +// +// The pointer is there only when the pages are: a project that wires no agent-pages generator +// is never told to read a file that does not exist. What is wired is read off the committed +// `.metaobjects/.gen-state/.hashes/` (one file per package, keyed by the project-relative path +// of every file a run wrote), which every port's `gen` writes, so the check needs no config +// evaluation and reads the same in every port. Python's init renders the same section from the +// same template (`agent_context/agent_pages.py`); fixtures/agent-pages-pointer/ pins both. + +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** The template of the section, under the content tree's `templates/`. */ +export const AGENT_PAGES_TEMPLATE = "agent-pages.md.mustache"; + +/** The heading the section is inserted above: the always-on file's rules. */ +export const AGENT_PAGES_ANCHOR = "\n## Rules\n"; + +/** Each agent page, by the path it ends with, and when to read it. In the order they are listed. */ +export const AGENT_PAGES: readonly { readonly suffix: string; readonly when: string }[] = [ + { suffix: "agent/schema.md", when: "before you touch persistence: tables, columns, keys and views" }, + { suffix: "agent/ui.md", when: "before you touch a form or a grid" }, + { suffix: "agent/requirements.md", when: "before you add or change a capability" }, + { suffix: "AGENT-API.md", when: "before you call or change the generated API" }, + { suffix: "requirements.toon", when: "the requirement ledger, in the form a tool reads" }, +]; + +const HASHES_DIR = join(".metaobjects", ".gen-state", ".hashes"); + +function pageIndex(path: string): number { + return AGENT_PAGES.findIndex((p) => path === p.suffix || path.endsWith(`/${p.suffix}`)); +} + +/** The agent pages the project's last `gen` wrote, as project-relative paths, in page order + * and then by path. Empty when nothing records one. */ +export function wiredAgentPages(cwd: string): string[] { + const dir = join(cwd, HASHES_DIR); + if (!existsSync(dir)) return []; + const found = new Set(); + for (const name of readdirSync(dir).filter((n) => n.endsWith(".json")).sort()) { + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(join(dir, name), "utf8")); + } catch { + continue; // an unreadable hashes file is `gen`'s to report, not this pointer's + } + if (typeof parsed !== "object" || parsed === null) continue; + for (const path of Object.keys(parsed)) if (pageIndex(path) >= 0) found.add(path); + } + return [...found].sort((a, b) => pageIndex(a) - pageIndex(b) || (a < b ? -1 : a > b ? 1 : 0)); +} + +/** The section for `pages`, from `template`; "" when there are none. */ +export function renderAgentPagesSection(template: string, pages: readonly string[]): string { + if (pages.length === 0) return ""; + const list = pages.map((p) => `- \`${p}\`: ${AGENT_PAGES[pageIndex(p)]!.when}.`).join("\n"); + return template.replace("{{pageList}}", list); +} + +/** `alwaysOn` with `section` inserted above its rules. Throws when the anchor is missing. */ +export function withAgentPagesSection(alwaysOn: string, section: string): string { + if (section === "") return alwaysOn; + const at = alwaysOn.indexOf(AGENT_PAGES_ANCHOR); + if (at < 0) throw new Error(`agent-context: the always-on file has no "${AGENT_PAGES_ANCHOR.trim()}" heading to place the agent pages above`); + return `${alwaysOn.slice(0, at + 1)}${section}${alwaysOn.slice(at + 1)}`; +} diff --git a/server/typescript/packages/sdk/src/agent-context/assemble.ts b/server/typescript/packages/sdk/src/agent-context/assemble.ts index 9c91f03d1a..f6af4bee39 100644 --- a/server/typescript/packages/sdk/src/agent-context/assemble.ts +++ b/server/typescript/packages/sdk/src/agent-context/assemble.ts @@ -128,6 +128,9 @@ function applyTemplate( }); } +/** Where the always-on file goes, relative to the project root. */ +export const ALWAYS_ON_PATH = ".metaobjects/AGENTS.md"; + /** * Assemble the consumer files for a resolved stack. Pure given the content tree. * @@ -161,7 +164,7 @@ export function assemble(opts: { contentRoot: string; stack: Stack; docsRef?: st // dialect; any other project migrates with its own tool. { migration: stack.migration }, ); - out.push({ path: ".metaobjects/AGENTS.md", contents: alwaysOn }); + out.push({ path: ALWAYS_ON_PATH, contents: alwaysOn }); // 2. Skills: body + only the references whose token is in the stack. for (const skill of SKILL_NAMES) { diff --git a/server/typescript/packages/sdk/src/agent-context/index.ts b/server/typescript/packages/sdk/src/agent-context/index.ts index 6e4ecf9f29..3c05323c37 100644 --- a/server/typescript/packages/sdk/src/agent-context/index.ts +++ b/server/typescript/packages/sdk/src/agent-context/index.ts @@ -1,5 +1,6 @@ export * from "./types.js"; export * from "./resolve.js"; +export * from "./agent-pages.js"; export * from "./assemble.js"; export * from "./content-root.js"; export * from "./scaffold.js"; diff --git a/server/typescript/packages/sdk/src/agent-context/shipped.ts b/server/typescript/packages/sdk/src/agent-context/shipped.ts index 37708a0bd7..6076f8c5b0 100644 --- a/server/typescript/packages/sdk/src/agent-context/shipped.ts +++ b/server/typescript/packages/sdk/src/agent-context/shipped.ts @@ -9,7 +9,10 @@ // `docsLinkPrefix + + "/"` in every file (what `pinDocsRefs` does), and // writes each file at its `path`. import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { DOCS_DEFAULT_REF, DOCS_REPO_URL } from "@metaobjectsdev/metadata"; +import { AGENT_PAGES_TEMPLATE } from "./agent-pages.js"; import { assemble } from "./assemble.js"; import { makeStack } from "./resolve.js"; import { @@ -103,6 +106,10 @@ export interface ShippedManifest { readonly docsLinkPrefix: string; /** The directory the skills' paths start with. */ readonly skillsDir: string; + /** The stored file holding the template of the always-on file's agent-pages section + * (`agent-pages.ts`): a port inserts it above the rules when the project's `.hashes/` + * record an agent page, and fixtures/agent-pages-pointer/ pins what it renders. */ + readonly agentPagesTemplate: string; readonly stacks: readonly ShippedStack[]; } @@ -140,11 +147,15 @@ export function buildShippedAgentContext(contentRoot: string): ShippedAgentConte }); stacks.push({ id: shippedStackId(stack), servers: stack.servers, clients: stack.clients, migration, files: refs }); } + const pagesTemplate = readFileSync(join(contentRoot, "templates", AGENT_PAGES_TEMPLATE), "utf8"); + const agentPagesTemplate = storedName(pagesTemplate); + files.set(agentPagesTemplate, pagesTemplate); const manifest: ShippedManifest = { schema: SHIPPED_AGENT_CONTEXT_SCHEMA, docsRef: DOCS_DEFAULT_REF, docsLinkPrefix: `${DOCS_REPO_URL}/blob/`, skillsDir: DEFAULT_SKILLS_DIR, + agentPagesTemplate, stacks, }; const sorted = new Map([...files.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); diff --git a/server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts b/server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts new file mode 100644 index 0000000000..09e043e943 --- /dev/null +++ b/server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + AGENT_PAGES_TEMPLATE, + renderAgentPagesSection, + wiredAgentPages, + withAgentPagesSection, +} from "../../src/agent-context/agent-pages.js"; + +const REPO = join(import.meta.dir, "..", "..", "..", "..", "..", ".."); +const CASES = join(REPO, "fixtures", "agent-pages-pointer", "cases"); +const TEMPLATE = readFileSync(join(REPO, "agent-context", "templates", AGENT_PAGES_TEMPLATE), "utf8"); + +describe("agent-pages-pointer corpus", () => { + for (const name of readdirSync(CASES).sort()) { + test(name, () => { + const dir = join(CASES, name); + const section = renderAgentPagesSection(TEMPLATE, wiredAgentPages(dir)); + expect(section).toBe(readFileSync(join(dir, "expected-section.md"), "utf8")); + }); + } +}); + +describe("withAgentPagesSection", () => { + test("inserts above the rules and leaves the rest", () => { + const file = "# T\n\nintro\n\n## Rules\n\n- a\n"; + expect(withAgentPagesSection(file, "## Pages\n\nx\n\n")).toBe("# T\n\nintro\n\n## Pages\n\nx\n\n## Rules\n\n- a\n"); + }); + test("an empty section leaves the file unchanged", () => { + expect(withAgentPagesSection("no anchor", "")).toBe("no anchor"); + }); + test("a file with no rules heading is refused", () => { + expect(() => withAgentPagesSection("no anchor", "## Pages\n")).toThrow(/Rules/); + }); +}); diff --git a/server/typescript/packages/sdk/test/agent-context/shipped.test.ts b/server/typescript/packages/sdk/test/agent-context/shipped.test.ts index 0732245490..27d2b6d817 100644 --- a/server/typescript/packages/sdk/test/agent-context/shipped.test.ts +++ b/server/typescript/packages/sdk/test/agent-context/shipped.test.ts @@ -92,7 +92,7 @@ describe("the stacks shipped", () => { }); test("a file shared by many stacks is stored once", () => { - const refs = built.manifest.stacks.flatMap((s) => s.files.map((f) => f.file)); + const refs = [...built.manifest.stacks.flatMap((s) => s.files.map((f) => f.file)), built.manifest.agentPagesTemplate]; expect(built.files.size).toBe(new Set(refs).size); expect(built.files.size).toBeLessThan(refs.length / 10); });