Skip to content

Commit f884621

Browse files
committed
feat(docs): model and API pages for reports in meta docs (FR-044)
meta docs now documents object.report (Plan 3, Table G), TypeScript. Model surface: every report gets a page, served or not, built from reportShape: its @from (linked), its view or 'Not served: declares no view source', its row scope, and a column table (name, type, nullable, role, definition). The index lists reports under their own heading. An entity that declares dimensions, measures or segments, or that a report reads from, gains a Reporting section. API surface: one unit for a served report, built from its read model: the row model, the list query and GET <served path> (plus the Hono GET when wired). No by-id, no write helper, no schema, no hook. A report that is not served has no unit, and its model page links to none. A keyless projection (no identity, no id column) no longer documents GET <path>/:id or find<Name>ById: the generators stopped emitting both. Site: the report skip in the link graph and the coverage audit's deferred bucket are gone. A report is an object page with a Report section, linked to its @from entity; the entity page gets the same Reporting section; all reporting kinds and attrs count as rendered. A model with no report renders every surface byte for byte as before (pinned by snapshots taken before the change; no existing golden moved).
1 parent c3f1d96 commit f884621

20 files changed

Lines changed: 2830 additions & 101 deletions

File tree

‎server/typescript/packages/cli/test/unit/reporting-inert.test.ts‎

Lines changed: 126 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@
1818
// `source.rdb @kind: view` (R5 allows one): that is the case that once leaked in C#, where
1919
// it emitted a keyless DbSet, a GET route and a filter allowlist for an object with no fields.
2020
//
21-
// `meta docs` is still held to the Plan 1 rule here (controller ruling, 2026-10-03): every
22-
// docs surface — model pages, agent pages, requirements, the HTML site, and the api surface
23-
// — comes out identical with and without the reporting nodes, bar the one view entry.
21+
// `meta docs` documents reports since Plan 3 (Table G), and the last describe states the
22+
// difference exactly: a model page and a site page for every report, served or not; a
23+
// "Reporting" section on each entity that declares reporting nodes; one api unit, for the
24+
// served report alone; the schema page's one view entry. `agent/ui.md` does not move: no
25+
// UI tier is generated for a report. Everything else is byte-identical.
2426

2527
import { describe, test, expect, beforeAll } from "bun:test";
2628
import { mkdtempSync, mkdirSync, copyFileSync, rmSync, readFileSync, readdirSync, statSync } from "node:fs";
@@ -292,7 +294,7 @@ describe("FR-044 a sourceless report is inert in migrate; a view-backed report p
292294
});
293295
});
294296

