canicode 0.11.2 → 0.11.4

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/comparison/visual-compare-helpers.ts","../../src/core/comparison/visual-compare.ts","../../src/core/contracts/category.ts","../../src/core/contracts/severity.ts","../../src/core/contracts/rule.ts","../../src/core/rules/rule-config.ts","../../src/core/rules/rule-registry.ts","../../src/core/contracts/acknowledgment.ts","../../src/core/contracts/analysis-scope.ts","../../src/core/engine/rule-engine.ts","../../src/core/adapters/figma-client.ts","../../src/core/adapters/figma-transformer.ts","../../src/core/adapters/component-resolver.ts","../../src/core/contracts/figma-node.ts","../../src/core/adapters/figma-file-loader.ts","../../src/core/adapters/figma-url-parser.ts","../../src/core/engine/config-store.ts","../../src/core/engine/loader.ts","../../src/core/adapters/instance-id-parser.ts","../../src/core/gotcha/apply-context.ts","../../package.json","../../src/core/engine/scoring.ts","../../src/core/rules/gotcha-questions.ts","../../src/core/gotcha/group-and-batch-questions.ts","../../src/core/gotcha/survey-generator.ts","../../src/core/ui-constants.ts","../../src/core/ui-helpers.ts","../../src/core/report-html/render.ts","../../src/core/report-html/index.ts","../../src/core/rules/config-loader.ts","../../src/core/monitoring/events.ts","../../src/core/monitoring/capture.ts","../../src/core/monitoring/index.ts","../../src/core/monitoring/keys.ts","../../src/core/contracts/design-key.ts","../../src/core/rules/node-semantics.ts","../../src/core/rules/rule-exceptions.ts","../../src/core/rules/rule-messages.ts","../../src/core/rules/structure/index.ts","../../src/core/rules/token/index.ts","../../src/core/rules/component/index.ts","../../src/core/rules/naming/index.ts","../../src/core/rules/interaction/index.ts","../../src/mcp/server.ts"],"names":["resolve","statSync","readFileSync","width","height","mkdirSync","dirname","writeFileSync","existsSync","PNG","z","config","BATCH_SIZE","join","response","file","componentDefs","interactionDests","findNodeById","esc","readFile","version","isFigmaUrl","require","visualCompare"],"mappings":";;;;;;;;;;;;;;;;;;;;;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EAAE,IAAA,EAAM,QAAiB,IAAA,EAAM,CAAA,OAAA,EAAU,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,IAAI,CAAA;AAAA,QAC7G,OAAA,EAAS;AAAA,OACX;AAAA,IACF;AAAA,EACF;AACF,CAAA;AAEA,eAAe,IAAA,GAAO;AACpB,EAAA,MAAM,gBAAA,GAAyD;AAAA,IAC7D,WAAA,EAAa,KAAA;AAAA,IACb,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,SAAS,mBAAA;AAAoB,GAC/B;AACA,EAAA,MAAM,KAAA,GAAQ,kBAAiB,IAAK,eAAA;AACpC,mBAA4B,aAAA,GAAgB,KAAA;AAC5C,EAAA,MAAM,IAAA,GAAO,cAAa,IAAK,UAAA;AAC/B,mBAA2B,SAAA,GAAY,IAAA;AACvC,EAAA,gBAAA,CAAiB,aAAa,WAAA,EAAY;AAC1C,EAAA,cAAA,CAAe,gBAAgB,CAAA;AAE/B,EAAA,MAAM,SAAA,GAAY,IAAI,oBAAA,EAAqB;AAC3C,EAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAChC;AAEA,OAAA,CAAQ,EAAA,CAAG,cAAc,MAAM;AAC7B,EAAA,kBAAA,EAAmB;AACrB,CAAC,CAAA;AAED,IAAA,EAAK,CAAE,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA","file":"server.js","sourcesContent":["/**\n * Pure helper functions extracted from visual-compare.ts.\n * These have no side effects beyond file I/O and can be tested directly.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, statSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\n/** Directory used for caching Figma screenshots. */\nexport const FIGMA_CACHE_DIR = \"/tmp/canicode-figma-cache\";\n\n/**\n * Known @1x screenshot widths from fixture convention.\n * Screenshots at these widths are captured at 1x scale (pixel width = logical width).\n * All other widths are assumed @2x (e.g., 2400px PNG = 1200px logical).\n */\nexport const KNOWN_1X_WIDTHS = [1920, 768];\n\n/**\n * Infer the export scale of a fixture screenshot based on its pixel width.\n * Uses KNOWN_1X_WIDTHS convention: 1920/768 = @1x, others = @2x.\n */\nexport function inferExportScale(pngWidth: number): number {\n return KNOWN_1X_WIDTHS.includes(pngWidth) ? 1 : 2;\n}\n\n/** Cache time-to-live: 1 hour. */\nexport const FIGMA_CACHE_TTL_MS = 60 * 60 * 1000;\n\n/**\n * Tolerance for detecting integer scale factors (@2x, @3x).\n * Broader tolerance because render/rounding errors accumulate at higher scales.\n */\nexport const SCALE_ROUNDING_TOLERANCE = 0.08;\n\n/**\n * Tolerance for detecting 1x (unity) scale.\n * Tighter to avoid false positives — misidentifying a scaled PNG as 1x.\n */\nexport const UNITY_SCALE_TOLERANCE = 0.02;\n\n/**\n * Get the cache path for a given fileKey + nodeId combination.\n */\nexport function getFigmaCachePath(fileKey: string, nodeId: string, scale: number): string {\n // Sanitize nodeId for use as filename (replace : with -)\n const safeNodeId = nodeId.replace(/:/g, \"-\");\n return resolve(FIGMA_CACHE_DIR, `${fileKey}_${safeNodeId}@${scale}x.png`);\n}\n\n/**\n * Check if a cached Figma screenshot exists and is still fresh (within TTL).\n */\nexport function isCacheFresh(cachePath: string): boolean {\n try {\n const stats = statSync(cachePath);\n return Date.now() - stats.mtimeMs < FIGMA_CACHE_TTL_MS;\n } catch {\n // File doesn't exist or was removed between check and stat (TOCTOU safe)\n return false;\n }\n}\n\n/**\n * Infer device pixel ratio so the Playwright screenshot matches Figma PNG pixel dimensions.\n */\nexport function inferDeviceScaleFactor(\n pngW: number,\n pngH: number,\n logicalW: number,\n logicalH: number,\n fallback: number,\n): number {\n if (logicalW <= 0 || logicalH <= 0) return 1;\n const sx = pngW / logicalW;\n const sy = pngH / logicalH;\n const rounded = Math.round((sx + sy) / 2);\n if (rounded >= 2 && Math.abs(sx - rounded) < SCALE_ROUNDING_TOLERANCE && Math.abs(sy - rounded) < SCALE_ROUNDING_TOLERANCE) {\n return rounded;\n }\n if (Math.abs(sx - 1) < UNITY_SCALE_TOLERANCE && Math.abs(sy - 1) < UNITY_SCALE_TOLERANCE) return 1;\n return fallback >= 2 ? fallback : Math.max(1, Math.round(sx));\n}\n\n/**\n * Pad a PNG to target dimensions with a high-contrast fill color (magenta #FF00FF).\n * Unlike resize, padding preserves original pixels 1:1 and guarantees that\n * any size difference is counted as mismatched pixels by pixelmatch.\n *\n * Note: If both images contain magenta in the padded area, those pixels\n * will match — extremely rare in real designs but theoretically possible.\n */\nexport function padPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const padded = new PNG({ width: targetWidth, height: targetHeight });\n // Fill entire canvas with magenta (FF00FF) — guaranteed to differ from any real content\n for (let i = 0; i < padded.data.length; i += 4) {\n padded.data[i] = 255; // R\n padded.data[i + 1] = 0; // G\n padded.data[i + 2] = 255; // B\n padded.data[i + 3] = 255; // A\n }\n // Copy original pixels into top-left corner\n for (let y = 0; y < png.height; y++) {\n for (let x = 0; x < png.width; x++) {\n const srcIdx = (y * png.width + x) * 4;\n const dstIdx = (y * targetWidth + x) * 4;\n padded.data[dstIdx] = png.data[srcIdx]!;\n padded.data[dstIdx + 1] = png.data[srcIdx + 1]!;\n padded.data[dstIdx + 2] = png.data[srcIdx + 2]!;\n padded.data[dstIdx + 3] = png.data[srcIdx + 3]!;\n }\n }\n return padded;\n}\n\n/** Options for screenshot comparison. */\nexport interface CompareOptions {\n /** How to handle size mismatches: \"pad\" (magenta fill) or \"crop\" (min dimensions). Default: \"pad\". */\n sizeMismatch?: \"pad\" | \"crop\";\n /** pixelmatch threshold (0-1). Default: 0.1. */\n threshold?: number;\n}\n\n/**\n * Crop a PNG to target dimensions (top-left corner preserved).\n */\nexport function cropPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const cropped = new PNG({ width: targetWidth, height: targetHeight });\n for (let y = 0; y < targetHeight; y++) {\n png.data.copy(cropped.data, y * targetWidth * 4, y * png.width * 4, y * png.width * 4 + targetWidth * 4);\n }\n return cropped;\n}\n\n/**\n * Compare two PNG files using pixelmatch.\n */\nexport function compareScreenshots(\n path1: string,\n path2: string,\n diffOutputPath: string,\n options?: CompareOptions,\n): { similarity: number; diffPixels: number; totalPixels: number; width: number; height: number } {\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold ?? 0.1;\n const raw1 = PNG.sync.read(readFileSync(path1));\n const raw2 = PNG.sync.read(readFileSync(path2));\n\n let img1: PNG = raw1;\n let img2: PNG = raw2;\n\n // Size mismatch — normalize to same dimensions\n if (raw1.width !== raw2.width || raw1.height !== raw2.height) {\n if (sizeMismatch === \"crop\") {\n const width = Math.min(raw1.width, raw2.width);\n const height = Math.min(raw1.height, raw2.height);\n img1 = cropPng(raw1, width, height);\n img2 = cropPng(raw2, width, height);\n } else {\n const width = Math.max(raw1.width, raw2.width);\n const height = Math.max(raw1.height, raw2.height);\n img1 = padPng(raw1, width, height);\n img2 = padPng(raw2, width, height);\n }\n }\n\n const { width, height } = img1;\n const diff = new PNG({ width, height });\n const diffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold });\n\n mkdirSync(dirname(diffOutputPath), { recursive: true });\n writeFileSync(diffOutputPath, PNG.sync.write(diff));\n\n const totalPixels = width * height;\n const similarity = diffPixels === 0 ? 100 : Math.floor((1 - diffPixels / totalPixels) * 100);\n\n return { similarity, diffPixels, totalPixels, width, height };\n}\n\n// ── Root width expansion (for responsive comparison) ─────────────────────\n\n/**\n * Replace fixed root-element widths in HTML with fluid values so the layout\n * can expand to fill a wider viewport.\n *\n * Targets the first CSS rule that sets a pixel `width` on the root container\n * (commonly `.root`, `body > div`, etc.) and replaces it with `width: 100%`.\n * Also removes `min-width` pixel constraints.\n *\n * Originally from `src/experiments/ablation/run-condition.ts`.\n */\nexport function expandRootWidth(html: string): string {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return html;\n\n const style = styleMatch[0];\n // Find the first CSS rule block (the root element's rule)\n const firstRuleMatch = style.match(/([^{}]*\\{)([^}]*)\\}/);\n if (!firstRuleMatch) return html;\n\n const rulePrefix = firstRuleMatch[1]!; // e.g. \".root {\"\n const ruleBody = firstRuleMatch[2]!; // e.g. \" width: 375px; min-width: 375px; \"\n\n // Replace width and min-width only inside the first rule\n const newBody = ruleBody\n .replace(/(?<![-\\w])width:\\s*\\d+px/, \"width: 100%\")\n .replace(/min-width:\\s*\\d+px/g, \"min-width: 0\");\n\n const newRule = `${rulePrefix}${newBody}}`;\n const newStyle = style.replace(firstRuleMatch[0], newRule);\n return html.replace(style, newStyle);\n}\n\n// ── Code metrics (shared with ablation helpers) ─────────────────────────\n\n/** Count unique CSS class selectors in an HTML string's <style> block. */\nexport function countCssClasses(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const classes = styleMatch[0].match(/\\.[a-zA-Z][\\w-]*\\s*[{,:]/g);\n return new Set(classes?.map((c) => c.replace(/\\s*[{,:]$/, \"\"))).size;\n}\n\n/** Count unique CSS custom property definitions in an HTML string's <style> block. */\nexport function countCssVariables(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const vars = styleMatch[0].match(/--[\\w-]+\\s*:/g);\n return new Set(vars?.map((v) => v.replace(/\\s*:$/, \"\"))).size;\n}\n\n/** Compute code metrics from an HTML string. */\nexport function computeCodeMetrics(html: string): {\n htmlBytes: number;\n htmlLines: number;\n cssClassCount: number;\n cssVariableCount: number;\n} {\n return {\n htmlBytes: Buffer.byteLength(html, \"utf-8\"),\n htmlLines: html.split(\"\\n\").length,\n cssClassCount: countCssClasses(html),\n cssVariableCount: countCssVariables(html),\n };\n}\n","/**\n * Visual comparison: renders HTML code with Playwright, fetches Figma screenshot,\n * and computes pixel-level similarity using pixelmatch.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, existsSync, copyFileSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { PNG } from \"pngjs\";\nimport {\n FIGMA_CACHE_DIR,\n getFigmaCachePath,\n isCacheFresh,\n inferDeviceScaleFactor,\n inferExportScale,\n compareScreenshots,\n expandRootWidth,\n type CompareOptions,\n} from \"./visual-compare-helpers.js\";\n\n/** Result of a visual comparison between Figma design and rendered code. */\nexport interface VisualCompareResult {\n similarity: number;\n diffPixels: number;\n totalPixels: number;\n width: number;\n height: number;\n figmaScreenshotPath: string;\n codeScreenshotPath: string;\n diffPath: string;\n}\n\n/** Options for the visual comparison pipeline. */\nexport interface VisualCompareOptions {\n figmaUrl: string;\n figmaToken: string;\n codePath: string;\n outputDir?: string | undefined;\n /**\n * Logical CSS viewport (CSS pixels). Omit a dimension to infer from the Figma PNG\n * using `figmaExportScale`. When the whole object is omitted, both dimensions are inferred.\n */\n viewport?: { width?: number; height?: number } | undefined;\n /**\n * Figma Images API `scale` and assumed scale for fixture `figma.png` (e.g. from `calibrate-save-fixture`).\n * Default 2 matches REST exports and avoids comparing a @2x PNG against a 1× Playwright capture.\n */\n figmaExportScale?: number | undefined;\n /**\n * Path to a local Figma screenshot file. When provided, skips URL-based fetch\n * and uses this file directly as the ground truth. Useful for responsive comparison\n * where multiple fixture screenshots exist at different viewports.\n */\n figmaScreenshotPath?: string | undefined;\n /**\n * When true, replace the root element's fixed pixel width with `width: 100%`\n * before rendering. This allows the layout to expand to fill the viewport,\n * which is needed for responsive comparison (e.g., 375px design rendered at 768px).\n */\n expandRoot?: boolean | undefined;\n}\n\n/**\n * Fetch Figma node screenshot via REST API, with file-based caching.\n * Cache key: fileKey + nodeId. Cache location: /tmp/canicode-figma-cache/. TTL: 1 hour.\n */\nasync function fetchFigmaScreenshot(\n fileKey: string,\n nodeId: string,\n token: string,\n outputPath: string,\n scale: number,\n): Promise<void> {\n const cachePath = getFigmaCachePath(fileKey, nodeId, scale);\n\n // Return cached version if fresh\n if (isCacheFresh(cachePath)) {\n mkdirSync(dirname(outputPath), { recursive: true });\n copyFileSync(cachePath, outputPath);\n return;\n }\n\n const res = await fetch(\n `https://api.figma.com/v1/images/${fileKey}?ids=${nodeId}&format=png&scale=${scale}`,\n { headers: { \"X-Figma-Token\": token } },\n );\n if (!res.ok) throw new Error(`Figma Images API: ${res.status} ${res.statusText}`);\n\n const data = (await res.json()) as { images: Record<string, string | null> };\n const imgUrl = data.images[nodeId];\n if (!imgUrl) throw new Error(`No image returned for node ${nodeId}`);\n\n const imgRes = await fetch(imgUrl);\n if (!imgRes.ok) throw new Error(`Failed to download Figma screenshot: ${imgRes.status}`);\n\n const buffer = Buffer.from(await imgRes.arrayBuffer());\n\n // Write to output path\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, buffer);\n\n // Save to cache\n mkdirSync(FIGMA_CACHE_DIR, { recursive: true });\n writeFileSync(cachePath, buffer);\n}\n\n/**\n * Render HTML file with Playwright and take a screenshot.\n * @param deviceScaleFactor - Pass 2 when the Figma reference is @2x and `viewport` is logical CSS size.\n */\nexport async function renderCodeScreenshot(\n codePath: string,\n outputPath: string,\n logicalViewport: { width: number; height: number },\n deviceScaleFactor: number = 1,\n): Promise<void> {\n // Dynamic import — playwright is an optional dependency\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch();\n try {\n const context = await browser.newContext({\n viewport: logicalViewport,\n deviceScaleFactor,\n });\n const page = await context.newPage();\n\n await page.goto(`file://${resolve(codePath)}`, {\n waitUntil: \"networkidle\",\n timeout: 30_000,\n });\n await page.waitForTimeout(1000);\n\n // Capture only the first child element (the design root), not the full body/viewport\n const root = page.locator(\"body > *:first-child\");\n if (await root.count() > 0) {\n await root.screenshot({ path: outputPath });\n } else {\n await page.screenshot({ path: outputPath });\n }\n } finally {\n await browser.close();\n }\n}\n\n/**\n * Run full visual comparison pipeline.\n */\nexport async function visualCompare(options: VisualCompareOptions): Promise<VisualCompareResult> {\n const outputDir = options.outputDir ?? \"/tmp/canicode-visual-compare\";\n const figmaScreenshotPath = resolve(outputDir, \"figma.png\");\n const codeScreenshotPath = resolve(outputDir, \"code.png\");\n const diffPath = resolve(outputDir, \"diff.png\");\n\n // Parse Figma URL\n const urlMatch = options.figmaUrl.match(/\\/design\\/([^/]+)\\//);\n const fileKey = urlMatch?.[1];\n if (!fileKey) throw new Error(\"Invalid Figma URL — could not extract file key\");\n\n const nodeIdMatch = options.figmaUrl.match(/node-id=([^&\\s]+)/);\n const nodeId = nodeIdMatch?.[1]?.replace(/-/g, \":\");\n if (!nodeId) throw new Error(\"Invalid Figma URL — missing node-id\");\n\n // Step 1: Figma screenshot — use local file if provided, otherwise fetch via API\n if (options.figmaScreenshotPath) {\n if (!existsSync(options.figmaScreenshotPath)) {\n throw new Error(`Figma screenshot not found: ${options.figmaScreenshotPath}`);\n }\n mkdirSync(dirname(figmaScreenshotPath), { recursive: true });\n copyFileSync(options.figmaScreenshotPath, figmaScreenshotPath);\n } else if (!existsSync(figmaScreenshotPath)) {\n const fetchScale = options.figmaExportScale ?? 2;\n await fetchFigmaScreenshot(fileKey, nodeId, options.figmaToken, figmaScreenshotPath, fetchScale);\n if (!existsSync(figmaScreenshotPath)) {\n throw new Error(`Figma screenshot was not created at expected path: ${figmaScreenshotPath}`);\n }\n }\n\n // Step 2: Logical viewport + deviceScaleFactor so code.png matches figma.png pixels (@2x, etc.)\n const figmaPng = PNG.sync.read(readFileSync(figmaScreenshotPath));\n // Auto-detect export scale from PNG width when using local screenshot (KNOWN_1X_WIDTHS convention)\n const exportScale = options.figmaExportScale ?? inferExportScale(figmaPng.width);\n const hasViewportOverride = options.viewport !== undefined;\n let logicalW: number;\n let logicalH: number;\n let deviceScaleFactor: number;\n\n if (!hasViewportOverride) {\n logicalW = Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH = Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = exportScale;\n } else {\n logicalW =\n options.viewport!.width ?? Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH =\n options.viewport!.height ?? Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = inferDeviceScaleFactor(\n figmaPng.width,\n figmaPng.height,\n logicalW,\n logicalH,\n exportScale,\n );\n }\n\n // Step 3: Render code screenshot at matching physical resolution\n let renderPath = options.codePath;\n if (options.expandRoot) {\n const originalHtml = readFileSync(resolve(options.codePath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderPath = resolve(outputDir, \"code-expanded.html\");\n writeFileSync(renderPath, expandedHtml);\n }\n await renderCodeScreenshot(\n renderPath,\n codeScreenshotPath,\n { width: logicalW, height: logicalH },\n deviceScaleFactor,\n );\n\n // Validate both screenshots exist before comparing\n if (!existsSync(codeScreenshotPath)) {\n throw new Error(`Code screenshot was not created at expected path: ${codeScreenshotPath}`);\n }\n\n // Compare\n const result = compareScreenshots(figmaScreenshotPath, codeScreenshotPath, diffPath);\n\n return {\n ...result,\n figmaScreenshotPath,\n codeScreenshotPath,\n diffPath,\n };\n}\n\n/** Options for renderAndCompare. */\nexport interface RenderAndCompareOptions {\n /** How to handle size mismatches. Default: \"pad\". */\n sizeMismatch?: CompareOptions[\"sizeMismatch\"];\n /** Output file suffix (e.g. \"baseline\", \"stripped-layout\"). */\n suffix?: string;\n /** pixelmatch threshold. Default: 0.1. */\n threshold?: number;\n /** Replace root element's fixed width with 100% before rendering. */\n expandRoot?: boolean;\n}\n\n/**\n * Render HTML → screenshot, then compare against a Figma screenshot.\n * Handles export scale inference and size normalization.\n *\n * Extracted from ablation helpers to be shared by calibration + experiments.\n */\nexport async function renderAndCompare(\n htmlPath: string,\n figmaScreenshotPath: string,\n outputDir: string,\n options?: RenderAndCompareOptions,\n): Promise<{ similarity: number }> {\n const suffix = options?.suffix ?? \"output\";\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold;\n\n const figmaImage = PNG.sync.read(readFileSync(figmaScreenshotPath));\n const figmaWidth = figmaImage.width;\n const exportScale = inferExportScale(figmaWidth);\n const logicalW = Math.max(1, Math.round(figmaWidth / exportScale));\n const logicalH = Math.max(1, Math.round(figmaImage.height / exportScale));\n\n let renderHtmlPath = htmlPath;\n if (options?.expandRoot) {\n const originalHtml = readFileSync(resolve(htmlPath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderHtmlPath = resolve(outputDir, `code-expanded-${suffix}.html`);\n writeFileSync(renderHtmlPath, expandedHtml);\n }\n const codePngPath = resolve(outputDir, `code-${suffix}.png`);\n await renderCodeScreenshot(renderHtmlPath, codePngPath, { width: logicalW, height: logicalH }, exportScale);\n\n const figmaCopyPath = resolve(outputDir, `figma-${suffix}.png`);\n copyFileSync(figmaScreenshotPath, figmaCopyPath);\n\n const diffPath = resolve(outputDir, `diff-${suffix}.png`);\n const compareOpts: CompareOptions = { sizeMismatch };\n if (threshold !== undefined) compareOpts.threshold = threshold;\n return compareScreenshots(figmaCopyPath, codePngPath, diffPath, compareOpts);\n}\n","import { z } from \"zod\";\n\nexport const CategorySchema = z.enum([\n \"pixel-critical\",\n \"responsive-critical\",\n \"code-quality\",\n \"token-management\",\n \"semantic\",\n \"interaction\",\n]);\n\nexport type Category = z.infer<typeof CategorySchema>;\n\nexport const CATEGORIES = CategorySchema.options;\n\nexport const CATEGORY_LABELS: Record<Category, string> = {\n \"pixel-critical\": \"Pixel Critical\",\n \"responsive-critical\": \"Responsive Critical\",\n \"code-quality\": \"Code Quality\",\n \"token-management\": \"Token Management\",\n \"semantic\": \"Semantic\",\n \"interaction\": \"Interaction\",\n};\n","import { z } from \"zod\";\n\nexport const SeveritySchema = z.enum([\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n]);\n\nexport type Severity = z.infer<typeof SeveritySchema>;\n\nexport const SEVERITY_WEIGHT: Record<Severity, number> = {\n blocking: 10,\n risk: 5,\n \"missing-info\": 2,\n suggestion: 1,\n};\n\nexport const SEVERITY_LABELS: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n};\n","import { z } from \"zod\";\nimport type { AnalysisScope } from \"./analysis-scope.js\";\nimport { CategorySchema, type Category } from \"./category.js\";\nimport { SeveritySchema } from \"./severity.js\";\nimport type { AnalysisFile, AnalysisNode } from \"./figma-node.js\";\n\n/**\n * Rule definition - static metadata (does not change)\n */\nexport const RuleDefinitionSchema = z.object({\n id: z.string(),\n name: z.string(),\n category: CategorySchema,\n why: z.string(),\n impact: z.string(),\n fix: z.string(),\n});\n\nexport type RuleDefinition = z.infer<typeof RuleDefinitionSchema>;\n\n/**\n * Rule config - adjustable settings (can be modified via presets)\n */\nexport const RuleConfigSchema = z.object({\n severity: SeveritySchema,\n score: z.number().int().max(0),\n depthWeight: z.number().min(1).max(2).optional(),\n enabled: z.boolean().default(true),\n options: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RuleConfig = z.infer<typeof RuleConfigSchema>;\n\n/**\n * Context passed to rule check functions\n */\nexport interface RuleContext {\n file: AnalysisFile;\n parent?: AnalysisNode | undefined;\n depth: number;\n /** Depth relative to the nearest COMPONENT/INSTANCE ancestor. Resets at component boundaries. */\n componentDepth: number;\n maxDepth: number;\n path: string[];\n /** Ancestor node types from root to parent (excludes current node). */\n ancestorTypes: string[];\n siblings?: AnalysisNode[] | undefined;\n /** Per-analysis shared state. Created fresh for each analysis run, eliminating module-level mutable state. */\n analysisState: Map<string, unknown>;\n /**\n * #404: Scope of the analysis root (`page` vs `component`). Rules use\n * this to decide whether expectations like \"container must define\n * bounds\" or \"repetition should become a component\" apply. Constant for\n * all nodes in a single analysis — whether the CURRENT node happens to\n * be a `COMPONENT` descendant of a page root is already signalled by\n * `componentDepth`, not by re-deriving scope per node.\n */\n scope: AnalysisScope;\n /**\n * #403: Figma node type of the analysis root, captured once in\n * `RuleEngine.analyze`. This is an *axis orthogonal to* `scope`:\n * `scope === \"component\"` does not tell a rule whether the root is a\n * `COMPONENT`/`COMPONENT_SET` (component being audited) or an\n * `INSTANCE` (component being used, possibly with overrides). The\n * `missing-size-constraint` redesign needs that distinction so the\n * gotcha question can ask the right thing — \"intentionally\n * non-responsive?\" vs \"override intended? original may be FILL\". The\n * value is the raw Figma node type string (no new enum) so it stays in\n * sync with `AnalysisNode.type` without a translation layer.\n */\n rootNodeType: string;\n}\n\n/**\n * Get or initialize per-analysis state for a rule.\n * Each key gets its own lazily-initialized state that persists for the duration of one analysis run.\n */\nexport function getAnalysisState<T>(context: RuleContext, key: string, init: () => T): T {\n if (context.analysisState.has(key)) {\n return context.analysisState.get(key) as T;\n }\n const value = init();\n context.analysisState.set(key, value);\n return value;\n}\n\n/**\n * Rule violation result from check function\n */\nexport interface RuleViolation {\n ruleId: string;\n subType?: string;\n nodeId: string;\n nodePath: string;\n message: string;\n suggestion: string;\n guide?: string;\n /**\n * Pre-computed name to write to `node.name` in Figma — populated by naming\n * rules whose suggestion is a deterministic function of the node's existing\n * state (`non-standard-naming`, `inconsistent-naming-convention`).\n * Capitalized for direct Plugin-API use; the human-readable `suggestion`\n * string keeps lowercase prose.\n */\n suggestedName?: string;\n}\n\n/**\n * Rule check function signature\n */\nexport type RuleCheckFn = (\n node: AnalysisNode,\n context: RuleContext,\n options?: Record<string, unknown>\n) => RuleViolation | null;\n\n/**\n * Complete rule with definition, config, and check function\n */\nexport interface Rule {\n definition: RuleDefinition;\n check: RuleCheckFn;\n}\n\n/**\n * Rule ID type for type safety\n */\nexport type RuleId =\n // Pixel Critical — layout issues that directly affect pixel accuracy (ΔV ≥ 5%)\n | \"no-auto-layout\"\n | \"absolute-position-in-auto-layout\"\n | \"non-layout-container\"\n // Responsive Critical — size issues that break at different viewports (ΔV ≥ 15%)\n | \"fixed-size-in-auto-layout\"\n | \"missing-size-constraint\"\n // Code Quality — structural issues affecting code reuse (ΔV ≈ 0%, CSS classes -8~15)\n | \"missing-component\"\n | \"detached-instance\"\n | \"variant-structure-mismatch\"\n | \"deep-nesting\"\n // Token Management — raw values without design tokens\n | \"raw-value\"\n | \"irregular-spacing\"\n // Interaction — missing state variants and prototype links for interactive components\n | \"missing-interaction-state\"\n | \"missing-prototype\"\n // Semantic — naming issues with negligible pixel impact (ΔV < 2%)\n | \"non-standard-naming\"\n | \"non-semantic-name\"\n | \"inconsistent-naming-convention\";\n\n/**\n * Categories that support depthWeight\n */\nexport const DEPTH_WEIGHT_CATEGORIES: Category[] = [\"pixel-critical\", \"responsive-critical\"];\n\n/**\n * Check if a category supports depth weighting\n */\nexport function supportsDepthWeight(category: Category): boolean {\n return DEPTH_WEIGHT_CATEGORIES.includes(category);\n}\n","import type { Category } from \"../contracts/category.js\";\nimport type { RulePurpose } from \"../contracts/channels.js\";\nimport type { RuleConfig, RuleId } from \"../contracts/rule.js\";\nimport type { AnnotationProperty } from \"../roundtrip/types.js\";\n\n/**\n * Maps each rule ID to its category.\n * Categories are based on ablation experiment data (PR #149, #150):\n * - pixel-critical: ΔV ≥ 5% — layout info removal directly degrades pixel accuracy\n * - responsive-critical: ΔV ≥ 15% at expanded viewport — size info critical for responsive\n * - code-quality: ΔV ≈ 0% but CSS classes -8~15 — affects code structure, not pixels\n * - token-management: raw values without design tokens — wrong input = wrong output\n * - semantic: ΔV < 2%, negligible code difference — naming and semantic issues\n */\nexport const RULE_ID_CATEGORY: Record<RuleId, Category> = {\n // Pixel Critical\n \"no-auto-layout\": \"pixel-critical\",\n \"absolute-position-in-auto-layout\": \"pixel-critical\",\n \"non-layout-container\": \"pixel-critical\",\n // Responsive Critical\n \"fixed-size-in-auto-layout\": \"responsive-critical\",\n \"missing-size-constraint\": \"responsive-critical\",\n // Code Quality\n \"missing-component\": \"code-quality\",\n \"detached-instance\": \"code-quality\",\n \"variant-structure-mismatch\": \"code-quality\",\n \"deep-nesting\": \"code-quality\",\n // Token Management\n \"raw-value\": \"token-management\",\n \"irregular-spacing\": \"token-management\",\n // Interaction\n \"missing-interaction-state\": \"interaction\",\n \"missing-prototype\": \"interaction\",\n // Semantic\n \"non-standard-naming\": \"semantic\",\n \"non-semantic-name\": \"semantic\",\n \"inconsistent-naming-convention\": \"semantic\",\n};\n\n/**\n * #406: Classifies each rule by primary output channel.\n *\n * - `violation` (default): score-primary. Rule fires when a best-practice\n * expectation is broken; the score penalty is the main signal, gotcha\n * questions are secondary context on how to resolve the violation.\n * - `info-collection`: annotation-primary. Rule fires on nodes that need\n * implementation context Figma cannot encode natively (click target,\n * state variants). The gotcha annotation IS the output; score impact is\n * kept minimal (-1 range) so presence/absence of the annotation — not\n * the penalty — differentiates designs.\n *\n * Sibling map (mirrors `RULE_ID_CATEGORY`) so existing `RuleDefinition`\n * call sites don't need to be touched. Look up via `getRulePurpose`.\n */\nexport const RULE_PURPOSE: Record<RuleId, RulePurpose> = {\n // Pixel Critical\n \"no-auto-layout\": \"violation\",\n \"absolute-position-in-auto-layout\": \"violation\",\n \"non-layout-container\": \"violation\",\n // Responsive Critical\n \"fixed-size-in-auto-layout\": \"violation\",\n // #403: missing-size-constraint reframed as info-collection. The rule\n // fires on width chains whose intent is structurally undecidable\n // (FILL container with no chain-bound ancestor; FIXED component or\n // instance root). The gotcha question is the primary signal; the\n // -1 score is just enough to keep the rule visible in\n // diversity scoring without driving grade swings on its own.\n \"missing-size-constraint\": \"info-collection\",\n // Code Quality\n \"missing-component\": \"violation\",\n \"detached-instance\": \"violation\",\n \"variant-structure-mismatch\": \"violation\",\n \"deep-nesting\": \"violation\",\n // Token Management\n \"raw-value\": \"violation\",\n \"irregular-spacing\": \"violation\",\n // Interaction — gotcha-primary: Figma cannot encode \"what happens on\n // click\" or \"which states exist\" in a way downstream code generation can\n // consume. Rules fire to trigger the annotation, not to flag a violation.\n \"missing-interaction-state\": \"info-collection\",\n \"missing-prototype\": \"info-collection\",\n // Semantic\n \"non-standard-naming\": \"violation\",\n \"non-semantic-name\": \"violation\",\n \"inconsistent-naming-convention\": \"violation\",\n};\n\n/**\n * Resolve a rule's purpose. Accepts `string` (not `RuleId`) because the\n * purpose concept must work for out-of-tree custom rules added via the\n * config loader — callers pass `issue.violation.ruleId` which is a plain\n * string. Defaults to `\"violation\"` for unknown ids. Keeping the cast\n * inside this helper (rather than forcing every caller to do `as RuleId`)\n * makes the fallback semantically honest.\n */\nexport function getRulePurpose(ruleId: string): RulePurpose {\n return RULE_PURPOSE[ruleId as RuleId] ?? \"violation\";\n}\n\n/**\n * Central configuration for all rules.\n * Scores based on ablation experiment + AI implementation interview (#200):\n * - pixel-critical: -10 ~ -7 (layout strip caused ΔV +5.4%)\n * - responsive-critical: -8 ~ -6 (size-constraints ΔV +15.9% at responsive viewports)\n * - code-quality: -7 ~ -3 (CSS classes -8~15, no pixel impact)\n * - token-management: -5 ~ -4 (wrong input = wrong output, irregular spacing actively causes errors)\n * - interaction: -1 (uncalibrated — no metric to validate, kept minimal #210)\n * - semantic: -4 ~ -1 (non-semantic-name upgraded per interview — causes actual implementation errors)\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n */\nexport const RULE_CONFIGS: Record<RuleId, RuleConfig> = {\n // ── Pixel Critical ──\n \"no-auto-layout\": {\n severity: \"blocking\",\n score: -10,\n depthWeight: 1.5,\n enabled: true,\n },\n \"absolute-position-in-auto-layout\": {\n severity: \"blocking\",\n score: -7,\n depthWeight: 1.3,\n enabled: true,\n },\n \"non-layout-container\": {\n severity: \"blocking\",\n score: -8,\n depthWeight: 1.2,\n enabled: true,\n },\n\n // ── Responsive Critical ──\n \"fixed-size-in-auto-layout\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"missing-size-constraint\": {\n // #403: severity downgraded `risk → missing-info` and score from\n // -8 → -1 to match the new info-collection purpose. Keeping the\n // rule enabled (not disabled) so its gotchas still surface in the\n // survey — see RULE_PURPOSE entry above for the full rationale.\n severity: \"missing-info\",\n score: -1,\n enabled: true,\n },\n\n // ── Code Quality ──\n \"missing-component\": {\n severity: \"risk\",\n score: -7,\n enabled: true,\n options: {\n minRepetitions: 2,\n structureMinRepetitions: 2,\n maxFingerprintDepth: 3,\n },\n },\n \"detached-instance\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"variant-structure-mismatch\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"deep-nesting\": {\n severity: \"risk\",\n score: -3,\n enabled: true,\n options: {\n maxDepth: 5,\n },\n },\n\n // ── Token Management ──\n \"raw-value\": {\n severity: \"missing-info\",\n score: -4,\n enabled: true,\n },\n \"irregular-spacing\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n options: {\n gridBase: 2,\n },\n },\n\n // ── Interaction ──\n // #406: both rules are `info-collection` — primary output is the gotcha\n // annotation, not the score. Severity is `missing-info` so they surface in\n // the gotcha survey (see `generateGotchaSurvey`) even though the penalty\n // is minimal. Score stays at -1 so re-enabling `missing-prototype` on\n // fixtures that lack `interactionDestinations` (#139) cannot swing grades.\n \"missing-interaction-state\": {\n severity: \"missing-info\",\n score: -1, // uncalibrated: no metric to validate score (#210), kept at -1 to preserve category visibility\n enabled: true,\n },\n \"missing-prototype\": {\n severity: \"missing-info\",\n score: -1, // #406: info-collection — annotation is primary output; score kept minimal so #139 fixtures don't skew calibration\n enabled: true,\n },\n\n // ── Semantic ──\n \"non-standard-naming\": {\n severity: \"suggestion\",\n score: -3, // higher than other naming rules: non-standard state names break interaction detection pipeline\n enabled: true,\n },\n \"non-semantic-name\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"inconsistent-naming-convention\": {\n severity: \"suggestion\",\n score: -1,\n enabled: true,\n },\n};\n\n/**\n * Preset types for different analysis modes\n */\nexport type Preset = \"relaxed\" | \"dev-friendly\" | \"ai-ready\" | \"strict\";\n\n/**\n * Get rule configs with preset applied\n */\nexport function getConfigsWithPreset(\n preset: Preset\n): Record<RuleId, RuleConfig> {\n const configs = { ...RULE_CONFIGS };\n\n switch (preset) {\n case \"relaxed\":\n // Disable blocking rules, reduce scores\n for (const [id, config] of Object.entries(configs)) {\n if (config.severity === \"blocking\") {\n configs[id as RuleId] = {\n ...config,\n severity: \"risk\",\n score: Math.round(config.score * 0.5),\n };\n }\n }\n break;\n\n case \"dev-friendly\":\n // Focus on pixel-critical and responsive-critical issues\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category !== \"pixel-critical\" && category !== \"responsive-critical\") {\n configs[ruleId] = { ...config, enabled: false };\n }\n }\n break;\n\n case \"ai-ready\":\n // Boost pixel-critical and token-management rules\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category === \"pixel-critical\" || category === \"token-management\") {\n configs[ruleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n }\n break;\n\n case \"strict\":\n // Increase scores but respect disabled rules\n for (const [id, config] of Object.entries(configs)) {\n configs[id as RuleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n break;\n }\n\n return configs;\n}\n\n/**\n * Per-rule annotation `properties` hints surfaced in Dev Mode. Kept as a\n * sibling map rather than a field on `RuleConfig` so the existing\n * `RuleConfigSchema` Zod contract and preset helpers stay untouched.\n *\n * `bySubType` takes precedence over `default` — mirrors the ruleId+subType\n * resolution pattern already used for `targetProperty` in apply-context.ts.\n * The Experiment 09 node-type matrix is enforced at write time by\n * `upsertCanicodeAnnotation`'s retry path, so hints can be passed\n * speculatively without server-side filtering.\n */\nexport const RULE_ANNOTATION_PROPERTIES: Partial<\n Record<\n RuleId,\n {\n default?: AnnotationProperty[];\n bySubType?: Record<string, AnnotationProperty[]>;\n }\n >\n> = {\n \"missing-size-constraint\": {\n // #403: width-only — the redesigned rule does not evaluate the\n // height axis (deferred follow-up). Emitting a `height` annotation\n // here would mark properties the rule never inspected and confuse\n // downstream Dev Mode hints.\n default: [{ type: \"width\" }],\n },\n \"irregular-spacing\": {\n bySubType: {\n gap: [{ type: \"itemSpacing\" }],\n padding: [{ type: \"padding\" }],\n },\n },\n \"fixed-size-in-auto-layout\": {\n default: [{ type: \"width\" }, { type: \"height\" }, { type: \"layoutMode\" }],\n },\n \"raw-value\": {\n bySubType: {\n color: [{ type: \"fills\" }],\n font: [\n { type: \"fontSize\" },\n { type: \"fontFamily\" },\n { type: \"fontWeight\" },\n { type: \"lineHeight\" },\n ],\n spacing: [{ type: \"itemSpacing\" }, { type: \"padding\" }],\n },\n },\n \"absolute-position-in-auto-layout\": {\n default: [{ type: \"layoutMode\" }],\n },\n};\n\n/**\n * Resolve the annotation `properties` hint for a ruleId (+ subType).\n * Returns `undefined` for rules with no entry.\n */\nexport function getAnnotationProperties(\n ruleId: RuleId,\n subType?: string\n): AnnotationProperty[] | undefined {\n const entry = RULE_ANNOTATION_PROPERTIES[ruleId];\n if (!entry) return undefined;\n if (subType !== undefined && entry.bySubType) {\n const match = entry.bySubType[subType];\n if (match) return match;\n }\n return entry.default;\n}\n\n/**\n * Get option value for a rule with type safety\n */\nexport function getRuleOption<T>(\n ruleId: RuleId,\n optionKey: string,\n defaultValue: T\n): T {\n const config = RULE_CONFIGS[ruleId];\n if (!config.options) return defaultValue;\n const value = config.options[optionKey];\n return (value as T) ?? defaultValue;\n}\n","import type { Rule, RuleConfig, RuleId } from \"../contracts/rule.js\";\nimport type { Category } from \"../contracts/category.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\n/**\n * Registry for all rules\n */\nclass RuleRegistry {\n private rules: Map<RuleId, Rule> = new Map();\n\n /**\n * Register a rule\n */\n register(rule: Rule): void {\n this.rules.set(rule.definition.id as RuleId, rule);\n }\n\n /**\n * Remove a rule by ID. Primarily used by tests that register a\n * throwaway rule and need to restore the registry afterwards. Returns\n * `true` if the rule was present.\n */\n unregister(id: RuleId): boolean {\n return this.rules.delete(id);\n }\n\n /**\n * Get a rule by ID\n */\n get(id: RuleId): Rule | undefined {\n return this.rules.get(id);\n }\n\n /**\n * Get all registered rules\n */\n getAll(): Rule[] {\n return Array.from(this.rules.values());\n }\n\n /**\n * Get rules by category\n */\n getByCategory(category: Category): Rule[] {\n return this.getAll().filter((rule) => rule.definition.category === category);\n }\n\n /**\n * Get enabled rules with their configs\n */\n getEnabled(configs: Record<RuleId, RuleConfig> = RULE_CONFIGS): Rule[] {\n return this.getAll().filter((rule) => {\n const config = configs[rule.definition.id as RuleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Get config for a rule\n */\n getConfig(\n id: RuleId,\n configs: Record<RuleId, RuleConfig> = RULE_CONFIGS\n ): RuleConfig {\n return configs[id];\n }\n\n /**\n * Check if a rule is registered\n */\n has(id: RuleId): boolean {\n return this.rules.has(id);\n }\n\n /**\n * Get count of registered rules\n */\n get size(): number {\n return this.rules.size;\n }\n}\n\n/**\n * Global rule registry instance\n */\nexport const ruleRegistry = new RuleRegistry();\n\n/**\n * Helper to create and register a rule\n */\nexport function defineRule(rule: Rule): Rule {\n ruleRegistry.register(rule);\n return rule;\n}\n","import { z } from \"zod\";\n\n/**\n * Acknowledgment marker — surfaced from a Figma Dev Mode annotation that\n * canicode itself wrote during a roundtrip. When the analysis pipeline\n * receives a list of acknowledgments, matching `(nodeId, ruleId)` issues are\n * flagged `acknowledged: true` and contribute half their normal weight to\n * the density score (#371).\n *\n * This contract is consumed by:\n * - The MCP `analyze` tool (`acknowledgments?: Acknowledgment[]` input)\n * - The CLI `analyze --acknowledgments <path>` flag\n * - `RuleEngineOptions.acknowledgments`\n *\n * It is produced by the Plugin-API helper\n * `extractAcknowledgmentsFromNode` / `readCanicodeAcknowledgments`\n * (see `src/core/roundtrip/read-acknowledgments.ts`).\n *\n * ADR-019 / #444: optional `intent`, `sceneWriteOutcome`, and `codegenDirective`\n * are read from a fenced canicode-json block when present; legacy annotations\n * omit them and remain valid for density scoring.\n */\nexport const AcknowledgmentIntentSchema = z.object({\n field: z.string(),\n value: z.unknown(),\n scope: z.enum([\"instance\", \"definition\"]),\n});\n\nexport type AcknowledgmentIntent = z.infer<typeof AcknowledgmentIntentSchema>;\n\nexport const AcknowledgmentSceneWriteOutcomeSchema = z.object({\n result: z.enum([\n \"succeeded\",\n \"silent-ignored\",\n \"api-rejected\",\n \"user-declined-propagation\",\n \"unknown\",\n ]),\n reason: z.string().optional(),\n});\n\nexport type AcknowledgmentSceneWriteOutcome = z.infer<\n typeof AcknowledgmentSceneWriteOutcomeSchema\n>;\n\nexport const AcknowledgmentSchema = z.object({\n nodeId: z.string(),\n ruleId: z.string(),\n intent: AcknowledgmentIntentSchema.optional(),\n sceneWriteOutcome: AcknowledgmentSceneWriteOutcomeSchema.optional(),\n codegenDirective: z.string().optional(),\n});\n\nexport type Acknowledgment = z.infer<typeof AcknowledgmentSchema>;\n\nexport const AcknowledgmentListSchema = z.array(AcknowledgmentSchema);\n\n/**\n * Normalize a Figma node id into `:`-separated form so callers can pass\n * either URL-style (`123-456`) or Plugin-API-style (`123:456`) ids and the\n * engine matches them consistently. Non-instance ids stay unchanged; the\n * `I…;…` instance-child format keeps its semicolon — only `-` → `:`\n * happens.\n */\nexport function normalizeNodeId(id: string): string {\n return id.replace(/-/g, \":\");\n}\n","import { z } from \"zod\";\nimport type { AnalysisNode } from \"./figma-node.js\";\n\n/**\n * #404: Analysis scope — what the user is asking canicode to reason about.\n *\n * - `page`: full screen / section / layout. Container frames are\n * responsible for bounds; repetition detection is meaningful; rules\n * that assume \"this is a self-contained screen\" apply.\n * - `component`: standalone reusable UI unit (COMPONENT / COMPONENT_SET\n * / INSTANCE analyzed in isolation). Root FILL is the design contract\n * rather than a missing bound; repetition detection is generally a\n * false signal because a component is itself the unit of reuse.\n *\n * The enum is intentionally two-valued; multi-scope analysis (analyzing\n * a page and its inner components in one run) is explicitly out of scope\n * per the issue. Each rule decides how (or whether) to switch on `scope`;\n * this PR only carries the context. Rule-level consumption lands in\n * follow-up PRs (e.g. #403 for `missing-size-constraint`).\n */\nexport const AnalysisScopeSchema = z.enum([\"page\", \"component\"]);\nexport type AnalysisScope = z.infer<typeof AnalysisScopeSchema>;\n\n/**\n * Figma node types that unambiguously indicate a component-scope analysis\n * when they appear as the analysis **root**.\n *\n * - `COMPONENT` / `COMPONENT_SET`: the design unit IS the component.\n * - `INSTANCE`: the root is a reusable unit's placement; treating it as\n * component scope keeps rules like `missing-size-constraint` from\n * demanding bounds on a node whose bounds are the container's job.\n *\n * Any other root type (`FRAME`, `SECTION`, `CANVAS`, `DOCUMENT`, `GROUP`,\n * etc.) resolves to page scope — the common case for analyzing a screen\n * or page section via `?node-id=...`.\n */\nconst COMPONENT_SCOPE_ROOT_TYPES = new Set([\"COMPONENT\", \"COMPONENT_SET\", \"INSTANCE\"]);\n\n/**\n * Deterministically detect analysis scope from the root node type. Returns\n * `\"component\"` for `COMPONENT` / `COMPONENT_SET` / `INSTANCE` roots, and\n * `\"page\"` for everything else.\n *\n * The CLI / MCP layer may override this with an explicit `scope` flag when\n * the user knows the heuristic mis-detects (e.g. analyzing a FRAME that\n * ships as a standalone design-system example rather than a screen).\n */\nexport function detectAnalysisScope(rootNode: AnalysisNode): AnalysisScope {\n return COMPONENT_SCOPE_ROOT_TYPES.has(rootNode.type) ? \"component\" : \"page\";\n}\n","import type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport type {\n Rule,\n RuleConfig,\n RuleContext,\n RuleId,\n RuleViolation,\n} from \"../contracts/rule.js\";\nimport { supportsDepthWeight } from \"../contracts/rule.js\";\nimport { ruleRegistry } from \"../rules/rule-registry.js\";\nimport { RULE_CONFIGS } from \"../rules/rule-config.js\";\nimport {\n normalizeNodeId,\n type Acknowledgment,\n} from \"../contracts/acknowledgment.js\";\nimport {\n detectAnalysisScope,\n type AnalysisScope,\n} from \"../contracts/analysis-scope.js\";\n\n/**\n * Analysis issue with calculated score and metadata.\n *\n * `acknowledged` (#371) — set when the analysis engine receives an\n * `acknowledgments` list (typically read from canicode-authored Figma\n * annotations) whose `(nodeId, ruleId)` matches this issue. Acknowledged\n * issues still surface in the result (so code-gen retains the context) but\n * contribute half their normal weight to the density score, so the grade\n * reflects \"the designer has a plan for this\" instead of treating the rule\n * as fully unaddressed.\n */\nexport interface AnalysisIssue {\n violation: RuleViolation;\n rule: Rule;\n config: RuleConfig;\n depth: number;\n maxDepth: number;\n calculatedScore: number;\n acknowledged?: boolean;\n}\n\n/**\n * Information about a rule that threw during analysis\n */\nexport interface RuleFailure {\n ruleId: string;\n nodeName: string;\n nodeId: string;\n error: string;\n}\n\n/**\n * Analysis result from the rule engine\n */\nexport interface AnalysisResult {\n file: AnalysisFile;\n issues: AnalysisIssue[];\n failedRules: RuleFailure[];\n maxDepth: number;\n nodeCount: number;\n analyzedAt: string;\n /**\n * #404: Resolved analysis scope (`page` vs `component`). Either detected\n * from the root node type or taken from the caller's explicit override.\n * Propagated to MCP / JSON output so downstream consumers (code-gen,\n * reports) can branch the same way rules do.\n */\n scope: AnalysisScope;\n}\n\n/**\n * Options for the rule engine\n */\nexport interface RuleEngineOptions {\n configs?: Record<RuleId, RuleConfig>;\n enabledRules?: RuleId[];\n disabledRules?: RuleId[];\n targetNodeId?: string;\n excludeNodeNames?: string[];\n excludeNodeTypes?: string[];\n /**\n * `(nodeId, ruleId)` pairs sourced from canicode-authored Figma annotations\n * (#371). Issues whose violation matches an entry are flagged\n * `acknowledged: true` and contribute half their normal weight to the\n * density score in `calculateScores`. nodeId may be passed in URL form\n * (`123-456`) or Plugin-API form (`123:456`) — both normalize to `:`.\n */\n acknowledgments?: Acknowledgment[];\n /**\n * #404: Explicit scope override. When omitted, the engine auto-detects\n * from the analysis root's node type via `detectAnalysisScope`. Supply\n * this when the caller knows the heuristic would mis-detect — e.g. a\n * FRAME that happens to be a design-system demo (component scope) or a\n * COMPONENT_SET being audited as part of a full page inventory (page\n * scope).\n */\n scope?: AnalysisScope;\n}\n\n/**\n * Calculate the maximum depth of a node tree\n */\nfunction calculateMaxDepth(node: AnalysisNode, currentDepth = 0): number {\n if (!node.children || node.children.length === 0) {\n return currentDepth;\n }\n\n let maxChildDepth = currentDepth;\n for (const child of node.children) {\n const childDepth = calculateMaxDepth(child, currentDepth + 1);\n if (childDepth > maxChildDepth) {\n maxChildDepth = childDepth;\n }\n }\n\n return maxChildDepth;\n}\n\n/**\n * Count total nodes in a tree\n */\nfunction countNodes(node: AnalysisNode): number {\n let count = 1;\n if (node.children) {\n for (const child of node.children) {\n count += countNodes(child);\n }\n }\n return count;\n}\n\n/**\n * Find a node by ID in the tree\n */\nfunction findNodeById(node: AnalysisNode, nodeId: string): AnalysisNode | null {\n // Figma node IDs use \":\" separator, URL uses \"-\"\n const normalizedId = nodeId.replace(/-/g, \":\");\n\n if (node.id === normalizedId) {\n return node;\n }\n\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, nodeId);\n if (found) return found;\n }\n }\n\n return null;\n}\n\n/**\n * Calculate depth weight multiplier for a rule\n * Higher values (closer to 1.5x) at root level, 1.0x at leaf level\n */\nfunction calcDepthWeight(\n depth: number,\n maxDepth: number,\n depthWeight?: number\n): number {\n if (!depthWeight || depthWeight <= 1) return 1;\n if (maxDepth === 0) return depthWeight;\n\n // Linear interpolation: depthWeight at depth 0, 1.0 at maxDepth\n const ratio = depth / maxDepth;\n return depthWeight - (depthWeight - 1) * ratio;\n}\n\n/**\n * Rule engine for analyzing Figma files\n */\nexport class RuleEngine {\n private configs: Record<RuleId, RuleConfig>;\n private enabledRuleIds: Set<RuleId> | null;\n private disabledRuleIds: Set<RuleId>;\n private targetNodeId: string | undefined;\n private excludeNamePattern: RegExp | null;\n private excludeNodeTypes: Set<string> | null;\n private acknowledgments: ReadonlySet<string>;\n private scopeOverride: AnalysisScope | undefined;\n\n constructor(options: RuleEngineOptions = {}) {\n this.configs = options.configs ?? RULE_CONFIGS;\n this.enabledRuleIds = options.enabledRules\n ? new Set(options.enabledRules)\n : null;\n this.disabledRuleIds = new Set(options.disabledRules ?? []);\n this.targetNodeId = options.targetNodeId;\n this.excludeNamePattern = options.excludeNodeNames && options.excludeNodeNames.length > 0\n ? new RegExp(`\\\\b(${options.excludeNodeNames.join(\"|\")})\\\\b`, \"i\")\n : null;\n this.excludeNodeTypes = options.excludeNodeTypes && options.excludeNodeTypes.length > 0\n ? new Set(options.excludeNodeTypes)\n : null;\n this.acknowledgments = new Set(\n (options.acknowledgments ?? []).map(\n (a) => `${normalizeNodeId(a.nodeId)}::${a.ruleId}`\n )\n );\n this.scopeOverride = options.scope;\n }\n\n /**\n * Analyze a Figma file and return issues\n */\n analyze(file: AnalysisFile): AnalysisResult {\n // Fresh per-analysis state — eliminates module-level mutable state in rules\n const analysisState = new Map<string, unknown>();\n\n // Find target node if specified\n let rootNode = file.document;\n if (this.targetNodeId) {\n const targetNode = findNodeById(file.document, this.targetNodeId);\n if (!targetNode) {\n throw new Error(`Node not found: ${this.targetNodeId}`);\n }\n rootNode = targetNode;\n }\n\n // Calculate max depth before analysis\n const maxDepth = calculateMaxDepth(rootNode);\n const nodeCount = countNodes(rootNode);\n\n // #404: resolve scope once per analysis. Caller override wins over\n // type-based detection so CLI/MCP users can correct false positives\n // (e.g. design-system demo frames classified as page scope).\n const scope: AnalysisScope =\n this.scopeOverride ?? detectAnalysisScope(rootNode);\n\n // #403: capture root node type as a separate axis from `scope`. Rules\n // that branch on whether a component-scope root is the component\n // itself vs an INSTANCE of one need this even when `scope` already\n // resolves to \"component\". Captured once here, threaded read-only\n // through every `RuleContext` in this analysis.\n const rootNodeType = rootNode.type;\n\n const issues: AnalysisIssue[] = [];\n const failedRules: RuleFailure[] = [];\n const enabledRules = this.getEnabledRules();\n\n // Traverse the tree and run rules on each node\n this.traverseAndCheck(\n rootNode,\n file,\n enabledRules,\n maxDepth,\n issues,\n failedRules,\n 0,\n [],\n [],\n 0,\n analysisState,\n scope,\n rootNodeType,\n undefined,\n undefined\n );\n\n if (this.acknowledgments.size > 0) {\n for (const issue of issues) {\n const key = `${normalizeNodeId(issue.violation.nodeId)}::${issue.violation.ruleId}`;\n if (this.acknowledgments.has(key)) {\n issue.acknowledged = true;\n }\n }\n }\n\n return {\n file,\n issues,\n failedRules,\n maxDepth,\n nodeCount,\n analyzedAt: new Date().toISOString(),\n scope,\n };\n }\n\n /**\n * Get rules that should be run based on configuration\n */\n private getEnabledRules(): Rule[] {\n return ruleRegistry.getAll().filter((rule) => {\n const ruleId = rule.definition.id as RuleId;\n\n // Check if explicitly disabled\n if (this.disabledRuleIds.has(ruleId)) return false;\n\n // Check if we have an explicit enable list\n if (this.enabledRuleIds && !this.enabledRuleIds.has(ruleId)) return false;\n\n // Check config enabled status\n const config = this.configs[ruleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Recursively traverse the tree and run rules\n */\n private traverseAndCheck(\n node: AnalysisNode,\n file: AnalysisFile,\n rules: Rule[],\n maxDepth: number,\n issues: AnalysisIssue[],\n failedRules: RuleFailure[],\n depth: number,\n path: string[],\n ancestorTypes: string[],\n componentDepth: number,\n analysisState: Map<string, unknown>,\n scope: AnalysisScope,\n rootNodeType: string,\n parent?: AnalysisNode,\n siblings?: AnalysisNode[]\n ): void {\n const nodePath = [...path, node.name];\n\n // Reset componentDepth at component boundaries\n const isComponentBoundary = node.type === \"COMPONENT\" || node.type === \"COMPONENT_SET\" || node.type === \"INSTANCE\";\n const currentComponentDepth = isComponentBoundary ? 0 : componentDepth;\n\n // Skip nodes matching excluded types or name patterns\n if (this.excludeNodeTypes && this.excludeNodeTypes.has(node.type)) {\n return;\n }\n if (this.excludeNamePattern && this.excludeNamePattern.test(node.name)) {\n return;\n }\n\n // Build context for this node\n const context: RuleContext = {\n file,\n parent,\n depth,\n componentDepth: currentComponentDepth,\n maxDepth,\n path: nodePath,\n ancestorTypes,\n siblings,\n analysisState,\n scope,\n rootNodeType,\n };\n\n // Run each rule on this node\n for (const rule of rules) {\n const ruleId = rule.definition.id as RuleId;\n const config = this.configs[ruleId];\n const options = config?.options;\n\n try {\n const violation = rule.check(node, context, options);\n\n if (violation) {\n // Calculate score with depth weight if applicable\n let calculatedScore = config.score;\n\n if (\n supportsDepthWeight(rule.definition.category) &&\n config.depthWeight\n ) {\n const weight = calcDepthWeight(depth, maxDepth, config.depthWeight);\n calculatedScore = Math.round(config.score * weight);\n }\n\n issues.push({\n violation,\n rule,\n config,\n depth,\n maxDepth,\n calculatedScore,\n });\n }\n } catch (error) {\n // Track failure and continue — never let one rule break the whole analysis\n failedRules.push({\n ruleId,\n nodeName: node.name,\n nodeId: node.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Recurse into children\n if (node.children && node.children.length > 0) {\n const childAncestorTypes = [...ancestorTypes, node.type];\n for (const child of node.children) {\n this.traverseAndCheck(\n child,\n file,\n rules,\n maxDepth,\n issues,\n failedRules,\n depth + 1,\n nodePath,\n childAncestorTypes,\n currentComponentDepth + 1,\n analysisState,\n scope,\n rootNodeType,\n node,\n node.children\n );\n }\n }\n }\n}\n\n/**\n * Create a rule engine with default configuration\n */\nexport function createRuleEngine(options?: RuleEngineOptions): RuleEngine {\n return new RuleEngine(options);\n}\n\n/**\n * Convenience function to analyze a file with default settings\n */\nexport function analyzeFile(\n file: AnalysisFile,\n options?: RuleEngineOptions\n): AnalysisResult {\n const engine = createRuleEngine(options);\n return engine.analyze(file);\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\n\nconst FIGMA_API_BASE = \"https://api.figma.com/v1\";\n\nexport interface GetFileNodesResponse {\n name: string;\n lastModified: string;\n version: string;\n nodes: Record<string, {\n document: Node;\n components: GetFileResponse[\"components\"];\n styles: GetFileResponse[\"styles\"];\n }>;\n}\n\nexport interface FigmaClientOptions {\n token: string;\n}\n\nexport class FigmaClient {\n private token: string;\n\n constructor(options: FigmaClientOptions) {\n this.token = options.token;\n }\n\n static fromEnv(): FigmaClient {\n const token = process.env[\"FIGMA_TOKEN\"];\n if (!token) {\n throw new FigmaClientError(\n \"FIGMA_TOKEN environment variable is not set\"\n );\n }\n return new FigmaClient({ token });\n }\n\n async getFile(fileKey: string): Promise<GetFileResponse> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch file: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileResponse>;\n }\n\n /**\n * Get rendered images for specific nodes\n * Returns a map of nodeId → image URL\n */\n async getNodeImages(\n fileKey: string,\n nodeIds: string[],\n options?: { format?: \"png\" | \"svg\" | \"jpg\"; scale?: number }\n ): Promise<Record<string, string | null>> {\n const format = options?.format ?? \"png\";\n const scale = options?.scale ?? 2;\n\n // Batch into chunks to avoid 414 URI Too Large\n const BATCH_SIZE = 50;\n const allImages: Record<string, string | null> = {};\n\n for (let i = 0; i < nodeIds.length; i += BATCH_SIZE) {\n const batch = nodeIds.slice(i, i + BATCH_SIZE);\n const ids = batch.join(\",\");\n const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodeURIComponent(ids)}&format=${format}&scale=${scale}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch images: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n const data = await response.json() as { images: Record<string, string | null> };\n for (const [nodeId, imageUrl] of Object.entries(data.images)) {\n allImages[nodeId] = imageUrl;\n }\n }\n\n return allImages;\n }\n\n /**\n * Get original image fill URLs by imageRef.\n * Returns a mapping of imageRef → download URL for all image fills in the file.\n */\n async getImageFills(fileKey: string): Promise<Record<string, string>> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}/images`;\n const response = await fetch(url, {\n headers: { \"X-Figma-Token\": this.token },\n });\n if (!response.ok) {\n const error = await response.text().catch(() => \"\");\n throw new FigmaClientError(\n `Failed to fetch image fills: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n const data = await response.json() as { meta?: { images?: Record<string, string> } };\n return data.meta?.images ?? {};\n }\n\n /**\n * Download an image URL and return as base64\n */\n async fetchImageAsBase64(imageUrl: string): Promise<string> {\n const response = await fetch(imageUrl);\n if (!response.ok) {\n throw new FigmaClientError(\n `Failed to download image: ${response.status}`,\n response.status\n );\n }\n const buffer = await response.arrayBuffer();\n return Buffer.from(buffer).toString(\"base64\");\n }\n\n async getFileNodes(\n fileKey: string,\n nodeIds: string[]\n ): Promise<GetFileNodesResponse> {\n const ids = nodeIds.join(\",\");\n const url = `${FIGMA_API_BASE}/files/${fileKey}/nodes?ids=${encodeURIComponent(ids)}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch nodes: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileNodesResponse>;\n }\n}\n\nexport class FigmaClientError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public responseBody?: unknown\n ) {\n super(message);\n this.name = \"FigmaClientError\";\n }\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\nimport type { GetFileNodesResponse } from \"./figma-client.js\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\n\n/**\n * Transform Figma API response to analysis types\n */\nexport function transformFigmaResponse(\n fileKey: string,\n response: GetFileResponse\n): AnalysisFile {\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(response.document),\n components: transformComponents(response.components),\n styles: transformStyles(response.styles),\n };\n}\n\nfunction transformNode(node: Node): AnalysisNode {\n const base: AnalysisNode = {\n id: node.id,\n name: node.name,\n type: node.type as AnalysisNode[\"type\"],\n visible: \"visible\" in node ? (node.visible ?? true) : true,\n };\n\n // Layout properties\n if (\"layoutMode\" in node && node.layoutMode) {\n base.layoutMode = node.layoutMode as AnalysisNode[\"layoutMode\"];\n }\n if (\"layoutAlign\" in node && node.layoutAlign) {\n base.layoutAlign = node.layoutAlign as AnalysisNode[\"layoutAlign\"];\n }\n if (\"layoutPositioning\" in node && node.layoutPositioning) {\n base.layoutPositioning =\n node.layoutPositioning as AnalysisNode[\"layoutPositioning\"];\n }\n if (\"layoutSizingHorizontal\" in node && node.layoutSizingHorizontal) {\n base.layoutSizingHorizontal =\n node.layoutSizingHorizontal as AnalysisNode[\"layoutSizingHorizontal\"];\n }\n if (\"layoutSizingVertical\" in node && node.layoutSizingVertical) {\n base.layoutSizingVertical =\n node.layoutSizingVertical as AnalysisNode[\"layoutSizingVertical\"];\n }\n if (\"primaryAxisAlignItems\" in node) {\n base.primaryAxisAlignItems = node.primaryAxisAlignItems as string;\n }\n if (\"counterAxisAlignItems\" in node) {\n base.counterAxisAlignItems = node.counterAxisAlignItems as string;\n }\n if (\"itemSpacing\" in node) {\n base.itemSpacing = node.itemSpacing as number;\n }\n if (\"paddingLeft\" in node) {\n base.paddingLeft = node.paddingLeft as number;\n }\n if (\"paddingRight\" in node) {\n base.paddingRight = node.paddingRight as number;\n }\n if (\"paddingTop\" in node) {\n base.paddingTop = node.paddingTop as number;\n }\n if (\"paddingBottom\" in node) {\n base.paddingBottom = node.paddingBottom as number;\n }\n\n // Size constraints (responsive)\n if (\"minWidth\" in node && typeof node.minWidth === \"number\") {\n base.minWidth = node.minWidth;\n }\n if (\"maxWidth\" in node && typeof node.maxWidth === \"number\") {\n base.maxWidth = node.maxWidth;\n }\n if (\"minHeight\" in node && typeof node.minHeight === \"number\") {\n base.minHeight = node.minHeight;\n }\n if (\"maxHeight\" in node && typeof node.maxHeight === \"number\") {\n base.maxHeight = node.maxHeight;\n }\n if (\"layoutGrow\" in node && node.layoutGrow !== undefined) {\n base.layoutGrow = node.layoutGrow as 0 | 1;\n }\n if (\"constraints\" in node && node.constraints) {\n base.constraints = node.constraints as AnalysisNode[\"constraints\"];\n }\n\n // Wrap (flex-wrap)\n if (\"layoutWrap\" in node && node.layoutWrap) {\n base.layoutWrap = node.layoutWrap as AnalysisNode[\"layoutWrap\"];\n }\n if (\"counterAxisSpacing\" in node && typeof node.counterAxisSpacing === \"number\") {\n base.counterAxisSpacing = node.counterAxisSpacing;\n }\n if (\"counterAxisAlignContent\" in node && node.counterAxisAlignContent) {\n base.counterAxisAlignContent =\n node.counterAxisAlignContent as AnalysisNode[\"counterAxisAlignContent\"];\n }\n\n // Grid layout (container)\n if (\"gridRowCount\" in node && typeof node.gridRowCount === \"number\") {\n base.gridRowCount = node.gridRowCount;\n }\n if (\"gridColumnCount\" in node && typeof node.gridColumnCount === \"number\") {\n base.gridColumnCount = node.gridColumnCount;\n }\n if (\"gridRowGap\" in node && typeof node.gridRowGap === \"number\") {\n base.gridRowGap = node.gridRowGap;\n }\n if (\"gridColumnGap\" in node && typeof node.gridColumnGap === \"number\") {\n base.gridColumnGap = node.gridColumnGap;\n }\n if (\"gridColumnsSizing\" in node && typeof node.gridColumnsSizing === \"string\") {\n base.gridColumnsSizing = node.gridColumnsSizing;\n }\n if (\"gridRowsSizing\" in node && typeof node.gridRowsSizing === \"string\") {\n base.gridRowsSizing = node.gridRowsSizing;\n }\n\n // Grid layout (child)\n if (\"gridChildHorizontalAlign\" in node && node.gridChildHorizontalAlign) {\n base.gridChildHorizontalAlign =\n node.gridChildHorizontalAlign as AnalysisNode[\"gridChildHorizontalAlign\"];\n }\n if (\"gridChildVerticalAlign\" in node && node.gridChildVerticalAlign) {\n base.gridChildVerticalAlign =\n node.gridChildVerticalAlign as AnalysisNode[\"gridChildVerticalAlign\"];\n }\n if (\"gridRowSpan\" in node && typeof node.gridRowSpan === \"number\") {\n base.gridRowSpan = node.gridRowSpan;\n }\n if (\"gridColumnSpan\" in node && typeof node.gridColumnSpan === \"number\") {\n base.gridColumnSpan = node.gridColumnSpan;\n }\n if (\"gridRowAnchorIndex\" in node && typeof node.gridRowAnchorIndex === \"number\") {\n base.gridRowAnchorIndex = node.gridRowAnchorIndex;\n }\n if (\"gridColumnAnchorIndex\" in node && typeof node.gridColumnAnchorIndex === \"number\") {\n base.gridColumnAnchorIndex = node.gridColumnAnchorIndex;\n }\n\n // Overflow / clip\n if (\"clipsContent\" in node && typeof node.clipsContent === \"boolean\") {\n base.clipsContent = node.clipsContent;\n }\n if (\"overflowDirection\" in node && node.overflowDirection) {\n base.overflowDirection =\n node.overflowDirection as AnalysisNode[\"overflowDirection\"];\n }\n\n // Size/position\n if (\"absoluteBoundingBox\" in node && node.absoluteBoundingBox) {\n base.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n // Component properties\n if (\"componentId\" in node) {\n base.componentId = node.componentId as string;\n }\n if (\"componentPropertyDefinitions\" in node) {\n base.componentPropertyDefinitions =\n node.componentPropertyDefinitions as Record<string, unknown>;\n }\n if (\"componentProperties\" in node) {\n base.componentProperties = node.componentProperties as Record<\n string,\n unknown\n >;\n }\n\n // Style properties\n if (\"styles\" in node) {\n base.styles = node.styles as Record<string, string>;\n }\n if (\"fills\" in node) {\n base.fills = node.fills as unknown[];\n }\n if (\"strokes\" in node) {\n base.strokes = node.strokes as unknown[];\n }\n if (\"strokeWeight\" in node && typeof node.strokeWeight === \"number\") {\n base.strokeWeight = node.strokeWeight;\n }\n if (\"individualStrokeWeights\" in node && node.individualStrokeWeights) {\n base.individualStrokeWeights = node.individualStrokeWeights as Record<string, number>;\n }\n if (\"effects\" in node) {\n base.effects = node.effects as unknown[];\n }\n if (\"cornerRadius\" in node && typeof node.cornerRadius === \"number\") {\n base.cornerRadius = node.cornerRadius;\n }\n if (\"opacity\" in node && typeof node.opacity === \"number\" && node.opacity < 1) {\n base.opacity = node.opacity;\n }\n\n // Variable bindings\n if (\"boundVariables\" in node && node.boundVariables) {\n base.boundVariables = node.boundVariables as Record<string, unknown>;\n }\n\n // Text properties\n if (\"characters\" in node) {\n base.characters = node.characters as string;\n }\n if (\"style\" in node) {\n base.style = node.style as Record<string, unknown>;\n }\n if (\"textTruncation\" in node && (node.textTruncation === \"DISABLED\" || node.textTruncation === \"ENDING\")) {\n base.textTruncation = node.textTruncation;\n }\n if (\"maxLines\" in node && typeof node.maxLines === \"number\") {\n base.maxLines = node.maxLines;\n }\n\n // Handoff status\n if (\"devStatus\" in node && node.devStatus) {\n base.devStatus = node.devStatus as AnalysisNode[\"devStatus\"];\n }\n\n // Prototype interactions\n if (\"interactions\" in node && Array.isArray(node.interactions) && node.interactions.length > 0) {\n base.interactions = node.interactions;\n }\n\n // Recursively transform children\n if (\"children\" in node && Array.isArray(node.children)) {\n base.children = node.children.map(transformNode);\n }\n\n return base;\n}\n\n/**\n * Transform Figma /v1/files/{key}/nodes response to analysis types.\n * Returns the first node's subtree as the document.\n */\nexport function transformFileNodesResponse(\n fileKey: string,\n response: GetFileNodesResponse\n): AnalysisFile {\n const entries = Object.values(response.nodes);\n const first = entries[0];\n if (!first)\n throw new Error(\n \"No nodes returned from Figma API — the node-id in the URL may be invalid or deleted. \" +\n \"Try selecting the frame in Figma and copying the link again.\"\n );\n\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(first.document),\n components: transformComponents(first.components),\n styles: transformStyles(first.styles),\n };\n}\n\n/**\n * Transform component master nodes from a /v1/files/{key}/nodes response.\n * Each requested node ID is transformed into an AnalysisNode if present.\n */\nexport function transformComponentMasterNodes(\n response: GetFileNodesResponse,\n requestedIds: string[]\n): Record<string, AnalysisNode> {\n const result: Record<string, AnalysisNode> = {};\n for (const id of requestedIds) {\n const entry = response.nodes[id];\n if (entry?.document) {\n result[id] = transformNode(entry.document);\n }\n }\n return result;\n}\n\nfunction transformComponents(\n components: GetFileResponse[\"components\"]\n): AnalysisFile[\"components\"] {\n const result: AnalysisFile[\"components\"] = {};\n for (const [id, component] of Object.entries(components)) {\n result[id] = {\n key: component.key,\n name: component.name,\n description: component.description,\n };\n }\n return result;\n}\n\nfunction transformStyles(\n styles: GetFileResponse[\"styles\"]\n): AnalysisFile[\"styles\"] {\n const result: AnalysisFile[\"styles\"] = {};\n for (const [id, style] of Object.entries(styles)) {\n result[id] = {\n key: style.key,\n name: style.name,\n styleType: style.styleType,\n };\n }\n return result;\n}\n","import type { FigmaClient } from \"./figma-client.js\";\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport { transformComponentMasterNodes } from \"./figma-transformer.js\";\n\nconst BATCH_SIZE = 50;\n\n/**\n * Recursively collect all unique componentId values from INSTANCE nodes.\n */\nexport function collectComponentIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.type === \"INSTANCE\" && n.componentId) {\n ids.add(n.componentId);\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Recursively collect all unique interaction destination IDs from nodes.\n * These are the node IDs that interactions (e.g., ON_HOVER → CHANGE_TO) point to.\n */\nexport function collectInteractionDestinationIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.interactions && Array.isArray(n.interactions)) {\n for (const interaction of n.interactions) {\n const i = interaction as {\n trigger?: { type?: string };\n actions?: Array<{ destinationId?: string; navigation?: string }>;\n };\n if (i.trigger?.type === \"ON_HOVER\" && i.actions) {\n for (const action of i.actions) {\n if (action.navigation === \"CHANGE_TO\" && action.destinationId) {\n ids.add(action.destinationId);\n }\n }\n }\n }\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Resolve component master node trees via multi-pass fetching.\n *\n * Pass 1: collect component IDs from the document tree, fetch their masters.\n * Pass 2+: collect component IDs from fetched masters that were not in previous passes.\n * Repeats up to maxPasses (default 2).\n *\n * Batches API calls at BATCH_SIZE IDs per request.\n * Skips IDs that return null (e.g. external library components).\n */\nexport async function resolveComponentDefinitions(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n maxPasses = 2\n): Promise<Record<string, AnalysisNode>> {\n const allDefinitions: Record<string, AnalysisNode> = {};\n const resolvedIds = new Set<string>();\n\n // Pass 1: collect from the original document\n let pendingIds = collectComponentIds(document);\n\n for (let pass = 0; pass < maxPasses; pass++) {\n // Filter out already-resolved IDs\n const idsToFetch = [...pendingIds].filter((id) => !resolvedIds.has(id));\n if (idsToFetch.length === 0) break;\n\n // Fetch in batches\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDefinitions[id] = node;\n }\n } catch (err) {\n // Skip failed batches (e.g. external library components)\n console.debug(`[component-resolver] batch fetch failed (${batch.length} ids):`, err);\n }\n }\n\n // Mark all attempted IDs as resolved (even if they failed/returned null)\n for (const id of idsToFetch) {\n resolvedIds.add(id);\n }\n\n // Collect new IDs only from masters fetched in this pass (not all accumulated)\n pendingIds = new Set<string>();\n for (const id of idsToFetch) {\n const node = allDefinitions[id];\n if (node) {\n for (const nestedId of collectComponentIds(node)) {\n if (!resolvedIds.has(nestedId)) {\n pendingIds.add(nestedId);\n }\n }\n }\n }\n }\n\n return allDefinitions;\n}\n\n/**\n * Resolve interaction destination nodes (e.g., hover variants).\n *\n * Collects all destinationId values from interactions in the document,\n * excludes those already in componentDefinitions, and fetches them.\n */\nexport async function resolveInteractionDestinations(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n existingDefinitions?: Record<string, AnalysisNode>,\n): Promise<Record<string, AnalysisNode>> {\n const destIds = collectInteractionDestinationIds(document);\n if (destIds.size === 0) return {};\n\n const allDestinations: Record<string, AnalysisNode> = {};\n const idsToFetch: string[] = [];\n\n for (const id of destIds) {\n const existing = existingDefinitions?.[id];\n if (existing) {\n allDestinations[id] = existing;\n } else {\n idsToFetch.push(id);\n }\n }\n\n if (idsToFetch.length === 0) return allDestinations;\n\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDestinations[id] = node;\n }\n } catch (err) {\n console.debug(`[component-resolver] interaction destination fetch failed (${batch.length} ids):`, err);\n }\n }\n\n return allDestinations;\n}\n","import { z } from \"zod\";\n\n/**\n * Figma node types required for analysis\n * See @figma/rest-api-spec for full API types\n */\n\nexport const AnalysisNodeTypeSchema = z.enum([\n \"DOCUMENT\",\n \"CANVAS\",\n \"FRAME\",\n \"GROUP\",\n \"SECTION\",\n \"COMPONENT\",\n \"COMPONENT_SET\",\n \"INSTANCE\",\n \"RECTANGLE\",\n \"ELLIPSE\",\n \"VECTOR\",\n \"TEXT\",\n \"LINE\",\n \"BOOLEAN_OPERATION\",\n \"STAR\",\n \"REGULAR_POLYGON\",\n \"SLICE\",\n \"STICKY\",\n \"SHAPE_WITH_TEXT\",\n \"CONNECTOR\",\n \"WIDGET\",\n \"EMBED\",\n \"LINK_UNFURL\",\n \"TABLE\",\n \"TABLE_CELL\",\n \"SLOT\",\n]);\n\nexport type AnalysisNodeType = z.infer<typeof AnalysisNodeTypeSchema>;\n\nexport const LayoutModeSchema = z.enum([\"NONE\", \"HORIZONTAL\", \"VERTICAL\", \"GRID\"]);\nexport type LayoutMode = z.infer<typeof LayoutModeSchema>;\n\nexport const LayoutAlignSchema = z.enum([\"MIN\", \"CENTER\", \"MAX\", \"STRETCH\", \"INHERIT\"]);\nexport type LayoutAlign = z.infer<typeof LayoutAlignSchema>;\n\nexport const LayoutPositioningSchema = z.enum([\"AUTO\", \"ABSOLUTE\"]);\nexport type LayoutPositioning = z.infer<typeof LayoutPositioningSchema>;\n\nexport const LayoutConstraintSchema = z.object({\n horizontal: z.enum([\"LEFT\", \"RIGHT\", \"CENTER\", \"LEFT_RIGHT\", \"SCALE\"]),\n vertical: z.enum([\"TOP\", \"BOTTOM\", \"CENTER\", \"TOP_BOTTOM\", \"SCALE\"]),\n});\nexport type LayoutConstraint = z.infer<typeof LayoutConstraintSchema>;\n\nexport const LayoutWrapSchema = z.enum([\"NO_WRAP\", \"WRAP\"]);\nexport type LayoutWrap = z.infer<typeof LayoutWrapSchema>;\n\nexport const OverflowDirectionSchema = z.enum([\n \"HORIZONTAL_SCROLLING\",\n \"VERTICAL_SCROLLING\",\n \"HORIZONTAL_AND_VERTICAL_SCROLLING\",\n \"NONE\",\n]);\nexport type OverflowDirection = z.infer<typeof OverflowDirectionSchema>;\n\nexport const GridChildAlignSchema = z.enum([\"AUTO\", \"MIN\", \"CENTER\", \"MAX\"]);\nexport type GridChildAlign = z.infer<typeof GridChildAlignSchema>;\n\n/**\n * Lightweight FigmaNode type for analysis\n * Contains only properties needed by rules\n */\nconst BaseAnalysisNodeSchema = z.object({\n // Basic identification\n id: z.string(),\n name: z.string(),\n type: AnalysisNodeTypeSchema,\n visible: z.boolean().default(true),\n\n // Layout analysis\n layoutMode: LayoutModeSchema.optional(),\n layoutAlign: LayoutAlignSchema.optional(),\n layoutPositioning: LayoutPositioningSchema.optional(),\n layoutSizingHorizontal: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n layoutSizingVertical: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n primaryAxisAlignItems: z.string().optional(),\n counterAxisAlignItems: z.string().optional(),\n itemSpacing: z.number().optional(),\n paddingLeft: z.number().optional(),\n paddingRight: z.number().optional(),\n paddingTop: z.number().optional(),\n paddingBottom: z.number().optional(),\n\n // Size constraints (responsive)\n minWidth: z.number().optional(),\n maxWidth: z.number().optional(),\n minHeight: z.number().optional(),\n maxHeight: z.number().optional(),\n layoutGrow: z.union([z.literal(0), z.literal(1)]).optional(),\n constraints: LayoutConstraintSchema.optional(),\n\n // Wrap (flex-wrap)\n layoutWrap: LayoutWrapSchema.optional(),\n counterAxisSpacing: z.number().optional(),\n counterAxisAlignContent: z.enum([\"AUTO\", \"SPACE_BETWEEN\"]).optional(),\n\n // Grid layout (container)\n gridRowCount: z.number().optional(),\n gridColumnCount: z.number().optional(),\n gridRowGap: z.number().optional(),\n gridColumnGap: z.number().optional(),\n gridColumnsSizing: z.string().optional(),\n gridRowsSizing: z.string().optional(),\n\n // Grid layout (child)\n gridChildHorizontalAlign: GridChildAlignSchema.optional(),\n gridChildVerticalAlign: GridChildAlignSchema.optional(),\n gridRowSpan: z.number().optional(),\n gridColumnSpan: z.number().optional(),\n gridRowAnchorIndex: z.number().optional(),\n gridColumnAnchorIndex: z.number().optional(),\n\n // Overflow / clip\n clipsContent: z.boolean().optional(),\n overflowDirection: OverflowDirectionSchema.optional(),\n\n // Size/position analysis\n absoluteBoundingBox: z\n .object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n })\n .nullable()\n .optional(),\n\n // Component analysis\n componentId: z.string().optional(),\n componentPropertyDefinitions: z.record(z.string(), z.unknown()).optional(),\n componentProperties: z.record(z.string(), z.unknown()).optional(),\n\n // Style/token analysis\n styles: z.record(z.string(), z.string()).optional(),\n fills: z.array(z.unknown()).optional(),\n strokes: z.array(z.unknown()).optional(),\n strokeWeight: z.number().optional(),\n individualStrokeWeights: z.record(z.string(), z.number()).optional(),\n effects: z.array(z.unknown()).optional(),\n cornerRadius: z.number().optional(),\n opacity: z.number().optional(),\n\n // Variable binding analysis (design tokens)\n boundVariables: z.record(z.string(), z.unknown()).optional(),\n\n // Text analysis\n characters: z.string().optional(),\n style: z.record(z.string(), z.unknown()).optional(),\n textTruncation: z.enum([\"DISABLED\", \"ENDING\"]).optional(),\n maxLines: z.number().optional(),\n\n // Handoff analysis\n devStatus: z\n .object({\n type: z.enum([\"NONE\", \"READY_FOR_DEV\", \"COMPLETED\"]),\n description: z.string().optional(),\n })\n .optional(),\n\n // Prototype interactions\n interactions: z.array(z.unknown()).optional(),\n\n // Naming analysis metadata\n isAsset: z.boolean().optional(),\n});\n\nexport type AnalysisNode = z.infer<typeof BaseAnalysisNodeSchema> & {\n children?: AnalysisNode[] | undefined;\n};\n\nexport const AnalysisNodeSchema: z.ZodType<AnalysisNode> =\n BaseAnalysisNodeSchema.extend({\n children: z.lazy(() => AnalysisNodeSchema.array().optional()),\n }) as z.ZodType<AnalysisNode>;\n\n/**\n * Figma file metadata for analysis\n */\nexport const AnalysisFileSchema = z.object({\n fileKey: z.string(),\n name: z.string(),\n lastModified: z.string(),\n version: z.string(),\n sourceUrl: z.string().optional(),\n document: AnalysisNodeSchema,\n components: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n description: z.string(),\n })\n ),\n componentDefinitions: z.record(z.string(), AnalysisNodeSchema).optional(),\n interactionDestinations: z.record(z.string(), AnalysisNodeSchema).optional(),\n styles: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n styleType: z.string(),\n })\n ),\n});\n\nexport type AnalysisFile = z.infer<typeof AnalysisFileSchema>;\n","import { readFile } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport type { GetFileResponse } from \"@figma/rest-api-spec\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport { AnalysisNodeSchema } from \"../contracts/figma-node.js\";\nimport { transformFigmaResponse } from \"./figma-transformer.js\";\n\n/**\n * Extract fileKey from fixture path.\n * - fixtures/name/data.json → name (directory-based fixture)\n * - fixtures/name.json → name (legacy flat fixture)\n */\nfunction extractFileKey(filePath: string): string {\n const fileName = basename(filePath, \".json\");\n if (fileName === \"data\") {\n // Directory-based fixture: use parent directory name\n return basename(dirname(filePath));\n }\n return fileName;\n}\n\n/**\n * Load Figma data from a JSON file\n * For MVP testing and fixture support\n */\nexport async function loadFigmaFileFromJson(\n filePath: string\n): Promise<AnalysisFile> {\n const content = await readFile(filePath, \"utf-8\");\n const data = JSON.parse(content) as GetFileResponse & {\n componentDefinitions?: Record<string, unknown>;\n interactionDestinations?: Record<string, unknown>;\n };\n\n const fileKey = extractFileKey(filePath);\n\n const file = transformFigmaResponse(fileKey, data);\n\n // Preserve componentDefinitions from previously-saved fixtures\n if (data.componentDefinitions) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.componentDefinitions)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] componentDefinitions[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.componentDefinitions = parsed;\n }\n }\n\n // Preserve interactionDestinations from previously-saved fixtures\n if (data.interactionDestinations) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.interactionDestinations)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] interactionDestinations[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.interactionDestinations = parsed;\n }\n }\n\n return file;\n}\n\n/**\n * Parse Figma data from a JSON string\n */\nexport function parseFigmaJson(\n json: string,\n fileKey: string\n): AnalysisFile {\n const data = JSON.parse(json) as GetFileResponse;\n return transformFigmaResponse(fileKey, data);\n}\n\nexport class FigmaFileLoadError extends Error {\n constructor(message: string, public filePath?: string) {\n super(message);\n this.name = \"FigmaFileLoadError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const FigmaUrlInfoSchema = z.object({\n fileKey: z.string(),\n nodeId: z.string().optional(),\n fileName: z.string().optional(),\n});\n\nexport type FigmaUrlInfo = z.infer<typeof FigmaUrlInfoSchema>;\n\nconst FIGMA_URL_PATTERNS = [\n // https://www.figma.com/design/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/design\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/file/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/file\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/proto/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/proto\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n];\n\nexport function parseFigmaUrl(url: string): FigmaUrlInfo {\n for (const pattern of FIGMA_URL_PATTERNS) {\n const match = url.match(pattern);\n if (match) {\n const [, fileKey, fileName, nodeId] = match;\n if (!fileKey) {\n throw new FigmaUrlParseError(`Invalid Figma URL: missing file key`);\n }\n return {\n fileKey,\n fileName: fileName ? decodeURIComponent(fileName) : undefined,\n nodeId: nodeId ? decodeURIComponent(nodeId) : undefined,\n };\n }\n }\n\n throw new FigmaUrlParseError(\n `Invalid Figma URL format. Expected: https://www.figma.com/design/FILE_KEY/...`\n );\n}\n\nexport class FigmaUrlParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FigmaUrlParseError\";\n }\n}\n\n/**\n * Extract the commentable node ID from a potentially nested instance path.\n * Instance-internal IDs like \"I3010:7457;1442:7704\" use semicolons to\n * separate path segments. The Figma Comments API only accepts simple IDs\n * (e.g. \"3010:7457\"), so we take the first segment and strip the \"I\" prefix.\n */\nexport function toCommentableNodeId(nodeId: string): string {\n const firstSegment = nodeId.split(\";\")[0]!;\n return firstSegment.replace(/^I/, \"\");\n}\n\nexport function buildFigmaDeepLink(fileKey: string, nodeId: string): string {\n // Strip instance-internal path to top-level node:\n // \"I175:7425;1442:7704\" → \"175:7425\" → \"175-7425\"\n const topNodeId = toCommentableNodeId(nodeId).replace(/:/g, \"-\");\n return `https://www.figma.com/design/${fileKey}?node-id=${topNodeId}`;\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst AIREADY_DIR = join(homedir(), \".canicode\");\nconst CONFIG_PATH = join(AIREADY_DIR, \"config.json\");\nconst REPORTS_DIR = join(AIREADY_DIR, \"reports\");\n\ninterface AireadyConfig {\n figmaToken?: string;\n telemetry?: boolean;\n posthogApiKey?: string;\n sentryDsn?: string;\n deviceId?: string;\n}\n\nfunction hardenPermissions(path: string, mode: number): void {\n if (process.platform !== \"win32\") {\n chmodSync(path, mode);\n }\n}\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n hardenPermissions(dir, 0o700);\n}\n\nexport function readConfig(): AireadyConfig {\n if (!existsSync(CONFIG_PATH)) {\n return {};\n }\n try {\n const raw = readFileSync(CONFIG_PATH, \"utf-8\");\n return JSON.parse(raw) as AireadyConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: AireadyConfig): void {\n ensureDir(AIREADY_DIR);\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + \"\\n\", {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n hardenPermissions(CONFIG_PATH, 0o600);\n}\n\nexport function getFigmaToken(): string | undefined {\n // Priority: env var > config file\n return process.env[\"FIGMA_TOKEN\"] ?? readConfig().figmaToken;\n}\n\nexport function setFigmaToken(token: string): void {\n const config = readConfig();\n config.figmaToken = token;\n writeConfig(config);\n}\n\nexport function hasConfig(): boolean {\n return existsSync(CONFIG_PATH);\n}\n\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n\nexport function getReportsDir(): string {\n return REPORTS_DIR;\n}\n\nexport function ensureReportsDir(): void {\n ensureDir(AIREADY_DIR);\n ensureDir(REPORTS_DIR);\n}\n\nexport function getTelemetryEnabled(): boolean {\n return readConfig().telemetry !== false;\n}\n\nexport function setTelemetryEnabled(enabled: boolean): void {\n const config = readConfig();\n config.telemetry = enabled;\n writeConfig(config);\n}\n\nexport function getPosthogApiKey(): string | undefined {\n return process.env[\"POSTHOG_API_KEY\"] ?? readConfig().posthogApiKey;\n}\n\nexport function getSentryDsn(): string | undefined {\n return process.env[\"SENTRY_DSN\"] ?? readConfig().sentryDsn;\n}\n\n/**\n * Get or create a stable anonymous device ID for telemetry.\n * Stored in ~/.canicode/config.json, persists across sessions.\n */\nexport function getDeviceId(): string {\n const config = readConfig();\n if (config.deviceId) return config.deviceId;\n\n const id = randomUUID();\n config.deviceId = id;\n writeConfig(config);\n return id;\n}\n\n/**\n * Initialize canicode: write config + create reports dir\n */\nexport function initAiready(token: string): void {\n setFigmaToken(token);\n ensureReportsDir();\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { resolve, join } from \"node:path\";\nimport { FigmaClient } from \"../adapters/figma-client.js\";\nimport { resolveComponentDefinitions, resolveInteractionDestinations } from \"../adapters/component-resolver.js\";\nimport { loadFigmaFileFromJson } from \"../adapters/figma-file-loader.js\";\nimport { transformFigmaResponse, transformFileNodesResponse } from \"../adapters/figma-transformer.js\";\nimport { parseFigmaUrl } from \"../adapters/figma-url-parser.js\";\nimport { getFigmaToken } from \"./config-store.js\";\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\n\nexport interface LoadResult {\n file: AnalysisFile;\n nodeId?: string | undefined;\n}\n\n/** Check if input string is a Figma URL. */\nexport function isFigmaUrl(input: string): boolean {\n return input.includes(\"figma.com/\");\n}\n\n/** Check if input string is a JSON file path. */\nexport function isJsonFile(input: string): boolean {\n return input.endsWith(\".json\");\n}\n\n/**\n * Check if input is a fixture directory (contains data.json).\n */\nexport function isFixtureDir(input: string): boolean {\n const resolved = resolve(input);\n if (!existsSync(resolved)) return false;\n try {\n if (!statSync(resolved).isDirectory()) return false;\n } catch {\n return false;\n }\n return existsSync(join(resolved, \"data.json\"));\n}\n\n/**\n * Resolve fixture input to data.json path.\n * Input: fixtures/name/ or fixtures/name → fixtures/name/data.json\n */\nexport function resolveFixturePath(input: string): string {\n if (isJsonFile(input)) return resolve(input);\n return resolve(join(input, \"data.json\"));\n}\n\n/**\n * Load a Figma file from a URL, JSON file, or fixture directory.\n * Resolves component master node trees for accurate analysis.\n */\nexport async function loadFile(\n input: string,\n token?: string,\n): Promise<LoadResult> {\n if (isJsonFile(input) || isFixtureDir(input)) {\n const filePath = resolveFixturePath(input);\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n console.error(`Loading from JSON: ${filePath}`);\n return { file: await loadFigmaFileFromJson(filePath) };\n }\n\n if (isFigmaUrl(input)) {\n const { fileKey, nodeId } = parseFigmaUrl(input);\n return loadFromApi(fileKey, nodeId, token);\n }\n\n throw new Error(\n `Invalid input: ${input}. Provide a Figma URL or fixture directory path.`\n );\n}\n\nasync function loadFromApi(\n fileKey: string,\n nodeId: string | undefined,\n token?: string\n): Promise<LoadResult> {\n console.error(`Fetching from Figma REST API: ${fileKey}`);\n if (nodeId) {\n console.error(`Target node: ${nodeId}`);\n }\n\n const figmaToken = token ?? getFigmaToken();\n if (!figmaToken) {\n throw new Error(\n \"Figma token required. Run 'canicode init --token YOUR_TOKEN' or set FIGMA_TOKEN env var.\"\n );\n }\n\n const client = new FigmaClient({ token: figmaToken });\n\n if (nodeId) {\n // Fetch only the target node subtree — faster, less rate limit impact\n const response = await client.getFileNodes(fileKey, [nodeId.replace(/-/g, \":\")]);\n const file = transformFileNodesResponse(fileKey, response);\n\n // Resolve component master node trees for accurate analysis\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n }\n\n const response = await client.getFile(fileKey);\n const file = transformFigmaResponse(fileKey, response);\n\n // Full file fetch may still miss component masters from external libraries\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n}\n","/**\n * Parse Figma instance-child node IDs.\n *\n * Nodes inside an instance carry an `I`-prefixed id with semicolon-separated\n * path segments: `I<parentInstanceId>;<sourceNodeId>`. For nested instances\n * the format chains further, e.g. `I<parentId>;<midId>;<sourceNodeId>` —\n * each `;` represents one additional level of instance expansion. The LAST\n * segment is always the id of the node inside the innermost source component,\n * which is reachable directly via `figma.getNodeById`.\n *\n * Siblings: `figma-url-parser.ts#toCommentableNodeId` handles the same id\n * format for a different purpose (stripping for the Comments API). That\n * helper is intentionally left alone — this module owns id parsing for the\n * apply pipeline.\n */\n\nexport interface InstanceChildIdParts {\n parentInstanceId: string;\n sourceNodeId: string;\n}\n\nexport function isInstanceChildNodeId(nodeId: string): boolean {\n return nodeId.startsWith(\"I\") && nodeId.includes(\";\");\n}\n\nexport function parseInstanceChildNodeId(\n nodeId: string,\n): InstanceChildIdParts | null {\n if (!isInstanceChildNodeId(nodeId)) return null;\n\n const segments = nodeId.split(\";\");\n if (segments.length < 2) return null;\n\n const parentInstanceId = segments[0]!.replace(/^I/, \"\");\n const sourceNodeId = segments[segments.length - 1]!;\n\n if (!parentInstanceId || !sourceNodeId) return null;\n\n return { parentInstanceId, sourceNodeId };\n}\n","import type { RuleId, RuleViolation } from \"../contracts/rule.js\";\nimport type { InstanceContext } from \"../contracts/gotcha-survey.js\";\nimport type { AnnotationProperty } from \"../roundtrip/types.js\";\nimport {\n isInstanceChildNodeId,\n parseInstanceChildNodeId,\n} from \"../adapters/instance-id-parser.js\";\nimport { getAnnotationProperties } from \"../rules/rule-config.js\";\n\n/**\n * Apply strategy for a rule violation. Tells the SKILL.md/`use_figma`\n * pipeline which Plugin-API path to take.\n *\n * - `property-mod` — Strategy A. Direct property write on the scene/instance node.\n * - `structural-mod` — Strategy B. Structural change; ask user to confirm before applying.\n * - `annotation` — Strategy C. Cannot be auto-fixed; record as a Figma annotation.\n * - `auto-fix` — Strategy D. Lower-severity rules from analyze output;\n * may be a property write (naming) or annotation-only.\n *\n * Sibling module `resolve-apply-target.ts` solves a different concern\n * (scene-vs-definition write target). Compose them — do not merge.\n */\nexport type RuleApplyStrategy =\n | \"property-mod\"\n | \"structural-mod\"\n | \"annotation\"\n | \"auto-fix\";\n\n/**\n * Pre-computed apply context attached to gotcha-survey questions and\n * analyze-output issues. Lets the SKILL.md consume the data directly\n * instead of re-deriving rule routing on every roundtrip run.\n *\n * `targetProperty` is `string` for single-property writes, `string[]`\n * for rules that require multiple writes (e.g. `irregular-spacing`\n * subType `padding` → 4 padding fields), and `undefined` for\n * annotation/structural strategies that have no single property target.\n */\nexport interface ApplyContext {\n applyStrategy: RuleApplyStrategy;\n targetProperty?: string | string[];\n annotationProperties?: AnnotationProperty[];\n isInstanceChild: boolean;\n sourceChildId?: string;\n}\n\nconst STRATEGY_BY_RULE: Record<RuleId, RuleApplyStrategy> = {\n // Strategy A — property modification\n \"no-auto-layout\": \"property-mod\",\n \"fixed-size-in-auto-layout\": \"property-mod\",\n \"missing-size-constraint\": \"property-mod\",\n \"irregular-spacing\": \"property-mod\",\n \"non-semantic-name\": \"property-mod\",\n // Strategy B — structural modification (needs user confirmation)\n \"non-layout-container\": \"structural-mod\",\n \"deep-nesting\": \"structural-mod\",\n \"missing-component\": \"structural-mod\",\n \"detached-instance\": \"structural-mod\",\n // Strategy C — annotation only\n \"absolute-position-in-auto-layout\": \"annotation\",\n \"variant-structure-mismatch\": \"annotation\",\n // Strategy D — auto-fix lower-severity issues from analyze output\n \"non-standard-naming\": \"auto-fix\",\n \"inconsistent-naming-convention\": \"auto-fix\",\n \"raw-value\": \"auto-fix\",\n \"missing-interaction-state\": \"auto-fix\",\n \"missing-prototype\": \"auto-fix\",\n};\n\n/**\n * Resolve the Figma Plugin-API target property (or properties) for a\n * violation. Returns `undefined` for rules whose strategy does not write\n * a single property (structural-mod, annotation), or for naming auto-fixes\n * where the value comes from `violation.suggestedName` rather than a\n * specific Figma property — except the `name` write itself, which we\n * surface so SKILL.md can branch uniformly on `targetProperty === 'name'`.\n */\nfunction resolveTargetProperty(\n ruleId: RuleId,\n subType: string | undefined,\n): string | string[] | undefined {\n switch (ruleId) {\n case \"no-auto-layout\":\n return [\"layoutMode\", \"itemSpacing\"];\n case \"fixed-size-in-auto-layout\":\n if (subType === \"horizontal\") return \"layoutSizingHorizontal\";\n // both-axes — write both axes\n return [\"layoutSizingHorizontal\", \"layoutSizingVertical\"];\n case \"missing-size-constraint\":\n // #374: always return BOTH bounds so `applyPropertyMod`'s array branch\n // iterates the full `{ minWidth, maxWidth }` answer shape. Pre-fix the\n // `wrap` subType returned `\"minWidth\"` and `max-width` returned\n // `\"maxWidth\"` as single strings — the user typically answered with\n // both keys (the gotcha hint asks for both) and the apply step\n // silently dropped half the intent because it only iterated the one\n // property in `targetProperty`. Partial answers still work: the per-\n // property lookup in `applyPropertyMod` returns `undefined` for the\n // missing key and the helper skips it.\n return [\"minWidth\", \"maxWidth\"];\n case \"irregular-spacing\":\n if (subType === \"gap\") return \"itemSpacing\";\n // padding — all four padding fields\n return [\"paddingTop\", \"paddingRight\", \"paddingBottom\", \"paddingLeft\"];\n case \"non-semantic-name\":\n return \"name\";\n case \"non-layout-container\":\n return \"layoutMode\";\n case \"non-standard-naming\":\n case \"inconsistent-naming-convention\":\n return \"name\";\n case \"deep-nesting\":\n case \"missing-component\":\n case \"detached-instance\":\n case \"absolute-position-in-auto-layout\":\n case \"variant-structure-mismatch\":\n case \"raw-value\":\n case \"missing-interaction-state\":\n case \"missing-prototype\":\n return undefined;\n }\n}\n\n/**\n * Compute the deterministic apply context for a rule violation.\n *\n * - `applyStrategy` and `targetProperty` come from the ruleId/subType tables above.\n * - `isInstanceChild` and `sourceChildId` are parsed from the violation `nodeId`\n * via `parseInstanceChildNodeId` — single source of truth for `I...;...` ids.\n * - `instanceContext`, when supplied, takes precedence for `sourceChildId` so\n * callers that already resolved the source component (gotcha-survey) do not\n * re-parse the id.\n *\n * Strategy D rules that target scene nodes (analyze output) can pass\n * `instanceContext: undefined` — the function still returns the parsed\n * `isInstanceChild`/`sourceChildId` so SKILL.md knows whether to walk the\n * instance fallback.\n */\nexport function computeApplyContext(\n violation: Pick<RuleViolation, \"ruleId\" | \"subType\" | \"nodeId\">,\n instanceContext?: InstanceContext,\n): ApplyContext {\n const ruleId = violation.ruleId as RuleId;\n const applyStrategy = STRATEGY_BY_RULE[ruleId] ?? \"annotation\";\n const targetProperty = resolveTargetProperty(ruleId, violation.subType);\n const annotationProperties = getAnnotationProperties(\n ruleId,\n violation.subType,\n );\n\n const parsed = parseInstanceChildNodeId(violation.nodeId);\n const isInstanceChild =\n parsed !== null || isInstanceChildNodeId(violation.nodeId);\n const sourceChildId = instanceContext?.sourceNodeId ?? parsed?.sourceNodeId;\n\n return {\n applyStrategy,\n ...(targetProperty !== undefined ? { targetProperty } : {}),\n ...(annotationProperties !== undefined ? { annotationProperties } : {}),\n isInstanceChild,\n ...(sourceChildId !== undefined ? { sourceChildId } : {}),\n };\n}\n","{\n \"name\": \"canicode\",\n \"version\": \"0.11.2\",\n \"mcpName\": \"io.github.let-sunny/canicode\",\n \"description\": \"Lint Figma designs for AI code-gen and roundtrip the answers back into the file. CLI + MCP server.\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"canicode\": \"dist/cli/index.js\",\n \"canicode-mcp\": \"dist/mcp/server.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup --config tsup.config.ts && pnpm build:roundtrip && pnpm bundle:skills\",\n \"build:web\": \"bash scripts/build-web.sh\",\n \"build:roundtrip\": \"tsup --config tsup.roundtrip.config.ts && tsx scripts/bundle-roundtrip-cache.ts\",\n \"bundle:skills\": \"bash scripts/bundle-skills.sh\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"tsc --noEmit\",\n \"build:plugin\": \"bash scripts/build-plugin.sh\",\n \"sync-docs\": \"tsx scripts/sync-rule-docs.ts\",\n \"check:skill-determinism\": \"tsx scripts/check-skill-determinism.ts\",\n \"clean\": \"rm -rf dist skills\"\n },\n \"files\": [\n \"dist\",\n \"skills\",\n \"README.md\",\n \"docs/CUSTOMIZATION.md\"\n ],\n \"keywords\": [\n \"figma\",\n \"design\",\n \"analysis\",\n \"cli\",\n \"mcp\",\n \"readiness\",\n \"ai\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/let-sunny/canicode.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/let-sunny/canicode/issues\"\n },\n \"homepage\": \"https://github.com/let-sunny/canicode\",\n \"author\": \"minseon\",\n \"license\": \"MIT\",\n \"pnpm\": {\n \"overrides\": {\n \"picomatch\": \"4.0.4\",\n \"path-to-regexp\": \"8.4.0\"\n }\n },\n \"packageManager\": \"pnpm@10.32.1\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"dependencies\": {\n \"@figma/rest-api-spec\": \"^0.36.0\",\n \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n \"cac\": \"^7.0.0\",\n \"dotenv\": \"^17.3.1\",\n \"pixelmatch\": \"^7.1.0\",\n \"pngjs\": \"^7.0.0\",\n \"zod\": \"^4.3.6\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.80.0\",\n \"@figma/plugin-typings\": \"^1.123.0\",\n \"@types/node\": \"^25.5.0\",\n \"@types/pngjs\": \"^6.0.5\",\n \"playwright\": \"^1.58.2\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.19.0\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.0\"\n }\n}\n","import type { Category } from \"../contracts/category.js\";\nimport { CATEGORIES, CATEGORY_LABELS } from \"../contracts/category.js\";\nimport type { RuleId, RuleConfig } from \"../contracts/rule.js\";\nimport type { Severity } from \"../contracts/severity.js\";\nimport type { AnalysisResult } from \"./rule-engine.js\";\nimport { RULE_CONFIGS, RULE_ID_CATEGORY, getRulePurpose } from \"../rules/rule-config.js\";\nimport { computeApplyContext } from \"../gotcha/apply-context.js\";\nimport { version as VERSION } from \"../../../package.json\";\n\n/**\n * Score breakdown for a single category\n */\nexport interface CategoryScoreResult {\n category: Category;\n score: number;\n maxScore: number;\n percentage: number;\n issueCount: number;\n uniqueRuleCount: number;\n weightedIssueCount: number;\n densityScore: number;\n diversityScore: number;\n bySeverity: Record<Severity, number>;\n}\n\n/**\n * Overall score report\n */\nexport interface ScoreReport {\n overall: {\n score: number;\n maxScore: number;\n percentage: number;\n grade: Grade;\n };\n byCategory: Record<Category, CategoryScoreResult>;\n summary: {\n totalIssues: number;\n blocking: number;\n risk: number;\n missingInfo: number;\n suggestion: number;\n nodeCount: number;\n /**\n * Number of issues marked `acknowledged` by an upstream\n * acknowledgments list (#371). Acknowledged issues are still counted in\n * `totalIssues` and the per-severity tallies — the count here is purely\n * additive context so consumers can render\n * `N issues — A acknowledged / N-A unaddressed`. They contribute half\n * weight to the density score upstream.\n */\n acknowledgedCount: number;\n };\n}\n\n/**\n * Grade levels based on percentage\n */\nexport type Grade = \"S\" | \"A+\" | \"A\" | \"B+\" | \"B\" | \"C+\" | \"C\" | \"D\" | \"F\";\n\n/**\n * Density weighting uses per-rule base |score| with sqrt damping (#226).\n *\n * Previously, each issue's |calculatedScore| was summed linearly — a rule\n * triggering N times contributed N× its score. This over-penalized designs\n * with many instances of the same issue (e.g., raw-value ×79 = -316 weight),\n * causing most real files to score Grade D/F with no differentiation.\n *\n * Now: same rule triggered N times contributes |score| × sqrt(N).\n * raw-value ×79 = 4 × sqrt(79) ≈ 36 instead of 316.\n * At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity.\n * At high counts the curve flattens — 79th occurrence adds ~0.2 vs 1st adding 4.\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n * Category importance is already encoded in rule scores (pixel-critical -10\n * vs semantic -4), so per-category weighting is unnecessary.\n */\n\n/**\n * Compute sum of |score| for all rules in each category from a given config map.\n * Used as denominator for severity-weighted diversity scoring.\n * Must use the same preset-adjusted config map that produced the analysis issues,\n * otherwise diversity ratios will be incorrect.\n */\nfunction computeTotalScorePerCategory(\n configs: Record<RuleId, RuleConfig>\n): Record<Category, number> {\n const totals = Object.fromEntries(\n CATEGORIES.map(c => [c, 0])\n ) as Record<Category, number>;\n\n for (const [id, config] of Object.entries(configs)) {\n const category = RULE_ID_CATEGORY[id as RuleId];\n if (category && config.enabled) {\n totals[category] += Math.abs(config.score);\n }\n }\n\n return totals;\n}\n\n/**\n * Score composition weights (initial intuition, pending calibration validation).\n *\n * Density (0.7): \"how many issues per node\" — measures issue volume relative to design size.\n * Designs with many issues per node are harder to implement accurately.\n *\n * Diversity (0.3): \"how many different rule types triggered\" — measures issue breadth.\n * A design that triggers 1 rule 50 times is easier to fix than one triggering 10 different rules.\n *\n * The 70:30 ratio prioritizes volume over variety. Rationale: a design with a single\n * systemic problem (e.g., all frames missing auto-layout) is still very hard to implement,\n * even though diversity is low. Density captures this; diversity adds a penalty for\n * designs with scattered, unrelated issues.\n *\n * Status: initial values. To be validated via /calibrate against visual-compare results.\n */\nconst DENSITY_WEIGHT = 0.7;\nconst DIVERSITY_WEIGHT = 0.3;\n\n/**\n * Minimum score floor.\n * Even the worst design gets 5% instead of 0%. Rationale: a score of 0 implies\n * \"completely unimplementable\", but any Figma file with visible nodes provides\n * some structural information. The floor also avoids demoralizing UX — seeing 0%\n * feels like the tool failed, not that the design needs improvement.\n */\nconst SCORE_FLOOR = 5;\n\n/**\n * Calculate grade from percentage.\n * Thresholds follow a 5-point interval pattern (95/90/85/80/75/70/65) with a wider\n * gap for D (50-64) and F (<50). This mirrors academic grading conventions where\n * the top tiers are tightly spaced and the failing range is broad.\n */\nfunction calculateGrade(percentage: number): Grade {\n if (percentage >= 95) return \"S\";\n if (percentage >= 90) return \"A+\";\n if (percentage >= 85) return \"A\";\n if (percentage >= 80) return \"B+\";\n if (percentage >= 75) return \"B\";\n if (percentage >= 70) return \"C+\";\n if (percentage >= 65) return \"C\";\n if (percentage >= 50) return \"D\";\n return \"F\";\n}\n\n/**\n * Returns true if the design is ready for code generation.\n * S, A+, and A grades (percentage >= 85) indicate the design has minimal blockers\n * and can be implemented accurately by AI or developers.\n */\nexport function isReadyForCodeGen(grade: Grade): boolean {\n return grade === \"S\" || grade === \"A+\" || grade === \"A\";\n}\n\n/**\n * Convert grade to a CSS-safe class name suffix\n * e.g. \"A+\" -> \"Aplus\", \"B+\" -> \"Bplus\", \"C+\" -> \"Cplus\"\n */\nexport function gradeToClassName(grade: Grade): string {\n return grade.replace(\"+\", \"plus\");\n}\n\n/**\n * Clamp a value between min and max\n */\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Calculate scores from analysis result using density + diversity scoring\n *\n * Density Score = 100 - (weighted issue count / node count) * 100\n * Diversity Score = (1 - weighted triggered rule scores / total category scores) * 100\n * Final Score = density * 0.7 + diversity * 0.3\n *\n * @param result Analysis result with issues\n * @param configs Optional preset-adjusted config map used to produce the issues.\n * If not provided, diversity totals are reconstructed from issue.config values.\n */\nexport function calculateScores(\n result: AnalysisResult,\n configs?: Record<RuleId, RuleConfig>\n): ScoreReport {\n const categoryScores = initializeCategoryScores();\n const nodeCount = result.nodeCount;\n\n // Track unique rules and their base |score| per category\n const uniqueRulesPerCategory = new Map<Category, Set<string>>();\n const ruleScorePerCategory = new Map<Category, Map<string, number>>();\n // Track issue counts per rule per category for sqrt damping (#226)\n const ruleIssueCountPerCategory = new Map<Category, Map<string, number>>();\n for (const category of CATEGORIES) {\n uniqueRulesPerCategory.set(category, new Set());\n ruleScorePerCategory.set(category, new Map());\n ruleIssueCountPerCategory.set(category, new Map());\n }\n\n // Compute totals from the config map.\n // If configs provided: use preset-adjusted totals (recommended when using presets).\n // If not: fall back to static RULE_CONFIGS — only correct when issues were\n // produced with default RULE_CONFIGS, otherwise diversity ratios will be skewed.\n const totalScorePerCategory = computeTotalScorePerCategory(configs ?? RULE_CONFIGS);\n\n // Count issues by severity per category and track unique rules with scores\n for (const issue of result.issues) {\n const category = issue.rule.definition.category;\n const severity = issue.config.severity;\n const ruleId = issue.rule.definition.id;\n\n categoryScores[category].issueCount++;\n categoryScores[category].bySeverity[severity]++;\n uniqueRulesPerCategory.get(category)!.add(ruleId);\n ruleScorePerCategory.get(category)!.set(ruleId, Math.abs(issue.config.score));\n // Accumulate per-rule issue count using a per-issue weight: 1.0 for\n // unacknowledged issues, 0.5 for acknowledged ones (#371). The sqrt\n // damping below treats this sum as the \"occurrence count\" so the\n // half-weight flows through to density without changing the formula.\n // Diversity is left untouched — acknowledgment is per-issue, not\n // per-rule, and the rule still represents a kind of problem.\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n const weight = issue.acknowledged === true ? 0.5 : 1;\n ruleCountMap.set(ruleId, (ruleCountMap.get(ruleId) ?? 0) + weight);\n }\n\n // Compute weightedIssueCount with sqrt damping per rule (#226).\n // Same rule triggered N times contributes |score| × sqrt(N) instead of |score| × N.\n // Rationale: 79 raw-value issues represent one systemic problem, not 79× the difficulty.\n // First few occurrences identify the problem; subsequent ones have diminishing impact.\n // At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity for rare issues.\n for (const category of CATEGORIES) {\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n const ruleScoreMap = ruleScorePerCategory.get(category)!;\n let dampedWeight = 0;\n for (const [ruleId, count] of ruleCountMap) {\n const ruleScore = ruleScoreMap.get(ruleId) ?? 0;\n dampedWeight += ruleScore * Math.sqrt(count);\n }\n categoryScores[category].weightedIssueCount = dampedWeight;\n }\n\n // Calculate percentage for each category based on density + diversity\n for (const category of CATEGORIES) {\n const catScore = categoryScores[category];\n const uniqueRules = uniqueRulesPerCategory.get(category)!;\n\n catScore.uniqueRuleCount = uniqueRules.size;\n\n // Density score: lower density = higher score\n let densityScore = 100;\n if (nodeCount > 0 && catScore.issueCount > 0) {\n const density = catScore.weightedIssueCount / nodeCount;\n densityScore = clamp(Math.round(100 - density * 100), 0, 100);\n }\n catScore.densityScore = densityScore;\n\n // Diversity score: weighted by base rule |score| (config.score, not calculatedScore).\n // Uses base score intentionally — diversity measures \"what types of problems exist\",\n // not \"where they occur\". depthWeight affects density (volume penalty) but not diversity\n // (breadth penalty). A blocking rule (score -10) penalizes diversity more than a\n // suggestion (score -1), so low-severity-only designs correctly get high diversity scores.\n let diversityScore = 100;\n if (catScore.issueCount > 0) {\n const ruleScores = ruleScorePerCategory.get(category)!;\n const weightedTriggered = Array.from(ruleScores.values()).reduce((sum, s) => sum + s, 0);\n const weightedTotal = totalScorePerCategory[category];\n const diversityRatio = weightedTotal > 0 ? weightedTriggered / weightedTotal : 0;\n diversityScore = clamp(Math.round((1 - diversityRatio) * 100), 0, 100);\n }\n catScore.diversityScore = diversityScore;\n\n // Combined score with floor\n const combinedScore = densityScore * DENSITY_WEIGHT + diversityScore * DIVERSITY_WEIGHT;\n catScore.percentage = catScore.issueCount > 0\n ? clamp(Math.round(combinedScore), SCORE_FLOOR, 100)\n : 100;\n\n catScore.score = catScore.percentage;\n catScore.maxScore = 100;\n }\n\n // Calculate overall score as simple average of categories\n // Category importance is already encoded in rule scores (weight baked in),\n // so no per-category weighting is needed.\n let categorySum = 0;\n for (const category of CATEGORIES) {\n categorySum += categoryScores[category].percentage;\n }\n\n const overallPercentage = CATEGORIES.length > 0\n ? Math.round(categorySum / CATEGORIES.length)\n : 100;\n\n // Count issues by severity\n const summary = {\n totalIssues: result.issues.length,\n blocking: 0,\n risk: 0,\n missingInfo: 0,\n suggestion: 0,\n nodeCount,\n acknowledgedCount: 0,\n };\n\n for (const issue of result.issues) {\n switch (issue.config.severity) {\n case \"blocking\":\n summary.blocking++;\n break;\n case \"risk\":\n summary.risk++;\n break;\n case \"missing-info\":\n summary.missingInfo++;\n break;\n case \"suggestion\":\n summary.suggestion++;\n break;\n }\n if (issue.acknowledged === true) summary.acknowledgedCount++;\n }\n\n return {\n overall: {\n score: overallPercentage,\n maxScore: 100,\n percentage: overallPercentage,\n grade: calculateGrade(overallPercentage),\n },\n byCategory: categoryScores,\n summary,\n };\n}\n\n/**\n * Initialize empty category scores\n */\nfunction initializeCategoryScores(): Record<Category, CategoryScoreResult> {\n const scores: Partial<Record<Category, CategoryScoreResult>> = {};\n\n for (const category of CATEGORIES) {\n scores[category] = {\n category,\n score: 100,\n maxScore: 100,\n percentage: 100,\n issueCount: 0,\n uniqueRuleCount: 0,\n weightedIssueCount: 0,\n densityScore: 100,\n diversityScore: 100,\n bySeverity: {\n blocking: 0,\n risk: 0,\n \"missing-info\": 0,\n suggestion: 0,\n },\n };\n }\n\n return scores as Record<Category, CategoryScoreResult>;\n}\n\n/**\n * Format score report as a summary string\n */\nexport function formatScoreSummary(report: ScoreReport): string {\n const lines: string[] = [];\n\n lines.push(`Overall: ${report.overall.grade} (${report.overall.percentage}%)`);\n lines.push(\"\");\n lines.push(\"By Category:\");\n\n for (const category of CATEGORIES) {\n const cat = report.byCategory[category];\n lines.push(` ${category}: ${cat.percentage}% (${cat.issueCount} issues, ${cat.uniqueRuleCount} rules)`);\n }\n\n lines.push(\"\");\n lines.push(\"Issues:\");\n lines.push(` Blocking: ${report.summary.blocking}`);\n lines.push(` Risk: ${report.summary.risk}`);\n lines.push(` Missing Info: ${report.summary.missingInfo}`);\n lines.push(` Suggestion: ${report.summary.suggestion}`);\n if (report.summary.acknowledgedCount > 0) {\n const unaddressed =\n report.summary.totalIssues - report.summary.acknowledgedCount;\n lines.push(\n ` Total: ${report.summary.totalIssues} (${report.summary.acknowledgedCount} acknowledged via canicode annotations / ${unaddressed} unaddressed)`\n );\n } else {\n lines.push(` Total: ${report.summary.totalIssues}`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Get category label for display\n */\nexport function getCategoryLabel(category: Category): string {\n return CATEGORY_LABELS[category];\n}\n\n/**\n * Get severity label for display\n */\nexport function getSeverityLabel(severity: Severity): string {\n const labels: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n };\n return labels[severity];\n}\n\n/**\n * Build a JSON-serializable analysis result summary.\n * Shared by CLI (--json) and MCP server (analyze tool response).\n */\nexport function buildResultJson(\n fileName: string,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: { fileKey?: string; designKey?: string },\n): Record<string, unknown> {\n const issuesByRule: Record<string, number> = {};\n for (const issue of result.issues) {\n const id = issue.violation.ruleId;\n issuesByRule[id] = (issuesByRule[id] ?? 0) + 1;\n }\n\n const issues = result.issues.map((issue) => {\n const applyContext = computeApplyContext(issue.violation);\n const suggestedName = issue.violation.suggestedName;\n return {\n ruleId: issue.violation.ruleId,\n detection: \"rule-based\" as const,\n outputChannel: \"score\" as const,\n persistenceIntent: \"transient\" as const,\n purpose: getRulePurpose(issue.violation.ruleId),\n ...(issue.violation.subType && { subType: issue.violation.subType }),\n severity: issue.config.severity,\n nodeId: issue.violation.nodeId,\n nodePath: issue.violation.nodePath,\n message: issue.violation.message,\n applyStrategy: applyContext.applyStrategy,\n ...(applyContext.targetProperty !== undefined\n ? { targetProperty: applyContext.targetProperty }\n : {}),\n ...(applyContext.annotationProperties !== undefined\n ? { annotationProperties: applyContext.annotationProperties }\n : {}),\n ...(suggestedName !== undefined ? { suggestedName } : {}),\n isInstanceChild: applyContext.isInstanceChild,\n ...(applyContext.sourceChildId !== undefined\n ? { sourceChildId: applyContext.sourceChildId }\n : {}),\n ...(issue.acknowledged === true ? { acknowledged: true as const } : {}),\n };\n });\n\n const json: Record<string, unknown> = {\n version: VERSION,\n analyzedAt: result.analyzedAt,\n ...(options?.fileKey && { fileKey: options.fileKey }),\n ...(options?.designKey && { designKey: options.designKey }),\n fileName,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n scope: result.scope,\n issueCount: result.issues.length,\n acknowledgedCount: scores.summary.acknowledgedCount,\n isReadyForCodeGen: isReadyForCodeGen(scores.overall.grade),\n blockingIssueCount: scores.summary.blocking,\n scores: {\n overall: scores.overall,\n categories: scores.byCategory,\n },\n issuesByRule,\n issues,\n summary: formatScoreSummary(scores),\n };\n\n if (result.failedRules.length > 0) {\n json[\"failedRules\"] = result.failedRules;\n }\n\n return json;\n}","import { z } from \"zod\";\nimport type { RuleId } from \"../contracts/rule.js\";\n\n/**\n * Gotcha question template for a single rule.\n * Used to generate user-facing surveys from analysis results (#236).\n *\n * - question: uses {nodeName} placeholder for the affected node\n * - hint: guides the user on what kind of answer is expected\n * - example: concrete example answer\n */\nexport const GotchaQuestionSchema = z.object({\n ruleId: z.string(),\n detection: z.literal(\"rule-based\"),\n outputChannel: z.literal(\"annotation\"),\n persistenceIntent: z.literal(\"durable\"),\n question: z.string(),\n hint: z.string(),\n example: z.string(),\n});\n\nexport type GotchaQuestion = z.infer<typeof GotchaQuestionSchema>;\n\n/**\n * Gotcha question mapping for all 16 rules.\n * Keyed by ruleId for O(1) lookup during survey generation.\n */\ntype GotchaQuestionContent = Omit<\n GotchaQuestion,\n \"detection\" | \"outputChannel\" | \"persistenceIntent\"\n>;\n\nconst GOTCHA_QUESTION_CONTENT: Record<RuleId, GotchaQuestionContent> = {\n // ── Pixel Critical (blocking) ──\n\n \"no-auto-layout\": {\n ruleId: \"no-auto-layout\",\n question: 'Frame \"{nodeName}\" has no Auto Layout. How should this area be laid out?',\n hint: \"Describe the flex direction, gap, and alignment\",\n example: \"Vertical flex, gap 16px, items centered\",\n },\n \"absolute-position-in-auto-layout\": {\n ruleId: \"absolute-position-in-auto-layout\",\n question: '\"{nodeName}\" uses absolute positioning inside an Auto Layout parent. Is this an intentional overlay, or should it flow with the layout?',\n hint: \"Specify if this is a badge/overlay, or should be part of the normal flow\",\n example: \"This is a notification badge — position absolute, top-right corner\",\n },\n \"non-layout-container\": {\n ruleId: \"non-layout-container\",\n question: '\"{nodeName}\" is a Group/Section used as a layout container. What layout structure should it have?',\n hint: \"Describe the intended layout: flex direction, wrap, gap\",\n example: \"Horizontal flex, gap 12px, wrap on mobile\",\n },\n\n // ── Responsive Critical (risk) ──\n\n \"fixed-size-in-auto-layout\": {\n ruleId: \"fixed-size-in-auto-layout\",\n question: '\"{nodeName}\" has a fixed size inside Auto Layout. Should it be responsive?',\n hint: \"Specify which axis should be flexible (width, height, or both)\",\n example: \"Width should FILL the parent, height can stay fixed\",\n },\n \"missing-size-constraint\": {\n ruleId: \"missing-size-constraint\",\n question: '\"{nodeName}\" uses FILL sizing without min/max constraints. What are the size boundaries?',\n hint: \"Provide min-width, max-width, or both\",\n example: \"min-width 320px, max-width 1200px\",\n },\n\n // ── Code Quality (risk) ──\n\n \"missing-component\": {\n ruleId: \"missing-component\",\n question: '\"{nodeName}\" appears to be a repeated structure. Should it be a reusable component?',\n hint: \"Describe if this should be extracted as a component and what props it needs\",\n example: \"Yes, extract as ProductCard component with title, image, and price props\",\n },\n \"detached-instance\": {\n ruleId: \"detached-instance\",\n question: '\"{nodeName}\" looks like a detached component instance. Should it use the original component or is it a new variant?',\n hint: \"Specify whether to restore the component link or create a new variant\",\n example: \"This is a new variant — create a 'compact' variant of the original component\",\n },\n \"variant-structure-mismatch\": {\n ruleId: \"variant-structure-mismatch\",\n question: '\"{nodeName}\" has variants with different child structures. Which structure is the canonical one?',\n hint: \"Describe which variant has the correct structure, or if they should all match\",\n example: \"Default variant is canonical — other variants should toggle child visibility instead of adding/removing elements\",\n },\n \"deep-nesting\": {\n ruleId: \"deep-nesting\",\n question: '\"{nodeName}\" is deeply nested. Can some intermediate layers be flattened or extracted?',\n hint: \"Identify which wrapper layers are unnecessary or should become sub-components\",\n example: \"The inner wrapper is just for spacing — flatten it and use padding instead\",\n },\n\n // ── Token Management ──\n\n \"raw-value\": {\n ruleId: \"raw-value\",\n question: '\"{nodeName}\" uses raw values without design tokens. What tokens should be used?',\n hint: \"Specify the token names or variable references for colors, fonts, spacing, etc.\",\n example: \"Use $color-primary for the fill, $font-body for the text style\",\n },\n \"irregular-spacing\": {\n ruleId: \"irregular-spacing\",\n question: '\"{nodeName}\" has spacing values that are off the design grid. What should the correct spacing be?',\n hint: \"Provide the intended spacing value aligned to the grid system\",\n example: \"Gap should be 16px (4pt grid), not 15px\",\n },\n\n // ── Interaction ──\n\n \"missing-interaction-state\": {\n ruleId: \"missing-interaction-state\",\n question: '\"{nodeName}\" appears interactive but is missing state variants. What interaction states are needed?',\n hint: \"List the needed states: Hover, Active, Disabled, Focus\",\n example: \"Needs Hover (darken 10%) and Disabled (opacity 50%, no pointer events)\",\n },\n \"missing-prototype\": {\n ruleId: \"missing-prototype\",\n question: '\"{nodeName}\" looks interactive but has no prototype interaction. What should happen on click/interaction?',\n hint: \"Describe the interaction behavior: navigation, overlay, state change, etc.\",\n example: \"On click, navigate to the product detail page\",\n },\n\n // ── Semantic ──\n\n \"non-standard-naming\": {\n ruleId: \"non-standard-naming\",\n question: '\"{nodeName}\" uses non-standard state names. What naming convention should be followed?',\n hint: \"Specify the expected state name format (e.g., Hover, Disabled, Active)\",\n example: 'Use \"Hover\" instead of \"hover_v1\", \"Disabled\" instead of \"off\"',\n },\n \"non-semantic-name\": {\n ruleId: \"non-semantic-name\",\n question: '\"{nodeName}\" has a non-semantic name. What is the purpose of this element?',\n hint: \"Provide a descriptive name that reflects the element's role in the UI\",\n example: 'Rename \"Frame 12\" to \"HeroSection\" or \"ProductGrid\"',\n },\n \"inconsistent-naming-convention\": {\n ruleId: \"inconsistent-naming-convention\",\n question: '\"{nodeName}\" uses a different naming convention than its siblings. Which convention should be used?',\n hint: \"Choose one: camelCase, kebab-case, PascalCase, or Title Case\",\n example: \"Use PascalCase for all component layers (e.g., CardTitle, CardBody)\",\n },\n};\n\n/**\n * #402: Keep 1:1 rule-keying for generation, but make the gotcha channel\n * semantics explicit in the registry itself.\n */\nexport const GOTCHA_QUESTIONS: Record<RuleId, GotchaQuestion> = Object.fromEntries(\n Object.entries(GOTCHA_QUESTION_CONTENT).map(([ruleId, content]) => [\n ruleId,\n {\n ...content,\n detection: \"rule-based\",\n outputChannel: \"annotation\",\n persistenceIntent: \"durable\",\n },\n ]),\n) as Record<RuleId, GotchaQuestion>;\n\n/**\n * Get the gotcha question for a specific rule.\n */\nexport function getGotchaQuestion(ruleId: RuleId): GotchaQuestion {\n return GOTCHA_QUESTIONS[ruleId];\n}\n\n/**\n * Format a gotcha question by replacing the {nodeName} placeholder.\n */\nexport function formatGotchaQuestion(ruleId: RuleId, nodeName: string): string {\n return GOTCHA_QUESTIONS[ruleId].question.replace(\"{nodeName}\", nodeName);\n}\n","import type {\n GotchaSurveyQuestion,\n InstanceContext,\n} from \"../contracts/gotcha-survey.js\";\nimport type { RuleId } from \"../contracts/rule.js\";\n\n/**\n * Rules whose answer is uniformly applicable to every member of a batch\n * (e.g. \"What min/max width should these layers share?\"). When N consecutive\n * questions in the same source-component group share one of these `ruleId`s,\n * the SKILL prompts the user **once** with all node names listed instead of\n * asking the same question N times.\n *\n * Maintained as an exported constant so the SKILL.md prose doesn't have to\n * keep a parallel whitelist in sync — vitest covers each rule's batch\n * behavior here, not in the LLM's prose interpretation. Add a rule here only\n * after confirming its `gotcha-question` text is actually phrased to accept a\n * single shared answer (the FILL-sizing question is, the\n * `non-semantic-name` question is not).\n */\nexport const BATCHABLE_RULE_IDS = [\n \"missing-size-constraint\",\n \"irregular-spacing\",\n \"no-auto-layout\",\n \"fixed-size-in-auto-layout\",\n] as const satisfies readonly RuleId[];\n\n/**\n * Rules whose answer is **usually** shareable across same-rule siblings but\n * may legitimately differ per node — so batching is offered as an opt-in\n * default with a per-node override escape hatch (the existing `split` verb).\n *\n * #426: `missing-prototype` on 9 sibling product cards produces 9 near-\n * identical \"Where does this navigate?\" prompts. A single shared answer (e.g.\n * \"navigates to `/product/{id}` detail page\") usually fits all of them — but\n * the user can reply `split` to answer each individually when, e.g., one card\n * opens a modal instead of a route.\n *\n * Unlike `BATCHABLE_RULE_IDS` (safe-mode — one uniform answer by definition),\n * opt-in members are rendered with an \"Apply this answer to all N?\" header\n * so the user knows the shared answer is a suggested default, not a uniform\n * truth. Grow this list one rule at a time with a justifying commit message —\n * same cadence `BATCHABLE_RULE_IDS` follows. Per ADR-016, the whitelist lives\n * here (vitest-covered) and the SKILL.md prose cites it rather than\n * duplicating it.\n */\nexport const OPT_IN_BATCHABLE_RULE_IDS = [\n \"missing-prototype\",\n] as const satisfies readonly RuleId[];\n\nconst BATCHABLE_SET: ReadonlySet<string> = new Set(BATCHABLE_RULE_IDS);\nconst OPT_IN_BATCHABLE_SET: ReadonlySet<string> = new Set(\n OPT_IN_BATCHABLE_RULE_IDS,\n);\n\nconst NO_SOURCE_SENTINEL = \"_no-source\";\n\n/**\n * Tri-state batch rendering mode consumed by `canicode-gotchas` /\n * `canicode-roundtrip` Step 3:\n *\n * - `\"safe\"` — rule is in `BATCHABLE_RULE_IDS`. One answer covers every\n * member by definition (#369).\n * - `\"opt-in\"` — rule is in `OPT_IN_BATCHABLE_RULE_IDS`. One shared answer is\n * offered as a suggested default; the user can reply `split` for per-node\n * override (#426).\n * - `\"none\"` — rule is in neither whitelist. The helper emits the question as\n * its own single-member batch; same-rule repeats stay separate so the SKILL\n * always renders the single-question template.\n */\nexport type BatchMode = \"safe\" | \"opt-in\" | \"none\";\n\nexport interface SurveyQuestionBatch {\n ruleId: string;\n /**\n * Rendering mode for this batch. `\"safe\"` and `\"opt-in\"` both imply\n * `questions.length >= 1` with a shared-prompt template; the difference is\n * whether the shared answer is uniform (`safe`) or a suggested default with\n * a per-node override escape hatch (`opt-in`). `\"none\"` guarantees\n * `questions.length === 1` — same-rule repeats for non-batchable rules do\n * not merge.\n */\n batchMode: BatchMode;\n questions: GotchaSurveyQuestion[];\n /**\n * Sum of `max(question.replicas, 1)` across members. Counts the actual\n * Figma scene fan-out so the SKILL can render `N instances` accurately\n * even when one batch member already collapses multiple replicas via the\n * #356 source-component dedupe.\n */\n totalScenes: number;\n}\n\nexport interface SurveyQuestionGroup {\n /**\n * The shared `instanceContext` for this group, or `null` for the trailing\n * group of non-instance questions. The SKILL emits the \"Instance note\"\n * header **once** per non-null group instead of once per question (#370).\n */\n instanceContext: InstanceContext | null;\n batches: SurveyQuestionBatch[];\n}\n\nexport interface GroupedSurvey {\n groups: SurveyQuestionGroup[];\n}\n\n/**\n * Pre-process a survey's `questions` array into the shape the\n * `canicode-roundtrip` and `canicode-gotchas` SKILLs need to prompt the user\n * with two UX optimizations baked in:\n *\n * - **#370** — source-component grouping. Consecutive questions sharing the\n * same `instanceContext.sourceComponentId` go in one group so the SKILL\n * prints the verbose \"Instance note\" paragraph once per group instead of\n * once per question.\n * - **#369** — batch-prompt for repeated identical answers. Within each\n * group, consecutive questions sharing the same `ruleId` *and* a\n * batchable answer-shape are collapsed into a single batch so the user\n * answers `min-width: 320px, max-width: 1200px` once instead of seven\n * times.\n *\n * Sort key is `(sourceComponentId ?? \"_no-source\", ruleId, nodeName)`. The\n * sentinel keeps non-instance questions contiguous at the end so they form\n * one trailing `instanceContext: null` group.\n *\n * `gotcha-survey` MCP/CLI returns the result on the `groupedQuestions`\n * field; the SKILL.md files iterate over `groups[].batches[]` directly with\n * no sort/partition logic in prose. See ADR-016.\n */\nexport function groupAndBatchSurveyQuestions(\n questions: readonly GotchaSurveyQuestion[],\n): GroupedSurvey {\n if (questions.length === 0) {\n return { groups: [] };\n }\n\n const sorted = [...questions].sort(compareQuestions);\n\n const groups: SurveyQuestionGroup[] = [];\n let currentGroup: SurveyQuestionGroup | null = null;\n let lastGroupKey: string | null = null;\n\n for (const question of sorted) {\n const groupKey = sourceComponentKey(question);\n if (currentGroup === null || groupKey !== lastGroupKey) {\n currentGroup = {\n instanceContext: question.instanceContext ?? null,\n batches: [],\n };\n groups.push(currentGroup);\n lastGroupKey = groupKey;\n }\n pushIntoBatch(currentGroup, question);\n }\n\n return { groups };\n}\n\nfunction compareQuestions(\n a: GotchaSurveyQuestion,\n b: GotchaSurveyQuestion,\n): number {\n const aKey = sourceComponentKey(a);\n const bKey = sourceComponentKey(b);\n if (aKey !== bKey) {\n if (aKey === NO_SOURCE_SENTINEL) return 1;\n if (bKey === NO_SOURCE_SENTINEL) return -1;\n return aKey.localeCompare(bKey);\n }\n if (a.ruleId !== b.ruleId) return a.ruleId.localeCompare(b.ruleId);\n if (a.nodeName !== b.nodeName) return a.nodeName.localeCompare(b.nodeName);\n return a.nodeId.localeCompare(b.nodeId);\n}\n\nfunction sourceComponentKey(question: GotchaSurveyQuestion): string {\n return question.instanceContext?.sourceComponentId ?? NO_SOURCE_SENTINEL;\n}\n\nfunction pushIntoBatch(\n group: SurveyQuestionGroup,\n question: GotchaSurveyQuestion,\n): void {\n const sceneWeight = Math.max(question.replicas ?? 1, 1);\n const batchMode = resolveBatchMode(question.ruleId);\n const last = group.batches.at(-1);\n\n if (\n last !== undefined &&\n last.ruleId === question.ruleId &&\n batchMode !== \"none\" &&\n last.batchMode === batchMode\n ) {\n last.questions.push(question);\n last.totalScenes += sceneWeight;\n return;\n }\n\n group.batches.push({\n ruleId: question.ruleId,\n batchMode,\n questions: [question],\n totalScenes: sceneWeight,\n });\n}\n\nfunction resolveBatchMode(ruleId: string): BatchMode {\n if (BATCHABLE_SET.has(ruleId)) return \"safe\";\n if (OPT_IN_BATCHABLE_SET.has(ruleId)) return \"opt-in\";\n return \"none\";\n}\n","import type { AnalysisResult, AnalysisIssue } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { isReadyForCodeGen } from \"../engine/scoring.js\";\nimport type {\n GotchaSurvey,\n GotchaSurveyQuestion,\n InstanceContext,\n} from \"../contracts/gotcha-survey.js\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport type { RuleId } from \"../contracts/rule.js\";\nimport { GOTCHA_QUESTIONS } from \"../rules/gotcha-questions.js\";\nimport { getRulePurpose } from \"../rules/rule-config.js\";\nimport {\n isInstanceChildNodeId,\n parseInstanceChildNodeId,\n} from \"../adapters/instance-id-parser.js\";\nimport { computeApplyContext } from \"./apply-context.js\";\nimport { groupAndBatchSurveyQuestions } from \"./group-and-batch-questions.js\";\n\nconst NODE_PATH_SEPARATOR = \" > \";\n\n/**\n * Generate a gotcha survey from analysis results.\n *\n * Filters to blocking and risk severity issues, deduplicates repeated rules\n * on sibling nodes (same parent + same ruleId), orders blocking first then\n * risk by original traversal order, and maps each issue to a survey question\n * using the GOTCHA_QUESTIONS lookup.\n */\nexport function generateGotchaSurvey(\n result: AnalysisResult,\n scores: ScoreReport,\n options: { designKey?: string } = {},\n): GotchaSurvey {\n const grade = scores.overall.grade;\n\n // Step 1: Filter to gotcha-relevant issues.\n // - `blocking` + `risk`: violation rules where the user needs to describe\n // how to resolve the violation (existing behavior).\n // - `missing-info` + purpose `info-collection` (#406): annotation-primary\n // rules like `missing-prototype` / `missing-interaction-state` where the\n // gotcha IS the output. Without this, info-collection rules would never\n // reach the survey because their penalty is intentionally minimal.\n // `suggestion` severity still stays out — it's prose-level advice, not an\n // implementation gap Figma can't encode.\n const relevantIssues = result.issues.filter((issue) => {\n const severity = issue.config.severity;\n if (severity === \"blocking\" || severity === \"risk\") return true;\n if (severity === \"missing-info\") {\n return getRulePurpose(issue.violation.ruleId) === \"info-collection\";\n }\n return false;\n });\n\n // Step 2: Deduplicate — same ruleId on siblings (same parent path) → keep first\n const deduped = deduplicateSiblingIssues(relevantIssues);\n\n // Step 3: Sort — blocking first, then risk; within same severity, preserve traversal order\n const sorted = stableSortBySeverity(deduped);\n\n // Step 4: Map to survey questions\n const mapped = sorted\n .map((issue) => mapToQuestion(issue, result.file))\n .filter((q): q is GotchaSurveyQuestion => q !== null);\n\n // Step 5 (#356): collapse N instance-child questions that share the same\n // `(sourceComponentId, sourceNodeId, ruleId)` tuple into ONE question that\n // names the source component. Apply step iterates the merged\n // `replicaNodeIds` so every replica still gets the answer; this saves the\n // user from answering the same question N times when the answer is single-\n // valued (e.g. 7 FILL children of `Platform=Desktop` all need the same\n // max-width). Cross-source-component dedupe is intentionally not done —\n // different source components stay separate.\n const questions = deduplicateBySourceComponent(mapped);\n\n // Step 6 (#369, #370, #381): pre-compute the grouped+batched view so the\n // SKILLs (`canicode-gotchas`, `canicode-roundtrip`) can iterate over it\n // directly without re-implementing sort / partition / batchable-rule\n // logic in prose. ADR-016.\n const groupedQuestions = groupAndBatchSurveyQuestions(questions);\n\n // Step 7 (#428): compute the threshold hint for the `allowDefinitionWrite`\n // picker. Count questions that target instance children — these are the only\n // candidates that benefit from definition-level writes. When fewer than 3\n // propagation candidates exist, surfacing the picker is over-engineered;\n // the skill silently uses the annotation default (ADR-012).\n const PROPAGATION_CANDIDATE_THRESHOLD = 3;\n const propagationCandidates = questions.filter(\n (q) => q.isInstanceChild,\n ).length;\n const suggestedDefaultApply =\n propagationCandidates >= PROPAGATION_CANDIDATE_THRESHOLD;\n\n return {\n designGrade: grade,\n isReadyForCodeGen: isReadyForCodeGen(grade),\n questions,\n groupedQuestions,\n designKey: options.designKey ?? \"\",\n suggestedDefaultApply,\n };\n}\n\n/**\n * Deduplicate issues where the same ruleId fires on multiple children of the\n * same parent. Keeps the first occurrence (preserving traversal order).\n *\n * #373: skip instance-child issues here. They are routed to the\n * source-component dedupe in Step 5, which preserves dropped scene ids on\n * `replicaNodeIds` so the apply step can fan the answer out to every replica.\n * The pre-#373 behaviour collapsed sibling instance children (e.g. `Title` +\n * `Subtitle` on the same `Card` instance — different definition nodes, same\n * `Card` parent path, same ruleId) into a single question and lost the\n * dropped scenes entirely (no `replicaNodeIds`, no annotation, no write).\n * Source-component dedupe naturally keeps different `sourceNodeId`s separate,\n * so the previously-dropped siblings now surface as their own questions.\n */\nfunction deduplicateSiblingIssues(issues: AnalysisIssue[]): AnalysisIssue[] {\n const seen = new Set<string>();\n const result: AnalysisIssue[] = [];\n\n for (const issue of issues) {\n if (isInstanceChildNodeId(issue.violation.nodeId)) {\n result.push(issue);\n continue;\n }\n const parentPath = getParentPath(issue.violation.nodePath);\n const key = `${parentPath}||${issue.violation.ruleId}`;\n\n if (!seen.has(key)) {\n seen.add(key);\n result.push(issue);\n }\n }\n\n return result;\n}\n\n/**\n * Extract the parent path from a full node path.\n * \"Root > Section > Child\" → \"Root > Section\"\n * \"Root\" → \"\" (root node has no parent)\n */\nfunction getParentPath(nodePath: string): string {\n const lastSep = nodePath.lastIndexOf(NODE_PATH_SEPARATOR);\n if (lastSep === -1) return \"\";\n return nodePath.slice(0, lastSep);\n}\n\n/**\n * Extract the node name from a full node path (last segment).\n * \"Root > Section > Child\" → \"Child\"\n */\nfunction getNodeName(nodePath: string): string {\n const lastSep = nodePath.lastIndexOf(NODE_PATH_SEPARATOR);\n if (lastSep === -1) return nodePath;\n return nodePath.slice(lastSep + NODE_PATH_SEPARATOR.length);\n}\n\n/**\n * Stable sort: blocking → risk → missing-info, preserving original array\n * order within each group. `missing-info` is surfaced only for\n * info-collection rules (#406), placed last because their penalty is\n * minimal; fix-describe questions for actual violations take priority.\n */\nfunction stableSortBySeverity(issues: AnalysisIssue[]): AnalysisIssue[] {\n const blocking: AnalysisIssue[] = [];\n const risk: AnalysisIssue[] = [];\n const missingInfo: AnalysisIssue[] = [];\n\n for (const issue of issues) {\n if (issue.config.severity === \"blocking\") {\n blocking.push(issue);\n } else if (issue.config.severity === \"missing-info\") {\n missingInfo.push(issue);\n } else {\n risk.push(issue);\n }\n }\n\n return [...blocking, ...risk, ...missingInfo];\n}\n\n/**\n * Map an AnalysisIssue to a GotchaSurveyQuestion using the GOTCHA_QUESTIONS table.\n * Returns null if no mapping exists for the ruleId.\n */\nfunction mapToQuestion(\n issue: AnalysisIssue,\n file: AnalysisFile,\n): GotchaSurveyQuestion | null {\n const ruleId = issue.violation.ruleId as RuleId;\n const template = GOTCHA_QUESTIONS[ruleId];\n if (!template) return null;\n\n const nodeName = getNodeName(issue.violation.nodePath);\n const instanceContext = buildInstanceContext(issue.violation.nodeId, file);\n const applyContext = computeApplyContext(\n issue.violation,\n instanceContext ?? undefined,\n );\n const suggestedName = issue.violation.suggestedName;\n\n return {\n nodeId: issue.violation.nodeId,\n nodeName,\n ruleId,\n detection: template.detection,\n outputChannel: template.outputChannel,\n persistenceIntent: template.persistenceIntent,\n purpose: getRulePurpose(issue.violation.ruleId),\n severity: issue.config.severity,\n question: template.question.replace(\"{nodeName}\", nodeName),\n hint: template.hint,\n example: template.example,\n ...(instanceContext ? { instanceContext } : {}),\n applyStrategy: applyContext.applyStrategy,\n ...(applyContext.targetProperty !== undefined\n ? { targetProperty: applyContext.targetProperty }\n : {}),\n ...(applyContext.annotationProperties !== undefined\n ? { annotationProperties: applyContext.annotationProperties }\n : {}),\n ...(suggestedName !== undefined ? { suggestedName } : {}),\n isInstanceChild: applyContext.isInstanceChild,\n ...(applyContext.sourceChildId !== undefined\n ? { sourceChildId: applyContext.sourceChildId }\n : {}),\n };\n}\n\n/**\n * Collapse questions that share the same `(sourceComponentId, sourceNodeId,\n * ruleId)` tuple. When N instance-child questions all point at the same\n * definition node inside the same source component for the same rule, the\n * answer is single-valued by definition (FILL children of `Platform=Desktop`\n * all need the same max-width) — so emit ONE question instead of N. The kept\n * question is the FIRST in the input order; subsequent matches are dropped\n * but their `nodeId`s are preserved on `replicaNodeIds` so the apply step can\n * iterate every instance scene node and land the answer on all of them.\n *\n * Out of scope: cross-source-component dedupe (e.g. \"Title\" missing-size-\n * constraint in 5 different components). Different sourceComponentIds always\n * stay separate.\n *\n * Questions without an `instanceContext` (or without both `sourceComponentId`\n * and `sourceNodeId`) are NOT touched — they pass through with no replicas\n * fields. This keeps non-instance-child questions and any partial-context\n * survivors behaving exactly as they did pre-#356.\n */\nfunction deduplicateBySourceComponent(\n questions: GotchaSurveyQuestion[],\n): GotchaSurveyQuestion[] {\n const groups = new Map<string, GotchaSurveyQuestion[]>();\n const order: string[] = [];\n let uniqueCounter = 0;\n\n for (const q of questions) {\n const ic = q.instanceContext;\n let key: string;\n if (ic && ic.sourceComponentId && ic.sourceNodeId) {\n key = `${ic.sourceComponentId}::${ic.sourceNodeId}::${q.ruleId}`;\n } else {\n // Non-deduplicable — assign a unique key so the question passes through\n // unchanged. Using a counter keeps insertion order stable.\n key = `__unique__${uniqueCounter++}`;\n }\n const bucket = groups.get(key);\n if (bucket) {\n bucket.push(q);\n } else {\n groups.set(key, [q]);\n order.push(key);\n }\n }\n\n return order.map((key) => {\n const group = groups.get(key)!;\n const first = group[0]!;\n if (group.length === 1) return first;\n\n const otherIds = group.slice(1).map((q) => q.nodeId);\n const sourceComponentName = first.instanceContext?.sourceComponentName;\n\n // Re-substitute `{nodeName}` with the source component name so the user-\n // facing question reads \"for Platform=Desktop\" instead of \"for Title\"\n // (the first instance's node name). Falls back silently when the source\n // component name was not resolved (rare — happens when the parent\n // instance's componentId is not in `file.components`).\n const template = GOTCHA_QUESTIONS[first.ruleId as RuleId];\n const renamed: GotchaSurveyQuestion = {\n ...first,\n replicas: group.length,\n replicaNodeIds: otherIds,\n };\n if (sourceComponentName) {\n renamed.nodeName = sourceComponentName;\n if (template) {\n renamed.question = template.question.replace(\n \"{nodeName}\",\n sourceComponentName,\n );\n }\n }\n return renamed;\n });\n}\n\n/**\n * Build instance context for a node id when it lives inside an instance.\n * Resolves source component name via the parent instance's componentId when\n * the parent is reachable in the analyzed subtree; falls back to the bare\n * parent/source ids otherwise so the apply pipeline can still resolve the\n * source component at runtime via `figma.getNodeById`.\n */\nfunction buildInstanceContext(\n nodeId: string,\n file: AnalysisFile,\n): InstanceContext | null {\n const parts = parseInstanceChildNodeId(nodeId);\n if (!parts) return null;\n\n const parentInstance = findNodeById(file.document, parts.parentInstanceId);\n const componentId = parentInstance?.componentId;\n const componentName = componentId ? file.components[componentId]?.name : undefined;\n\n return {\n parentInstanceNodeId: parts.parentInstanceId,\n sourceNodeId: parts.sourceNodeId,\n ...(componentId ? { sourceComponentId: componentId } : {}),\n ...(componentName ? { sourceComponentName: componentName } : {}),\n };\n}\n\n/**\n * Walk the document tree for a node id (exact match — no `-`/`:` normalization;\n * instance node ids natively use `:` and the input here is already in that form).\n */\nfunction findNodeById(node: AnalysisNode, id: string): AnalysisNode | null {\n if (node.id === id) return node;\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, id);\n if (found) return found;\n }\n }\n return null;\n}\n","// Shared UI constants — single source of truth for report-html (Node) and app/shared (browser)\n\nimport type { Category } from \"./contracts/category.js\";\nimport type { Severity } from \"./contracts/severity.js\";\n\n// Re-export category/severity constants that already exist\nexport { CATEGORIES, CATEGORY_LABELS } from \"./contracts/category.js\";\nexport { SEVERITY_LABELS } from \"./contracts/severity.js\";\n\n// Gauge geometry\nexport const GAUGE_R = 54;\nexport const GAUGE_C = Math.round(2 * Math.PI * GAUGE_R); // ~339\n\nexport const CATEGORY_DESCRIPTIONS: Record<Category, string> = {\n \"pixel-critical\":\n \"Auto Layout, absolute positioning, group usage — layout issues that directly affect pixel accuracy\",\n \"responsive-critical\":\n \"Fixed sizing, size constraints, responsive behavior — issues that break at different viewports\",\n \"code-quality\":\n \"Component reuse, detached instances, variant structure, nesting depth\",\n \"token-management\":\n \"Design token binding for colors, fonts, shadows, opacity, spacing grid\",\n \"interaction\":\n \"State variants for interactive components — hover, disabled, active, focus\",\n \"semantic\":\n \"Semantic layer names, naming conventions, default names\",\n};\n\nexport const SEVERITY_ORDER: Severity[] = [\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n];\n","// Shared UI helper functions — single source of truth for report-html (Node) and app/shared (browser)\n// All functions here must be pure (no Node.js or DOM dependencies)\n\nimport type { Severity } from \"./contracts/severity.js\";\nimport { GAUGE_R, GAUGE_C } from \"./ui-constants.js\";\n\n/** Map a percentage score to a color hex string */\nexport function gaugeColor(pct: number): string {\n if (pct >= 75) return \"#22c55e\";\n if (pct >= 50) return \"#f59e0b\";\n return \"#ef4444\";\n}\n\n/** Map a percentage score to a color class name (green/amber/red) */\nexport function scoreClass(pct: number): string {\n if (pct >= 75) return \"green\";\n if (pct >= 50) return \"amber\";\n return \"red\";\n}\n\n/** Escape HTML special characters — works in both Node.js and browser */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n\n/** Severity to CSS modifier class (used with .rpt-dot, .rpt-issue-score) */\nexport function severityDot(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Severity to CSS modifier class (used with .rpt-issue-score) */\nexport function severityBadge(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Score percentage to CSS modifier class (used with .rpt-badge) */\nexport function scoreBadgeStyle(pct: number): string {\n if (pct >= 75) return \"score-green\";\n if (pct >= 50) return \"score-amber\";\n return \"score-red\";\n}\n\n/** Render a circular gauge SVG string — works in both Node.js and browser */\nexport function renderGaugeSvg(\n pct: number,\n size: number,\n strokeW: number,\n grade?: string\n): string {\n const offset = GAUGE_C * (1 - pct / 100);\n const color = gaugeColor(pct);\n if (grade) {\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"60\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"48\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${escapeHtml(grade)}</text>\n </svg>`;\n }\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"62\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"28\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${pct}</text>\n </svg>`;\n}\n","/**\n * Pure template functions for report HTML rendering.\n * No Node.js dependencies — usable in browser via CanICode.* globals.\n *\n * Single source of truth for all report UI:\n * - CLI: generateHtmlReport() wraps with <html> shell\n * - Web app: CanICode.renderReportBody() → innerHTML\n * - Figma plugin: CanICode.renderReportBody() → innerHTML\n *\n * Layout: category tabs → rule sections (static info) → node accordion (dynamic info)\n * Styled via self-contained CSS (app/shared/styles.css) — no Tailwind dependency.\n */\n\nimport type { Category } from \"../contracts/category.js\";\nimport type { AnalysisIssue } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { version as VERSION } from \"../../../package.json\";\nimport { buildFigmaDeepLink } from \"../adapters/figma-url-parser.js\";\nimport {\n CATEGORIES,\n CATEGORY_LABELS,\n} from \"../ui-constants.js\";\nimport {\n escapeHtml,\n severityDot,\n severityBadge,\n renderGaugeSvg,\n} from \"../ui-helpers.js\";\n\n// ---- Data interface ----\n\nexport interface ReportData {\n fileName: string;\n fileKey: string;\n scores: ScoreReport;\n issues: AnalysisIssue[];\n nodeCount: number;\n maxDepth: number;\n figmaToken?: string;\n}\n\n/** Issues grouped by rule within a category */\ninterface RuleGroup {\n ruleId: string;\n ruleName: string;\n severity: string;\n severityClass: string;\n why: string;\n impact: string;\n fix: string;\n issues: AnalysisIssue[];\n totalScore: number;\n}\n\n// ---- Main render ----\n\n/**\n * Render the report body content (everything inside <main>).\n * Does NOT include <html>, <head>, <body> — caller wraps as needed.\n */\nexport function renderReportBody(data: ReportData): string {\n const { scores, issues, fileKey, figmaToken } = data;\n const issuesByCategory = groupIssuesByCategory(issues);\n const ruleOpportunities = getTopRules(issues, 5);\n\n return `\n <!-- Overall Score -->\n <section class=\"rpt-overall\">\n ${renderGaugeSvg(scores.overall.percentage, 200, 10, scores.overall.grade)}\n <div class=\"rpt-score\">\n <span class=\"rpt-score-value\">${scores.overall.percentage}</span>\n <span class=\"rpt-score-max\">/ 100</span>\n </div>\n <p class=\"rpt-score-label\">Overall Score</p>\n </section>\n\n <!-- Category Gauges -->\n <section class=\"card rpt-gauges\">\n <div class=\"rpt-gauges-grid\">\n${CATEGORIES.map((cat) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" class=\"rpt-gauge-item\" data-tab=\"${cat}\">\n ${renderGaugeSvg(cs.percentage, 100, 7)}\n <span class=\"rpt-gauge-label\">${CATEGORY_LABELS[cat]}</span>\n <span class=\"rpt-gauge-count\">${cs.issueCount} issues</span>\n </button>`;\n }).join(\"\\n\")}\n </div>\n </section>\n\n <!-- Issue Summary -->\n <section class=\"card rpt-summary\">\n <div class=\"rpt-summary-inner\">\n ${renderSummaryDot(\"sev-blocking\", scores.summary.blocking, \"Blocking\")}\n ${renderSummaryDot(\"sev-risk\", scores.summary.risk, \"Risk\")}\n ${renderSummaryDot(\"sev-missing\", scores.summary.missingInfo, \"Missing Info\")}\n ${renderSummaryDot(\"sev-suggestion\", scores.summary.suggestion, \"Suggestion\")}\n <div class=\"rpt-summary-total\">\n <span class=\"rpt-summary-count\">${scores.summary.totalIssues}</span>\n <span class=\"rpt-summary-label\">Total</span>\n </div>\n </div>\n </section>\n\n${ruleOpportunities.length > 0 ? renderOpportunities(ruleOpportunities) : \"\"}\n\n <!-- Category Tabs -->\n <div class=\"rpt-tabs\">\n <div class=\"rpt-tab-list\" role=\"tablist\">\n${CATEGORIES.map((cat, i) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" role=\"tab\" class=\"rpt-tab${i === 0 ? \" active\" : \"\"}\" data-tab=\"${cat}\" aria-selected=\"${i === 0}\">${CATEGORY_LABELS[cat]} <span class=\"rpt-tab-count\">${cs.issueCount}</span></button>`;\n }).join(\"\\n\")}\n </div>\n\n${CATEGORIES.map((cat, i) => {\n const catIssues = issuesByCategory.get(cat) ?? [];\n const ruleGroups = groupIssuesByRule(catIssues);\n return ` <div class=\"rpt-tab-panel${i === 0 ? \" active\" : \"\"}\" data-panel=\"${cat}\" role=\"tabpanel\">\n${ruleGroups.length === 0\n ? ' <div class=\"rpt-cat-empty\">No issues found</div>'\n : ruleGroups.map(rg => renderRuleSection(rg, fileKey, figmaToken)).join(\"\\n\")\n}\n </div>`;\n }).join(\"\\n\")}\n </div>\n\n <!-- Footer -->\n <footer class=\"rpt-footer\">\n <p class=\"rpt-footer-main\"><strong>CanICode</strong> <span style=\"opacity:0.5\">v${VERSION}</span></p>\n <p class=\"rpt-footer-meta\">${new Date().toLocaleString()} · ${data.nodeCount} nodes · Max depth ${data.maxDepth}</p>\n <p class=\"rpt-footer-links\"><a href=\"https://github.com/let-sunny/canicode/issues\" target=\"_blank\" rel=\"noopener\">Feedback</a> <span style=\"opacity:0.3\">&middot;</span> <a href=\"https://github.com/let-sunny/canicode/discussions/new?category=share-your-figma\" target=\"_blank\" rel=\"noopener\">Share your Figma</a></p>\n </footer>`;\n}\n\n// ---- Components ----\n\nexport function renderSummaryDot(sevClass: string, count: number, label: string): string {\n return `<div class=\"rpt-summary-item\">\n <span class=\"rpt-dot ${sevClass}\"></span>\n <span class=\"rpt-summary-count\">${count}</span>\n <span class=\"rpt-summary-label\">${label}</span>\n </div>`;\n}\n\nexport function renderOpportunities(ruleGroups: RuleGroup[]): string {\n const maxAbs = ruleGroups.reduce((m, rg) => Math.max(m, Math.abs(rg.totalScore)), 1);\n return `\n <!-- Opportunities -->\n <section class=\"card rpt-opps\">\n <div class=\"rpt-opps-header\">\n <h2 class=\"rpt-opps-title\">\n <span class=\"rpt-dot sev-blocking\"></span>\n Opportunities\n </h2>\n <p class=\"rpt-opps-desc\">Top impact rules — fix these first for the biggest improvement.</p>\n </div>\n <div class=\"rpt-opps-list\">\n${ruleGroups.map(rg => {\n const barW = Math.round((Math.abs(rg.totalScore) / maxAbs) * 100);\n const cat = rg.issues[0]?.rule.definition.category ?? \"\";\n return ` <div class=\"rpt-opps-item\" data-opp-rule=\"${esc(rg.ruleId)}\" data-opp-cat=\"${cat}\" style=\"cursor:pointer\">\n <div class=\"rpt-opps-info\">\n <div class=\"rpt-opps-name\">${esc(rg.ruleName)}</div>\n <div class=\"rpt-opps-msg\">${rg.issues.length} issues</div>\n </div>\n <div class=\"rpt-opps-bar-wrap\">\n <div class=\"rpt-opps-bar\">\n <div class=\"rpt-opps-bar-fill\" style=\"width:${barW}%\"></div>\n </div>\n <span class=\"rpt-opps-score\">${rg.totalScore}</span>\n </div>\n </div>`;\n }).join(\"\\n\")}\n </div>\n </section>`;\n}\n\nexport function renderRuleSection(\n rg: RuleGroup,\n fileKey: string,\n figmaToken?: string\n): string {\n const isOpen = rg.severity === \"blocking\" || rg.severity === \"risk\";\n return ` <details class=\"card rpt-rule\" data-rule=\"${esc(rg.ruleId)}\"${isOpen ? \" open\" : \"\"}>\n <summary class=\"rpt-rule-header\">\n <span class=\"rpt-badge score-red\">${rg.totalScore}</span>\n <span class=\"rpt-rule-title\">\n <span class=\"rpt-rule-name\">${esc(rg.ruleName)}</span>\n <span class=\"rpt-rule-meta\">\n <span class=\"rpt-dot-sm ${rg.severityClass}\"></span>\n ${esc(rg.severity)} · ${rg.issues.length} issues\n </span>\n <span class=\"rpt-rule-info\">\n <span class=\"rpt-rule-info-line\"><strong>Why:</strong> ${esc(rg.why)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Impact:</strong> ${esc(rg.impact)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Fix:</strong> ${esc(rg.fix)}</span>\n </span>\n </span>\n <svg class=\"rpt-rule-chevron no-print\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M19 9l-7 7-7-7\"/></svg>\n </summary>\n <div class=\"rpt-rule-issues\">\n${rg.issues.map(issue => renderIssueRow(issue, fileKey, figmaToken)).join(\"\\n\")}\n </div>\n </details>`;\n}\n\nexport function renderIssueRow(\n issue: AnalysisIssue,\n fileKey: string,\n figmaToken?: string\n): string {\n const sev = issue.config.severity;\n const v = issue.violation;\n const link = buildFigmaDeepLink(fileKey, v.nodeId);\n\n return ` <details class=\"rpt-issue\">\n <summary class=\"rpt-issue-header\">\n <span class=\"rpt-issue-msg\">${esc(v.message)}</span>\n <span class=\"rpt-issue-score ${severityBadge(sev)}\">${issue.calculatedScore}</span>\n </summary>\n <div class=\"rpt-issue-body\">\n <div class=\"rpt-issue-suggestion\">${esc(v.suggestion)}</div>${v.guide ? `\n <div class=\"rpt-issue-guide\">${esc(v.guide)}</div>` : \"\"}\n <div class=\"rpt-issue-path\">${esc(v.nodePath)}</div>\n <div class=\"rpt-issue-actions no-print\">\n <a href=\"${link}\" target=\"_blank\" rel=\"noopener\" data-node-id=\"${esc(v.nodeId)}\" class=\"rpt-btn\">Go to node <span>→</span></a>${figmaToken ? `\n <button onclick=\"postComment(this)\" data-file-key=\"${esc(fileKey)}\" data-node-id=\"${esc(v.nodeId)}\" data-message=\"${esc(v.message)} — ${esc(v.suggestion)}\" class=\"rpt-btn\">Comment on Figma</button>` : \"\"}\n </div>\n </div>\n </details>`;\n}\n\n// ---- Interactions ----\n\n/**\n * Initialize tab switching + navigation for a rendered report.\n * Call after inserting renderReportBody() HTML into a container.\n * Uses 'any' to avoid DOM type dependency (this file targets Node.js).\n */\nexport function initReportInteractions(container: any): void {\n // Remove previous handler if re-initialized (e.g., re-analysis)\n if (container._rptHandler) {\n container.removeEventListener(\"click\", container._rptHandler);\n }\n function activate(cat: string, scrollTo: boolean) {\n container.querySelectorAll(\".rpt-tab\").forEach((t: any) => {\n const active = t.dataset.tab === cat;\n t.classList.toggle(\"active\", active);\n t.setAttribute(\"aria-selected\", String(active));\n });\n container.querySelectorAll(\".rpt-tab-panel\").forEach((p: any) => {\n p.classList.toggle(\"active\", p.dataset.panel === cat);\n });\n if (scrollTo) {\n const tabList = container.querySelector(\".rpt-tab-list\");\n if (tabList) tabList.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n }\n }\n function focusRule(ruleId: string) {\n const el = container.querySelector('[data-rule=\"' + ruleId + '\"]');\n if (el) {\n el.open = true;\n setTimeout(() => el.scrollIntoView({ behavior: \"smooth\", block: \"start\" }), 50);\n }\n }\n const handler = (e: any) => {\n const tab = e.target.closest(\"[data-tab]\");\n if (tab) {\n const isGauge = tab.classList.contains(\"rpt-gauge-item\");\n activate(tab.dataset.tab ?? \"\", isGauge);\n return;\n }\n const opp = e.target.closest(\"[data-opp-rule]\");\n if (opp) {\n const cat = opp.dataset.oppCat ?? \"\";\n const rule = opp.dataset.oppRule ?? \"\";\n if (cat) activate(cat, false);\n setTimeout(() => focusRule(rule), 50);\n }\n };\n container._rptHandler = handler;\n container.addEventListener(\"click\", handler);\n}\n\n// ---- Utils ----\n\n/** Get top N rules by total score impact */\nfunction getTopRules(issues: AnalysisIssue[], limit: number): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n return [...byRule.values()]\n .sort((a, b) => a.totalScore - b.totalScore)\n .slice(0, limit);\n}\n\nfunction groupIssuesByCategory(issues: AnalysisIssue[]): Map<Category, AnalysisIssue[]> {\n const grouped = new Map<Category, AnalysisIssue[]>();\n for (const category of CATEGORIES) grouped.set(category, []);\n for (const issue of issues) grouped.get(issue.rule.definition.category)!.push(issue);\n return grouped;\n}\n\n/** Group issues by rule within a category, sorted by severity then score */\nfunction groupIssuesByRule(issues: AnalysisIssue[]): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n\n const SEVERITY_RANK: Record<string, number> = { blocking: 0, risk: 1, \"missing-info\": 2, suggestion: 3 };\n return [...byRule.values()].sort((a, b) => {\n const sevDiff = (SEVERITY_RANK[a.severity] ?? 4) - (SEVERITY_RANK[b.severity] ?? 4);\n return sevDiff !== 0 ? sevDiff : a.totalScore - b.totalScore;\n });\n}\n\nconst esc = escapeHtml;\n","// Report HTML module — full page generation for CLI\n// Rendering logic lives in render.ts (shared with web/plugin)\n\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\nimport type { AnalysisResult } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { escapeHtml } from \"../ui-helpers.js\";\nimport { renderReportBody, initReportInteractions } from \"./render.js\";\nimport type { ReportData } from \"./render.js\";\n\ndeclare const __REPORT_CSS__: string;\nconst reportCss: string = __REPORT_CSS__;\n\nexport type { ReportData } from \"./render.js\";\nexport { renderReportBody, initReportInteractions } from \"./render.js\";\n\nexport interface NodeScreenshot {\n nodeId: string;\n nodePath: string;\n screenshotBase64: string;\n issueCount: number;\n topSeverity: string;\n}\n\nexport interface HtmlReportOptions {\n nodeScreenshots?: NodeScreenshot[];\n figmaToken?: string | undefined;\n}\n\nconst esc = escapeHtml;\n\n/**\n * Generate a complete standalone HTML report page.\n * Used by CLI — opens in browser.\n */\nexport function generateHtmlReport(\n file: AnalysisFile,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: HtmlReportOptions\n): string {\n const figmaToken = options?.figmaToken;\n\n const data: ReportData = {\n fileName: file.name,\n fileKey: file.fileKey,\n scores,\n issues: result.issues,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n ...(figmaToken && { figmaToken }),\n };\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>CanICode Report — ${esc(file.name)}</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap\" rel=\"stylesheet\">\n <style>\n${reportCss}\n .cli-topbar {\n background: #09090b; color: white;\n border-bottom: 1px solid #27272a;\n }\n .cli-topbar-inner {\n max-width: 960px; margin: 0 auto;\n padding: 12px 24px;\n display: flex; align-items: center; gap: 16px;\n }\n .cli-topbar-logo { font-weight: 600; font-size: 14px; letter-spacing: -0.01em; }\n .cli-topbar-file { color: #a1a1aa; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .cli-topbar-date { margin-left: auto; color: #71717a; font-size: 12px; }\n .cli-main { max-width: 960px; margin: 0 auto; padding: 0 24px 64px; }\n @media print {\n .cli-topbar { position: static !important; background: white !important; color: var(--fg) !important; }\n .cli-topbar-file { color: var(--fg-muted) !important; }\n }\n </style>\n</head>\n<body>\n\n <!-- Top Bar -->\n <header class=\"cli-topbar\">\n <div class=\"cli-topbar-inner\">\n <span class=\"cli-topbar-logo\">CanICode</span>\n <span class=\"cli-topbar-file\">${esc(file.name)}</span>\n <span class=\"cli-topbar-date no-print\">${new Date().toLocaleDateString()}</span>\n </div>\n </header>\n\n <main class=\"cli-main\">\n${renderReportBody(data)}\n </main>\n\n <script>(${String(initReportInteractions)})(document.querySelector('.cli-main'));</script>\n${figmaToken ? renderFigmaCommentScript(figmaToken) : \"\"}\n</body>\n</html>`;\n}\n\nfunction renderFigmaCommentScript(figmaToken: string): string {\n return ` <script>\n const FIGMA_TOKEN = '${figmaToken}';\n async function postComment(btn) {\n const fileKey = btn.dataset.fileKey;\n const nodeId = btn.dataset.nodeId.replace(/-/g, ':');\n const commentNodeId = nodeId.split(';')[0].replace(/^I/, '');\n const message = btn.dataset.message;\n const commentBody = '[CanICode] ' + message;\n btn.disabled = true;\n btn.textContent = 'Sending...';\n btn.title = '';\n try {\n const res = await fetch('https://api.figma.com/v1/files/' + fileKey + '/comments', {\n method: 'POST',\n headers: { 'X-FIGMA-TOKEN': FIGMA_TOKEN, 'Content-Type': 'application/json' },\n body: JSON.stringify({ message: commentBody, client_meta: { node_id: commentNodeId, node_offset: { x: 0, y: 0 } } }),\n });\n if (!res.ok) {\n const errBody = await res.text().catch(() => '');\n const errMsg = res.status === 400 ? 'Bad request' : res.status === 403 ? 'Token lacks file access' : res.status === 404 ? 'File not found' : res.status === 429 ? 'Rate limited' : 'HTTP ' + res.status;\n throw new Error(errMsg + (errBody ? ': ' + errBody.slice(0, 100) : ''));\n }\n btn.textContent = 'Sent';\n btn.classList.remove('rpt-btn-fail');\n btn.classList.add('rpt-btn-ok');\n } catch (e) {\n btn.textContent = 'Failed';\n btn.title = e.message || String(e);\n btn.classList.remove('rpt-btn-ok');\n btn.classList.add('rpt-btn-fail');\n btn.disabled = false;\n }\n }\n </script>`;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { SeveritySchema } from \"../contracts/severity.js\";\nimport type { RuleConfig } from \"../contracts/rule.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\nconst VALID_RULE_IDS = new Set(Object.keys(RULE_CONFIGS));\n\nconst RuleOverrideSchema = z.object({\n score: z.number().int().max(0).optional(),\n severity: SeveritySchema.optional(),\n enabled: z.boolean().optional(),\n});\n\nconst ConfigFileSchema = z.object({\n excludeNodeTypes: z.array(z.string()).optional(),\n excludeNodeNames: z.array(z.string()).optional(),\n gridBase: z.number().int().positive().optional(),\n rules: z.record(z.string(), RuleOverrideSchema)\n .superRefine((rules, ctx) => {\n const unknown = Object.keys(rules).filter((id) => !VALID_RULE_IDS.has(id));\n if (unknown.length > 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Unknown rule ID(s): ${unknown.join(\", \")}. Valid IDs: ${[...VALID_RULE_IDS].join(\", \")}`,\n });\n }\n })\n .optional(),\n});\n\nexport type ConfigFile = z.infer<typeof ConfigFileSchema>;\n\nexport async function loadConfigFile(filePath: string): Promise<ConfigFile> {\n const absPath = resolve(filePath);\n const raw = await readFile(absPath, \"utf-8\");\n const parsed: unknown = JSON.parse(raw);\n return ConfigFileSchema.parse(parsed);\n}\n\n/**\n * Merge config overrides into the base rule configs\n */\nexport function mergeConfigs(\n base: Record<string, RuleConfig>,\n overrides: ConfigFile,\n): Record<string, RuleConfig> {\n const merged = { ...base };\n\n // Apply global gridBase to relevant rules\n if (overrides.gridBase !== undefined) {\n for (const [id, config] of Object.entries(merged)) {\n if (config.options && \"gridBase\" in config.options) {\n merged[id] = {\n ...config,\n options: { ...config.options, gridBase: overrides.gridBase },\n };\n }\n }\n }\n\n // Apply per-rule overrides\n if (overrides.rules) {\n for (const [ruleId, override] of Object.entries(overrides.rules)) {\n const existing = merged[ruleId];\n if (existing) {\n merged[ruleId] = {\n ...existing,\n ...(override.score !== undefined && { score: override.score }),\n ...(override.severity !== undefined && { severity: override.severity }),\n ...(override.enabled !== undefined && { enabled: override.enabled }),\n };\n }\n }\n }\n\n return merged;\n}\n","/**\n * Typed event definitions for PostHog analytics.\n * All events are prefixed with `cic_` (CanICode) to distinguish\n * from noise/spam in PostHog dashboards.\n *\n * Only event metadata is tracked — no design data, tokens, or file contents.\n */\n\n/** Event name prefix — use this to filter genuine events in PostHog */\nexport const EVENT_PREFIX = \"cic_\";\n\nexport const EVENTS = {\n // Analysis\n ANALYSIS_STARTED: `${EVENT_PREFIX}analysis_started`,\n ANALYSIS_COMPLETED: `${EVENT_PREFIX}analysis_completed`,\n ANALYSIS_FAILED: `${EVENT_PREFIX}analysis_failed`,\n\n // Report\n REPORT_GENERATED: `${EVENT_PREFIX}report_generated`,\n COMMENT_POSTED: `${EVENT_PREFIX}comment_posted`,\n COMMENT_FAILED: `${EVENT_PREFIX}comment_failed`,\n\n // MCP\n MCP_TOOL_CALLED: `${EVENT_PREFIX}mcp_tool_called`,\n\n // CLI\n CLI_COMMAND: `${EVENT_PREFIX}cli_command`,\n CLI_INIT: `${EVENT_PREFIX}cli_init`,\n\n // Roundtrip (ADR-012)\n // Wiring point for the roundtrip helper's `telemetry` callback. No Node-side\n // orchestrator reads this yet — the helper ships in a sandbox-pure IIFE that\n // cannot import `core/monitoring` directly, so the event fires through a\n // caller-supplied callback. Define the typed name here so a future consumer\n // has a single place to wire it up.\n ROUNDTRIP_DEFINITION_WRITE_SKIPPED: `${EVENT_PREFIX}roundtrip_definition_write_skipped`,\n /** CLI `canicode roundtrip-tally` completed successfully. */\n ROUNDTRIP_TALLY: `${EVENT_PREFIX}roundtrip_tally`,\n} as const;\n\nexport type EventName = (typeof EVENTS)[keyof typeof EVENTS];\n","/**\n * Unified fetch-based monitoring capture for all environments (CLI, MCP, browser, plugin).\n *\n * No external dependencies — uses native `fetch` (Node 18+ / browser).\n * All operations are fire-and-forget; never throws.\n */\n\nimport type { MonitoringConfig } from \"./types.js\";\n\nlet monitoringEnabled = false;\nlet posthogApiKey: string | undefined;\nlet sentryDsn: string | undefined;\nlet distinctId = \"anonymous\";\nlet environment = \"unknown\";\nlet version = \"unknown\";\nlet commonProps: Record<string, unknown> = {};\n\n/** Generate a simple UUID v4 (no crypto dependency needed for monitoring) */\nfunction uuid4(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/** Parse Sentry DSN into components */\nfunction parseSentryDsn(dsn: string): { key: string; host: string; projectId: string } | null {\n try {\n // DSN format: https://{key}@{host}/{projectId}\n const url = new URL(dsn);\n const key = url.username;\n const projectId = url.pathname.slice(1); // remove leading /\n const host = url.protocol + \"//\" + url.host;\n if (!key || !projectId) return null;\n return { key, host, projectId };\n } catch {\n return null;\n }\n}\n\nexport function initCapture(config: MonitoringConfig): void {\n if (config.enabled === false) return;\n if (!config.posthogApiKey && !config.sentryDsn) return;\n\n monitoringEnabled = true;\n posthogApiKey = config.posthogApiKey;\n sentryDsn = config.sentryDsn;\n distinctId = config.distinctId ?? \"anonymous\";\n environment = config.environment ?? \"unknown\";\n version = config.version ?? \"unknown\";\n commonProps = {\n _sdk: \"canicode\",\n _sdk_version: version,\n _env: environment,\n };\n}\n\nexport function captureEvent(event: string, properties?: Record<string, unknown>): void {\n if (!monitoringEnabled || !posthogApiKey) return;\n\n try {\n fetch(\"https://us.i.posthog.com/i/v0/e/\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n api_key: posthogApiKey,\n event,\n distinct_id: distinctId,\n properties: { ...commonProps, ...properties },\n timestamp: new Date().toISOString(),\n }),\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n}\n\nexport function captureError(error: Error, context?: Record<string, unknown>): void {\n if (!monitoringEnabled) return;\n\n // Send to Sentry via envelope API\n if (sentryDsn) {\n const parsed = parseSentryDsn(sentryDsn);\n if (parsed) {\n try {\n const eventId = uuid4();\n const envelope = [\n JSON.stringify({ event_id: eventId, sent_at: new Date().toISOString(), dsn: sentryDsn }),\n JSON.stringify({ type: \"event\", content_type: \"application/json\" }),\n JSON.stringify({\n event_id: eventId,\n exception: { values: [{ type: error.name, value: error.message }] },\n platform: \"node\",\n environment,\n release: `canicode@${version}`,\n timestamp: Date.now() / 1000,\n extra: context,\n }),\n ].join(\"\\n\");\n\n fetch(`${parsed.host}/api/${parsed.projectId}/envelope/`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-sentry-envelope\",\n \"X-Sentry-Auth\": `Sentry sentry_version=7, sentry_key=${parsed.key}`,\n },\n body: envelope,\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n }\n }\n\n // Also send to PostHog as error event\n captureEvent(\"cic_error\", { error: error.message, ...context });\n}\n\nexport function shutdownCapture(): void {\n monitoringEnabled = false;\n posthogApiKey = undefined;\n sentryDsn = undefined;\n distinctId = \"anonymous\";\n environment = \"unknown\";\n version = \"unknown\";\n commonProps = {};\n}\n","/**\n * Shared monitoring module that works across CLI, MCP, and browser environments.\n *\n * Key design principles:\n * - If no API keys are configured, all functions are silent no-ops\n * - All tracking is fire-and-forget (never blocks or throws)\n * - Zero external dependencies — uses native fetch (Node 18+ / browser)\n * - CLI users can opt out via `canicode config --no-telemetry`\n * - No design data, tokens, or file contents are ever sent\n */\n\nexport type { MonitoringConfig } from \"./types.js\";\nexport { EVENTS } from \"./events.js\";\nexport type { EventName } from \"./events.js\";\n\nimport type { MonitoringConfig } from \"./types.js\";\nimport { initCapture, captureEvent, captureError, shutdownCapture } from \"./capture.js\";\n\n/**\n * Initialise monitoring for the current environment.\n * Safe to call multiple times — subsequent calls are ignored.\n */\nexport function initMonitoring(config: MonitoringConfig): void {\n initCapture(config);\n}\n\n/**\n * Track an analytics event. Fire-and-forget; never throws.\n */\nexport function trackEvent(event: string, properties?: Record<string, unknown>): void {\n try {\n captureEvent(event, properties);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Track an error. Fire-and-forget; never throws.\n */\nexport function trackError(error: Error, context?: Record<string, unknown>): void {\n try {\n captureError(error, context);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Shut down monitoring. Call before process exit.\n */\nexport function shutdownMonitoring(): void {\n try {\n shutdownCapture();\n } catch {\n // never throw from monitoring\n }\n}\n","/**\n * Monitoring keys injected at build time via tsup `define`.\n * These are replaced with actual values during CI builds.\n * Locally they default to empty strings (monitoring disabled).\n */\n\ndeclare const __POSTHOG_API_KEY__: string;\ndeclare const __SENTRY_DSN__: string;\n\nexport const POSTHOG_API_KEY: string =\n typeof __POSTHOG_API_KEY__ !== \"undefined\" ? __POSTHOG_API_KEY__ : \"\";\nexport const SENTRY_DSN: string =\n typeof __SENTRY_DSN__ !== \"undefined\" ? __SENTRY_DSN__ : \"\";\n","import { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { parseFigmaUrl } from \"../adapters/figma-url-parser.js\";\n\n/**\n * Local copy of `isFigmaUrl` (lives in `core/engine/loader.ts`). Inlined to\n * avoid a contracts/ → engine/ dependency cycle: contracts/ is meant to be\n * importable by every other layer, including engine/.\n */\nfunction isFigmaUrl(input: string): boolean {\n return input.includes(\"figma.com/\");\n}\n\nexport const DesignKeySchema = z.string();\nexport type DesignKey = z.infer<typeof DesignKeySchema>;\n\n/**\n * Compute the canonical `designKey` that uniquely identifies a design across\n * canicode runs.\n *\n * - **Figma URL** → `<fileKey>#<nodeId>` with `-` → `:` normalization on the\n * nodeId (matching the Figma MCP convention). Example:\n * `https://figma.com/design/abc123/My-File?node-id=42-100&t=ref` →\n * `abc123#42:100`. Trailing query parameters other than `node-id`\n * (`?t=...`, `?mode=...`) are dropped — they would otherwise break\n * string-matching on re-runs.\n * - **Figma URL without `node-id`** → just `<fileKey>` (file-level key).\n * - **Anything else** (fixture directory, JSON path, raw filename) →\n * absolute path via `node:path.resolve(input)`. Keeps fixture-based\n * smoke tests stable across cwd.\n *\n * Both `gotcha-survey` and `analyze` MCP/CLI tools surface the result on\n * their response's top-level `designKey` field. The `canicode-gotchas` and\n * `canicode-roundtrip` SKILLs read that field directly — neither one\n * re-implements URL parsing in prose anymore (per ADR-016).\n */\nexport function computeDesignKey(input: string): string {\n if (isFigmaUrl(input)) {\n const { fileKey, nodeId } = parseFigmaUrl(input);\n if (!nodeId) return fileKey;\n return `${fileKey}#${nodeId.replace(/-/g, \":\")}`;\n }\n return resolve(input);\n}\n","/**\n * Centralized node semantic classification.\n * All \"what is this node?\" logic lives here so rules share the same predicates.\n *\n * Categories:\n * - Container: layout containers (frame, group, component, instance)\n * - Visual: decorative/graphic elements (vector, shape, image)\n * - Interactive: user-interactable elements (button, link, tab, input, toggle)\n * - Overlay: elements that open on top (modal, drawer, dropdown)\n * - Carousel: elements that slide/swipe (carousel, slider, gallery)\n * - Token: style/variable binding checks\n * - Naming: name pattern classification\n */\n\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\n\n// ── Container classification ─────────────────────────────────────────────────\n\nexport function isContainerNode(node: AnalysisNode): boolean {\n return node.type === \"FRAME\" || node.type === \"GROUP\" || node.type === \"COMPONENT\" || node.type === \"INSTANCE\";\n}\n\nexport function hasAutoLayout(node: AnalysisNode): boolean {\n return node.layoutMode !== undefined && node.layoutMode !== \"NONE\";\n}\n\nexport function hasTextContent(node: AnalysisNode): boolean {\n return node.type === \"TEXT\" || (node.children?.some((c) => c.type === \"TEXT\") ?? false);\n}\n\nexport function hasOverlappingBounds(a: AnalysisNode, b: AnalysisNode): boolean {\n const boxA = a.absoluteBoundingBox;\n const boxB = b.absoluteBoundingBox;\n\n if (!boxA || !boxB) return false;\n\n return !(\n boxA.x + boxA.width <= boxB.x ||\n boxB.x + boxB.width <= boxA.x ||\n boxA.y + boxA.height <= boxB.y ||\n boxB.y + boxB.height <= boxA.y\n );\n}\n\n// ── Visual classification ────────────────────────────────────────────────────\n\nconst VISUAL_LEAF_TYPES = new Set([\n \"VECTOR\", \"BOOLEAN_OPERATION\", \"ELLIPSE\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\", \"RECTANGLE\",\n]);\n\nexport function isVisualLeafType(type: string): boolean {\n return VISUAL_LEAF_TYPES.has(type);\n}\n\nexport function hasImageFill(node: AnalysisNode): boolean {\n if (!Array.isArray(node.fills)) return false;\n return node.fills.some(\n (fill) =>\n typeof fill === \"object\" &&\n fill !== null &&\n (fill as { type?: unknown }).type === \"IMAGE\",\n );\n}\n\nexport function isVisualOnlyNode(node: AnalysisNode): boolean {\n if (VISUAL_LEAF_TYPES.has(node.type)) return true;\n const hasOnlyVisualChildren =\n node.children !== undefined &&\n node.children.length > 0 &&\n node.children.every((c) => VISUAL_LEAF_TYPES.has(c.type));\n // Image fill only counts as visual-only when there are no content children\n if (hasImageFill(node) && (!node.children || node.children.length === 0 || hasOnlyVisualChildren)) {\n return true;\n }\n if (hasOnlyVisualChildren) return true;\n return false;\n}\n\n// ── Interactive classification ───────────────────────────────────────────────\n\nexport type StatefulComponentType = \"button\" | \"link\" | \"tab\" | \"input\" | \"toggle\";\n\n/** Name patterns → interactive type mapping */\nexport const STATEFUL_PATTERNS: Array<{ pattern: RegExp; type: StatefulComponentType }> = [\n { pattern: /\\b(btn|button|cta)\\b/i, type: \"button\" },\n { pattern: /\\b(link|anchor)\\b/i, type: \"link\" },\n { pattern: /\\b(tab|tabs)\\b/i, type: \"tab\" },\n { pattern: /\\b(nav|navigation|menu|navbar)\\b/i, type: \"tab\" },\n { pattern: /\\b(input|text-?field|search-?bar|textarea)\\b/i, type: \"input\" },\n { pattern: /\\b(select|dropdown|combo-?box)\\b/i, type: \"input\" },\n { pattern: /\\b(toggle|switch|checkbox|radio)\\b/i, type: \"toggle\" },\n];\n\nexport function getStatefulComponentType(node: AnalysisNode): StatefulComponentType | null {\n if (!node.name) return null;\n for (const entry of STATEFUL_PATTERNS) {\n if (entry.pattern.test(node.name)) return entry.type;\n }\n return null;\n}\n\nexport function isStatefulComponent(node: AnalysisNode): boolean {\n return getStatefulComponentType(node) !== null;\n}\n\n/**\n * Standard state names across web + mobile platforms.\n * Used by missing-interaction-state (to detect presence) and\n * non-standard-naming (to flag non-standard names).\n *\n * Sources:\n * - CSS: :hover, :active, :focus, :disabled, :enabled — https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-classes\n * - Material Design 3: Hovered, Focused, Pressed, Dragged — https://m3.material.io/foundations/interaction/states\n * - UIKit: highlighted, selected, disabled, focused — https://developer.apple.com/documentation/uikit/uicontrol/state\n */\nexport const STANDARD_STATE_NAMES = new Set([\n // CSS pseudo-classes (web)\n \"default\", \"hover\", \"active\", \"focus\", \"focused\", \"disabled\", \"enabled\",\n // Material Design 3 (Android)\n \"pressed\", \"dragged\",\n // UIKit (iOS)\n \"highlighted\",\n // Common\n \"selected\",\n]);\n\n/**\n * Patterns that look like state names but aren't in the standard set.\n * Maps common non-standard names to their standard equivalent for suggestions.\n */\nexport const STATE_NAME_SUGGESTIONS: Record<string, string> = {\n on: \"active\",\n off: \"default\",\n clicked: \"pressed\",\n tapped: \"pressed\",\n inactive: \"disabled\",\n normal: \"default\",\n rest: \"default\",\n hovered: \"hover\",\n activated: \"active\",\n checked: \"selected\",\n unchecked: \"default\",\n};\n\n/** Pattern to detect state-like variant option names (broad match) */\nexport const STATE_LIKE_PATTERN = /\\b(on|off|clicked|tapped|inactive|normal|rest|hovered|activated|checked|unchecked)\\b/i;\n\n// ── Overlay / Carousel patterns ──────────────────────────────────────────────\n\n/** Elements that open on top of current view */\nexport const OVERLAY_PATTERN = /\\b(dropdown|select|combo-?box|popover|accordion|drawer|modal|bottom-?sheet|sheet|sidebar|panel|dialog|popup|toast)\\b/i;\n\n/** Elements that swipe/slide between items */\nexport const CAROUSEL_PATTERN = /\\b(carousel|slider|swiper|slide-?show|gallery)\\b/i;\n\nexport function isOverlayNode(node: AnalysisNode): boolean {\n return node.name !== undefined && OVERLAY_PATTERN.test(node.name);\n}\n\nexport function isCarouselNode(node: AnalysisNode): boolean {\n return node.name !== undefined && CAROUSEL_PATTERN.test(node.name);\n}\n\n// ── Token classification ─────────────────────────────────────────────────────\n\nexport function hasStyleReference(node: AnalysisNode, styleType: string): boolean {\n return node.styles !== undefined && styleType in node.styles;\n}\n\nexport function hasBoundVariable(node: AnalysisNode, key: string): boolean {\n return node.boundVariables !== undefined && key in node.boundVariables;\n}\n\n// ── Naming patterns ──────────────────────────────────────────────────────────\n\n/** Figma default name patterns (Frame 1, Group 2, etc.) */\nexport const DEFAULT_NAME_PATTERNS = [\n /^Frame\\s*\\d*$/i,\n /^Group\\s*\\d*$/i,\n /^Rectangle\\s*\\d*$/i,\n /^Ellipse\\s*\\d*$/i,\n /^Vector\\s*\\d*$/i,\n /^Line\\s*\\d*$/i,\n /^Text\\s*\\d*$/i,\n /^Image\\s*\\d*$/i,\n /^Component\\s*\\d*$/i,\n /^Instance\\s*\\d*$/i,\n];\n\nexport function isDefaultName(name: string): boolean {\n return DEFAULT_NAME_PATTERNS.some((pattern) => pattern.test(name));\n}\n\n/** Shape-only non-semantic names */\nexport const NON_SEMANTIC_NAMES = [\n \"rectangle\", \"ellipse\", \"vector\", \"line\", \"polygon\",\n \"star\", \"path\", \"shape\", \"image\", \"fill\", \"stroke\",\n];\n\nexport function isNonSemanticName(name: string): boolean {\n return NON_SEMANTIC_NAMES.includes(name.toLowerCase().trim());\n}\n\n// ── Exclusion ────────────────────────────────────────────────────────────────\n\nexport const EXCLUDED_NAME_PATTERN = /(badge|close|dismiss|overlay|float|fab|dot|indicator|corner|decoration|tag|status|notification|icon|ico|image|asset|filter|dim|dimmed|bg|background|logo|avatar|divider|separator|nav|navigation|gnb|header|footer|sidebar|toolbar|modal|dialog|popup|toast|tooltip|dropdown|menu|sticky|spinner|loader|cursor|cta|chatbot|thumb|thumbnail|tabbar|tab-bar|statusbar|status-bar)/i;\n\nexport function isExcludedName(name: string): boolean {\n return EXCLUDED_NAME_PATTERN.test(name);\n}\n","import type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport { isVisualLeafType, isVisualOnlyNode, isExcludedName } from \"./node-semantics.js\";\n\n// ============================================\n// Auto-layout exceptions\n// ============================================\n\n/** Frames that don't need auto-layout (only visual-leaf children like icon paths) */\nexport function isAutoLayoutExempt(node: AnalysisNode): boolean {\n if (\n node.children &&\n node.children.length > 0 &&\n node.children.every((c) => isVisualLeafType(c.type))\n ) return true;\n\n return false;\n}\n\n// ============================================\n// Absolute-position exceptions\n// ============================================\n\n/** Nodes that are allowed to use absolute positioning inside auto-layout */\nexport function isAbsolutePositionExempt(node: AnalysisNode): boolean {\n if (isVisualOnlyNode(node)) return true;\n\n // Intentional name patterns (badge, close, overlay, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n\n// ============================================\n// Size-constraint exceptions\n// ============================================\n//\n// `isSizeConstraintExempt` was removed in #403 (commit\n// `feat(rules): missing-size-constraint scope-aware…`). The new rule\n// walks the full ancestor chain to determine whether any container\n// already establishes a width bound, which strictly subsumes the old\n// \"parent has maxWidth OR depth <= 1\" heuristic. Keeping the helper\n// would produce two divergent definitions of \"bound\" in the codebase.\n\n// ============================================\n// Fixed-size exceptions\n// ============================================\n\n/** Nodes that are allowed to use fixed sizing inside auto-layout */\nexport function isFixedSizeExempt(node: AnalysisNode): boolean {\n // Visual-only nodes (icons, images, shapes) — intentionally fixed\n if (isVisualOnlyNode(node)) return true;\n\n // Excluded names (nav, header, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n","/**\n * Centralized rule violation messages.\n * All message text lives here so CLI, web, plugin, and MCP share the same strings.\n *\n * Each message function returns { message, suggestion, guide? }:\n * - message: what's wrong (node-specific, dynamic)\n * - suggestion: how to fix it (node-specific, dynamic)\n * - guide: exemption hint (optional, when the rule auto-excludes certain cases)\n */\n\n// ── Message return type ─────────────────────────────────────────────────────\n\nexport interface ViolationMsg {\n message: string;\n suggestion: string;\n guide?: string;\n}\n\n// ── Sub-type definitions ─────────────────────────────────────────────────────\n\nexport type RawValueSubType = \"color\" | \"font\" | \"shadow\" | \"opacity\" | \"spacing\";\nexport type NoAutoLayoutSubType = \"overlapping\" | \"nested\" | \"basic\";\nexport type FixedSizeSubType = \"both-axes\" | \"horizontal\";\nexport type MissingComponentSubType = \"unused-component\" | \"name-repetition\" | \"structure-repetition\" | \"style-override\";\n\n// ── raw-value ────────────────────────────────────────────────────────────────\n\nexport const rawValueMsg = {\n color: (name: string, hex: string): ViolationMsg => ({\n message: `\"${name}\" uses raw fill color ${hex} without style or variable`,\n suggestion: `Bind to a color token`,\n }),\n font: (name: string, fontDesc: string): ViolationMsg => ({\n message: `\"${name}\" uses raw font${fontDesc} without text style`,\n suggestion: `Apply a text style`,\n }),\n shadow: (name: string, shadowType: string, details: string): ViolationMsg => ({\n message: `\"${name}\" has ${shadowType}${details} without effect style`,\n suggestion: `Apply an effect style`,\n }),\n opacity: (name: string, pct: number): ViolationMsg => ({\n message: `\"${name}\" uses raw opacity (${pct}%) without a variable binding`,\n suggestion: `Bind opacity to a variable`,\n }),\n spacing: (name: string, label: string, value: number): ViolationMsg => ({\n message: `\"${name}\" uses raw ${label} (${value}px) without a variable binding`,\n suggestion: `Bind spacing to a variable`,\n }),\n};\n\n// ── irregular-spacing ────────────────────────────────────────────────────────\n\nexport type IrregularSpacingSubType = \"padding\" | \"gap\";\n\nexport const irregularSpacingMsg = (name: string, spacing: number, gridBase: number, nearest: number): ViolationMsg => ({\n message: `\"${name}\" has spacing ${spacing}px not on ${gridBase}pt grid`,\n suggestion: `Round to nearest ${gridBase}pt multiple (${nearest}px)`,\n});\n\n// ── no-auto-layout ───────────────────────────────────────────────────────────\n\nexport const noAutoLayoutMsg = {\n overlapping: (name: string): ViolationMsg => ({\n message: `\"${name}\" has overlapping children without Auto Layout`,\n suggestion: `Apply auto-layout to separate overlapping children`,\n guide: `If this is an intentional overlay (e.g., badge on avatar), this can be ignored`,\n }),\n nested: (name: string): ViolationMsg => ({\n message: `\"${name}\" has nested containers without layout hints`,\n suggestion: `Apply auto-layout to organize nested containers`,\n guide: `Icon wrappers containing only vectors are automatically excluded`,\n }),\n basic: (name: string, arrangement: string, directionHint: string): ViolationMsg => ({\n message: `Frame \"${name}\" has no auto-layout${arrangement}`,\n suggestion: directionHint ? `Apply ${directionHint} auto-layout` : `Apply auto-layout`,\n guide: `Single-child wrappers and icon containers are automatically excluded`,\n }),\n};\n\n// ── absolute-position-in-auto-layout ─────────────────────────────────────────\n\nexport const absolutePositionMsg = (name: string, parentName: string): ViolationMsg => ({\n message: `\"${name}\" uses absolute positioning inside Auto Layout parent \"${parentName}\"`,\n suggestion: `Remove absolute positioning or restructure outside the auto-layout parent`,\n guide: `If this is a badge or overlay, name it with \"badge\", \"overlay\", or \"icon\" to auto-exclude`,\n});\n\n// ── fixed-size-in-auto-layout ────────────────────────────────────────────────\n\nexport const fixedSizeMsg = {\n bothAxes: (name: string, width: number, height: number): ViolationMsg => ({\n message: `Container \"${name}\" (${width}×${height}) uses fixed size on both axes inside auto-layout`,\n suggestion: `Set at least one axis to HUG or FILL`,\n }),\n horizontal: (name: string, width: number): ViolationMsg => ({\n message: `\"${name}\" has fixed width (${width}px) inside auto-layout`,\n suggestion: `Set horizontal sizing to FILL`,\n }),\n};\n\n// ── missing-size-constraint ──────────────────────────────────────────────────\n//\n// #403: Subtypes are case-of-firing rather than property-of-fix. Each\n// subtype's gotcha question is a pure function of the subtype — the\n// message function does not need to read `rootNodeType` or `scope`\n// again. This keeps gotcha rendering simple at the cost of a slightly\n// longer subtype list (4 instead of 1).\n\nexport type MissingSizeConstraintSubType =\n | \"page-container-unbound\"\n | \"page-instance-fixed\"\n | \"component-fixed-by-design\"\n | \"component-fixed-by-override\";\n\nexport const missingSizeConstraintMsg = {\n pageContainerUnbound: (name: string, currentWidth: string): ViolationMsg => ({\n message: `Container \"${name}\" uses FILL width (currently ${currentWidth}) and no ancestor defines a width bound`,\n suggestion: `Decide whether this area should stretch with the screen, or set min/max-width here so the responsive behavior is explicit`,\n }),\n pageInstanceFixed: (name: string, currentWidth: string): ViolationMsg => ({\n message: `Instance \"${name}\" has fixed width (${currentWidth}) inside an Auto Layout parent`,\n suggestion: `Confirm whether this fixed width is intentional — if not, set the instance to FILL so it follows the parent's layout`,\n }),\n componentFixedByDesign: (name: string, currentWidth: string): ViolationMsg => ({\n message: `Component \"${name}\" has fixed width (${currentWidth}) at its root`,\n suggestion: `Confirm whether this component is intentionally non-responsive — otherwise switch root sizing to FILL or set min/max bounds`,\n }),\n componentFixedByOverride: (name: string, currentWidth: string): ViolationMsg => ({\n message: `Instance \"${name}\" overrides root width to fixed (${currentWidth}); the original component may be FILL`,\n suggestion: `Confirm whether the fixed-width override is intentional — if not, restore root sizing to inherit from the component definition`,\n }),\n};\n\n// ── non-layout-container (was group-usage) ───────────────────────────────────\n\nexport type NonLayoutContainerSubType = \"group\" | \"section\";\n\nexport const nonLayoutContainerMsg = {\n group: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Group`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n section: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Section used as layout container`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n};\n\n// ── deep-nesting ─────────────────────────────────────────────────────────────\n\nexport const deepNestingMsg = (name: string, depth: number, maxDepth: number): ViolationMsg => ({\n message: `\"${name}\" is nested ${depth} levels deep within its component (max: ${maxDepth})`,\n suggestion: `Extract into a sub-component to reduce depth`,\n});\n\n// ── missing-component ────────────────────────────────────────────────────────\n\nexport const missingComponentMsg = {\n unusedComponent: (componentName: string, count: number): ViolationMsg => ({\n message: `Component \"${componentName}\" exists but ${count} repeated frames found instead of instances`,\n suggestion: `Replace frames with component instances`,\n }),\n nameRepetition: (name: string, count: number): ViolationMsg => ({\n message: `\"${name}\" appears ${count} times`,\n suggestion: `Extract as a reusable component`,\n }),\n structureRepetition: (name: string, siblingCount: number): ViolationMsg => ({\n message: `\"${name}\" and ${siblingCount} sibling frame(s) share the same internal structure`,\n suggestion: `Extract a shared component from the repeated structure`,\n }),\n styleOverride: (componentName: string, overrides: string[]): ViolationMsg => ({\n message: `\"${componentName}\" instance has style overrides (${overrides.join(\", \")})`,\n suggestion: `Create a new variant for this style combination`,\n }),\n};\n\n// ── detached-instance ────────────────────────────────────────────────────────\n\nexport const detachedInstanceMsg = (name: string, componentName: string): ViolationMsg => ({\n message: `\"${name}\" may be a detached instance of component \"${componentName}\"`,\n suggestion: `Restore as an instance of \"${componentName}\" or create a new variant`,\n});\n\n// ── variant-structure-mismatch ───────────────────────────────────────────────\n\nexport const variantStructureMismatchMsg = (name: string, mismatchCount: number, totalVariants: number): ViolationMsg => ({\n message: `\"${name}\" has ${mismatchCount}/${totalVariants} variants with different child structures`,\n suggestion: `Unify variant structures using visibility toggles for optional elements`,\n});\n\n// ── non-standard-naming ──────────────────────────────────────────────────────\n\nexport type NonStandardNamingSubType = \"state-name\";\n\nexport const nonStandardNamingMsg = {\n stateName: (name: string, nonStandard: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" has non-standard state name \"${nonStandard}\"`,\n suggestion: `Use \"${suggested}\" for dev-friendly naming`,\n }),\n};\n\n// ── non-semantic-name (merged: default-name + non-semantic-name) ─────────────\n\nexport type NonSemanticNameSubType = \"frame\" | \"group\" | \"vector\" | \"shape\" | \"text\" | \"image\" | \"component\" | \"instance\" | \"shape-name\";\n\nconst DEFAULT_NAME_SUBTYPE_MAP: Record<string, NonSemanticNameSubType> = {\n FRAME: \"frame\",\n GROUP: \"group\",\n RECTANGLE: \"shape\",\n ELLIPSE: \"shape\",\n VECTOR: \"vector\",\n LINE: \"vector\",\n STAR: \"shape\",\n REGULAR_POLYGON: \"shape\",\n TEXT: \"text\",\n IMAGE: \"image\",\n COMPONENT: \"component\",\n COMPONENT_SET: \"component\",\n INSTANCE: \"instance\",\n};\n\nexport function getDefaultNameSubType(nodeType: string): NonSemanticNameSubType {\n return DEFAULT_NAME_SUBTYPE_MAP[nodeType] ?? \"frame\";\n}\n\nconst NON_SEMANTIC_EXAMPLES: Record<string, string> = {\n FRAME: '\"Header\", \"ProductCard\", \"Sidebar\"',\n GROUP: '\"NavItems\", \"ButtonGroup\", \"CardContent\"',\n VECTOR: '\"ArrowIcon\", \"CheckMark\", \"LogoSymbol\"',\n LINE: '\"Divider\", \"Separator\", \"Underline\"',\n RECTANGLE: '\"Background\", \"Divider\", \"Overlay\"',\n ELLIPSE: '\"AvatarShape\", \"StatusDot\", \"Badge\"',\n STAR: '\"RatingIcon\", \"FavoriteIcon\", \"StarBadge\"',\n REGULAR_POLYGON: '\"PlayIcon\", \"WarningIcon\", \"ShapeDecor\"',\n TEXT: '\"PageTitle\", \"Description\", \"Price\"',\n IMAGE: '\"Avatar\", \"ProductPhoto\", \"Banner\"',\n COMPONENT: '\"PrimaryButton\", \"InputField\", \"CardTemplate\"',\n COMPONENT_SET: '\"Button\", \"Input\", \"Card\"',\n INSTANCE: '\"CloseButton\", \"UserAvatar\", \"StarIcon\"',\n};\n\nexport const nonSemanticNameMsg = (type: string, name: string): ViolationMsg => {\n const examples = NON_SEMANTIC_EXAMPLES[type] ?? '\"Header\", \"ProductCard\", \"Icon\"';\n return {\n message: `${type} \"${name}\" is a non-semantic name`,\n suggestion: `Rename to describe its role (e.g., ${examples})`,\n };\n};\n\n// ── missing-interaction-state ─────────────────────────────────────────────────\n\nexport type MissingInteractionStateSubType = \"hover\" | \"disabled\" | \"active\" | \"focus\";\n\nexport const missingInteractionStateMsg = {\n hover: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Hover state variant`,\n suggestion: `Add a State=Hover variant`,\n }),\n disabled: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Disabled state variant`,\n suggestion: `Add a State=Disabled variant`,\n }),\n active: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Active state variant`,\n suggestion: `Add a State=Active variant`,\n }),\n focus: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Focus state variant`,\n suggestion: `Add a State=Focus variant`,\n }),\n};\n\n// ── missing-prototype ─────────────────────────────────────────────────────────\n\nexport type MissingPrototypeSubType = \"button\" | \"navigation\" | \"tab\" | \"overlay\" | \"carousel\" | \"input\" | \"toggle\";\n\nexport const missingPrototypeMsg = {\n button: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a button but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the click behavior`,\n }),\n navigation: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a navigation link but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the destination`,\n }),\n tab: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a tab but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define tab switching behavior`,\n }),\n overlay: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an overlay trigger but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define open/close behavior`,\n }),\n carousel: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a carousel but has no interaction prototype`,\n suggestion: `Add an ON_CLICK or ON_DRAG interaction to define slide navigation`,\n }),\n input: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an input but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define focus/interaction behavior`,\n }),\n toggle: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a toggle but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define on/off behavior`,\n }),\n};\n\n// ── inconsistent-naming-convention ───────────────────────────────────────────\n\nexport const inconsistentNamingMsg = (name: string, nodeConvention: string, dominantConvention: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" uses ${nodeConvention} while siblings use ${dominantConvention}`,\n suggestion: `Rename to \"${suggested}\"`,\n guide: `This checks sibling layers at the same level — you don't have to follow the exact suggestion, just keep naming consistent across siblings`,\n});\n","import type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport type { RuleCheckFn, RuleContext, RuleDefinition, RuleViolation } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { isAutoLayoutExempt, isAbsolutePositionExempt, isFixedSizeExempt } from \"../rule-exceptions.js\";\nimport { noAutoLayoutMsg, absolutePositionMsg, fixedSizeMsg, missingSizeConstraintMsg, nonLayoutContainerMsg, deepNestingMsg } from \"../rule-messages.js\";\nimport { isContainerNode, hasAutoLayout, hasOverlappingBounds } from \"../node-semantics.js\";\n\n// ============================================\n// no-auto-layout (merged: absorbs ambiguous-structure + missing-layout-hint)\n// ============================================\n\nconst noAutoLayoutDef: RuleDefinition = {\n id: \"no-auto-layout\",\n name: \"No Auto Layout\",\n category: \"pixel-critical\",\n why: \"Without Auto Layout, AI must guess positioning from absolute coordinates instead of reading explicit layout rules\",\n impact: \"Generated code uses hardcoded positions that break on any content or screen size change\",\n fix: \"Apply Auto Layout to create clear, explicit structure — enables AI to generate flexbox/grid instead of absolute positioning\",\n};\n\nconst noAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n if (hasAutoLayout(node)) return null;\n if (!node.children || node.children.length === 0) return null;\n\n if (isAutoLayoutExempt(node)) return null;\n\n // Priority 1: Check for overlapping visible children (ambiguous-structure)\n if (node.children.length >= 2) {\n for (let i = 0; i < node.children.length; i++) {\n for (let j = i + 1; j < node.children.length; j++) {\n const childA = node.children[i];\n const childB = node.children[j];\n if (!childA || !childB) continue;\n\n if (hasOverlappingBounds(childA, childB)) {\n if (childA.visible !== false && childB.visible !== false) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"overlapping\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.overlapping(node.name),\n };\n }\n }\n }\n }\n }\n\n // Priority 2: Check for nested containers without layout hints (missing-layout-hint)\n if (node.children.length >= 2) {\n const nestedContainers = node.children.filter((c) => isContainerNode(c));\n if (nestedContainers.length >= 2) {\n const withoutLayout = nestedContainers.filter((c) => !hasAutoLayout(c));\n if (withoutLayout.length >= 2) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"nested\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.nested(node.name),\n };\n }\n }\n }\n\n // Priority 3: Basic no-auto-layout check (FRAME only)\n if (node.type !== \"FRAME\") return null;\n\n const childCount = node.children?.length ?? 0;\n let directionHint = \"\";\n if (node.children && node.children.length >= 2) {\n const boxes = node.children.filter(c => c.absoluteBoundingBox).map(c => c.absoluteBoundingBox!);\n if (boxes.length >= 2) {\n const yRange = Math.max(...boxes.map(b => b.y)) - Math.min(...boxes.map(b => b.y));\n const xRange = Math.max(...boxes.map(b => b.x)) - Math.min(...boxes.map(b => b.x));\n directionHint = yRange > xRange ? \"VERTICAL\" : \"HORIZONTAL\";\n }\n }\n\n const arrangement = directionHint\n ? ` (${childCount} children arranged ${directionHint.toLowerCase()}ly)`\n : childCount > 0 ? ` (${childCount} children)` : \"\";\n\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"basic\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.basic(node.name, arrangement, directionHint),\n };\n};\n\nexport const noAutoLayout = defineRule({\n definition: noAutoLayoutDef,\n check: noAutoLayoutCheck,\n});\n\n// ============================================\n// absolute-position-in-auto-layout\n// ============================================\n\nconst absolutePositionInAutoLayoutDef: RuleDefinition = {\n id: \"absolute-position-in-auto-layout\",\n name: \"Absolute Position in Auto Layout\",\n category: \"pixel-critical\",\n why: \"Absolute positioning inside Auto Layout contradicts the parent's layout rules — AI sees conflicting instructions\",\n impact: \"AI must decide whether to follow the parent's flexbox or the child's absolute position — often gets it wrong\",\n fix: \"Remove absolute positioning or use proper Auto Layout alignment\",\n};\n\nconst absolutePositionInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (node.layoutPositioning !== \"ABSOLUTE\") return null;\n\n if (isAbsolutePositionExempt(node)) return null;\n\n return {\n ruleId: absolutePositionInAutoLayoutDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...absolutePositionMsg(node.name, context.parent.name),\n };\n};\n\nexport const absolutePositionInAutoLayout = defineRule({\n definition: absolutePositionInAutoLayoutDef,\n check: absolutePositionInAutoLayoutCheck,\n});\n\n// ============================================\n// fixed-size-in-auto-layout (merged: absorbs fixed-width-in-responsive-context)\n// ============================================\n\nconst fixedSizeInAutoLayoutDef: RuleDefinition = {\n id: \"fixed-size-in-auto-layout\",\n name: \"Fixed Size in Auto Layout\",\n category: \"responsive-critical\",\n why: \"Fixed sizing inside Auto Layout contradicts the flexible layout intent\",\n impact: \"AI generates a rigid element inside a flex container — the layout won't respond to content changes\",\n fix: \"Use 'Hug' or 'Fill' for at least one axis. Both-axes FIXED → layout completely rigid; horizontal-only FIXED → width won't adapt to parent resize\",\n};\n\nconst fixedSizeInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (!isContainerNode(node)) return null;\n if (!node.absoluteBoundingBox) return null;\n\n if (isFixedSizeExempt(node)) return null;\n\n const { width, height } = node.absoluteBoundingBox;\n\n // Check both axes FIXED (stronger case)\n const hFixed =\n node.layoutSizingHorizontal === \"FIXED\" || node.layoutSizingHorizontal === undefined;\n const vFixed =\n node.layoutSizingVertical === \"FIXED\" || node.layoutSizingVertical === undefined;\n\n if (hFixed && vFixed) {\n // Skip if it has its own auto-layout\n if (node.layoutMode && node.layoutMode !== \"NONE\") return null;\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"both-axes\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.bothAxes(node.name, width, height),\n };\n }\n\n // Check horizontal-only FIXED (lighter case, from fixed-width-in-responsive-context)\n if (hFixed && !vFixed) {\n // Use layoutSizingHorizontal if available (accurate)\n if (node.layoutSizingHorizontal) {\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n } else {\n // Fallback: STRETCH means fill, skip\n if (node.layoutAlign === \"STRETCH\") return null;\n if (node.layoutAlign !== \"INHERIT\") return null;\n }\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"horizontal\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.horizontal(node.name, width),\n };\n }\n\n return null;\n};\n\nexport const fixedSizeInAutoLayout = defineRule({\n definition: fixedSizeInAutoLayoutDef,\n check: fixedSizeInAutoLayoutCheck,\n});\n\n// ============================================\n// missing-size-constraint (#403 redesign — scope-aware, info-collection)\n// ============================================\n//\n// Pre-#403 this rule fired on every FILL container with no max-width\n// regardless of whether an ancestor already established a bound, and\n// scored -8/risk. The redesign narrows it to genuinely ambiguous sizing\n// situations and reframes the output as a gotcha rather than a\n// violation (per ADR-017 channel separation):\n//\n// page scope:\n// - container FRAME/SECTION with FILL width AND no chain-bound\n// ancestor (chain-bound = FIXED width OR FILL/HUG with explicit\n// min/max). Fires `page-container-unbound` — designer intent\n// (stretch with screen vs. cap at content) is structurally\n// undecidable.\n// - INSTANCE with FIXED width inside an Auto Layout parent. Fires\n// `page-instance-fixed` — could be intentional override or a stale\n// size carried over from the component definition.\n//\n// component scope:\n// - the analysis root (and only the root — internal nodes pass)\n// with FIXED width. Fires `component-fixed-by-design` for\n// COMPONENT/COMPONENT_SET roots, `component-fixed-by-override`\n// for INSTANCE roots — same shape, different gotcha framing.\n//\n// Deliberately scoped out (see PR body):\n// - INSTANCE FIXED outside Auto Layout — `no-auto-layout` already\n// owns the score channel on the non-auto-layout parent. Firing\n// here too would double-penalize one structural concern.\n// - Nodes inside an INSTANCE — Plugin API silently ignores min/max\n// overrides on instance internal nodes, so the gotcha would be\n// un-actionable.\n// - Height axis — width is the dominant responsive concern; height\n// redesign deferred to a follow-up issue.\n\nconst missingSizeConstraintDef: RuleDefinition = {\n id: \"missing-size-constraint\",\n name: \"Missing Size Constraint\",\n category: \"responsive-critical\",\n why: \"Width sizing without explicit bounds (FIXED root or FILL chained to a bounded ancestor) is structurally indistinguishable from missing information — AI cannot tell whether the designer intended responsive stretching, a fixed cap, or simply forgot to set min/max\",\n impact: \"Generated code either guesses hard-coded widths or omits responsive constraints; either way the runtime layout drifts from the design intent at viewports the designer never explicitly considered\",\n fix: \"Answer the gotcha to declare intent (responsive vs. fixed-by-design vs. instance override), then encode the answer in Figma sizing — FILL/HUG with min/max for responsive bounds, FIXED only when intentionally non-responsive\",\n};\n\n// ── Chain-bound walker (memoized via analysisState) ──────────────────────\n//\n// \"Chain-bound\" = some ancestor in the analysis tree (root included)\n// resolves the width chain by either fixing the width or capping a\n// FILL with min/max. Computed lazily as the rule visits each node:\n// because traverseAndCheck runs the check fn parent-first, by the time\n// a child asks `parentChainBound(child)` the parent's entry is already\n// in the cache. The side-effect MUST run for every visited node — see\n// `recordChainBound` call placement below.\n\ntype ChainBoundCache = Map<string, boolean>;\nconst CHAIN_BOUND_KEY = \"missing-size-constraint:chain-bound\";\n\nfunction getChainBoundCache(context: RuleContext): ChainBoundCache {\n return getAnalysisState(context, CHAIN_BOUND_KEY, () => new Map<string, boolean>());\n}\n\nfunction establishesOwnWidthBound(node: AnalysisNode): boolean {\n if (node.layoutSizingHorizontal === \"FIXED\") return true;\n if (node.minWidth !== undefined || node.maxWidth !== undefined) return true;\n return false;\n}\n\nfunction recordChainBound(context: RuleContext, node: AnalysisNode): boolean {\n const cache = getChainBoundCache(context);\n const cached = cache.get(node.id);\n if (cached !== undefined) return cached;\n const own = establishesOwnWidthBound(node);\n const parent = context.parent;\n const inherited = parent ? cache.get(parent.id) ?? false : false;\n const result = own || inherited;\n cache.set(node.id, result);\n return result;\n}\n\nfunction parentChainBound(context: RuleContext): boolean {\n if (!context.parent) return false;\n return getChainBoundCache(context).get(context.parent.id) ?? false;\n}\n\n// ── Subtype dispatchers ──────────────────────────────────────────────────\n\nconst PAGE_CONTAINER_FRAME_TYPES = new Set([\"FRAME\", \"SECTION\"]);\n\nfunction formatWidth(node: AnalysisNode): string {\n return node.absoluteBoundingBox ? `${node.absoluteBoundingBox.width}px` : \"unknown\";\n}\n\nfunction buildViolation(\n subType: \"page-container-unbound\" | \"page-instance-fixed\" | \"component-fixed-by-design\" | \"component-fixed-by-override\",\n node: AnalysisNode,\n context: RuleContext,\n msg: { message: string; suggestion: string; guide?: string }\n): RuleViolation {\n return {\n ruleId: missingSizeConstraintDef.id,\n subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...msg,\n };\n}\n\nfunction checkComponentScopeRoot(\n node: AnalysisNode,\n context: RuleContext\n): RuleViolation | null {\n // Only the analysis root in component scope — internal nodes pass.\n // Variants of a COMPONENT_SET sit at depth=1 and are intentionally\n // skipped; variant-level sizing is the variant-structure-mismatch\n // rule's concern, not this one.\n if (context.depth !== 0) return null;\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n\n const currentWidth = formatWidth(node);\n if (context.rootNodeType === \"INSTANCE\") {\n return buildViolation(\n \"component-fixed-by-override\",\n node,\n context,\n missingSizeConstraintMsg.componentFixedByOverride(node.name, currentWidth),\n );\n }\n // COMPONENT, COMPONENT_SET, or scope-overridden FRAME treated as a\n // component definition. The gotcha framing is identical — \"is this\n // intentionally non-responsive?\" — so they share the subtype.\n return buildViolation(\n \"component-fixed-by-design\",\n node,\n context,\n missingSizeConstraintMsg.componentFixedByDesign(node.name, currentWidth),\n );\n}\n\nfunction checkPageInstanceFixed(\n node: AnalysisNode,\n context: RuleContext\n): RuleViolation | null {\n if (node.type !== \"INSTANCE\") return null;\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n\n // Scope-out (#403): when the parent is not Auto Layout,\n // `no-auto-layout` already fires on that parent and owns the score\n // channel for the structural problem. Adding a sizing gotcha on top\n // double-counts one underlying issue. The leak case\n // (INSTANCE direct child of a SECTION page-root, where\n // no-auto-layout's behavior on SECTION is ambiguous) will surface in\n // Phase 4's fire-rate gate; revisit then if it actually appears.\n if (!context.parent || !hasAutoLayout(context.parent)) return null;\n\n const currentWidth = formatWidth(node);\n return buildViolation(\n \"page-instance-fixed\",\n node,\n context,\n missingSizeConstraintMsg.pageInstanceFixed(node.name, currentWidth),\n );\n}\n\nfunction checkPageContainerUnbound(\n node: AnalysisNode,\n context: RuleContext\n): RuleViolation | null {\n if (!PAGE_CONTAINER_FRAME_TYPES.has(node.type)) return null;\n if (node.layoutSizingHorizontal !== \"FILL\") return null;\n // Some ancestor already establishes the width bound for this chain —\n // the FILL here will resolve to a finite range, no ambiguity.\n if (parentChainBound(context)) return null;\n\n const currentWidth = formatWidth(node);\n return buildViolation(\n \"page-container-unbound\",\n node,\n context,\n missingSizeConstraintMsg.pageContainerUnbound(node.name, currentWidth),\n );\n}\n\nconst missingSizeConstraintCheck: RuleCheckFn = (node, context) => {\n // Side-effect: record this node's chain-bound status for descendants.\n // MUST run for every visited node BEFORE any early return, otherwise\n // `parentChainBound` lookups on children will miss and silently\n // default to `false`. Co-locating the recorder with the only consumer\n // (this rule) keeps the cache contract local.\n recordChainBound(context, node);\n\n // Actionability filter (#403, D6): the Figma Plugin API silently\n // ignores min/max writes targeting nodes inside an INSTANCE, so any\n // gotcha generated here would be un-actionable. We exclude INSTANCE\n // descendants (but keep the INSTANCE node itself in scope — that's\n // the page-instance-fixed case, where the override IS actionable).\n if (context.ancestorTypes.includes(\"INSTANCE\")) return null;\n\n if (context.scope === \"component\") {\n return checkComponentScopeRoot(node, context);\n }\n\n // page scope — at most one of these fires per node by construction\n // (different node-type predicates), so order does not matter.\n return checkPageInstanceFixed(node, context) ?? checkPageContainerUnbound(node, context);\n};\n\nexport const missingSizeConstraint = defineRule({\n definition: missingSizeConstraintDef,\n check: missingSizeConstraintCheck,\n});\n\n// ============================================\n// non-layout-container (was group-usage — now also catches Section)\n// ============================================\n\nconst nonLayoutContainerDef: RuleDefinition = {\n id: \"non-layout-container\",\n name: \"Non-Layout Container\",\n category: \"pixel-critical\",\n why: \"Groups and Sections lack proper layout rules — AI sees children with absolute coordinates but no container logic\",\n impact: \"AI wraps elements in a plain div with no spacing/alignment, producing fragile layouts\",\n fix: \"Convert to Frame with Auto Layout so AI can generate proper flex/grid containers\",\n};\n\nconst nonLayoutContainerCheck: RuleCheckFn = (node, context) => {\n if (node.type === \"GROUP\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"group\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.group(node.name),\n };\n }\n\n if (node.type === \"SECTION\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"section\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.section(node.name),\n };\n }\n\n return null;\n};\n\nexport const nonLayoutContainer = defineRule({\n definition: nonLayoutContainerDef,\n check: nonLayoutContainerCheck,\n});\n\n// ============================================\n// deep-nesting\n// ============================================\n\nconst deepNestingDef: RuleDefinition = {\n id: \"deep-nesting\",\n name: \"Deep Nesting\",\n category: \"code-quality\",\n why: \"Deep nesting consumes AI context exponentially — each level adds indentation and structural overhead\",\n impact: \"AI may lose track of parent-child relationships in deeply nested trees, producing wrong layout hierarchy\",\n fix: \"Flatten the structure by extracting deeply nested groups into sub-components\",\n};\n\nconst deepNestingCheck: RuleCheckFn = (node, context, options) => {\n const maxDepth = (options?.[\"maxDepth\"] as number) ?? getRuleOption(\"deep-nesting\", \"maxDepth\", 5);\n\n if (context.componentDepth < maxDepth) return null;\n if (!isContainerNode(node)) return null;\n\n return {\n ruleId: deepNestingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...deepNestingMsg(node.name, context.componentDepth, maxDepth),\n };\n};\n\nexport const deepNesting = defineRule({\n definition: deepNestingDef,\n check: deepNestingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { rawValueMsg, irregularSpacingMsg } from \"../rule-messages.js\";\nimport { hasStyleReference, hasBoundVariable } from \"../node-semantics.js\";\n\nfunction isOnGrid(value: number, gridBase: number): boolean {\n return value % gridBase === 0;\n}\n\n// ============================================\n// raw-value (merged: raw-color + raw-font + raw-shadow + raw-opacity + raw-spacing)\n// ============================================\n\nconst rawValueDef: RuleDefinition = {\n id: \"raw-value\",\n name: \"Raw Value\",\n category: \"token-management\",\n why: \"Values without design tokens or variables must be reproduced exactly per node — one typo means a visible difference\",\n impact: \"AI cannot reference a shared token, so each raw value is an independent source of error across large pages\",\n fix: \"Use design tokens or variables (color styles, text styles, effect styles, opacity/spacing variables) so values are referenceable\",\n};\n\nconst rawValueCheck: RuleCheckFn = (node, context) => {\n const nodePath = context.path.join(\" > \");\n\n // Check 1: Raw fill color\n if (node.fills && Array.isArray(node.fills) && node.fills.length > 0) {\n if (!hasStyleReference(node, \"fill\") && !hasBoundVariable(node, \"fills\")) {\n for (const fill of node.fills) {\n const fillObj = fill as Record<string, unknown>;\n if (fillObj[\"type\"] === \"SOLID\" && fillObj[\"color\"]) {\n const c = fillObj[\"color\"] as Record<string, number>;\n const hex = `#${Math.round((c[\"r\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"g\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"b\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}`.toUpperCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"color\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.color(node.name, hex),\n };\n }\n }\n }\n }\n\n // Check 2: Raw font (TEXT nodes without text style)\n if (node.type === \"TEXT\") {\n if (\n !hasStyleReference(node, \"text\") &&\n (!hasBoundVariable(node, \"fontFamily\") || !hasBoundVariable(node, \"fontSize\"))\n ) {\n const fontParts: string[] = [];\n const s = node.style;\n if (s) {\n if (s[\"fontFamily\"]) fontParts.push(String(s[\"fontFamily\"]));\n if (s[\"fontSize\"]) fontParts.push(`${s[\"fontSize\"]}px`);\n if (s[\"fontWeight\"]) fontParts.push(String(s[\"fontWeight\"]));\n }\n const fontDesc = fontParts.length > 0 ? ` (${fontParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"font\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.font(node.name, fontDesc),\n };\n }\n }\n\n // Check 3: Raw shadow (effects without effect style)\n if (node.effects && Array.isArray(node.effects) && node.effects.length > 0) {\n if (!hasStyleReference(node, \"effect\")) {\n for (const effect of node.effects) {\n const effectObj = effect as Record<string, unknown>;\n if (effectObj[\"type\"] === \"DROP_SHADOW\" || effectObj[\"type\"] === \"INNER_SHADOW\") {\n const shadowType = effectObj[\"type\"] === \"DROP_SHADOW\" ? \"drop shadow\" : \"inner shadow\";\n const offset = effectObj[\"offset\"] as Record<string, number> | undefined;\n const radius = effectObj[\"radius\"] as number | undefined;\n const detailParts: string[] = [];\n if (offset) detailParts.push(`offset ${Math.round(offset[\"x\"] ?? 0)},${Math.round(offset[\"y\"] ?? 0)}`);\n if (radius !== undefined) detailParts.push(`blur ${Math.round(radius)}`);\n const details = detailParts.length > 0 ? ` (${detailParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"shadow\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.shadow(node.name, shadowType, details),\n };\n }\n }\n }\n }\n\n // Check 4: Raw opacity (non-default opacity without variable)\n if (node.opacity !== undefined && node.opacity < 1 && !hasBoundVariable(node, \"opacity\")) {\n return {\n ruleId: rawValueDef.id,\n subType: \"opacity\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.opacity(node.name, Math.round(node.opacity * 100)),\n };\n }\n\n // Check 5: Raw spacing (padding/gap without variable binding)\n const spacingKeys = [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\", \"itemSpacing\"] as const;\n for (const key of spacingKeys) {\n const value = node[key];\n if (value !== undefined && value > 0 && !hasBoundVariable(node, key)) {\n const label = key === \"itemSpacing\" ? \"gap\" : key.replace(\"padding\", \"padding-\").toLowerCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"spacing\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.spacing(node.name, label, value),\n };\n }\n }\n\n return null;\n};\n\nexport const rawValue = defineRule({\n definition: rawValueDef,\n check: rawValueCheck,\n});\n\n// ============================================\n// irregular-spacing (merged: inconsistent-spacing + magic-number-spacing)\n// ============================================\n\nconst irregularSpacingDef: RuleDefinition = {\n id: \"irregular-spacing\",\n name: \"Irregular Spacing\",\n category: \"token-management\",\n why: \"Off-grid or arbitrary spacing values force AI to handle many unique values instead of a predictable pattern\",\n impact: \"Higher chance of pixel-level differences when AI substitutes nearby round values\",\n fix: \"Align spacing to the design system grid (e.g., 4pt/8pt increments) for predictable implementation\",\n};\n\nconst irregularSpacingCheck: RuleCheckFn = (node, context, options) => {\n const configuredGridBase = (options?.[\"gridBase\"] as number) ?? getRuleOption(\"irregular-spacing\", \"gridBase\", 4);\n const gridBase = Number.isFinite(configuredGridBase) && configuredGridBase > 0 ? configuredGridBase : 4;\n\n const spacingEntries: Array<{ value: number; subType: \"padding\" | \"gap\" }> = [];\n for (const key of [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\"] as const) {\n const v = node[key];\n if (v !== undefined && v > 0) spacingEntries.push({ value: v, subType: \"padding\" });\n }\n if (node.itemSpacing !== undefined && node.itemSpacing > 0) {\n spacingEntries.push({ value: node.itemSpacing, subType: \"gap\" });\n }\n\n // Allow small intentional values\n const commonValues = [1, 2];\n\n for (const entry of spacingEntries) {\n if (commonValues.includes(entry.value)) continue;\n if (!isOnGrid(entry.value, gridBase)) {\n return {\n ruleId: irregularSpacingDef.id,\n subType: entry.subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...irregularSpacingMsg(node.name, entry.value, gridBase, Math.round(entry.value / gridBase) * gridBase),\n };\n }\n }\n\n return null;\n};\n\nexport const irregularSpacing = defineRule({\n definition: irregularSpacingDef,\n check: irregularSpacingCheck,\n});\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { missingComponentMsg, detachedInstanceMsg, variantStructureMismatchMsg } from \"../rule-messages.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\n\n/** Style properties to compare between master and instance. */\nconst STYLE_COMPARE_KEYS = [\"fills\", \"strokes\", \"effects\", \"cornerRadius\", \"strokeWeight\", \"individualStrokeWeights\"] as const;\n\n/**\n * Detect style overrides between a component master and an instance.\n * Returns list of property names that differ.\n */\nfunction detectStyleOverrides(master: AnalysisNode, instance: AnalysisNode): string[] {\n const overrides: string[] = [];\n for (const key of STYLE_COMPARE_KEYS) {\n const masterVal = master[key];\n const instanceVal = instance[key];\n // Both undefined/null → no override\n if (masterVal == null && instanceVal == null) continue;\n // One exists, other doesn't → override\n if (masterVal == null || instanceVal == null) {\n overrides.push(key);\n continue;\n }\n // Deep compare via JSON\n if (JSON.stringify(masterVal) !== JSON.stringify(instanceVal)) {\n overrides.push(key);\n }\n }\n return overrides;\n}\n\n/**\n * Collect all frame names in the file for duplicate detection\n */\nfunction collectFrameNames(\n node: AnalysisNode,\n names: Map<string, string[]> = new Map()\n): Map<string, string[]> {\n if (node.type === \"FRAME\" && node.name) {\n const existing = names.get(node.name) ?? [];\n existing.push(node.id);\n names.set(node.name, existing);\n }\n\n if (node.children) {\n for (const child of node.children) {\n collectFrameNames(child, names);\n }\n }\n\n return names;\n}\n\n/**\n * Build a structural fingerprint for a node.\n * The fingerprint encodes type, layoutMode, and child types recursively up to maxDepth.\n */\nfunction buildFingerprint(node: AnalysisNode, depth: number): string {\n if (depth <= 0 || !node.children || node.children.length === 0) {\n return `${node.type}:${node.layoutMode ?? \"NONE\"}`;\n }\n\n const childFingerprints = node.children\n .map((child) => buildFingerprint(child, depth - 1))\n .join(\",\");\n\n return `${node.type}:${node.layoutMode ?? \"NONE\"}:[${childFingerprints}]`;\n}\n\n/**\n * Check if the node is inside an INSTANCE subtree.\n * Walks the full ancestor type chain to detect INSTANCE at any level.\n */\nfunction isInsideInstance(context: {\n ancestorTypes: string[];\n}): boolean {\n return context.ancestorTypes.includes(\"INSTANCE\");\n}\n\n\n\n// ============================================\n// missing-component (unified 4-stage rule)\n// ============================================\n\n/** State keys for per-analysis deduplication via RuleContext.analysisState */\nconst SEEN_STAGE1_KEY = \"missing-component:seenStage1ComponentNames\";\nconst SEEN_STAGE4_KEY = \"missing-component:seenStage4ComponentIds\";\n\nfunction getSeenStage1(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE1_KEY, () => new Set<string>());\n}\n\nfunction getSeenStage4(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE4_KEY, () => new Set<string>());\n}\n\nconst missingComponentDef: RuleDefinition = {\n id: \"missing-component\",\n name: \"Missing Component\",\n category: \"code-quality\",\n why: \"Repeated structures, unused components, and divergent instance overrides indicate missing or underutilized components. This inflates AI token consumption and forces manual maintenance.\",\n impact: \"AI code generators reproduce each repeated frame independently instead of emitting a reusable component. Divergent instance overrides produce inconsistent implementations.\",\n fix: \"Create components from repeated structures, use instances instead of duplicated frames, and create variants for instances with significantly different overrides.\",\n};\n\nconst missingComponentCheck: RuleCheckFn = (node, context, options) => {\n // ========================================\n // FRAME stages (1, 2, 3) — ordered by priority\n // ========================================\n if (node.type === \"FRAME\") {\n // Stage 1: Component exists but not used — FRAME name matches a component in metadata AND frame is repeated\n const components = context.file.components;\n const matchingComponent = Object.values(components).find(\n (c) => c.name.toLowerCase() === node.name.toLowerCase()\n );\n\n // Collect frame names once for Stage 1 and Stage 2\n const frameNames = collectFrameNames(context.file.document);\n const sameNameFrames = frameNames.get(node.name);\n const firstFrame = sameNameFrames?.[0];\n\n if (matchingComponent) {\n const seenStage1 = getSeenStage1(context);\n if (\n sameNameFrames &&\n firstFrame !== undefined &&\n sameNameFrames.length >= 2 &&\n !seenStage1.has(node.name.toLowerCase()) &&\n firstFrame === node.id\n ) {\n seenStage1.add(node.name.toLowerCase());\n return {\n ruleId: missingComponentDef.id,\n subType: \"unused-component\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.unusedComponent(matchingComponent.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 2: Name-based repetition (existing logic)\n const minRepetitions =\n (options?.[\"minRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"minRepetitions\", 3);\n\n if (sameNameFrames && firstFrame !== undefined && sameNameFrames.length >= minRepetitions) {\n if (firstFrame === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"name-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.nameRepetition(node.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 3: Structure-based repetition (absorbed from repeated-frame-structure)\n // Skip if node is inside an INSTANCE subtree\n if (isInsideInstance(context)) return null;\n\n // Skip if parent is COMPONENT_SET\n if (context.parent?.type === \"COMPONENT_SET\") return null;\n\n // Skip if node has no children\n if (!node.children || node.children.length === 0) return null;\n\n const structureMinRepetitions =\n (options?.[\"structureMinRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"structureMinRepetitions\", 2);\n\n const maxFingerprintDepth =\n (options?.[\"maxFingerprintDepth\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"maxFingerprintDepth\", 3);\n\n // Compute fingerprint for this node\n const fingerprint = buildFingerprint(node, maxFingerprintDepth);\n\n // Access siblings (may be undefined)\n const siblings = context.siblings ?? [];\n\n // Filter siblings to qualifying frames (type === FRAME, not inside INSTANCE, has children)\n const qualifyingSiblings = siblings.filter(\n (s) =>\n s.type === \"FRAME\" &&\n s.children !== undefined &&\n s.children.length > 0\n );\n\n // Count siblings (including self) sharing the same fingerprint\n const matchingNodes = qualifyingSiblings.filter(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // Ensure self is counted (it should be in siblings, but add a guard)\n const selfIsInSiblings = qualifyingSiblings.some((s) => s.id === node.id);\n const count = selfIsInSiblings\n ? matchingNodes.length\n : matchingNodes.length + 1;\n\n if (count >= structureMinRepetitions) {\n // Only emit for the first sibling (by array order) with this fingerprint\n const firstMatch = qualifyingSiblings.find(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // If self is not in siblings list, treat self as first match when no earlier match exists\n const firstMatchId = firstMatch?.id ?? node.id;\n if (firstMatchId === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"structure-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.structureRepetition(node.name, count - 1),\n };\n }\n }\n\n return null;\n }\n\n // ========================================\n // Stage 4: Instance style override detection\n // Compares instance styles against component master.\n // Any style override (fills, strokes, effects, cornerRadius) means\n // the designer should use a variant instead.\n // ========================================\n if (node.type === \"INSTANCE\" && node.componentId) {\n const seenStage4 = getSeenStage4(context);\n if (seenStage4.has(node.componentId)) return null;\n\n const componentDefs = context.file.componentDefinitions;\n if (!componentDefs) return null;\n\n const master = componentDefs[node.componentId];\n if (!master) return null;\n\n // Compare style properties between master and instance\n const overrides = detectStyleOverrides(master, node);\n if (overrides.length > 0) {\n // Only mark as seen when we actually flag — allows other instances to be checked\n seenStage4.add(node.componentId);\n const componentMeta = context.file.components[node.componentId];\n const componentName = componentMeta?.name ?? node.name;\n\n return {\n ruleId: missingComponentDef.id,\n subType: \"style-override\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.styleOverride(componentName, overrides),\n };\n }\n return null;\n }\n\n return null;\n};\n\nexport const missingComponent = defineRule({\n definition: missingComponentDef,\n check: missingComponentCheck,\n});\n\n// ============================================\n// detached-instance\n// ============================================\n\nconst detachedInstanceDef: RuleDefinition = {\n id: \"detached-instance\",\n name: \"Detached Instance\",\n category: \"code-quality\",\n why: \"Detached instances lose component relationship — AI sees a one-off frame instead of a reusable component reference\",\n impact: \"AI generates duplicate code instead of reusing the component, inflating output and causing inconsistencies\",\n fix: \"Reset the instance or create a new variant if customization is needed\",\n};\n\nconst detachedInstanceCheck: RuleCheckFn = (node, context) => {\n // A detached instance would be a FRAME that was once an INSTANCE\n // This is hard to detect without historical data\n // Heuristic: Frame with a name that looks like it came from a component\n if (node.type !== \"FRAME\") return null;\n\n // Check if there's a component in the file with a matching name (word boundary)\n const components = context.file.components;\n\n for (const [, component] of Object.entries(components)) {\n const pattern = new RegExp(`\\\\b${component.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`);\n if (pattern.test(node.name)) {\n // This frame might be a detached instance of this component\n return {\n ruleId: detachedInstanceDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...detachedInstanceMsg(node.name, component.name),\n };\n }\n }\n\n return null;\n};\n\nexport const detachedInstance = defineRule({\n definition: detachedInstanceDef,\n check: detachedInstanceCheck,\n});\n\n// ============================================\n// variant-structure-mismatch\n// ============================================\n\nconst variantStructureMismatchDef: RuleDefinition = {\n id: \"variant-structure-mismatch\",\n name: \"Variant Structure Mismatch\",\n category: \"code-quality\",\n why: \"Variants with different child structures prevent AI from creating a unified component template\",\n impact: \"AI must generate separate implementations for each variant instead of a single parameterized component\",\n fix: \"Ensure all variants share the same child structure, using visibility toggles for optional elements\",\n};\n\nconst variantStructureMismatchCheck: RuleCheckFn = (node, context) => {\n // Only COMPONENT_SET\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.children?.length || node.children.length < 2) return null;\n\n // Build fingerprint for each variant child\n const fingerprints = node.children\n .filter(child => child.type === \"COMPONENT\")\n .map(child => buildFingerprint(child, 2));\n\n if (fingerprints.length < 2) return null;\n\n // Compare all fingerprints to the first one\n const base = fingerprints[0];\n const mismatched = fingerprints.filter(fp => fp !== base);\n\n if (mismatched.length === 0) return null;\n\n const mismatchCount = mismatched.length;\n const totalVariants = fingerprints.length;\n\n return {\n ruleId: variantStructureMismatchDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...variantStructureMismatchMsg(node.name, mismatchCount, totalVariants),\n };\n};\n\nexport const variantStructureMismatch = defineRule({\n definition: variantStructureMismatchDef,\n check: variantStructureMismatchCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getDefaultNameSubType, nonSemanticNameMsg, inconsistentNamingMsg, nonStandardNamingMsg } from \"../rule-messages.js\";\nimport { isExcludedName, isDefaultName, isNonSemanticName, STANDARD_STATE_NAMES, STATE_NAME_SUGGESTIONS, STATE_LIKE_PATTERN } from \"../node-semantics.js\";\n\nfunction capitalize(s: string): string {\n if (!s) return s;\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction detectNamingConvention(name: string): string | null {\n if (/^[a-z]+(-[a-z]+)*$/.test(name)) return \"kebab-case\";\n if (/^[a-z]+(_[a-z]+)*$/.test(name)) return \"snake_case\";\n if (/^[a-z]+([A-Z][a-z]*)*$/.test(name)) return \"camelCase\";\n if (/^[A-Z][a-z]+([A-Z][a-z]*)*$/.test(name)) return \"PascalCase\";\n if (/^[A-Z]+(_[A-Z]+)*$/.test(name)) return \"SCREAMING_SNAKE_CASE\";\n if (/\\s/.test(name)) return \"Title Case\";\n return null;\n}\n\n/** Single capitalized word is compatible with both PascalCase and Title Case */\nfunction isCompatible(nodeConvention: string, dominantConvention: string, name: string): boolean {\n if (!/^[A-Z][a-z]+$/.test(name)) return false;\n const pair = new Set([nodeConvention, dominantConvention]);\n return pair.has(\"PascalCase\") && pair.has(\"Title Case\");\n}\n\n/** Split a name into words regardless of convention */\nfunction splitWords(name: string): string[] {\n // Title Case / space-separated\n if (/\\s/.test(name)) return name.split(/\\s+/);\n // SCREAMING_SNAKE_CASE or snake_case\n if (name.includes(\"_\")) return name.split(\"_\");\n // kebab-case\n if (name.includes(\"-\")) return name.split(\"-\");\n // camelCase / PascalCase — split on uppercase boundaries (including acronym runs)\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1\\0$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1\\0$2\")\n .split(\"\\0\");\n}\n\n/** Convert a name to the target convention */\nfunction convertName(name: string, target: string): string {\n const words = splitWords(name);\n switch (target) {\n case \"kebab-case\":\n return words.map(w => w.toLowerCase()).join(\"-\");\n case \"snake_case\":\n return words.map(w => w.toLowerCase()).join(\"_\");\n case \"camelCase\":\n return words.map((w, i) => i === 0 ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"PascalCase\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"SCREAMING_SNAKE_CASE\":\n return words.map(w => w.toUpperCase()).join(\"_\");\n case \"Title Case\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\" \");\n default:\n return name;\n }\n}\n\n// ============================================\n// non-semantic-name (merged: default-name + non-semantic-name)\n// ============================================\n\nconst nonSemanticNameDef: RuleDefinition = {\n id: \"non-semantic-name\",\n name: \"Non-Semantic Name\",\n category: \"semantic\",\n why: \"Default or shape names give AI no semantic context — it cannot choose appropriate HTML tags or class names\",\n impact: \"AI generates generic <div> wrappers instead of semantic elements like <header>, <nav>, <article>\",\n fix: \"Rename with a descriptive, purpose-driven name (e.g., 'Header', 'ProductCard', 'Divider')\",\n};\n\nconst nonSemanticNameCheck: RuleCheckFn = (node, context) => {\n if (!node.name) return null;\n if (isExcludedName(node.name)) return null;\n\n // Check 1: Figma default names (Frame 1, Group 2, etc.)\n if (isDefaultName(node.name)) {\n return {\n ruleId: nonSemanticNameDef.id,\n subType: getDefaultNameSubType(node.type),\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n // Check 2: Shape-only names (rectangle, ellipse, vector, etc.)\n if (isNonSemanticName(node.name)) {\n // Allow shape names for actual shape primitives at leaf level\n if (!node.children || node.children.length === 0) {\n const shapeTypes = [\"RECTANGLE\", \"ELLIPSE\", \"VECTOR\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\"];\n if (shapeTypes.includes(node.type)) return null;\n }\n\n return {\n ruleId: nonSemanticNameDef.id,\n subType: \"shape-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n return null;\n};\n\nexport const nonSemanticName = defineRule({\n definition: nonSemanticNameDef,\n check: nonSemanticNameCheck,\n});\n\n// ============================================\n// inconsistent-naming-convention\n// ============================================\n\nconst inconsistentNamingConventionDef: RuleDefinition = {\n id: \"inconsistent-naming-convention\",\n name: \"Inconsistent Naming Convention\",\n category: \"semantic\",\n why: \"Mixed naming conventions (camelCase + kebab-case + Title Case) at the same level confuse AI pattern recognition\",\n impact: \"AI generates inconsistent class/component names, making the codebase harder to maintain\",\n fix: \"Pick one convention for sibling elements (e.g., kebab-case: 'product-card', or PascalCase: 'ProductCard') — AI maps names to CSS classes and component names, so mixed conventions produce inconsistent code\",\n};\n\nconst inconsistentNamingConventionCheck: RuleCheckFn = (node, context) => {\n if (!context.siblings || context.siblings.length < 2) return null;\n\n // Detect conventions used by siblings\n const conventions = new Map<string, number>();\n let ambiguousPascalCount = 0;\n\n for (const sibling of context.siblings) {\n if (!sibling.name) continue;\n const convention = detectNamingConvention(sibling.name);\n if (convention) {\n conventions.set(convention, (conventions.get(convention) ?? 0) + 1);\n if (convention === \"PascalCase\" && /^[A-Z][a-z]+$/.test(sibling.name)) {\n ambiguousPascalCount++;\n }\n }\n }\n\n // Single capitalized words (Header, Footer) are detected as PascalCase but are\n // equally valid as Title Case. When both conventions appear, discount these\n // ambiguous names so they don't bias the dominant convention toward PascalCase.\n if (conventions.has(\"PascalCase\") && conventions.has(\"Title Case\") && ambiguousPascalCount > 0) {\n const adjusted = (conventions.get(\"PascalCase\") ?? 0) - ambiguousPascalCount;\n if (adjusted <= 0) {\n conventions.delete(\"PascalCase\");\n } else {\n conventions.set(\"PascalCase\", adjusted);\n }\n }\n\n // Skip if we can't detect clear conventions\n if (conventions.size < 2) return null;\n\n // Find the dominant convention\n let dominantConvention = \"\";\n let maxCount = 0;\n for (const [convention, count] of conventions) {\n if (count > maxCount) {\n maxCount = count;\n dominantConvention = convention;\n }\n }\n\n // Check if current node violates the dominant convention\n const nodeConvention = detectNamingConvention(node.name);\n if (nodeConvention && nodeConvention !== dominantConvention && maxCount >= 2) {\n // Single capitalized word is compatible with both PascalCase and Title Case\n if (isCompatible(nodeConvention, dominantConvention, node.name)) return null;\n\n const suggested = convertName(node.name, dominantConvention);\n // #372: suppress when the case-conversion produces the same string as\n // the current name. Single-character names (\"X\"), all-numeric names, and\n // any input whose every word maps to itself across cases all fall into\n // this bucket — flagging them produces a no-op rename, an empty diff\n // visible as a misleading \"✅ resolved\" wrap-up entry.\n if (suggested === node.name) return null;\n return {\n ruleId: inconsistentNamingConventionDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n suggestedName: suggested,\n ...inconsistentNamingMsg(node.name, nodeConvention, dominantConvention, suggested),\n };\n }\n\n return null;\n};\n\nexport const inconsistentNamingConvention = defineRule({\n definition: inconsistentNamingConventionDef,\n check: inconsistentNamingConventionCheck,\n});\n\n// ============================================\n// non-standard-naming\n// ============================================\n\nconst nonStandardNamingDef: RuleDefinition = {\n id: \"non-standard-naming\",\n name: \"Non-Standard Naming\",\n category: \"semantic\",\n why: \"Non-standard state names prevent interaction rules from detecting state variants — AI cannot generate correct :hover/:active/:disabled styles\",\n impact: \"Interaction state detection fails, resulting in static UI with no state transitions\",\n fix: \"Use platform-standard state names: default, hover, active, pressed, selected, highlighted, disabled, enabled, focus, focused, dragged\",\n};\n\nconst nonStandardNamingCheck: RuleCheckFn = (node, context) => {\n // Only check COMPONENT_SET (variant container)\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.componentPropertyDefinitions) return null;\n\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n\n for (const opt of options) {\n if (typeof opt !== \"string\") continue;\n const lower = opt.toLowerCase().trim();\n\n // Skip if it's a standard name\n if (STANDARD_STATE_NAMES.has(lower)) continue;\n\n // Check if it matches a known non-standard state name\n if (STATE_LIKE_PATTERN.test(opt)) {\n const suggestion = STATE_NAME_SUGGESTIONS[lower];\n if (suggestion) {\n return {\n ruleId: nonStandardNamingDef.id,\n subType: \"state-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n suggestedName: capitalize(suggestion),\n ...nonStandardNamingMsg.stateName(node.name, opt, suggestion),\n };\n }\n }\n }\n }\n\n return null;\n};\n\nexport const nonStandardNaming = defineRule({\n definition: nonStandardNamingDef,\n check: nonStandardNamingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport type { MissingInteractionStateSubType, MissingPrototypeSubType } from \"../rule-messages.js\";\nimport { missingInteractionStateMsg, missingPrototypeMsg } from \"../rule-messages.js\";\nimport { getStatefulComponentType, isOverlayNode, isCarouselNode, type StatefulComponentType } from \"../node-semantics.js\";\n\n/** Expected state variants by interactive type */\nconst EXPECTED_STATES: Record<StatefulComponentType, MissingInteractionStateSubType[]> = {\n button: [\"hover\", \"active\", \"disabled\"],\n link: [\"hover\"],\n tab: [\"hover\", \"active\"],\n input: [\"focus\", \"disabled\"],\n toggle: [\"disabled\"],\n};\n\n/** State name patterns — web + mobile platform standard names */\nconst STATE_PATTERNS: Record<MissingInteractionStateSubType, RegExp> = {\n hover: /\\bhover\\b/i,\n disabled: /\\bdisabled\\b/i,\n active: /\\b(active|pressed|selected|highlighted)\\b/i,\n focus: /\\bfocus(ed)?\\b/i,\n};\n\n// ============================================\n// Helpers\n// ============================================\n\n/** Dedup key: emit at most one violation per componentId + subType */\nconst SEEN_KEY = \"missing-interaction-state:seen\";\n\nfunction getSeen(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_KEY, () => new Set<string>());\n}\n\n/**\n * Check if a state variant exists via componentPropertyDefinitions.\n * Looks for VARIANT type properties where variantOptions contain the state name.\n */\nfunction hasStateInVariantProps(node: AnalysisNode, statePattern: RegExp): boolean {\n if (!node.componentPropertyDefinitions) return false;\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n if (options.some((opt) => typeof opt === \"string\" && statePattern.test(opt))) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if a state variant exists via component master's componentPropertyDefinitions.\n * Falls back to componentDefinitions (fetched masters) when the instance itself\n * doesn't carry the property definitions.\n */\nfunction hasStateInComponentMaster(\n node: AnalysisNode,\n context: RuleContext,\n statePattern: RegExp,\n): boolean {\n if (!node.componentId) return false;\n const defs = context.file.componentDefinitions;\n if (!defs) return false;\n const master = defs[node.componentId];\n if (!master) return false;\n return hasStateInVariantProps(master, statePattern);\n}\n\n/**\n * Master names that look like a single variant of a SET (e.g. `State=Default`,\n * `Variant=Primary, State=Default, Size=Medium`). When a fetched COMPONENT\n * carries this naming AND has no own `componentPropertyDefinitions`, the\n * variant axes live on the parent COMPONENT_SET — which the loader does not\n * fetch today (#397). Treat as undeterminable rather than asserting a missing\n * variant we cannot actually see.\n */\nconst VARIANT_POSITION_NAME_RE = /^[\\w ]+=[^,]+(,\\s*[\\w ]+=[^,]+)*$/;\n\nfunction hasUsablePropDefs(propDefs: unknown): boolean {\n // `undefined` = not fetched; `null` = REST returned blank (e.g. variant\n // INSIDE a SET — axes live on the SET parent, not here). Both are\n // non-evidence. `{}` (fetched-and-empty) IS positive evidence the master\n // truly has no axes — must keep firing per the test for #354.\n return propDefs != null && typeof propDefs === \"object\";\n}\n\n/**\n * Decide whether we have enough source data to assert a state variant is missing.\n *\n * The Figma REST API does not consistently mirror `componentPropertyDefinitions`\n * onto deeply-nested INSTANCE children, and `context.file.componentDefinitions`\n * only contains masters the loader actually fetched (external-library masters\n * stay null even after extra passes). When BOTH paths are empty for an INSTANCE\n * we cannot tell whether the master defines the variant or not — treat that as\n * \"unknown\" (return false here) rather than asserting a missing variant.\n *\n * The fetched master may also be a single variant of a SET (name like\n * `State=Default`); the variant axes live on the SET parent which we do not\n * fetch. Detect this via name pattern and treat as undeterminable too (#397).\n *\n * COMPONENT nodes are special: a COMPONENT IS the master, so the absence of\n * `componentPropertyDefinitions` on a COMPONENT is itself meaningful evidence\n * (standalone master with no variant axis at all) — UNLESS the COMPONENT name\n * follows the variant-position pattern, in which case the SET parent holds the\n * axes and we cannot decide.\n */\nfunction canDetermineVariants(node: AnalysisNode, context: RuleContext): boolean {\n if (hasUsablePropDefs(node.componentPropertyDefinitions)) return true;\n if (node.type === \"COMPONENT\") {\n return !VARIANT_POSITION_NAME_RE.test(node.name);\n }\n if (node.componentId !== undefined) {\n const defs = context.file.componentDefinitions;\n const master = defs?.[node.componentId];\n if (master) {\n if (hasUsablePropDefs(master.componentPropertyDefinitions)) return true;\n return !VARIANT_POSITION_NAME_RE.test(master.name);\n }\n }\n return false;\n}\n\n// ============================================\n// missing-interaction-state\n// ============================================\n\nconst missingInteractionStateDef: RuleDefinition = {\n id: \"missing-interaction-state\",\n name: \"Missing Interaction State\",\n category: \"interaction\",\n why: \"Interactive components without state variants force AI to guess hover/focus/disabled appearances — or skip them entirely\",\n impact: \"Generated code has no :hover, :focus, or :disabled styles, making the UI feel static and unresponsive\",\n fix: \"Add state variants (Hover, Disabled, Focus, Active) to interactive components in Figma\",\n};\n\nconst missingInteractionStateCheck: RuleCheckFn = (node, context) => {\n // Only check component instances and components\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\") return null;\n\n const interactiveType = getStatefulComponentType(node);\n if (!interactiveType) return null;\n\n const expectedStates = EXPECTED_STATES[interactiveType];\n if (!expectedStates) return null;\n\n // Probe gate: only assert a missing variant when we can actually observe the\n // master's variant axes. For nested INSTANCE children whose master was not\n // fetched into `componentDefinitions` and whose own `componentPropertyDefinitions`\n // is undefined, treat the verdict as unknown and skip — this avoids the\n // false-positive class described in #354. The data-availability check is\n // per-node (not per-state), so it lives outside the for-loop below.\n if (!canDetermineVariants(node, context)) return null;\n\n const seen = getSeen(context);\n const nodePath = context.path.join(\" > \");\n\n for (const state of expectedStates) {\n const dedupeKey = `${node.componentId ?? node.id}:${state}`;\n if (seen.has(dedupeKey)) continue;\n\n const pattern = STATE_PATTERNS[state];\n\n // Check variant properties on instance\n if (hasStateInVariantProps(node, pattern)) continue;\n\n // Check variant properties on component master (fetched definitions)\n if (hasStateInComponentMaster(node, context, pattern)) continue;\n\n // Missing state — report first missing one\n seen.add(dedupeKey);\n return {\n ruleId: missingInteractionStateDef.id,\n subType: state,\n nodeId: node.id,\n nodePath,\n ...missingInteractionStateMsg[state](node.name),\n };\n }\n\n return null;\n};\n\nexport const missingInteractionState = defineRule({\n definition: missingInteractionStateDef,\n check: missingInteractionStateCheck,\n});\n\n// ============================================\n// missing-prototype\n// ============================================\n\n/** Interactive types that need click prototype */\nconst PROTOTYPE_TYPES: Record<StatefulComponentType, MissingPrototypeSubType> = {\n button: \"button\",\n link: \"navigation\",\n tab: \"tab\",\n input: \"input\",\n toggle: \"toggle\",\n};\n\nfunction getPrototypeSubType(node: AnalysisNode): MissingPrototypeSubType | null {\n // Check overlay/carousel first — select/dropdown are classified as \"input\" in\n // STATEFUL_PATTERNS but need \"overlay\" subType for prototype checks\n if (isOverlayNode(node)) return \"overlay\";\n if (isCarouselNode(node)) return \"carousel\";\n const interactiveType = getStatefulComponentType(node);\n if (interactiveType) {\n const mapped = PROTOTYPE_TYPES[interactiveType];\n if (mapped) return mapped;\n }\n return null;\n}\n\nfunction hasInteractionTrigger(node: AnalysisNode, triggerType: string): boolean {\n if (!node.interactions || !Array.isArray(node.interactions)) return false;\n return node.interactions.some((interaction) => {\n const i = interaction as { trigger?: { type?: string } };\n return i.trigger?.type === triggerType;\n });\n}\n\n/** Check if node (or its component master) has any of the given trigger types */\nfunction hasAnyInteraction(node: AnalysisNode, context: RuleContext, triggers: string[]): boolean {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(node, trigger)) return true;\n }\n // INSTANCE nodes don't inherit interactions from master — check master fallback\n if (node.componentId && context.file.componentDefinitions) {\n const master = context.file.componentDefinitions[node.componentId];\n if (master) {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(master, trigger)) return true;\n }\n }\n }\n return false;\n}\n\n/** Trigger types to check per subType */\nconst PROTOTYPE_TRIGGERS: Record<string, string[]> = {\n carousel: [\"ON_CLICK\", \"ON_DRAG\"],\n};\n\nconst DEFAULT_TRIGGERS = [\"ON_CLICK\"];\n\nconst missingPrototypeDef: RuleDefinition = {\n id: \"missing-prototype\",\n name: \"Missing Prototype\",\n category: \"interaction\",\n why: \"Interactive elements without prototype interactions give AI no information about navigation or behavior\",\n impact: \"AI cannot generate interaction handlers, routing, or state changes — interactive elements become static\",\n fix: \"Add prototype interactions (ON_CLICK, ON_DRAG) to define navigation targets or state changes\",\n};\n\nconst SEEN_PROTO_KEY = \"missing-prototype:seen\";\n\nfunction getSeenProto(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_PROTO_KEY, () => new Set<string>());\n}\n\nconst missingPrototypeCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\" && node.type !== \"FRAME\") return null;\n\n const subType = getPrototypeSubType(node);\n if (!subType) return null;\n\n // Already has relevant interaction (click, or drag for carousel)\n const triggers = PROTOTYPE_TRIGGERS[subType] ?? DEFAULT_TRIGGERS;\n if (hasAnyInteraction(node, context, triggers)) return null;\n\n // Dedup per componentId + subType\n const seen = getSeenProto(context);\n const dedupeKey = `${node.componentId ?? node.id}:${subType}`;\n if (seen.has(dedupeKey)) return null;\n seen.add(dedupeKey);\n\n return {\n ruleId: missingPrototypeDef.id,\n subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingPrototypeMsg[subType](node.name),\n };\n};\n\nexport const missingPrototype = defineRule({\n definition: missingPrototypeDef,\n check: missingPrototypeCheck,\n});\n","#!/usr/bin/env node\nimport { createRequire } from \"node:module\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\nimport { writeFile } from \"node:fs\";\nimport { exec } from \"node:child_process\";\nimport { analyzeFile } from \"../core/engine/rule-engine.js\";\nimport { loadFile, isJsonFile, isFixtureDir } from \"../core/engine/loader.js\";\nimport { calculateScores, buildResultJson } from \"../core/engine/scoring.js\";\nimport { generateGotchaSurvey } from \"../core/gotcha/survey-generator.js\";\nimport { generateHtmlReport } from \"../core/report-html/index.js\";\nimport { getReportsDir, ensureReportsDir } from \"../core/engine/config-store.js\";\nimport { getConfigsWithPreset, RULE_CONFIGS, type Preset } from \"../core/rules/rule-config.js\";\nimport { loadConfigFile, mergeConfigs } from \"../core/rules/config-loader.js\";\nimport { ruleRegistry } from \"../core/rules/rule-registry.js\";\nimport type { RuleConfig, RuleId } from \"../core/contracts/rule.js\";\nimport { initMonitoring, trackEvent, trackError, shutdownMonitoring, EVENTS } from \"../core/monitoring/index.js\";\nimport { POSTHOG_API_KEY as BUILTIN_PH_KEY, SENTRY_DSN as BUILTIN_SENTRY_DSN } from \"../core/monitoring/keys.js\";\nimport { getTelemetryEnabled, getPosthogApiKey, getSentryDsn, getDeviceId } from \"../core/engine/config-store.js\";\nimport { AcknowledgmentSchema } from \"../core/contracts/acknowledgment.js\";\nimport { computeDesignKey } from \"../core/contracts/design-key.js\";\n\n// Load .env for FIGMA_TOKEN (quiet: suppress dotenv's stdout banner — MCP uses stdout for JSON-RPC)\nconfig({ quiet: true });\n\n// Import rules to register them\nimport \"../core/rules/index.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../../package.json\") as { version: string };\n\nconst server = new McpServer({\n name: \"canicode\",\n version: pkg.version,\n});\n\nserver.tool(\n \"analyze\",\n `Analyze a Figma design for development-friendliness and AI-friendliness.\n\nProvide a Figma URL or fixture path via the input parameter. Requires FIGMA_TOKEN env var or the token parameter for live Figma URLs.`,\n {\n input: z.string().describe(\"Figma URL or local fixture path. Requires FIGMA_TOKEN for live URLs.\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n preset: z.enum([\"relaxed\", \"dev-friendly\", \"ai-ready\", \"strict\"]).optional().describe(\"Analysis preset\"),\n targetNodeId: z.string().optional().describe(\"Scope analysis to a specific node ID\"),\n configPath: z.string().optional().describe(\"Path to config JSON file for rule overrides\"),\n openReport: z.boolean().optional().describe(\"Open the generated HTML report in the user's browser. Defaults to false — opt in only when a visible report is the explicit user request (#365). The HTML file is always written to disk regardless.\"),\n acknowledgments: z.array(AcknowledgmentSchema).optional().describe(\"(#371 / ADR-019) Pre-resolved acknowledgments from canicode-authored Figma annotations (e.g. via readCanicodeAcknowledgments in a use_figma batch). Each entry includes nodeId and ruleId; newer annotations may also carry intent, sceneWriteOutcome, and codegenDirective from a canicode-json fenced block (#444). Matching issues are flagged acknowledged and contribute half weight to the density score.\"),\n scope: z.enum([\"page\", \"component\"]).optional().describe(\"(#404) Override analysis scope — `page` (screen/section where container bounds are required) or `component` (standalone reusable unit where root FILL is the design contract). Defaults to auto-detection from the root node type: `COMPONENT` / `COMPONENT_SET` / `INSTANCE` roots resolve to `component`, everything else to `page`.\"),\n },\n {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Analyze Figma Design\",\n },\n async ({ input, token, preset, targetNodeId, configPath, openReport, acknowledgments, scope }) => {\n trackEvent(EVENTS.MCP_TOOL_CALLED, { tool: \"analyze\" });\n try {\n // Fetch via REST API or load from fixture\n const { file, nodeId } = await loadFile(input, token);\n\n const effectiveNodeId = targetNodeId ?? nodeId;\n\n let configs: Record<string, RuleConfig> = preset\n ? { ...getConfigsWithPreset(preset as Preset) }\n : { ...RULE_CONFIGS };\n\n if (configPath) {\n const configFile = await loadConfigFile(configPath);\n configs = mergeConfigs(configs, configFile);\n }\n\n const result = analyzeFile(file, {\n configs: configs as Record<RuleId, RuleConfig>,\n ...(effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}),\n ...(acknowledgments && acknowledgments.length > 0\n ? { acknowledgments }\n : {}),\n ...(scope ? { scope } : {}),\n });\n\n const scores = calculateScores(result, configs as Record<RuleId, RuleConfig>);\n\n // Generate HTML report (with Figma token for comment buttons)\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n const html = generateHtmlReport(file, result, scores, { figmaToken });\n\n // Save report to disk\n const now = new Date();\n const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}-${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}`;\n ensureReportsDir();\n const reportPath = `${getReportsDir()}/report-${ts}-${file.fileKey}.html`;\n await new Promise<void>((resolve, reject) => {\n writeFile(reportPath, html, \"utf-8\", (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n\n // #365: only open the report in the user's browser when explicitly\n // requested. The MCP `analyze` tool is machine-callable from skill\n // workflows (e.g. `/canicode-roundtrip` Step 1 + Step 5), where\n // popping a browser tab mid-conversation breaks flow. The HTML file\n // is still written to disk so follow-up sessions can open it manually.\n if (openReport === true) {\n const openCmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n exec(`${openCmd} \"${reportPath}\"`);\n }\n\n trackEvent(EVENTS.ANALYSIS_COMPLETED, {\n nodeCount: result.nodeCount,\n issueCount: result.issues.length,\n grade: scores.overall.grade,\n percentage: scores.overall.percentage,\n source: isJsonFile(input) || isFixtureDir(input) ? \"fixture\" : \"figma\",\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(buildResultJson(file.name, result, scores, { fileKey: file.fileKey, designKey: computeDesignKey(input) }), null, 2),\n },\n ],\n };\n } catch (error) {\n trackError(\n error instanceof Error ? error : new Error(String(error)),\n { tool: \"analyze\" },\n );\n trackEvent(EVENTS.ANALYSIS_FAILED, {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Error: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"gotcha-survey\",\n `Generate a gotcha survey from a Figma design analysis.\n\nAnalyzes the design and returns a GotchaSurvey JSON with designGrade, isReadyForCodeGen, and questions[].\nWhen isReadyForCodeGen is true, questions will be empty (no survey needed).\n\nProvide a Figma URL or fixture path via the input parameter. Requires FIGMA_TOKEN env var or the token parameter for live Figma URLs.`,\n {\n input: z.string().describe(\"Figma URL or local fixture path. Requires FIGMA_TOKEN for live URLs.\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n preset: z.enum([\"relaxed\", \"dev-friendly\", \"ai-ready\", \"strict\"]).optional().describe(\"Analysis preset\"),\n targetNodeId: z.string().optional().describe(\"Scope analysis to a specific node ID\"),\n configPath: z.string().optional().describe(\"Path to config JSON file for rule overrides\"),\n scope: z.enum([\"page\", \"component\"]).optional().describe(\"(#404) Override analysis scope — `page` or `component`. Defaults to auto-detection from the root node type.\"),\n },\n {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Gotcha Survey\",\n },\n async ({ input, token, preset, targetNodeId, configPath, scope }) => {\n trackEvent(EVENTS.MCP_TOOL_CALLED, { tool: \"gotcha-survey\" });\n try {\n const { file, nodeId } = await loadFile(input, token);\n\n const effectiveNodeId = targetNodeId ?? nodeId;\n\n let configs: Record<string, RuleConfig> = preset\n ? { ...getConfigsWithPreset(preset as Preset) }\n : { ...RULE_CONFIGS };\n\n if (configPath) {\n const configFile = await loadConfigFile(configPath);\n configs = mergeConfigs(configs, configFile);\n }\n\n const result = analyzeFile(file, {\n configs: configs as Record<RuleId, RuleConfig>,\n ...(effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}),\n ...(scope ? { scope } : {}),\n });\n\n const scores = calculateScores(result, configs as Record<RuleId, RuleConfig>);\n const survey = generateGotchaSurvey(result, scores, { designKey: computeDesignKey(input) });\n\n trackEvent(EVENTS.ANALYSIS_COMPLETED, {\n nodeCount: result.nodeCount,\n issueCount: result.issues.length,\n grade: scores.overall.grade,\n percentage: scores.overall.percentage,\n source: isJsonFile(input) || isFixtureDir(input) ? \"fixture\" : \"figma\",\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(survey, null, 2),\n },\n ],\n };\n } catch (error) {\n trackError(\n error instanceof Error ? error : new Error(String(error)),\n { tool: \"gotcha-survey\" },\n );\n trackEvent(EVENTS.ANALYSIS_FAILED, {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Error: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"list-rules\",\n \"List all available analysis rules with their current configuration\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"List Analysis Rules\",\n },\n async () => {\n const rules = ruleRegistry.getAll().map((rule) => {\n const config =\n RULE_CONFIGS[rule.definition.id as keyof typeof RULE_CONFIGS];\n return {\n id: rule.definition.id,\n name: rule.definition.name,\n category: rule.definition.category,\n severity: config?.severity,\n score: config?.score,\n enabled: config?.enabled,\n why: rule.definition.why,\n };\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(rules, null, 2),\n },\n ],\n };\n },\n);\n\nserver.tool(\n \"version\",\n \"Get the current canicode version. Use this when the user asks what version is installed.\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Version\",\n },\n async () => ({\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}` }],\n }),\n);\n\nserver.tool(\n \"docs\",\n `Get documentation for CanICode.\n\nAvailable topics:\n- setup: Installation and token configuration\n- scoring: Scoring model formula (density+diversity, severity weights, grades)\n- rules: All rule IDs with default scores and severity\n- config: Config overrides (scores, severity, node exclusions, thresholds)\n- visual-compare: Pixel-level comparison between Figma and AI-generated code\n- design-tree: Generate DOM-like design tree from fixture for AI code generation\n- all: Full customization guide\n\nUse this when the user asks about how to use canicode, configuration, rules, visual comparison, or any feature.`,\n {\n topic: z.enum([\"all\", \"setup\", \"scoring\", \"rules\", \"config\", \"visual-compare\", \"design-tree\"]).optional()\n .describe(\"Topic to retrieve. Default: all\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Documentation\",\n },\n async ({ topic }) => {\n const selectedTopic = topic ?? \"all\";\n\n // Inline topics (not from CUSTOMIZATION.md)\n const inlineTopics: Record<string, string> = {\n \"setup\": `# Setup\n\n## CLI\n\\`\\`\\`bash\nnpm install -g canicode\ncanicode init --token figd_xxxxxxxxxxxxx\n\\`\\`\\`\n\nGet your token: Figma → Settings → Security → Personal access tokens → Generate new token\n\n## MCP Server (Claude Code / Cursor / Claude Desktop)\n\\`\\`\\`bash\nclaude mcp add canicode -- npx --yes --package=canicode canicode-mcp\n\\`\\`\\`\n\nRequires FIGMA_TOKEN for live Figma URL analysis. The MCP server reads it from \\`~/.canicode/config.json\\` (set via \\`canicode init --token …\\`) or from the host's environment, so do **not** pass \\`-e FIGMA_TOKEN=…\\` to \\`claude mcp add\\` — \\`@anthropic-ai/claude-code\\`'s current parser rejects short-form flags placed before \\`--\\`. (#364, #366)\n\n## CLI only (no MCP server)\n\nUser-facing MCP tools have CLI equivalents with the same JSON shape, so skills and scripts can run without installing the canicode MCP server:\n\n\\`\\`\\`bash\nnpx canicode analyze <input>\nnpx canicode gotcha-survey <input> --json\n\\`\\`\\`\n\nThe CLI spawns per call (slower than the long-running MCP server) but needs no extra setup beyond \\`FIGMA_TOKEN\\`.`,\n\n \"visual-compare\": `# Visual Compare\n\nPixel-level comparison between Figma design and AI-generated code.\n\n## Usage\n\\`\\`\\`bash\ncanicode visual-compare ./index.html --figma-url 'https://www.figma.com/design/ABC/File?node-id=1-234'\n\\`\\`\\`\n\n## Options\n| Option | Default | Description |\n|--------|---------|-------------|\n| --figma-url <url> | (required) | Figma URL with node-id |\n| --token <token> | FIGMA_TOKEN env | Figma API token |\n| --output <dir> | /tmp/canicode-visual-compare | Output directory |\n| --width <px> | (inferred from Figma PNG ÷ scale) | Logical viewport width in CSS px |\n| --height <px> | (inferred from Figma PNG ÷ scale) | Logical viewport height in CSS px |\n| --figma-scale <n> | 2 | Figma export scale (matches @2x fixture PNGs) |\n\nViewport and device pixel ratio are auto-inferred from the Figma PNG dimensions and export scale. Override only when needed.\n\n## Output Files\n/tmp/canicode-visual-compare/\n figma.png — Figma screenshot (at export scale, default @2x)\n code.png — Playwright render of your HTML\n diff.png — Pixel diff (red = different)\n\n## JSON Output (stdout)\n{\n \"similarity\": 87,\n \"diffPixels\": 1340,\n \"totalPixels\": 102400,\n \"width\": 800, \"height\": 600,\n \"figmaScreenshot\": \"...\", \"codeScreenshot\": \"...\", \"diff\": \"...\"\n}\n\n## How It Works\n1. Fetches Figma screenshot via REST API (scale=2)\n2. Reads screenshot dimensions\n3. Renders HTML with Playwright at same viewport size\n4. Compares pixel-by-pixel with pixelmatch (threshold: 0.1)\n\n## Requirements\n- npx playwright install chromium\n- Figma API token with read access`,\n\n \"scoring\": `# Scoring Model\n\nScore = density (70%) + diversity (30%), averaged across 6 categories.\n\n## Severity weights\n\n| Severity | Weight |\n|----------|--------|\n| blocking | 3.0x |\n| risk | 2.0x |\n| missing-info | 1.0x |\n| suggestion | 0.5x |\n\n## Grades\n\n| Grade | Min score |\n|-------|-----------|\n| S | 95 |\n| A+ | 90 |\n| A | 85 |\n| B+ | 80 |\n| B | 75 |\n| C+ | 70 |\n| C | 65 |\n| D | 50 |\n| F | <50 |\n\nFloor: 5% minimum.\n\nFull documentation: https://github.com/let-sunny/canicode/wiki/Scoring-Model`,\n\n \"design-tree\": `# Design Tree\n\nGenerate a DOM-like design tree from a Figma fixture. Converts the node tree to a concise text format with inline CSS styles — 50-100x smaller than raw JSON.\n\n## Usage\n\\`\\`\\`bash\ncanicode design-tree ./fixtures/design\ncanicode design-tree ./fixtures/design --output tree.txt\ncanicode design-tree \"https://www.figma.com/design/ABC/File?node-id=1-234\"\n\\`\\`\\`\n\n## Output Format\nEach node = one line with name, type, dimensions, followed by CSS-ready styles:\n\\`\\`\\`\nHero Form (INSTANCE, 375x960)\n style: display: flex; flex-direction: column; gap: 32px; padding: 160px 24px; background: #F5F5F5\n Title (TEXT, 117x58)\n style: font-family: \"Inter\"; font-weight: 700; font-size: 48px; color: #2C2C2C; text: \"Title\"\n\\`\\`\\`\n\n## Use Cases\n- AI code generation — feed this to an LLM instead of raw 250KB fixture JSON\n- Calibration pipeline — Converter uses this for accurate code reproduction\n- Debugging — quickly see the design structure and styles`,\n };\n\n // Check inline topics first\n if (selectedTopic in inlineTopics) {\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${inlineTopics[selectedTopic]}` }],\n };\n }\n\n // Fall back to CUSTOMIZATION.md for config/rules/all\n const { readFile } = await import(\"node:fs/promises\");\n const { resolve, dirname } = await import(\"node:path\");\n const { fileURLToPath } = await import(\"node:url\");\n\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n const docPath = resolve(__dirname, \"../../docs/CUSTOMIZATION.md\");\n let content: string;\n\n try {\n content = await readFile(docPath, \"utf-8\");\n } catch {\n const altPath = resolve(__dirname, \"../docs/CUSTOMIZATION.md\");\n content = await readFile(altPath, \"utf-8\");\n }\n\n if (selectedTopic !== \"all\") {\n const sections: Record<string, string> = {\n \"config\": \"## Config Overrides\",\n \"rules\": \"### All Rule IDs\",\n };\n const header = sections[selectedTopic];\n if (header) {\n const startIdx = content.indexOf(header);\n if (startIdx !== -1) {\n const nextH2 = content.indexOf(\"\\n## \", startIdx + header.length);\n content = nextH2 !== -1\n ? content.slice(startIdx, nextH2)\n : content.slice(startIdx);\n }\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${content}` }],\n };\n } catch {\n return {\n content: [{ type: \"text\" as const, text: \"Documentation not found. See: https://github.com/let-sunny/canicode\" }],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"visual-compare\",\n `Compare AI-generated code against a Figma design at the pixel level.\n\nTakes an HTML file path and a Figma URL, renders the HTML with Playwright,\nfetches the Figma screenshot, and computes pixel-level similarity using pixelmatch.\n\nReturns similarity percentage (0-100%), diff pixel count, and paths to\nthe Figma screenshot, code screenshot, and diff image.\n\nLogical viewport and device pixel ratio are inferred from the Figma PNG export scale (default 2×) so code.png matches figma.png pixels.\n\nRequires: Playwright with Chromium installed, Figma API token.`,\n {\n codePath: z.string().describe(\"Path to the HTML file to render and compare\"),\n figmaUrl: z.string().describe(\"Figma URL with node-id (e.g., https://www.figma.com/design/ABC/File?node-id=1-234)\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n outputDir: z.string().optional().describe(\"Output directory for screenshots (default: /tmp/canicode-visual-compare)\"),\n figmaExportScale: z.number().int().min(1).max(4).optional().describe(\"Figma export scale (default 2, matches @2x fixture PNGs)\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Visual Compare\",\n },\n async ({ codePath, figmaUrl, token, outputDir, figmaExportScale }) => {\n try {\n const { visualCompare } = await import(\"../core/comparison/visual-compare.js\");\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n if (!figmaToken) {\n return {\n content: [{ type: \"text\" as const, text: \"Error: Figma token required. Provide via token parameter or FIGMA_TOKEN env var.\" }],\n isError: true,\n };\n }\n\n const result = await visualCompare({\n figmaUrl,\n figmaToken,\n codePath,\n outputDir,\n ...(figmaExportScale !== undefined ? { figmaExportScale } : {}),\n });\n\n return {\n content: [{\n type: \"text\" as const,\n text: JSON.stringify({\n similarity: result.similarity,\n diffPixels: result.diffPixels,\n totalPixels: result.totalPixels,\n width: result.width,\n height: result.height,\n figmaScreenshot: result.figmaScreenshotPath,\n codeScreenshot: result.codeScreenshotPath,\n diff: result.diffPath,\n }, null, 2),\n }],\n };\n } catch (error) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${error instanceof Error ? error.message : String(error)}` }],\n isError: true,\n };\n }\n },\n);\n\nasync function main() {\n const monitoringConfig: Parameters<typeof initMonitoring>[0] = {\n environment: \"mcp\",\n version: pkg.version,\n enabled: getTelemetryEnabled(),\n };\n const phKey = getPosthogApiKey() || BUILTIN_PH_KEY;\n if (phKey) monitoringConfig.posthogApiKey = phKey;\n const sDsn = getSentryDsn() || BUILTIN_SENTRY_DSN;\n if (sDsn) monitoringConfig.sentryDsn = sDsn;\n monitoringConfig.distinctId = getDeviceId();\n initMonitoring(monitoringConfig);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nprocess.on(\"beforeExit\", () => {\n shutdownMonitoring();\n});\n\nmain().catch(console.error);\n"]}
1
+ {"version":3,"sources":["../../src/core/comparison/visual-compare-helpers.ts","../../src/core/comparison/visual-compare.ts","../../src/core/contracts/category.ts","../../src/core/contracts/severity.ts","../../src/core/contracts/rule.ts","../../src/core/rules/rule-config.ts","../../src/core/rules/rule-registry.ts","../../src/core/contracts/acknowledgment.ts","../../src/core/contracts/analysis-scope.ts","../../src/core/engine/rule-engine.ts","../../src/core/adapters/figma-client.ts","../../src/core/adapters/figma-transformer.ts","../../src/core/adapters/component-resolver.ts","../../src/core/contracts/figma-node.ts","../../src/core/adapters/figma-file-loader.ts","../../src/core/adapters/figma-url-parser.ts","../../src/core/engine/config-store.ts","../../src/core/engine/loader.ts","../../src/core/adapters/instance-id-parser.ts","../../src/core/gotcha/apply-context.ts","../../package.json","../../src/core/engine/scoring.ts","../../src/core/rules/gotcha-questions.ts","../../src/core/gotcha/group-and-batch-questions.ts","../../src/core/gotcha/survey-generator.ts","../../src/core/ui-constants.ts","../../src/core/ui-helpers.ts","../../src/core/report-html/render.ts","../../src/core/report-html/index.ts","../../src/core/rules/config-loader.ts","../../src/core/monitoring/events.ts","../../src/core/monitoring/capture.ts","../../src/core/monitoring/index.ts","../../src/core/monitoring/keys.ts","../../src/core/contracts/design-key.ts","../../src/core/rules/node-semantics.ts","../../src/core/rules/rule-exceptions.ts","../../src/core/rules/rule-messages.ts","../../src/core/rules/structure/index.ts","../../src/core/rules/token/index.ts","../../src/core/rules/component/index.ts","../../src/core/rules/naming/index.ts","../../src/core/rules/interaction/index.ts","../../src/mcp/server.ts"],"names":["resolve","statSync","readFileSync","width","height","mkdirSync","dirname","writeFileSync","existsSync","PNG","z","config","BATCH_SIZE","join","response","file","componentDefs","interactionDests","findNodeById","esc","readFile","version","isFigmaUrl","require","visualCompare"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBO,SAAS,iBAAiB,QAAA,EAA0B;AACzD,EAAA,OAAO,eAAA,CAAgB,QAAA,CAAS,QAAQ,CAAA,GAAI,CAAA,GAAI,CAAA;AAClD;AAoBO,SAAS,iBAAA,CAAkB,OAAA,EAAiB,MAAA,EAAgB,KAAA,EAAuB;AAExF,EAAA,MAAM,UAAA,GAAa,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA;AAC3C,EAAA,OAAOA,OAAAA,CAAQ,iBAAiB,CAAA,EAAG,OAAO,IAAI,UAAU,CAAA,CAAA,EAAI,KAAK,CAAA,KAAA,CAAO,CAAA;AAC1E;AAKO,SAAS,aAAa,SAAA,EAA4B;AACvD,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,GAAQC,SAAS,SAAS,CAAA;AAChC,IAAA,OAAO,IAAA,CAAK,GAAA,EAAI,GA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,IAAA,GAAO;AACpB,EAAA,MAAM,gBAAA,GAAyD;AAAA,IAC7D,WAAA,EAAa,KAAA;AAAA,IACb,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,SAAS,mBAAA;AAAoB,GAC/B;AACA,EAAA,MAAM,KAAA,GAAQ,kBAAiB,IAAK,eAAA;AACpC,mBAA4B,aAAA,GAAgB,KAAA;AAC5C,EAAA,MAAM,IAAA,GAAO,cAAa,IAAK,UAAA;AAC/B,mBAA2B,SAAA,GAAY,IAAA;AACvC,EAAA,gBAAA,CAAiB,aAAa,WAAA,EAAY;AAC1C,EAAA,cAAA,CAAe,gBAAgB,CAAA;AAE/B,EAAA,MAAM,SAAA,GAAY,IAAI,oBAAA,EAAqB;AAC3C,EAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAChC;AAEA,OAAA,CAAQ,EAAA,CAAG,cAAc,MAAM;AAC7B,EAAA,kBAAA,EAAmB;AACrB,CAAC,CAAA;AAED,IAAA,EAAK,CAAE,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA","file":"server.js","sourcesContent":["/**\n * Pure helper functions extracted from visual-compare.ts.\n * These have no side effects beyond file I/O and can be tested directly.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, statSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport pixelmatch from \"pixelmatch\";\nimport { PNG } from \"pngjs\";\n\n/** Directory used for caching Figma screenshots. */\nexport const FIGMA_CACHE_DIR = \"/tmp/canicode-figma-cache\";\n\n/**\n * Known @1x screenshot widths from fixture convention.\n * Screenshots at these widths are captured at 1x scale (pixel width = logical width).\n * All other widths are assumed @2x (e.g., 2400px PNG = 1200px logical).\n */\nexport const KNOWN_1X_WIDTHS = [1920, 768];\n\n/**\n * Infer the export scale of a fixture screenshot based on its pixel width.\n * Uses KNOWN_1X_WIDTHS convention: 1920/768 = @1x, others = @2x.\n */\nexport function inferExportScale(pngWidth: number): number {\n return KNOWN_1X_WIDTHS.includes(pngWidth) ? 1 : 2;\n}\n\n/** Cache time-to-live: 1 hour. */\nexport const FIGMA_CACHE_TTL_MS = 60 * 60 * 1000;\n\n/**\n * Tolerance for detecting integer scale factors (@2x, @3x).\n * Broader tolerance because render/rounding errors accumulate at higher scales.\n */\nexport const SCALE_ROUNDING_TOLERANCE = 0.08;\n\n/**\n * Tolerance for detecting 1x (unity) scale.\n * Tighter to avoid false positives — misidentifying a scaled PNG as 1x.\n */\nexport const UNITY_SCALE_TOLERANCE = 0.02;\n\n/**\n * Get the cache path for a given fileKey + nodeId combination.\n */\nexport function getFigmaCachePath(fileKey: string, nodeId: string, scale: number): string {\n // Sanitize nodeId for use as filename (replace : with -)\n const safeNodeId = nodeId.replace(/:/g, \"-\");\n return resolve(FIGMA_CACHE_DIR, `${fileKey}_${safeNodeId}@${scale}x.png`);\n}\n\n/**\n * Check if a cached Figma screenshot exists and is still fresh (within TTL).\n */\nexport function isCacheFresh(cachePath: string): boolean {\n try {\n const stats = statSync(cachePath);\n return Date.now() - stats.mtimeMs < FIGMA_CACHE_TTL_MS;\n } catch {\n // File doesn't exist or was removed between check and stat (TOCTOU safe)\n return false;\n }\n}\n\n/**\n * Infer device pixel ratio so the Playwright screenshot matches Figma PNG pixel dimensions.\n */\nexport function inferDeviceScaleFactor(\n pngW: number,\n pngH: number,\n logicalW: number,\n logicalH: number,\n fallback: number,\n): number {\n if (logicalW <= 0 || logicalH <= 0) return 1;\n const sx = pngW / logicalW;\n const sy = pngH / logicalH;\n const rounded = Math.round((sx + sy) / 2);\n if (rounded >= 2 && Math.abs(sx - rounded) < SCALE_ROUNDING_TOLERANCE && Math.abs(sy - rounded) < SCALE_ROUNDING_TOLERANCE) {\n return rounded;\n }\n if (Math.abs(sx - 1) < UNITY_SCALE_TOLERANCE && Math.abs(sy - 1) < UNITY_SCALE_TOLERANCE) return 1;\n return fallback >= 2 ? fallback : Math.max(1, Math.round(sx));\n}\n\n/**\n * Pad a PNG to target dimensions with a high-contrast fill color (magenta #FF00FF).\n * Unlike resize, padding preserves original pixels 1:1 and guarantees that\n * any size difference is counted as mismatched pixels by pixelmatch.\n *\n * Note: If both images contain magenta in the padded area, those pixels\n * will match — extremely rare in real designs but theoretically possible.\n */\nexport function padPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const padded = new PNG({ width: targetWidth, height: targetHeight });\n // Fill entire canvas with magenta (FF00FF) — guaranteed to differ from any real content\n for (let i = 0; i < padded.data.length; i += 4) {\n padded.data[i] = 255; // R\n padded.data[i + 1] = 0; // G\n padded.data[i + 2] = 255; // B\n padded.data[i + 3] = 255; // A\n }\n // Copy original pixels into top-left corner\n for (let y = 0; y < png.height; y++) {\n for (let x = 0; x < png.width; x++) {\n const srcIdx = (y * png.width + x) * 4;\n const dstIdx = (y * targetWidth + x) * 4;\n padded.data[dstIdx] = png.data[srcIdx]!;\n padded.data[dstIdx + 1] = png.data[srcIdx + 1]!;\n padded.data[dstIdx + 2] = png.data[srcIdx + 2]!;\n padded.data[dstIdx + 3] = png.data[srcIdx + 3]!;\n }\n }\n return padded;\n}\n\n/** Options for screenshot comparison. */\nexport interface CompareOptions {\n /** How to handle size mismatches: \"pad\" (magenta fill) or \"crop\" (min dimensions). Default: \"pad\". */\n sizeMismatch?: \"pad\" | \"crop\";\n /** pixelmatch threshold (0-1). Default: 0.1. */\n threshold?: number;\n}\n\n/**\n * Crop a PNG to target dimensions (top-left corner preserved).\n */\nexport function cropPng(png: PNG, targetWidth: number, targetHeight: number): PNG {\n const cropped = new PNG({ width: targetWidth, height: targetHeight });\n for (let y = 0; y < targetHeight; y++) {\n png.data.copy(cropped.data, y * targetWidth * 4, y * png.width * 4, y * png.width * 4 + targetWidth * 4);\n }\n return cropped;\n}\n\n/**\n * Compare two PNG files using pixelmatch.\n */\nexport function compareScreenshots(\n path1: string,\n path2: string,\n diffOutputPath: string,\n options?: CompareOptions,\n): { similarity: number; diffPixels: number; totalPixels: number; width: number; height: number } {\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold ?? 0.1;\n const raw1 = PNG.sync.read(readFileSync(path1));\n const raw2 = PNG.sync.read(readFileSync(path2));\n\n let img1: PNG = raw1;\n let img2: PNG = raw2;\n\n // Size mismatch — normalize to same dimensions\n if (raw1.width !== raw2.width || raw1.height !== raw2.height) {\n if (sizeMismatch === \"crop\") {\n const width = Math.min(raw1.width, raw2.width);\n const height = Math.min(raw1.height, raw2.height);\n img1 = cropPng(raw1, width, height);\n img2 = cropPng(raw2, width, height);\n } else {\n const width = Math.max(raw1.width, raw2.width);\n const height = Math.max(raw1.height, raw2.height);\n img1 = padPng(raw1, width, height);\n img2 = padPng(raw2, width, height);\n }\n }\n\n const { width, height } = img1;\n const diff = new PNG({ width, height });\n const diffPixels = pixelmatch(img1.data, img2.data, diff.data, width, height, { threshold });\n\n mkdirSync(dirname(diffOutputPath), { recursive: true });\n writeFileSync(diffOutputPath, PNG.sync.write(diff));\n\n const totalPixels = width * height;\n const similarity = diffPixels === 0 ? 100 : Math.floor((1 - diffPixels / totalPixels) * 100);\n\n return { similarity, diffPixels, totalPixels, width, height };\n}\n\n// ── Root width expansion (for responsive comparison) ─────────────────────\n\n/**\n * Replace fixed root-element widths in HTML with fluid values so the layout\n * can expand to fill a wider viewport.\n *\n * Targets the first CSS rule that sets a pixel `width` on the root container\n * (commonly `.root`, `body > div`, etc.) and replaces it with `width: 100%`.\n * Also removes `min-width` pixel constraints.\n *\n * Originally from `src/experiments/ablation/run-condition.ts`.\n */\nexport function expandRootWidth(html: string): string {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return html;\n\n const style = styleMatch[0];\n // Find the first CSS rule block (the root element's rule)\n const firstRuleMatch = style.match(/([^{}]*\\{)([^}]*)\\}/);\n if (!firstRuleMatch) return html;\n\n const rulePrefix = firstRuleMatch[1]!; // e.g. \".root {\"\n const ruleBody = firstRuleMatch[2]!; // e.g. \" width: 375px; min-width: 375px; \"\n\n // Replace width and min-width only inside the first rule\n const newBody = ruleBody\n .replace(/(?<![-\\w])width:\\s*\\d+px/, \"width: 100%\")\n .replace(/min-width:\\s*\\d+px/g, \"min-width: 0\");\n\n const newRule = `${rulePrefix}${newBody}}`;\n const newStyle = style.replace(firstRuleMatch[0], newRule);\n return html.replace(style, newStyle);\n}\n\n// ── Code metrics (shared with ablation helpers) ─────────────────────────\n\n/** Count unique CSS class selectors in an HTML string's <style> block. */\nexport function countCssClasses(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const classes = styleMatch[0].match(/\\.[a-zA-Z][\\w-]*\\s*[{,:]/g);\n return new Set(classes?.map((c) => c.replace(/\\s*[{,:]$/, \"\"))).size;\n}\n\n/** Count unique CSS custom property definitions in an HTML string's <style> block. */\nexport function countCssVariables(html: string): number {\n const styleMatch = html.match(/<style[\\s\\S]*?<\\/style>/i);\n if (!styleMatch) return 0;\n const vars = styleMatch[0].match(/--[\\w-]+\\s*:/g);\n return new Set(vars?.map((v) => v.replace(/\\s*:$/, \"\"))).size;\n}\n\n/** Compute code metrics from an HTML string. */\nexport function computeCodeMetrics(html: string): {\n htmlBytes: number;\n htmlLines: number;\n cssClassCount: number;\n cssVariableCount: number;\n} {\n return {\n htmlBytes: Buffer.byteLength(html, \"utf-8\"),\n htmlLines: html.split(\"\\n\").length,\n cssClassCount: countCssClasses(html),\n cssVariableCount: countCssVariables(html),\n };\n}\n","/**\n * Visual comparison: renders HTML code with Playwright, fetches Figma screenshot,\n * and computes pixel-level similarity using pixelmatch.\n */\n\nimport { writeFileSync, readFileSync, mkdirSync, existsSync, copyFileSync } from \"node:fs\";\nimport { resolve, dirname } from \"node:path\";\nimport { PNG } from \"pngjs\";\nimport {\n FIGMA_CACHE_DIR,\n getFigmaCachePath,\n isCacheFresh,\n inferDeviceScaleFactor,\n inferExportScale,\n compareScreenshots,\n expandRootWidth,\n type CompareOptions,\n} from \"./visual-compare-helpers.js\";\n\n/** Result of a visual comparison between Figma design and rendered code. */\nexport interface VisualCompareResult {\n similarity: number;\n diffPixels: number;\n totalPixels: number;\n width: number;\n height: number;\n figmaScreenshotPath: string;\n codeScreenshotPath: string;\n diffPath: string;\n}\n\n/** Options for the visual comparison pipeline. */\nexport interface VisualCompareOptions {\n figmaUrl: string;\n figmaToken: string;\n codePath: string;\n outputDir?: string | undefined;\n /**\n * Logical CSS viewport (CSS pixels). Omit a dimension to infer from the Figma PNG\n * using `figmaExportScale`. When the whole object is omitted, both dimensions are inferred.\n */\n viewport?: { width?: number; height?: number } | undefined;\n /**\n * Figma Images API `scale` and assumed scale for fixture `figma.png` (e.g. from `calibrate-save-fixture`).\n * Default 2 matches REST exports and avoids comparing a @2x PNG against a 1× Playwright capture.\n */\n figmaExportScale?: number | undefined;\n /**\n * Path to a local Figma screenshot file. When provided, skips URL-based fetch\n * and uses this file directly as the ground truth. Useful for responsive comparison\n * where multiple fixture screenshots exist at different viewports.\n */\n figmaScreenshotPath?: string | undefined;\n /**\n * When true, replace the root element's fixed pixel width with `width: 100%`\n * before rendering. This allows the layout to expand to fill the viewport,\n * which is needed for responsive comparison (e.g., 375px design rendered at 768px).\n */\n expandRoot?: boolean | undefined;\n}\n\n/**\n * Fetch Figma node screenshot via REST API, with file-based caching.\n * Cache key: fileKey + nodeId. Cache location: /tmp/canicode-figma-cache/. TTL: 1 hour.\n */\nasync function fetchFigmaScreenshot(\n fileKey: string,\n nodeId: string,\n token: string,\n outputPath: string,\n scale: number,\n): Promise<void> {\n const cachePath = getFigmaCachePath(fileKey, nodeId, scale);\n\n // Return cached version if fresh\n if (isCacheFresh(cachePath)) {\n mkdirSync(dirname(outputPath), { recursive: true });\n copyFileSync(cachePath, outputPath);\n return;\n }\n\n const res = await fetch(\n `https://api.figma.com/v1/images/${fileKey}?ids=${nodeId}&format=png&scale=${scale}`,\n { headers: { \"X-Figma-Token\": token } },\n );\n if (!res.ok) throw new Error(`Figma Images API: ${res.status} ${res.statusText}`);\n\n const data = (await res.json()) as { images: Record<string, string | null> };\n const imgUrl = data.images[nodeId];\n if (!imgUrl) throw new Error(`No image returned for node ${nodeId}`);\n\n const imgRes = await fetch(imgUrl);\n if (!imgRes.ok) throw new Error(`Failed to download Figma screenshot: ${imgRes.status}`);\n\n const buffer = Buffer.from(await imgRes.arrayBuffer());\n\n // Write to output path\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, buffer);\n\n // Save to cache\n mkdirSync(FIGMA_CACHE_DIR, { recursive: true });\n writeFileSync(cachePath, buffer);\n}\n\n/**\n * Render HTML file with Playwright and take a screenshot.\n * @param deviceScaleFactor - Pass 2 when the Figma reference is @2x and `viewport` is logical CSS size.\n */\nexport async function renderCodeScreenshot(\n codePath: string,\n outputPath: string,\n logicalViewport: { width: number; height: number },\n deviceScaleFactor: number = 1,\n): Promise<void> {\n // Dynamic import — playwright is an optional dependency\n const { chromium } = await import(\"playwright\");\n const browser = await chromium.launch();\n try {\n const context = await browser.newContext({\n viewport: logicalViewport,\n deviceScaleFactor,\n });\n const page = await context.newPage();\n\n await page.goto(`file://${resolve(codePath)}`, {\n waitUntil: \"networkidle\",\n timeout: 30_000,\n });\n await page.waitForTimeout(1000);\n\n // Capture only the first child element (the design root), not the full body/viewport\n const root = page.locator(\"body > *:first-child\");\n if (await root.count() > 0) {\n await root.screenshot({ path: outputPath });\n } else {\n await page.screenshot({ path: outputPath });\n }\n } finally {\n await browser.close();\n }\n}\n\n/**\n * Run full visual comparison pipeline.\n */\nexport async function visualCompare(options: VisualCompareOptions): Promise<VisualCompareResult> {\n const outputDir = options.outputDir ?? \"/tmp/canicode-visual-compare\";\n const figmaScreenshotPath = resolve(outputDir, \"figma.png\");\n const codeScreenshotPath = resolve(outputDir, \"code.png\");\n const diffPath = resolve(outputDir, \"diff.png\");\n\n // Parse Figma URL\n const urlMatch = options.figmaUrl.match(/\\/design\\/([^/]+)\\//);\n const fileKey = urlMatch?.[1];\n if (!fileKey) throw new Error(\"Invalid Figma URL — could not extract file key\");\n\n const nodeIdMatch = options.figmaUrl.match(/node-id=([^&\\s]+)/);\n const nodeId = nodeIdMatch?.[1]?.replace(/-/g, \":\");\n if (!nodeId) throw new Error(\"Invalid Figma URL — missing node-id\");\n\n // Step 1: Figma screenshot — use local file if provided, otherwise fetch via API\n if (options.figmaScreenshotPath) {\n if (!existsSync(options.figmaScreenshotPath)) {\n throw new Error(`Figma screenshot not found: ${options.figmaScreenshotPath}`);\n }\n mkdirSync(dirname(figmaScreenshotPath), { recursive: true });\n copyFileSync(options.figmaScreenshotPath, figmaScreenshotPath);\n } else if (!existsSync(figmaScreenshotPath)) {\n const fetchScale = options.figmaExportScale ?? 2;\n await fetchFigmaScreenshot(fileKey, nodeId, options.figmaToken, figmaScreenshotPath, fetchScale);\n if (!existsSync(figmaScreenshotPath)) {\n throw new Error(`Figma screenshot was not created at expected path: ${figmaScreenshotPath}`);\n }\n }\n\n // Step 2: Logical viewport + deviceScaleFactor so code.png matches figma.png pixels (@2x, etc.)\n const figmaPng = PNG.sync.read(readFileSync(figmaScreenshotPath));\n // Auto-detect export scale from PNG width when using local screenshot (KNOWN_1X_WIDTHS convention)\n const exportScale = options.figmaExportScale ?? inferExportScale(figmaPng.width);\n const hasViewportOverride = options.viewport !== undefined;\n let logicalW: number;\n let logicalH: number;\n let deviceScaleFactor: number;\n\n if (!hasViewportOverride) {\n logicalW = Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH = Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = exportScale;\n } else {\n logicalW =\n options.viewport!.width ?? Math.max(1, Math.round(figmaPng.width / exportScale));\n logicalH =\n options.viewport!.height ?? Math.max(1, Math.round(figmaPng.height / exportScale));\n deviceScaleFactor = inferDeviceScaleFactor(\n figmaPng.width,\n figmaPng.height,\n logicalW,\n logicalH,\n exportScale,\n );\n }\n\n // Step 3: Render code screenshot at matching physical resolution\n let renderPath = options.codePath;\n if (options.expandRoot) {\n const originalHtml = readFileSync(resolve(options.codePath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderPath = resolve(outputDir, \"code-expanded.html\");\n writeFileSync(renderPath, expandedHtml);\n }\n await renderCodeScreenshot(\n renderPath,\n codeScreenshotPath,\n { width: logicalW, height: logicalH },\n deviceScaleFactor,\n );\n\n // Validate both screenshots exist before comparing\n if (!existsSync(codeScreenshotPath)) {\n throw new Error(`Code screenshot was not created at expected path: ${codeScreenshotPath}`);\n }\n\n // Compare\n const result = compareScreenshots(figmaScreenshotPath, codeScreenshotPath, diffPath);\n\n return {\n ...result,\n figmaScreenshotPath,\n codeScreenshotPath,\n diffPath,\n };\n}\n\n/** Options for renderAndCompare. */\nexport interface RenderAndCompareOptions {\n /** How to handle size mismatches. Default: \"pad\". */\n sizeMismatch?: CompareOptions[\"sizeMismatch\"];\n /** Output file suffix (e.g. \"baseline\", \"stripped-layout\"). */\n suffix?: string;\n /** pixelmatch threshold. Default: 0.1. */\n threshold?: number;\n /** Replace root element's fixed width with 100% before rendering. */\n expandRoot?: boolean;\n}\n\n/**\n * Render HTML → screenshot, then compare against a Figma screenshot.\n * Handles export scale inference and size normalization.\n *\n * Extracted from ablation helpers to be shared by calibration + experiments.\n */\nexport async function renderAndCompare(\n htmlPath: string,\n figmaScreenshotPath: string,\n outputDir: string,\n options?: RenderAndCompareOptions,\n): Promise<{ similarity: number }> {\n const suffix = options?.suffix ?? \"output\";\n const sizeMismatch = options?.sizeMismatch ?? \"pad\";\n const threshold = options?.threshold;\n\n const figmaImage = PNG.sync.read(readFileSync(figmaScreenshotPath));\n const figmaWidth = figmaImage.width;\n const exportScale = inferExportScale(figmaWidth);\n const logicalW = Math.max(1, Math.round(figmaWidth / exportScale));\n const logicalH = Math.max(1, Math.round(figmaImage.height / exportScale));\n\n let renderHtmlPath = htmlPath;\n if (options?.expandRoot) {\n const originalHtml = readFileSync(resolve(htmlPath), \"utf-8\");\n const expandedHtml = expandRootWidth(originalHtml);\n renderHtmlPath = resolve(outputDir, `code-expanded-${suffix}.html`);\n writeFileSync(renderHtmlPath, expandedHtml);\n }\n const codePngPath = resolve(outputDir, `code-${suffix}.png`);\n await renderCodeScreenshot(renderHtmlPath, codePngPath, { width: logicalW, height: logicalH }, exportScale);\n\n const figmaCopyPath = resolve(outputDir, `figma-${suffix}.png`);\n copyFileSync(figmaScreenshotPath, figmaCopyPath);\n\n const diffPath = resolve(outputDir, `diff-${suffix}.png`);\n const compareOpts: CompareOptions = { sizeMismatch };\n if (threshold !== undefined) compareOpts.threshold = threshold;\n return compareScreenshots(figmaCopyPath, codePngPath, diffPath, compareOpts);\n}\n","import { z } from \"zod\";\n\nexport const CategorySchema = z.enum([\n \"pixel-critical\",\n \"responsive-critical\",\n \"code-quality\",\n \"token-management\",\n \"semantic\",\n \"interaction\",\n]);\n\nexport type Category = z.infer<typeof CategorySchema>;\n\nexport const CATEGORIES = CategorySchema.options;\n\nexport const CATEGORY_LABELS: Record<Category, string> = {\n \"pixel-critical\": \"Pixel Critical\",\n \"responsive-critical\": \"Responsive Critical\",\n \"code-quality\": \"Code Quality\",\n \"token-management\": \"Token Management\",\n \"semantic\": \"Semantic\",\n \"interaction\": \"Interaction\",\n};\n","import { z } from \"zod\";\n\nexport const SeveritySchema = z.enum([\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n]);\n\nexport type Severity = z.infer<typeof SeveritySchema>;\n\nexport const SEVERITY_WEIGHT: Record<Severity, number> = {\n blocking: 10,\n risk: 5,\n \"missing-info\": 2,\n suggestion: 1,\n};\n\nexport const SEVERITY_LABELS: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n};\n","import { z } from \"zod\";\nimport type { AnalysisScope } from \"./analysis-scope.js\";\nimport { CategorySchema, type Category } from \"./category.js\";\nimport { SeveritySchema } from \"./severity.js\";\nimport type { AnalysisFile, AnalysisNode } from \"./figma-node.js\";\n\n/**\n * Rule definition - static metadata (does not change)\n */\nexport const RuleDefinitionSchema = z.object({\n id: z.string(),\n name: z.string(),\n category: CategorySchema,\n why: z.string(),\n impact: z.string(),\n fix: z.string(),\n});\n\nexport type RuleDefinition = z.infer<typeof RuleDefinitionSchema>;\n\n/**\n * Rule config - adjustable settings (can be modified via presets)\n */\nexport const RuleConfigSchema = z.object({\n severity: SeveritySchema,\n score: z.number().int().max(0),\n depthWeight: z.number().min(1).max(2).optional(),\n enabled: z.boolean().default(true),\n options: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type RuleConfig = z.infer<typeof RuleConfigSchema>;\n\n/**\n * Context passed to rule check functions\n */\nexport interface RuleContext {\n file: AnalysisFile;\n parent?: AnalysisNode | undefined;\n depth: number;\n /** Depth relative to the nearest COMPONENT/INSTANCE ancestor. Resets at component boundaries. */\n componentDepth: number;\n maxDepth: number;\n path: string[];\n /** Ancestor node types from root to parent (excludes current node). */\n ancestorTypes: string[];\n siblings?: AnalysisNode[] | undefined;\n /** Per-analysis shared state. Created fresh for each analysis run, eliminating module-level mutable state. */\n analysisState: Map<string, unknown>;\n /**\n * #404: Scope of the analysis root (`page` vs `component`). Rules use\n * this to decide whether expectations like \"container must define\n * bounds\" or \"repetition should become a component\" apply. Constant for\n * all nodes in a single analysis — whether the CURRENT node happens to\n * be a `COMPONENT` descendant of a page root is already signalled by\n * `componentDepth`, not by re-deriving scope per node.\n */\n scope: AnalysisScope;\n /**\n * #403: Figma node type of the analysis root, captured once in\n * `RuleEngine.analyze`. This is an *axis orthogonal to* `scope`:\n * `scope === \"component\"` does not tell a rule whether the root is a\n * `COMPONENT`/`COMPONENT_SET` (component being audited) or an\n * `INSTANCE` (component being used, possibly with overrides). The\n * `missing-size-constraint` redesign needs that distinction so the\n * gotcha question can ask the right thing — \"intentionally\n * non-responsive?\" vs \"override intended? original may be FILL\". The\n * value is the raw Figma node type string (no new enum) so it stays in\n * sync with `AnalysisNode.type` without a translation layer.\n */\n rootNodeType: string;\n}\n\n/**\n * Get or initialize per-analysis state for a rule.\n * Each key gets its own lazily-initialized state that persists for the duration of one analysis run.\n */\nexport function getAnalysisState<T>(context: RuleContext, key: string, init: () => T): T {\n if (context.analysisState.has(key)) {\n return context.analysisState.get(key) as T;\n }\n const value = init();\n context.analysisState.set(key, value);\n return value;\n}\n\n/**\n * Rule violation result from check function\n */\nexport interface RuleViolation {\n ruleId: string;\n subType?: string;\n nodeId: string;\n nodePath: string;\n message: string;\n suggestion: string;\n guide?: string;\n /**\n * Pre-computed name to write to `node.name` in Figma — populated by naming\n * rules whose suggestion is a deterministic function of the node's existing\n * state (`non-standard-naming`, `inconsistent-naming-convention`).\n * Capitalized for direct Plugin-API use; the human-readable `suggestion`\n * string keeps lowercase prose.\n */\n suggestedName?: string;\n}\n\n/**\n * Rule check function signature\n */\nexport type RuleCheckFn = (\n node: AnalysisNode,\n context: RuleContext,\n options?: Record<string, unknown>\n) => RuleViolation | null;\n\n/**\n * Complete rule with definition, config, and check function\n */\nexport interface Rule {\n definition: RuleDefinition;\n check: RuleCheckFn;\n}\n\n/**\n * Rule ID type for type safety\n */\nexport type RuleId =\n // Pixel Critical — layout issues that directly affect pixel accuracy (ΔV ≥ 5%)\n | \"no-auto-layout\"\n | \"absolute-position-in-auto-layout\"\n | \"non-layout-container\"\n // Responsive Critical — size issues that break at different viewports (ΔV ≥ 15%)\n | \"fixed-size-in-auto-layout\"\n | \"missing-size-constraint\"\n // Code Quality — structural issues affecting code reuse (ΔV ≈ 0%, CSS classes -8~15)\n | \"missing-component\"\n | \"detached-instance\"\n | \"variant-structure-mismatch\"\n | \"deep-nesting\"\n // Token Management — raw values without design tokens\n | \"raw-value\"\n | \"irregular-spacing\"\n // Interaction — missing state variants and prototype links for interactive components\n | \"missing-interaction-state\"\n | \"missing-prototype\"\n // Semantic — naming issues with negligible pixel impact (ΔV < 2%)\n | \"non-standard-naming\"\n | \"non-semantic-name\"\n | \"inconsistent-naming-convention\";\n\n/**\n * Categories that support depthWeight\n */\nexport const DEPTH_WEIGHT_CATEGORIES: Category[] = [\"pixel-critical\", \"responsive-critical\"];\n\n/**\n * Check if a category supports depth weighting\n */\nexport function supportsDepthWeight(category: Category): boolean {\n return DEPTH_WEIGHT_CATEGORIES.includes(category);\n}\n","import type { Category } from \"../contracts/category.js\";\nimport type { RulePurpose } from \"../contracts/channels.js\";\nimport type { RuleConfig, RuleId } from \"../contracts/rule.js\";\nimport type { AnnotationProperty } from \"../roundtrip/types.js\";\n\n/**\n * Maps each rule ID to its category.\n * Categories are based on ablation experiment data (PR #149, #150):\n * - pixel-critical: ΔV ≥ 5% — layout info removal directly degrades pixel accuracy\n * - responsive-critical: ΔV ≥ 15% at expanded viewport — size info critical for responsive\n * - code-quality: ΔV ≈ 0% but CSS classes -8~15 — affects code structure, not pixels\n * - token-management: raw values without design tokens — wrong input = wrong output\n * - semantic: ΔV < 2%, negligible code difference — naming and semantic issues\n */\nexport const RULE_ID_CATEGORY: Record<RuleId, Category> = {\n // Pixel Critical\n \"no-auto-layout\": \"pixel-critical\",\n \"absolute-position-in-auto-layout\": \"pixel-critical\",\n \"non-layout-container\": \"pixel-critical\",\n // Responsive Critical\n \"fixed-size-in-auto-layout\": \"responsive-critical\",\n \"missing-size-constraint\": \"responsive-critical\",\n // Code Quality\n \"missing-component\": \"code-quality\",\n \"detached-instance\": \"code-quality\",\n \"variant-structure-mismatch\": \"code-quality\",\n \"deep-nesting\": \"code-quality\",\n // Token Management\n \"raw-value\": \"token-management\",\n \"irregular-spacing\": \"token-management\",\n // Interaction\n \"missing-interaction-state\": \"interaction\",\n \"missing-prototype\": \"interaction\",\n // Semantic\n \"non-standard-naming\": \"semantic\",\n \"non-semantic-name\": \"semantic\",\n \"inconsistent-naming-convention\": \"semantic\",\n};\n\n/**\n * #406: Classifies each rule by primary output channel.\n *\n * - `violation` (default): score-primary. Rule fires when a best-practice\n * expectation is broken; the score penalty is the main signal, gotcha\n * questions are secondary context on how to resolve the violation.\n * - `info-collection`: annotation-primary. Rule fires on nodes that need\n * implementation context Figma cannot encode natively (click target,\n * state variants). The gotcha annotation IS the output; score impact is\n * kept minimal (-1 range) so presence/absence of the annotation — not\n * the penalty — differentiates designs.\n *\n * Sibling map (mirrors `RULE_ID_CATEGORY`) so existing `RuleDefinition`\n * call sites don't need to be touched. Look up via `getRulePurpose`.\n */\nexport const RULE_PURPOSE: Record<RuleId, RulePurpose> = {\n // Pixel Critical\n \"no-auto-layout\": \"violation\",\n \"absolute-position-in-auto-layout\": \"violation\",\n \"non-layout-container\": \"violation\",\n // Responsive Critical\n \"fixed-size-in-auto-layout\": \"violation\",\n // #403: missing-size-constraint reframed as info-collection. The rule\n // fires on width chains whose intent is structurally undecidable\n // (FILL container with no chain-bound ancestor; FIXED component or\n // instance root). The gotcha question is the primary signal; the\n // -1 score is just enough to keep the rule visible in\n // diversity scoring without driving grade swings on its own.\n \"missing-size-constraint\": \"info-collection\",\n // Code Quality\n \"missing-component\": \"violation\",\n \"detached-instance\": \"violation\",\n \"variant-structure-mismatch\": \"violation\",\n \"deep-nesting\": \"violation\",\n // Token Management\n \"raw-value\": \"violation\",\n \"irregular-spacing\": \"violation\",\n // Interaction — gotcha-primary: Figma cannot encode \"what happens on\n // click\" or \"which states exist\" in a way downstream code generation can\n // consume. Rules fire to trigger the annotation, not to flag a violation.\n \"missing-interaction-state\": \"info-collection\",\n \"missing-prototype\": \"info-collection\",\n // Semantic\n \"non-standard-naming\": \"violation\",\n \"non-semantic-name\": \"violation\",\n \"inconsistent-naming-convention\": \"violation\",\n};\n\n/**\n * Resolve a rule's purpose. Accepts `string` (not `RuleId`) because the\n * purpose concept must work for out-of-tree custom rules added via the\n * config loader — callers pass `issue.violation.ruleId` which is a plain\n * string. Defaults to `\"violation\"` for unknown ids. Keeping the cast\n * inside this helper (rather than forcing every caller to do `as RuleId`)\n * makes the fallback semantically honest.\n */\nexport function getRulePurpose(ruleId: string): RulePurpose {\n return RULE_PURPOSE[ruleId as RuleId] ?? \"violation\";\n}\n\n/**\n * Central configuration for all rules.\n * Scores based on ablation experiment + AI implementation interview (#200):\n * - pixel-critical: -10 ~ -7 (layout strip caused ΔV +5.4%)\n * - responsive-critical: -8 ~ -6 (size-constraints ΔV +15.9% at responsive viewports)\n * - code-quality: -7 ~ -3 (CSS classes -8~15, no pixel impact)\n * - token-management: -5 ~ -4 (wrong input = wrong output, irregular spacing actively causes errors)\n * - interaction: -1 (uncalibrated — no metric to validate, kept minimal #210)\n * - semantic: -4 ~ -1 (non-semantic-name upgraded per interview — causes actual implementation errors)\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n */\nexport const RULE_CONFIGS: Record<RuleId, RuleConfig> = {\n // ── Pixel Critical ──\n \"no-auto-layout\": {\n severity: \"blocking\",\n score: -10,\n depthWeight: 1.5,\n enabled: true,\n },\n \"absolute-position-in-auto-layout\": {\n severity: \"blocking\",\n score: -7,\n depthWeight: 1.3,\n enabled: true,\n },\n \"non-layout-container\": {\n severity: \"blocking\",\n score: -8,\n depthWeight: 1.2,\n enabled: true,\n },\n\n // ── Responsive Critical ──\n \"fixed-size-in-auto-layout\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"missing-size-constraint\": {\n // #403: severity downgraded `risk → missing-info` and score from\n // -8 → -1 to match the new info-collection purpose. Keeping the\n // rule enabled (not disabled) so its gotchas still surface in the\n // survey — see RULE_PURPOSE entry above for the full rationale.\n severity: \"missing-info\",\n score: -1,\n enabled: true,\n },\n\n // ── Code Quality ──\n \"missing-component\": {\n severity: \"risk\",\n score: -7,\n enabled: true,\n options: {\n minRepetitions: 2,\n structureMinRepetitions: 2,\n maxFingerprintDepth: 3,\n },\n },\n \"detached-instance\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"variant-structure-mismatch\": {\n severity: \"risk\",\n score: -6,\n enabled: true,\n },\n \"deep-nesting\": {\n severity: \"risk\",\n score: -3,\n enabled: true,\n options: {\n maxDepth: 5,\n },\n },\n\n // ── Token Management ──\n \"raw-value\": {\n severity: \"missing-info\",\n score: -4,\n enabled: true,\n },\n \"irregular-spacing\": {\n severity: \"risk\",\n score: -5,\n enabled: true,\n options: {\n gridBase: 2,\n },\n },\n\n // ── Interaction ──\n // #406: both rules are `info-collection` — primary output is the gotcha\n // annotation, not the score. Severity is `missing-info` so they surface in\n // the gotcha survey (see `generateGotchaSurvey`) even though the penalty\n // is minimal. Score stays at -1 so re-enabling `missing-prototype` on\n // fixtures that lack `interactionDestinations` (#139) cannot swing grades.\n \"missing-interaction-state\": {\n severity: \"missing-info\",\n score: -1, // uncalibrated: no metric to validate score (#210), kept at -1 to preserve category visibility\n enabled: true,\n },\n \"missing-prototype\": {\n severity: \"missing-info\",\n score: -1, // #406: info-collection — annotation is primary output; score kept minimal so #139 fixtures don't skew calibration\n enabled: true,\n },\n\n // ── Semantic ──\n \"non-standard-naming\": {\n severity: \"suggestion\",\n score: -3, // higher than other naming rules: non-standard state names break interaction detection pipeline\n enabled: true,\n },\n \"non-semantic-name\": {\n severity: \"risk\",\n score: -4,\n enabled: true,\n },\n \"inconsistent-naming-convention\": {\n severity: \"suggestion\",\n score: -1,\n enabled: true,\n },\n};\n\n/**\n * Preset types for different analysis modes\n */\nexport type Preset = \"relaxed\" | \"dev-friendly\" | \"ai-ready\" | \"strict\";\n\n/**\n * Get rule configs with preset applied\n */\nexport function getConfigsWithPreset(\n preset: Preset\n): Record<RuleId, RuleConfig> {\n const configs = { ...RULE_CONFIGS };\n\n switch (preset) {\n case \"relaxed\":\n // Disable blocking rules, reduce scores\n for (const [id, config] of Object.entries(configs)) {\n if (config.severity === \"blocking\") {\n configs[id as RuleId] = {\n ...config,\n severity: \"risk\",\n score: Math.round(config.score * 0.5),\n };\n }\n }\n break;\n\n case \"dev-friendly\":\n // Focus on pixel-critical and responsive-critical issues\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category !== \"pixel-critical\" && category !== \"responsive-critical\") {\n configs[ruleId] = { ...config, enabled: false };\n }\n }\n break;\n\n case \"ai-ready\":\n // Boost pixel-critical and token-management rules\n for (const [id, config] of Object.entries(configs)) {\n const ruleId = id as RuleId;\n const category = RULE_ID_CATEGORY[ruleId];\n if (category === \"pixel-critical\" || category === \"token-management\") {\n configs[ruleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n }\n break;\n\n case \"strict\":\n // Increase scores but respect disabled rules\n for (const [id, config] of Object.entries(configs)) {\n configs[id as RuleId] = {\n ...config,\n score: Math.round(config.score * 1.5),\n };\n }\n break;\n }\n\n return configs;\n}\n\n/**\n * Per-rule annotation `properties` hints surfaced in Dev Mode. Kept as a\n * sibling map rather than a field on `RuleConfig` so the existing\n * `RuleConfigSchema` Zod contract and preset helpers stay untouched.\n *\n * `bySubType` takes precedence over `default` — mirrors the ruleId+subType\n * resolution pattern already used for `targetProperty` in apply-context.ts.\n * The Experiment 09 node-type matrix is enforced at write time by\n * `upsertCanicodeAnnotation`'s retry path, so hints can be passed\n * speculatively without server-side filtering.\n */\nexport const RULE_ANNOTATION_PROPERTIES: Partial<\n Record<\n RuleId,\n {\n default?: AnnotationProperty[];\n bySubType?: Record<string, AnnotationProperty[]>;\n }\n >\n> = {\n \"missing-size-constraint\": {\n // #403: width-only — the redesigned rule does not evaluate the\n // height axis (deferred follow-up). Emitting a `height` annotation\n // here would mark properties the rule never inspected and confuse\n // downstream Dev Mode hints.\n default: [{ type: \"width\" }],\n },\n \"irregular-spacing\": {\n bySubType: {\n gap: [{ type: \"itemSpacing\" }],\n padding: [{ type: \"padding\" }],\n },\n },\n \"fixed-size-in-auto-layout\": {\n default: [{ type: \"width\" }, { type: \"height\" }, { type: \"layoutMode\" }],\n },\n \"raw-value\": {\n bySubType: {\n color: [{ type: \"fills\" }],\n font: [\n { type: \"fontSize\" },\n { type: \"fontFamily\" },\n { type: \"fontWeight\" },\n { type: \"lineHeight\" },\n ],\n spacing: [{ type: \"itemSpacing\" }, { type: \"padding\" }],\n },\n },\n \"absolute-position-in-auto-layout\": {\n default: [{ type: \"layoutMode\" }],\n },\n};\n\n/**\n * Resolve the annotation `properties` hint for a ruleId (+ subType).\n * Returns `undefined` for rules with no entry.\n */\nexport function getAnnotationProperties(\n ruleId: RuleId,\n subType?: string\n): AnnotationProperty[] | undefined {\n const entry = RULE_ANNOTATION_PROPERTIES[ruleId];\n if (!entry) return undefined;\n if (subType !== undefined && entry.bySubType) {\n const match = entry.bySubType[subType];\n if (match) return match;\n }\n return entry.default;\n}\n\n/**\n * Get option value for a rule with type safety\n */\nexport function getRuleOption<T>(\n ruleId: RuleId,\n optionKey: string,\n defaultValue: T\n): T {\n const config = RULE_CONFIGS[ruleId];\n if (!config.options) return defaultValue;\n const value = config.options[optionKey];\n return (value as T) ?? defaultValue;\n}\n","import type { Rule, RuleConfig, RuleId } from \"../contracts/rule.js\";\nimport type { Category } from \"../contracts/category.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\n/**\n * Registry for all rules\n */\nclass RuleRegistry {\n private rules: Map<RuleId, Rule> = new Map();\n\n /**\n * Register a rule\n */\n register(rule: Rule): void {\n this.rules.set(rule.definition.id as RuleId, rule);\n }\n\n /**\n * Remove a rule by ID. Primarily used by tests that register a\n * throwaway rule and need to restore the registry afterwards. Returns\n * `true` if the rule was present.\n */\n unregister(id: RuleId): boolean {\n return this.rules.delete(id);\n }\n\n /**\n * Get a rule by ID\n */\n get(id: RuleId): Rule | undefined {\n return this.rules.get(id);\n }\n\n /**\n * Get all registered rules\n */\n getAll(): Rule[] {\n return Array.from(this.rules.values());\n }\n\n /**\n * Get rules by category\n */\n getByCategory(category: Category): Rule[] {\n return this.getAll().filter((rule) => rule.definition.category === category);\n }\n\n /**\n * Get enabled rules with their configs\n */\n getEnabled(configs: Record<RuleId, RuleConfig> = RULE_CONFIGS): Rule[] {\n return this.getAll().filter((rule) => {\n const config = configs[rule.definition.id as RuleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Get config for a rule\n */\n getConfig(\n id: RuleId,\n configs: Record<RuleId, RuleConfig> = RULE_CONFIGS\n ): RuleConfig {\n return configs[id];\n }\n\n /**\n * Check if a rule is registered\n */\n has(id: RuleId): boolean {\n return this.rules.has(id);\n }\n\n /**\n * Get count of registered rules\n */\n get size(): number {\n return this.rules.size;\n }\n}\n\n/**\n * Global rule registry instance\n */\nexport const ruleRegistry = new RuleRegistry();\n\n/**\n * Helper to create and register a rule\n */\nexport function defineRule(rule: Rule): Rule {\n ruleRegistry.register(rule);\n return rule;\n}\n","import { z } from \"zod\";\n\n/**\n * Acknowledgment marker — surfaced from a Figma Dev Mode annotation that\n * canicode itself wrote during a roundtrip. When the analysis pipeline\n * receives a list of acknowledgments, matching `(nodeId, ruleId)` issues are\n * flagged `acknowledged: true` and contribute half their normal weight to\n * the density score (#371).\n *\n * This contract is consumed by:\n * - The MCP `analyze` tool (`acknowledgments?: Acknowledgment[]` input)\n * - The CLI `analyze --acknowledgments <path>` flag\n * - `RuleEngineOptions.acknowledgments`\n *\n * It is produced by the Plugin-API helper\n * `extractAcknowledgmentsFromNode` / `readCanicodeAcknowledgments`\n * (see `src/core/roundtrip/read-acknowledgments.ts`).\n *\n * ADR-019 / #444: optional `intent`, `sceneWriteOutcome`, and `codegenDirective`\n * are read from a fenced canicode-json block when present; legacy annotations\n * omit them and remain valid for density scoring.\n */\nexport const AcknowledgmentIntentSchema = z.object({\n field: z.string(),\n value: z.unknown(),\n scope: z.enum([\"instance\", \"definition\"]),\n});\n\nexport type AcknowledgmentIntent = z.infer<typeof AcknowledgmentIntentSchema>;\n\nexport const AcknowledgmentSceneWriteOutcomeSchema = z.object({\n result: z.enum([\n \"succeeded\",\n \"silent-ignored\",\n \"api-rejected\",\n \"user-declined-propagation\",\n \"unknown\",\n ]),\n reason: z.string().optional(),\n});\n\nexport type AcknowledgmentSceneWriteOutcome = z.infer<\n typeof AcknowledgmentSceneWriteOutcomeSchema\n>;\n\nexport const AcknowledgmentSchema = z.object({\n nodeId: z.string(),\n ruleId: z.string(),\n intent: AcknowledgmentIntentSchema.optional(),\n sceneWriteOutcome: AcknowledgmentSceneWriteOutcomeSchema.optional(),\n codegenDirective: z.string().optional(),\n});\n\nexport type Acknowledgment = z.infer<typeof AcknowledgmentSchema>;\n\nexport const AcknowledgmentListSchema = z.array(AcknowledgmentSchema);\n\n/**\n * Normalize a Figma node id into `:`-separated form so callers can pass\n * either URL-style (`123-456`) or Plugin-API-style (`123:456`) ids and the\n * engine matches them consistently. Non-instance ids stay unchanged; the\n * `I…;…` instance-child format keeps its semicolon — only `-` → `:`\n * happens.\n */\nexport function normalizeNodeId(id: string): string {\n return id.replace(/-/g, \":\");\n}\n","import { z } from \"zod\";\nimport type { AnalysisNode } from \"./figma-node.js\";\n\n/**\n * #404: Analysis scope — what the user is asking canicode to reason about.\n *\n * - `page`: full screen / section / layout. Container frames are\n * responsible for bounds; repetition detection is meaningful; rules\n * that assume \"this is a self-contained screen\" apply.\n * - `component`: standalone reusable UI unit (COMPONENT / COMPONENT_SET\n * / INSTANCE analyzed in isolation). Root FILL is the design contract\n * rather than a missing bound; repetition detection is generally a\n * false signal because a component is itself the unit of reuse.\n *\n * The enum is intentionally two-valued; multi-scope analysis (analyzing\n * a page and its inner components in one run) is explicitly out of scope\n * per the issue. Each rule decides how (or whether) to switch on `scope`;\n * this PR only carries the context. Rule-level consumption lands in\n * follow-up PRs (e.g. #403 for `missing-size-constraint`).\n */\nexport const AnalysisScopeSchema = z.enum([\"page\", \"component\"]);\nexport type AnalysisScope = z.infer<typeof AnalysisScopeSchema>;\n\n/**\n * Figma node types that unambiguously indicate a component-scope analysis\n * when they appear as the analysis **root**.\n *\n * - `COMPONENT` / `COMPONENT_SET`: the design unit IS the component.\n * - `INSTANCE`: the root is a reusable unit's placement; treating it as\n * component scope keeps rules like `missing-size-constraint` from\n * demanding bounds on a node whose bounds are the container's job.\n *\n * Any other root type (`FRAME`, `SECTION`, `CANVAS`, `DOCUMENT`, `GROUP`,\n * etc.) resolves to page scope — the common case for analyzing a screen\n * or page section via `?node-id=...`.\n */\nconst COMPONENT_SCOPE_ROOT_TYPES = new Set([\"COMPONENT\", \"COMPONENT_SET\", \"INSTANCE\"]);\n\n/**\n * Deterministically detect analysis scope from the root node type. Returns\n * `\"component\"` for `COMPONENT` / `COMPONENT_SET` / `INSTANCE` roots, and\n * `\"page\"` for everything else.\n *\n * The CLI / MCP layer may override this with an explicit `scope` flag when\n * the user knows the heuristic mis-detects (e.g. analyzing a FRAME that\n * ships as a standalone design-system example rather than a screen).\n */\nexport function detectAnalysisScope(rootNode: AnalysisNode): AnalysisScope {\n return COMPONENT_SCOPE_ROOT_TYPES.has(rootNode.type) ? \"component\" : \"page\";\n}\n","import type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport type {\n Rule,\n RuleConfig,\n RuleContext,\n RuleId,\n RuleViolation,\n} from \"../contracts/rule.js\";\nimport { supportsDepthWeight } from \"../contracts/rule.js\";\nimport { ruleRegistry } from \"../rules/rule-registry.js\";\nimport { RULE_CONFIGS } from \"../rules/rule-config.js\";\nimport {\n normalizeNodeId,\n type Acknowledgment,\n} from \"../contracts/acknowledgment.js\";\nimport {\n detectAnalysisScope,\n type AnalysisScope,\n} from \"../contracts/analysis-scope.js\";\n\n/**\n * Analysis issue with calculated score and metadata.\n *\n * `acknowledged` (#371) — set when the analysis engine receives an\n * `acknowledgments` list (typically read from canicode-authored Figma\n * annotations) whose `(nodeId, ruleId)` matches this issue. Acknowledged\n * issues still surface in the result (so code-gen retains the context) but\n * contribute half their normal weight to the density score, so the grade\n * reflects \"the designer has a plan for this\" instead of treating the rule\n * as fully unaddressed.\n */\nexport interface AnalysisIssue {\n violation: RuleViolation;\n rule: Rule;\n config: RuleConfig;\n depth: number;\n maxDepth: number;\n calculatedScore: number;\n acknowledged?: boolean;\n}\n\n/**\n * Information about a rule that threw during analysis\n */\nexport interface RuleFailure {\n ruleId: string;\n nodeName: string;\n nodeId: string;\n error: string;\n}\n\n/**\n * Analysis result from the rule engine\n */\nexport interface AnalysisResult {\n file: AnalysisFile;\n issues: AnalysisIssue[];\n failedRules: RuleFailure[];\n maxDepth: number;\n nodeCount: number;\n analyzedAt: string;\n /**\n * #404: Resolved analysis scope (`page` vs `component`). Either detected\n * from the root node type or taken from the caller's explicit override.\n * Propagated to MCP / JSON output so downstream consumers (code-gen,\n * reports) can branch the same way rules do.\n */\n scope: AnalysisScope;\n}\n\n/**\n * Options for the rule engine\n */\nexport interface RuleEngineOptions {\n configs?: Record<RuleId, RuleConfig>;\n enabledRules?: RuleId[];\n disabledRules?: RuleId[];\n targetNodeId?: string;\n excludeNodeNames?: string[];\n excludeNodeTypes?: string[];\n /**\n * `(nodeId, ruleId)` pairs sourced from canicode-authored Figma annotations\n * (#371). Issues whose violation matches an entry are flagged\n * `acknowledged: true` and contribute half their normal weight to the\n * density score in `calculateScores`. nodeId may be passed in URL form\n * (`123-456`) or Plugin-API form (`123:456`) — both normalize to `:`.\n */\n acknowledgments?: Acknowledgment[];\n /**\n * #404: Explicit scope override. When omitted, the engine auto-detects\n * from the analysis root's node type via `detectAnalysisScope`. Supply\n * this when the caller knows the heuristic would mis-detect — e.g. a\n * FRAME that happens to be a design-system demo (component scope) or a\n * COMPONENT_SET being audited as part of a full page inventory (page\n * scope).\n */\n scope?: AnalysisScope;\n}\n\n/**\n * Calculate the maximum depth of a node tree\n */\nfunction calculateMaxDepth(node: AnalysisNode, currentDepth = 0): number {\n if (!node.children || node.children.length === 0) {\n return currentDepth;\n }\n\n let maxChildDepth = currentDepth;\n for (const child of node.children) {\n const childDepth = calculateMaxDepth(child, currentDepth + 1);\n if (childDepth > maxChildDepth) {\n maxChildDepth = childDepth;\n }\n }\n\n return maxChildDepth;\n}\n\n/**\n * Count total nodes in a tree\n */\nfunction countNodes(node: AnalysisNode): number {\n let count = 1;\n if (node.children) {\n for (const child of node.children) {\n count += countNodes(child);\n }\n }\n return count;\n}\n\n/**\n * Find a node by ID in the tree\n */\nfunction findNodeById(node: AnalysisNode, nodeId: string): AnalysisNode | null {\n // Figma node IDs use \":\" separator, URL uses \"-\"\n const normalizedId = nodeId.replace(/-/g, \":\");\n\n if (node.id === normalizedId) {\n return node;\n }\n\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, nodeId);\n if (found) return found;\n }\n }\n\n return null;\n}\n\n/**\n * Calculate depth weight multiplier for a rule\n * Higher values (closer to 1.5x) at root level, 1.0x at leaf level\n */\nfunction calcDepthWeight(\n depth: number,\n maxDepth: number,\n depthWeight?: number\n): number {\n if (!depthWeight || depthWeight <= 1) return 1;\n if (maxDepth === 0) return depthWeight;\n\n // Linear interpolation: depthWeight at depth 0, 1.0 at maxDepth\n const ratio = depth / maxDepth;\n return depthWeight - (depthWeight - 1) * ratio;\n}\n\n/**\n * Rule engine for analyzing Figma files\n */\nexport class RuleEngine {\n private configs: Record<RuleId, RuleConfig>;\n private enabledRuleIds: Set<RuleId> | null;\n private disabledRuleIds: Set<RuleId>;\n private targetNodeId: string | undefined;\n private excludeNamePattern: RegExp | null;\n private excludeNodeTypes: Set<string> | null;\n private acknowledgments: ReadonlySet<string>;\n private scopeOverride: AnalysisScope | undefined;\n\n constructor(options: RuleEngineOptions = {}) {\n this.configs = options.configs ?? RULE_CONFIGS;\n this.enabledRuleIds = options.enabledRules\n ? new Set(options.enabledRules)\n : null;\n this.disabledRuleIds = new Set(options.disabledRules ?? []);\n this.targetNodeId = options.targetNodeId;\n this.excludeNamePattern = options.excludeNodeNames && options.excludeNodeNames.length > 0\n ? new RegExp(`\\\\b(${options.excludeNodeNames.join(\"|\")})\\\\b`, \"i\")\n : null;\n this.excludeNodeTypes = options.excludeNodeTypes && options.excludeNodeTypes.length > 0\n ? new Set(options.excludeNodeTypes)\n : null;\n this.acknowledgments = new Set(\n (options.acknowledgments ?? []).map(\n (a) => `${normalizeNodeId(a.nodeId)}::${a.ruleId}`\n )\n );\n this.scopeOverride = options.scope;\n }\n\n /**\n * Analyze a Figma file and return issues\n */\n analyze(file: AnalysisFile): AnalysisResult {\n // Fresh per-analysis state — eliminates module-level mutable state in rules\n const analysisState = new Map<string, unknown>();\n\n // Find target node if specified\n let rootNode = file.document;\n if (this.targetNodeId) {\n const targetNode = findNodeById(file.document, this.targetNodeId);\n if (!targetNode) {\n throw new Error(`Node not found: ${this.targetNodeId}`);\n }\n rootNode = targetNode;\n }\n\n // Calculate max depth before analysis\n const maxDepth = calculateMaxDepth(rootNode);\n const nodeCount = countNodes(rootNode);\n\n // #404: resolve scope once per analysis. Caller override wins over\n // type-based detection so CLI/MCP users can correct false positives\n // (e.g. design-system demo frames classified as page scope).\n const scope: AnalysisScope =\n this.scopeOverride ?? detectAnalysisScope(rootNode);\n\n // #403: capture root node type as a separate axis from `scope`. Rules\n // that branch on whether a component-scope root is the component\n // itself vs an INSTANCE of one need this even when `scope` already\n // resolves to \"component\". Captured once here, threaded read-only\n // through every `RuleContext` in this analysis.\n const rootNodeType = rootNode.type;\n\n const issues: AnalysisIssue[] = [];\n const failedRules: RuleFailure[] = [];\n const enabledRules = this.getEnabledRules();\n\n // Traverse the tree and run rules on each node\n this.traverseAndCheck(\n rootNode,\n file,\n enabledRules,\n maxDepth,\n issues,\n failedRules,\n 0,\n [],\n [],\n 0,\n analysisState,\n scope,\n rootNodeType,\n undefined,\n undefined\n );\n\n if (this.acknowledgments.size > 0) {\n for (const issue of issues) {\n const key = `${normalizeNodeId(issue.violation.nodeId)}::${issue.violation.ruleId}`;\n if (this.acknowledgments.has(key)) {\n issue.acknowledged = true;\n }\n }\n }\n\n return {\n file,\n issues,\n failedRules,\n maxDepth,\n nodeCount,\n analyzedAt: new Date().toISOString(),\n scope,\n };\n }\n\n /**\n * Get rules that should be run based on configuration\n */\n private getEnabledRules(): Rule[] {\n return ruleRegistry.getAll().filter((rule) => {\n const ruleId = rule.definition.id as RuleId;\n\n // Check if explicitly disabled\n if (this.disabledRuleIds.has(ruleId)) return false;\n\n // Check if we have an explicit enable list\n if (this.enabledRuleIds && !this.enabledRuleIds.has(ruleId)) return false;\n\n // Check config enabled status\n const config = this.configs[ruleId];\n return config?.enabled ?? true;\n });\n }\n\n /**\n * Recursively traverse the tree and run rules\n */\n private traverseAndCheck(\n node: AnalysisNode,\n file: AnalysisFile,\n rules: Rule[],\n maxDepth: number,\n issues: AnalysisIssue[],\n failedRules: RuleFailure[],\n depth: number,\n path: string[],\n ancestorTypes: string[],\n componentDepth: number,\n analysisState: Map<string, unknown>,\n scope: AnalysisScope,\n rootNodeType: string,\n parent?: AnalysisNode,\n siblings?: AnalysisNode[]\n ): void {\n const nodePath = [...path, node.name];\n\n // Reset componentDepth at component boundaries\n const isComponentBoundary = node.type === \"COMPONENT\" || node.type === \"COMPONENT_SET\" || node.type === \"INSTANCE\";\n const currentComponentDepth = isComponentBoundary ? 0 : componentDepth;\n\n // Skip nodes matching excluded types or name patterns\n if (this.excludeNodeTypes && this.excludeNodeTypes.has(node.type)) {\n return;\n }\n if (this.excludeNamePattern && this.excludeNamePattern.test(node.name)) {\n return;\n }\n\n // Build context for this node\n const context: RuleContext = {\n file,\n parent,\n depth,\n componentDepth: currentComponentDepth,\n maxDepth,\n path: nodePath,\n ancestorTypes,\n siblings,\n analysisState,\n scope,\n rootNodeType,\n };\n\n // Run each rule on this node\n for (const rule of rules) {\n const ruleId = rule.definition.id as RuleId;\n const config = this.configs[ruleId];\n const options = config?.options;\n\n try {\n const violation = rule.check(node, context, options);\n\n if (violation) {\n // Calculate score with depth weight if applicable\n let calculatedScore = config.score;\n\n if (\n supportsDepthWeight(rule.definition.category) &&\n config.depthWeight\n ) {\n const weight = calcDepthWeight(depth, maxDepth, config.depthWeight);\n calculatedScore = Math.round(config.score * weight);\n }\n\n issues.push({\n violation,\n rule,\n config,\n depth,\n maxDepth,\n calculatedScore,\n });\n }\n } catch (error) {\n // Track failure and continue — never let one rule break the whole analysis\n failedRules.push({\n ruleId,\n nodeName: node.name,\n nodeId: node.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Recurse into children\n if (node.children && node.children.length > 0) {\n const childAncestorTypes = [...ancestorTypes, node.type];\n for (const child of node.children) {\n this.traverseAndCheck(\n child,\n file,\n rules,\n maxDepth,\n issues,\n failedRules,\n depth + 1,\n nodePath,\n childAncestorTypes,\n currentComponentDepth + 1,\n analysisState,\n scope,\n rootNodeType,\n node,\n node.children\n );\n }\n }\n }\n}\n\n/**\n * Create a rule engine with default configuration\n */\nexport function createRuleEngine(options?: RuleEngineOptions): RuleEngine {\n return new RuleEngine(options);\n}\n\n/**\n * Convenience function to analyze a file with default settings\n */\nexport function analyzeFile(\n file: AnalysisFile,\n options?: RuleEngineOptions\n): AnalysisResult {\n const engine = createRuleEngine(options);\n return engine.analyze(file);\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\n\nconst FIGMA_API_BASE = \"https://api.figma.com/v1\";\n\nexport interface GetFileNodesResponse {\n name: string;\n lastModified: string;\n version: string;\n nodes: Record<string, {\n document: Node;\n components: GetFileResponse[\"components\"];\n styles: GetFileResponse[\"styles\"];\n }>;\n}\n\nexport interface FigmaClientOptions {\n token: string;\n}\n\nexport class FigmaClient {\n private token: string;\n\n constructor(options: FigmaClientOptions) {\n this.token = options.token;\n }\n\n static fromEnv(): FigmaClient {\n const token = process.env[\"FIGMA_TOKEN\"];\n if (!token) {\n throw new FigmaClientError(\n \"FIGMA_TOKEN environment variable is not set\"\n );\n }\n return new FigmaClient({ token });\n }\n\n async getFile(fileKey: string): Promise<GetFileResponse> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch file: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileResponse>;\n }\n\n /**\n * Get rendered images for specific nodes\n * Returns a map of nodeId → image URL\n */\n async getNodeImages(\n fileKey: string,\n nodeIds: string[],\n options?: { format?: \"png\" | \"svg\" | \"jpg\"; scale?: number }\n ): Promise<Record<string, string | null>> {\n const format = options?.format ?? \"png\";\n const scale = options?.scale ?? 2;\n\n // Batch into chunks to avoid 414 URI Too Large\n const BATCH_SIZE = 50;\n const allImages: Record<string, string | null> = {};\n\n for (let i = 0; i < nodeIds.length; i += BATCH_SIZE) {\n const batch = nodeIds.slice(i, i + BATCH_SIZE);\n const ids = batch.join(\",\");\n const url = `${FIGMA_API_BASE}/images/${fileKey}?ids=${encodeURIComponent(ids)}&format=${format}&scale=${scale}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch images: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n const data = await response.json() as { images: Record<string, string | null> };\n for (const [nodeId, imageUrl] of Object.entries(data.images)) {\n allImages[nodeId] = imageUrl;\n }\n }\n\n return allImages;\n }\n\n /**\n * Get original image fill URLs by imageRef.\n * Returns a mapping of imageRef → download URL for all image fills in the file.\n */\n async getImageFills(fileKey: string): Promise<Record<string, string>> {\n const url = `${FIGMA_API_BASE}/files/${fileKey}/images`;\n const response = await fetch(url, {\n headers: { \"X-Figma-Token\": this.token },\n });\n if (!response.ok) {\n const error = await response.text().catch(() => \"\");\n throw new FigmaClientError(\n `Failed to fetch image fills: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n const data = await response.json() as { meta?: { images?: Record<string, string> } };\n return data.meta?.images ?? {};\n }\n\n /**\n * Download an image URL and return as base64\n */\n async fetchImageAsBase64(imageUrl: string): Promise<string> {\n const response = await fetch(imageUrl);\n if (!response.ok) {\n throw new FigmaClientError(\n `Failed to download image: ${response.status}`,\n response.status\n );\n }\n const buffer = await response.arrayBuffer();\n return Buffer.from(buffer).toString(\"base64\");\n }\n\n async getFileNodes(\n fileKey: string,\n nodeIds: string[]\n ): Promise<GetFileNodesResponse> {\n const ids = nodeIds.join(\",\");\n const url = `${FIGMA_API_BASE}/files/${fileKey}/nodes?ids=${encodeURIComponent(ids)}`;\n const response = await fetch(url, {\n headers: {\n \"X-Figma-Token\": this.token,\n },\n });\n\n if (!response.ok) {\n const error = await response.json().catch(() => ({}));\n throw new FigmaClientError(\n `Failed to fetch nodes: ${response.status} ${response.statusText}`,\n response.status,\n error\n );\n }\n\n return response.json() as Promise<GetFileNodesResponse>;\n }\n}\n\nexport class FigmaClientError extends Error {\n constructor(\n message: string,\n public statusCode?: number,\n public responseBody?: unknown\n ) {\n super(message);\n this.name = \"FigmaClientError\";\n }\n}\n","import type { GetFileResponse, Node } from \"@figma/rest-api-spec\";\nimport type { GetFileNodesResponse } from \"./figma-client.js\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\n\n/**\n * Transform Figma API response to analysis types\n */\nexport function transformFigmaResponse(\n fileKey: string,\n response: GetFileResponse\n): AnalysisFile {\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(response.document),\n components: transformComponents(response.components),\n styles: transformStyles(response.styles),\n };\n}\n\nfunction transformNode(node: Node): AnalysisNode {\n const base: AnalysisNode = {\n id: node.id,\n name: node.name,\n type: node.type as AnalysisNode[\"type\"],\n visible: \"visible\" in node ? (node.visible ?? true) : true,\n };\n\n // Layout properties\n if (\"layoutMode\" in node && node.layoutMode) {\n base.layoutMode = node.layoutMode as AnalysisNode[\"layoutMode\"];\n }\n if (\"layoutAlign\" in node && node.layoutAlign) {\n base.layoutAlign = node.layoutAlign as AnalysisNode[\"layoutAlign\"];\n }\n if (\"layoutPositioning\" in node && node.layoutPositioning) {\n base.layoutPositioning =\n node.layoutPositioning as AnalysisNode[\"layoutPositioning\"];\n }\n if (\"layoutSizingHorizontal\" in node && node.layoutSizingHorizontal) {\n base.layoutSizingHorizontal =\n node.layoutSizingHorizontal as AnalysisNode[\"layoutSizingHorizontal\"];\n }\n if (\"layoutSizingVertical\" in node && node.layoutSizingVertical) {\n base.layoutSizingVertical =\n node.layoutSizingVertical as AnalysisNode[\"layoutSizingVertical\"];\n }\n if (\"primaryAxisAlignItems\" in node) {\n base.primaryAxisAlignItems = node.primaryAxisAlignItems as string;\n }\n if (\"counterAxisAlignItems\" in node) {\n base.counterAxisAlignItems = node.counterAxisAlignItems as string;\n }\n if (\"itemSpacing\" in node) {\n base.itemSpacing = node.itemSpacing as number;\n }\n if (\"paddingLeft\" in node) {\n base.paddingLeft = node.paddingLeft as number;\n }\n if (\"paddingRight\" in node) {\n base.paddingRight = node.paddingRight as number;\n }\n if (\"paddingTop\" in node) {\n base.paddingTop = node.paddingTop as number;\n }\n if (\"paddingBottom\" in node) {\n base.paddingBottom = node.paddingBottom as number;\n }\n\n // Size constraints (responsive)\n if (\"minWidth\" in node && typeof node.minWidth === \"number\") {\n base.minWidth = node.minWidth;\n }\n if (\"maxWidth\" in node && typeof node.maxWidth === \"number\") {\n base.maxWidth = node.maxWidth;\n }\n if (\"minHeight\" in node && typeof node.minHeight === \"number\") {\n base.minHeight = node.minHeight;\n }\n if (\"maxHeight\" in node && typeof node.maxHeight === \"number\") {\n base.maxHeight = node.maxHeight;\n }\n if (\"layoutGrow\" in node && node.layoutGrow !== undefined) {\n base.layoutGrow = node.layoutGrow as 0 | 1;\n }\n if (\"constraints\" in node && node.constraints) {\n base.constraints = node.constraints as AnalysisNode[\"constraints\"];\n }\n\n // Wrap (flex-wrap)\n if (\"layoutWrap\" in node && node.layoutWrap) {\n base.layoutWrap = node.layoutWrap as AnalysisNode[\"layoutWrap\"];\n }\n if (\"counterAxisSpacing\" in node && typeof node.counterAxisSpacing === \"number\") {\n base.counterAxisSpacing = node.counterAxisSpacing;\n }\n if (\"counterAxisAlignContent\" in node && node.counterAxisAlignContent) {\n base.counterAxisAlignContent =\n node.counterAxisAlignContent as AnalysisNode[\"counterAxisAlignContent\"];\n }\n\n // Grid layout (container)\n if (\"gridRowCount\" in node && typeof node.gridRowCount === \"number\") {\n base.gridRowCount = node.gridRowCount;\n }\n if (\"gridColumnCount\" in node && typeof node.gridColumnCount === \"number\") {\n base.gridColumnCount = node.gridColumnCount;\n }\n if (\"gridRowGap\" in node && typeof node.gridRowGap === \"number\") {\n base.gridRowGap = node.gridRowGap;\n }\n if (\"gridColumnGap\" in node && typeof node.gridColumnGap === \"number\") {\n base.gridColumnGap = node.gridColumnGap;\n }\n if (\"gridColumnsSizing\" in node && typeof node.gridColumnsSizing === \"string\") {\n base.gridColumnsSizing = node.gridColumnsSizing;\n }\n if (\"gridRowsSizing\" in node && typeof node.gridRowsSizing === \"string\") {\n base.gridRowsSizing = node.gridRowsSizing;\n }\n\n // Grid layout (child)\n if (\"gridChildHorizontalAlign\" in node && node.gridChildHorizontalAlign) {\n base.gridChildHorizontalAlign =\n node.gridChildHorizontalAlign as AnalysisNode[\"gridChildHorizontalAlign\"];\n }\n if (\"gridChildVerticalAlign\" in node && node.gridChildVerticalAlign) {\n base.gridChildVerticalAlign =\n node.gridChildVerticalAlign as AnalysisNode[\"gridChildVerticalAlign\"];\n }\n if (\"gridRowSpan\" in node && typeof node.gridRowSpan === \"number\") {\n base.gridRowSpan = node.gridRowSpan;\n }\n if (\"gridColumnSpan\" in node && typeof node.gridColumnSpan === \"number\") {\n base.gridColumnSpan = node.gridColumnSpan;\n }\n if (\"gridRowAnchorIndex\" in node && typeof node.gridRowAnchorIndex === \"number\") {\n base.gridRowAnchorIndex = node.gridRowAnchorIndex;\n }\n if (\"gridColumnAnchorIndex\" in node && typeof node.gridColumnAnchorIndex === \"number\") {\n base.gridColumnAnchorIndex = node.gridColumnAnchorIndex;\n }\n\n // Overflow / clip\n if (\"clipsContent\" in node && typeof node.clipsContent === \"boolean\") {\n base.clipsContent = node.clipsContent;\n }\n if (\"overflowDirection\" in node && node.overflowDirection) {\n base.overflowDirection =\n node.overflowDirection as AnalysisNode[\"overflowDirection\"];\n }\n\n // Size/position\n if (\"absoluteBoundingBox\" in node && node.absoluteBoundingBox) {\n base.absoluteBoundingBox = node.absoluteBoundingBox;\n }\n\n // Component properties\n if (\"componentId\" in node) {\n base.componentId = node.componentId as string;\n }\n if (\"componentPropertyDefinitions\" in node) {\n base.componentPropertyDefinitions =\n node.componentPropertyDefinitions as Record<string, unknown>;\n }\n if (\"componentProperties\" in node) {\n base.componentProperties = node.componentProperties as Record<\n string,\n unknown\n >;\n }\n\n // Style properties\n if (\"styles\" in node) {\n base.styles = node.styles as Record<string, string>;\n }\n if (\"fills\" in node) {\n base.fills = node.fills as unknown[];\n }\n if (\"strokes\" in node) {\n base.strokes = node.strokes as unknown[];\n }\n if (\"strokeWeight\" in node && typeof node.strokeWeight === \"number\") {\n base.strokeWeight = node.strokeWeight;\n }\n if (\"individualStrokeWeights\" in node && node.individualStrokeWeights) {\n base.individualStrokeWeights = node.individualStrokeWeights as Record<string, number>;\n }\n if (\"effects\" in node) {\n base.effects = node.effects as unknown[];\n }\n if (\"cornerRadius\" in node && typeof node.cornerRadius === \"number\") {\n base.cornerRadius = node.cornerRadius;\n }\n if (\"opacity\" in node && typeof node.opacity === \"number\" && node.opacity < 1) {\n base.opacity = node.opacity;\n }\n\n // Variable bindings\n if (\"boundVariables\" in node && node.boundVariables) {\n base.boundVariables = node.boundVariables as Record<string, unknown>;\n }\n\n // Text properties\n if (\"characters\" in node) {\n base.characters = node.characters as string;\n }\n if (\"style\" in node) {\n base.style = node.style as Record<string, unknown>;\n }\n if (\"textTruncation\" in node && (node.textTruncation === \"DISABLED\" || node.textTruncation === \"ENDING\")) {\n base.textTruncation = node.textTruncation;\n }\n if (\"maxLines\" in node && typeof node.maxLines === \"number\") {\n base.maxLines = node.maxLines;\n }\n\n // Handoff status\n if (\"devStatus\" in node && node.devStatus) {\n base.devStatus = node.devStatus as AnalysisNode[\"devStatus\"];\n }\n\n // Prototype interactions\n if (\"interactions\" in node && Array.isArray(node.interactions) && node.interactions.length > 0) {\n base.interactions = node.interactions;\n }\n\n // Recursively transform children\n if (\"children\" in node && Array.isArray(node.children)) {\n base.children = node.children.map(transformNode);\n }\n\n return base;\n}\n\n/**\n * Transform Figma /v1/files/{key}/nodes response to analysis types.\n * Returns the first node's subtree as the document.\n */\nexport function transformFileNodesResponse(\n fileKey: string,\n response: GetFileNodesResponse\n): AnalysisFile {\n const entries = Object.values(response.nodes);\n const first = entries[0];\n if (!first)\n throw new Error(\n \"No nodes returned from Figma API — the node-id in the URL may be invalid or deleted. \" +\n \"Try selecting the frame in Figma and copying the link again.\"\n );\n\n return {\n fileKey,\n name: response.name,\n lastModified: response.lastModified,\n version: response.version,\n document: transformNode(first.document),\n components: transformComponents(first.components),\n styles: transformStyles(first.styles),\n };\n}\n\n/**\n * Transform component master nodes from a /v1/files/{key}/nodes response.\n * Each requested node ID is transformed into an AnalysisNode if present.\n */\nexport function transformComponentMasterNodes(\n response: GetFileNodesResponse,\n requestedIds: string[]\n): Record<string, AnalysisNode> {\n const result: Record<string, AnalysisNode> = {};\n for (const id of requestedIds) {\n const entry = response.nodes[id];\n if (entry?.document) {\n result[id] = transformNode(entry.document);\n }\n }\n return result;\n}\n\nfunction transformComponents(\n components: GetFileResponse[\"components\"]\n): AnalysisFile[\"components\"] {\n const result: AnalysisFile[\"components\"] = {};\n for (const [id, component] of Object.entries(components)) {\n result[id] = {\n key: component.key,\n name: component.name,\n description: component.description,\n };\n }\n return result;\n}\n\nfunction transformStyles(\n styles: GetFileResponse[\"styles\"]\n): AnalysisFile[\"styles\"] {\n const result: AnalysisFile[\"styles\"] = {};\n for (const [id, style] of Object.entries(styles)) {\n result[id] = {\n key: style.key,\n name: style.name,\n styleType: style.styleType,\n };\n }\n return result;\n}\n","import type { FigmaClient } from \"./figma-client.js\";\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport { transformComponentMasterNodes } from \"./figma-transformer.js\";\n\nconst BATCH_SIZE = 50;\n\n/**\n * Recursively collect all unique componentId values from INSTANCE nodes.\n */\nexport function collectComponentIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.type === \"INSTANCE\" && n.componentId) {\n ids.add(n.componentId);\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Recursively collect all unique interaction destination IDs from nodes.\n * These are the node IDs that interactions (e.g., ON_HOVER → CHANGE_TO) point to.\n */\nexport function collectInteractionDestinationIds(node: AnalysisNode): Set<string> {\n const ids = new Set<string>();\n\n function walk(n: AnalysisNode): void {\n if (n.interactions && Array.isArray(n.interactions)) {\n for (const interaction of n.interactions) {\n const i = interaction as {\n trigger?: { type?: string };\n actions?: Array<{ destinationId?: string; navigation?: string }>;\n };\n if (i.trigger?.type === \"ON_HOVER\" && i.actions) {\n for (const action of i.actions) {\n if (action.navigation === \"CHANGE_TO\" && action.destinationId) {\n ids.add(action.destinationId);\n }\n }\n }\n }\n }\n if (n.children) {\n for (const child of n.children) {\n walk(child);\n }\n }\n }\n\n walk(node);\n return ids;\n}\n\n/**\n * Resolve component master node trees via multi-pass fetching.\n *\n * Pass 1: collect component IDs from the document tree, fetch their masters.\n * Pass 2+: collect component IDs from fetched masters that were not in previous passes.\n * Repeats up to maxPasses (default 2).\n *\n * Batches API calls at BATCH_SIZE IDs per request.\n * Skips IDs that return null (e.g. external library components).\n */\nexport async function resolveComponentDefinitions(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n maxPasses = 2\n): Promise<Record<string, AnalysisNode>> {\n const allDefinitions: Record<string, AnalysisNode> = {};\n const resolvedIds = new Set<string>();\n\n // Pass 1: collect from the original document\n let pendingIds = collectComponentIds(document);\n\n for (let pass = 0; pass < maxPasses; pass++) {\n // Filter out already-resolved IDs\n const idsToFetch = [...pendingIds].filter((id) => !resolvedIds.has(id));\n if (idsToFetch.length === 0) break;\n\n // Fetch in batches\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDefinitions[id] = node;\n }\n } catch (err) {\n // Skip failed batches (e.g. external library components)\n console.debug(`[component-resolver] batch fetch failed (${batch.length} ids):`, err);\n }\n }\n\n // Mark all attempted IDs as resolved (even if they failed/returned null)\n for (const id of idsToFetch) {\n resolvedIds.add(id);\n }\n\n // Collect new IDs only from masters fetched in this pass (not all accumulated)\n pendingIds = new Set<string>();\n for (const id of idsToFetch) {\n const node = allDefinitions[id];\n if (node) {\n for (const nestedId of collectComponentIds(node)) {\n if (!resolvedIds.has(nestedId)) {\n pendingIds.add(nestedId);\n }\n }\n }\n }\n }\n\n return allDefinitions;\n}\n\n/**\n * Resolve interaction destination nodes (e.g., hover variants).\n *\n * Collects all destinationId values from interactions in the document,\n * excludes those already in componentDefinitions, and fetches them.\n */\nexport async function resolveInteractionDestinations(\n client: FigmaClient,\n fileKey: string,\n document: AnalysisNode,\n existingDefinitions?: Record<string, AnalysisNode>,\n): Promise<Record<string, AnalysisNode>> {\n const destIds = collectInteractionDestinationIds(document);\n if (destIds.size === 0) return {};\n\n const allDestinations: Record<string, AnalysisNode> = {};\n const idsToFetch: string[] = [];\n\n for (const id of destIds) {\n const existing = existingDefinitions?.[id];\n if (existing) {\n allDestinations[id] = existing;\n } else {\n idsToFetch.push(id);\n }\n }\n\n if (idsToFetch.length === 0) return allDestinations;\n\n for (let i = 0; i < idsToFetch.length; i += BATCH_SIZE) {\n const batch = idsToFetch.slice(i, i + BATCH_SIZE);\n try {\n const response = await client.getFileNodes(fileKey, batch);\n const transformed = transformComponentMasterNodes(response, batch);\n for (const [id, node] of Object.entries(transformed)) {\n allDestinations[id] = node;\n }\n } catch (err) {\n console.debug(`[component-resolver] interaction destination fetch failed (${batch.length} ids):`, err);\n }\n }\n\n return allDestinations;\n}\n","import { z } from \"zod\";\n\n/**\n * Figma node types required for analysis\n * See @figma/rest-api-spec for full API types\n */\n\nexport const AnalysisNodeTypeSchema = z.enum([\n \"DOCUMENT\",\n \"CANVAS\",\n \"FRAME\",\n \"GROUP\",\n \"SECTION\",\n \"COMPONENT\",\n \"COMPONENT_SET\",\n \"INSTANCE\",\n \"RECTANGLE\",\n \"ELLIPSE\",\n \"VECTOR\",\n \"TEXT\",\n \"LINE\",\n \"BOOLEAN_OPERATION\",\n \"STAR\",\n \"REGULAR_POLYGON\",\n \"SLICE\",\n \"STICKY\",\n \"SHAPE_WITH_TEXT\",\n \"CONNECTOR\",\n \"WIDGET\",\n \"EMBED\",\n \"LINK_UNFURL\",\n \"TABLE\",\n \"TABLE_CELL\",\n \"SLOT\",\n]);\n\nexport type AnalysisNodeType = z.infer<typeof AnalysisNodeTypeSchema>;\n\nexport const LayoutModeSchema = z.enum([\"NONE\", \"HORIZONTAL\", \"VERTICAL\", \"GRID\"]);\nexport type LayoutMode = z.infer<typeof LayoutModeSchema>;\n\nexport const LayoutAlignSchema = z.enum([\"MIN\", \"CENTER\", \"MAX\", \"STRETCH\", \"INHERIT\"]);\nexport type LayoutAlign = z.infer<typeof LayoutAlignSchema>;\n\nexport const LayoutPositioningSchema = z.enum([\"AUTO\", \"ABSOLUTE\"]);\nexport type LayoutPositioning = z.infer<typeof LayoutPositioningSchema>;\n\nexport const LayoutConstraintSchema = z.object({\n horizontal: z.enum([\"LEFT\", \"RIGHT\", \"CENTER\", \"LEFT_RIGHT\", \"SCALE\"]),\n vertical: z.enum([\"TOP\", \"BOTTOM\", \"CENTER\", \"TOP_BOTTOM\", \"SCALE\"]),\n});\nexport type LayoutConstraint = z.infer<typeof LayoutConstraintSchema>;\n\nexport const LayoutWrapSchema = z.enum([\"NO_WRAP\", \"WRAP\"]);\nexport type LayoutWrap = z.infer<typeof LayoutWrapSchema>;\n\nexport const OverflowDirectionSchema = z.enum([\n \"HORIZONTAL_SCROLLING\",\n \"VERTICAL_SCROLLING\",\n \"HORIZONTAL_AND_VERTICAL_SCROLLING\",\n \"NONE\",\n]);\nexport type OverflowDirection = z.infer<typeof OverflowDirectionSchema>;\n\nexport const GridChildAlignSchema = z.enum([\"AUTO\", \"MIN\", \"CENTER\", \"MAX\"]);\nexport type GridChildAlign = z.infer<typeof GridChildAlignSchema>;\n\n/**\n * Lightweight FigmaNode type for analysis\n * Contains only properties needed by rules\n */\nconst BaseAnalysisNodeSchema = z.object({\n // Basic identification\n id: z.string(),\n name: z.string(),\n type: AnalysisNodeTypeSchema,\n visible: z.boolean().default(true),\n\n // Layout analysis\n layoutMode: LayoutModeSchema.optional(),\n layoutAlign: LayoutAlignSchema.optional(),\n layoutPositioning: LayoutPositioningSchema.optional(),\n layoutSizingHorizontal: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n layoutSizingVertical: z.enum([\"FIXED\", \"HUG\", \"FILL\"]).optional(),\n primaryAxisAlignItems: z.string().optional(),\n counterAxisAlignItems: z.string().optional(),\n itemSpacing: z.number().optional(),\n paddingLeft: z.number().optional(),\n paddingRight: z.number().optional(),\n paddingTop: z.number().optional(),\n paddingBottom: z.number().optional(),\n\n // Size constraints (responsive)\n minWidth: z.number().optional(),\n maxWidth: z.number().optional(),\n minHeight: z.number().optional(),\n maxHeight: z.number().optional(),\n layoutGrow: z.union([z.literal(0), z.literal(1)]).optional(),\n constraints: LayoutConstraintSchema.optional(),\n\n // Wrap (flex-wrap)\n layoutWrap: LayoutWrapSchema.optional(),\n counterAxisSpacing: z.number().optional(),\n counterAxisAlignContent: z.enum([\"AUTO\", \"SPACE_BETWEEN\"]).optional(),\n\n // Grid layout (container)\n gridRowCount: z.number().optional(),\n gridColumnCount: z.number().optional(),\n gridRowGap: z.number().optional(),\n gridColumnGap: z.number().optional(),\n gridColumnsSizing: z.string().optional(),\n gridRowsSizing: z.string().optional(),\n\n // Grid layout (child)\n gridChildHorizontalAlign: GridChildAlignSchema.optional(),\n gridChildVerticalAlign: GridChildAlignSchema.optional(),\n gridRowSpan: z.number().optional(),\n gridColumnSpan: z.number().optional(),\n gridRowAnchorIndex: z.number().optional(),\n gridColumnAnchorIndex: z.number().optional(),\n\n // Overflow / clip\n clipsContent: z.boolean().optional(),\n overflowDirection: OverflowDirectionSchema.optional(),\n\n // Size/position analysis\n absoluteBoundingBox: z\n .object({\n x: z.number(),\n y: z.number(),\n width: z.number(),\n height: z.number(),\n })\n .nullable()\n .optional(),\n\n // Component analysis\n componentId: z.string().optional(),\n componentPropertyDefinitions: z.record(z.string(), z.unknown()).optional(),\n componentProperties: z.record(z.string(), z.unknown()).optional(),\n\n // Style/token analysis\n styles: z.record(z.string(), z.string()).optional(),\n fills: z.array(z.unknown()).optional(),\n strokes: z.array(z.unknown()).optional(),\n strokeWeight: z.number().optional(),\n individualStrokeWeights: z.record(z.string(), z.number()).optional(),\n effects: z.array(z.unknown()).optional(),\n cornerRadius: z.number().optional(),\n opacity: z.number().optional(),\n\n // Variable binding analysis (design tokens)\n boundVariables: z.record(z.string(), z.unknown()).optional(),\n\n // Text analysis\n characters: z.string().optional(),\n style: z.record(z.string(), z.unknown()).optional(),\n textTruncation: z.enum([\"DISABLED\", \"ENDING\"]).optional(),\n maxLines: z.number().optional(),\n\n // Handoff analysis\n devStatus: z\n .object({\n type: z.enum([\"NONE\", \"READY_FOR_DEV\", \"COMPLETED\"]),\n description: z.string().optional(),\n })\n .optional(),\n\n // Prototype interactions\n interactions: z.array(z.unknown()).optional(),\n\n // Naming analysis metadata\n isAsset: z.boolean().optional(),\n});\n\nexport type AnalysisNode = z.infer<typeof BaseAnalysisNodeSchema> & {\n children?: AnalysisNode[] | undefined;\n};\n\nexport const AnalysisNodeSchema: z.ZodType<AnalysisNode> =\n BaseAnalysisNodeSchema.extend({\n children: z.lazy(() => AnalysisNodeSchema.array().optional()),\n }) as z.ZodType<AnalysisNode>;\n\n/**\n * Figma file metadata for analysis\n */\nexport const AnalysisFileSchema = z.object({\n fileKey: z.string(),\n name: z.string(),\n lastModified: z.string(),\n version: z.string(),\n sourceUrl: z.string().optional(),\n document: AnalysisNodeSchema,\n components: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n description: z.string(),\n })\n ),\n componentDefinitions: z.record(z.string(), AnalysisNodeSchema).optional(),\n interactionDestinations: z.record(z.string(), AnalysisNodeSchema).optional(),\n styles: z.record(\n z.string(),\n z.object({\n key: z.string(),\n name: z.string(),\n styleType: z.string(),\n })\n ),\n});\n\nexport type AnalysisFile = z.infer<typeof AnalysisFileSchema>;\n","import { readFile } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport type { GetFileResponse } from \"@figma/rest-api-spec\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport { AnalysisNodeSchema } from \"../contracts/figma-node.js\";\nimport { transformFigmaResponse } from \"./figma-transformer.js\";\n\n/**\n * Extract fileKey from fixture path.\n * - fixtures/name/data.json → name (directory-based fixture)\n * - fixtures/name.json → name (legacy flat fixture)\n */\nfunction extractFileKey(filePath: string): string {\n const fileName = basename(filePath, \".json\");\n if (fileName === \"data\") {\n // Directory-based fixture: use parent directory name\n return basename(dirname(filePath));\n }\n return fileName;\n}\n\n/**\n * Load Figma data from a JSON file\n * For MVP testing and fixture support\n */\nexport async function loadFigmaFileFromJson(\n filePath: string\n): Promise<AnalysisFile> {\n const content = await readFile(filePath, \"utf-8\");\n const data = JSON.parse(content) as GetFileResponse & {\n componentDefinitions?: Record<string, unknown>;\n interactionDestinations?: Record<string, unknown>;\n };\n\n const fileKey = extractFileKey(filePath);\n\n const file = transformFigmaResponse(fileKey, data);\n\n // Preserve componentDefinitions from previously-saved fixtures\n if (data.componentDefinitions) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.componentDefinitions)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] componentDefinitions[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.componentDefinitions = parsed;\n }\n }\n\n // Preserve interactionDestinations from previously-saved fixtures\n if (data.interactionDestinations) {\n const parsed: Record<string, AnalysisNode> = {};\n for (const [id, raw] of Object.entries(data.interactionDestinations)) {\n const result = AnalysisNodeSchema.safeParse(raw);\n if (result.success) {\n parsed[id] = result.data;\n } else {\n console.debug(`[figma-file-loader] interactionDestinations[${id}] failed validation:`, result.error.issues);\n }\n }\n if (Object.keys(parsed).length > 0) {\n file.interactionDestinations = parsed;\n }\n }\n\n return file;\n}\n\n/**\n * Parse Figma data from a JSON string\n */\nexport function parseFigmaJson(\n json: string,\n fileKey: string\n): AnalysisFile {\n const data = JSON.parse(json) as GetFileResponse;\n return transformFigmaResponse(fileKey, data);\n}\n\nexport class FigmaFileLoadError extends Error {\n constructor(message: string, public filePath?: string) {\n super(message);\n this.name = \"FigmaFileLoadError\";\n }\n}\n","import { z } from \"zod\";\n\nexport const FigmaUrlInfoSchema = z.object({\n fileKey: z.string(),\n nodeId: z.string().optional(),\n fileName: z.string().optional(),\n});\n\nexport type FigmaUrlInfo = z.infer<typeof FigmaUrlInfoSchema>;\n\nconst FIGMA_URL_PATTERNS = [\n // https://www.figma.com/design/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/design\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/file/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/file\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n // https://www.figma.com/proto/FILE_KEY/FILE_NAME?node-id=NODE_ID\n /figma\\.com\\/proto\\/([a-zA-Z0-9]+)(?:\\/([^?]+))?(?:\\?.*node-id=([^&]+))?/,\n];\n\nexport function parseFigmaUrl(url: string): FigmaUrlInfo {\n for (const pattern of FIGMA_URL_PATTERNS) {\n const match = url.match(pattern);\n if (match) {\n const [, fileKey, fileName, nodeId] = match;\n if (!fileKey) {\n throw new FigmaUrlParseError(`Invalid Figma URL: missing file key`);\n }\n return {\n fileKey,\n fileName: fileName ? decodeURIComponent(fileName) : undefined,\n nodeId: nodeId ? decodeURIComponent(nodeId) : undefined,\n };\n }\n }\n\n throw new FigmaUrlParseError(\n `Invalid Figma URL format. Expected: https://www.figma.com/design/FILE_KEY/...`\n );\n}\n\nexport class FigmaUrlParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FigmaUrlParseError\";\n }\n}\n\n/**\n * Extract the commentable node ID from a potentially nested instance path.\n * Instance-internal IDs like \"I3010:7457;1442:7704\" use semicolons to\n * separate path segments. The Figma Comments API only accepts simple IDs\n * (e.g. \"3010:7457\"), so we take the first segment and strip the \"I\" prefix.\n */\nexport function toCommentableNodeId(nodeId: string): string {\n const firstSegment = nodeId.split(\";\")[0]!;\n return firstSegment.replace(/^I/, \"\");\n}\n\nexport function buildFigmaDeepLink(fileKey: string, nodeId: string): string {\n // Strip instance-internal path to top-level node:\n // \"I175:7425;1442:7704\" → \"175:7425\" → \"175-7425\"\n const topNodeId = toCommentableNodeId(nodeId).replace(/:/g, \"-\");\n return `https://www.figma.com/design/${fileKey}?node-id=${topNodeId}`;\n}\n","import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nconst AIREADY_DIR = join(homedir(), \".canicode\");\nconst CONFIG_PATH = join(AIREADY_DIR, \"config.json\");\nconst REPORTS_DIR = join(AIREADY_DIR, \"reports\");\n\ninterface AireadyConfig {\n figmaToken?: string;\n telemetry?: boolean;\n posthogApiKey?: string;\n sentryDsn?: string;\n deviceId?: string;\n}\n\nfunction hardenPermissions(path: string, mode: number): void {\n if (process.platform !== \"win32\") {\n chmodSync(path, mode);\n }\n}\n\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n hardenPermissions(dir, 0o700);\n}\n\nexport function readConfig(): AireadyConfig {\n if (!existsSync(CONFIG_PATH)) {\n return {};\n }\n try {\n const raw = readFileSync(CONFIG_PATH, \"utf-8\");\n return JSON.parse(raw) as AireadyConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: AireadyConfig): void {\n ensureDir(AIREADY_DIR);\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + \"\\n\", {\n encoding: \"utf-8\",\n mode: 0o600,\n });\n hardenPermissions(CONFIG_PATH, 0o600);\n}\n\nexport function getFigmaToken(): string | undefined {\n // Priority: env var > config file\n return process.env[\"FIGMA_TOKEN\"] ?? readConfig().figmaToken;\n}\n\nexport function setFigmaToken(token: string): void {\n const config = readConfig();\n config.figmaToken = token;\n writeConfig(config);\n}\n\nexport function hasConfig(): boolean {\n return existsSync(CONFIG_PATH);\n}\n\nexport function getConfigPath(): string {\n return CONFIG_PATH;\n}\n\nexport function getReportsDir(): string {\n return REPORTS_DIR;\n}\n\nexport function ensureReportsDir(): void {\n ensureDir(AIREADY_DIR);\n ensureDir(REPORTS_DIR);\n}\n\nexport function getTelemetryEnabled(): boolean {\n return readConfig().telemetry !== false;\n}\n\nexport function setTelemetryEnabled(enabled: boolean): void {\n const config = readConfig();\n config.telemetry = enabled;\n writeConfig(config);\n}\n\nexport function getPosthogApiKey(): string | undefined {\n return process.env[\"POSTHOG_API_KEY\"] ?? readConfig().posthogApiKey;\n}\n\nexport function getSentryDsn(): string | undefined {\n return process.env[\"SENTRY_DSN\"] ?? readConfig().sentryDsn;\n}\n\n/**\n * Get or create a stable anonymous device ID for telemetry.\n * Stored in ~/.canicode/config.json, persists across sessions.\n */\nexport function getDeviceId(): string {\n const config = readConfig();\n if (config.deviceId) return config.deviceId;\n\n const id = randomUUID();\n config.deviceId = id;\n writeConfig(config);\n return id;\n}\n\n/**\n * Initialize canicode: write config + create reports dir\n */\nexport function initAiready(token: string): void {\n setFigmaToken(token);\n ensureReportsDir();\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { resolve, join } from \"node:path\";\nimport { FigmaClient } from \"../adapters/figma-client.js\";\nimport { resolveComponentDefinitions, resolveInteractionDestinations } from \"../adapters/component-resolver.js\";\nimport { loadFigmaFileFromJson } from \"../adapters/figma-file-loader.js\";\nimport { transformFigmaResponse, transformFileNodesResponse } from \"../adapters/figma-transformer.js\";\nimport { parseFigmaUrl } from \"../adapters/figma-url-parser.js\";\nimport { getFigmaToken } from \"./config-store.js\";\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\n\nexport interface LoadResult {\n file: AnalysisFile;\n nodeId?: string | undefined;\n}\n\n/** Check if input string is a Figma URL. */\nexport function isFigmaUrl(input: string): boolean {\n return input.includes(\"figma.com/\");\n}\n\n/** Check if input string is a JSON file path. */\nexport function isJsonFile(input: string): boolean {\n return input.endsWith(\".json\");\n}\n\n/**\n * Check if input is a fixture directory (contains data.json).\n */\nexport function isFixtureDir(input: string): boolean {\n const resolved = resolve(input);\n if (!existsSync(resolved)) return false;\n try {\n if (!statSync(resolved).isDirectory()) return false;\n } catch {\n return false;\n }\n return existsSync(join(resolved, \"data.json\"));\n}\n\n/**\n * Resolve fixture input to data.json path.\n * Input: fixtures/name/ or fixtures/name → fixtures/name/data.json\n */\nexport function resolveFixturePath(input: string): string {\n if (isJsonFile(input)) return resolve(input);\n return resolve(join(input, \"data.json\"));\n}\n\n/**\n * Load a Figma file from a URL, JSON file, or fixture directory.\n * Resolves component master node trees for accurate analysis.\n */\nexport async function loadFile(\n input: string,\n token?: string,\n): Promise<LoadResult> {\n if (isJsonFile(input) || isFixtureDir(input)) {\n const filePath = resolveFixturePath(input);\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n console.error(`Loading from JSON: ${filePath}`);\n return { file: await loadFigmaFileFromJson(filePath) };\n }\n\n if (isFigmaUrl(input)) {\n const { fileKey, nodeId } = parseFigmaUrl(input);\n return loadFromApi(fileKey, nodeId, token);\n }\n\n throw new Error(\n `Invalid input: ${input}. Provide a Figma URL or fixture directory path.`\n );\n}\n\nasync function loadFromApi(\n fileKey: string,\n nodeId: string | undefined,\n token?: string\n): Promise<LoadResult> {\n console.error(`Fetching from Figma REST API: ${fileKey}`);\n if (nodeId) {\n console.error(`Target node: ${nodeId}`);\n }\n\n const figmaToken = token ?? getFigmaToken();\n if (!figmaToken) {\n throw new Error(\n \"Figma token required. Run 'canicode init --token YOUR_TOKEN' or set FIGMA_TOKEN env var.\"\n );\n }\n\n const client = new FigmaClient({ token: figmaToken });\n\n if (nodeId) {\n // Fetch only the target node subtree — faster, less rate limit impact\n const response = await client.getFileNodes(fileKey, [nodeId.replace(/-/g, \":\")]);\n const file = transformFileNodesResponse(fileKey, response);\n\n // Resolve component master node trees for accurate analysis\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n }\n\n const response = await client.getFile(fileKey);\n const file = transformFigmaResponse(fileKey, response);\n\n // Full file fetch may still miss component masters from external libraries\n const componentDefs = await resolveComponentDefinitions(client, fileKey, file.document);\n if (Object.keys(componentDefs).length > 0) {\n file.componentDefinitions = componentDefs;\n }\n\n // Resolve interaction destination nodes (e.g., hover variants)\n const interactionDests = await resolveInteractionDestinations(client, fileKey, file.document, file.componentDefinitions);\n if (Object.keys(interactionDests).length > 0) {\n file.interactionDestinations = interactionDests;\n }\n\n return { file, nodeId };\n}\n","/**\n * Parse Figma instance-child node IDs.\n *\n * Nodes inside an instance carry an `I`-prefixed id with semicolon-separated\n * path segments: `I<parentInstanceId>;<sourceNodeId>`. For nested instances\n * the format chains further, e.g. `I<parentId>;<midId>;<sourceNodeId>` —\n * each `;` represents one additional level of instance expansion. The LAST\n * segment is always the id of the node inside the innermost source component,\n * which is reachable directly via `figma.getNodeById`.\n *\n * Siblings: `figma-url-parser.ts#toCommentableNodeId` handles the same id\n * format for a different purpose (stripping for the Comments API). That\n * helper is intentionally left alone — this module owns id parsing for the\n * apply pipeline.\n */\n\nexport interface InstanceChildIdParts {\n parentInstanceId: string;\n sourceNodeId: string;\n}\n\nexport function isInstanceChildNodeId(nodeId: string): boolean {\n return nodeId.startsWith(\"I\") && nodeId.includes(\";\");\n}\n\nexport function parseInstanceChildNodeId(\n nodeId: string,\n): InstanceChildIdParts | null {\n if (!isInstanceChildNodeId(nodeId)) return null;\n\n const segments = nodeId.split(\";\");\n if (segments.length < 2) return null;\n\n const parentInstanceId = segments[0]!.replace(/^I/, \"\");\n const sourceNodeId = segments[segments.length - 1]!;\n\n if (!parentInstanceId || !sourceNodeId) return null;\n\n return { parentInstanceId, sourceNodeId };\n}\n","import type { RuleId, RuleViolation } from \"../contracts/rule.js\";\nimport type { InstanceContext } from \"../contracts/gotcha-survey.js\";\nimport type { AnnotationProperty } from \"../roundtrip/types.js\";\nimport {\n isInstanceChildNodeId,\n parseInstanceChildNodeId,\n} from \"../adapters/instance-id-parser.js\";\nimport { getAnnotationProperties } from \"../rules/rule-config.js\";\n\n/**\n * Apply strategy for a rule violation. Tells the SKILL.md/`use_figma`\n * pipeline which Plugin-API path to take.\n *\n * - `property-mod` — Strategy A. Direct property write on the scene/instance node.\n * - `structural-mod` — Strategy B. Structural change; ask user to confirm before applying.\n * - `annotation` — Strategy C. Cannot be auto-fixed; record as a Figma annotation.\n * - `auto-fix` — Strategy D. Lower-severity rules from analyze output;\n * may be a property write (naming) or annotation-only.\n *\n * Sibling module `resolve-apply-target.ts` solves a different concern\n * (scene-vs-definition write target). Compose them — do not merge.\n */\nexport type RuleApplyStrategy =\n | \"property-mod\"\n | \"structural-mod\"\n | \"annotation\"\n | \"auto-fix\";\n\n/**\n * Pre-computed apply context attached to gotcha-survey questions and\n * analyze-output issues. Lets the SKILL.md consume the data directly\n * instead of re-deriving rule routing on every roundtrip run.\n *\n * `targetProperty` is `string` for single-property writes, `string[]`\n * for rules that require multiple writes (e.g. `irregular-spacing`\n * subType `padding` → 4 padding fields), and `undefined` for\n * annotation/structural strategies that have no single property target.\n */\nexport interface ApplyContext {\n applyStrategy: RuleApplyStrategy;\n targetProperty?: string | string[];\n annotationProperties?: AnnotationProperty[];\n isInstanceChild: boolean;\n sourceChildId?: string;\n}\n\nconst STRATEGY_BY_RULE: Record<RuleId, RuleApplyStrategy> = {\n // Strategy A — property modification\n \"no-auto-layout\": \"property-mod\",\n \"fixed-size-in-auto-layout\": \"property-mod\",\n \"missing-size-constraint\": \"property-mod\",\n \"irregular-spacing\": \"property-mod\",\n \"non-semantic-name\": \"property-mod\",\n // Strategy B — structural modification (needs user confirmation)\n \"non-layout-container\": \"structural-mod\",\n \"deep-nesting\": \"structural-mod\",\n \"missing-component\": \"structural-mod\",\n \"detached-instance\": \"structural-mod\",\n // Strategy C — annotation only\n \"absolute-position-in-auto-layout\": \"annotation\",\n \"variant-structure-mismatch\": \"annotation\",\n // Strategy D — auto-fix lower-severity issues from analyze output\n \"non-standard-naming\": \"auto-fix\",\n \"inconsistent-naming-convention\": \"auto-fix\",\n \"raw-value\": \"auto-fix\",\n \"missing-interaction-state\": \"auto-fix\",\n \"missing-prototype\": \"auto-fix\",\n};\n\n/**\n * Resolve the Figma Plugin-API target property (or properties) for a\n * violation. Returns `undefined` for rules whose strategy does not write\n * a single property (structural-mod, annotation), or for naming auto-fixes\n * where the value comes from `violation.suggestedName` rather than a\n * specific Figma property — except the `name` write itself, which we\n * surface so SKILL.md can branch uniformly on `targetProperty === 'name'`.\n */\nfunction resolveTargetProperty(\n ruleId: RuleId,\n subType: string | undefined,\n): string | string[] | undefined {\n switch (ruleId) {\n case \"no-auto-layout\":\n return [\"layoutMode\", \"itemSpacing\"];\n case \"fixed-size-in-auto-layout\":\n if (subType === \"horizontal\") return \"layoutSizingHorizontal\";\n // both-axes — write both axes\n return [\"layoutSizingHorizontal\", \"layoutSizingVertical\"];\n case \"missing-size-constraint\":\n // #374: always return BOTH bounds so `applyPropertyMod`'s array branch\n // iterates the full `{ minWidth, maxWidth }` answer shape. Pre-fix the\n // `wrap` subType returned `\"minWidth\"` and `max-width` returned\n // `\"maxWidth\"` as single strings — the user typically answered with\n // both keys (the gotcha hint asks for both) and the apply step\n // silently dropped half the intent because it only iterated the one\n // property in `targetProperty`. Partial answers still work: the per-\n // property lookup in `applyPropertyMod` returns `undefined` for the\n // missing key and the helper skips it.\n return [\"minWidth\", \"maxWidth\"];\n case \"irregular-spacing\":\n if (subType === \"gap\") return \"itemSpacing\";\n // padding — all four padding fields\n return [\"paddingTop\", \"paddingRight\", \"paddingBottom\", \"paddingLeft\"];\n case \"non-semantic-name\":\n return \"name\";\n case \"non-layout-container\":\n return \"layoutMode\";\n case \"non-standard-naming\":\n case \"inconsistent-naming-convention\":\n return \"name\";\n case \"deep-nesting\":\n case \"missing-component\":\n case \"detached-instance\":\n case \"absolute-position-in-auto-layout\":\n case \"variant-structure-mismatch\":\n case \"raw-value\":\n case \"missing-interaction-state\":\n case \"missing-prototype\":\n return undefined;\n }\n}\n\n/**\n * Compute the deterministic apply context for a rule violation.\n *\n * - `applyStrategy` and `targetProperty` come from the ruleId/subType tables above.\n * - `isInstanceChild` and `sourceChildId` are parsed from the violation `nodeId`\n * via `parseInstanceChildNodeId` — single source of truth for `I...;...` ids.\n * - `instanceContext`, when supplied, takes precedence for `sourceChildId` so\n * callers that already resolved the source component (gotcha-survey) do not\n * re-parse the id.\n *\n * Strategy D rules that target scene nodes (analyze output) can pass\n * `instanceContext: undefined` — the function still returns the parsed\n * `isInstanceChild`/`sourceChildId` so SKILL.md knows whether to walk the\n * instance fallback.\n */\nexport function computeApplyContext(\n violation: Pick<RuleViolation, \"ruleId\" | \"subType\" | \"nodeId\">,\n instanceContext?: InstanceContext,\n): ApplyContext {\n const ruleId = violation.ruleId as RuleId;\n const applyStrategy = STRATEGY_BY_RULE[ruleId] ?? \"annotation\";\n const targetProperty = resolveTargetProperty(ruleId, violation.subType);\n const annotationProperties = getAnnotationProperties(\n ruleId,\n violation.subType,\n );\n\n const parsed = parseInstanceChildNodeId(violation.nodeId);\n const isInstanceChild =\n parsed !== null || isInstanceChildNodeId(violation.nodeId);\n const sourceChildId = instanceContext?.sourceNodeId ?? parsed?.sourceNodeId;\n\n return {\n applyStrategy,\n ...(targetProperty !== undefined ? { targetProperty } : {}),\n ...(annotationProperties !== undefined ? { annotationProperties } : {}),\n isInstanceChild,\n ...(sourceChildId !== undefined ? { sourceChildId } : {}),\n };\n}\n","{\n \"name\": \"canicode\",\n \"version\": \"0.11.4\",\n \"mcpName\": \"io.github.let-sunny/canicode\",\n \"description\": \"Lint Figma designs for AI code-gen and roundtrip the answers back into the file. CLI + MCP server.\",\n \"type\": \"module\",\n \"main\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"canicode\": \"dist/cli/index.js\",\n \"canicode-mcp\": \"dist/mcp/server.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\"\n }\n },\n \"scripts\": {\n \"build\": \"tsup --config tsup.config.ts && pnpm build:roundtrip && pnpm bundle:skills\",\n \"build:web\": \"bash scripts/build-web.sh\",\n \"build:roundtrip\": \"tsup --config tsup.roundtrip.config.ts && tsx scripts/bundle-roundtrip-cache.ts\",\n \"bundle:skills\": \"bash scripts/bundle-skills.sh\",\n \"dev\": \"tsup --watch\",\n \"test\": \"vitest\",\n \"test:run\": \"vitest run\",\n \"lint\": \"tsc --noEmit\",\n \"build:plugin\": \"bash scripts/build-plugin.sh\",\n \"sync-docs\": \"tsx scripts/sync-rule-docs.ts\",\n \"check:skill-determinism\": \"tsx scripts/check-skill-determinism.ts\",\n \"check:server-json\": \"tsx scripts/check-server-json.ts\",\n \"clean\": \"rm -rf dist skills\"\n },\n \"files\": [\n \"dist\",\n \"skills\",\n \".claude-plugin\",\n \"README.md\",\n \"docs/CUSTOMIZATION.md\"\n ],\n \"keywords\": [\n \"figma\",\n \"design\",\n \"analysis\",\n \"cli\",\n \"mcp\",\n \"readiness\",\n \"ai\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/let-sunny/canicode.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/let-sunny/canicode/issues\"\n },\n \"homepage\": \"https://github.com/let-sunny/canicode\",\n \"author\": \"minseon\",\n \"license\": \"MIT\",\n \"pnpm\": {\n \"overrides\": {\n \"picomatch\": \"4.0.4\",\n \"path-to-regexp\": \"8.4.0\"\n }\n },\n \"packageManager\": \"pnpm@10.32.1\",\n \"engines\": {\n \"node\": \">=22\"\n },\n \"dependencies\": {\n \"@figma/rest-api-spec\": \"^0.36.0\",\n \"@modelcontextprotocol/sdk\": \"^1.27.1\",\n \"cac\": \"^7.0.0\",\n \"dotenv\": \"^17.3.1\",\n \"pixelmatch\": \"^7.1.0\",\n \"pngjs\": \"^7.0.0\",\n \"zod\": \"^4.3.6\"\n },\n \"devDependencies\": {\n \"@anthropic-ai/sdk\": \"^0.80.0\",\n \"@figma/plugin-typings\": \"^1.123.0\",\n \"@types/node\": \"^25.5.0\",\n \"@types/pngjs\": \"^6.0.5\",\n \"playwright\": \"^1.58.2\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.19.0\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.0\"\n }\n}\n","import type { Category } from \"../contracts/category.js\";\nimport { CATEGORIES, CATEGORY_LABELS } from \"../contracts/category.js\";\nimport type { RuleId, RuleConfig } from \"../contracts/rule.js\";\nimport type { Severity } from \"../contracts/severity.js\";\nimport type { AnalysisResult } from \"./rule-engine.js\";\nimport { RULE_CONFIGS, RULE_ID_CATEGORY, getRulePurpose } from \"../rules/rule-config.js\";\nimport { computeApplyContext } from \"../gotcha/apply-context.js\";\nimport { version as VERSION } from \"../../../package.json\";\n\n/**\n * Score breakdown for a single category\n */\nexport interface CategoryScoreResult {\n category: Category;\n score: number;\n maxScore: number;\n percentage: number;\n issueCount: number;\n uniqueRuleCount: number;\n weightedIssueCount: number;\n densityScore: number;\n diversityScore: number;\n bySeverity: Record<Severity, number>;\n}\n\n/**\n * Overall score report\n */\nexport interface ScoreReport {\n overall: {\n score: number;\n maxScore: number;\n percentage: number;\n grade: Grade;\n };\n byCategory: Record<Category, CategoryScoreResult>;\n summary: {\n totalIssues: number;\n blocking: number;\n risk: number;\n missingInfo: number;\n suggestion: number;\n nodeCount: number;\n /**\n * Number of issues marked `acknowledged` by an upstream\n * acknowledgments list (#371). Acknowledged issues are still counted in\n * `totalIssues` and the per-severity tallies — the count here is purely\n * additive context so consumers can render\n * `N issues — A acknowledged / N-A unaddressed`. They contribute half\n * weight to the density score upstream.\n */\n acknowledgedCount: number;\n };\n}\n\n/**\n * Grade levels based on percentage\n */\nexport type Grade = \"S\" | \"A+\" | \"A\" | \"B+\" | \"B\" | \"C+\" | \"C\" | \"D\" | \"F\";\n\n/**\n * Grade ordinal order from best to worst. Lower index = better grade.\n * Used for ordinal comparison in isReadyForCodeGen.\n */\nexport const GRADE_ORDER: readonly Grade[] = [\"S\", \"A+\", \"A\", \"B+\", \"B\", \"C+\", \"C\", \"D\", \"F\"] as const;\n\n/**\n * Default minimum grade for code-gen readiness. Designs at this grade or better\n * are considered ready for code generation. User-configurable via --ready-min-grade\n * CLI flag, codegenReadyMinGrade configPath field, or MCP param.\n */\nexport const DEFAULT_CODEGEN_READY_MIN_GRADE: Grade = \"A\";\n\n/**\n * Density weighting uses per-rule base |score| with sqrt damping (#226).\n *\n * Previously, each issue's |calculatedScore| was summed linearly — a rule\n * triggering N times contributed N× its score. This over-penalized designs\n * with many instances of the same issue (e.g., raw-value ×79 = -316 weight),\n * causing most real files to score Grade D/F with no differentiation.\n *\n * Now: same rule triggered N times contributes |score| × sqrt(N).\n * raw-value ×79 = 4 × sqrt(79) ≈ 36 instead of 316.\n * At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity.\n * At high counts the curve flattens — 79th occurrence adds ~0.2 vs 1st adding 4.\n *\n * Category weights removed (#196) — overall score is simple average of categories.\n * Category importance is already encoded in rule scores (pixel-critical -10\n * vs semantic -4), so per-category weighting is unnecessary.\n */\n\n/**\n * Compute sum of |score| for all rules in each category from a given config map.\n * Used as denominator for severity-weighted diversity scoring.\n * Must use the same preset-adjusted config map that produced the analysis issues,\n * otherwise diversity ratios will be incorrect.\n */\nfunction computeTotalScorePerCategory(\n configs: Record<RuleId, RuleConfig>\n): Record<Category, number> {\n const totals = Object.fromEntries(\n CATEGORIES.map(c => [c, 0])\n ) as Record<Category, number>;\n\n for (const [id, config] of Object.entries(configs)) {\n const category = RULE_ID_CATEGORY[id as RuleId];\n if (category && config.enabled) {\n totals[category] += Math.abs(config.score);\n }\n }\n\n return totals;\n}\n\n/**\n * Score composition weights (initial intuition, pending calibration validation).\n *\n * Density (0.7): \"how many issues per node\" — measures issue volume relative to design size.\n * Designs with many issues per node are harder to implement accurately.\n *\n * Diversity (0.3): \"how many different rule types triggered\" — measures issue breadth.\n * A design that triggers 1 rule 50 times is easier to fix than one triggering 10 different rules.\n *\n * The 70:30 ratio prioritizes volume over variety. Rationale: a design with a single\n * systemic problem (e.g., all frames missing auto-layout) is still very hard to implement,\n * even though diversity is low. Density captures this; diversity adds a penalty for\n * designs with scattered, unrelated issues.\n *\n * Status: initial values. To be validated via /calibrate against visual-compare results.\n */\nconst DENSITY_WEIGHT = 0.7;\nconst DIVERSITY_WEIGHT = 0.3;\n\n/**\n * Minimum score floor.\n * Even the worst design gets 5% instead of 0%. Rationale: a score of 0 implies\n * \"completely unimplementable\", but any Figma file with visible nodes provides\n * some structural information. The floor also avoids demoralizing UX — seeing 0%\n * feels like the tool failed, not that the design needs improvement.\n */\nconst SCORE_FLOOR = 5;\n\n/**\n * Calculate grade from percentage.\n * Thresholds follow a 5-point interval pattern (95/90/85/80/75/70/65) with a wider\n * gap for D (50-64) and F (<50). This mirrors academic grading conventions where\n * the top tiers are tightly spaced and the failing range is broad.\n */\nfunction calculateGrade(percentage: number): Grade {\n if (percentage >= 95) return \"S\";\n if (percentage >= 90) return \"A+\";\n if (percentage >= 85) return \"A\";\n if (percentage >= 80) return \"B+\";\n if (percentage >= 75) return \"B\";\n if (percentage >= 70) return \"C+\";\n if (percentage >= 65) return \"C\";\n if (percentage >= 50) return \"D\";\n return \"F\";\n}\n\n/**\n * Returns true if the design is ready for code generation.\n * By default, S, A+, and A grades (percentage >= 85) pass. Users can tighten or\n * loosen this threshold via the optional minGrade parameter (or codegenReadyMinGrade\n * in config / --ready-min-grade CLI flag). A grade passes when its ordinal position\n * in GRADE_ORDER is <= the minGrade position (lower index = better grade).\n */\nexport function isReadyForCodeGen(grade: Grade, minGrade?: Grade): boolean {\n const threshold = minGrade ?? DEFAULT_CODEGEN_READY_MIN_GRADE;\n return GRADE_ORDER.indexOf(grade) <= GRADE_ORDER.indexOf(threshold);\n}\n\n/**\n * Convert grade to a CSS-safe class name suffix\n * e.g. \"A+\" -> \"Aplus\", \"B+\" -> \"Bplus\", \"C+\" -> \"Cplus\"\n */\nexport function gradeToClassName(grade: Grade): string {\n return grade.replace(\"+\", \"plus\");\n}\n\n/**\n * Clamp a value between min and max\n */\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/**\n * Calculate scores from analysis result using density + diversity scoring\n *\n * Density Score = 100 - (weighted issue count / node count) * 100\n * Diversity Score = (1 - weighted triggered rule scores / total category scores) * 100\n * Final Score = density * 0.7 + diversity * 0.3\n *\n * @param result Analysis result with issues\n * @param configs Optional preset-adjusted config map used to produce the issues.\n * If not provided, diversity totals are reconstructed from issue.config values.\n */\nexport function calculateScores(\n result: AnalysisResult,\n configs?: Record<RuleId, RuleConfig>\n): ScoreReport {\n const categoryScores = initializeCategoryScores();\n const nodeCount = result.nodeCount;\n\n // Track unique rules and their base |score| per category\n const uniqueRulesPerCategory = new Map<Category, Set<string>>();\n const ruleScorePerCategory = new Map<Category, Map<string, number>>();\n // Track issue counts per rule per category for sqrt damping (#226)\n const ruleIssueCountPerCategory = new Map<Category, Map<string, number>>();\n for (const category of CATEGORIES) {\n uniqueRulesPerCategory.set(category, new Set());\n ruleScorePerCategory.set(category, new Map());\n ruleIssueCountPerCategory.set(category, new Map());\n }\n\n // Compute totals from the config map.\n // If configs provided: use preset-adjusted totals (recommended when using presets).\n // If not: fall back to static RULE_CONFIGS — only correct when issues were\n // produced with default RULE_CONFIGS, otherwise diversity ratios will be skewed.\n const totalScorePerCategory = computeTotalScorePerCategory(configs ?? RULE_CONFIGS);\n\n // Count issues by severity per category and track unique rules with scores\n for (const issue of result.issues) {\n const category = issue.rule.definition.category;\n const severity = issue.config.severity;\n const ruleId = issue.rule.definition.id;\n\n categoryScores[category].issueCount++;\n categoryScores[category].bySeverity[severity]++;\n uniqueRulesPerCategory.get(category)!.add(ruleId);\n ruleScorePerCategory.get(category)!.set(ruleId, Math.abs(issue.config.score));\n // Accumulate per-rule issue count using a per-issue weight: 1.0 for\n // unacknowledged issues, 0.5 for acknowledged ones (#371). The sqrt\n // damping below treats this sum as the \"occurrence count\" so the\n // half-weight flows through to density without changing the formula.\n // Diversity is left untouched — acknowledgment is per-issue, not\n // per-rule, and the rule still represents a kind of problem.\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n const weight = issue.acknowledged === true ? 0.5 : 1;\n ruleCountMap.set(ruleId, (ruleCountMap.get(ruleId) ?? 0) + weight);\n }\n\n // Compute weightedIssueCount with sqrt damping per rule (#226).\n // Same rule triggered N times contributes |score| × sqrt(N) instead of |score| × N.\n // Rationale: 79 raw-value issues represent one systemic problem, not 79× the difficulty.\n // First few occurrences identify the problem; subsequent ones have diminishing impact.\n // At low counts sqrt ≈ linear (sqrt(1)=1, sqrt(4)=2), preserving sensitivity for rare issues.\n for (const category of CATEGORIES) {\n const ruleCountMap = ruleIssueCountPerCategory.get(category)!;\n const ruleScoreMap = ruleScorePerCategory.get(category)!;\n let dampedWeight = 0;\n for (const [ruleId, count] of ruleCountMap) {\n const ruleScore = ruleScoreMap.get(ruleId) ?? 0;\n dampedWeight += ruleScore * Math.sqrt(count);\n }\n categoryScores[category].weightedIssueCount = dampedWeight;\n }\n\n // Calculate percentage for each category based on density + diversity\n for (const category of CATEGORIES) {\n const catScore = categoryScores[category];\n const uniqueRules = uniqueRulesPerCategory.get(category)!;\n\n catScore.uniqueRuleCount = uniqueRules.size;\n\n // Density score: lower density = higher score\n let densityScore = 100;\n if (nodeCount > 0 && catScore.issueCount > 0) {\n const density = catScore.weightedIssueCount / nodeCount;\n densityScore = clamp(Math.round(100 - density * 100), 0, 100);\n }\n catScore.densityScore = densityScore;\n\n // Diversity score: weighted by base rule |score| (config.score, not calculatedScore).\n // Uses base score intentionally — diversity measures \"what types of problems exist\",\n // not \"where they occur\". depthWeight affects density (volume penalty) but not diversity\n // (breadth penalty). A blocking rule (score -10) penalizes diversity more than a\n // suggestion (score -1), so low-severity-only designs correctly get high diversity scores.\n let diversityScore = 100;\n if (catScore.issueCount > 0) {\n const ruleScores = ruleScorePerCategory.get(category)!;\n const weightedTriggered = Array.from(ruleScores.values()).reduce((sum, s) => sum + s, 0);\n const weightedTotal = totalScorePerCategory[category];\n const diversityRatio = weightedTotal > 0 ? weightedTriggered / weightedTotal : 0;\n diversityScore = clamp(Math.round((1 - diversityRatio) * 100), 0, 100);\n }\n catScore.diversityScore = diversityScore;\n\n // Combined score with floor\n const combinedScore = densityScore * DENSITY_WEIGHT + diversityScore * DIVERSITY_WEIGHT;\n catScore.percentage = catScore.issueCount > 0\n ? clamp(Math.round(combinedScore), SCORE_FLOOR, 100)\n : 100;\n\n catScore.score = catScore.percentage;\n catScore.maxScore = 100;\n }\n\n // Calculate overall score as simple average of categories\n // Category importance is already encoded in rule scores (weight baked in),\n // so no per-category weighting is needed.\n let categorySum = 0;\n for (const category of CATEGORIES) {\n categorySum += categoryScores[category].percentage;\n }\n\n const overallPercentage = CATEGORIES.length > 0\n ? Math.round(categorySum / CATEGORIES.length)\n : 100;\n\n // Count issues by severity\n const summary = {\n totalIssues: result.issues.length,\n blocking: 0,\n risk: 0,\n missingInfo: 0,\n suggestion: 0,\n nodeCount,\n acknowledgedCount: 0,\n };\n\n for (const issue of result.issues) {\n switch (issue.config.severity) {\n case \"blocking\":\n summary.blocking++;\n break;\n case \"risk\":\n summary.risk++;\n break;\n case \"missing-info\":\n summary.missingInfo++;\n break;\n case \"suggestion\":\n summary.suggestion++;\n break;\n }\n if (issue.acknowledged === true) summary.acknowledgedCount++;\n }\n\n return {\n overall: {\n score: overallPercentage,\n maxScore: 100,\n percentage: overallPercentage,\n grade: calculateGrade(overallPercentage),\n },\n byCategory: categoryScores,\n summary,\n };\n}\n\n/**\n * Initialize empty category scores\n */\nfunction initializeCategoryScores(): Record<Category, CategoryScoreResult> {\n const scores: Partial<Record<Category, CategoryScoreResult>> = {};\n\n for (const category of CATEGORIES) {\n scores[category] = {\n category,\n score: 100,\n maxScore: 100,\n percentage: 100,\n issueCount: 0,\n uniqueRuleCount: 0,\n weightedIssueCount: 0,\n densityScore: 100,\n diversityScore: 100,\n bySeverity: {\n blocking: 0,\n risk: 0,\n \"missing-info\": 0,\n suggestion: 0,\n },\n };\n }\n\n return scores as Record<Category, CategoryScoreResult>;\n}\n\n/**\n * Format score report as a summary string\n */\nexport function formatScoreSummary(report: ScoreReport): string {\n const lines: string[] = [];\n\n lines.push(`Overall: ${report.overall.grade} (${report.overall.percentage}%)`);\n lines.push(\"\");\n lines.push(\"By Category:\");\n\n for (const category of CATEGORIES) {\n const cat = report.byCategory[category];\n lines.push(` ${category}: ${cat.percentage}% (${cat.issueCount} issues, ${cat.uniqueRuleCount} rules)`);\n }\n\n lines.push(\"\");\n lines.push(\"Issues:\");\n lines.push(` Blocking: ${report.summary.blocking}`);\n lines.push(` Risk: ${report.summary.risk}`);\n lines.push(` Missing Info: ${report.summary.missingInfo}`);\n lines.push(` Suggestion: ${report.summary.suggestion}`);\n if (report.summary.acknowledgedCount > 0) {\n const unaddressed =\n report.summary.totalIssues - report.summary.acknowledgedCount;\n lines.push(\n ` Total: ${report.summary.totalIssues} (${report.summary.acknowledgedCount} acknowledged via canicode annotations / ${unaddressed} unaddressed)`\n );\n } else {\n lines.push(` Total: ${report.summary.totalIssues}`);\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Get category label for display\n */\nexport function getCategoryLabel(category: Category): string {\n return CATEGORY_LABELS[category];\n}\n\n/**\n * Get severity label for display\n */\nexport function getSeverityLabel(severity: Severity): string {\n const labels: Record<Severity, string> = {\n blocking: \"Blocking\",\n risk: \"Risk\",\n \"missing-info\": \"Missing Info\",\n suggestion: \"Suggestion\",\n };\n return labels[severity];\n}\n\n/**\n * Build a JSON-serializable analysis result summary.\n * Shared by CLI (--json) and MCP server (analyze tool response).\n */\nexport function buildResultJson(\n fileName: string,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: { fileKey?: string; designKey?: string; codegenReadyMinGrade?: Grade },\n): Record<string, unknown> {\n const issuesByRule: Record<string, number> = {};\n for (const issue of result.issues) {\n const id = issue.violation.ruleId;\n issuesByRule[id] = (issuesByRule[id] ?? 0) + 1;\n }\n\n const issues = result.issues.map((issue) => {\n const applyContext = computeApplyContext(issue.violation);\n const suggestedName = issue.violation.suggestedName;\n return {\n ruleId: issue.violation.ruleId,\n detection: \"rule-based\" as const,\n outputChannel: \"score\" as const,\n persistenceIntent: \"transient\" as const,\n purpose: getRulePurpose(issue.violation.ruleId),\n ...(issue.violation.subType && { subType: issue.violation.subType }),\n severity: issue.config.severity,\n nodeId: issue.violation.nodeId,\n nodePath: issue.violation.nodePath,\n message: issue.violation.message,\n applyStrategy: applyContext.applyStrategy,\n ...(applyContext.targetProperty !== undefined\n ? { targetProperty: applyContext.targetProperty }\n : {}),\n ...(applyContext.annotationProperties !== undefined\n ? { annotationProperties: applyContext.annotationProperties }\n : {}),\n ...(suggestedName !== undefined ? { suggestedName } : {}),\n isInstanceChild: applyContext.isInstanceChild,\n ...(applyContext.sourceChildId !== undefined\n ? { sourceChildId: applyContext.sourceChildId }\n : {}),\n ...(issue.acknowledged === true ? { acknowledged: true as const } : {}),\n };\n });\n\n const json: Record<string, unknown> = {\n version: VERSION,\n analyzedAt: result.analyzedAt,\n ...(options?.fileKey && { fileKey: options.fileKey }),\n ...(options?.designKey && { designKey: options.designKey }),\n fileName,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n scope: result.scope,\n issueCount: result.issues.length,\n acknowledgedCount: scores.summary.acknowledgedCount,\n isReadyForCodeGen: isReadyForCodeGen(scores.overall.grade, options?.codegenReadyMinGrade),\n blockingIssueCount: scores.summary.blocking,\n scores: {\n overall: scores.overall,\n categories: scores.byCategory,\n },\n issuesByRule,\n issues,\n summary: formatScoreSummary(scores),\n };\n\n if (result.failedRules.length > 0) {\n json[\"failedRules\"] = result.failedRules;\n }\n\n return json;\n}","import { z } from \"zod\";\nimport type { RuleId } from \"../contracts/rule.js\";\n\n/**\n * Gotcha question template for a single rule.\n * Used to generate user-facing surveys from analysis results (#236).\n *\n * - question: uses {nodeName} placeholder for the affected node\n * - hint: guides the user on what kind of answer is expected\n * - example: concrete example answer\n */\nexport const GotchaQuestionSchema = z.object({\n ruleId: z.string(),\n detection: z.literal(\"rule-based\"),\n outputChannel: z.literal(\"annotation\"),\n persistenceIntent: z.literal(\"durable\"),\n question: z.string(),\n hint: z.string(),\n example: z.string(),\n});\n\nexport type GotchaQuestion = z.infer<typeof GotchaQuestionSchema>;\n\n/**\n * Gotcha question mapping for all 16 rules.\n * Keyed by ruleId for O(1) lookup during survey generation.\n */\ntype GotchaQuestionContent = Omit<\n GotchaQuestion,\n \"detection\" | \"outputChannel\" | \"persistenceIntent\"\n>;\n\nconst GOTCHA_QUESTION_CONTENT: Record<RuleId, GotchaQuestionContent> = {\n // ── Pixel Critical (blocking) ──\n\n \"no-auto-layout\": {\n ruleId: \"no-auto-layout\",\n question: 'Frame \"{nodeName}\" has no Auto Layout. How should this area be laid out?',\n hint: \"Describe the flex direction, gap, and alignment\",\n example: \"Vertical flex, gap 16px, items centered\",\n },\n \"absolute-position-in-auto-layout\": {\n ruleId: \"absolute-position-in-auto-layout\",\n question: '\"{nodeName}\" uses absolute positioning inside an Auto Layout parent. Is this an intentional overlay, or should it flow with the layout?',\n hint: \"Specify if this is a badge/overlay, or should be part of the normal flow\",\n example: \"This is a notification badge — position absolute, top-right corner\",\n },\n \"non-layout-container\": {\n ruleId: \"non-layout-container\",\n question: '\"{nodeName}\" is a Group/Section used as a layout container. What layout structure should it have?',\n hint: \"Describe the intended layout: flex direction, wrap, gap\",\n example: \"Horizontal flex, gap 12px, wrap on mobile\",\n },\n\n // ── Responsive Critical (risk) ──\n\n \"fixed-size-in-auto-layout\": {\n ruleId: \"fixed-size-in-auto-layout\",\n question: '\"{nodeName}\" has a fixed size inside Auto Layout. Should it be responsive?',\n hint: \"Specify which axis should be flexible (width, height, or both)\",\n example: \"Width should FILL the parent, height can stay fixed\",\n },\n \"missing-size-constraint\": {\n ruleId: \"missing-size-constraint\",\n question: '\"{nodeName}\" uses FILL sizing without min/max constraints. What are the size boundaries?',\n hint: \"Provide min-width, max-width, or both\",\n example: \"min-width 320px, max-width 1200px\",\n },\n\n // ── Code Quality (risk) ──\n\n \"missing-component\": {\n ruleId: \"missing-component\",\n question: '\"{nodeName}\" appears to be a repeated structure. Should it be a reusable component?',\n hint: \"Describe if this should be extracted as a component and what props it needs\",\n example: \"Yes, extract as ProductCard component with title, image, and price props\",\n },\n \"detached-instance\": {\n ruleId: \"detached-instance\",\n question: '\"{nodeName}\" looks like a detached component instance. Should it use the original component or is it a new variant?',\n hint: \"Specify whether to restore the component link or create a new variant\",\n example: \"This is a new variant — create a 'compact' variant of the original component\",\n },\n \"variant-structure-mismatch\": {\n ruleId: \"variant-structure-mismatch\",\n question: '\"{nodeName}\" has variants with different child structures. Which structure is the canonical one?',\n hint: \"Describe which variant has the correct structure, or if they should all match\",\n example: \"Default variant is canonical — other variants should toggle child visibility instead of adding/removing elements\",\n },\n \"deep-nesting\": {\n ruleId: \"deep-nesting\",\n question: '\"{nodeName}\" is deeply nested. Can some intermediate layers be flattened or extracted?',\n hint: \"Identify which wrapper layers are unnecessary or should become sub-components\",\n example: \"The inner wrapper is just for spacing — flatten it and use padding instead\",\n },\n\n // ── Token Management ──\n\n \"raw-value\": {\n ruleId: \"raw-value\",\n question: '\"{nodeName}\" uses raw values without design tokens. What tokens should be used?',\n hint: \"Specify the token names or variable references for colors, fonts, spacing, etc.\",\n example: \"Use $color-primary for the fill, $font-body for the text style\",\n },\n \"irregular-spacing\": {\n ruleId: \"irregular-spacing\",\n question: '\"{nodeName}\" has spacing values that are off the design grid. What should the correct spacing be?',\n hint: \"Provide the intended spacing value aligned to the grid system\",\n example: \"Gap should be 16px (4pt grid), not 15px\",\n },\n\n // ── Interaction ──\n\n \"missing-interaction-state\": {\n ruleId: \"missing-interaction-state\",\n question: '\"{nodeName}\" appears interactive but is missing state variants. What interaction states are needed?',\n hint: \"List the needed states: Hover, Active, Disabled, Focus\",\n example: \"Needs Hover (darken 10%) and Disabled (opacity 50%, no pointer events)\",\n },\n \"missing-prototype\": {\n ruleId: \"missing-prototype\",\n question: '\"{nodeName}\" looks interactive but has no prototype interaction. What should happen on click/interaction?',\n hint: \"Describe the interaction behavior: navigation, overlay, state change, etc.\",\n example: \"On click, navigate to the product detail page\",\n },\n\n // ── Semantic ──\n\n \"non-standard-naming\": {\n ruleId: \"non-standard-naming\",\n question: '\"{nodeName}\" uses non-standard state names. What naming convention should be followed?',\n hint: \"Specify the expected state name format (e.g., Hover, Disabled, Active)\",\n example: 'Use \"Hover\" instead of \"hover_v1\", \"Disabled\" instead of \"off\"',\n },\n \"non-semantic-name\": {\n ruleId: \"non-semantic-name\",\n question: '\"{nodeName}\" has a non-semantic name. What is the purpose of this element?',\n hint: \"Provide a descriptive name that reflects the element's role in the UI\",\n example: 'Rename \"Frame 12\" to \"HeroSection\" or \"ProductGrid\"',\n },\n \"inconsistent-naming-convention\": {\n ruleId: \"inconsistent-naming-convention\",\n question: '\"{nodeName}\" uses a different naming convention than its siblings. Which convention should be used?',\n hint: \"Choose one: camelCase, kebab-case, PascalCase, or Title Case\",\n example: \"Use PascalCase for all component layers (e.g., CardTitle, CardBody)\",\n },\n};\n\n/**\n * #402: Keep 1:1 rule-keying for generation, but make the gotcha channel\n * semantics explicit in the registry itself.\n */\nexport const GOTCHA_QUESTIONS: Record<RuleId, GotchaQuestion> = Object.fromEntries(\n Object.entries(GOTCHA_QUESTION_CONTENT).map(([ruleId, content]) => [\n ruleId,\n {\n ...content,\n detection: \"rule-based\",\n outputChannel: \"annotation\",\n persistenceIntent: \"durable\",\n },\n ]),\n) as Record<RuleId, GotchaQuestion>;\n\n/**\n * Get the gotcha question for a specific rule.\n */\nexport function getGotchaQuestion(ruleId: RuleId): GotchaQuestion {\n return GOTCHA_QUESTIONS[ruleId];\n}\n\n/**\n * Format a gotcha question by replacing the {nodeName} placeholder.\n */\nexport function formatGotchaQuestion(ruleId: RuleId, nodeName: string): string {\n return GOTCHA_QUESTIONS[ruleId].question.replace(\"{nodeName}\", nodeName);\n}\n","import type {\n GotchaSurveyQuestion,\n InstanceContext,\n} from \"../contracts/gotcha-survey.js\";\nimport type { RuleId } from \"../contracts/rule.js\";\n\n/**\n * Rules whose answer is uniformly applicable to every member of a batch\n * (e.g. \"What min/max width should these layers share?\"). When N consecutive\n * questions in the same source-component group share one of these `ruleId`s,\n * the SKILL prompts the user **once** with all node names listed instead of\n * asking the same question N times.\n *\n * Maintained as an exported constant so the SKILL.md prose doesn't have to\n * keep a parallel whitelist in sync — vitest covers each rule's batch\n * behavior here, not in the LLM's prose interpretation. Add a rule here only\n * after confirming its `gotcha-question` text is actually phrased to accept a\n * single shared answer (the FILL-sizing question is, the\n * `non-semantic-name` question is not).\n */\nexport const BATCHABLE_RULE_IDS = [\n \"missing-size-constraint\",\n \"irregular-spacing\",\n \"no-auto-layout\",\n \"fixed-size-in-auto-layout\",\n] as const satisfies readonly RuleId[];\n\n/**\n * Rules whose answer is **usually** shareable across same-rule siblings but\n * may legitimately differ per node — so batching is offered as an opt-in\n * default with a per-node override escape hatch (the existing `split` verb).\n *\n * #426: `missing-prototype` on 9 sibling product cards produces 9 near-\n * identical \"Where does this navigate?\" prompts. A single shared answer (e.g.\n * \"navigates to `/product/{id}` detail page\") usually fits all of them — but\n * the user can reply `split` to answer each individually when, e.g., one card\n * opens a modal instead of a route.\n *\n * Unlike `BATCHABLE_RULE_IDS` (safe-mode — one uniform answer by definition),\n * opt-in members are rendered with an \"Apply this answer to all N?\" header\n * so the user knows the shared answer is a suggested default, not a uniform\n * truth. Grow this list one rule at a time with a justifying commit message —\n * same cadence `BATCHABLE_RULE_IDS` follows. Per ADR-016, the whitelist lives\n * here (vitest-covered) and the SKILL.md prose cites it rather than\n * duplicating it.\n */\nexport const OPT_IN_BATCHABLE_RULE_IDS = [\n \"missing-prototype\",\n] as const satisfies readonly RuleId[];\n\nconst BATCHABLE_SET: ReadonlySet<string> = new Set(BATCHABLE_RULE_IDS);\nconst OPT_IN_BATCHABLE_SET: ReadonlySet<string> = new Set(\n OPT_IN_BATCHABLE_RULE_IDS,\n);\n\nconst NO_SOURCE_SENTINEL = \"_no-source\";\n\n/**\n * Tri-state batch rendering mode consumed by `canicode-gotchas` /\n * `canicode-roundtrip` Step 3:\n *\n * - `\"safe\"` — rule is in `BATCHABLE_RULE_IDS`. One answer covers every\n * member by definition (#369).\n * - `\"opt-in\"` — rule is in `OPT_IN_BATCHABLE_RULE_IDS`. One shared answer is\n * offered as a suggested default; the user can reply `split` for per-node\n * override (#426).\n * - `\"none\"` — rule is in neither whitelist. The helper emits the question as\n * its own single-member batch; same-rule repeats stay separate so the SKILL\n * always renders the single-question template.\n */\nexport type BatchMode = \"safe\" | \"opt-in\" | \"none\";\n\nexport interface SurveyQuestionBatch {\n ruleId: string;\n /**\n * Rendering mode for this batch. `\"safe\"` and `\"opt-in\"` both imply\n * `questions.length >= 1` with a shared-prompt template; the difference is\n * whether the shared answer is uniform (`safe`) or a suggested default with\n * a per-node override escape hatch (`opt-in`). `\"none\"` guarantees\n * `questions.length === 1` — same-rule repeats for non-batchable rules do\n * not merge.\n */\n batchMode: BatchMode;\n questions: GotchaSurveyQuestion[];\n /**\n * Sum of `max(question.replicas, 1)` across members. Counts the actual\n * Figma scene fan-out so the SKILL can render `N instances` accurately\n * even when one batch member already collapses multiple replicas via the\n * #356 source-component dedupe.\n */\n totalScenes: number;\n}\n\nexport interface SurveyQuestionGroup {\n /**\n * The shared `instanceContext` for this group, or `null` for the trailing\n * group of non-instance questions. The SKILL emits the \"Instance note\"\n * header **once** per non-null group instead of once per question (#370).\n */\n instanceContext: InstanceContext | null;\n batches: SurveyQuestionBatch[];\n}\n\nexport interface GroupedSurvey {\n groups: SurveyQuestionGroup[];\n}\n\n/**\n * Pre-process a survey's `questions` array into the shape the\n * `canicode-roundtrip` and `canicode-gotchas` SKILLs need to prompt the user\n * with two UX optimizations baked in:\n *\n * - **#370** — source-component grouping. Consecutive questions sharing the\n * same `instanceContext.sourceComponentId` go in one group so the SKILL\n * prints the verbose \"Instance note\" paragraph once per group instead of\n * once per question.\n * - **#369** — batch-prompt for repeated identical answers. Within each\n * group, consecutive questions sharing the same `ruleId` *and* a\n * batchable answer-shape are collapsed into a single batch so the user\n * answers `min-width: 320px, max-width: 1200px` once instead of seven\n * times.\n *\n * Sort key is `(sourceComponentId ?? \"_no-source\", ruleId, nodeName)`. The\n * sentinel keeps non-instance questions contiguous at the end so they form\n * one trailing `instanceContext: null` group.\n *\n * `gotcha-survey` MCP/CLI returns the result on the `groupedQuestions`\n * field; the SKILL.md files iterate over `groups[].batches[]` directly with\n * no sort/partition logic in prose. See ADR-016.\n */\nexport function groupAndBatchSurveyQuestions(\n questions: readonly GotchaSurveyQuestion[],\n): GroupedSurvey {\n if (questions.length === 0) {\n return { groups: [] };\n }\n\n const sorted = [...questions].sort(compareQuestions);\n\n const groups: SurveyQuestionGroup[] = [];\n let currentGroup: SurveyQuestionGroup | null = null;\n let lastGroupKey: string | null = null;\n\n for (const question of sorted) {\n const groupKey = sourceComponentKey(question);\n if (currentGroup === null || groupKey !== lastGroupKey) {\n currentGroup = {\n instanceContext: question.instanceContext ?? null,\n batches: [],\n };\n groups.push(currentGroup);\n lastGroupKey = groupKey;\n }\n pushIntoBatch(currentGroup, question);\n }\n\n return { groups };\n}\n\nfunction compareQuestions(\n a: GotchaSurveyQuestion,\n b: GotchaSurveyQuestion,\n): number {\n const aKey = sourceComponentKey(a);\n const bKey = sourceComponentKey(b);\n if (aKey !== bKey) {\n if (aKey === NO_SOURCE_SENTINEL) return 1;\n if (bKey === NO_SOURCE_SENTINEL) return -1;\n return aKey.localeCompare(bKey);\n }\n if (a.ruleId !== b.ruleId) return a.ruleId.localeCompare(b.ruleId);\n if (a.nodeName !== b.nodeName) return a.nodeName.localeCompare(b.nodeName);\n return a.nodeId.localeCompare(b.nodeId);\n}\n\nfunction sourceComponentKey(question: GotchaSurveyQuestion): string {\n return question.instanceContext?.sourceComponentId ?? NO_SOURCE_SENTINEL;\n}\n\nfunction pushIntoBatch(\n group: SurveyQuestionGroup,\n question: GotchaSurveyQuestion,\n): void {\n const sceneWeight = Math.max(question.replicas ?? 1, 1);\n const batchMode = resolveBatchMode(question.ruleId);\n const last = group.batches.at(-1);\n\n if (\n last !== undefined &&\n last.ruleId === question.ruleId &&\n batchMode !== \"none\" &&\n last.batchMode === batchMode\n ) {\n last.questions.push(question);\n last.totalScenes += sceneWeight;\n return;\n }\n\n group.batches.push({\n ruleId: question.ruleId,\n batchMode,\n questions: [question],\n totalScenes: sceneWeight,\n });\n}\n\nfunction resolveBatchMode(ruleId: string): BatchMode {\n if (BATCHABLE_SET.has(ruleId)) return \"safe\";\n if (OPT_IN_BATCHABLE_SET.has(ruleId)) return \"opt-in\";\n return \"none\";\n}\n","import type { AnalysisResult, AnalysisIssue } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { isReadyForCodeGen } from \"../engine/scoring.js\";\nimport type { Grade } from \"../engine/scoring.js\";\nimport type {\n GotchaSurvey,\n GotchaSurveyQuestion,\n InstanceContext,\n} from \"../contracts/gotcha-survey.js\";\nimport type { AnalysisFile, AnalysisNode } from \"../contracts/figma-node.js\";\nimport type { RuleId } from \"../contracts/rule.js\";\nimport { GOTCHA_QUESTIONS } from \"../rules/gotcha-questions.js\";\nimport { getRulePurpose } from \"../rules/rule-config.js\";\nimport {\n isInstanceChildNodeId,\n parseInstanceChildNodeId,\n} from \"../adapters/instance-id-parser.js\";\nimport { computeApplyContext } from \"./apply-context.js\";\nimport { groupAndBatchSurveyQuestions } from \"./group-and-batch-questions.js\";\n\nconst NODE_PATH_SEPARATOR = \" > \";\n\n/**\n * Generate a gotcha survey from analysis results.\n *\n * Filters to blocking and risk severity issues, deduplicates repeated rules\n * on sibling nodes (same parent + same ruleId), orders blocking first then\n * risk by original traversal order, and maps each issue to a survey question\n * using the GOTCHA_QUESTIONS lookup.\n */\nexport function generateGotchaSurvey(\n result: AnalysisResult,\n scores: ScoreReport,\n options: { designKey?: string; codegenReadyMinGrade?: Grade } = {},\n): GotchaSurvey {\n const grade = scores.overall.grade;\n\n // Step 1: Filter to gotcha-relevant issues.\n // - `blocking` + `risk`: violation rules where the user needs to describe\n // how to resolve the violation (existing behavior).\n // - `missing-info` + purpose `info-collection` (#406): annotation-primary\n // rules like `missing-prototype` / `missing-interaction-state` where the\n // gotcha IS the output. Without this, info-collection rules would never\n // reach the survey because their penalty is intentionally minimal.\n // `suggestion` severity still stays out — it's prose-level advice, not an\n // implementation gap Figma can't encode.\n const relevantIssues = result.issues.filter((issue) => {\n const severity = issue.config.severity;\n if (severity === \"blocking\" || severity === \"risk\") return true;\n if (severity === \"missing-info\") {\n return getRulePurpose(issue.violation.ruleId) === \"info-collection\";\n }\n return false;\n });\n\n // Step 2: Deduplicate — same ruleId on siblings (same parent path) → keep first\n const deduped = deduplicateSiblingIssues(relevantIssues);\n\n // Step 3: Sort — blocking first, then risk; within same severity, preserve traversal order\n const sorted = stableSortBySeverity(deduped);\n\n // Step 4: Map to survey questions\n const mapped = sorted\n .map((issue) => mapToQuestion(issue, result.file))\n .filter((q): q is GotchaSurveyQuestion => q !== null);\n\n // Step 5 (#356): collapse N instance-child questions that share the same\n // `(sourceComponentId, sourceNodeId, ruleId)` tuple into ONE question that\n // names the source component. Apply step iterates the merged\n // `replicaNodeIds` so every replica still gets the answer; this saves the\n // user from answering the same question N times when the answer is single-\n // valued (e.g. 7 FILL children of `Platform=Desktop` all need the same\n // max-width). Cross-source-component dedupe is intentionally not done —\n // different source components stay separate.\n const questions = deduplicateBySourceComponent(mapped);\n\n // Step 6 (#369, #370, #381): pre-compute the grouped+batched view so the\n // SKILLs (`canicode-gotchas`, `canicode-roundtrip`) can iterate over it\n // directly without re-implementing sort / partition / batchable-rule\n // logic in prose. ADR-016.\n const groupedQuestions = groupAndBatchSurveyQuestions(questions);\n\n // Step 7 (#428): compute the threshold hint for the `allowDefinitionWrite`\n // picker. Count questions that target instance children — these are the only\n // candidates that benefit from definition-level writes. When fewer than 3\n // propagation candidates exist, surfacing the picker is over-engineered;\n // the skill silently uses the annotation default (ADR-012).\n const PROPAGATION_CANDIDATE_THRESHOLD = 3;\n const propagationCandidates = questions.filter(\n (q) => q.isInstanceChild,\n ).length;\n const suggestedDefaultApply =\n propagationCandidates >= PROPAGATION_CANDIDATE_THRESHOLD;\n\n return {\n designGrade: grade,\n isReadyForCodeGen: isReadyForCodeGen(grade, options.codegenReadyMinGrade),\n questions,\n groupedQuestions,\n designKey: options.designKey ?? \"\",\n suggestedDefaultApply,\n };\n}\n\n/**\n * Deduplicate issues where the same ruleId fires on multiple children of the\n * same parent. Keeps the first occurrence (preserving traversal order).\n *\n * #373: skip instance-child issues here. They are routed to the\n * source-component dedupe in Step 5, which preserves dropped scene ids on\n * `replicaNodeIds` so the apply step can fan the answer out to every replica.\n * The pre-#373 behaviour collapsed sibling instance children (e.g. `Title` +\n * `Subtitle` on the same `Card` instance — different definition nodes, same\n * `Card` parent path, same ruleId) into a single question and lost the\n * dropped scenes entirely (no `replicaNodeIds`, no annotation, no write).\n * Source-component dedupe naturally keeps different `sourceNodeId`s separate,\n * so the previously-dropped siblings now surface as their own questions.\n */\nfunction deduplicateSiblingIssues(issues: AnalysisIssue[]): AnalysisIssue[] {\n const seen = new Set<string>();\n const result: AnalysisIssue[] = [];\n\n for (const issue of issues) {\n if (isInstanceChildNodeId(issue.violation.nodeId)) {\n result.push(issue);\n continue;\n }\n const parentPath = getParentPath(issue.violation.nodePath);\n const key = `${parentPath}||${issue.violation.ruleId}`;\n\n if (!seen.has(key)) {\n seen.add(key);\n result.push(issue);\n }\n }\n\n return result;\n}\n\n/**\n * Extract the parent path from a full node path.\n * \"Root > Section > Child\" → \"Root > Section\"\n * \"Root\" → \"\" (root node has no parent)\n */\nfunction getParentPath(nodePath: string): string {\n const lastSep = nodePath.lastIndexOf(NODE_PATH_SEPARATOR);\n if (lastSep === -1) return \"\";\n return nodePath.slice(0, lastSep);\n}\n\n/**\n * Extract the node name from a full node path (last segment).\n * \"Root > Section > Child\" → \"Child\"\n */\nfunction getNodeName(nodePath: string): string {\n const lastSep = nodePath.lastIndexOf(NODE_PATH_SEPARATOR);\n if (lastSep === -1) return nodePath;\n return nodePath.slice(lastSep + NODE_PATH_SEPARATOR.length);\n}\n\n/**\n * Stable sort: blocking → risk → missing-info, preserving original array\n * order within each group. `missing-info` is surfaced only for\n * info-collection rules (#406), placed last because their penalty is\n * minimal; fix-describe questions for actual violations take priority.\n */\nfunction stableSortBySeverity(issues: AnalysisIssue[]): AnalysisIssue[] {\n const blocking: AnalysisIssue[] = [];\n const risk: AnalysisIssue[] = [];\n const missingInfo: AnalysisIssue[] = [];\n\n for (const issue of issues) {\n if (issue.config.severity === \"blocking\") {\n blocking.push(issue);\n } else if (issue.config.severity === \"missing-info\") {\n missingInfo.push(issue);\n } else {\n risk.push(issue);\n }\n }\n\n return [...blocking, ...risk, ...missingInfo];\n}\n\n/**\n * Map an AnalysisIssue to a GotchaSurveyQuestion using the GOTCHA_QUESTIONS table.\n * Returns null if no mapping exists for the ruleId.\n */\nfunction mapToQuestion(\n issue: AnalysisIssue,\n file: AnalysisFile,\n): GotchaSurveyQuestion | null {\n const ruleId = issue.violation.ruleId as RuleId;\n const template = GOTCHA_QUESTIONS[ruleId];\n if (!template) return null;\n\n const nodeName = getNodeName(issue.violation.nodePath);\n const instanceContext = buildInstanceContext(issue.violation.nodeId, file);\n const applyContext = computeApplyContext(\n issue.violation,\n instanceContext ?? undefined,\n );\n const suggestedName = issue.violation.suggestedName;\n\n return {\n nodeId: issue.violation.nodeId,\n nodeName,\n ruleId,\n detection: template.detection,\n outputChannel: template.outputChannel,\n persistenceIntent: template.persistenceIntent,\n purpose: getRulePurpose(issue.violation.ruleId),\n severity: issue.config.severity,\n question: template.question.replace(\"{nodeName}\", nodeName),\n hint: template.hint,\n example: template.example,\n ...(instanceContext ? { instanceContext } : {}),\n applyStrategy: applyContext.applyStrategy,\n ...(applyContext.targetProperty !== undefined\n ? { targetProperty: applyContext.targetProperty }\n : {}),\n ...(applyContext.annotationProperties !== undefined\n ? { annotationProperties: applyContext.annotationProperties }\n : {}),\n ...(suggestedName !== undefined ? { suggestedName } : {}),\n isInstanceChild: applyContext.isInstanceChild,\n ...(applyContext.sourceChildId !== undefined\n ? { sourceChildId: applyContext.sourceChildId }\n : {}),\n };\n}\n\n/**\n * Collapse questions that share the same `(sourceComponentId, sourceNodeId,\n * ruleId)` tuple. When N instance-child questions all point at the same\n * definition node inside the same source component for the same rule, the\n * answer is single-valued by definition (FILL children of `Platform=Desktop`\n * all need the same max-width) — so emit ONE question instead of N. The kept\n * question is the FIRST in the input order; subsequent matches are dropped\n * but their `nodeId`s are preserved on `replicaNodeIds` so the apply step can\n * iterate every instance scene node and land the answer on all of them.\n *\n * Out of scope: cross-source-component dedupe (e.g. \"Title\" missing-size-\n * constraint in 5 different components). Different sourceComponentIds always\n * stay separate.\n *\n * Questions without an `instanceContext` (or without both `sourceComponentId`\n * and `sourceNodeId`) are NOT touched — they pass through with no replicas\n * fields. This keeps non-instance-child questions and any partial-context\n * survivors behaving exactly as they did pre-#356.\n */\nfunction deduplicateBySourceComponent(\n questions: GotchaSurveyQuestion[],\n): GotchaSurveyQuestion[] {\n const groups = new Map<string, GotchaSurveyQuestion[]>();\n const order: string[] = [];\n let uniqueCounter = 0;\n\n for (const q of questions) {\n const ic = q.instanceContext;\n let key: string;\n if (ic && ic.sourceComponentId && ic.sourceNodeId) {\n key = `${ic.sourceComponentId}::${ic.sourceNodeId}::${q.ruleId}`;\n } else {\n // Non-deduplicable — assign a unique key so the question passes through\n // unchanged. Using a counter keeps insertion order stable.\n key = `__unique__${uniqueCounter++}`;\n }\n const bucket = groups.get(key);\n if (bucket) {\n bucket.push(q);\n } else {\n groups.set(key, [q]);\n order.push(key);\n }\n }\n\n return order.map((key) => {\n const group = groups.get(key)!;\n const first = group[0]!;\n if (group.length === 1) return first;\n\n const otherIds = group.slice(1).map((q) => q.nodeId);\n const sourceComponentName = first.instanceContext?.sourceComponentName;\n\n // Re-substitute `{nodeName}` with the source component name so the user-\n // facing question reads \"for Platform=Desktop\" instead of \"for Title\"\n // (the first instance's node name). Falls back silently when the source\n // component name was not resolved (rare — happens when the parent\n // instance's componentId is not in `file.components`).\n const template = GOTCHA_QUESTIONS[first.ruleId as RuleId];\n const renamed: GotchaSurveyQuestion = {\n ...first,\n replicas: group.length,\n replicaNodeIds: otherIds,\n };\n if (sourceComponentName) {\n renamed.nodeName = sourceComponentName;\n if (template) {\n renamed.question = template.question.replace(\n \"{nodeName}\",\n sourceComponentName,\n );\n }\n }\n return renamed;\n });\n}\n\n/**\n * Build instance context for a node id when it lives inside an instance.\n * Resolves source component name via the parent instance's componentId when\n * the parent is reachable in the analyzed subtree; falls back to the bare\n * parent/source ids otherwise so the apply pipeline can still resolve the\n * source component at runtime via `figma.getNodeById`.\n */\nfunction buildInstanceContext(\n nodeId: string,\n file: AnalysisFile,\n): InstanceContext | null {\n const parts = parseInstanceChildNodeId(nodeId);\n if (!parts) return null;\n\n const parentInstance = findNodeById(file.document, parts.parentInstanceId);\n const componentId = parentInstance?.componentId;\n const componentName = componentId ? file.components[componentId]?.name : undefined;\n\n return {\n parentInstanceNodeId: parts.parentInstanceId,\n sourceNodeId: parts.sourceNodeId,\n ...(componentId ? { sourceComponentId: componentId } : {}),\n ...(componentName ? { sourceComponentName: componentName } : {}),\n };\n}\n\n/**\n * Walk the document tree for a node id (exact match — no `-`/`:` normalization;\n * instance node ids natively use `:` and the input here is already in that form).\n */\nfunction findNodeById(node: AnalysisNode, id: string): AnalysisNode | null {\n if (node.id === id) return node;\n if (node.children) {\n for (const child of node.children) {\n const found = findNodeById(child, id);\n if (found) return found;\n }\n }\n return null;\n}\n","// Shared UI constants — single source of truth for report-html (Node) and app/shared (browser)\n\nimport type { Category } from \"./contracts/category.js\";\nimport type { Severity } from \"./contracts/severity.js\";\n\n// Re-export category/severity constants that already exist\nexport { CATEGORIES, CATEGORY_LABELS } from \"./contracts/category.js\";\nexport { SEVERITY_LABELS } from \"./contracts/severity.js\";\n\n// Gauge geometry\nexport const GAUGE_R = 54;\nexport const GAUGE_C = Math.round(2 * Math.PI * GAUGE_R); // ~339\n\nexport const CATEGORY_DESCRIPTIONS: Record<Category, string> = {\n \"pixel-critical\":\n \"Auto Layout, absolute positioning, group usage — layout issues that directly affect pixel accuracy\",\n \"responsive-critical\":\n \"Fixed sizing, size constraints, responsive behavior — issues that break at different viewports\",\n \"code-quality\":\n \"Component reuse, detached instances, variant structure, nesting depth\",\n \"token-management\":\n \"Design token binding for colors, fonts, shadows, opacity, spacing grid\",\n \"interaction\":\n \"State variants for interactive components — hover, disabled, active, focus\",\n \"semantic\":\n \"Semantic layer names, naming conventions, default names\",\n};\n\nexport const SEVERITY_ORDER: Severity[] = [\n \"blocking\",\n \"risk\",\n \"missing-info\",\n \"suggestion\",\n];\n","// Shared UI helper functions — single source of truth for report-html (Node) and app/shared (browser)\n// All functions here must be pure (no Node.js or DOM dependencies)\n\nimport type { Severity } from \"./contracts/severity.js\";\nimport { GAUGE_R, GAUGE_C } from \"./ui-constants.js\";\n\n/** Map a percentage score to a color hex string */\nexport function gaugeColor(pct: number): string {\n if (pct >= 75) return \"#22c55e\";\n if (pct >= 50) return \"#f59e0b\";\n return \"#ef4444\";\n}\n\n/** Map a percentage score to a color class name (green/amber/red) */\nexport function scoreClass(pct: number): string {\n if (pct >= 75) return \"green\";\n if (pct >= 50) return \"amber\";\n return \"red\";\n}\n\n/** Escape HTML special characters — works in both Node.js and browser */\nexport function escapeHtml(text: string): string {\n return text\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#039;\");\n}\n\n\n/** Severity to CSS modifier class (used with .rpt-dot, .rpt-issue-score) */\nexport function severityDot(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Severity to CSS modifier class (used with .rpt-issue-score) */\nexport function severityBadge(sev: Severity): string {\n const map: Record<Severity, string> = {\n blocking: \"sev-blocking\",\n risk: \"sev-risk\",\n \"missing-info\": \"sev-missing\",\n suggestion: \"sev-suggestion\",\n };\n return map[sev];\n}\n\n/** Score percentage to CSS modifier class (used with .rpt-badge) */\nexport function scoreBadgeStyle(pct: number): string {\n if (pct >= 75) return \"score-green\";\n if (pct >= 50) return \"score-amber\";\n return \"score-red\";\n}\n\n/** Render a circular gauge SVG string — works in both Node.js and browser */\nexport function renderGaugeSvg(\n pct: number,\n size: number,\n strokeW: number,\n grade?: string\n): string {\n const offset = GAUGE_C * (1 - pct / 100);\n const color = gaugeColor(pct);\n if (grade) {\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"60\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"48\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${escapeHtml(grade)}</text>\n </svg>`;\n }\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 120 120\" class=\"gauge-svg\">\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke-width=\"${strokeW}\" stroke=\"#e4e4e7\" />\n <circle cx=\"60\" cy=\"60\" r=\"${GAUGE_R}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${strokeW}\" stroke-linecap=\"round\" stroke-dasharray=\"${GAUGE_C}\" stroke-dashoffset=\"${offset}\" transform=\"rotate(-90 60 60)\" class=\"gauge-fill\" />\n <text x=\"60\" y=\"62\" text-anchor=\"middle\" dominant-baseline=\"central\" fill=\"currentColor\" font-size=\"28\" font-weight=\"700\" font-family=\"Inter,-apple-system,sans-serif\">${pct}</text>\n </svg>`;\n}\n","/**\n * Pure template functions for report HTML rendering.\n * No Node.js dependencies — usable in browser via CanICode.* globals.\n *\n * Single source of truth for all report UI:\n * - CLI: generateHtmlReport() wraps with <html> shell\n * - Web app: CanICode.renderReportBody() → innerHTML\n * - Figma plugin: CanICode.renderReportBody() → innerHTML\n *\n * Layout: category tabs → rule sections (static info) → node accordion (dynamic info)\n * Styled via self-contained CSS (app/shared/styles.css) — no Tailwind dependency.\n */\n\nimport type { Category } from \"../contracts/category.js\";\nimport type { AnalysisIssue } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { version as VERSION } from \"../../../package.json\";\nimport { buildFigmaDeepLink } from \"../adapters/figma-url-parser.js\";\nimport {\n CATEGORIES,\n CATEGORY_LABELS,\n} from \"../ui-constants.js\";\nimport {\n escapeHtml,\n severityDot,\n severityBadge,\n renderGaugeSvg,\n} from \"../ui-helpers.js\";\n\n// ---- Data interface ----\n\nexport interface ReportData {\n fileName: string;\n fileKey: string;\n scores: ScoreReport;\n issues: AnalysisIssue[];\n nodeCount: number;\n maxDepth: number;\n figmaToken?: string;\n}\n\n/** Issues grouped by rule within a category */\ninterface RuleGroup {\n ruleId: string;\n ruleName: string;\n severity: string;\n severityClass: string;\n why: string;\n impact: string;\n fix: string;\n issues: AnalysisIssue[];\n totalScore: number;\n}\n\n// ---- Main render ----\n\n/**\n * Render the report body content (everything inside <main>).\n * Does NOT include <html>, <head>, <body> — caller wraps as needed.\n */\nexport function renderReportBody(data: ReportData): string {\n const { scores, issues, fileKey, figmaToken } = data;\n const issuesByCategory = groupIssuesByCategory(issues);\n const ruleOpportunities = getTopRules(issues, 5);\n\n return `\n <!-- Overall Score -->\n <section class=\"rpt-overall\">\n ${renderGaugeSvg(scores.overall.percentage, 200, 10, scores.overall.grade)}\n <div class=\"rpt-score\">\n <span class=\"rpt-score-value\">${scores.overall.percentage}</span>\n <span class=\"rpt-score-max\">/ 100</span>\n </div>\n <p class=\"rpt-score-label\">Overall Score</p>\n </section>\n\n <!-- Category Gauges -->\n <section class=\"card rpt-gauges\">\n <div class=\"rpt-gauges-grid\">\n${CATEGORIES.map((cat) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" class=\"rpt-gauge-item\" data-tab=\"${cat}\">\n ${renderGaugeSvg(cs.percentage, 100, 7)}\n <span class=\"rpt-gauge-label\">${CATEGORY_LABELS[cat]}</span>\n <span class=\"rpt-gauge-count\">${cs.issueCount} issues</span>\n </button>`;\n }).join(\"\\n\")}\n </div>\n </section>\n\n <!-- Issue Summary -->\n <section class=\"card rpt-summary\">\n <div class=\"rpt-summary-inner\">\n ${renderSummaryDot(\"sev-blocking\", scores.summary.blocking, \"Blocking\")}\n ${renderSummaryDot(\"sev-risk\", scores.summary.risk, \"Risk\")}\n ${renderSummaryDot(\"sev-missing\", scores.summary.missingInfo, \"Missing Info\")}\n ${renderSummaryDot(\"sev-suggestion\", scores.summary.suggestion, \"Suggestion\")}\n <div class=\"rpt-summary-total\">\n <span class=\"rpt-summary-count\">${scores.summary.totalIssues}</span>\n <span class=\"rpt-summary-label\">Total</span>\n </div>\n </div>\n </section>\n\n${ruleOpportunities.length > 0 ? renderOpportunities(ruleOpportunities) : \"\"}\n\n <!-- Category Tabs -->\n <div class=\"rpt-tabs\">\n <div class=\"rpt-tab-list\" role=\"tablist\">\n${CATEGORIES.map((cat, i) => {\n const cs = scores.byCategory[cat];\n return ` <button type=\"button\" role=\"tab\" class=\"rpt-tab${i === 0 ? \" active\" : \"\"}\" data-tab=\"${cat}\" aria-selected=\"${i === 0}\">${CATEGORY_LABELS[cat]} <span class=\"rpt-tab-count\">${cs.issueCount}</span></button>`;\n }).join(\"\\n\")}\n </div>\n\n${CATEGORIES.map((cat, i) => {\n const catIssues = issuesByCategory.get(cat) ?? [];\n const ruleGroups = groupIssuesByRule(catIssues);\n return ` <div class=\"rpt-tab-panel${i === 0 ? \" active\" : \"\"}\" data-panel=\"${cat}\" role=\"tabpanel\">\n${ruleGroups.length === 0\n ? ' <div class=\"rpt-cat-empty\">No issues found</div>'\n : ruleGroups.map(rg => renderRuleSection(rg, fileKey, figmaToken)).join(\"\\n\")\n}\n </div>`;\n }).join(\"\\n\")}\n </div>\n\n <!-- Footer -->\n <footer class=\"rpt-footer\">\n <p class=\"rpt-footer-main\"><strong>CanICode</strong> <span style=\"opacity:0.5\">v${VERSION}</span></p>\n <p class=\"rpt-footer-meta\">${new Date().toLocaleString()} · ${data.nodeCount} nodes · Max depth ${data.maxDepth}</p>\n <p class=\"rpt-footer-links\"><a href=\"https://github.com/let-sunny/canicode/issues\" target=\"_blank\" rel=\"noopener\">Feedback</a> <span style=\"opacity:0.3\">&middot;</span> <a href=\"https://github.com/let-sunny/canicode/discussions/new?category=share-your-figma\" target=\"_blank\" rel=\"noopener\">Share your Figma</a></p>\n </footer>`;\n}\n\n// ---- Components ----\n\nexport function renderSummaryDot(sevClass: string, count: number, label: string): string {\n return `<div class=\"rpt-summary-item\">\n <span class=\"rpt-dot ${sevClass}\"></span>\n <span class=\"rpt-summary-count\">${count}</span>\n <span class=\"rpt-summary-label\">${label}</span>\n </div>`;\n}\n\nexport function renderOpportunities(ruleGroups: RuleGroup[]): string {\n const maxAbs = ruleGroups.reduce((m, rg) => Math.max(m, Math.abs(rg.totalScore)), 1);\n return `\n <!-- Opportunities -->\n <section class=\"card rpt-opps\">\n <div class=\"rpt-opps-header\">\n <h2 class=\"rpt-opps-title\">\n <span class=\"rpt-dot sev-blocking\"></span>\n Opportunities\n </h2>\n <p class=\"rpt-opps-desc\">Top impact rules — fix these first for the biggest improvement.</p>\n </div>\n <div class=\"rpt-opps-list\">\n${ruleGroups.map(rg => {\n const barW = Math.round((Math.abs(rg.totalScore) / maxAbs) * 100);\n const cat = rg.issues[0]?.rule.definition.category ?? \"\";\n return ` <div class=\"rpt-opps-item\" data-opp-rule=\"${esc(rg.ruleId)}\" data-opp-cat=\"${cat}\" style=\"cursor:pointer\">\n <div class=\"rpt-opps-info\">\n <div class=\"rpt-opps-name\">${esc(rg.ruleName)}</div>\n <div class=\"rpt-opps-msg\">${rg.issues.length} issues</div>\n </div>\n <div class=\"rpt-opps-bar-wrap\">\n <div class=\"rpt-opps-bar\">\n <div class=\"rpt-opps-bar-fill\" style=\"width:${barW}%\"></div>\n </div>\n <span class=\"rpt-opps-score\">${rg.totalScore}</span>\n </div>\n </div>`;\n }).join(\"\\n\")}\n </div>\n </section>`;\n}\n\nexport function renderRuleSection(\n rg: RuleGroup,\n fileKey: string,\n figmaToken?: string\n): string {\n const isOpen = rg.severity === \"blocking\" || rg.severity === \"risk\";\n return ` <details class=\"card rpt-rule\" data-rule=\"${esc(rg.ruleId)}\"${isOpen ? \" open\" : \"\"}>\n <summary class=\"rpt-rule-header\">\n <span class=\"rpt-badge score-red\">${rg.totalScore}</span>\n <span class=\"rpt-rule-title\">\n <span class=\"rpt-rule-name\">${esc(rg.ruleName)}</span>\n <span class=\"rpt-rule-meta\">\n <span class=\"rpt-dot-sm ${rg.severityClass}\"></span>\n ${esc(rg.severity)} · ${rg.issues.length} issues\n </span>\n <span class=\"rpt-rule-info\">\n <span class=\"rpt-rule-info-line\"><strong>Why:</strong> ${esc(rg.why)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Impact:</strong> ${esc(rg.impact)}</span>\n <span class=\"rpt-rule-info-line\"><strong>Fix:</strong> ${esc(rg.fix)}</span>\n </span>\n </span>\n <svg class=\"rpt-rule-chevron no-print\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M19 9l-7 7-7-7\"/></svg>\n </summary>\n <div class=\"rpt-rule-issues\">\n${rg.issues.map(issue => renderIssueRow(issue, fileKey, figmaToken)).join(\"\\n\")}\n </div>\n </details>`;\n}\n\nexport function renderIssueRow(\n issue: AnalysisIssue,\n fileKey: string,\n figmaToken?: string\n): string {\n const sev = issue.config.severity;\n const v = issue.violation;\n const link = buildFigmaDeepLink(fileKey, v.nodeId);\n\n return ` <details class=\"rpt-issue\">\n <summary class=\"rpt-issue-header\">\n <span class=\"rpt-issue-msg\">${esc(v.message)}</span>\n <span class=\"rpt-issue-score ${severityBadge(sev)}\">${issue.calculatedScore}</span>\n </summary>\n <div class=\"rpt-issue-body\">\n <div class=\"rpt-issue-suggestion\">${esc(v.suggestion)}</div>${v.guide ? `\n <div class=\"rpt-issue-guide\">${esc(v.guide)}</div>` : \"\"}\n <div class=\"rpt-issue-path\">${esc(v.nodePath)}</div>\n <div class=\"rpt-issue-actions no-print\">\n <a href=\"${link}\" target=\"_blank\" rel=\"noopener\" data-node-id=\"${esc(v.nodeId)}\" class=\"rpt-btn\">Go to node <span>→</span></a>${figmaToken ? `\n <button onclick=\"postComment(this)\" data-file-key=\"${esc(fileKey)}\" data-node-id=\"${esc(v.nodeId)}\" data-message=\"${esc(v.message)} — ${esc(v.suggestion)}\" class=\"rpt-btn\">Comment on Figma</button>` : \"\"}\n </div>\n </div>\n </details>`;\n}\n\n// ---- Interactions ----\n\n/**\n * Initialize tab switching + navigation for a rendered report.\n * Call after inserting renderReportBody() HTML into a container.\n * Uses 'any' to avoid DOM type dependency (this file targets Node.js).\n */\nexport function initReportInteractions(container: any): void {\n // Remove previous handler if re-initialized (e.g., re-analysis)\n if (container._rptHandler) {\n container.removeEventListener(\"click\", container._rptHandler);\n }\n function activate(cat: string, scrollTo: boolean) {\n container.querySelectorAll(\".rpt-tab\").forEach((t: any) => {\n const active = t.dataset.tab === cat;\n t.classList.toggle(\"active\", active);\n t.setAttribute(\"aria-selected\", String(active));\n });\n container.querySelectorAll(\".rpt-tab-panel\").forEach((p: any) => {\n p.classList.toggle(\"active\", p.dataset.panel === cat);\n });\n if (scrollTo) {\n const tabList = container.querySelector(\".rpt-tab-list\");\n if (tabList) tabList.scrollIntoView({ behavior: \"smooth\", block: \"start\" });\n }\n }\n function focusRule(ruleId: string) {\n const el = container.querySelector('[data-rule=\"' + ruleId + '\"]');\n if (el) {\n el.open = true;\n setTimeout(() => el.scrollIntoView({ behavior: \"smooth\", block: \"start\" }), 50);\n }\n }\n const handler = (e: any) => {\n const tab = e.target.closest(\"[data-tab]\");\n if (tab) {\n const isGauge = tab.classList.contains(\"rpt-gauge-item\");\n activate(tab.dataset.tab ?? \"\", isGauge);\n return;\n }\n const opp = e.target.closest(\"[data-opp-rule]\");\n if (opp) {\n const cat = opp.dataset.oppCat ?? \"\";\n const rule = opp.dataset.oppRule ?? \"\";\n if (cat) activate(cat, false);\n setTimeout(() => focusRule(rule), 50);\n }\n };\n container._rptHandler = handler;\n container.addEventListener(\"click\", handler);\n}\n\n// ---- Utils ----\n\n/** Get top N rules by total score impact */\nfunction getTopRules(issues: AnalysisIssue[], limit: number): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n return [...byRule.values()]\n .sort((a, b) => a.totalScore - b.totalScore)\n .slice(0, limit);\n}\n\nfunction groupIssuesByCategory(issues: AnalysisIssue[]): Map<Category, AnalysisIssue[]> {\n const grouped = new Map<Category, AnalysisIssue[]>();\n for (const category of CATEGORIES) grouped.set(category, []);\n for (const issue of issues) grouped.get(issue.rule.definition.category)!.push(issue);\n return grouped;\n}\n\n/** Group issues by rule within a category, sorted by severity then score */\nfunction groupIssuesByRule(issues: AnalysisIssue[]): RuleGroup[] {\n const byRule = new Map<string, RuleGroup>();\n for (const issue of issues) {\n const id = issue.rule.definition.id;\n let group = byRule.get(id);\n if (!group) {\n const def = issue.rule.definition;\n group = {\n ruleId: id,\n ruleName: def.name,\n severity: issue.config.severity,\n severityClass: severityDot(issue.config.severity),\n why: def.why,\n impact: def.impact,\n fix: def.fix,\n issues: [],\n totalScore: 0,\n };\n byRule.set(id, group);\n }\n group.issues.push(issue);\n group.totalScore += issue.calculatedScore;\n }\n\n const SEVERITY_RANK: Record<string, number> = { blocking: 0, risk: 1, \"missing-info\": 2, suggestion: 3 };\n return [...byRule.values()].sort((a, b) => {\n const sevDiff = (SEVERITY_RANK[a.severity] ?? 4) - (SEVERITY_RANK[b.severity] ?? 4);\n return sevDiff !== 0 ? sevDiff : a.totalScore - b.totalScore;\n });\n}\n\nconst esc = escapeHtml;\n","// Report HTML module — full page generation for CLI\n// Rendering logic lives in render.ts (shared with web/plugin)\n\nimport type { AnalysisFile } from \"../contracts/figma-node.js\";\nimport type { AnalysisResult } from \"../engine/rule-engine.js\";\nimport type { ScoreReport } from \"../engine/scoring.js\";\nimport { escapeHtml } from \"../ui-helpers.js\";\nimport { renderReportBody, initReportInteractions } from \"./render.js\";\nimport type { ReportData } from \"./render.js\";\n\ndeclare const __REPORT_CSS__: string;\nconst reportCss: string = __REPORT_CSS__;\n\nexport type { ReportData } from \"./render.js\";\nexport { renderReportBody, initReportInteractions } from \"./render.js\";\n\nexport interface NodeScreenshot {\n nodeId: string;\n nodePath: string;\n screenshotBase64: string;\n issueCount: number;\n topSeverity: string;\n}\n\nexport interface HtmlReportOptions {\n nodeScreenshots?: NodeScreenshot[];\n figmaToken?: string | undefined;\n}\n\nconst esc = escapeHtml;\n\n/**\n * Generate a complete standalone HTML report page.\n * Used by CLI — opens in browser.\n */\nexport function generateHtmlReport(\n file: AnalysisFile,\n result: AnalysisResult,\n scores: ScoreReport,\n options?: HtmlReportOptions\n): string {\n const figmaToken = options?.figmaToken;\n\n const data: ReportData = {\n fileName: file.name,\n fileKey: file.fileKey,\n scores,\n issues: result.issues,\n nodeCount: result.nodeCount,\n maxDepth: result.maxDepth,\n ...(figmaToken && { figmaToken }),\n };\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>CanICode Report — ${esc(file.name)}</title>\n <link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n <link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n <link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap\" rel=\"stylesheet\">\n <style>\n${reportCss}\n .cli-topbar {\n background: #09090b; color: white;\n border-bottom: 1px solid #27272a;\n }\n .cli-topbar-inner {\n max-width: 960px; margin: 0 auto;\n padding: 12px 24px;\n display: flex; align-items: center; gap: 16px;\n }\n .cli-topbar-logo { font-weight: 600; font-size: 14px; letter-spacing: -0.01em; }\n .cli-topbar-file { color: #a1a1aa; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .cli-topbar-date { margin-left: auto; color: #71717a; font-size: 12px; }\n .cli-main { max-width: 960px; margin: 0 auto; padding: 0 24px 64px; }\n @media print {\n .cli-topbar { position: static !important; background: white !important; color: var(--fg) !important; }\n .cli-topbar-file { color: var(--fg-muted) !important; }\n }\n </style>\n</head>\n<body>\n\n <!-- Top Bar -->\n <header class=\"cli-topbar\">\n <div class=\"cli-topbar-inner\">\n <span class=\"cli-topbar-logo\">CanICode</span>\n <span class=\"cli-topbar-file\">${esc(file.name)}</span>\n <span class=\"cli-topbar-date no-print\">${new Date().toLocaleDateString()}</span>\n </div>\n </header>\n\n <main class=\"cli-main\">\n${renderReportBody(data)}\n </main>\n\n <script>(${String(initReportInteractions)})(document.querySelector('.cli-main'));</script>\n${figmaToken ? renderFigmaCommentScript(figmaToken) : \"\"}\n</body>\n</html>`;\n}\n\nfunction renderFigmaCommentScript(figmaToken: string): string {\n return ` <script>\n const FIGMA_TOKEN = '${figmaToken}';\n async function postComment(btn) {\n const fileKey = btn.dataset.fileKey;\n const nodeId = btn.dataset.nodeId.replace(/-/g, ':');\n const commentNodeId = nodeId.split(';')[0].replace(/^I/, '');\n const message = btn.dataset.message;\n const commentBody = '[CanICode] ' + message;\n btn.disabled = true;\n btn.textContent = 'Sending...';\n btn.title = '';\n try {\n const res = await fetch('https://api.figma.com/v1/files/' + fileKey + '/comments', {\n method: 'POST',\n headers: { 'X-FIGMA-TOKEN': FIGMA_TOKEN, 'Content-Type': 'application/json' },\n body: JSON.stringify({ message: commentBody, client_meta: { node_id: commentNodeId, node_offset: { x: 0, y: 0 } } }),\n });\n if (!res.ok) {\n const errBody = await res.text().catch(() => '');\n const errMsg = res.status === 400 ? 'Bad request' : res.status === 403 ? 'Token lacks file access' : res.status === 404 ? 'File not found' : res.status === 429 ? 'Rate limited' : 'HTTP ' + res.status;\n throw new Error(errMsg + (errBody ? ': ' + errBody.slice(0, 100) : ''));\n }\n btn.textContent = 'Sent';\n btn.classList.remove('rpt-btn-fail');\n btn.classList.add('rpt-btn-ok');\n } catch (e) {\n btn.textContent = 'Failed';\n btn.title = e.message || String(e);\n btn.classList.remove('rpt-btn-ok');\n btn.classList.add('rpt-btn-fail');\n btn.disabled = false;\n }\n }\n </script>`;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { SeveritySchema } from \"../contracts/severity.js\";\nimport type { RuleConfig } from \"../contracts/rule.js\";\nimport { RULE_CONFIGS } from \"./rule-config.js\";\n\nconst VALID_RULE_IDS = new Set(Object.keys(RULE_CONFIGS));\n\nconst RuleOverrideSchema = z.object({\n score: z.number().int().max(0).optional(),\n severity: SeveritySchema.optional(),\n enabled: z.boolean().optional(),\n});\n\nconst ConfigFileSchema = z.object({\n excludeNodeTypes: z.array(z.string()).optional(),\n excludeNodeNames: z.array(z.string()).optional(),\n gridBase: z.number().int().positive().optional(),\n codegenReadyMinGrade: z.enum([\"S\", \"A+\", \"A\", \"B+\", \"B\", \"C+\", \"C\", \"D\", \"F\"]).optional(),\n rules: z.record(z.string(), RuleOverrideSchema)\n .superRefine((rules, ctx) => {\n const unknown = Object.keys(rules).filter((id) => !VALID_RULE_IDS.has(id));\n if (unknown.length > 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Unknown rule ID(s): ${unknown.join(\", \")}. Valid IDs: ${[...VALID_RULE_IDS].join(\", \")}`,\n });\n }\n })\n .optional(),\n});\n\nexport type ConfigFile = z.infer<typeof ConfigFileSchema>;\n\nexport async function loadConfigFile(filePath: string): Promise<ConfigFile> {\n const absPath = resolve(filePath);\n const raw = await readFile(absPath, \"utf-8\");\n const parsed: unknown = JSON.parse(raw);\n return ConfigFileSchema.parse(parsed);\n}\n\n/**\n * Merge config overrides into the base rule configs\n */\nexport function mergeConfigs(\n base: Record<string, RuleConfig>,\n overrides: ConfigFile,\n): Record<string, RuleConfig> {\n const merged = { ...base };\n\n // Apply global gridBase to relevant rules\n if (overrides.gridBase !== undefined) {\n for (const [id, config] of Object.entries(merged)) {\n if (config.options && \"gridBase\" in config.options) {\n merged[id] = {\n ...config,\n options: { ...config.options, gridBase: overrides.gridBase },\n };\n }\n }\n }\n\n // Apply per-rule overrides\n if (overrides.rules) {\n for (const [ruleId, override] of Object.entries(overrides.rules)) {\n const existing = merged[ruleId];\n if (existing) {\n merged[ruleId] = {\n ...existing,\n ...(override.score !== undefined && { score: override.score }),\n ...(override.severity !== undefined && { severity: override.severity }),\n ...(override.enabled !== undefined && { enabled: override.enabled }),\n };\n }\n }\n }\n\n return merged;\n}\n","/**\n * Typed event definitions for PostHog analytics.\n * All events are prefixed with `cic_` (CanICode) to distinguish\n * from noise/spam in PostHog dashboards.\n *\n * Only event metadata is tracked — no design data, tokens, or file contents.\n */\n\n/** Event name prefix — use this to filter genuine events in PostHog */\nexport const EVENT_PREFIX = \"cic_\";\n\nexport const EVENTS = {\n // Analysis\n ANALYSIS_STARTED: `${EVENT_PREFIX}analysis_started`,\n ANALYSIS_COMPLETED: `${EVENT_PREFIX}analysis_completed`,\n ANALYSIS_FAILED: `${EVENT_PREFIX}analysis_failed`,\n\n // Report\n REPORT_GENERATED: `${EVENT_PREFIX}report_generated`,\n COMMENT_POSTED: `${EVENT_PREFIX}comment_posted`,\n COMMENT_FAILED: `${EVENT_PREFIX}comment_failed`,\n\n // MCP\n MCP_TOOL_CALLED: `${EVENT_PREFIX}mcp_tool_called`,\n\n // CLI\n CLI_COMMAND: `${EVENT_PREFIX}cli_command`,\n CLI_INIT: `${EVENT_PREFIX}cli_init`,\n\n // Roundtrip (ADR-012)\n // Wiring point for the roundtrip helper's `telemetry` callback. No Node-side\n // orchestrator reads this yet — the helper ships in a sandbox-pure IIFE that\n // cannot import `core/monitoring` directly, so the event fires through a\n // caller-supplied callback. Define the typed name here so a future consumer\n // has a single place to wire it up.\n ROUNDTRIP_DEFINITION_WRITE_SKIPPED: `${EVENT_PREFIX}roundtrip_definition_write_skipped`,\n /** CLI `canicode roundtrip-tally` completed successfully. */\n ROUNDTRIP_TALLY: `${EVENT_PREFIX}roundtrip_tally`,\n} as const;\n\nexport type EventName = (typeof EVENTS)[keyof typeof EVENTS];\n","/**\n * Unified fetch-based monitoring capture for all environments (CLI, MCP, browser, plugin).\n *\n * No external dependencies — uses native `fetch` (Node 18+ / browser).\n * All operations are fire-and-forget; never throws.\n */\n\nimport type { MonitoringConfig } from \"./types.js\";\n\nlet monitoringEnabled = false;\nlet posthogApiKey: string | undefined;\nlet sentryDsn: string | undefined;\nlet distinctId = \"anonymous\";\nlet environment = \"unknown\";\nlet version = \"unknown\";\nlet commonProps: Record<string, unknown> = {};\n\n/** Generate a simple UUID v4 (no crypto dependency needed for monitoring) */\nfunction uuid4(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/** Parse Sentry DSN into components */\nfunction parseSentryDsn(dsn: string): { key: string; host: string; projectId: string } | null {\n try {\n // DSN format: https://{key}@{host}/{projectId}\n const url = new URL(dsn);\n const key = url.username;\n const projectId = url.pathname.slice(1); // remove leading /\n const host = url.protocol + \"//\" + url.host;\n if (!key || !projectId) return null;\n return { key, host, projectId };\n } catch {\n return null;\n }\n}\n\nexport function initCapture(config: MonitoringConfig): void {\n if (config.enabled === false) return;\n if (!config.posthogApiKey && !config.sentryDsn) return;\n\n monitoringEnabled = true;\n posthogApiKey = config.posthogApiKey;\n sentryDsn = config.sentryDsn;\n distinctId = config.distinctId ?? \"anonymous\";\n environment = config.environment ?? \"unknown\";\n version = config.version ?? \"unknown\";\n commonProps = {\n _sdk: \"canicode\",\n _sdk_version: version,\n _env: environment,\n };\n}\n\nexport function captureEvent(event: string, properties?: Record<string, unknown>): void {\n if (!monitoringEnabled || !posthogApiKey) return;\n\n try {\n fetch(\"https://us.i.posthog.com/i/v0/e/\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n api_key: posthogApiKey,\n event,\n distinct_id: distinctId,\n properties: { ...commonProps, ...properties },\n timestamp: new Date().toISOString(),\n }),\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n}\n\nexport function captureError(error: Error, context?: Record<string, unknown>): void {\n if (!monitoringEnabled) return;\n\n // Send to Sentry via envelope API\n if (sentryDsn) {\n const parsed = parseSentryDsn(sentryDsn);\n if (parsed) {\n try {\n const eventId = uuid4();\n const envelope = [\n JSON.stringify({ event_id: eventId, sent_at: new Date().toISOString(), dsn: sentryDsn }),\n JSON.stringify({ type: \"event\", content_type: \"application/json\" }),\n JSON.stringify({\n event_id: eventId,\n exception: { values: [{ type: error.name, value: error.message }] },\n platform: \"node\",\n environment,\n release: `canicode@${version}`,\n timestamp: Date.now() / 1000,\n extra: context,\n }),\n ].join(\"\\n\");\n\n fetch(`${parsed.host}/api/${parsed.projectId}/envelope/`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-sentry-envelope\",\n \"X-Sentry-Auth\": `Sentry sentry_version=7, sentry_key=${parsed.key}`,\n },\n body: envelope,\n }).catch(() => {});\n } catch {\n // never throw from monitoring\n }\n }\n }\n\n // Also send to PostHog as error event\n captureEvent(\"cic_error\", { error: error.message, ...context });\n}\n\nexport function shutdownCapture(): void {\n monitoringEnabled = false;\n posthogApiKey = undefined;\n sentryDsn = undefined;\n distinctId = \"anonymous\";\n environment = \"unknown\";\n version = \"unknown\";\n commonProps = {};\n}\n","/**\n * Shared monitoring module that works across CLI, MCP, and browser environments.\n *\n * Key design principles:\n * - If no API keys are configured, all functions are silent no-ops\n * - All tracking is fire-and-forget (never blocks or throws)\n * - Zero external dependencies — uses native fetch (Node 18+ / browser)\n * - CLI users can opt out via `canicode config --no-telemetry`\n * - No design data, tokens, or file contents are ever sent\n */\n\nexport type { MonitoringConfig } from \"./types.js\";\nexport { EVENTS } from \"./events.js\";\nexport type { EventName } from \"./events.js\";\n\nimport type { MonitoringConfig } from \"./types.js\";\nimport { initCapture, captureEvent, captureError, shutdownCapture } from \"./capture.js\";\n\n/**\n * Initialise monitoring for the current environment.\n * Safe to call multiple times — subsequent calls are ignored.\n */\nexport function initMonitoring(config: MonitoringConfig): void {\n initCapture(config);\n}\n\n/**\n * Track an analytics event. Fire-and-forget; never throws.\n */\nexport function trackEvent(event: string, properties?: Record<string, unknown>): void {\n try {\n captureEvent(event, properties);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Track an error. Fire-and-forget; never throws.\n */\nexport function trackError(error: Error, context?: Record<string, unknown>): void {\n try {\n captureError(error, context);\n } catch {\n // never throw from monitoring\n }\n}\n\n/**\n * Shut down monitoring. Call before process exit.\n */\nexport function shutdownMonitoring(): void {\n try {\n shutdownCapture();\n } catch {\n // never throw from monitoring\n }\n}\n","/**\n * Monitoring keys injected at build time via tsup `define`.\n * These are replaced with actual values during CI builds.\n * Locally they default to empty strings (monitoring disabled).\n */\n\ndeclare const __POSTHOG_API_KEY__: string;\ndeclare const __SENTRY_DSN__: string;\n\nexport const POSTHOG_API_KEY: string =\n typeof __POSTHOG_API_KEY__ !== \"undefined\" ? __POSTHOG_API_KEY__ : \"\";\nexport const SENTRY_DSN: string =\n typeof __SENTRY_DSN__ !== \"undefined\" ? __SENTRY_DSN__ : \"\";\n","import { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { parseFigmaUrl } from \"../adapters/figma-url-parser.js\";\n\n/**\n * Local copy of `isFigmaUrl` (lives in `core/engine/loader.ts`). Inlined to\n * avoid a contracts/ → engine/ dependency cycle: contracts/ is meant to be\n * importable by every other layer, including engine/.\n */\nfunction isFigmaUrl(input: string): boolean {\n return input.includes(\"figma.com/\");\n}\n\nexport const DesignKeySchema = z.string();\nexport type DesignKey = z.infer<typeof DesignKeySchema>;\n\n/**\n * Compute the canonical `designKey` that uniquely identifies a design across\n * canicode runs.\n *\n * - **Figma URL** → `<fileKey>#<nodeId>` with `-` → `:` normalization on the\n * nodeId (matching the Figma MCP convention). Example:\n * `https://figma.com/design/abc123/My-File?node-id=42-100&t=ref` →\n * `abc123#42:100`. Trailing query parameters other than `node-id`\n * (`?t=...`, `?mode=...`) are dropped — they would otherwise break\n * string-matching on re-runs.\n * - **Figma URL without `node-id`** → just `<fileKey>` (file-level key).\n * - **Anything else** (fixture directory, JSON path, raw filename) →\n * absolute path via `node:path.resolve(input)`. Keeps fixture-based\n * smoke tests stable across cwd.\n *\n * Both `gotcha-survey` and `analyze` MCP/CLI tools surface the result on\n * their response's top-level `designKey` field. The `canicode-gotchas` and\n * `canicode-roundtrip` SKILLs read that field directly — neither one\n * re-implements URL parsing in prose anymore (per ADR-016).\n */\nexport function computeDesignKey(input: string): string {\n if (isFigmaUrl(input)) {\n const { fileKey, nodeId } = parseFigmaUrl(input);\n if (!nodeId) return fileKey;\n return `${fileKey}#${nodeId.replace(/-/g, \":\")}`;\n }\n return resolve(input);\n}\n","/**\n * Centralized node semantic classification.\n * All \"what is this node?\" logic lives here so rules share the same predicates.\n *\n * Categories:\n * - Container: layout containers (frame, group, component, instance)\n * - Visual: decorative/graphic elements (vector, shape, image)\n * - Interactive: user-interactable elements (button, link, tab, input, toggle)\n * - Overlay: elements that open on top (modal, drawer, dropdown)\n * - Carousel: elements that slide/swipe (carousel, slider, gallery)\n * - Token: style/variable binding checks\n * - Naming: name pattern classification\n */\n\nimport type { AnalysisNode } from \"../contracts/figma-node.js\";\n\n// ── Container classification ─────────────────────────────────────────────────\n\nexport function isContainerNode(node: AnalysisNode): boolean {\n return node.type === \"FRAME\" || node.type === \"GROUP\" || node.type === \"COMPONENT\" || node.type === \"INSTANCE\";\n}\n\nexport function hasAutoLayout(node: AnalysisNode): boolean {\n return node.layoutMode !== undefined && node.layoutMode !== \"NONE\";\n}\n\nexport function hasTextContent(node: AnalysisNode): boolean {\n return node.type === \"TEXT\" || (node.children?.some((c) => c.type === \"TEXT\") ?? false);\n}\n\nexport function hasOverlappingBounds(a: AnalysisNode, b: AnalysisNode): boolean {\n const boxA = a.absoluteBoundingBox;\n const boxB = b.absoluteBoundingBox;\n\n if (!boxA || !boxB) return false;\n\n return !(\n boxA.x + boxA.width <= boxB.x ||\n boxB.x + boxB.width <= boxA.x ||\n boxA.y + boxA.height <= boxB.y ||\n boxB.y + boxB.height <= boxA.y\n );\n}\n\n// ── Visual classification ────────────────────────────────────────────────────\n\nconst VISUAL_LEAF_TYPES = new Set([\n \"VECTOR\", \"BOOLEAN_OPERATION\", \"ELLIPSE\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\", \"RECTANGLE\",\n]);\n\nexport function isVisualLeafType(type: string): boolean {\n return VISUAL_LEAF_TYPES.has(type);\n}\n\nexport function hasImageFill(node: AnalysisNode): boolean {\n if (!Array.isArray(node.fills)) return false;\n return node.fills.some(\n (fill) =>\n typeof fill === \"object\" &&\n fill !== null &&\n (fill as { type?: unknown }).type === \"IMAGE\",\n );\n}\n\nexport function isVisualOnlyNode(node: AnalysisNode): boolean {\n if (VISUAL_LEAF_TYPES.has(node.type)) return true;\n const hasOnlyVisualChildren =\n node.children !== undefined &&\n node.children.length > 0 &&\n node.children.every((c) => VISUAL_LEAF_TYPES.has(c.type));\n // Image fill only counts as visual-only when there are no content children\n if (hasImageFill(node) && (!node.children || node.children.length === 0 || hasOnlyVisualChildren)) {\n return true;\n }\n if (hasOnlyVisualChildren) return true;\n return false;\n}\n\n// ── Interactive classification ───────────────────────────────────────────────\n\nexport type StatefulComponentType = \"button\" | \"link\" | \"tab\" | \"input\" | \"toggle\";\n\n/** Name patterns → interactive type mapping */\nexport const STATEFUL_PATTERNS: Array<{ pattern: RegExp; type: StatefulComponentType }> = [\n { pattern: /\\b(btn|button|cta)\\b/i, type: \"button\" },\n { pattern: /\\b(link|anchor)\\b/i, type: \"link\" },\n { pattern: /\\b(tab|tabs)\\b/i, type: \"tab\" },\n { pattern: /\\b(nav|navigation|menu|navbar)\\b/i, type: \"tab\" },\n { pattern: /\\b(input|text-?field|search-?bar|textarea)\\b/i, type: \"input\" },\n { pattern: /\\b(select|dropdown|combo-?box)\\b/i, type: \"input\" },\n { pattern: /\\b(toggle|switch|checkbox|radio)\\b/i, type: \"toggle\" },\n];\n\nexport function getStatefulComponentType(node: AnalysisNode): StatefulComponentType | null {\n if (!node.name) return null;\n for (const entry of STATEFUL_PATTERNS) {\n if (entry.pattern.test(node.name)) return entry.type;\n }\n return null;\n}\n\nexport function isStatefulComponent(node: AnalysisNode): boolean {\n return getStatefulComponentType(node) !== null;\n}\n\n/**\n * Standard state names across web + mobile platforms.\n * Used by missing-interaction-state (to detect presence) and\n * non-standard-naming (to flag non-standard names).\n *\n * Sources:\n * - CSS: :hover, :active, :focus, :disabled, :enabled — https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-classes\n * - Material Design 3: Hovered, Focused, Pressed, Dragged — https://m3.material.io/foundations/interaction/states\n * - UIKit: highlighted, selected, disabled, focused — https://developer.apple.com/documentation/uikit/uicontrol/state\n */\nexport const STANDARD_STATE_NAMES = new Set([\n // CSS pseudo-classes (web)\n \"default\", \"hover\", \"active\", \"focus\", \"focused\", \"disabled\", \"enabled\",\n // Material Design 3 (Android)\n \"pressed\", \"dragged\",\n // UIKit (iOS)\n \"highlighted\",\n // Common\n \"selected\",\n]);\n\n/**\n * Patterns that look like state names but aren't in the standard set.\n * Maps common non-standard names to their standard equivalent for suggestions.\n */\nexport const STATE_NAME_SUGGESTIONS: Record<string, string> = {\n on: \"active\",\n off: \"default\",\n clicked: \"pressed\",\n tapped: \"pressed\",\n inactive: \"disabled\",\n normal: \"default\",\n rest: \"default\",\n hovered: \"hover\",\n activated: \"active\",\n checked: \"selected\",\n unchecked: \"default\",\n};\n\n/** Pattern to detect state-like variant option names (broad match) */\nexport const STATE_LIKE_PATTERN = /\\b(on|off|clicked|tapped|inactive|normal|rest|hovered|activated|checked|unchecked)\\b/i;\n\n// ── Overlay / Carousel patterns ──────────────────────────────────────────────\n\n/** Elements that open on top of current view */\nexport const OVERLAY_PATTERN = /\\b(dropdown|select|combo-?box|popover|accordion|drawer|modal|bottom-?sheet|sheet|sidebar|panel|dialog|popup|toast)\\b/i;\n\n/** Elements that swipe/slide between items */\nexport const CAROUSEL_PATTERN = /\\b(carousel|slider|swiper|slide-?show|gallery)\\b/i;\n\nexport function isOverlayNode(node: AnalysisNode): boolean {\n return node.name !== undefined && OVERLAY_PATTERN.test(node.name);\n}\n\nexport function isCarouselNode(node: AnalysisNode): boolean {\n return node.name !== undefined && CAROUSEL_PATTERN.test(node.name);\n}\n\n// ── Token classification ─────────────────────────────────────────────────────\n\nexport function hasStyleReference(node: AnalysisNode, styleType: string): boolean {\n return node.styles !== undefined && styleType in node.styles;\n}\n\nexport function hasBoundVariable(node: AnalysisNode, key: string): boolean {\n return node.boundVariables !== undefined && key in node.boundVariables;\n}\n\n// ── Naming patterns ──────────────────────────────────────────────────────────\n\n/** Figma default name patterns (Frame 1, Group 2, etc.) */\nexport const DEFAULT_NAME_PATTERNS = [\n /^Frame\\s*\\d*$/i,\n /^Group\\s*\\d*$/i,\n /^Rectangle\\s*\\d*$/i,\n /^Ellipse\\s*\\d*$/i,\n /^Vector\\s*\\d*$/i,\n /^Line\\s*\\d*$/i,\n /^Text\\s*\\d*$/i,\n /^Image\\s*\\d*$/i,\n /^Component\\s*\\d*$/i,\n /^Instance\\s*\\d*$/i,\n];\n\nexport function isDefaultName(name: string): boolean {\n return DEFAULT_NAME_PATTERNS.some((pattern) => pattern.test(name));\n}\n\n/** Shape-only non-semantic names */\nexport const NON_SEMANTIC_NAMES = [\n \"rectangle\", \"ellipse\", \"vector\", \"line\", \"polygon\",\n \"star\", \"path\", \"shape\", \"image\", \"fill\", \"stroke\",\n];\n\nexport function isNonSemanticName(name: string): boolean {\n return NON_SEMANTIC_NAMES.includes(name.toLowerCase().trim());\n}\n\n// ── Exclusion ────────────────────────────────────────────────────────────────\n\nexport const EXCLUDED_NAME_PATTERN = /(badge|close|dismiss|overlay|float|fab|dot|indicator|corner|decoration|tag|status|notification|icon|ico|image|asset|filter|dim|dimmed|bg|background|logo|avatar|divider|separator|nav|navigation|gnb|header|footer|sidebar|toolbar|modal|dialog|popup|toast|tooltip|dropdown|menu|sticky|spinner|loader|cursor|cta|chatbot|thumb|thumbnail|tabbar|tab-bar|statusbar|status-bar)/i;\n\nexport function isExcludedName(name: string): boolean {\n return EXCLUDED_NAME_PATTERN.test(name);\n}\n","import type { AnalysisNode } from \"../contracts/figma-node.js\";\nimport { isVisualLeafType, isVisualOnlyNode, isExcludedName } from \"./node-semantics.js\";\n\n// ============================================\n// Auto-layout exceptions\n// ============================================\n\n/** Frames that don't need auto-layout (only visual-leaf children like icon paths) */\nexport function isAutoLayoutExempt(node: AnalysisNode): boolean {\n if (\n node.children &&\n node.children.length > 0 &&\n node.children.every((c) => isVisualLeafType(c.type))\n ) return true;\n\n return false;\n}\n\n// ============================================\n// Absolute-position exceptions\n// ============================================\n\n/** Nodes that are allowed to use absolute positioning inside auto-layout */\nexport function isAbsolutePositionExempt(node: AnalysisNode): boolean {\n if (isVisualOnlyNode(node)) return true;\n\n // Intentional name patterns (badge, close, overlay, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n\n// ============================================\n// Size-constraint exceptions\n// ============================================\n//\n// `isSizeConstraintExempt` was removed in #403 (commit\n// `feat(rules): missing-size-constraint scope-aware…`). The new rule\n// walks the full ancestor chain to determine whether any container\n// already establishes a width bound, which strictly subsumes the old\n// \"parent has maxWidth OR depth <= 1\" heuristic. Keeping the helper\n// would produce two divergent definitions of \"bound\" in the codebase.\n\n// ============================================\n// Fixed-size exceptions\n// ============================================\n\n/** Nodes that are allowed to use fixed sizing inside auto-layout */\nexport function isFixedSizeExempt(node: AnalysisNode): boolean {\n // Visual-only nodes (icons, images, shapes) — intentionally fixed\n if (isVisualOnlyNode(node)) return true;\n\n // Excluded names (nav, header, etc.)\n if (isExcludedName(node.name)) return true;\n\n return false;\n}\n","/**\n * Centralized rule violation messages.\n * All message text lives here so CLI, web, plugin, and MCP share the same strings.\n *\n * Each message function returns { message, suggestion, guide? }:\n * - message: what's wrong (node-specific, dynamic)\n * - suggestion: how to fix it (node-specific, dynamic)\n * - guide: exemption hint (optional, when the rule auto-excludes certain cases)\n */\n\n// ── Message return type ─────────────────────────────────────────────────────\n\nexport interface ViolationMsg {\n message: string;\n suggestion: string;\n guide?: string;\n}\n\n// ── Sub-type definitions ─────────────────────────────────────────────────────\n\nexport type RawValueSubType = \"color\" | \"font\" | \"shadow\" | \"opacity\" | \"spacing\";\nexport type NoAutoLayoutSubType = \"overlapping\" | \"nested\" | \"basic\";\nexport type FixedSizeSubType = \"both-axes\" | \"horizontal\";\nexport type MissingComponentSubType = \"unused-component\" | \"name-repetition\" | \"structure-repetition\" | \"style-override\";\n\n// ── raw-value ────────────────────────────────────────────────────────────────\n\nexport const rawValueMsg = {\n color: (name: string, hex: string): ViolationMsg => ({\n message: `\"${name}\" uses raw fill color ${hex} without style or variable`,\n suggestion: `Bind to a color token`,\n }),\n font: (name: string, fontDesc: string): ViolationMsg => ({\n message: `\"${name}\" uses raw font${fontDesc} without text style`,\n suggestion: `Apply a text style`,\n }),\n shadow: (name: string, shadowType: string, details: string): ViolationMsg => ({\n message: `\"${name}\" has ${shadowType}${details} without effect style`,\n suggestion: `Apply an effect style`,\n }),\n opacity: (name: string, pct: number): ViolationMsg => ({\n message: `\"${name}\" uses raw opacity (${pct}%) without a variable binding`,\n suggestion: `Bind opacity to a variable`,\n }),\n spacing: (name: string, label: string, value: number): ViolationMsg => ({\n message: `\"${name}\" uses raw ${label} (${value}px) without a variable binding`,\n suggestion: `Bind spacing to a variable`,\n }),\n};\n\n// ── irregular-spacing ────────────────────────────────────────────────────────\n\nexport type IrregularSpacingSubType = \"padding\" | \"gap\";\n\nexport const irregularSpacingMsg = (name: string, spacing: number, gridBase: number, nearest: number): ViolationMsg => ({\n message: `\"${name}\" has spacing ${spacing}px not on ${gridBase}pt grid`,\n suggestion: `Round to nearest ${gridBase}pt multiple (${nearest}px)`,\n});\n\n// ── no-auto-layout ───────────────────────────────────────────────────────────\n\nexport const noAutoLayoutMsg = {\n overlapping: (name: string): ViolationMsg => ({\n message: `\"${name}\" has overlapping children without Auto Layout`,\n suggestion: `Apply auto-layout to separate overlapping children`,\n guide: `If this is an intentional overlay (e.g., badge on avatar), this can be ignored`,\n }),\n nested: (name: string): ViolationMsg => ({\n message: `\"${name}\" has nested containers without layout hints`,\n suggestion: `Apply auto-layout to organize nested containers`,\n guide: `Icon wrappers containing only vectors are automatically excluded`,\n }),\n basic: (name: string, arrangement: string, directionHint: string): ViolationMsg => ({\n message: `Frame \"${name}\" has no auto-layout${arrangement}`,\n suggestion: directionHint ? `Apply ${directionHint} auto-layout` : `Apply auto-layout`,\n guide: `Single-child wrappers and icon containers are automatically excluded`,\n }),\n};\n\n// ── absolute-position-in-auto-layout ─────────────────────────────────────────\n\nexport const absolutePositionMsg = (name: string, parentName: string): ViolationMsg => ({\n message: `\"${name}\" uses absolute positioning inside Auto Layout parent \"${parentName}\"`,\n suggestion: `Remove absolute positioning or restructure outside the auto-layout parent`,\n guide: `If this is a badge or overlay, name it with \"badge\", \"overlay\", or \"icon\" to auto-exclude`,\n});\n\n// ── fixed-size-in-auto-layout ────────────────────────────────────────────────\n\nexport const fixedSizeMsg = {\n bothAxes: (name: string, width: number, height: number): ViolationMsg => ({\n message: `Container \"${name}\" (${width}×${height}) uses fixed size on both axes inside auto-layout`,\n suggestion: `Set at least one axis to HUG or FILL`,\n }),\n horizontal: (name: string, width: number): ViolationMsg => ({\n message: `\"${name}\" has fixed width (${width}px) inside auto-layout`,\n suggestion: `Set horizontal sizing to FILL`,\n }),\n};\n\n// ── missing-size-constraint ──────────────────────────────────────────────────\n//\n// #403: Subtypes are case-of-firing rather than property-of-fix. Each\n// subtype's gotcha question is a pure function of the subtype — the\n// message function does not need to read `rootNodeType` or `scope`\n// again. This keeps gotcha rendering simple at the cost of a slightly\n// longer subtype list (4 instead of 1).\n\nexport type MissingSizeConstraintSubType =\n | \"page-container-unbound\"\n | \"page-instance-fixed\"\n | \"component-fixed-by-design\"\n | \"component-fixed-by-override\";\n\nexport const missingSizeConstraintMsg = {\n pageContainerUnbound: (name: string, currentWidth: string): ViolationMsg => ({\n message: `Container \"${name}\" uses FILL width (currently ${currentWidth}) and no ancestor defines a width bound`,\n suggestion: `Decide whether this area should stretch with the screen, or set min/max-width here so the responsive behavior is explicit`,\n }),\n pageInstanceFixed: (name: string, currentWidth: string): ViolationMsg => ({\n message: `Instance \"${name}\" has fixed width (${currentWidth}) inside an Auto Layout parent`,\n suggestion: `Confirm whether this fixed width is intentional — if not, set the instance to FILL so it follows the parent's layout`,\n }),\n componentFixedByDesign: (name: string, currentWidth: string): ViolationMsg => ({\n message: `Component \"${name}\" has fixed width (${currentWidth}) at its root`,\n suggestion: `Confirm whether this component is intentionally non-responsive — otherwise switch root sizing to FILL or set min/max bounds`,\n }),\n componentFixedByOverride: (name: string, currentWidth: string): ViolationMsg => ({\n message: `Instance \"${name}\" overrides root width to fixed (${currentWidth}); the original component may be FILL`,\n suggestion: `Confirm whether the fixed-width override is intentional — if not, restore root sizing to inherit from the component definition`,\n }),\n};\n\n// ── non-layout-container (was group-usage) ───────────────────────────────────\n\nexport type NonLayoutContainerSubType = \"group\" | \"section\";\n\nexport const nonLayoutContainerMsg = {\n group: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Group`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n section: (name: string): ViolationMsg => ({\n message: `\"${name}\" is a Section used as layout container`,\n suggestion: `Convert to Frame and apply auto-layout`,\n }),\n};\n\n// ── deep-nesting ─────────────────────────────────────────────────────────────\n\nexport const deepNestingMsg = (name: string, depth: number, maxDepth: number): ViolationMsg => ({\n message: `\"${name}\" is nested ${depth} levels deep within its component (max: ${maxDepth})`,\n suggestion: `Extract into a sub-component to reduce depth`,\n});\n\n// ── missing-component ────────────────────────────────────────────────────────\n\nexport const missingComponentMsg = {\n unusedComponent: (componentName: string, count: number): ViolationMsg => ({\n message: `Component \"${componentName}\" exists but ${count} repeated frames found instead of instances`,\n suggestion: `Replace frames with component instances`,\n }),\n nameRepetition: (name: string, count: number): ViolationMsg => ({\n message: `\"${name}\" appears ${count} times`,\n suggestion: `Extract as a reusable component`,\n }),\n structureRepetition: (name: string, siblingCount: number): ViolationMsg => ({\n message: `\"${name}\" and ${siblingCount} sibling frame(s) share the same internal structure`,\n suggestion: `Extract a shared component from the repeated structure`,\n }),\n styleOverride: (componentName: string, overrides: string[]): ViolationMsg => ({\n message: `\"${componentName}\" instance has style overrides (${overrides.join(\", \")})`,\n suggestion: `Create a new variant for this style combination`,\n }),\n};\n\n// ── detached-instance ────────────────────────────────────────────────────────\n\nexport const detachedInstanceMsg = (name: string, componentName: string): ViolationMsg => ({\n message: `\"${name}\" may be a detached instance of component \"${componentName}\"`,\n suggestion: `Restore as an instance of \"${componentName}\" or create a new variant`,\n});\n\n// ── variant-structure-mismatch ───────────────────────────────────────────────\n\nexport const variantStructureMismatchMsg = (name: string, mismatchCount: number, totalVariants: number): ViolationMsg => ({\n message: `\"${name}\" has ${mismatchCount}/${totalVariants} variants with different child structures`,\n suggestion: `Unify variant structures using visibility toggles for optional elements`,\n});\n\n// ── non-standard-naming ──────────────────────────────────────────────────────\n\nexport type NonStandardNamingSubType = \"state-name\";\n\nexport const nonStandardNamingMsg = {\n stateName: (name: string, nonStandard: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" has non-standard state name \"${nonStandard}\"`,\n suggestion: `Use \"${suggested}\" for dev-friendly naming`,\n }),\n};\n\n// ── non-semantic-name (merged: default-name + non-semantic-name) ─────────────\n\nexport type NonSemanticNameSubType = \"frame\" | \"group\" | \"vector\" | \"shape\" | \"text\" | \"image\" | \"component\" | \"instance\" | \"shape-name\";\n\nconst DEFAULT_NAME_SUBTYPE_MAP: Record<string, NonSemanticNameSubType> = {\n FRAME: \"frame\",\n GROUP: \"group\",\n RECTANGLE: \"shape\",\n ELLIPSE: \"shape\",\n VECTOR: \"vector\",\n LINE: \"vector\",\n STAR: \"shape\",\n REGULAR_POLYGON: \"shape\",\n TEXT: \"text\",\n IMAGE: \"image\",\n COMPONENT: \"component\",\n COMPONENT_SET: \"component\",\n INSTANCE: \"instance\",\n};\n\nexport function getDefaultNameSubType(nodeType: string): NonSemanticNameSubType {\n return DEFAULT_NAME_SUBTYPE_MAP[nodeType] ?? \"frame\";\n}\n\nconst NON_SEMANTIC_EXAMPLES: Record<string, string> = {\n FRAME: '\"Header\", \"ProductCard\", \"Sidebar\"',\n GROUP: '\"NavItems\", \"ButtonGroup\", \"CardContent\"',\n VECTOR: '\"ArrowIcon\", \"CheckMark\", \"LogoSymbol\"',\n LINE: '\"Divider\", \"Separator\", \"Underline\"',\n RECTANGLE: '\"Background\", \"Divider\", \"Overlay\"',\n ELLIPSE: '\"AvatarShape\", \"StatusDot\", \"Badge\"',\n STAR: '\"RatingIcon\", \"FavoriteIcon\", \"StarBadge\"',\n REGULAR_POLYGON: '\"PlayIcon\", \"WarningIcon\", \"ShapeDecor\"',\n TEXT: '\"PageTitle\", \"Description\", \"Price\"',\n IMAGE: '\"Avatar\", \"ProductPhoto\", \"Banner\"',\n COMPONENT: '\"PrimaryButton\", \"InputField\", \"CardTemplate\"',\n COMPONENT_SET: '\"Button\", \"Input\", \"Card\"',\n INSTANCE: '\"CloseButton\", \"UserAvatar\", \"StarIcon\"',\n};\n\nexport const nonSemanticNameMsg = (type: string, name: string): ViolationMsg => {\n const examples = NON_SEMANTIC_EXAMPLES[type] ?? '\"Header\", \"ProductCard\", \"Icon\"';\n return {\n message: `${type} \"${name}\" is a non-semantic name`,\n suggestion: `Rename to describe its role (e.g., ${examples})`,\n };\n};\n\n// ── missing-interaction-state ─────────────────────────────────────────────────\n\nexport type MissingInteractionStateSubType = \"hover\" | \"disabled\" | \"active\" | \"focus\";\n\nexport const missingInteractionStateMsg = {\n hover: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Hover state variant`,\n suggestion: `Add a State=Hover variant`,\n }),\n disabled: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Disabled state variant`,\n suggestion: `Add a State=Disabled variant`,\n }),\n active: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Active state variant`,\n suggestion: `Add a State=Active variant`,\n }),\n focus: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks interactive but has no Focus state variant`,\n suggestion: `Add a State=Focus variant`,\n }),\n};\n\n// ── missing-prototype ─────────────────────────────────────────────────────────\n\nexport type MissingPrototypeSubType = \"button\" | \"navigation\" | \"tab\" | \"overlay\" | \"carousel\" | \"input\" | \"toggle\";\n\nexport const missingPrototypeMsg = {\n button: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a button but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the click behavior`,\n }),\n navigation: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a navigation link but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define the destination`,\n }),\n tab: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a tab but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define tab switching behavior`,\n }),\n overlay: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an overlay trigger but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define open/close behavior`,\n }),\n carousel: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a carousel but has no interaction prototype`,\n suggestion: `Add an ON_CLICK or ON_DRAG interaction to define slide navigation`,\n }),\n input: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like an input but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define focus/interaction behavior`,\n }),\n toggle: (name: string): ViolationMsg => ({\n message: `\"${name}\" looks like a toggle but has no click prototype`,\n suggestion: `Add an ON_CLICK interaction to define on/off behavior`,\n }),\n};\n\n// ── inconsistent-naming-convention ───────────────────────────────────────────\n\nexport const inconsistentNamingMsg = (name: string, nodeConvention: string, dominantConvention: string, suggested: string): ViolationMsg => ({\n message: `\"${name}\" uses ${nodeConvention} while siblings use ${dominantConvention}`,\n suggestion: `Rename to \"${suggested}\"`,\n guide: `This checks sibling layers at the same level — you don't have to follow the exact suggestion, just keep naming consistent across siblings`,\n});\n","import type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport type { RuleCheckFn, RuleContext, RuleDefinition, RuleViolation } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { isAutoLayoutExempt, isAbsolutePositionExempt, isFixedSizeExempt } from \"../rule-exceptions.js\";\nimport { noAutoLayoutMsg, absolutePositionMsg, fixedSizeMsg, missingSizeConstraintMsg, nonLayoutContainerMsg, deepNestingMsg } from \"../rule-messages.js\";\nimport { isContainerNode, hasAutoLayout, hasOverlappingBounds } from \"../node-semantics.js\";\n\n// ============================================\n// no-auto-layout (merged: absorbs ambiguous-structure + missing-layout-hint)\n// ============================================\n\nconst noAutoLayoutDef: RuleDefinition = {\n id: \"no-auto-layout\",\n name: \"No Auto Layout\",\n category: \"pixel-critical\",\n why: \"Without Auto Layout, AI must guess positioning from absolute coordinates instead of reading explicit layout rules\",\n impact: \"Generated code uses hardcoded positions that break on any content or screen size change\",\n fix: \"Apply Auto Layout to create clear, explicit structure — enables AI to generate flexbox/grid instead of absolute positioning\",\n};\n\nconst noAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!isContainerNode(node)) return null;\n if (hasAutoLayout(node)) return null;\n if (!node.children || node.children.length === 0) return null;\n\n if (isAutoLayoutExempt(node)) return null;\n\n // Priority 1: Check for overlapping visible children (ambiguous-structure)\n if (node.children.length >= 2) {\n for (let i = 0; i < node.children.length; i++) {\n for (let j = i + 1; j < node.children.length; j++) {\n const childA = node.children[i];\n const childB = node.children[j];\n if (!childA || !childB) continue;\n\n if (hasOverlappingBounds(childA, childB)) {\n if (childA.visible !== false && childB.visible !== false) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"overlapping\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.overlapping(node.name),\n };\n }\n }\n }\n }\n }\n\n // Priority 2: Check for nested containers without layout hints (missing-layout-hint)\n if (node.children.length >= 2) {\n const nestedContainers = node.children.filter((c) => isContainerNode(c));\n if (nestedContainers.length >= 2) {\n const withoutLayout = nestedContainers.filter((c) => !hasAutoLayout(c));\n if (withoutLayout.length >= 2) {\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"nested\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.nested(node.name),\n };\n }\n }\n }\n\n // Priority 3: Basic no-auto-layout check (FRAME only)\n if (node.type !== \"FRAME\") return null;\n\n const childCount = node.children?.length ?? 0;\n let directionHint = \"\";\n if (node.children && node.children.length >= 2) {\n const boxes = node.children.filter(c => c.absoluteBoundingBox).map(c => c.absoluteBoundingBox!);\n if (boxes.length >= 2) {\n const yRange = Math.max(...boxes.map(b => b.y)) - Math.min(...boxes.map(b => b.y));\n const xRange = Math.max(...boxes.map(b => b.x)) - Math.min(...boxes.map(b => b.x));\n directionHint = yRange > xRange ? \"VERTICAL\" : \"HORIZONTAL\";\n }\n }\n\n const arrangement = directionHint\n ? ` (${childCount} children arranged ${directionHint.toLowerCase()}ly)`\n : childCount > 0 ? ` (${childCount} children)` : \"\";\n\n return {\n ruleId: noAutoLayoutDef.id,\n subType: \"basic\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...noAutoLayoutMsg.basic(node.name, arrangement, directionHint),\n };\n};\n\nexport const noAutoLayout = defineRule({\n definition: noAutoLayoutDef,\n check: noAutoLayoutCheck,\n});\n\n// ============================================\n// absolute-position-in-auto-layout\n// ============================================\n\nconst absolutePositionInAutoLayoutDef: RuleDefinition = {\n id: \"absolute-position-in-auto-layout\",\n name: \"Absolute Position in Auto Layout\",\n category: \"pixel-critical\",\n why: \"Absolute positioning inside Auto Layout contradicts the parent's layout rules — AI sees conflicting instructions\",\n impact: \"AI must decide whether to follow the parent's flexbox or the child's absolute position — often gets it wrong\",\n fix: \"Remove absolute positioning or use proper Auto Layout alignment\",\n};\n\nconst absolutePositionInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (node.layoutPositioning !== \"ABSOLUTE\") return null;\n\n if (isAbsolutePositionExempt(node)) return null;\n\n return {\n ruleId: absolutePositionInAutoLayoutDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...absolutePositionMsg(node.name, context.parent.name),\n };\n};\n\nexport const absolutePositionInAutoLayout = defineRule({\n definition: absolutePositionInAutoLayoutDef,\n check: absolutePositionInAutoLayoutCheck,\n});\n\n// ============================================\n// fixed-size-in-auto-layout (merged: absorbs fixed-width-in-responsive-context)\n// ============================================\n\nconst fixedSizeInAutoLayoutDef: RuleDefinition = {\n id: \"fixed-size-in-auto-layout\",\n name: \"Fixed Size in Auto Layout\",\n category: \"responsive-critical\",\n why: \"Fixed sizing inside Auto Layout contradicts the flexible layout intent\",\n impact: \"AI generates a rigid element inside a flex container — the layout won't respond to content changes\",\n fix: \"Use 'Hug' or 'Fill' for at least one axis. Both-axes FIXED → layout completely rigid; horizontal-only FIXED → width won't adapt to parent resize\",\n};\n\nconst fixedSizeInAutoLayoutCheck: RuleCheckFn = (node, context) => {\n if (!context.parent) return null;\n if (!hasAutoLayout(context.parent)) return null;\n if (!isContainerNode(node)) return null;\n if (!node.absoluteBoundingBox) return null;\n\n if (isFixedSizeExempt(node)) return null;\n\n const { width, height } = node.absoluteBoundingBox;\n\n // Check both axes FIXED (stronger case)\n const hFixed =\n node.layoutSizingHorizontal === \"FIXED\" || node.layoutSizingHorizontal === undefined;\n const vFixed =\n node.layoutSizingVertical === \"FIXED\" || node.layoutSizingVertical === undefined;\n\n if (hFixed && vFixed) {\n // Skip if it has its own auto-layout\n if (node.layoutMode && node.layoutMode !== \"NONE\") return null;\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"both-axes\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.bothAxes(node.name, width, height),\n };\n }\n\n // Check horizontal-only FIXED (lighter case, from fixed-width-in-responsive-context)\n if (hFixed && !vFixed) {\n // Use layoutSizingHorizontal if available (accurate)\n if (node.layoutSizingHorizontal) {\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n } else {\n // Fallback: STRETCH means fill, skip\n if (node.layoutAlign === \"STRETCH\") return null;\n if (node.layoutAlign !== \"INHERIT\") return null;\n }\n\n return {\n ruleId: fixedSizeInAutoLayoutDef.id,\n subType: \"horizontal\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...fixedSizeMsg.horizontal(node.name, width),\n };\n }\n\n return null;\n};\n\nexport const fixedSizeInAutoLayout = defineRule({\n definition: fixedSizeInAutoLayoutDef,\n check: fixedSizeInAutoLayoutCheck,\n});\n\n// ============================================\n// missing-size-constraint (#403 redesign — scope-aware, info-collection)\n// ============================================\n//\n// Pre-#403 this rule fired on every FILL container with no max-width\n// regardless of whether an ancestor already established a bound, and\n// scored -8/risk. The redesign narrows it to genuinely ambiguous sizing\n// situations and reframes the output as a gotcha rather than a\n// violation (per ADR-017 channel separation):\n//\n// page scope:\n// - container FRAME/SECTION with FILL width AND no chain-bound\n// ancestor (chain-bound = FIXED width OR FILL/HUG with explicit\n// min/max). Fires `page-container-unbound` — designer intent\n// (stretch with screen vs. cap at content) is structurally\n// undecidable.\n// - INSTANCE with FIXED width inside an Auto Layout parent. Fires\n// `page-instance-fixed` — could be intentional override or a stale\n// size carried over from the component definition.\n//\n// component scope:\n// - the analysis root (and only the root — internal nodes pass)\n// with FIXED width. Fires `component-fixed-by-design` for\n// COMPONENT/COMPONENT_SET roots, `component-fixed-by-override`\n// for INSTANCE roots — same shape, different gotcha framing.\n//\n// Deliberately scoped out (see PR body):\n// - INSTANCE FIXED outside Auto Layout — `no-auto-layout` already\n// owns the score channel on the non-auto-layout parent. Firing\n// here too would double-penalize one structural concern.\n// - Nodes inside an INSTANCE — Plugin API silently ignores min/max\n// overrides on instance internal nodes, so the gotcha would be\n// un-actionable.\n// - Height axis — width is the dominant responsive concern; height\n// redesign deferred to a follow-up issue.\n\nconst missingSizeConstraintDef: RuleDefinition = {\n id: \"missing-size-constraint\",\n name: \"Missing Size Constraint\",\n category: \"responsive-critical\",\n why: \"Width sizing without explicit bounds (FIXED root or FILL chained to a bounded ancestor) is structurally indistinguishable from missing information — AI cannot tell whether the designer intended responsive stretching, a fixed cap, or simply forgot to set min/max\",\n impact: \"Generated code either guesses hard-coded widths or omits responsive constraints; either way the runtime layout drifts from the design intent at viewports the designer never explicitly considered\",\n fix: \"Answer the gotcha to declare intent (responsive vs. fixed-by-design vs. instance override), then encode the answer in Figma sizing — FILL/HUG with min/max for responsive bounds, FIXED only when intentionally non-responsive\",\n};\n\n// ── Chain-bound walker (memoized via analysisState) ──────────────────────\n//\n// \"Chain-bound\" = some ancestor in the analysis tree (root included)\n// resolves the width chain by either fixing the width or capping a\n// FILL with min/max. Computed lazily as the rule visits each node:\n// because traverseAndCheck runs the check fn parent-first, by the time\n// a child asks `parentChainBound(child)` the parent's entry is already\n// in the cache. The side-effect MUST run for every visited node — see\n// `recordChainBound` call placement below.\n\ntype ChainBoundCache = Map<string, boolean>;\nconst CHAIN_BOUND_KEY = \"missing-size-constraint:chain-bound\";\n\nfunction getChainBoundCache(context: RuleContext): ChainBoundCache {\n return getAnalysisState(context, CHAIN_BOUND_KEY, () => new Map<string, boolean>());\n}\n\nfunction establishesOwnWidthBound(node: AnalysisNode): boolean {\n if (node.layoutSizingHorizontal === \"FIXED\") return true;\n if (node.minWidth !== undefined || node.maxWidth !== undefined) return true;\n return false;\n}\n\nfunction recordChainBound(context: RuleContext, node: AnalysisNode): boolean {\n const cache = getChainBoundCache(context);\n const cached = cache.get(node.id);\n if (cached !== undefined) return cached;\n const own = establishesOwnWidthBound(node);\n const parent = context.parent;\n const inherited = parent ? cache.get(parent.id) ?? false : false;\n const result = own || inherited;\n cache.set(node.id, result);\n return result;\n}\n\nfunction parentChainBound(context: RuleContext): boolean {\n if (!context.parent) return false;\n return getChainBoundCache(context).get(context.parent.id) ?? false;\n}\n\n// ── Subtype dispatchers ──────────────────────────────────────────────────\n\nconst PAGE_CONTAINER_FRAME_TYPES = new Set([\"FRAME\", \"SECTION\"]);\n\nfunction formatWidth(node: AnalysisNode): string {\n return node.absoluteBoundingBox ? `${node.absoluteBoundingBox.width}px` : \"unknown\";\n}\n\nfunction buildViolation(\n subType: \"page-container-unbound\" | \"page-instance-fixed\" | \"component-fixed-by-design\" | \"component-fixed-by-override\",\n node: AnalysisNode,\n context: RuleContext,\n msg: { message: string; suggestion: string; guide?: string }\n): RuleViolation {\n return {\n ruleId: missingSizeConstraintDef.id,\n subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...msg,\n };\n}\n\nfunction checkComponentScopeRoot(\n node: AnalysisNode,\n context: RuleContext\n): RuleViolation | null {\n // Only the analysis root in component scope — internal nodes pass.\n // Variants of a COMPONENT_SET sit at depth=1 and are intentionally\n // skipped; variant-level sizing is the variant-structure-mismatch\n // rule's concern, not this one.\n if (context.depth !== 0) return null;\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n\n const currentWidth = formatWidth(node);\n if (context.rootNodeType === \"INSTANCE\") {\n return buildViolation(\n \"component-fixed-by-override\",\n node,\n context,\n missingSizeConstraintMsg.componentFixedByOverride(node.name, currentWidth),\n );\n }\n // COMPONENT, COMPONENT_SET, or scope-overridden FRAME treated as a\n // component definition. The gotcha framing is identical — \"is this\n // intentionally non-responsive?\" — so they share the subtype.\n return buildViolation(\n \"component-fixed-by-design\",\n node,\n context,\n missingSizeConstraintMsg.componentFixedByDesign(node.name, currentWidth),\n );\n}\n\nfunction checkPageInstanceFixed(\n node: AnalysisNode,\n context: RuleContext\n): RuleViolation | null {\n if (node.type !== \"INSTANCE\") return null;\n if (node.layoutSizingHorizontal !== \"FIXED\") return null;\n\n // Scope-out (#403): when the parent is not Auto Layout,\n // `no-auto-layout` already fires on that parent and owns the score\n // channel for the structural problem. Adding a sizing gotcha on top\n // double-counts one underlying issue. The leak case\n // (INSTANCE direct child of a SECTION page-root, where\n // no-auto-layout's behavior on SECTION is ambiguous) will surface in\n // Phase 4's fire-rate gate; revisit then if it actually appears.\n if (!context.parent || !hasAutoLayout(context.parent)) return null;\n\n const currentWidth = formatWidth(node);\n return buildViolation(\n \"page-instance-fixed\",\n node,\n context,\n missingSizeConstraintMsg.pageInstanceFixed(node.name, currentWidth),\n );\n}\n\nfunction checkPageContainerUnbound(\n node: AnalysisNode,\n context: RuleContext\n): RuleViolation | null {\n if (!PAGE_CONTAINER_FRAME_TYPES.has(node.type)) return null;\n if (node.layoutSizingHorizontal !== \"FILL\") return null;\n // Some ancestor already establishes the width bound for this chain —\n // the FILL here will resolve to a finite range, no ambiguity.\n if (parentChainBound(context)) return null;\n\n const currentWidth = formatWidth(node);\n return buildViolation(\n \"page-container-unbound\",\n node,\n context,\n missingSizeConstraintMsg.pageContainerUnbound(node.name, currentWidth),\n );\n}\n\nconst missingSizeConstraintCheck: RuleCheckFn = (node, context) => {\n // Side-effect: record this node's chain-bound status for descendants.\n // MUST run for every visited node BEFORE any early return, otherwise\n // `parentChainBound` lookups on children will miss and silently\n // default to `false`. Co-locating the recorder with the only consumer\n // (this rule) keeps the cache contract local.\n recordChainBound(context, node);\n\n // Actionability filter (#403, D6): the Figma Plugin API silently\n // ignores min/max writes targeting nodes inside an INSTANCE, so any\n // gotcha generated here would be un-actionable. We exclude INSTANCE\n // descendants (but keep the INSTANCE node itself in scope — that's\n // the page-instance-fixed case, where the override IS actionable).\n if (context.ancestorTypes.includes(\"INSTANCE\")) return null;\n\n if (context.scope === \"component\") {\n return checkComponentScopeRoot(node, context);\n }\n\n // page scope — at most one of these fires per node by construction\n // (different node-type predicates), so order does not matter.\n return checkPageInstanceFixed(node, context) ?? checkPageContainerUnbound(node, context);\n};\n\nexport const missingSizeConstraint = defineRule({\n definition: missingSizeConstraintDef,\n check: missingSizeConstraintCheck,\n});\n\n// ============================================\n// non-layout-container (was group-usage — now also catches Section)\n// ============================================\n\nconst nonLayoutContainerDef: RuleDefinition = {\n id: \"non-layout-container\",\n name: \"Non-Layout Container\",\n category: \"pixel-critical\",\n why: \"Groups and Sections lack proper layout rules — AI sees children with absolute coordinates but no container logic\",\n impact: \"AI wraps elements in a plain div with no spacing/alignment, producing fragile layouts\",\n fix: \"Convert to Frame with Auto Layout so AI can generate proper flex/grid containers\",\n};\n\nconst nonLayoutContainerCheck: RuleCheckFn = (node, context) => {\n if (node.type === \"GROUP\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"group\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.group(node.name),\n };\n }\n\n if (node.type === \"SECTION\") {\n return {\n ruleId: nonLayoutContainerDef.id,\n subType: \"section\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonLayoutContainerMsg.section(node.name),\n };\n }\n\n return null;\n};\n\nexport const nonLayoutContainer = defineRule({\n definition: nonLayoutContainerDef,\n check: nonLayoutContainerCheck,\n});\n\n// ============================================\n// deep-nesting\n// ============================================\n\nconst deepNestingDef: RuleDefinition = {\n id: \"deep-nesting\",\n name: \"Deep Nesting\",\n category: \"code-quality\",\n why: \"Deep nesting consumes AI context exponentially — each level adds indentation and structural overhead\",\n impact: \"AI may lose track of parent-child relationships in deeply nested trees, producing wrong layout hierarchy\",\n fix: \"Flatten the structure by extracting deeply nested groups into sub-components\",\n};\n\nconst deepNestingCheck: RuleCheckFn = (node, context, options) => {\n const maxDepth = (options?.[\"maxDepth\"] as number) ?? getRuleOption(\"deep-nesting\", \"maxDepth\", 5);\n\n if (context.componentDepth < maxDepth) return null;\n if (!isContainerNode(node)) return null;\n\n return {\n ruleId: deepNestingDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...deepNestingMsg(node.name, context.componentDepth, maxDepth),\n };\n};\n\nexport const deepNesting = defineRule({\n definition: deepNestingDef,\n check: deepNestingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { rawValueMsg, irregularSpacingMsg } from \"../rule-messages.js\";\nimport { hasStyleReference, hasBoundVariable } from \"../node-semantics.js\";\n\nfunction isOnGrid(value: number, gridBase: number): boolean {\n return value % gridBase === 0;\n}\n\n// ============================================\n// raw-value (merged: raw-color + raw-font + raw-shadow + raw-opacity + raw-spacing)\n// ============================================\n\nconst rawValueDef: RuleDefinition = {\n id: \"raw-value\",\n name: \"Raw Value\",\n category: \"token-management\",\n why: \"Values without design tokens or variables must be reproduced exactly per node — one typo means a visible difference\",\n impact: \"AI cannot reference a shared token, so each raw value is an independent source of error across large pages\",\n fix: \"Use design tokens or variables (color styles, text styles, effect styles, opacity/spacing variables) so values are referenceable\",\n};\n\nconst rawValueCheck: RuleCheckFn = (node, context) => {\n const nodePath = context.path.join(\" > \");\n\n // Check 1: Raw fill color\n if (node.fills && Array.isArray(node.fills) && node.fills.length > 0) {\n if (!hasStyleReference(node, \"fill\") && !hasBoundVariable(node, \"fills\")) {\n for (const fill of node.fills) {\n const fillObj = fill as Record<string, unknown>;\n if (fillObj[\"type\"] === \"SOLID\" && fillObj[\"color\"]) {\n const c = fillObj[\"color\"] as Record<string, number>;\n const hex = `#${Math.round((c[\"r\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"g\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}${Math.round((c[\"b\"] ?? 0) * 255).toString(16).padStart(2, \"0\")}`.toUpperCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"color\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.color(node.name, hex),\n };\n }\n }\n }\n }\n\n // Check 2: Raw font (TEXT nodes without text style)\n if (node.type === \"TEXT\") {\n if (\n !hasStyleReference(node, \"text\") &&\n (!hasBoundVariable(node, \"fontFamily\") || !hasBoundVariable(node, \"fontSize\"))\n ) {\n const fontParts: string[] = [];\n const s = node.style;\n if (s) {\n if (s[\"fontFamily\"]) fontParts.push(String(s[\"fontFamily\"]));\n if (s[\"fontSize\"]) fontParts.push(`${s[\"fontSize\"]}px`);\n if (s[\"fontWeight\"]) fontParts.push(String(s[\"fontWeight\"]));\n }\n const fontDesc = fontParts.length > 0 ? ` (${fontParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"font\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.font(node.name, fontDesc),\n };\n }\n }\n\n // Check 3: Raw shadow (effects without effect style)\n if (node.effects && Array.isArray(node.effects) && node.effects.length > 0) {\n if (!hasStyleReference(node, \"effect\")) {\n for (const effect of node.effects) {\n const effectObj = effect as Record<string, unknown>;\n if (effectObj[\"type\"] === \"DROP_SHADOW\" || effectObj[\"type\"] === \"INNER_SHADOW\") {\n const shadowType = effectObj[\"type\"] === \"DROP_SHADOW\" ? \"drop shadow\" : \"inner shadow\";\n const offset = effectObj[\"offset\"] as Record<string, number> | undefined;\n const radius = effectObj[\"radius\"] as number | undefined;\n const detailParts: string[] = [];\n if (offset) detailParts.push(`offset ${Math.round(offset[\"x\"] ?? 0)},${Math.round(offset[\"y\"] ?? 0)}`);\n if (radius !== undefined) detailParts.push(`blur ${Math.round(radius)}`);\n const details = detailParts.length > 0 ? ` (${detailParts.join(\" \")})` : \"\";\n return {\n ruleId: rawValueDef.id,\n subType: \"shadow\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.shadow(node.name, shadowType, details),\n };\n }\n }\n }\n }\n\n // Check 4: Raw opacity (non-default opacity without variable)\n if (node.opacity !== undefined && node.opacity < 1 && !hasBoundVariable(node, \"opacity\")) {\n return {\n ruleId: rawValueDef.id,\n subType: \"opacity\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.opacity(node.name, Math.round(node.opacity * 100)),\n };\n }\n\n // Check 5: Raw spacing (padding/gap without variable binding)\n const spacingKeys = [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\", \"itemSpacing\"] as const;\n for (const key of spacingKeys) {\n const value = node[key];\n if (value !== undefined && value > 0 && !hasBoundVariable(node, key)) {\n const label = key === \"itemSpacing\" ? \"gap\" : key.replace(\"padding\", \"padding-\").toLowerCase();\n return {\n ruleId: rawValueDef.id,\n subType: \"spacing\" as const,\n nodeId: node.id,\n nodePath,\n ...rawValueMsg.spacing(node.name, label, value),\n };\n }\n }\n\n return null;\n};\n\nexport const rawValue = defineRule({\n definition: rawValueDef,\n check: rawValueCheck,\n});\n\n// ============================================\n// irregular-spacing (merged: inconsistent-spacing + magic-number-spacing)\n// ============================================\n\nconst irregularSpacingDef: RuleDefinition = {\n id: \"irregular-spacing\",\n name: \"Irregular Spacing\",\n category: \"token-management\",\n why: \"Off-grid or arbitrary spacing values force AI to handle many unique values instead of a predictable pattern\",\n impact: \"Higher chance of pixel-level differences when AI substitutes nearby round values\",\n fix: \"Align spacing to the design system grid (e.g., 4pt/8pt increments) for predictable implementation\",\n};\n\nconst irregularSpacingCheck: RuleCheckFn = (node, context, options) => {\n const configuredGridBase = (options?.[\"gridBase\"] as number) ?? getRuleOption(\"irregular-spacing\", \"gridBase\", 4);\n const gridBase = Number.isFinite(configuredGridBase) && configuredGridBase > 0 ? configuredGridBase : 4;\n\n const spacingEntries: Array<{ value: number; subType: \"padding\" | \"gap\" }> = [];\n for (const key of [\"paddingLeft\", \"paddingRight\", \"paddingTop\", \"paddingBottom\"] as const) {\n const v = node[key];\n if (v !== undefined && v > 0) spacingEntries.push({ value: v, subType: \"padding\" });\n }\n if (node.itemSpacing !== undefined && node.itemSpacing > 0) {\n spacingEntries.push({ value: node.itemSpacing, subType: \"gap\" });\n }\n\n // Allow small intentional values\n const commonValues = [1, 2];\n\n for (const entry of spacingEntries) {\n if (commonValues.includes(entry.value)) continue;\n if (!isOnGrid(entry.value, gridBase)) {\n return {\n ruleId: irregularSpacingDef.id,\n subType: entry.subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...irregularSpacingMsg(node.name, entry.value, gridBase, Math.round(entry.value / gridBase) * gridBase),\n };\n }\n }\n\n return null;\n};\n\nexport const irregularSpacing = defineRule({\n definition: irregularSpacingDef,\n check: irregularSpacingCheck,\n});\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getRuleOption } from \"../rule-config.js\";\nimport { missingComponentMsg, detachedInstanceMsg, variantStructureMismatchMsg } from \"../rule-messages.js\";\n\n// ============================================\n// Helper functions\n// ============================================\n\n\n/** Style properties to compare between master and instance. */\nconst STYLE_COMPARE_KEYS = [\"fills\", \"strokes\", \"effects\", \"cornerRadius\", \"strokeWeight\", \"individualStrokeWeights\"] as const;\n\n/**\n * Detect style overrides between a component master and an instance.\n * Returns list of property names that differ.\n */\nfunction detectStyleOverrides(master: AnalysisNode, instance: AnalysisNode): string[] {\n const overrides: string[] = [];\n for (const key of STYLE_COMPARE_KEYS) {\n const masterVal = master[key];\n const instanceVal = instance[key];\n // Both undefined/null → no override\n if (masterVal == null && instanceVal == null) continue;\n // One exists, other doesn't → override\n if (masterVal == null || instanceVal == null) {\n overrides.push(key);\n continue;\n }\n // Deep compare via JSON\n if (JSON.stringify(masterVal) !== JSON.stringify(instanceVal)) {\n overrides.push(key);\n }\n }\n return overrides;\n}\n\n/**\n * Collect all frame names in the file for duplicate detection\n */\nfunction collectFrameNames(\n node: AnalysisNode,\n names: Map<string, string[]> = new Map()\n): Map<string, string[]> {\n if (node.type === \"FRAME\" && node.name) {\n const existing = names.get(node.name) ?? [];\n existing.push(node.id);\n names.set(node.name, existing);\n }\n\n if (node.children) {\n for (const child of node.children) {\n collectFrameNames(child, names);\n }\n }\n\n return names;\n}\n\n/**\n * Build a structural fingerprint for a node.\n * The fingerprint encodes type, layoutMode, and child types recursively up to maxDepth.\n */\nfunction buildFingerprint(node: AnalysisNode, depth: number): string {\n if (depth <= 0 || !node.children || node.children.length === 0) {\n return `${node.type}:${node.layoutMode ?? \"NONE\"}`;\n }\n\n const childFingerprints = node.children\n .map((child) => buildFingerprint(child, depth - 1))\n .join(\",\");\n\n return `${node.type}:${node.layoutMode ?? \"NONE\"}:[${childFingerprints}]`;\n}\n\n/**\n * Check if the node is inside an INSTANCE subtree.\n * Walks the full ancestor type chain to detect INSTANCE at any level.\n */\nfunction isInsideInstance(context: {\n ancestorTypes: string[];\n}): boolean {\n return context.ancestorTypes.includes(\"INSTANCE\");\n}\n\n\n\n// ============================================\n// missing-component (unified 4-stage rule)\n// ============================================\n\n/** State keys for per-analysis deduplication via RuleContext.analysisState */\nconst SEEN_STAGE1_KEY = \"missing-component:seenStage1ComponentNames\";\nconst SEEN_STAGE4_KEY = \"missing-component:seenStage4ComponentIds\";\n\nfunction getSeenStage1(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE1_KEY, () => new Set<string>());\n}\n\nfunction getSeenStage4(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_STAGE4_KEY, () => new Set<string>());\n}\n\nconst missingComponentDef: RuleDefinition = {\n id: \"missing-component\",\n name: \"Missing Component\",\n category: \"code-quality\",\n why: \"Repeated structures, unused components, and divergent instance overrides indicate missing or underutilized components. This inflates AI token consumption and forces manual maintenance.\",\n impact: \"AI code generators reproduce each repeated frame independently instead of emitting a reusable component. Divergent instance overrides produce inconsistent implementations.\",\n fix: \"Create components from repeated structures, use instances instead of duplicated frames, and create variants for instances with significantly different overrides.\",\n};\n\nconst missingComponentCheck: RuleCheckFn = (node, context, options) => {\n // ========================================\n // FRAME stages (1, 2, 3) — ordered by priority\n // ========================================\n if (node.type === \"FRAME\") {\n // Stage 1: Component exists but not used — FRAME name matches a component in metadata AND frame is repeated\n const components = context.file.components;\n const matchingComponent = Object.values(components).find(\n (c) => c.name.toLowerCase() === node.name.toLowerCase()\n );\n\n // Collect frame names once for Stage 1 and Stage 2\n const frameNames = collectFrameNames(context.file.document);\n const sameNameFrames = frameNames.get(node.name);\n const firstFrame = sameNameFrames?.[0];\n\n if (matchingComponent) {\n const seenStage1 = getSeenStage1(context);\n if (\n sameNameFrames &&\n firstFrame !== undefined &&\n sameNameFrames.length >= 2 &&\n !seenStage1.has(node.name.toLowerCase()) &&\n firstFrame === node.id\n ) {\n seenStage1.add(node.name.toLowerCase());\n return {\n ruleId: missingComponentDef.id,\n subType: \"unused-component\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.unusedComponent(matchingComponent.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 2: Name-based repetition (existing logic)\n const minRepetitions =\n (options?.[\"minRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"minRepetitions\", 3);\n\n if (sameNameFrames && firstFrame !== undefined && sameNameFrames.length >= minRepetitions) {\n if (firstFrame === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"name-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.nameRepetition(node.name, sameNameFrames.length),\n };\n }\n }\n\n // Stage 3: Structure-based repetition (absorbed from repeated-frame-structure)\n // Skip if node is inside an INSTANCE subtree\n if (isInsideInstance(context)) return null;\n\n // Skip if parent is COMPONENT_SET\n if (context.parent?.type === \"COMPONENT_SET\") return null;\n\n // Skip if node has no children\n if (!node.children || node.children.length === 0) return null;\n\n const structureMinRepetitions =\n (options?.[\"structureMinRepetitions\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"structureMinRepetitions\", 2);\n\n const maxFingerprintDepth =\n (options?.[\"maxFingerprintDepth\"] as number | undefined) ??\n getRuleOption(\"missing-component\", \"maxFingerprintDepth\", 3);\n\n // Compute fingerprint for this node\n const fingerprint = buildFingerprint(node, maxFingerprintDepth);\n\n // Access siblings (may be undefined)\n const siblings = context.siblings ?? [];\n\n // Filter siblings to qualifying frames (type === FRAME, not inside INSTANCE, has children)\n const qualifyingSiblings = siblings.filter(\n (s) =>\n s.type === \"FRAME\" &&\n s.children !== undefined &&\n s.children.length > 0\n );\n\n // Count siblings (including self) sharing the same fingerprint\n const matchingNodes = qualifyingSiblings.filter(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // Ensure self is counted (it should be in siblings, but add a guard)\n const selfIsInSiblings = qualifyingSiblings.some((s) => s.id === node.id);\n const count = selfIsInSiblings\n ? matchingNodes.length\n : matchingNodes.length + 1;\n\n if (count >= structureMinRepetitions) {\n // Only emit for the first sibling (by array order) with this fingerprint\n const firstMatch = qualifyingSiblings.find(\n (s) => buildFingerprint(s, maxFingerprintDepth) === fingerprint\n );\n\n // If self is not in siblings list, treat self as first match when no earlier match exists\n const firstMatchId = firstMatch?.id ?? node.id;\n if (firstMatchId === node.id) {\n return {\n ruleId: missingComponentDef.id,\n subType: \"structure-repetition\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.structureRepetition(node.name, count - 1),\n };\n }\n }\n\n return null;\n }\n\n // ========================================\n // Stage 4: Instance style override detection\n // Compares instance styles against component master.\n // Any style override (fills, strokes, effects, cornerRadius) means\n // the designer should use a variant instead.\n // ========================================\n if (node.type === \"INSTANCE\" && node.componentId) {\n const seenStage4 = getSeenStage4(context);\n if (seenStage4.has(node.componentId)) return null;\n\n const componentDefs = context.file.componentDefinitions;\n if (!componentDefs) return null;\n\n const master = componentDefs[node.componentId];\n if (!master) return null;\n\n // Compare style properties between master and instance\n const overrides = detectStyleOverrides(master, node);\n if (overrides.length > 0) {\n // Only mark as seen when we actually flag — allows other instances to be checked\n seenStage4.add(node.componentId);\n const componentMeta = context.file.components[node.componentId];\n const componentName = componentMeta?.name ?? node.name;\n\n return {\n ruleId: missingComponentDef.id,\n subType: \"style-override\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingComponentMsg.styleOverride(componentName, overrides),\n };\n }\n return null;\n }\n\n return null;\n};\n\nexport const missingComponent = defineRule({\n definition: missingComponentDef,\n check: missingComponentCheck,\n});\n\n// ============================================\n// detached-instance\n// ============================================\n\nconst detachedInstanceDef: RuleDefinition = {\n id: \"detached-instance\",\n name: \"Detached Instance\",\n category: \"code-quality\",\n why: \"Detached instances lose component relationship — AI sees a one-off frame instead of a reusable component reference\",\n impact: \"AI generates duplicate code instead of reusing the component, inflating output and causing inconsistencies\",\n fix: \"Reset the instance or create a new variant if customization is needed\",\n};\n\nconst detachedInstanceCheck: RuleCheckFn = (node, context) => {\n // A detached instance would be a FRAME that was once an INSTANCE\n // This is hard to detect without historical data\n // Heuristic: Frame with a name that looks like it came from a component\n if (node.type !== \"FRAME\") return null;\n\n // Check if there's a component in the file with a matching name (word boundary)\n const components = context.file.components;\n\n for (const [, component] of Object.entries(components)) {\n const pattern = new RegExp(`\\\\b${component.name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`);\n if (pattern.test(node.name)) {\n // This frame might be a detached instance of this component\n return {\n ruleId: detachedInstanceDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...detachedInstanceMsg(node.name, component.name),\n };\n }\n }\n\n return null;\n};\n\nexport const detachedInstance = defineRule({\n definition: detachedInstanceDef,\n check: detachedInstanceCheck,\n});\n\n// ============================================\n// variant-structure-mismatch\n// ============================================\n\nconst variantStructureMismatchDef: RuleDefinition = {\n id: \"variant-structure-mismatch\",\n name: \"Variant Structure Mismatch\",\n category: \"code-quality\",\n why: \"Variants with different child structures prevent AI from creating a unified component template\",\n impact: \"AI must generate separate implementations for each variant instead of a single parameterized component\",\n fix: \"Ensure all variants share the same child structure, using visibility toggles for optional elements\",\n};\n\nconst variantStructureMismatchCheck: RuleCheckFn = (node, context) => {\n // Only COMPONENT_SET\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.children?.length || node.children.length < 2) return null;\n\n // Build fingerprint for each variant child\n const fingerprints = node.children\n .filter(child => child.type === \"COMPONENT\")\n .map(child => buildFingerprint(child, 2));\n\n if (fingerprints.length < 2) return null;\n\n // Compare all fingerprints to the first one\n const base = fingerprints[0];\n const mismatched = fingerprints.filter(fp => fp !== base);\n\n if (mismatched.length === 0) return null;\n\n const mismatchCount = mismatched.length;\n const totalVariants = fingerprints.length;\n\n return {\n ruleId: variantStructureMismatchDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...variantStructureMismatchMsg(node.name, mismatchCount, totalVariants),\n };\n};\n\nexport const variantStructureMismatch = defineRule({\n definition: variantStructureMismatchDef,\n check: variantStructureMismatchCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition } from \"../../contracts/rule.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport { getDefaultNameSubType, nonSemanticNameMsg, inconsistentNamingMsg, nonStandardNamingMsg } from \"../rule-messages.js\";\nimport { isExcludedName, isDefaultName, isNonSemanticName, STANDARD_STATE_NAMES, STATE_NAME_SUGGESTIONS, STATE_LIKE_PATTERN } from \"../node-semantics.js\";\n\nfunction capitalize(s: string): string {\n if (!s) return s;\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction detectNamingConvention(name: string): string | null {\n if (/^[a-z]+(-[a-z]+)*$/.test(name)) return \"kebab-case\";\n if (/^[a-z]+(_[a-z]+)*$/.test(name)) return \"snake_case\";\n if (/^[a-z]+([A-Z][a-z]*)*$/.test(name)) return \"camelCase\";\n if (/^[A-Z][a-z]+([A-Z][a-z]*)*$/.test(name)) return \"PascalCase\";\n if (/^[A-Z]+(_[A-Z]+)*$/.test(name)) return \"SCREAMING_SNAKE_CASE\";\n if (/\\s/.test(name)) return \"Title Case\";\n return null;\n}\n\n/** Single capitalized word is compatible with both PascalCase and Title Case */\nfunction isCompatible(nodeConvention: string, dominantConvention: string, name: string): boolean {\n if (!/^[A-Z][a-z]+$/.test(name)) return false;\n const pair = new Set([nodeConvention, dominantConvention]);\n return pair.has(\"PascalCase\") && pair.has(\"Title Case\");\n}\n\n/** Split a name into words regardless of convention */\nfunction splitWords(name: string): string[] {\n // Title Case / space-separated\n if (/\\s/.test(name)) return name.split(/\\s+/);\n // SCREAMING_SNAKE_CASE or snake_case\n if (name.includes(\"_\")) return name.split(\"_\");\n // kebab-case\n if (name.includes(\"-\")) return name.split(\"-\");\n // camelCase / PascalCase — split on uppercase boundaries (including acronym runs)\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1\\0$2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1\\0$2\")\n .split(\"\\0\");\n}\n\n/** Convert a name to the target convention */\nfunction convertName(name: string, target: string): string {\n const words = splitWords(name);\n switch (target) {\n case \"kebab-case\":\n return words.map(w => w.toLowerCase()).join(\"-\");\n case \"snake_case\":\n return words.map(w => w.toLowerCase()).join(\"_\");\n case \"camelCase\":\n return words.map((w, i) => i === 0 ? w.toLowerCase() : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"PascalCase\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\"\");\n case \"SCREAMING_SNAKE_CASE\":\n return words.map(w => w.toUpperCase()).join(\"_\");\n case \"Title Case\":\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(\" \");\n default:\n return name;\n }\n}\n\n// ============================================\n// non-semantic-name (merged: default-name + non-semantic-name)\n// ============================================\n\nconst nonSemanticNameDef: RuleDefinition = {\n id: \"non-semantic-name\",\n name: \"Non-Semantic Name\",\n category: \"semantic\",\n why: \"Default or shape names give AI no semantic context — it cannot choose appropriate HTML tags or class names\",\n impact: \"AI generates generic <div> wrappers instead of semantic elements like <header>, <nav>, <article>\",\n fix: \"Rename with a descriptive, purpose-driven name (e.g., 'Header', 'ProductCard', 'Divider')\",\n};\n\nconst nonSemanticNameCheck: RuleCheckFn = (node, context) => {\n if (!node.name) return null;\n if (isExcludedName(node.name)) return null;\n\n // Check 1: Figma default names (Frame 1, Group 2, etc.)\n if (isDefaultName(node.name)) {\n return {\n ruleId: nonSemanticNameDef.id,\n subType: getDefaultNameSubType(node.type),\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n // Check 2: Shape-only names (rectangle, ellipse, vector, etc.)\n if (isNonSemanticName(node.name)) {\n // Allow shape names for actual shape primitives at leaf level\n if (!node.children || node.children.length === 0) {\n const shapeTypes = [\"RECTANGLE\", \"ELLIPSE\", \"VECTOR\", \"LINE\", \"STAR\", \"REGULAR_POLYGON\"];\n if (shapeTypes.includes(node.type)) return null;\n }\n\n return {\n ruleId: nonSemanticNameDef.id,\n subType: \"shape-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...nonSemanticNameMsg(node.type, node.name),\n };\n }\n\n return null;\n};\n\nexport const nonSemanticName = defineRule({\n definition: nonSemanticNameDef,\n check: nonSemanticNameCheck,\n});\n\n// ============================================\n// inconsistent-naming-convention\n// ============================================\n\nconst inconsistentNamingConventionDef: RuleDefinition = {\n id: \"inconsistent-naming-convention\",\n name: \"Inconsistent Naming Convention\",\n category: \"semantic\",\n why: \"Mixed naming conventions (camelCase + kebab-case + Title Case) at the same level confuse AI pattern recognition\",\n impact: \"AI generates inconsistent class/component names, making the codebase harder to maintain\",\n fix: \"Pick one convention for sibling elements (e.g., kebab-case: 'product-card', or PascalCase: 'ProductCard') — AI maps names to CSS classes and component names, so mixed conventions produce inconsistent code\",\n};\n\nconst inconsistentNamingConventionCheck: RuleCheckFn = (node, context) => {\n if (!context.siblings || context.siblings.length < 2) return null;\n\n // Detect conventions used by siblings\n const conventions = new Map<string, number>();\n let ambiguousPascalCount = 0;\n\n for (const sibling of context.siblings) {\n if (!sibling.name) continue;\n const convention = detectNamingConvention(sibling.name);\n if (convention) {\n conventions.set(convention, (conventions.get(convention) ?? 0) + 1);\n if (convention === \"PascalCase\" && /^[A-Z][a-z]+$/.test(sibling.name)) {\n ambiguousPascalCount++;\n }\n }\n }\n\n // Single capitalized words (Header, Footer) are detected as PascalCase but are\n // equally valid as Title Case. When both conventions appear, discount these\n // ambiguous names so they don't bias the dominant convention toward PascalCase.\n if (conventions.has(\"PascalCase\") && conventions.has(\"Title Case\") && ambiguousPascalCount > 0) {\n const adjusted = (conventions.get(\"PascalCase\") ?? 0) - ambiguousPascalCount;\n if (adjusted <= 0) {\n conventions.delete(\"PascalCase\");\n } else {\n conventions.set(\"PascalCase\", adjusted);\n }\n }\n\n // Skip if we can't detect clear conventions\n if (conventions.size < 2) return null;\n\n // Find the dominant convention\n let dominantConvention = \"\";\n let maxCount = 0;\n for (const [convention, count] of conventions) {\n if (count > maxCount) {\n maxCount = count;\n dominantConvention = convention;\n }\n }\n\n // Check if current node violates the dominant convention\n const nodeConvention = detectNamingConvention(node.name);\n if (nodeConvention && nodeConvention !== dominantConvention && maxCount >= 2) {\n // Single capitalized word is compatible with both PascalCase and Title Case\n if (isCompatible(nodeConvention, dominantConvention, node.name)) return null;\n\n const suggested = convertName(node.name, dominantConvention);\n // #372: suppress when the case-conversion produces the same string as\n // the current name. Single-character names (\"X\"), all-numeric names, and\n // any input whose every word maps to itself across cases all fall into\n // this bucket — flagging them produces a no-op rename, an empty diff\n // visible as a misleading \"✅ resolved\" wrap-up entry.\n if (suggested === node.name) return null;\n return {\n ruleId: inconsistentNamingConventionDef.id,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n suggestedName: suggested,\n ...inconsistentNamingMsg(node.name, nodeConvention, dominantConvention, suggested),\n };\n }\n\n return null;\n};\n\nexport const inconsistentNamingConvention = defineRule({\n definition: inconsistentNamingConventionDef,\n check: inconsistentNamingConventionCheck,\n});\n\n// ============================================\n// non-standard-naming\n// ============================================\n\nconst nonStandardNamingDef: RuleDefinition = {\n id: \"non-standard-naming\",\n name: \"Non-Standard Naming\",\n category: \"semantic\",\n why: \"Non-standard state names prevent interaction rules from detecting state variants — AI cannot generate correct :hover/:active/:disabled styles\",\n impact: \"Interaction state detection fails, resulting in static UI with no state transitions\",\n fix: \"Use platform-standard state names: default, hover, active, pressed, selected, highlighted, disabled, enabled, focus, focused, dragged\",\n};\n\nconst nonStandardNamingCheck: RuleCheckFn = (node, context) => {\n // Only check COMPONENT_SET (variant container)\n if (node.type !== \"COMPONENT_SET\") return null;\n if (!node.componentPropertyDefinitions) return null;\n\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n\n for (const opt of options) {\n if (typeof opt !== \"string\") continue;\n const lower = opt.toLowerCase().trim();\n\n // Skip if it's a standard name\n if (STANDARD_STATE_NAMES.has(lower)) continue;\n\n // Check if it matches a known non-standard state name\n if (STATE_LIKE_PATTERN.test(opt)) {\n const suggestion = STATE_NAME_SUGGESTIONS[lower];\n if (suggestion) {\n return {\n ruleId: nonStandardNamingDef.id,\n subType: \"state-name\" as const,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n suggestedName: capitalize(suggestion),\n ...nonStandardNamingMsg.stateName(node.name, opt, suggestion),\n };\n }\n }\n }\n }\n\n return null;\n};\n\nexport const nonStandardNaming = defineRule({\n definition: nonStandardNamingDef,\n check: nonStandardNamingCheck,\n});\n\n","import type { RuleCheckFn, RuleDefinition, RuleContext } from \"../../contracts/rule.js\";\nimport { getAnalysisState } from \"../../contracts/rule.js\";\nimport type { AnalysisNode } from \"../../contracts/figma-node.js\";\nimport { defineRule } from \"../rule-registry.js\";\nimport type { MissingInteractionStateSubType, MissingPrototypeSubType } from \"../rule-messages.js\";\nimport { missingInteractionStateMsg, missingPrototypeMsg } from \"../rule-messages.js\";\nimport { getStatefulComponentType, isOverlayNode, isCarouselNode, type StatefulComponentType } from \"../node-semantics.js\";\n\n/** Expected state variants by interactive type */\nconst EXPECTED_STATES: Record<StatefulComponentType, MissingInteractionStateSubType[]> = {\n button: [\"hover\", \"active\", \"disabled\"],\n link: [\"hover\"],\n tab: [\"hover\", \"active\"],\n input: [\"focus\", \"disabled\"],\n toggle: [\"disabled\"],\n};\n\n/** State name patterns — web + mobile platform standard names */\nconst STATE_PATTERNS: Record<MissingInteractionStateSubType, RegExp> = {\n hover: /\\bhover\\b/i,\n disabled: /\\bdisabled\\b/i,\n active: /\\b(active|pressed|selected|highlighted)\\b/i,\n focus: /\\bfocus(ed)?\\b/i,\n};\n\n// ============================================\n// Helpers\n// ============================================\n\n/** Dedup key: emit at most one violation per componentId + subType */\nconst SEEN_KEY = \"missing-interaction-state:seen\";\n\nfunction getSeen(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_KEY, () => new Set<string>());\n}\n\n/**\n * Check if a state variant exists via componentPropertyDefinitions.\n * Looks for VARIANT type properties where variantOptions contain the state name.\n */\nfunction hasStateInVariantProps(node: AnalysisNode, statePattern: RegExp): boolean {\n if (!node.componentPropertyDefinitions) return false;\n for (const prop of Object.values(node.componentPropertyDefinitions)) {\n const p = prop as Record<string, unknown>;\n if (p[\"type\"] !== \"VARIANT\") continue;\n const options = p[\"variantOptions\"];\n if (!Array.isArray(options)) continue;\n if (options.some((opt) => typeof opt === \"string\" && statePattern.test(opt))) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if a state variant exists via component master's componentPropertyDefinitions.\n * Falls back to componentDefinitions (fetched masters) when the instance itself\n * doesn't carry the property definitions.\n */\nfunction hasStateInComponentMaster(\n node: AnalysisNode,\n context: RuleContext,\n statePattern: RegExp,\n): boolean {\n if (!node.componentId) return false;\n const defs = context.file.componentDefinitions;\n if (!defs) return false;\n const master = defs[node.componentId];\n if (!master) return false;\n return hasStateInVariantProps(master, statePattern);\n}\n\n/**\n * Master names that look like a single variant of a SET (e.g. `State=Default`,\n * `Variant=Primary, State=Default, Size=Medium`). When a fetched COMPONENT\n * carries this naming AND has no own `componentPropertyDefinitions`, the\n * variant axes live on the parent COMPONENT_SET — which the loader does not\n * fetch today (#397). Treat as undeterminable rather than asserting a missing\n * variant we cannot actually see.\n */\nconst VARIANT_POSITION_NAME_RE = /^[\\w ]+=[^,]+(,\\s*[\\w ]+=[^,]+)*$/;\n\nfunction hasUsablePropDefs(propDefs: unknown): boolean {\n // `undefined` = not fetched; `null` = REST returned blank (e.g. variant\n // INSIDE a SET — axes live on the SET parent, not here). Both are\n // non-evidence. `{}` (fetched-and-empty) IS positive evidence the master\n // truly has no axes — must keep firing per the test for #354.\n return propDefs != null && typeof propDefs === \"object\";\n}\n\n/**\n * Decide whether we have enough source data to assert a state variant is missing.\n *\n * The Figma REST API does not consistently mirror `componentPropertyDefinitions`\n * onto deeply-nested INSTANCE children, and `context.file.componentDefinitions`\n * only contains masters the loader actually fetched (external-library masters\n * stay null even after extra passes). When BOTH paths are empty for an INSTANCE\n * we cannot tell whether the master defines the variant or not — treat that as\n * \"unknown\" (return false here) rather than asserting a missing variant.\n *\n * The fetched master may also be a single variant of a SET (name like\n * `State=Default`); the variant axes live on the SET parent which we do not\n * fetch. Detect this via name pattern and treat as undeterminable too (#397).\n *\n * COMPONENT nodes are special: a COMPONENT IS the master, so the absence of\n * `componentPropertyDefinitions` on a COMPONENT is itself meaningful evidence\n * (standalone master with no variant axis at all) — UNLESS the COMPONENT name\n * follows the variant-position pattern, in which case the SET parent holds the\n * axes and we cannot decide.\n */\nfunction canDetermineVariants(node: AnalysisNode, context: RuleContext): boolean {\n if (hasUsablePropDefs(node.componentPropertyDefinitions)) return true;\n if (node.type === \"COMPONENT\") {\n return !VARIANT_POSITION_NAME_RE.test(node.name);\n }\n if (node.componentId !== undefined) {\n const defs = context.file.componentDefinitions;\n const master = defs?.[node.componentId];\n if (master) {\n if (hasUsablePropDefs(master.componentPropertyDefinitions)) return true;\n return !VARIANT_POSITION_NAME_RE.test(master.name);\n }\n }\n return false;\n}\n\n// ============================================\n// missing-interaction-state\n// ============================================\n\nconst missingInteractionStateDef: RuleDefinition = {\n id: \"missing-interaction-state\",\n name: \"Missing Interaction State\",\n category: \"interaction\",\n why: \"Interactive components without state variants force AI to guess hover/focus/disabled appearances — or skip them entirely\",\n impact: \"Generated code has no :hover, :focus, or :disabled styles, making the UI feel static and unresponsive\",\n fix: \"Add state variants (Hover, Disabled, Focus, Active) to interactive components in Figma\",\n};\n\nconst missingInteractionStateCheck: RuleCheckFn = (node, context) => {\n // Only check component instances and components\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\") return null;\n\n const interactiveType = getStatefulComponentType(node);\n if (!interactiveType) return null;\n\n const expectedStates = EXPECTED_STATES[interactiveType];\n if (!expectedStates) return null;\n\n // Probe gate: only assert a missing variant when we can actually observe the\n // master's variant axes. For nested INSTANCE children whose master was not\n // fetched into `componentDefinitions` and whose own `componentPropertyDefinitions`\n // is undefined, treat the verdict as unknown and skip — this avoids the\n // false-positive class described in #354. The data-availability check is\n // per-node (not per-state), so it lives outside the for-loop below.\n if (!canDetermineVariants(node, context)) return null;\n\n const seen = getSeen(context);\n const nodePath = context.path.join(\" > \");\n\n for (const state of expectedStates) {\n const dedupeKey = `${node.componentId ?? node.id}:${state}`;\n if (seen.has(dedupeKey)) continue;\n\n const pattern = STATE_PATTERNS[state];\n\n // Check variant properties on instance\n if (hasStateInVariantProps(node, pattern)) continue;\n\n // Check variant properties on component master (fetched definitions)\n if (hasStateInComponentMaster(node, context, pattern)) continue;\n\n // Missing state — report first missing one\n seen.add(dedupeKey);\n return {\n ruleId: missingInteractionStateDef.id,\n subType: state,\n nodeId: node.id,\n nodePath,\n ...missingInteractionStateMsg[state](node.name),\n };\n }\n\n return null;\n};\n\nexport const missingInteractionState = defineRule({\n definition: missingInteractionStateDef,\n check: missingInteractionStateCheck,\n});\n\n// ============================================\n// missing-prototype\n// ============================================\n\n/** Interactive types that need click prototype */\nconst PROTOTYPE_TYPES: Record<StatefulComponentType, MissingPrototypeSubType> = {\n button: \"button\",\n link: \"navigation\",\n tab: \"tab\",\n input: \"input\",\n toggle: \"toggle\",\n};\n\nfunction getPrototypeSubType(node: AnalysisNode): MissingPrototypeSubType | null {\n // Check overlay/carousel first — select/dropdown are classified as \"input\" in\n // STATEFUL_PATTERNS but need \"overlay\" subType for prototype checks\n if (isOverlayNode(node)) return \"overlay\";\n if (isCarouselNode(node)) return \"carousel\";\n const interactiveType = getStatefulComponentType(node);\n if (interactiveType) {\n const mapped = PROTOTYPE_TYPES[interactiveType];\n if (mapped) return mapped;\n }\n return null;\n}\n\nfunction hasInteractionTrigger(node: AnalysisNode, triggerType: string): boolean {\n if (!node.interactions || !Array.isArray(node.interactions)) return false;\n return node.interactions.some((interaction) => {\n const i = interaction as { trigger?: { type?: string } };\n return i.trigger?.type === triggerType;\n });\n}\n\n/** Check if node (or its component master) has any of the given trigger types */\nfunction hasAnyInteraction(node: AnalysisNode, context: RuleContext, triggers: string[]): boolean {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(node, trigger)) return true;\n }\n // INSTANCE nodes don't inherit interactions from master — check master fallback\n if (node.componentId && context.file.componentDefinitions) {\n const master = context.file.componentDefinitions[node.componentId];\n if (master) {\n for (const trigger of triggers) {\n if (hasInteractionTrigger(master, trigger)) return true;\n }\n }\n }\n return false;\n}\n\n/** Trigger types to check per subType */\nconst PROTOTYPE_TRIGGERS: Record<string, string[]> = {\n carousel: [\"ON_CLICK\", \"ON_DRAG\"],\n};\n\nconst DEFAULT_TRIGGERS = [\"ON_CLICK\"];\n\nconst missingPrototypeDef: RuleDefinition = {\n id: \"missing-prototype\",\n name: \"Missing Prototype\",\n category: \"interaction\",\n why: \"Interactive elements without prototype interactions give AI no information about navigation or behavior\",\n impact: \"AI cannot generate interaction handlers, routing, or state changes — interactive elements become static\",\n fix: \"Add prototype interactions (ON_CLICK, ON_DRAG) to define navigation targets or state changes\",\n};\n\nconst SEEN_PROTO_KEY = \"missing-prototype:seen\";\n\nfunction getSeenProto(context: RuleContext): Set<string> {\n return getAnalysisState(context, SEEN_PROTO_KEY, () => new Set<string>());\n}\n\nconst missingPrototypeCheck: RuleCheckFn = (node, context) => {\n if (node.type !== \"INSTANCE\" && node.type !== \"COMPONENT\" && node.type !== \"FRAME\") return null;\n\n const subType = getPrototypeSubType(node);\n if (!subType) return null;\n\n // Already has relevant interaction (click, or drag for carousel)\n const triggers = PROTOTYPE_TRIGGERS[subType] ?? DEFAULT_TRIGGERS;\n if (hasAnyInteraction(node, context, triggers)) return null;\n\n // Dedup per componentId + subType\n const seen = getSeenProto(context);\n const dedupeKey = `${node.componentId ?? node.id}:${subType}`;\n if (seen.has(dedupeKey)) return null;\n seen.add(dedupeKey);\n\n return {\n ruleId: missingPrototypeDef.id,\n subType,\n nodeId: node.id,\n nodePath: context.path.join(\" > \"),\n ...missingPrototypeMsg[subType](node.name),\n };\n};\n\nexport const missingPrototype = defineRule({\n definition: missingPrototypeDef,\n check: missingPrototypeCheck,\n});\n","#!/usr/bin/env node\nimport { createRequire } from \"node:module\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\nimport { writeFile } from \"node:fs\";\nimport { exec } from \"node:child_process\";\nimport { analyzeFile } from \"../core/engine/rule-engine.js\";\nimport { loadFile, isJsonFile, isFixtureDir } from \"../core/engine/loader.js\";\nimport { calculateScores, buildResultJson } from \"../core/engine/scoring.js\";\nimport type { Grade } from \"../core/engine/scoring.js\";\nimport { generateGotchaSurvey } from \"../core/gotcha/survey-generator.js\";\nimport { generateHtmlReport } from \"../core/report-html/index.js\";\nimport { getReportsDir, ensureReportsDir } from \"../core/engine/config-store.js\";\nimport { getConfigsWithPreset, RULE_CONFIGS, type Preset } from \"../core/rules/rule-config.js\";\nimport { loadConfigFile, mergeConfigs } from \"../core/rules/config-loader.js\";\nimport { ruleRegistry } from \"../core/rules/rule-registry.js\";\nimport type { RuleConfig, RuleId } from \"../core/contracts/rule.js\";\nimport { initMonitoring, trackEvent, trackError, shutdownMonitoring, EVENTS } from \"../core/monitoring/index.js\";\nimport { POSTHOG_API_KEY as BUILTIN_PH_KEY, SENTRY_DSN as BUILTIN_SENTRY_DSN } from \"../core/monitoring/keys.js\";\nimport { getTelemetryEnabled, getPosthogApiKey, getSentryDsn, getDeviceId } from \"../core/engine/config-store.js\";\nimport { AcknowledgmentSchema } from \"../core/contracts/acknowledgment.js\";\nimport { computeDesignKey } from \"../core/contracts/design-key.js\";\n\n// Load .env for FIGMA_TOKEN (quiet: suppress dotenv's stdout banner — MCP uses stdout for JSON-RPC)\nconfig({ quiet: true });\n\n// Import rules to register them\nimport \"../core/rules/index.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../../package.json\") as { version: string };\n\nconst SERVER_INSTRUCTIONS = `canicode has three channels. The MCP tools below cover analysis only — design write-back is a separate channel.\n\n- **MCP tools** (this server): \\`analyze\\`, \\`gotcha-survey\\`, \\`list-rules\\`, \\`docs\\`, \\`version\\`, \\`visual-compare\\`. Use these for read-only analysis and reports.\n- **Skills** (slash commands, NOT MCP tools): \\`/canicode\\`, \\`/canicode-gotchas\\`, \\`/canicode-roundtrip\\`. Install with \\`npx canicode init\\` (Claude Code) or \\`npx canicode init --cursor-skills\\` (Cursor). The roundtrip skill is the only path that writes back to the Figma file via Plugin API.\n- **CLI**: \\`npx canicode <command>\\` — same JSON shape as MCP tools, useful for CI / scripting.\n\nIf a user asks to \"run the roundtrip\" or \"fix gotchas in Figma\" and you don't see \\`canicode-roundtrip\\` as a slash command, the skill isn't installed yet — tell them to run \\`npx canicode init\\`. Don't try to compose roundtrip out of MCP tools; the write-back logic lives in the skill.\n\nCall \\`docs\\` with topic \\`channels\\` for the full matrix.`;\n\nconst server = new McpServer(\n {\n name: \"canicode\",\n version: pkg.version,\n },\n {\n instructions: SERVER_INSTRUCTIONS,\n },\n);\n\nserver.tool(\n \"analyze\",\n `Analyze a Figma design for development-friendliness and AI-friendliness.\n\nProvide a Figma URL or fixture path via the input parameter. Requires FIGMA_TOKEN env var or the token parameter for live Figma URLs.`,\n {\n input: z.string().describe(\"Figma URL or local fixture path. Requires FIGMA_TOKEN for live URLs.\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n preset: z.enum([\"relaxed\", \"dev-friendly\", \"ai-ready\", \"strict\"]).optional().describe(\"Analysis preset\"),\n targetNodeId: z.string().optional().describe(\"Scope analysis to a specific node ID\"),\n configPath: z.string().optional().describe(\"Path to config JSON file for rule overrides\"),\n openReport: z.boolean().optional().describe(\"Open the generated HTML report in the user's browser. Defaults to false — opt in only when a visible report is the explicit user request (#365). The HTML file is always written to disk regardless.\"),\n acknowledgments: z.array(AcknowledgmentSchema).optional().describe(\"(#371 / ADR-019) Pre-resolved acknowledgments from canicode-authored Figma annotations (e.g. via readCanicodeAcknowledgments in a use_figma batch). Each entry includes nodeId and ruleId; newer annotations may also carry intent, sceneWriteOutcome, and codegenDirective from a canicode-json fenced block (#444). Matching issues are flagged acknowledged and contribute half weight to the density score.\"),\n scope: z.enum([\"page\", \"component\"]).optional().describe(\"(#404) Override analysis scope — `page` (screen/section where container bounds are required) or `component` (standalone reusable unit where root FILL is the design contract). Defaults to auto-detection from the root node type: `COMPONENT` / `COMPONENT_SET` / `INSTANCE` roots resolve to `component`, everything else to `page`.\"),\n codegenReadyMinGrade: z.enum([\"S\", \"A+\", \"A\", \"B+\", \"B\", \"C+\", \"C\", \"D\", \"F\"]).optional().describe(\"Minimum grade for code-gen readiness. Overrides the codegenReadyMinGrade field in configPath. Default: A\"),\n },\n {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Analyze Figma Design\",\n },\n async ({ input, token, preset, targetNodeId, configPath, openReport, acknowledgments, scope, codegenReadyMinGrade }) => {\n trackEvent(EVENTS.MCP_TOOL_CALLED, { tool: \"analyze\" });\n try {\n // Fetch via REST API or load from fixture\n const { file, nodeId } = await loadFile(input, token);\n\n const effectiveNodeId = targetNodeId ?? nodeId;\n\n let configs: Record<string, RuleConfig> = preset\n ? { ...getConfigsWithPreset(preset as Preset) }\n : { ...RULE_CONFIGS };\n\n let configFileMinGrade: Grade | undefined;\n if (configPath) {\n const configFile = await loadConfigFile(configPath);\n configs = mergeConfigs(configs, configFile);\n configFileMinGrade = configFile.codegenReadyMinGrade;\n }\n // MCP param takes priority over configPath field\n const effectiveMinGrade = codegenReadyMinGrade ?? configFileMinGrade;\n\n const result = analyzeFile(file, {\n configs: configs as Record<RuleId, RuleConfig>,\n ...(effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}),\n ...(acknowledgments && acknowledgments.length > 0\n ? { acknowledgments }\n : {}),\n ...(scope ? { scope } : {}),\n });\n\n const scores = calculateScores(result, configs as Record<RuleId, RuleConfig>);\n\n // Generate HTML report (with Figma token for comment buttons)\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n const html = generateHtmlReport(file, result, scores, { figmaToken });\n\n // Save report to disk\n const now = new Date();\n const ts = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}-${String(now.getHours()).padStart(2, \"0\")}-${String(now.getMinutes()).padStart(2, \"0\")}`;\n ensureReportsDir();\n const reportPath = `${getReportsDir()}/report-${ts}-${file.fileKey}.html`;\n await new Promise<void>((resolve, reject) => {\n writeFile(reportPath, html, \"utf-8\", (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n\n // #365: only open the report in the user's browser when explicitly\n // requested. The MCP `analyze` tool is machine-callable from skill\n // workflows (e.g. `/canicode-roundtrip` Step 1 + Step 5), where\n // popping a browser tab mid-conversation breaks flow. The HTML file\n // is still written to disk so follow-up sessions can open it manually.\n if (openReport === true) {\n const openCmd = process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"start\" : \"xdg-open\";\n exec(`${openCmd} \"${reportPath}\"`);\n }\n\n trackEvent(EVENTS.ANALYSIS_COMPLETED, {\n nodeCount: result.nodeCount,\n issueCount: result.issues.length,\n grade: scores.overall.grade,\n percentage: scores.overall.percentage,\n source: isJsonFile(input) || isFixtureDir(input) ? \"fixture\" : \"figma\",\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(buildResultJson(file.name, result, scores, { fileKey: file.fileKey, designKey: computeDesignKey(input), ...(effectiveMinGrade ? { codegenReadyMinGrade: effectiveMinGrade } : {}) }), null, 2),\n },\n ],\n };\n } catch (error) {\n trackError(\n error instanceof Error ? error : new Error(String(error)),\n { tool: \"analyze\" },\n );\n trackEvent(EVENTS.ANALYSIS_FAILED, {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Error: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"gotcha-survey\",\n `Generate a gotcha survey from a Figma design analysis.\n\nAnalyzes the design and returns a GotchaSurvey JSON with designGrade, isReadyForCodeGen, and questions[].\nWhen isReadyForCodeGen is true, questions will be empty (no survey needed).\n\nProvide a Figma URL or fixture path via the input parameter. Requires FIGMA_TOKEN env var or the token parameter for live Figma URLs.`,\n {\n input: z.string().describe(\"Figma URL or local fixture path. Requires FIGMA_TOKEN for live URLs.\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n preset: z.enum([\"relaxed\", \"dev-friendly\", \"ai-ready\", \"strict\"]).optional().describe(\"Analysis preset\"),\n targetNodeId: z.string().optional().describe(\"Scope analysis to a specific node ID\"),\n configPath: z.string().optional().describe(\"Path to config JSON file for rule overrides\"),\n scope: z.enum([\"page\", \"component\"]).optional().describe(\"(#404) Override analysis scope — `page` or `component`. Defaults to auto-detection from the root node type.\"),\n codegenReadyMinGrade: z.enum([\"S\", \"A+\", \"A\", \"B+\", \"B\", \"C+\", \"C\", \"D\", \"F\"]).optional().describe(\"Minimum grade for code-gen readiness. Overrides the codegenReadyMinGrade field in configPath. Default: A\"),\n },\n {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Gotcha Survey\",\n },\n async ({ input, token, preset, targetNodeId, configPath, scope, codegenReadyMinGrade }) => {\n trackEvent(EVENTS.MCP_TOOL_CALLED, { tool: \"gotcha-survey\" });\n try {\n const { file, nodeId } = await loadFile(input, token);\n\n const effectiveNodeId = targetNodeId ?? nodeId;\n\n let configs: Record<string, RuleConfig> = preset\n ? { ...getConfigsWithPreset(preset as Preset) }\n : { ...RULE_CONFIGS };\n\n let configFileMinGrade: Grade | undefined;\n if (configPath) {\n const configFile = await loadConfigFile(configPath);\n configs = mergeConfigs(configs, configFile);\n configFileMinGrade = configFile.codegenReadyMinGrade;\n }\n // MCP param takes priority over configPath field\n const effectiveMinGrade = codegenReadyMinGrade ?? configFileMinGrade;\n\n const result = analyzeFile(file, {\n configs: configs as Record<RuleId, RuleConfig>,\n ...(effectiveNodeId ? { targetNodeId: effectiveNodeId } : {}),\n ...(scope ? { scope } : {}),\n });\n\n const scores = calculateScores(result, configs as Record<RuleId, RuleConfig>);\n const survey = generateGotchaSurvey(result, scores, {\n designKey: computeDesignKey(input),\n ...(effectiveMinGrade ? { codegenReadyMinGrade: effectiveMinGrade } : {}),\n });\n\n trackEvent(EVENTS.ANALYSIS_COMPLETED, {\n nodeCount: result.nodeCount,\n issueCount: result.issues.length,\n grade: scores.overall.grade,\n percentage: scores.overall.percentage,\n source: isJsonFile(input) || isFixtureDir(input) ? \"fixture\" : \"figma\",\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(survey, null, 2),\n },\n ],\n };\n } catch (error) {\n trackError(\n error instanceof Error ? error : new Error(String(error)),\n { tool: \"gotcha-survey\" },\n );\n trackEvent(EVENTS.ANALYSIS_FAILED, {\n error: error instanceof Error ? error.message : String(error),\n });\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Error: ${error instanceof Error ? error.message : String(error)}`,\n },\n ],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"list-rules\",\n \"List all available analysis rules with their current configuration\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"List Analysis Rules\",\n },\n async () => {\n const rules = ruleRegistry.getAll().map((rule) => {\n const config =\n RULE_CONFIGS[rule.definition.id as keyof typeof RULE_CONFIGS];\n return {\n id: rule.definition.id,\n name: rule.definition.name,\n category: rule.definition.category,\n severity: config?.severity,\n score: config?.score,\n enabled: config?.enabled,\n why: rule.definition.why,\n };\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify(rules, null, 2),\n },\n ],\n };\n },\n);\n\nserver.tool(\n \"version\",\n \"Get the current canicode version. Use this when the user asks what version is installed.\",\n {},\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Version\",\n },\n async () => ({\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}` }],\n }),\n);\n\nserver.tool(\n \"docs\",\n `Get documentation for CanICode.\n\nAvailable topics:\n- setup: Installation and token configuration\n- channels: Which canicode features are MCP tools vs skills vs CLI — call this when a user asks for a feature you can't find as an MCP tool\n- scoring: Scoring model formula (density+diversity, severity weights, grades)\n- rules: All rule IDs with default scores and severity\n- config: Config overrides (scores, severity, node exclusions, thresholds)\n- visual-compare: Pixel-level comparison between Figma and AI-generated code\n- design-tree: Generate DOM-like design tree from fixture for AI code generation\n- all: Full customization guide\n\nUse this when the user asks about how to use canicode, configuration, rules, visual comparison, or any feature.`,\n {\n topic: z.enum([\"all\", \"setup\", \"channels\", \"scoring\", \"rules\", \"config\", \"visual-compare\", \"design-tree\"]).optional()\n .describe(\"Topic to retrieve. Default: all\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: false,\n title: \"Get Documentation\",\n },\n async ({ topic }) => {\n const selectedTopic = topic ?? \"all\";\n\n // Inline topics (not from CUSTOMIZATION.md)\n const inlineTopics: Record<string, string> = {\n \"channels\": `# Channels — Where Each Feature Lives\n\ncanicode is delivered through three channels. Knowing which is which prevents the common confusion where an agent searches the MCP tool list for a feature that actually lives in a skill.\n\n| Feature | Channel | How to invoke |\n|---------|---------|---------------|\n| Analyze a Figma design | MCP tool / CLI | \\`analyze\\` (this server) or \\`npx canicode analyze <url>\\` |\n| Generate gotcha questions | MCP tool / CLI | \\`gotcha-survey\\` or \\`npx canicode gotcha-survey <url> --json\\` |\n| List rules / get docs / version | MCP tool | \\`list-rules\\`, \\`docs\\`, \\`version\\` |\n| Pixel-compare Figma vs HTML | MCP tool / CLI | \\`visual-compare\\` |\n| Q&A workflow that saves answers locally | **Skill** (slash command) | \\`/canicode-gotchas <url>\\` — install with \\`npx canicode init\\` |\n| Roundtrip: analyze → gotcha → write back to Figma → re-analyze | **Skill** (slash command) | \\`/canicode-roundtrip <url>\\` — install with \\`npx canicode init\\` |\n| Lightweight analyze-only skill (no MCP install) | **Skill** (slash command) | \\`/canicode <url>\\` — install with \\`npx canicode init\\` |\n\n**Skills are NOT MCP tools.** They are slash commands installed under \\`.claude/skills/\\` (Claude Code) or \\`.cursor/skills/\\` (Cursor). If \\`canicode-roundtrip\\` is not in the slash-command list, the skill isn't installed — run \\`npx canicode init\\` (or \\`--cursor-skills\\` for Cursor).\n\nThe roundtrip skill is the **only** path that writes back to the Figma file (via the Figma MCP server's \\`use_figma\\`). Don't try to compose roundtrip out of \\`analyze\\` + \\`gotcha-survey\\` MCP calls — the write-back orchestration lives inside the skill.`,\n\n \"setup\": `# Setup\n\n## CLI\n\\`\\`\\`bash\nnpm install -g canicode\ncanicode init --token figd_xxxxxxxxxxxxx\n\\`\\`\\`\n\nGet your token: Figma → Settings → Security → Personal access tokens → Generate new token\n\n## MCP Server (Claude Code / Cursor / Claude Desktop)\n\\`\\`\\`bash\nclaude mcp add canicode -- npx --yes --package=canicode canicode-mcp\n\\`\\`\\`\n\nRequires FIGMA_TOKEN for live Figma URL analysis. The MCP server reads it from \\`~/.canicode/config.json\\` (set via \\`canicode init --token …\\`) or from the host's environment, so do **not** pass \\`-e FIGMA_TOKEN=…\\` to \\`claude mcp add\\` — \\`@anthropic-ai/claude-code\\`'s current parser rejects short-form flags placed before \\`--\\`. (#364, #366)\n\n## CLI only (no MCP server)\n\nUser-facing MCP tools have CLI equivalents with the same JSON shape, so skills and scripts can run without installing the canicode MCP server:\n\n\\`\\`\\`bash\nnpx canicode analyze <input>\nnpx canicode gotcha-survey <input> --json\n\\`\\`\\`\n\nThe CLI spawns per call (slower than the long-running MCP server) but needs no extra setup beyond \\`FIGMA_TOKEN\\`.`,\n\n \"visual-compare\": `# Visual Compare\n\nPixel-level comparison between Figma design and AI-generated code.\n\n## Usage\n\\`\\`\\`bash\ncanicode visual-compare ./index.html --figma-url 'https://www.figma.com/design/ABC/File?node-id=1-234'\n\\`\\`\\`\n\n## Options\n| Option | Default | Description |\n|--------|---------|-------------|\n| --figma-url <url> | (required) | Figma URL with node-id |\n| --token <token> | FIGMA_TOKEN env | Figma API token |\n| --output <dir> | /tmp/canicode-visual-compare | Output directory |\n| --width <px> | (inferred from Figma PNG ÷ scale) | Logical viewport width in CSS px |\n| --height <px> | (inferred from Figma PNG ÷ scale) | Logical viewport height in CSS px |\n| --figma-scale <n> | 2 | Figma export scale (matches @2x fixture PNGs) |\n\nViewport and device pixel ratio are auto-inferred from the Figma PNG dimensions and export scale. Override only when needed.\n\n## Output Files\n/tmp/canicode-visual-compare/\n figma.png — Figma screenshot (at export scale, default @2x)\n code.png — Playwright render of your HTML\n diff.png — Pixel diff (red = different)\n\n## JSON Output (stdout)\n{\n \"similarity\": 87,\n \"diffPixels\": 1340,\n \"totalPixels\": 102400,\n \"width\": 800, \"height\": 600,\n \"figmaScreenshot\": \"...\", \"codeScreenshot\": \"...\", \"diff\": \"...\"\n}\n\n## How It Works\n1. Fetches Figma screenshot via REST API (scale=2)\n2. Reads screenshot dimensions\n3. Renders HTML with Playwright at same viewport size\n4. Compares pixel-by-pixel with pixelmatch (threshold: 0.1)\n\n## Requirements\n- npx playwright install chromium\n- Figma API token with read access`,\n\n \"scoring\": `# Scoring Model\n\nScore = density (70%) + diversity (30%), averaged across 6 categories.\n\n## Severity weights\n\n| Severity | Weight |\n|----------|--------|\n| blocking | 3.0x |\n| risk | 2.0x |\n| missing-info | 1.0x |\n| suggestion | 0.5x |\n\n## Grades\n\n| Grade | Min score |\n|-------|-----------|\n| S | 95 |\n| A+ | 90 |\n| A | 85 |\n| B+ | 80 |\n| B | 75 |\n| C+ | 70 |\n| C | 65 |\n| D | 50 |\n| F | <50 |\n\nFloor: 5% minimum.\n\nFull documentation: https://github.com/let-sunny/canicode/wiki/Scoring-Model`,\n\n \"design-tree\": `# Design Tree\n\nGenerate a DOM-like design tree from a Figma fixture. Converts the node tree to a concise text format with inline CSS styles — 50-100x smaller than raw JSON.\n\n## Usage\n\\`\\`\\`bash\ncanicode design-tree ./fixtures/design\ncanicode design-tree ./fixtures/design --output tree.txt\ncanicode design-tree \"https://www.figma.com/design/ABC/File?node-id=1-234\"\n\\`\\`\\`\n\n## Output Format\nEach node = one line with name, type, dimensions, followed by CSS-ready styles:\n\\`\\`\\`\nHero Form (INSTANCE, 375x960)\n style: display: flex; flex-direction: column; gap: 32px; padding: 160px 24px; background: #F5F5F5\n Title (TEXT, 117x58)\n style: font-family: \"Inter\"; font-weight: 700; font-size: 48px; color: #2C2C2C; text: \"Title\"\n\\`\\`\\`\n\n## Use Cases\n- AI code generation — feed this to an LLM instead of raw 250KB fixture JSON\n- Calibration pipeline — Converter uses this for accurate code reproduction\n- Debugging — quickly see the design structure and styles`,\n };\n\n // Check inline topics first\n if (selectedTopic in inlineTopics) {\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${inlineTopics[selectedTopic]}` }],\n };\n }\n\n // Fall back to CUSTOMIZATION.md for config/rules/all\n const { readFile } = await import(\"node:fs/promises\");\n const { resolve, dirname } = await import(\"node:path\");\n const { fileURLToPath } = await import(\"node:url\");\n\n try {\n const __dirname = dirname(fileURLToPath(import.meta.url));\n const docPath = resolve(__dirname, \"../../docs/CUSTOMIZATION.md\");\n let content: string;\n\n try {\n content = await readFile(docPath, \"utf-8\");\n } catch {\n const altPath = resolve(__dirname, \"../docs/CUSTOMIZATION.md\");\n content = await readFile(altPath, \"utf-8\");\n }\n\n if (selectedTopic !== \"all\") {\n const sections: Record<string, string> = {\n \"config\": \"## Config Overrides\",\n \"rules\": \"### All Rule IDs\",\n };\n const header = sections[selectedTopic];\n if (header) {\n const startIdx = content.indexOf(header);\n if (startIdx !== -1) {\n const nextH2 = content.indexOf(\"\\n## \", startIdx + header.length);\n content = nextH2 !== -1\n ? content.slice(startIdx, nextH2)\n : content.slice(startIdx);\n }\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: `canicode v${pkg.version}\\n\\n${content}` }],\n };\n } catch {\n return {\n content: [{ type: \"text\" as const, text: \"Documentation not found. See: https://github.com/let-sunny/canicode\" }],\n isError: true,\n };\n }\n },\n);\n\nserver.tool(\n \"visual-compare\",\n `Compare AI-generated code against a Figma design at the pixel level.\n\nTakes an HTML file path and a Figma URL, renders the HTML with Playwright,\nfetches the Figma screenshot, and computes pixel-level similarity using pixelmatch.\n\nReturns similarity percentage (0-100%), diff pixel count, and paths to\nthe Figma screenshot, code screenshot, and diff image.\n\nLogical viewport and device pixel ratio are inferred from the Figma PNG export scale (default 2×) so code.png matches figma.png pixels.\n\nRequires: Playwright with Chromium installed, Figma API token.`,\n {\n codePath: z.string().describe(\"Path to the HTML file to render and compare\"),\n figmaUrl: z.string().describe(\"Figma URL with node-id (e.g., https://www.figma.com/design/ABC/File?node-id=1-234)\"),\n token: z.string().optional().describe(\"Figma API token (falls back to FIGMA_TOKEN env var)\"),\n outputDir: z.string().optional().describe(\"Output directory for screenshots (default: /tmp/canicode-visual-compare)\"),\n figmaExportScale: z.number().int().min(1).max(4).optional().describe(\"Figma export scale (default 2, matches @2x fixture PNGs)\"),\n },\n {\n readOnlyHint: true,\n destructiveHint: false,\n openWorldHint: true,\n title: \"Visual Compare\",\n },\n async ({ codePath, figmaUrl, token, outputDir, figmaExportScale }) => {\n try {\n const { visualCompare } = await import(\"../core/comparison/visual-compare.js\");\n const figmaToken = token ?? process.env[\"FIGMA_TOKEN\"];\n if (!figmaToken) {\n return {\n content: [{ type: \"text\" as const, text: \"Error: Figma token required. Provide via token parameter or FIGMA_TOKEN env var.\" }],\n isError: true,\n };\n }\n\n const result = await visualCompare({\n figmaUrl,\n figmaToken,\n codePath,\n outputDir,\n ...(figmaExportScale !== undefined ? { figmaExportScale } : {}),\n });\n\n return {\n content: [{\n type: \"text\" as const,\n text: JSON.stringify({\n similarity: result.similarity,\n diffPixels: result.diffPixels,\n totalPixels: result.totalPixels,\n width: result.width,\n height: result.height,\n figmaScreenshot: result.figmaScreenshotPath,\n codeScreenshot: result.codeScreenshotPath,\n diff: result.diffPath,\n }, null, 2),\n }],\n };\n } catch (error) {\n return {\n content: [{ type: \"text\" as const, text: `Error: ${error instanceof Error ? error.message : String(error)}` }],\n isError: true,\n };\n }\n },\n);\n\nasync function main() {\n const monitoringConfig: Parameters<typeof initMonitoring>[0] = {\n environment: \"mcp\",\n version: pkg.version,\n enabled: getTelemetryEnabled(),\n };\n const phKey = getPosthogApiKey() || BUILTIN_PH_KEY;\n if (phKey) monitoringConfig.posthogApiKey = phKey;\n const sDsn = getSentryDsn() || BUILTIN_SENTRY_DSN;\n if (sDsn) monitoringConfig.sentryDsn = sDsn;\n monitoringConfig.distinctId = getDeviceId();\n initMonitoring(monitoringConfig);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\nprocess.on(\"beforeExit\", () => {\n shutdownMonitoring();\n});\n\nmain().catch(console.error);\n"]}