From 40dbfcb8efe3f9282bf76ca2a553e32a8f22f5e7 Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:01:43 +0300 Subject: [PATCH] fix: section-only blocks in bodies, list_entries default, long-line per column, body button colour - core-ts: body surfaces refuse theme blocks without where body (allowedInBody); catalogPrompt lists what bodies may use. - mcp-server: list_entries defaults to every collection; where/orderBy without a collection are refused instead of ignored. - render_page long-line counts rendered lines and pools paragraphs of one column, so identical paragraphs agree. - blog starter: .ch-richtext links no longer recolour .ch-button. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- .changeset/body-blocks-and-tools.md | 12 +++ packages/cli/test/render-chrome-text.test.ts | 84 +++++++++++++++++++ packages/core-ts/src/surfaces/body.ts | 25 +++++- packages/core-ts/src/surfaces/prompt.ts | 13 +++ .../core-ts/test/body-surface-blocks.test.ts | 68 +++++++++++++++ packages/mcp-server/src/entry-list.ts | 3 + packages/mcp-server/src/entry-tools.ts | 11 +-- .../mcp-server/src/render/checks/content.ts | 55 ++++++++++-- packages/mcp-server/test/listings.test.ts | 17 ++++ starters/blog/src/styles/features/tokens.css | 3 +- 10 files changed, 274 insertions(+), 17 deletions(-) create mode 100644 .changeset/body-blocks-and-tools.md create mode 100644 packages/cli/test/render-chrome-text.test.ts create mode 100644 packages/core-ts/test/body-surface-blocks.test.ts diff --git a/.changeset/body-blocks-and-tools.md b/.changeset/body-blocks-and-tools.md new file mode 100644 index 00000000..fa934370 --- /dev/null +++ b/.changeset/body-blocks-and-tools.md @@ -0,0 +1,12 @@ +--- +"@cloudhal/core-ts": patch +"@cloudhal/mcp-server": patch +"@cloudhal/cli": patch +--- + +Gaps an agent hit building a site through MCP: + +- **Section-only theme blocks in article bodies are refused.** A theme block type with `where: ["section"]` (say `link-cards`) has no component in an article, and drew "unknown component" there. `create_entry`/`update_entry` now refuse it inside a body ```` ```surface ```` fence (`invalid_surface`, with the component's path); primitives, built-in blocks and theme blocks that allow `body` stay. `get_catalog`'s "In article bodies" lists which blocks a body may use and which are page sections only. +- **`list_entries` lists every collection by default**, not only `posts`: a site whose articles live in `blog` got `[]`. `where`/`orderBy` need the collection whose list fields they use; without one they are refused (`invalid_query` at `collection`) instead of ignored. +- **`long-line` gives a text column one verdict.** It counted characters over a rounded line count, so how full a paragraph's last line was decided whether it passed, and identical paragraphs in one column disagreed. It now counts the characters on each rendered line, leaves each paragraph's last line out, and pools the paragraphs of one width and font: one example per column, with its width and how many paragraphs it holds. +- **Blog starter:** a primary surface `Button` in an article body keeps its `on-brand` text; the body's link colour no longer applies to buttons (it failed contrast at 2.5:1 light, 1.3:1 dark). diff --git a/packages/cli/test/render-chrome-text.test.ts b/packages/cli/test/render-chrome-text.test.ts new file mode 100644 index 00000000..3f02a1ba --- /dev/null +++ b/packages/cli/test/render-chrome-text.test.ts @@ -0,0 +1,84 @@ +/** + * render_page's text checks in the local Chrome: a column's line length (`long-line`) and a body + * button's contrast under the blog starter's own link rule. Skipped where this machine has no + * Chrome (set CHROME_PATH). + */ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { renderPage } from "@cloudhal/mcp-server/render"; +import { afterAll, describe, expect, it } from "vitest"; +import { chromeRenderer, findChrome } from "../src/render-chrome.ts"; + +const chrome = findChrome(); + +describe.skipIf(!chrome)("render_page text checks in Chrome", () => { + let dir: string; + afterAll(async () => { + if (dir) await rm(dir, { recursive: true, force: true }); + }); + + it("a primary surface Button in an article body keeps on-brand text (the starter's link rule)", async () => { + dir ??= await mkdtemp(path.join(os.tmpdir(), "cloudhal-render-test-")); + const tokens = await readFile( + path.join(import.meta.dirname, "../../../starters/blog/src/styles/features/tokens.css"), + "utf8", + ); + const linkRule = /\.ch-richtext a[^{]*\{[^}]*\}/.exec(tokens)?.[0]; + expect(linkRule).toBeDefined(); + // The button rule as blocks.css applies it; the link colour is the brand, as on cloudhal.com. + const html = `