295-
describe("FR-044 reporting nodes are inert in meta docs, bar the one view entry", () => {
297+
describe("FR-044 meta docs differs by exactly the report pages, the Reporting sections and one api unit", () => {
296298
/** Run `meta docs` over a project holding one variant, once per surface flag set, and
297299
* read back everything written. The project directory has the SAME basename for both
298300
* variants: the site stamps it into every page title. */
@@ -311,21 +313,101 @@ describe("FR-044 reporting nodes are inert in meta docs, bar the one view entry"
311313
const files: Record<string, string> = {};
312314
for (const rel of walkFiles(root)) {
313315
if (rel.split(sep)[0] === "metaobjects") continue;
314-
files[rel] = readFileSync(join(root, rel), "utf8");
316+
files[rel.split(sep).join("/")] = readFileSync(join(root, rel), "utf8");
315317
}
316318
return files;
317319
} finally {
318320
rmSync(parent, { recursive: true, force: true });
319321
}
320322
}
321323

322-
test("model, agent, requirements and site output are identical", async () => {
324+
const REPORTS = ["DailyRevenue", "ProgramEngagement", "StoreTotals"] as const;
325+
/** The entities that declare dimensions, measures or segments in the with-model. */
326+
const REPORTING_ENTITIES = ["Purchase", "WorkoutEvent"] as const;
327+
const SITE = "out--site/site";
328+
const SITE_PKG = `${SITE}/acme/shop`;
329+
330+
/** The lines of `after` that are not the next unmatched line of `before`: what was
331+
* inserted. Throws when `before` is not a subsequence of `after`, i.e. when a line
332+
* was removed or rewritten rather than added. */
333+
function insertedLines(before: string, after: string): string[] {
334+
const want = before.split("\n");
335+
const added: string[] = [];
336+
let i = 0;
337+
for (const line of after.split("\n")) {
338+
if (i < want.length && line === want[i]) i++;
339+
else added.push(line);
340+
}
341+
if (i !== want.length) throw new Error(`a line was removed or rewritten: ${JSON.stringify(want[i])}`);
342+
return added;
343+
}
344+
345+
test("model pages: a page per report, a Reports index list, a Reporting section on Purchase and WorkoutEvent", async () => {
323346
const expected = await docsOutput("without");
324347
const actual = await docsOutput("with");
325-
expect(Object.keys(expected).some((p) => p.endsWith(".html"))).toBe(true);
326-
expect(Object.keys(expected).some((p) => p.endsWith(".md"))).toBe(true);
327-
expect(Object.keys(actual)).toEqual(Object.keys(expected));
328-
expect(actual).toEqual(expected);
348+
const model = (files: Record<string, string>): string[] =>
349+
Object.keys(files).filter((p) => p.startsWith("out/"));
350+
351+
expect(model(actual).filter((p) => !(p in expected))).toEqual(REPORTS.map((n) => `out/${n}.md`));
352+
expect(model(expected).filter((p) => !(p in actual))).toEqual([]);
353+
354+
// A served report names its view; a sourceless one says it is not served (answer 7).
355+
expect(actual["out/StoreTotals.md"]).toContain("**View:** `v_store_totals`");
356+
for (const name of SOURCELESS_REPORTS) {
357+
expect(actual[`out/${name}.md`]).toContain("**View:** Not served: declares no view source");
358+
}
359+
360+
for (const path of model(expected)) {
361+
const before = expected[path]!;
362+
const after = actual[path]!;
363+
if (path === "out/README.md") {
364+
// The index gains the Reports list and nothing else: no entity entry and no
365+
// diagram line moves.
366+
expect(insertedLines(before, after)).toEqual(["## Reports", "", ...REPORTS.map((n) => `- [${n}](./${n}.md)`), ""]);
367+
} else if (REPORTING_ENTITIES.some((e) => path === `out/${e}.md`)) {
368+
// The page is what it was, with the Reporting section appended.
369+
expect(after.startsWith(before + "\n## Reporting\n")).toBe(true);
370+
} else {
371+
expect({ path, content: after }).toEqual({ path, content: before });
372+
}
373+
}
374+
});
375+
376+
test("agent and requirements output (no gen config) is identical", async () => {
377+
const expected = await docsOutput("without");
378+
const actual = await docsOutput("with");
379+
const other = (files: Record<string, string>): Record<string, string> =>
380+
Object.fromEntries(Object.entries(files).filter(([p]) => !p.startsWith("out/") && !p.startsWith(`${SITE}/`)));
381+
expect(other(actual)).toEqual(other(expected));
382+
});
383+
384+
test("site: a page per report, the Reporting sections, and no page lost", async () => {
385+
const expected = await docsOutput("without");
386+
const actual = await docsOutput("with");
387+
const site = (files: Record<string, string>): string[] =>
388+
Object.keys(files).filter((p) => p.startsWith(`${SITE}/`));
389+
expect(site(expected).some((p) => p.endsWith(".html"))).toBe(true);
390+
391+
expect(site(actual).filter((p) => !(p in expected))).toEqual(REPORTS.map((n) => `${SITE_PKG}/${n}.html`));
392+
expect(site(expected).filter((p) => !(p in actual))).toEqual([]);
393+
394+
expect(actual[`${SITE_PKG}/StoreTotals.html`]).toContain("<code>v_store_totals</code>");
395+
for (const name of SOURCELESS_REPORTS) {
396+
expect(actual[`${SITE_PKG}/${name}.html`]).toContain("Not served: declares no view source");
397+
}
398+
for (const name of REPORTING_ENTITIES) {
399+
expect(actual[`${SITE_PKG}/${name}.html`]).toContain('id="s-reporting"');
400+
expect(expected[`${SITE_PKG}/${name}.html`]).not.toContain('id="s-reporting"');
401+
}
402+
// An entity with no reporting nodes changes by its sidebar alone: the three report
403+
// links, in the package it shares with them.
404+
const added = insertedLines(expected[`${SITE_PKG}/Program.html`]!, actual[`${SITE_PKG}/Program.html`]!);
405+
expect(added.length).toBe(REPORTS.length);
406+
for (const [i, name] of REPORTS.entries()) expect(added[i]).toContain(`${name}.html`);
407+
// The stylesheet and script are the same bytes either way.
408+
for (const asset of [`${SITE}/assets/site.css`, `${SITE}/assets/site.js`]) {
409+
expect(actual[asset]).toBe(expected[asset]!);
410+
}
329411
});
330412

331413
/** The GenContext `meta docs` builds, with a full generator suite wired: the Hono
@@ -351,7 +433,7 @@ describe("FR-044 reporting nodes are inert in meta docs, bar the one view entry"
351433
expect(actual).toEqual(expected);
352434
};
353435

354-
test("the api surface is identical", async () => {
436+
test("the api surface gains one unit, for the served report: its row model, list query and GET", async () => {
355437
// `meta docs --api` materializes only with a loadable gen config, which a temp project
356438
// cannot import; so drive the generator with the GenContext `meta docs` builds.
357439
const api = async (metadata: MetaRoot): Promise<Record<string, string>> => {
@@ -361,7 +443,36 @@ describe("FR-044 reporting nodes are inert in meta docs, bar the one view entry"
361443
};
362444
const expected = await api(withoutReporting);
363445
expect(Object.keys(expected).length).toBeGreaterThan(2);
364-
compare(expected, await api(withReporting));
446+
const actual = await api(withReporting);
447+
448+
// One new page, and no page for a report that is not served (answer 7).
449+
expect(Object.keys(actual).filter((p) => !(p in expected))).toEqual(["api/StoreTotals.md"]);
450+
expect(Object.keys(expected).filter((p) => !(p in actual))).toEqual([]);
451+
452+
// Answer 6: the unit is the row model, the list query function and GET <served path>
453+
// (once per wired route surface). No by-id, no write, no schema, no hook.
454+
const page = actual["api/StoreTotals.md"]!;
455+
expect(page.split("\n").filter((l) => l.startsWith("### "))).toEqual([
456+
"### `interface StoreTotals`",
457+
"### `listStoreTotals(db: Db, opts?: { limit?: number; offset?: number }): Promise<StoreTotals[]>`",
458+
"### `GET /api/store_totals`",
459+
"### `GET /api/store_totals`",
460+
]);
461+
expect(page).not.toMatch(/\buse[A-Z]\w*/);
462+
463+
// Every other page is byte-identical, bar the two indexes, which gain the report's
464+
// entry and lose nothing.
465+
for (const [path, before] of Object.entries(expected)) {
466+
const after = actual[path]!;
467+
if (path === "api/README.md" || path === "api/AGENT-API.md") {
468+
const added = after.split("\n").filter((l) => !before.split("\n").includes(l));
469+
expect(added.length).toBeGreaterThan(0);
470+
for (const l of added) expect(l).toContain("StoreTotals");
471+
for (const name of SOURCELESS_REPORTS) expect(after).not.toContain(name);
472+
continue;
473+
}
474+
expect({ path, content: after }).toEqual({ path, content: before });
475+
}
365476
});
366477

367478
test("the agent surface differs only by the schema page's v_store_totals view, with the UI tier wired", async () => {
@@ -407,5 +518,8 @@ describe("FR-044 reporting nodes are inert in meta docs, bar the one view entry"
407518
const rest = { ...expected };
408519
delete rest[schemaPage];
409520
compare(rest, actual);
521+
// Answer 6: no UI tier is generated for a report, so the UI page names none.
522+
const uiPage = Object.keys(actual).find((p) => p.endsWith("ui.md"))!;
523+
for (const name of ["StoreTotals", ...SOURCELESS_REPORTS]) expect(actual[uiPage]).not.toContain(name);
410524
});
411525
});

‎server/typescript/packages/codegen-ts/src/generators/api-model.ts‎

Lines changed: 70 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,16 @@
7777
// subtype REST subpaths are NOT YET documented by this builder — that fuller
7878
// TPH modeling is a tracked follow-up (under-documentation, allowed).
7979
//
80+
// • object.report (FR-044): a unit exists only for a SERVED report (Table A: not
81+
// abstract, read source of @kind view), built from its read model. It carries the
82+
// row model, `list<Plural>` and `GET <served path>` (plus the Hono GET when wired)
83+
// and nothing else: a report has no identity, so no by-id query and no `/:id`; no
84+
// write helper; no insert/update schema. No hook is documented for any object here
85+
// (see DEFERRALS), and none is generated for a report at all (`servesClientTier`).
86+
// • A KEYLESS projection (no identity and no `id` column) likewise documents no
87+
// `find<Name>ById` and no `/:id`: the read-only generators emit neither
88+
// (`hasItemRoute`).
89+
//
8090
// NOT modelled here (stated so the gap is known + intentional): a generator's own
8191
// `filter` option. `routesFile({ filter })` narrows what the routes generator emits,
8292
// and this builder reads the MODEL, not the wired generator set, so it cannot see
@@ -121,11 +131,11 @@ import { responseShape } from "../templates/find-inbound.js";
121131
import { isTphSubtype } from "../templates/zod-validators.js";
122132
import { isTphDiscriminatorBase } from "../templates/tph-discriminator.js";
123133
import { isCallableEntity } from "../templates/callable-file.js";
124-
import { servedPath, servesReadApi } from "../api-surface.js";
134+
import { hasItemRoute, servedPath, servesReadApi } from "../api-surface.js";
125135
import { isProjection } from "../projection/projection-detector.js";
126136
import { buildPkMap } from "../pk-resolver.js";
127137
import { buildRelationMap, type RelationEntry, type RelationMap } from "../relation-resolver.js";
128-
import { isReport } from "../source-detect.js";
138+
import { generatableObjects, isReport } from "../source-detect.js";
129139
import { effectivePackage } from "../docs-paths.js";
130140
import { entityOutputPath, type OutputLayout } from "../import-path.js";
131141
import type { RenderContext } from "../render-context.js";
@@ -297,10 +307,11 @@ export function buildApiModel(root: MetaRoot, ctx: ApiModelContext): ApiModel {
297307

298308
const units: ApiUnitDoc[] = [];
299309

300-
for (const obj of root.objects()) {
301-
// FR-044 Plan 1: object.report has no output until its lowering lands (Plan 2/3).
302-
// It has no generated API to document yet.
303-
if (isReport(obj)) continue;
310+
// FR-044 (Table G): a report has a unit exactly when it is served (Table A), and the
311+
// unit is built from its READ MODEL: the declared node has no fields, so the row shape
312+
// every symbol documents is the derived one. `generatableObjects` is the same swap
313+
// `runGen` hands the generators, so the units are the objects code was emitted for.
314+
for (const obj of generatableObjects(root.objects(), root)) {
304315
units.push(buildEntityUnit(obj, pkCtx, root, layout, relationMap, includeHono, apiPrefix));
305316
}
306317

@@ -380,6 +391,17 @@ function isQueryable(obj: MetaObject): boolean {
380391
return servesReadApi(obj) && !isTphSubtype(obj);
381392
}
382393

394+
/**
395+
* True for a READ-ONLY object the generators give no item surface: no `/:id` route and
396+
* no by-id query. That is a projection with no identity and no `id` column, and every
397+
* report (FR-044). `hasItemRoute` is the generators' own predicate; it is only meaningful
398+
* for the read-only surface, hence the `isProjection` guard (a report's read model
399+
* carries a read-only source, so it is one too).
400+
*/
401+
function lacksItemSurface(obj: MetaObject): boolean {
402+
return isProjection(obj) && !hasItemRoute(obj);
403+
}
404+
383405
function buildEntityUnit(
384406
obj: MetaObject,
385407
ctx: RenderContext,
@@ -410,7 +432,9 @@ function buildEntityUnit(
410432

411433
if (isQueryable(obj)) {
412434
symbols.push(...dataAccessSymbols(obj, ctx, root, layout));
413-
symbols.push(...validationSymbols(obj, entityMod));
435+
// A report's entity module exports a read schema only: no insert or update schema
436+
// exists to document (FR-044).
437+
if (!isReport(obj)) symbols.push(...validationSymbols(obj, entityMod));
414438
// REST needs no gate of its own: the routes generator's built-in filter is
415439
// `servesReadApi && !isTphSubtype` — exactly isQueryable — so every queryable
416440
// object gets routes. (Its `filter` option can narrow that further; this builder
@@ -483,26 +507,36 @@ function dataAccessSymbols(
483507
const update = updateFnName(name);
484508
const del = deleteByIdFnName(name);
485509

486-
const reads: ApiSymbol[] = [
487-
{
488-
name: find,
489-
kind: "data-access",
490-
importPath: mod,
491-
signature: `${find}(db: Db, ${pk}: ${pkType}): Promise<${name} | null>`,
492-
params: [`db: Db`, `${pk}: ${pkType}`],
493-
returns: `Promise<${name} | null>`,
494-
usage: `Fetch a single ${name} by its primary key; null when not found.`,
495-
},
496-
{
497-
name: list,
498-
kind: "data-access",
499-
importPath: mod,
500-
signature: `${list}(db: Db, opts?: { limit?: number; offset?: number }): Promise<${name}[]>`,
501-
params: [`db: Db`, `opts?: { limit?: number; offset?: number }`],
502-
returns: `Promise<${name}[]>`,
503-
usage: `List ${name} rows with optional limit/offset paging.`,
504-
},
505-
];
510+
const findSymbol: ApiSymbol = {
511+
name: find,
512+
kind: "data-access",
513+
importPath: mod,
514+
signature: `${find}(db: Db, ${pk}: ${pkType}): Promise<${name} | null>`,
515+
params: [`db: Db`, `${pk}: ${pkType}`],
516+
returns: `Promise<${name} | null>`,
517+
usage: `Fetch a single ${name} by its primary key; null when not found.`,
518+
};
519+
const listSymbol: ApiSymbol = {
520+
name: list,
521+
kind: "data-access",
522+
importPath: mod,
523+
signature: `${list}(db: Db, opts?: { limit?: number; offset?: number }): Promise<${name}[]>`,
524+
params: [`db: Db`, `opts?: { limit?: number; offset?: number }`],
525+
returns: `Promise<${name}[]>`,
526+
usage: `List ${name} rows with optional limit/offset paging.`,
527+
};
528+
529+
// A read-only object with no column to address a row by gets the list alone: the
530+
// read-only queries file emits `find<Name>ById` only when `hasItemRoute` (a keyless
531+
// projection and every report have none). Only the read-only surface asks; a writable
532+
// entity's queries file emits its by-id helpers unconditionally.
533+
const reads: ApiSymbol[] = lacksItemSurface(obj) ? [listSymbol] : [findSymbol, listSymbol];
534+
535+
// FR-044: a report is served by its list and nothing else. No create, update or delete
536+
// exists on any generated seam, so none is documented.
537+
if (isReport(obj)) {
538+
return reads;
539+
}
506540

507541
// A TPH discriminator base emits ONLY the polymorphic reads — the write
508542
// helpers are per concrete subtype (create<Sub> …), not on the base.
@@ -636,8 +670,12 @@ function restSymbols(
636670

637671
const symbols: ApiSymbol[] = [
638672
ep("GET", path, `List ${name} (supports filter/sort/paging query params).`, modelShape),
639-
ep("GET", `${path}/:id`, `Fetch a single ${name} by id (404 when not found).`, modelShape),
640673
];
674+
// `/:id` is mounted only when a row can be addressed (`hasItemRoute`): not for a
675+
// keyless projection, and never for a report.
676+
if (!lacksItemSurface(obj)) {
677+
symbols.push(ep("GET", `${path}/:id`, `Fetch a single ${name} by id (404 when not found).`, modelShape));
678+
}
641679

642680
if (!readOnly) {
643681
symbols.push(
@@ -842,8 +880,11 @@ function restHonoSymbols(
842880

843881
const symbols: ApiSymbol[] = [
844882
ep("GET", path, `[Hono] List ${name} (filter/sort/paging query params).`, modelShape),
845-
ep("GET", `${path}/:id`, `[Hono] Fetch a single ${name} by id (404 when not found).`, modelShape),
846883
];
884+
// The same rule as the Fastify surface: no `/:id` without an addressable row.
885+
if (!lacksItemSurface(obj)) {
886+
symbols.push(ep("GET", `${path}/:id`, `[Hono] Fetch a single ${name} by id (404 when not found).`, modelShape));
887+
}
847888

848889
if (!readOnly) {
849890
symbols.push(

‎server/typescript/packages/codegen-ts/src/generators/docs-data-builder.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ import type { OutputLayout } from "../import-path.js";
5252
import { docPageHref, docPageNode, effectivePackage } from "../docs-paths.js";
5353
import { fieldAnchorHtml } from "./field-anchor.js";
5454
import { enumValues } from "../enum-meta.js";
55-
import { hasWritableRdbSource } from "../source-detect.js";
55+
import { hasWritableRdbSource, isReport } from "../source-detect.js";
56+
import { buildReportBlock, buildReportingBlock } from "./report-doc.js";
5657
import { GENERATED_HEADER } from "../constants.js";
5758
import { renderEntityNeighborhoodErBlock } from "../templates/mermaid-er.js";
5859
// Shape C reuses the SAME walk the stub generator and the requirements index use, so
@@ -843,6 +844,18 @@ export function buildEntityDocData(
843844
data.claimedBy = claimedBy;
844845
data.hasClaimedBy = true;
845846
}
847+
// FR-044 (Table G): a report's page gets its "Report" section, and the entity a
848+
// report reads from (or that declares reporting members) gets "Reporting". Both are
849+
// absent for every other object.
850+
if (isReport(entity)) {
851+
data.reportBlock = buildReportBlock(entity, root, layout);
852+
data.hasReport = true;
853+
}
854+
const reportingBlock = buildReportingBlock(entity, root, layout);
855+
if (reportingBlock !== undefined) {
856+
data.reportingBlock = reportingBlock;
857+
data.hasReporting = true;
858+
}
846859
// Cross-link to the api surfaces — present ONLY when the caller computed the
847860
// hrefs (api surfaces emitted alongside model); model-only runs stay identical.
848861
// `last` flags the final ref so the template renders an inline ` · ` separator.

0 commit comments

Comments
 (0)