@getchomp/mcp 0.0.0-stage → 0.2.43

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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +15 -2
  3. package/dist/conventionsReference.d.ts +84 -0
  4. package/dist/conventionsReference.js +313 -0
  5. package/dist/designSystem/astScanner.d.ts +153 -0
  6. package/dist/designSystem/astScanner.js +2014 -0
  7. package/dist/designSystem/baseline.d.ts +65 -0
  8. package/dist/designSystem/baseline.js +136 -0
  9. package/dist/designSystem/color.d.ts +35 -0
  10. package/dist/designSystem/color.js +265 -0
  11. package/dist/designSystem/config.d.ts +183 -0
  12. package/dist/designSystem/config.js +469 -0
  13. package/dist/designSystem/contrast.d.ts +55 -0
  14. package/dist/designSystem/contrast.js +377 -0
  15. package/dist/designSystem/cssParser.d.ts +63 -0
  16. package/dist/designSystem/cssParser.js +469 -0
  17. package/dist/designSystem/merges.d.ts +57 -0
  18. package/dist/designSystem/merges.js +94 -0
  19. package/dist/designSystem/preprocessors.d.ts +46 -0
  20. package/dist/designSystem/preprocessors.js +1108 -0
  21. package/dist/designSystem/presentation.d.ts +45 -0
  22. package/dist/designSystem/presentation.js +796 -0
  23. package/dist/designSystem/styleVectors.d.ts +27 -0
  24. package/dist/designSystem/styleVectors.js +484 -0
  25. package/dist/designSystem/tokens.d.ts +39 -0
  26. package/dist/designSystem/tokens.js +409 -0
  27. package/dist/designSystem/topology.d.ts +64 -0
  28. package/dist/designSystem/topology.js +254 -0
  29. package/dist/designSystem/types.d.ts +857 -0
  30. package/dist/designSystem/types.js +113 -0
  31. package/dist/designSystem/typography.d.ts +25 -0
  32. package/dist/designSystem/typography.js +244 -0
  33. package/dist/designSystem/uiShapes.d.ts +74 -0
  34. package/dist/designSystem/uiShapes.js +285 -0
  35. package/dist/designSystem/valueClusters.d.ts +76 -0
  36. package/dist/designSystem/valueClusters.js +281 -0
  37. package/dist/designSystemPlugin.d.ts +321 -0
  38. package/dist/designSystemPlugin.js +4730 -0
  39. package/dist/enrichNodesPlugin.d.ts +160 -0
  40. package/dist/enrichNodesPlugin.js +957 -0
  41. package/dist/index.d.ts +65 -0
  42. package/dist/index.js +1298 -0
  43. package/dist/intelligence.d.ts +502 -0
  44. package/dist/intelligence.js +3058 -0
  45. package/dist/pluginRunner.d.ts +364 -0
  46. package/dist/pluginRunner.js +1096 -0
  47. package/dist/plugins/design-system/index.d.ts +14 -0
  48. package/dist/plugins/design-system/index.js +241 -0
  49. package/dist/plugins/enrich-nodes/index.d.ts +388 -0
  50. package/dist/plugins/enrich-nodes/index.js +697 -0
  51. package/dist/plugins/index.d.ts +15 -0
  52. package/dist/plugins/index.js +20 -0
  53. package/dist/plugins/local-shims/index.d.ts +121 -0
  54. package/dist/plugins/local-shims/index.js +237 -0
  55. package/dist/shimsPlugin.d.ts +134 -0
  56. package/dist/shimsPlugin.js +1392 -0
  57. package/package.json +39 -3
