An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): tailor agent-docs styling guidance to the project's styling system (#3139)
Joeyd53a9248bcde
diff --git a/.changeset/env-aware-styling-docs.md b/.changeset/env-aware-styling-docs.mdnew file mode 100644index 0000000000..d0ee2a5f72--- /dev/null+++ b/.changeset/env-aware-styling-docs.md@@ -0,0 +1,25 @@+---+'@astryxdesign/cli': patch+---++[feat] Densify agent docs + tailor styling guidance to the project's configured system++Tightened the generated `CLAUDE.md`/`AGENTS.md` block from ~48 lines to ~26+(the per-topic `docs` dump collapsed to one line, `build`/`search`/`component`+no longer duplicated between workflow and reference, run-prefix stated once,+filler prose removed) — same information, far denser.++`init`/`agent-docs` now detect whether the consumer project has the StyleX+compiler, Tailwind, or neither, and write the matching custom-styling guidance+into the generated `CLAUDE.md`/`AGENTS.md`:++- StyleX compiler wired → `xstyle` / StyleX token imports+- Tailwind → utility classes backed by `@astryxdesign/core/tailwind-theme.css`+- neither → `style`/`className` with `var(--token)` design tokens, plus an+ explicit note NOT to use `xstyle`/utilities (they would not compile)++Previously the docs hardcoded "use the xstyle prop," which throws at runtime+(blank page) in a plain Vite app with no StyleX compiler, and ignored the+Tailwind bridge entirely. Also corrects the token prefix in the theme rule+(`--astryx-color-*` → `--color-*`).+@joeyfarinadiff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjsindex 3ea352ee82..f5f023c9c6 100644--- a/packages/cli/src/commands/agent-docs.mjs+++ b/packages/cli/src/commands/agent-docs.mjs@@ -93,14 +93,55 @@ export function resolveAgentPaths(targetDir, agent) {return {inject: [], create: [searchPaths[searchPaths.length - 1]]};}+/**+ * Detect which styling system the consumer project has wired up, so the agent+ * docs recommend a path that actually compiles in THIS project.+ *+ * `xstyle`/StyleX needs the StyleX compiler (the `@stylexjs/stylex` runtime+ * alone throws at runtime → blank page); Tailwind utilities need Tailwind.+ * Recommending either when it isn't configured yields unstyled or blank output.+ * Plain CSS variables (via `style`/`className`) always work, so they're the+ * safe default. Precedence: stylex (compiler wired) → tailwind → css.+ *+ * @param {string} targetDir+ * @returns {'stylex' | 'tailwind' | 'css'}+ */+export function detectStylingSystem(targetDir) {+ try {+ const pkgPath = path.join(targetDir, 'package.json');+ if (!fs.existsSync(pkgPath)) return 'css';+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));+ const deps = {...pkg.dependencies, ...pkg.devDependencies};+ // Key off a StyleX *compiler* plugin — the runtime alone won't render.+ const stylexCompilers = [+ '@stylexjs/babel-plugin',+ 'vite-plugin-stylex',+ 'unplugin-stylex',+ '@stylexswc/unplugin',+ '@stylexswc/nextjs-plugin',+ 'stylex-webpack',+ ];+ if (stylexCompilers.some(d => d in deps)) return 'stylex';+ if ('tailwindcss' in deps) return 'tailwind';+ return 'css';+ } catch {+ // Best-effort: default to the universally-safe CSS-variable path.+ return 'css';+ }+}+/*** 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.+ *+ * `stylingSystem` tailors the custom-styling guidance to what the project has+ * configured (see {@link detectStylingSystem}) so the agent never reaches for a+ * styling path that isn't compiled here.*/-export function generateCompressedIndex(version, {coreDir, runPrefix = getRunPrefix()} = {}) {+export function generateCompressedIndex(version, {coreDir, runPrefix = getRunPrefix(), stylingSystem = 'css'} = {}) {const run = `${runPrefix} astryx`;const lines = [MARKER_START];@@ -117,86 +158,57 @@ export function generateCompressedIndex(version, {coreDir, runPrefix = getRunPre}}- // Header- lines.push(`Astryx v${version} — ${componentCount} components`);+ // Header — state the CLI prefix once; commands below are shown as `astryx <cmd>`.+ lines.push(`Astryx v${version} · ${componentCount} components`);+ lines.push(`CLI: run every command as \`${run} <cmd>\` (shown below as \`astryx ...\`).`);lines.push('');- // One-time project setup — components ship precompiled CSS that MUST be- // imported, or everything renders unstyled. Stated as text (the CLI does not- // edit your files). The Theme provider is OPTIONAL (a default theme ships in- // astryx.css); only the CSS imports are required.- lines.push('SETUP (required, once) — in your app entry (e.g. main.tsx):');+ // Required setup — components ship precompiled CSS; without these imports+ // everything renders unstyled. Theme is optional (a default ships in astryx.css).+ lines.push('SETUP (once, in your app entry e.g. main.tsx) — without these, components render unstyled:');lines.push(' import "@astryxdesign/core/reset.css";');lines.push(' import "@astryxdesign/core/astryx.css";');- lines.push('Without these CSS imports, components render completely unstyled.');- lines.push(`Optional: apply a specific theme with <Theme> — see \`${run} docs theme\`.`);lines.push('');- // Behavioral workflow — `build` is the front door for making pages: it returns- // a composition kit, and `build` with no args prints the full how-to playbook.- lines.push('Before writing any UI code:');- lines.push(- `1. \`${run} build "<what you're building>"\` — START HERE. Returns a composition kit: the closest [page] recipe (scaffold it, or use as a layout reference), the [block]s that cover parts, and the [component]s to fill gaps. (Run \`${run} build\` with no args for the full how-to-build playbook.)`,- );- lines.push(`2. \`${run} template <name> --skeleton\` — scaffold a matched [page], or study its layout (gap, padding, nesting)`);- lines.push(`3. \`${run} template <BlockName>\` — drop in each [block] the kit surfaced (ready-made multi-component patterns) instead of hand-building`);- lines.push(`4. \`${run} component <Name>\` — read props + examples for EVERY component you use`);- lines.push('');- lines.push('Templates and blocks are reference code — read them for composition patterns, not just scaffolding.');- lines.push(`(\`${run} search <query>\` is a neutral find across components/hooks/docs/templates when you just need to look something up.)`);+ // 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.');lines.push('');- // Rules — inline, compact, prevents the top error categories- lines.push('No <div> anywhere — not for layout, not for wrappers, not for spacing. Use components.');- lines.push('Full-page shells → AppShell (not Layout). Sidebar nav → SideNav (not List).');- lines.push('No style={{}} — use the xstyle prop on components for custom styling.');- lines.push('If a component prop does what you need, use it — never replicate with CSS/stylex.');- lines.push(`No magic values — run \`${run} docs tokens\` for spacing/color/radius.`);- lines.push(`To change accent/brand colors: \`${run} theme\` — never override --astryx-color-* in :root.`);+ // Rules — the top error-preventers.+ lines.push('RULES:');+ lines.push('- No <div> — components do all layout/spacing. Full page → AppShell; sidebar nav → SideNav.');+ // Styling guidance tailored to the project's configured system — never+ // recommend a path that isn't compiled here (xstyle needs the StyleX compiler;+ // utilities need Tailwind). Tokens are always the source of truth.+ if (stylingSystem === 'stylex') {+ lines.push('- Custom styling: component props first; else the xstyle prop / StyleX tokens (@astryxdesign/core/theme/tokens.stylex). No raw hex/px.');+ } else if (stylingSystem === 'tailwind') {+ lines.push('- Custom styling: component props first; else Tailwind utilities backed by tokens (bg-surface, text-primary, rounded-lg) via tailwind-theme.css. No raw hex/px.');+ } else {+ lines.push("- Custom styling: component props first; else style/className with tokens — var(--color-*|--spacing-*|--radius-*). No raw hex/px. (No StyleX/Tailwind compiler here — don't use xstyle/utility classes.)");+ }+ lines.push('- Tokens for every value (`astryx docs tokens`). Brand/accent via `astryx theme` — never override --color-* in :root.');lines.push('');- // CLI quick reference- lines.push(`${run} build "<idea>" START HERE for pages — kit: closest page + blocks + components (\`build\` = how-to playbook)`);- lines.push(`${run} search "<query>" find anything: components, hooks, docs, templates, blocks`);- lines.push(`${run} component --list ${componentCount} components by category`);- lines.push(`${run} component <Name> props, types, examples`);-- // Doc topics from live discovery+ // 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(` component --list ${componentCount} components by category`);+ lines.push(' template --list page + block recipes');const docsDir = path.join(CLI_ROOT, 'docs');if (fs.existsSync(docsDir)) {- for (const file of fs.readdirSync(docsDir).sort()) {- const match = file.match(/^(\w+)\.doc\.mjs$/);- if (!match) continue;- const topic = match[1];- let desc = topic;- try {- const fileContent = fs.readFileSync(path.join(docsDir, file), 'utf-8');- const descMatch = fileContent.match(/description:\s*['"](.+?)['"]/);- if (descMatch) desc = descMatch[1];- } catch {- // Best-effort: fall back to the topic name if the file is unreadable.- }- if (desc.length > 50) desc = desc.slice(0, 47) + '...';- lines.push(`${run} docs ${topic.padEnd(20)} ${desc}`);- }- }-- // Templates- const templatesDir = path.join(CLI_ROOT, 'templates');- if (fs.existsSync(templatesDir)) {- const templates = fs.readdirSync(templatesDir, {withFileTypes: true})- .filter(e => e.isDirectory())- .map(e => e.name)+ const topics = fs.readdirSync(docsDir)+ .map(f => f.match(/^(\w+)\.doc\.mjs$/))+ .filter(Boolean)+ .map(m => m[1]).sort();- if (templates.length > 0) {- lines.push(`${run} template --list page recipes with component lists`);- lines.push(`${run} template <name> [path] scaffold from template`);- }+ if (topics.length > 0) lines.push(` docs <topic> ${topics.join(', ')}`);}-- lines.push(`${run} swizzle <Name> eject source (--gap to report why)`);- lines.push(`${run} upgrade --apply codemods after version bump`);- lines.push(`after @astryxdesign/core bump, always run ${run} upgrade --apply`);+ lines.push(' swizzle <Name> eject component source (--gap reports why)');+ lines.push(' upgrade --apply run after any @astryxdesign/core bump');lines.push(MARKER_END);return lines.join('\n');@@ -275,7 +287,10 @@ export function injectXdsBlock(filePath, compressedIndex, {createIfMissing = fal*/export function injectAgentsMd(targetDir, version) {const agentsPath = path.join(targetDir, AGENTS_MD);- const compressedIndex = generateCompressedIndex(version, {coreDir: findCoreDir(targetDir)});+ const compressedIndex = generateCompressedIndex(version, {+ coreDir: findCoreDir(targetDir),+ stylingSystem: detectStylingSystem(targetDir),+ });injectXdsBlock(agentsPath, compressedIndex, {createIfMissing: true,header: `# AGENTS.md\n\nProject-specific guidance for AI coding agents.`,@@ -290,7 +305,10 @@ export function injectAgentsMd(targetDir, version) {*/export function injectClaudeMd(targetDir, version) {const claudePath = path.join(targetDir, CLAUDE_MD);- const compressedIndex = generateCompressedIndex(version, {coreDir: findCoreDir(targetDir)});+ const compressedIndex = generateCompressedIndex(version, {+ coreDir: findCoreDir(targetDir),+ stylingSystem: detectStylingSystem(targetDir),+ });return injectXdsBlock(claudePath, compressedIndex);}@@ -373,7 +391,8 @@ export function installAgentDocs(targetDir, {zh = false, lang, agent, paths, onlconst coreDir = findCoreDir(targetDir);const version = getXdsVersion(coreDir);const runPrefix = getRunPrefix(targetDir);- const compressedIndex = generateCompressedIndex(version, {coreDir, zh, lang, runPrefix});+ const stylingSystem = detectStylingSystem(targetDir);+ const compressedIndex = generateCompressedIndex(version, {coreDir, zh, lang, runPrefix, stylingSystem});const written = [];// Explicit paths override everythingdiff --git a/packages/cli/src/commands/agent-docs.test.mjs b/packages/cli/src/commands/agent-docs.test.mjsindex f76d863c60..de7564d2de 100644--- a/packages/cli/src/commands/agent-docs.test.mjs+++ b/packages/cli/src/commands/agent-docs.test.mjs@@ -6,6 +6,7 @@ import * as path from 'node:path';import * as os from 'node:os';import {generateCompressedIndex,+ detectStylingSystem,getXdsVersion,installAgentDocs,injectAgentsMd,@@ -39,31 +40,86 @@ describe('generateCompressedIndex', () => {it('includes theme nudge rule', () => {const result = generateCompressedIndex('1.0.0');expect(result).toMatch(/astryx theme/);- expect(result).toMatch(/never override --astryx-color/);+ expect(result).toMatch(/never override --color-/);+ });++ it('defaults to the CSS-variable styling path (no compiler)', () => {+ const result = generateCompressedIndex('1.0.0');+ expect(result).toMatch(/style\/className with tokens/);+ expect(result).toMatch(/var\(--color-\*/);+ // Must NOT push xstyle when no StyleX compiler is present.+ expect(result).not.toMatch(/xstyle prop/);+ });++ it('recommends xstyle when StyleX is configured', () => {+ const result = generateCompressedIndex('1.0.0', {stylingSystem: 'stylex'});+ expect(result).toMatch(/xstyle prop \/ StyleX tokens/);+ });++ it('recommends Tailwind utilities when Tailwind is configured', () => {+ const result = generateCompressedIndex('1.0.0', {stylingSystem: 'tailwind'});+ expect(result).toMatch(/Tailwind utilities backed by tokens/);+ expect(result).toMatch(/tailwind-theme\.css/);});it('includes upgrade command and migration rule', () => {const result = generateCompressedIndex('1.0.0');- expect(result).toContain('astryx upgrade');- expect(result).toContain('astryx upgrade --apply');- expect(result).toMatch(/always run .+ astryx upgrade --apply/);+ expect(result).toContain('upgrade --apply');+ expect(result).toMatch(/after any @astryxdesign\/core bump/);});- it('uses custom runPrefix when provided', () => {+ it('states the runPrefix once in the CLI header', () => {const result = generateCompressedIndex('1.0.0', {runPrefix: 'yarn'});- expect(result).toContain('yarn astryx component <Name>');- expect(result).toContain('yarn astryx upgrade --apply');- expect(result).toContain('after @astryxdesign/core bump, always run yarn astryx upgrade --apply');+ expect(result).toContain('yarn astryx <cmd>');expect(result).not.toContain('npx astryx');});it('uses pnpm exec prefix', () => {const result = generateCompressedIndex('1.0.0', {runPrefix: 'pnpm exec'});- expect(result).toContain('pnpm exec astryx component <Name>');+ expect(result).toContain('pnpm exec astryx <cmd>');expect(result).not.toContain('npx astryx');});});+describe('detectStylingSystem', () => {+ function writePkg(deps) {+ fs.writeFileSync(+ path.join(tmpDir, 'package.json'),+ JSON.stringify({name: 'x', devDependencies: deps}),+ );+ }++ it('defaults to css when no package.json', () => {+ expect(detectStylingSystem(tmpDir)).toBe('css');+ });++ it('returns css for a plain project', () => {+ writePkg({react: '19.0.0', vite: '6.0.0'});+ expect(detectStylingSystem(tmpDir)).toBe('css');+ });++ it('detects stylex when the compiler plugin is present', () => {+ writePkg({'@stylexjs/babel-plugin': '0.0.1'});+ expect(detectStylingSystem(tmpDir)).toBe('stylex');+ });++ it('detects tailwind when tailwindcss is present', () => {+ writePkg({tailwindcss: '4.0.0'});+ expect(detectStylingSystem(tmpDir)).toBe('tailwind');+ });++ it('does NOT treat the StyleX runtime alone as a compiler', () => {+ // Only the runtime, no compiler plugin → must stay on the safe css path.+ writePkg({'@stylexjs/stylex': '0.0.1'});+ expect(detectStylingSystem(tmpDir)).toBe('css');+ });++ it('prefers stylex over tailwind when both are configured', () => {+ writePkg({'@stylexjs/babel-plugin': '0.0.1', tailwindcss: '4.0.0'});+ expect(detectStylingSystem(tmpDir)).toBe('stylex');+ });+});+describe('getXdsVersion', () => {it('reads version from core package.json', () => {const coreDir = path.join(tmpDir, 'core');