@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.js CHANGED
@@ -167,13 +167,15 @@ function buildTable(headers, rows) {
167
167
  }
168
168
  function formatListTable(rows) {
169
169
  if (rows.length === 0) return "No components found.";
170
- const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS"];
170
+ const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS", "COLLECTION", "INTERNAL"];
171
171
  const tableRows = rows.map((r) => [
172
172
  r.name,
173
173
  r.file,
174
174
  r.complexityClass,
175
175
  String(r.hookCount),
176
- String(r.contextCount)
176
+ String(r.contextCount),
177
+ r.collection ?? "\u2014",
178
+ r.internal ? "yes" : "no"
177
179
  ]);
178
180
  return buildTable(headers, tableRows);
179
181
  }
@@ -204,6 +206,8 @@ function formatGetTable(name, descriptor) {
204
206
  ` Composes: ${descriptor.composes.join(", ") || "none"}`,
205
207
  ` Composed By: ${descriptor.composedBy.join(", ") || "none"}`,
206
208
  ` Side Effects: ${formatSideEffects(descriptor.sideEffects)}`,
209
+ ` Collection: ${descriptor.collection ?? "\u2014"}`,
210
+ ` Internal: ${descriptor.internal}`,
207
211
  "",
208
212
  ` Props (${propNames.length}):`
209
213
  ];
@@ -226,8 +230,16 @@ function formatGetJson(name, descriptor) {
226
230
  }