@@ -0,0 +1,4730 @@
1
+ /**
2
+ * packages/mcp/src/designSystemPlugin.ts
3
+ *
4
+ * Design System & Frontend Agent Plugin (`L1_DESIGN_SYSTEM` / `source: 'design-system'`)
5
+ * Enforces [PAT-DB-03], [PAT-DB-05], [PAT-VIS-13], [PAT-VIS-21], [PAT-MCP-08], [PAT-MCP-09].
6
+ *
7
+ * Repo-agnostic, deterministic static analysis plugin for **frontend packages only** (detected
8
+ * from `package.json` dependencies, or listed in `chomp.config.json` → `designSystem.scope`).
9
+ *
10
+ * Nothing here assumes a particular repo's naming. The system is either *derived from the code*
11
+ * (`extract` mode) or *declared in `chomp.config.json`* (`adhere` mode) — see
12
+ * `designSystem/config.ts`. Capabilities:
13
+ * 1. Parses `.css` stylesheets (`:root`, theme selectors, `@theme`, `@property`, CSS nesting) to
14
+ * inventory tokens and derives their tiers from the token reference graph; detects undefined
15
+ * `var(--*)` leaks, duplicate/forked declarations, unused tokens, and WCAG 2.1 contrast across
16
+ * dark/light themes (hex, rgb, hsl, oklch…) — reporting un-evaluable pairs explicitly.
17
+ * 2. Scans React/TSX/TS components for styling convention mix, arbitrary Tailwind, raw palette
18
+ * use, hardcoded color/length literals (CSS, TS, JSX props, inline styles) and **clusters them
19
+ * into candidate tokens**; checks prop-literal invariants and atom composability.
20
+ * 3. Derives the atomic hierarchy, parallel-twin components (with a proposed merged prop API),
21
+ * structural/compositional JSX clones, and shared-atom adoption.
22
+ * 4. Provides the Closed-Loop Frontend Agent Gate (`auditDesignSystem` and `diffDesignSystem`)
23
+ * against a pinned baseline snapshot ("Query Before Write, Diff After Write").
24
+ */
25
+ import { createHash } from "node:crypto";
26
+ import { basename, dirname, posix as posixPath, resolve } from "node:path";
27
+ import { analyzeTarget } from "@getchomp/core";
28
+ import { packageMatchesFilter } from "./intelligence.js";
29
+ import { loadPluginSettings, resolveRepoName, runChompPlugin, } from "./pluginRunner.js";
30
+ import { TAILWIND_DEFAULT_PALETTES, isTailwindUtilityToken, scanTsxOrTsFile, } from "./designSystem/astScanner.js";
31
+ import { checkWorkingTreeClean, countFindings, diffFindings, findingKey, readBaselineSnapshot, resolveBaselinePath, totalsByCategory, writeBaselineSnapshot, } from "./designSystem/baseline.js";
32
+ import { compositeOver, parseCssColorString, rgbaToHex, toOklab, oklabDistance, } from "./designSystem/color.js";
33
+ import { compileRegexes, detectFrontendScope, globToRegExp, resolveDesignSystemConfig, } from "./designSystem/config.js";
34
+ import { CANVAS_TOKEN_PROBES, evaluateContrast, normalizeBareHsl, parseColorWithAlphaSyntax, resolveThemeTokenColor, substituteVars, } from "./designSystem/contrast.js";
35
+ import { parseCssStylesheet, } from "./designSystem/cssParser.js";
36
+ import { readMergeDecisions } from "./designSystem/merges.js";
37
+ import { deriveComponentNameFromPath, detectStylesheetSyntax, extractEmbeddedStyleBlocks, isPreprocessedUiComponentFile, isSupportedStylesheetFile, preprocessUiComponentToTsx, } from "./designSystem/preprocessors.js";
38
+ import { attachDesignSystemPresentations } from "./designSystem/presentation.js";
39
+ import { buildTokenLookupMaps, computeStyleVectorDeltas, resolveComponentStyleVector, } from "./designSystem/styleVectors.js";
40
+ import { analyzeTokenLineageAndSymmetry, computeLiveReferencedTokens, deriveTokenTiers, isScaleStepTokenName, } from "./designSystem/tokens.js";
41
+ import { UNSUPPORTED_UI_EXTENSIONS, classifyAtomicTier, cleanNodeDisplayLabel, computeSubtreeHealth, getPrimaryNodeEvidence, inferSuggestedComponentName, matchUiRoleConvention, matchesDynamicPrefix, resolveAtomCatalog, } from "./designSystem/topology.js";
42
+ import { analyzeTypographyAndContextualOverrides } from "./designSystem/typography.js";
43
+ import { analyzeUiShapesAndSiblingOverlaps, isAuthorizedAtomOwner, resolveCanonicalAtomsByTarget, } from "./designSystem/uiShapes.js";
44
+ import { clusterLiteralValues, extractColorLiterals, extractLengthLiterals, parseCssLengthToPx, } from "./designSystem/valueClusters.js";
45
+ export * from "./designSystem/types.js";
46
+ export { classifyTokenTier, parseCssStylesheet, } from "./designSystem/cssParser.js";
47
+ export { computeRelativeLuminance, computeWcagContrastRatio, evaluateContrast, evaluateThemeContrastPairs, parseCssColorString, } from "./designSystem/contrast.js";
48
+ export { scanTsxOrTsFile, } from "./designSystem/astScanner.js";
49
+ export { classifyAtomicTier, computeSubtreeHealth, matchUiRoleConvention, resolveAtomCatalog, } from "./designSystem/topology.js";
50
+ export { buildTokenLookupMaps, computeStyleVectorDeltas, resolveComponentStyleVector, } from "./designSystem/styleVectors.js";
51
+ export { analyzeTypographyAndContextualOverrides } from "./designSystem/typography.js";
52
+ export { analyzeUiShapesAndSiblingOverlaps, isAuthorizedAtomOwner, resolveCanonicalAtomsByTarget, } from "./designSystem/uiShapes.js";
53
+ export { analyzeTokenLineageAndSymmetry, computeLiveReferencedTokens, deriveTokenTiers, isScaleStepTokenName, } from "./designSystem/tokens.js";
54
+ function isBareColorOrScaleValue(value) {
55
+ return parseCssColorString(value) !== null;
56
+ }
57
+ export function analyzeRepositoryDesignSystem(ctx, analyzeOptions = {}) {
58
+ const resolved = analyzeOptions.resolvedConfig ??
59
+ resolveDesignSystemConfig(ctx.repoPath, analyzeOptions.configOverrides);
60
+ const config = resolved.config;
61
+ const themeRes = {
62
+ dark: compileRegexes(config.themes.dark),
63
+ light: compileRegexes(config.themes.light),
64
+ };
65
+ // 0. Frontend scope: only frontend packages are audited (detected from package.json or configured)
66
+ const excludeFileRes = compileRegexes(config.scope.excludeFiles);
67
+ const scope = detectFrontendScope(ctx.files, ctx.readFile, config);
68
+ const inScopeFiles = ctx.files.filter((f) => scope.includeFile(f) && !excludeFileRes.some((re) => re.test(f)));
69
+ const cssFiles = inScopeFiles.filter((f) => isSupportedStylesheetFile(f));
70
+ const uiComponentFiles = inScopeFiles.filter((f) => isPreprocessedUiComponentFile(f));
71
+ const codeFiles = inScopeFiles.filter((f) => (f.endsWith(".tsx") ||
72
+ f.endsWith(".ts") ||
73
+ f.endsWith(".jsx") ||
74
+ f.endsWith(".js")) &&
75
+ !f.endsWith(".d.ts"));
76
+ const unsupportedByExt = new Map();
77
+ for (const f of inScopeFiles) {
78
+ const ext = UNSUPPORTED_UI_EXTENSIONS.find((e) => f.endsWith(e));
79
+ if (!ext)
80
+ continue;
81
+ let list = unsupportedByExt.get(ext);
82
+ if (!list) {
83
+ list = [];
84
+ unsupportedByExt.set(ext, list);
85
+ }
86
+ list.push(f);
87
+ }
88
+ const atomDefinitions = resolveAtomCatalog(config);
89
+ // 1. Parse all `.css` / `.scss` / `.less` files plus embedded `<style>` blocks in `.vue` / `.svelte` / `.astro` / `.mdx`
90
+ const parsedCssList = [];
91
+ const cssInputDeps = [];
92
+ const seenCssDepPaths = new Set();
93
+ const addCssDep = (filePath) => {
94
+ if (seenCssDepPaths.has(filePath))
95
+ return;
96
+ const dep = ctx.hashFile(filePath);
97
+ if (dep) {
98
+ seenCssDepPaths.add(filePath);
99
+ cssInputDeps.push(dep);
100
+ }
101
+ };
102
+ for (const cssFile of cssFiles) {
103
+ const content = ctx.readFile(cssFile);
104
+ if (content === null)
105
+ continue;
106
+ parsedCssList.push(parseCssStylesheet(cssFile, content, {
107
+ themes: themeRes,
108
+ tiers: config.tokens.tiers,
109
+ syntax: detectStylesheetSyntax(cssFile),
110
+ }));
111
+ addCssDep(cssFile);
112
+ }
113
+ const uiRawContents = new Map();
114
+ for (const uiFile of uiComponentFiles) {
115
+ const content = ctx.readFile(uiFile);
116
+ if (content === null)
117
+ continue;
118
+ uiRawContents.set(uiFile, content);
119
+ const styleBlocks = extractEmbeddedStyleBlocks(uiFile, content);
120
+ for (const block of styleBlocks) {
121
+ parsedCssList.push(parseCssStylesheet(uiFile, block.paddedCssText, {
122
+ themes: themeRes,
123
+ tiers: config.tokens.tiers,
124
+ syntax: block.syntax,
125
+ defaultScoped: block.defaultScoped,
126
+ }));
127
+ }
128
+ if (styleBlocks.length > 0) {
129
+ addCssDep(uiFile);
130
+ }
131
+ }
132
+ // Class names & Tailwind v4 `@theme` surface metadata derived from the repo's stylesheets
133
+ const knownCssClasses = new Set();
134
+ const definedCssClasses = new Set();
135
+ const knownThemeColorSlugs = new Set();
136
+ const bridgeTextSizeCandidates = new Set();
137
+ const knownThemeSpacingSteps = new Set();
138
+ for (const sheet of parsedCssList) {
139
+ for (const cls of sheet.definedClasses) {
140
+ knownCssClasses.add(cls);
141
+ definedCssClasses.add(cls);
142
+ }
143
+ for (const rule of sheet.styleRules) {
144
+ for (const cls of rule.classesInSelector) {
145
+ knownCssClasses.add(cls);
146
+ definedCssClasses.add(cls);
147
+ }
148
+ }
149
+ for (const decl of sheet.tokenDeclarations) {
150
+ if (decl.scope === "scoped")
151
+ continue;
152
+ if (decl.name.startsWith("--text-color-")) {
153
+ knownThemeColorSlugs.add(decl.name.slice("--text-color-".length));
154
+ }
155
+ else if (decl.name.startsWith("--background-color-")) {
156
+ knownThemeColorSlugs.add(decl.name.slice("--background-color-".length));
157
+ }
158
+ else if (decl.name.startsWith("--color-")) {
159
+ knownThemeColorSlugs.add(decl.name.slice("--color-".length));
160
+ }
161
+ else if (decl.themeContext === "theme-bridge" && decl.name.startsWith("--text-")) {
162
+ bridgeTextSizeCandidates.add(decl.name.slice("--text-".length));
163
+ }
164
+ else if (decl.name.startsWith("--spacing-")) {
165
+ knownThemeSpacingSteps.add(decl.name.slice("--spacing-".length));
166
+ }
167
+ else if (decl.name.startsWith("--") &&
168
+ (isBareColorOrScaleValue(decl.value) || decl.referencedVars.length > 0) &&
169
+ !/font|text-size|leading|tracking|radius|space|spacing|geom|width|height|shadow|z-/.test(decl.name)) {
170
+ knownThemeColorSlugs.add(decl.name.slice(2));
171
+ }
172
+ }
173
+ }
174
+ const nonColorThemeTextSlugs = new Set([...bridgeTextSizeCandidates].filter((slug) => !knownThemeColorSlugs.has(slug)));
175
+ // 3. Scan all in-scope TS/TSX and preprocessed `.vue`/`.svelte`/`.astro`/`.mdx` files via AST
176
+ const scanOpts = {
177
+ knownCssClasses,
178
+ cssClassPrefixes: config.styling.cssClassPrefixes,
179
+ atomDefinitions,
180
+ colorPropPattern: config.invariants.colorPropPattern,
181
+ canvasSlotRecorderFactories: config.styling.canvas.slotRecorderFactories,
182
+ canvasCssValueHelpers: config.styling.canvas.cssValueHelpers,
183
+ canvasTokenReaderHelpers: config.styling.canvas.tokenReaderHelpers,
184
+ knownThemeColorSlugs,
185
+ nonColorThemeTextSlugs,
186
+ knownThemeSpacingSteps,
187
+ };
188
+ const scannedFiles = new Map();
189
+ for (const file of codeFiles) {
190
+ const content = ctx.readFile(file);
191
+ if (content === null)
192
+ continue;
193
+ scannedFiles.set(file, scanTsxOrTsFile(file, content, scanOpts));
194
+ }
195
+ for (const [uiFile, rawContent] of uiRawContents.entries()) {
196
+ const tsxSource = preprocessUiComponentToTsx(uiFile, rawContent);
197
+ scannedFiles.set(uiFile, scanTsxOrTsFile(uiFile, tsxSource, scanOpts));
198
+ }
199
+ // 4. Aggregate all defined tokens (`.css` + JS/TS CSS custom property variables)
200
+ const allTokenDecls = [];
201
+ for (const sheet of parsedCssList) {
202
+ allTokenDecls.push(...sheet.tokenDeclarations);
203
+ }
204
+ for (const scanned of scannedFiles.values()) {
205
+ for (const fv of scanned.definedFontVars) {
206
+ allTokenDecls.push({
207
+ name: fv.name,
208
+ value: fv.fontFamily ?? "runtime-font",
209
+ tier: fv.scope === "scoped" ? "component" : "primitive",
210
+ themeContext: "root",
211
+ selector: "js-variable",
212
+ filePath: scanned.filePath,
213
+ lineNumber: fv.lineNumber,
214
+ referencedVars: [],
215
+ scope: fv.scope ?? "global",
216
+ });
217
+ }
218
+ }
219
+ // 4a. Derive token tiers from the reference graph (explicit config regexes always win)
220
+ const derivedTiers = deriveTokenTiers(allTokenDecls, config.tokens.tiers);
221
+ const tierSources = {
222
+ config: 0,
223
+ derived: 0,
224
+ scoped: 0,
225
+ "theme-bridge": 0,
226
+ };
227
+ for (const [, t] of derivedTiers)
228
+ tierSources[t.source]++;
229
+ for (const d of allTokenDecls) {
230
+ const t = derivedTiers.get(d.name);
231
+ if (t)
232
+ d.tier = t.tier;
233
+ }
234
+ const tokenLineage = analyzeTokenLineageAndSymmetry(allTokenDecls, derivedTiers);
235
+ const tokenMaps = buildTokenLookupMaps(allTokenDecls);
236
+ const definedTokenNames = new Set(allTokenDecls.map((d) => d.name));
237
+ const primitiveTokens = new Set();
238
+ const semanticTokens = new Set();
239
+ const componentTokens = new Set();
240
+ const themeBridgeTokens = new Set();
241
+ for (const decl of allTokenDecls) {
242
+ if (decl.themeContext === "theme-bridge") {
243
+ themeBridgeTokens.add(decl.name);
244
+ }
245
+ else if (decl.tier === "primitive") {
246
+ primitiveTokens.add(decl.name);
247
+ }
248
+ else if (decl.tier === "component") {
249
+ componentTokens.add(decl.name);
250
+ }
251
+ else {
252
+ semanticTokens.add(decl.name);
253
+ }
254
+ }
255
+ // 4b. Adhere mode: which tokens are declared inside / outside the declared system sources
256
+ const tokenSourceRes = config.tokens.sources.map((g) => globToRegExp(g));
257
+ const isSystemSourceFile = (f) => tokenSourceRes.some((re) => re.test(f));
258
+ const tokensOutsideSystem = [];
259
+ if (resolved.mode === "adhere" && tokenSourceRes.length > 0) {
260
+ const systemNames = new Set(allTokenDecls.filter((d) => isSystemSourceFile(d.filePath)).map((d) => d.name));
261
+ const seenOutside = new Set();
262
+ for (const d of allTokenDecls) {
263
+ if (systemNames.has(d.name) || d.scope === "scoped" || d.selector === "js-variable")
264
+ continue;
265
+ if (seenOutside.has(d.name))
266
+ continue;
267
+ seenOutside.add(d.name);
268
+ tokensOutsideSystem.push({ name: d.name, filePath: d.filePath, lineNumber: d.lineNumber });
269
+ }
270
+ }
271
+ // 4c. Raw palettes, derived from the repo's own token layers: palette P is a "raw primitive" palette
272
+ // when a semantic/component token aliases one of its steps (`--accent: var(--yellow-9)`), i.e. the
273
+ // system routes P through a semantic layer. Config can add / remove palettes.
274
+ const aliasedByHigherTier = new Map();
275
+ for (const d of allTokenDecls) {
276
+ if (d.scope === "scoped" || d.tier === "primitive")
277
+ continue;
278
+ if (isScaleStepTokenName(d.name))
279
+ continue; // pass-through bridge (`--color-yellow-9: var(--yellow-9)`)
280
+ for (const ref of d.referencedVars) {
281
+ let list = aliasedByHigherTier.get(ref);
282
+ if (!list) {
283
+ list = [];
284
+ aliasedByHigherTier.set(ref, list);
285
+ }
286
+ if (!list.includes(d.name))
287
+ list.push(d.name);
288
+ }
289
+ }
290
+ const rawPalettes = new Set();
291
+ const primitiveColorTokenNames = new Set();
292
+ for (const d of allTokenDecls) {
293
+ if (d.scope === "scoped" || d.tier !== "primitive")
294
+ continue;
295
+ const isExplicitScale = isScaleStepTokenName(d.name);
296
+ if (!aliasedByHigherTier.has(d.name) && !isExplicitScale)
297
+ continue;
298
+ if (isBareColorOrScaleValue(d.value) || isExplicitScale) {
299
+ const m = d.name.match(/^--(?:color-)?([a-z][a-z-]*?)-(\d{1,4})$/i);
300
+ const isColorScale = isBareColorOrScaleValue(d.value);
301
+ if (isColorScale || aliasedByHigherTier.has(d.name)) {
302
+ primitiveColorTokenNames.add(d.name);
303
+ }
304
+ if (m && isColorScale)
305
+ rawPalettes.add(m[1].toLowerCase());
306
+ }
307
+ }
308
+ for (const p of config.styling.tailwind.rawPalettes)
309
+ rawPalettes.add(p.toLowerCase());
310
+ if (config.styling.tailwind.defaultPalette === "flag") {
311
+ for (const p of TAILWIND_DEFAULT_PALETTES)
312
+ rawPalettes.add(p);
313
+ }
314
+ for (const p of config.styling.tailwind.allowedPalettes)
315
+ rawPalettes.delete(p.toLowerCase());
316
+ const semanticSuggestionFor = (primitiveName) => {
317
+ if (!primitiveName)
318
+ return undefined;
319
+ const aliases = aliasedByHigherTier.get(primitiveName);
320
+ return aliases && aliases.length > 0
321
+ ? `${aliases.slice(0, 3).join(" / ")} (aliases ${primitiveName})`
322
+ : undefined;
323
+ };
324
+ // 5. Aggregate all token references across CSS and TS/TSX (+ Tailwind v4 `@theme` utilities)
325
+ const themeBridgeColorSlugs = new Map();
326
+ const themeBridgeTextColorSlugs = new Map();
327
+ const themeBridgeTextSizeSlugs = new Map();
328
+ const themeBridgeFontSlugs = new Map();
329
+ const themeBridgeRadiusSlugs = new Map();
330
+ const themeBridgeSpacingSlugs = new Map();
331
+ const themeBridgeShadowSlugs = new Map();
332
+ const addBridgeSlug = (map, slug, decl) => {
333
+ const tokens = [decl.name, ...decl.referencedVars.filter((r) => definedTokenNames.has(r))];
334
+ const prev = map.get(slug) ?? [];
335
+ for (const t of tokens) {
336
+ if (!prev.includes(t))
337
+ prev.push(t);
338
+ }
339
+ map.set(slug, prev);
340
+ };
341
+ for (const decl of allTokenDecls) {
342
+ if (decl.themeContext !== "theme-bridge")
343
+ continue;
344
+ if (decl.name.startsWith("--text-color-")) {
345
+ addBridgeSlug(themeBridgeTextColorSlugs, decl.name.slice("--text-color-".length), decl);
346
+ }
347
+ else if (decl.name.startsWith("--text-")) {
348
+ addBridgeSlug(themeBridgeTextSizeSlugs, decl.name.slice("--text-".length), decl);
349
+ }
350
+ else if (decl.name.startsWith("--color-")) {
351
+ addBridgeSlug(themeBridgeColorSlugs, decl.name.slice("--color-".length), decl);
352
+ }
353
+ else if (decl.name.startsWith("--font-")) {
354
+ addBridgeSlug(themeBridgeFontSlugs, decl.name.slice("--font-".length), decl);
355
+ }
356
+ else if (decl.name.startsWith("--radius-")) {
357
+ addBridgeSlug(themeBridgeRadiusSlugs, decl.name.slice("--radius-".length), decl);
358
+ }
359
+ else if (decl.name.startsWith("--spacing-")) {
360
+ addBridgeSlug(themeBridgeSpacingSlugs, decl.name.slice("--spacing-".length), decl);
361
+ }
362
+ else if (decl.name.startsWith("--shadow-")) {
363
+ addBridgeSlug(themeBridgeShadowSlugs, decl.name.slice("--shadow-".length), decl);
364
+ }
365
+ }
366
+ const resolveTailwindUtilityTokens = (rawClass) => {
367
+ const base = (rawClass.split(":").pop() ?? rawClass).split("/")[0];
368
+ if (!base)
369
+ return [];
370
+ if (base.startsWith("text-")) {
371
+ const slug = base.slice("text-".length);
372
+ const tcHit = themeBridgeTextColorSlugs.get(slug);
373
+ if (tcHit)
374
+ return tcHit;
375
+ const tsHit = themeBridgeTextSizeSlugs.get(slug);
376
+ if (tsHit)
377
+ return tsHit;
378
+ }
379
+ const colorMatch = base.match(/^(?:bg|text|border|border-[trblxy]|ring|outline|fill|stroke|from|via|to|divide|placeholder|caret|accent|decoration)-([a-z0-9-]+)$/);
380
+ if (colorMatch) {
381
+ const hit = themeBridgeColorSlugs.get(colorMatch[1]);
382
+ if (hit)
383
+ return hit;
384
+ }
385
+ if (base.startsWith("font-")) {
386
+ const hit = themeBridgeFontSlugs.get(base.slice("font-".length));
387
+ if (hit)
388
+ return hit;
389
+ }
390
+ const radiusMatch = base.match(/^rounded(?:-[trblxy]|-[tb][lr])?-([a-z0-9-]+)$/);
391
+ if (radiusMatch) {
392
+ const hit = themeBridgeRadiusSlugs.get(radiusMatch[1]);
393
+ if (hit)
394
+ return hit;
395
+ }
396
+ const spaceMatch = base.match(/^(?:(?:min|max)-)?(?:p|px|py|pt|pr|pb|pl|m|mx|my|mt|mr|mb|ml|gap|gap-x|gap-y|space-x|space-y|w|h|size|inset|top|right|bottom|left)-([a-z0-9-]+)$/);
397
+ if (spaceMatch) {
398
+ const hit = themeBridgeSpacingSlugs.get(spaceMatch[1]);
399
+ if (hit)
400
+ return hit;
401
+ }
402
+ if (base.startsWith("shadow-")) {
403
+ const hit = themeBridgeShadowSlugs.get(base.slice("shadow-".length));
404
+ if (hit)
405
+ return hit;
406
+ }
407
+ return [];
408
+ };
409
+ const bridgedTokensByBucket = new Map();
410
+ const allTokenRefs = [];
411
+ for (const sheet of parsedCssList) {
412
+ allTokenRefs.push(...sheet.varReferences);
413
+ }
414
+ for (const scanned of scannedFiles.values()) {
415
+ allTokenRefs.push(...scanned.tokenReferences);
416
+ for (const bucket of scanned.functionsAndClasses.values()) {
417
+ const bucketKey = `${scanned.filePath}::${bucket.name}`;
418
+ let bSet = bridgedTokensByBucket.get(bucketKey);
419
+ for (const tw of bucket.tailwindClassesUsed) {
420
+ const matchedTokens = resolveTailwindUtilityTokens(tw.className);
421
+ if (matchedTokens.length === 0)
422
+ continue;
423
+ if (!bSet) {
424
+ bSet = new Set();
425
+ bridgedTokensByBucket.set(bucketKey, bSet);
426
+ }
427
+ for (const tokName of matchedTokens) {
428
+ bSet.add(tokName);
429
+ allTokenRefs.push({
430
+ name: tokName,
431
+ filePath: scanned.filePath,
432
+ lineNumber: tw.lineNumber,
433
+ snippet: tw.snippet,
434
+ kind: "tailwind-theme",
435
+ consumerLabel: bucket.name === "__module__" ? undefined : bucket.name,
436
+ });
437
+ }
438
+ }
439
+ }
440
+ }
441
+ const externalPrefixes = config.tokens.externalPrefixes;
442
+ // 6. Compute Undefined `var(--*)` Leaks
443
+ const undefinedByName = new Map();
444
+ for (const ref of allTokenRefs) {
445
+ // `var(--x, fallback)` hooks and third-party-owned prefixes (`--tw-*`, `--radix-*`) are not leaks.
446
+ if (ref.hasFallback)
447
+ continue;
448
+ if (externalPrefixes.some((p) => ref.name.startsWith(p)))
449
+ continue;
450
+ if (!definedTokenNames.has(ref.name)) {
451
+ let list = undefinedByName.get(ref.name);
452
+ if (!list) {
453
+ list = [];
454
+ undefinedByName.set(ref.name, list);
455
+ }
456
+ if (!list.some((item) => item.filePath === ref.filePath && item.lineNumber === ref.lineNumber)) {
457
+ list.push({
458
+ filePath: ref.filePath,
459
+ lineNumber: ref.lineNumber,
460
+ snippet: ref.snippet,
461
+ });
462
+ }
463
+ }
464
+ }
465
+ const undefinedTokens = [
466
+ ...undefinedByName.entries(),
467
+ ]
468
+ .map(([name, occurrences]) => ({
469
+ name,
470
+ occurrenceCount: occurrences.length,
471
+ occurrences,
472
+ }))
473
+ .sort((a, b) => b.occurrenceCount - a.occurrenceCount || a.name.localeCompare(b.name));
474
+ // 7. Compute Duplicate / Forked Token Declarations across stylesheets
475
+ const declsByTokenName = new Map();
476
+ for (const d of allTokenDecls) {
477
+ // Scoped declarations (`.card { --card-bg }`) legitimately re-declare names per component.
478
+ if (d.selector === "js-variable" || d.scope === "scoped")
479
+ continue;
480
+ let list = declsByTokenName.get(d.name);
481
+ if (!list) {
482
+ list = [];
483
+ declsByTokenName.set(d.name, list);
484
+ }
485
+ list.push(d);
486
+ }
487
+ const duplicateTokens = [];
488
+ for (const [name, decls] of declsByTokenName.entries()) {
489
+ const distinctFiles = new Set(decls.map((d) => d.filePath));
490
+ if (distinctFiles.size < 2)
491
+ continue;
492
+ const valuesByTheme = new Map();
493
+ for (const d of decls) {
494
+ let set = valuesByTheme.get(d.themeContext);
495
+ if (!set) {
496
+ set = new Set();
497
+ valuesByTheme.set(d.themeContext, set);
498
+ }
499
+ set.add(d.value.replace(/\s+/g, " ").trim().toLowerCase());
500
+ }
501
+ const isForkedValue = [...valuesByTheme.values()].some((s) => s.size > 1);
502
+ const uniqueDecls = [];
503
+ const seenDeclKey = new Set();
504
+ for (const d of decls) {
505
+ const k = `${d.filePath}:${d.lineNumber}:${d.themeContext}`;
506
+ if (seenDeclKey.has(k))
507
+ continue;
508
+ seenDeclKey.add(k);
509
+ uniqueDecls.push({
510
+ filePath: d.filePath,
511
+ lineNumber: d.lineNumber,
512
+ selector: d.selector,
513
+ themeContext: d.themeContext,
514
+ value: d.value,
515
+ });
516
+ }
517
+ duplicateTokens.push({
518
+ name,
519
+ tier: decls[0].tier,
520
+ distinctFileCount: distinctFiles.size,
521
+ isForkedValue,
522
+ declarations: uniqueDecls,
523
+ });
524
+ }
525
+ duplicateTokens.sort((a, b) => Number(b.isForkedValue) - Number(a.isForkedValue) ||
526
+ b.distinctFileCount - a.distinctFileCount ||
527
+ a.name.localeCompare(b.name));
528
+ // 8. Compute Unused Tokens via transitive liveness from actual consumer roots only
529
+ const consumerRootTokenNames = new Set();
530
+ for (const sheet of parsedCssList) {
531
+ for (const ref of sheet.styleRuleTokenRefs)
532
+ consumerRootTokenNames.add(ref);
533
+ }
534
+ for (const ref of allTokenRefs) {
535
+ if (ref.kind !== "css-var")
536
+ consumerRootTokenNames.add(ref.name);
537
+ }
538
+ const { liveTokens: liveReferencedTokens } = computeLiveReferencedTokens(consumerRootTokenNames, allTokenDecls);
539
+ const unusedTokens = [];
540
+ const seenUnused = new Set();
541
+ for (const d of allTokenDecls) {
542
+ if (seenUnused.has(d.name))
543
+ continue;
544
+ if (d.themeContext === "theme-bridge")
545
+ continue;
546
+ if (d.selector === "js-variable")
547
+ continue;
548
+ if (!liveReferencedTokens.has(d.name)) {
549
+ seenUnused.add(d.name);
550
+ unusedTokens.push({
551
+ name: d.name,
552
+ tier: d.tier,
553
+ filePath: d.filePath,
554
+ lineNumber: d.lineNumber,
555
+ });
556
+ }
557
+ }
558
+ unusedTokens.sort((a, b) => a.name.localeCompare(b.name));
559
+ // 9. Compute WCAG 2.1 Theme Contrast Audits (`dark` vs `light`)
560
+ const allStyleRules = parsedCssList.flatMap((s) => s.styleRules);
561
+ const allTailwindClassPairs = [...scannedFiles.values()].flatMap((s) => s.tailwindClassPairs);
562
+ const contrastEvaluation = evaluateContrast(allTokenDecls, allStyleRules, {
563
+ pairs: config.contrast.pairs,
564
+ minRatio: config.contrast.minRatio,
565
+ discoverFromRules: config.contrast.discoverFromRules,
566
+ discoverFromNaming: config.contrast.discoverFromNaming,
567
+ tailwindClassPairs: allTailwindClassPairs,
568
+ canvasToken: config.contrast.canvasToken,
569
+ });
570
+ const contrastAudits = contrastEvaluation.audits;
571
+ const contrastUnresolved = contrastEvaluation.unresolved;
572
+ const contrastFailures = contrastAudits.filter((c) => !c.passesAll);
573
+ const contrastCandidateCount = new Set([
574
+ ...contrastAudits.map((a) => a.pairId),
575
+ ...contrastUnresolved.map((u) => u.pairId),
576
+ ]).size;
577
+ // 10. Map CSS classes to the tokens they consume & index rules by class for StylePropertyVector resolution
578
+ const tokensByCssClass = new Map();
579
+ const cssRulesByClass = new Map();
580
+ for (const rule of allStyleRules) {
581
+ for (const cls of rule.classesInSelector) {
582
+ let set = tokensByCssClass.get(cls);
583
+ if (!set) {
584
+ set = new Set();
585
+ tokensByCssClass.set(cls, set);
586
+ }
587
+ for (const tok of rule.tokensConsumed) {
588
+ set.add(tok);
589
+ }
590
+ let ruleList = cssRulesByClass.get(cls);
591
+ if (!ruleList) {
592
+ ruleList = [];
593
+ cssRulesByClass.set(cls, ruleList);
594
+ }
595
+ ruleList.push(rule);
596
+ }
597
+ }
598
+ const allUsedCssClasses = new Set();
599
+ const allDynamicClassPrefixes = new Set();
600
+ for (const scanned of scannedFiles.values()) {
601
+ for (const b of scanned.functionsAndClasses.values()) {
602
+ for (const c of b.cssClassesUsed)
603
+ allUsedCssClasses.add(c);
604
+ for (const p of b.dynamicClassPrefixes)
605
+ allDynamicClassPrefixes.add(p);
606
+ }
607
+ }
608
+ const unusedCssSelectors = [];
609
+ for (const rule of allStyleRules) {
610
+ if (rule.classesInSelector.length === 0)
611
+ continue;
612
+ const anyClassUsed = rule.classesInSelector.some((cls) => {
613
+ if (allUsedCssClasses.has(cls))
614
+ return true;
615
+ if (matchesDynamicPrefix(cls, allDynamicClassPrefixes))
616
+ return true;
617
+ const baseBem = cls.split("--")[0];
618
+ if (baseBem !== cls &&
619
+ allUsedCssClasses.has(baseBem) &&
620
+ matchesDynamicPrefix(cls, allDynamicClassPrefixes)) {
621
+ return true;
622
+ }
623
+ return false;
624
+ });
625
+ if (!anyClassUsed) {
626
+ unusedCssSelectors.push({
627
+ selector: rule.selector,
628
+ filePath: rule.filePath,
629
+ lineNumber: rule.lineNumber,
630
+ });
631
+ }
632
+ }
633
+ // 11. Build Per-Component `ComponentDesignProfile`s anchored to `graph.nodes`
634
+ const nodeById = new Map();
635
+ const deploymentUnitsById = new Map();
636
+ for (const n of ctx.graph.nodes) {
637
+ nodeById.set(n.id, n);
638
+ if (n.entityType === "DEPLOYMENT_UNIT") {
639
+ deploymentUnitsById.set(n.id, n);
640
+ }
641
+ }
642
+ const resolvePackageLabel = (node) => {
643
+ let curr = node;
644
+ const visited = new Set();
645
+ while (curr && !visited.has(curr.id)) {
646
+ visited.add(curr.id);
647
+ if (curr.entityType === "DEPLOYMENT_UNIT") {
648
+ return cleanNodeDisplayLabel(curr.name).replace(/^@[^/]+\//, "");
649
+ }
650
+ curr = curr.parentBoundaryId
651
+ ? nodeById.get(curr.parentBoundaryId)
652
+ : undefined;
653
+ }
654
+ const ev = getPrimaryNodeEvidence(node);
655
+ if (ev.filePath) {
656
+ const owning = scope.packages
657
+ .filter((p) => p.dir !== "." && ev.filePath.startsWith(`${p.dir}/`))
658
+ .sort((a, b) => b.dir.length - a.dir.length)[0];
659
+ if (owning) {
660
+ return owning.name?.replace(/^@[^/]+\//, "") ?? basename(owning.dir);
661
+ }
662
+ }
663
+ return ctx.repoName;
664
+ };
665
+ const realGraphNodeIds = new Set(ctx.graph.nodes.map((n) => n.id));
666
+ // Group graph CONTRACT / CLASS nodes by their source file
667
+ const contractsByFile = new Map();
668
+ for (const n of ctx.graph.nodes) {
669
+ if (n.entityType === "DEPLOYMENT_UNIT" ||
670
+ n.entityType === "INIT_BLOCK" ||
671
+ n.entityType === "EXTERNAL_PACKAGE" ||
672
+ n.entityType === "NODE_BUILTIN" ||
673
+ n.entityType === "EXPORTED_TYPE" ||
674
+ n.entityType === "NEXTJS_METADATA") {
675
+ continue;
676
+ }
677
+ const ev = getPrimaryNodeEvidence(n);
678
+ if (!ev.filePath || !scannedFiles.has(ev.filePath))
679
+ continue;
680
+ let list = contractsByFile.get(ev.filePath);
681
+ if (!list) {
682
+ list = [];
683
+ contractsByFile.set(ev.filePath, list);
684
+ }
685
+ list.push(n);
686
+ }
687
+ // Synthesize internal file-level component contracts for preprocessed UI files (e.g. `.svelte`,
688
+ // or `.vue`/`.astro`/`.mdx` when invoked without L0 contracts) so they participate in profiling
689
+ // and `UI_ROLE_CONVENTIONS` without writing unanchored overlays to `entity_overlays`.
690
+ for (const uiFile of uiComponentFiles) {
691
+ if (contractsByFile.has(uiFile) || !scannedFiles.has(uiFile))
692
+ continue;
693
+ let owningBoundaryId;
694
+ let bestDirLen = -1;
695
+ for (const du of deploymentUnitsById.values()) {
696
+ const duEv = getPrimaryNodeEvidence(du);
697
+ const duDir = duEv.filePath ? dirname(duEv.filePath) : ".";
698
+ const matches = duDir === "." ? true : uiFile === duDir || uiFile.startsWith(`${duDir}/`);
699
+ if (matches && duDir.length > bestDirLen) {
700
+ bestDirLen = duDir.length;
701
+ owningBoundaryId = du.id;
702
+ }
703
+ }
704
+ const syntheticName = deriveComponentNameFromPath(uiFile);
705
+ const syntheticId = `ui-file:${createHash("sha256").update(uiFile).digest("hex").slice(0, 12)}`;
706
+ const syntheticNode = {
707
+ id: syntheticId,
708
+ name: `Exported Function: ${syntheticName}`,
709
+ type: "CONTRACT",
710
+ entityType: "EXPORTED_FUNCTION",
711
+ patternId: "contract.exported-function",
712
+ ...(owningBoundaryId ? { parentBoundaryId: owningBoundaryId } : {}),
713
+ scope: "USER",
714
+ evidence: { filePath: uiFile, lineNumber: 1 },
715
+ };
716
+ contractsByFile.set(uiFile, [syntheticNode]);
717
+ }
718
+ const componentProfiles = [];
719
+ const contractNodeById = new Map();
720
+ /** Per-profile structural facts needed for post-classification composability checks. */
721
+ const compositionFactsById = new Map();
722
+ const combinedBucketByEntityId = new Map();
723
+ const undefinedCssByClassName = new Map();
724
+ const allTailwindTypographyGroups = [];
725
+ /** Primary contract per file (page/layout/first exported function) for path-convention matching. */
726
+ const primaryContractIdByFile = new Map();
727
+ for (const [filePath, fileContracts] of contractsByFile.entries()) {
728
+ const scanned = scannedFiles.get(filePath);
729
+ if (!scanned)
730
+ continue;
731
+ fileContracts.sort((a, b) => (getPrimaryNodeEvidence(a).lineNumber ?? 0) -
732
+ (getPrimaryNodeEvidence(b).lineNumber ?? 0));
733
+ const buckets = [...scanned.functionsAndClasses.values()].filter((b) => b.name !== "__module__");
734
+ const assignedBucketNames = new Set();
735
+ const matchBucketForNode = (node) => {
736
+ const cleanName = cleanNodeDisplayLabel(node.name);
737
+ const compMetaName = typeof node.metadata?.componentName === "string"
738
+ ? node.metadata.componentName
739
+ : undefined;
740
+ const evLine = getPrimaryNodeEvidence(node).lineNumber;
741
+ for (const b of buckets) {
742
+ if (b.name === cleanName || (compMetaName && b.name === compMetaName)) {
743
+ assignedBucketNames.add(b.name);
744
+ return b;
745
+ }
746
+ }
747
+ if (evLine !== undefined) {
748
+ for (const b of buckets) {
749
+ if (Math.abs(b.lineNumber - evLine) <= 2) {
750
+ assignedBucketNames.add(b.name);
751
+ return b;
752
+ }
753
+ }
754
+ }
755
+ if (isPreprocessedUiComponentFile(filePath) && fileContracts.length === 1 && buckets.length > 0) {
756
+ const derivedName = deriveComponentNameFromPath(filePath);
757
+ const chosen = buckets.find((b) => b.name === derivedName) ?? buckets[0];
758
+ assignedBucketNames.add(chosen.name);
759
+ return chosen;
760
+ }
761
+ return undefined;
762
+ };
763
+ const matchedBucketsByNodeId = new Map();
764
+ for (const contract of fileContracts) {
765
+ const primary = matchBucketForNode(contract);
766
+ matchedBucketsByNodeId.set(contract.id, primary ? [primary] : []);
767
+ }
768
+ // Attribute any private helper buckets in the same file plus `__module__` constants
769
+ // to the file's primary exported contract (using framework-agnostic convention matching)
770
+ if (fileContracts.length > 0) {
771
+ const isStructural = (c, allowPath) => {
772
+ const conv = matchUiRoleConvention(c, filePath, {
773
+ allowPathMatchForStructuralRoles: allowPath,
774
+ });
775
+ return conv?.role === "ROUTE" || conv?.role === "TEMPLATE";
776
+ };
777
+ const contractHasJsx = (c) => (matchedBucketsByNodeId.get(c.id) ?? []).some((b) => b.jsxDomElementCount > 0 || b.jsxCustomComponentCount > 0);
778
+ const isPascalCaseContract = (c) => /^[A-Z]/.test(cleanNodeDisplayLabel(c.name));
779
+ const fileStem = basename(filePath).replace(/\.[^.]+$/, "").toLowerCase();
780
+ // Prefer a contract the extractor already typed as a page/layout; then the one named like the
781
+ // file; then a PascalCase JSX component over lowercase non-JSX utilities; never let a pure utility
782
+ // absorb private JSX helpers in multi-export component files.
783
+ const primaryContract = fileContracts.find((c) => isStructural(c, false)) ??
784
+ fileContracts.find((c) => isStructural(c, true) &&
785
+ cleanNodeDisplayLabel(c.name).toLowerCase() === fileStem) ??
786
+ fileContracts.find((c) => isStructural(c, true)) ??
787
+ fileContracts.find((c) => contractHasJsx(c) && isPascalCaseContract(c)) ??
788
+ fileContracts.find((c) => contractHasJsx(c)) ??
789
+ fileContracts.find((c) => c.entityType === "EXPORTED_FUNCTION" && isPascalCaseContract(c)) ??
790
+ fileContracts.find((c) => c.entityType === "EXPORTED_FUNCTION") ??
791
+ fileContracts[0];
792
+ primaryContractIdByFile.set(filePath, primaryContract.id);
793
+ const primaryList = matchedBucketsByNodeId.get(primaryContract.id) ?? [];
794
+ const modBucket = scanned.functionsAndClasses.get("__module__");
795
+ if (modBucket && fileContracts.length === 1) {
796
+ primaryList.push(modBucket);
797
+ }
798
+ for (const b of buckets) {
799
+ if (!assignedBucketNames.has(b.name)) {
800
+ // If a specific contract renders this private helper directly, attribute it there first.
801
+ const directCaller = fileContracts.find((c) => (matchedBucketsByNodeId.get(c.id) ?? []).some((cb) => cb.renderedComponents.has(b.name)));
802
+ if (directCaller) {
803
+ matchedBucketsByNodeId.get(directCaller.id).push(b);
804
+ }
805
+ else {
806
+ primaryList.push(b);
807
+ }
808
+ assignedBucketNames.add(b.name);
809
+ }
810
+ }
811
+ matchedBucketsByNodeId.set(primaryContract.id, primaryList);
812
+ }
813
+ for (const contract of fileContracts) {
814
+ const nodeBuckets = matchedBucketsByNodeId.get(contract.id) ?? [];
815
+ if (nodeBuckets.length === 0)
816
+ continue;
817
+ let jsxDomElementCount = 0;
818
+ let jsxCustomComponentCount = 0;
819
+ let stateHookCount = 0;
820
+ let propContract = [];
821
+ const jsxCallSites = [];
822
+ const jsxSkeletons = [];
823
+ const stylingConventions = new Set();
824
+ const cssClassesUsed = new Set();
825
+ const dynamicClassPrefixes = new Set();
826
+ const tokensConsumed = new Set();
827
+ const bridgedTokensConsumed = new Set();
828
+ const directTokensConsumed = new Set();
829
+ const rawBridgedTokens = new Set();
830
+ const arbitraryTailwind = [];
831
+ const primitiveScaleSkips = [];
832
+ const inlineStyleLiterals = [];
833
+ let usesSlotRecorder = false;
834
+ let canvasCssCount = 0;
835
+ let canvasTsConstCount = 0;
836
+ let canvasLiteralCount = 0;
837
+ const canvasLiterals = [];
838
+ const rawDomPrimitives = [];
839
+ const rawDomOffsets = [];
840
+ const magicSpacingUtilities = [];
841
+ const nestedInteractive = [];
842
+ const cssClassOccurrences = [];
843
+ const uiShapeCandidates = [];
844
+ const elementStyleSnapshots = [];
845
+ const tailwindTypographyGroups = [];
846
+ const renderedComponents = new Set();
847
+ const domTags = new Set();
848
+ const literalValues = [];
849
+ const invariantViolations = [];
850
+ let rootElement = nodeBuckets.find((b) => b.rootElement)?.rootElement;
851
+ let tailwindUtilityCount = 0;
852
+ for (const b of nodeBuckets) {
853
+ tailwindUtilityCount += b.tailwindUtilityCount;
854
+ for (const t of b.domTags)
855
+ domTags.add(t);
856
+ literalValues.push(...b.literalValues);
857
+ invariantViolations.push(...b.invariantViolations);
858
+ magicSpacingUtilities.push(...b.magicSpacingUtilities);
859
+ nestedInteractive.push(...b.nestedInteractive);
860
+ cssClassOccurrences.push(...b.cssClassOccurrences);
861
+ uiShapeCandidates.push(...b.uiShapeCandidates);
862
+ elementStyleSnapshots.push(...b.elementStyleSnapshots);
863
+ tailwindTypographyGroups.push(...b.tailwindTypographyGroups);
864
+ for (const c of b.paletteClassCandidates) {
865
+ if (!rawPalettes.has(c.palette.toLowerCase()))
866
+ continue;
867
+ const prim = [`--${c.palette}-${c.step}`, `--color-${c.palette}-${c.step}`].find((n) => definedTokenNames.has(n));
868
+ const sem = semanticSuggestionFor(prim);
869
+ primitiveScaleSkips.push({
870
+ tokenOrClass: c.className,
871
+ kind: "tailwind-primitive",
872
+ suggestedSemantic: sem
873
+ ? `Use ${sem}`
874
+ : `Use a semantic token instead of raw palette step '${c.palette}-${c.step}'`,
875
+ filePath: c.filePath,
876
+ lineNumber: c.lineNumber,
877
+ snippet: c.snippet,
878
+ });
879
+ }
880
+ for (const r of b.tsTokenRefs) {
881
+ if (!primitiveColorTokenNames.has(r.name))
882
+ continue;
883
+ const sem = semanticSuggestionFor(r.name);
884
+ primitiveScaleSkips.push({
885
+ tokenOrClass: `var(${r.name})`,
886
+ kind: "css-primitive-var",
887
+ suggestedSemantic: sem
888
+ ? `Use ${sem}`
889
+ : "Reference a semantic token instead of a primitive token in component code",
890
+ filePath: r.filePath,
891
+ lineNumber: r.lineNumber,
892
+ snippet: r.snippet,
893
+ });
894
+ }
895
+ jsxDomElementCount += b.jsxDomElementCount;
896
+ jsxCustomComponentCount += b.jsxCustomComponentCount;
897
+ stateHookCount += b.stateHookCount;
898
+ if (propContract.length === 0 && b.propContract.length > 0) {
899
+ propContract = b.propContract;
900
+ }
901
+ jsxCallSites.push(...b.jsxCallSites);
902
+ jsxSkeletons.push(...b.jsxSkeletons);
903
+ for (const c of b.stylingConventions)
904
+ stylingConventions.add(c);
905
+ for (const cls of b.cssClassesUsed) {
906
+ cssClassesUsed.add(cls);
907
+ const clsTokens = tokensByCssClass.get(cls);
908
+ if (clsTokens) {
909
+ for (const t of clsTokens) {
910
+ tokensConsumed.add(t);
911
+ directTokensConsumed.add(t);
912
+ }
913
+ }
914
+ }
915
+ for (const p of b.dynamicClassPrefixes)
916
+ dynamicClassPrefixes.add(p);
917
+ for (const t of b.tokensConsumed) {
918
+ tokensConsumed.add(t);
919
+ directTokensConsumed.add(t);
920
+ }
921
+ const bridgedSet = bridgedTokensByBucket.get(`${scanned.filePath}::${b.name}`);
922
+ if (bridgedSet) {
923
+ for (const bt of bridgedSet) {
924
+ rawBridgedTokens.add(bt);
925
+ tokensConsumed.add(bt);
926
+ }
927
+ }
928
+ arbitraryTailwind.push(...b.arbitraryTailwind);
929
+ primitiveScaleSkips.push(...b.primitiveScaleSkips);
930
+ inlineStyleLiterals.push(...b.inlineStyleLiterals);
931
+ if (b.usesSlotRecorder)
932
+ usesSlotRecorder = true;
933
+ canvasCssCount += b.canvasCssCount;
934
+ canvasTsConstCount += b.canvasTsConstCount;
935
+ canvasLiteralCount += b.canvasLiteralCount;
936
+ canvasLiterals.push(...b.canvasLiterals);
937
+ rawDomPrimitives.push(...b.rawDomPrimitives);
938
+ rawDomOffsets.push(...b.rawDomOffsets);
939
+ for (const rc of b.renderedComponents)
940
+ renderedComponents.add(rc);
941
+ }
942
+ for (const bt of rawBridgedTokens) {
943
+ if (!directTokensConsumed.has(bt)) {
944
+ bridgedTokensConsumed.add(bt);
945
+ }
946
+ }
947
+ const ev = getPrimaryNodeEvidence(contract);
948
+ const resolvedFilePath = ev.filePath ?? filePath;
949
+ const matchedConvention = matchUiRoleConvention(contract, resolvedFilePath);
950
+ const hasAnyDesignSignal = Boolean(matchedConvention) ||
951
+ jsxDomElementCount > 0 ||
952
+ jsxCustomComponentCount > 0 ||
953
+ stylingConventions.size > 0 ||
954
+ tokensConsumed.size > 0 ||
955
+ arbitraryTailwind.length > 0 ||
956
+ primitiveScaleSkips.length > 0 ||
957
+ inlineStyleLiterals.length > 0 ||
958
+ usesSlotRecorder ||
959
+ rawDomPrimitives.length > 0 ||
960
+ renderedComponents.size > 0;
961
+ if (!hasAnyDesignSignal)
962
+ continue;
963
+ const compUndefinedTokens = undefinedTokens.filter((u) => tokensConsumed.has(u.name));
964
+ const atomicCandidates = Array.from(new Set(rawDomPrimitives.map((r) => r.atomicTarget)));
965
+ contractNodeById.set(contract.id, contract);
966
+ const rawCleanLabel = cleanNodeDisplayLabel(contract.name);
967
+ const profileLabel = isPreprocessedUiComponentFile(resolvedFilePath) &&
968
+ /^(?:__(?:VueSfc|Astro|Mdx)(?:Component|Template)__|default)$/i.test(rawCleanLabel)
969
+ ? deriveComponentNameFromPath(resolvedFilePath)
970
+ : rawCleanLabel;
971
+ const compUndefinedCssSet = new Set();
972
+ for (const occ of cssClassOccurrences) {
973
+ const cls = occ.className;
974
+ if ((!cls.includes("-") && !cls.includes("_")) ||
975
+ definedCssClasses.has(cls) ||
976
+ config.styling.cssClassPrefixes.some((p) => cls.startsWith(p)) ||
977
+ matchesDynamicPrefix(cls, dynamicClassPrefixes) ||
978
+ isTailwindUtilityToken(cls) ||
979
+ cls.includes("[") ||
980
+ cls.startsWith("--")) {
981
+ continue;
982
+ }
983
+ compUndefinedCssSet.add(cls);
984
+ let list = undefinedCssByClassName.get(cls);
985
+ if (!list) {
986
+ list = [];
987
+ undefinedCssByClassName.set(cls, list);
988
+ }
989
+ if (!list.some((x) => x.filePath === resolvedFilePath && x.lineNumber === occ.lineNumber)) {
990
+ list.push({
991
+ filePath: resolvedFilePath,
992
+ lineNumber: occ.lineNumber,
993
+ snippet: occ.snippet,
994
+ componentName: profileLabel,
995
+ });
996
+ }
997
+ }
998
+ for (const tg of tailwindTypographyGroups) {
999
+ allTailwindTypographyGroups.push({ componentName: profileLabel, group: tg });
1000
+ }
1001
+ const resolvedStyleVector = resolveComponentStyleVector(elementStyleSnapshots, cssRulesByClass, tokenMaps);
1002
+ const profile = {
1003
+ entityId: contract.id,
1004
+ name: contract.name,
1005
+ label: profileLabel,
1006
+ entityType: contract.entityType,
1007
+ packageName: resolvePackageLabel(contract),
1008
+ filePath: resolvedFilePath,
1009
+ lineNumber: ev.lineNumber,
1010
+ atomicTier: "MOLECULE", // Finalized in Stage 1 after RENDERS graph topology resolution
1011
+ uiKind: "component",
1012
+ classificationSource: "ast-footprint",
1013
+ rendersInDegree: 0,
1014
+ rendersOutDegree: 0,
1015
+ usageCount: 0,
1016
+ inboundCallSites: [],
1017
+ jsxDomElementCount,
1018
+ jsxCustomComponentCount,
1019
+ stateHookCount,
1020
+ propContract,
1021
+ jsxCallSites,
1022
+ jsxSkeletons,
1023
+ usedInRoutes: [],
1024
+ stylingConventions: [...stylingConventions],
1025
+ cssClassesUsed: [...cssClassesUsed].sort(),
1026
+ undefinedCssClasses: [...compUndefinedCssSet].sort(),
1027
+ dynamicClassPrefixes: [...dynamicClassPrefixes].sort(),
1028
+ tokensConsumed: [...tokensConsumed].sort(),
1029
+ bridgedTokensConsumed: [...bridgedTokensConsumed].sort(),
1030
+ undefinedTokens: compUndefinedTokens,
1031
+ arbitraryTailwind,
1032
+ magicSpacingUtilities,
1033
+ primitiveScaleSkips,
1034
+ inlineStyleLiterals,
1035
+ canvasProvenance: {
1036
+ usesSlotRecorder,
1037
+ cssCount: canvasCssCount,
1038
+ tsConstCount: canvasTsConstCount,
1039
+ literalCount: canvasLiteralCount,
1040
+ literals: canvasLiterals,
1041
+ },
1042
+ rawDomPrimitives,
1043
+ siblingAtomOverlaps: [],
1044
+ nestedInteractive,
1045
+ unextractedShapes: [],
1046
+ ...(resolvedStyleVector ? { styleVector: resolvedStyleVector } : {}),
1047
+ atomicCandidates,
1048
+ renderedComponents: [...renderedComponents].sort(),
1049
+ domTags: [...domTags].sort(),
1050
+ tailwindUtilityCount,
1051
+ variantAxes: scanned.variantAxes,
1052
+ literalValues,
1053
+ invariantViolations,
1054
+ composabilityIssues: [],
1055
+ health: {
1056
+ score: 100,
1057
+ status: "healthy",
1058
+ issueCount: 0,
1059
+ subtreeScore: 100,
1060
+ subtreeStatus: "healthy",
1061
+ subtreeIssueCount: 0,
1062
+ descendantOffenders: [],
1063
+ tokenAdherence: null,
1064
+ breakdown: {
1065
+ arbitraryTailwind: 0,
1066
+ magicSpacing: 0,
1067
+ primitiveSkips: 0,
1068
+ hardcodedLiterals: 0,
1069
+ rawDomBypasses: 0,
1070
+ siblingAtomOverlaps: 0,
1071
+ nestedInteractive: 0,
1072
+ composabilityIssues: 0,
1073
+ undefinedTokens: 0,
1074
+ undefinedCssClasses: 0,
1075
+ duplicateClones: 0,
1076
+ callSiteOverrides: 0,
1077
+ },
1078
+ },
1079
+ observedStates: ["rest"],
1080
+ similarComponents: [],
1081
+ };
1082
+ const primaryBucket = nodeBuckets[0];
1083
+ combinedBucketByEntityId.set(contract.id, {
1084
+ ...primaryBucket,
1085
+ rawDomPrimitives,
1086
+ rawDomOffsets,
1087
+ uiShapeCandidates,
1088
+ renderedComponents,
1089
+ domTags,
1090
+ elementStyleSnapshots,
1091
+ tailwindTypographyGroups,
1092
+ });
1093
+ compositionFactsById.set(contract.id, {
1094
+ root: rootElement,
1095
+ imports: scanned.importedModules,
1096
+ });
1097
+ componentProfiles.push(profile);
1098
+ }
1099
+ }
1100
+ // -------------------------------------------------------------------------
1101
+ // 12. Stage 1 — Atomic Hierarchy Classification (`UI_ROLE_CONVENTIONS` + `RENDERS` Topology + AST Footprint)
1102
+ // -------------------------------------------------------------------------
1103
+ const profileById = new Map();
1104
+ const profilesByFile = new Map();
1105
+ const profilesByLabelAll = new Map();
1106
+ const addProfileLabelIndex = (labelKey, p) => {
1107
+ let list = profilesByLabelAll.get(labelKey);
1108
+ if (!list) {
1109
+ list = [];
1110
+ profilesByLabelAll.set(labelKey, list);
1111
+ }
1112
+ if (!list.some((x) => x.entityId === p.entityId)) {
1113
+ list.push(p);
1114
+ }
1115
+ };
1116
+ for (const p of componentProfiles) {
1117
+ profileById.set(p.entityId, p);
1118
+ let fileList = profilesByFile.get(p.filePath);
1119
+ if (!fileList) {
1120
+ fileList = [];
1121
+ profilesByFile.set(p.filePath, fileList);
1122
+ }
1123
+ fileList.push(p);
1124
+ addProfileLabelIndex(p.label, p);
1125
+ const contract = contractNodeById.get(p.entityId);
1126
+ const compMetaName = typeof contract?.metadata?.componentName === "string"
1127
+ ? (contract?.metadata).componentName
1128
+ : undefined;
1129
+ if (compMetaName) {
1130
+ addProfileLabelIndex(compMetaName, p);
1131
+ }
1132
+ }
1133
+ // Workspace package name → directory index for cross-package import resolution
1134
+ const workspacePkgDirByName = new Map();
1135
+ for (const pkg of scope.packages) {
1136
+ if (pkg.name)
1137
+ workspacePkgDirByName.set(pkg.name, pkg.dir);
1138
+ }
1139
+ for (const f of ctx.files) {
1140
+ if (f !== "package.json" && !f.endsWith("/package.json"))
1141
+ continue;
1142
+ const raw = ctx.readFile(f);
1143
+ if (!raw)
1144
+ continue;
1145
+ try {
1146
+ const parsed = JSON.parse(raw);
1147
+ if (typeof parsed.name === "string" && parsed.name && !workspacePkgDirByName.has(parsed.name)) {
1148
+ workspacePkgDirByName.set(parsed.name, f === "package.json" ? "." : dirname(f));
1149
+ }
1150
+ }
1151
+ catch {
1152
+ // ignore malformed package.json
1153
+ }
1154
+ }
1155
+ const sortedWorkspacePackages = [...workspacePkgDirByName.entries()].sort((a, b) => b[0].length - a[0].length);
1156
+ const MODULE_PROBE_SUFFIXES = [
1157
+ "",
1158
+ ".tsx",
1159
+ ".ts",
1160
+ ".jsx",
1161
+ ".js",
1162
+ ".vue",
1163
+ ".svelte",
1164
+ ".astro",
1165
+ ".mdx",
1166
+ "/index.tsx",
1167
+ "/index.ts",
1168
+ "/index.jsx",
1169
+ "/index.js",
1170
+ "/index.vue",
1171
+ "/index.svelte",
1172
+ "/index.astro",
1173
+ "/index.mdx",
1174
+ ];
1175
+ const resolveSpecifierToFiles = (fromFile, specifier) => {
1176
+ const hits = new Set();
1177
+ const probeBase = (rawBase) => {
1178
+ const clean = rawBase.replace(/\/+$/, "");
1179
+ if (!clean || clean.startsWith(".."))
1180
+ return;
1181
+ for (const suffix of MODULE_PROBE_SUFFIXES) {
1182
+ const cand = `${clean}${suffix}`;
1183
+ if (scannedFiles.has(cand))
1184
+ hits.add(cand);
1185
+ }
1186
+ if (/\.(?:m?js|jsx)$/i.test(clean)) {
1187
+ const stem = clean.replace(/\.(?:m?js|jsx)$/i, "");
1188
+ for (const suffix of MODULE_PROBE_SUFFIXES) {
1189
+ const cand = `${stem}${suffix}`;
1190
+ if (scannedFiles.has(cand))
1191
+ hits.add(cand);
1192
+ }
1193
+ }
1194
+ };
1195
+ if (specifier.startsWith("./") || specifier.startsWith("../")) {
1196
+ probeBase(posixPath.normalize(posixPath.join(posixPath.dirname(fromFile), specifier)));
1197
+ return [...hits];
1198
+ }
1199
+ if (specifier.startsWith("@/") || specifier.startsWith("~/") || specifier.startsWith("#/")) {
1200
+ const sub = specifier.slice(2);
1201
+ const owningPkg = scope.packages
1202
+ .filter((p) => p.dir !== "." && (fromFile === p.dir || fromFile.startsWith(`${p.dir}/`)))
1203
+ .sort((a, b) => b.dir.length - a.dir.length)[0];
1204
+ if (owningPkg) {
1205
+ probeBase(posixPath.normalize(`${owningPkg.dir}/src/${sub}`));
1206
+ probeBase(posixPath.normalize(`${owningPkg.dir}/${sub}`));
1207
+ }
1208
+ probeBase(posixPath.normalize(`src/${sub}`));
1209
+ probeBase(posixPath.normalize(sub));
1210
+ return [...hits];
1211
+ }
1212
+ for (const [pkgName, pkgDir] of sortedWorkspacePackages) {
1213
+ if (specifier === pkgName) {
1214
+ probeBase(pkgDir === "." ? "src/index" : `${pkgDir}/src/index`);
1215
+ probeBase(pkgDir === "." ? "index" : `${pkgDir}/index`);
1216
+ if (hits.size > 0)
1217
+ return [...hits];
1218
+ }
1219
+ else if (specifier.startsWith(`${pkgName}/`)) {
1220
+ const sub = specifier.slice(pkgName.length + 1);
1221
+ probeBase(pkgDir === "." ? `src/${sub}` : `${pkgDir}/src/${sub}`);
1222
+ probeBase(pkgDir === "." ? sub : `${pkgDir}/${sub}`);
1223
+ if (hits.size > 0)
1224
+ return [...hits];
1225
+ }
1226
+ }
1227
+ if (!specifier.startsWith("@")) {
1228
+ const owningPkg = scope.packages
1229
+ .filter((p) => p.dir !== "." && (fromFile === p.dir || fromFile.startsWith(`${p.dir}/`)))
1230
+ .sort((a, b) => b.dir.length - a.dir.length)[0];
1231
+ if (owningPkg) {
1232
+ probeBase(posixPath.normalize(`${owningPkg.dir}/src/${specifier}`));
1233
+ probeBase(posixPath.normalize(`${owningPkg.dir}/${specifier}`));
1234
+ }
1235
+ probeBase(posixPath.normalize(`src/${specifier}`));
1236
+ probeBase(posixPath.normalize(specifier));
1237
+ }
1238
+ return [...hits];
1239
+ };
1240
+ const resolveExportedProfilesFromFile = (targetFile, exportedName, visited = new Set()) => {
1241
+ const visitKey = `${targetFile}::${exportedName}`;
1242
+ if (visited.has(visitKey) || visited.size > 10)
1243
+ return [];
1244
+ visited.add(visitKey);
1245
+ const fileProfiles = profilesByFile.get(targetFile) ?? [];
1246
+ if (exportedName === "default") {
1247
+ if (fileProfiles.length === 1)
1248
+ return [fileProfiles[0]];
1249
+ const primId = primaryContractIdByFile.get(targetFile);
1250
+ const prim = primId ? profileById.get(primId) : undefined;
1251
+ if (prim && prim.filePath === targetFile)
1252
+ return [prim];
1253
+ if (fileProfiles.length > 0)
1254
+ return [fileProfiles[0]];
1255
+ }
1256
+ else if (exportedName === "*") {
1257
+ if (fileProfiles.length > 0)
1258
+ return [...fileProfiles];
1259
+ }
1260
+ else {
1261
+ const direct = fileProfiles.filter((p) => p.label === exportedName || cleanNodeDisplayLabel(p.name) === exportedName);
1262
+ if (direct.length > 0)
1263
+ return direct;
1264
+ if (isPreprocessedUiComponentFile(targetFile) && fileProfiles.length === 1) {
1265
+ return [fileProfiles[0]];
1266
+ }
1267
+ }
1268
+ const reExports = scannedFiles.get(targetFile)?.reExports ?? [];
1269
+ const out = [];
1270
+ const pushUnique = (items) => {
1271
+ for (const item of items) {
1272
+ if (!out.some((x) => x.entityId === item.entityId))
1273
+ out.push(item);
1274
+ }
1275
+ };
1276
+ for (const re of reExports) {
1277
+ if (re.exportedName === "*" && exportedName !== "default") {
1278
+ for (const sf of resolveSpecifierToFiles(targetFile, re.specifier)) {
1279
+ pushUnique(resolveExportedProfilesFromFile(sf, exportedName, visited));
1280
+ }
1281
+ }
1282
+ else if (re.exportedName === exportedName) {
1283
+ for (const sf of resolveSpecifierToFiles(targetFile, re.specifier)) {
1284
+ pushUnique(resolveExportedProfilesFromFile(sf, re.sourceName || exportedName, visited));
1285
+ }
1286
+ }
1287
+ }
1288
+ return out;
1289
+ };
1290
+ // Build unified `RENDERS` adjacency list combining `@getchomp/core` `RENDERS` edges and import-resolved `renderedComponents`
1291
+ const rendersChildrenById = new Map();
1292
+ const rendersParentsById = new Map();
1293
+ const graphRendersTargetsBySrc = new Map();
1294
+ for (const p of componentProfiles) {
1295
+ rendersChildrenById.set(p.entityId, new Set());
1296
+ rendersParentsById.set(p.entityId, new Set());
1297
+ }
1298
+ const addRendersLink = (parentId, childId) => {
1299
+ if (parentId === childId)
1300
+ return;
1301
+ if (!profileById.has(parentId) || !profileById.has(childId))
1302
+ return;
1303
+ rendersChildrenById.get(parentId).add(childId);
1304
+ rendersParentsById.get(childId).add(parentId);
1305
+ };
1306
+ for (const edge of ctx.graph.edges) {
1307
+ if (edge.entityType === "RENDERS" || edge.type === "RENDERS") {
1308
+ const src = edge.sourceId ?? edge.source;
1309
+ const tgt = edge.targetId ?? edge.target;
1310
+ if (src && tgt) {
1311
+ addRendersLink(src, tgt);
1312
+ const tgtProf = profileById.get(tgt);
1313
+ if (tgtProf) {
1314
+ let list = graphRendersTargetsBySrc.get(src);
1315
+ if (!list) {
1316
+ list = [];
1317
+ graphRendersTargetsBySrc.set(src, list);
1318
+ }
1319
+ if (!list.some((x) => x.entityId === tgtProf.entityId)) {
1320
+ list.push(tgtProf);
1321
+ }
1322
+ }
1323
+ }
1324
+ }
1325
+ }
1326
+ const resolveTargetProfile = (callerProfile, rawTagName) => {
1327
+ const rootIdent = rawTagName.split(".")[0];
1328
+ const memberIdent = rawTagName.includes(".")
1329
+ ? rawTagName.split(".").slice(1).join(".")
1330
+ : undefined;
1331
+ // 1. Check explicit imports in caller's file first so same-named components across files never collide
1332
+ const binding = scannedFiles.get(callerProfile.filePath)?.importedBindings.get(rootIdent);
1333
+ if (binding) {
1334
+ const lookupExport = binding.importedName === "*" ? (memberIdent ?? "*") : binding.importedName;
1335
+ const targetFiles = resolveSpecifierToFiles(callerProfile.filePath, binding.specifier);
1336
+ for (const tf of targetFiles) {
1337
+ const found = resolveExportedProfilesFromFile(tf, lookupExport);
1338
+ if (found.length > 0)
1339
+ return found[0];
1340
+ }
1341
+ // Also check if graph RENDERS edges already resolved this imported binding to a target profile
1342
+ const graphTargets = graphRendersTargetsBySrc.get(callerProfile.entityId) ?? [];
1343
+ if (targetFiles.length > 0) {
1344
+ const graphHit = graphTargets.find((tp) => targetFiles.includes(tp.filePath));
1345
+ if (graphHit)
1346
+ return graphHit;
1347
+ }
1348
+ // Explicitly imported from an external package or unprofiled module — never fall back to a same-named local component
1349
+ return undefined;
1350
+ }
1351
+ // 2. Check graph RENDERS edge targets from this caller
1352
+ const graphTargets = graphRendersTargetsBySrc.get(callerProfile.entityId) ?? [];
1353
+ const directGraphHit = graphTargets.find((tp) => tp.label === rawTagName || tp.label === rootIdent);
1354
+ if (directGraphHit)
1355
+ return directGraphHit;
1356
+ // 3. Same-file sibling component declaration
1357
+ const sameFileHit = (profilesByFile.get(callerProfile.filePath) ?? []).find((p) => p.entityId !== callerProfile.entityId &&
1358
+ (p.label === rawTagName || p.label === rootIdent));
1359
+ if (sameFileHit)
1360
+ return sameFileHit;
1361
+ // 4. Unimported / auto-imported component: link only when unambiguous
1362
+ const candidates = (profilesByLabelAll.get(rawTagName) ??
1363
+ profilesByLabelAll.get(rootIdent) ??
1364
+ []).filter((p) => p.entityId !== callerProfile.entityId);
1365
+ if (candidates.length === 1)
1366
+ return candidates[0];
1367
+ const samePkg = candidates.filter((p) => p.packageName === callerProfile.packageName);
1368
+ if (samePkg.length === 1)
1369
+ return samePkg[0];
1370
+ return undefined;
1371
+ };
1372
+ for (const p of componentProfiles) {
1373
+ for (const rcName of p.renderedComponents) {
1374
+ const targetProfile = resolveTargetProfile(p, rcName);
1375
+ if (targetProfile) {
1376
+ addRendersLink(p.entityId, targetProfile.entityId);
1377
+ }
1378
+ }
1379
+ }
1380
+ const tierCounts = {
1381
+ ROUTE: 0,
1382
+ TEMPLATE: 0,
1383
+ ORGANISM: 0,
1384
+ MOLECULE: 0,
1385
+ ATOM: 0,
1386
+ UTILITY: 0,
1387
+ };
1388
+ const conventionMatchMap = new Map();
1389
+ const byTier = {
1390
+ ROUTE: [],
1391
+ TEMPLATE: [],
1392
+ ORGANISM: [],
1393
+ MOLECULE: [],
1394
+ ATOM: [],
1395
+ UTILITY: [],
1396
+ };
1397
+ for (const p of componentProfiles) {
1398
+ p.rendersInDegree = rendersParentsById.get(p.entityId)?.size ?? 0;
1399
+ p.rendersOutDegree = rendersChildrenById.get(p.entityId)?.size ?? 0;
1400
+ const contract = contractNodeById.get(p.entityId);
1401
+ const classified = classifyAtomicTier({
1402
+ node: contract,
1403
+ filePath: p.filePath,
1404
+ jsxDomElementCount: p.jsxDomElementCount,
1405
+ jsxCustomComponentCount: p.jsxCustomComponentCount,
1406
+ stateHookCount: p.stateHookCount,
1407
+ rendersInDegree: p.rendersInDegree,
1408
+ rendersOutDegree: p.rendersOutDegree,
1409
+ domTags: new Set(p.domTags),
1410
+ isPrimaryInFile: primaryContractIdByFile.get(getPrimaryNodeEvidence(contract).filePath ?? p.filePath) === p.entityId,
1411
+ });
1412
+ p.atomicTier = classified.atomicTier;
1413
+ p.classificationSource = classified.classificationSource;
1414
+ const isCanvasRenderer = p.canvasProvenance.usesSlotRecorder ||
1415
+ (p.stylingConventions.includes("pixi-canvas") && p.jsxDomElementCount === 0);
1416
+ p.uiKind =
1417
+ p.atomicTier === "ROUTE"
1418
+ ? "route"
1419
+ : p.atomicTier === "TEMPLATE"
1420
+ ? "template"
1421
+ : isCanvasRenderer
1422
+ ? "canvas-renderer"
1423
+ : p.atomicTier === "UTILITY" || /^[a-z]/.test(p.label)
1424
+ ? "utility"
1425
+ : "component";
1426
+ if (classified.convention) {
1427
+ p.conventionId = classified.convention.id;
1428
+ const existing = conventionMatchMap.get(classified.convention.id);
1429
+ if (existing) {
1430
+ existing.matchCount++;
1431
+ }
1432
+ else {
1433
+ conventionMatchMap.set(classified.convention.id, {
1434
+ conventionId: classified.convention.id,
1435
+ framework: classified.convention.framework,
1436
+ role: classified.convention.role,
1437
+ matchCount: 1,
1438
+ });
1439
+ }
1440
+ }
1441
+ tierCounts[p.atomicTier]++;
1442
+ byTier[p.atomicTier].push({
1443
+ entityId: p.entityId,
1444
+ label: p.label,
1445
+ filePath: p.filePath,
1446
+ lineNumber: p.lineNumber,
1447
+ rendersInDegree: p.rendersInDegree,
1448
+ rendersOutDegree: p.rendersOutDegree,
1449
+ domElements: p.jsxDomElementCount,
1450
+ customChildren: p.jsxCustomComponentCount,
1451
+ propCount: p.propContract.length,
1452
+ classificationSource: p.classificationSource,
1453
+ });
1454
+ }
1455
+ const atomicHierarchy = {
1456
+ tierCounts,
1457
+ conventionsMatched: [...conventionMatchMap.values()],
1458
+ byTier,
1459
+ };
1460
+ // Populate inbound call sites and real usage counts per component
1461
+ for (const caller of componentProfiles) {
1462
+ for (const cs of caller.jsxCallSites) {
1463
+ const target = resolveTargetProfile(caller, cs.targetComponent);
1464
+ if (target && target.entityId !== caller.entityId) {
1465
+ target.inboundCallSites.push({
1466
+ callerEntityId: caller.entityId,
1467
+ callerLabel: caller.label,
1468
+ callerTier: caller.atomicTier,
1469
+ filePath: cs.filePath,
1470
+ lineNumber: cs.lineNumber,
1471
+ passedProps: cs.passedProps,
1472
+ snippet: cs.snippet,
1473
+ });
1474
+ }
1475
+ }
1476
+ }
1477
+ for (const target of componentProfiles) {
1478
+ const parentIds = rendersParentsById.get(target.entityId);
1479
+ if (parentIds) {
1480
+ for (const pid of parentIds) {
1481
+ if (target.inboundCallSites.some((c) => c.callerEntityId === pid))
1482
+ continue;
1483
+ const caller = profileById.get(pid);
1484
+ if (!caller)
1485
+ continue;
1486
+ target.inboundCallSites.push({
1487
+ callerEntityId: caller.entityId,
1488
+ callerLabel: caller.label,
1489
+ callerTier: caller.atomicTier,
1490
+ filePath: caller.filePath,
1491
+ lineNumber: caller.lineNumber,
1492
+ passedProps: [],
1493
+ });
1494
+ }
1495
+ }
1496
+ target.usageCount =
1497
+ target.atomicTier === "ROUTE" || target.atomicTier === "TEMPLATE"
1498
+ ? Math.max(1, target.inboundCallSites.length)
1499
+ : target.inboundCallSites.length;
1500
+ }
1501
+ // -------------------------------------------------------------------------
1502
+ // 13. Stage 2 — Route Composition Trees (`Route → Template → Organism → Molecule → Atom`)
1503
+ // -------------------------------------------------------------------------
1504
+ const routeProfiles = componentProfiles.filter((p) => p.atomicTier === "ROUTE");
1505
+ const templateProfiles = componentProfiles.filter((p) => p.atomicTier === "TEMPLATE");
1506
+ // First pass: find all reachable components for each route so we can compute shared vs route-exclusive
1507
+ const reachableByRouteId = new Map();
1508
+ for (const route of routeProfiles) {
1509
+ const visited = new Set();
1510
+ const walk = (currId, depth) => {
1511
+ if (depth > 6 || visited.has(currId))
1512
+ return;
1513
+ visited.add(currId);
1514
+ const children = rendersChildrenById.get(currId);
1515
+ if (children) {
1516
+ for (const childId of children) {
1517
+ walk(childId, depth + 1);
1518
+ }
1519
+ }
1520
+ };
1521
+ walk(route.entityId, 0);
1522
+ visited.delete(route.entityId);
1523
+ reachableByRouteId.set(route.entityId, visited);
1524
+ for (const compId of visited) {
1525
+ const compProf = profileById.get(compId);
1526
+ if (compProf && !compProf.usedInRoutes.includes(route.label)) {
1527
+ compProf.usedInRoutes.push(route.label);
1528
+ }
1529
+ }
1530
+ if (!route.usedInRoutes.includes(route.label)) {
1531
+ route.usedInRoutes.push(route.label);
1532
+ }
1533
+ }
1534
+ const routeComposition = [];
1535
+ for (const route of routeProfiles) {
1536
+ const reachableIds = reachableByRouteId.get(route.entityId) ?? new Set();
1537
+ const routeDir = dirname(route.filePath);
1538
+ const enclosingTemplateProfiles = templateProfiles.filter((tpl) => {
1539
+ const tplDir = dirname(tpl.filePath);
1540
+ return routeDir === tplDir || routeDir.startsWith(`${tplDir}/`);
1541
+ });
1542
+ const enclosingTemplates = enclosingTemplateProfiles.map((tpl) => tpl.label);
1543
+ for (const tplProf of enclosingTemplateProfiles) {
1544
+ if (!tplProf.usedInRoutes.includes(route.label)) {
1545
+ tplProf.usedInRoutes.push(route.label);
1546
+ }
1547
+ }
1548
+ const buildTreeNode = (entityId, ancestors) => {
1549
+ const prof = profileById.get(entityId);
1550
+ const nextAncestors = new Set(ancestors);
1551
+ nextAncestors.add(entityId);
1552
+ const childIds = [...(rendersChildrenById.get(entityId) ?? [])].filter((cid) => !nextAncestors.has(cid) && profileById.has(cid));
1553
+ return {
1554
+ entityId: prof.entityId,
1555
+ label: prof.label,
1556
+ atomicTier: prof.atomicTier,
1557
+ filePath: prof.filePath,
1558
+ children: childIds.map((cid) => buildTreeNode(cid, nextAncestors)),
1559
+ };
1560
+ };
1561
+ const compositionTree = buildTreeNode(route.entityId, new Set());
1562
+ const templates = [...enclosingTemplates];
1563
+ const organisms = [];
1564
+ const molecules = [];
1565
+ const atoms = [];
1566
+ const utilities = [];
1567
+ const sharedComponentsUsed = [];
1568
+ const routeExclusiveComponents = [];
1569
+ let subtreeDomElements = route.jsxDomElementCount;
1570
+ let subtreeCustomComponents = route.jsxCustomComponentCount;
1571
+ let subtreeRawDomPrimitives = route.rawDomPrimitives.length;
1572
+ for (const cid of reachableIds) {
1573
+ const cp = profileById.get(cid);
1574
+ if (!cp)
1575
+ continue;
1576
+ if (cp.atomicTier === "TEMPLATE" && !templates.includes(cp.label)) {
1577
+ templates.push(cp.label);
1578
+ }
1579
+ else if (cp.atomicTier === "ORGANISM") {
1580
+ organisms.push(cp.label);
1581
+ }
1582
+ else if (cp.atomicTier === "MOLECULE") {
1583
+ molecules.push(cp.label);
1584
+ }
1585
+ else if (cp.atomicTier === "ATOM") {
1586
+ atoms.push(cp.label);
1587
+ }
1588
+ else if (cp.atomicTier === "UTILITY") {
1589
+ utilities.push(cp.label);
1590
+ }
1591
+ if (cp.usedInRoutes.length >= 2 || cp.rendersInDegree >= 2) {
1592
+ sharedComponentsUsed.push(cp.label);
1593
+ }
1594
+ else {
1595
+ routeExclusiveComponents.push(cp.label);
1596
+ }
1597
+ subtreeDomElements += cp.jsxDomElementCount;
1598
+ subtreeCustomComponents += cp.jsxCustomComponentCount;
1599
+ if (cp.atomicTier !== "ATOM") {
1600
+ subtreeRawDomPrimitives += cp.rawDomPrimitives.length;
1601
+ }
1602
+ }
1603
+ // Composition ratio measures how much of the route's UI is delegated to composed components vs raw inline primitives
1604
+ const totalBuildingBlocks = reachableIds.size +
1605
+ subtreeCustomComponents +
1606
+ Math.max(route.jsxDomElementCount, route.rawDomPrimitives.length);
1607
+ const compositionRatio = totalBuildingBlocks > 0
1608
+ ? Math.round(((reachableIds.size + subtreeCustomComponents) /
1609
+ (totalBuildingBlocks + route.rawDomPrimitives.length)) *
1610
+ 100) / 100
1611
+ : 1;
1612
+ const routeSmells = [];
1613
+ if (route.jsxDomElementCount >= 25 && reachableIds.size <= 1) {
1614
+ routeSmells.push({
1615
+ code: "MONOLITHIC_ROUTE",
1616
+ severity: "WARN",
1617
+ message: `Route '${route.label}' inline-renders ${route.jsxDomElementCount} raw DOM elements with only ${reachableIds.size} composed child component(s); extract feature sections into Organisms/Molecules.`,
1618
+ });
1619
+ }
1620
+ if (routeProfiles.length >= 2 &&
1621
+ reachableIds.size > 0 &&
1622
+ sharedComponentsUsed.length === 0) {
1623
+ routeSmells.push({
1624
+ code: "ISOLATED_ROUTE_VOCABULARY",
1625
+ severity: "INFO",
1626
+ message: `Route '${route.label}' shares 0 UI components with other routes (${routeExclusiveComponents.length} route-exclusive component(s)).`,
1627
+ });
1628
+ }
1629
+ if (subtreeRawDomPrimitives >= 5) {
1630
+ routeSmells.push({
1631
+ code: "BYPASSED_ATOMS",
1632
+ severity: "WARN",
1633
+ message: `Route '${route.label}' tree contains ${subtreeRawDomPrimitives} raw DOM primitive instance(s) (<button>, role="switch", <aside>, <dl>) that bypass shared Atoms.`,
1634
+ });
1635
+ }
1636
+ if ((organisms.length > 0 || molecules.length > 0) &&
1637
+ atoms.length === 0 &&
1638
+ subtreeDomElements >= 15) {
1639
+ routeSmells.push({
1640
+ code: "MISSING_ATOM_LAYER",
1641
+ severity: "INFO",
1642
+ message: `Route '${route.label}' composes Organisms/Molecules (${[...organisms, ...molecules].join(", ")}) directly over raw DOM without any shared Atom primitives.`,
1643
+ });
1644
+ }
1645
+ routeComposition.push({
1646
+ routeId: route.entityId,
1647
+ routeLabel: route.label,
1648
+ filePath: route.filePath,
1649
+ frameworkConvention: route.conventionId ?? "route.entry",
1650
+ enclosingTemplates,
1651
+ tierBreakdown: {
1652
+ templates,
1653
+ organisms,
1654
+ molecules,
1655
+ atoms,
1656
+ utilities,
1657
+ },
1658
+ compositionTree,
1659
+ totalReachableComponents: reachableIds.size,
1660
+ sharedComponentsUsed,
1661
+ routeExclusiveComponents,
1662
+ inlineRawDomCount: route.jsxDomElementCount,
1663
+ compositionRatio,
1664
+ routeSmells,
1665
+ });
1666
+ }
1667
+ // -------------------------------------------------------------------------
1668
+ // 13b. Canonical Atom Ownership, Sibling Overlaps & Stateful UI Shapes
1669
+ // -------------------------------------------------------------------------
1670
+ const canonicalAtomsByTarget = resolveCanonicalAtomsByTarget(componentProfiles.map((p) => ({
1671
+ name: p.name,
1672
+ label: p.label,
1673
+ entityId: p.entityId,
1674
+ atomicTier: p.atomicTier,
1675
+ usageCount: p.usageCount,
1676
+ filePath: p.filePath,
1677
+ domTags: new Set(p.domTags),
1678
+ jsxDomElementCount: p.jsxDomElementCount,
1679
+ })), atomDefinitions);
1680
+ const canonicalAtomNameByTarget = new Map();
1681
+ for (const [k, v] of canonicalAtomsByTarget.entries()) {
1682
+ canonicalAtomNameByTarget.set(k, v.name);
1683
+ }
1684
+ const uiShapesAudit = analyzeUiShapesAndSiblingOverlaps({
1685
+ components: componentProfiles.map((p) => ({
1686
+ entityId: p.entityId,
1687
+ name: p.name,
1688
+ label: p.label,
1689
+ filePath: p.filePath,
1690
+ lineNumber: p.lineNumber,
1691
+ atomicTier: p.atomicTier,
1692
+ usageCount: p.usageCount,
1693
+ bucket: combinedBucketByEntityId.get(p.entityId),
1694
+ })),
1695
+ canonicalAtomsByTarget,
1696
+ cssRulesByClass,
1697
+ tokenMaps,
1698
+ });
1699
+ // Absorb inner raw `<button>` primitives into detected Tabs/SegmentedControl shapes before Stage 14+15
1700
+ for (const p of componentProfiles) {
1701
+ const suppressed = uiShapesAudit.suppressedRawDomIndicesByEntity.get(p.entityId);
1702
+ if (suppressed && suppressed.size > 0) {
1703
+ p.rawDomPrimitives = p.rawDomPrimitives.filter((_, idx) => !suppressed.has(idx));
1704
+ p.atomicCandidates = Array.from(new Set(p.rawDomPrimitives.map((r) => r.atomicTarget)));
1705
+ }
1706
+ p.unextractedShapes = uiShapesAudit.unextractedShapesByEntity.get(p.entityId) ?? [];
1707
+ p.siblingAtomOverlaps = uiShapesAudit.siblingAtomOverlapsByEntity.get(p.entityId) ?? [];
1708
+ }
1709
+ const isCompAuthorizedForAtom = (p, atomTarget) => {
1710
+ if (isAuthorizedAtomOwner({
1711
+ componentName: p.label,
1712
+ atomicTier: p.atomicTier,
1713
+ atomTarget,
1714
+ jsxDomElementCount: p.jsxDomElementCount,
1715
+ jsxCustomComponentCount: p.jsxCustomComponentCount,
1716
+ canonicalAtomsByTarget: canonicalAtomNameByTarget,
1717
+ })) {
1718
+ return true;
1719
+ }
1720
+ return false;
1721
+ };
1722
+ // -------------------------------------------------------------------------
1723
+ // 14. Atom adoption & consolidation (driven by the configurable / derived atom catalog)
1724
+ // -------------------------------------------------------------------------
1725
+ const sharedNamesFor = (def) => new Set([def.name, `Shared${def.name}`, ...(def.sharedComponentNames ?? [])].map((n) => n.toLowerCase()));
1726
+ const sharedNamesByAtom = new Map(atomDefinitions.map((d) => [d.name, sharedNamesFor(d)]));
1727
+ const existingSharedByAtom = new Map();
1728
+ const isUiLibraryPath = (p) => /(?:^|\/)(?:ui|atoms|primitives|design-system|components)\//i.test(p);
1729
+ const sharedCandidates = [];
1730
+ for (const n of ctx.graph.nodes) {
1731
+ if (n.type !== "CONTRACT")
1732
+ continue;
1733
+ const ev = getPrimaryNodeEvidence(n);
1734
+ if (!ev.filePath || !scannedFiles.has(ev.filePath))
1735
+ continue;
1736
+ sharedCandidates.push({
1737
+ name: cleanNodeDisplayLabel(n.name),
1738
+ filePath: ev.filePath,
1739
+ lineNumber: ev.lineNumber,
1740
+ });
1741
+ }
1742
+ for (const [tsPath, tsAudit] of scannedFiles.entries()) {
1743
+ for (const [, bucket] of tsAudit.functionsAndClasses.entries()) {
1744
+ if (!bucket.isExported || bucket.name === "__module__")
1745
+ continue;
1746
+ sharedCandidates.push({ name: bucket.name, filePath: tsPath, lineNumber: bucket.lineNumber });
1747
+ }
1748
+ }
1749
+ for (const def of atomDefinitions) {
1750
+ const names = sharedNamesByAtom.get(def.name);
1751
+ const hits = sharedCandidates.filter((c) => names.has(c.name.toLowerCase()));
1752
+ const best = hits.find((h) => isUiLibraryPath(h.filePath)) ?? hits[0];
1753
+ if (best)
1754
+ existingSharedByAtom.set(def.name, best);
1755
+ }
1756
+ const isOwnAtomImplementation = (compLabel, atomName) => sharedNamesByAtom.get(atomName)?.has(compLabel.toLowerCase()) ?? false;
1757
+ const minUnshared = resolved.mode === "adhere" ? 1 : config.atoms.minUnsharedInstances;
1758
+ const atomicConsolidation = [];
1759
+ /** atomName → raw instances not belonging to the atom's own implementation. */
1760
+ const rawInstancesByAtom = new Map();
1761
+ let totalAdopters = 0;
1762
+ let totalReportedRaw = 0;
1763
+ const exportedBucketCountByFile = new Map();
1764
+ for (const [tsPath, tsAudit] of scannedFiles.entries()) {
1765
+ let count = 0;
1766
+ for (const [, bucket] of tsAudit.functionsAndClasses.entries()) {
1767
+ if (bucket.isExported && bucket.name !== "__module__")
1768
+ count++;
1769
+ }
1770
+ exportedBucketCountByFile.set(tsPath, count);
1771
+ }
1772
+ for (const def of atomDefinitions) {
1773
+ const names = sharedNamesByAtom.get(def.name);
1774
+ const existingShared = existingSharedByAtom.get(def.name);
1775
+ const isMultiExportSharedFile = Boolean(existingShared &&
1776
+ ((exportedBucketCountByFile.get(existingShared.filePath) ?? 0) > 1 ||
1777
+ (contractsByFile.get(existingShared.filePath)?.length ?? 0) > 1));
1778
+ const raw = [];
1779
+ let adopters = 0;
1780
+ for (const comp of componentProfiles) {
1781
+ const isSelfAtomComponent = (existingShared &&
1782
+ existingShared.filePath === comp.filePath &&
1783
+ existingShared.name.toLowerCase() === comp.label.toLowerCase()) ||
1784
+ (isOwnAtomImplementation(comp.label, def.name) &&
1785
+ (comp.atomicTier === "ATOM" || isUiLibraryPath(comp.filePath)));
1786
+ for (const rawDom of comp.rawDomPrimitives) {
1787
+ if (rawDom.atomicTarget !== def.name)
1788
+ continue;
1789
+ if (isCompAuthorizedForAtom(comp, def.name) || isSelfAtomComponent)
1790
+ continue;
1791
+ raw.push({
1792
+ componentName: comp.label,
1793
+ filePath: rawDom.filePath,
1794
+ lineNumber: rawDom.lineNumber,
1795
+ snippet: rawDom.snippet,
1796
+ });
1797
+ }
1798
+ for (const cs of comp.jsxCallSites) {
1799
+ const resolvedTarget = resolveTargetProfile(comp, cs.targetComponent);
1800
+ if (existingShared) {
1801
+ if (resolvedTarget && resolvedTarget.filePath === existingShared.filePath) {
1802
+ if (!isMultiExportSharedFile || names.has(resolvedTarget.label.toLowerCase())) {
1803
+ adopters++;
1804
+ }
1805
+ continue;
1806
+ }
1807
+ const rootIdent = cs.targetComponent.split(".")[0];
1808
+ const binding = scannedFiles.get(comp.filePath)?.importedBindings.get(rootIdent);
1809
+ if (binding) {
1810
+ const matchesImportedName = !isMultiExportSharedFile ||
1811
+ names.has((binding.importedName &&
1812
+ binding.importedName !== "default" &&
1813
+ binding.importedName !== "*"
1814
+ ? binding.importedName
1815
+ : cs.targetComponent).toLowerCase());
1816
+ if (!matchesImportedName)
1817
+ continue;
1818
+ const targetFiles = resolveSpecifierToFiles(comp.filePath, binding.specifier);
1819
+ if (targetFiles.includes(existingShared.filePath)) {
1820
+ adopters++;
1821
+ }
1822
+ else {
1823
+ // Check barrel re-exports to existingShared.filePath when existingShared wasn't in `ctx.graph`
1824
+ const reachesShared = targetFiles.some((tf) => {
1825
+ const reList = scannedFiles.get(tf)?.reExports ?? [];
1826
+ return reList.some((re) => resolveSpecifierToFiles(tf, re.specifier).includes(existingShared.filePath));
1827
+ });
1828
+ if (reachesShared)
1829
+ adopters++;
1830
+ }
1831
+ }
1832
+ else if (!resolvedTarget && names.has(cs.targetComponent.toLowerCase())) {
1833
+ adopters++;
1834
+ }
1835
+ }
1836
+ else if (names.has(cs.targetComponent.toLowerCase())) {
1837
+ adopters++;
1838
+ }
1839
+ }
1840
+ }
1841
+ rawInstancesByAtom.set(def.name, raw);
1842
+ const reportable = raw.length > 0 && (Boolean(existingShared) || raw.length >= minUnshared);
1843
+ if (!reportable)
1844
+ continue;
1845
+ totalAdopters += adopters;
1846
+ totalReportedRaw += raw.length;
1847
+ const distinctFiles = Array.from(new Set(raw.map((i) => i.filePath))).sort();
1848
+ const adoptionRate = existingShared
1849
+ ? Math.round((adopters / Math.max(1, adopters + raw.length)) * 100)
1850
+ : null;
1851
+ atomicConsolidation.push({
1852
+ atomName: def.name,
1853
+ description: def.description ?? `Raw DOM that should be a shared <${def.name}>.`,
1854
+ instanceCount: raw.length,
1855
+ adopterCount: adopters,
1856
+ adoptionRate,
1857
+ distinctFiles,
1858
+ ...(existingShared ? { existingSharedComponent: existingShared } : {}),
1859
+ instances: raw.slice(0, 15),
1860
+ consolidationGuidance: existingShared
1861
+ ? `Replace ${raw.length} raw ${def.name}-shaped element(s) across ${distinctFiles.length} file(s) with the existing shared <${existingShared.name}> (${existingShared.filePath}); ${adopters} call site(s) already use it.`
1862
+ : `Extract a shared <${def.name}> atom from ${raw.length} raw instance(s) across ${distinctFiles.length} file(s).`,
1863
+ });
1864
+ }
1865
+ atomicConsolidation.sort((a, b) => b.instanceCount - a.instanceCount || a.atomName.localeCompare(b.atomName));
1866
+ const reportedAtomNames = new Set(atomicConsolidation.map((a) => a.atomName));
1867
+ // -------------------------------------------------------------------------
1868
+ // 15. Stage 3 — Cross-Route & Component Alignment Audit (`bypassedAtoms`, `parallelTwins`, `callSiteOverrides`, `propApiDrift`, invariants, composability)
1869
+ // -------------------------------------------------------------------------
1870
+ const bypassedAtoms = [];
1871
+ for (const comp of componentProfiles) {
1872
+ for (const rawDom of comp.rawDomPrimitives) {
1873
+ if (!reportedAtomNames.has(rawDom.atomicTarget))
1874
+ continue;
1875
+ if (isCompAuthorizedForAtom(comp, rawDom.atomicTarget))
1876
+ continue;
1877
+ const existingShared = existingSharedByAtom.get(rawDom.atomicTarget);
1878
+ bypassedAtoms.push({
1879
+ atomTarget: rawDom.atomicTarget,
1880
+ bypassingComponent: comp.label,
1881
+ bypassingTier: comp.atomicTier,
1882
+ filePath: rawDom.filePath,
1883
+ lineNumber: rawDom.lineNumber,
1884
+ snippet: rawDom.snippet,
1885
+ ...(existingShared ? { existingSharedComponent: existingShared.name } : {}),
1886
+ recommendation: existingShared
1887
+ ? `Replace raw ${rawDom.tagOrRole} in ${comp.label} with existing shared <${existingShared.name} /> (${existingShared.filePath}).`
1888
+ : `Extract raw ${rawDom.tagOrRole} in ${comp.label} into a shared <${rawDom.atomicTarget} /> Atom and compose it.`,
1889
+ });
1890
+ }
1891
+ }
1892
+ // Detect `parallelTwins`: components that share a name concept (`SubmitButton` / `NavButton` / `ActionBtn`
1893
+ // → "button") AND a similar signature (props ∪ DOM tags ∪ tokens). Concepts are derived from names, not a preset list.
1894
+ const BOILERPLATE_PROP_NAMES = new Set([
1895
+ "children",
1896
+ "className",
1897
+ "style",
1898
+ "ref",
1899
+ "key",
1900
+ "id",
1901
+ ]);
1902
+ const conceptOfLabel = (label) => {
1903
+ const words = label.replace(/Tw$/, "").match(/[A-Z]+(?![a-z])|[A-Z][a-z0-9]*|[a-z][a-z0-9]*/g);
1904
+ if (!words || words.length === 0)
1905
+ return null;
1906
+ const rawLast = words[words.length - 1];
1907
+ const cap = rawLast[0].toUpperCase() + rawLast.slice(1);
1908
+ const normalized = config.concepts.abbreviations[cap] ?? cap;
1909
+ return { concept: normalized.toLowerCase(), display: normalized };
1910
+ };
1911
+ const signatureOf = (p) => {
1912
+ const sig = new Set();
1913
+ const bridged = new Set(p.bridgedTokensConsumed);
1914
+ for (const prop of p.propContract) {
1915
+ if (!BOILERPLATE_PROP_NAMES.has(prop.name))
1916
+ sig.add(`prop:${prop.name}`);
1917
+ }
1918
+ for (const t of p.domTags)
1919
+ sig.add(`tag:${t}`);
1920
+ for (const t of p.tokensConsumed) {
1921
+ if (!bridged.has(t))
1922
+ sig.add(`tok:${t}`);
1923
+ }
1924
+ return sig;
1925
+ };
1926
+ const jaccard = (a, b) => {
1927
+ if (a.size === 0 && b.size === 0)
1928
+ return 0;
1929
+ let inter = 0;
1930
+ for (const x of a)
1931
+ if (b.has(x))
1932
+ inter++;
1933
+ return inter / (a.size + b.size - inter);
1934
+ };
1935
+ const parallelTwins = [];
1936
+ const profilesByConcept = new Map();
1937
+ for (const p of componentProfiles) {
1938
+ if (p.atomicTier === "ROUTE" || p.atomicTier === "TEMPLATE" || p.atomicTier === "UTILITY")
1939
+ continue;
1940
+ if (p.jsxDomElementCount === 0 && p.rawDomPrimitives.length === 0)
1941
+ continue;
1942
+ const c = conceptOfLabel(p.label);
1943
+ if (!c)
1944
+ continue;
1945
+ let bucket = profilesByConcept.get(c.concept);
1946
+ if (!bucket) {
1947
+ bucket = { display: c.display, profiles: [] };
1948
+ profilesByConcept.set(c.concept, bucket);
1949
+ }
1950
+ bucket.profiles.push(p);
1951
+ }
1952
+ for (const [concept, { display, profiles }] of [...profilesByConcept.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
1953
+ if (profiles.length < config.concepts.minGroupSize)
1954
+ continue;
1955
+ const memberIds = new Set(profiles.map((m) => m.entityId));
1956
+ // Exclude only trivial direct wrappers (single-child passthroughs), keeping sibling organisms
1957
+ // that happen to compose a shared atom sharing the concept suffix (e.g. multiple *Drawers using <Drawer>).
1958
+ const nonTrivial = profiles.filter((p) => {
1959
+ const composesSibling = [...(rendersChildrenById.get(p.entityId) ?? [])].some((cid) => memberIds.has(cid) && cid !== p.entityId);
1960
+ if (!composesSibling)
1961
+ return true;
1962
+ return !(p.jsxDomElementCount <= 2 && p.rendersOutDegree === 1);
1963
+ });
1964
+ if (nonTrivial.length < config.concepts.minGroupSize)
1965
+ continue;
1966
+ const sigs = nonTrivial.map(signatureOf);
1967
+ let simSum = 0;
1968
+ let simPairs = 0;
1969
+ for (let i = 0; i < sigs.length; i++) {
1970
+ for (let j = i + 1; j < sigs.length; j++) {
1971
+ simSum += jaccard(sigs[i], sigs[j]);
1972
+ simPairs++;
1973
+ }
1974
+ }
1975
+ const similarity = simPairs > 0 ? Math.round((simSum / simPairs) * 100) / 100 : 0;
1976
+ if (similarity < config.concepts.minSimilarity)
1977
+ continue;
1978
+ // Proposed unified prop API from observed prop vocabularies
1979
+ const propAgg = new Map();
1980
+ for (const m of nonTrivial) {
1981
+ for (const prop of m.propContract) {
1982
+ if (BOILERPLATE_PROP_NAMES.has(prop.name))
1983
+ continue;
1984
+ let agg = propAgg.get(prop.name);
1985
+ if (!agg) {
1986
+ agg = { types: new Map(), usedBy: 0, requiredEverywhere: true, variants: new Set() };
1987
+ propAgg.set(prop.name, agg);
1988
+ }
1989
+ agg.usedBy++;
1990
+ agg.types.set(prop.type, (agg.types.get(prop.type) ?? 0) + 1);
1991
+ if (!prop.required)
1992
+ agg.requiredEverywhere = false;
1993
+ for (const v of prop.variants ?? [])
1994
+ agg.variants.add(v);
1995
+ }
1996
+ }
1997
+ const observedVariants = {};
1998
+ for (const [name, agg] of propAgg) {
1999
+ if (agg.variants.size > 0)
2000
+ observedVariants[name] = [...agg.variants].sort();
2001
+ }
2002
+ for (const m of nonTrivial) {
2003
+ for (const [axis, values] of Object.entries(m.variantAxes)) {
2004
+ observedVariants[axis] = [...new Set([...(observedVariants[axis] ?? []), ...values])].sort();
2005
+ }
2006
+ }
2007
+ const proposedProps = [...propAgg.entries()]
2008
+ .map(([name, agg]) => ({
2009
+ name,
2010
+ type: [...agg.types.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0][0],
2011
+ usedBy: agg.usedBy,
2012
+ required: agg.requiredEverywhere && agg.usedBy === nonTrivial.length,
2013
+ }))
2014
+ .sort((a, b) => b.usedBy - a.usedBy || a.name.localeCompare(b.name));
2015
+ const sharedSignals = [
2016
+ ...[...sigs[0]].filter((x) => sigs.every((s2) => s2.has(x))),
2017
+ ].slice(0, 6);
2018
+ const existingShared = [...existingSharedByAtom.values()].find((e) => e.name.toLowerCase() === concept);
2019
+ const topProps = proposedProps
2020
+ .slice(0, 6)
2021
+ .map((p) => `${p.name}${p.required ? "" : "?"}`)
2022
+ .join(", ");
2023
+ const styleVectorDeltas = [];
2024
+ for (let i = 0; i < nonTrivial.length; i++) {
2025
+ for (let j = i + 1; j < nonTrivial.length; j++) {
2026
+ const left = nonTrivial[i];
2027
+ const right = nonTrivial[j];
2028
+ const deltas = computeStyleVectorDeltas(left.styleVector, right.styleVector);
2029
+ if (deltas.length > 0) {
2030
+ styleVectorDeltas.push({
2031
+ leftLabel: left.label,
2032
+ rightLabel: right.label,
2033
+ deltas,
2034
+ });
2035
+ }
2036
+ }
2037
+ }
2038
+ parallelTwins.push({
2039
+ concept: `${display} family`,
2040
+ components: nonTrivial.map((p) => ({
2041
+ entityId: p.entityId,
2042
+ label: p.label,
2043
+ atomicTier: p.atomicTier,
2044
+ filePath: p.filePath,
2045
+ lineNumber: p.lineNumber,
2046
+ })),
2047
+ sharedSignals: sharedSignals.length > 0 ? sharedSignals : ["shared naming concept"],
2048
+ similarity,
2049
+ proposedProps,
2050
+ observedVariants,
2051
+ ...(styleVectorDeltas.length > 0 ? { styleVectorDeltas } : {}),
2052
+ recommendation: existingShared
2053
+ ? `Fold ${nonTrivial.map((p) => p.label).join(", ")} into the existing <${existingShared.name}> (${existingShared.filePath}) as variants${topProps ? ` (observed props: ${topProps})` : ""}.`
2054
+ : `Merge ${nonTrivial.map((p) => p.label).join(", ")} into a single <${display}> with variants${topProps ? `; proposed props { ${topProps} }` : ""}.`,
2055
+ });
2056
+ }
2057
+ // Detect `callSiteOverrides` where a parent injects `style={{}}` or arbitrary Tailwind `[Npx]` onto a `<ChildComponent />`
2058
+ const callSiteOverrides = [];
2059
+ for (const comp of componentProfiles) {
2060
+ for (const cs of comp.jsxCallSites) {
2061
+ if (!cs.hasInlineStyleOverride &&
2062
+ cs.arbitraryTailwindOverrides.length === 0) {
2063
+ continue;
2064
+ }
2065
+ const overrideKind = cs.hasInlineStyleOverride && cs.arbitraryTailwindOverrides.length > 0
2066
+ ? "both"
2067
+ : cs.hasInlineStyleOverride
2068
+ ? "inline-style"
2069
+ : "arbitrary-tailwind";
2070
+ const details = [];
2071
+ if (cs.inlineStyleProps.length > 0) {
2072
+ details.push(`style={{ ${cs.inlineStyleProps.join(", ")} }}`);
2073
+ }
2074
+ if (cs.arbitraryTailwindOverrides.length > 0) {
2075
+ details.push(`className arbitrary: ${cs.arbitraryTailwindOverrides.join(", ")}`);
2076
+ }
2077
+ callSiteOverrides.push({
2078
+ parentComponent: comp.label,
2079
+ childComponent: cs.targetComponent,
2080
+ filePath: cs.filePath,
2081
+ lineNumber: cs.lineNumber,
2082
+ snippet: cs.snippet,
2083
+ overrideKind,
2084
+ details,
2085
+ });
2086
+ }
2087
+ }
2088
+ // Detect `propApiDrift`: configured synonym families plus spelling drift derived from the repo's own prop vocabulary
2089
+ const formatDisambiguatedComponentName = (prof) => (profilesByLabelAll.get(prof.label)?.length ?? 0) > 1
2090
+ ? `${prof.label} (${prof.filePath})`
2091
+ : prof.label;
2092
+ const propUsers = new Map();
2093
+ for (const comp of componentProfiles) {
2094
+ const compKey = formatDisambiguatedComponentName(comp);
2095
+ for (const prop of comp.propContract) {
2096
+ let set = propUsers.get(prop.name);
2097
+ if (!set) {
2098
+ set = new Set();
2099
+ propUsers.set(prop.name, set);
2100
+ }
2101
+ set.add(compKey);
2102
+ }
2103
+ for (const cs of comp.jsxCallSites) {
2104
+ const resolvedTarget = resolveTargetProfile(comp, cs.targetComponent);
2105
+ const rootIdent = cs.targetComponent.split(".")[0];
2106
+ const binding = scannedFiles.get(comp.filePath)?.importedBindings.get(rootIdent);
2107
+ if (binding && !resolvedTarget) {
2108
+ // If imported from an external npm package (not resolved to any in-repo file), skip attributing external prop APIs
2109
+ const targetFiles = resolveSpecifierToFiles(comp.filePath, binding.specifier);
2110
+ if (targetFiles.length === 0)
2111
+ continue;
2112
+ }
2113
+ const targetKey = resolvedTarget
2114
+ ? formatDisambiguatedComponentName(resolvedTarget)
2115
+ : cs.targetComponent;
2116
+ for (const pName of cs.passedProps) {
2117
+ let set = propUsers.get(pName);
2118
+ if (!set) {
2119
+ set = new Set();
2120
+ propUsers.set(pName, set);
2121
+ }
2122
+ set.add(targetKey);
2123
+ }
2124
+ }
2125
+ }
2126
+ const propApiDrift = [];
2127
+ const coveredByFamily = new Set();
2128
+ for (const family of config.propFamilies) {
2129
+ const variants = family.propNames
2130
+ .filter((n) => propUsers.has(n))
2131
+ .map((propName) => ({ propName, components: [...propUsers.get(propName)].sort() }));
2132
+ if (variants.length >= 2) {
2133
+ for (const v of variants)
2134
+ coveredByFamily.add(v.propName);
2135
+ propApiDrift.push({
2136
+ semanticRole: family.semanticRole,
2137
+ variants,
2138
+ canonicalRecommendation: family.canonicalRecommendation ??
2139
+ `Standardize on one spelling (most used: ${[...variants].sort((a, b) => b.components.length - a.components.length)[0].propName}).`,
2140
+ });
2141
+ }
2142
+ }
2143
+ const propStem = (name) => {
2144
+ const handle = name.match(/^handle([A-Z].*)$/);
2145
+ const n = handle ? `on${handle[1]}` : name;
2146
+ // `isOpen` ≡ `open`, but `hasData` is a different concept than `data`: only `is*` is a spelling variant.
2147
+ const bool = n.match(/^is([A-Z].*)$/);
2148
+ const stem = bool ? bool[1][0].toLowerCase() + bool[1].slice(1) : n;
2149
+ return stem;
2150
+ };
2151
+ const stemGroups = new Map();
2152
+ for (const name of propUsers.keys()) {
2153
+ if (coveredByFamily.has(name) || BOILERPLATE_PROP_NAMES.has(name))
2154
+ continue;
2155
+ const stem = propStem(name);
2156
+ let list = stemGroups.get(stem);
2157
+ if (!list) {
2158
+ list = [];
2159
+ stemGroups.set(stem, list);
2160
+ }
2161
+ list.push(name);
2162
+ }
2163
+ for (const [stem, names] of [...stemGroups.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
2164
+ if (names.length < 2)
2165
+ continue;
2166
+ const variants = names
2167
+ .map((propName) => ({ propName, components: [...propUsers.get(propName)].sort() }))
2168
+ .sort((a, b) => b.components.length - a.components.length || a.propName.localeCompare(b.propName));
2169
+ propApiDrift.push({
2170
+ semanticRole: `Prop spelling drift: "${stem}"`,
2171
+ variants,
2172
+ canonicalRecommendation: `Standardize on the most-used spelling (${variants[0].propName}, ${variants[0].components.length} component(s)).`,
2173
+ });
2174
+ }
2175
+ // Prop-literal invariants: raw color literals passed to design-token-like props
2176
+ const invariantViolations = componentProfiles.flatMap((c) => c.invariantViolations);
2177
+ // Composability: drop-in atoms/molecules must not carry hidden margins, fixed widths, or data-layer imports
2178
+ const cssDeclsByClass = new Map();
2179
+ for (const rule of allStyleRules) {
2180
+ for (const cls of rule.classesInSelector) {
2181
+ let list = cssDeclsByClass.get(cls);
2182
+ if (!list) {
2183
+ list = [];
2184
+ cssDeclsByClass.set(cls, list);
2185
+ }
2186
+ for (const d of rule.declarations) {
2187
+ list.push({ prop: d.prop, value: d.value, filePath: rule.filePath, lineNumber: d.lineNumber });
2188
+ }
2189
+ }
2190
+ }
2191
+ const forbiddenImports = config.composability.forbiddenImports;
2192
+ const isZeroLike = (v) => /^(?:0|0px|0rem|0em|auto|inherit|initial|unset)$/i.test(v.trim());
2193
+ const isExtrinsicFixedWidthValue = (raw) => {
2194
+ const parsed = parseCssLengthToPx(raw.trim());
2195
+ return parsed !== null && parsed.px >= 96;
2196
+ };
2197
+ const composabilityIssues = [];
2198
+ for (const comp of componentProfiles) {
2199
+ if (comp.atomicTier !== "ATOM" && comp.atomicTier !== "MOLECULE")
2200
+ continue;
2201
+ const facts = compositionFactsById.get(comp.entityId);
2202
+ if (!facts)
2203
+ continue;
2204
+ const issues = [];
2205
+ const root = facts.root;
2206
+ if (root) {
2207
+ const classTokens = root.classes.split(/\s+/).filter(Boolean);
2208
+ if (config.composability.flagRootMargin) {
2209
+ const marginClass = classTokens.find((t) => {
2210
+ const base = t.split(":").pop() ?? t;
2211
+ return /^-?m[trblxy]?-(?!0$|px$)/.test(base) && !/^m[trblxy]?-0$/.test(base);
2212
+ });
2213
+ const marginStyle = Object.entries(root.styleProps).find(([k, v]) => /^margin/.test(k) && !isZeroLike(v));
2214
+ const marginCss = classTokens
2215
+ .flatMap((t) => cssDeclsByClass.get(t) ?? [])
2216
+ .find((d) => /^margin/.test(d.prop) && !isZeroLike(d.value));
2217
+ if (marginClass || marginStyle || marginCss) {
2218
+ issues.push({
2219
+ kind: "root-margin",
2220
+ component: comp.label,
2221
+ detail: marginClass
2222
+ ? `root <${root.tag}> carries margin utility \`${marginClass}\``
2223
+ : marginStyle
2224
+ ? `root <${root.tag}> sets inline ${marginStyle[0]}: ${marginStyle[1]}`
2225
+ : `root <${root.tag}> class has CSS ${marginCss.prop}: ${marginCss.value}`,
2226
+ filePath: marginCss && !marginClass && !marginStyle ? marginCss.filePath : comp.filePath,
2227
+ lineNumber: marginCss && !marginClass && !marginStyle ? marginCss.lineNumber : root.lineNumber,
2228
+ snippet: root.snippet,
2229
+ });
2230
+ }
2231
+ }
2232
+ if (config.composability.flagFixedWidth) {
2233
+ const rootDecls = classTokens.flatMap((t) => cssDeclsByClass.get(t) ?? []);
2234
+ const isFloatingRoot = rootDecls.some((d) => d.prop === "position" && /^(?:absolute|fixed)$/i.test(d.value.trim()));
2235
+ const widthClass = classTokens.find((t) => {
2236
+ const base = t.split(":").pop() ?? t;
2237
+ const bracketMatch = base.match(/^(?:min-|max-)?w-\[(\d+(?:\.\d+)?(?:px|rem|em))\]$/);
2238
+ if (bracketMatch)
2239
+ return isExtrinsicFixedWidthValue(bracketMatch[1]);
2240
+ const numeric = base.match(/^w-(\d+)$/);
2241
+ return numeric !== null && Number(numeric[1]) >= 24;
2242
+ });
2243
+ const widthStyle = Object.entries(root.styleProps).find(([k, v]) => /^(?:width|minWidth)$/.test(k) && isExtrinsicFixedWidthValue(v));
2244
+ const widthCss = isFloatingRoot
2245
+ ? undefined
2246
+ : rootDecls.find((d) => /^(?:width|min-width)$/.test(d.prop) && isExtrinsicFixedWidthValue(d.value));
2247
+ if (widthClass || widthStyle || widthCss) {
2248
+ issues.push({
2249
+ kind: "fixed-width",
2250
+ component: comp.label,
2251
+ detail: widthClass
2252
+ ? `root <${root.tag}> has fixed width \`${widthClass}\``
2253
+ : widthStyle
2254
+ ? `root <${root.tag}> sets inline ${widthStyle[0]}: ${widthStyle[1]}`
2255
+ : `root <${root.tag}> class has CSS ${widthCss.prop}: ${widthCss.value}`,
2256
+ filePath: widthCss && !widthClass && !widthStyle ? widthCss.filePath : comp.filePath,
2257
+ lineNumber: widthCss && !widthClass && !widthStyle ? widthCss.lineNumber : root.lineNumber,
2258
+ snippet: root.snippet,
2259
+ });
2260
+ }
2261
+ }
2262
+ }
2263
+ if (comp.atomicTier === "ATOM") {
2264
+ for (const spec of facts.imports) {
2265
+ const hit = forbiddenImports.find((f) => spec === f || spec.startsWith(`${f}/`));
2266
+ if (hit) {
2267
+ issues.push({
2268
+ kind: "forbidden-import",
2269
+ component: comp.label,
2270
+ detail: `atom imports \`${spec}\` (binds a primitive to a router / data layer)`,
2271
+ filePath: comp.filePath,
2272
+ lineNumber: comp.lineNumber ?? 1,
2273
+ });
2274
+ }
2275
+ }
2276
+ }
2277
+ comp.composabilityIssues = issues;
2278
+ composabilityIssues.push(...issues);
2279
+ }
2280
+ const siblingAtomOverlaps = uiShapesAudit.allSiblingAtomOverlaps;
2281
+ const nestedInteractive = componentProfiles.flatMap((p) => p.nestedInteractive);
2282
+ const unextractedShapes = uiShapesAudit.allUnextractedShapes;
2283
+ const typographyAudit = analyzeTypographyAndContextualOverrides({
2284
+ styleRules: allStyleRules,
2285
+ tailwindGroups: allTailwindTypographyGroups,
2286
+ tokenMaps,
2287
+ });
2288
+ const undefinedCssClasses = [
2289
+ ...undefinedCssByClassName.entries(),
2290
+ ]
2291
+ .map(([className, occurrences]) => ({
2292
+ className,
2293
+ occurrenceCount: occurrences.length,
2294
+ occurrences,
2295
+ }))
2296
+ .sort((a, b) => b.occurrenceCount - a.occurrenceCount || a.className.localeCompare(b.className));
2297
+ const alignmentAudit = {
2298
+ bypassedAtoms,
2299
+ siblingAtomOverlaps,
2300
+ nestedInteractive,
2301
+ unextractedShapes,
2302
+ parallelTwins,
2303
+ callSiteOverrides,
2304
+ propApiDrift,
2305
+ invariantViolations,
2306
+ composabilityIssues,
2307
+ };
2308
+ // -------------------------------------------------------------------------
2309
+ // 16. Stage 4 — Structural DRY Audit (`structuralJsxClones` via Normalized JSX Skeleton Fingerprints)
2310
+ // -------------------------------------------------------------------------
2311
+ const skeletonsByHash = new Map();
2312
+ for (const comp of componentProfiles) {
2313
+ if (comp.atomicTier === "ATOM")
2314
+ continue;
2315
+ const seenLineInComp = new Set();
2316
+ for (const sk of comp.jsxSkeletons) {
2317
+ const locKey = `${sk.filePath}:${sk.lineNumber}:${sk.skeletonHash}`;
2318
+ if (seenLineInComp.has(locKey))
2319
+ continue;
2320
+ seenLineInComp.add(locKey);
2321
+ let list = skeletonsByHash.get(sk.skeletonHash);
2322
+ if (!list) {
2323
+ list = [];
2324
+ skeletonsByHash.set(sk.skeletonHash, list);
2325
+ }
2326
+ if (!list.some((item) => item.filePath === sk.filePath && item.lineNumber === sk.lineNumber)) {
2327
+ list.push({
2328
+ ...sk,
2329
+ componentName: comp.label,
2330
+ });
2331
+ }
2332
+ }
2333
+ }
2334
+ const rawCloneGroups = [];
2335
+ for (const [skeletonHash, occs] of skeletonsByHash.entries()) {
2336
+ const distinctFiles = new Set(occs.map((o) => o.filePath));
2337
+ const distinctComponents = new Set(occs.map((o) => o.componentName));
2338
+ // Report when a non-trivial JSX skeleton is duplicated across >= 2 files/components, or >= 3 times total
2339
+ if (distinctFiles.size >= 2 ||
2340
+ distinctComponents.size >= 2 ||
2341
+ occs.length >= 3) {
2342
+ const sample = occs[0];
2343
+ const suggested = inferSuggestedComponentName(sample.rootTag, sample.canonicalSignature, sample.elementCount);
2344
+ rawCloneGroups.push({
2345
+ skeletonHash,
2346
+ skeletonShape: sample.skeletonShape,
2347
+ canonicalSignature: sample.canonicalSignature,
2348
+ elementCount: sample.elementCount,
2349
+ occurrenceCount: occs.length,
2350
+ distinctFileCount: distinctFiles.size,
2351
+ suggestedTier: suggested.tier,
2352
+ suggestedComponentName: suggested.name,
2353
+ nameConfidence: suggested.confidence,
2354
+ compositional: sample.customCount >= 3,
2355
+ occurrences: occs.slice(0, 12).map((o) => ({
2356
+ componentName: o.componentName,
2357
+ filePath: o.filePath,
2358
+ lineNumber: o.lineNumber,
2359
+ snippet: o.snippet,
2360
+ })),
2361
+ });
2362
+ }
2363
+ }
2364
+ // Sort largest/most-duplicated clones first and suppress child sub-skeletons already covered by an enclosing parent clone
2365
+ rawCloneGroups.sort((a, b) => b.distinctFileCount - a.distinctFileCount ||
2366
+ b.occurrenceCount - a.occurrenceCount ||
2367
+ b.elementCount - a.elementCount);
2368
+ const structuralJsxClones = [];
2369
+ for (const candidate of rawCloneGroups) {
2370
+ const isSubtreeOfExisting = structuralJsxClones.some((accepted) => {
2371
+ const accWithSig = rawCloneGroups.find((r) => r.skeletonHash === accepted.skeletonHash);
2372
+ return (accWithSig &&
2373
+ accWithSig.canonicalSignature !== candidate.canonicalSignature &&
2374
+ accWithSig.canonicalSignature.includes(candidate.canonicalSignature) &&
2375
+ accepted.occurrenceCount >= candidate.occurrenceCount);
2376
+ });
2377
+ if (!isSubtreeOfExisting) {
2378
+ const { canonicalSignature: _unused, ...cleanGroup } = candidate;
2379
+ structuralJsxClones.push(cleanGroup);
2380
+ }
2381
+ }
2382
+ const dryAudit = {
2383
+ structuralJsxClones,
2384
+ atomicConsolidation,
2385
+ duplicateCssTokens: duplicateTokens,
2386
+ };
2387
+ // -------------------------------------------------------------------------
2388
+ // 17. Stage 5 — Measured pillars, bottom-up token derivation & Paved-Road Blueprint
2389
+ // -------------------------------------------------------------------------
2390
+ let arbitraryTailwindCount = 0;
2391
+ let magicSpacingCount = 0;
2392
+ let primitiveScaleSkipCount = 0;
2393
+ let inlineStyleLiteralCount = 0;
2394
+ let canvasCssSlotCount = 0;
2395
+ let canvasTsConstSlotCount = 0;
2396
+ let canvasLiteralSlotCount = 0;
2397
+ let rawDomPrimitiveCount = 0;
2398
+ const conventionBreakdown = {
2399
+ "css-classes": 0,
2400
+ "css-modules": 0,
2401
+ "css-in-js": 0,
2402
+ tailwind: 0,
2403
+ "inline-style": 0,
2404
+ "pixi-canvas": 0,
2405
+ };
2406
+ for (const comp of componentProfiles) {
2407
+ for (const conv of comp.stylingConventions) {
2408
+ conventionBreakdown[conv] = (conventionBreakdown[conv] ?? 0) + 1;
2409
+ }
2410
+ arbitraryTailwindCount += comp.arbitraryTailwind.length;
2411
+ magicSpacingCount += comp.magicSpacingUtilities.length;
2412
+ primitiveScaleSkipCount += comp.primitiveScaleSkips.length;
2413
+ inlineStyleLiteralCount += comp.inlineStyleLiterals.length;
2414
+ canvasCssSlotCount += comp.canvasProvenance.cssCount;
2415
+ canvasTsConstSlotCount += comp.canvasProvenance.tsConstCount;
2416
+ canvasLiteralSlotCount += comp.canvasProvenance.literalCount;
2417
+ rawDomPrimitiveCount += comp.rawDomPrimitives.length;
2418
+ }
2419
+ // 17a. Bottom-up derivation: every hardcoded color / length literal, clustered into candidate tokens
2420
+ const literalPool = [];
2421
+ for (const sheet of parsedCssList)
2422
+ literalPool.push(...sheet.literals);
2423
+ for (const scanned of scannedFiles.values()) {
2424
+ for (const bucket of scanned.functionsAndClasses.values()) {
2425
+ literalPool.push(...bucket.literalValues);
2426
+ for (const lit of bucket.inlineStyleLiterals) {
2427
+ const colors = extractColorLiterals(lit.value);
2428
+ const lengths = colors.length === 0 ? extractLengthLiterals(lit.value) : [];
2429
+ for (const c of colors) {
2430
+ literalPool.push({
2431
+ kind: "color",
2432
+ value: c,
2433
+ surface: "inline-style",
2434
+ context: lit.property,
2435
+ filePath: lit.filePath,
2436
+ lineNumber: lit.lineNumber,
2437
+ snippet: lit.snippet,
2438
+ });
2439
+ }
2440
+ for (const l of lengths) {
2441
+ literalPool.push({
2442
+ kind: "length",
2443
+ value: l,
2444
+ surface: "inline-style",
2445
+ context: lit.property,
2446
+ filePath: lit.filePath,
2447
+ lineNumber: lit.lineNumber,
2448
+ snippet: lit.snippet,
2449
+ });
2450
+ }
2451
+ }
2452
+ }
2453
+ }
2454
+ const rootDeclMap = new Map();
2455
+ const emptyDeclMap = new Map();
2456
+ for (const d of allTokenDecls) {
2457
+ if (d.scope === "global" && d.themeContext === "root") {
2458
+ rootDeclMap.set(d.name, d);
2459
+ }
2460
+ }
2461
+ const resolvedTokenValues = [];
2462
+ for (const d of rootDeclMap.values()) {
2463
+ const value = substituteVars(d.value, emptyDeclMap, rootDeclMap);
2464
+ if (value !== null && value !== "") {
2465
+ resolvedTokenValues.push({ name: d.name, value: normalizeBareHsl(value) });
2466
+ }
2467
+ }
2468
+ const derivedTokens = clusterLiteralValues(literalPool, resolvedTokenValues, config.clustering);
2469
+ // 17b. Measured pillars (ratios with evidence), computed globally and per package
2470
+ const BOILERPLATE_LIT_SURFACES = new Set(["tailwind-arbitrary"]);
2471
+ const computeMeasures = (profiles, includeStylesheetLiterals) => {
2472
+ const labels = new Set(profiles.map((p) => p.label));
2473
+ let hardcoded = 0;
2474
+ let tokenized = 0;
2475
+ for (const p of profiles) {
2476
+ hardcoded +=
2477
+ p.arbitraryTailwind.length +
2478
+ p.magicSpacingUtilities.length +
2479
+ p.primitiveScaleSkips.length +
2480
+ p.inlineStyleLiterals.length +
2481
+ p.canvasProvenance.literalCount +
2482
+ p.literalValues.filter((l) => !BOILERPLATE_LIT_SURFACES.has(l.surface)).length;
2483
+ const directTokenCount = p.tokensConsumed.length - p.bridgedTokensConsumed.length;
2484
+ tokenized +=
2485
+ directTokenCount + p.tailwindUtilityCount + p.canvasProvenance.cssCount;
2486
+ }
2487
+ if (includeStylesheetLiterals) {
2488
+ hardcoded += parsedCssList.reduce((n, sheet) => n + sheet.literals.length, 0);
2489
+ }
2490
+ const tokenAdherence = tokenized + hardcoded > 0 ? Math.round((tokenized / (tokenized + hardcoded)) * 100) : null;
2491
+ let adopters = 0;
2492
+ let raw = 0;
2493
+ for (const def of atomDefinitions) {
2494
+ if (!reportedAtomNames.has(def.name))
2495
+ continue;
2496
+ const names = sharedNamesByAtom.get(def.name);
2497
+ for (const p of profiles) {
2498
+ for (const r of p.rawDomPrimitives) {
2499
+ if (r.atomicTarget === def.name && !isOwnAtomImplementation(p.label, def.name))
2500
+ raw++;
2501
+ }
2502
+ for (const cs of p.jsxCallSites) {
2503
+ if (names.has(cs.targetComponent.toLowerCase()))
2504
+ adopters++;
2505
+ }
2506
+ }
2507
+ }
2508
+ const atomAdoption = adopters + raw > 0 ? Math.round((adopters / (adopters + raw)) * 100) : null;
2509
+ const participating = new Set();
2510
+ for (const g of structuralJsxClones) {
2511
+ for (const o of g.occurrences)
2512
+ if (labels.has(o.componentName))
2513
+ participating.add(o.componentName);
2514
+ }
2515
+ for (const t of parallelTwins) {
2516
+ for (const c of t.components)
2517
+ if (labels.has(c.label))
2518
+ participating.add(c.label);
2519
+ }
2520
+ const dryness = profiles.length > 0
2521
+ ? Math.max(0, 100 - Math.round((participating.size / profiles.length) * 100))
2522
+ : null;
2523
+ const totalCallSites = profiles.reduce((n, p) => n + p.jsxCallSites.length, 0);
2524
+ const overrides = callSiteOverrides.filter((o) => labels.has(o.parentComponent)).length +
2525
+ invariantViolations.filter((v) => labels.has(v.parentComponent)).length;
2526
+ const encapsulation = totalCallSites > 0
2527
+ ? Math.max(0, 100 - Math.round((overrides / totalCallSites) * 100))
2528
+ : null;
2529
+ return { tokenAdherence, atomAdoption, dryness, encapsulation };
2530
+ };
2531
+ const MEASURE_LABELS = {
2532
+ tokenAdherence: "Token usage",
2533
+ atomAdoption: "Shared component reuse",
2534
+ dryness: "No duplicate UI",
2535
+ encapsulation: "Clean component props",
2536
+ };
2537
+ const summarizeMeasures = (measures) => {
2538
+ const entries = Object.entries(measures);
2539
+ const evidenced = entries.filter(([, v]) => v !== null);
2540
+ const notes = entries
2541
+ .filter(([, v]) => v === null)
2542
+ .map(([k]) => `${MEASURE_LABELS[k] ?? k}: not applicable in this package (not scored)`);
2543
+ if (evidenced.length < 2) {
2544
+ notes.unshift("Fewer than two pillars have evidence; no overall grade is assigned.");
2545
+ return { score: null, grade: "N/A", notes };
2546
+ }
2547
+ const score = Math.round(evidenced.reduce((n, [, v]) => n + v, 0) / evidenced.length);
2548
+ const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 65 ? "C" : score >= 50 ? "D" : "F";
2549
+ return { score, grade, notes };
2550
+ };
2551
+ const globalMeasures = computeMeasures(componentProfiles, true);
2552
+ const globalSummary = summarizeMeasures(globalMeasures);
2553
+ const overallExtendabilityScore = globalSummary.score;
2554
+ const extendabilityGrade = globalSummary.grade;
2555
+ const allSemanticAndCompTokens = [
2556
+ ...semanticTokens,
2557
+ ...componentTokens,
2558
+ ].sort();
2559
+ const canonicalTokensByRole = {
2560
+ surfaces: allSemanticAndCompTokens
2561
+ .filter((t) => /surface|fill|bg|background|board|canvas|card|popover/i.test(t))
2562
+ .slice(0, 12),
2563
+ text: allSemanticAndCompTokens
2564
+ .filter((t) => /text|fg|foreground|label|heading/i.test(t))
2565
+ .slice(0, 12),
2566
+ borders: allSemanticAndCompTokens
2567
+ .filter((t) => /border|stroke|divider|outline|ring/i.test(t))
2568
+ .slice(0, 12),
2569
+ accents: allSemanticAndCompTokens
2570
+ .filter((t) => /accent|brand|primary|highlight|focus/i.test(t))
2571
+ .slice(0, 10),
2572
+ states: allSemanticAndCompTokens
2573
+ .filter((t) => /state|added|modified|removed|active|status|success|warning|danger|destructive/i.test(t))
2574
+ .slice(0, 12),
2575
+ };
2576
+ const reusableBuildingBlocks = [...componentProfiles]
2577
+ .filter((c) => c.atomicTier === "ATOM" ||
2578
+ c.atomicTier === "MOLECULE" ||
2579
+ c.atomicTier === "ORGANISM")
2580
+ .sort((a, b) => b.rendersInDegree - a.rendersInDegree ||
2581
+ b.usedInRoutes.length - a.usedInRoutes.length ||
2582
+ a.label.localeCompare(b.label))
2583
+ .slice(0, 12)
2584
+ .map((c) => {
2585
+ const propsStr = c.propContract.length > 0
2586
+ ? `{ ${c.propContract
2587
+ .slice(0, 5)
2588
+ .map((p) => `${p.name}${p.required ? "" : "?"}`)
2589
+ .join(", ")}${c.propContract.length > 5 ? ", ..." : ""} }`
2590
+ : "";
2591
+ return {
2592
+ entityId: c.entityId,
2593
+ label: c.label,
2594
+ atomicTier: c.atomicTier,
2595
+ filePath: c.filePath,
2596
+ rendersInDegree: c.rendersInDegree,
2597
+ propSignature: `<${c.label}${propsStr ? ` ${propsStr}` : ""} />`,
2598
+ };
2599
+ });
2600
+ const missingPrimitivesToExtract = [];
2601
+ for (const ac of atomicConsolidation.slice(0, 5)) {
2602
+ missingPrimitivesToExtract.push(ac.existingSharedComponent
2603
+ ? `Adopt shared <${ac.atomName}> (${ac.instanceCount} raw instances across ${ac.distinctFiles.length} files, ${ac.adoptionRate ?? 0}% adopted): ${ac.consolidationGuidance}`
2604
+ : `Extract shared <${ac.atomName}> Atom (${ac.instanceCount} raw DOM instances across ${ac.distinctFiles.length} files): ${ac.consolidationGuidance}`);
2605
+ }
2606
+ for (const clone of structuralJsxClones.slice(0, 3)) {
2607
+ const item = `Extract <${clone.suggestedComponentName}> (${clone.suggestedTier}${clone.nameConfidence === "low" ? ", rename needed" : ""}) from ${clone.occurrenceCount}x duplicated ${clone.compositional ? "component composition" : "JSX skeleton"} '${clone.skeletonShape}' across ${clone.distinctFileCount} file(s).`;
2608
+ if (!missingPrimitivesToExtract.includes(item)) {
2609
+ missingPrimitivesToExtract.push(item);
2610
+ }
2611
+ }
2612
+ for (const twin of parallelTwins.slice(0, 2)) {
2613
+ missingPrimitivesToExtract.push(`Align parallel ${twin.concept} components (${twin.components.map((c) => c.label).join(", ")}): ${twin.recommendation}`);
2614
+ }
2615
+ for (const dt of derivedTokens.slice(0, 3)) {
2616
+ missingPrimitivesToExtract.push(`${dt.recommendation} (${dt.members.length} distinct value(s), e.g. ${dt.members.slice(0, 3).map((m) => m.value).join(", ")}).`);
2617
+ }
2618
+ const sharedAtomNames = [...existingSharedByAtom.values()].map((e) => e.name);
2619
+ const primitiveExamples = [...primitiveColorTokenNames].sort().slice(0, 3);
2620
+ const propDriftPicks = propApiDrift
2621
+ .slice(0, 3)
2622
+ .map((g) => g.variants[0]?.propName ?? g.canonicalRecommendation);
2623
+ const agentExtendability = {
2624
+ overallScore: overallExtendabilityScore,
2625
+ grade: extendabilityGrade,
2626
+ evidenceNotes: globalSummary.notes,
2627
+ measures: globalMeasures,
2628
+ pavedRoadBlueprint: {
2629
+ canonicalTokensByRole,
2630
+ reusableBuildingBlocks,
2631
+ missingPrimitivesToExtract,
2632
+ extensionRules: [
2633
+ `1. LAYER COMPOSITION: Compose Routes from Templates -> Organisms -> Molecules -> Atoms. Do not inline raw DOM that an existing shared atom already covers${sharedAtomNames.length > 0 ? ` (${[...new Set(sharedAtomNames)].slice(0, 6).map((n) => `<${n}>`).join(", ")})` : ""}.`,
2634
+ `2. TOKEN DISCIPLINE: Consume semantic/component tokens from \`canonicalTokensByRole\`.${primitiveExamples.length > 0 ? ` Never reference primitive tokens directly in components (e.g. ${primitiveExamples.join(", ")}).` : ""} Do not introduce raw color/length literals; reuse an existing token or the nearest \`derivedTokens\` proposal.`,
2635
+ "3. ENCAPSULATION: Never inject inline `style={{ ... }}`, arbitrary Tailwind `[Npx]` overrides, or raw color literals onto a child `<Component />` call site; expose semantic `variant` or `size` props on the child instead.",
2636
+ propDriftPicks.length > 0
2637
+ ? `4. PROP CONSISTENCY: Reuse the repo's dominant prop spellings (${propDriftPicks.join(", ")}) rather than introducing synonyms.`
2638
+ : "4. PROP CONSISTENCY: Reuse existing prop names for the same concept (open/close/checked/disabled) rather than introducing synonyms.",
2639
+ ],
2640
+ },
2641
+ };
2642
+ // -------------------------------------------------------------------------
2643
+ // 18. Build Concise, Non-Overwhelming `L1_DESIGN_SYSTEM` Overlays for Inspector Drawers
2644
+ // -------------------------------------------------------------------------
2645
+ const componentOverlays = [];
2646
+ for (const profile of componentProfiles) {
2647
+ const compCloneGroups = structuralJsxClones.filter((g) => g.occurrences.some((o) => o.componentName === profile.label));
2648
+ // Do not attach a Design System overlay to pure non-UI helper functions
2649
+ const isNonUiUtility = profile.atomicTier === "UTILITY" &&
2650
+ profile.jsxDomElementCount === 0 &&
2651
+ profile.jsxCustomComponentCount === 0 &&
2652
+ profile.stylingConventions.length === 0 &&
2653
+ profile.tokensConsumed.length === 0 &&
2654
+ !profile.canvasProvenance.usesSlotRecorder &&
2655
+ profile.undefinedTokens.length === 0 &&
2656
+ profile.undefinedCssClasses.length === 0 &&
2657
+ profile.arbitraryTailwind.length === 0 &&
2658
+ profile.magicSpacingUtilities.length === 0 &&
2659
+ profile.primitiveScaleSkips.length === 0 &&
2660
+ profile.inlineStyleLiterals.length === 0 &&
2661
+ profile.canvasProvenance.literalCount === 0 &&
2662
+ profile.rawDomPrimitives.length === 0 &&
2663
+ profile.nestedInteractive.length === 0 &&
2664
+ compCloneGroups.length === 0;
2665
+ if (isNonUiUtility) {
2666
+ continue;
2667
+ }
2668
+ const isCanvasRenderer = profile.canvasProvenance.usesSlotRecorder ||
2669
+ (profile.stylingConventions.includes("pixi-canvas") &&
2670
+ profile.jsxDomElementCount === 0);
2671
+ const layerLabel = isCanvasRenderer
2672
+ ? "Canvas Renderer"
2673
+ : profile.atomicTier === "ROUTE"
2674
+ ? "Page"
2675
+ : profile.atomicTier === "TEMPLATE"
2676
+ ? "Template"
2677
+ : profile.atomicTier === "ORGANISM"
2678
+ ? "Organism"
2679
+ : profile.atomicTier === "MOLECULE"
2680
+ ? "Molecule"
2681
+ : profile.atomicTier === "ATOM"
2682
+ ? "Atom"
2683
+ : "Utility";
2684
+ const stylingLabels = [];
2685
+ for (const conv of profile.stylingConventions) {
2686
+ if (conv === "tailwind")
2687
+ stylingLabels.push("Tailwind");
2688
+ else if (conv === "css-classes")
2689
+ stylingLabels.push(profile.tokensConsumed.length > 0 ? "CSS Variables" : "CSS");
2690
+ else if (conv === "pixi-canvas")
2691
+ stylingLabels.push("Canvas 2D");
2692
+ else if (conv === "inline-style")
2693
+ stylingLabels.push("Inline");
2694
+ else if (conv === "css-modules")
2695
+ stylingLabels.push("CSS Modules");
2696
+ else if (conv === "css-in-js")
2697
+ stylingLabels.push("CSS-in-JS");
2698
+ }
2699
+ if (profile.tokensConsumed.length > 0 &&
2700
+ !stylingLabels.includes("CSS Variables")) {
2701
+ stylingLabels.push("CSS Variables");
2702
+ }
2703
+ // Concise variant/configuration props for Atoms & Molecules
2704
+ const BOILERPLATE_PROPS = new Set([
2705
+ "children",
2706
+ "className",
2707
+ "onClick",
2708
+ "onClose",
2709
+ "onChange",
2710
+ "style",
2711
+ "id",
2712
+ "key",
2713
+ "ref",
2714
+ "ariaLabel",
2715
+ "title",
2716
+ ]);
2717
+ const variantProps = profile.atomicTier === "ATOM" || profile.atomicTier === "MOLECULE"
2718
+ ? profile.propContract
2719
+ .filter((p) => !BOILERPLATE_PROPS.has(p.name))
2720
+ .slice(0, 5)
2721
+ .map((p) => p.name)
2722
+ : [];
2723
+ // 1. Unshared primitives (grouped by tag -> target Atom with line numbers)
2724
+ const unsharedPrimitives = [];
2725
+ if (profile.atomicTier !== "ATOM" && profile.rawDomPrimitives.length > 0) {
2726
+ const byTarget = new Map();
2727
+ for (const rawDom of profile.rawDomPrimitives) {
2728
+ const key = `${rawDom.tagOrRole}->${rawDom.atomicTarget}`;
2729
+ let group = byTarget.get(key);
2730
+ if (!group) {
2731
+ group = {
2732
+ tagOrRole: rawDom.tagOrRole,
2733
+ target: rawDom.atomicTarget,
2734
+ lines: [],
2735
+ };
2736
+ byTarget.set(key, group);
2737
+ }
2738
+ if (rawDom.lineNumber &&
2739
+ !group.lines.includes(rawDom.lineNumber) &&
2740
+ group.lines.length < 4) {
2741
+ group.lines.push(rawDom.lineNumber);
2742
+ }
2743
+ }
2744
+ for (const group of byTarget.values()) {
2745
+ const lineSuffix = group.lines.length > 0
2746
+ ? ` (${group.lines.map((l) => `L${l}`).join(", ")})`
2747
+ : "";
2748
+ unsharedPrimitives.push(`Raw ${group.tagOrRole}${lineSuffix} → use <${group.target}>`);
2749
+ }
2750
+ }
2751
+ // 2. Hardcoded values (arbitrary Tailwind + primitive scale skips + inline style literals + canvas literals)
2752
+ const hardcodedValues = [];
2753
+ const seenHardcoded = new Set();
2754
+ const pushHardcoded = (item) => {
2755
+ if (!seenHardcoded.has(item)) {
2756
+ seenHardcoded.add(item);
2757
+ hardcodedValues.push(item);
2758
+ }
2759
+ };
2760
+ for (const tw of profile.arbitraryTailwind) {
2761
+ pushHardcoded(`${tw.className} (L${tw.lineNumber})`);
2762
+ }
2763
+ for (const skip of profile.primitiveScaleSkips) {
2764
+ pushHardcoded(`${skip.tokenOrClass} (L${skip.lineNumber})`);
2765
+ }
2766
+ for (const lit of profile.inlineStyleLiterals) {
2767
+ pushHardcoded(`${lit.property}: ${lit.value} (L${lit.lineNumber})`);
2768
+ }
2769
+ for (const cLit of profile.canvasProvenance.literals) {
2770
+ pushHardcoded(`${cLit.slot}.${cLit.prop}=${cLit.value} (L${cLit.lineNumber})`);
2771
+ }
2772
+ for (const lit of profile.literalValues) {
2773
+ if (lit.surface === "tailwind-arbitrary")
2774
+ continue; // already listed via arbitraryTailwind
2775
+ pushHardcoded(`${lit.context ? `${lit.context}: ` : ""}${lit.value} (L${lit.lineNumber})`);
2776
+ }
2777
+ for (const v of profile.invariantViolations) {
2778
+ pushHardcoded(`<${v.childComponent} ${v.prop}="${v.value}"> (L${v.lineNumber})`);
2779
+ }
2780
+ const composability = profile.composabilityIssues.map((c) => `${c.kind}: ${c.detail}`);
2781
+ // 3. Duplicate markup (DRY JSX clones)
2782
+ const duplicateMarkup = compCloneGroups.map((g) => `<${g.suggestedComponentName}> (${g.occurrenceCount}× repeated)`);
2783
+ // 4. Missing tokens (undefined var(--*))
2784
+ const missingTokens = profile.undefinedTokens.map((u) => {
2785
+ const firstLine = u.occurrences[0]?.lineNumber;
2786
+ return firstLine ? `${u.name} (L${firstLine})` : u.name;
2787
+ });
2788
+ const findingCount = unsharedPrimitives.length +
2789
+ hardcodedValues.length +
2790
+ duplicateMarkup.length +
2791
+ missingTokens.length +
2792
+ composability.length;
2793
+ const overlayEvidence = [];
2794
+ for (const u of profile.undefinedTokens) {
2795
+ for (const occ of u.occurrences.slice(0, 2)) {
2796
+ overlayEvidence.push(ctx.evidence(occ.filePath, occ.lineNumber, occ.snippet, `missing-token:${u.name}`));
2797
+ }
2798
+ }
2799
+ for (const clone of compCloneGroups.slice(0, 2)) {
2800
+ const occ = clone.occurrences.find((o) => o.componentName === profile.label);
2801
+ if (occ) {
2802
+ overlayEvidence.push(ctx.evidence(occ.filePath, occ.lineNumber, occ.snippet, `duplicate-markup:${clone.suggestedComponentName}`));
2803
+ }
2804
+ }
2805
+ for (const tw of profile.arbitraryTailwind.slice(0, 3)) {
2806
+ overlayEvidence.push(ctx.evidence(tw.filePath, tw.lineNumber, tw.snippet, `hardcoded:${tw.className}`));
2807
+ }
2808
+ for (const skip of profile.primitiveScaleSkips.slice(0, 2)) {
2809
+ overlayEvidence.push(ctx.evidence(skip.filePath, skip.lineNumber, skip.snippet, `hardcoded:${skip.tokenOrClass}`));
2810
+ }
2811
+ for (const litItem of profile.canvasProvenance.literals.slice(0, 3)) {
2812
+ overlayEvidence.push(ctx.evidence(litItem.filePath, litItem.lineNumber, litItem.snippet, `hardcoded:${litItem.slot}.${litItem.prop}=${litItem.value}`));
2813
+ }
2814
+ for (const rawDom of profile.rawDomPrimitives.slice(0, 3)) {
2815
+ overlayEvidence.push(ctx.evidence(rawDom.filePath, rawDom.lineNumber, rawDom.snippet, `unshared-primitive:${rawDom.atomicTarget}`));
2816
+ }
2817
+ if (!realGraphNodeIds.has(profile.entityId)) {
2818
+ continue;
2819
+ }
2820
+ componentOverlays.push({
2821
+ repositoryId: ctx.repoId,
2822
+ entityId: profile.entityId,
2823
+ layer: "L1_DESIGN_SYSTEM",
2824
+ source: "design-system",
2825
+ environment: ctx.environment,
2826
+ derivation: "EXTRACTED",
2827
+ inputs: [
2828
+ ...cssInputDeps,
2829
+ ...(() => {
2830
+ const dep = ctx.hashFile(profile.filePath);
2831
+ return dep ? [dep] : [];
2832
+ })(),
2833
+ ],
2834
+ evidence: overlayEvidence,
2835
+ payload: {
2836
+ layer: layerLabel,
2837
+ ...(stylingLabels.length > 0 ? { styling: stylingLabels } : {}),
2838
+ ...(variantProps.length > 0 ? { variantProps } : {}),
2839
+ ...(profile.tokensConsumed.length > 0
2840
+ ? { designTokens: profile.tokensConsumed }
2841
+ : {}),
2842
+ ...(profile.canvasProvenance.usesSlotRecorder
2843
+ ? {
2844
+ themeSlots: `${profile.canvasProvenance.cssCount} CSS tokens · ${profile.canvasProvenance.tsConstCount} constants`,
2845
+ }
2846
+ : {}),
2847
+ ...(unsharedPrimitives.length > 0 ? { unsharedPrimitives } : {}),
2848
+ ...(hardcodedValues.length > 0 ? { hardcodedValues } : {}),
2849
+ ...(duplicateMarkup.length > 0 ? { duplicateMarkup } : {}),
2850
+ ...(missingTokens.length > 0 ? { missingTokens } : {}),
2851
+ ...(composability.length > 0 ? { composability } : {}),
2852
+ findingCount,
2853
+ // Retain machine baseline fields for `diffDesignSystem` working-tree regression checks
2854
+ metrics: {
2855
+ tokens: profile.tokensConsumed.length,
2856
+ composes: profile.renderedComponents.length,
2857
+ routes: profile.usedInRoutes.length,
2858
+ arbitraryTw: profile.arbitraryTailwind.length,
2859
+ literals: profile.inlineStyleLiterals.length +
2860
+ profile.canvasProvenance.literalCount,
2861
+ rawDom: profile.rawDomPrimitives.length,
2862
+ },
2863
+ ...(profile.undefinedTokens.length > 0
2864
+ ? {
2865
+ undefinedTokens: profile.undefinedTokens.map((u) => u.name),
2866
+ }
2867
+ : {}),
2868
+ ...(profile.arbitraryTailwind.length > 0
2869
+ ? {
2870
+ arbitraryTailwind: Array.from(new Set(profile.arbitraryTailwind.map((a) => a.className))),
2871
+ }
2872
+ : {}),
2873
+ ...(profile.primitiveScaleSkips.length > 0
2874
+ ? {
2875
+ primitiveScaleSkips: Array.from(new Set(profile.primitiveScaleSkips.map((s) => s.tokenOrClass))),
2876
+ }
2877
+ : {}),
2878
+ },
2879
+ });
2880
+ }
2881
+ // 19. Attach Concise Package-Level `L1_DESIGN_SYSTEM` Overlay onto Frontend `DEPLOYMENT_UNIT`(s)
2882
+ const frontendBoundaryNodes = [];
2883
+ for (const du of deploymentUnitsById.values()) {
2884
+ const ev = getPrimaryNodeEvidence(du);
2885
+ const fp = ev.filePath ?? "";
2886
+ const matchesFrontendPackage = scope.includedDirs.some((dir) => dir === "." ? fp === "package.json" : fp === dir || fp.startsWith(`${dir}/`));
2887
+ if (matchesFrontendPackage) {
2888
+ frontendBoundaryNodes.push(du);
2889
+ }
2890
+ }
2891
+ for (const du of frontendBoundaryNodes) {
2892
+ const pkgEvidence = [];
2893
+ for (const u of undefinedTokens.slice(0, 3)) {
2894
+ const occ = u.occurrences[0];
2895
+ if (occ) {
2896
+ pkgEvidence.push(ctx.evidence(occ.filePath, occ.lineNumber, occ.snippet, `missing-token:${u.name}`));
2897
+ }
2898
+ }
2899
+ for (const clone of structuralJsxClones.slice(0, 3)) {
2900
+ const occ = clone.occurrences[0];
2901
+ if (occ) {
2902
+ pkgEvidence.push(ctx.evidence(occ.filePath, occ.lineNumber, `${clone.skeletonShape} (${clone.occurrenceCount}x across ${clone.distinctFileCount} files)`, `duplicate-markup:${clone.suggestedComponentName}`));
2903
+ }
2904
+ }
2905
+ for (const cf of contrastFailures.slice(0, 3)) {
2906
+ if (cf.filePath) {
2907
+ pkgEvidence.push(ctx.evidence(cf.filePath, cf.lineNumber, `${cf.foregroundToken} on ${cf.backgroundToken} (dark: ${cf.dark?.ratio ?? "-"}:1, light: ${cf.light?.ratio ?? "-"}:1, min: ${cf.minRequiredRatio}:1)`, `contrast-fail:${cf.pairId}`));
2908
+ }
2909
+ }
2910
+ const cleanPkgName = du.name.replace(/^Deployment Unit:\s*/i, "").trim();
2911
+ const pkgShortKey = cleanPkgName.replace(/^@[^/]+\//, "");
2912
+ const pkgProfiles = componentProfiles.filter((p) => p.packageName === pkgShortKey);
2913
+ const pkgLabels = new Set(pkgProfiles.map((p) => p.label));
2914
+ const pkgMeasures = computeMeasures(pkgProfiles, false);
2915
+ const pkgSummary = summarizeMeasures(pkgMeasures);
2916
+ const pkgBypassed = bypassedAtoms.filter((b) => pkgLabels.has(b.bypassingComponent));
2917
+ const pkgClones = structuralJsxClones.filter((g) => g.occurrences.some((o) => pkgLabels.has(o.componentName)));
2918
+ const pkgTwins = parallelTwins.filter((t) => t.components.some((c) => pkgLabels.has(c.label)));
2919
+ const pkgInvariants = invariantViolations.filter((v) => pkgLabels.has(v.parentComponent));
2920
+ const pkgComposability = composabilityIssues.filter((c) => pkgLabels.has(c.component));
2921
+ const pkgTierCounts = {
2922
+ ROUTE: 0,
2923
+ TEMPLATE: 0,
2924
+ ORGANISM: 0,
2925
+ MOLECULE: 0,
2926
+ ATOM: 0,
2927
+ UTILITY: 0,
2928
+ };
2929
+ for (const p of pkgProfiles)
2930
+ pkgTierCounts[p.atomicTier]++;
2931
+ const totalHardcodedCount = pkgProfiles.reduce((n, p) => n +
2932
+ p.arbitraryTailwind.length +
2933
+ p.primitiveScaleSkips.length +
2934
+ p.inlineStyleLiterals.length +
2935
+ p.canvasProvenance.literalCount +
2936
+ p.literalValues.filter((l) => l.surface !== "tailwind-arbitrary").length, 0);
2937
+ const openFindings = [];
2938
+ if (undefinedTokens.length > 0) {
2939
+ openFindings.push({
2940
+ label: "Missing tokens",
2941
+ value: `${undefinedTokens.length} undefined var(--*)`,
2942
+ });
2943
+ }
2944
+ if (contrastFailures.length > 0) {
2945
+ openFindings.push({
2946
+ label: "WCAG contrast",
2947
+ value: `${contrastFailures.length} failing pair(s)`,
2948
+ });
2949
+ }
2950
+ if (duplicateTokens.length > 0) {
2951
+ openFindings.push({
2952
+ label: "Duplicate tokens",
2953
+ value: `${duplicateTokens.length} across stylesheets`,
2954
+ });
2955
+ }
2956
+ if (contrastUnresolved.length > 0) {
2957
+ openFindings.push({
2958
+ label: "Contrast not evaluated",
2959
+ value: `${contrastUnresolved.length} pair/theme(s) unresolved`,
2960
+ });
2961
+ }
2962
+ if (pkgClones.length > 0) {
2963
+ openFindings.push({
2964
+ label: "Duplicate markup",
2965
+ value: `${pkgClones.length} repeated JSX block(s)`,
2966
+ });
2967
+ }
2968
+ if (pkgBypassed.length > 0) {
2969
+ const topAtoms = Array.from(new Set(pkgBypassed.map((b) => `<${b.atomTarget}>`))).slice(0, 3);
2970
+ openFindings.push({
2971
+ label: "Unshared primitives",
2972
+ value: `${pkgBypassed.length} raw element(s) → ${topAtoms.join(", ")}`,
2973
+ });
2974
+ }
2975
+ if (pkgInvariants.length > 0) {
2976
+ openFindings.push({
2977
+ label: "Prop literal violations",
2978
+ value: `${pkgInvariants.length} raw color literal(s) passed to token props`,
2979
+ });
2980
+ }
2981
+ if (pkgComposability.length > 0) {
2982
+ openFindings.push({
2983
+ label: "Composability",
2984
+ value: `${pkgComposability.length} hidden margin / fixed width / data-layer import(s)`,
2985
+ });
2986
+ }
2987
+ if (pkgTwins.length > 0) {
2988
+ const twinDesc = pkgTwins
2989
+ .slice(0, 2)
2990
+ .map((t) => t.components.map((c) => c.label).join(" / "))
2991
+ .join(", ");
2992
+ openFindings.push({
2993
+ label: "Parallel components",
2994
+ value: twinDesc,
2995
+ });
2996
+ }
2997
+ if (totalHardcodedCount > 0) {
2998
+ openFindings.push({
2999
+ label: "Hardcoded values",
3000
+ value: `${totalHardcodedCount} untokenized value(s)`,
3001
+ });
3002
+ }
3003
+ const passedChecks = [];
3004
+ if (contrastFailures.length === 0 &&
3005
+ contrastAudits.length > 0 &&
3006
+ contrastUnresolved.length === 0) {
3007
+ passedChecks.push(`${contrastAudits.length}/${contrastCandidateCount} WCAG contrast`);
3008
+ }
3009
+ if (undefinedTokens.length === 0) {
3010
+ passedChecks.push("0 missing tokens");
3011
+ }
3012
+ if (duplicateTokens.length === 0) {
3013
+ passedChecks.push("0 duplicate tokens");
3014
+ }
3015
+ if (pkgClones.length === 0) {
3016
+ passedChecks.push("0 duplicate markup");
3017
+ }
3018
+ componentOverlays.unshift({
3019
+ repositoryId: ctx.repoId,
3020
+ entityId: du.id,
3021
+ layer: "L1_DESIGN_SYSTEM",
3022
+ source: "design-system",
3023
+ environment: ctx.environment,
3024
+ derivation: "EXTRACTED",
3025
+ inputs: cssInputDeps,
3026
+ evidence: pkgEvidence,
3027
+ payload: {
3028
+ isPackageOverlay: true,
3029
+ packageName: cleanPkgName,
3030
+ packageShortKey: pkgShortKey,
3031
+ ...(pkgSummary.score !== null ? { score: pkgSummary.score } : {}),
3032
+ grade: pkgSummary.grade,
3033
+ findingCount: openFindings.length,
3034
+ // Measured, per-package ratios (a pillar is omitted when this package gives no evidence for it)
3035
+ pillars: {
3036
+ ...(pkgMeasures.atomAdoption !== null ? { componentReuse: pkgMeasures.atomAdoption } : {}),
3037
+ ...(pkgMeasures.tokenAdherence !== null ? { tokenCoverage: pkgMeasures.tokenAdherence } : {}),
3038
+ ...(pkgMeasures.encapsulation !== null ? { consistency: pkgMeasures.encapsulation } : {}),
3039
+ ...(pkgMeasures.dryness !== null ? { dryMarkup: pkgMeasures.dryness } : {}),
3040
+ },
3041
+ evidenceNotes: pkgSummary.notes,
3042
+ inventory: {
3043
+ pages: pkgTierCounts.ROUTE + pkgTierCounts.TEMPLATE,
3044
+ organisms: pkgTierCounts.ORGANISM,
3045
+ molecules: pkgTierCounts.MOLECULE,
3046
+ atoms: pkgTierCounts.ATOM,
3047
+ tokens: definedTokenNames.size,
3048
+ },
3049
+ openFindings,
3050
+ passedChecks,
3051
+ agentExtendability: pkgSummary.score !== null ? `${pkgSummary.score}/100 (${pkgSummary.grade})` : "N/A",
3052
+ metrics: {
3053
+ extendabilityScore: pkgSummary.score,
3054
+ routes: pkgTierCounts.ROUTE,
3055
+ components: pkgProfiles.length,
3056
+ definedTokens: definedTokenNames.size,
3057
+ jsxClones: pkgClones.length,
3058
+ contrastFailures: contrastFailures.length,
3059
+ },
3060
+ },
3061
+ });
3062
+ }
3063
+ const unsupportedFiles = [...unsupportedByExt.entries()]
3064
+ .map(([extension, files]) => ({
3065
+ extension,
3066
+ count: files.length,
3067
+ sample: files.slice(0, 5),
3068
+ }))
3069
+ .sort((a, b) => b.count - a.count || a.extension.localeCompare(b.extension));
3070
+ const unsupportedFileCount = unsupportedFiles.reduce((n, u) => n + u.count, 0);
3071
+ const themesObserved = [
3072
+ ...new Set(allTokenDecls.filter((d) => d.scope === "global").map((d) => d.themeContext)),
3073
+ ].sort();
3074
+ const coverageNotes = [];
3075
+ if (scope.includedDirs.length === 0) {
3076
+ coverageNotes.push("No frontend packages were detected. Set `designSystem.scope.packages` in chomp.config.json to opt packages in explicitly.");
3077
+ }
3078
+ if (unsupportedFileCount > 0) {
3079
+ coverageNotes.push(`${unsupportedFileCount} file(s) in frontend packages use a style/markup language this plugin does not parse (${unsupportedFiles.map((u) => u.extension).join(", ")}); findings do not cover them.`);
3080
+ }
3081
+ if (contrastUnresolved.length > 0) {
3082
+ coverageNotes.push(`${contrastUnresolved.length} contrast pair/theme combination(s) could not be evaluated (see coverage.contrastUnresolved); absence of failures does not mean they pass.`);
3083
+ }
3084
+ if (contrastAudits.length === 0 && contrastUnresolved.length === 0) {
3085
+ coverageNotes.push("No contrast pairs were found: declare fg/bg token pairs in `designSystem.contrast.pairs` or follow a `--x` / `--x-foreground` naming pair convention.");
3086
+ }
3087
+ if (resolved.mode === "adhere" && !resolved.declaresSystem) {
3088
+ coverageNotes.push(resolved.modeReason);
3089
+ }
3090
+ coverageNotes.push(...resolved.warnings);
3091
+ const systemInfo = {
3092
+ mode: resolved.mode,
3093
+ modeReason: resolved.modeReason,
3094
+ configPath: resolved.configPath,
3095
+ configWarnings: resolved.warnings,
3096
+ packages: scope.packages,
3097
+ atomCatalog: atomDefinitions.map((d) => d.name),
3098
+ tokenSources: config.tokens.sources,
3099
+ tierSources,
3100
+ themesObserved,
3101
+ primaryTokenFiles: (() => {
3102
+ const counts = new Map();
3103
+ for (const d of allTokenDecls) {
3104
+ if (d.scope !== "global" || d.selector === "js-variable" || d.themeContext === "theme-bridge")
3105
+ continue;
3106
+ counts.set(d.filePath, (counts.get(d.filePath) ?? 0) + 1);
3107
+ }
3108
+ return [...counts.entries()]
3109
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
3110
+ .slice(0, 2)
3111
+ .map(([f]) => f);
3112
+ })(),
3113
+ };
3114
+ // 18b. Enrich per-component `observedStates`, `health`, and `similarComponents`
3115
+ const STATE_ORDER = [
3116
+ "rest",
3117
+ "active",
3118
+ "passive",
3119
+ "disabled",
3120
+ "loading",
3121
+ "added",
3122
+ "modified",
3123
+ "removed",
3124
+ "warning",
3125
+ ];
3126
+ const cloneCountForComp = (p) => {
3127
+ let n = 0;
3128
+ for (const g of structuralJsxClones) {
3129
+ if (g.occurrences.some((o) => o.componentName === p.label && o.filePath === p.filePath)) {
3130
+ n++;
3131
+ }
3132
+ }
3133
+ return n;
3134
+ };
3135
+ const overrideCountByParent = new Map();
3136
+ for (const ov of alignmentAudit.callSiteOverrides) {
3137
+ overrideCountByParent.set(ov.parentComponent, (overrideCountByParent.get(ov.parentComponent) ?? 0) + 1);
3138
+ }
3139
+ const directNodesById = new Map();
3140
+ for (const p of componentProfiles) {
3141
+ const detectedStates = new Set(["rest"]);
3142
+ const propNamesLower = p.propContract.map((pr) => pr.name.toLowerCase());
3143
+ const variantValuesLower = [
3144
+ ...p.propContract.flatMap((pr) => pr.variants ?? []),
3145
+ ...Object.values(p.variantAxes).flat(),
3146
+ ].map((v) => v.toLowerCase());
3147
+ const styleSignalsLower = [
3148
+ ...p.tokensConsumed,
3149
+ ...p.cssClassesUsed,
3150
+ ...p.dynamicClassPrefixes,
3151
+ ].map((s) => s.toLowerCase());
3152
+ const renderedLower = [p.label, ...p.renderedComponents].map((s) => s.toLowerCase());
3153
+ const hasPropMatching = (re) => propNamesLower.some((n) => re.test(n));
3154
+ const hasVariantMatching = (re) => variantValuesLower.some((v) => re.test(v));
3155
+ const hasStyleMatching = (re) => styleSignalsLower.some((s) => re.test(s));
3156
+ const hasRenderedMatching = (re) => renderedLower.some((s) => re.test(s));
3157
+ if (hasPropMatching(/^(?:active|isactive|selected|isselected|open|isopen|checked|pressed|expanded)$/) ||
3158
+ hasVariantMatching(/^(?:active|selected|open|pressed|expanded)$/) ||
3159
+ hasStyleMatching(/(?:--active|-active|selected|--open|aria-selected|interactive-active)/)) {
3160
+ detectedStates.add("active");
3161
+ }
3162
+ if (hasPropMatching(/^(?:passive|ispassive|muted|dimmed|subtle|inactive|secondary)$/) ||
3163
+ hasVariantMatching(/^(?:passive|muted|subtle|inactive|secondary)$/) ||
3164
+ hasStyleMatching(/(?:passive|muted|subtle|inactive|dimmed|secondary)/)) {
3165
+ detectedStates.add("passive");
3166
+ }
3167
+ if (hasPropMatching(/^(?:disabled|isdisabled|readonly)$/) ||
3168
+ hasStyleMatching(/(?:disabled|readonly)/)) {
3169
+ detectedStates.add("disabled");
3170
+ }
3171
+ if (hasPropMatching(/^(?:loading|isloading|pending|busy|progress|fetching)$/) ||
3172
+ hasStyleMatching(/(?:loading|skeleton|spinner|progress|pulse)/) ||
3173
+ hasRenderedMatching(/(?:loading|progress|skeleton|spinner)/)) {
3174
+ detectedStates.add("loading");
3175
+ }
3176
+ const hasDiffAtom = renderedLower.some((r) => r.includes("diffbadge"));
3177
+ const hasGenericDiffProp = hasPropMatching(/^(?:diffstatus|changetype|changekind|diff)$/);
3178
+ if (hasDiffAtom ||
3179
+ hasGenericDiffProp ||
3180
+ hasPropMatching(/^added$/) ||
3181
+ hasVariantMatching(/^added$/) ||
3182
+ hasStyleMatching(/--status-added|--diff-added|\badded\b/)) {
3183
+ detectedStates.add("added");
3184
+ }
3185
+ if (hasDiffAtom ||
3186
+ hasGenericDiffProp ||
3187
+ hasPropMatching(/^modified$/) ||
3188
+ hasVariantMatching(/^modified$/) ||
3189
+ hasStyleMatching(/--status-modified|--diff-modified|\bmodified\b/)) {
3190
+ detectedStates.add("modified");
3191
+ }
3192
+ if (hasDiffAtom ||
3193
+ hasGenericDiffProp ||
3194
+ hasPropMatching(/^removed$/) ||
3195
+ hasVariantMatching(/^removed$/) ||
3196
+ hasStyleMatching(/--status-removed|--diff-removed|\bremoved\b/)) {
3197
+ detectedStates.add("removed");
3198
+ }
3199
+ if (hasPropMatching(/^(?:error|warning|invalid|danger|severity|tone)$/) ||
3200
+ hasVariantMatching(/^(?:warn|warning|error|danger|critical)$/) ||
3201
+ hasStyleMatching(/--status-warning|--status-removed|--danger|warning|danger|critical|alert|banner/) ||
3202
+ hasRenderedMatching(/banner|warning|alert/)) {
3203
+ detectedStates.add("warning");
3204
+ }
3205
+ p.observedStates = STATE_ORDER.filter((s) => detectedStates.has(s));
3206
+ const rawDomBypasses = p.rawDomPrimitives.filter((r) => !isCompAuthorizedForAtom(p, r.atomicTarget)).length;
3207
+ const siblingAtomOverlapsComp = p.siblingAtomOverlaps.length;
3208
+ const nestedInteractiveComp = p.nestedInteractive.length;
3209
+ const magicSpacingComp = p.magicSpacingUtilities.length;
3210
+ const undefinedCssComp = p.undefinedCssClasses.length;
3211
+ const warnShapesComp = p.unextractedShapes.filter((s) => s.tone === "warn").length;
3212
+ const duplicateClones = cloneCountForComp(p);
3213
+ const callSiteOverrides = (overrideCountByParent.get(p.label) ?? 0) + p.invariantViolations.length;
3214
+ const hardcodedLiterals = p.inlineStyleLiterals.length +
3215
+ p.canvasProvenance.literalCount +
3216
+ p.literalValues.filter((l) => !BOILERPLATE_LIT_SURFACES.has(l.surface)).length;
3217
+ const arbitraryTailwindCountComp = p.arbitraryTailwind.length;
3218
+ const primitiveSkipsComp = p.primitiveScaleSkips.length;
3219
+ const composabilityCountComp = p.composabilityIssues.length;
3220
+ const undefinedTokensComp = p.undefinedTokens.length;
3221
+ const directTokenCount = Math.max(0, p.tokensConsumed.length - p.bridgedTokensConsumed.length);
3222
+ const tokenized = directTokenCount + p.tailwindUtilityCount + p.canvasProvenance.cssCount;
3223
+ const hardcodedForAdherence = arbitraryTailwindCountComp + magicSpacingComp + primitiveSkipsComp + hardcodedLiterals;
3224
+ const tokenAdherence = tokenized + hardcodedForAdherence > 0
3225
+ ? Math.round((tokenized / (tokenized + hardcodedForAdherence)) * 100)
3226
+ : null;
3227
+ const issueCount = arbitraryTailwindCountComp +
3228
+ magicSpacingComp +
3229
+ primitiveSkipsComp +
3230
+ hardcodedLiterals +
3231
+ rawDomBypasses +
3232
+ siblingAtomOverlapsComp +
3233
+ nestedInteractiveComp +
3234
+ warnShapesComp +
3235
+ composabilityCountComp +
3236
+ undefinedTokensComp +
3237
+ undefinedCssComp +
3238
+ duplicateClones +
3239
+ callSiteOverrides;
3240
+ const penalty = undefinedTokensComp * 15 +
3241
+ undefinedCssComp * 10 +
3242
+ nestedInteractiveComp * 10 +
3243
+ rawDomBypasses * 8 +
3244
+ siblingAtomOverlapsComp * 8 +
3245
+ Math.min(24, duplicateClones * 8) +
3246
+ primitiveSkipsComp * 6 +
3247
+ warnShapesComp * 6 +
3248
+ arbitraryTailwindCountComp * 4 +
3249
+ magicSpacingComp * 4 +
3250
+ hardcodedLiterals * 4 +
3251
+ composabilityCountComp * 6 +
3252
+ callSiteOverrides * 5;
3253
+ const healthScore = Math.max(0, Math.min(100, 100 - penalty));
3254
+ const healthStatus = undefinedTokensComp > 0 || undefinedCssComp > 0 || healthScore < 60
3255
+ ? "critical"
3256
+ : issueCount > 0 || healthScore < 85
3257
+ ? "warn"
3258
+ : "healthy";
3259
+ directNodesById.set(p.entityId, {
3260
+ entityId: p.entityId,
3261
+ label: p.label,
3262
+ filePath: p.filePath,
3263
+ directScore: healthScore,
3264
+ directStatus: healthStatus,
3265
+ directIssueCount: issueCount,
3266
+ });
3267
+ p.health = {
3268
+ score: healthScore,
3269
+ status: healthStatus,
3270
+ issueCount,
3271
+ subtreeScore: healthScore,
3272
+ subtreeStatus: healthStatus,
3273
+ subtreeIssueCount: 0,
3274
+ descendantOffenders: [],
3275
+ tokenAdherence,
3276
+ breakdown: {
3277
+ arbitraryTailwind: arbitraryTailwindCountComp,
3278
+ magicSpacing: magicSpacingComp,
3279
+ primitiveSkips: primitiveSkipsComp,
3280
+ hardcodedLiterals,
3281
+ rawDomBypasses,
3282
+ siblingAtomOverlaps: siblingAtomOverlapsComp,
3283
+ nestedInteractive: nestedInteractiveComp,
3284
+ composabilityIssues: composabilityCountComp,
3285
+ undefinedTokens: undefinedTokensComp,
3286
+ undefinedCssClasses: undefinedCssComp,
3287
+ duplicateClones,
3288
+ callSiteOverrides,
3289
+ },
3290
+ };
3291
+ }
3292
+ const subtreeHealthById = computeSubtreeHealth(directNodesById, rendersChildrenById);
3293
+ for (const p of componentProfiles) {
3294
+ const sub = subtreeHealthById.get(p.entityId);
3295
+ if (!sub)
3296
+ continue;
3297
+ p.health.subtreeScore = sub.subtreeScore;
3298
+ p.health.subtreeStatus = sub.subtreeStatus;
3299
+ p.health.subtreeIssueCount = sub.subtreeIssueCount;
3300
+ p.health.descendantOffenders = sub.descendantOffenders;
3301
+ }
3302
+ // 18c. Similar Component Matches (drives side-by-side comparison & merge recommendations)
3303
+ const twinPairKeys = new Set();
3304
+ for (const tw of alignmentAudit.parallelTwins) {
3305
+ for (let i = 0; i < tw.components.length; i++) {
3306
+ for (let j = i + 1; j < tw.components.length; j++) {
3307
+ const pair = [tw.components[i].entityId, tw.components[j].entityId].sort().join("::");
3308
+ twinPairKeys.add(pair);
3309
+ }
3310
+ }
3311
+ }
3312
+ const clonePairKeys = new Set();
3313
+ const profilesByLabelExact = new Map();
3314
+ for (const p of componentProfiles) {
3315
+ const arr = profilesByLabelExact.get(p.label) ?? [];
3316
+ arr.push(p);
3317
+ profilesByLabelExact.set(p.label, arr);
3318
+ }
3319
+ for (const cg of structuralJsxClones) {
3320
+ const occIds = new Set();
3321
+ for (const occ of cg.occurrences) {
3322
+ for (const p of profilesByLabelExact.get(occ.componentName) ?? []) {
3323
+ if (p.filePath === occ.filePath)
3324
+ occIds.add(p.entityId);
3325
+ }
3326
+ }
3327
+ const arr = [...occIds];
3328
+ for (let i = 0; i < arr.length; i++) {
3329
+ for (let j = i + 1; j < arr.length; j++) {
3330
+ clonePairKeys.add([arr[i], arr[j]].sort().join("::"));
3331
+ }
3332
+ }
3333
+ }
3334
+ const splitCamelWords = (label) => new Set(label
3335
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
3336
+ .split(/[\s_-]+/)
3337
+ .map((w) => w.trim().toLowerCase())
3338
+ .filter((w) => w.length >= 2));
3339
+ const compCompareCandidates = componentProfiles.filter((p) => p.uiKind === "component" && p.atomicTier !== "ROUTE");
3340
+ const featureByEntityId = new Map();
3341
+ for (const p of compCompareCandidates) {
3342
+ const bridged = new Set(p.bridgedTokensConsumed);
3343
+ featureByEntityId.set(p.entityId, {
3344
+ props: new Set(p.propContract.map((pr) => pr.name).filter((n) => !BOILERPLATE_PROP_NAMES.has(n))),
3345
+ domTags: new Set(p.domTags),
3346
+ renderedAndSkel: new Set([
3347
+ ...p.renderedComponents,
3348
+ ...p.jsxSkeletons.map((s) => `skel:${s.skeletonHash}`),
3349
+ ]),
3350
+ styleVocab: new Set([
3351
+ ...p.tokensConsumed.filter((t) => !bridged.has(t)),
3352
+ ...p.cssClassesUsed,
3353
+ ]),
3354
+ nameWords: splitCamelWords(p.label),
3355
+ });
3356
+ }
3357
+ const setIntersection = (a, b) => {
3358
+ const out = [];
3359
+ for (const item of a) {
3360
+ if (b.has(item))
3361
+ out.push(item);
3362
+ }
3363
+ return out;
3364
+ };
3365
+ const pickRecommendedSource = (a, b) => {
3366
+ if (a.usageCount !== b.usageCount) {
3367
+ return a.usageCount < b.usageCount ? a.entityId : b.entityId;
3368
+ }
3369
+ if (a.health.score !== b.health.score) {
3370
+ return a.health.score < b.health.score ? a.entityId : b.entityId;
3371
+ }
3372
+ return a.entityId.localeCompare(b.entityId) > 0 ? a.entityId : b.entityId;
3373
+ };
3374
+ for (let i = 0; i < compCompareCandidates.length; i++) {
3375
+ const a = compCompareCandidates[i];
3376
+ const fa = featureByEntityId.get(a.entityId);
3377
+ const matches = [];
3378
+ for (let j = 0; j < compCompareCandidates.length; j++) {
3379
+ if (i === j)
3380
+ continue;
3381
+ const b = compCompareCandidates[j];
3382
+ const fb = featureByEntityId.get(b.entityId);
3383
+ const dims = [
3384
+ { a: fa.props, b: fb.props, w: 0.22 },
3385
+ { a: fa.domTags, b: fb.domTags, w: 0.16 },
3386
+ { a: fa.renderedAndSkel, b: fb.renderedAndSkel, w: 0.27 },
3387
+ { a: fa.styleVocab, b: fb.styleVocab, w: 0.20 },
3388
+ ];
3389
+ let weightedSum = 0;
3390
+ let activeWeight = 0;
3391
+ for (const dim of dims) {
3392
+ if (dim.a.size === 0 && dim.b.size === 0)
3393
+ continue;
3394
+ activeWeight += dim.w;
3395
+ weightedSum += dim.w * jaccard(dim.a, dim.b);
3396
+ }
3397
+ const nameJaccard = fa.nameWords.size > 0 || fb.nameWords.size > 0
3398
+ ? jaccard(fa.nameWords, fb.nameWords)
3399
+ : 0;
3400
+ const roleDim = nameJaccard * 0.75 + (a.atomicTier === b.atomicTier ? 0.25 : 0);
3401
+ activeWeight += 0.15;
3402
+ weightedSum += 0.15 * roleDim;
3403
+ const sharedProps = setIntersection(fa.props, fb.props);
3404
+ const sharedDom = setIntersection(fa.domTags, fb.domTags);
3405
+ const sharedRendered = setIntersection(new Set(a.renderedComponents), new Set(b.renderedComponents));
3406
+ const sharedSkels = setIntersection(new Set(a.jsxSkeletons.map((s) => s.skeletonHash)), new Set(b.jsxSkeletons.map((s) => s.skeletonHash)));
3407
+ const sharedStyles = setIntersection(fa.styleVocab, fb.styleVocab);
3408
+ const sharedWords = setIntersection(fa.nameWords, fb.nameWords);
3409
+ const pairKey = [a.entityId, b.entityId].sort().join("::");
3410
+ const isTwin = twinPairKeys.has(pairKey);
3411
+ const isClone = clonePairKeys.has(pairKey);
3412
+ const concreteOverlapCount = sharedProps.length +
3413
+ sharedDom.length +
3414
+ sharedRendered.length +
3415
+ sharedSkels.length +
3416
+ sharedStyles.length +
3417
+ sharedWords.length;
3418
+ let similarity = activeWeight > 0 ? Math.round((weightedSum / activeWeight) * 100) : 0;
3419
+ if (isTwin || isClone) {
3420
+ similarity = Math.max(similarity, 65);
3421
+ }
3422
+ if (!isTwin && !isClone && (similarity < 22 || concreteOverlapCount < 2)) {
3423
+ continue;
3424
+ }
3425
+ const sharedSignals = [];
3426
+ if (isTwin)
3427
+ sharedSignals.push("parallel twin");
3428
+ if (isClone)
3429
+ sharedSignals.push("shared JSX skeleton");
3430
+ if (sharedRendered.length > 0) {
3431
+ sharedSignals.push(`renders ${sharedRendered.slice(0, 3).join(", ")}`);
3432
+ }
3433
+ if (sharedProps.length > 0) {
3434
+ sharedSignals.push(`props: ${sharedProps.slice(0, 3).join(", ")}`);
3435
+ }
3436
+ if (sharedDom.length > 0) {
3437
+ sharedSignals.push(`dom: ${sharedDom.slice(0, 3).join(", ")}`);
3438
+ }
3439
+ if (sharedStyles.length > 0) {
3440
+ sharedSignals.push(`style: ${sharedStyles.slice(0, 2).join(", ")}`);
3441
+ }
3442
+ if (sharedWords.length > 0 && sharedSignals.length < 6) {
3443
+ sharedSignals.push(`concept: ${sharedWords.slice(0, 3).join(" ")}`);
3444
+ }
3445
+ const divergentSignals = [];
3446
+ if (a.usageCount !== b.usageCount) {
3447
+ divergentSignals.push(`usage ${a.usageCount} vs ${b.usageCount}`);
3448
+ }
3449
+ if (a.atomicTier !== b.atomicTier) {
3450
+ divergentSignals.push(`tier ${a.atomicTier} vs ${b.atomicTier}`);
3451
+ }
3452
+ const onlyAProps = [...fa.props].filter((pName) => !fb.props.has(pName));
3453
+ const onlyBProps = [...fb.props].filter((pName) => !fa.props.has(pName));
3454
+ if (onlyAProps.length > 0) {
3455
+ divergentSignals.push(`only ${a.label}: ${onlyAProps.slice(0, 2).join(", ")}`);
3456
+ }
3457
+ if (onlyBProps.length > 0) {
3458
+ divergentSignals.push(`only ${b.label}: ${onlyBProps.slice(0, 2).join(", ")}`);
3459
+ }
3460
+ const svDeltas = computeStyleVectorDeltas(a.styleVector, b.styleVector);
3461
+ matches.push({
3462
+ entityId: b.entityId,
3463
+ label: b.label,
3464
+ atomicTier: b.atomicTier,
3465
+ filePath: b.filePath,
3466
+ ...(b.lineNumber !== undefined ? { lineNumber: b.lineNumber } : {}),
3467
+ usageCount: b.usageCount,
3468
+ healthScore: b.health.score,
3469
+ subtreeScore: b.health.subtreeScore,
3470
+ similarity,
3471
+ sharedSignals: sharedSignals.slice(0, 6),
3472
+ divergentSignals: divergentSignals.slice(0, 4),
3473
+ ...(svDeltas.length > 0 ? { styleVectorDeltas: svDeltas } : {}),
3474
+ recommendedMergeSourceId: pickRecommendedSource(a, b),
3475
+ });
3476
+ }
3477
+ matches.sort((x, y) => y.similarity - x.similarity ||
3478
+ y.usageCount - x.usageCount ||
3479
+ x.label.localeCompare(y.label));
3480
+ a.similarComponents = matches.slice(0, 6);
3481
+ }
3482
+ // 18d. Rich `tokenRegistry` (Colors, Typography, Spacing, Radii, Shadows & Usage Graph)
3483
+ const regRootMap = new Map();
3484
+ const regDarkMap = new Map();
3485
+ const regLightMap = new Map();
3486
+ const regBridgeMap = new Map();
3487
+ const declsByNameAll = new Map();
3488
+ const globalDeclLocToVar = new Map();
3489
+ for (const decl of allTokenDecls) {
3490
+ if (decl.selector === "js-variable" && decl.scope === "scoped")
3491
+ continue;
3492
+ const list = declsByNameAll.get(decl.name) ?? [];
3493
+ list.push(decl);
3494
+ declsByNameAll.set(decl.name, list);
3495
+ if (decl.scope === "global") {
3496
+ if (decl.themeContext === "root")
3497
+ regRootMap.set(decl.name, decl);
3498
+ else if (decl.themeContext === "dark")
3499
+ regDarkMap.set(decl.name, decl);
3500
+ else if (decl.themeContext === "light")
3501
+ regLightMap.set(decl.name, decl);
3502
+ else if (decl.themeContext === "theme-bridge")
3503
+ regBridgeMap.set(decl.name, decl);
3504
+ if (decl.referencedVars.length > 0) {
3505
+ const locKey = `${decl.filePath}:${decl.lineNumber}`;
3506
+ const set = globalDeclLocToVar.get(locKey) ?? new Set();
3507
+ for (const r of decl.referencedVars)
3508
+ set.add(r);
3509
+ globalDeclLocToVar.set(locKey, set);
3510
+ }
3511
+ }
3512
+ }
3513
+ const canvasProbeTokens = [config.contrast.canvasToken, ...CANVAS_TOKEN_PROBES].filter((t) => Boolean(t));
3514
+ const resolveRegCanvas = (themeMap) => {
3515
+ for (const t of canvasProbeTokens) {
3516
+ const res = resolveThemeTokenColor(t, themeMap, regRootMap, regBridgeMap);
3517
+ if (res.ok && res.color.a >= 0.999)
3518
+ return res.color;
3519
+ }
3520
+ return null;
3521
+ };
3522
+ const rootCanvasColor = resolveRegCanvas(regRootMap);
3523
+ const darkCanvasColor = resolveRegCanvas(regDarkMap) ?? rootCanvasColor;
3524
+ const lightCanvasColor = resolveRegCanvas(regLightMap) ?? rootCanvasColor;
3525
+ const parseResolvedColorForRegistry = (resolved) => parseColorWithAlphaSyntax(resolved);
3526
+ const parseCssPx = (resolved) => {
3527
+ if (!resolved)
3528
+ return undefined;
3529
+ const trimmed = resolved.trim();
3530
+ const pxMatch = trimmed.match(/^(-?\d*\.?\d+)px$/i);
3531
+ if (pxMatch)
3532
+ return Math.round(Number(pxMatch[1]) * 100) / 100;
3533
+ const remMatch = trimmed.match(/^(-?\d*\.?\d+)r?em$/i);
3534
+ if (remMatch)
3535
+ return Math.round(Number(remMatch[1]) * 16 * 100) / 100;
3536
+ return undefined;
3537
+ };
3538
+ const resolveThemeSlot = (decl, themeMap, canvasColor) => {
3539
+ if (!decl)
3540
+ return undefined;
3541
+ const resolved = substituteVars(decl.value, themeMap, regRootMap, regBridgeMap);
3542
+ const parsedColor = parseResolvedColorForRegistry(resolved);
3543
+ let hex;
3544
+ let alpha;
3545
+ if (parsedColor) {
3546
+ alpha = Math.round(parsedColor.a * 1000) / 1000;
3547
+ const displayColor = parsedColor.a < 0.999 && canvasColor
3548
+ ? compositeOver(parsedColor, canvasColor)
3549
+ : parsedColor;
3550
+ hex = rgbaToHex(displayColor);
3551
+ }
3552
+ const px = parseCssPx(resolved);
3553
+ return {
3554
+ raw: decl.value,
3555
+ resolved,
3556
+ ...(hex !== undefined ? { hex } : {}),
3557
+ ...(alpha !== undefined ? { alpha } : {}),
3558
+ ...(px !== undefined ? { px } : {}),
3559
+ };
3560
+ };
3561
+ const unusedTokenNameSet = new Set(unusedTokens.map((u) => u.name));
3562
+ const duplicateByTokenName = new Map(duplicateTokens.map((d) => [d.name, d]));
3563
+ const derivedByTokenName = new Map();
3564
+ for (const dt of derivedTokens) {
3565
+ const matchName = dt.existingTokenMatch?.name;
3566
+ if (!matchName)
3567
+ continue;
3568
+ const prev = derivedByTokenName.get(matchName);
3569
+ if (!prev || dt.occurrenceCount > prev.occurrenceCount) {
3570
+ derivedByTokenName.set(matchName, dt);
3571
+ }
3572
+ }
3573
+ const contrastByTokenName = new Map();
3574
+ for (const ca of contrastAudits) {
3575
+ const baseEntry = {
3576
+ pairId: ca.pairId,
3577
+ contextLabel: ca.contextLabel,
3578
+ ...(ca.dark ? { darkRatio: ca.dark.ratio } : {}),
3579
+ ...(ca.light ? { lightRatio: ca.light.ratio } : {}),
3580
+ ...(ca.root ? { rootRatio: ca.root.ratio } : {}),
3581
+ passesAll: ca.passesAll,
3582
+ };
3583
+ const fgArr = contrastByTokenName.get(ca.foregroundToken) ?? [];
3584
+ fgArr.push({ ...baseEntry, role: "fg", peerToken: ca.backgroundToken });
3585
+ contrastByTokenName.set(ca.foregroundToken, fgArr);
3586
+ const bgArr = contrastByTokenName.get(ca.backgroundToken) ?? [];
3587
+ bgArr.push({ ...baseEntry, role: "bg", peerToken: ca.foregroundToken });
3588
+ contrastByTokenName.set(ca.backgroundToken, bgArr);
3589
+ }
3590
+ // Build reverse alias edges: targetVar -> Set<declaringVar>
3591
+ const aliasedByMap = new Map();
3592
+ const aliasUsagesByTarget = new Map();
3593
+ for (const [declName, decls] of declsByNameAll.entries()) {
3594
+ for (const d of decls) {
3595
+ if (d.scope !== "global")
3596
+ continue;
3597
+ for (const refVar of d.referencedVars) {
3598
+ if (refVar === declName)
3599
+ continue;
3600
+ const set = aliasedByMap.get(refVar) ?? new Set();
3601
+ set.add(declName);
3602
+ aliasedByMap.set(refVar, set);
3603
+ const arr = aliasUsagesByTarget.get(refVar) ?? [];
3604
+ if (!arr.some((u) => u.filePath === d.filePath && u.lineNumber === d.lineNumber)) {
3605
+ arr.push({
3606
+ filePath: d.filePath,
3607
+ lineNumber: d.lineNumber,
3608
+ kind: "css-alias",
3609
+ consumerLabel: declName,
3610
+ snippet: `${declName}: ${d.value}`,
3611
+ });
3612
+ aliasUsagesByTarget.set(refVar, arr);
3613
+ }
3614
+ }
3615
+ }
3616
+ }
3617
+ // Direct consumer usages per token (excluding token declaration alias lines)
3618
+ const directUsagesByToken = new Map();
3619
+ const directKeysByToken = new Map();
3620
+ for (const ref of allTokenRefs) {
3621
+ const locKey = `${ref.filePath}:${ref.lineNumber}`;
3622
+ if (ref.kind === "css-var" && globalDeclLocToVar.get(locKey)?.has(ref.name)) {
3623
+ continue;
3624
+ }
3625
+ const keys = directKeysByToken.get(ref.name) ?? new Set();
3626
+ const usageKey = `${locKey}:${ref.kind}:${ref.consumerLabel ?? ""}`;
3627
+ if (keys.has(`${locKey}`)) {
3628
+ // Allow adding usage sample if kind differs while deduplicating location key count
3629
+ const arr = directUsagesByToken.get(ref.name) ?? [];
3630
+ if (!arr.some((u) => u.filePath === ref.filePath &&
3631
+ u.lineNumber === ref.lineNumber &&
3632
+ u.kind === ref.kind)) {
3633
+ arr.push({
3634
+ filePath: ref.filePath,
3635
+ lineNumber: ref.lineNumber,
3636
+ kind: ref.kind,
3637
+ ...(ref.consumerLabel ? { consumerLabel: ref.consumerLabel } : {}),
3638
+ snippet: ref.snippet,
3639
+ });
3640
+ directUsagesByToken.set(ref.name, arr);
3641
+ }
3642
+ continue;
3643
+ }
3644
+ keys.add(locKey);
3645
+ directKeysByToken.set(ref.name, keys);
3646
+ const arr = directUsagesByToken.get(ref.name) ?? [];
3647
+ if (!arr.some((u) => `${u.filePath}:${u.lineNumber}:${u.kind}:${u.consumerLabel ?? ""}` === usageKey)) {
3648
+ arr.push({
3649
+ filePath: ref.filePath,
3650
+ lineNumber: ref.lineNumber,
3651
+ kind: ref.kind,
3652
+ ...(ref.consumerLabel ? { consumerLabel: ref.consumerLabel } : {}),
3653
+ snippet: ref.snippet,
3654
+ });
3655
+ directUsagesByToken.set(ref.name, arr);
3656
+ }
3657
+ }
3658
+ const classifyRegistryCategory = (name, valuesByTheme) => {
3659
+ const hasColor = Boolean(valuesByTheme.root?.hex ||
3660
+ valuesByTheme.dark?.hex ||
3661
+ valuesByTheme.light?.hex ||
3662
+ valuesByTheme.themeBridge?.hex);
3663
+ const hasPx = Boolean(valuesByTheme.root?.px !== undefined ||
3664
+ valuesByTheme.dark?.px !== undefined ||
3665
+ valuesByTheme.light?.px !== undefined ||
3666
+ valuesByTheme.themeBridge?.px !== undefined);
3667
+ if (/font-size|text-size/i.test(name)) {
3668
+ return { category: "typography", subCategory: "font-size" };
3669
+ }
3670
+ if (/line-height|leading/i.test(name)) {
3671
+ return { category: "typography", subCategory: "line-height" };
3672
+ }
3673
+ if (/letter-spacing|tracking/i.test(name)) {
3674
+ return { category: "typography", subCategory: "letter-spacing" };
3675
+ }
3676
+ if (/^--font-/i.test(name) && !hasColor) {
3677
+ return /weight/i.test(name)
3678
+ ? { category: "typography" }
3679
+ : { category: "typography", subCategory: "font-family" };
3680
+ }
3681
+ if (hasColor) {
3682
+ return { category: "color" };
3683
+ }
3684
+ if (/^--text-(?:2xs|xs|sm|base|md|lg|xl|\d+xl)$/i.test(name) || (/^--text-/i.test(name) && hasPx)) {
3685
+ return { category: "typography", subCategory: "font-size" };
3686
+ }
3687
+ if (/shadow|elevation|glow/i.test(name))
3688
+ return { category: "shadow" };
3689
+ if (/radius|rounded/i.test(name))
3690
+ return { category: "radius" };
3691
+ if (/space|gap|pad|margin/i.test(name))
3692
+ return { category: "spacing" };
3693
+ if (/^--z-|z-index|width|height|size|stroke-width|border-width/i.test(name)) {
3694
+ return { category: "geometry" };
3695
+ }
3696
+ return { category: "other" };
3697
+ };
3698
+ const tokenRegistry = [];
3699
+ const tokenColorLabByName = new Map();
3700
+ for (const [name, decls] of [...declsByNameAll.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
3701
+ const firstDecl = decls[0];
3702
+ const allDeclsBridge = decls.every((d) => d.themeContext === "theme-bridge");
3703
+ const allDeclsScoped = decls.every((d) => d.scope === "scoped");
3704
+ const rootDecl = regRootMap.get(name) ?? decls.find((d) => d.themeContext === "root");
3705
+ const darkDecl = regDarkMap.get(name) ?? decls.find((d) => d.themeContext === "dark");
3706
+ const lightDecl = regLightMap.get(name) ?? decls.find((d) => d.themeContext === "light");
3707
+ const bridgeDecl = regBridgeMap.get(name) ?? decls.find((d) => d.themeContext === "theme-bridge");
3708
+ const valuesByTheme = {};
3709
+ const vRoot = resolveThemeSlot(rootDecl, regRootMap, rootCanvasColor);
3710
+ const vDark = resolveThemeSlot(darkDecl, regDarkMap, darkCanvasColor);
3711
+ const vLight = resolveThemeSlot(lightDecl, regLightMap, lightCanvasColor);
3712
+ const vBridge = resolveThemeSlot(bridgeDecl, regBridgeMap, darkCanvasColor ?? rootCanvasColor);
3713
+ if (vRoot)
3714
+ valuesByTheme.root = vRoot;
3715
+ if (vDark)
3716
+ valuesByTheme.dark = vDark;
3717
+ if (vLight)
3718
+ valuesByTheme.light = vLight;
3719
+ if (vBridge)
3720
+ valuesByTheme.themeBridge = vBridge;
3721
+ const { category, subCategory } = classifyRegistryCategory(name, valuesByTheme);
3722
+ const referencedVars = [
3723
+ ...new Set(decls.flatMap((d) => d.referencedVars)),
3724
+ ].sort();
3725
+ const aliasedBy = [...(aliasedByMap.get(name) ?? [])].sort();
3726
+ const directUsages = directUsagesByToken.get(name) ?? [];
3727
+ const directKeys = directKeysByToken.get(name) ?? new Set();
3728
+ const transitiveKeys = new Set();
3729
+ const bfsQueue = [...aliasedBy];
3730
+ const visitedAliases = new Set([name]);
3731
+ while (bfsQueue.length > 0) {
3732
+ const aliasName = bfsQueue.shift();
3733
+ if (visitedAliases.has(aliasName))
3734
+ continue;
3735
+ visitedAliases.add(aliasName);
3736
+ for (const dk of directKeysByToken.get(aliasName) ?? []) {
3737
+ if (!directKeys.has(dk))
3738
+ transitiveKeys.add(dk);
3739
+ }
3740
+ for (const nextAlias of aliasedByMap.get(aliasName) ?? []) {
3741
+ if (!visitedAliases.has(nextAlias))
3742
+ bfsQueue.push(nextAlias);
3743
+ }
3744
+ }
3745
+ const directUsageCount = directKeys.size;
3746
+ const transitiveUsageCount = transitiveKeys.size;
3747
+ const usageCount = directUsageCount + transitiveUsageCount;
3748
+ const usagesCombined = [
3749
+ ...directUsages,
3750
+ ...(aliasUsagesByTarget.get(name) ?? []),
3751
+ ].slice(0, 25);
3752
+ const contrastPairs = contrastByTokenName.get(name) ?? [];
3753
+ const contrastFailCount = contrastPairs.filter((cp) => !cp.passesAll).length;
3754
+ const dupDiag = duplicateByTokenName.get(name);
3755
+ const isDuplicate = Boolean(dupDiag);
3756
+ const isForked = Boolean(dupDiag?.isForkedValue);
3757
+ const unused = !allDeclsBridge
3758
+ ? unusedTokenNameSet.has(name) || usageCount === 0
3759
+ : usageCount === 0;
3760
+ const matchingDerived = derivedByTokenName.get(name);
3761
+ const matchingHardcodedCount = matchingDerived?.occurrenceCount ?? 0;
3762
+ const tokPenalty = (isForked ? 30 : isDuplicate ? 10 : 0) +
3763
+ contrastFailCount * 25 +
3764
+ (!allDeclsBridge && unused ? 20 : 0) +
3765
+ (matchingHardcodedCount > 0 ? Math.min(20, matchingHardcodedCount * 2) : 0);
3766
+ const tokScore = Math.max(0, Math.min(100, 100 - tokPenalty));
3767
+ const tokIssueCount = (isForked || isDuplicate ? 1 : 0) +
3768
+ contrastFailCount +
3769
+ (!allDeclsBridge && unused ? 1 : 0) +
3770
+ (matchingHardcodedCount > 0 ? 1 : 0);
3771
+ const tokStatus = isForked || contrastFailCount > 0 || tokScore < 60
3772
+ ? "critical"
3773
+ : tokIssueCount > 0 || tokScore < 85
3774
+ ? "warn"
3775
+ : "healthy";
3776
+ const uniqueDecls = [];
3777
+ const seenDeclKeyReg = new Set();
3778
+ for (const d of decls) {
3779
+ const k = `${d.filePath}:${d.lineNumber}:${d.themeContext}`;
3780
+ if (seenDeclKeyReg.has(k))
3781
+ continue;
3782
+ seenDeclKeyReg.add(k);
3783
+ uniqueDecls.push({
3784
+ filePath: d.filePath,
3785
+ lineNumber: d.lineNumber,
3786
+ selector: d.selector,
3787
+ themeContext: d.themeContext,
3788
+ value: d.value,
3789
+ });
3790
+ }
3791
+ const lineageRole = tokenLineage.lineageRoleByName.get(name);
3792
+ const backing = tokenLineage.backingByName.get(name);
3793
+ const isUnbackedLiteral = backing === "unbacked-literal";
3794
+ const entry = {
3795
+ name,
3796
+ tier: firstDecl.tier,
3797
+ ...(lineageRole ? { lineageRole } : {}),
3798
+ ...(backing ? { backing } : {}),
3799
+ category,
3800
+ ...(subCategory ? { subCategory } : {}),
3801
+ themeBridge: allDeclsBridge,
3802
+ scope: allDeclsScoped ? "scoped" : "global",
3803
+ filePath: firstDecl.filePath,
3804
+ lineNumber: firstDecl.lineNumber,
3805
+ declarations: uniqueDecls,
3806
+ valuesByTheme,
3807
+ referencedVars,
3808
+ aliasedBy,
3809
+ directUsageCount,
3810
+ transitiveUsageCount,
3811
+ usageCount,
3812
+ usages: usagesCombined,
3813
+ contrastPairs,
3814
+ ...(matchingDerived
3815
+ ? {
3816
+ matchingDerivedCluster: {
3817
+ representative: matchingDerived.representative,
3818
+ occurrenceCount: matchingDerived.occurrenceCount,
3819
+ distinctFileCount: matchingDerived.distinctFileCount,
3820
+ members: matchingDerived.members,
3821
+ },
3822
+ }
3823
+ : {}),
3824
+ health: {
3825
+ status: tokStatus,
3826
+ score: tokScore,
3827
+ issueCount: tokIssueCount,
3828
+ unused,
3829
+ isDuplicate,
3830
+ isForked,
3831
+ ...(isUnbackedLiteral ? { isUnbackedLiteral } : {}),
3832
+ contrastFailures: contrastFailCount,
3833
+ matchingHardcodedCount,
3834
+ },
3835
+ similarTokens: [],
3836
+ };
3837
+ tokenRegistry.push(entry);
3838
+ if (category === "color") {
3839
+ const primaryColorStr = valuesByTheme.dark?.resolved ??
3840
+ valuesByTheme.root?.resolved ??
3841
+ valuesByTheme.light?.resolved ??
3842
+ valuesByTheme.themeBridge?.resolved ??
3843
+ null;
3844
+ const rgba = parseResolvedColorForRegistry(primaryColorStr);
3845
+ if (rgba) {
3846
+ tokenColorLabByName.set(name, {
3847
+ lab: toOklab(rgba),
3848
+ hexDark: valuesByTheme.dark?.hex ?? valuesByTheme.root?.hex,
3849
+ hexLight: valuesByTheme.light?.hex,
3850
+ });
3851
+ }
3852
+ }
3853
+ }
3854
+ // Compute `similarTokens` for color (OKLab) and typography (px / font stack) entries
3855
+ const colorEntries = tokenRegistry.filter((t) => t.category === "color");
3856
+ for (const a of colorEntries) {
3857
+ const aLab = tokenColorLabByName.get(a.name);
3858
+ if (!aLab)
3859
+ continue;
3860
+ const sims = [];
3861
+ for (const b of colorEntries) {
3862
+ if (a.name === b.name)
3863
+ continue;
3864
+ if (!a.themeBridge && b.themeBridge)
3865
+ continue;
3866
+ if (a.referencedVars.includes(b.name) || b.referencedVars.includes(a.name))
3867
+ continue;
3868
+ const bLab = tokenColorLabByName.get(b.name);
3869
+ if (!bLab)
3870
+ continue;
3871
+ const dist = oklabDistance(aLab.lab, bLab.lab);
3872
+ if (dist > 0.045)
3873
+ continue;
3874
+ const distRounded = Math.round(dist * 1000) / 1000;
3875
+ sims.push({
3876
+ name: b.name,
3877
+ tier: b.tier,
3878
+ themeContext: b.declarations[0]?.themeContext,
3879
+ distance: distRounded,
3880
+ reason: distRounded === 0
3881
+ ? "Identical resolved color value"
3882
+ : `Near-identical OKLab color (ΔE ${distRounded})`,
3883
+ usageCount: b.usageCount,
3884
+ ...(bLab.hexDark ? { hexDark: bLab.hexDark } : {}),
3885
+ ...(bLab.hexLight ? { hexLight: bLab.hexLight } : {}),
3886
+ });
3887
+ }
3888
+ sims.sort((x, y) => (x.distance ?? 1) - (y.distance ?? 1) ||
3889
+ y.usageCount - x.usageCount ||
3890
+ x.name.localeCompare(y.name));
3891
+ a.similarTokens = sims.slice(0, 5);
3892
+ }
3893
+ const typographyEntries = tokenRegistry.filter((t) => t.category === "typography");
3894
+ const primaryValueOf = (t) => t.valuesByTheme.root ??
3895
+ t.valuesByTheme.dark ??
3896
+ t.valuesByTheme.light ??
3897
+ t.valuesByTheme.themeBridge;
3898
+ for (const a of typographyEntries) {
3899
+ const aVal = primaryValueOf(a);
3900
+ if (!aVal)
3901
+ continue;
3902
+ const sims = [];
3903
+ for (const b of typographyEntries) {
3904
+ if (a.name === b.name)
3905
+ continue;
3906
+ if (!a.themeBridge && b.themeBridge)
3907
+ continue;
3908
+ if (a.referencedVars.includes(b.name) || b.referencedVars.includes(a.name))
3909
+ continue;
3910
+ if (a.subCategory !== b.subCategory)
3911
+ continue;
3912
+ const bVal = primaryValueOf(b);
3913
+ if (!bVal)
3914
+ continue;
3915
+ if (a.subCategory === "font-size" && aVal.px !== undefined && bVal.px !== undefined) {
3916
+ const pxDiff = Math.round(Math.abs(aVal.px - bVal.px) * 100) / 100;
3917
+ if (pxDiff > 2)
3918
+ continue;
3919
+ sims.push({
3920
+ name: b.name,
3921
+ tier: b.tier,
3922
+ themeContext: b.declarations[0]?.themeContext,
3923
+ pxDiff,
3924
+ reason: pxDiff === 0
3925
+ ? `Identical size (${bVal.px}px)`
3926
+ : `Within ${pxDiff}px (${bVal.px}px vs ${aVal.px}px)`,
3927
+ usageCount: b.usageCount,
3928
+ });
3929
+ }
3930
+ else {
3931
+ const aNorm = (aVal.resolved ?? aVal.raw).replace(/\s+/g, " ").trim().toLowerCase();
3932
+ const bNorm = (bVal.resolved ?? bVal.raw).replace(/\s+/g, " ").trim().toLowerCase();
3933
+ const aNum = Number.parseFloat(aNorm);
3934
+ const bNum = Number.parseFloat(bNorm);
3935
+ const sameNumeric = Number.isFinite(aNum) &&
3936
+ Number.isFinite(bNum) &&
3937
+ Math.abs(aNum - bNum) <= 0.12 &&
3938
+ !/family/i.test(a.subCategory ?? "");
3939
+ const aHead = aNorm.split(",")[0]?.trim() ?? "";
3940
+ const bHead = bNorm.split(",")[0]?.trim() ?? "";
3941
+ if (aNorm === bNorm || (aHead && aHead === bHead) || sameNumeric) {
3942
+ sims.push({
3943
+ name: b.name,
3944
+ tier: b.tier,
3945
+ themeContext: b.declarations[0]?.themeContext,
3946
+ reason: aNorm === bNorm
3947
+ ? "Identical resolved typography value"
3948
+ : `Shared ${a.subCategory ?? "typography"} base (${bNorm})`,
3949
+ usageCount: b.usageCount,
3950
+ });
3951
+ }
3952
+ }
3953
+ }
3954
+ sims.sort((x, y) => (x.pxDiff ?? 0) - (y.pxDiff ?? 0) ||
3955
+ y.usageCount - x.usageCount ||
3956
+ x.name.localeCompare(y.name));
3957
+ a.similarTokens = sims.slice(0, 5);
3958
+ }
3959
+ const mergeDecisions = readMergeDecisions(ctx.repoPath);
3960
+ const report = {
3961
+ repoId: ctx.repoId,
3962
+ repoName: ctx.repoName,
3963
+ system: systemInfo,
3964
+ coverage: {
3965
+ unsupportedFiles,
3966
+ contrastUnresolved,
3967
+ tokensOutsideSystem,
3968
+ notes: coverageNotes,
3969
+ },
3970
+ derivedTokens,
3971
+ summary: {
3972
+ cssFilesScanned: parsedCssList.length,
3973
+ componentFilesScanned: scannedFiles.size,
3974
+ componentsProfiled: componentProfiles.length,
3975
+ routeCount: tierCounts.ROUTE,
3976
+ templateCount: tierCounts.TEMPLATE,
3977
+ organismCount: tierCounts.ORGANISM,
3978
+ moleculeCount: tierCounts.MOLECULE,
3979
+ atomCount: tierCounts.ATOM,
3980
+ utilityCount: tierCounts.UTILITY,
3981
+ structuralJsxCloneCount: structuralJsxClones.length,
3982
+ bypassedAtomCount: bypassedAtoms.length,
3983
+ siblingAtomOverlapCount: siblingAtomOverlaps.length,
3984
+ nestedInteractiveCount: nestedInteractive.length,
3985
+ unextractedShapeCount: unextractedShapes.length,
3986
+ parallelTwinGroupCount: parallelTwins.length,
3987
+ callSiteOverrideCount: callSiteOverrides.length,
3988
+ propApiDriftGroupCount: propApiDrift.length,
3989
+ agentExtendabilityScore: overallExtendabilityScore,
3990
+ agentExtendabilityGrade: extendabilityGrade,
3991
+ totalDefinedTokens: definedTokenNames.size,
3992
+ primitiveTokenCount: primitiveTokens.size,
3993
+ semanticTokenCount: semanticTokens.size,
3994
+ componentTokenCount: componentTokens.size,
3995
+ themeBridgeTokenCount: themeBridgeTokens.size,
3996
+ unbackedSemanticTokenCount: tokenLineage.unbackedSemanticTokens.length,
3997
+ themeSymmetryIssueCount: tokenLineage.themeSymmetryIssues.length,
3998
+ undefinedTokenCount: undefinedTokens.length,
3999
+ undefinedCssClassCount: undefinedCssClasses.length,
4000
+ duplicateTokenCount: duplicateTokens.length,
4001
+ forkedTokenCount: duplicateTokens.filter((d) => d.isForkedValue).length,
4002
+ unusedTokenCount: unusedTokens.length,
4003
+ contrastPairsAudited: contrastAudits.length,
4004
+ contrastCandidateCount,
4005
+ contrastFailureCount: contrastFailures.length,
4006
+ contrastPairsUnresolved: contrastUnresolved.length,
4007
+ hardcodedLiteralCount: literalPool.length,
4008
+ derivedTokenProposalCount: derivedTokens.length,
4009
+ invariantViolationCount: invariantViolations.length,
4010
+ composabilityIssueCount: composabilityIssues.length,
4011
+ frontendPackageCount: scope.includedDirs.length,
4012
+ unsupportedFileCount,
4013
+ arbitraryTailwindCount,
4014
+ magicSpacingCount,
4015
+ primitiveScaleSkipCount,
4016
+ inlineStyleLiteralCount,
4017
+ canvasCssSlotCount,
4018
+ canvasTsConstSlotCount,
4019
+ canvasLiteralSlotCount,
4020
+ rawDomPrimitiveCount,
4021
+ atomicConsolidationGroupCount: atomicConsolidation.length,
4022
+ dynamicClassPrefixCount: allDynamicClassPrefixes.size,
4023
+ unusedCssSelectorCount: unusedCssSelectors.length,
4024
+ typographyTupleCount: typographyAudit.typographyTuples.length,
4025
+ typographyDriftRoleCount: typographyAudit.typographyRoleClusters.length,
4026
+ contextualOverrideCount: typographyAudit.contextualStyleOverrides.length,
4027
+ conventionBreakdown,
4028
+ },
4029
+ routeComposition,
4030
+ atomicHierarchy,
4031
+ alignmentAudit,
4032
+ dryAudit,
4033
+ agentExtendability,
4034
+ tokenCatalog: {
4035
+ primitive: [...primitiveTokens].sort(),
4036
+ semantic: [...semanticTokens].sort(),
4037
+ component: [...componentTokens].sort(),
4038
+ themeBridge: [...themeBridgeTokens].sort(),
4039
+ },
4040
+ tokenRegistry,
4041
+ mergeDecisions,
4042
+ diagnostics: {
4043
+ undefinedTokens,
4044
+ undefinedCssClasses,
4045
+ duplicateTokens,
4046
+ unusedTokens,
4047
+ unbackedSemanticTokens: tokenLineage.unbackedSemanticTokens,
4048
+ themeSymmetryIssues: tokenLineage.themeSymmetryIssues,
4049
+ typographyTuples: typographyAudit.typographyTuples,
4050
+ typographyRoleClusters: typographyAudit.typographyRoleClusters,
4051
+ contextualStyleOverrides: typographyAudit.contextualStyleOverrides,
4052
+ contrastFailures,
4053
+ contrastAudits,
4054
+ unusedCssSelectors,
4055
+ dynamicClassPrefixes: [...allDynamicClassPrefixes].sort(),
4056
+ hardcodedCssLiterals: parsedCssList.flatMap((sheet) => sheet.literals),
4057
+ },
4058
+ atomicConsolidation,
4059
+ components: componentProfiles,
4060
+ };
4061
+ // Plugin Presentation Contract: what the HUD / inspector show, built from the finished report
4062
+ const { records: findingRecords } = collectDesignSystemFindings(report);
4063
+ attachDesignSystemPresentations(report, componentOverlays, { path: resolveBaselinePath(ctx.repoPath, config.baseline.path) }, findingRecords, (shortKey) => {
4064
+ const m = computeMeasures(componentProfiles.filter((p) => p.packageName === shortKey), false);
4065
+ const sum = summarizeMeasures(m);
4066
+ return { score: sum.score, grade: sum.grade, notes: sum.notes, pillars: m };
4067
+ });
4068
+ return {
4069
+ report,
4070
+ overlays: componentOverlays,
4071
+ };
4072
+ }
4073
+ // ---------------------------------------------------------------------------
4074
+ // 6. Registered `ChompPlugin` Definition (`design-system`)
4075
+ // ---------------------------------------------------------------------------
4076
+ /**
4077
+ * Builds the `design-system` plugin. `configOverrides` is merged over `chomp.config.json` → `designSystem`
4078
+ * and the built-in defaults (used by tests and programmatic callers; the registered plugin uses none).
4079
+ */
4080
+ export function createDesignSystemPlugin(configOverrides) {
4081
+ return {
4082
+ name: "design-system",
4083
+ version: "2.1.0",
4084
+ displayName: "Design system",
4085
+ order: 30,
4086
+ layer: "L1_DESIGN_SYSTEM",
4087
+ legacySources: ["design-audit"],
4088
+ description: "Audits design tokens, color contrast, styling conventions, and shared components.",
4089
+ accepts: (filePath) => isSupportedStylesheetFile(filePath) ||
4090
+ isPreprocessedUiComponentFile(filePath) ||
4091
+ UNSUPPORTED_UI_EXTENSIONS.some((e) => filePath.endsWith(e)) ||
4092
+ ((filePath.endsWith(".tsx") ||
4093
+ filePath.endsWith(".ts") ||
4094
+ filePath.endsWith(".jsx") ||
4095
+ filePath.endsWith(".js")) &&
4096
+ !filePath.endsWith(".d.ts")),
4097
+ extract: (ctx) => {
4098
+ const { report, overlays } = analyzeRepositoryDesignSystem(ctx, { configOverrides });
4099
+ return {
4100
+ overlays,
4101
+ summary: {
4102
+ ...report.summary,
4103
+ report,
4104
+ },
4105
+ };
4106
+ },
4107
+ };
4108
+ }
4109
+ export const designSystemPlugin = createDesignSystemPlugin();
4110
+ // ---------------------------------------------------------------------------
4111
+ // 7. Closed-Loop Frontend Agent Gate ("Query Before Write, Diff After Write")
4112
+ // ---------------------------------------------------------------------------
4113
+ /**
4114
+ * Flattens a report into identity-keyed findings (no line numbers) plus the set of failing
4115
+ * contrast `pairId::theme` identities. This is the unit the pinned baseline snapshot stores.
4116
+ */
4117
+ export function collectDesignSystemFindings(report) {
4118
+ const records = [];
4119
+ for (const u of report.diagnostics.undefinedTokens) {
4120
+ for (const occ of u.occurrences) {
4121
+ records.push({
4122
+ category: "undefinedToken",
4123
+ key: findingKey("undefinedToken", occ.filePath, "", u.name),
4124
+ filePath: occ.filePath,
4125
+ lineNumber: occ.lineNumber,
4126
+ label: u.name,
4127
+ snippet: occ.snippet,
4128
+ });
4129
+ }
4130
+ }
4131
+ for (const uc of report.diagnostics.undefinedCssClasses ?? []) {
4132
+ for (const occ of uc.occurrences) {
4133
+ records.push({
4134
+ category: "undefinedToken",
4135
+ key: findingKey("undefinedToken", occ.filePath, occ.componentName ?? "", `class:${uc.className}`),
4136
+ filePath: occ.filePath,
4137
+ lineNumber: occ.lineNumber,
4138
+ label: `.${uc.className}`,
4139
+ snippet: occ.snippet,
4140
+ });
4141
+ }
4142
+ }
4143
+ for (const comp of report.components) {
4144
+ for (const ms of comp.magicSpacingUtilities ?? []) {
4145
+ records.push({
4146
+ category: "arbitraryTailwind",
4147
+ key: findingKey("arbitraryTailwind", ms.filePath, comp.label, ms.className),
4148
+ filePath: ms.filePath,
4149
+ lineNumber: ms.lineNumber,
4150
+ label: ms.className,
4151
+ snippet: ms.snippet,
4152
+ });
4153
+ }
4154
+ for (const ni of comp.nestedInteractive ?? []) {
4155
+ records.push({
4156
+ category: "composability",
4157
+ key: findingKey("composability", ni.filePath, comp.label, `nested:${ni.outerTag}>${ni.innerTag}`),
4158
+ filePath: ni.filePath,
4159
+ lineNumber: ni.lineNumber,
4160
+ label: `nested ${ni.innerTag} inside ${ni.outerTag}`,
4161
+ snippet: ni.snippet,
4162
+ });
4163
+ }
4164
+ for (const ov of comp.siblingAtomOverlaps ?? []) {
4165
+ records.push({
4166
+ category: "rawPrimitive",
4167
+ key: findingKey("rawPrimitive", ov.filePath, comp.label, `overlap:${ov.atomTarget}`),
4168
+ filePath: ov.filePath,
4169
+ lineNumber: ov.lineNumber,
4170
+ label: `overlapping ${ov.atomTarget} atom in ${comp.label}`,
4171
+ snippet: ov.snippet,
4172
+ });
4173
+ }
4174
+ for (const tw of comp.arbitraryTailwind) {
4175
+ records.push({
4176
+ category: "arbitraryTailwind",
4177
+ key: findingKey("arbitraryTailwind", tw.filePath, comp.label, tw.className),
4178
+ filePath: tw.filePath,
4179
+ lineNumber: tw.lineNumber,
4180
+ label: tw.className,
4181
+ snippet: tw.snippet,
4182
+ });
4183
+ }
4184
+ for (const skip of comp.primitiveScaleSkips) {
4185
+ records.push({
4186
+ category: "primitiveSkip",
4187
+ key: findingKey("primitiveSkip", skip.filePath, comp.label, skip.tokenOrClass),
4188
+ filePath: skip.filePath,
4189
+ lineNumber: skip.lineNumber,
4190
+ label: skip.tokenOrClass,
4191
+ snippet: skip.snippet,
4192
+ });
4193
+ }
4194
+ for (const lit of comp.inlineStyleLiterals) {
4195
+ const label = `${lit.property}: ${lit.value}`;
4196
+ records.push({
4197
+ category: "hardcodedLiteral",
4198
+ key: findingKey("hardcodedLiteral", lit.filePath, comp.label, `inline:${label}`),
4199
+ filePath: lit.filePath,
4200
+ lineNumber: lit.lineNumber,
4201
+ label,
4202
+ snippet: lit.snippet,
4203
+ });
4204
+ }
4205
+ for (const lit of comp.canvasProvenance.literals) {
4206
+ const label = `${lit.slot}.${lit.prop}=${lit.value}`;
4207
+ records.push({
4208
+ category: "hardcodedLiteral",
4209
+ key: findingKey("hardcodedLiteral", lit.filePath, comp.label, `canvas:${label}`),
4210
+ filePath: lit.filePath,
4211
+ lineNumber: lit.lineNumber,
4212
+ label,
4213
+ snippet: lit.snippet,
4214
+ });
4215
+ }
4216
+ for (const lit of comp.literalValues) {
4217
+ if (lit.surface === "tailwind-arbitrary")
4218
+ continue; // counted as arbitraryTailwind
4219
+ const label = `${lit.context ? `${lit.context}: ` : ""}${lit.value}`;
4220
+ records.push({
4221
+ category: "hardcodedLiteral",
4222
+ key: findingKey("hardcodedLiteral", lit.filePath, comp.label, `${lit.surface}:${label}`),
4223
+ filePath: lit.filePath,
4224
+ lineNumber: lit.lineNumber,
4225
+ label,
4226
+ snippet: lit.snippet,
4227
+ });
4228
+ }
4229
+ for (const v of comp.invariantViolations) {
4230
+ const label = `<${v.childComponent} ${v.prop}="${v.value}">`;
4231
+ records.push({
4232
+ category: "invariantViolation",
4233
+ key: findingKey("invariantViolation", v.filePath, comp.label, label),
4234
+ filePath: v.filePath,
4235
+ lineNumber: v.lineNumber,
4236
+ label,
4237
+ snippet: v.snippet,
4238
+ });
4239
+ }
4240
+ for (const c of comp.composabilityIssues) {
4241
+ records.push({
4242
+ category: "composability",
4243
+ key: findingKey("composability", c.filePath, comp.label, `${c.kind}:${c.detail}`),
4244
+ filePath: c.filePath,
4245
+ lineNumber: c.lineNumber,
4246
+ label: `${c.kind}: ${c.detail}`,
4247
+ ...(c.snippet ? { snippet: c.snippet } : {}),
4248
+ });
4249
+ }
4250
+ }
4251
+ for (const lit of report.diagnostics.hardcodedCssLiterals) {
4252
+ const label = `${lit.context ? `${lit.context}: ` : ""}${lit.value}`;
4253
+ records.push({
4254
+ category: "hardcodedLiteral",
4255
+ key: findingKey("hardcodedLiteral", lit.filePath, "", `css:${label}`),
4256
+ filePath: lit.filePath,
4257
+ lineNumber: lit.lineNumber,
4258
+ label,
4259
+ snippet: lit.snippet,
4260
+ });
4261
+ }
4262
+ for (const b of report.alignmentAudit.bypassedAtoms) {
4263
+ records.push({
4264
+ category: "rawPrimitive",
4265
+ key: findingKey("rawPrimitive", b.filePath, b.bypassingComponent, b.atomTarget),
4266
+ filePath: b.filePath,
4267
+ lineNumber: b.lineNumber,
4268
+ label: `raw ${b.atomTarget} in ${b.bypassingComponent}`,
4269
+ snippet: b.snippet,
4270
+ });
4271
+ }
4272
+ for (const o of report.alignmentAudit.callSiteOverrides) {
4273
+ records.push({
4274
+ category: "callSiteOverride",
4275
+ key: findingKey("callSiteOverride", o.filePath, o.parentComponent, `${o.childComponent}:${o.details.join("|")}`),
4276
+ filePath: o.filePath,
4277
+ lineNumber: o.lineNumber,
4278
+ label: `${o.parentComponent} overrides <${o.childComponent}> (${o.overrideKind})`,
4279
+ snippet: o.snippet,
4280
+ });
4281
+ }
4282
+ const failingContrast = [];
4283
+ for (const c of report.diagnostics.contrastFailures) {
4284
+ for (const theme of ["root", "light", "dark"]) {
4285
+ const r = c[theme];
4286
+ if (r && !r.passes)
4287
+ failingContrast.push(`${c.pairId}::${theme}`);
4288
+ }
4289
+ }
4290
+ failingContrast.sort();
4291
+ return { records, failingContrast };
4292
+ }
4293
+ function buildBaselineSnapshot(report, pluginVersion, commitSha, workingTreeDirty) {
4294
+ const { records, failingContrast } = collectDesignSystemFindings(report);
4295
+ return {
4296
+ schemaVersion: 1,
4297
+ createdAt: new Date().toISOString(),
4298
+ pluginVersion,
4299
+ ...(commitSha ? { commitSha } : {}),
4300
+ ...(workingTreeDirty ? { workingTreeDirty: true } : {}),
4301
+ mode: report.system.mode,
4302
+ counts: countFindings(records),
4303
+ failingContrast,
4304
+ totals: totalsByCategory(records),
4305
+ };
4306
+ }
4307
+ export async function auditDesignSystem(options) {
4308
+ const maxItems = Math.max(1, Math.min(options.limit ?? 25, 1000));
4309
+ const plugin = createDesignSystemPlugin(options.configOverrides);
4310
+ const pluginResult = await runChompPlugin(plugin, {
4311
+ repoPath: options.repoPath,
4312
+ repoId: options.repoId,
4313
+ repoName: options.repoName,
4314
+ dbPath: options.dbPath,
4315
+ graph: options.graph,
4316
+ persist: options.persistOverlays ?? true,
4317
+ });
4318
+ const fullReport = pluginResult.summary.report;
4319
+ const pkgFilter = options.packageName?.trim();
4320
+ const searchFilter = options.searchTerm?.trim().toLowerCase();
4321
+ // Pinned diff baseline: created if absent, replaced only on explicit request
4322
+ const repoPath = resolve(options.repoPath);
4323
+ const resolvedConfig = resolveDesignSystemConfig(repoPath, options.configOverrides);
4324
+ const baselinePath = options.baselinePath
4325
+ ? resolve(repoPath, options.baselinePath)
4326
+ : resolveBaselinePath(repoPath, resolvedConfig.config.baseline.path);
4327
+ const existingBaseline = readBaselineSnapshot(baselinePath);
4328
+ const scopeDirs = [
4329
+ ...new Set(fullReport.system.packages.filter((p) => p.frontend).map((p) => p.dir)),
4330
+ ];
4331
+ const explicit = options.setBaseline === true;
4332
+ const dsSettings = loadPluginSettings(repoPath, "design-system");
4333
+ const autoPinClean = options.autoPinCleanBaseline ?? (dsSettings.autoPinCleanBaseline !== false);
4334
+ const needsBootstrap = existingBaseline === null && !explicit && autoPinClean;
4335
+ const requireClean = options.requireCleanTree !== false;
4336
+ // Only inspect the tree when we are about to pin something
4337
+ const tree = explicit || needsBootstrap
4338
+ ? (options.workingTreeCheck ?? checkWorkingTreeClean)(repoPath, [
4339
+ ...scopeDirs,
4340
+ "chomp.config.json",
4341
+ ])
4342
+ : null;
4343
+ let baselineStatus;
4344
+ if (needsBootstrap && requireClean && tree?.clean === false) {
4345
+ baselineStatus = {
4346
+ path: baselinePath,
4347
+ exists: false,
4348
+ bootstrapped: false,
4349
+ written: false,
4350
+ refused: true,
4351
+ dirtyFiles: tree.dirtyFiles,
4352
+ note: `No baseline is pinned and the in-scope working tree has uncommitted changes (${tree.dirtyFiles.slice(0, 5).join(", ")}${tree.dirtyFiles.length > 5 ? ", …" : ""}). Pinning now would hide that drift inside the baseline, so it was refused. Commit or stash the changes and re-audit, or pin deliberately with set_baseline (\`chomp plugin baseline\`). chomp_diff_design_system returns NO_BASELINE until then.`,
4353
+ };
4354
+ }
4355
+ else if (explicit || needsBootstrap) {
4356
+ const dirty = tree?.clean === false;
4357
+ const snapshot = buildBaselineSnapshot(fullReport, pluginResult.pluginVersion, tree?.commitSha, dirty);
4358
+ writeBaselineSnapshot(baselinePath, snapshot);
4359
+ baselineStatus = {
4360
+ path: baselinePath,
4361
+ exists: true,
4362
+ bootstrapped: needsBootstrap,
4363
+ written: true,
4364
+ createdAt: snapshot.createdAt,
4365
+ ...(tree?.commitSha ? { commitSha: tree.commitSha } : {}),
4366
+ ...(dirty ? { dirtyFiles: tree.dirtyFiles } : {}),
4367
+ note: dirty
4368
+ ? "Baseline pinned explicitly from a working tree with uncommitted in-scope changes (recorded as workingTreeDirty); drift present in those changes is now part of the baseline."
4369
+ : tree?.clean === null
4370
+ ? needsBootstrap
4371
+ ? "No baseline existed, so this audit pinned the current tree. Working-tree cleanliness could not be verified (not a git repo, or git unavailable)."
4372
+ : "Baseline replaced on explicit request. Working-tree cleanliness could not be verified."
4373
+ : needsBootstrap
4374
+ ? "No baseline existed; pinned from a clean working tree."
4375
+ : "Baseline replaced from a clean working tree on explicit request.",
4376
+ };
4377
+ }
4378
+ else if (existingBaseline === null) {
4379
+ baselineStatus = {
4380
+ path: baselinePath,
4381
+ exists: false,
4382
+ bootstrapped: false,
4383
+ written: false,
4384
+ note: "Auto-pinning clean baseline is disabled in design-system settings; pin explicitly with set_baseline or `chomp plugin baseline`.",
4385
+ };
4386
+ }
4387
+ else {
4388
+ baselineStatus = {
4389
+ path: baselinePath,
4390
+ exists: true,
4391
+ bootstrapped: false,
4392
+ written: false,
4393
+ createdAt: existingBaseline.createdAt,
4394
+ ...(existingBaseline.commitSha ? { commitSha: existingBaseline.commitSha } : {}),
4395
+ ...(existingBaseline.workingTreeDirty
4396
+ ? { note: "The pinned baseline was cut from a dirty working tree (workingTreeDirty)." }
4397
+ : {}),
4398
+ };
4399
+ }
4400
+ let filteredComponents = fullReport.components;
4401
+ if (pkgFilter) {
4402
+ filteredComponents = filteredComponents.filter((c) => packageMatchesFilter(c.packageName, c.filePath, pkgFilter));
4403
+ }
4404
+ if (searchFilter) {
4405
+ filteredComponents = filteredComponents.filter((c) => c.label.toLowerCase().includes(searchFilter) ||
4406
+ c.name.toLowerCase().includes(searchFilter) ||
4407
+ c.filePath.toLowerCase().includes(searchFilter) ||
4408
+ c.entityId.toLowerCase().includes(searchFilter) ||
4409
+ c.atomicCandidates.some((a) => a.toLowerCase().includes(searchFilter)));
4410
+ }
4411
+ // Recommend top hotspot component node IDs for optional Active View highlighting
4412
+ const hotspotScore = (c) => c.undefinedTokens.length * 5 +
4413
+ c.arbitraryTailwind.length * 2 +
4414
+ c.primitiveScaleSkips.length * 2 +
4415
+ c.canvasProvenance.literalCount * 2 +
4416
+ c.invariantViolations.length * 3 +
4417
+ c.composabilityIssues.length * 2 +
4418
+ c.rawDomPrimitives.length;
4419
+ const recommendedHighlightNodeIds = [...filteredComponents]
4420
+ .sort((a, b) => hotspotScore(b) - hotspotScore(a))
4421
+ .filter((c) => hotspotScore(c) > 0)
4422
+ .slice(0, 12)
4423
+ .map((c) => c.entityId);
4424
+ return {
4425
+ plugin: {
4426
+ name: pluginResult.pluginName,
4427
+ version: pluginResult.pluginVersion,
4428
+ layer: pluginResult.layer,
4429
+ runId: pluginResult.runId,
4430
+ overlaysPersisted: pluginResult.overlayCount,
4431
+ durationMs: pluginResult.durationMs,
4432
+ },
4433
+ system: fullReport.system,
4434
+ coverage: fullReport.coverage,
4435
+ baseline: baselineStatus,
4436
+ summary: fullReport.summary,
4437
+ routeComposition: fullReport.routeComposition,
4438
+ atomicHierarchy: fullReport.atomicHierarchy,
4439
+ alignmentAudit: {
4440
+ bypassedAtoms: fullReport.alignmentAudit.bypassedAtoms.slice(0, maxItems),
4441
+ siblingAtomOverlaps: fullReport.alignmentAudit.siblingAtomOverlaps.slice(0, maxItems),
4442
+ nestedInteractive: fullReport.alignmentAudit.nestedInteractive.slice(0, maxItems),
4443
+ unextractedShapes: fullReport.alignmentAudit.unextractedShapes.slice(0, maxItems),
4444
+ parallelTwins: fullReport.alignmentAudit.parallelTwins.slice(0, maxItems),
4445
+ callSiteOverrides: fullReport.alignmentAudit.callSiteOverrides.slice(0, maxItems),
4446
+ propApiDrift: fullReport.alignmentAudit.propApiDrift.slice(0, maxItems),
4447
+ invariantViolations: fullReport.alignmentAudit.invariantViolations.slice(0, maxItems),
4448
+ composabilityIssues: fullReport.alignmentAudit.composabilityIssues.slice(0, maxItems),
4449
+ },
4450
+ dryAudit: {
4451
+ structuralJsxClones: fullReport.dryAudit.structuralJsxClones.slice(0, maxItems),
4452
+ atomicConsolidation: fullReport.dryAudit.atomicConsolidation,
4453
+ duplicateCssTokens: fullReport.dryAudit.duplicateCssTokens.slice(0, maxItems),
4454
+ },
4455
+ derivedTokens: fullReport.derivedTokens.slice(0, maxItems),
4456
+ agentExtendability: fullReport.agentExtendability,
4457
+ tokenCatalog: fullReport.tokenCatalog,
4458
+ tokenRegistry: fullReport.tokenRegistry,
4459
+ mergeDecisions: readMergeDecisions(repoPath),
4460
+ atomicConsolidation: fullReport.atomicConsolidation,
4461
+ diagnostics: {
4462
+ undefinedTokens: fullReport.diagnostics.undefinedTokens.slice(0, maxItems),
4463
+ undefinedCssClasses: fullReport.diagnostics.undefinedCssClasses.slice(0, maxItems),
4464
+ duplicateTokens: fullReport.diagnostics.duplicateTokens.slice(0, maxItems),
4465
+ unusedTokens: fullReport.diagnostics.unusedTokens.slice(0, maxItems),
4466
+ unbackedSemanticTokens: fullReport.diagnostics.unbackedSemanticTokens.slice(0, maxItems),
4467
+ themeSymmetryIssues: fullReport.diagnostics.themeSymmetryIssues.slice(0, maxItems),
4468
+ typographyTuples: fullReport.diagnostics.typographyTuples.slice(0, maxItems),
4469
+ typographyRoleClusters: fullReport.diagnostics.typographyRoleClusters.slice(0, maxItems),
4470
+ contextualStyleOverrides: fullReport.diagnostics.contextualStyleOverrides.slice(0, maxItems),
4471
+ contrastFailures: fullReport.diagnostics.contrastFailures.slice(0, maxItems),
4472
+ contrastAudits: fullReport.diagnostics.contrastAudits.slice(0, maxItems),
4473
+ dynamicClassPrefixes: fullReport.diagnostics.dynamicClassPrefixes,
4474
+ unusedCssSelectors: fullReport.diagnostics.unusedCssSelectors.slice(0, maxItems),
4475
+ hardcodedCssLiteralCount: fullReport.diagnostics.hardcodedCssLiterals.length,
4476
+ },
4477
+ components: filteredComponents.slice(0, maxItems),
4478
+ recommendedHighlightNodeIds,
4479
+ agentGuidance: [
4480
+ `System audited in ${fullReport.system.mode} mode (${fullReport.system.modeReason}); ${fullReport.system.packages.filter((p) => p.frontend).length} frontend package(s) in scope.`,
4481
+ ...fullReport.agentExtendability.pavedRoadBlueprint.extensionRules,
4482
+ "QUERY BEFORE WRITE ([PAT-MCP-08], [PAT-VIS-21]): Reuse tokens from `tokenCatalog.semantic` / `agentExtendability.pavedRoadBlueprint.canonicalTokensByRole`, building blocks from `reusableBuildingBlocks`, and `derivedTokens[].existingTokenMatch` instead of introducing raw hex/px literals or inline DOM primitives.",
4483
+ "VERIFY AFTER WRITE: After editing CSS or React/TSX components, call `chomp_diff_design_system` (and `chomp_get_diff`) to confirm no newly introduced undefined `var(--*)` tokens, arbitrary values, raw literals, bypassed atoms, composability issues or contrast regressions against the pinned baseline.",
4484
+ ...(fullReport.coverage.notes.length > 0
4485
+ ? [`COVERAGE: ${fullReport.coverage.notes.join(" ")}`]
4486
+ : []),
4487
+ ],
4488
+ };
4489
+ }
4490
+ /** Short labels (scope stripped) of the frontend packages in a report's scope. */
4491
+ export function frontendPackageLabels(report) {
4492
+ return report.system.packages
4493
+ .filter((p) => p.frontend)
4494
+ .map((p) => p.name?.replace(/^@[^/]+\//, "") ?? basename(p.dir === "." ? report.repoName : p.dir));
4495
+ }
4496
+ /**
4497
+ * Pins the current working tree as the diff baseline. Explicit by design: no other call ever
4498
+ * moves the baseline, so a re-audit can never silently move the goalposts of the gate.
4499
+ */
4500
+ export async function snapshotDesignSystemBaseline(options) {
4501
+ const repoPath = resolve(options.repoPath);
4502
+ const plugin = createDesignSystemPlugin(options.configOverrides);
4503
+ const liveGraph = options.graph ?? analyzeTarget(repoPath);
4504
+ const res = await runChompPlugin(plugin, {
4505
+ repoPath,
4506
+ repoId: options.repoId,
4507
+ repoName: options.repoName,
4508
+ dbPath: options.dbPath,
4509
+ graph: liveGraph,
4510
+ persist: false,
4511
+ });
4512
+ const report = res.summary.report;
4513
+ const resolvedConfig = resolveDesignSystemConfig(repoPath, options.configOverrides);
4514
+ const path = options.baselinePath
4515
+ ? resolve(repoPath, options.baselinePath)
4516
+ : resolveBaselinePath(repoPath, resolvedConfig.config.baseline.path);
4517
+ const tree = checkWorkingTreeClean(repoPath, [
4518
+ ...new Set(report.system.packages.filter((p) => p.frontend).map((p) => p.dir)),
4519
+ "chomp.config.json",
4520
+ ]);
4521
+ const snapshot = buildBaselineSnapshot(report, res.pluginVersion, options.commitSha ?? tree.commitSha ?? liveGraph.commitSha, tree.clean === false);
4522
+ writeBaselineSnapshot(path, snapshot);
4523
+ return { path, snapshot, workingTree: tree };
4524
+ }
4525
+ /**
4526
+ * Compares the live working-tree scan against the pinned baseline snapshot (`[PAT-MCP-02]`).
4527
+ * Findings are keyed by identity (file, component, value) and compared by occurrence count.
4528
+ */
4529
+ export async function diffDesignSystem(options) {
4530
+ const repoPath = resolve(options.repoPath);
4531
+ const repoName = options.repoName ?? resolveRepoName(repoPath);
4532
+ const repoId = options.repoId ?? repoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
4533
+ const resolvedConfig = resolveDesignSystemConfig(repoPath, options.configOverrides);
4534
+ const baselinePath = options.baselinePath
4535
+ ? resolve(repoPath, options.baselinePath)
4536
+ : resolveBaselinePath(repoPath, resolvedConfig.config.baseline.path);
4537
+ const baseline = readBaselineSnapshot(baselinePath);
4538
+ const liveGraph = options.graph ?? analyzeTarget(repoPath);
4539
+ const livePluginRes = await runChompPlugin(createDesignSystemPlugin(options.configOverrides), {
4540
+ repoPath,
4541
+ repoId,
4542
+ repoName,
4543
+ graph: liveGraph,
4544
+ persist: false,
4545
+ });
4546
+ const liveReport = livePluginRes.summary.report;
4547
+ const { records, failingContrast } = collectDesignSystemFindings(liveReport);
4548
+ const liveTotals = totalsByCategory(records);
4549
+ const emptyIssues = {
4550
+ undefinedTokens: [],
4551
+ arbitraryTailwind: [],
4552
+ primitiveScaleSkips: [],
4553
+ hardcodedLiterals: [],
4554
+ invariantViolations: [],
4555
+ rawPrimitives: [],
4556
+ composabilityIssues: [],
4557
+ callSiteOverrides: [],
4558
+ contrastFailures: [],
4559
+ };
4560
+ if (!baseline) {
4561
+ return {
4562
+ gateStatus: "NO_BASELINE",
4563
+ hasBaseline: false,
4564
+ baseline: { path: baselinePath },
4565
+ frontendPackages: frontendPackageLabels(liveReport),
4566
+ summary: {
4567
+ newUndefinedTokenCount: 0,
4568
+ resolvedUndefinedTokenCount: 0,
4569
+ newArbitraryTailwindCount: 0,
4570
+ resolvedArbitraryTailwindCount: 0,
4571
+ newPrimitiveScaleSkipCount: 0,
4572
+ newHardcodedLiteralCount: 0,
4573
+ newInvariantViolationCount: 0,
4574
+ newRawPrimitiveCount: 0,
4575
+ newComposabilityIssueCount: 0,
4576
+ newCallSiteOverrideCount: 0,
4577
+ newContrastFailureCount: 0,
4578
+ resolvedContrastFailureCount: 0,
4579
+ regressedComponentCount: 0,
4580
+ improvedComponentCount: 0,
4581
+ },
4582
+ newIssues: emptyIssues,
4583
+ resolvedIssues: { undefinedTokens: [], arbitraryTailwind: [], contrastFailures: [] },
4584
+ componentDeltas: [],
4585
+ liveTotals,
4586
+ remediationGuidance: [
4587
+ `No design-system baseline is pinned at ${baselinePath}. The gate cannot tell new drift from existing drift, so this is NOT a pass. Run chomp_audit_design_system on a clean working tree (it pins the baseline automatically and refuses when in-scope changes are uncommitted), or pin deliberately with \`chomp plugin baseline\` / set_baseline: true, then re-run the diff.`,
4588
+ ],
4589
+ };
4590
+ }
4591
+ const diff = diffFindings(baseline.counts, records);
4592
+ const byCategory = (cat) => diff.added.filter((r) => r.category === cat);
4593
+ const resolvedByCategory = (cat) => diff.resolved.filter((r) => r.key.startsWith(`${cat}|`));
4594
+ const baseFailing = new Set(baseline.failingContrast);
4595
+ const newContrastFailures = liveReport.diagnostics.contrastFailures.filter((c) => ["root", "light", "dark"].some((theme) => {
4596
+ const r = c[theme];
4597
+ return r && !r.passes && !baseFailing.has(`${c.pairId}::${theme}`);
4598
+ }));
4599
+ const liveFailingSet = new Set(failingContrast);
4600
+ const resolvedContrast = baseline.failingContrast.filter((id) => !liveFailingSet.has(id));
4601
+ // Per-component deltas (component label is the 3rd segment of the finding key)
4602
+ const labelFile = new Map();
4603
+ for (const c of liveReport.components) {
4604
+ labelFile.set(`${c.filePath}|${c.label}`, { entityId: c.entityId, filePath: c.filePath });
4605
+ }
4606
+ const deltas = new Map();
4607
+ const deltaFor = (filePath, label) => {
4608
+ const k = `${filePath}|${label}`;
4609
+ let d = deltas.get(k);
4610
+ if (!d) {
4611
+ d = {
4612
+ entityId: labelFile.get(k)?.entityId,
4613
+ label,
4614
+ filePath,
4615
+ added: 0,
4616
+ resolved: 0,
4617
+ addedFindings: [],
4618
+ };
4619
+ deltas.set(k, d);
4620
+ }
4621
+ return d;
4622
+ };
4623
+ for (const r of diff.added) {
4624
+ const component = r.key.split("|")[2];
4625
+ if (!component)
4626
+ continue;
4627
+ const d = deltaFor(r.filePath, component);
4628
+ d.added++;
4629
+ if (d.addedFindings.length < 6)
4630
+ d.addedFindings.push(`${r.category}: ${r.label}`);
4631
+ }
4632
+ for (const r of diff.resolved) {
4633
+ const [, file, component] = r.key.split("|");
4634
+ if (!component)
4635
+ continue;
4636
+ deltaFor(file, component).resolved += r.removed;
4637
+ }
4638
+ const componentDeltas = [...deltas.values()]
4639
+ .filter((d) => d.added > 0 || d.resolved > 0)
4640
+ .map((d) => ({
4641
+ ...(d.entityId ? { entityId: d.entityId } : {}),
4642
+ label: d.label,
4643
+ filePath: d.filePath,
4644
+ status: d.added > 0 ? "REGRESSED" : "IMPROVED",
4645
+ added: d.added,
4646
+ resolved: d.resolved,
4647
+ addedFindings: d.addedFindings,
4648
+ }))
4649
+ .sort((a, b) => b.added - a.added || a.label.localeCompare(b.label));
4650
+ const newIssues = {
4651
+ undefinedTokens: byCategory("undefinedToken"),
4652
+ arbitraryTailwind: byCategory("arbitraryTailwind"),
4653
+ primitiveScaleSkips: byCategory("primitiveSkip"),
4654
+ hardcodedLiterals: byCategory("hardcodedLiteral"),
4655
+ invariantViolations: byCategory("invariantViolation"),
4656
+ rawPrimitives: byCategory("rawPrimitive"),
4657
+ composabilityIssues: byCategory("composability"),
4658
+ callSiteOverrides: byCategory("callSiteOverride"),
4659
+ contrastFailures: newContrastFailures,
4660
+ };
4661
+ const regressedComponentCount = componentDeltas.filter((d) => d.status === "REGRESSED").length;
4662
+ const improvedComponentCount = componentDeltas.filter((d) => d.status === "IMPROVED").length;
4663
+ const gateStatus = diff.added.length === 0 && newContrastFailures.length === 0 ? "PASS" : "WARN";
4664
+ const tokenHome = liveReport.system.primaryTokenFiles[0];
4665
+ const remediationGuidance = [];
4666
+ if (newIssues.undefinedTokens.length > 0) {
4667
+ const names = [...new Set(newIssues.undefinedTokens.map((u) => u.label))];
4668
+ remediationGuidance.push(`Define ${names.map((n) => `\`${n}\``).join(", ")}${tokenHome ? ` in \`${tokenHome}\`` : " in the stylesheet that owns your theme tokens"} (or replace with an existing semantic token from \`tokenCatalog.semantic\`).`);
4669
+ }
4670
+ if (newIssues.arbitraryTailwind.length > 0) {
4671
+ remediationGuidance.push(`Replace ${newIssues.arbitraryTailwind.length} newly introduced arbitrary Tailwind class(es) (${[...new Set(newIssues.arbitraryTailwind.map((a) => `\`${a.label}\``))].slice(0, 5).join(", ")}) with theme utilities or tokens.`);
4672
+ }
4673
+ if (newIssues.primitiveScaleSkips.length > 0) {
4674
+ remediationGuidance.push(`Replace raw primitive reference(s) (${[...new Set(newIssues.primitiveScaleSkips.map((s) => `\`${s.label}\``))].join(", ")}) with the semantic token that aliases them (see \`primitiveScaleSkips[].suggestedSemantic\` in the audit).`);
4675
+ }
4676
+ if (newIssues.hardcodedLiterals.length > 0) {
4677
+ remediationGuidance.push(`Replace ${newIssues.hardcodedLiterals.length} newly introduced hardcoded value(s) with tokens; check \`derivedTokens[].existingTokenMatch\` for the nearest existing token.`);
4678
+ }
4679
+ if (newIssues.invariantViolations.length > 0) {
4680
+ remediationGuidance.push(`Pass a semantic token / variant instead of raw color literals to ${[...new Set(newIssues.invariantViolations.map((v) => `\`${v.label}\``))].slice(0, 4).join(", ")}.`);
4681
+ }
4682
+ if (newIssues.rawPrimitives.length > 0) {
4683
+ remediationGuidance.push(`Use the shared atom instead of ${newIssues.rawPrimitives.length} newly introduced raw element(s) (${[...new Set(newIssues.rawPrimitives.map((r) => `\`${r.label}\``))].slice(0, 4).join(", ")}).`);
4684
+ }
4685
+ if (newIssues.composabilityIssues.length > 0) {
4686
+ remediationGuidance.push(`Remove hidden margins / fixed widths / data-layer imports from drop-in components: ${newIssues.composabilityIssues.slice(0, 3).map((c) => c.label).join("; ")}.`);
4687
+ }
4688
+ if (newContrastFailures.length > 0) {
4689
+ remediationGuidance.push(`Fix ${newContrastFailures.length} new WCAG 2.1 contrast failure(s) (${newContrastFailures.map((c) => `${c.foregroundToken} on ${c.backgroundToken}`).join(", ")}).`);
4690
+ }
4691
+ if (remediationGuidance.length === 0) {
4692
+ remediationGuidance.push("Design System Gate PASSED: no findings beyond the pinned baseline (no new undefined tokens, arbitrary values, hardcoded literals, bypassed atoms, composability issues or contrast regressions).");
4693
+ }
4694
+ return {
4695
+ gateStatus,
4696
+ hasBaseline: true,
4697
+ baseline: {
4698
+ path: baselinePath,
4699
+ createdAt: baseline.createdAt,
4700
+ ...(baseline.commitSha ? { commitSha: baseline.commitSha } : {}),
4701
+ pluginVersion: baseline.pluginVersion,
4702
+ },
4703
+ frontendPackages: frontendPackageLabels(liveReport),
4704
+ summary: {
4705
+ newUndefinedTokenCount: newIssues.undefinedTokens.length,
4706
+ resolvedUndefinedTokenCount: resolvedByCategory("undefinedToken").length,
4707
+ newArbitraryTailwindCount: newIssues.arbitraryTailwind.length,
4708
+ resolvedArbitraryTailwindCount: resolvedByCategory("arbitraryTailwind").length,
4709
+ newPrimitiveScaleSkipCount: newIssues.primitiveScaleSkips.length,
4710
+ newHardcodedLiteralCount: newIssues.hardcodedLiterals.length,
4711
+ newInvariantViolationCount: newIssues.invariantViolations.length,
4712
+ newRawPrimitiveCount: newIssues.rawPrimitives.length,
4713
+ newComposabilityIssueCount: newIssues.composabilityIssues.length,
4714
+ newCallSiteOverrideCount: newIssues.callSiteOverrides.length,
4715
+ newContrastFailureCount: newContrastFailures.length,
4716
+ resolvedContrastFailureCount: resolvedContrast.length,
4717
+ regressedComponentCount,
4718
+ improvedComponentCount,
4719
+ },
4720
+ newIssues,
4721
+ resolvedIssues: {
4722
+ undefinedTokens: resolvedByCategory("undefinedToken").map((r) => r.key.split("|")[3]),
4723
+ arbitraryTailwind: resolvedByCategory("arbitraryTailwind").map((r) => r.key.split("|")[3]),
4724
+ contrastFailures: resolvedContrast,
4725
+ },
4726
+ componentDeltas,
4727
+ liveTotals,
4728
+ remediationGuidance,
4729
+ };
4730
+ }