@agent-scope/cli 1.19.0 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -191,13 +191,15 @@ function buildTable(headers, rows) {
191
191
  }
192
192
  function formatListTable(rows) {
193
193
  if (rows.length === 0) return "No components found.";
194
- const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS"];
194
+ const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS", "COLLECTION", "INTERNAL"];
195
195
  const tableRows = rows.map((r) => [
196
196
  r.name,
197
197
  r.file,
198
198
  r.complexityClass,
199
199
  String(r.hookCount),
200
- String(r.contextCount)
200
+ String(r.contextCount),
201
+ r.collection ?? "\u2014",
202
+ r.internal ? "yes" : "no"
201
203
  ]);
202
204
  return buildTable(headers, tableRows);
203
205
  }
@@ -228,6 +230,8 @@ function formatGetTable(name, descriptor) {
228
230
  ` Composes: ${descriptor.composes.join(", ") || "none"}`,
229
231
  ` Composed By: ${descriptor.composedBy.join(", ") || "none"}`,
230
232
  ` Side Effects: ${formatSideEffects(descriptor.sideEffects)}`,
233
+ ` Collection: ${descriptor.collection ?? "\u2014"}`,
234
+ ` Internal: ${descriptor.internal}`,
231
235
  "",
232
236
  ` Props (${propNames.length}):`
233
237
  ];
@@ -250,8 +254,16 @@ function formatGetJson(name, descriptor) {
250
254
  }