227
231
  function formatQueryTable(rows, queryDesc) {
228
232
  if (rows.length === 0) return `No components match: ${queryDesc}`;
229
- const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS"];
230
- const tableRows = rows.map((r) => [r.name, r.file, r.complexityClass, r.hooks, r.contexts]);
233
+ const headers = ["NAME", "FILE", "COMPLEXITY", "HOOKS", "CONTEXTS", "COLLECTION", "INTERNAL"];
234
+ const tableRows = rows.map((r) => [
235
+ r.name,
236
+ r.file,
237
+ r.complexityClass,
238
+ r.hooks,
239
+ r.contexts,
240
+ r.collection ?? "\u2014",
241
+ r.internal ? "yes" : "no"
242
+ ]);
231
243
  return `Query: ${queryDesc}
232
244
 
233
245
  ${buildTable(headers, tableRows)}`;
@@ -946,7 +958,7 @@ function parseChecks(raw) {
946
958
  }
947
959
  function createCiCommand() {
948
960
  return new Command("ci").description(
949
- "Run a non-interactive CI pipeline (manifest -> render -> compliance -> regression) with exit codes"
961
+ "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"
950
962
  ).option(
951
963
  "-b, --baseline <dir>",
952
964
  "Baseline directory for visual regression comparison (omit to skip)"
@@ -1103,7 +1115,25 @@ function formatCheck(check) {
1103
1115
  return ` [${ICONS[check.status]}] ${check.name.padEnd(12)} ${check.message}`;
1104
1116
  }
1105
1117
  function createDoctorCommand() {
1106
- return new Command("doctor").description("Check the health of your Scope setup (config, tokens, CSS, manifest)").option("--json", "Emit structured JSON output", false).action((opts) => {
1118
+ return new Command("doctor").description(
1119
+ `Verify your Scope project setup before running other commands.
1120
+
1121
+ CHECKS PERFORMED:
1122
+ config reactscope.config.json exists and is valid JSON
1123
+ tokens reactscope.tokens.json exists and passes validation
1124
+ css globalCSS files referenced in config actually exist
1125
+ manifest .reactscope/manifest.json exists and is not stale
1126
+ (stale = source files modified after last generate)
1127
+
1128
+ STATUS LEVELS: ok | warn | error
1129
+
1130
+ Run this first whenever renders fail or produce unexpected output.
1131
+
1132
+ Examples:
1133
+ scope doctor
1134
+ scope doctor --json
1135
+ scope doctor --json | jq '.checks[] | select(.status == "error")'`
1136
+ ).option("--json", "Emit structured JSON output", false).action((opts) => {
1107
1137
  const cwd = process.cwd();
1108
1138
  const checks = [
1109
1139
  checkConfig(cwd),
@@ -1140,6 +1170,23 @@ function createDoctorCommand() {
1140
1170
  }
1141
1171
  });
1142
1172
  }
1173
+
1174
+ // src/skill-content.ts
1175
+ 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';
1176
+
1177
+ // src/get-skill-command.ts
1178
+ function createGetSkillCommand() {
1179
+ return new Command("get-skill").description(
1180
+ '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'
1181
+ ).option("--json", "Wrap output in JSON { skill: string } instead of raw markdown").action((opts) => {
1182
+ if (opts.json) {
1183
+ process.stdout.write(`${JSON.stringify({ skill: SKILL_CONTENT }, null, 2)}
1184
+ `);
1185
+ } else {
1186
+ process.stdout.write(SKILL_CONTENT);
1187
+ }
1188
+ });
1189
+ }
1143
1190
  function hasConfigFile(dir, stem) {
1144
1191
  if (!existsSync(dir)) return false;
1145
1192
  try {
@@ -1613,7 +1660,9 @@ async function runInit(options) {
1613
1660
  };
1614
1661
  }
1615
1662
  function createInitCommand() {
1616
- return new 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) => {
1663
+ return new Command("init").description(
1664
+ "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"
1665
+ ).option("-y, --yes", "Accept all detected defaults without prompting", false).option("--force", "Overwrite existing reactscope.config.json if present", false).action(async (opts) => {
1617
1666
  try {
1618
1667
  const result = await runInit({ yes: opts.yes, force: opts.force });
1619
1668
  if (!result.success && !result.skipped) {
@@ -1642,34 +1691,56 @@ function resolveFormat(formatFlag) {
1642
1691
  return isTTY() ? "table" : "json";
1643
1692
  }
1644
1693
  function registerList(manifestCmd) {
1645
- 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) => {
1646
- try {
1647
- const manifest = loadManifest(opts.manifest);
1648
- const format = resolveFormat(opts.format);
1649
- let entries = Object.entries(manifest.components);
1650
- if (opts.filter !== void 0) {
1651
- const filterPattern = opts.filter ?? "";
1652
- entries = entries.filter(([name]) => matchGlob(filterPattern, name));
1653
- }
1654
- const rows = entries.map(([name, descriptor]) => ({
1655
- name,
1656
- file: descriptor.filePath,
1657
- complexityClass: descriptor.complexityClass,
1658
- hookCount: descriptor.detectedHooks.length,
1659
- contextCount: descriptor.requiredContexts.length
1660
- }));
1661
- const output = format === "json" ? formatListJson(rows) : formatListTable(rows);
1662
- process.stdout.write(`${output}
1694
+ manifestCmd.command("list").description(
1695
+ `List all components in the manifest as a table (TTY) or JSON (piped).
1696
+
1697
+ Examples:
1698
+ scope manifest list
1699
+ scope manifest list --format json | jq '.[].name'
1700
+ scope manifest list --filter "Button*"`
1701
+ ).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(
1702
+ (opts) => {
1703
+ try {
1704
+ const manifest = loadManifest(opts.manifest);
1705
+ const format = resolveFormat(opts.format);
1706
+ let entries = Object.entries(manifest.components);
1707
+ if (opts.filter !== void 0) {
1708
+ const filterPattern = opts.filter ?? "";
1709
+ entries = entries.filter(([name]) => matchGlob(filterPattern, name));
1710
+ }
1711
+ if (opts.collection !== void 0) {
1712
+ const col = opts.collection;
1713
+ entries = entries.filter(([, d]) => d.collection === col);
1714
+ }
1715
+ if (opts.internal === true) {
1716
+ entries = entries.filter(([, d]) => d.internal);
1717
+ } else if (opts.internal === false) {
1718
+ entries = entries.filter(([, d]) => !d.internal);
1719
+ }
1720
+ const rows = entries.map(([name, descriptor]) => ({
1721
+ name,
1722
+ file: descriptor.filePath,
1723
+ complexityClass: descriptor.complexityClass,
1724
+ hookCount: descriptor.detectedHooks.length,
1725
+ contextCount: descriptor.requiredContexts.length,
1726
+ collection: descriptor.collection,
1727
+ internal: descriptor.internal
1728
+ }));
1729
+ const output = format === "json" ? formatListJson(rows) : formatListTable(rows);
1730
+ process.stdout.write(`${output}
1663
1731
  `);
1664
- } catch (err) {
1665
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
1732
+ } catch (err) {
1733
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
1666
1734
  `);
1667
- process.exit(1);
1735
+ process.exit(1);
1736
+ }
1668
1737
  }
1669
- });
1738
+ );
1670
1739
  }
1671
1740
  function registerGet(manifestCmd) {
1672
- 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) => {
1741
+ manifestCmd.command("get <name>").description(
1742
+ "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'"
1743
+ ).option("--format <fmt>", "Output format: json or table (default: auto-detect)").option("--manifest <path>", "Path to manifest.json", MANIFEST_PATH).action((name, opts) => {
1673
1744
  try {
1674
1745
  const manifest = loadManifest(opts.manifest);
1675
1746
  const format = resolveFormat(opts.format);
@@ -1693,10 +1764,12 @@ Available: ${available}${hint}`
1693
1764
  });
1694
1765
  }
1695
1766
  function registerQuery(manifestCmd) {
1696
- 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(
1767
+ manifestCmd.command("query").description(
1768
+ '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'
1769
+ ).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(
1697
1770
  "--has-prop <spec>",
1698
1771
  "Find components with a prop matching name or name:type (e.g. 'loading' or 'variant:union')"
1699
- ).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(
1772
+ ).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(
1700
1773
  (opts) => {
1701
1774
  try {
1702
1775
  const manifest = loadManifest(opts.manifest);
@@ -1709,9 +1782,11 @@ function registerQuery(manifestCmd) {
1709
1782
  if (opts.hasFetch) queryParts.push("has-fetch");
1710
1783
  if (opts.hasProp !== void 0) queryParts.push(`has-prop=${opts.hasProp}`);
1711
1784
  if (opts.composedBy !== void 0) queryParts.push(`composed-by=${opts.composedBy}`);
1785
+ if (opts.internal) queryParts.push("internal");
1786
+ if (opts.collection !== void 0) queryParts.push(`collection=${opts.collection}`);
1712
1787
  if (queryParts.length === 0) {
1713
1788
  process.stderr.write(
1714
- "No query flags specified. Use --context, --hook, --complexity, --side-effects, --has-fetch, --has-prop, or --composed-by.\n"
1789
+ "No query flags specified. Use --context, --hook, --complexity, --side-effects, --has-fetch, --has-prop, --composed-by, --internal, or --collection.\n"
1715
1790
  );
1716
1791
  process.exit(1);
1717
1792
  }
@@ -1756,15 +1831,24 @@ function registerQuery(manifestCmd) {
1756
1831
  const targetName = opts.composedBy;
1757
1832
  entries = entries.filter(([, d]) => {
1758
1833
  const composedBy = d.composedBy;
1759
- return composedBy !== void 0 && composedBy.includes(targetName);
1834
+ return composedBy?.includes(targetName);
1760
1835
  });
1761
1836
  }
1837
+ if (opts.internal) {
1838
+ entries = entries.filter(([, d]) => d.internal);
1839
+ }
1840
+ if (opts.collection !== void 0) {
1841
+ const col = opts.collection;
1842
+ entries = entries.filter(([, d]) => d.collection === col);
1843
+ }
1762
1844
  const rows = entries.map(([name, d]) => ({
1763
1845
  name,
1764
1846
  file: d.filePath,
1765
1847
  complexityClass: d.complexityClass,
1766
1848
  hooks: d.detectedHooks.join(", ") || "\u2014",
1767
- contexts: d.requiredContexts.join(", ") || "\u2014"
1849
+ contexts: d.requiredContexts.join(", ") || "\u2014",
1850
+ collection: d.collection,
1851
+ internal: d.internal
1768
1852
  }));
1769
1853
  const output = format === "json" ? formatQueryJson(rows) : formatQueryTable(rows, queryDesc);
1770
1854
  process.stdout.write(`${output}
@@ -1779,7 +1863,7 @@ function registerQuery(manifestCmd) {
1779
1863
  }
1780
1864
  function registerGenerate(manifestCmd) {
1781
1865
  manifestCmd.command("generate").description(
1782
- "Generate the component manifest from source and write to .reactscope/manifest.json"
1866
+ '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'
1783
1867
  ).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) => {
1784
1868
  try {
1785
1869
  const rootDir = resolve(process.cwd(), opts.root ?? ".");
@@ -1814,7 +1898,7 @@ function registerGenerate(manifestCmd) {
1814
1898
  }
1815
1899
  function createManifestCommand() {
1816
1900
  const manifestCmd = new Command("manifest").description(
1817
- "Query and explore the component manifest"
1901
+ "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"
1818
1902
  );
1819
1903
  registerList(manifestCmd);
1820
1904
  registerGet(manifestCmd);
@@ -2130,7 +2214,19 @@ async function runHooksProfiling(componentName, filePath, props) {
2130
2214
  }
2131
2215
  function createInstrumentHooksCommand() {
2132
2216
  const cmd = new Command("hooks").description(
2133
- "Profile per-hook-instance data for a component: update counts, cache hit rates, effect counts, and more"
2217
+ `Profile per-hook-instance data for a component.
2218
+
2219
+ METRICS CAPTURED per hook instance:
2220
+ useState update count, current value
2221
+ useCallback cache hit rate (stable reference %)
2222
+ useMemo cache hit rate (recompute %)
2223
+ useEffect execution count
2224
+ useRef current value snapshot
2225
+
2226
+ Examples:
2227
+ scope instrument hooks SearchInput
2228
+ scope instrument hooks SearchInput --props '{"value":"hello"}' --json
2229
+ scope instrument hooks Dropdown --json | jq '.hooks[] | select(.type == "useMemo")' `
2134
2230
  ).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(
2135
2231
  async (componentName, opts) => {
2136
2232
  try {
@@ -2414,7 +2510,19 @@ async function runInteractionProfile(componentName, filePath, props, interaction
2414
2510
  }
2415
2511
  function createInstrumentProfileCommand() {
2416
2512
  const cmd = new Command("profile").description(
2417
- "Capture a full interaction-scoped performance profile: renders, timing, layout shifts"
2513
+ `Capture a full performance profile for an interaction sequence.
2514
+
2515
+ PROFILE INCLUDES:
2516
+ renders total re-renders triggered by the interaction
2517
+ timing interaction start \u2192 paint time (ms)
2518
+ layoutShifts cumulative layout shift (CLS) score
2519
+ scriptTime JS execution time (ms)
2520
+ longTasks count of tasks >50ms
2521
+
2522
+ Examples:
2523
+ scope instrument profile Button --interaction '[{"action":"click","target":"button"}]'
2524
+ scope instrument profile Modal --interaction '[{"action":"click","target":".open-btn"}]' --json
2525
+ scope instrument profile Form --json | jq '.summary.renderCount'`
2418
2526
  ).argument("<component>", "Component name (must exist in the manifest)").option(
2419
2527
  "--interaction <json>",
2420
2528
  `Interaction steps JSON, e.g. '[{"action":"click","target":"button.primary"}]'`,
@@ -2750,7 +2858,21 @@ async function runInstrumentTree(options) {
2750
2858
  }
2751
2859
  }
2752
2860
  function createInstrumentTreeCommand() {
2753
- return new 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(
2861
+ return new Command("tree").description(
2862
+ `Render a component and output the full instrumentation tree:
2863
+ DOM structure, computed styles per node, a11y roles, and React fibers.
2864
+
2865
+ OUTPUT STRUCTURE per node:
2866
+ tag / id / className DOM identity
2867
+ computedStyles resolved CSS properties
2868
+ a11y role, name, focusable
2869
+ children nested child nodes
2870
+
2871
+ Examples:
2872
+ scope instrument tree Card
2873
+ scope instrument tree Button --props '{"variant":"primary"}' --json
2874
+ scope instrument tree Input --json | jq '.tree.computedStyles'`
2875
+ ).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(
2754
2876
  "--wasted-renders",
2755
2877
  "Filter to components with wasted renders (no prop/state/context changes, not memoized)",
2756
2878
  false
@@ -3144,7 +3266,8 @@ Available: ${available}`
3144
3266
  }
3145
3267
  const rootDir = process.cwd();
3146
3268
  const filePath = resolve(rootDir, descriptor.filePath);
3147
- const preScript = getBrowserEntryScript() + "\n" + buildInstrumentationScript();
3269
+ const preScript = `${getBrowserEntryScript()}
3270
+ ${buildInstrumentationScript()}`;
3148
3271
  const htmlHarness = await buildComponentHarness(
3149
3272
  filePath,
3150
3273
  options.componentName,
@@ -3233,7 +3356,24 @@ function formatRendersTable(result) {
3233
3356
  return lines.join("\n");
3234
3357
  }
3235
3358
  function createInstrumentRendersCommand() {
3236
- return new 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(
3359
+ return new Command("renders").description(
3360
+ `Trace every re-render triggered by an interaction and identify root causes.
3361
+
3362
+ OUTPUT INCLUDES per render event:
3363
+ component which component re-rendered
3364
+ trigger why it re-rendered: state_change | props_change | context_change |
3365
+ parent_rerender | force_update | hook_dependency
3366
+ wasted true if re-rendered with no changed inputs and not memoized
3367
+ chain full causality chain from root cause to this render
3368
+
3369
+ WASTED RENDERS: propsChanged=false AND stateChanged=false AND contextChanged=false
3370
+ AND memoized=false \u2014 these are optimisation opportunities.
3371
+
3372
+ Examples:
3373
+ scope instrument renders SearchPage --interaction '[{"action":"type","target":"input","text":"hello"}]'
3374
+ scope instrument renders Button --interaction '[{"action":"click","target":"button"}]' --json
3375
+ scope instrument renders Form --json | jq '.events[] | select(.wasted == true)'`
3376
+ ).argument("<component>", "Component name to instrument (must be in manifest)").option(
3237
3377
  "--interaction <json>",
3238
3378
  `Interaction sequence JSON, e.g. '[{"action":"click","target":"button"}]'`,
3239
3379
  "[]"
@@ -3279,7 +3419,28 @@ function createInstrumentRendersCommand() {
3279
3419
  }
3280
3420
  function createInstrumentCommand() {
3281
3421
  const instrumentCmd = new Command("instrument").description(
3282
- "Structured instrumentation commands for React component analysis"
3422
+ `Runtime instrumentation for React component behaviour analysis.
3423
+
3424
+ All instrument commands:
3425
+ 1. Build an esbuild harness for the component
3426
+ 2. Load it in a Playwright browser
3427
+ 3. Inject instrumentation hooks into React DevTools fiber
3428
+ 4. Execute interactions and collect events
3429
+
3430
+ PREREQUISITES:
3431
+ scope manifest generate (component must be in manifest)
3432
+ reactscope.config.json (for wrappers/globalCSS)
3433
+
3434
+ INTERACTION FORMAT:
3435
+ JSON array of step objects: [{action, target, text?}]
3436
+ Actions: click | type | focus | blur | hover | key
3437
+ Target: CSS selector for the element to interact with
3438
+
3439
+ Examples:
3440
+ scope instrument renders Button --interaction '[{"action":"click","target":"button"}]'
3441
+ scope instrument hooks SearchInput --props '{"value":"hello"}'
3442
+ scope instrument profile Modal --interaction '[{"action":"click","target":".open-btn"}]'
3443
+ scope instrument tree Card`
3283
3444
  );
3284
3445
  instrumentCmd.addCommand(createInstrumentRendersCommand());
3285
3446
  instrumentCmd.addCommand(createInstrumentHooksCommand());
@@ -3709,7 +3870,27 @@ Available: ${available}`
3709
3870
  return { __default__: {} };
3710
3871
  }
3711
3872
  function registerRenderSingle(renderCmd) {
3712
- 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(
3873
+ renderCmd.command("component <component>", { isDefault: true }).description(
3874
+ `Render one component to a PNG screenshot or JSON data object.
3875
+
3876
+ PROP SOURCES (in priority order):
3877
+ --scenario <name> named scenario from <ComponentName>.scope file
3878
+ --props <json> inline props JSON string
3879
+ (no flag) component rendered with all-default props
3880
+
3881
+ FORMAT DETECTION:
3882
+ --format png always write PNG
3883
+ --format json always write JSON render data
3884
+ auto (default) PNG when -o has .png extension or stdout is file;
3885
+ JSON when stdout is a pipe
3886
+
3887
+ Examples:
3888
+ scope render component Button
3889
+ scope render component Button --props '{"variant":"primary","size":"lg"}'
3890
+ scope render component Button --scenario hover-state -o button-hover.png
3891
+ scope render component Card --viewport 375x812 --theme dark
3892
+ scope render component Badge --format json | jq '.a11y'`
3893
+ ).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(
3713
3894
  async (componentName, opts) => {
3714
3895
  try {
3715
3896
  const manifest = loadManifest(opts.manifest);
@@ -3834,7 +4015,9 @@ Available: ${available}`
3834
4015
  );
3835
4016
  }
3836
4017
  function registerRenderMatrix(renderCmd) {
3837
- renderCmd.command("matrix <component>").description("Render a component across a matrix of prop axes").option(
4018
+ renderCmd.command("matrix <component>").description(
4019
+ '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'
4020
+ ).option(
3838
4021
  "--axes <spec>",
3839
4022
  `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"]}'`
3840
4023
  ).option(
@@ -3993,7 +4176,9 @@ Available: ${available}`
3993
4176
  );
3994
4177
  }
3995
4178
  function registerRenderAll(renderCmd) {
3996
- 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(
4179
+ renderCmd.command("all").description(
4180
+ "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"
4181
+ ).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(
3997
4182
  async (opts) => {
3998
4183
  try {
3999
4184
  const manifest = loadManifest(opts.manifest);
@@ -4215,7 +4400,7 @@ function resolveMatrixFormat(formatFlag, spriteAlreadyWritten) {
4215
4400
  }
4216
4401
  function createRenderCommand() {
4217
4402
  const renderCmd = new Command("render").description(
4218
- "Render components to PNG or JSON via esbuild + BrowserPool"
4403
+ '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'
4219
4404
  );
4220
4405
  registerRenderSingle(renderCmd);
4221
4406
  registerRenderMatrix(renderCmd);
@@ -5433,7 +5618,9 @@ var MIME_TYPES = {
5433
5618
  ".ico": "image/x-icon"
5434
5619
  };
5435
5620
  function registerBuild(siteCmd) {
5436
- 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(
5621
+ siteCmd.command("build").description(
5622
+ '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'
5623
+ ).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(
5437
5624
  async (opts) => {
5438
5625
  try {
5439
5626
  const inputDir = resolve(process.cwd(), opts.input);
@@ -5475,7 +5662,9 @@ Run \`scope manifest generate\` first.`
5475
5662
  );
5476
5663
  }
5477
5664
  function registerServe(siteCmd) {
5478
- 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) => {
5665
+ siteCmd.command("serve").description(
5666
+ "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"
5667
+ ).option("-p, --port <number>", "Port to listen on", "3000").option("-d, --dir <path>", "Directory to serve", ".reactscope/site").action((opts) => {
5479
5668
  try {
5480
5669
  const port = Number.parseInt(opts.port, 10);
5481
5670
  if (Number.isNaN(port) || port < 1 || port > 65535) {
@@ -5539,7 +5728,7 @@ Run \`scope site build\` first.`
5539
5728
  }
5540
5729
  function createSiteCommand() {
5541
5730
  const siteCmd = new Command("site").description(
5542
- "Build and serve the static component gallery site"
5731
+ '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'
5543
5732
  );
5544
5733
  registerBuild(siteCmd);
5545
5734
  registerServe(siteCmd);
@@ -5677,7 +5866,9 @@ function formatComplianceReport(batch, threshold) {
5677
5866
  return lines.join("\n");
5678
5867
  }
5679
5868
  function registerCompliance(tokensCmd) {
5680
- 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) => {
5869
+ tokensCmd.command("compliance").description(
5870
+ "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"
5871
+ ).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) => {
5681
5872
  try {
5682
5873
  const tokenFilePath = resolveTokenFilePath(opts.file);
5683
5874
  const { tokens } = loadTokens(tokenFilePath);
@@ -5735,7 +5926,9 @@ function resolveTokenFilePath2(fileFlag) {
5735
5926
  return resolve(process.cwd(), DEFAULT_TOKEN_FILE);
5736
5927
  }
5737
5928
  function createTokensExportCommand() {
5738
- return new 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(
5929
+ return new Command("export").description(
5930
+ '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'
5931
+ ).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(
5739
5932
  "--theme <name>",
5740
5933
  "Include theme overrides for the named theme (applies to css, ts, scss, tailwind, figma)"
5741
5934
  ).action(
@@ -5875,7 +6068,9 @@ function formatImpactSummary(report) {
5875
6068
  return `\u2192 ${parts.join(", ")}`;
5876
6069
  }
5877
6070
  function registerImpact(tokensCmd) {
5878
- 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(
6071
+ tokensCmd.command("impact <path>").description(
6072
+ "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"
6073
+ ).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(
5879
6074
  (tokenPath, opts) => {
5880
6075
  try {
5881
6076
  const tokenFilePath = resolveTokenFilePath(opts.file);
@@ -5964,7 +6159,9 @@ async function renderComponentWithCssOverride(filePath, componentName, cssOverri
5964
6159
  }
5965
6160
  }
5966
6161
  function registerPreview(tokensCmd) {
5967
- 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(
6162
+ tokensCmd.command("preview <path>").description(
6163
+ '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'
6164
+ ).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(
5968
6165
  async (tokenPath, opts) => {
5969
6166
  try {
5970
6167
  const tokenFilePath = resolveTokenFilePath(opts.file);
@@ -6211,7 +6408,9 @@ function buildResolutionChain(startPath, rawTokens) {
6211
6408
  return chain;
6212
6409
  }
6213
6410
  function registerGet2(tokensCmd) {
6214
- 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) => {
6411
+ tokensCmd.command("get <path>").description(
6412
+ "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"
6413
+ ).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((tokenPath, opts) => {
6215
6414
  try {
6216
6415
  const filePath = resolveTokenFilePath(opts.file);
6217
6416
  const { tokens } = loadTokens(filePath);
@@ -6236,7 +6435,18 @@ function registerGet2(tokensCmd) {
6236
6435
  });
6237
6436
  }
6238
6437
  function registerList2(tokensCmd) {
6239
- 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(
6438
+ tokensCmd.command("list [category]").description(
6439
+ `List all tokens, optionally filtered by category prefix or type.
6440
+
6441
+ CATEGORY: top-level token namespace (e.g. "color", "spacing", "typography")
6442
+ TYPE: token value type \u2014 color | spacing | typography | shadow | radius | opacity
6443
+
6444
+ Examples:
6445
+ scope tokens list
6446
+ scope tokens list color
6447
+ scope tokens list --type spacing
6448
+ scope tokens list color --format json | jq '.[].path'`
6449
+ ).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(
6240
6450
  (category, opts) => {
6241
6451
  try {
6242
6452
  const filePath = resolveTokenFilePath(opts.file);
@@ -6266,7 +6476,9 @@ function registerList2(tokensCmd) {
6266
6476
  );
6267
6477
  }
6268
6478
  function registerSearch(tokensCmd) {
6269
- 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(
6479
+ tokensCmd.command("search <value>").description(
6480
+ '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'
6481
+ ).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(
6270
6482
  (value, opts) => {
6271
6483
  try {
6272
6484
  const filePath = resolveTokenFilePath(opts.file);
@@ -6349,7 +6561,9 @@ Tip: use --fuzzy for nearest-match search.
6349
6561
  );
6350
6562
  }
6351
6563
  function registerResolve(tokensCmd) {
6352
- 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) => {
6564
+ tokensCmd.command("resolve <path>").description(
6565
+ "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"
6566
+ ).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((tokenPath, opts) => {
6353
6567
  try {
6354
6568
  const filePath = resolveTokenFilePath(opts.file);
6355
6569
  const absFilePath = filePath;
@@ -6385,7 +6599,19 @@ function registerResolve(tokensCmd) {
6385
6599
  }
6386
6600
  function registerValidate(tokensCmd) {
6387
6601
  tokensCmd.command("validate").description(
6388
- "Validate the token file for errors (circular refs, missing refs, type mismatches)"
6602
+ `Validate the token file and report errors.
6603
+
6604
+ CHECKS:
6605
+ - Circular reference chains (A \u2192 B \u2192 A)
6606
+ - Broken references ({path.that.does.not.exist})
6607
+ - Type mismatches (token declared as "color" but value is a number)
6608
+ - Duplicate paths
6609
+
6610
+ Exits 1 if any errors are found (suitable for CI).
6611
+
6612
+ Examples:
6613
+ scope tokens validate
6614
+ scope tokens validate --format json | jq '.errors'`
6389
6615
  ).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((opts) => {
6390
6616
  try {
6391
6617
  const filePath = resolveTokenFilePath(opts.file);
@@ -6464,7 +6690,7 @@ function outputValidationResult(filePath, errors, useJson) {
6464
6690
  }
6465
6691
  function createTokensCommand() {
6466
6692
  const tokensCmd = new Command("tokens").description(
6467
- "Query and validate design tokens from a reactscope.tokens.json file"
6693
+ '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'
6468
6694
  );
6469
6695
  registerGet2(tokensCmd);
6470
6696
  registerList2(tokensCmd);
@@ -6480,8 +6706,12 @@ function createTokensCommand() {
6480
6706
 
6481
6707
  // src/program.ts
6482
6708
  function createProgram(options = {}) {
6483
- const program = new Command("scope").version(options.version ?? "0.1.0").description("Scope \u2014 React instrumentation toolkit");
6484
- 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(
6709
+ const program = new Command("scope").version(options.version ?? "0.1.0").description(
6710
+ '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.'
6711
+ );
6712
+ program.command("capture <url>").description(
6713
+ "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"
6714
+ ).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(
6485
6715
  async (url, opts) => {
6486
6716
  try {
6487
6717
  const { report } = await browserCapture({
@@ -6505,7 +6735,9 @@ function createProgram(options = {}) {
6505
6735
  }
6506
6736
  }
6507
6737
  );
6508
- 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(
6738
+ program.command("tree <url>").description(
6739
+ "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"
6740
+ ).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(
6509
6741
  async (url, opts) => {
6510
6742
  try {
6511
6743
  const { report } = await browserCapture({
@@ -6528,7 +6760,9 @@ function createProgram(options = {}) {
6528
6760
  }
6529
6761
  }
6530
6762
  );
6531
- 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(
6763
+ program.command("report <url>").description(
6764
+ "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"
6765
+ ).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(
6532
6766
  async (url, opts) => {
6533
6767
  try {
6534
6768
  const { report } = await browserCapture({
@@ -6552,7 +6786,9 @@ function createProgram(options = {}) {
6552
6786
  }
6553
6787
  }
6554
6788
  );
6555
- 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) => {
6789
+ program.command("generate").description(
6790
+ '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"'
6791
+ ).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) => {
6556
6792
  const raw = readFileSync(tracePath, "utf-8");
6557
6793
  const trace = loadTrace(raw);
6558
6794
  const source = generateTest(trace, {
@@ -6569,6 +6805,7 @@ function createProgram(options = {}) {
6569
6805
  program.addCommand(createInitCommand());
6570
6806
  program.addCommand(createCiCommand());
6571
6807
  program.addCommand(createDoctorCommand());
6808
+ program.addCommand(createGetSkillCommand());
6572
6809
  const existingReportCmd = program.commands.find((c) => c.name() === "report");
6573
6810
  if (existingReportCmd !== void 0) {
6574
6811
  registerBaselineSubCommand(existingReportCmd);
@@ -6579,6 +6816,6 @@ function createProgram(options = {}) {
6579
6816
  return program;
6580
6817
  }
6581
6818
 
6582
- export { CI_EXIT, createCiCommand, createDoctorCommand, createInitCommand, createInstrumentCommand, createManifestCommand, createProgram, createTokensCommand, createTokensExportCommand, formatCiReport, isTTY, matchGlob, resolveTokenFilePath2 as resolveTokenFilePath, runCi, runInit };
6819
+ export { CI_EXIT, createCiCommand, createDoctorCommand, createGetSkillCommand, createInitCommand, createInstrumentCommand, createManifestCommand, createProgram, createTokensCommand, createTokensExportCommand, formatCiReport, isTTY, matchGlob, resolveTokenFilePath2 as resolveTokenFilePath, runCi, runInit };
6583
6820
  //# sourceMappingURL=index.js.map
6584
6821
  //# sourceMappingURL=index.js.map