Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): better search ranking, themes in search, and pointers to discover (#6959)

Joeya477e48a2b2e
diff --git a/.changeset/discover-pointers.md b/.changeset/discover-pointers.md
new file mode 100644
index 0000000000..51d7a8d194
--- /dev/null
+++ b/.changeset/discover-pointers.md
@@ -0,0 +1,15 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Point at `discover` where people look for things to add
+
+Nothing an agent reads named `discover`, so agents asked to find a theme
+searched the package registry instead. The agent block `astryx init` writes now
+lists `discover <words>` (integrations you could add, and the ones you have),
+`theme list` ends with `More themes in packages you could add: astryx discover
+theme`, and a text search ends with `More in packages you could add: astryx
+discover <query>` (except `--type hook`, since no integration adds hooks). JSON
+output is unchanged.
+
+@josephfarina
diff --git a/.changeset/search-quality-scoring-tie.md b/.changeset/search-quality-scoring-tie.md
new file mode 100644
index 0000000000..74ac799a24
--- /dev/null
+++ b/.changeset/search-quality-scoring-tie.md
@@ -0,0 +1,23 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Search: differentiate all-word matches by total quality; index themes
+
+Within the all-words tier, every candidate whose strongest token hit was a
+keyword scored the same (e.g. 157), regardless of how the other query words
+matched. A doc matching both words by keyword outranked nothing, and `search
+"how to use a theme"` put API reference docs above the consumer theme guide.
+
+The bonus now uses the sum of ALL token scores instead of just the strongest,
+so a candidate matching every word by keyword outranks one matching
+keyword + prose. The `theme` doc also gains consumer-facing keywords so it
+surfaces for questions like "how to use a theme" and "how to apply a theme".
+
+Themes are now a search domain: bundled and integration-provided themes appear
+in results with their slug, displayName, package, and the `astryx theme add`
+command. `--type theme` filters to them. Like `--type doc`, it works outside an
+app, where an open search now covers the docs and themes. Search help, the
+manifest, and the API reference list the new domain and its result fields.
+
+@josephfarina
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 13b89696cc..9155797c39 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -69,7 +69,7 @@ Results for "button" (20 of 239):
Options:
-- `--type <component|hook|doc|template>`: restrict to a single domain
+- `--type <component|hook|doc|template|theme>`: restrict to a single domain (`doc` and `theme` work outside an app too)
- `--limit <n>`: cap the number of results (default 20)
- `--verbose`: also print each result's match score and reason
- `--json`: typed `{ apiVersion, type: 'search', data: { query, matchCount, results } }` envelope — `matchCount` is how many candidates matched in total, `results` the slice `--limit` allowed
@@ -91,7 +91,7 @@ Options:
| `init` | Initialize the design system in your project |
| `integration` | Author and verify an Astryx integration package |
| `layout` | Generate XDS layouts from compressed expressions (XLE/XLO) |
-| `search` | Search components, hooks, docs, and templates in one ranked list |
+| `search` | Search components, hooks, docs, templates, and themes in one ranked list |
| `swizzle` | Copy component source for customization |
| `template` | List, show, or scaffold page and block templates |
| `theme` | Create and build themes: add a shipped one, compile to CSS, or list what a theme can override |
diff --git a/packages/cli/api/search/search.doc.mjs b/packages/cli/api/search/search.doc.mjs
index 79e66b5fb9..9115972413 100644
--- a/packages/cli/api/search/search.doc.mjs
+++ b/packages/cli/api/search/search.doc.mjs
@@ -14,7 +14,7 @@ export const doc = {
namespace: 'cli/api',
displayName: 'search()',
summary:
- 'Unified ranked search across components, hooks, docs, and templates.',
+ 'Unified ranked search across components, hooks, docs, templates, and themes.',
description:
'The single "I\'m looking for X" entry point across every content domain. ' +
'Ranking is keyword + fuzzy (not embeddings); name and keyword signals outrank ' +
@@ -35,7 +35,7 @@ export const doc = {
},
{
name: 'options.type',
- type: "'component' | 'hook' | 'doc' | 'template'",
+ type: "'component' | 'hook' | 'doc' | 'template' | 'theme'",
description: 'Restrict results to a single domain.',
},
{
@@ -48,14 +48,14 @@ export const doc = {
name: 'options.cwd',
type: 'string',
description:
- "Directory to resolve @astryxdesign/core from. A docs-only search (`type: 'doc'`) does not need it, and a search with no `type` covers the docs alone when core is missing.",
+ "Directory to resolve @astryxdesign/core from. A docs-only or themes-only search (`type: 'doc'` or `type: 'theme'`) does not need it, and a search with no `type` covers the docs and themes alone when core is missing.",
},
],
returns: [
{
type: 'search',
description:
- 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, and `displayName` and `kind` for templates. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from).',
+ 'The query echoed back, `matchCount` (how many candidates matched in total, before `limit`), plus a ranked SearchResultEntry[] bounded by `limit`: each has domain, name, score, reason, description, and follow-up command, plus `import` for components and hooks, `title` for docs, `displayName` and `kind` for templates, and `displayName` for themes. A doc result is the smallest part that answers: one section (with `section`, and a command that reads only it), one docs-tree route, or a topic, whose command lists its sections. `parent` is the command that opens the level above it: the section list of its topic, the namespace a tree node sits in, the Unorganized level for a flat topic, or the topic list for a top-level namespace. Every doc result also carries `package`, the npm package that authored it (for a section, the package its file came from). A theme result is one theme you can add: `name` is its slug, its command is the `astryx theme add` that copies it into the app, and `package` is the npm package that ships it (`@astryxdesign/cli` for the CLI\'s own themes).',
},
],
throws: [
diff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjs
index fd06f92f4c..f9c95347cc 100644
--- a/packages/cli/api/search/search.mjs
+++ b/packages/cli/api/search/search.mjs
@@ -7,10 +7,10 @@
* outputs. The CLI command handler is a thin wrapper around this function.
*
* `search(query)` is the single "I'm looking for X" entry point across ALL
- * content domains — components, hooks, docs topics, and templates (page +
- * block). Today, finding the right thing requires four separate list calls
- * (`component --list`, `hook --list`, `docs`, `template --list`) plus manual
- * scanning; this collapses them into one ranked, typed result set.
+ * content domains — components, hooks, docs topics, templates (page + block),
+ * and themes. Finding the right thing otherwise takes separate list calls
+ * (`component --list`, `hook --list`, `docs`, `template --list`, `theme list`)
+ * plus manual scanning; this collapses them into one ranked, typed result set.
*
* Scoring is keyword + fuzzy ranking (NOT semantic / embeddings — that is a
* deliberate future follow-up). It reuses the same signal weighting as the
@@ -89,6 +89,7 @@ import {loadIntegrationsSafely} from '../component/_adapter.mjs';
import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
import {discoverTemplates, extractComponents} from '../template/template.mjs';
import {templateLookupIds} from '../../foundation/discovery/template-adapter.mjs';
+import {listAvailableThemes} from '../theme/_adapter.mjs';
import {
guideEntry,
loadDocsCatalog,
@@ -110,7 +111,7 @@ import {setResultCoverage} from './coverage.mjs';
* A search candidate gathered from one content domain. Extra underscore-
* prefixed fields carry domain-specific payload used only by {@link toResult}.
* @typedef {object} Candidate
- * @property {'component'|'hook'|'doc'|'template'} domain
+ * @property {'component'|'hook'|'doc'|'template'|'theme'} domain
* @property {string} name
* @property {string[]} [keywords]
* @property {string[]} [weakKeywords]
@@ -291,7 +292,13 @@ const isTypo = (a, b, dist) =>
TYPO_MIN_LENGTH[/** @type {1 | 2 | 3} */ (dist)];
/** Valid domain filters for `--type`. */
-export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template'];
+export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template', 'theme'];
+
+/**
+ * The domains a search reads without @astryxdesign/core. An open search outside
+ * an app covers these alone.
+ */
+const CORELESS_DOMAINS = ['doc', 'theme'];
/**
* Filler words stripped from multi-word queries so natural-language phrasing
@@ -618,6 +625,7 @@ export function scoreQuery(term, tokens, candidate) {
// strong hits, then reward coverage so candidates matching more terms win.
let strongest = 0;
let matched = 0;
+ let tokenSum = 0;
/** @type {string[]} */
const hitTerms = [];
for (const tok of tokens) {
@@ -626,6 +634,7 @@ export function scoreQuery(term, tokens, candidate) {
if (h.score > strongest) strongest = h.score;
matched++;
hitTerms.push(tok);
+ tokenSum += h.score;
}
}
// The reverse of the title tier, a step lower: the query holds a whole title
@@ -650,14 +659,25 @@ export function scoreQuery(term, tokens, candidate) {
// (50 + bonus + coverage = 77) lost to thirty docs that each match
// `integration` alone, by name or in a code tick (98-108). The reader asked for
// both; a candidate that has both comes first, ordered among its peers by
- // how strong its strongest match is. It needs one keyword-strength hit:
+ // how strong its matches are. It needs one keyword-strength hit:
// every word mentioned in prose, or rendered by a page, is breadth, and
// stays on the token sum below an exact hit on one word.
+ //
+ // The TOTAL quality of matches orders candidates within this tier, not
+ // just the strongest single hit. A doc matching both words by keyword
+ // (90 + 90 = 180) outranks one matching keyword + prose (90 + 50 = 140).
+ // Before this, every all-word match whose strongest hit was a keyword (90)
+ // scored 157, burying the better match among dozens of ties.
if (matched === tokens.length && strongest >= STRONG_TOKEN_SCORE) {
return {
score:
FULL_COVERAGE_SCORE +
- Math.floor((strongest - MIN_TOKEN_SCORE) / 6.25),
+ Math.min(
+ Math.floor(
+ (tokenSum - matched * MIN_TOKEN_SCORE) / (matched * 5),
+ ),
+ 8,
+ ),
reason,
matched,
total,
@@ -1463,6 +1483,33 @@ async function gatherTemplates(cwd) {
});
}
+/**
+ * Build theme candidates from bundled and integration-provided themes. Without
+ * this, an integration's themes are invisible to `search` even though
+ * `theme list` and `discover` already resolve them.
+ * @param {string} cwd
+ * @returns {Promise<Candidate[]>}
+ */
+async function gatherThemes(cwd) {
+ let themes;
+ try {
+ themes = await listAvailableThemes(cwd);
+ } catch {
+ return [];
+ }
+ return themes.map(t => ({
+ domain: 'theme',
+ name: t.slug,
+ keywords: [
+ t.displayName,
+ ...(t.description ? t.description.split(/[^A-Za-z0-9]+/).filter(w => w.length > 3) : []),
+ ],
+ description: t.description || '',
+ _displayName: t.displayName,
+ _package: t.package,
+ }));
+}
+
/**
* Map a scored candidate to its public, actionable result shape. Each result
* carries enough to act on it: the domain, name, a one-line description, and
@@ -1519,6 +1566,14 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
command: `astryx template ${c._commandName ?? c.name} --type ${c._kind}`,
};
break;
+ case 'theme':
+ result = {
+ ...base,
+ displayName: c._displayName,
+ command: `astryx theme add ${c.name}`,
+ ...(c._package ? {package: c._package} : {}),
+ };
+ break;
default:
result = base;
}
@@ -1526,12 +1581,12 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
}
/**
- * Unified ranked search across components, hooks, docs, and templates.
+ * Unified ranked search across components, hooks, docs, templates, and themes.
*
* @param {string} query - Free-text search term.
* @param {object} [options]
* @param {string} [options.cwd]
- * @param {'component'|'hook'|'doc'|'template'} [options.type] - Restrict to one domain.
+ * @param {'component'|'hook'|'doc'|'template'|'theme'} [options.type] - Restrict to one domain.
* @param {number} [options.limit] - Max results (default 20).
* @returns {Promise<import('./search.type.mjs').SearchResponse>}
*/
@@ -1568,12 +1623,14 @@ export async function search(query, options = {}) {
const term = String(query).trim().toLowerCase();
const tokens = tokenizeQuery(term);
- // `astryx docs` reads docs without @astryxdesign/core, so a docs-only
- // search must too. Every other domain reads core: asked for by name, it is
- // an error without core; an open search then covers the docs alone.
- const docsOnly = type === 'doc';
- const coreDir = docsOnly ? null : findCoreDir(cwd);
- if (type && !docsOnly && !coreDir) {
+ // `astryx docs` reads docs without @astryxdesign/core, and `astryx theme
+ // list` reads themes without it (bundled themes need no project), so a
+ // search of either must too. Every other domain reads core: asked for by
+ // name, it is an error without core; an open search then covers the docs
+ // and themes alone.
+ const needsCore = !type || !CORELESS_DOMAINS.includes(type);
+ const coreDir = needsCore ? findCoreDir(cwd) : null;
+ if (type && needsCore && !coreDir) {
throw new AstryxError(
'Could not find @astryxdesign/core package',
undefined,
@@ -1583,17 +1640,19 @@ export async function search(query, options = {}) {
// Gather candidates from each requested domain in parallel.
/** @param {string} d */
- const wants = d => (!type && (coreDir != null || d === 'doc')) || type === d;
- const [components, hooks, docTopics, templates] = await Promise.all([
+ const wants = d =>
+ (!type && (coreDir != null || CORELESS_DOMAINS.includes(d))) || type === d;
+ const [components, hooks, docTopics, templates, themes] = await Promise.all([
wants('component')
? gatherComponents(/** @type {string} */ (coreDir), cwd)
: [],
wants('hook') ? gatherHooks(/** @type {string} */ (coreDir)) : [],
wants('doc') ? gatherDocs(cwd) : [],
wants('template') ? gatherTemplates(cwd) : [],
+ wants('theme') ? gatherThemes(cwd) : [],
]);
- const all = [...components, ...hooks, ...docTopics, ...templates];
+ const all = [...components, ...hooks, ...docTopics, ...templates, ...themes];
// Score every candidate on its own merits. The consumer groups results by
// role (page / block / component) and takes the top of each, so there's no
@@ -1610,7 +1669,7 @@ export async function search(query, options = {}) {
// Sort by score desc, then domain (stable order), then name.
/** @type {Record<string, number>} */
- const domainOrder = {component: 0, hook: 1, doc: 2, template: 3};
+ const domainOrder = {component: 0, hook: 1, doc: 2, template: 3, theme: 4};
scored.sort(
(a, b) =>
b.score - a.score ||
diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjs
index f5734963c4..ca297daaf5 100644
--- a/packages/cli/api/search/search.test.mjs
+++ b/packages/cli/api/search/search.test.mjs
@@ -75,7 +75,7 @@ describe('search leaf — envelope + ranking', () => {
});
describe('search leaf — per-domain result fields', () => {
- it('carries import for components and hooks, title for docs, displayName and kind for templates', async () => {
+ it('carries import for components and hooks, title for docs, displayName and kind for templates, displayName for themes', async () => {
const r = await search('theme', {cwd, limit: 60});
expect(new Set(r.data.results.map(res => res.domain))).toEqual(
new Set(SEARCH_DOMAINS),
@@ -89,9 +89,12 @@ describe('search leaf — per-domain result fields', () => {
expect(res.title).toMatch(/\S/);
const read = `astryx docs ${res.name}`;
expect([read, `${read} --index`, `${read} ${res.section}`]).toContain(res.command);
- } else {
+ } else if (res.domain === 'template') {
expect(res.displayName).toMatch(/\S/);
expect(['page', 'block']).toContain(res.kind);
+ } else if (res.domain === 'theme') {
+ expect(res.displayName).toMatch(/\S/);
+ expect(res.command).toMatch(/^astryx theme add /);
}
}
}, SLOW);
@@ -397,11 +400,10 @@ describe('search leaf — a candidate that matches every word outranks a partial
expect(score(q, all)).toBeLessThan(160);
});
- // Among candidates that match every word, the stronger match should come
- // first. Today every all-word match with a keyword hit gets the same score,
- // so this records the order without enforcing it: it fails, as expected,
- // until the scoring tells the two apart.
- it.fails('ranks the stronger of two all-word matches first', () => {
+ // Among candidates that match every word, the stronger match comes first:
+ // the all-words tier uses total match quality (sum of token scores), not
+ // just the strongest, so an exact keyword outranks a stem-form keyword.
+ it('ranks the stronger of two all-word matches first', () => {
const all = {name: 'x', keywords: ['alphas'], description: 'alpha beta gamma delta'};
const q = 'alpha beta gamma delta';
expect(score(q, {name: 'y', keywords: ['alpha'], description: 'beta gamma delta'})).toBeGreaterThan(
diff --git a/packages/cli/api/search/search.type.mjs b/packages/cli/api/search/search.type.mjs
index 23b868b12f..6fd6b2afb9 100644
--- a/packages/cli/api/search/search.type.mjs
+++ b/packages/cli/api/search/search.type.mjs
@@ -9,24 +9,24 @@
/**
* The domain a search result belongs to.
- * @typedef {'component' | 'hook' | 'doc' | 'template'} SearchDomain
+ * @typedef {'component' | 'hook' | 'doc' | 'template' | 'theme'} SearchDomain
*/
/**
* A single ranked search result, tagged with its domain.
* @typedef {object} SearchResultEntry
* @property {SearchDomain} domain - Which content domain this result came from.
- * @property {string} name - Primary identifier (component/hook name, doc topic or docs-tree route, template dir).
+ * @property {string} name - Primary identifier (component/hook name, doc topic or docs-tree route, template dir, theme slug).
* @property {number} score - Relevance score (higher is better).
* @property {string} reason - Human-readable reason the candidate matched (e.g. `keyword "button"`).
* @property {string} description - One-line description, when available.
- * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`).
+ * @property {string} command - Follow-up command to act on this result (e.g. `astryx component Button`, or `astryx theme add neutral` for a theme).
* @property {string} [import] - Import path — present for component and hook results.
* @property {string} [title] - Doc title — present for doc results.
* @property {string} [section] - Section key — present when a doc result is one section of a topic; `command` reads only that section.
- * @property {string} [package] - The npm package that authored a doc result; for a section, the package whose file the section came from.
+ * @property {string} [package] - The npm package that authored a doc result (for a section, the package whose file the section came from), or that ships a theme result.
* @property {string} [parent] - Command that opens the level above a doc result — its topic's section list for a section, the docs-tree namespace it sits in for a tree node — so a reader can see the siblings and open another.
- * @property {string} [displayName] - Friendly display name — present for template results.
+ * @property {string} [displayName] - Friendly display name — present for template and theme results.
* @property {'page' | 'block'} [kind] - Template kind (`page` | `block`) — present for template results.
*/
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index e2c84b9eaa..9d32718d40 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -6,8 +6,9 @@ export const docs = {
name: 'theme',
title: 'Theme System',
category: 'guide',
+ keywords: ['use', 'apply', 'setup'],
description:
- 'Theme provider, custom themes, theme build for production/SSR, light/dark mode, and component style overrides.',
+ 'How to use and apply themes in your app: providers, custom themes, light/dark mode, production builds, and component style overrides.',
sections: [
{
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index 56e50cf59a..55f49d1e94 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -209,11 +209,16 @@ async function warnOnThemeIntegrationIssues(json) {
* @param {import('../../../api/theme/theme.type.mjs').ThemeListEntry[]} themes
*/
function printThemeList(themes) {
+ const run = getCliInvocation();
+ // `theme list` shows what this project can add now. Themes in packages it
+ // has not installed are `discover`'s.
+ const more = text(
+ `More themes in packages you could add: ${run} discover theme`,
+ );
if (themes.length === 0) {
- emit(text('No themes are available in this project.'));
+ emit(text('No themes are available in this project.'), more);
return;
}
- const run = getCliInvocation();
emit(
section('Themes'),
list(
@@ -226,6 +231,7 @@ function printThemeList(themes) {
text(
`Usage:\n ${run} theme add <slug> [target-path] Scaffold a theme file you own`,
),
+ more,
);
}
diff --git a/packages/cli/clients/cli/commands/search.doc.mjs b/packages/cli/clients/cli/commands/search.doc.mjs
index cdf397112b..91408a86cf 100644
--- a/packages/cli/clients/cli/commands/search.doc.mjs
+++ b/packages/cli/clients/cli/commands/search.doc.mjs
@@ -13,11 +13,11 @@ export const doc = {
name: 'search',
displayName: 'astryx search',
namespace: 'cli/commands',
- summary: 'Search components, hooks, docs, and templates in one ranked list',
+ summary: 'Search components, hooks, docs, templates, and themes in one ranked list',
description:
'Terminal front-end to search(): prints one ranked, greppable list across ' +
'every content domain, each row carrying a follow-up command to act on it. ' +
- 'Outside an app, where @astryxdesign/core is not installed, it searches the docs.',
+ 'Outside an app, where @astryxdesign/core is not installed, it searches the docs and themes.',
fn: 'search',
// Every word after `search` is the query: `astryx search dark mode` searches
// for "dark mode", with no quotes needed.
@@ -26,8 +26,8 @@ export const doc = {
{
flag: '--type <domain>',
param: 'options.type',
- choices: ['component', 'hook', 'doc', 'template'],
- description: 'Filter to one domain (component|hook|doc|template)',
+ choices: ['component', 'hook', 'doc', 'template', 'theme'],
+ description: 'Filter to one domain (component|hook|doc|template|theme)',
},
{
flag: '--limit <n>',
@@ -49,6 +49,7 @@ export const doc = {
label: 'Filter + JSON',
cli: 'astryx search "data table" --type template --json',
},
+ {label: 'Themes you can add', cli: 'astryx search warm --type theme'},
],
exitCodes: [
{code: 0, when: 'success (including zero matches)'},
diff --git a/packages/cli/clients/cli/commands/search.mjs b/packages/cli/clients/cli/commands/search.mjs
index d9142fc4a4..383e328c68 100644
--- a/packages/cli/clients/cli/commands/search.mjs
+++ b/packages/cli/clients/cli/commands/search.mjs
@@ -4,9 +4,9 @@
* @file search command — unified ranked search with a stable result summary.
*
* One "I'm looking for X" entry point spanning components, hooks, docs topics,
- * and templates (page + block). Results are ranked by relevance and tagged
- * with their domain, with a follow-up command so the user knows what to run
- * next.
+ * templates (page + block), and themes. Results are ranked by relevance and
+ * tagged with their domain, with a follow-up command so the user knows what to
+ * run next.
*
* The command surface (description, args, flags) is sourced from the colocated
* `search.doc.mjs` CommandDoc via `defineCommand`; this file supplies only the
@@ -104,13 +104,13 @@ export function registerSearch(program) {
// ── Text output ──────────────────────────────────────────────
const run = getCliInvocation();
const {query: q, matchCount, results} = result.data;
- // Outside an app an open search covers the docs alone. Say so, so a
- // docs-only list does not read as "Astryx has no such component".
+ // Outside an app an open search covers the docs and themes alone. Say
+ // so, so that list does not read as "Astryx has no such component".
const note =
!options.type && !findCoreDir(process.cwd())
? [
text(
- '@astryxdesign/core is not installed here, so only the docs were searched.',
+ '@astryxdesign/core is not installed here, so only the docs and themes were searched.',
),
]
: [];
@@ -123,6 +123,7 @@ export function registerSearch(program) {
text(
`Try a broader term, or browse: ${run} ${note.length > 0 ? 'docs' : 'component --list'}`,
),
+ ...discoverHint(run, q, options.type),
);
return answered;
}
@@ -174,11 +175,34 @@ export function registerSearch(program) {
format: {command: formatCliCommand, parent: formatCliCommand},
}),
...note,
+ ...discoverHint(run, q, options.type),
);
return answered;
},
});
}
+/**
+ * Search reads only what is installed. Point at `discover` for the packages
+ * that could add more, except for hooks, which no integration adds.
+ * @param {string} run - The caller's CLI invocation prefix.
+ * @param {string} query
+ * @param {string | undefined} type
+ */
+function discoverHint(run, query, type) {
+ if (type === 'hook') return [];
+ return [
+ text(`More in packages you could add: ${run} discover ${shellWord(query)}`),
+ ];
+}
+
+/**
+ * One shell word: the value itself when it is plain, else single-quoted.
+ * @param {string} value
+ */
+function shellWord(value) {
+ return /^[\w@./:-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
+}
+
// Re-export the API for external consumers.
export {search, SEARCH_DOMAINS} from '../../../api/search/search.mjs';
diff --git a/packages/cli/clients/cli/commands/search.test.mjs b/packages/cli/clients/cli/commands/search.test.mjs
index 38e35f37a5..d6a08d1a6d 100644
--- a/packages/cli/clients/cli/commands/search.test.mjs
+++ b/packages/cli/clients/cli/commands/search.test.mjs
@@ -118,6 +118,15 @@ describe('search() API — filters', () => {
}
});
+ it('--type theme returns only themes, each with the command that adds it', async () => {
+ const {data} = await search('warm', {...OPTS, type: 'theme'});
+ expect(data.results.map(r => r.name)).toContain('neutral');
+ for (const r of data.results) {
+ expect(r.domain).toBe('theme');
+ expect(r.command).toBe(`astryx theme add ${r.name}`);
+ }
+ });
+
it('respects --limit', async () => {
const {data} = await search('button', {...OPTS, limit: 3});
expect(data.results.length).toBeLessThanOrEqual(3);
@@ -279,7 +288,7 @@ describe('search CLI — exit codes + JSON contract', () => {
});
it('prints every result field under its JSON key (score and reason with --verbose)', async () => {
- // One query that reaches all four domains, so every per-domain field shows.
+ // One query that reaches every domain, so every per-domain field shows.
const args = ['search', 'theme', '--limit', '60'];
const env = JSON.parse((await runCli(['--json', ...args], REPO_ROOT)).stdout);
expect(new Set(env.data.results.map(r => r.domain))).toEqual(new Set(SEARCH_DOMAINS));
@@ -311,16 +320,42 @@ describe('search CLI — exit codes + JSON contract', () => {
expect(r.stdout).toContain('reason:');
});
- it('searches the docs when no @astryxdesign/core is reachable, and exits 1 for --type component', async () => {
+ it('points at discover for packages that could add more, except for hooks', async () => {
+ const open = await runCli(['search', 'data', 'table'], REPO_ROOT);
+ expect(open.status).toBe(0);
+ expect(open.stdout).toMatch(/^More in packages you could add: .*discover 'data table'$/m);
+ const none = await runCli(['search', 'zzqqxxnomatch'], REPO_ROOT);
+ expect(none.stdout).toMatch(/^More in packages you could add: .*discover zzqqxxnomatch$/m);
+ const hooks = await runCli(['search', 'click', '--type', 'hook'], REPO_ROOT);
+ expect(hooks.status).toBe(0);
+ expect(hooks.stdout).not.toContain('More in packages you could add');
+ const json = await runCli(['--json', 'search', 'button'], REPO_ROOT);
+ expect(json.stdout).not.toContain('More in packages you could add');
+ });
+
+ it('searches the docs and themes when no @astryxdesign/core is reachable, and exits 1 for --type component', async () => {
const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-search-cli-no-core-'));
try {
const open = await runCli(['--json', 'search', 'make', 'an', 'integration'], empty);
expect(open.status).toBe(0);
expect(JSON.parse(open.stdout).data.results[0]).toMatchObject({domain: 'doc'});
- // The text says the search covered the docs alone.
+ // Bundled themes need no project, so an open search finds them too.
+ const theme = await runCli(['--json', 'search', 'neutral'], empty);
+ expect(theme.status).toBe(0);
+ expect(JSON.parse(theme.stdout).data.results[0]).toMatchObject({
+ domain: 'theme',
+ name: 'neutral',
+ });
+ // The text says the search covered the docs and themes alone.
const text = await runCli(['search', 'button'], empty);
expect(text.status).toBe(0);
- expect(text.stdout).toContain('only the docs were searched');
+ expect(text.stdout).toContain('only the docs and themes were searched');
+ // A themes-only search needs no core, like a docs-only one.
+ const themes = await runCli(['--json', 'search', 'warm', '--type', 'theme'], empty);
+ expect(themes.status).toBe(0);
+ const found = JSON.parse(themes.stdout).data.results;
+ expect(found.map(r => r.name)).toContain('neutral');
+ expect(found.every(r => r.domain === 'theme')).toBe(true);
const json = await runCli(['--json', 'search', 'button', '--type', 'component'], empty);
expect(json.status).toBe(1);
expect(JSON.parse(json.stdout)).toMatchObject({code: 'ERR_CORE_NOT_FOUND'});
diff --git a/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs b/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs
new file mode 100644
index 0000000000..b0bd1aa628
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-list.behavior.test.mjs
@@ -0,0 +1,41 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CLI behavior for `astryx theme list`.
+ *
+ * `theme list` shows the themes this project can add now. Themes in packages
+ * it has not installed are `discover`'s, so the list ends by pointing there:
+ * an agent that never learns `discover` exists searches the registry instead.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-cli-theme-list-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('astryx theme list', () => {
+ it('lists the bundled themes and points at discover for more', async () => {
+ const {status, stdout} = await runCli(['theme', 'list'], {cwd: tmpDir});
+
+ expect(status).toBe(0);
+ expect(stdout).toMatch(/^- neutral \(maintained, @astryxdesign\/cli\)/m);
+ expect(stdout).toMatch(/More themes in packages you could add: .*discover theme$/m);
+ });
+
+ it('keeps the JSON envelope free of the hint', async () => {
+ const {status, stdout} = await runCli(['--json', 'theme', 'list'], {cwd: tmpDir});
+
+ expect(status).toBe(0);
+ expect(stdout).not.toContain('discover');
+ expect(JSON.parse(stdout).type).toBe('theme.list');
+ });
+});
diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjs
index 8ebccb34ca..eaa6b59d41 100644
--- a/packages/cli/foundation/agent-docs/agent-docs.mjs
+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs
@@ -472,7 +472,8 @@ export function generateCompressedIndex(
// Command reference — build/template/component are covered in WORKFLOW above.
lines.push('MORE CLI:');
- lines.push(' search "<query>" find any component / hook / doc / template / block');
+ lines.push(' search "<query>" find any component / hook / doc / template / block / theme');
+ lines.push(' discover <words> integrations you could add, and the ones you have');
lines.push(` component --list ${componentCount} components by category`);
lines.push(' template --list page + block recipes');
const docsDir = path.join(CLI_ROOT, 'assets', 'docs');
diff --git a/packages/cli/foundation/agent-docs/agent-docs.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.test.mjs
index 6413db590c..797ca865a4 100644
--- a/packages/cli/foundation/agent-docs/agent-docs.test.mjs
+++ b/packages/cli/foundation/agent-docs/agent-docs.test.mjs
@@ -110,6 +110,14 @@ describe('generateCompressedIndex', () => {
expect(result).toMatch(/after any Astryx or integration dependency bump/);
});
+ it('points agents at discover for integrations they could add', () => {
+ const result = generateCompressedIndex('1.0.0');
+ // Without this line no surface an agent reads names `discover`, and agents
+ // look for a theme in the package registry instead.
+ expect(result).toMatch(/^ {2}discover <words> {3}integrations you could add, and the ones you have$/m);
+ expect(result).toMatch(/^ {2}search "<query>" .*\/ theme$/m);
+ });
+
it('states the invocation once in the CLI header (yarn)', () => {
const result = generateCompressedIndex('1.0.0', {invocation: 'yarn astryx'});
expect(result).toContain('yarn astryx <cmd>');
diff --git a/packages/cli/test/__golden__/search.json b/packages/cli/test/__golden__/search.json
index 1cd71aef35..568d44bfbe 100644
--- a/packages/cli/test/__golden__/search.json
+++ b/packages/cli/test/__golden__/search.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "zorblax",
- "matchCount": 3,
+ "matchCount": 4,
"results": [
{
"domain": "component",
@@ -14,6 +14,16 @@
"import": "@acme/kit",
"command": "astryx component AcmeCard"
},
+ {
+ "domain": "theme",
+ "name": "ocean",
+ "score": 90,
+ "reason": "keyword \"zorblax\"",
+ "description": "A zorblax blue.",
+ "displayName": "Ocean",
+ "command": "astryx theme add ocean",
+ "package": "@acme/kit"
+ },
{
"domain": "doc",
"name": "acme-guide",