Post

`; + const file = path.join(dir, "body-button.html"); + await writeFile(file, html); + const r = await renderPage( + chromeRenderer(chrome as string, { idleMs: 10 }), + pathToFileURL(file).href, + { + widths: [1440], + fullPage: false, + timeoutMs: 50_000, + }, + ); + expect(r.checks.find((c) => c.id === "contrast")).toMatchObject({ ok: true }); + }, 90_000); + + it("long-line gives a column one verdict, whatever its paragraphs' last lines hold", async () => { + dir ??= await mkdtemp(path.join(os.tmpdir(), "cloudhal-render-test-")); + // A monospace font: every character is as wide as the next, so a column's measure is exact. + const para = (chars: number) => + `

${"abcd " + .repeat(Math.ceil(chars / 5)) + .slice(0, chars) + .trim()}

`; + const page = (width: number) => + `

L

${ + // The same column, last lines from nearly empty to nearly full. + [3 * 95 + 2, 3 * 95 + 90, 4 * 95 + 40].map(para).join("") + }
`; + const render = async (name: string, html: string) => { + const file = path.join(dir, name); + await writeFile(file, html); + const r = await renderPage( + chromeRenderer(chrome as string, { idleMs: 10 }), + pathToFileURL(file).href, + { + widths: [1440], + fullPage: false, + timeoutMs: 50_000, + }, + ); + return r.checks.find((c) => c.id === "long-line"); + }; + const wide = await render("long-wide.html", page(95)); + expect(wide).toMatchObject({ ok: false, count: 1 }); + expect(wide?.examples[0]).toMatch( + /about 9[45] characters a line in this \d+ px column \(3 paragraphs\)$/, + ); + expect(await render("long-narrow.html", page(80))).toMatchObject({ ok: true }); + }, 90_000); +}); diff --git a/packages/core-ts/src/surfaces/body.ts b/packages/core-ts/src/surfaces/body.ts index b20389a4..f3b00487 100644 --- a/packages/core-ts/src/surfaces/body.ts +++ b/packages/core-ts/src/surfaces/body.ts @@ -1,7 +1,7 @@ /** Surfaces in markdown bodies (RFC-0020 §5): fences, parsing and checks. */ import type { SurfaceComponent, SurfaceSection } from "@cloudhal/core-contracts"; -import type { PropsIssue } from "../blocks.ts"; -import type { Catalog } from "./catalog/index.ts"; +import { BUILT_IN_BLOCK_TYPES, type PropsIssue } from "../blocks.ts"; +import type { Catalog, CatalogEntry } from "./catalog/index.ts"; import { INPUT_COMPONENTS } from "./catalog/props.ts"; import { checkSurface } from "./checks/index.ts"; import { isObj } from "./shared.ts"; @@ -130,6 +130,19 @@ export function bodySurfaces(markdown: string): BodySurface[] { return out; } +const BUILT_IN = new Set(BUILT_IN_BLOCK_TYPES.map((t) => t.name)); + +/** + * Whether a catalog component may sit in an article body's surface: every primitive and built-in + * block (Cloudhal draws them anywhere), and a theme's block only when its type allows `body`. A + * section-only theme block (`where: ["section"]`) is drawn by the theme's page sections alone. + */ +export function allowedInBody(entry: CatalogEntry): boolean { + return ( + entry.kind === "primitive" || BUILT_IN.has(entry.name) || entry.type.where.includes("body") + ); +} + /** Problems with a body's surfaces (paths start with the fence's id); unknown components pass. */ export function checkBodySurfaces(markdown: string, catalog: Catalog): PropsIssue[] { const out: PropsIssue[] = []; @@ -143,6 +156,14 @@ export function checkBodySurfaces(markdown: string, catalog: Catalog): PropsIssu for (const i of f.issues) out.push({ path: `${at}${i.path}`, message: i.message }); for (const i of checkSurface(f.section, catalog).issues) out.push({ path: `${at}${i.path}`, message: i.message }); + f.section.components.forEach((c, n) => { + const entry = catalog.get(c.component); + if (entry && !allowedInBody(entry)) + out.push({ + path: `${at}/components/${n}/component`, + message: `${c.component} is a section block of the theme, not allowed in article bodies; put it in a page section`, + }); + }); } return out; } diff --git a/packages/core-ts/src/surfaces/prompt.ts b/packages/core-ts/src/surfaces/prompt.ts index 67c5b477..cb76dc1d 100644 --- a/packages/core-ts/src/surfaces/prompt.ts +++ b/packages/core-ts/src/surfaces/prompt.ts @@ -2,6 +2,7 @@ import { BLOCK_LIMITS, localized, type PropSchema } from "../blocks.ts"; import { ICON_GROUPS } from "../icon-names.ts"; import { SURFACE_FUNCTIONS } from "./bindings/values.ts"; +import { allowedInBody } from "./body.ts"; import { type Catalog, childRule } from "./catalog/index.ts"; import { MOTION_REVEALS, MOTION_STAGGER } from "./motion.ts"; import { SURFACE_LIMITS } from "./shared.ts"; @@ -52,6 +53,17 @@ export function describeProp(name: string, s: PropSchema, required: boolean): st * Instructions for a model writing surfaces against this catalog: the format, bindings, limits * and every component with its props and an example. The same catalog validates what it writes. */ +/** Which blocks a body surface may use, when the theme has blocks it may not. */ +function bodyBlockLines(catalog: Catalog): string[] { + const blocks = catalog.entries().filter((e) => e.kind === "block"); + const pagesOnly = blocks.filter((e) => !allowedInBody(e)).map((e) => e.name); + if (!pagesOnly.length) return ["Every component below may be used in a body surface."]; + const allowed = blocks.filter(allowedInBody).map((e) => e.name); + return [ + `Every primitive may be used in a body surface, and these blocks: ${allowed.join(", ") || "none"}. These are page-section blocks only and are refused in bodies: ${pagesOnly.join(", ")}.`, + ]; +} + export function catalogPrompt(catalog: Catalog, locale = "en"): string { const lines: string[] = [ `# Cloudhal surfaces — catalog ${catalog.id}`, @@ -100,6 +112,7 @@ export function catalogPrompt(catalog: Catalog, locale = "en"): string { '{"id":"t","component":"Text","props":{"text":"Hello"}}', "```", "Body surfaces cannot load entries ($source); page surfaces can.", + ...bodyBlockLines(catalog), "", "## Editing", "Change a page with RFC 6902 JSON Patch operations on /title, /sections and /seo, e.g.", diff --git a/packages/core-ts/test/body-surface-blocks.test.ts b/packages/core-ts/test/body-surface-blocks.test.ts new file mode 100644 index 00000000..0dbe252e --- /dev/null +++ b/packages/core-ts/test/body-surface-blocks.test.ts @@ -0,0 +1,68 @@ +/** + * A body ```surface fence may use every primitive and built-in block, and a theme block only when + * its type allows `body`: a section-only theme block (`where: ["section"]`) has no component in an + * article and drew "unknown component" there, so writes refuse it and the catalog says so. + */ +import { describe, expect, it } from "vitest"; +import { createBlockRegistry, defineBlockTypes } from "../src/blocks.ts"; +import { checkBodyFences } from "../src/store/validation.ts"; +import { catalogPrompt, checkBodySurfaces, createCatalog } from "../src/surfaces.ts"; + +const block = (name: string, where: ("section" | "body")[]) => ({ + name, + title: name, + where, + props: { + type: "object" as const, + additionalProperties: false as const, + properties: { title: { type: "string" as const, maxLength: 80 } }, + }, + example: { props: { title: "x" } }, +}); +const blocks = createBlockRegistry( + defineBlockTypes([block("link-cards", ["section"]), block("testimonial", ["section", "body"])]), +); +const catalog = createCatalog({ name: "lens", blocks }); + +const body = (component: string) => + [ + "Intro.", + "", + '```surface {"id":"more","catalog":"lens@1"}', + '{"id":"root","component":"Stack","children":["b"]}', + `{"id":"b","component":"${component}","props":{"title":"Read on"}}`, + "```", + ].join("\n"); + +describe("blocks in article body surfaces", () => { + it("refuses a section-only theme block and names it", () => { + expect( + checkBodySurfaces(body("link-cards"), catalog).map((i) => `${i.path} ${i.message}`), + ).toEqual([ + "/surface/more/components/1/component link-cards is a section block of the theme, not allowed in article bodies; put it in a page section", + ]); + expect(() => checkBodyFences(blocks, body("link-cards"), "entry ent_1")).toThrow( + expect.objectContaining({ code: "invalid_surface" }), + ); + }); + + it("keeps primitives, built-in blocks, body-allowed theme blocks and unknown names", () => { + for (const ok of ["testimonial", "faq", "Text", "not-registered"]) + expect( + checkBodySurfaces(body(ok), catalog).filter((i) => i.path.endsWith("/component")), + ok, + ).toEqual([]); + }); + + it("get_catalog's prompt lists what bodies may use and what they may not", () => { + const prompt = catalogPrompt(catalog); + const line = prompt + .split("\n") + .find((l) => l.startsWith("Every primitive may be used in a body")); + expect(line).toContain("testimonial"); + expect(line).toMatch(/refused in bodies: link-cards\.$/); + expect(catalogPrompt(createCatalog())).toContain( + "Every component below may be used in a body surface.", + ); + }); +}); diff --git a/packages/mcp-server/src/entry-list.ts b/packages/mcp-server/src/entry-list.ts index f264d364..5c35d19e 100644 --- a/packages/mcp-server/src/entry-list.ts +++ b/packages/mcp-server/src/entry-list.ts @@ -79,6 +79,9 @@ export async function listEntries( const orderBy = a.orderBy as FieldOrder | undefined; const limit = a.limit as number | undefined; if (a.cursor !== undefined && limit === undefined) refuse("cursor", "a cursor needs limit"); + // List fields belong to one collection; without it they would be silently ignored. + if (base.collection === undefined && (where !== undefined || orderBy !== undefined)) + refuse("collection", "where and orderBy need the collection whose list fields they use"); const offset = a.cursor === undefined ? 0 : decodeCursor(a.cursor as string); const { entries } = await queryContentEntries(ctx.store, siteId, { ...base, diff --git a/packages/mcp-server/src/entry-tools.ts b/packages/mcp-server/src/entry-tools.ts index 6c3f401a..fa701615 100644 --- a/packages/mcp-server/src/entry-tools.ts +++ b/packages/mcp-server/src/entry-tools.ts @@ -42,11 +42,13 @@ const listEntriesTool: ToolDefinition = { name: "list_entries", title: "List articles", description: - 'Content entries, newest first. `collection` defaults to posts (unless the filter names one). `filter` selects by terms (RFC-0002 grammar): clauses joined by "+" (AND), "[a,b]" = either, "-" = none of, "primary:category:x" = primary term, "category:x>*" = x or a sub-category, "collection:posts"; values are term slugs (old slugs work) or ids. Example: "category:news+tag:[ai,llm]+-tag:sponsored". `where`/`orderBy` filter and sort by the collection\'s list fields (RFC-0042; list_collections → listFields), e.g. upcoming events: where [{"field":"startsAt","op":"gte","value":"now"}], orderBy {"field":"startsAt","direction":"asc"}; `limit` pages the answer (total, nextCursor → cursor).', + 'Content entries, newest first. Without `collection` (or a "collection:" filter clause), entries of every collection; each entry carries its `collection`. `filter` selects by terms (RFC-0002 grammar): clauses joined by "+" (AND), "[a,b]" = either, "-" = none of, "primary:category:x" = primary term, "category:x>*" = x or a sub-category, "collection:posts"; values are term slugs (old slugs work) or ids. Example: "category:news+tag:[ai,llm]+-tag:sponsored". `where`/`orderBy` filter and sort by the collection\'s list fields (RFC-0042; list_collections → listFields), e.g. upcoming events: where [{"field":"startsAt","op":"gte","value":"now"}], orderBy {"field":"startsAt","direction":"asc"}; `limit` pages the answer (total, nextCursor → cursor).', inputSchema: obj( { siteId: id, - collection: str("Collection slug", { default: "posts", pattern: SLUG_PATTERN }), + collection: str("Collection slug; leave out for every collection", { + pattern: SLUG_PATTERN, + }), filter: str("Filter over term assignments, e.g. category:news+tag:ai", { minLength: 1, maxLength: 512, @@ -81,9 +83,8 @@ const listEntriesTool: ToolDefinition = { handler: async (a, ctx) => { await requireSite(ctx, a.siteId as string); const filter = a.filter as string | undefined; - const collection = - (a.collection as string | undefined) ?? - (filter && /(^|\+)-?collection:/.test(filter) ? undefined : "posts"); + // Every collection by default: a site whose articles live in `blog` saw none under `posts`. + const collection = a.collection as string | undefined; const query: EntryQuery = { ...(collection !== undefined ? { collection } : {}), ...(filter !== undefined ? { filter } : {}), diff --git a/packages/mcp-server/src/render/checks/content.ts b/packages/mcp-server/src/render/checks/content.ts index 78c2c0d4..f7b258ee 100644 --- a/packages/mcp-server/src/render/checks/content.ts +++ b/packages/mcp-server/src/render/checks/content.ts @@ -48,16 +48,53 @@ export const CONTENT_CHECKS = ` // empty-section // chart-empty: a chart whose data has no rows. for (const el of document.querySelectorAll("[data-ch-chart-empty]")) add("chart-empty", el, "no rows in its data"); - // long-line: paragraphs averaging more than 90 characters a line. + // long-line: text columns whose full lines hold more than 90 characters on average. Counted on + // the rendered lines (each paragraph's last, partly filled one left out) and pooled over every + // paragraph of the same width and font, so paragraphs of one column get one verdict. + const range = document.createRange(); + const columns = new Map(); + let measured = 0; for (const p of document.querySelectorAll("p,li,dd,blockquote")) { - if (!visible(p) || p.querySelector("p,li")) continue; - const text = (p.innerText || "").trim(); - if (text.length < 180) continue; + if (measured >= 80 || !visible(p) || p.querySelector("p,li")) continue; + if ((p.innerText || "").trim().length < 180) continue; + measured++; + // Characters by the line they are drawn on, in reading order: a character more than half a + // line below the current line starts the next (inline code in another size stays on its line). + // A run of spaces counts once, as it is shown. const s = getComputedStyle(p); - const lh = s.lineHeight === "normal" ? parseFloat(s.fontSize) * 1.2 : parseFloat(s.lineHeight); - const lines = Math.round(p.getBoundingClientRect().height / lh); - if (lines < 3) continue; - const per = Math.round(text.length / lines); - if (per > 90) add("long-line", p, "about " + per + " characters a line"); + const half = (s.lineHeight === "normal" ? parseFloat(s.fontSize) * 1.2 : parseFloat(s.lineHeight)) / 2; + const rows = []; + let top = -Infinity, seen = 0, space = true; + const tw = document.createTreeWalker(p, NodeFilter.SHOW_TEXT); + while (tw.nextNode() && seen < 800) { + const n = tw.currentNode; + for (let i = 0; i < n.length && seen < 800; i++) { + const blank = /\s/.test(n.data[i]); + if (blank && space) continue; + space = blank; + seen++; + range.setStart(n, i); + range.setEnd(n, i + 1); + const b = range.getClientRects()[0]; + if (!b) continue; + if (b.top > top + half) { rows.push(0); top = b.top; } + rows[rows.length - 1]++; + } + } + // The last line seen may be partly filled (the paragraph's end, or where counting stopped). + const full = rows.slice(0, -1); + if (full.length < 2) continue; + const width = Math.round(p.getBoundingClientRect().width); + const key = width + "|" + s.fontSize + "|" + s.fontFamily; + const col = columns.get(key) || { width, first: p, paragraphs: 0, lines: 0, chars: 0 }; + col.paragraphs++; + col.lines += full.length; + col.chars += full.reduce((a, b) => a + b, 0); + columns.set(key, col); + } + for (const col of columns.values()) { + const per = Math.round(col.chars / col.lines); + if (per > 90) + add("long-line", col.first, "about " + per + " characters a line in this " + col.width + " px column" + (col.paragraphs > 1 ? " (" + col.paragraphs + " paragraphs)" : "")); } `; diff --git a/packages/mcp-server/test/listings.test.ts b/packages/mcp-server/test/listings.test.ts index 1a035a3d..7d39066b 100644 --- a/packages/mcp-server/test/listings.test.ts +++ b/packages/mcp-server/test/listings.test.ts @@ -445,6 +445,23 @@ describe("listings, expiry and structured data over MCP (RFC-0042 §7)", () => { expect(bad.message).toContain("list_collections"); const cursor = await rejection(list({ collection: "events", limit: 2, cursor: "zzz" })); expect(paths(cursor)).toEqual(["cursor"]); + // List fields belong to one collection: without it they are refused, not ignored. + const noCollection = await rejection( + list({ orderBy: { field: "startsAt", direction: "asc" } }), + ); + expect(paths(noCollection)).toEqual(["collection"]); + }); + + it("list_entries without a collection lists every collection, not only posts", async () => { + w = await world(LISTED); + await event(w, "Soon gig", { startsAt: at(T + 2 * HOUR), state: "scheduled", price: 20 }); + const all = (await call(w, "list_entries")({})).result as { entries: ContentEntry[] }; + expect(new Set(all.entries.map((e) => e.collection))).toEqual(new Set(["posts", "events"])); + const posts = (await call(w, "list_entries")({ collection: "posts" })).result as { + entries: ContentEntry[]; + }; + expect(posts.entries.every((e) => e.collection === "posts")).toBe(true); + expect(posts.entries.length).toBe(all.entries.length - 1); }); it("preview_structured_data returns the entry's JSON-LD and its issues", async () => { diff --git a/starters/blog/src/styles/features/tokens.css b/starters/blog/src/styles/features/tokens.css index 7d65a1f9..50ba886b 100644 --- a/starters/blog/src/styles/features/tokens.css +++ b/starters/blog/src/styles/features/tokens.css @@ -107,6 +107,7 @@ .ch-body :is(p, li, blockquote) { text-wrap: pretty; } -.ch-richtext a { +/* Links in a body, not buttons: a surface Button keeps its own colours (on-brand on brand). */ +.ch-richtext a:not(.ch-button) { color: var(--ch-color-link); }