251
255
  function formatQueryTable(rows, queryDesc) {
252
256
  if (rows.length === 0) return `No components match: ${queryDesc}`;
253
- const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS"];
254
- const tableRows = rows.map((r) => [r.name, r.file, r.complexityClass, r.hooks, r.contexts]);
257
+ const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS", "COLLECTION", "INTERNAL"];
258
+ const tableRows = rows.map((r) => [
259
+ r.name,
260
+ r.file,
261
+ r.complexityClass,
262
+ r.hooks,
263
+ r.contexts,
264
+ r.collection ?? "\u2014",
265
+ r.internal ? "yes" : "no"
266
+ ]);
255
267
  return `Query: ${queryDesc}
256
268
 
257
269
  ${buildTable(headers, tableRows)}`;
@@ -970,7 +982,7 @@ function parseChecks(raw) {
970
982
  }
971
983
  function createCiCommand() {
972
984
  return new commander.Command("ci").description(
973
- "Run a non-interactive CI pipeline (manifest -> render -> compliance -> regression) with exit codes"
985
+ "Run the full Scope pipeline non-interactively and exit with a structured code.\n\nPIPELINE STEPS (in order):\n 1. manifest generate scan source, build .reactscope/manifest.json\n 2. render all screenshot every component\n 3. tokens compliance score on-token CSS coverage\n 4. visual regression pixel diff against --baseline (if provided)\n\nCHECKS (--checks flag, comma-separated):\n compliance token coverage below --threshold \u2192 exit 1\n a11y accessibility violations \u2192 exit 2\n console-errors console.error during render \u2192 exit 3\n visual-regression pixel diff against baseline \u2192 exit 4\n (render failures always \u2192 exit 5 regardless of --checks)\n\nEXIT CODES:\n 0 all checks passed\n 1 compliance below threshold\n 2 accessibility violations\n 3 console errors during render\n 4 visual regression detected\n 5 component render failures\n\nExamples:\n scope ci\n scope ci --baseline .reactscope/baseline --threshold 0.95\n scope ci --checks compliance,a11y --json -o ci-result.json\n scope ci --viewport 1280x720"
974
986
  ).option(
975
987
  "-b, --baseline <dir>",
976
988
  "Baseline directory for visual regression comparison (omit to skip)"
@@ -1127,7 +1139,25 @@ function formatCheck(check) {
1127
1139
  return ` [${ICONS[check.status]}] ${check.name.padEnd(12)} ${check.message}`;
1128
1140
  }
1129
1141
  function createDoctorCommand() {
1130
- return new commander.Command("doctor").description("Check the health of your Scope setup (config, tokens, CSS, manifest)").option("--json", "Emit structured JSON output", false).action((opts) => {
1142
+ return new commander.Command("doctor").description(
1143
+ `Verify your Scope project setup before running other commands.
1144
+
1145
+ CHECKS PERFORMED:
1146
+ config reactscope.config.json exists and is valid JSON
1147
+ tokens reactscope.tokens.json exists and passes validation
1148
+ css globalCSS files referenced in config actually exist
1149
+ manifest .reactscope/manifest.json exists and is not stale
1150
+ (stale = source files modified after last generate)
1151
+
1152
+ STATUS LEVELS: ok | warn | error
1153
+
1154
+ Run this first whenever renders fail or produce unexpected output.
1155
+
1156
+ Examples:
1157
+ scope doctor
1158
+ scope doctor --json
1159
+ scope doctor --json | jq '.checks[] | select(.status == "error")'`
1160
+ ).option("--json", "Emit structured JSON output", false).action((opts) => {
1131
1161
  const cwd = process.cwd();
1132
1162
  const checks = [
1133
1163
  checkConfig(cwd),
@@ -1164,6 +1194,23 @@ function createDoctorCommand() {
1164
1194
  }
1165
1195
  });
1166
1196
  }
1197
+
1198
+ // src/skill-content.ts
1199
+ var SKILL_CONTENT = '# Scope \u2014 Agent Skill\n\n## TLDR\nScope is a React codebase introspection toolkit. Use it to answer questions about component structure, props, context dependencies, side effects, and visual output \u2014 without running the app.\n\n**When to reach for it:** Any task requiring "which components use X", "what props does Y accept", "render Z for visual verification", "does this component depend on a provider", or "what design tokens are in use".\n\n**3-command workflow:**\n```\nscope init # scaffold config + auto-generate manifest\nscope manifest query --context ThemeContext # ask questions about the codebase\nscope render Button # produce a PNG of a component\n```\n\n---\n\n---\n\n## Mental Model\n\nUnderstanding how Scope\'s data flows is the key to using it effectively as an agent.\n\n```\nSource TypeScript files\n \u2193 (ts-morph AST parse)\n manifest.json \u2190 structural facts: props, hooks, contexts, complexity\n \u2193 (esbuild + Playwright)\n renders/*.json \u2190 visual facts: screenshot, computedStyles, dom, a11y\n \u2193 (token engine)\n compliance-styles.json \u2190 audit facts: which CSS values match tokens, which don\'t\n \u2193 (site generator)\n site/ \u2190 human-readable docs combining all of the above\n```\n\nEach layer depends on the previous. If you\'re getting unexpected results, check whether the earlier layers are stale (run `scope doctor` to diagnose).\n\n---\n\n## The Four Subsystems\n\n### 1. Manifest (`scope manifest *`)\nThe manifest is a static analysis snapshot of your TypeScript source. It tells you:\n- What components exist, where they live, and how they\'re exported\n- What props each component accepts (types, defaults, required/optional)\n- What React hooks they call (`detectedHooks`)\n- What contexts they consume (`requiredContexts`) \u2014 must be provided for a render to succeed\n- Whether they compose other components (`composes` / `composedBy`)\n- Their **complexity class** \u2014 `"simple"` or `"complex"` \u2014 which determines the render engine\n\nThe manifest never runs your code. It only reads TypeScript. This means it\'s fast and safe, but it can\'t know about runtime values.\n\n### 2. Render Engine (`scope render *`)\nThe render engine compiles components with esbuild and renders them in Chromium (Playwright). Two paths exist:\n\n| Path | When | Speed | Capability |\n|------|------|-------|------------|\n| **Satori** | `complexityClass: "simple"` | ~8ms | Flexbox only, no JS, no CSS-in-JS |\n| **BrowserPool** | `complexityClass: "complex"` | ~200\u2013800ms | Full DOM, CSS, Tailwind, animations |\n\nMost real-world components route through BrowserPool. Scope defaults to `"complex"` when uncertain (safe fallback).\n\nEach render produces:\n- `screenshot` \u2014 retina-quality PNG (2\xD7 `deviceScaleFactor`; display at CSS px dimensions)\n- `width` / `height` \u2014 CSS pixel dimensions of the component root\n- `computedStyles` \u2014 per-node computed CSS keyed by `#node-0`, `#node-1`, etc.\n- `dom` \u2014 full DOM tree with bounding boxes (BrowserPool only)\n- `accessibility` \u2014 role, aria-name, violation list (BrowserPool only)\n- `renderTimeMs` \u2014 wall-clock render duration\n\n### 3. Scope Files (`.scope.tsx`)\nScope files let you define **named rendering scenarios** for a component alongside it in the source tree. They are the primary way to ensure `render all` produces meaningful screenshots.\n\n```tsx\n// Button.scope.tsx\nimport type { ScopeFile } from \'@agent-scope/cli\';\nimport { Button } from \'./Button\';\n\nexport default {\n default: { variant: \'primary\', children: \'Click me\' },\n ghost: { variant: \'ghost\', children: \'Cancel\' },\n danger: { variant: \'danger\', children: \'Delete\' },\n disabled: { variant: \'primary\', children: \'Disabled\', disabled: true },\n} satisfies ScopeFile<typeof Button>;\n```\n\nKey rules:\n- The file must be named `<ComponentName>.scope.tsx` in the same directory\n- Export a default object where keys are scenario names and values are props\n- `render all` uses the `default` scenario (or first defined) as the primary screenshot\n- If 2+ scenarios exist, `render all` automatically runs a matrix and merges cells into the component JSON\n- Scenarios also feed the interactive Playground in the docs site\n\nWhen a component renders blank with `{}` props, **the fix is usually to create a `.scope.tsx` file** with real props.\n\n### 4. Token Compliance\nThe compliance pipeline:\n1. `scope render all` captures `computedStyles` for every element in every component\n2. These are written to `.reactscope/compliance-styles.json`\n3. The token engine compares each computed CSS value against your `reactscope.tokens.json`\n4. `scope tokens compliance` reports the aggregate on-system percentage\n5. `scope ci` fails if the percentage is below `complianceThreshold` (default 90%)\n\n**On-system** means the value exactly matches a resolved token value. Off-system means it\'s a hardcoded value with no token backing it.\n\n---\n\n## Complexity Classes \u2014 Practical Guide\n\nThe `complexityClass` field determines which render engine runs. Scope auto-detects it, but agents should understand it:\n\n**`"simple"` components:**\n- Pure presentational, flexbox layout only\n- No CSS grid, no absolute/fixed/sticky positioning\n- No CSS animations, transitions, or transforms\n- No `className` values Scope can\'t statically trace (e.g. dynamic Tailwind classes)\n- Renders in ~8ms via Satori (SVG-based, no browser needed)\n\n**`"complex"` components:**\n- Anything using Tailwind (CSS injection required)\n- CSS grid, positioned elements, overflow, z-index\n- Components that read from context at render time\n- Any component Scope isn\'t sure about (conservative default)\n- Renders in ~200\u2013800ms via Playwright BrowserPool\n\nWhen in doubt: complex is always safe. Simple is an optimization.\n\n---\n\n## Required Contexts \u2014 Why Renders Fail\n\nIf `requiredContexts` is non-empty, the component calls `useContext` on one or more contexts. Without a provider, it will either render broken or throw entirely.\n\nTwo ways to fix:\n1. **Provider presets in config** (recommended): add provider names to `reactscope.config.json \u2192 components.wrappers.providers`\n2. **Scope file with wrapper**: wrap the component in a provider in the scenario itself\n\nBuilt-in mocks (always provided): `ThemeContext \u2192 { theme: \'light\' }`, `LocaleContext \u2192 { locale: \'en-US\' }`.\n\n---\n\n## `scope doctor` \u2014 Always Run This First\n\nBefore debugging any render issue, run:\n```bash\nscope doctor\n```\n\nIt checks:\n- `reactscope.config.json` is valid JSON\n- Token file exists and has a `version` field\n- Every path in `globalCSS` resolves on disk\n- Manifest is present and up to date (not stale relative to source)\n\n**If `globalCSS` is empty or missing**: Tailwind styles won\'t apply to renders. Every component will look unstyled. This is the most common footgun. Fix: add your CSS entry file (the one with `@tailwind base; @tailwind components; @tailwind utilities;`) to `globalCSS` in config.\n\n---\n\n## Agent Decision Tree\n\n**"I want to know what props Component X accepts"**\n\u2192 `scope manifest get X --format json | jq \'.props\'`\n\n**"I want to know which components will break if I change a context"**\n\u2192 `scope manifest query --context MyContext --format json`\n\n**"I want to render a component to verify visual output"**\n\u2192 Create a `.scope.tsx` file with real props first, then `scope render X`\n\n**"I want to render all variants of a component"**\n\u2192 Define all variants in `.scope.tsx`, then `scope render all` (auto-matrix)\n\u2192 Or: `scope render matrix X --axes \'variant:primary,secondary,danger\'`\n\n**"I want to audit token compliance"**\n\u2192 `scope render all` first (populates computedStyles), then `scope tokens compliance`\n\n**"Renders look unstyled / blank"**\n\u2192 Run `scope doctor` \u2014 likely missing `globalCSS`\n\u2192 If props are the issue: create/update the `.scope.tsx` file\n\n**"I want to understand blast radius of a token change"**\n\u2192 `scope tokens impact color.primary.500 --new-value \'#0077dd\'`\n\u2192 `scope tokens preview color.primary.500 --new-value \'#0077dd\'` for visual diff\n\n**"I need to set up Scope in a new project"**\n\u2192 `scope init --yes` (auto-detects Tailwind + CSS, generates manifest automatically)\n\u2192 `scope doctor` to validate\n\u2192 Create `.scope.tsx` files for key components\n\u2192 `scope render all`\n\n**"I want to run Scope in CI"**\n\u2192 `scope ci --json --output ci-result.json`\n\u2192 Exit code 0 = pass, non-zero = specific failure type\n\n---\n\n\n## Installation\n\n```bash\nnpm install -g @agent-scope/cli # global\nnpm install --save-dev @agent-scope/cli # per-project\n```\n\nBinary: `scope`\n\n---\n\n## Core Workflow\n\n```\ninit \u2192 manifest generate \u2192 manifest query/get/list \u2192 render \u2192 (token audit) \u2192 ci\n```\n\n- **init**: Scaffold `reactscope.config.json` + token stub, auto-detect framework/globalCSS, **immediately runs `manifest generate`** so you see results right away.\n- **doctor**: Health-check command \u2014 validates config, token file, globalCSS presence, and manifest staleness.\n- **generate**: Parse TypeScript AST and emit `.reactscope/manifest.json`. Run once per codebase change (or automatically via `scope init`).\n- **query / get / list**: Ask structural questions. No network required. Works from manifest alone. Supports filtering by `--collection` and `--internal`.\n- **render**: Produce PNGs of components via esbuild + Playwright (BrowserPool). Requires manifest for file paths. Auto-injects required prop defaults and globalCSS.\n- **token audit**: Validate design tokens via `@scope/tokens` CLI commands (`tokens list`, `tokens compliance`, `tokens impact`, `tokens preview`, `tokens export`).\n- **ci**: Run compliance checks and exit with code 0/1 for CI pipelines. `report pr-comment` posts results to GitHub PRs.\n\n---\n\n## Full CLI Reference\n\n### `scope init`\nScaffold config, detect framework, extract Tailwind tokens, detect globalCSS files, and **automatically run `scope manifest generate`**.\n\n```bash\nscope init\nscope init --force # overwrite existing config\n```\n\nAfter init completes, the manifest is already written \u2014 no manual `scope manifest generate` step needed.\n\n**Tailwind token extraction**: reads `tailwind.config.js`, extracts colors (with nested scale support), spacing, fontFamily, borderRadius. Stored in `reactscope.tokens.json`.\n\n**globalCSS detection**: checks 9 common patterns (`src/styles.css`, `src/index.css`, `app/globals.css`, etc.). Stored in `components.wrappers.globalCSS` in config.\n\n---\n\n### `scope doctor`\nValidate the Scope setup. Exits non-zero on errors, zero on warnings-only.\n\n```bash\nscope doctor\nscope doctor --json\n```\n\nChecks:\n- `config` \u2014 `reactscope.config.json` is valid JSON with required fields\n- `tokens` \u2014 token file is present and has a valid `version` field\n- `globalCSS` \u2014 globalCSS files listed in config exist on disk\n- `manifest` \u2014 manifest exists and is not stale (compares source file mtimes)\n\n```\n$ scope doctor\nScope Doctor\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n [\u2713] config reactscope.config.json valid\n [\u2713] tokens Token file valid\n [\u2713] globalCSS 1 globalCSS file(s) present\n [!] manifest Manifest may be stale \u2014 5 source file(s) modified since last generate\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n 1 warning(s) \u2014 everything works but could be better\n```\n\n---\n\n### `scope capture <url>`\nCapture a live React component tree from a running app URL.\n\n```bash\nscope capture http://localhost:3000\nscope capture http://localhost:3000 --output report.json --pretty\nscope capture http://localhost:3000 --timeout 15000 --wait 2000\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `-o, --output <path>` | string | stdout | Write JSON to file |\n| `--pretty` | bool | false | Pretty-print JSON |\n| `--timeout <ms>` | number | 10000 | Max wait for React to mount |\n| `--wait <ms>` | number | 0 | Additional wait after page load |\n\nOutput (stdout): serialized PageReport JSON (or path when `--output` is set)\n\n---\n\n### `scope tree <url>`\nPrint the React component tree from a live URL.\n\n```bash\nscope tree http://localhost:3000\nscope tree http://localhost:3000 --depth 3 --show-props --show-hooks\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--depth <n>` | number | unlimited | Max depth to display |\n| `--show-props` | bool | false | Include prop names next to components |\n| `--show-hooks` | bool | false | Show hook counts per component |\n| `--timeout <ms>` | number | 10000 | Max wait for React to mount |\n| `--wait <ms>` | number | 0 | Additional wait after page load |\n\n---\n\n### `scope report <url>`\nCapture and print a human-readable summary of a React app.\n\n```bash\nscope report http://localhost:3000\nscope report http://localhost:3000 --json\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--json` | bool | false | Emit structured JSON instead of text |\n| `--timeout <ms>` | number | 10000 | Max wait for React to mount |\n| `--wait <ms>` | number | 0 | Additional wait after page load |\n\n---\n\n### `scope report baseline`\nSave a baseline snapshot for future diff comparisons.\n\n```bash\nscope report baseline\nscope report baseline --output baselines/my-baseline.json\n```\n\n---\n\n### `scope report diff`\nDiff the current app state against a saved baseline.\n\n```bash\nscope report diff\nscope report diff --baseline baselines/my-baseline.json\nscope report diff --json\n```\n\n---\n\n### `scope report pr-comment`\nPost a Scope CI report as a GitHub PR comment. Used in CI pipelines via the reusable `scope-ci` workflow.\n\n```bash\nscope report pr-comment --report-path scope-ci-report.json\n```\n\nRequires `GITHUB_TOKEN`, `GITHUB_REPOSITORY`, and `GITHUB_PR_NUMBER` in environment.\n\n---\n\n### `scope manifest generate`\nScan source files and write `.reactscope/manifest.json`.\n\n```bash\nscope manifest generate\nscope manifest generate --root ./packages/ui\nscope manifest generate --include "src/**/*.tsx" --exclude "**/*.test.tsx"\nscope manifest generate --output custom/manifest.json\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--root <path>` | string | cwd | Project root directory |\n| `--output <path>` | string | `.reactscope/manifest.json` | Output path |\n| `--include <globs>` | string | `src/**/*.tsx,src/**/*.ts` | Comma-separated include globs |\n| `--exclude <globs>` | string | `**/node_modules/**,...` | Comma-separated exclude globs |\n\n---\n\n### `scope manifest list`\nList all components in the manifest.\n\n```bash\nscope manifest list\nscope manifest list --filter "Button*"\nscope manifest list --format json\nscope manifest list --collection Forms # filter to named collection\nscope manifest list --internal # only internal components\nscope manifest list --no-internal # hide internal components\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--format <fmt>` | `json\\|table` | auto (TTY\u2192table, pipe\u2192json) | Output format |\n| `--filter <glob>` | string | \u2014 | Filter component names by glob |\n| `--collection <name>` | string | \u2014 | Filter to named collection |\n| `--internal` | bool | false | Show only internal components |\n| `--no-internal` | bool | false | Hide internal components |\n| `--manifest <path>` | string | `.reactscope/manifest.json` | Manifest path |\n\nTTY table output (includes COLLECTION and INTERNAL columns):\n```\nNAME FILE COMPLEXITY HOOKS CONTEXTS COLLECTION INTERNAL\n------------ --------------------------- ---------- ----- -------- ---------- --------\nButton src/components/Button.tsx simple 1 0 \u2014 no\nThemeToggle src/components/Toggle.tsx complex 3 1 Forms no\n```\n\n---\n\n### `scope manifest get <name>`\nGet full details of a single component.\n\n```bash\nscope manifest get Button\nscope manifest get Button --format json\n```\n\nJSON output includes `collection` and `internal` fields:\n```json\n{\n "name": "Button",\n "filePath": "src/components/Button.tsx",\n "collection": "Primitives",\n "internal": false,\n ...\n}\n```\n\n---\n\n### `scope manifest query`\nQuery components by attributes.\n\n```bash\nscope manifest query --context ThemeContext\nscope manifest query --hook useEffect\nscope manifest query --complexity complex\nscope manifest query --side-effects\nscope manifest query --has-fetch\nscope manifest query --has-prop <propName>\nscope manifest query --composed-by <ComponentName>\nscope manifest query --internal\nscope manifest query --collection Forms\nscope manifest query --context ThemeContext --format json\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--context <name>` | string | \u2014 | Find components consuming a context by name |\n| `--hook <name>` | string | \u2014 | Find components using a specific hook |\n| `--complexity <class>` | `simple\\|complex` | \u2014 | Filter by complexity class |\n| `--side-effects` | bool | false | Any side effects detected |\n| `--has-fetch` | bool | false | Components with fetch calls specifically |\n| `--has-prop <name>` | string | \u2014 | Components that accept a specific prop |\n| `--composed-by <name>` | string | \u2014 | Components rendered inside a specific parent |\n| `--internal` | bool | false | Only internal components |\n| `--collection <name>` | string | \u2014 | Filter to named collection |\n| `--format <fmt>` | `json\\|table` | auto | Output format |\n| `--manifest <path>` | string | `.reactscope/manifest.json` | Manifest path |\n\n---\n\n### `scope render <component>`\nRender a single component to PNG (TTY) or JSON (pipe).\n\n**Auto prop defaults**: if `--props` is omitted, Scope injects sensible defaults so required props don\'t produce blank renders: strings/nodes \u2192 component name, unions \u2192 first value, booleans \u2192 `false`, numbers \u2192 `0`.\n\n**globalCSS auto-injection**: reads `components.wrappers.globalCSS` from config and compiles/injects CSS (supports Tailwind v3 via PostCSS) into the render harness. A warning is printed to stderr if no globalCSS is configured (common cause of unstyled renders).\n\n```bash\nscope render Button\nscope render Button --props \'{"variant":"primary","children":"Click me"}\'\nscope render Button --viewport 375x812\nscope render Button --output button.png\nscope render Button --format json\n```\n\nFlags:\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n| `--props <json>` | string | `{}` | Inline props as JSON string |\n| `--viewport <WxH>` | string | `375x812` | Viewport size |\n| `--theme <name>` | string | \u2014 | Theme name from token system |\n| `-o, --output <path>` | string | \u2014 | Write PNG to specific path |\n| `--format <fmt>` | `png\\|json` | auto (TTY\u2192file, pipe\u2192json) | Output format |\n| `--manifest <path>` | string | `.reactscope/manifest.json` | Manifest path |\n\n---\n\n### `scope render matrix <component>`\nRender across a Cartesian product of prop axes. Accepts both `key:v1,v2` and `{"key":["v1","v2"]}` JSON format for `--axes`.\n\n```bash\nscope render matrix Button --axes \'variant:primary,secondary,danger\'\nscope render matrix Button --axes \'{"variant":["primary","secondary"]}\'\nscope render matrix Button --axes \'variant:primary,secondary size:sm,md,lg\'\nscope render matrix Button --sprite button-matrix.png --format json\n```\n\n---\n\n### `scope render all`\nRender every component in the manifest.\n\n```bash\nscope render all\nscope render all --concurrency 4 --output-dir renders/\n```\n\nHandles imports of CSS files in components (maps to empty loader so styles are injected at page level). SVG and font imports are handled via dataurl loaders.\n\n---\n\n### `scope instrument tree`\nCapture the live React component tree with instrumentation metadata.\n\n```bash\nscope instrument tree http://localhost:3000\nscope instrument tree http://localhost:3000 --depth 5 --show-props\n```\n\n**Implementation note**: uses a fresh `chromium.launch()` + `newContext()` + `newPage()` per call (not BrowserPool), with `addInitScript` called before `setContent` to ensure the Scope runtime is injected at document-start before React loads.\n\n---\n\n### `scope instrument hooks`\nProfile hook execution in live components.\n\n```bash\nscope instrument hooks http://localhost:3000\nscope instrument hooks http://localhost:3000 --component Button\n```\n\n**Implementation note**: requires `addInitScript({ content: getBrowserEntryScript() })` before `setContent` so `__REACT_DEVTOOLS_GLOBAL_HOOK__` is present when React loads its renderer.\n\n---\n\n### `scope instrument profile`\nProfile render performance of live components.\n\n```bash\nscope instrument profile http://localhost:3000\n```\n\n---\n\n### `scope instrument renders`\nRe-render causality analysis \u2014 what triggered each render.\n\n```bash\nscope instrument renders http://localhost:3000\n```\n\n---\n\n### `scope tokens get <name>`\nGet details of a single design token.\n\n### `scope tokens list`\nList all tokens. Token file must have a `version` field (written by `scope init`).\n\n```bash\nscope tokens list\nscope tokens list --type color\nscope tokens list --format json\n```\n\n### `scope tokens search <query>`\nFull-text search across token names/values.\n\n### `scope tokens resolve <value>`\nResolve a CSS value or alias back to its token name.\n\n### `scope tokens validate`\nValidate token file schema.\n\n### `scope tokens compliance`\nCheck rendered components for design token compliance.\n\n```bash\nscope tokens compliance\nscope tokens compliance --threshold 95\n```\n\n### `scope tokens impact <token>`\nAnalyze impact of changing a token \u2014 which components use it.\n\n```bash\nscope tokens impact --token color.primary.500\n```\n\n### `scope tokens preview <token>`\nPreview a token value change visually before committing.\n\n### `scope tokens export`\nExport tokens in multiple formats.\n\n```bash\nscope tokens export --format flat-json\nscope tokens export --format css\nscope tokens export --format scss\nscope tokens export --format ts\nscope tokens export --format tailwind\nscope tokens export --format style-dictionary\n```\n\n**Format aliases** (auto-corrected with "Did you mean?" hint):\n- `json` \u2192 `flat-json`\n- `js` \u2192 `ts`\n- `sass` \u2192 `scss`\n- `tw` \u2192 `tailwind`\n\n---\n\n### `scope ci`\nRun all CI checks (compliance, accessibility, console errors) and exit 0/1.\n\n```bash\nscope ci\nscope ci --json\nscope ci --threshold 90 # compliance threshold (default: 90)\n```\n\n```\n$ scope ci --json\n\u2192 CI passed in 3.2s\n\u2192 Compliance 100.0% >= threshold 90.0% \u2705\n\u2192 Accessibility audit not yet implemented \u2014 skipped \u2705\n\u2192 No console errors detected \u2705\n\u2192 Exit code 0\n```\n\nThe `scope-ci` **reusable GitHub Actions workflow** is available at `.github/workflows/scope-ci.yml` and can be included in any repo\'s CI to run `scope ci` and post results as a PR comment via `scope report pr-comment`.\n\n---\n\n### `scope site build`\nGenerate a static HTML component gallery site from the manifest.\n\n```bash\nscope site build\nscope site build --output ./dist/site\n```\n\n**Collections support**: components are grouped under named collection sections in the sidebar and index grid. Internal components are hidden from the sidebar and card grid but appear in composition detail sections with an `internal` badge.\n\n**Collection display rules**:\n- Sidebar: one section divider per collection + an "Ungrouped" section; internal components excluded\n- Index page: named sections with heading + optional description; internal components excluded\n- Component detail page: Composes/Composed By lists ALL components including internal ones (with subtle badge)\n- Falls back to flat list when no collections configured (backwards-compatible)\n\n### `scope site serve`\nServe the generated site locally.\n\n```bash\nscope site serve\nscope site serve --port 4000\n```\n\n---\n\n## Collections & Internal Components\n\nComponents can be organized into named **collections** and flagged as **internal** (library implementation details not shown in the public gallery).\n\n### Defining collections\n\n**1. TSDoc tag** (highest precedence):\n```tsx\n/**\n * @collection Forms\n */\nexport function Input() { ... }\n```\n\n**2. `.scope.ts` co-located file**:\n```ts\n// Input.scope.ts\nexport const collection = "Forms"\n```\n\n**3. Config-level glob patterns**:\n```json\n// reactscope.config.json\n{\n "collections": [\n { "name": "Forms", "description": "Form inputs and controls", "patterns": ["src/forms/**"] },\n { "name": "Primitives", "patterns": ["src/primitives/**"] }\n ]\n}\n```\n\nResolution precedence: TSDoc `@collection` > `.scope.ts` export > config pattern.\n\n### Flagging internal components\n\n**TSDoc tag**:\n```tsx\n/**\n * @internal\n */\nexport function InternalHelperButton() { ... }\n```\n\n**Config glob patterns**:\n```json\n{\n "internalPatterns": ["src/internal/**", "src/**/*Internal*"]\n}\n```\n\n---\n\n## Manifest Output Schema\n\nFile: `.reactscope/manifest.json`\n\n```typescript\n{\n version: "0.1",\n generatedAt: string, // ISO 8601\n collections: CollectionConfig[], // echoes config.collections, [] when not set\n components: Record<string, ComponentDescriptor>,\n tree: Record<string, { children: string[], parents: string[] }>\n}\n```\n\n### `ComponentDescriptor` fields\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `filePath` | `string` | Relative path from project root to source file |\n| `exportType` | `"named" \\| "default" \\| "none"` | How the component is exported |\n| `displayName` | `string` | `displayName` if set, else function/class name |\n| `collection` | `string?` | Resolved collection name (`undefined` = ungrouped) |\n| `internal` | `boolean` | `true` if flagged as internal (default: `false`) |\n| `props` | `Record<string, PropDescriptor>` | Extracted prop types keyed by prop name |\n| `composes` | `string[]` | Components this one renders in its JSX |\n| `composedBy` | `string[]` | Components that render this one in their JSX |\n| `complexityClass` | `"simple" \\| "complex"` | Render path: simple = Satori-safe, complex = requires BrowserPool |\n| `requiredContexts` | `string[]` | React context names consumed |\n| `detectedHooks` | `string[]` | All hooks called, sorted alphabetically |\n| `sideEffects` | `SideEffects` | Side effect categories detected |\n| `memoized` | `boolean` | Wrapped with `React.memo` |\n| `forwardedRef` | `boolean` | Wrapped with `React.forwardRef` |\n| `hocWrappers` | `string[]` | HOC wrapper names (excluding memo/forwardRef) |\n| `loc` | `{ start: number, end: number }` | Line numbers in source file |\n\n---\n\n## Common Agent Workflows\n\n### Structural queries\n\n```bash\n# Which components use ThemeContext?\nscope manifest query --context ThemeContext\n\n# What props does Button accept?\nscope manifest get Button --format json | jq \'.props\'\n\n# Which components are safe to render without a provider?\nscope manifest query --complexity simple # + check requiredContexts === []\n\n# Show all components with side effects\nscope manifest query --side-effects\n\n# Which components make fetch calls?\nscope manifest query --has-fetch\n\n# Which components use useEffect?\nscope manifest query --hook useEffect\n\n# Which components accept a disabled prop?\nscope manifest query --has-prop disabled\n\n# Which components are composed inside Modal?\nscope manifest query --composed-by Modal\n\n# All components in the Forms collection\nscope manifest list --collection Forms\n\n# All internal components (library implementation details)\nscope manifest list --internal\n\n# Public components only (hide internals)\nscope manifest list --no-internal\n```\n\n### Render workflows\n\n```bash\n# Render Button in all variants (auto-defaults props if not provided)\nscope render matrix Button --axes \'variant:primary,secondary,danger\'\n\n# Render with JSON axes format\nscope render matrix Button --axes \'{"variant":["primary","secondary"]}\'\n\n# Render with explicit props\nscope render Button --props \'{"variant":"primary","disabled":true}\'\n\n# Render all components (handles CSS/SVG/font imports automatically)\nscope render all --concurrency 8\n\n# Get render as JSON\nscope render Button --format json | jq \'.screenshot\' | base64 -d > button.png\n```\n\n### Token workflows\n\n```bash\n# List all tokens\nscope tokens list\n\n# Check compliance\nscope tokens compliance --threshold 95\n\n# See what a token change impacts\nscope tokens impact --token color.primary.500\n\n# Export for Tailwind\nscope tokens export --format tailwind\n```\n\n### CI workflow\n\n```bash\n# Full compliance check\nscope ci --json\n\n# In GitHub Actions \u2014 use the reusable workflow\n# .github/workflows/ci.yml:\n# uses: FlatFilers/Scope/.github/workflows/scope-ci.yml@main\n```\n\n---\n\n## Error Patterns\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| `"React root not found"` | App not running, wrong URL, or Vite HMR interfering | Use `scope capture --wait 2000` |\n| `"Component not in manifest"` | Manifest is stale | Run `scope manifest generate` first |\n| `"Manifest not found"` | Missing manifest | Run `scope init` or `scope manifest generate` |\n| `"requiredContexts missing"` | Component needs a provider | Add provider presets to `reactscope.config.json` |\n| Blank PNG / 16\xD76px renders | No globalCSS injected (common with Tailwind) | Set `components.wrappers.globalCSS` in config; run `scope doctor` to verify |\n| `"Invalid props JSON"` | Malformed JSON in `--props` | Use single outer quotes: `--props \'{"key":"val"}\'` |\n| `"SCOPE_CAPTURE_JSON not available"` | Scope runtime not injected before React loaded | Fixed in PR #83 \u2014 update CLI |\n| `"No React DevTools hook found"` | Hook instrumentation init order bug | Fixed in PR #83 \u2014 update CLI |\n| `"ERR_MODULE_NOT_FOUND"` after tokens commands | Old Node shebang in CLI binary | Fixed in PR #90 \u2014 CLI now uses `#!/usr/bin/env bun` |\n| `"version" field missing in tokens` | Token stub written by old `scope init` | Re-run `scope init --force` or add `"version": "1"` to token file |\n| `"unknown option --has-prop"` | Old CLI version | Fixed in PR #90 \u2014 update CLI |\n| Format alias error (`json`, `js`, `sass`, `tw`) | Wrong format name for `tokens export` | Use `flat-json`, `ts`, `scss`, `tailwind`; CLI shows "Did you mean?" hint |\n\n---\n\n## `reactscope.config.json`\n\n```json\n{\n "components": {\n "wrappers": {\n "globalCSS": ["src/styles.css"]\n }\n },\n "tokens": {\n "file": "reactscope.tokens.json"\n },\n "collections": [\n { "name": "Forms", "description": "Form inputs and controls", "patterns": ["src/forms/**"] },\n { "name": "Primitives", "patterns": ["src/primitives/**"] }\n ],\n "internalPatterns": ["src/internal/**"],\n "providers": {\n "theme": { "component": "ThemeProvider", "props": { "theme": "light" } },\n "router": { "component": "MemoryRouter", "props": { "initialEntries": ["/"] } }\n }\n}\n```\n\n**Built-in mock providers** (always available, no config needed):\n- `ThemeContext` \u2192 `{ theme: \'light\' }` (or `--theme <name>`)\n- `LocaleContext` \u2192 `{ locale: \'en-US\' }`\n\n---\n\n## What Scope Cannot Do\n\n- **Runtime state**: `useState` values after user interaction\n- **Network requests**: `fetch`, `XHR`, `WebSocket`\n- **User interactions**: click, type, hover, drag\n- **Auth/session-gated components**: components that redirect or throw without a session\n- **Server components (RSC)**: React Server Components\n- **Dynamic CSS**: CSS-in-JS styles computed at runtime from props Scope can\'t infer\n\n---\n\n## Version History\n\n| Version | Date | Summary |\n|---------|------|---------|\n| v1.0 | 2026-03-11 | Initial SKILL.md (PR #36) \u2014 manifest, render, capture, tree, report, tokens, ci commands |\n| v1.1 | 2026-03-11 | Updated through PR #82 \u2014 Phase 2 CLI commands complete |\n| v1.2 | 2026-03-13 | PRs #83\u2013#95: runtime injection fix, dogfooding fixes (12 bugs), `scope doctor`, `scope init` auto-manifest, globalCSS render warning, collections & internal components feature |\n';
1200
+
1201
+ // src/get-skill-command.ts
1202
+ function createGetSkillCommand() {
1203
+ return new commander.Command("get-skill").description(
1204
+ 'Print the embedded Scope SKILL.md to stdout.\n\nAgents: pipe this command into your context loader to bootstrap Scope knowledge.\nThe skill covers: when to use each command, config requirements, output format,\nrender engine selection, and common failure modes.\n\nEMBEDDED AT BUILD TIME \u2014 works in any install context (global npm, npx, local).\n\nExamples:\n scope get-skill # raw markdown to stdout\n scope get-skill --json # { "skill": "..." } for structured ingestion\n scope get-skill | head -50 # preview the skill\n scope get-skill > /tmp/SKILL.md # save locally'
1205
+ ).option("--json", "Wrap output in JSON { skill: string } instead of raw markdown").action((opts) => {
1206
+ if (opts.json) {
1207
+ process.stdout.write(`${JSON.stringify({ skill: SKILL_CONTENT }, null, 2)}
1208
+ `);
1209
+ } else {
1210
+ process.stdout.write(SKILL_CONTENT);
1211
+ }
1212
+ });
1213
+ }
1167
1214
  function hasConfigFile(dir, stem) {
1168
1215
  if (!fs.existsSync(dir)) return false;
1169
1216
  try {
@@ -1637,7 +1684,9 @@ async function runInit(options) {
1637
1684
  };
1638
1685
  }
1639
1686
  function createInitCommand() {
1640
- return new commander.Command("init").description("Initialise a Scope project \u2014 scaffold reactscope.config.json and friends").option("-y, --yes", "Accept all detected defaults without prompting", false).option("--force", "Overwrite existing reactscope.config.json if present", false).action(async (opts) => {
1687
+ return new commander.Command("init").description(
1688
+ "Auto-detect your project layout and scaffold reactscope.config.json.\n\nWHAT IT DOES:\n - Detects component glob patterns from tsconfig / package.json / directory scan\n - Detects globalCSS files (Tailwind, PostCSS)\n - Writes reactscope.config.json with all detected values\n - Adds .reactscope/ to .gitignore\n - Creates .reactscope/ output directory\n\nCONFIG FIELDS GENERATED:\n components.include glob patterns for component discovery\n components.wrappers providers + globalCSS to inject on every render\n render.viewport default viewport (1280\xD7800)\n tokens.file path to reactscope.tokens.json\n output.dir .reactscope/ (all outputs go here)\n ci.complianceThreshold 0.90 (90% on-token required to pass CI)\n\nSafe to re-run \u2014 will not overwrite existing config unless --force.\n\nExamples:\n scope init\n scope init --yes # accept all detected defaults, no prompts\n scope init --force # overwrite existing config"
1689
+ ).option("-y, --yes", "Accept all detected defaults without prompting", false).option("--force", "Overwrite existing reactscope.config.json if present", false).action(async (opts) => {
1641
1690
  try {
1642
1691
  const result = await runInit({ yes: opts.yes, force: opts.force });
1643
1692
  if (!result.success && !result.skipped) {
@@ -1666,34 +1715,56 @@ function resolveFormat(formatFlag) {
1666
1715
  return isTTY() ? "table" : "json";
1667
1716
  }
1668
1717
  function registerList(manifestCmd) {
1669
- manifestCmd.command("list").description("List all components in the manifest").option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--filter <glob>", "Filter components by name glob pattern").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action((opts) => {
1670
- try {
1671
- const manifest = loadManifest(opts.manifest);
1672
- const format = resolveFormat(opts.format);
1673
- let entries = Object.entries(manifest.components);
1674
- if (opts.filter !== void 0) {
1675
- const filterPattern = opts.filter ?? "";
1676
- entries = entries.filter(([name]) => matchGlob(filterPattern, name));
1677
- }
1678
- const rows = entries.map(([name, descriptor]) => ({
1679
- name,
1680
- file: descriptor.filePath,
1681
- complexityClass: descriptor.complexityClass,
1682
- hookCount: descriptor.detectedHooks.length,
1683
- contextCount: descriptor.requiredContexts.length
1684
- }));
1685
- const output = format === "json" ? formatListJson(rows) : formatListTable(rows);
1686
- process.stdout.write(`${output}
1718
+ manifestCmd.command("list").description(
1719
+ `List all components in the manifest as a table (TTY) or JSON (piped).
1720
+
1721
+ Examples:
1722
+ scope manifest list
1723
+ scope manifest list --format json | jq '.[].name'
1724
+ scope manifest list --filter "Button*"`
1725
+ ).option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--filter <glob>", "Filter components by name glob pattern").option("--collection <name>", "Filter to only components in the named collection").option("--internal", "Show only internal components").option("--no-internal", "Hide internal components from output").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action(
1726
+ (opts) => {
1727
+ try {
1728
+ const manifest = loadManifest(opts.manifest);
1729
+ const format = resolveFormat(opts.format);
1730
+ let entries = Object.entries(manifest.components);
1731
+ if (opts.filter !== void 0) {
1732
+ const filterPattern = opts.filter ?? "";
1733
+ entries = entries.filter(([name]) => matchGlob(filterPattern, name));
1734
+ }
1735
+ if (opts.collection !== void 0) {
1736
+ const col = opts.collection;
1737
+ entries = entries.filter(([, d]) => d.collection === col);
1738
+ }
1739
+ if (opts.internal === true) {
1740
+ entries = entries.filter(([, d]) => d.internal);
1741
+ } else if (opts.internal === false) {
1742
+ entries = entries.filter(([, d]) => !d.internal);
1743
+ }
1744
+ const rows = entries.map(([name, descriptor]) => ({
1745
+ name,
1746
+ file: descriptor.filePath,
1747
+ complexityClass: descriptor.complexityClass,
1748
+ hookCount: descriptor.detectedHooks.length,
1749
+ contextCount: descriptor.requiredContexts.length,
1750
+ collection: descriptor.collection,
1751
+ internal: descriptor.internal
1752
+ }));
1753
+ const output = format === "json" ? formatListJson(rows) : formatListTable(rows);
1754
+ process.stdout.write(`${output}
1687
1755
  `);
1688
- } catch (err) {
1689
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
1756
+ } catch (err) {
1757
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
1690
1758
  `);
1691
- process.exit(1);
1759
+ process.exit(1);
1760
+ }
1692
1761
  }
1693
- });
1762
+ );
1694
1763
  }
1695
1764
  function registerGet(manifestCmd) {
1696
- manifestCmd.command("get <name>").description("Get full details of a single component by name").option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action((name, opts) => {
1765
+ manifestCmd.command("get <name>").description(
1766
+ "Get full details of a single component: props, hooks, complexity class, file path.\n\nExamples:\n scope manifest get Button\n scope manifest get Button --format json\n scope manifest get Button --format json | jq '.complexity'"
1767
+ ).option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action((name, opts) => {
1697
1768
  try {
1698
1769
  const manifest = loadManifest(opts.manifest);
1699
1770
  const format = resolveFormat(opts.format);
@@ -1717,10 +1788,12 @@ Available: ${available}${hint}`
1717
1788
  });
1718
1789
  }
1719
1790
  function registerQuery(manifestCmd) {
1720
- manifestCmd.command("query").description("Query components by attributes").option("--context <name>", "Find components consuming a context").option("--hook <name>", "Find components using a specific hook").option("--complexity <class>", "Filter by complexity class: simple or complex").option("--side-effects", "Find components with any side effects", false).option("--has-fetch", "Find components with fetch calls", false).option(
1791
+ manifestCmd.command("query").description(
1792
+ 'Filter components by structural attributes. All flags are AND-combined.\n\nCOMPLEXITY CLASSES:\n simple \u2014 pure/presentational, no side effects, Satori-renderable\n complex \u2014 uses context/hooks/effects, requires BrowserPool to render\n\nExamples:\n scope manifest query --complexity simple\n scope manifest query --has-fetch\n scope manifest query --hook useContext --side-effects\n scope manifest query --has-prop "variant:union" --format json\n scope manifest query --composed-by Layout'
1793
+ ).option("--context <name>", "Find components consuming a context").option("--hook <name>", "Find components using a specific hook").option("--complexity <class>", "Filter by complexity class: simple or complex").option("--side-effects", "Find components with any side effects", false).option("--has-fetch", "Find components with fetch calls", false).option(
1721
1794
  "--has-prop <spec>",
1722
1795
  "Find components with a prop matching name or name:type (e.g. 'loading' or 'variant:union')"
1723
- ).option("--composed-by <name>", "Find components that compose the named component").option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action(
1796
+ ).option("--composed-by <name>", "Find components that compose the named component").option("--internal", "Find only internal components", false).option("--collection <name>", "Filter to only components in the named collection").option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action(
1724
1797
  (opts) => {
1725
1798
  try {
1726
1799
  const manifest = loadManifest(opts.manifest);
@@ -1733,9 +1806,11 @@ function registerQuery(manifestCmd) {
1733
1806
  if (opts.hasFetch) queryParts.push("has-fetch");
1734
1807
  if (opts.hasProp !== void 0) queryParts.push(`has-prop=${opts.hasProp}`);
1735
1808
  if (opts.composedBy !== void 0) queryParts.push(`composed-by=${opts.composedBy}`);
1809
+ if (opts.internal) queryParts.push("internal");
1810
+ if (opts.collection !== void 0) queryParts.push(`collection=${opts.collection}`);
1736
1811
  if (queryParts.length === 0) {
1737
1812
  process.stderr.write(
1738
- "No query flags specified. Use --context, --hook, --complexity, --side-effects, --has-fetch, --has-prop, or --composed-by.\n"
1813
+ "No query flags specified. Use --context, --hook, --complexity, --side-effects, --has-fetch, --has-prop, --composed-by, --internal, or --collection.\n"
1739
1814
  );
1740
1815
  process.exit(1);
1741
1816
  }
@@ -1780,15 +1855,24 @@ function registerQuery(manifestCmd) {
1780
1855
  const targetName = opts.composedBy;
1781
1856
  entries = entries.filter(([, d]) => {
1782
1857
  const composedBy = d.composedBy;
1783
- return composedBy !== void 0 && composedBy.includes(targetName);
1858
+ return composedBy?.includes(targetName);
1784
1859
  });
1785
1860
  }
1861
+ if (opts.internal) {
1862
+ entries = entries.filter(([, d]) => d.internal);
1863
+ }
1864
+ if (opts.collection !== void 0) {
1865
+ const col = opts.collection;
1866
+ entries = entries.filter(([, d]) => d.collection === col);
1867
+ }
1786
1868
  const rows = entries.map(([name, d]) => ({
1787
1869
  name,
1788
1870
  file: d.filePath,
1789
1871
  complexityClass: d.complexityClass,
1790
1872
  hooks: d.detectedHooks.join(", ") || "\u2014",
1791
- contexts: d.requiredContexts.join(", ") || "\u2014"
1873
+ contexts: d.requiredContexts.join(", ") || "\u2014",
1874
+ collection: d.collection,
1875
+ internal: d.internal
1792
1876
  }));
1793
1877
  const output = format === "json" ? formatQueryJson(rows) : formatQueryTable(rows, queryDesc);
1794
1878
  process.stdout.write(`${output}
@@ -1803,7 +1887,7 @@ function registerQuery(manifestCmd) {
1803
1887
  }
1804
1888
  function registerGenerate(manifestCmd) {
1805
1889
  manifestCmd.command("generate").description(
1806
- "Generate the component manifest from source and write to .reactscope/manifest.json"
1890
+ 'Scan source files and generate .reactscope/manifest.json.\n\nUses Babel static analysis \u2014 no runtime or bundler required.\nRe-run whenever components are added, removed, or significantly changed.\n\nWHAT IT CAPTURES per component:\n - File path and export name\n - All props with types and default values\n - Hook usage (useState, useEffect, useContext, custom hooks)\n - Side effects (fetch, timers, subscriptions)\n - Complexity class: simple | complex\n - Context dependencies and composed child components\n\nExamples:\n scope manifest generate\n scope manifest generate --root ./packages/ui\n scope manifest generate --include "src/components/**/*.tsx" --exclude "**/*.stories.tsx"\n scope manifest generate --output ./custom-manifest.json'
1807
1891
  ).option("--root <path>", "Project root directory (default: cwd)").option("--output <path>", "Output path for manifest.json", MANIFEST_PATH).option("--include <globs>", "Comma-separated glob patterns to include").option("--exclude <globs>", "Comma-separated glob patterns to exclude").action(async (opts) => {
1808
1892
  try {
1809
1893
  const rootDir = path.resolve(process.cwd(), opts.root ?? ".");
@@ -1838,7 +1922,7 @@ function registerGenerate(manifestCmd) {
1838
1922
  }
1839
1923
  function createManifestCommand() {
1840
1924
  const manifestCmd = new commander.Command("manifest").description(
1841
- "Query and explore the component manifest"
1925
+ "Query and explore the component manifest (.reactscope/manifest.json).\n\nThe manifest is the source-of-truth registry of every React component\nin your codebase \u2014 generated by static analysis (no runtime needed).\n\nRun `scope manifest generate` first, then use list/get/query to explore.\n\nExamples:\n scope manifest generate\n scope manifest list\n scope manifest get Button\n scope manifest query --complexity complex --has-fetch"
1842
1926
  );
1843
1927
  registerList(manifestCmd);
1844
1928
  registerGet(manifestCmd);
@@ -2154,7 +2238,19 @@ async function runHooksProfiling(componentName, filePath, props) {
2154
2238
  }
2155
2239
  function createInstrumentHooksCommand() {
2156
2240
  const cmd = new commander.Command("hooks").description(
2157
- "Profile per-hook-instance data for a component: update counts, cache hit rates, effect counts, and more"
2241
+ `Profile per-hook-instance data for a component.
2242
+
2243
+ METRICS CAPTURED per hook instance:
2244
+ useState update count, current value
2245
+ useCallback cache hit rate (stable reference %)
2246
+ useMemo cache hit rate (recompute %)
2247
+ useEffect execution count
2248
+ useRef current value snapshot
2249
+
2250
+ Examples:
2251
+ scope instrument hooks SearchInput
2252
+ scope instrument hooks SearchInput --props '{"value":"hello"}' --json
2253
+ scope instrument hooks Dropdown --json | jq '.hooks[] | select(.type == "useMemo")' `
2158
2254
  ).argument("<component>", "Component name (must exist in the manifest)").option("--props <json>", "Inline props JSON passed to the component", "{}").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH2).option("--format <fmt>", "Output format: json|text (default: auto)", "json").option("--show-flags", "Show heuristic flags only (useful for CI checks)", false).action(
2159
2255
  async (componentName, opts) => {
2160
2256
  try {
@@ -2438,7 +2534,19 @@ async function runInteractionProfile(componentName, filePath, props, interaction
2438
2534
  }
2439
2535
  function createInstrumentProfileCommand() {
2440
2536
  const cmd = new commander.Command("profile").description(
2441
- "Capture a full interaction-scoped performance profile: renders, timing, layout shifts"
2537
+ `Capture a full performance profile for an interaction sequence.
2538
+
2539
+ PROFILE INCLUDES:
2540
+ renders total re-renders triggered by the interaction
2541
+ timing interaction start \u2192 paint time (ms)
2542
+ layoutShifts cumulative layout shift (CLS) score
2543
+ scriptTime JS execution time (ms)
2544
+ longTasks count of tasks >50ms
2545
+
2546
+ Examples:
2547
+ scope instrument profile Button --interaction '[{"action":"click","target":"button"}]'
2548
+ scope instrument profile Modal --interaction '[{"action":"click","target":".open-btn"}]' --json
2549
+ scope instrument profile Form --json | jq '.summary.renderCount'`
2442
2550
  ).argument("<component>", "Component name (must exist in the manifest)").option(
2443
2551
  "--interaction <json>",
2444
2552
  `Interaction steps JSON, e.g. '[{"action":"click","target":"button.primary"}]'`,
@@ -2774,7 +2882,21 @@ async function runInstrumentTree(options) {
2774
2882
  }
2775
2883
  }
2776
2884
  function createInstrumentTreeCommand() {
2777
- return new commander.Command("tree").description("Render a component via BrowserPool and output a structured instrumentation tree").argument("<component>", "Component name to instrument (must exist in the manifest)").option("--sort-by <field>", "Sort nodes by field: renderCount | depth").option("--limit <n>", "Limit output to the first N nodes (depth-first)").option("--uses-context <name>", "Filter to components that use a specific context").option("--provider-depth", "Annotate each node with its context-provider nesting depth", false).option(
2885
+ return new commander.Command("tree").description(
2886
+ `Render a component and output the full instrumentation tree:
2887
+ DOM structure, computed styles per node, a11y roles, and React fibers.
2888
+
2889
+ OUTPUT STRUCTURE per node:
2890
+ tag / id / className DOM identity
2891
+ computedStyles resolved CSS properties
2892
+ a11y role, name, focusable
2893
+ children nested child nodes
2894
+
2895
+ Examples:
2896
+ scope instrument tree Card
2897
+ scope instrument tree Button --props '{"variant":"primary"}' --json
2898
+ scope instrument tree Input --json | jq '.tree.computedStyles'`
2899
+ ).argument("<component>", "Component name to instrument (must exist in the manifest)").option("--sort-by <field>", "Sort nodes by field: renderCount | depth").option("--limit <n>", "Limit output to the first N nodes (depth-first)").option("--uses-context <name>", "Filter to components that use a specific context").option("--provider-depth", "Annotate each node with its context-provider nesting depth", false).option(
2778
2900
  "--wasted-renders",
2779
2901
  "Filter to components with wasted renders (no prop/state/context changes, not memoized)",
2780
2902
  false
@@ -3168,7 +3290,8 @@ Available: ${available}`
3168
3290
  }
3169
3291
  const rootDir = process.cwd();
3170
3292
  const filePath = path.resolve(rootDir, descriptor.filePath);
3171
- const preScript = playwright.getBrowserEntryScript() + "\n" + buildInstrumentationScript();
3293
+ const preScript = `${playwright.getBrowserEntryScript()}
3294
+ ${buildInstrumentationScript()}`;
3172
3295
  const htmlHarness = await buildComponentHarness(
3173
3296
  filePath,
3174
3297
  options.componentName,
@@ -3257,7 +3380,24 @@ function formatRendersTable(result) {
3257
3380
  return lines.join("\n");
3258
3381
  }
3259
3382
  function createInstrumentRendersCommand() {
3260
- return new commander.Command("renders").description("Trace re-render causality chains for a component during an interaction sequence").argument("<component>", "Component name to instrument (must be in manifest)").option(
3383
+ return new commander.Command("renders").description(
3384
+ `Trace every re-render triggered by an interaction and identify root causes.
3385
+
3386
+ OUTPUT INCLUDES per render event:
3387
+ component which component re-rendered
3388
+ trigger why it re-rendered: state_change | props_change | context_change |
3389
+ parent_rerender | force_update | hook_dependency
3390
+ wasted true if re-rendered with no changed inputs and not memoized
3391
+ chain full causality chain from root cause to this render
3392
+
3393
+ WASTED RENDERS: propsChanged=false AND stateChanged=false AND contextChanged=false
3394
+ AND memoized=false \u2014 these are optimisation opportunities.
3395
+
3396
+ Examples:
3397
+ scope instrument renders SearchPage --interaction '[{"action":"type","target":"input","text":"hello"}]'
3398
+ scope instrument renders Button --interaction '[{"action":"click","target":"button"}]' --json
3399
+ scope instrument renders Form --json | jq '.events[] | select(.wasted == true)'`
3400
+ ).argument("<component>", "Component name to instrument (must be in manifest)").option(
3261
3401
  "--interaction <json>",
3262
3402
  `Interaction sequence JSON, e.g. '[{"action":"click","target":"button"}]'`,
3263
3403
  "[]"
@@ -3303,7 +3443,28 @@ function createInstrumentRendersCommand() {
3303
3443
  }
3304
3444
  function createInstrumentCommand() {
3305
3445
  const instrumentCmd = new commander.Command("instrument").description(
3306
- "Structured instrumentation commands for React component analysis"
3446
+ `Runtime instrumentation for React component behaviour analysis.
3447
+
3448
+ All instrument commands:
3449
+ 1. Build an esbuild harness for the component
3450
+ 2. Load it in a Playwright browser
3451
+ 3. Inject instrumentation hooks into React DevTools fiber
3452
+ 4. Execute interactions and collect events
3453
+
3454
+ PREREQUISITES:
3455
+ scope manifest generate (component must be in manifest)
3456
+ reactscope.config.json (for wrappers/globalCSS)
3457
+
3458
+ INTERACTION FORMAT:
3459
+ JSON array of step objects: [{action, target, text?}]
3460
+ Actions: click | type | focus | blur | hover | key
3461
+ Target: CSS selector for the element to interact with
3462
+
3463
+ Examples:
3464
+ scope instrument renders Button --interaction '[{"action":"click","target":"button"}]'
3465
+ scope instrument hooks SearchInput --props '{"value":"hello"}'
3466
+ scope instrument profile Modal --interaction '[{"action":"click","target":".open-btn"}]'
3467
+ scope instrument tree Card`
3307
3468
  );
3308
3469
  instrumentCmd.addCommand(createInstrumentRendersCommand());
3309
3470
  instrumentCmd.addCommand(createInstrumentHooksCommand());
@@ -3733,7 +3894,27 @@ Available: ${available}`
3733
3894
  return { __default__: {} };
3734
3895
  }
3735
3896
  function registerRenderSingle(renderCmd) {
3736
- renderCmd.command("component <component>", { isDefault: true }).description("Render a single component to PNG or JSON").option("--props <json>", `Inline props JSON, e.g. '{"variant":"primary"}'`).option("--scenario <name>", "Run a named scenario from the component's .scope file").option("--viewport <WxH>", "Viewport size e.g. 1280x720", "375x812").option("--theme <name>", "Theme name from the token system").option("-o, --output <path>", "Write PNG to file instead of stdout").option("--format <fmt>", "Output format: png or json (default: auto)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH6).action(
3897
+ renderCmd.command("component <component>", { isDefault: true }).description(
3898
+ `Render one component to a PNG screenshot or JSON data object.
3899
+
3900
+ PROP SOURCES (in priority order):
3901
+ --scenario <name> named scenario from <ComponentName>.scope file
3902
+ --props <json> inline props JSON string
3903
+ (no flag) component rendered with all-default props
3904
+
3905
+ FORMAT DETECTION:
3906
+ --format png always write PNG
3907
+ --format json always write JSON render data
3908
+ auto (default) PNG when -o has .png extension or stdout is file;
3909
+ JSON when stdout is a pipe
3910
+
3911
+ Examples:
3912
+ scope render component Button
3913
+ scope render component Button --props '{"variant":"primary","size":"lg"}'
3914
+ scope render component Button --scenario hover-state -o button-hover.png
3915
+ scope render component Card --viewport 375x812 --theme dark
3916
+ scope render component Badge --format json | jq '.a11y'`
3917
+ ).option("--props <json>", `Inline props JSON, e.g. '{"variant":"primary"}'`).option("--scenario <name>", "Run a named scenario from the component's .scope file").option("--viewport <WxH>", "Viewport size e.g. 1280x720", "375x812").option("--theme <name>", "Theme name from the token system").option("-o, --output <path>", "Write PNG to file instead of stdout").option("--format <fmt>", "Output format: png or json (default: auto)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH6).action(
3737
3918
  async (componentName, opts) => {
3738
3919
  try {
3739
3920
  const manifest = loadManifest(opts.manifest);
@@ -3858,7 +4039,9 @@ Available: ${available}`
3858
4039
  );
3859
4040
  }
3860
4041
  function registerRenderMatrix(renderCmd) {
3861
- renderCmd.command("matrix <component>").description("Render a component across a matrix of prop axes").option(
4042
+ renderCmd.command("matrix <component>").description(
4043
+ 'Render every combination of values across one or more prop axes.\nProduces a matrix of screenshots \u2014 one cell per combination.\n\nAXES FORMAT (two equivalent forms):\n Short: --axes "variant:primary,ghost size:sm,md,lg"\n JSON: --axes {"variant":["primary","ghost"],"size":["sm","md","lg"]}\n\nCOMPOSITION CONTEXTS (--contexts):\n Test component in different layout environments.\n Available IDs: centered, rtl, sidebar, dark-bg, light-bg\n (Define custom contexts in reactscope.config.json)\n\nSTRESS PRESETS (--stress):\n Inject adversarial content to test edge cases.\n Available IDs: text.long, text.unicode, text.empty\n\nExamples:\n scope render matrix Button --axes "variant:primary,ghost,destructive"\n scope render matrix Button --axes "variant:primary,ghost size:sm,lg" --sprite matrix.png\n scope render matrix Badge --axes "type:info,warn,error" --contexts centered,rtl\n scope render matrix Input --stress text.long,text.unicode --format json'
4044
+ ).option(
3862
4045
  "--axes <spec>",
3863
4046
  `Axis definitions: key:v1,v2 space-separated OR JSON object e.g. 'variant:primary,ghost size:sm,lg' or '{"variant":["primary","ghost"],"size":["sm","lg"]}'`
3864
4047
  ).option(
@@ -4017,7 +4200,9 @@ Available: ${available}`
4017
4200
  );
4018
4201
  }
4019
4202
  function registerRenderAll(renderCmd) {
4020
- renderCmd.command("all").description("Render all components from the manifest").option("--concurrency <n>", "Max parallel renders", "4").option("--output-dir <dir>", "Output directory for renders", DEFAULT_OUTPUT_DIR).option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH6).option("--format <fmt>", "Output format: json|png (default: png)", "png").action(
4203
+ renderCmd.command("all").description(
4204
+ "Render every component in the manifest and write to .reactscope/renders/.\n\nAlso emits .reactscope/compliance-styles.json (computed CSS class\u2192value map)\nwhich is required by `scope tokens compliance`.\n\nSCENARIO SELECTION:\n Each component is rendered using its default scenario from its .scope file\n if one exists, otherwise with all-default props.\n\nMATRIX AUTO-DETECTION:\n If a component has a .scope file with a matrix block, render all\n will render the matrix cells in addition to the default screenshot.\n\nExamples:\n scope render all\n scope render all --concurrency 8\n scope render all --format json --output-dir .reactscope/renders\n scope render all --manifest ./custom/manifest.json"
4205
+ ).option("--concurrency <n>", "Max parallel renders", "4").option("--output-dir <dir>", "Output directory for renders", DEFAULT_OUTPUT_DIR).option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH6).option("--format <fmt>", "Output format: json|png (default: png)", "png").action(
4021
4206
  async (opts) => {
4022
4207
  try {
4023
4208
  const manifest = loadManifest(opts.manifest);
@@ -4239,7 +4424,7 @@ function resolveMatrixFormat(formatFlag, spriteAlreadyWritten) {
4239
4424
  }
4240
4425
  function createRenderCommand() {
4241
4426
  const renderCmd = new commander.Command("render").description(
4242
- "Render components to PNG or JSON via esbuild + BrowserPool"
4427
+ 'Render React components to PNG screenshots or JSON render data.\n\nScope uses two render engines depending on component complexity:\n Satori \u2014 fast SVG\u2192PNG renderer for simple/presentational components\n BrowserPool \u2014 Playwright headless browser for complex components\n (context providers, hooks, async, global CSS)\n\nPREREQUISITES:\n 1. reactscope.config.json exists (scope init)\n 2. manifest.json is up to date (scope manifest generate)\n 3. If using globalCSS: Tailwind/PostCSS is configured in the project\n\nOUTPUTS (written to .reactscope/renders/<ComponentName>/):\n screenshot.png retina-quality PNG (2\xD7 physical pixels, displayed at 1\xD7)\n render.json props, dimensions, DOM snapshot, a11y, computed styles\n compliance-styles.json (render all only) \u2014 token matching input\n\nExamples:\n scope render component Button\n scope render matrix Button --axes "variant:primary,ghost size:sm,md,lg"\n scope render all\n scope render all --format json --output-dir ./out'
4243
4428
  );
4244
4429
  registerRenderSingle(renderCmd);
4245
4430
  registerRenderMatrix(renderCmd);
@@ -5457,7 +5642,9 @@ var MIME_TYPES = {
5457
5642
  ".ico": "image/x-icon"
5458
5643
  };
5459
5644
  function registerBuild(siteCmd) {
5460
- siteCmd.command("build").description("Build a static HTML gallery from .reactscope/ output").option("-i, --input <path>", "Path to .reactscope input directory", ".reactscope").option("-o, --output <path>", "Output directory for generated site", ".reactscope/site").option("--base-path <path>", "Base URL path prefix for subdirectory deployment", "/").option("--compliance <path>", "Path to compliance batch report JSON").option("--title <text>", "Site title", "Scope \u2014 Component Gallery").action(
5645
+ siteCmd.command("build").description(
5646
+ 'Build the static HTML site from manifest + render outputs.\n\nINPUT DIRECTORY (.reactscope/ by default) must contain:\n manifest.json component registry\n renders/ screenshots and render.json files from `scope render all`\n\nOPTIONAL:\n --compliance <path> include token compliance scores on detail pages\n --base-path <path> set if deploying to a subdirectory (e.g. /ui-docs)\n\nExamples:\n scope site build\n scope site build --title "Design System" -o .reactscope/site\n scope site build --compliance .reactscope/compliance-styles.json\n scope site build --base-path /ui'
5647
+ ).option("-i, --input <path>", "Path to .reactscope input directory", ".reactscope").option("-o, --output <path>", "Output directory for generated site", ".reactscope/site").option("--base-path <path>", "Base URL path prefix for subdirectory deployment", "/").option("--compliance <path>", "Path to compliance batch report JSON").option("--title <text>", "Site title", "Scope \u2014 Component Gallery").action(
5461
5648
  async (opts) => {
5462
5649
  try {
5463
5650
  const inputDir = path.resolve(process.cwd(), opts.input);
@@ -5499,7 +5686,9 @@ Run \`scope manifest generate\` first.`
5499
5686
  );
5500
5687
  }
5501
5688
  function registerServe(siteCmd) {
5502
- siteCmd.command("serve").description("Serve the built static site locally").option("-p, --port <number>", "Port to listen on", "3000").option("-d, --dir <path>", "Directory to serve", ".reactscope/site").action((opts) => {
5689
+ siteCmd.command("serve").description(
5690
+ "Start a local HTTP server for the built site directory.\n\nRun `scope site build` first.\nCtrl+C to stop.\n\nExamples:\n scope site serve\n scope site serve --port 8080\n scope site serve --dir ./my-site-output"
5691
+ ).option("-p, --port <number>", "Port to listen on", "3000").option("-d, --dir <path>", "Directory to serve", ".reactscope/site").action((opts) => {
5503
5692
  try {
5504
5693
  const port = Number.parseInt(opts.port, 10);
5505
5694
  if (Number.isNaN(port) || port < 1 || port > 65535) {
@@ -5563,7 +5752,7 @@ Run \`scope site build\` first.`
5563
5752
  }
5564
5753
  function createSiteCommand() {
5565
5754
  const siteCmd = new commander.Command("site").description(
5566
- "Build and serve the static component gallery site"
5755
+ 'Build and serve the static HTML component gallery site.\n\nPREREQUISITES:\n scope manifest generate (manifest.json)\n scope render all (renders/ + compliance-styles.json)\n\nSITE CONTENTS:\n /index.html component gallery with screenshots + metadata\n /<component>/index.html detail page: props, renders, matrix, X-Ray, compliance\n\nExamples:\n scope site build && scope site serve\n scope site build --title "Acme UI" --compliance .reactscope/compliance-styles.json\n scope site serve --port 8080'
5567
5756
  );
5568
5757
  registerBuild(siteCmd);
5569
5758
  registerServe(siteCmd);
@@ -5701,7 +5890,9 @@ function formatComplianceReport(batch, threshold) {
5701
5890
  return lines.join("\n");
5702
5891
  }
5703
5892
  function registerCompliance(tokensCmd) {
5704
- tokensCmd.command("compliance").description("Aggregate token compliance report across all components (Token Spec \xA73.3 format)").option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH})`).option("--threshold <n>", "Exit code 1 if compliance score is below this percentage (0-100)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((opts) => {
5893
+ tokensCmd.command("compliance").description(
5894
+ "Compute a token compliance score across all rendered components.\n\nCompares computed CSS values from .reactscope/compliance-styles.json\nagainst the token file \u2014 reports what % of style values are on-token.\n\nPREREQUISITES:\n scope render all must have run first (produces compliance-styles.json)\n\nSCORING:\n compliant value exactly matches a token\n near-match value is within tolerance of a token (e.g. close color)\n off-token value not found in token file\n\nEXIT CODES:\n 0 compliance >= threshold (or no --threshold set)\n 1 compliance < threshold\n\nExamples:\n scope tokens compliance\n scope tokens compliance --threshold 90\n scope tokens compliance --format json | jq '.summary'\n scope tokens compliance --styles ./custom/compliance-styles.json"
5895
+ ).option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH})`).option("--threshold <n>", "Exit code 1 if compliance score is below this percentage (0-100)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((opts) => {
5705
5896
  try {
5706
5897
  const tokenFilePath = resolveTokenFilePath(opts.file);
5707
5898
  const { tokens: tokens$1 } = loadTokens(tokenFilePath);
@@ -5759,7 +5950,9 @@ function resolveTokenFilePath2(fileFlag) {
5759
5950
  return path.resolve(process.cwd(), DEFAULT_TOKEN_FILE);
5760
5951
  }
5761
5952
  function createTokensExportCommand() {
5762
- return new commander.Command("export").description("Export design tokens to a downstream format").requiredOption("--format <fmt>", `Output format: ${SUPPORTED_FORMATS.join(", ")}`).option("--file <path>", "Path to token file (overrides config)").option("--out <path>", "Write output to file instead of stdout").option("--prefix <prefix>", "CSS/SCSS: prefix for variable names (e.g. 'scope')").option("--selector <selector>", "CSS: custom root selector (default: ':root')").option(
5953
+ return new commander.Command("export").description(
5954
+ 'Export design tokens to CSS variables, TypeScript, SCSS, Tailwind config, Figma, or flat JSON.\n\nFORMATS:\n css CSS custom properties (:root { --color-primary-500: #3b82f6; })\n scss SCSS variables ($color-primary-500: #3b82f6;)\n ts TypeScript const export (export const tokens = {...})\n tailwind Tailwind theme.extend block (paste into tailwind.config.js)\n flat-json Flat { path: value } map (useful for tooling integration)\n figma Figma Tokens plugin format\n\nExamples:\n scope tokens export --format css --out src/tokens.css\n scope tokens export --format css --prefix brand --selector ":root, [data-theme]"\n scope tokens export --format tailwind --out tailwind-tokens.js\n scope tokens export --format ts --out src/tokens.ts\n scope tokens export --format css --theme dark --out dark-tokens.css'
5955
+ ).requiredOption("--format <fmt>", `Output format: ${SUPPORTED_FORMATS.join(", ")}`).option("--file <path>", "Path to token file (overrides config)").option("--out <path>", "Write output to file instead of stdout").option("--prefix <prefix>", "CSS/SCSS: prefix for variable names (e.g. 'scope')").option("--selector <selector>", "CSS: custom root selector (default: ':root')").option(
5763
5956
  "--theme <name>",
5764
5957
  "Include theme overrides for the named theme (applies to css, ts, scss, tailwind, figma)"
5765
5958
  ).action(
@@ -5899,7 +6092,9 @@ function formatImpactSummary(report) {
5899
6092
  return `\u2192 ${parts.join(", ")}`;
5900
6093
  }
5901
6094
  function registerImpact(tokensCmd) {
5902
- tokensCmd.command("impact <path>").description("List all components and elements that consume a given token (Token Spec \xA74.3)").option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH2})`).option("--new-value <value>", "Proposed new value \u2014 report visual severity of the change").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action(
6095
+ tokensCmd.command("impact <path>").description(
6096
+ "List every component and CSS element that uses a given token.\nUse this to understand the blast radius before changing a token value.\n\nPREREQUISITE: scope render all (populates compliance-styles.json)\n\nExamples:\n scope tokens impact color.primary.500\n scope tokens impact spacing.4 --format json\n scope tokens impact font.size.base | grep Button"
6097
+ ).option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH2})`).option("--new-value <value>", "Proposed new value \u2014 report visual severity of the change").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action(
5903
6098
  (tokenPath, opts) => {
5904
6099
  try {
5905
6100
  const tokenFilePath = resolveTokenFilePath(opts.file);
@@ -5988,7 +6183,9 @@ async function renderComponentWithCssOverride(filePath, componentName, cssOverri
5988
6183
  }
5989
6184
  }
5990
6185
  function registerPreview(tokensCmd) {
5991
- tokensCmd.command("preview <path>").description("Render before/after sprite sheet for components affected by a token change").requiredOption("--new-value <value>", "The proposed new resolved value for the token").option("--sprite", "Output a PNG sprite sheet (default when TTY)", false).option("-o, --output <path>", "Output PNG path (default: .reactscope/previews/<token>.png)").option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH3})`).option("--manifest <path>", "Path to manifest.json", DEFAULT_MANIFEST_PATH).option("--format <fmt>", "Output format: json or text (default: auto-detect)").option("--timeout <ms>", "Browser timeout per render (ms)", "10000").option("--viewport-width <px>", "Viewport width in pixels", "1280").option("--viewport-height <px>", "Viewport height in pixels", "720").action(
6186
+ tokensCmd.command("preview <path>").description(
6187
+ 'Render before/after screenshots of all components affected by a token change.\nUseful for visual review before committing a token value update.\n\nPREREQUISITE: scope render all (provides baseline renders)\n\nExamples:\n scope tokens preview color.primary.500\n scope tokens preview color.primary.500 --new-value "#2563eb" -o preview.png'
6188
+ ).requiredOption("--new-value <value>", "The proposed new resolved value for the token").option("--sprite", "Output a PNG sprite sheet (default when TTY)", false).option("-o, --output <path>", "Output PNG path (default: .reactscope/previews/<token>.png)").option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH3})`).option("--manifest <path>", "Path to manifest.json", DEFAULT_MANIFEST_PATH).option("--format <fmt>", "Output format: json or text (default: auto-detect)").option("--timeout <ms>", "Browser timeout per render (ms)", "10000").option("--viewport-width <px>", "Viewport width in pixels", "1280").option("--viewport-height <px>", "Viewport height in pixels", "720").action(
5992
6189
  async (tokenPath, opts) => {
5993
6190
  try {
5994
6191
  const tokenFilePath = resolveTokenFilePath(opts.file);
@@ -6235,7 +6432,9 @@ function buildResolutionChain(startPath, rawTokens) {
6235
6432
  return chain;
6236
6433
  }
6237
6434
  function registerGet2(tokensCmd) {
6238
- tokensCmd.command("get <path>").description("Resolve a token path to its computed value").option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((tokenPath, opts) => {
6435
+ tokensCmd.command("get <path>").description(
6436
+ "Resolve a token path and print its final computed value.\nFollows all {ref} chains to the raw value.\n\nExamples:\n scope tokens get color.primary.500\n scope tokens get spacing.4 --format json\n scope tokens get font.size.base --file ./tokens/brand.json"
6437
+ ).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((tokenPath, opts) => {
6239
6438
  try {
6240
6439
  const filePath = resolveTokenFilePath(opts.file);
6241
6440
  const { tokens: tokens$1 } = loadTokens(filePath);
@@ -6260,7 +6459,18 @@ function registerGet2(tokensCmd) {
6260
6459
  });
6261
6460
  }
6262
6461
  function registerList2(tokensCmd) {
6263
- tokensCmd.command("list [category]").description("List tokens, optionally filtered by category or type").option("--type <type>", "Filter by token type (color, dimension, fontFamily, etc.)").option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or table (default: auto-detect)").action(
6462
+ tokensCmd.command("list [category]").description(
6463
+ `List all tokens, optionally filtered by category prefix or type.
6464
+
6465
+ CATEGORY: top-level token namespace (e.g. "color", "spacing", "typography")
6466
+ TYPE: token value type \u2014 color | spacing | typography | shadow | radius | opacity
6467
+
6468
+ Examples:
6469
+ scope tokens list
6470
+ scope tokens list color
6471
+ scope tokens list --type spacing
6472
+ scope tokens list color --format json | jq '.[].path'`
6473
+ ).option("--type <type>", "Filter by token type (color, dimension, fontFamily, etc.)").option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or table (default: auto-detect)").action(
6264
6474
  (category, opts) => {
6265
6475
  try {
6266
6476
  const filePath = resolveTokenFilePath(opts.file);
@@ -6290,7 +6500,9 @@ function registerList2(tokensCmd) {
6290
6500
  );
6291
6501
  }
6292
6502
  function registerSearch(tokensCmd) {
6293
- tokensCmd.command("search <value>").description("Find which token(s) match a computed value (supports fuzzy color matching)").option("--type <type>", "Restrict search to a specific token type").option("--fuzzy", "Return nearest match even if no exact match exists", false).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or table (default: auto-detect)").action(
6503
+ tokensCmd.command("search <value>").description(
6504
+ 'Find the token(s) whose computed value matches the given raw value.\nSupports fuzzy color matching (hex \u2194 rgb \u2194 hsl equivalence).\n\nExamples:\n scope tokens search "#3b82f6"\n scope tokens search "16px"\n scope tokens search "rgb(59, 130, 246)" # fuzzy-matches #3b82f6'
6505
+ ).option("--type <type>", "Restrict search to a specific token type").option("--fuzzy", "Return nearest match even if no exact match exists", false).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or table (default: auto-detect)").action(
6294
6506
  (value, opts) => {
6295
6507
  try {
6296
6508
  const filePath = resolveTokenFilePath(opts.file);
@@ -6373,7 +6585,9 @@ Tip: use --fuzzy for nearest-match search.
6373
6585
  );
6374
6586
  }
6375
6587
  function registerResolve(tokensCmd) {
6376
- tokensCmd.command("resolve <path>").description("Show the full resolution chain for a token").option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((tokenPath, opts) => {
6588
+ tokensCmd.command("resolve <path>").description(
6589
+ "Print the full reference chain from a token path down to its raw value.\nUseful for debugging circular references or understanding token inheritance.\n\nExamples:\n scope tokens resolve color.primary.500\n scope tokens resolve button.background --format json"
6590
+ ).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((tokenPath, opts) => {
6377
6591
  try {
6378
6592
  const filePath = resolveTokenFilePath(opts.file);
6379
6593
  const absFilePath = filePath;
@@ -6409,7 +6623,19 @@ function registerResolve(tokensCmd) {
6409
6623
  }
6410
6624
  function registerValidate(tokensCmd) {
6411
6625
  tokensCmd.command("validate").description(
6412
- "Validate the token file for errors (circular refs, missing refs, type mismatches)"
6626
+ `Validate the token file and report errors.
6627
+
6628
+ CHECKS:
6629
+ - Circular reference chains (A \u2192 B \u2192 A)
6630
+ - Broken references ({path.that.does.not.exist})
6631
+ - Type mismatches (token declared as "color" but value is a number)
6632
+ - Duplicate paths
6633
+
6634
+ Exits 1 if any errors are found (suitable for CI).
6635
+
6636
+ Examples:
6637
+ scope tokens validate
6638
+ scope tokens validate --format json | jq '.errors'`
6413
6639
  ).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((opts) => {
6414
6640
  try {
6415
6641
  const filePath = resolveTokenFilePath(opts.file);
@@ -6488,7 +6714,7 @@ function outputValidationResult(filePath, errors, useJson) {
6488
6714
  }
6489
6715
  function createTokensCommand() {
6490
6716
  const tokensCmd = new commander.Command("tokens").description(
6491
- "Query and validate design tokens from a reactscope.tokens.json file"
6717
+ 'Query, validate, and export design tokens from reactscope.tokens.json.\n\nTOKEN FILE RESOLUTION (in priority order):\n 1. --file <path> explicit override\n 2. tokens.file in reactscope.config.json\n 3. reactscope.tokens.json default (project root)\n\nTOKEN FILE FORMAT (reactscope.tokens.json):\n Nested JSON. Each leaf is a token with { value, type } or just a raw value.\n Paths use dot notation: color.primary.500, spacing.4, font.size.base\n References use {path.to.other.token} syntax.\n Themes: top-level "themes" key with named override maps.\n\nTOKEN TYPES: color | spacing | typography | shadow | radius | opacity | other\n\nExamples:\n scope tokens validate\n scope tokens list color\n scope tokens get color.primary.500\n scope tokens compliance\n scope tokens export --format css --out tokens.css'
6492
6718
  );
6493
6719
  registerGet2(tokensCmd);
6494
6720
  registerList2(tokensCmd);
@@ -6504,8 +6730,12 @@ function createTokensCommand() {
6504
6730
 
6505
6731
  // src/program.ts
6506
6732
  function createProgram(options = {}) {
6507
- const program = new commander.Command("scope").version(options.version ?? "0.1.0").description("Scope \u2014 React instrumentation toolkit");
6508
- program.command("capture <url>").description("Capture a React component tree from a live URL and output as JSON").option("-o, --output <path>", "Write JSON to file instead of stdout").option("--pretty", "Pretty-print JSON output (default: minified)", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
6733
+ const program = new commander.Command("scope").version(options.version ?? "0.1.0").description(
6734
+ 'Scope \u2014 static analysis + visual rendering toolkit for React component libraries.\n\nScope answers questions about React codebases \u2014 structure, props, visual output,\ndesign token compliance \u2014 without running the full application.\n\nQUICKSTART (new project):\n scope init # detect config, scaffold reactscope.config.json\n scope doctor # verify setup before doing anything else\n scope manifest generate # scan source and build component manifest\n scope render all # screenshot every component\n scope site build # build HTML gallery\n scope site serve # open at http://localhost:3000\n\nQUICKSTART (existing project / CI):\n scope ci # manifest \u2192 render \u2192 compliance \u2192 regression in one step\n\nAGENT BOOTSTRAP:\n scope get-skill # print SKILL.md to stdout \u2014 pipe into agent context\n\nCONFIG FILE: reactscope.config.json (created by `scope init`)\n components.include glob patterns for component files (e.g. "src/**/*.tsx")\n components.wrappers providers and globalCSS to wrap every render\n render.viewport default viewport width\xD7height in px\n tokens.file path to reactscope.tokens.json (default)\n output.dir output root (default: .reactscope/)\n ci.complianceThreshold fail threshold for `scope ci` (default: 0.90)\n\nOUTPUT DIRECTORY: .reactscope/\n manifest.json component registry \u2014 updated by `scope manifest generate`\n renders/<Name>/ PNGs + render.json per component\n compliance-styles.json computed-style map for token matching\n site/ static HTML gallery (built by `scope site build`)\n\nRun `scope <command> --help` for detailed flags and examples.'
6735
+ );
6736
+ program.command("capture <url>").description(
6737
+ "Capture the live React component tree from a running app and emit it as JSON.\nRequires a running dev server at the given URL (e.g. http://localhost:5173).\n\nExamples:\n scope capture http://localhost:5173\n scope capture http://localhost:5173 -o report.json --pretty\n scope capture http://localhost:5173 --timeout 15000 --wait 500"
6738
+ ).option("-o, --output <path>", "Write JSON to file instead of stdout").option("--pretty", "Pretty-print JSON output (default: minified)", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
6509
6739
  async (url, opts) => {
6510
6740
  try {
6511
6741
  const { report } = await browserCapture({
@@ -6529,7 +6759,9 @@ function createProgram(options = {}) {
6529
6759
  }
6530
6760
  }
6531
6761
  );
6532
- program.command("tree <url>").description("Display the React component tree from a live URL").option("--depth <n>", "Max depth to display (default: unlimited)").option("--show-props", "Include prop names next to components", false).option("--show-hooks", "Show hook counts per component", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
6762
+ program.command("tree <url>").description(
6763
+ "Print a formatted React component tree from a running app.\nUseful for quickly understanding component hierarchy without full capture.\n\nExamples:\n scope tree http://localhost:5173\n scope tree http://localhost:5173 --show-props --show-hooks\n scope tree http://localhost:5173 --depth 4"
6764
+ ).option("--depth <n>", "Max depth to display (default: unlimited)").option("--show-props", "Include prop names next to components", false).option("--show-hooks", "Show hook counts per component", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
6533
6765
  async (url, opts) => {
6534
6766
  try {
6535
6767
  const { report } = await browserCapture({
@@ -6552,7 +6784,9 @@ function createProgram(options = {}) {
6552
6784
  }
6553
6785
  }
6554
6786
  );
6555
- program.command("report <url>").description("Capture and display a human-readable summary of a React app").option("--json", "Output as structured JSON instead of human-readable text", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
6787
+ program.command("report <url>").description(
6788
+ "Capture a React app and print a human-readable analysis summary.\nIncludes component count, hook usage, side-effect summary, and more.\n\nExamples:\n scope report http://localhost:5173\n scope report http://localhost:5173 --json\n scope report http://localhost:5173 --json -o report.json"
6789
+ ).option("--json", "Output as structured JSON instead of human-readable text", false).option("--timeout <ms>", "Max wait time for React to mount (ms)", "10000").option("--wait <ms>", "Additional wait after page load before capture (ms)", "0").action(
6556
6790
  async (url, opts) => {
6557
6791
  try {
6558
6792
  const { report } = await browserCapture({
@@ -6576,7 +6810,9 @@ function createProgram(options = {}) {
6576
6810
  }
6577
6811
  }
6578
6812
  );
6579
- program.command("generate").description("Generate a Playwright test from a Scope trace file").argument("<trace>", "Path to a serialized Scope trace (.json)").option("-o, --output <path>", "Output file path", "scope.spec.ts").option("-d, --description <text>", "Test description").action((tracePath, opts) => {
6813
+ program.command("generate").description(
6814
+ 'Generate a Playwright test file from a Scope trace (.json).\nTraces are produced by scope instrument renders or scope capture.\n\nExamples:\n scope generate trace.json\n scope generate trace.json -o tests/scope.spec.ts -d "User login flow"'
6815
+ ).argument("<trace>", "Path to a serialized Scope trace (.json)").option("-o, --output <path>", "Output file path", "scope.spec.ts").option("-d, --description <text>", "Test description").action((tracePath, opts) => {
6580
6816
  const raw = fs.readFileSync(tracePath, "utf-8");
6581
6817
  const trace = playwright.loadTrace(raw);
6582
6818
  const source = playwright.generateTest(trace, {
@@ -6593,6 +6829,7 @@ function createProgram(options = {}) {
6593
6829
  program.addCommand(createInitCommand());
6594
6830
  program.addCommand(createCiCommand());
6595
6831
  program.addCommand(createDoctorCommand());
6832
+ program.addCommand(createGetSkillCommand());
6596
6833
  const existingReportCmd = program.commands.find((c) => c.name() === "report");
6597
6834
  if (existingReportCmd !== void 0) {
6598
6835
  registerBaselineSubCommand(existingReportCmd);
@@ -6606,6 +6843,7 @@ function createProgram(options = {}) {
6606
6843
  exports.CI_EXIT = CI_EXIT;
6607
6844
  exports.createCiCommand = createCiCommand;
6608
6845
  exports.createDoctorCommand = createDoctorCommand;
6846
+ exports.createGetSkillCommand = createGetSkillCommand;
6609
6847
  exports.createInitCommand = createInitCommand;
6610
6848
  exports.createInstrumentCommand = createInstrumentCommand;
6611
6849
  exports.createManifestCommand = createManifestCommand;