@agent-scope/cli 1.20.0 → 1.20.1

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/cli.js CHANGED
@@ -1,7 +1,13 @@
1
1
  #!/usr/bin/env bun
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
2
8
 
3
9
  // src/program.ts
4
- import { readFileSync as readFileSync13 } from "fs";
10
+ import { readFileSync as readFileSync17 } from "fs";
5
11
  import { generateTest, loadTrace } from "@agent-scope/playwright";
6
12
  import { Command as Command12 } from "commander";
7
13
 
@@ -61,9 +67,9 @@ import { Command } from "commander";
61
67
  // src/component-bundler.ts
62
68
  import { dirname } from "path";
63
69
  import * as esbuild from "esbuild";
64
- async function buildComponentHarness(filePath, componentName, props, viewportWidth, projectCss, wrapperScript) {
70
+ async function buildComponentHarness(filePath, componentName, props, viewportWidth, projectCss, wrapperScript, screenshotPadding = 0) {
65
71
  const bundledScript = await bundleComponentToIIFE(filePath, componentName, props);
66
- return wrapInHtml(bundledScript, viewportWidth, projectCss, wrapperScript);
72
+ return wrapInHtml(bundledScript, viewportWidth, projectCss, wrapperScript, screenshotPadding);
67
73
  }
68
74
  async function bundleComponentToIIFE(filePath, componentName, props) {
69
75
  const propsJson = JSON.stringify(props).replace(/<\/script>/gi, "<\\/script>");
@@ -169,7 +175,7 @@ ${msg}`);
169
175
  }
170
176
  return outputFile.text;
171
177
  }
172
- function wrapInHtml(bundledScript, viewportWidth, projectCss, wrapperScript) {
178
+ function wrapInHtml(bundledScript, viewportWidth, projectCss, wrapperScript, screenshotPadding = 0) {
173
179
  const projectStyleBlock = projectCss != null && projectCss.length > 0 ? `<style id="scope-project-css">
174
180
  ${projectCss.replace(/<\/style>/gi, "<\\/style>")}
175
181
  </style>` : "";
@@ -179,10 +185,17 @@ ${projectCss.replace(/<\/style>/gi, "<\\/style>")}
179
185
  <head>
180
186
  <meta charset="UTF-8" />
181
187
  <meta name="viewport" content="width=${viewportWidth}, initial-scale=1.0" />
188
+ <script>
189
+ // Reset globals that persist on window across page.setContent() calls
190
+ // (document.open/write/close clears the DOM but NOT the JS global scope)
191
+ window.__SCOPE_WRAPPER__ = null;
192
+ window.__SCOPE_RENDER_COMPLETE__ = false;
193
+ window.__SCOPE_RENDER_ERROR__ = null;
194
+ </script>
182
195
  <style>
183
196
  *, *::before, *::after { box-sizing: border-box; }
184
197
  html, body { margin: 0; padding: 0; background: #fff; font-family: system-ui, sans-serif; }
185
- #scope-root { display: inline-block; min-width: 1px; min-height: 1px; }
198
+ #scope-root { display: inline-block; min-width: 1px; min-height: 1px; margin: ${screenshotPadding}px; }
186
199
  </style>
187
200
  ${projectStyleBlock}
188
201
  </head>
@@ -569,22 +582,22 @@ async function getTailwindCompiler(cwd) {
569
582
  from: entryPath,
570
583
  loadStylesheet
571
584
  });
572
- const build3 = result.build.bind(result);
573
- compilerCache = { cwd, build: build3 };
574
- return build3;
585
+ const build4 = result.build.bind(result);
586
+ compilerCache = { cwd, build: build4 };
587
+ return build4;
575
588
  }
576
589
  async function getCompiledCssForClasses(cwd, classes) {
577
- const build3 = await getTailwindCompiler(cwd);
578
- if (build3 === null) return null;
590
+ const build4 = await getTailwindCompiler(cwd);
591
+ if (build4 === null) return null;
579
592
  const deduped = [...new Set(classes)].filter(Boolean);
580
593
  if (deduped.length === 0) return null;
581
- return build3(deduped);
594
+ return build4(deduped);
582
595
  }
583
596
  async function compileGlobalCssFile(cssFilePath, cwd) {
584
- const { existsSync: existsSync16, readFileSync: readFileSync14 } = await import("fs");
597
+ const { existsSync: existsSync18, readFileSync: readFileSync18 } = await import("fs");
585
598
  const { createRequire: createRequire3 } = await import("module");
586
- if (!existsSync16(cssFilePath)) return null;
587
- const raw = readFileSync14(cssFilePath, "utf-8");
599
+ if (!existsSync18(cssFilePath)) return null;
600
+ const raw = readFileSync18(cssFilePath, "utf-8");
588
601
  const needsCompile = /@tailwind|@import\s+['"]tailwindcss/.test(raw);
589
602
  if (!needsCompile) {
590
603
  return raw;
@@ -667,8 +680,17 @@ async function shutdownPool() {
667
680
  }
668
681
  }
669
682
  async function renderComponent(filePath, componentName, props, viewportWidth, viewportHeight) {
683
+ const PAD = 24;
670
684
  const pool = await getPool(viewportWidth, viewportHeight);
671
- const htmlHarness = await buildComponentHarness(filePath, componentName, props, viewportWidth);
685
+ const htmlHarness = await buildComponentHarness(
686
+ filePath,
687
+ componentName,
688
+ props,
689
+ viewportWidth,
690
+ void 0,
691
+ void 0,
692
+ PAD
693
+ );
672
694
  const slot = await pool.acquire();
673
695
  const { page } = slot;
674
696
  try {
@@ -708,7 +730,6 @@ async function renderComponent(filePath, componentName, props, viewportWidth, vi
708
730
  `Component "${componentName}" rendered with zero bounding box \u2014 it may be invisible or not mounted`
709
731
  );
710
732
  }
711
- const PAD = 24;
712
733
  const MIN_W = 320;
713
734
  const MIN_H = 200;
714
735
  const clipX = Math.max(0, boundingBox.x - PAD);
@@ -1055,14 +1076,137 @@ function createCiCommand() {
1055
1076
  }
1056
1077
 
1057
1078
  // src/doctor-commands.ts
1058
- import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync3, statSync } from "fs";
1059
- import { join, resolve as resolve3 } from "path";
1079
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync4, statSync } from "fs";
1080
+ import { join as join2, resolve as resolve3 } from "path";
1060
1081
  import { Command as Command2 } from "commander";
1082
+
1083
+ // src/diagnostics.ts
1084
+ import { constants, existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
1085
+ import { access } from "fs/promises";
1086
+ import { dirname as dirname2, join } from "path";
1087
+ var PLAYWRIGHT_BROWSER_HINTS = [
1088
+ "executable doesn't exist",
1089
+ "browserType.launch",
1090
+ "looks like playwright was just installed or updated",
1091
+ "please run the following command to download new browsers",
1092
+ "could not find chromium"
1093
+ ];
1094
+ var MISSING_DEPENDENCY_HINTS = ["could not resolve", "cannot find module", "module not found"];
1095
+ var REQUIRED_HARNESS_DEPENDENCIES = ["react", "react-dom", "react/jsx-runtime"];
1096
+ function getEffectivePlaywrightBrowsersPath() {
1097
+ const value = process.env.PLAYWRIGHT_BROWSERS_PATH;
1098
+ return typeof value === "string" && value.length > 0 ? value : null;
1099
+ }
1100
+ function getPlaywrightBrowserRemediation(status) {
1101
+ const effectivePath = status?.effectiveBrowserPath ?? getEffectivePlaywrightBrowsersPath();
1102
+ if (effectivePath !== null) {
1103
+ const pathProblem = status?.browserPathExists === false ? "missing" : status?.browserPathWritable === false ? "unwritable" : "unavailable";
1104
+ return `PLAYWRIGHT_BROWSERS_PATH is set to ${effectivePath}, but that browser cache is ${pathProblem}. Unset PLAYWRIGHT_BROWSERS_PATH and run \`bunx playwright install chromium\`, or install and run with the same writable path: \`PLAYWRIGHT_BROWSERS_PATH=${effectivePath} bunx playwright install chromium\`.`;
1105
+ }
1106
+ return "Run `bunx playwright install chromium` in this sandbox, then retry the Scope command.";
1107
+ }
1108
+ function diagnoseScopeError(error, cwd = process.cwd()) {
1109
+ const message = error instanceof Error ? error.message : String(error);
1110
+ const normalized = message.toLowerCase();
1111
+ if (PLAYWRIGHT_BROWSER_HINTS.some((hint) => normalized.includes(hint))) {
1112
+ const browserPath = extractPlaywrightBrowserPath(message);
1113
+ const browserPathHint = browserPath === null ? "" : ` Scope tried to launch Chromium from ${browserPath}.`;
1114
+ return {
1115
+ code: "PLAYWRIGHT_BROWSERS_MISSING",
1116
+ message: "Playwright Chromium is unavailable for Scope browser rendering.",
1117
+ recovery: getPlaywrightBrowserRemediation() + browserPathHint + " Use `scope doctor --json` to verify the browser check passes before rerunning render/site/instrument."
1118
+ };
1119
+ }
1120
+ if (MISSING_DEPENDENCY_HINTS.some((hint) => normalized.includes(hint))) {
1121
+ const packageManager = detectPackageManager(cwd);
1122
+ return {
1123
+ code: "TARGET_PROJECT_DEPENDENCIES_MISSING",
1124
+ message: "The target project's dependencies appear to be missing or incomplete.",
1125
+ recovery: `Run \`${packageManager} install\` in ${cwd}, then rerun \`scope doctor\` and retry the Scope command.`
1126
+ };
1127
+ }
1128
+ return null;
1129
+ }
1130
+ function formatScopeDiagnostic(error, cwd = process.cwd()) {
1131
+ const message = error instanceof Error ? error.message : String(error);
1132
+ const diagnostic = diagnoseScopeError(error, cwd);
1133
+ if (diagnostic === null) return `Error: ${message}`;
1134
+ return `Error [${diagnostic.code}]: ${diagnostic.message}
1135
+ Recovery: ${diagnostic.recovery}
1136
+ Cause: ${message}`;
1137
+ }
1138
+ async function getPlaywrightBrowserStatus(cwd = process.cwd()) {
1139
+ const effectiveBrowserPath = getEffectivePlaywrightBrowsersPath();
1140
+ const executablePath = getPlaywrightChromiumExecutablePath(cwd);
1141
+ const available = executablePath !== null && existsSync3(executablePath);
1142
+ const browserPathExists = effectiveBrowserPath === null ? null : existsSync3(effectiveBrowserPath);
1143
+ const browserPathWritable = effectiveBrowserPath === null ? null : await isWritableBrowserPath(effectiveBrowserPath);
1144
+ return {
1145
+ effectiveBrowserPath,
1146
+ executablePath,
1147
+ available,
1148
+ browserPathExists,
1149
+ browserPathWritable,
1150
+ remediation: getPlaywrightBrowserRemediation({
1151
+ effectiveBrowserPath,
1152
+ browserPathExists,
1153
+ browserPathWritable
1154
+ })
1155
+ };
1156
+ }
1157
+ function getPlaywrightChromiumExecutablePath(cwd = process.cwd()) {
1158
+ try {
1159
+ const packageJsonPath = __require.resolve("playwright/package.json", { paths: [cwd] });
1160
+ const packageJson = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
1161
+ if (!packageJson.version) return null;
1162
+ const playwrightPath = __require.resolve("playwright", { paths: [cwd] });
1163
+ const { chromium: chromium5 } = __require(playwrightPath);
1164
+ const executablePath = chromium5?.executablePath?.();
1165
+ if (typeof executablePath !== "string" || executablePath.length === 0) return null;
1166
+ return executablePath;
1167
+ } catch {
1168
+ return null;
1169
+ }
1170
+ }
1171
+ async function isWritableBrowserPath(browserPath) {
1172
+ const candidate = existsSync3(browserPath) ? browserPath : dirname2(browserPath);
1173
+ try {
1174
+ await access(candidate, constants.W_OK);
1175
+ return true;
1176
+ } catch {
1177
+ return false;
1178
+ }
1179
+ }
1180
+ function detectPackageManager(cwd = process.cwd()) {
1181
+ if (existsSync3(join(cwd, "bun.lock")) || existsSync3(join(cwd, "bun.lockb"))) return "bun";
1182
+ if (existsSync3(join(cwd, "pnpm-lock.yaml"))) return "pnpm";
1183
+ if (existsSync3(join(cwd, "yarn.lock"))) return "yarn";
1184
+ return "npm";
1185
+ }
1186
+ function hasLikelyInstalledDependencies(cwd = process.cwd()) {
1187
+ return existsSync3(join(cwd, "node_modules"));
1188
+ }
1189
+ function getMissingHarnessDependencies(cwd = process.cwd()) {
1190
+ return REQUIRED_HARNESS_DEPENDENCIES.filter((dependencyName) => {
1191
+ try {
1192
+ __require.resolve(dependencyName, { paths: [cwd] });
1193
+ return false;
1194
+ } catch {
1195
+ return true;
1196
+ }
1197
+ });
1198
+ }
1199
+ function extractPlaywrightBrowserPath(message) {
1200
+ const match = message.match(/Executable doesn't exist at\s+([^\n]+)/i);
1201
+ return match?.[1]?.trim() ?? null;
1202
+ }
1203
+
1204
+ // src/doctor-commands.ts
1061
1205
  function collectSourceFiles(dir) {
1062
- if (!existsSync3(dir)) return [];
1206
+ if (!existsSync4(dir)) return [];
1063
1207
  const results = [];
1064
1208
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1065
- const full = join(dir, entry.name);
1209
+ const full = join2(dir, entry.name);
1066
1210
  if (entry.isDirectory() && entry.name !== "node_modules" && entry.name !== ".reactscope") {
1067
1211
  results.push(...collectSourceFiles(full));
1068
1212
  } else if (entry.isFile() && /\.(tsx?|jsx?)$/.test(entry.name)) {
@@ -1071,17 +1215,47 @@ function collectSourceFiles(dir) {
1071
1215
  }
1072
1216
  return results;
1073
1217
  }
1218
+ var TAILWIND_CONFIG_FILES = [
1219
+ "tailwind.config.js",
1220
+ "tailwind.config.cjs",
1221
+ "tailwind.config.mjs",
1222
+ "tailwind.config.ts",
1223
+ "postcss.config.js",
1224
+ "postcss.config.cjs",
1225
+ "postcss.config.mjs",
1226
+ "postcss.config.ts"
1227
+ ];
1228
+ function hasTailwindSetup(cwd) {
1229
+ if (TAILWIND_CONFIG_FILES.some((file) => existsSync4(resolve3(cwd, file)))) {
1230
+ return true;
1231
+ }
1232
+ const packageJsonPath = resolve3(cwd, "package.json");
1233
+ if (!existsSync4(packageJsonPath)) return false;
1234
+ try {
1235
+ const pkg = JSON.parse(readFileSync4(packageJsonPath, "utf-8"));
1236
+ return [pkg.dependencies, pkg.devDependencies].some(
1237
+ (deps) => deps && Object.keys(deps).some(
1238
+ (name) => name === "tailwindcss" || name.startsWith("@tailwindcss/")
1239
+ )
1240
+ );
1241
+ } catch {
1242
+ return false;
1243
+ }
1244
+ }
1245
+ function getPlaywrightInstallCommand(effectiveBrowserPath) {
1246
+ return effectiveBrowserPath === null ? "bunx playwright install chromium" : `PLAYWRIGHT_BROWSERS_PATH=${effectiveBrowserPath} bunx playwright install chromium`;
1247
+ }
1074
1248
  function checkConfig(cwd) {
1075
1249
  const configPath = resolve3(cwd, "reactscope.config.json");
1076
- if (!existsSync3(configPath)) {
1250
+ if (!existsSync4(configPath)) {
1077
1251
  return {
1078
1252
  name: "config",
1079
1253
  status: "error",
1080
- message: "reactscope.config.json not found \u2014 run `scope init`"
1254
+ message: "reactscope.config.json not found \u2014 run `scope init` in the target project root"
1081
1255
  };
1082
1256
  }
1083
1257
  try {
1084
- JSON.parse(readFileSync3(configPath, "utf-8"));
1258
+ JSON.parse(readFileSync4(configPath, "utf-8"));
1085
1259
  return { name: "config", status: "ok", message: "reactscope.config.json valid" };
1086
1260
  } catch {
1087
1261
  return { name: "config", status: "error", message: "reactscope.config.json is not valid JSON" };
@@ -1090,14 +1264,14 @@ function checkConfig(cwd) {
1090
1264
  function checkTokens(cwd) {
1091
1265
  const configPath = resolve3(cwd, "reactscope.config.json");
1092
1266
  let tokensPath = resolve3(cwd, "reactscope.tokens.json");
1093
- if (existsSync3(configPath)) {
1267
+ if (existsSync4(configPath)) {
1094
1268
  try {
1095
- const cfg = JSON.parse(readFileSync3(configPath, "utf-8"));
1269
+ const cfg = JSON.parse(readFileSync4(configPath, "utf-8"));
1096
1270
  if (cfg.tokens?.file) tokensPath = resolve3(cwd, cfg.tokens.file);
1097
1271
  } catch {
1098
1272
  }
1099
1273
  }
1100
- if (!existsSync3(tokensPath)) {
1274
+ if (!existsSync4(tokensPath)) {
1101
1275
  return {
1102
1276
  name: "tokens",
1103
1277
  status: "warn",
@@ -1105,7 +1279,7 @@ function checkTokens(cwd) {
1105
1279
  };
1106
1280
  }
1107
1281
  try {
1108
- const raw = JSON.parse(readFileSync3(tokensPath, "utf-8"));
1282
+ const raw = JSON.parse(readFileSync4(tokensPath, "utf-8"));
1109
1283
  if (!raw.version) {
1110
1284
  return { name: "tokens", status: "warn", message: "Token file is missing a `version` field" };
1111
1285
  }
@@ -1117,21 +1291,28 @@ function checkTokens(cwd) {
1117
1291
  function checkGlobalCss(cwd) {
1118
1292
  const configPath = resolve3(cwd, "reactscope.config.json");
1119
1293
  let globalCss = [];
1120
- if (existsSync3(configPath)) {
1294
+ if (existsSync4(configPath)) {
1121
1295
  try {
1122
- const cfg = JSON.parse(readFileSync3(configPath, "utf-8"));
1296
+ const cfg = JSON.parse(readFileSync4(configPath, "utf-8"));
1123
1297
  globalCss = cfg.components?.wrappers?.globalCSS ?? [];
1124
1298
  } catch {
1125
1299
  }
1126
1300
  }
1127
1301
  if (globalCss.length === 0) {
1302
+ if (!hasTailwindSetup(cwd)) {
1303
+ return {
1304
+ name: "globalCSS",
1305
+ status: "ok",
1306
+ message: "No globalCSS configured \u2014 skipping CSS injection for this non-Tailwind project"
1307
+ };
1308
+ }
1128
1309
  return {
1129
1310
  name: "globalCSS",
1130
1311
  status: "warn",
1131
1312
  message: "No globalCSS configured \u2014 Tailwind styles won't apply to renders. Add `components.wrappers.globalCSS` to reactscope.config.json"
1132
1313
  };
1133
1314
  }
1134
- const missing = globalCss.filter((f) => !existsSync3(resolve3(cwd, f)));
1315
+ const missing = globalCss.filter((f) => !existsSync4(resolve3(cwd, f)));
1135
1316
  if (missing.length > 0) {
1136
1317
  return {
1137
1318
  name: "globalCSS",
@@ -1147,11 +1328,11 @@ function checkGlobalCss(cwd) {
1147
1328
  }
1148
1329
  function checkManifest(cwd) {
1149
1330
  const manifestPath = resolve3(cwd, ".reactscope", "manifest.json");
1150
- if (!existsSync3(manifestPath)) {
1331
+ if (!existsSync4(manifestPath)) {
1151
1332
  return {
1152
1333
  name: "manifest",
1153
1334
  status: "warn",
1154
- message: "Manifest not found \u2014 run `scope manifest generate`"
1335
+ message: "Manifest not found \u2014 run `scope manifest generate` in the target project root"
1155
1336
  };
1156
1337
  }
1157
1338
  const manifestMtime = statSync(manifestPath).mtimeMs;
@@ -1168,6 +1349,54 @@ function checkManifest(cwd) {
1168
1349
  return { name: "manifest", status: "ok", message: "Manifest present and up to date" };
1169
1350
  }
1170
1351
  var ICONS = { ok: "\u2713", warn: "!", error: "\u2717" };
1352
+ function checkDependencies(cwd) {
1353
+ const packageManager = detectPackageManager(cwd);
1354
+ if (!hasLikelyInstalledDependencies(cwd)) {
1355
+ return {
1356
+ name: "dependencies",
1357
+ status: "error",
1358
+ remediationCode: "TARGET_PROJECT_DEPENDENCIES_MISSING",
1359
+ fixCommand: `${packageManager} install`,
1360
+ message: `node_modules not found \u2014 run \`${packageManager} install\` in ${cwd} before render/site/instrument`
1361
+ };
1362
+ }
1363
+ const missingHarnessDependencies = getMissingHarnessDependencies(cwd);
1364
+ if (missingHarnessDependencies.length > 0) {
1365
+ return {
1366
+ name: "dependencies",
1367
+ status: "error",
1368
+ remediationCode: "TARGET_PROJECT_HARNESS_DEPENDENCIES_MISSING",
1369
+ fixCommand: `${packageManager} install`,
1370
+ message: `Missing React harness dependencies: ${missingHarnessDependencies.join(", ")}. Run \`${packageManager} install\` in ${cwd}, then retry render/site/instrument.`
1371
+ };
1372
+ }
1373
+ return {
1374
+ name: "dependencies",
1375
+ status: "ok",
1376
+ message: "node_modules and React harness dependencies present"
1377
+ };
1378
+ }
1379
+ async function checkPlaywright(cwd) {
1380
+ const status = await getPlaywrightBrowserStatus(cwd);
1381
+ const pathDetails = status.effectiveBrowserPath === null ? "PLAYWRIGHT_BROWSERS_PATH is unset" : `PLAYWRIGHT_BROWSERS_PATH=${status.effectiveBrowserPath}; exists=${status.browserPathExists}; writable=${status.browserPathWritable}`;
1382
+ if (status.available) {
1383
+ return {
1384
+ name: "playwright",
1385
+ status: "ok",
1386
+ message: `Playwright package available (${pathDetails})`
1387
+ };
1388
+ }
1389
+ return {
1390
+ name: "playwright",
1391
+ status: "error",
1392
+ remediationCode: "PLAYWRIGHT_BROWSERS_MISSING",
1393
+ fixCommand: getPlaywrightInstallCommand(status.effectiveBrowserPath),
1394
+ message: `Playwright Chromium unavailable (${pathDetails}) \u2014 ${status.remediation}`
1395
+ };
1396
+ }
1397
+ function collectFixCommands(checks) {
1398
+ return checks.filter((check) => check.status === "error" && check.fixCommand !== void 0).map((check) => check.fixCommand).filter((command, index, commands) => commands.indexOf(command) === index);
1399
+ }
1171
1400
  function formatCheck(check) {
1172
1401
  return ` [${ICONS[check.status]}] ${check.name.padEnd(12)} ${check.message}`;
1173
1402
  }
@@ -1180,6 +1409,8 @@ CHECKS PERFORMED:
1180
1409
  tokens reactscope.tokens.json exists and passes validation
1181
1410
  css globalCSS files referenced in config actually exist
1182
1411
  manifest .reactscope/manifest.json exists and is not stale
1412
+ dependencies node_modules exists in the target project root
1413
+ playwright Playwright browser runtime is available
1183
1414
  (stale = source files modified after last generate)
1184
1415
 
1185
1416
  STATUS LEVELS: ok | warn | error
@@ -1189,20 +1420,34 @@ Run this first whenever renders fail or produce unexpected output.
1189
1420
  Examples:
1190
1421
  scope doctor
1191
1422
  scope doctor --json
1423
+ scope doctor --print-fix-commands
1192
1424
  scope doctor --json | jq '.checks[] | select(.status == "error")'`
1193
- ).option("--json", "Emit structured JSON output", false).action((opts) => {
1425
+ ).option("--json", "Emit structured JSON output", false).option(
1426
+ "--print-fix-commands",
1427
+ "Print deduplicated shell remediation commands for failing checks",
1428
+ false
1429
+ ).action(async (opts) => {
1194
1430
  const cwd = process.cwd();
1195
1431
  const checks = [
1196
1432
  checkConfig(cwd),
1197
1433
  checkTokens(cwd),
1198
1434
  checkGlobalCss(cwd),
1199
- checkManifest(cwd)
1435
+ checkManifest(cwd),
1436
+ checkDependencies(cwd),
1437
+ await checkPlaywright(cwd)
1200
1438
  ];
1201
1439
  const errors = checks.filter((c) => c.status === "error").length;
1202
1440
  const warnings = checks.filter((c) => c.status === "warn").length;
1441
+ const fixCommands = collectFixCommands(checks);
1442
+ if (opts.printFixCommands) {
1443
+ process.stdout.write(`${JSON.stringify({ cwd, fixCommands }, null, 2)}
1444
+ `);
1445
+ if (errors > 0) process.exit(1);
1446
+ return;
1447
+ }
1203
1448
  if (opts.json) {
1204
1449
  process.stdout.write(
1205
- `${JSON.stringify({ passed: checks.length - errors - warnings, warnings, errors, checks }, null, 2)}
1450
+ `${JSON.stringify({ passed: checks.length - errors - warnings, warnings, errors, fixCommands, checks }, null, 2)}
1206
1451
  `
1207
1452
  );
1208
1453
  if (errors > 0) process.exit(1);
@@ -1232,12 +1477,12 @@ Examples:
1232
1477
  import { Command as Command3 } from "commander";
1233
1478
 
1234
1479
  // src/skill-content.ts
1235
- 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';
1480
+ 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**Canonical agent workflow:**\n```\nscope get-skill > /tmp/scope-skill.md # bootstrap command semantics into agent context\nscope init --yes # scaffold config + auto-generate manifest\nscope doctor --json # validate config, tokens, globalCSS, manifest freshness, deps, Playwright\nscope manifest query --context ThemeContext --format json\nscope render all --format json --output-dir .reactscope/renders\nscope site build --output .reactscope/site\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` / `.scope.ts`)\nScope files define **named rendering scenarios** and optional provider wrappers next to a component. They are the primary way to ensure `render all` produces meaningful screenshots.\n\nDiscovery is deterministic: for `Button.tsx`, Scope checks `Button.scope.tsx`, then `.scope.ts`, `.scope.jsx`, `.scope.js` in the same directory and uses the first file that exists.\n\n```tsx\n// Button.scope.tsx\nexport const scenarios = {\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 Record<string, Record<string, unknown>>;\n```\n\nOptional wrapper:\n\n```tsx\nimport type { ReactNode } from \'react\';\nimport { ThemeProvider } from \'../providers/ThemeProvider\';\n\nexport function wrapper({ children }: { children: ReactNode }) {\n return <ThemeProvider theme="dark">{children}</ThemeProvider>;\n}\n```\n\nContract:\n- Export `scenarios` as a plain object of scenario-name \u2192 props-object, either as a named export or under `default.scenarios`\n- Export `wrapper` as a function, either as a named export or under `default.wrapper`\n- Non-object scenario values are skipped with a warning\n- If no scope file or no valid scenarios exist, Scope falls back to one bare render and inferred required-prop defaults\n- If 2+ scenarios exist, `render all` automatically runs a matrix and merges cells into each component JSON\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 --json\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- Target-project dependencies are installed (`node_modules` exists)\n- Playwright Chromium is available for render/site/instrument commands\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 component X --format json`\n\n**"I want to render all variants of a component"**\n\u2192 Define all variants in `.scope.tsx`, then `scope render all --format json --output-dir .reactscope/renders` (auto-matrix)\n\u2192 Or: `scope render matrix X --axes \'variant:primary,secondary,danger\' --format json`\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 profile a live SPA"**\n\u2192 Generate a manifest, then `scope instrument profile SearchPage --interaction \'[{"action":"click","target":"button"}]\'`\n\u2192 For auth/timing-heavy apps, follow `docs/profiling-production-spas.md`\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\nPublished package:\n\n```bash\nnpm install -g @agent-scope/cli # global\nnpm install --save-dev @agent-scope/cli # per-project\n```\n\nLocal-from-source quickstart for this repo:\n\n```bash\nbun install\nbun run build\nbunx playwright install chromium\ncd fixtures/tailwind-showcase\nbun install\n../../packages/cli/dist/cli.js init --yes\n../../packages/cli/dist/cli.js doctor --json\n../../packages/cli/dist/cli.js render all --format json --output-dir .reactscope/renders\n../../packages/cli/dist/cli.js site build --output .reactscope/site\n```\n\nBinary: `scope` (published install) or `packages/cli/dist/cli.js` (local build)\n\n---\n\n## Core Workflow\n\n```\nget-skill \u2192 init --yes \u2192 doctor --json \u2192 manifest query/get/list --format json \u2192 render all --format json \u2192 site build \u2192 instrument profile \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, manifest staleness, target-project dependencies, and Playwright Chromium availability.\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 --json\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- `dependencies` \u2014 `node_modules` exists in the target project root\n- `playwright` \u2014 Playwright Chromium is available before render/site/instrument\n\nIf `dependencies` fails, run `bun install` (or the package manager detected by your lockfile) in the target project root, then rerun `scope doctor --json`.\n\nIf `playwright` fails, run `bunx playwright install chromium`, then rerun `scope doctor --json` before retrying `scope render component`, `scope render all`, `scope site build`, or `scope instrument ...`.\n\n```\n$ scope doctor --json\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 component Button\nscope render component Button --props \'{"variant":"primary","children":"Click me"}\'\nscope render component Button --viewport 375x812\nscope render component Button --output button.png\nscope render component 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 SearchPage --interaction \'[{"action":"click","target":"button"}]\'\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 component 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 component 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| `PLAYWRIGHT_BROWSERS_MISSING` / `browserType.launch: Executable doesn\'t exist` | Playwright Chromium is not installed in this sandbox | Run `bunx playwright install chromium`, then `scope doctor --json`, then retry render/site/instrument |\n| `TARGET_PROJECT_DEPENDENCIES_MISSING` / `Could not resolve "react"` | Target project dependencies are missing | Run `bun install` (or the detected package manager) in the target project root, then `scope doctor --json` |\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';
1236
1481
 
1237
1482
  // src/get-skill-command.ts
1238
1483
  function createGetSkillCommand() {
1239
1484
  return new Command3("get-skill").description(
1240
- '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'
1485
+ 'Print the embedded Scope SKILL.md to stdout.\n\nAgents: load this first, then follow the canonical workflow in the skill:\n init --yes \u2192 doctor --json \u2192 manifest --format json \u2192 render all --format json \u2192 site build\nThe skill documents .scope.tsx discovery/exports, config paths, profiler usage,\nand failure recovery.\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'
1241
1486
  ).option("--json", "Wrap output in JSON { skill: string } instead of raw markdown").action((opts) => {
1242
1487
  if (opts.json) {
1243
1488
  process.stdout.write(`${JSON.stringify({ skill: SKILL_CONTENT }, null, 2)}
@@ -1249,15 +1494,15 @@ function createGetSkillCommand() {
1249
1494
  }
1250
1495
 
1251
1496
  // src/init/index.ts
1252
- import { appendFileSync, existsSync as existsSync5, mkdirSync, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
1253
- import { join as join3 } from "path";
1497
+ import { appendFileSync, existsSync as existsSync6, mkdirSync, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
1498
+ import { join as join4 } from "path";
1254
1499
  import * as readline from "readline";
1255
1500
 
1256
1501
  // src/init/detect.ts
1257
- import { existsSync as existsSync4, readdirSync as readdirSync2, readFileSync as readFileSync4 } from "fs";
1258
- import { join as join2 } from "path";
1502
+ import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync5 } from "fs";
1503
+ import { join as join3 } from "path";
1259
1504
  function hasConfigFile(dir, stem) {
1260
- if (!existsSync4(dir)) return false;
1505
+ if (!existsSync5(dir)) return false;
1261
1506
  try {
1262
1507
  const entries = readdirSync2(dir);
1263
1508
  return entries.some((f) => f === stem || f.startsWith(`${stem}.`));
@@ -1267,7 +1512,7 @@ function hasConfigFile(dir, stem) {
1267
1512
  }
1268
1513
  function readSafe(path) {
1269
1514
  try {
1270
- return readFileSync4(path, "utf-8");
1515
+ return readFileSync5(path, "utf-8");
1271
1516
  } catch {
1272
1517
  return null;
1273
1518
  }
@@ -1279,16 +1524,16 @@ function detectFramework(rootDir, packageDeps) {
1279
1524
  if ("react-scripts" in packageDeps) return "cra";
1280
1525
  return "unknown";
1281
1526
  }
1282
- function detectPackageManager(rootDir) {
1283
- if (existsSync4(join2(rootDir, "bun.lock"))) return "bun";
1284
- if (existsSync4(join2(rootDir, "yarn.lock"))) return "yarn";
1285
- if (existsSync4(join2(rootDir, "pnpm-lock.yaml"))) return "pnpm";
1286
- if (existsSync4(join2(rootDir, "package-lock.json"))) return "npm";
1527
+ function detectPackageManager2(rootDir) {
1528
+ if (existsSync5(join3(rootDir, "bun.lock"))) return "bun";
1529
+ if (existsSync5(join3(rootDir, "yarn.lock"))) return "yarn";
1530
+ if (existsSync5(join3(rootDir, "pnpm-lock.yaml"))) return "pnpm";
1531
+ if (existsSync5(join3(rootDir, "package-lock.json"))) return "npm";
1287
1532
  return "npm";
1288
1533
  }
1289
1534
  function detectTypeScript(rootDir) {
1290
- const candidate = join2(rootDir, "tsconfig.json");
1291
- if (existsSync4(candidate)) {
1535
+ const candidate = join3(rootDir, "tsconfig.json");
1536
+ if (existsSync5(candidate)) {
1292
1537
  return { typescript: true, tsconfigPath: candidate };
1293
1538
  }
1294
1539
  return { typescript: false, tsconfigPath: null };
@@ -1300,8 +1545,8 @@ function detectComponentPatterns(rootDir, typescript) {
1300
1545
  const ext = typescript ? "tsx" : "jsx";
1301
1546
  const altExt = typescript ? "jsx" : "jsx";
1302
1547
  for (const dir of COMPONENT_DIRS) {
1303
- const absDir = join2(rootDir, dir);
1304
- if (!existsSync4(absDir)) continue;
1548
+ const absDir = join3(rootDir, dir);
1549
+ if (!existsSync5(absDir)) continue;
1305
1550
  let hasComponents = false;
1306
1551
  try {
1307
1552
  const entries = readdirSync2(absDir, { withFileTypes: true });
@@ -1312,7 +1557,7 @@ function detectComponentPatterns(rootDir, typescript) {
1312
1557
  hasComponents = entries.some(
1313
1558
  (e) => e.isDirectory() && (() => {
1314
1559
  try {
1315
- return readdirSync2(join2(absDir, e.name)).some(
1560
+ return readdirSync2(join3(absDir, e.name)).some(
1316
1561
  (f) => COMPONENT_EXTS.some((x) => f.endsWith(x))
1317
1562
  );
1318
1563
  } catch {
@@ -1349,12 +1594,37 @@ var GLOBAL_CSS_CANDIDATES = [
1349
1594
  "styles/index.css"
1350
1595
  ];
1351
1596
  function detectGlobalCSSFiles(rootDir) {
1352
- return GLOBAL_CSS_CANDIDATES.filter((rel) => existsSync4(join2(rootDir, rel)));
1597
+ return GLOBAL_CSS_CANDIDATES.filter((rel) => existsSync5(join3(rootDir, rel)));
1353
1598
  }
1354
1599
  var TAILWIND_STEMS = ["tailwind.config"];
1355
1600
  var CSS_EXTS = [".css", ".scss", ".sass", ".less"];
1356
1601
  var THEME_SUFFIXES = [".theme.ts", ".theme.js", ".theme.tsx"];
1357
1602
  var CSS_CUSTOM_PROPS_RE = /:root\s*\{[^}]*--[a-zA-Z]/;
1603
+ var TAILWIND_V4_THEME_RE = /@theme\s*(?:inline\s*)?\{[^}]*--[a-zA-Z]/;
1604
+ var MAX_SCAN_DEPTH = 4;
1605
+ var SKIP_CSS_NAMES = ["compiled", ".min."];
1606
+ function collectCSSFiles(dir, depth) {
1607
+ if (depth > MAX_SCAN_DEPTH) return [];
1608
+ const results = [];
1609
+ try {
1610
+ const entries = readdirSync2(dir, { withFileTypes: true });
1611
+ for (const entry of entries) {
1612
+ if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".next") {
1613
+ continue;
1614
+ }
1615
+ const full = join3(dir, entry.name);
1616
+ if (entry.isFile() && CSS_EXTS.some((x) => entry.name.endsWith(x))) {
1617
+ if (!SKIP_CSS_NAMES.some((skip) => entry.name.includes(skip))) {
1618
+ results.push(full);
1619
+ }
1620
+ } else if (entry.isDirectory()) {
1621
+ results.push(...collectCSSFiles(full, depth + 1));
1622
+ }
1623
+ }
1624
+ } catch {
1625
+ }
1626
+ return results;
1627
+ }
1358
1628
  function detectTokenSources(rootDir) {
1359
1629
  const sources = [];
1360
1630
  for (const stem of TAILWIND_STEMS) {
@@ -1363,44 +1633,65 @@ function detectTokenSources(rootDir) {
1363
1633
  const entries = readdirSync2(rootDir);
1364
1634
  const match = entries.find((f) => f === stem || f.startsWith(`${stem}.`));
1365
1635
  if (match) {
1366
- sources.push({ kind: "tailwind-config", path: join2(rootDir, match) });
1636
+ sources.push({ kind: "tailwind-config", path: join3(rootDir, match) });
1367
1637
  }
1368
1638
  } catch {
1369
1639
  }
1370
1640
  }
1371
1641
  }
1372
- const srcDir = join2(rootDir, "src");
1373
- const dirsToScan = existsSync4(srcDir) ? [srcDir] : [];
1374
- for (const scanDir of dirsToScan) {
1375
- try {
1376
- const entries = readdirSync2(scanDir, { withFileTypes: true });
1377
- for (const entry of entries) {
1378
- if (entry.isFile() && CSS_EXTS.some((x) => entry.name.endsWith(x))) {
1379
- const filePath = join2(scanDir, entry.name);
1380
- const content = readSafe(filePath);
1381
- if (content !== null && CSS_CUSTOM_PROPS_RE.test(content)) {
1382
- sources.push({ kind: "css-custom-properties", path: filePath });
1383
- }
1384
- }
1642
+ const srcDir = join3(rootDir, "src");
1643
+ if (existsSync5(srcDir)) {
1644
+ const cssFiles = collectCSSFiles(srcDir, 0);
1645
+ const seen = /* @__PURE__ */ new Set();
1646
+ for (const filePath of cssFiles) {
1647
+ const content = readSafe(filePath);
1648
+ if (content === null) continue;
1649
+ if (TAILWIND_V4_THEME_RE.test(content) && !seen.has(filePath)) {
1650
+ sources.push({ kind: "tailwind-v4-theme", path: filePath });
1651
+ seen.add(filePath);
1652
+ }
1653
+ if (CSS_CUSTOM_PROPS_RE.test(content) && !seen.has(filePath)) {
1654
+ sources.push({ kind: "css-custom-properties", path: filePath });
1655
+ seen.add(filePath);
1385
1656
  }
1386
- } catch {
1387
1657
  }
1388
1658
  }
1389
- if (existsSync4(srcDir)) {
1390
- try {
1391
- const entries = readdirSync2(srcDir);
1392
- for (const entry of entries) {
1393
- if (THEME_SUFFIXES.some((s) => entry.endsWith(s))) {
1394
- sources.push({ kind: "theme-file", path: join2(srcDir, entry) });
1395
- }
1659
+ for (const tokenDir of ["tokens", "styles", "theme"]) {
1660
+ const dir = join3(rootDir, tokenDir);
1661
+ if (!existsSync5(dir)) continue;
1662
+ const cssFiles = collectCSSFiles(dir, 0);
1663
+ for (const filePath of cssFiles) {
1664
+ const content = readSafe(filePath);
1665
+ if (content === null) continue;
1666
+ if (TAILWIND_V4_THEME_RE.test(content)) {
1667
+ sources.push({ kind: "tailwind-v4-theme", path: filePath });
1668
+ } else if (CSS_CUSTOM_PROPS_RE.test(content)) {
1669
+ sources.push({ kind: "css-custom-properties", path: filePath });
1396
1670
  }
1397
- } catch {
1398
1671
  }
1399
1672
  }
1673
+ if (existsSync5(srcDir)) {
1674
+ const scanThemeFiles = (dir, depth) => {
1675
+ if (depth > MAX_SCAN_DEPTH) return;
1676
+ try {
1677
+ const entries = readdirSync2(dir, { withFileTypes: true });
1678
+ for (const entry of entries) {
1679
+ if (entry.name === "node_modules" || entry.name === "dist") continue;
1680
+ if (entry.isFile() && THEME_SUFFIXES.some((s) => entry.name.endsWith(s))) {
1681
+ sources.push({ kind: "theme-file", path: join3(dir, entry.name) });
1682
+ } else if (entry.isDirectory()) {
1683
+ scanThemeFiles(join3(dir, entry.name), depth + 1);
1684
+ }
1685
+ }
1686
+ } catch {
1687
+ }
1688
+ };
1689
+ scanThemeFiles(srcDir, 0);
1690
+ }
1400
1691
  return sources;
1401
1692
  }
1402
1693
  function detectProject(rootDir) {
1403
- const pkgPath = join2(rootDir, "package.json");
1694
+ const pkgPath = join3(rootDir, "package.json");
1404
1695
  let packageDeps = {};
1405
1696
  const pkgContent = readSafe(pkgPath);
1406
1697
  if (pkgContent !== null) {
@@ -1415,7 +1706,7 @@ function detectProject(rootDir) {
1415
1706
  }
1416
1707
  const framework = detectFramework(rootDir, packageDeps);
1417
1708
  const { typescript, tsconfigPath } = detectTypeScript(rootDir);
1418
- const packageManager = detectPackageManager(rootDir);
1709
+ const packageManager = detectPackageManager2(rootDir);
1419
1710
  const componentPatterns = detectComponentPatterns(rootDir, typescript);
1420
1711
  const tokenSources = detectTokenSources(rootDir);
1421
1712
  const globalCSSFiles = detectGlobalCSSFiles(rootDir);
@@ -1470,9 +1761,9 @@ function createRL() {
1470
1761
  });
1471
1762
  }
1472
1763
  async function ask(rl, question) {
1473
- return new Promise((resolve19) => {
1764
+ return new Promise((resolve21) => {
1474
1765
  rl.question(question, (answer) => {
1475
- resolve19(answer.trim());
1766
+ resolve21(answer.trim());
1476
1767
  });
1477
1768
  });
1478
1769
  }
@@ -1481,9 +1772,9 @@ async function askWithDefault(rl, label, defaultValue) {
1481
1772
  return answer.length > 0 ? answer : defaultValue;
1482
1773
  }
1483
1774
  function ensureGitignoreEntry(rootDir, entry) {
1484
- const gitignorePath = join3(rootDir, ".gitignore");
1485
- if (existsSync5(gitignorePath)) {
1486
- const content = readFileSync5(gitignorePath, "utf-8");
1775
+ const gitignorePath = join4(rootDir, ".gitignore");
1776
+ if (existsSync6(gitignorePath)) {
1777
+ const content = readFileSync6(gitignorePath, "utf-8");
1487
1778
  const normalised = entry.replace(/\/$/, "");
1488
1779
  const lines = content.split("\n").map((l) => l.trim());
1489
1780
  if (lines.includes(entry) || lines.includes(normalised)) {
@@ -1512,7 +1803,7 @@ function extractTailwindTokens(tokenSources) {
1512
1803
  return result;
1513
1804
  };
1514
1805
  var parseBlock = parseBlock2;
1515
- const raw = readFileSync5(tailwindSource.path, "utf-8");
1806
+ const raw = readFileSync6(tailwindSource.path, "utf-8");
1516
1807
  const tokens = {};
1517
1808
  const colorsKeyIdx = raw.indexOf("colors:");
1518
1809
  if (colorsKeyIdx !== -1) {
@@ -1593,14 +1884,14 @@ function extractTailwindTokens(tokenSources) {
1593
1884
  }
1594
1885
  }
1595
1886
  function scaffoldConfig(rootDir, config) {
1596
- const path = join3(rootDir, "reactscope.config.json");
1887
+ const path = join4(rootDir, "reactscope.config.json");
1597
1888
  writeFileSync3(path, `${JSON.stringify(config, null, 2)}
1598
1889
  `);
1599
1890
  return path;
1600
1891
  }
1601
1892
  function scaffoldTokenFile(rootDir, tokenFile, extractedTokens) {
1602
- const path = join3(rootDir, tokenFile);
1603
- if (!existsSync5(path)) {
1893
+ const path = join4(rootDir, tokenFile);
1894
+ if (!existsSync6(path)) {
1604
1895
  const stub = {
1605
1896
  $schema: "https://raw.githubusercontent.com/FlatFilers/Scope/main/packages/tokens/schema.json",
1606
1897
  version: "1.0.0",
@@ -1616,19 +1907,19 @@ function scaffoldTokenFile(rootDir, tokenFile, extractedTokens) {
1616
1907
  return path;
1617
1908
  }
1618
1909
  function scaffoldOutputDir(rootDir, outputDir) {
1619
- const dirPath = join3(rootDir, outputDir);
1910
+ const dirPath = join4(rootDir, outputDir);
1620
1911
  mkdirSync(dirPath, { recursive: true });
1621
- const keepPath = join3(dirPath, ".gitkeep");
1622
- if (!existsSync5(keepPath)) {
1912
+ const keepPath = join4(dirPath, ".gitkeep");
1913
+ if (!existsSync6(keepPath)) {
1623
1914
  writeFileSync3(keepPath, "");
1624
1915
  }
1625
1916
  return dirPath;
1626
1917
  }
1627
1918
  async function runInit(options) {
1628
1919
  const rootDir = options.cwd ?? process.cwd();
1629
- const configPath = join3(rootDir, "reactscope.config.json");
1920
+ const configPath = join4(rootDir, "reactscope.config.json");
1630
1921
  const created = [];
1631
- if (existsSync5(configPath) && !options.force) {
1922
+ if (existsSync6(configPath) && !options.force) {
1632
1923
  const msg = "reactscope.config.json already exists. Run with --force to overwrite.";
1633
1924
  process.stderr.write(`\u26A0\uFE0F ${msg}
1634
1925
  `);
@@ -1711,8 +2002,8 @@ async function runInit(options) {
1711
2002
  };
1712
2003
  const manifest = await generateManifest2(manifestConfig);
1713
2004
  const manifestCount = Object.keys(manifest.components).length;
1714
- const manifestOutPath = join3(rootDir, config.output.dir, "manifest.json");
1715
- mkdirSync(join3(rootDir, config.output.dir), { recursive: true });
2005
+ const manifestOutPath = join4(rootDir, config.output.dir, "manifest.json");
2006
+ mkdirSync(join4(rootDir, config.output.dir), { recursive: true });
1716
2007
  writeFileSync3(manifestOutPath, `${JSON.stringify(manifest, null, 2)}
1717
2008
  `);
1718
2009
  process.stdout.write(
@@ -1756,18 +2047,18 @@ import { BrowserPool as BrowserPool2 } from "@agent-scope/render";
1756
2047
  import { Command as Command7 } from "commander";
1757
2048
 
1758
2049
  // src/manifest-commands.ts
1759
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
2050
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "fs";
1760
2051
  import { resolve as resolve4 } from "path";
1761
2052
  import { generateManifest as generateManifest3 } from "@agent-scope/manifest";
1762
2053
  import { Command as Command5 } from "commander";
1763
2054
  var MANIFEST_PATH = ".reactscope/manifest.json";
1764
2055
  function loadManifest(manifestPath = MANIFEST_PATH) {
1765
2056
  const absPath = resolve4(process.cwd(), manifestPath);
1766
- if (!existsSync6(absPath)) {
2057
+ if (!existsSync7(absPath)) {
1767
2058
  throw new Error(`Manifest not found at ${absPath}.
1768
2059
  Run \`scope manifest generate\` first.`);
1769
2060
  }
1770
- const raw = readFileSync6(absPath, "utf-8");
2061
+ const raw = readFileSync7(absPath, "utf-8");
1771
2062
  return JSON.parse(raw);
1772
2063
  }
1773
2064
  function resolveFormat(formatFlag) {
@@ -1946,27 +2237,70 @@ function registerQuery(manifestCmd) {
1946
2237
  }
1947
2238
  );
1948
2239
  }
2240
+ function loadReactScopeConfig(rootDir) {
2241
+ const configPath = resolve4(rootDir, "reactscope.config.json");
2242
+ if (!existsSync7(configPath)) return null;
2243
+ try {
2244
+ const raw = readFileSync7(configPath, "utf-8");
2245
+ const cfg = JSON.parse(raw);
2246
+ const result = {};
2247
+ const components = cfg.components;
2248
+ if (components !== void 0 && typeof components === "object" && components !== null) {
2249
+ if (Array.isArray(components.include)) {
2250
+ result.include = components.include;
2251
+ }
2252
+ if (Array.isArray(components.exclude)) {
2253
+ result.exclude = components.exclude;
2254
+ }
2255
+ }
2256
+ if (Array.isArray(cfg.internalPatterns)) {
2257
+ result.internalPatterns = cfg.internalPatterns;
2258
+ }
2259
+ if (Array.isArray(cfg.collections)) {
2260
+ result.collections = cfg.collections;
2261
+ }
2262
+ const icons = cfg.icons;
2263
+ if (icons !== void 0 && typeof icons === "object" && icons !== null) {
2264
+ if (Array.isArray(icons.patterns)) {
2265
+ result.iconPatterns = icons.patterns;
2266
+ }
2267
+ }
2268
+ return result;
2269
+ } catch {
2270
+ return null;
2271
+ }
2272
+ }
1949
2273
  function registerGenerate(manifestCmd) {
1950
2274
  manifestCmd.command("generate").description(
1951
- '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'
2275
+ '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\nReads reactscope.config.json for:\n components.include glob patterns for source files\n components.exclude glob patterns to skip\n internalPatterns globs to flag components as internal\n collections named groups of components\n\nCLI flags (--include, --exclude) override config-file values.\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'
1952
2276
  ).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) => {
1953
2277
  try {
1954
2278
  const rootDir = resolve4(process.cwd(), opts.root ?? ".");
1955
2279
  const outputPath = resolve4(process.cwd(), opts.output);
1956
- const include = opts.include?.split(",").map((s) => s.trim());
1957
- const exclude = opts.exclude?.split(",").map((s) => s.trim());
2280
+ const configValues = loadReactScopeConfig(rootDir);
2281
+ const include = opts.include?.split(",").map((s) => s.trim()) ?? configValues?.include;
2282
+ const exclude = opts.exclude?.split(",").map((s) => s.trim()) ?? configValues?.exclude;
1958
2283
  process.stderr.write(`Scanning ${rootDir} for React components...
1959
2284
  `);
1960
2285
  const manifest = await generateManifest3({
1961
2286
  rootDir,
1962
2287
  ...include !== void 0 && { include },
1963
- ...exclude !== void 0 && { exclude }
2288
+ ...exclude !== void 0 && { exclude },
2289
+ ...configValues?.internalPatterns !== void 0 && {
2290
+ internalPatterns: configValues.internalPatterns
2291
+ },
2292
+ ...configValues?.collections !== void 0 && {
2293
+ collections: configValues.collections
2294
+ },
2295
+ ...configValues?.iconPatterns !== void 0 && {
2296
+ iconPatterns: configValues.iconPatterns
2297
+ }
1964
2298
  });
1965
2299
  const componentCount = Object.keys(manifest.components).length;
1966
2300
  process.stderr.write(`Found ${componentCount} components.
1967
2301
  `);
1968
2302
  const outputDir = outputPath.replace(/\/[^/]+$/, "");
1969
- if (!existsSync6(outputDir)) {
2303
+ if (!existsSync7(outputDir)) {
1970
2304
  mkdirSync2(outputDir, { recursive: true });
1971
2305
  }
1972
2306
  writeFileSync4(outputPath, JSON.stringify(manifest, null, 2), "utf-8");
@@ -2355,7 +2689,7 @@ Available: ${available}`
2355
2689
  process.stdout.write(`${JSON.stringify(result, null, 2)}
2356
2690
  `);
2357
2691
  } catch (err) {
2358
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
2692
+ process.stderr.write(`${formatScopeDiagnostic(err)}
2359
2693
  `);
2360
2694
  process.exit(1);
2361
2695
  }
@@ -2464,13 +2798,11 @@ function buildProfilingCollectScript() {
2464
2798
  // mount commit), it *may* have been wasted if it didn't actually need to re-render.
2465
2799
  // For the initial snapshot we approximate: wastedRenders = max(0, totalCommits - 1) * 0.3
2466
2800
  // This is a heuristic \u2014 real wasted render detection needs shouldComponentUpdate/React.memo tracing.
2467
- var wastedRenders = Math.max(0, Math.round((totalCommits - 1) * uniqueNames.length * 0.3));
2468
-
2469
2801
  return {
2470
2802
  commitCount: totalCommits,
2471
2803
  uniqueComponents: uniqueNames.length,
2472
2804
  componentNames: uniqueNames,
2473
- wastedRenders: wastedRenders,
2805
+ wastedRenders: null,
2474
2806
  layoutTime: window.__scopeLayoutTime || 0,
2475
2807
  paintTime: window.__scopePaintTime || 0,
2476
2808
  layoutShifts: window.__scopeLayoutShifts || { count: 0, score: 0 }
@@ -2518,7 +2850,7 @@ async function replayInteraction(page, steps) {
2518
2850
  }
2519
2851
  function analyzeProfileFlags(totalRenders, wastedRenders, timing, layoutShifts) {
2520
2852
  const flags = /* @__PURE__ */ new Set();
2521
- if (wastedRenders > 0 && wastedRenders / Math.max(1, totalRenders) > 0.3) {
2853
+ if (wastedRenders !== null && wastedRenders > 0 && wastedRenders / Math.max(1, totalRenders) > 0.3) {
2522
2854
  flags.add("WASTED_RENDER");
2523
2855
  }
2524
2856
  if (totalRenders > 10) {
@@ -2589,13 +2921,18 @@ async function runInteractionProfile(componentName, filePath, props, interaction
2589
2921
  };
2590
2922
  const totalRenders = profileData.commitCount ?? 0;
2591
2923
  const uniqueComponents = profileData.uniqueComponents ?? 0;
2592
- const wastedRenders = profileData.wastedRenders ?? 0;
2924
+ const wastedRenders = profileData.wastedRenders ?? null;
2593
2925
  const flags = analyzeProfileFlags(totalRenders, wastedRenders, timing, layoutShifts);
2594
2926
  return {
2595
2927
  component: componentName,
2596
2928
  totalRenders,
2597
2929
  uniqueComponents,
2598
2930
  wastedRenders,
2931
+ wastedRendersHeuristic: {
2932
+ measured: false,
2933
+ value: null,
2934
+ note: "profile.wastedRenders is retained for compatibility but set to null because Scope does not directly measure wasted renders yet."
2935
+ },
2599
2936
  timing,
2600
2937
  layoutShifts,
2601
2938
  flags,
@@ -2670,7 +3007,7 @@ Available: ${available}`
2670
3007
  process.stdout.write(`${JSON.stringify(result, null, 2)}
2671
3008
  `);
2672
3009
  } catch (err) {
2673
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
3010
+ process.stderr.write(`${formatScopeDiagnostic(err)}
2674
3011
  `);
2675
3012
  process.exit(1);
2676
3013
  }
@@ -3023,7 +3360,7 @@ Available: ${available}`
3023
3360
  `);
3024
3361
  }
3025
3362
  } catch (err) {
3026
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
3363
+ process.stderr.write(`${formatScopeDiagnostic(err)}
3027
3364
  `);
3028
3365
  process.exit(1);
3029
3366
  }
@@ -3517,7 +3854,7 @@ Examples:
3517
3854
  }
3518
3855
  } catch (err) {
3519
3856
  await shutdownPool2();
3520
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
3857
+ process.stderr.write(`${formatScopeDiagnostic(err)}
3521
3858
  `);
3522
3859
  process.exit(1);
3523
3860
  }
@@ -3557,8 +3894,8 @@ Examples:
3557
3894
  }
3558
3895
 
3559
3896
  // src/render-commands.ts
3560
- import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
3561
- import { resolve as resolve10 } from "path";
3897
+ import { existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync9, writeFileSync as writeFileSync6 } from "fs";
3898
+ import { resolve as resolve11 } from "path";
3562
3899
  import {
3563
3900
  ALL_CONTEXT_IDS,
3564
3901
  ALL_STRESS_IDS,
@@ -3571,27 +3908,79 @@ import {
3571
3908
  } from "@agent-scope/render";
3572
3909
  import { Command as Command8 } from "commander";
3573
3910
 
3911
+ // src/run-summary.ts
3912
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "fs";
3913
+ import { dirname as dirname3, resolve as resolve9 } from "path";
3914
+ var RUN_SUMMARY_PATH = ".reactscope/run-summary.json";
3915
+ function buildNextActions(summary) {
3916
+ const actions = /* @__PURE__ */ new Set();
3917
+ for (const failure of summary.failures) {
3918
+ if (failure.stage === "render" || failure.stage === "matrix") {
3919
+ actions.add(
3920
+ `Inspect ${failure.outputPath ?? ".reactscope/renders"} and add/fix ${failure.component}.scope.tsx scenarios or wrappers.`
3921
+ );
3922
+ } else if (failure.stage === "playground") {
3923
+ actions.add(
3924
+ `Open the generated component page and inspect the playground bundling error for ${failure.component}.`
3925
+ );
3926
+ } else if (failure.stage === "compliance") {
3927
+ actions.add(
3928
+ "Run `scope render all` first, then inspect .reactscope/compliance-styles.json and reactscope.tokens.json."
3929
+ );
3930
+ } else if (failure.stage === "site") {
3931
+ actions.add(
3932
+ "Inspect .reactscope/site output and rerun `scope site build` after fixing render/playground failures."
3933
+ );
3934
+ }
3935
+ }
3936
+ if (summary.compliance && summary.compliance.auditedProperties === 0) {
3937
+ actions.add(
3938
+ "No CSS properties were audited. Verify renders produced computed styles and your token file contains matching token categories."
3939
+ );
3940
+ } else if (summary.compliance && summary.compliance.threshold !== void 0 && summary.compliance.score < summary.compliance.threshold) {
3941
+ actions.add(
3942
+ "Inspect .reactscope/compliance-report.json for off-system values and update tokens or component styles."
3943
+ );
3944
+ }
3945
+ if (actions.size === 0) {
3946
+ actions.add("No follow-up needed. Outputs are ready for inspection.");
3947
+ }
3948
+ return [...actions];
3949
+ }
3950
+ function writeRunSummary(summary, summaryPath = RUN_SUMMARY_PATH) {
3951
+ const outputPath = resolve9(process.cwd(), summaryPath);
3952
+ mkdirSync3(dirname3(outputPath), { recursive: true });
3953
+ const payload = {
3954
+ ...summary,
3955
+ generatedAt: summary.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
3956
+ nextActions: summary.nextActions ?? buildNextActions(summary)
3957
+ };
3958
+ writeFileSync5(outputPath, `${JSON.stringify(payload, null, 2)}
3959
+ `, "utf-8");
3960
+ return outputPath;
3961
+ }
3962
+
3574
3963
  // src/scope-file.ts
3575
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, rmSync } from "fs";
3964
+ import { existsSync as existsSync8, mkdirSync as mkdirSync4, rmSync } from "fs";
3576
3965
  import { createRequire as createRequire2 } from "module";
3577
3966
  import { tmpdir } from "os";
3578
- import { dirname as dirname2, join as join4, resolve as resolve9 } from "path";
3967
+ import { dirname as dirname4, join as join5, resolve as resolve10 } from "path";
3579
3968
  import * as esbuild2 from "esbuild";
3580
3969
  var SCOPE_EXTENSIONS = [".scope.tsx", ".scope.ts", ".scope.jsx", ".scope.js"];
3581
3970
  function findScopeFile(componentFilePath) {
3582
- const dir = dirname2(componentFilePath);
3971
+ const dir = dirname4(componentFilePath);
3583
3972
  const stem = componentFilePath.replace(/\.(tsx?|jsx?)$/, "");
3584
3973
  const baseName = stem.slice(dir.length + 1);
3585
3974
  for (const ext of SCOPE_EXTENSIONS) {
3586
- const candidate = join4(dir, `${baseName}${ext}`);
3587
- if (existsSync7(candidate)) return candidate;
3975
+ const candidate = join5(dir, `${baseName}${ext}`);
3976
+ if (existsSync8(candidate)) return candidate;
3588
3977
  }
3589
3978
  return null;
3590
3979
  }
3591
3980
  async function loadScopeFile(scopeFilePath) {
3592
- const tmpDir = join4(tmpdir(), `scope-file-${Date.now()}-${Math.random().toString(36).slice(2)}`);
3593
- mkdirSync3(tmpDir, { recursive: true });
3594
- const outFile = join4(tmpDir, "scope-file.cjs");
3981
+ const tmpDir = join5(tmpdir(), `scope-file-${Date.now()}-${Math.random().toString(36).slice(2)}`);
3982
+ mkdirSync4(tmpDir, { recursive: true });
3983
+ const outFile = join5(tmpDir, "scope-file.cjs");
3595
3984
  try {
3596
3985
  const result = await esbuild2.build({
3597
3986
  entryPoints: [scopeFilePath],
@@ -3616,7 +4005,7 @@ async function loadScopeFile(scopeFilePath) {
3616
4005
  ${msg}`);
3617
4006
  }
3618
4007
  const req = createRequire2(import.meta.url);
3619
- delete req.cache[resolve9(outFile)];
4008
+ delete req.cache[resolve10(outFile)];
3620
4009
  const mod = req(outFile);
3621
4010
  const scenarios = extractScenarios(mod, scopeFilePath);
3622
4011
  const hasWrapper = typeof mod.wrapper === "function" || typeof mod.default?.wrapper === "function";
@@ -3666,7 +4055,7 @@ window.__SCOPE_WRAPPER__ = wrapper;
3666
4055
  const result = await esbuild2.build({
3667
4056
  stdin: {
3668
4057
  contents: wrapperEntry,
3669
- resolveDir: dirname2(scopeFilePath),
4058
+ resolveDir: dirname4(scopeFilePath),
3670
4059
  loader: "tsx",
3671
4060
  sourcefile: "__scope_wrapper_entry__.tsx"
3672
4061
  },
@@ -3694,16 +4083,73 @@ ${msg}`);
3694
4083
 
3695
4084
  // src/render-commands.ts
3696
4085
  function loadGlobalCssFilesFromConfig(cwd) {
3697
- const configPath = resolve10(cwd, "reactscope.config.json");
3698
- if (!existsSync8(configPath)) return [];
4086
+ const configPath = resolve11(cwd, "reactscope.config.json");
4087
+ if (!existsSync9(configPath)) return [];
3699
4088
  try {
3700
- const raw = readFileSync7(configPath, "utf-8");
4089
+ const raw = readFileSync9(configPath, "utf-8");
3701
4090
  const cfg = JSON.parse(raw);
3702
4091
  return cfg.components?.wrappers?.globalCSS ?? [];
3703
4092
  } catch {
3704
4093
  return [];
3705
4094
  }
3706
4095
  }
4096
+ var TAILWIND_CONFIG_FILES2 = [
4097
+ "tailwind.config.js",
4098
+ "tailwind.config.cjs",
4099
+ "tailwind.config.mjs",
4100
+ "tailwind.config.ts",
4101
+ "postcss.config.js",
4102
+ "postcss.config.cjs",
4103
+ "postcss.config.mjs",
4104
+ "postcss.config.ts"
4105
+ ];
4106
+ function shouldWarnForMissingGlobalCss(cwd) {
4107
+ if (TAILWIND_CONFIG_FILES2.some((file) => existsSync9(resolve11(cwd, file)))) {
4108
+ return true;
4109
+ }
4110
+ const packageJsonPath = resolve11(cwd, "package.json");
4111
+ if (!existsSync9(packageJsonPath)) return false;
4112
+ try {
4113
+ const pkg = JSON.parse(readFileSync9(packageJsonPath, "utf-8"));
4114
+ return [pkg.dependencies, pkg.devDependencies].some(
4115
+ (deps) => deps && Object.keys(deps).some(
4116
+ (name) => name === "tailwindcss" || name.startsWith("@tailwindcss/")
4117
+ )
4118
+ );
4119
+ } catch {
4120
+ return false;
4121
+ }
4122
+ }
4123
+ function loadIconPatternsFromConfig(cwd) {
4124
+ const configPath = resolve11(cwd, "reactscope.config.json");
4125
+ if (!existsSync9(configPath)) return [];
4126
+ try {
4127
+ const raw = readFileSync9(configPath, "utf-8");
4128
+ const cfg = JSON.parse(raw);
4129
+ return cfg.icons?.patterns ?? [];
4130
+ } catch {
4131
+ return [];
4132
+ }
4133
+ }
4134
+ function matchGlob2(pattern, value) {
4135
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
4136
+ const regexStr = escaped.replace(/\*\*/g, "\xA7GLOBSTAR\xA7").replace(/\*/g, "[^/]*").replace(/§GLOBSTAR§/g, ".*");
4137
+ return new RegExp(`^${regexStr}$`, "i").test(value);
4138
+ }
4139
+ function isIconComponent(filePath, displayName, patterns) {
4140
+ return patterns.length > 0 && patterns.some((p) => matchGlob2(p, filePath) || matchGlob2(p, displayName));
4141
+ }
4142
+ function formatAggregateRenderFailureJson(componentName, failures, scenarioCount, runSummaryPath) {
4143
+ return {
4144
+ command: `scope render component ${componentName}`,
4145
+ status: "failed",
4146
+ component: componentName,
4147
+ scenarioCount,
4148
+ failureCount: failures.length,
4149
+ failures,
4150
+ runSummaryPath
4151
+ };
4152
+ }
3707
4153
  var MANIFEST_PATH6 = ".reactscope/manifest.json";
3708
4154
  var DEFAULT_OUTPUT_DIR = ".reactscope/renders";
3709
4155
  var _pool3 = null;
@@ -3724,7 +4170,7 @@ async function shutdownPool3() {
3724
4170
  _pool3 = null;
3725
4171
  }
3726
4172
  }
3727
- function buildRenderer(filePath, componentName, viewportWidth, viewportHeight, globalCssFiles = [], projectCwd = process.cwd(), wrapperScript) {
4173
+ function buildRenderer(filePath, componentName, viewportWidth, viewportHeight, globalCssFiles = [], projectCwd = process.cwd(), wrapperScript, iconMode = false) {
3728
4174
  const satori = new SatoriRenderer({
3729
4175
  defaultViewport: { width: viewportWidth, height: viewportHeight }
3730
4176
  });
@@ -3734,13 +4180,15 @@ function buildRenderer(filePath, componentName, viewportWidth, viewportHeight, g
3734
4180
  const startMs = performance.now();
3735
4181
  const pool = await getPool3(viewportWidth, viewportHeight);
3736
4182
  const projectCss = await loadGlobalCss(globalCssFiles, projectCwd);
4183
+ const PAD = 8;
3737
4184
  const htmlHarness = await buildComponentHarness(
3738
4185
  filePath,
3739
4186
  componentName,
3740
4187
  props,
3741
4188
  viewportWidth,
3742
4189
  projectCss ?? void 0,
3743
- wrapperScript
4190
+ wrapperScript,
4191
+ PAD
3744
4192
  );
3745
4193
  const slot = await pool.acquire();
3746
4194
  const { page } = slot;
@@ -3781,17 +4229,28 @@ function buildRenderer(filePath, componentName, viewportWidth, viewportHeight, g
3781
4229
  `Component "${componentName}" rendered with zero bounding box \u2014 it may be invisible or not mounted`
3782
4230
  );
3783
4231
  }
3784
- const PAD = 8;
3785
4232
  const clipX = Math.max(0, boundingBox.x - PAD);
3786
4233
  const clipY = Math.max(0, boundingBox.y - PAD);
3787
4234
  const rawW = boundingBox.width + PAD * 2;
3788
4235
  const rawH = boundingBox.height + PAD * 2;
3789
4236
  const safeW = Math.min(rawW, viewportWidth - clipX);
3790
4237
  const safeH = Math.min(rawH, viewportHeight - clipY);
3791
- const screenshot = await page.screenshot({
3792
- clip: { x: clipX, y: clipY, width: safeW, height: safeH },
3793
- type: "png"
3794
- });
4238
+ let svgContent;
4239
+ let screenshot;
4240
+ if (iconMode) {
4241
+ svgContent = await page.evaluate((sel) => {
4242
+ const root = document.querySelector(sel);
4243
+ const el = root?.firstElementChild;
4244
+ if (!el) return void 0;
4245
+ return el.outerHTML;
4246
+ }, "[data-reactscope-root]") ?? void 0;
4247
+ screenshot = Buffer.alloc(0);
4248
+ } else {
4249
+ screenshot = await page.screenshot({
4250
+ clip: { x: clipX, y: clipY, width: safeW, height: safeH },
4251
+ type: "png"
4252
+ });
4253
+ }
3795
4254
  const STYLE_PROPS = [
3796
4255
  "display",
3797
4256
  "width",
@@ -3914,7 +4373,7 @@ function buildRenderer(filePath, componentName, viewportWidth, viewportHeight, g
3914
4373
  name: a11yInfo.name,
3915
4374
  violations: imgViolations
3916
4375
  };
3917
- return {
4376
+ const renderResult = {
3918
4377
  screenshot,
3919
4378
  width: Math.round(safeW),
3920
4379
  height: Math.round(safeH),
@@ -3923,6 +4382,10 @@ function buildRenderer(filePath, componentName, viewportWidth, viewportHeight, g
3923
4382
  dom,
3924
4383
  accessibility
3925
4384
  };
4385
+ if (iconMode && svgContent) {
4386
+ renderResult.svgContent = svgContent;
4387
+ }
4388
+ return renderResult;
3926
4389
  } finally {
3927
4390
  pool.release(slot);
3928
4391
  }
@@ -4017,12 +4480,12 @@ Available: ${available}`
4017
4480
  }
4018
4481
  const { width, height } = parseViewport(opts.viewport);
4019
4482
  const rootDir = process.cwd();
4020
- const filePath = resolve10(rootDir, descriptor.filePath);
4483
+ const filePath = resolve11(rootDir, descriptor.filePath);
4021
4484
  const scopeData = await loadScopeFileForComponent(filePath);
4022
4485
  const wrapperScript = scopeData?.hasWrapper === true ? await buildWrapperScript(scopeData.filePath) : void 0;
4023
4486
  const scenarios = buildScenarioMap(opts, scopeData);
4024
4487
  const globalCssFiles = loadGlobalCssFilesFromConfig(rootDir);
4025
- if (globalCssFiles.length === 0) {
4488
+ if (globalCssFiles.length === 0 && shouldWarnForMissingGlobalCss(rootDir)) {
4026
4489
  process.stderr.write(
4027
4490
  "warning: No globalCSS files configured. Tailwind/CSS styles will not be applied to renders.\n Add `components.wrappers.globalCSS` to reactscope.config.json\n"
4028
4491
  );
@@ -4041,7 +4504,8 @@ Available: ${available}`
4041
4504
  `
4042
4505
  );
4043
4506
  const fmt2 = resolveSingleFormat(opts.format);
4044
- let anyFailed = false;
4507
+ const failures = [];
4508
+ const outputPaths = [];
4045
4509
  for (const [scenarioName, props2] of Object.entries(scenarios)) {
4046
4510
  const isNamed = scenarioName !== "__default__";
4047
4511
  const label = isNamed ? `${componentName}:${scenarioName}` : componentName;
@@ -4064,14 +4528,22 @@ Available: ${available}`
4064
4528
  process.stderr.write(` Hints: ${hintList}
4065
4529
  `);
4066
4530
  }
4067
- anyFailed = true;
4531
+ failures.push({
4532
+ component: componentName,
4533
+ scenario: isNamed ? scenarioName : void 0,
4534
+ stage: "render",
4535
+ message: outcome.error.message,
4536
+ outputPath: `${DEFAULT_OUTPUT_DIR}/${isNamed ? `${componentName}-${scenarioName}.error.json` : `${componentName}.error.json`}`,
4537
+ hints: outcome.error.heuristicFlags
4538
+ });
4068
4539
  continue;
4069
4540
  }
4070
4541
  const result = outcome.result;
4071
4542
  const outFileName = isNamed ? `${componentName}-${scenarioName}.png` : `${componentName}.png`;
4072
4543
  if (opts.output !== void 0 && !isNamed) {
4073
- const outPath = resolve10(process.cwd(), opts.output);
4074
- writeFileSync5(outPath, result.screenshot);
4544
+ const outPath = resolve11(process.cwd(), opts.output);
4545
+ writeFileSync6(outPath, result.screenshot);
4546
+ outputPaths.push(outPath);
4075
4547
  process.stdout.write(
4076
4548
  `\u2713 ${label} \u2192 ${opts.output} (${result.width}\xD7${result.height}, ${result.renderTimeMs.toFixed(0)}ms)
4077
4549
  `
@@ -4081,22 +4553,41 @@ Available: ${available}`
4081
4553
  process.stdout.write(`${JSON.stringify(json, null, 2)}
4082
4554
  `);
4083
4555
  } else {
4084
- const dir = resolve10(process.cwd(), DEFAULT_OUTPUT_DIR);
4085
- mkdirSync4(dir, { recursive: true });
4086
- const outPath = resolve10(dir, outFileName);
4087
- writeFileSync5(outPath, result.screenshot);
4556
+ const dir = resolve11(process.cwd(), DEFAULT_OUTPUT_DIR);
4557
+ mkdirSync5(dir, { recursive: true });
4558
+ const outPath = resolve11(dir, outFileName);
4559
+ writeFileSync6(outPath, result.screenshot);
4088
4560
  const relPath = `${DEFAULT_OUTPUT_DIR}/${outFileName}`;
4561
+ outputPaths.push(relPath);
4089
4562
  process.stdout.write(
4090
4563
  `\u2713 ${label} \u2192 ${relPath} (${result.width}\xD7${result.height}, ${result.renderTimeMs.toFixed(0)}ms)
4091
4564
  `
4092
4565
  );
4093
4566
  }
4094
4567
  }
4568
+ const summaryPath = writeRunSummary({
4569
+ command: `scope render ${componentName}`,
4570
+ status: failures.length > 0 ? "failed" : "success",
4571
+ outputPaths,
4572
+ failures
4573
+ });
4574
+ process.stderr.write(`[scope/render] Run summary written to ${summaryPath}
4575
+ `);
4576
+ if (fmt2 === "json" && failures.length > 0) {
4577
+ const aggregateFailure = formatAggregateRenderFailureJson(
4578
+ componentName,
4579
+ failures,
4580
+ Object.keys(scenarios).length,
4581
+ summaryPath
4582
+ );
4583
+ process.stderr.write(`${JSON.stringify(aggregateFailure, null, 2)}
4584
+ `);
4585
+ }
4095
4586
  await shutdownPool3();
4096
- if (anyFailed) process.exit(1);
4587
+ if (failures.length > 0) process.exit(1);
4097
4588
  } catch (err) {
4098
4589
  await shutdownPool3();
4099
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
4590
+ process.stderr.write(`${formatScopeDiagnostic(err)}
4100
4591
  `);
4101
4592
  process.exit(1);
4102
4593
  }
@@ -4127,7 +4618,7 @@ Available: ${available}`
4127
4618
  const concurrency = Math.max(1, parseInt(opts.concurrency, 10) || 8);
4128
4619
  const { width, height } = { width: 375, height: 812 };
4129
4620
  const rootDir = process.cwd();
4130
- const filePath = resolve10(rootDir, descriptor.filePath);
4621
+ const filePath = resolve11(rootDir, descriptor.filePath);
4131
4622
  const matrixCssFiles = loadGlobalCssFilesFromConfig(rootDir);
4132
4623
  const renderer = buildRenderer(
4133
4624
  filePath,
@@ -4220,8 +4711,8 @@ Available: ${available}`
4220
4711
  const { SpriteSheetGenerator: SpriteSheetGenerator2 } = await import("@agent-scope/render");
4221
4712
  const gen = new SpriteSheetGenerator2();
4222
4713
  const sheet = await gen.generate(result);
4223
- const spritePath = resolve10(process.cwd(), opts.sprite);
4224
- writeFileSync5(spritePath, sheet.png);
4714
+ const spritePath = resolve11(process.cwd(), opts.sprite);
4715
+ writeFileSync6(spritePath, sheet.png);
4225
4716
  process.stderr.write(`Sprite sheet saved to ${spritePath}
4226
4717
  `);
4227
4718
  }
@@ -4230,10 +4721,10 @@ Available: ${available}`
4230
4721
  const { SpriteSheetGenerator: SpriteSheetGenerator2 } = await import("@agent-scope/render");
4231
4722
  const gen = new SpriteSheetGenerator2();
4232
4723
  const sheet = await gen.generate(result);
4233
- const dir = resolve10(process.cwd(), DEFAULT_OUTPUT_DIR);
4234
- mkdirSync4(dir, { recursive: true });
4235
- const outPath = resolve10(dir, `${componentName}-matrix.png`);
4236
- writeFileSync5(outPath, sheet.png);
4724
+ const dir = resolve11(process.cwd(), DEFAULT_OUTPUT_DIR);
4725
+ mkdirSync5(dir, { recursive: true });
4726
+ const outPath = resolve11(dir, `${componentName}-matrix.png`);
4727
+ writeFileSync6(outPath, sheet.png);
4237
4728
  const relPath = `${DEFAULT_OUTPUT_DIR}/${componentName}-matrix.png`;
4238
4729
  process.stdout.write(
4239
4730
  `\u2713 ${componentName} matrix (${result.stats.totalCells} cells) \u2192 ${relPath} (${result.stats.wallClockTimeMs.toFixed(0)}ms total)
@@ -4257,7 +4748,7 @@ Available: ${available}`
4257
4748
  }
4258
4749
  } catch (err) {
4259
4750
  await shutdownPool3();
4260
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
4751
+ process.stderr.write(`${formatScopeDiagnostic(err)}
4261
4752
  `);
4262
4753
  process.exit(1);
4263
4754
  }
@@ -4275,22 +4766,40 @@ function registerRenderAll(renderCmd) {
4275
4766
  const total = componentNames.length;
4276
4767
  if (total === 0) {
4277
4768
  process.stderr.write("No components found in manifest.\n");
4278
- return;
4769
+ const summaryPath2 = writeRunSummary({
4770
+ command: "scope render all",
4771
+ status: "failed",
4772
+ outputPaths: [],
4773
+ failures: [
4774
+ {
4775
+ component: "*",
4776
+ stage: "render",
4777
+ message: "No components found in manifest; refusing to report a false-green batch render."
4778
+ }
4779
+ ]
4780
+ });
4781
+ process.stderr.write(`[scope/render] Run summary written to ${summaryPath2}
4782
+ `);
4783
+ process.exit(1);
4279
4784
  }
4280
4785
  const concurrency = Math.max(1, parseInt(opts.concurrency, 10) || 4);
4281
- const outputDir = resolve10(process.cwd(), opts.outputDir);
4282
- mkdirSync4(outputDir, { recursive: true });
4786
+ const outputDir = resolve11(process.cwd(), opts.outputDir);
4787
+ mkdirSync5(outputDir, { recursive: true });
4283
4788
  const rootDir = process.cwd();
4284
4789
  process.stderr.write(`Rendering ${total} components (concurrency: ${concurrency})\u2026
4285
4790
  `);
4286
4791
  const results = [];
4792
+ const failures = [];
4793
+ const outputPaths = [];
4287
4794
  const complianceStylesMap = {};
4288
4795
  let completed = 0;
4796
+ const iconPatterns = loadIconPatternsFromConfig(process.cwd());
4289
4797
  const renderOne = async (name) => {
4290
4798
  const descriptor = manifest.components[name];
4291
4799
  if (descriptor === void 0) return;
4292
- const filePath = resolve10(rootDir, descriptor.filePath);
4800
+ const filePath = resolve11(rootDir, descriptor.filePath);
4293
4801
  const allCssFiles = loadGlobalCssFilesFromConfig(process.cwd());
4802
+ const isIcon = isIconComponent(descriptor.filePath, name, iconPatterns);
4294
4803
  const scopeData = await loadScopeFileForComponent(filePath);
4295
4804
  const scenarioEntries = scopeData !== null ? Object.entries(scopeData.scenarios) : [];
4296
4805
  const defaultEntry = scenarioEntries.find(([k]) => k === "default") ?? scenarioEntries[0];
@@ -4303,7 +4812,8 @@ function registerRenderAll(renderCmd) {
4303
4812
  812,
4304
4813
  allCssFiles,
4305
4814
  process.cwd(),
4306
- wrapperScript
4815
+ wrapperScript,
4816
+ isIcon
4307
4817
  );
4308
4818
  const outcome = await safeRender2(
4309
4819
  () => renderer.renderCell(renderProps, descriptor.complexityClass),
@@ -4326,8 +4836,8 @@ function registerRenderAll(renderCmd) {
4326
4836
  success: false,
4327
4837
  errorMessage: outcome.error.message
4328
4838
  });
4329
- const errPath = resolve10(outputDir, `${name}.error.json`);
4330
- writeFileSync5(
4839
+ const errPath = resolve11(outputDir, `${name}.error.json`);
4840
+ writeFileSync6(
4331
4841
  errPath,
4332
4842
  JSON.stringify(
4333
4843
  {
@@ -4340,14 +4850,32 @@ function registerRenderAll(renderCmd) {
4340
4850
  2
4341
4851
  )
4342
4852
  );
4853
+ failures.push({
4854
+ component: name,
4855
+ stage: "render",
4856
+ message: outcome.error.message,
4857
+ outputPath: errPath,
4858
+ hints: outcome.error.heuristicFlags
4859
+ });
4860
+ outputPaths.push(errPath);
4343
4861
  return;
4344
4862
  }
4345
4863
  const result = outcome.result;
4346
4864
  results.push({ name, renderTimeMs: result.renderTimeMs, success: true });
4347
- const pngPath = resolve10(outputDir, `${name}.png`);
4348
- writeFileSync5(pngPath, result.screenshot);
4349
- const jsonPath = resolve10(outputDir, `${name}.json`);
4350
- writeFileSync5(jsonPath, JSON.stringify(formatRenderJson(name, {}, result), null, 2));
4865
+ if (!isIcon) {
4866
+ const pngPath = resolve11(outputDir, `${name}.png`);
4867
+ writeFileSync6(pngPath, result.screenshot);
4868
+ outputPaths.push(pngPath);
4869
+ }
4870
+ const jsonPath = resolve11(outputDir, `${name}.json`);
4871
+ const renderJson = formatRenderJson(name, {}, result);
4872
+ const extResult = result;
4873
+ if (isIcon && extResult.svgContent) {
4874
+ renderJson.svgContent = extResult.svgContent;
4875
+ delete renderJson.screenshot;
4876
+ }
4877
+ writeFileSync6(jsonPath, JSON.stringify(renderJson, null, 2));
4878
+ outputPaths.push(jsonPath);
4351
4879
  const rawStyles = result.computedStyles["[data-reactscope-root] > *"] ?? {};
4352
4880
  const compStyles = {
4353
4881
  colors: {},
@@ -4408,20 +4936,26 @@ function registerRenderAll(renderCmd) {
4408
4936
  height: cell.result.height,
4409
4937
  renderTimeMs: cell.result.renderTimeMs
4410
4938
  }));
4411
- const existingJson = JSON.parse(readFileSync7(jsonPath, "utf-8"));
4939
+ const existingJson = JSON.parse(readFileSync9(jsonPath, "utf-8"));
4412
4940
  existingJson.cells = matrixCells;
4413
4941
  existingJson.axisLabels = [scenarioAxis.values];
4414
- writeFileSync5(jsonPath, JSON.stringify(existingJson, null, 2));
4942
+ writeFileSync6(jsonPath, JSON.stringify(existingJson, null, 2));
4415
4943
  } catch (matrixErr) {
4416
- process.stderr.write(
4417
- ` [warn] Matrix render for ${name} failed: ${matrixErr instanceof Error ? matrixErr.message : String(matrixErr)}
4418
- `
4419
- );
4944
+ const message = matrixErr instanceof Error ? matrixErr.message : String(matrixErr);
4945
+ process.stderr.write(` [warn] Matrix render for ${name} failed: ${message}
4946
+ `);
4947
+ failures.push({
4948
+ component: name,
4949
+ stage: "matrix",
4950
+ message,
4951
+ outputPath: jsonPath
4952
+ });
4420
4953
  }
4421
4954
  }
4422
4955
  if (isTTY()) {
4956
+ const suffix = isIcon ? " [icon/svg]" : "";
4423
4957
  process.stdout.write(
4424
- `\u2713 ${name} \u2192 ${opts.outputDir}/${name}.png (${result.width}\xD7${result.height}, ${result.renderTimeMs.toFixed(0)}ms)
4958
+ `\u2713 ${name} \u2192 ${opts.outputDir}/${name}${isIcon ? ".json" : ".png"} (${result.width}\xD7${result.height}, ${result.renderTimeMs.toFixed(0)}ms)${suffix}
4425
4959
  `
4426
4960
  );
4427
4961
  }
@@ -4442,21 +4976,31 @@ function registerRenderAll(renderCmd) {
4442
4976
  }
4443
4977
  await Promise.all(workers);
4444
4978
  await shutdownPool3();
4445
- const compStylesPath = resolve10(
4446
- resolve10(process.cwd(), opts.outputDir),
4979
+ const compStylesPath = resolve11(
4980
+ resolve11(process.cwd(), opts.outputDir),
4447
4981
  "..",
4448
4982
  "compliance-styles.json"
4449
4983
  );
4450
- writeFileSync5(compStylesPath, JSON.stringify(complianceStylesMap, null, 2));
4984
+ writeFileSync6(compStylesPath, JSON.stringify(complianceStylesMap, null, 2));
4985
+ outputPaths.push(compStylesPath);
4451
4986
  process.stderr.write(`[scope/render] \u2713 Wrote compliance-styles.json
4452
4987
  `);
4453
4988
  process.stderr.write("\n");
4454
4989
  const summary = formatSummaryText(results, outputDir);
4455
4990
  process.stderr.write(`${summary}
4456
4991
  `);
4992
+ const summaryPath = writeRunSummary({
4993
+ command: "scope render all",
4994
+ status: failures.length > 0 ? "failed" : "success",
4995
+ outputPaths,
4996
+ failures
4997
+ });
4998
+ process.stderr.write(`[scope/render] Run summary written to ${summaryPath}
4999
+ `);
5000
+ if (failures.length > 0) process.exit(1);
4457
5001
  } catch (err) {
4458
5002
  await shutdownPool3();
4459
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
5003
+ process.stderr.write(`${formatScopeDiagnostic(err)}
4460
5004
  `);
4461
5005
  process.exit(1);
4462
5006
  }
@@ -4498,8 +5042,8 @@ function createRenderCommand() {
4498
5042
  }
4499
5043
 
4500
5044
  // src/report/baseline.ts
4501
- import { existsSync as existsSync9, mkdirSync as mkdirSync5, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
4502
- import { resolve as resolve11 } from "path";
5045
+ import { existsSync as existsSync10, mkdirSync as mkdirSync6, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "fs";
5046
+ import { resolve as resolve12 } from "path";
4503
5047
  import { generateManifest as generateManifest4 } from "@agent-scope/manifest";
4504
5048
  import { BrowserPool as BrowserPool4, safeRender as safeRender3 } from "@agent-scope/render";
4505
5049
  import { ComplianceEngine as ComplianceEngine2, TokenResolver as TokenResolver2 } from "@agent-scope/tokens";
@@ -4523,8 +5067,17 @@ async function shutdownPool4() {
4523
5067
  }
4524
5068
  }
4525
5069
  async function renderComponent2(filePath, componentName, props, viewportWidth, viewportHeight) {
5070
+ const PAD = 24;
4526
5071
  const pool = await getPool4(viewportWidth, viewportHeight);
4527
- const htmlHarness = await buildComponentHarness(filePath, componentName, props, viewportWidth);
5072
+ const htmlHarness = await buildComponentHarness(
5073
+ filePath,
5074
+ componentName,
5075
+ props,
5076
+ viewportWidth,
5077
+ void 0,
5078
+ void 0,
5079
+ PAD
5080
+ );
4528
5081
  const slot = await pool.acquire();
4529
5082
  const { page } = slot;
4530
5083
  try {
@@ -4564,7 +5117,6 @@ async function renderComponent2(filePath, componentName, props, viewportWidth, v
4564
5117
  `Component "${componentName}" rendered with zero bounding box \u2014 it may be invisible or not mounted`
4565
5118
  );
4566
5119
  }
4567
- const PAD = 24;
4568
5120
  const MIN_W = 320;
4569
5121
  const MIN_H = 200;
4570
5122
  const clipX = Math.max(0, boundingBox.x - PAD);
@@ -4648,20 +5200,20 @@ async function runBaseline(options = {}) {
4648
5200
  } = options;
4649
5201
  const startTime = performance.now();
4650
5202
  const rootDir = process.cwd();
4651
- const baselineDir = resolve11(rootDir, outputDir);
4652
- const rendersDir = resolve11(baselineDir, "renders");
4653
- if (existsSync9(baselineDir)) {
5203
+ const baselineDir = resolve12(rootDir, outputDir);
5204
+ const rendersDir = resolve12(baselineDir, "renders");
5205
+ if (existsSync10(baselineDir)) {
4654
5206
  rmSync2(baselineDir, { recursive: true, force: true });
4655
5207
  }
4656
- mkdirSync5(rendersDir, { recursive: true });
5208
+ mkdirSync6(rendersDir, { recursive: true });
4657
5209
  let manifest;
4658
5210
  if (manifestPath !== void 0) {
4659
- const { readFileSync: readFileSync14 } = await import("fs");
4660
- const absPath = resolve11(rootDir, manifestPath);
4661
- if (!existsSync9(absPath)) {
5211
+ const { readFileSync: readFileSync18 } = await import("fs");
5212
+ const absPath = resolve12(rootDir, manifestPath);
5213
+ if (!existsSync10(absPath)) {
4662
5214
  throw new Error(`Manifest not found at ${absPath}.`);
4663
5215
  }
4664
- manifest = JSON.parse(readFileSync14(absPath, "utf-8"));
5216
+ manifest = JSON.parse(readFileSync18(absPath, "utf-8"));
4665
5217
  process.stderr.write(`Loaded manifest from ${manifestPath}
4666
5218
  `);
4667
5219
  } else {
@@ -4671,7 +5223,7 @@ async function runBaseline(options = {}) {
4671
5223
  process.stderr.write(`Found ${count} components.
4672
5224
  `);
4673
5225
  }
4674
- writeFileSync6(resolve11(baselineDir, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");
5226
+ writeFileSync7(resolve12(baselineDir, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");
4675
5227
  let componentNames = Object.keys(manifest.components);
4676
5228
  if (componentsGlob !== void 0) {
4677
5229
  componentNames = componentNames.filter((name) => matchGlob(componentsGlob, name));
@@ -4691,8 +5243,8 @@ async function runBaseline(options = {}) {
4691
5243
  aggregateCompliance: 1,
4692
5244
  auditedAt: (/* @__PURE__ */ new Date()).toISOString()
4693
5245
  };
4694
- writeFileSync6(
4695
- resolve11(baselineDir, "compliance.json"),
5246
+ writeFileSync7(
5247
+ resolve12(baselineDir, "compliance.json"),
4696
5248
  JSON.stringify(emptyReport, null, 2),
4697
5249
  "utf-8"
4698
5250
  );
@@ -4713,7 +5265,7 @@ async function runBaseline(options = {}) {
4713
5265
  const renderOne = async (name) => {
4714
5266
  const descriptor = manifest.components[name];
4715
5267
  if (descriptor === void 0) return;
4716
- const filePath = resolve11(rootDir, descriptor.filePath);
5268
+ const filePath = resolve12(rootDir, descriptor.filePath);
4717
5269
  const outcome = await safeRender3(
4718
5270
  () => renderComponent2(filePath, name, {}, viewportWidth, viewportHeight),
4719
5271
  {
@@ -4732,8 +5284,8 @@ async function runBaseline(options = {}) {
4732
5284
  }
4733
5285
  if (outcome.crashed) {
4734
5286
  failureCount++;
4735
- const errPath = resolve11(rendersDir, `${name}.error.json`);
4736
- writeFileSync6(
5287
+ const errPath = resolve12(rendersDir, `${name}.error.json`);
5288
+ writeFileSync7(
4737
5289
  errPath,
4738
5290
  JSON.stringify(
4739
5291
  {
@@ -4750,10 +5302,10 @@ async function runBaseline(options = {}) {
4750
5302
  return;
4751
5303
  }
4752
5304
  const result = outcome.result;
4753
- writeFileSync6(resolve11(rendersDir, `${name}.png`), result.screenshot);
5305
+ writeFileSync7(resolve12(rendersDir, `${name}.png`), result.screenshot);
4754
5306
  const jsonOutput = formatRenderJson(name, {}, result);
4755
- writeFileSync6(
4756
- resolve11(rendersDir, `${name}.json`),
5307
+ writeFileSync7(
5308
+ resolve12(rendersDir, `${name}.json`),
4757
5309
  JSON.stringify(jsonOutput, null, 2),
4758
5310
  "utf-8"
4759
5311
  );
@@ -4780,8 +5332,8 @@ async function runBaseline(options = {}) {
4780
5332
  const resolver = new TokenResolver2([]);
4781
5333
  const engine = new ComplianceEngine2(resolver);
4782
5334
  const batchReport = engine.auditBatch(computedStylesMap);
4783
- writeFileSync6(
4784
- resolve11(baselineDir, "compliance.json"),
5335
+ writeFileSync7(
5336
+ resolve12(baselineDir, "compliance.json"),
4785
5337
  JSON.stringify(batchReport, null, 2),
4786
5338
  "utf-8"
4787
5339
  );
@@ -4824,22 +5376,22 @@ function registerBaselineSubCommand(reportCmd) {
4824
5376
  }
4825
5377
 
4826
5378
  // src/report/diff.ts
4827
- import { existsSync as existsSync10, readFileSync as readFileSync8, writeFileSync as writeFileSync7 } from "fs";
4828
- import { resolve as resolve12 } from "path";
5379
+ import { existsSync as existsSync11, readFileSync as readFileSync10, writeFileSync as writeFileSync8 } from "fs";
5380
+ import { resolve as resolve13 } from "path";
4829
5381
  import { generateManifest as generateManifest5 } from "@agent-scope/manifest";
4830
5382
  import { BrowserPool as BrowserPool5, safeRender as safeRender4 } from "@agent-scope/render";
4831
5383
  import { ComplianceEngine as ComplianceEngine3, TokenResolver as TokenResolver3 } from "@agent-scope/tokens";
4832
5384
  var DEFAULT_BASELINE_DIR2 = ".reactscope/baseline";
4833
5385
  function loadBaselineCompliance(baselineDir) {
4834
- const compliancePath = resolve12(baselineDir, "compliance.json");
4835
- if (!existsSync10(compliancePath)) return null;
4836
- const raw = JSON.parse(readFileSync8(compliancePath, "utf-8"));
5386
+ const compliancePath = resolve13(baselineDir, "compliance.json");
5387
+ if (!existsSync11(compliancePath)) return null;
5388
+ const raw = JSON.parse(readFileSync10(compliancePath, "utf-8"));
4837
5389
  return raw;
4838
5390
  }
4839
5391
  function loadBaselineRenderJson2(baselineDir, componentName) {
4840
- const jsonPath = resolve12(baselineDir, "renders", `${componentName}.json`);
4841
- if (!existsSync10(jsonPath)) return null;
4842
- return JSON.parse(readFileSync8(jsonPath, "utf-8"));
5392
+ const jsonPath = resolve13(baselineDir, "renders", `${componentName}.json`);
5393
+ if (!existsSync11(jsonPath)) return null;
5394
+ return JSON.parse(readFileSync10(jsonPath, "utf-8"));
4843
5395
  }
4844
5396
  var _pool5 = null;
4845
5397
  async function getPool5(viewportWidth, viewportHeight) {
@@ -4860,8 +5412,17 @@ async function shutdownPool5() {
4860
5412
  }
4861
5413
  }
4862
5414
  async function renderComponent3(filePath, componentName, props, viewportWidth, viewportHeight) {
5415
+ const PAD = 24;
4863
5416
  const pool = await getPool5(viewportWidth, viewportHeight);
4864
- const htmlHarness = await buildComponentHarness(filePath, componentName, props, viewportWidth);
5417
+ const htmlHarness = await buildComponentHarness(
5418
+ filePath,
5419
+ componentName,
5420
+ props,
5421
+ viewportWidth,
5422
+ void 0,
5423
+ void 0,
5424
+ PAD
5425
+ );
4865
5426
  const slot = await pool.acquire();
4866
5427
  const { page } = slot;
4867
5428
  try {
@@ -4901,7 +5462,6 @@ async function renderComponent3(filePath, componentName, props, viewportWidth, v
4901
5462
  `Component "${componentName}" rendered with zero bounding box \u2014 it may be invisible or not mounted`
4902
5463
  );
4903
5464
  }
4904
- const PAD = 24;
4905
5465
  const MIN_W = 320;
4906
5466
  const MIN_H = 200;
4907
5467
  const clipX = Math.max(0, boundingBox.x - PAD);
@@ -4998,6 +5558,7 @@ function classifyComponent(entry, regressionThreshold) {
4998
5558
  async function runDiff(options = {}) {
4999
5559
  const {
5000
5560
  baselineDir: baselineDirRaw = DEFAULT_BASELINE_DIR2,
5561
+ complianceTokens = [],
5001
5562
  componentsGlob,
5002
5563
  manifestPath,
5003
5564
  viewportWidth = 375,
@@ -5006,19 +5567,19 @@ async function runDiff(options = {}) {
5006
5567
  } = options;
5007
5568
  const startTime = performance.now();
5008
5569
  const rootDir = process.cwd();
5009
- const baselineDir = resolve12(rootDir, baselineDirRaw);
5010
- if (!existsSync10(baselineDir)) {
5570
+ const baselineDir = resolve13(rootDir, baselineDirRaw);
5571
+ if (!existsSync11(baselineDir)) {
5011
5572
  throw new Error(
5012
5573
  `Baseline directory not found at "${baselineDir}". Run \`scope report baseline\` first to create a baseline snapshot.`
5013
5574
  );
5014
5575
  }
5015
- const baselineManifestPath = resolve12(baselineDir, "manifest.json");
5016
- if (!existsSync10(baselineManifestPath)) {
5576
+ const baselineManifestPath = resolve13(baselineDir, "manifest.json");
5577
+ if (!existsSync11(baselineManifestPath)) {
5017
5578
  throw new Error(
5018
5579
  `Baseline manifest.json not found at "${baselineManifestPath}". The baseline directory may be incomplete \u2014 re-run \`scope report baseline\`.`
5019
5580
  );
5020
5581
  }
5021
- const baselineManifest = JSON.parse(readFileSync8(baselineManifestPath, "utf-8"));
5582
+ const baselineManifest = JSON.parse(readFileSync10(baselineManifestPath, "utf-8"));
5022
5583
  const baselineCompliance = loadBaselineCompliance(baselineDir);
5023
5584
  const baselineComponentNames = new Set(Object.keys(baselineManifest.components));
5024
5585
  process.stderr.write(
@@ -5027,11 +5588,11 @@ async function runDiff(options = {}) {
5027
5588
  );
5028
5589
  let currentManifest;
5029
5590
  if (manifestPath !== void 0) {
5030
- const absPath = resolve12(rootDir, manifestPath);
5031
- if (!existsSync10(absPath)) {
5591
+ const absPath = resolve13(rootDir, manifestPath);
5592
+ if (!existsSync11(absPath)) {
5032
5593
  throw new Error(`Manifest not found at "${absPath}".`);
5033
5594
  }
5034
- currentManifest = JSON.parse(readFileSync8(absPath, "utf-8"));
5595
+ currentManifest = JSON.parse(readFileSync10(absPath, "utf-8"));
5035
5596
  process.stderr.write(`Loaded manifest from ${manifestPath}
5036
5597
  `);
5037
5598
  } else {
@@ -5064,7 +5625,7 @@ async function runDiff(options = {}) {
5064
5625
  const renderOne = async (name) => {
5065
5626
  const descriptor = currentManifest.components[name];
5066
5627
  if (descriptor === void 0) return;
5067
- const filePath = resolve12(rootDir, descriptor.filePath);
5628
+ const filePath = resolve13(rootDir, descriptor.filePath);
5068
5629
  const outcome = await safeRender4(
5069
5630
  () => renderComponent3(filePath, name, {}, viewportWidth, viewportHeight),
5070
5631
  {
@@ -5113,7 +5674,7 @@ async function runDiff(options = {}) {
5113
5674
  if (isTTY() && total > 0) {
5114
5675
  process.stderr.write("\n");
5115
5676
  }
5116
- const resolver = new TokenResolver3([]);
5677
+ const resolver = new TokenResolver3(complianceTokens);
5117
5678
  const engine = new ComplianceEngine3(resolver);
5118
5679
  const currentBatchReport = engine.auditBatch(computedStylesMap);
5119
5680
  const entries = [];
@@ -5282,7 +5843,7 @@ function registerDiffSubCommand(reportCmd) {
5282
5843
  regressionThreshold
5283
5844
  });
5284
5845
  if (opts.output !== void 0) {
5285
- writeFileSync7(opts.output, JSON.stringify(result, null, 2), "utf-8");
5846
+ writeFileSync8(opts.output, JSON.stringify(result, null, 2), "utf-8");
5286
5847
  process.stderr.write(`Diff written to ${opts.output}
5287
5848
  `);
5288
5849
  }
@@ -5304,8 +5865,8 @@ function registerDiffSubCommand(reportCmd) {
5304
5865
  }
5305
5866
 
5306
5867
  // src/report/pr-comment.ts
5307
- import { existsSync as existsSync11, readFileSync as readFileSync9, writeFileSync as writeFileSync8 } from "fs";
5308
- import { resolve as resolve13 } from "path";
5868
+ import { existsSync as existsSync12, readFileSync as readFileSync11, writeFileSync as writeFileSync9 } from "fs";
5869
+ import { resolve as resolve14 } from "path";
5309
5870
  var STATUS_BADGE = {
5310
5871
  added: "\u2705 added",
5311
5872
  removed: "\u{1F5D1}\uFE0F removed",
@@ -5388,13 +5949,13 @@ function formatPrComment(diff) {
5388
5949
  return lines.join("\n");
5389
5950
  }
5390
5951
  function loadDiffResult(filePath) {
5391
- const abs = resolve13(filePath);
5392
- if (!existsSync11(abs)) {
5952
+ const abs = resolve14(filePath);
5953
+ if (!existsSync12(abs)) {
5393
5954
  throw new Error(`DiffResult file not found: ${abs}`);
5394
5955
  }
5395
5956
  let raw;
5396
5957
  try {
5397
- raw = readFileSync9(abs, "utf-8");
5958
+ raw = readFileSync11(abs, "utf-8");
5398
5959
  } catch (err) {
5399
5960
  throw new Error(
5400
5961
  `Failed to read DiffResult file: ${err instanceof Error ? err.message : String(err)}`
@@ -5421,7 +5982,7 @@ function registerPrCommentSubCommand(reportCmd) {
5421
5982
  const diff = loadDiffResult(opts.input);
5422
5983
  const comment = formatPrComment(diff);
5423
5984
  if (opts.output !== void 0) {
5424
- writeFileSync8(resolve13(opts.output), comment, "utf-8");
5985
+ writeFileSync9(resolve14(opts.output), comment, "utf-8");
5425
5986
  process.stderr.write(`PR comment written to ${opts.output}
5426
5987
  `);
5427
5988
  } else {
@@ -5716,60 +6277,678 @@ function buildStructuredReport(report) {
5716
6277
  }
5717
6278
 
5718
6279
  // src/site-commands.ts
5719
- import { createReadStream, existsSync as existsSync12, statSync as statSync2 } from "fs";
6280
+ import {
6281
+ createReadStream,
6282
+ existsSync as existsSync13,
6283
+ watch as fsWatch,
6284
+ readFileSync as readFileSync12,
6285
+ statSync as statSync2,
6286
+ writeFileSync as writeFileSync10
6287
+ } from "fs";
6288
+ import { mkdir, writeFile } from "fs/promises";
5720
6289
  import { createServer } from "http";
5721
- import { extname, join as join5, resolve as resolve14 } from "path";
6290
+ import { extname, join as join6, resolve as resolve15 } from "path";
6291
+ import { generateManifest as generateManifest6 } from "@agent-scope/manifest";
6292
+ import { safeRender as safeRender5 } from "@agent-scope/render";
5722
6293
  import { buildSite } from "@agent-scope/site";
5723
6294
  import { Command as Command9 } from "commander";
5724
- var MIME_TYPES = {
5725
- ".html": "text/html; charset=utf-8",
5726
- ".css": "text/css; charset=utf-8",
5727
- ".js": "application/javascript; charset=utf-8",
5728
- ".json": "application/json; charset=utf-8",
5729
- ".png": "image/png",
5730
- ".jpg": "image/jpeg",
5731
- ".jpeg": "image/jpeg",
5732
- ".svg": "image/svg+xml",
5733
- ".ico": "image/x-icon"
5734
- };
5735
- function registerBuild(siteCmd) {
5736
- siteCmd.command("build").description(
5737
- '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'
5738
- ).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(
5739
- async (opts) => {
5740
- try {
5741
- const inputDir = resolve14(process.cwd(), opts.input);
5742
- const outputDir = resolve14(process.cwd(), opts.output);
5743
- if (!existsSync12(inputDir)) {
5744
- throw new Error(
5745
- `Input directory not found: ${inputDir}
5746
- Run \`scope manifest generate\` and \`scope render\` first.`
5747
- );
5748
- }
5749
- const manifestPath = join5(inputDir, "manifest.json");
5750
- if (!existsSync12(manifestPath)) {
5751
- throw new Error(
5752
- `Manifest not found at ${manifestPath}
5753
- Run \`scope manifest generate\` first.`
5754
- );
5755
- }
5756
- process.stderr.write(`Building site from ${inputDir}\u2026
5757
- `);
5758
- await buildSite({
5759
- inputDir,
5760
- outputDir,
5761
- basePath: opts.basePath,
5762
- ...opts.compliance !== void 0 && {
5763
- compliancePath: resolve14(process.cwd(), opts.compliance)
5764
- },
5765
- title: opts.title
5766
- });
5767
- process.stderr.write(`Site written to ${outputDir}
6295
+
6296
+ // src/playground-bundler.ts
6297
+ import { dirname as dirname5 } from "path";
6298
+ import * as esbuild3 from "esbuild";
6299
+ async function buildPlaygroundHarness(filePath, componentName, projectCss, wrapperScript) {
6300
+ const bundledScript = await bundlePlaygroundIIFE(filePath, componentName);
6301
+ return wrapPlaygroundHtml(bundledScript, projectCss, wrapperScript);
6302
+ }
6303
+ async function bundlePlaygroundIIFE(filePath, componentName) {
6304
+ const wrapperCode = (
6305
+ /* ts */
6306
+ `
6307
+ import * as __scopeMod from ${JSON.stringify(filePath)};
6308
+ import { createRoot } from "react-dom/client";
6309
+ import { createElement, Component as ReactComponent } from "react";
6310
+
6311
+ (function scopePlaygroundHarness() {
6312
+ var Target =
6313
+ __scopeMod["default"] ||
6314
+ __scopeMod[${JSON.stringify(componentName)}] ||
6315
+ (Object.values(__scopeMod).find(
6316
+ function(v) { return typeof v === "function" && /^[A-Z]/.test(v.name || ""); }
6317
+ ));
6318
+
6319
+ if (!Target) {
6320
+ document.getElementById("scope-root").innerHTML =
6321
+ '<p style="color:#dc2626;font-family:system-ui;font-size:13px">No renderable component found.</p>';
6322
+ return;
6323
+ }
6324
+
6325
+ // Error boundary to catch async render errors (React unmounts the whole
6326
+ // root when an error is uncaught \u2014 this keeps the error visible instead).
6327
+ var errorStyle = "color:#dc2626;font-family:system-ui;font-size:13px;padding:12px";
6328
+ class ScopeBoundary extends ReactComponent {
6329
+ constructor(p) { super(p); this.state = { error: null }; }
6330
+ static getDerivedStateFromError(err) { return { error: err }; }
6331
+ render() {
6332
+ if (this.state.error) {
6333
+ return createElement("pre", { style: errorStyle },
6334
+ "Render error: " + (this.state.error.message || String(this.state.error)));
6335
+ }
6336
+ return this.props.children;
6337
+ }
6338
+ }
6339
+
6340
+ var rootEl = document.getElementById("scope-root");
6341
+ var root = createRoot(rootEl);
6342
+ var Wrapper = window.__SCOPE_WRAPPER__;
6343
+
6344
+ function render(props) {
6345
+ var inner = createElement(Target, props);
6346
+ if (Wrapper) inner = createElement(Wrapper, null, inner);
6347
+ root.render(createElement(ScopeBoundary, null, inner));
6348
+ }
6349
+
6350
+ // Render immediately with empty props
6351
+ render({});
6352
+
6353
+ // Listen for messages from the parent frame
6354
+ window.addEventListener("message", function(e) {
6355
+ if (!e.data) return;
6356
+ if (e.data.type === "scope-playground-props") {
6357
+ render(e.data.props || {});
6358
+ } else if (e.data.type === "scope-playground-theme") {
6359
+ document.documentElement.classList.toggle("dark", e.data.theme === "dark");
6360
+ }
6361
+ });
6362
+
6363
+ // Report content height changes to the parent frame
6364
+ var ro = new ResizeObserver(function() {
6365
+ var h = rootEl.scrollHeight;
6366
+ if (parent !== window) {
6367
+ parent.postMessage({ type: "scope-playground-height", height: h }, "*");
6368
+ }
6369
+ });
6370
+ ro.observe(rootEl);
6371
+ })();
6372
+ `
6373
+ );
6374
+ const result = await esbuild3.build({
6375
+ stdin: {
6376
+ contents: wrapperCode,
6377
+ resolveDir: dirname5(filePath),
6378
+ loader: "tsx",
6379
+ sourcefile: "__scope_playground__.tsx"
6380
+ },
6381
+ bundle: true,
6382
+ format: "iife",
6383
+ write: false,
6384
+ platform: "browser",
6385
+ jsx: "automatic",
6386
+ jsxImportSource: "react",
6387
+ target: "es2020",
6388
+ external: [],
6389
+ define: {
6390
+ "process.env.NODE_ENV": '"production"',
6391
+ global: "globalThis"
6392
+ },
6393
+ logLevel: "silent",
6394
+ banner: {
6395
+ js: "/* @agent-scope/cli playground harness */"
6396
+ },
6397
+ loader: {
6398
+ ".css": "empty",
6399
+ ".svg": "dataurl",
6400
+ ".png": "dataurl",
6401
+ ".jpg": "dataurl",
6402
+ ".jpeg": "dataurl",
6403
+ ".gif": "dataurl",
6404
+ ".webp": "dataurl",
6405
+ ".ttf": "dataurl",
6406
+ ".woff": "dataurl",
6407
+ ".woff2": "dataurl"
6408
+ }
6409
+ });
6410
+ if (result.errors.length > 0) {
6411
+ const msg = result.errors.map((e) => `${e.text}${e.location ? ` (${e.location.file}:${e.location.line})` : ""}`).join("\n");
6412
+ throw new Error(`esbuild failed to bundle playground component:
6413
+ ${msg}`);
6414
+ }
6415
+ const outputFile = result.outputFiles?.[0];
6416
+ if (outputFile === void 0 || outputFile.text.length === 0) {
6417
+ throw new Error("esbuild produced no playground output");
6418
+ }
6419
+ return outputFile.text;
6420
+ }
6421
+ function wrapPlaygroundHtml(bundledScript, projectCss, wrapperScript) {
6422
+ const projectStyleBlock = projectCss != null && projectCss.length > 0 ? `<style id="scope-project-css">
6423
+ ${projectCss.replace(/<\/style>/gi, "<\\/style>")}
6424
+ </style>` : "";
6425
+ const wrapperScriptBlock = wrapperScript != null && wrapperScript.length > 0 ? `<script id="scope-wrapper-script">${wrapperScript}</script>` : "";
6426
+ return `<!DOCTYPE html>
6427
+ <html lang="en">
6428
+ <head>
6429
+ <meta charset="UTF-8" />
6430
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6431
+ <script>
6432
+ window.__SCOPE_WRAPPER__ = null;
6433
+ // Prevent React DevTools from interfering with the embedded playground.
6434
+ // The hook causes render instability in same-origin iframes.
6435
+ delete window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
6436
+ </script>
6437
+ <style>
6438
+ *, *::before, *::after { box-sizing: border-box; }
6439
+ html, body { margin: 0; padding: 0; font-family: system-ui, sans-serif; }
6440
+ #scope-root { padding: 16px; min-width: 1px; min-height: 1px; }
6441
+ </style>
6442
+ ${projectStyleBlock}
6443
+ <style>html, body { background: transparent !important; }</style>
6444
+ </head>
6445
+ <body>
6446
+ <div id="scope-root" data-reactscope-root></div>
6447
+ ${wrapperScriptBlock}
6448
+ <script>${bundledScript}</script>
6449
+ </body>
6450
+ </html>`;
6451
+ }
6452
+
6453
+ // src/site-commands.ts
6454
+ var MIME_TYPES = {
6455
+ ".html": "text/html; charset=utf-8",
6456
+ ".css": "text/css; charset=utf-8",
6457
+ ".js": "application/javascript; charset=utf-8",
6458
+ ".json": "application/json; charset=utf-8",
6459
+ ".png": "image/png",
6460
+ ".jpg": "image/jpeg",
6461
+ ".jpeg": "image/jpeg",
6462
+ ".svg": "image/svg+xml",
6463
+ ".ico": "image/x-icon"
6464
+ };
6465
+ function slugify(name) {
6466
+ return name.replace(/([A-Z])/g, (m) => `-${m.toLowerCase()}`).replace(/^-/, "").replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
6467
+ }
6468
+ function loadGlobalCssFilesFromConfig2(cwd) {
6469
+ const configPath = resolve15(cwd, "reactscope.config.json");
6470
+ if (!existsSync13(configPath)) return [];
6471
+ try {
6472
+ const raw = readFileSync12(configPath, "utf-8");
6473
+ const cfg = JSON.parse(raw);
6474
+ return cfg.components?.wrappers?.globalCSS ?? [];
6475
+ } catch {
6476
+ return [];
6477
+ }
6478
+ }
6479
+ function loadIconPatternsFromConfig2(cwd) {
6480
+ const configPath = resolve15(cwd, "reactscope.config.json");
6481
+ if (!existsSync13(configPath)) return [];
6482
+ try {
6483
+ const raw = readFileSync12(configPath, "utf-8");
6484
+ const cfg = JSON.parse(raw);
6485
+ return cfg.icons?.patterns ?? [];
6486
+ } catch {
6487
+ return [];
6488
+ }
6489
+ }
6490
+ var LIVERELOAD_SCRIPT = `<script>(function(){var s=new EventSource("/__livereload");s.onmessage=function(e){if(e.data==="reload")location.reload()};s.onerror=function(){setTimeout(function(){location.reload()},2000)}})()</script>`;
6491
+ function injectLiveReloadScript(html) {
6492
+ const idx = html.lastIndexOf("</body>");
6493
+ if (idx >= 0) return html.slice(0, idx) + LIVERELOAD_SCRIPT + html.slice(idx);
6494
+ return html + LIVERELOAD_SCRIPT;
6495
+ }
6496
+ function loadWatchConfig(rootDir) {
6497
+ const configPath = resolve15(rootDir, "reactscope.config.json");
6498
+ if (!existsSync13(configPath)) return null;
6499
+ try {
6500
+ const raw = readFileSync12(configPath, "utf-8");
6501
+ const cfg = JSON.parse(raw);
6502
+ const result = {};
6503
+ const components = cfg.components;
6504
+ if (components && typeof components === "object") {
6505
+ if (Array.isArray(components.include)) result.include = components.include;
6506
+ if (Array.isArray(components.exclude)) result.exclude = components.exclude;
6507
+ }
6508
+ if (Array.isArray(cfg.internalPatterns))
6509
+ result.internalPatterns = cfg.internalPatterns;
6510
+ if (Array.isArray(cfg.collections)) result.collections = cfg.collections;
6511
+ const icons = cfg.icons;
6512
+ if (icons && typeof icons === "object" && Array.isArray(icons.patterns)) {
6513
+ result.iconPatterns = icons.patterns;
6514
+ }
6515
+ return result;
6516
+ } catch {
6517
+ return null;
6518
+ }
6519
+ }
6520
+ function watchGlob(pattern, filePath) {
6521
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
6522
+ const regexStr = escaped.replace(/\*\*/g, "\xA7GLOBSTAR\xA7").replace(/\*/g, "[^/]*").replace(/\u00a7GLOBSTAR\u00a7/g, ".*");
6523
+ return new RegExp(`^${regexStr}$`, "i").test(filePath);
6524
+ }
6525
+ function matchesWatchPatterns(filePath, include, exclude) {
6526
+ for (const pattern of exclude) {
6527
+ if (watchGlob(pattern, filePath)) return false;
6528
+ }
6529
+ for (const pattern of include) {
6530
+ if (watchGlob(pattern, filePath)) return true;
6531
+ }
6532
+ return false;
6533
+ }
6534
+ function findAffectedComponents(manifest, changedFiles, previousManifest) {
6535
+ const affected = /* @__PURE__ */ new Set();
6536
+ const normalised = changedFiles.map((f) => f.replace(/\\/g, "/"));
6537
+ for (const [name, descriptor] of Object.entries(manifest.components)) {
6538
+ const componentFile = descriptor.filePath.replace(/\\/g, "/");
6539
+ for (const changed of normalised) {
6540
+ if (componentFile === changed) {
6541
+ affected.add(name);
6542
+ break;
6543
+ }
6544
+ const scopeBase = changed.replace(/\.scope\.(ts|tsx|js|jsx)$/, "");
6545
+ const compBase = componentFile.replace(/\.(tsx|ts|jsx|js)$/, "");
6546
+ if (scopeBase !== changed && compBase === scopeBase) {
6547
+ affected.add(name);
6548
+ break;
6549
+ }
6550
+ }
6551
+ }
6552
+ if (previousManifest) {
6553
+ const oldNames = new Set(Object.keys(previousManifest.components));
6554
+ for (const name of Object.keys(manifest.components)) {
6555
+ if (!oldNames.has(name)) affected.add(name);
6556
+ }
6557
+ }
6558
+ return [...affected];
6559
+ }
6560
+ async function renderComponentsForWatch(manifest, componentNames, rootDir, inputDir) {
6561
+ if (componentNames.length === 0) return;
6562
+ const rendersDir = join6(inputDir, "renders");
6563
+ await mkdir(rendersDir, { recursive: true });
6564
+ const cssFiles = loadGlobalCssFilesFromConfig2(rootDir);
6565
+ const iconPatterns = loadIconPatternsFromConfig2(rootDir);
6566
+ const complianceStylesPath = join6(inputDir, "compliance-styles.json");
6567
+ let complianceStyles = {};
6568
+ if (existsSync13(complianceStylesPath)) {
6569
+ try {
6570
+ complianceStyles = JSON.parse(readFileSync12(complianceStylesPath, "utf-8"));
6571
+ } catch {
6572
+ }
6573
+ }
6574
+ for (const name of componentNames) {
6575
+ const descriptor = manifest.components[name];
6576
+ if (!descriptor) continue;
6577
+ const filePath = resolve15(rootDir, descriptor.filePath);
6578
+ const isIcon = isIconComponent(descriptor.filePath, name, iconPatterns);
6579
+ let scopeData = null;
6580
+ try {
6581
+ scopeData = await loadScopeFileForComponent(filePath);
6582
+ } catch {
6583
+ }
6584
+ const scenarioEntries = scopeData ? Object.entries(scopeData.scenarios) : [];
6585
+ const defaultEntry = scenarioEntries.find(([k]) => k === "default") ?? scenarioEntries[0];
6586
+ const renderProps = defaultEntry?.[1] ?? {};
6587
+ let wrapperScript;
6588
+ try {
6589
+ wrapperScript = scopeData?.hasWrapper ? await buildWrapperScript(scopeData.filePath) : void 0;
6590
+ } catch {
6591
+ }
6592
+ const renderer = buildRenderer(
6593
+ filePath,
6594
+ name,
6595
+ 375,
6596
+ 812,
6597
+ cssFiles,
6598
+ rootDir,
6599
+ wrapperScript,
6600
+ isIcon
6601
+ );
6602
+ const outcome = await safeRender5(
6603
+ () => renderer.renderCell(renderProps, descriptor.complexityClass),
6604
+ {
6605
+ props: renderProps,
6606
+ sourceLocation: { file: descriptor.filePath, line: descriptor.loc.start, column: 0 }
6607
+ }
6608
+ );
6609
+ if (outcome.crashed) {
6610
+ process.stderr.write(` \u2717 ${name}: ${outcome.error.message}
6611
+ `);
6612
+ continue;
6613
+ }
6614
+ const result = outcome.result;
6615
+ if (!isIcon) {
6616
+ writeFileSync10(join6(rendersDir, `${name}.png`), result.screenshot);
6617
+ }
6618
+ const renderJson = formatRenderJson(name, renderProps, result);
6619
+ const extResult = result;
6620
+ if (isIcon && extResult.svgContent) {
6621
+ renderJson.svgContent = extResult.svgContent;
6622
+ delete renderJson.screenshot;
6623
+ }
6624
+ writeFileSync10(join6(rendersDir, `${name}.json`), JSON.stringify(renderJson, null, 2));
6625
+ const rawStyles = result.computedStyles["[data-reactscope-root] > *"] ?? {};
6626
+ const compStyles = {
6627
+ colors: {},
6628
+ spacing: {},
6629
+ typography: {},
6630
+ borders: {},
6631
+ shadows: {}
6632
+ };
6633
+ for (const [prop, val] of Object.entries(rawStyles)) {
6634
+ if (!val || val === "none" || val === "") continue;
6635
+ const lower = prop.toLowerCase();
6636
+ if (lower.includes("color") || lower.includes("background")) {
6637
+ compStyles.colors[prop] = val;
6638
+ } else if (lower.includes("padding") || lower.includes("margin") || lower.includes("gap") || lower.includes("width") || lower.includes("height")) {
6639
+ compStyles.spacing[prop] = val;
6640
+ } else if (lower.includes("font") || lower.includes("lineheight") || lower.includes("letterspacing") || lower.includes("texttransform")) {
6641
+ compStyles.typography[prop] = val;
6642
+ } else if (lower.includes("border") || lower.includes("radius") || lower.includes("outline")) {
6643
+ compStyles.borders[prop] = val;
6644
+ } else if (lower.includes("shadow")) {
6645
+ compStyles.shadows[prop] = val;
6646
+ }
6647
+ }
6648
+ complianceStyles[name] = compStyles;
6649
+ process.stderr.write(` \u2713 ${name} (${result.renderTimeMs.toFixed(0)}ms)
6650
+ `);
6651
+ }
6652
+ await shutdownPool3();
6653
+ writeFileSync10(complianceStylesPath, JSON.stringify(complianceStyles, null, 2), "utf-8");
6654
+ }
6655
+ async function watchRebuildSite(inputDir, outputDir, title, basePath) {
6656
+ const rootDir = process.cwd();
6657
+ await generatePlaygrounds(inputDir, outputDir);
6658
+ const iconPatterns = loadIconPatternsFromConfig2(rootDir);
6659
+ let tokenFilePath;
6660
+ const autoPath = resolve15(rootDir, "reactscope.tokens.json");
6661
+ if (existsSync13(autoPath)) tokenFilePath = autoPath;
6662
+ let compliancePath;
6663
+ const crPath = join6(inputDir, "compliance-report.json");
6664
+ if (existsSync13(crPath)) compliancePath = crPath;
6665
+ await buildSite({
6666
+ inputDir,
6667
+ outputDir,
6668
+ basePath,
6669
+ ...compliancePath && { compliancePath },
6670
+ ...tokenFilePath && { tokenFilePath },
6671
+ title,
6672
+ iconPatterns
6673
+ });
6674
+ }
6675
+ function findStaleComponents(manifest, previousManifest, rendersDir) {
6676
+ const stale = [];
6677
+ for (const [name, descriptor] of Object.entries(manifest.components)) {
6678
+ const jsonPath = join6(rendersDir, `${name}.json`);
6679
+ if (!existsSync13(jsonPath)) {
6680
+ stale.push(name);
6681
+ continue;
6682
+ }
6683
+ if (!previousManifest) continue;
6684
+ const prev = previousManifest.components[name];
6685
+ if (!prev) {
6686
+ stale.push(name);
6687
+ continue;
6688
+ }
6689
+ if (JSON.stringify(prev) !== JSON.stringify(descriptor)) {
6690
+ stale.push(name);
6691
+ }
6692
+ }
6693
+ return stale;
6694
+ }
6695
+ async function runFullBuild(rootDir, inputDir, outputDir, title, basePath) {
6696
+ process.stderr.write("[watch] Starting\u2026\n");
6697
+ const config = loadWatchConfig(rootDir);
6698
+ const manifestPath = join6(inputDir, "manifest.json");
6699
+ let previousManifest = null;
6700
+ if (existsSync13(manifestPath)) {
6701
+ try {
6702
+ previousManifest = JSON.parse(readFileSync12(manifestPath, "utf-8"));
6703
+ } catch {
6704
+ }
6705
+ }
6706
+ process.stderr.write("[watch] Generating manifest\u2026\n");
6707
+ const manifest = await generateManifest6({
6708
+ rootDir,
6709
+ ...config?.include && { include: config.include },
6710
+ ...config?.exclude && { exclude: config.exclude },
6711
+ ...config?.internalPatterns && { internalPatterns: config.internalPatterns },
6712
+ ...config?.collections && { collections: config.collections },
6713
+ ...config?.iconPatterns && { iconPatterns: config.iconPatterns }
6714
+ });
6715
+ await mkdir(inputDir, { recursive: true });
6716
+ writeFileSync10(join6(inputDir, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");
6717
+ const count = Object.keys(manifest.components).length;
6718
+ process.stderr.write(`[watch] Found ${count} components
6719
+ `);
6720
+ const rendersDir = join6(inputDir, "renders");
6721
+ const stale = findStaleComponents(manifest, previousManifest, rendersDir);
6722
+ if (stale.length > 0) {
6723
+ process.stderr.write(
6724
+ `[watch] Rendering ${stale.length} component(s) (${count - stale.length} already up-to-date)
6725
+ `
6726
+ );
6727
+ await renderComponentsForWatch(manifest, stale, rootDir, inputDir);
6728
+ } else {
6729
+ process.stderr.write("[watch] All renders up-to-date, skipping render step\n");
6730
+ }
6731
+ process.stderr.write("[watch] Building site\u2026\n");
6732
+ await watchRebuildSite(inputDir, outputDir, title, basePath);
6733
+ process.stderr.write("[watch] Ready\n");
6734
+ return manifest;
6735
+ }
6736
+ function startFileWatcher(opts) {
6737
+ const { rootDir, inputDir, outputDir, title, basePath, notifyReload } = opts;
6738
+ let previousManifest = opts.previousManifest;
6739
+ const config = loadWatchConfig(rootDir);
6740
+ const includePatterns = config?.include ?? ["src/**/*.tsx", "src/**/*.ts"];
6741
+ const excludePatterns = config?.exclude ?? [
6742
+ "**/node_modules/**",
6743
+ "**/*.test.*",
6744
+ "**/*.spec.*",
6745
+ "**/dist/**",
6746
+ "**/*.d.ts"
6747
+ ];
6748
+ let debounceTimer = null;
6749
+ const pendingFiles = /* @__PURE__ */ new Set();
6750
+ let isRunning = false;
6751
+ const IGNORE_PREFIXES = ["node_modules/", ".reactscope/", "dist/", ".git/", ".next/", ".turbo/"];
6752
+ const handleChange = async () => {
6753
+ if (isRunning) return;
6754
+ isRunning = true;
6755
+ const changedFiles = [...pendingFiles];
6756
+ pendingFiles.clear();
6757
+ try {
6758
+ process.stderr.write(`
6759
+ [watch] ${changedFiles.length} file(s) changed
6760
+ `);
6761
+ process.stderr.write("[watch] Regenerating manifest\u2026\n");
6762
+ const newManifest = await generateManifest6({
6763
+ rootDir,
6764
+ ...config?.include && { include: config.include },
6765
+ ...config?.exclude && { exclude: config.exclude },
6766
+ ...config?.internalPatterns && { internalPatterns: config.internalPatterns },
6767
+ ...config?.collections && { collections: config.collections },
6768
+ ...config?.iconPatterns && { iconPatterns: config.iconPatterns }
6769
+ });
6770
+ writeFileSync10(join6(inputDir, "manifest.json"), JSON.stringify(newManifest, null, 2), "utf-8");
6771
+ const affected = findAffectedComponents(newManifest, changedFiles, previousManifest);
6772
+ if (affected.length > 0) {
6773
+ process.stderr.write(`[watch] Re-rendering: ${affected.join(", ")}
6774
+ `);
6775
+ await renderComponentsForWatch(newManifest, affected, rootDir, inputDir);
6776
+ } else {
6777
+ process.stderr.write("[watch] No components directly affected\n");
6778
+ }
6779
+ process.stderr.write("[watch] Rebuilding site\u2026\n");
6780
+ await watchRebuildSite(inputDir, outputDir, title, basePath);
6781
+ previousManifest = newManifest;
6782
+ process.stderr.write("[watch] Done\n");
6783
+ notifyReload();
6784
+ } catch (err) {
6785
+ process.stderr.write(`[watch] Error: ${err instanceof Error ? err.message : String(err)}
6786
+ `);
6787
+ } finally {
6788
+ isRunning = false;
6789
+ if (pendingFiles.size > 0) {
6790
+ handleChange();
6791
+ }
6792
+ }
6793
+ };
6794
+ const onFileChange = (_eventType, filename) => {
6795
+ if (!filename) return;
6796
+ const normalised = filename.replace(/\\/g, "/");
6797
+ for (const prefix of IGNORE_PREFIXES) {
6798
+ if (normalised.startsWith(prefix)) return;
6799
+ }
6800
+ if (!matchesWatchPatterns(normalised, includePatterns, excludePatterns)) return;
6801
+ pendingFiles.add(normalised);
6802
+ if (debounceTimer) clearTimeout(debounceTimer);
6803
+ debounceTimer = setTimeout(() => {
6804
+ debounceTimer = null;
6805
+ handleChange();
6806
+ }, 500);
6807
+ };
6808
+ try {
6809
+ fsWatch(rootDir, { recursive: true }, onFileChange);
6810
+ process.stderr.write(`[watch] Watching for changes (${includePatterns.join(", ")})
6811
+ `);
6812
+ } catch (err) {
6813
+ process.stderr.write(
6814
+ `[watch] Warning: Could not start watcher: ${err instanceof Error ? err.message : String(err)}
6815
+ `
6816
+ );
6817
+ }
6818
+ }
6819
+ async function generatePlaygrounds(inputDir, outputDir) {
6820
+ const manifestPath = join6(inputDir, "manifest.json");
6821
+ const raw = readFileSync12(manifestPath, "utf-8");
6822
+ const manifest = JSON.parse(raw);
6823
+ const rootDir = process.cwd();
6824
+ const componentNames = Object.keys(manifest.components);
6825
+ if (componentNames.length === 0) return [];
6826
+ const playgroundDir = join6(outputDir, "playground");
6827
+ await mkdir(playgroundDir, { recursive: true });
6828
+ const cssFiles = loadGlobalCssFilesFromConfig2(rootDir);
6829
+ const projectCss = await loadGlobalCss(cssFiles, rootDir) ?? void 0;
6830
+ let succeeded = 0;
6831
+ const failures = [];
6832
+ const allDefaults = {};
6833
+ for (const name of componentNames) {
6834
+ const descriptor = manifest.components[name];
6835
+ if (!descriptor) continue;
6836
+ const filePath = resolve15(rootDir, descriptor.filePath);
6837
+ const slug = slugify(name);
6838
+ try {
6839
+ const scopeData = await loadScopeFileForComponent(filePath);
6840
+ if (scopeData) {
6841
+ const defaultScenario = scopeData.scenarios.default ?? Object.values(scopeData.scenarios)[0];
6842
+ if (defaultScenario) allDefaults[name] = defaultScenario;
6843
+ }
6844
+ } catch {
6845
+ }
6846
+ try {
6847
+ const html = await buildPlaygroundHarness(filePath, name, projectCss);
6848
+ await writeFile(join6(playgroundDir, `${slug}.html`), html, "utf-8");
6849
+ succeeded++;
6850
+ } catch (err) {
6851
+ process.stderr.write(
6852
+ `[scope/site] \u26A0 playground skip: ${name} \u2014 ${err instanceof Error ? err.message : String(err)}
6853
+ `
6854
+ );
6855
+ failures.push({
6856
+ component: name,
6857
+ stage: "playground",
6858
+ message: err instanceof Error ? err.message : String(err),
6859
+ outputPath: join6(playgroundDir, `${slug}.html`)
6860
+ });
6861
+ }
6862
+ }
6863
+ await writeFile(
6864
+ join6(inputDir, "playground-defaults.json"),
6865
+ JSON.stringify(allDefaults, null, 2),
6866
+ "utf-8"
6867
+ );
6868
+ process.stderr.write(
6869
+ `[scope/site] Playgrounds: ${succeeded} built${failures.length > 0 ? `, ${failures.length} failed` : ""}
6870
+ `
6871
+ );
6872
+ return failures;
6873
+ }
6874
+ function registerBuild(siteCmd) {
6875
+ siteCmd.command("build").description(
6876
+ '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-report.json\n scope site build --tokens reactscope.tokens.json\n scope site build --base-path /ui'
6877
+ ).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("--tokens <path>", "Path to reactscope.tokens.json (enables token browser page)").option("--title <text>", "Site title", "Scope \u2014 Component Gallery").action(
6878
+ async (opts) => {
6879
+ try {
6880
+ const inputDir = resolve15(process.cwd(), opts.input);
6881
+ const outputDir = resolve15(process.cwd(), opts.output);
6882
+ if (!existsSync13(inputDir)) {
6883
+ throw new Error(
6884
+ `Input directory not found: ${inputDir}
6885
+ Run \`scope manifest generate\` and \`scope render\` first.`
6886
+ );
6887
+ }
6888
+ const manifestPath = join6(inputDir, "manifest.json");
6889
+ if (!existsSync13(manifestPath)) {
6890
+ throw new Error(
6891
+ `Manifest not found at ${manifestPath}
6892
+ Run \`scope manifest generate\` first.`
6893
+ );
6894
+ }
6895
+ process.stderr.write(`Building site from ${inputDir}\u2026
6896
+ `);
6897
+ process.stderr.write("Bundling playgrounds\u2026\n");
6898
+ const failures = await generatePlaygrounds(inputDir, outputDir);
6899
+ const iconPatterns = loadIconPatternsFromConfig2(process.cwd());
6900
+ let tokenFilePath = opts.tokens ? resolve15(process.cwd(), opts.tokens) : void 0;
6901
+ if (tokenFilePath === void 0) {
6902
+ const autoPath = resolve15(process.cwd(), "reactscope.tokens.json");
6903
+ if (existsSync13(autoPath)) {
6904
+ tokenFilePath = autoPath;
6905
+ }
6906
+ }
6907
+ await buildSite({
6908
+ inputDir,
6909
+ outputDir,
6910
+ basePath: opts.basePath,
6911
+ ...opts.compliance !== void 0 && {
6912
+ compliancePath: resolve15(process.cwd(), opts.compliance)
6913
+ },
6914
+ ...tokenFilePath !== void 0 && { tokenFilePath },
6915
+ title: opts.title,
6916
+ iconPatterns
6917
+ });
6918
+ const manifest = JSON.parse(readFileSync12(manifestPath, "utf-8"));
6919
+ const componentCount = Object.keys(manifest.components).length;
6920
+ const generatedPlaygroundCount = componentCount === 0 ? 0 : statSync2(join6(outputDir, "playground")).isDirectory() ? componentCount - failures.length : 0;
6921
+ const siteFailures = [...failures];
6922
+ if (componentCount === 0) {
6923
+ siteFailures.push({
6924
+ component: "*",
6925
+ stage: "site",
6926
+ message: "Manifest contains zero components; generated site is structurally degraded.",
6927
+ outputPath: manifestPath
6928
+ });
6929
+ } else if (generatedPlaygroundCount === 0) {
6930
+ siteFailures.push({
6931
+ component: "*",
6932
+ stage: "site",
6933
+ message: "No playground pages were generated successfully; site build is degraded and should not be treated as green.",
6934
+ outputPath: join6(outputDir, "playground")
6935
+ });
6936
+ }
6937
+ const summaryPath = writeRunSummary({
6938
+ command: "scope site build",
6939
+ status: siteFailures.length > 0 ? "failed" : "success",
6940
+ outputPaths: [outputDir, join6(outputDir, "index.html")],
6941
+ failures: siteFailures
6942
+ });
6943
+ process.stderr.write(`Site written to ${outputDir}
6944
+ `);
6945
+ process.stderr.write(`[scope/site] Run summary written to ${summaryPath}
5768
6946
  `);
5769
6947
  process.stdout.write(`${outputDir}
5770
6948
  `);
6949
+ if (siteFailures.length > 0) process.exit(1);
5771
6950
  } catch (err) {
5772
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
6951
+ process.stderr.write(`${formatScopeDiagnostic(err)}
5773
6952
  `);
5774
6953
  process.exit(1);
5775
6954
  }
@@ -5778,72 +6957,142 @@ Run \`scope manifest generate\` first.`
5778
6957
  }
5779
6958
  function registerServe(siteCmd) {
5780
6959
  siteCmd.command("serve").description(
5781
- "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"
5782
- ).option("-p, --port <number>", "Port to listen on", "3000").option("-d, --dir <path>", "Directory to serve", ".reactscope/site").action((opts) => {
5783
- try {
5784
- const port = Number.parseInt(opts.port, 10);
5785
- if (Number.isNaN(port) || port < 1 || port > 65535) {
5786
- throw new Error(`Invalid port: ${opts.port}`);
5787
- }
5788
- const serveDir = resolve14(process.cwd(), opts.dir);
5789
- if (!existsSync12(serveDir)) {
5790
- throw new Error(
5791
- `Serve directory not found: ${serveDir}
5792
- Run \`scope site build\` first.`
5793
- );
5794
- }
5795
- const server = createServer((req, res) => {
5796
- const rawUrl = req.url ?? "/";
5797
- const urlPath = decodeURIComponent(rawUrl.split("?")[0] ?? "/");
5798
- const filePath = join5(serveDir, urlPath.endsWith("/") ? `${urlPath}index.html` : urlPath);
5799
- if (!filePath.startsWith(serveDir)) {
5800
- res.writeHead(403, { "Content-Type": "text/plain" });
5801
- res.end("Forbidden");
5802
- return;
6960
+ "Start a local HTTP server for the built site directory.\n\nRun `scope site build` first, or use --watch to auto-rebuild on changes.\nCtrl+C to stop.\n\nExamples:\n scope site serve\n scope site serve --port 8080\n scope site serve --dir ./my-site-output\n scope site serve --watch"
6961
+ ).option("-p, --port <number>", "Port to listen on", "3000").option("-d, --dir <path>", "Directory to serve", ".reactscope/site").option("-w, --watch", "Watch source files and rebuild on changes").option(
6962
+ "-i, --input <path>",
6963
+ "Input directory for .reactscope data (watch mode)",
6964
+ ".reactscope"
6965
+ ).option("--title <text>", "Site title (watch mode)", "Scope \u2014 Component Gallery").option("--base-path <path>", "Base URL path prefix (watch mode)", "/").action(
6966
+ async (opts) => {
6967
+ try {
6968
+ let notifyReload2 = function() {
6969
+ for (const client of sseClients) {
6970
+ client.write("data: reload\n\n");
6971
+ }
6972
+ };
6973
+ var notifyReload = notifyReload2;
6974
+ const port = Number.parseInt(opts.port, 10);
6975
+ if (Number.isNaN(port) || port < 1 || port > 65535) {
6976
+ throw new Error(`Invalid port: ${opts.port}`);
5803
6977
  }
5804
- if (existsSync12(filePath) && statSync2(filePath).isFile()) {
5805
- const ext = extname(filePath).toLowerCase();
5806
- const contentType = MIME_TYPES[ext] ?? "application/octet-stream";
5807
- res.writeHead(200, { "Content-Type": contentType });
5808
- createReadStream(filePath).pipe(res);
5809
- return;
6978
+ const serveDir = resolve15(process.cwd(), opts.dir);
6979
+ const watchMode = opts.watch === true;
6980
+ const sseClients = /* @__PURE__ */ new Set();
6981
+ if (watchMode) {
6982
+ await mkdir(serveDir, { recursive: true });
5810
6983
  }
5811
- const htmlPath = `${filePath}.html`;
5812
- if (existsSync12(htmlPath) && statSync2(htmlPath).isFile()) {
5813
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
5814
- createReadStream(htmlPath).pipe(res);
5815
- return;
6984
+ if (!watchMode && !existsSync13(serveDir)) {
6985
+ throw new Error(
6986
+ `Serve directory not found: ${serveDir}
6987
+ Run \`scope site build\` first.`
6988
+ );
5816
6989
  }
5817
- res.writeHead(404, { "Content-Type": "text/plain" });
5818
- res.end(`Not found: ${urlPath}`);
5819
- });
5820
- server.listen(port, () => {
5821
- process.stderr.write(`Scope site running at http://localhost:${port}
6990
+ const server = createServer((req, res) => {
6991
+ const rawUrl = req.url ?? "/";
6992
+ const urlPath = decodeURIComponent(rawUrl.split("?")[0] ?? "/");
6993
+ if (watchMode && urlPath === "/__livereload") {
6994
+ res.writeHead(200, {
6995
+ "Content-Type": "text/event-stream",
6996
+ "Cache-Control": "no-cache",
6997
+ Connection: "keep-alive",
6998
+ "Access-Control-Allow-Origin": "*"
6999
+ });
7000
+ res.write("data: connected\n\n");
7001
+ sseClients.add(res);
7002
+ req.on("close", () => sseClients.delete(res));
7003
+ return;
7004
+ }
7005
+ const filePath = join6(
7006
+ serveDir,
7007
+ urlPath.endsWith("/") ? `${urlPath}index.html` : urlPath
7008
+ );
7009
+ if (!filePath.startsWith(serveDir)) {
7010
+ res.writeHead(403, { "Content-Type": "text/plain" });
7011
+ res.end("Forbidden");
7012
+ return;
7013
+ }
7014
+ if (existsSync13(filePath) && statSync2(filePath).isFile()) {
7015
+ const ext = extname(filePath).toLowerCase();
7016
+ const contentType = MIME_TYPES[ext] ?? "application/octet-stream";
7017
+ if (watchMode && ext === ".html") {
7018
+ const html = injectLiveReloadScript(readFileSync12(filePath, "utf-8"));
7019
+ res.writeHead(200, { "Content-Type": contentType });
7020
+ res.end(html);
7021
+ return;
7022
+ }
7023
+ res.writeHead(200, { "Content-Type": contentType });
7024
+ createReadStream(filePath).pipe(res);
7025
+ return;
7026
+ }
7027
+ const htmlPath = `${filePath}.html`;
7028
+ if (existsSync13(htmlPath) && statSync2(htmlPath).isFile()) {
7029
+ if (watchMode) {
7030
+ const html = injectLiveReloadScript(readFileSync12(htmlPath, "utf-8"));
7031
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
7032
+ res.end(html);
7033
+ return;
7034
+ }
7035
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
7036
+ createReadStream(htmlPath).pipe(res);
7037
+ return;
7038
+ }
7039
+ res.writeHead(404, { "Content-Type": "text/plain" });
7040
+ res.end(`Not found: ${urlPath}`);
7041
+ });
7042
+ server.listen(port, () => {
7043
+ process.stderr.write(`Scope site running at http://localhost:${port}
5822
7044
  `);
5823
- process.stderr.write(`Serving ${serveDir}
7045
+ process.stderr.write(`Serving ${serveDir}
5824
7046
  `);
5825
- process.stderr.write("Press Ctrl+C to stop.\n");
5826
- });
5827
- server.on("error", (err) => {
5828
- if (err.code === "EADDRINUSE") {
5829
- process.stderr.write(`Error: Port ${port} is already in use.
7047
+ if (watchMode) {
7048
+ process.stderr.write(
7049
+ "Watch mode enabled \u2014 source changes trigger rebuild + browser reload\n"
7050
+ );
7051
+ }
7052
+ process.stderr.write("Press Ctrl+C to stop.\n");
7053
+ });
7054
+ server.on("error", (err) => {
7055
+ if (err.code === "EADDRINUSE") {
7056
+ process.stderr.write(`Error: Port ${port} is already in use.
5830
7057
  `);
5831
- } else {
5832
- process.stderr.write(`Server error: ${err.message}
7058
+ } else {
7059
+ process.stderr.write(`Server error: ${err.message}
5833
7060
  `);
7061
+ }
7062
+ process.exit(1);
7063
+ });
7064
+ if (watchMode) {
7065
+ const rootDir = process.cwd();
7066
+ const inputDir = resolve15(rootDir, opts.input);
7067
+ const initialManifest = await runFullBuild(
7068
+ rootDir,
7069
+ inputDir,
7070
+ serveDir,
7071
+ opts.title,
7072
+ opts.basePath
7073
+ );
7074
+ notifyReload2();
7075
+ startFileWatcher({
7076
+ rootDir,
7077
+ inputDir,
7078
+ outputDir: serveDir,
7079
+ title: opts.title,
7080
+ basePath: opts.basePath,
7081
+ previousManifest: initialManifest,
7082
+ notifyReload: notifyReload2
7083
+ });
5834
7084
  }
5835
- process.exit(1);
5836
- });
5837
- } catch (err) {
5838
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
7085
+ } catch (err) {
7086
+ process.stderr.write(`${formatScopeDiagnostic(err)}
5839
7087
  `);
5840
- process.exit(1);
7088
+ process.exit(1);
7089
+ }
5841
7090
  }
5842
- });
7091
+ );
5843
7092
  }
5844
7093
  function createSiteCommand() {
5845
7094
  const siteCmd = new Command9("site").description(
5846
- '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'
7095
+ '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-report.json\n scope site serve --port 8080'
5847
7096
  );
5848
7097
  registerBuild(siteCmd);
5849
7098
  registerServe(siteCmd);
@@ -5851,8 +7100,8 @@ function createSiteCommand() {
5851
7100
  }
5852
7101
 
5853
7102
  // src/tokens/commands.ts
5854
- import { existsSync as existsSync15, readFileSync as readFileSync12 } from "fs";
5855
- import { resolve as resolve18 } from "path";
7103
+ import { existsSync as existsSync17, readFileSync as readFileSync16 } from "fs";
7104
+ import { resolve as resolve20 } from "path";
5856
7105
  import {
5857
7106
  parseTokenFileSync as parseTokenFileSync2,
5858
7107
  TokenParseError,
@@ -5863,23 +7112,23 @@ import {
5863
7112
  import { Command as Command11 } from "commander";
5864
7113
 
5865
7114
  // src/tokens/compliance.ts
5866
- import { existsSync as existsSync13, readFileSync as readFileSync10 } from "fs";
5867
- import { resolve as resolve15 } from "path";
7115
+ import { existsSync as existsSync14, readFileSync as readFileSync13, writeFileSync as writeFileSync11 } from "fs";
7116
+ import { resolve as resolve16 } from "path";
5868
7117
  import {
5869
7118
  ComplianceEngine as ComplianceEngine4,
5870
7119
  TokenResolver as TokenResolver4
5871
7120
  } from "@agent-scope/tokens";
5872
7121
  var DEFAULT_STYLES_PATH = ".reactscope/compliance-styles.json";
5873
7122
  function loadStylesFile(stylesPath) {
5874
- const absPath = resolve15(process.cwd(), stylesPath);
5875
- if (!existsSync13(absPath)) {
7123
+ const absPath = resolve16(process.cwd(), stylesPath);
7124
+ if (!existsSync14(absPath)) {
5876
7125
  throw new Error(
5877
7126
  `Compliance styles file not found at ${absPath}.
5878
7127
  Run \`scope render all\` first to generate component styles, or use --styles to specify a path.
5879
7128
  Expected format: { "ComponentName": { colors: {}, spacing: {}, typography: {}, borders: {}, shadows: {} } }`
5880
7129
  );
5881
7130
  }
5882
- const raw = readFileSync10(absPath, "utf-8");
7131
+ const raw = readFileSync13(absPath, "utf-8");
5883
7132
  let parsed;
5884
7133
  try {
5885
7134
  parsed = JSON.parse(raw);
@@ -5907,11 +7156,11 @@ function categoryForProperty(property) {
5907
7156
  }
5908
7157
  function buildCategorySummary(batch) {
5909
7158
  const cats = {
5910
- color: { total: 0, onSystem: 0, offSystem: 0, compliance: 1 },
5911
- spacing: { total: 0, onSystem: 0, offSystem: 0, compliance: 1 },
5912
- typography: { total: 0, onSystem: 0, offSystem: 0, compliance: 1 },
5913
- border: { total: 0, onSystem: 0, offSystem: 0, compliance: 1 },
5914
- shadow: { total: 0, onSystem: 0, offSystem: 0, compliance: 1 }
7159
+ color: { total: 0, onSystem: 0, offSystem: 0, compliance: 0 },
7160
+ spacing: { total: 0, onSystem: 0, offSystem: 0, compliance: 0 },
7161
+ typography: { total: 0, onSystem: 0, offSystem: 0, compliance: 0 },
7162
+ border: { total: 0, onSystem: 0, offSystem: 0, compliance: 0 },
7163
+ shadow: { total: 0, onSystem: 0, offSystem: 0, compliance: 0 }
5915
7164
  };
5916
7165
  for (const report of Object.values(batch.components)) {
5917
7166
  for (const [property, result] of Object.entries(report.properties)) {
@@ -5927,7 +7176,7 @@ function buildCategorySummary(batch) {
5927
7176
  }
5928
7177
  }
5929
7178
  for (const summary of Object.values(cats)) {
5930
- summary.compliance = summary.total === 0 ? 1 : summary.onSystem / summary.total;
7179
+ summary.compliance = summary.total === 0 ? 0 : summary.onSystem / summary.total;
5931
7180
  }
5932
7181
  return cats;
5933
7182
  }
@@ -5968,6 +7217,11 @@ function formatComplianceReport(batch, threshold) {
5968
7217
  const lines = [];
5969
7218
  const thresholdLabel = threshold !== void 0 ? pct >= threshold ? " \u2713 (pass)" : ` \u2717 (below threshold ${threshold}%)` : "";
5970
7219
  lines.push(`Overall compliance score: ${pct}%${thresholdLabel}`);
7220
+ if (batch.totalProperties === 0) {
7221
+ lines.push(
7222
+ "No CSS properties were audited; run `scope render all` and inspect .reactscope/compliance-styles.json before treating compliance as green."
7223
+ );
7224
+ }
5971
7225
  lines.push("");
5972
7226
  const cats = buildCategorySummary(batch);
5973
7227
  const catEntries = Object.entries(cats).filter(([, s]) => s.total > 0);
@@ -6002,47 +7256,89 @@ function formatComplianceReport(batch, threshold) {
6002
7256
  }
6003
7257
  function registerCompliance(tokensCmd) {
6004
7258
  tokensCmd.command("compliance").description(
6005
- "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"
6006
- ).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) => {
6007
- try {
6008
- const tokenFilePath = resolveTokenFilePath(opts.file);
6009
- const { tokens } = loadTokens(tokenFilePath);
6010
- const resolver = new TokenResolver4(tokens);
6011
- const engine = new ComplianceEngine4(resolver);
6012
- const stylesPath = opts.styles ?? DEFAULT_STYLES_PATH;
6013
- const stylesFile = loadStylesFile(stylesPath);
6014
- const componentMap = /* @__PURE__ */ new Map();
6015
- for (const [name, styles] of Object.entries(stylesFile)) {
6016
- componentMap.set(name, styles);
6017
- }
6018
- if (componentMap.size === 0) {
6019
- process.stderr.write(`Warning: No components found in styles file at ${stylesPath}
7259
+ "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 --out .reactscope/compliance-report.json\n scope tokens compliance --styles ./custom/compliance-styles.json"
7260
+ ).option("--file <path>", "Path to token file (overrides config)").option("--styles <path>", `Path to compliance styles JSON (default: ${DEFAULT_STYLES_PATH})`).option(
7261
+ "--out <path>",
7262
+ "Write JSON report to file (for use with scope site build --compliance)"
7263
+ ).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(
7264
+ (opts) => {
7265
+ try {
7266
+ const tokenFilePath = resolveTokenFilePath(opts.file);
7267
+ const { tokens } = loadTokens(tokenFilePath);
7268
+ const resolver = new TokenResolver4(tokens);
7269
+ const engine = new ComplianceEngine4(resolver);
7270
+ const stylesPath = opts.styles ?? DEFAULT_STYLES_PATH;
7271
+ const stylesFile = loadStylesFile(stylesPath);
7272
+ const componentMap = /* @__PURE__ */ new Map();
7273
+ for (const [name, styles] of Object.entries(stylesFile)) {
7274
+ componentMap.set(name, styles);
7275
+ }
7276
+ if (componentMap.size === 0) {
7277
+ process.stderr.write(`Warning: No components found in styles file at ${stylesPath}
6020
7278
  `);
6021
- }
6022
- const batch = engine.auditBatch(componentMap);
6023
- const useJson = opts.format === "json" || opts.format !== "text" && !isTTY();
6024
- const threshold = opts.threshold !== void 0 ? Number.parseInt(opts.threshold, 10) : void 0;
6025
- if (useJson) {
6026
- process.stdout.write(`${JSON.stringify(batch, null, 2)}
7279
+ }
7280
+ const batch = engine.auditBatch(componentMap);
7281
+ const threshold = opts.threshold !== void 0 ? Number.parseInt(opts.threshold, 10) : void 0;
7282
+ const failures = [];
7283
+ if (batch.totalProperties === 0) {
7284
+ failures.push({
7285
+ component: "*",
7286
+ stage: "compliance",
7287
+ message: `No CSS properties were audited from ${stylesPath}; refusing to report silent success.`,
7288
+ outputPath: stylesPath
7289
+ });
7290
+ } else if (threshold !== void 0 && Math.round(batch.aggregateCompliance * 100) < threshold) {
7291
+ failures.push({
7292
+ component: "*",
7293
+ stage: "compliance",
7294
+ message: `Compliance ${Math.round(batch.aggregateCompliance * 100)}% is below threshold ${threshold}%.`,
7295
+ outputPath: opts.out ?? ".reactscope/compliance-report.json"
7296
+ });
7297
+ }
7298
+ if (opts.out !== void 0) {
7299
+ const outPath = resolve16(process.cwd(), opts.out);
7300
+ writeFileSync11(outPath, JSON.stringify(batch, null, 2), "utf-8");
7301
+ process.stderr.write(`Compliance report written to ${outPath}
6027
7302
  `);
6028
- } else {
6029
- process.stdout.write(`${formatComplianceReport(batch, threshold)}
7303
+ }
7304
+ const useJson = opts.format === "json" || opts.format !== "text" && !isTTY();
7305
+ if (useJson) {
7306
+ process.stdout.write(`${JSON.stringify(batch, null, 2)}
7307
+ `);
7308
+ } else {
7309
+ process.stdout.write(`${formatComplianceReport(batch, threshold)}
7310
+ `);
7311
+ }
7312
+ const summaryPath = writeRunSummary({
7313
+ command: "scope tokens compliance",
7314
+ status: failures.length > 0 ? "failed" : "success",
7315
+ outputPaths: [opts.out ?? ".reactscope/compliance-report.json", stylesPath],
7316
+ compliance: {
7317
+ auditedProperties: batch.totalProperties,
7318
+ onSystemProperties: batch.totalOnSystem,
7319
+ offSystemProperties: batch.totalOffSystem,
7320
+ score: Math.round(batch.aggregateCompliance * 100),
7321
+ threshold
7322
+ },
7323
+ failures
7324
+ });
7325
+ process.stderr.write(`[scope/tokens] Run summary written to ${summaryPath}
7326
+ `);
7327
+ if (failures.length > 0) {
7328
+ process.exit(1);
7329
+ }
7330
+ } catch (err) {
7331
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
6030
7332
  `);
6031
- }
6032
- if (threshold !== void 0 && Math.round(batch.aggregateCompliance * 100) < threshold) {
6033
7333
  process.exit(1);
6034
7334
  }
6035
- } catch (err) {
6036
- process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
6037
- `);
6038
- process.exit(1);
6039
7335
  }
6040
- });
7336
+ );
6041
7337
  }
6042
7338
 
6043
7339
  // src/tokens/export.ts
6044
- import { existsSync as existsSync14, readFileSync as readFileSync11, writeFileSync as writeFileSync9 } from "fs";
6045
- import { resolve as resolve16 } from "path";
7340
+ import { existsSync as existsSync15, readFileSync as readFileSync14, writeFileSync as writeFileSync12 } from "fs";
7341
+ import { resolve as resolve17 } from "path";
6046
7342
  import {
6047
7343
  exportTokens,
6048
7344
  parseTokenFileSync,
@@ -6055,21 +7351,21 @@ var CONFIG_FILE = "reactscope.config.json";
6055
7351
  var SUPPORTED_FORMATS = ["css", "ts", "scss", "tailwind", "flat-json", "figma"];
6056
7352
  function resolveTokenFilePath2(fileFlag) {
6057
7353
  if (fileFlag !== void 0) {
6058
- return resolve16(process.cwd(), fileFlag);
7354
+ return resolve17(process.cwd(), fileFlag);
6059
7355
  }
6060
- const configPath = resolve16(process.cwd(), CONFIG_FILE);
6061
- if (existsSync14(configPath)) {
7356
+ const configPath = resolve17(process.cwd(), CONFIG_FILE);
7357
+ if (existsSync15(configPath)) {
6062
7358
  try {
6063
- const raw = readFileSync11(configPath, "utf-8");
7359
+ const raw = readFileSync14(configPath, "utf-8");
6064
7360
  const config = JSON.parse(raw);
6065
7361
  if (typeof config === "object" && config !== null && "tokens" in config && typeof config.tokens === "object" && config.tokens !== null && typeof config.tokens?.file === "string") {
6066
7362
  const file = config.tokens.file;
6067
- return resolve16(process.cwd(), file);
7363
+ return resolve17(process.cwd(), file);
6068
7364
  }
6069
7365
  } catch {
6070
7366
  }
6071
7367
  }
6072
- return resolve16(process.cwd(), DEFAULT_TOKEN_FILE);
7368
+ return resolve17(process.cwd(), DEFAULT_TOKEN_FILE);
6073
7369
  }
6074
7370
  function createTokensExportCommand() {
6075
7371
  return new Command10("export").description(
@@ -6100,13 +7396,13 @@ Supported formats: ${SUPPORTED_FORMATS.join(", ")}
6100
7396
  const format = opts.format;
6101
7397
  try {
6102
7398
  const filePath = resolveTokenFilePath2(opts.file);
6103
- if (!existsSync14(filePath)) {
7399
+ if (!existsSync15(filePath)) {
6104
7400
  throw new Error(
6105
7401
  `Token file not found at ${filePath}.
6106
7402
  Create a reactscope.tokens.json file or use --file to specify a path.`
6107
7403
  );
6108
7404
  }
6109
- const raw = readFileSync11(filePath, "utf-8");
7405
+ const raw = readFileSync14(filePath, "utf-8");
6110
7406
  const { tokens, rawFile } = parseTokenFileSync(raw);
6111
7407
  let themesMap;
6112
7408
  if (opts.theme !== void 0) {
@@ -6145,8 +7441,8 @@ Available themes: ${themeNames.join(", ")}`
6145
7441
  themes: themesMap
6146
7442
  });
6147
7443
  if (opts.out !== void 0) {
6148
- const outPath = resolve16(process.cwd(), opts.out);
6149
- writeFileSync9(outPath, output, "utf-8");
7444
+ const outPath = resolve17(process.cwd(), opts.out);
7445
+ writeFileSync12(outPath, output, "utf-8");
6150
7446
  process.stderr.write(`Exported ${tokens.length} tokens to ${outPath}
6151
7447
  `);
6152
7448
  } else {
@@ -6261,23 +7557,251 @@ ${formatImpactSummary(report)}
6261
7557
  );
6262
7558
  }
6263
7559
 
7560
+ // src/tokens/init.ts
7561
+ import { existsSync as existsSync16, readFileSync as readFileSync15, writeFileSync as writeFileSync13 } from "fs";
7562
+ import { resolve as resolve18 } from "path";
7563
+ var DEFAULT_TOKEN_FILE2 = "reactscope.tokens.json";
7564
+ var CONFIG_FILE2 = "reactscope.config.json";
7565
+ function resolveOutputPath(fileFlag) {
7566
+ if (fileFlag !== void 0) {
7567
+ return resolve18(process.cwd(), fileFlag);
7568
+ }
7569
+ const configPath = resolve18(process.cwd(), CONFIG_FILE2);
7570
+ if (existsSync16(configPath)) {
7571
+ try {
7572
+ const raw = readFileSync15(configPath, "utf-8");
7573
+ const config = JSON.parse(raw);
7574
+ if (typeof config === "object" && config !== null && "tokens" in config && typeof config.tokens === "object" && config.tokens !== null && typeof config.tokens?.file === "string") {
7575
+ const file = config.tokens.file;
7576
+ return resolve18(process.cwd(), file);
7577
+ }
7578
+ } catch {
7579
+ }
7580
+ }
7581
+ return resolve18(process.cwd(), DEFAULT_TOKEN_FILE2);
7582
+ }
7583
+ var CSS_VAR_RE = /--([\w-]+)\s*:\s*([^;]+)/g;
7584
+ var HEX_COLOR_RE = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
7585
+ var COLOR_FN_RE = /^(?:rgba?|hsla?|oklch|oklab|lch|lab|color|hwb)\(/;
7586
+ var DIMENSION_RE = /^-?\d+(?:\.\d+)?(?:px|rem|em|%|vw|vh|ch|ex|cap|lh|dvh|svh|lvh)$/;
7587
+ var DURATION_RE = /^-?\d+(?:\.\d+)?(?:ms|s)$/;
7588
+ var FONT_FAMILY_RE = /^["']|,\s*(?:sans-serif|serif|monospace|cursive|fantasy|system-ui)/;
7589
+ var NUMBER_RE = /^-?\d+(?:\.\d+)?$/;
7590
+ var CUBIC_BEZIER_RE = /^cubic-bezier\(/;
7591
+ var SHADOW_RE = /^\d.*(?:px|rem|em)\s+(?:#|rgba?|hsla?|oklch|oklab)/i;
7592
+ function inferTokenType(value) {
7593
+ const v = value.trim();
7594
+ if (HEX_COLOR_RE.test(v) || COLOR_FN_RE.test(v)) return "color";
7595
+ if (DURATION_RE.test(v)) return "duration";
7596
+ if (DIMENSION_RE.test(v)) return "dimension";
7597
+ if (FONT_FAMILY_RE.test(v)) return "fontFamily";
7598
+ if (CUBIC_BEZIER_RE.test(v)) return "cubicBezier";
7599
+ if (SHADOW_RE.test(v)) return "shadow";
7600
+ if (NUMBER_RE.test(v)) return "number";
7601
+ return "color";
7602
+ }
7603
+ function setNestedToken(root, segments, value, type) {
7604
+ let node = root;
7605
+ for (let i = 0; i < segments.length - 1; i++) {
7606
+ const seg = segments[i];
7607
+ if (seg === void 0) continue;
7608
+ if (!(seg in node) || typeof node[seg] !== "object" || node[seg] === null) {
7609
+ node[seg] = {};
7610
+ }
7611
+ node = node[seg];
7612
+ }
7613
+ const leaf = segments[segments.length - 1];
7614
+ if (leaf === void 0) return;
7615
+ node[leaf] = { value, type };
7616
+ }
7617
+ function extractBlockBody(css, openBrace) {
7618
+ let depth = 0;
7619
+ let end = -1;
7620
+ for (let i = openBrace; i < css.length; i++) {
7621
+ if (css[i] === "{") depth++;
7622
+ else if (css[i] === "}") {
7623
+ depth--;
7624
+ if (depth === 0) {
7625
+ end = i;
7626
+ break;
7627
+ }
7628
+ }
7629
+ }
7630
+ if (end === -1) return "";
7631
+ return css.slice(openBrace + 1, end);
7632
+ }
7633
+ function parseScopedBlocks(css) {
7634
+ const blocks = [];
7635
+ const blockRe = /(?::root|@theme(?:\s+inline)?|\.dark\.high-contrast|\.dark)\s*\{/g;
7636
+ let match = blockRe.exec(css);
7637
+ while (match !== null) {
7638
+ const selector = match[0];
7639
+ const braceIdx = css.indexOf("{", match.index);
7640
+ if (braceIdx === -1) {
7641
+ match = blockRe.exec(css);
7642
+ continue;
7643
+ }
7644
+ const body = extractBlockBody(css, braceIdx);
7645
+ let scope;
7646
+ if (selector.includes(".dark.high-contrast")) scope = "dark-high-contrast";
7647
+ else if (selector.includes(".dark")) scope = "dark";
7648
+ else if (selector.includes("@theme")) scope = "theme";
7649
+ else scope = "root";
7650
+ blocks.push({ scope, body });
7651
+ match = blockRe.exec(css);
7652
+ }
7653
+ return blocks;
7654
+ }
7655
+ function extractVarsFromBody(body) {
7656
+ const results = [];
7657
+ for (const m of body.matchAll(CSS_VAR_RE)) {
7658
+ const name = m[1];
7659
+ const value = m[2]?.trim();
7660
+ if (name === void 0 || value === void 0 || value.length === 0) continue;
7661
+ if (value.startsWith("var(") || value.startsWith("calc(")) continue;
7662
+ results.push({ name, value });
7663
+ }
7664
+ return results;
7665
+ }
7666
+ function extractCSSCustomProperties(tokenSources) {
7667
+ const cssSources = tokenSources.filter(
7668
+ (s) => s.kind === "css-custom-properties" || s.kind === "tailwind-v4-theme"
7669
+ );
7670
+ if (cssSources.length === 0) return null;
7671
+ const tokens = {};
7672
+ const themes = {};
7673
+ let found = false;
7674
+ for (const source of cssSources) {
7675
+ try {
7676
+ if (source.path.includes("compiled") || source.path.includes(".min.")) continue;
7677
+ const raw = readFileSync15(source.path, "utf-8");
7678
+ const blocks = parseScopedBlocks(raw);
7679
+ for (const block of blocks) {
7680
+ const vars = extractVarsFromBody(block.body);
7681
+ for (const { name, value } of vars) {
7682
+ const segments = name.split("-").filter(Boolean);
7683
+ if (segments.length === 0) continue;
7684
+ if (block.scope === "root" || block.scope === "theme") {
7685
+ const type = inferTokenType(value);
7686
+ setNestedToken(tokens, segments, value, type);
7687
+ found = true;
7688
+ } else {
7689
+ const themeName = block.scope;
7690
+ if (!themes[themeName]) themes[themeName] = {};
7691
+ const path = segments.join(".");
7692
+ themes[themeName][path] = value;
7693
+ found = true;
7694
+ }
7695
+ }
7696
+ }
7697
+ } catch {
7698
+ }
7699
+ }
7700
+ return found ? { tokens, themes } : null;
7701
+ }
7702
+ function registerTokensInit(tokensCmd) {
7703
+ tokensCmd.command("init").description(
7704
+ "Detect design-token sources in the project and generate a token file.\n\nDETECTED SOURCES:\n - Tailwind config (colors, spacing, fontFamily, borderRadius)\n - CSS custom properties (:root { --color-primary: #0070f3; })\n\nWill not overwrite an existing token file unless --force is passed.\n\nOUTPUT PATH 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\nExamples:\n scope tokens init\n scope tokens init --force\n scope tokens init --file tokens/brand.json\n scope tokens init --force --file custom-tokens.json"
7705
+ ).option("--file <path>", "Output path for the token file (overrides config)").option("--force", "Overwrite existing token file", false).action((opts) => {
7706
+ try {
7707
+ const outPath = resolveOutputPath(opts.file);
7708
+ if (existsSync16(outPath) && !opts.force) {
7709
+ process.stderr.write(
7710
+ `Token file already exists at ${outPath}.
7711
+ Run with --force to overwrite.
7712
+ `
7713
+ );
7714
+ process.exit(1);
7715
+ }
7716
+ const rootDir = process.cwd();
7717
+ const detected = detectProject(rootDir);
7718
+ const tailwindTokens = extractTailwindTokens(detected.tokenSources);
7719
+ const cssResult = extractCSSCustomProperties(detected.tokenSources);
7720
+ const mergedTokens = {};
7721
+ const mergedThemes = {};
7722
+ if (tailwindTokens !== null) {
7723
+ Object.assign(mergedTokens, tailwindTokens);
7724
+ }
7725
+ if (cssResult !== null) {
7726
+ for (const [key, value] of Object.entries(cssResult.tokens)) {
7727
+ if (!(key in mergedTokens)) {
7728
+ mergedTokens[key] = value;
7729
+ }
7730
+ }
7731
+ for (const [themeName, overrides] of Object.entries(cssResult.themes)) {
7732
+ if (!mergedThemes[themeName]) mergedThemes[themeName] = {};
7733
+ Object.assign(mergedThemes[themeName], overrides);
7734
+ }
7735
+ }
7736
+ const tokenFile = {
7737
+ $schema: "https://raw.githubusercontent.com/FlatFilers/Scope/main/packages/tokens/schema.json",
7738
+ version: "1.0.0",
7739
+ meta: {
7740
+ name: "Design Tokens",
7741
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString().split("T")[0]
7742
+ },
7743
+ tokens: mergedTokens
7744
+ };
7745
+ if (Object.keys(mergedThemes).length > 0) {
7746
+ tokenFile.themes = mergedThemes;
7747
+ }
7748
+ writeFileSync13(outPath, `${JSON.stringify(tokenFile, null, 2)}
7749
+ `);
7750
+ const tokenGroupCount = Object.keys(mergedTokens).length;
7751
+ const themeNames = Object.keys(mergedThemes);
7752
+ if (detected.tokenSources.length > 0) {
7753
+ process.stdout.write("Detected token sources:\n");
7754
+ for (const source of detected.tokenSources) {
7755
+ process.stdout.write(` ${source.kind}: ${source.path}
7756
+ `);
7757
+ }
7758
+ process.stdout.write("\n");
7759
+ }
7760
+ if (tokenGroupCount > 0) {
7761
+ process.stdout.write(`Extracted ${tokenGroupCount} token group(s) \u2192 ${outPath}
7762
+ `);
7763
+ if (themeNames.length > 0) {
7764
+ for (const name of themeNames) {
7765
+ const count = Object.keys(mergedThemes[name] ?? {}).length;
7766
+ process.stdout.write(` theme "${name}": ${count} override(s)
7767
+ `);
7768
+ }
7769
+ }
7770
+ } else {
7771
+ process.stdout.write(
7772
+ `No token sources detected. Created empty token file \u2192 ${outPath}
7773
+ Add tokens manually or re-run after configuring a design system.
7774
+ `
7775
+ );
7776
+ }
7777
+ } catch (err) {
7778
+ process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}
7779
+ `);
7780
+ process.exit(1);
7781
+ }
7782
+ });
7783
+ }
7784
+
6264
7785
  // src/tokens/preview.ts
6265
- import { mkdirSync as mkdirSync6, writeFileSync as writeFileSync10 } from "fs";
6266
- import { resolve as resolve17 } from "path";
7786
+ import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync14 } from "fs";
7787
+ import { resolve as resolve19 } from "path";
6267
7788
  import { BrowserPool as BrowserPool6, SpriteSheetGenerator } from "@agent-scope/render";
6268
7789
  import { ComplianceEngine as ComplianceEngine6, ImpactAnalyzer as ImpactAnalyzer2, TokenResolver as TokenResolver7 } from "@agent-scope/tokens";
6269
7790
  var DEFAULT_STYLES_PATH3 = ".reactscope/compliance-styles.json";
6270
7791
  var DEFAULT_MANIFEST_PATH = ".reactscope/manifest.json";
6271
7792
  var DEFAULT_OUTPUT_DIR2 = ".reactscope/previews";
6272
7793
  async function renderComponentWithCssOverride(filePath, componentName, cssOverride, vpWidth, vpHeight, timeoutMs) {
7794
+ const PAD = 16;
6273
7795
  const htmlHarness = await buildComponentHarness(
6274
7796
  filePath,
6275
7797
  componentName,
6276
7798
  {},
6277
7799
  // no props
6278
7800
  vpWidth,
6279
- cssOverride
7801
+ cssOverride,
6280
7802
  // injected as <style>
7803
+ void 0,
7804
+ PAD
6281
7805
  );
6282
7806
  const pool = new BrowserPool6({
6283
7807
  size: { browsers: 1, pagesPerBrowser: 1 },
@@ -6298,7 +7822,6 @@ async function renderComponentWithCssOverride(filePath, componentName, cssOverri
6298
7822
  );
6299
7823
  const rootLocator = page.locator("[data-reactscope-root]");
6300
7824
  const bb = await rootLocator.boundingBox();
6301
- const PAD = 16;
6302
7825
  const MIN_W = 320;
6303
7826
  const MIN_H = 120;
6304
7827
  const clipX = Math.max(0, (bb?.x ?? 0) - PAD);
@@ -6446,10 +7969,10 @@ function registerPreview(tokensCmd) {
6446
7969
  });
6447
7970
  const spriteResult = await generator.generate(matrixResult);
6448
7971
  const tokenLabel = tokenPath.replace(/\./g, "-");
6449
- const outputPath = opts.output ?? resolve17(process.cwd(), DEFAULT_OUTPUT_DIR2, `preview-${tokenLabel}.png`);
6450
- const outputDir = resolve17(outputPath, "..");
6451
- mkdirSync6(outputDir, { recursive: true });
6452
- writeFileSync10(outputPath, spriteResult.png);
7972
+ const outputPath = opts.output ?? resolve19(process.cwd(), DEFAULT_OUTPUT_DIR2, `preview-${tokenLabel}.png`);
7973
+ const outputDir = resolve19(outputPath, "..");
7974
+ mkdirSync7(outputDir, { recursive: true });
7975
+ writeFileSync14(outputPath, spriteResult.png);
6453
7976
  const useJson = opts.format === "json" || opts.format !== "text" && !isTTY();
6454
7977
  if (useJson) {
6455
7978
  process.stdout.write(
@@ -6487,8 +8010,8 @@ function registerPreview(tokensCmd) {
6487
8010
  }
6488
8011
 
6489
8012
  // src/tokens/commands.ts
6490
- var DEFAULT_TOKEN_FILE2 = "reactscope.tokens.json";
6491
- var CONFIG_FILE2 = "reactscope.config.json";
8013
+ var DEFAULT_TOKEN_FILE3 = "reactscope.tokens.json";
8014
+ var CONFIG_FILE3 = "reactscope.config.json";
6492
8015
  function isTTY2() {
6493
8016
  return process.stdout.isTTY === true;
6494
8017
  }
@@ -6508,30 +8031,30 @@ function buildTable2(headers, rows) {
6508
8031
  }
6509
8032
  function resolveTokenFilePath(fileFlag) {
6510
8033
  if (fileFlag !== void 0) {
6511
- return resolve18(process.cwd(), fileFlag);
8034
+ return resolve20(process.cwd(), fileFlag);
6512
8035
  }
6513
- const configPath = resolve18(process.cwd(), CONFIG_FILE2);
6514
- if (existsSync15(configPath)) {
8036
+ const configPath = resolve20(process.cwd(), CONFIG_FILE3);
8037
+ if (existsSync17(configPath)) {
6515
8038
  try {
6516
- const raw = readFileSync12(configPath, "utf-8");
8039
+ const raw = readFileSync16(configPath, "utf-8");
6517
8040
  const config = JSON.parse(raw);
6518
8041
  if (typeof config === "object" && config !== null && "tokens" in config && typeof config.tokens === "object" && config.tokens !== null && typeof config.tokens?.file === "string") {
6519
8042
  const file = config.tokens.file;
6520
- return resolve18(process.cwd(), file);
8043
+ return resolve20(process.cwd(), file);
6521
8044
  }
6522
8045
  } catch {
6523
8046
  }
6524
8047
  }
6525
- return resolve18(process.cwd(), DEFAULT_TOKEN_FILE2);
8048
+ return resolve20(process.cwd(), DEFAULT_TOKEN_FILE3);
6526
8049
  }
6527
8050
  function loadTokens(absPath) {
6528
- if (!existsSync15(absPath)) {
8051
+ if (!existsSync17(absPath)) {
6529
8052
  throw new Error(
6530
8053
  `Token file not found at ${absPath}.
6531
8054
  Create a reactscope.tokens.json file or use --file to specify a path.`
6532
8055
  );
6533
8056
  }
6534
- const raw = readFileSync12(absPath, "utf-8");
8057
+ const raw = readFileSync16(absPath, "utf-8");
6535
8058
  return parseTokenFileSync2(raw);
6536
8059
  }
6537
8060
  function getRawValue(node, segments) {
@@ -6774,13 +8297,13 @@ Examples:
6774
8297
  ).option("--file <path>", "Path to token file (overrides config)").option("--format <fmt>", "Output format: json or text (default: auto-detect)").action((opts) => {
6775
8298
  try {
6776
8299
  const filePath = resolveTokenFilePath(opts.file);
6777
- if (!existsSync15(filePath)) {
8300
+ if (!existsSync17(filePath)) {
6778
8301
  throw new Error(
6779
8302
  `Token file not found at ${filePath}.
6780
8303
  Create a reactscope.tokens.json file or use --file to specify a path.`
6781
8304
  );
6782
8305
  }
6783
- const raw = readFileSync12(filePath, "utf-8");
8306
+ const raw = readFileSync16(filePath, "utf-8");
6784
8307
  const useJson = opts.format === "json" || opts.format !== "text" && !isTTY2();
6785
8308
  const errors = [];
6786
8309
  let parsed;
@@ -6851,6 +8374,7 @@ function createTokensCommand() {
6851
8374
  const tokensCmd = new Command11("tokens").description(
6852
8375
  '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'
6853
8376
  );
8377
+ registerTokensInit(tokensCmd);
6854
8378
  registerGet2(tokensCmd);
6855
8379
  registerList2(tokensCmd);
6856
8380
  registerSearch(tokensCmd);
@@ -6866,7 +8390,7 @@ function createTokensCommand() {
6866
8390
  // src/program.ts
6867
8391
  function createProgram(options = {}) {
6868
8392
  const program2 = new Command12("scope").version(options.version ?? "0.1.0").description(
6869
- '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.'
8393
+ '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\nAGENT QUICKSTART:\n scope get-skill > /tmp/scope-skill.md\n scope init --yes\n scope doctor --json\n scope manifest list --format json\n scope render all --format json --output-dir .reactscope/renders\n scope site build --output .reactscope/site\n scope instrument profile http://localhost:5173\n\nCI QUICKSTART:\n scope ci --json --output .reactscope/ci-result.json\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.'
6870
8394
  );
6871
8395
  program2.command("capture <url>").description(
6872
8396
  "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"
@@ -6948,7 +8472,7 @@ function createProgram(options = {}) {
6948
8472
  program2.command("generate").description(
6949
8473
  '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"'
6950
8474
  ).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) => {
6951
- const raw = readFileSync13(tracePath, "utf-8");
8475
+ const raw = readFileSync17(tracePath, "utf-8");
6952
8476
  const trace = loadTrace(raw);
6953
8477
  const source = generateTest(trace, {
6954
8478
  description: opts.description,