An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): `astryx build` always names a page template to start from (#6707)
Joeyaa041548afa1
diff --git a/.changeset/cli-build-starts-from-a-template.md b/.changeset/cli-build-starts-from-a-template.mdnew file mode 100644index 0000000000..383d85d46f--- /dev/null+++ b/.changeset/cli-build-starts-from-a-template.md@@ -0,0 +1,18 @@+---+'@astryxdesign/cli': patch+---++[feat] `astryx build "<idea>"` now always names a page template to start from.++A page template carries the page frame, the spacing, and the section rhythm. A page composed from components has to rediscover them. Before, the kit recommended scaffolding only when a template matched almost by name. Other ideas got "use it as a layout reference", which pointed at a 35-line `--skeleton`, and an idea that no template matched got "frame with AppShell, then compose". Now:++- `start` names the template to scaffold, with the `template <id> --type page <path>` command that selects it (an integration replacement through the Core id it replaces), a `basis`, a one-line `reason`, and `alternatives`: the next two templates. A page ranker built for the long ideas builders write ("ops dashboard with a KPI row, a sortable table and a trend chart") picks it. Every matched word counts, weighted by how rare it is among page templates. The words before the first "with", ":" or "," name the page's family, a container ("in a modal") names its frame, and a word that only modifies another ("product" in "product response") counts half. A family's base template (`dashboard`, `settings`) leads its family unless a variant's own words outweigh it. Family words come from the templates' own ids. `basis` is `direct` when the ranker's pick is also search's direct match, `closest` when it is not, and `fallback` when nothing has the evidence to lead and the page starts from the `shell-top-nav` app shell (`blank` when that is not available). A template that is not ready yet is never the start.+- Search matches words more strictly. A term matches inside a name or keyword only at the start of one of its words ("input" finds `TextInput`, "file" no longer finds "profile"), plurals and stems count as the same word, and typo tolerance applies only to one-word lookups of words long enough that one edit rarely makes another word ("site" no longer matches "side", nor "cable" "table").+- Blocks and components that matched only one description word of a multi-word idea are no longer offered.+- The text output has four sections: TEMPLATE (with its reason and command), OTHER TEMPLATES, BLOCKS, and COMPONENTS (with the frame and foundation names). They replace RECOMMENDED START and PAGE TEMPLATES. Search's page matches (`pages`) move to one line, with their full entries under `--verbose`. Descriptions stop at their first sentence, and blocks and components show the top three, each with one shared command line. `--verbose` shows every block and component, with full descriptions, import paths, and match reasons. The recommended command always scaffolds (`template <id> --type page <path>`), where for most ideas it used to print a `--skeleton` or `component AppShell`.++The `build` playbook, the generated agent docs, and the `working-with-ai` and `layout` guides now start every page from a template.++Compatibility: the `build.kit` JSON only gains `start`. Every existing field keeps its shape and meaning. Which pages, blocks, and components are listed, and `directMatch`, change with the stricter matching, as ranking results do. The human-readable output is reorganized. Options, exit codes, and the `build.help` shape are unchanged, and `build` still writes nothing. The same matching changes the ranking of `search` results.++@josephfarinadiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 9edd32f5c6..94e4dd3a83 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -80,7 +80,7 @@ Options:| Command | Description || ------------- | ----------------------------------------------------------------------------- || `blog` | Read the Astryx blog from the published feed |-| `build` | Build a page: composition kit for an idea, or the workflow playbook (no args) |+| `build` | Build a page: the template to start from, or the workflow playbook (no query) || `component` | List components or print component docs || `discover` | Discover external packages and components || `docs` | Print reference docs |@@ -441,7 +441,7 @@ Every response has a `type` discriminant. The full set is below (generated from| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. || `search` | The echoed query, `matchCount` (total matches, before `limit`), and results, a ranked SearchResultEntry[] bounded by `limit`: each {domain, name, score, reason, description, command}, plus import (components, hooks), title, parent (the command that opens the level above), package (for a docs-tree hit), and, for a hit on one section, section (docs), or displayName and kind (templates). || `build.help` | The how-to-build-a-page playbook, emitted when no query is given: `playbook: true`, a title, the ordered steps (title, commands, optional returns), the on-system rules, and related lookups. Commands are bare subcommands for the caller to render with its own invocation. |-| `build.kit` | The composition kit: echoed query, hasResults, matchCount (total matched, never a cap), directMatch, pages (closest templates), blocks (drop-in patterns) and domain (idea components/hooks) as SearchResultEntry[], frame and foundation name arrays, and hint {reason, commands} when thin. |+| `build.kit` | The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, command, basis, reason, alternatives, ...}, pages (search's closest templates), blocks and domain as SearchResultEntry[], frame, foundation, and hint {reason, commands} when thin. || `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. || `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. || `gap-report.categories` | The fixed gap category values and human-readable labels. |diff --git a/packages/cli/api/build/_adapter.mjs b/packages/cli/api/build/_adapter.mjsnew file mode 100644index 0000000000..1f423cb35b--- /dev/null+++ b/packages/cli/api/build/_adapter.mjs@@ -0,0 +1,60 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The build subject's environment access: the page templates a project+ * can scaffold.+ *+ * @input Template discovery for `cwd` — the CLI's own templates plus any that+ * the project's configured integrations contribute.+ * @output Ready page templates as `{name, displayName, description, category,+ * command}`, where `command` is the `astryx template` command that selects+ * exactly that template.+ * @position Beside build.mjs (api/build/). The kit leaf reads templates only+ * through here, because a subject's `_adapter.mjs` is its only environment+ * access. Search keeps its own discovery; this adds none of its own, it+ * reuses the template subject's.+ */++import {discoverTemplates} from '../template/template.mjs';++/**+ * A page template the kit can recommend starting from.+ * @typedef {object} PageTemplate+ * @property {string} name The template's own id, as search reports it.+ * @property {string} command `astryx template <id> --type page`, the command that selects exactly this template: an integration replacement is selected by the Core id it replaces, and `--type page` keeps a block with the same id from making it ambiguous. Search prints template commands the same way.+ * @property {string} displayName Human-facing name.+ * @property {string} description What the page is: its layout and the ideas it serves.+ * @property {string} category The template's own `Family - Variant` label; empty when it declares none.+ */++/**+ * Every ready page template the project can scaffold, in discovery order. This+ * is the default discovery view: an active integration replacement stands in+ * for the Core template it replaces, as it does for `astryx template <id>`.+ *+ * Discovery failures leave the kit without a start rather than failing the+ * command: the kit still carries its search matches, and `template --list`+ * reports what went wrong.+ *+ * @param {string} cwd+ * @returns {Promise<PageTemplate[]>}+ */+export async function loadPageTemplates(cwd) {+ let templates;+ try {+ templates = await discoverTemplates(cwd);+ } catch {+ return [];+ }+ return templates+ .filter(t => t.type === 'page' && t.isReady !== false)+ .map(t => ({+ name: t.dirName,+ displayName: t.displayName || t.name,+ description: t.description || '',+ category: t.category || '',+ // The id `template()` resolves back to this entry: an active replacement+ // owns the Core id it names, so that id selects it, not its own.+ command: `astryx template ${t.replaces ?? t.dirName} --type page`,+ }));+}diff --git a/packages/cli/api/build/build.doc.mjs b/packages/cli/api/build/build.doc.mjsindex de33d2a2d2..c9ef6901e2 100644--- a/packages/cli/api/build/build.doc.mjs+++ b/packages/cli/api/build/build.doc.mjs@@ -14,13 +14,16 @@ export const doc = {namespace: 'cli/api',displayName: 'build()',summary:- 'Page-building assistant: the how-to-build playbook, or a composition kit for an idea.',+ 'Page-building assistant: the how-to-build playbook, or the page template to start from for an idea.',description:- 'The "assemble a page" entry point. Called with no query it returns the ' ++ 'The "build a page" entry point. Called with no query it returns the ' +'how-to-build-a-page playbook as data: the workflow steps with their ' +- 'commands, the on-system rules, and related lookups. Called with a query it runs the unified search and groups the ' +- 'hits into a composition KIT: the closest page templates, drop-in blocks, ' +- 'and idea-specific components/hooks, plus the always-on frame + foundation.',+ 'commands, the on-system rules, and related lookups. Called with a query it names the page template to ' ++ 'START from (always one: the page template a ranker built for long descriptions puts first, else the app ' ++ 'shell) and the next two templates, ' ++ 'and the unified search grouped around it: the other close page templates, drop-in blocks, and ' ++ 'idea-specific components/hooks, plus the always-on frame + foundation. A template carries the page ' ++ 'frame and spacing, so the kit never recommends composing a page from components.',importPath: '@astryxdesign/cli/api',signature:'build(query?: string, options?: BuildOptions): Promise<BuildHelpResponse | BuildKitResponse>',@@ -60,7 +63,7 @@ export const doc = {{type: 'build.kit',description:- 'The grouped composition kit: the echoed query, hasResults/matchCount/directMatch fields, the closest page templates (≤3), drop-in block patterns (≤5), idea-specific components/hooks (≤6), and the always-on frame + foundation component-name arrays. Carries `hint` only when the kit came back thin — what to try instead, so a caller does not read a near-empty kit as "the package has nothing".',+ "The page template to start from and the kit around it: the echoed query, hasResults/matchCount/directMatch fields, `start` (the template to scaffold, the `template <id> --type page <path>` command that selects it, whether the page ranker's pick is also search's direct match, the closest page, or the fallback app shell, and the ranker's next two `alternatives`), search's closest page templates (≤3), drop-in block patterns (≤5), idea-specific components/hooks (≤6), and the always-on frame + foundation component-name arrays. Carries `hint` only when the kit came back thin — what to try instead, so a caller does not read a near-empty kit as \"the package has nothing\".",},],throws: [@@ -71,7 +74,10 @@ export const doc = {],examples: [{label: 'Get the playbook', code: 'const r = await build();'},- {label: 'Compose a page', code: "await build('analytics dashboard');"},+ {+ label: 'Find the template to start from',+ code: "const {data} = await build('analytics dashboard');\n// data.start.command: 'astryx template dashboard --type page <path>'",+ },{label: 'Restrict + limit',code: "await build('pricing', {type: 'template', limit: 10});",diff --git a/packages/cli/api/build/build.test.mjs b/packages/cli/api/build/build.test.mjsindex b2f551b062..4b2c0780ef 100644--- a/packages/cli/api/build/build.test.mjs+++ b/packages/cli/api/build/build.test.mjs@@ -1,7 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Tests for the build API (playbook + composition kit).+ * @file Tests for the build API (playbook + the template-first kit).*/import {describe, it, expect, vi} from 'vitest';@@ -37,6 +37,15 @@ describe('build API', () => {for (const {command} of commands) expect(command).not.toMatch(/^(astryx|npx|pnpm|yarn|bunx?)\b/);});+ it('the playbook scaffolds the named template before composing', async () => {+ const r = await build();+ if (r.type !== 'build.help') throw new Error(r.type);+ const commands = r.data.steps.map(s => s.commands.map(c => c.command));+ expect(commands[0][0]).toMatch(/^build /);+ expect(commands[1]).toContain('template <name> <path>');+ expect(JSON.stringify(r.data)).not.toMatch(/--skeleton|reference code/);+ });+it('query → build.kit with raw entries + static frame/foundation', async () => {const r = await build('dashboard', {cwd: REPO});expect(r.type).toBe('build.kit');@@ -76,10 +85,10 @@ describe('build API', () => {expect(blocks.length).toBeLessThanOrEqual(5);expect(domain.length).toBeLessThanOrEqual(6);- // Score floors: pages ≥ PAGE_FLOOR(50); blocks/domain ≥ DOMAIN_FLOOR(55).+ // Score floors: pages ≥ PAGE_FLOOR(50); blocks/domain ≥ DOMAIN_FLOOR(60).for (const p of pages) expect(p.score).toBeGreaterThanOrEqual(50);- for (const b of blocks) expect(b.score).toBeGreaterThanOrEqual(55);- for (const d of domain) expect(d.score).toBeGreaterThanOrEqual(55);+ for (const b of blocks) expect(b.score).toBeGreaterThanOrEqual(60);+ for (const d of domain) expect(d.score).toBeGreaterThanOrEqual(60);// directMatch iff the top page is a confident match (PAGE_DIRECT = 95).expect(directMatch).toBe(pages.length > 0 && pages[0].score >= 95);@@ -201,7 +210,7 @@ describe('build kit — a thin kit says what to try next', () => {it('hints for a matched-then-filtered query: hasResults true, nothing offerable', async () => {// The case most likely to be misread, and the reason the threshold counts// what SURVIVED the floors rather than what search returned.- const r = await build('blockchain', {cwd: REPO});+ const r = await build('hydration', {cwd: REPO});expect(r.type).toBe('build.kit');if (r.type !== 'build.kit') return;expect(r.data.hasResults).toBe(true);@@ -224,12 +233,28 @@ describe('build kit — a thin kit says what to try next', () => {}});+ it('still starts from the closest page on a loose match, and scaffolds it', async () => {+ // A skeleton is a 35-line excerpt: a reader who studies it and composes+ // the rest loses the spacing the template exists to carry. A loose match+ // is still the best start there is, so `start` scaffolds it.+ const r = await build('executive summary', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.directMatch).toBe(false);+ expect(r.data.start).toMatchObject({+ name: 'dashboard-scorecard',+ basis: 'closest',+ command: 'astryx template dashboard-scorecard --type page <path>',+ });+ });+it('recommends scaffolding on a direct match', async () => {const r = await build('contact form', {cwd: REPO});expect(r.type).toBe('build.kit');if (r.type !== 'build.kit') return;expect(r.data.directMatch).toBe(true);expect(r.data.pages.length).toBeGreaterThan(0);+ expect(r.data.start).toMatchObject({name: r.data.pages[0].name, basis: 'direct'});for (const page of r.data.pages) {expect(page.command).not.toMatch(/--skeleton/);}@@ -238,12 +263,13 @@ describe('build kit — a thin kit says what to try next', () => {it('keeps the recommendation package-manager-agnostic', async () => {// Appending a flag must not turn into prefixing an invocation; that stays// the renderer's job.- const r = await build('notifications', {cwd: REPO});+ const r = await build('executive summary', {cwd: REPO});expect(r.type).toBe('build.kit');if (r.type !== 'build.kit') return;for (const page of r.data.pages) {expect(page.command).not.toMatch(/^(pnpm|npm|yarn|bun|npx)\b/);}+ expect(r.data.start?.command).not.toMatch(/^(pnpm|npm|yarn|bun|npx)\b/);});it('keeps recovery commands bare, for the caller to render', async () => {@@ -258,3 +284,155 @@ describe('build kit — a thin kit says what to try next', () => {}});});++describe('build kit — every page starts from a template', () => {+ it('falls back to the app shell when no page template matches', async () => {+ // Before, an unmatched idea got "compose from AppShell": the one path+ // with no frame, no spacing, and no section rhythm.+ const r = await build('zzznomatch99', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.hasResults).toBe(false);+ expect(r.data.start).toMatchObject({+ name: 'shell-top-nav',+ basis: 'fallback',+ command: 'astryx template shell-top-nav --type page <path>',+ });+ expect(r.data.start?.description).toBeTruthy();+ });++ it('starts a long idea from the family its words name', async () => {+ // The coverage gate cannot tell layout words from subject matter: every+ // dashboard covers one term of three, so search offers no page at all.+ // The ranker still starts the page from the dashboard.+ const r = await build('quarterly revenue dashboard', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.start).toMatchObject({name: 'dashboard', basis: 'closest'});+ expect(r.data.directMatch).toBe(false);+ });++ it('does not start from a direct match that is not ready yet, and says so', async () => {+ const r = await build('incident console', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.directMatch).toBe(true);+ expect(r.data.pages[0].name).toBe('incident-console');+ expect(r.data.start?.name).not.toBe('incident-console');+ expect(r.data.start?.reason).toMatch(/`incident-console` matches but is not ready yet/);+ });++ it('does not start from a page that matched one incidental word', async () => {+ // A work-item detail page mentions a feed in its description. That is a+ // worse start for a news feed than the app shell.+ const r = await build('news feed', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.start?.basis).toBe('fallback');+ });++ it('starts a part from the page it is placed in, else from the app shell', async () => {+ const placed = await build('an empty state for a settings page', {cwd: REPO});+ if (placed.type !== 'build.kit') throw new Error(placed.type);+ expect(placed.data.start).toMatchObject({name: 'settings', basis: 'closest'});+ const loose = await build('a date range picker', {cwd: REPO});+ if (loose.type !== 'build.kit') throw new Error(loose.type);+ expect(loose.data.start).toMatchObject({name: 'shell-top-nav', basis: 'fallback'});+ });++ it('names a direct match the ranker outweighed in the reason', async () => {+ const r = await build('dashboard with a login form', {cwd: REPO});+ if (r.type !== 'build.kit') throw new Error(r.type);+ expect(r.data.directMatch).toBe(true);+ expect(r.data.pages[0].name).toBe('login');+ expect(r.data.start).toMatchObject({name: 'dashboard', basis: 'closest'});+ expect(r.data.start?.reason).toContain('`login`');+ });++ it('names the loose page matches when it falls back to the shell', async () => {+ const r = await build('news feed', {cwd: REPO});+ if (r.type !== 'build.kit') throw new Error(r.type);+ expect(r.data.pages.length).toBeGreaterThan(0);+ expect(r.data.start?.basis).toBe('fallback');+ for (const page of r.data.pages) expect(r.data.start?.reason).toContain(`\`${page.name}\``);+ });++ it('never gives a reason that denies a match the response reports', async () => {+ for (const q of ['news feed', 'dashboard with a login form', 'user profile', 'incident console']) {+ const r = await build(q, {cwd: REPO});+ if (r.type !== 'build.kit') throw new Error(r.type);+ if (r.data.pages.length) expect(r.data.start?.reason).not.toMatch(/No template matched/);+ if (r.data.directMatch) expect(r.data.start?.reason).not.toMatch(/none is exactly this page/);+ }+ });++ it('names no start when the kit is narrowed to components', async () => {+ const r = await build('dashboard', {cwd: REPO, type: 'component'});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.start).toBeNull();+ });++++ it('keeps incidental description matches out of blocks and components', async () => {+ // Toast, Popover and TextInput all say "brief" somewhere in their+ // descriptions; none of them is part of a brief.+ const r = await build('weekly brief', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ const names = [...r.data.blocks, ...r.data.domain].map(e => e.name);+ for (const noise of ['Toast', 'Popover', 'TextInput']) expect(names).not.toContain(noise);+ });++ it('names the ranker\'s next two templates beside every start', async () => {+ for (const idea of ['quarterly revenue dashboard', 'contact form']) {+ const r = await build(idea, {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ const alternatives = r.data.start?.alternatives ?? [];+ expect(alternatives.length).toBeGreaterThan(0);+ expect(alternatives.length).toBeLessThanOrEqual(2);+ for (const alt of alternatives) {+ expect(alt.name).not.toBe(r.data.start?.name);+ expect(alt.description).toBeTruthy();+ expect(alt.command).toBe(`astryx template ${alt.name} --type page <path>`);+ }+ }+ });++ it('calls a start direct only when search and the ranker agree', async () => {+ const r = await build('contact form', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.directMatch).toBe(true);+ expect(r.data.start).toMatchObject({name: r.data.pages[0].name, basis: 'direct'});+ });++ it('never lets a noisy search match pick the start', async () => {+ // Search once matched "site" to the gallery's "side" and started a+ // navigation bar from a gallery. The ranker alone picks the start now.+ const r = await build('horizontal site navigation with a current section indicator', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.start?.name).toBe('shell-top-nav');+ expect(r.data.pages.map(p => p.name)).not.toContain('side-gallery');+ });++ it('starts a component in a container from a template with that frame', async () => {+ // "in a modal": the modal is the frame, so the dialog template leads+ // instead of the app shell.+ const r = await build('saved drafts in a modal with resume and delete row actions', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.start?.name).toBe('settings-dialog');+ });++ it('does not start from a template named only by a word that modifies another', async () => {+ // "product" describes the response; it is not a product page.+ const r = await build('an interactive command catalog with side-by-side product response and trace', {cwd: REPO});+ expect(r.type).toBe('build.kit');+ if (r.type !== 'build.kit') return;+ expect(r.data.start?.name).not.toMatch(/^product-/);+ });+});diff --git a/packages/cli/api/build/build.type.mjs b/packages/cli/api/build/build.type.mjsindex f893ffd7c0..110561fc5c 100644--- a/packages/cli/api/build/build.type.mjs+++ b/packages/cli/api/build/build.type.mjs@@ -3,14 +3,13 @@/*** @file Colocated types for the `build` command — source of truth for the* `build.help` (playbook) and `build.kit` (composition kit) JSON responses.- * Re-exported by types/build.d.ts.*//*** A command the playbook tells the caller to run.** @typedef {object} BuildPlaybookCommand- * @property {string} command Bare subcommand with `<placeholder>` arguments (e.g. `template <name> --skeleton`) and no package-manager prefix — render it with your own CLI invocation.+ * @property {string} command Bare subcommand with `<placeholder>` arguments (e.g. `template <name> <path>`) and no package-manager prefix — render it with your own CLI invocation.* @property {string} [purpose] What running it is for.*/@@ -37,7 +36,30 @@*//**- * astryx --json build "<idea>" — the composition kit for what you're building.+ * The page template a kit recommends starting from.+ *+ * @typedef {object} BuildStart+ * @property {string} name Template id, as `astryx template <name>` takes it.+ * @property {string} displayName Human-facing template name.+ * @property {string} description What the page is: its layout and the ideas it serves.+ * @property {string} command The scaffold command that selects exactly this template, `astryx template <id> --type page <path>`: `<id>` is the Core id an integration replacement stands in for, else the template's own id, `<path>` is a placeholder for the file or folder to write the template to, and the `astryx` prefix is for the caller to replace with its own invocation.+ * @property {'direct' | 'closest' | 'fallback'} basis Why this template. The page ranker picks every start: it weighs each matched word by how rare it is among page templates, favors the family the idea's head names and the container it names ("in a modal"), and discounts words that only modify another. `direct` when its pick is also search's direct match (`directMatch`); `closest` when it is not; `fallback` when no template has the evidence to lead and the page starts from the app shell.+ * @property {string} reason One sentence saying the same as `basis`, for a reader.+ * @property {BuildAlternative[]} alternatives The ranker's next closest page templates (≤2), for when the start's layout is wrong.+ */++/**+ * A page template to consider instead of the start.+ *+ * @typedef {object} BuildAlternative+ * @property {string} name Template id, as `astryx template <name>` takes it.+ * @property {string} displayName Human-facing template name.+ * @property {string} description What the page is: its layout and the ideas it serves.+ * @property {string} command The scaffold command, in the same form as the start's.+ */++/**+ * astryx --json build "<idea>" — the page template to start from, and the kit around it.** Entries are raw `SearchResultEntry` objects (no package-manager-prefixed* command strings — the CLI adds those); `frame`/`foundation` are static@@ -47,14 +69,15 @@* @property {'build.kit'} type* @property {object} data* @property {string} data.query- * @property {boolean} data.hasResults False when search returned nothing (renderer shows "No matches").+ * @property {boolean} data.hasResults False when search returned nothing. The kit still names a template in `start`.* @property {number} data.matchCount Total ranked search matches for the query — counted before the search `limit`, the kit's score floors, and its per-group caps, so it is never a cap read back.* @property {boolean} data.directMatch True when the top page template is a confident direct match.- * @property {import('../search/search.type.mjs').SearchResultEntry[]} data.pages Closest page templates (≤3). Each entry's `command` carries `--skeleton` when `directMatch` is false, so it recommends reading the layout rather than scaffolding it.+ * @property {BuildStart | null} data.start The page template to start from: the ranker's pick, else the app shell. Null only when the kit is narrowed to components or hooks (`type`), or when the project has no page template to offer.+ * @property {import('../search/search.type.mjs').SearchResultEntry[]} data.pages Closest page templates by search (≤3). Each entry's `command` carries `--skeleton` when `directMatch` is false, so it previews the layout; `start.command` is the scaffold.* @property {import('../search/search.type.mjs').SearchResultEntry[]} data.blocks Drop-in block patterns covering parts of the idea (≤5).* @property {import('../search/search.type.mjs').SearchResultEntry[]} data.domain Idea-specific components/hooks (≤6), excluding frame/foundation.- * @property {string[]} data.frame Always-on page-shell component names.- * @property {string[]} data.foundation Always-on layout/typography/action component names.+ * @property {string[]} data.frame Always-on page-shell component names. Every page template already uses them.+ * @property {string[]} data.foundation Always-on layout/typography/action component names. Every page template already uses them.* @property {{reason: string, commands: string[]}} [data.hint] Present only when the kit is thin. `reason` says why, `commands` are bare subcommands (e.g. `component --list`) for the caller to render with its own invocation — so a reader is never handed a command that does not resolve in their project.*/diff --git a/packages/cli/api/build/help/help.mjs b/packages/cli/api/build/help/help.mjsindex 32eb64fe92..70a3ae5228 100644--- a/packages/cli/api/build/help/help.mjs+++ b/packages/cli/api/build/help/help.mjs@@ -9,6 +9,10 @@* package-manager prefix, which keeps the JSON environment-agnostic; the CLI* renders each one with the caller's invocation, as it does build.kit's* `hint.commands`.+ *+ * The workflow starts every page from a template, because a template already+ * has the frame, spacing, and section rhythm that a page composed from+ * components has to rediscover.*//**@@ -24,39 +28,48 @@ export function buildHelp() {title: 'How to build a page with Astryx',steps: [{- title: "Find a starting point for what you're building",+ title: 'Find the page template to start from',commands: [{command: 'build "<what you\'re building>"'}],returns:- 'the closest [page] template, the [block]s that cover parts, and the [component]s to fill the gaps, with a recommended start',- },- {- title: 'If a [page] template matches, scaffold it and adapt',- commands: [{command: 'template <name> [path]'}],+ 'the [page] template to start from (always one: the closest match, or the app shell when nothing matches), the next two templates, and the [block]s and [component]s for the parts it lacks',},{- title: 'If nothing matches exactly, compose',+ title: 'Scaffold that template into your project',commands: [{- command: 'template <name> --skeleton',- purpose: "study a close page's layout",+ command: 'template <name> <path>',+ purpose: 'write the page template to <path>',},+ ],+ },+ {+ title: 'Adapt it: keep its frame and spacing, replace its content',+ commands: [{command: 'template <BlockName>',- purpose: 'drop in each block from the kit',+ purpose:+ 'print a block to put inside a section, for a part the template lacks',},{command: 'component <Name>',- purpose: 'fill remaining gaps (read props)',+ purpose: 'read props before you change a component',},],},],rules: [+ 'Start every page from a page template. Never lay out a page from scratch.',+ 'Changing a page you already have? Keep it. Add blocks and components inside its sections.',+ "Keep the template's page frame, gap, and padding values. Replace its data, copy, and sections.",'No <div>/raw HTML for layout — use VStack/HStack/Grid/Stack/Card etc.','No style={{}} — use component props, and design tokens for values.','Wrap the app in <Theme theme={...}> and import core reset.css + astryx.css.',],related: [+ {+ command: 'template --list --type page',+ purpose: 'every page template',+ },{command: 'docs tokens', purpose: 'the design tokens'},{command: 'search <query>',diff --git a/packages/cli/api/build/kit/kit.mjs b/packages/cli/api/build/kit/kit.mjsindex ecea1e8319..a25e1cbcfe 100644--- a/packages/cli/api/build/kit/kit.mjs+++ b/packages/cli/api/build/kit/kit.mjs@@ -1,44 +1,57 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file build.kit leaf — the grouped composition kit and raw match count.+ * @file build.kit leaf — the page template to start from, and the kit around it.*- * Runs the unified search for the query and groups the results into a- * composition KIT: the closest page templates, the blocks that cover parts,- * and the domain components to fill gaps, plus the always-on frame + foundation.+ * Every kit names a page template to START from: the page the page ranker+ * (rank.mjs) puts first when it has the evidence to lead, else the app shell.+ * The ranker is the only thing that picks the start, so one noisy signal —+ * search matching "site" to a gallery's "side" — cannot choose the page. A+ * template carries the page frame, the spacing, and the section rhythm; a page+ * composed from components carries none of that, so the kit never recommends+ * composing from scratch while a template exists. Next to the start it names+ * the ranker's next two templates, then groups the unified search into the+ * blocks that cover parts and the domain components to fill gaps, plus the+ * always-on frame + foundation names. `pages` and `directMatch` keep search's+ * own view for callers that read them.** The kit carries RAW `SearchResultEntry` objects and static name arrays only —* never pre-formatted command strings. All CLI prefixing (formatCliCommand /* getCliInvocation) and the section prose live in the command renderer, so the* JSON shape stays package-manager-agnostic and stable across environments.*- * The one adjustment it makes is on a page's `command`: when the top page is- * not a direct match the kit appends `--skeleton`, so the field agrees with- * the recommendation the kit itself computed. That is still not prefixing —+ * Two commands are the kit's own: `start.command`, the scaffold (`astryx+ * template <id> --type page <path>`, with `<path>` a placeholder), and the `--skeleton`+ * a page entry carries when it is not a direct match, so a loose page reads+ * as a layout preview rather than the thing to build. Neither is prefixing —* the invocation stays the renderer's job.*/import {search} from '../../search/search.mjs';import {getResultCoverage} from '../../search/coverage.mjs';+import {loadPageTemplates} from '../_adapter.mjs';+import {pickAlternatives, pickStart, rankPages} from './rank.mjs';/** A page at/above this score is a confident direct match. */const PAGE_DIRECT = 95;-/** Below this a page is too weak to offer even as a layout reference. */+/** Below this a page is too weak to offer at all. */const PAGE_FLOOR = 50;-/** Below this a block/domain-component match is incidental noise. */-const DOMAIN_FLOOR = 55;/**- * How much of a multi-word query a result must cover to be offered as a PAGE.- *- * Score alone cannot carry this. A page's keywords include every component its- * source renders, so `build "actionable warning banner"` scored `login`,- * `contact-form` and `documentation-design` at 95 apiece — an exact keyword hit- * (90) on "banner" alone, plus the coverage garnish, lands exactly on- * PAGE_DIRECT. Three pages that are not warnings, presented as a direct match,- * because each happens to render a Banner somewhere.+ * Below this a block/domain-component match is incidental noise. A single+ * description word in a multi-word idea scores 50 plus at most 7.5 of coverage+ * garnish, so it stays below; a name or keyword hit clears it. `build "weekly+ * brief"` used to offer Toast, Popover and TextInput because their+ * descriptions say "brief".+ */+const DOMAIN_FLOOR = 60;+/**+ * How much of a multi-word query a page must cover to be offered on breadth.*- * Coverage has to gate rather than garnish: matching one of three concepts is- * not the same claim as matching three.+ * Score alone cannot carry this. A page's derived keywords include every+ * component its source renders, so `build "actionable warning banner"` once+ * scored `login`, `contact-form` and `documentation-design` at 95 apiece — an+ * exact hit on "banner" alone, plus the coverage garnish. Matching one of+ * three concepts is not the same claim as matching three.*/const PAGE_COVERAGE = 0.5;/**@@ -50,12 +63,21 @@ const PAGE_COVERAGE = 0.5;* Astryx contains, which is exactly the failure `build` exists to prevent.*/const THIN_KIT = 3;+/**+ * Where a page starts when no page template matched: the first of these the+ * project can scaffold. A top nav over empty, full-width content is the least+ * opinionated frame that still has navigation; `blank` is the floor, with no+ * chrome at all. Either one still hands the reader a page frame and its+ * padding, which composing from components does not.+ */+const FALLBACK_STARTS = ['shell-top-nav', 'blank'];/*** Always-surfaced primitives. Every page needs a shell + layout/typography/* action atoms, but these never keyword-match an idea ("dashboard" != "Stack"),* so search alone never returns them. Kept here (not the renderer) because they* are ALSO used to exclude these names from the idea-specific `domain` group.+ * Every page template already uses them.*/const FRAME = ['AppShell', 'TopNav', 'SideNav', 'Layout'];const FOUNDATION = [@@ -75,7 +97,90 @@ const FOUNDATION = [const ALWAYS = new Set([...FRAME, ...FOUNDATION]);/**- * The grouped composition kit for what you're building.+ * @typedef {import('../../search/search.type.mjs').SearchResultEntry} SearchResultEntry+ * @typedef {import('../build.type.mjs').BuildStart} BuildStart+ * @typedef {import('../_adapter.mjs').PageTemplate} PageTemplate+ */++/**+ * A page template as the kit names it: the command that selects exactly that+ * template, scaffolding into `<path>`, a placeholder for the file or folder to+ * write it to.+ * @param {PageTemplate} t+ */+const asTemplate = t => ({+ name: t.name,+ displayName: t.displayName,+ description: t.description,+ command: `${t.command} <path>`,+});++/**+ * The template to start from: the ready page the ranker puts first when it+ * has the evidence to lead, else the first fallback shell the project can+ * scaffold. Null only when the project has no page template to offer at all.+ *+ * `direct` means two independent signals agree: the ranker's pick is also+ * search's direct match. The ranker sees only ready templates, so a template+ * still marked not ready is never the start; when search matched one directly+ * the reason names it, so the reader knows why the kit starts elsewhere.+ *+ * @param {import('./rank.mjs').RankedPage[]} ranked+ * @param {SearchResultEntry[]} pages+ * @param {boolean} directMatch+ * @param {PageTemplate[]} catalog+ * @returns {Omit<BuildStart, 'alternatives'> | null}+ */+function chooseStart(ranked, pages, directMatch, catalog) {+ const direct = directMatch ? pages[0].name : null;+ const unready =+ direct && !catalog.some(t => t.name === direct) ? direct : null;+ // The reason never denies a match the same response reports: a direct+ // match the ranker outweighed is named, and so are the loose page matches+ // search listed when the kit falls back to the shell.+ const loose = pages.map(p => `\`${p.name}\``).join(', ');+ const pick = pickStart(ranked);+ const closest = pick && catalog.find(t => t.name === pick.name);+ if (closest) {+ const agrees = closest.name === direct;+ return {+ ...asTemplate(closest),+ basis: agrees ? 'direct' : 'closest',+ reason: agrees+ ? 'Matches the idea.'+ : unready+ ? `\`${unready}\` matches but is not ready yet; this is the closest ready template.`+ : direct+ ? `Search matched \`${direct}\` by name, but this template fits more of the idea.`+ : 'The closest template; none is exactly this page.',+ };+ }+ for (const id of FALLBACK_STARTS) {+ const shell = catalog.find(t => t.name === id);+ if (shell) {+ // The shell can also be the ranker's best guess without the evidence to+ // lead ("horizontal site navigation"); say so rather than "no match".+ const nearest = ranked[0]?.name === shell.name && ranked[0].hits > 0;+ return {+ ...asTemplate(shell),+ basis: 'fallback',+ reason: unready+ ? `\`${unready}\` matches but is not ready yet, so start from the app shell.`+ : direct+ ? `Search matched \`${direct}\` by name, but too little of the idea fits it, so start from the app shell.`+ : nearest+ ? 'No template is a clear match; the app shell is the closest.'+ : loose+ ? `Search matched ${loose} only loosely, so start from the app shell.`+ : 'No template matched, so start from the app shell.',+ };+ }+ }+ return null;+}++/**+ * The page template to start from, and the kit around it.** @param {string} query what you're building (e.g. "analytics dashboard")* @param {{cwd?: string, type?: import('../../search/search.type.mjs').SearchDomain, limit?: number}} [options]@@ -98,7 +203,7 @@ export async function buildKit(query, options = {}) {const matchCount = result.data.matchCount;/**- * Did this result answer enough of the query to stand as a page?+ * Did this result answer enough of the query to stand as a page on breadth?* Single-concept queries have nothing to cover, so they always pass. Coverage* stays in a module-private WeakMap and never enters public search/build JSON.* @param {object} r@@ -110,7 +215,7 @@ export async function buildKit(query, options = {}) {return (coverage?.matched ?? 0) / total >= PAGE_COVERAGE;};- const pages = results+ const matchedPages = results.filter(r =>r.domain === 'template' &&@@ -135,32 +240,42 @@ export async function buildKit(query, options = {}) {!ALWAYS.has(r.name),).slice(0, 6);- const directMatch = pages.length > 0 && pages[0].score >= PAGE_DIRECT;+ const directMatch =+ matchedPages.length > 0 && matchedPages[0].score >= PAGE_DIRECT;/**- * On a loose match, recommend reading the layout rather than scaffolding it.- *- * A page entry's `command` is what a caller runs next, and it was always the- * scaffold command — `template <name>` — even when the kit had just decided- * the top page was NOT a direct match. The renderer already says the right- * thing to a human in that case: RECOMMENDED START prints- * `template <name> --skeleton` and the PAGE TEMPLATES heading reads "use as- * a layout reference". But prose is not what a program reads. A JSON caller- * takes `command` and gets the scaffold, so the two audiences were given- * opposite advice from the same kit.- *- * That matters most for the caller least able to notice. `template <name>`- * emits the whole page, and an agent handed a full template it did not quite- * ask for tends to adapt it anyway — which is how a request for one thing- * comes back as a competent version of another. `--skeleton` gives the- * layout without the invitation.- *- * Copied rather than mutated: these entries come from `search()` and are not- * this function's to modify.+ * On a loose match, a page entry's `command` previews the layout rather+ * than printing the whole template: `--skeleton` gives the shape without+ * presenting the page as the thing to build. The recommendation itself is+ * `start`, which always scaffolds. Copied rather than mutated: these entries+ * come from `search()` and are not this function's to modify.*/- const recommendedPages = directMatch- ? pages- : pages.map(page => ({...page, command: `${page.command} --skeleton`}));+ const pages = directMatch+ ? matchedPages+ : matchedPages.map(page => ({+ ...page,+ command: `${page.command} --skeleton`,+ }));++ // A kit narrowed to components or hooks has no page to start from; every+ // other kit does, so the reader is never left to compose a page from scratch.+ const wantsPages = !type || type === 'template';+ const catalog = wantsPages ? await loadPageTemplates(cwd) : [];+ const ranked = wantsPages ? rankPages(query, catalog) : [];+ const chosen = wantsPages+ ? chooseStart(ranked, matchedPages, directMatch, catalog)+ : null;+ // Name the ranker's next two templates beside the start: the reader judges+ // meaning better than keywords do, and an acceptable template is in these+ // three far more often than it is the start alone.+ /** @type {BuildStart | null} */+ const start = chosen && {+ ...chosen,+ alternatives: pickAlternatives(ranked, chosen.name).flatMap(r => {+ const t = catalog.find(c => c.name === r.name);+ return t ? [asTemplate(t)] : [];+ }),+ };// What to try when the kit comes back thin. Keyword search over a design// system misses in a predictable way — the reader's words and the package's@@ -185,12 +300,13 @@ export async function buildKit(query, options = {}) {type: 'build.kit',data: {query: result.data.query,- // Distinguishes "search found nothing" (renderer shows "No matches")- // from a weak-but-non-empty result set (renderer still shows the kit).+ // Distinguishes "search found nothing" from a weak-but-non-empty result+ // set. Either way the kit still names a template to start from.hasResults: matchCount > 0,matchCount,directMatch,- pages: recommendedPages,+ start,+ pages,blocks,domain,frame: FRAME,diff --git a/packages/cli/api/build/kit/rank.mjs b/packages/cli/api/build/kit/rank.mjsnew file mode 100644index 0000000000..0928b13caa--- /dev/null+++ b/packages/cli/api/build/kit/rank.mjs@@ -0,0 +1,432 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file The page ranker behind `build`'s START: which page template an idea+ * should start from.+ *+ * @input A free-text idea and the project's ready page templates (id, display+ * name, description, `Family - Variant` category), all read from each+ * template's own descriptor.+ * @output Every template, ranked, with the query terms it matched and whether+ * the idea names its family; `pickStart` turns that into a template or null.+ * @position Beside kit.mjs (api/build/kit/). Search ranks components, docs,+ * blocks and pages against short lookups; this ranks only page templates,+ * against the long descriptions builders actually write ("ops dashboard with+ * a KPI row, a sortable table and a trend chart"). Search's scorer is left+ * alone: its callers depend on its scores.+ *+ * Why a separate ranker. Real `build` queries run to fifteen words or more.+ * Search scores a page on its single strongest term plus a garnish, so one+ * incidental word decides: "status" picks the project-status dashboard,+ * "board" picks the kanban board for a game board. Here every matched term+ * counts, weighted by how rare it is among page templates (inverse document+ * frequency), so the page that answers more of the idea — and its rarer words —+ * wins. Structural signals sit on top:+ *+ * - The head noun. The words before the first "with", ":" or "," name what+ * the page is ("audit dashboard: dense table with …"); a family word there+ * outweighs the same word among the parts.+ * - The container. In "draft history in a modal", the modal is the page's+ * frame, and a template is its frame; container words count double, and a+ * container match is evidence enough to start from. Only an overlay frame+ * counts: "inside a data card" names a component the part lives in, and "in+ * an existing dashboard" names the page being changed.+ * - Phrase heads. In "side-by-side product response", "product" describes the+ * response; it is not a product page. A word that only ever modifies the+ * next one counts half, unless the template names the same pair+ * ("executive summary").+ * - The family base. A template whose id is its family's name (`dashboard`,+ * `settings`) is that family's default; it wins when no variant's own words+ * outweigh it.+ *+ * Family words come from the templates' own ids — a word in the ids of two or+ * more templates of one family, plus the family's name when a template carries+ * it — never from a list kept here or from synonyms, so an integration's+ * templates join the vocabulary by being named like their family, and "a+ * landing page" is not a hero because "landing" is a synonym of "hero".+ */++import {stem, STOPWORDS, SYNONYMS} from '../../search/search.mjs';++/**+ * How much a term counts by where the template names it. The id and category+ * are the author's own label for what the page is; the description's last+ * sentence lists the ideas it serves; its body describes the layout.+ */+const FIELD_WEIGHT = {+ id: 3,+ variant: 3,+ family: 2,+ display: 2,+ intent: 2,+ body: 1,+};+/** A synonym hit counts at this share of a direct hit. */+const SYNONYM_SHARE = 0.5;+/** A container word ("in a modal") counts this many times over. */+const CONTAINER = 2;+/** A word that only modifies another ("product" in "product response"). */+const MODIFIER = 0.5;+/** Added when the idea's head names the template's family. */+const HEAD_FAMILY = 12;+/** Added when the family is named anywhere else in the idea. */+const BODY_FAMILY = 2;+/** Added to a family's base template when the idea names that family. */+const FAMILY_BASE = 2;+/**+ * The least a start must score, and the evidence it needs: two matched terms,+ * or the idea naming its family. One rare word alone is how a tic-tac-toe game+ * board became a kanban board.+ */+const START_SCORE = 10;+const START_TERMS = 2;++/**+ * Words search drops that name layout: "side navigation", "side by side".+ */+const LAYOUT_WORDS = new Set(['side']);++/** Filler that search keeps but that says nothing about a page's layout. */+const FILLER = new Set([+ 'per',+ 'each',+ 'every',+ 'using',+ 'via',+ 'into',+ 'onto',+ 'about',+ 'above',+ 'below',+ 'across',+ 'within',+ 'without',+ 'between',+ 'plus',+ 'also',+ 'then',+ 'them',+ 'they',+ 'which',+ 'while',+ 'when',+ 'all',+ 'any',+ 'new',+ 'use',+ 'used',+ 'show',+ 'shows',+ 'showing',+ 'display',+ 'displays',+ 'displaying',+]);++/**+ * Where an idea's head ends: its first clause, before the parts it lists.+ */+const HEAD_END =+ /:|,|;|\(|\s[-\u2013\u2014]\s|\b(?:with|showing|listing|for|that|where|plus|including|containing|featuring|which|to|from|of)\b/i;++/**+ * Frames a page can live in, above whatever is underneath. A container phrase+ * counts only when it names one of these.+ */+const OVERLAY_FRAMES = new Set([+ 'modal',+ 'dialog',+ 'drawer',+ 'sheet',+ 'popup',+ 'overlay',+]);++/** A container phrase: "in a modal", "inside the side panel". */+const CONTAINER_PHRASE =+ /\b(?:in|inside|within)\s+(?:a|an|the)\s+([a-z-]+)(?:\s+([a-z-]+))?/gi;++/**+ * Where a phrase ends, for finding the word that heads it: punctuation and+ * the words that join phrases.+ */+const PHRASE_END =+ /[^a-z0-9\s-]+|\s(?:and|or|with|for|of|to|in|on|at|by|from|the|a|an|plus)\s/;++/** @param {string} t */+const isContentWord = t =>+ t.length >= 2 &&+ (LAYOUT_WORDS.has(t) || (!STOPWORDS.has(t) && !FILLER.has(t)));++/**+ * Content terms of a text: lowercase alphanumeric words, stopwords and filler+ * removed, stemmed.+ * @param {string} text+ * @returns {string[]}+ */+function terms(text) {+ return (+ String(text)+ .toLowerCase()+ .match(/[a-z0-9]+/g) ?? []+ )+ .filter(isContentWord)+ .map(stem);+}++/**+ * The terms of an idea that only ever modify another word, each with the words+ * it modifies: in each phrase the last content word is its head, and the ones+ * before it describe the next.+ * @param {string} query+ * @returns {Map<string, Set<string>>}+ */+function modifiersOf(query) {+ const heads = new Set();+ /** @type {Map<string, Set<string>>} */+ const modifiers = new Map();+ for (const phrase of String(query).toLowerCase().split(PHRASE_END)) {+ const words = terms(phrase);+ words.forEach((w, i) => {+ if (i === words.length - 1) heads.add(w);+ else modifiers.set(w, (modifiers.get(w) ?? new Set()).add(words[i + 1]));+ });+ }+ for (const h of heads) modifiers.delete(h);+ return modifiers;+}++/**+ * Adjacent term pairs a text names, "a b", for telling a template that names+ * a whole compound ("executive summary") from one that names only its parts.+ * @param {string[]} texts+ * @returns {Set<string>}+ */+function pairsOf(texts) {+ const pairs = new Set();+ for (const text of texts) {+ for (const phrase of String(text).toLowerCase().split(PHRASE_END)) {+ const words = terms(phrase);+ for (let i = 1; i < words.length; i++)+ pairs.add(`${words[i - 1]} ${words[i]}`);+ }+ }+ return pairs;+}++/**+ * The terms of an idea that name its frame: "modal" in "in a modal". A card, a+ * table or an existing page after "in a" is where a part goes, not a frame.+ * @param {string} query+ * @returns {Set<string>}+ */+function containersOf(query) {+ const found = new Set();+ for (const m of String(query).matchAll(CONTAINER_PHRASE)) {+ for (const t of terms(`${m[1]} ${m[2] ?? ''}`)) {+ if (OVERLAY_FRAMES.has(t)) found.add(t);+ }+ }+ return found;+}++/** @param {string} text */+const normalized = text =>+ (+ String(text)+ .toLowerCase()+ .match(/[a-z0-9]+/g) ?? []+ ).join(' ');++/** Stemmed synonym lookup built from search's vocabulary, both directions. */+const SYNONYMS_OF = (() => {+ /** @type {Map<string, Set<string>>} */+ const index = new Map();+ /** @param {string} a @param {string} b */+ const add = (a, b) => {+ const set = index.get(a) ?? new Set();+ set.add(b);+ index.set(a, set);+ };+ for (const [key, values] of Object.entries(SYNONYMS)) {+ const k = stem(key);+ for (const value of values) {+ const v = stem(value);+ add(k, v);+ add(v, k);+ for (const other of values) if (other !== value) add(v, stem(other));+ }+ }+ return index;+})();++/**+ * @typedef {import('../_adapter.mjs').PageTemplate} PageTemplate+ * @typedef {{name: string, score: number, hits: number, familyNamed: boolean, containerMatched: boolean}} RankedPage+ */++/**+ * Rank page templates against an idea, best first. Ties go to the template+ * with the shorter id (the family's broader page), then by name.+ *+ * @param {string} query+ * @param {PageTemplate[]} pages+ * @returns {RankedPage[]}+ */+export function rankPages(query, pages) {+ const docs = pages.map(page => {+ const [family = '', ...variantParts] = page.category.split(' - ');+ const sentences = page.description.trim().split(/(?<=[.!?])\s+/);+ const intent = sentences.length > 1 ? sentences[sentences.length - 1] : '';+ const body =+ sentences.length > 1+ ? sentences.slice(0, -1).join(' ')+ : page.description;+ /** @type {Record<keyof typeof FIELD_WEIGHT, string>} */+ const fields = {+ id: page.name.replace(/-/g, ' '),+ variant: variantParts.join(' - '),+ family,+ display: page.displayName,+ intent,+ body,+ };+ /** @type {Map<string, number>} */+ const bag = new Map();+ for (const [field, text] of Object.entries(fields)) {+ const weight =+ FIELD_WEIGHT[/** @type {keyof typeof FIELD_WEIGHT} */ (field)];+ for (const t of terms(text))+ bag.set(t, Math.max(bag.get(t) ?? 0, weight));+ }+ return {+ page,+ family: family.trim(),+ bag,+ pairs: pairsOf(Object.values(fields)),+ };+ });++ // Inverse document frequency over page templates: a word every dashboard+ // carries says less than one only the funnel carries.+ /** @type {Map<string, number>} */+ const df = new Map();+ for (const {bag} of docs)+ for (const t of bag.keys()) df.set(t, (df.get(t) ?? 0) + 1);+ const n = docs.length;+ /** @param {string} t */+ const idf = t => {+ const d = df.get(t);+ return d ? Math.log(1 + (n - d + 0.5) / (d + 0.5)) : 0;+ };++ // Family words, from the templates' own ids.+ /** @type {Map<string, Map<string, number>>} */+ const idWords = new Map();+ for (const {page, family} of docs) {+ const counts = idWords.get(family) ?? new Map();+ for (const w of new Set(page.name.split('-'))) {+ if (w.length >= 3) counts.set(stem(w), (counts.get(stem(w)) ?? 0) + 1);+ }+ idWords.set(family, counts);+ }+ /** @type {Map<string, string>} */+ const familyOfWord = new Map();+ for (const [family, counts] of idWords) {+ const heads = [...counts].filter(([, c]) => c >= 2).map(([w]) => w);+ const name = normalized(family).split(' ').pop() ?? '';+ if (name.length >= 3 && counts.has(stem(name))) heads.push(stem(name));+ for (const head of heads) {+ if (!familyOfWord.has(head)) familyOfWord.set(head, family);+ }+ }+ /** @param {string[]} ts */+ const familiesIn = ts =>+ new Set(ts.filter(t => familyOfWord.has(t)).map(t => familyOfWord.get(t)));++ const queryTerms = [...new Set(terms(query))];+ const headFamilies = familiesIn(+ terms(String(query).split(HEAD_END)[0] ?? ''),+ );+ const namedFamilies = familiesIn(queryTerms);+ const modifiers = modifiersOf(query);+ const containers = containersOf(query);++ return docs+ .map(({page, family, bag, pairs}) => {+ let score = 0;+ let hits = 0;+ let containerMatched = false;+ for (const t of queryTerms) {+ // A modifier is discounted where the template names it outright; a+ // synonym hit is already discounted by SYNONYM_SHARE.+ const modified = modifiers.get(t);+ const discounted =+ modified !== undefined &&+ ![...modified].some(n => pairs.has(`${t} ${n}`));+ const direct = idf(t) * (bag.get(t) ?? 0) * (discounted ? MODIFIER : 1);+ let viaSynonym = 0;+ for (const s of SYNONYMS_OF.get(t) ?? []) {+ if (queryTerms.includes(s)) continue;+ viaSynonym = Math.max(+ viaSynonym,+ SYNONYM_SHARE * idf(s) * (bag.get(s) ?? 0),+ );+ }+ const value =+ Math.max(direct, viaSynonym) * (containers.has(t) ? CONTAINER : 1);+ if (value > 0) {+ score += value;+ hits++;+ if (containers.has(t)) containerMatched = true;+ }+ }+ const familyNamed = namedFamilies.has(family);+ if (headFamilies.has(family)) score += HEAD_FAMILY;+ else if (familyNamed) score += BODY_FAMILY;+ if (familyNamed && normalized(page.name) === normalized(family)) {+ score += FAMILY_BASE;+ }+ return {name: page.name, score, hits, familyNamed, containerMatched};+ })+ .sort(+ (a, b) =>+ b.score - a.score ||+ a.name.split('-').length - b.name.split('-').length ||+ a.name.localeCompare(b.name),+ );+}++/**+ * The next closest templates after the start, best first: the ones a reader+ * should check the idea against when the start's shape is wrong. Each matched+ * at least one term and scored at least half of what a start needs.+ *+ * @param {RankedPage[]} ranked+ * @param {string} startName+ * @param {number} [count]+ * @returns {RankedPage[]}+ */+export function pickAlternatives(ranked, startName, count = 2) {+ return ranked+ .filter(+ r => r.name !== startName && r.hits > 0 && r.score >= START_SCORE / 2,+ )+ .slice(0, count);+}++/**+ * The template to start from, or null when the best one has too little+ * evidence to lead and the page should start from the app shell. Evidence is+ * two matched terms, the idea naming the template's family, or its container.+ *+ * @param {RankedPage[]} ranked+ * @returns {RankedPage | null}+ */+export function pickStart(ranked) {+ const top = ranked[0];+ if (!top || top.score < START_SCORE) return null;+ return top.hits >= START_TERMS || top.familyNamed || top.containerMatched+ ? top+ : null;+}diff --git a/packages/cli/api/build/kit/rank.test.mjs b/packages/cli/api/build/kit/rank.test.mjsnew file mode 100644index 0000000000..6833bd234a--- /dev/null+++ b/packages/cli/api/build/kit/rank.test.mjs@@ -0,0 +1,196 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tests for build's page ranker: long ideas, head nouns, family bases,+ * rare-word weighting, and family words taken from the templates themselves.+ */++import {describe, it, expect} from 'vitest';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {pickStart, rankPages} from './rank.mjs';+import {loadPageTemplates} from '../_adapter.mjs';++// api/build/kit/ -> up 5 = repo root (has packages/core and the templates).+const REPO = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../../..',+);++/** @param {string} name @param {string} category @param {string} description */+const page = (name, category, description) => ({+ name,+ displayName: name,+ category,+ description,+});++describe('rankPages on the shipped page templates', () => {+ /** @param {string} query */+ const start = async query =>+ pickStart(rankPages(query, await loadPageTemplates(REPO)))?.name ?? null;++ it('starts a long dashboard idea from the family base', async () => {+ expect(+ await start(+ 'ops dashboard with a KPI row, a sortable table and a trend chart',+ ),+ ).toBe('dashboard');+ });++ it("lets a variant's own words beat the base", async () => {+ expect(+ await start(+ 'conversion funnel dashboard with drop-off and retention by cohort',+ ),+ ).toBe('dashboard-cohort-funnel');+ expect(await start('program milestone tracker with delivery status')).toBe(+ 'dashboard-progress',+ );+ });++ it('lets the head noun decide between families', async () => {+ // Both ideas mention a table and summary numbers; the head says which+ // page it is.+ expect(+ await start(+ 'audit dashboard: dense filterable data table with a KPI stat row',+ ),+ ).toMatch(/^dashboard/);+ expect(+ await start(+ 'a data table of campaigns with spend and revenue, plus summary metrics above it',+ ),+ ).toMatch(/^table-/);+ });++ it('does not start from one rare word', async () => {+ // "board" is the kanban board's own word; a game board is not a kanban.+ expect(+ await start('accessible responsive tic-tac-toe game board'),+ ).toBeNull();+ });+});++describe('rankPages on any catalog', () => {+ it('ranks only the templates it is given', () => {+ const ranked = rankPages('dashboard', [+ page(+ 'dashboard',+ 'Dashboard - Analytics',+ 'Tiles, charts, tables. Dashboard, metrics.',+ ),+ ]);+ expect(ranked.map(r => r.name)).toEqual(['dashboard']);+ });++ it('takes family words from template ids, so a new family needs no list', () => {+ // An integration's family: its word is in two of its ids, so an idea+ // naming it picks the family, and its base template leads it.+ const catalog = [+ page(+ 'dashboard',+ 'Dashboard - Analytics',+ 'Tiles, charts, tables. Dashboard, metrics.',+ ),+ page('widget', 'Widget - Basic', 'One compact card. Widget, tile.'),+ page(+ 'widget-grid',+ 'Widget - Grid',+ 'Many compact cards in a grid. Widget wall.',+ ),+ ];+ const ranked = rankPages('weather widget with charts', catalog);+ expect(ranked[0].name).toBe('widget');+ expect(ranked[0].familyNamed).toBe(true);+ expect(pickStart(ranked)?.name).toBe('widget');+ });++ it('weighs a word by how rare it is among page templates', () => {+ const catalog = [+ page('alpha', 'Dashboard - Alpha', 'Status tiles. Status overview.'),+ page('beta', 'Dashboard - Beta', 'Status rows. Status list.'),+ page(+ 'gamma',+ 'Dashboard - Gamma',+ 'Funnel of stages. Funnel conversion.',+ ),+ ];+ // "status" is on two templates, "funnel" on one: the rare word wins.+ const ranked = rankPages('status funnel', catalog);+ expect(ranked[0].name).toBe('gamma');+ });+});++describe('rankPages structure signals', () => {+ const catalog = [+ page(+ 'dialog-panel',+ 'Settings - Dialog',+ 'Preferences inside a modal container. Settings, or modal dialog.',+ ),+ page(+ 'tree-table',+ 'Table - Tree',+ 'Nested rows under parents. Tree, nested rows, file browser.',+ ),+ page(+ 'item-detail',+ 'Content - Item Detail',+ 'One item with its media. Product, listing, or item detail.',+ ),+ page(+ 'docs-catalog',+ 'Content - Documentation Catalog',+ 'A grid of category cards. Documentation, docs, or API index.',+ ),+ ];++ it('doubles a container word and lets it carry the start', () => {+ const ranked = rankPages(+ 'draft history in a modal with delete row actions',+ catalog,+ );+ expect(ranked[0].name).toBe('dialog-panel');+ expect(ranked[0].containerMatched).toBe(true);+ });++ it('counts only an overlay frame as a container', () => {+ // A card or an existing page after "in a" is where a part goes.+ for (const idea of [+ 'view toggle inside a data card',+ 'status filter in an existing dashboard',+ ]) {+ expect(rankPages(idea, catalog).every(r => !r.containerMatched)).toBe(+ true,+ );+ }+ });++ it('halves a word that only modifies the next one', () => {+ // "item" modifies "response" here; "catalog" heads its own phrase.+ const ranked = rankPages(+ 'endpoint catalog with side-by-side item response',+ catalog,+ );+ expect(ranked[0].name).toBe('docs-catalog');+ });++ it('does not treat a synonym as a family name', () => {+ // "landing" is a synonym of "hero" in search, not a family word here.+ const heroes = [+ page(+ 'hero-centered',+ 'Gallery - Hero',+ 'A centered hero. Hero, banner, or landing.',+ ),+ page(+ 'hero-split',+ 'Gallery - Hero Split',+ 'A split hero. Hero or splash.',+ ),+ ];+ const ranked = rankPages('internal landing page', heroes);+ expect(ranked.every(r => !r.familyNamed)).toBe(true);+ });+});diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex e8f845bcc1..94d74ec4d7 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -17,21 +17,31 @@* component fuzzy resolver in lib/string-utils.mjs:** 100 exact name match+ * 95 name is the term's plural or stem form ("buttons" -> Button)* 90 exact keyword match- * 80 name Levenshtein distance 1- * 70 keyword substring / distance 1- * 60 name substring (>=4 chars, >=50% coverage)+ * 88 keyword is the term's plural or stem form+ * 80 name Levenshtein distance 1 (one-word lookups, words of 5+ letters)+ * 70 keyword word prefix / distance 1 (distance: one-word lookups, 5+ letters)+ * 60 name word prefix (>=4 chars, >=50% coverage)* 60 exact weak-keyword match* 50 description / prose mentions the term* 45 usage guidance mentions the term- * 40 name Levenshtein distance 2- * 40 weak-keyword substring- * 30 keyword Levenshtein distance 2- * 20 name Levenshtein distance 3+ * 40 name Levenshtein distance 2 (one-word lookups, 8+ letters)+ * 40 weak-keyword word prefix+ * 30 keyword Levenshtein distance 2 (one-word lookups, 8+ letters)+ * 20 name Levenshtein distance 3 (one-word lookups, 11+ letters)** Name + keyword signals always outweigh description/prose, so an exact match* sorts above an incidental mention.*+ * A term matches inside a name or keyword only at the start of one of its+ * words: "dash" finds "dashboard" and "input" finds "TextInput", but "file"+ * does not find "profile". Edit distance is typo tolerance, so it applies only+ * to a one-word lookup, where a typo is the likely explanation, and only to+ * words long enough that one edit rarely makes another real word. In a+ * sentence, a near miss is usually a different word: "site" is not "side",+ * "cable" is not "table".+ ** Description and guidance are separate tiers on purpose. A component's own* one-line description saying "notification" is a claim about what it IS; the* same word inside another component's best-practice advice is a passing@@ -115,9 +125,10 @@ import {setResultCoverage} from './coverage.mjs';* Synonym / intent map: product-language terms an agent is likely to type,* expanded to the catalog's vocabulary so oblique queries still rank. Keys and* values are matched bidirectionally (typing any value also pulls in the key- * and its siblings). Lowercase, single words or short phrases.+ * and its siblings). Lowercase, single words or short phrases. Exported for+ * `build`, whose page ranker expands a query with the same vocabulary.*/-const SYNONYMS = {+export const SYNONYMS = {dashboard: ['overview','analytics',@@ -189,14 +200,90 @@ export function stem(w) {return s;}+/**+ * The forms of a word that count as the same word: itself, its stem, and its+ * singular when it ends in a plural suffix — so "tables" is "table",+ * "statuses" is "status", and "filtering" is "filter".+ * @param {string} w - Lowercase word.+ * @returns {Set<string>}+ */+function wordForms(w) {+ const forms = new Set([w, stem(w)]);+ if (w.length > 3 && w.endsWith('s')) forms.add(w.slice(0, -1));+ if (w.length > 4 && w.endsWith('es')) forms.add(w.slice(0, -2));+ if (w.length > 4 && w.endsWith('ies')) forms.add(w.slice(0, -3) + 'y');+ return forms;+}++/**+ * Whether two lowercase words are the same word, up to plural and stem form.+ * @param {string} a+ * @param {string} b+ * @returns {boolean}+ */+export function sameWord(a, b) {+ if (a === b) return true;+ const forms = wordForms(a);+ for (const f of wordForms(b)) if (forms.has(f)) return true;+ return false;+}++/**+ * The lowercase words of a name or keyword: split at non-alphanumerics and at+ * camelCase boundaries, so "TextInput" is ["text", "input"] and+ * "Dashboard - Analytics" is ["dashboard", "analytics"].+ * @param {string} text+ * @returns {string[]}+ */+function wordsOf(text) {+ return String(text)+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')+ .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter(Boolean);+}++/**+ * Whether a term is found inside a name or keyword: it is one of its words, or+ * the start of one (a truncation), and covers at least half of the whole+ * string. Four letters minimum, so a short term never matches by accident.+ * @param {string} term - Lowercase term.+ * @param {string} text - The name or keyword as authored.+ * @returns {boolean}+ */+function startsAWordOf(term, text) {+ if (term.length < 4) return false;+ if (term.length / String(text).length < 0.5) return false;+ return wordsOf(text).some(w => w.startsWith(term) || sameWord(term, w));+}++/**+ * The fewest letters both words need before an edit distance counts as a+ * typo, by distance. Below them, one edit usually makes a different word.+ */+const TYPO_MIN_LENGTH = {1: 5, 2: 8, 3: 11};++/**+ * @param {string} a+ * @param {string} b+ * @param {number} dist+ */+const isTypo = (a, b, dist) =>+ dist > 0 &&+ dist <= 3 &&+ Math.min(a.length, b.length) >=+ TYPO_MIN_LENGTH[/** @type {1 | 2 | 3} */ (dist)];+/** Valid domain filters for `--type`. */export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template'];/*** Filler words stripped from multi-word queries so natural-language phrasing* ("a page where you can see business stats") ranks on its content words.+ * Exported for `build`, whose page ranker strips the same words.*/-const STOPWORDS = new Set([+export const STOPWORDS = new Set(['a','an','the',@@ -308,14 +395,15 @@ const MIN_TOKEN_SCORE = 50;* (synonym hits are discounted so a direct hit always wins).* @param {string} tok* @param {Candidate} candidate+ * @param {{fuzzy?: boolean}} [opts]* @returns {{score: number, reason: string} | null}*/-function bestForToken(tok, candidate) {- let best = scoreCandidate(tok, candidate);+function bestForToken(tok, candidate, opts = {}) {+ let best = scoreCandidate(tok, candidate, opts);const syns = SYNONYM_INDEX.get(tok);if (syns) {for (const s of syns) {- const h = scoreCandidate(s, candidate);+ const h = scoreCandidate(s, candidate, opts);if (h) {const score = Math.round(h.score * 0.85);if (!best || score > best.score)@@ -345,14 +433,17 @@ export function scoreQuery(term, tokens, candidate) {matched: total,total,});- const full = scoreCandidate(term, candidate);+ // Typo tolerance is for one-word lookups. In a multi-word query a near miss+ // is usually a different word, not a typo.+ const fuzzy = tokens.length <= 1;+ const full = scoreCandidate(term, candidate, {fuzzy});// 0–1 content tokens: keep whole-phrase fuzzy matching (typo tolerance for// single words), but if stopwords left exactly one DIFFERENT token (e.g.// "pricing page" → "pricing"), score that token too and take the stronger.if (tokens.length <= 1) {const single =- tokens.length === 1 ? bestForToken(tokens[0], candidate) : null;+ tokens.length === 1 ? bestForToken(tokens[0], candidate, {fuzzy}) : null;if (full && (!single || full.score >= single.score)) return asFull(full);return single ? asFull(single) : null;}@@ -379,7 +470,7 @@ export function scoreQuery(term, tokens, candidate) {/** @type {string[]} */const hitTerms = [];for (const tok of tokens) {- const h = bestForToken(tok, candidate);+ const h = bestForToken(tok, candidate, {fuzzy});if (h && h.score >= MIN_TOKEN_SCORE) {if (h.score > strongest) strongest = h.score;matched++;@@ -432,6 +523,7 @@ export function scoreQuery(term, tokens, candidate) {* @param {string} [candidate.description]* @param {string[]} [candidate.prose] - Extra free-text blobs (doc section text, best practices).* @param {string[]} [candidate.guidance] - Usage guidance (features, best practices) — scored a tier below description.+ * @param {{fuzzy?: boolean}} [opts] - `fuzzy`: allow edit-distance (typo) matches. Default true; multi-word queries pass false.* @returns {{score: number, reason: string} | null}*/export function scoreCandidate(@@ -444,6 +536,7 @@ export function scoreCandidate(prose = [],guidance = [],},+ {fuzzy = true} = {},) {let best = 0;let reason = '';@@ -464,20 +557,20 @@ export function scoreCandidate(if (nameLower === term) {consider(100, 'exact name');} else {- // Substring (both directions), min 4 chars, >=50% coverage.- const shorter = term.length < nameLower.length ? term : nameLower;- const longer = term.length < nameLower.length ? nameLower : term;- if (- shorter.length >= 4 &&- longer.includes(shorter) &&- shorter.length / longer.length >= 0.5- ) {- consider(60, `name contains "${shorter}"`);+ if (sameWord(term, nameLower)) consider(95, `name "${name}"`);+ // The term is a word of the name, or starts one: "input" in TextInput.+ else if (startsAWordOf(term, name)) {+ consider(60, `name contains "${term}"`);+ }+ if (fuzzy) {+ const dist = levenshteinDistance(term, nameLower);+ if (isTypo(term, nameLower, dist)) {+ consider(+ dist === 1 ? 80 : dist === 2 ? 40 : 20,+ `similar name (distance ${dist})`,+ );+ }}- const dist = levenshteinDistance(term, nameLower);- if (dist === 1) consider(80, `similar name (distance ${dist})`);- else if (dist === 2) consider(40, `similar name (distance ${dist})`);- else if (dist === 3) consider(20, `similar name (distance ${dist})`);}// ── Keyword signals ─────────────────────────────────────────────@@ -487,14 +580,17 @@ export function scoreCandidate(consider(90, `keyword "${kw}"`);continue;}- const s = term.length < kwLower.length ? term : kwLower;- const l = term.length < kwLower.length ? kwLower : term;- if (s.length >= 4 && l.includes(s) && s.length / l.length >= 0.5) {- consider(70, `keyword "${kw}"`);+ if (sameWord(term, kwLower)) {+ consider(88, `keyword "${kw}"`);+ continue;+ }+ if (startsAWordOf(term, kw)) consider(70, `keyword "${kw}"`);+ if (fuzzy) {+ const dist = levenshteinDistance(term, kwLower);+ if (isTypo(term, kwLower, dist) && dist <= 2) {+ consider(dist === 1 ? 70 : 30, `keyword "${kw}" (distance ${dist})`);+ }}- const dist = levenshteinDistance(term, kwLower);- if (dist === 1) consider(70, `keyword "${kw}" (distance ${dist})`);- else if (dist === 2) consider(30, `keyword "${kw}" (distance ${dist})`);}// ── Weak keyword signals (derived, not authored) ─────────────────@@ -504,15 +600,11 @@ export function scoreCandidate(// No Levenshtein tier — fuzzy matching a derived signal is pure noise.for (const kw of weakKeywords) {const kwLower = String(kw).toLowerCase();- if (kwLower === term) {+ if (kwLower === term || sameWord(term, kwLower)) {consider(60, `renders ${kw}`);continue;}- const s = term.length < kwLower.length ? term : kwLower;- const l = term.length < kwLower.length ? kwLower : term;- if (s.length >= 4 && l.includes(s) && s.length / l.length >= 0.5) {- consider(40, `renders ${kw}`);- }+ if (startsAWordOf(term, kw)) consider(40, `renders ${kw}`);}// ── Prose / description / guidance signals (stem-tolerant whole word) ──diff --git a/packages/cli/api/template/template-integration.test.mjs b/packages/cli/api/template/template-integration.test.mjsindex 3aee706c93..7588e39802 100644--- a/packages/cli/api/template/template-integration.test.mjs+++ b/packages/cli/api/template/template-integration.test.mjs@@ -1271,3 +1271,53 @@ describe('integration template discovery', () => {expect(fs.existsSync(path.join(tmpDir, 'dest', 'hero.tsx'))).toBe(true);});});++describe('build names a start its command selects', () => {+ it('scaffolds an integration replacement through the Core id it replaces', async () => {+ const pkgDir = installWidgets(tmpDir);+ writeTemplate(pkgDir, 'acme-app-shell', {+ kind: 'page',+ body: "export default {type: 'page', name: 'Acme App Shell', category: 'Shell - Acme Sidebar', description: 'Acme application frame with a left sidebar navigation. Shell, frame, or sidebar navigation.'};\n",+ });+ declareReplaces(pkgDir, {'acme-app-shell': 'shell-side-nav'});++ const kit = await build('acme application frame with sidebar navigation', {+ cwd: tmpDir,+ });+ expect(kit.type).toBe('build.kit');+ if (kit.type !== 'build.kit') throw new Error('expected build.kit');+ expect(kit.data.start).toMatchObject({+ name: 'acme-app-shell',+ command: 'astryx template shell-side-nav --type page <path>',+ });+ const selected = await template('shell-side-nav', {+ type: 'page',+ show: true,+ cwd: tmpDir,+ });+ expect(selected.data.template).toBe('acme-app-shell');+ });++ it('keeps the start command unambiguous when a block shares the id', async () => {+ const pkgDir = installWidgets(tmpDir);+ writeTemplate(pkgDir, 'contact-form', {kind: 'block'});++ const kit = await build('contact form', {cwd: tmpDir});+ expect(kit.type).toBe('build.kit');+ if (kit.type !== 'build.kit') throw new Error('expected build.kit');+ expect(kit.data.start).toMatchObject({+ name: 'contact-form',+ command: 'astryx template contact-form --type page <path>',+ });+ const selected = await template('contact-form', {+ type: 'page',+ show: true,+ cwd: tmpDir,+ });+ expect(selected.data.template).toBe('contact-form');+ // The bare id is ambiguous here, which is why the command carries --type.+ await expect(+ template('contact-form', {show: true, cwd: tmpDir}),+ ).rejects.toMatchObject({code: 'ERR_AMBIGUOUS_TEMPLATE'});+ });+});diff --git a/packages/cli/assets/docs/layout.doc.dense.mjs b/packages/cli/assets/docs/layout.doc.dense.mjsindex 7e5a25fe9d..9a634221de 100644--- a/packages/cli/assets/docs/layout.doc.dense.mjs+++ b/packages/cli/assets/docs/layout.doc.dense.mjs@@ -25,7 +25,7 @@ export const docsDense = {},{type: 'prose',- text: 'decides layout, not component APIs. npx astryx build "<idea>" = closest template for your app type. npx astryx component <Name> = props.',+ text: 'decides layout, not component APIs. npx astryx build "<idea>" = the template to start from for your app type. npx astryx component <Name> = props.',},],},@@ -71,7 +71,7 @@ export const docsDense = {null,{type: 'prose',- text: 'verify: you can state the reason in one sentence, and it still holds if the nav doubles. npx astryx build "<idea>" names the closest template, --skeleton shows the pairing wired up.',+ text: 'verify: you can state the reason in one sentence, and it still holds if the nav doubles. npx astryx build "<idea>" names the template to start from; scaffold it and the pairing is wired up.',},// Best practicesnull,diff --git a/packages/cli/assets/docs/layout.doc.mjs b/packages/cli/assets/docs/layout.doc.mjsindex 81dbe72198..25b65ddd13 100644--- a/packages/cli/assets/docs/layout.doc.mjs+++ b/packages/cli/assets/docs/layout.doc.mjs@@ -106,7 +106,7 @@ export const docs = {},{type: 'prose',- text: 'Verify: you can state the reason in one sentence, and the choice still holds if the nav doubles in size. `npx astryx build "<idea>"` names the closest template, and its `--skeleton` shows the pairing already wired up.',+ text: 'Verify: you can state the reason in one sentence, and the choice still holds if the nav doubles in size. `npx astryx build "<idea>"` names the template to start from; scaffold it and the pairing is already wired up.',},{type: 'heading', level: 3, text: 'Best practices'},diff --git a/packages/cli/assets/docs/working-with-ai.doc.mjs b/packages/cli/assets/docs/working-with-ai.doc.mjsindex f62c3cc226..581a0e202c 100644--- a/packages/cli/assets/docs/working-with-ai.doc.mjs+++ b/packages/cli/assets/docs/working-with-ai.doc.mjs@@ -66,14 +66,14 @@ npx @astryxdesign/cli init --features agents --agent muse # AGENTS.md (Musetype: 'list',style: 'ordered',items: [- '`astryx template --list`: find a related page pattern to use as reference',- '`astryx template <name> --skeleton`: study the layout structure',+ '`astryx build "<idea>"`: get the page template to start from (always one: the closest match, or the app shell), two other templates, and the blocks and components for the parts it lacks',+ '`astryx template <name> <path>`: scaffold that template into the project, keep its frame and spacing, and replace its content','`astryx component <Name>`: read props and examples for every component used',],},{type: 'prose',- text: "It also includes rules that prevent common mistakes (no raw divs, no style={{}}, use tokens not magic values), a CLI quick reference, and package-labeled integration guidance when a configured manifest declares `agentDocs`. After setup, you shouldn't need to manually correct your AI on these conventions; the agent docs handle it at the system level.",+ text: "It also includes rules that prevent common mistakes (start every page from a template, no raw divs, no style={{}}, use tokens not magic values), a CLI quick reference, and package-labeled integration guidance when a configured manifest declares `agentDocs`. After setup, you shouldn't need to manually correct your AI on these conventions; the agent docs handle it at the system level.",},],},diff --git a/packages/cli/clients/cli/commands/build.doc.mjs b/packages/cli/clients/cli/commands/build.doc.mjsindex f1fc56ad0c..33dfac0951 100644--- a/packages/cli/clients/cli/commands/build.doc.mjs+++ b/packages/cli/clients/cli/commands/build.doc.mjs@@ -14,11 +14,12 @@ export const doc = {displayName: 'astryx build',namespace: 'cli/commands',summary:- 'Build a page: composition kit for an idea, or the workflow playbook (no args)',+ 'Build a page: the template to start from, or the workflow playbook (no query)',description:- 'The assemble-a-page entry point. With no query it returns the how-to-build-a-page ' +- 'playbook; with a query it groups the unified search hits into a composition kit: ' +- 'the closest templates, drop-in blocks, and idea-specific components and hooks.',+ 'The build-a-page entry point. With no query it returns the how-to-build-a-page ' ++ 'playbook; with a query it names the page template to start from (always one: the ' ++ 'closest page template, or the app shell when none matches), the next two templates, and the ' ++ 'drop-in blocks and idea-specific components and hooks around it.',fn: 'build',args: [{name: 'query', param: 'query', required: false}],options: [@@ -35,12 +36,16 @@ export const doc = {},{flag: '--verbose',- description: 'Verbose output (include import paths and match reason)',+ description:+ 'Verbose output (every block and component, full descriptions, import paths and match reason)',},],examples: [{label: 'Get the playbook', cli: 'astryx build'},- {label: 'Compose a page', cli: 'astryx build "analytics dashboard" --json'},+ {+ label: 'Find the template to start from',+ cli: 'astryx build "analytics dashboard" --json',+ },],exitCodes: [{code: 0, when: 'success (including zero matches)'},diff --git a/packages/cli/clients/cli/commands/build.mjs b/packages/cli/clients/cli/commands/build.mjsindex 218089f1de..99252eca90 100644--- a/packages/cli/clients/cli/commands/build.mjs+++ b/packages/cli/clients/cli/commands/build.mjs@@ -4,8 +4,9 @@* @file build command — thin wrapper with a stable result summary.** astryx build → the PLAYBOOK (how to build a page)- * astryx build "<what>" → a COMPOSITION KIT (closest page template,- * blocks, components) with a recommended START.+ * astryx build "<what>" → the TEMPLATE to start from (always one: the+ * closest page, or the app shell), other+ * templates, then blocks and components.** All grouping/scoring lives in api/build; this file only parses flags and* renders. Command strings are prefixed for the caller's package manager here@@ -27,6 +28,7 @@ import {records,} from '../formatters/index.mjs';import {cliError} from '../lib/cli-error.mjs';+import {firstSentence} from '../../../foundation/text/string-utils.mjs';import {defineCommand} from '../lib/define-command.mjs';import {build as buildApi} from '../../../api/build/build.mjs';import {doc as buildCommand} from './build.doc.mjs';@@ -126,6 +128,7 @@ export function registerBuild(program) {hasResults,matchCount,directMatch,+ start,pages,blocks,domain,@@ -134,8 +137,8 @@ export function registerBuild(program) {hint,} = result.data;// The kit spans domains, so its kind comes from the pieces themselves.- // `frame` and `foundation` are always-on and deliberately excluded: they- // are not what the query matched.+ // `start` (which may be the fallback shell), `frame` and `foundation`+ // are deliberately excluded: they are not what the query matched.const answered = resultSetOf([...pages, ...blocks, ...domain], {count: matchCount,empty: !hasResults,@@ -148,7 +151,7 @@ export function registerBuild(program) {return answered;}- if (!hasResults) {+ if (!hasResults && !start) {emit(text(`No matches for "${q}".`),text(`Try a broader term, or browse: ${run} component --list`),@@ -156,94 +159,126 @@ export function registerBuild(program) {return answered;}- // Same JSON->text projection as search, but leaner: the section header- // already says the kind, so drop `domain`/`import` by default (they're in- // --json and under --verbose). Keeps each item to name/displayName/desc/cmd.- const fields = options.verbose- ? [- 'name',- 'domain',- 'displayName',- 'score',- 'reason',- 'import',- 'description',- 'command',- ]- : ['name', 'displayName', 'description', 'command'];+ // Four sections, one job each: the TEMPLATE to scaffold, OTHER+ // TEMPLATES if its layout is wrong, BLOCKS for parts it lacks, and+ // COMPONENTS for the rest. Descriptions stop at their first sentence and+ // blocks and components share one command line in their heading; the+ // JSON and --verbose carry everything.+ const verbose = Boolean(options.verbose);/** @type {import('../formatters/index.mjs').RecordOptions} */- const recordOpts = {fields, format: {command: formatCliCommand}};-- // `template <name> <path>` scaffolds into your project; <path> is the file- // (or folder) to write it to — a placeholder, since we can't know your- // layout. `--skeleton` and `component <Name>` just print, so no path.- const pageCommand = pages.length- ? formatCliCommand(pages[0].command)- : null;- const startCmd = directMatch- ? `${pageCommand} <path>`- : pages.length- ? pageCommand- : `${run} component AppShell`;- const startNote = directMatch- ? `This \`${pages[0].name}\` page template appears to be the closest to what you want, so we recommend scaffolding it into your project — replace \`<path>\` with the file (or folder) to write it to — then adapting. Otherwise, browse PAGE TEMPLATES first, then BLOCKS and DOMAIN COMPONENTS below.`- : pages.length- ? `No exact match, but \`${pages[0].name}\` is the closest page template — run the above to print its layout as a reference, then compose. Otherwise, browse PAGE TEMPLATES first, then BLOCKS and DOMAIN COMPONENTS below.`- : 'No page template fits — frame with AppShell, then compose from BLOCKS and DOMAIN COMPONENTS below.';-- // A short legend up top: what this output is, how to use it, and the exact- // order of the sections below (only the ones actually present) so it reads- // clearly and parses predictably.- const sectionsOrder = ['RECOMMENDED START'];- if (pages.length) sectionsOrder.push('PAGE TEMPLATES');- if (blocks.length) sectionsOrder.push('BLOCKS');- if (domain.length) sectionsOrder.push('DOMAIN COMPONENTS');- sectionsOrder.push('FRAME + FOUNDATION');- // The legend promises the complete order, so a section emitted after it- // has to be in it.- if (hint) sectionsOrder.push('FEW MATCHES');+ const full = {+ fields: [+ 'name',+ 'domain',+ 'displayName',+ 'score',+ 'reason',+ 'import',+ 'description',+ 'command',+ ],+ format: {command: formatCliCommand},+ };+ /** @param {string[]} fields */+ const brief = fields => ({+ fields,+ format: {command: formatCliCommand, description: firstSentence},+ });+ // Blocks and components are extras: the text names the top few, and+ // says how many more the JSON and --verbose carry.+ const TOP = 3;+ /** @param {unknown[]} items */+ const shown = items => (verbose ? items : items.slice(0, TOP));+ /** @param {unknown[]} items */+ const more = items =>+ !verbose && items.length > TOP+ ? ` (top ${TOP} of ${items.length}; --verbose for all)`+ : '';/** @type {import('../formatters/index.mjs').Block[]} */const out = [section(`Build kit for "${q}"`),text(- 'A recommended set of pieces to assemble this page, in the order to use them. ' +- 'Begin with RECOMMENDED START, then pull from the sections below — each ' +- 'recommended item includes a `command:` to run next.\n' +- `Sections in order: ${sectionsOrder.join(', ')}.`,+ start+ ? 'Start from the TEMPLATE, fill it with BLOCKS, and use COMPONENTS only for what is left.\n' ++ 'Changing a page you already have? Keep it, and use only the blocks and components.'+ : 'This kit is narrowed by --type, so it names no template.',),- section('RECOMMENDED START', `${startNote}\n${startCmd}`),];- if (pages.length) {+ if (start) {out.push(section(- 'PAGE TEMPLATES',- directMatch- ? 'Closest full-page templates — scaffold one, then adapt it.'- : 'Closest full-page templates — use as a layout reference.',+ 'TEMPLATE',+ `${start.reason} ${+ start.basis === 'fallback'+ ? 'Scaffold it, then put blocks inside it.'+ : 'Scaffold it, then replace its content. Keep its layout and spacing.'+ }`,+ ),+ record(+ start,+ verbose+ ? {+ fields: ['name', 'displayName', 'description', 'command'],+ format: {command: formatCliCommand},+ }+ : brief(['name', 'description', 'command']),),- records(pages, recordOpts),);+ if (start.alternatives.length) {+ out.push(+ section(+ 'OTHER TEMPLATES',+ `If the layout is wrong, scaffold one of these instead. All page templates: ${formatCliCommand('template --list --type page')}`,+ ),+ records(+ start.alternatives,+ verbose ? full : brief(['name', 'description', 'command']),+ ),+ );+ }}- if (blocks.length) {+ // Search's own page matches, so the text carries every field the JSON+ // does: one line by default, the full entries under --verbose.+ if (pages.length) {out.push(- section('BLOCKS', 'Drop-in patterns that cover parts of the page.'),- records(blocks, recordOpts),+ verbose+ ? section(+ 'SEARCH MATCHES',+ 'Page templates keyword search matched, best first.',+ )+ : text(+ `Keyword search matched these page templates: ${pages.map(p => p.name).join(', ')}.`,+ ),);+ if (verbose) out.push(records(pages, full));}- if (domain.length) {+ if (blocks.length) {out.push(- section('DOMAIN COMPONENTS', 'Components specific to this idea.'),- records(domain, recordOpts),+ section(+ 'BLOCKS',+ `Ready-made sections for parts the template lacks${more(blocks)}. Print one: ${formatCliCommand('template <name>')}`,+ ),+ records(+ shown(blocks),+ verbose ? full : brief(['name', 'description']),+ ),);}-out.push(section(- 'FRAME + FOUNDATION',- 'Always-available shell + layout/text/action primitives.',+ 'COMPONENTS',+ `For what the template and blocks do not cover${more(domain)}. Read one: ${formatCliCommand('component <name>')}`,),+ ...(domain.length+ ? [+ records(+ shown(domain),+ verbose ? full : brief(['name', 'description']),+ ),+ ]+ : []),record({frame, foundation}),);diff --git a/packages/cli/clients/cli/commands/build.text-fields.test.mjs b/packages/cli/clients/cli/commands/build.text-fields.test.mjsindex 085e008e7d..79f71f01c4 100644--- a/packages/cli/clients/cli/commands/build.text-fields.test.mjs+++ b/packages/cli/clients/cli/commands/build.text-fields.test.mjs@@ -21,6 +21,8 @@ describe('build kit text fields mirror the JSON keys', () => {const {data} = JSON.parse(json.stdout);const keys = new Set([...Object.keys(data),+ ...Object.keys(data.start ?? {}),+ ...(data.start?.alternatives ?? []).flatMap(a => Object.keys(a)),...[...data.pages, ...data.blocks, ...data.domain].flatMap(e => Object.keys(e)),]);@@ -35,6 +37,45 @@ describe('build kit text fields mirror the JSON keys', () => {),];expect(fields).toContain('frame');+ // The start is printed as a record, so its fields are checked too.+ expect(fields).toContain('command');+ expect(fields).toContain('displayName');for (const field of fields) expect(keys).toContain(field);}, SLOW);++ it('leads with the start, then the alternatives, blocks and components', async () => {+ const human = await runCli(['build', 'analytics dashboard'], REPO);+ expect(human.status).toBe(0);+ const headings = human.stdout+ .split('\n')+ .filter(line => /^(TEMPLATE|OTHER TEMPLATES|BLOCKS|COMPONENTS)$/.test(line));+ expect(headings).toEqual(['TEMPLATE', 'OTHER TEMPLATES', 'BLOCKS', 'COMPONENTS']);+ // A builder changing a page they already have keeps it.+ expect(human.stdout).toContain(+ 'Changing a page you already have? Keep it, and use only the blocks and components.',+ );+ }, SLOW);++ it("shortens the start's description by default and prints it whole under --verbose", async () => {+ const json = await runCli(['build', 'quarterly revenue dashboard', '--json'], REPO);+ const {start} = JSON.parse(json.stdout).data;+ const first = start.description.slice(0, start.description.indexOf('. ') + 1);+ expect(first.length).toBeGreaterThan(0);+ expect(first.length).toBeLessThan(start.description.length);+ const line = out => out.split('\n').find(l => l.startsWith('description:'));+ const brief = await runCli(['build', 'quarterly revenue dashboard'], REPO);+ expect(line(brief.stdout)).toBe(`description: ${first}`);+ const whole = await runCli(['build', 'quarterly revenue dashboard', '--verbose'], REPO);+ expect(whole.stdout).toContain(start.description);+ }, SLOW);++ it("names search's page matches in the default text", async () => {+ const json = await runCli(['build', 'contact form', '--json'], REPO);+ const {data} = JSON.parse(json.stdout);+ expect(data.pages.length).toBeGreaterThan(0);+ const human = await runCli(['build', 'contact form'], REPO);+ expect(human.stdout).toContain(+ `Keyword search matched these page templates: ${data.pages.map(p => p.name).join(', ')}.`,+ );+ }, SLOW);});diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex d4c4031083..22308c0e63 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -354,8 +354,9 @@ export function detectStylingSystem(targetDir) {* Generate the agent cheat sheet from live CLI metadata.** Structured as: workflow (behavioral) → rules (error prevention) → CLI reference.- * Templates are positioned first in the workflow to teach agents the- * "look at reference code" reflex before writing any UI.+ * Templates lead the workflow: every page starts from a scaffolded template,+ * because the template already carries the frame and spacing that an agent+ * composing from components would have to re-derive, and usually gets wrong.** `stylingSystem` tailors the custom-styling guidance to what the project has* configured (see {@link detectStylingSystem}) so the agent never reaches for a@@ -428,17 +429,19 @@ export function generateCompressedIndex(lines.push(' import "@astryxdesign/core/astryx.css";');lines.push('');- // Workflow — `build` is the front door; discover before writing UI.- lines.push("WORKFLOW — discover, don't guess. Before writing UI:");- lines.push('1. `astryx build "<idea>"` — START HERE: returns a kit (closest [page] + [block]s + [component]s). No args = full playbook.');- lines.push('2. `astryx template <name> [--skeleton]` — scaffold the [page]/[block]s it named, or study their layout. Templates are reference code.');- lines.push('3. `astryx component <Name>` — props + examples for every component you use.');+ // Workflow — `build` is the front door, and every page starts from the+ // template it names.+ lines.push('WORKFLOW — start every page from a template. Never lay out a page from scratch:');+ lines.push('1. `astryx build "<idea>"` — START HERE: names the [page] template to start from (always one: the closest match, or the app shell), two other templates, and the [block]s + [component]s for parts it lacks. No args = full playbook.');+ lines.push('2. `astryx template <name> <path>` — scaffold that template into your project. Keep its frame, gap and padding; replace its data, copy and sections; delete sections you do not need.');+ lines.push('3. `astryx template <Block>` for a part the template lacks; `astryx component <Name>` for props + examples before you use or change a component.');+ lines.push('Changing a page you already have? Keep it: skip step 2 and add blocks and components inside its sections.');lines.push('');// Rules — the top error-preventers.lines.push('RULES:');lines.push('- No <div> — components do all layout/spacing, page frame included.');- lines.push('- Frame first: read `astryx docs layout` before writing any page or screen — page frame, region widths, breakpoint behavior.');+ lines.push('- Frame first: the template you scaffold sets the page frame. Read `astryx docs layout` before you change it — region widths, breakpoint behavior.');lines.push('- Dense data = rows (Table, List/Item), never Card-wrapped list items; Card is for standalone widgets. Status = StatusDot/Token; Badge = counts only.');// Styling guidance tailored to the project's configured system — never// recommend a path that isn't compiled here (xstyle needs the StyleX compiler;@@ -463,7 +466,7 @@ export function generateCompressedIndex(css: 'replace any raw <div>/<span> layout, imported .css/@apply, or hardcoded value (#hex, 16px) with the component or a token (var(--color-*|--spacing-*|…))',};lines.push(- `- SELF-CHECK before you finish: re-read the file and ${selfCheckFix[stylingSystem] ?? selfCheckFix.css}. If unsure a component/prop exists, run \`astryx component <Name>\` / \`astryx search "<thing>"\`; don't hand-roll CSS.`,+ `- SELF-CHECK before you finish: re-read the file and ${selfCheckFix[stylingSystem] ?? selfCheckFix.css}. Confirm the page kept its template's frame, gap and padding. If unsure a component/prop exists, run \`astryx component <Name>\` / \`astryx search "<thing>"\`; don't hand-roll CSS.`,);lines.push('');diff --git a/packages/cli/foundation/agent-docs/agent-docs.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.test.mjsindex 84623d68b0..4b6ac3bd1f 100644--- a/packages/cli/foundation/agent-docs/agent-docs.test.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.test.mjs@@ -55,6 +55,15 @@ describe('generateCompressedIndex', () => {expect(frameRule).not.toMatch(/https?:/);});+ it('starts every page from a template before any component', () => {+ const lines = generateCompressedIndex('1.0.0').split('\n');+ const workflow = lines.findIndex(l => l.startsWith('WORKFLOW'));+ expect(lines[workflow]).toMatch(/start every page from a template/);+ expect(lines[workflow + 1]).toMatch(/^1\. `astryx build /);+ expect(lines[workflow + 2]).toMatch(/^2\. `astryx template <name> <path>`/);+ expect(lines.join('\n')).not.toMatch(/reference code/);+ });+it('includes the post-generation self-check rule', () => {const result = generateCompressedIndex('1.0.0');expect(result).toContain('SELF-CHECK before you finish');diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 273dbb6d05..419a2c1b60 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -137,7 +137,7 @@ export const doc = {{value: 'build.kit',description:- 'The composition kit: echoed query, hasResults, matchCount (total matched, never a cap), directMatch, pages (closest templates), blocks (drop-in patterns) and domain (idea components/hooks) as SearchResultEntry[], frame and foundation name arrays, and hint {reason, commands} when thin.',+ "The template to start from and its kit: query, hasResults, matchCount (never a cap), directMatch, start {name, command, basis, reason, alternatives, ...}, pages (search's closest templates), blocks and domain as SearchResultEntry[], frame, foundation, and hint {reason, commands} when thin.",},// swizzlediff --git a/packages/cli/foundation/text/string-utils.mjs b/packages/cli/foundation/text/string-utils.mjsindex f5289da0ef..0266dc3bb2 100644--- a/packages/cli/foundation/text/string-utils.mjs+++ b/packages/cli/foundation/text/string-utils.mjs@@ -208,3 +208,21 @@ export async function searchComponents(needle, coreDir, components) {return results;}++/**+ * The first sentence of a text, whitespace collapsed. A period after "e.g" or+ * "i.e" does not end the sentence. Used where a description has to fit on one+ * line: `build`'s alternatives and its text kit.+ * @param {string} text+ * @returns {string}+ */+export function firstSentence(text) {+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();+ const ends = /[.!?](?=\s|$)/g;+ for (let m = ends.exec(flat); m; m = ends.exec(flat)) {+ if (!/\b(e\.g|i\.e)$/i.test(flat.slice(0, m.index))) {+ return flat.slice(0, m.index + 1);+ }+ }+ return flat;+}