stylelint-plugin-rhythmguard 3.18.0 → 3.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/CONTRIBUTING.md +2 -2
  3. package/README.md +4 -4
  4. package/SECURITY.md +14 -0
  5. package/agents/claude-code/SKILL.md +14 -1
  6. package/agents/copilot/{copilot-instructions.md → rhythmguard.instructions.md} +7 -1
  7. package/agents/cursor/rhythmguard.mdc +5 -3
  8. package/package.json +2 -2
  9. package/src/audit/args.js +30 -8
  10. package/src/audit/baseline.js +44 -2
  11. package/src/audit/codemod.js +2 -0
  12. package/src/audit/config.js +7 -0
  13. package/src/audit/contract.js +131 -17
  14. package/src/audit/next-steps.js +86 -0
  15. package/src/audit/non-authored.js +1 -0
  16. package/src/audit/render-github.js +52 -15
  17. package/src/audit/render-markdown.js +58 -17
  18. package/src/audit/render-text.js +76 -6
  19. package/src/audit/render-utils.js +14 -0
  20. package/src/audit/report.js +235 -10
  21. package/src/audit/scan/files.js +5 -0
  22. package/src/audit/scan/stylesheets.js +63 -59
  23. package/src/audit/scan/templates.js +2 -0
  24. package/src/audit/shared.js +7 -1
  25. package/src/audit/token-chains.js +1 -0
  26. package/src/cli/audit.js +20 -11
  27. package/src/cli/doctor.js +853 -237
  28. package/src/cli/first-run.js +210 -0
  29. package/src/cli/index.js +25 -1
  30. package/src/cli/index.mjs +3 -0
  31. package/src/cli/init.js +75 -26
  32. package/src/cli/quickstart.js +109 -118
  33. package/src/cli/scale.js +223 -0
  34. package/src/configs/recommended.js +3 -1
  35. package/src/configs/strict.js +3 -1
  36. package/src/configs/tailwind.js +15 -0
  37. package/src/core/decisions.js +18 -5
  38. package/src/core/fs-cache.js +1 -0
  39. package/src/core/options.js +2 -1
  40. package/src/core/scale-inference.js +72 -52
  41. package/src/core/tailwind-class-analysis.js +56 -13
  42. package/src/core/token-index.js +55 -14
  43. package/src/core/token-map.js +140 -88
  44. package/src/core/token-sources.js +461 -40
  45. package/src/core/value-nodes.js +4 -2
  46. package/src/eslint/class-context.js +330 -0
  47. package/src/eslint/literal-spans.js +5 -4
  48. package/src/eslint/rules/tailwind-class-use-scale.js +30 -9
  49. package/src/presets/default-scale.js +42 -0
  50. package/src/presets/scales.js +6 -1
  51. package/src/rules/no-offscale-transform/index.js +17 -5
  52. package/src/rules/prefer-token/index.js +51 -15
  53. package/src/rules/use-scale/index.js +7 -4
  54. package/types/__checks__/consumer.ts +17 -0
  55. package/types/__checks__/eslint-config.ts +5 -0
  56. package/types/audit.d.ts +42 -3
  57. package/types/cli.d.ts +77 -1
  58. package/types/shared.d.ts +10 -0
@@ -8,6 +8,7 @@ const {
8
8
  getNormalizedValueKeys,
9
9
  hasLineComments,
10
10
  } = require('../core/token-sources');
11
+ const { findDeclarationProperty } = require('./scan/stylesheets');
11
12
  const { formatPath } = require('./shared');
12
13
 
13
14
  function collectTokenContract({
@@ -32,12 +33,14 @@ function collectTokenContract({
32
33
  try {
33
34
  source = readSource(filePath);
34
35
  } catch {
36
+ // Unreadable since the scan (deleted, permissions): this pass reads only what it can.
35
37
  continue;
36
38
  }
37
39
 
38
40
  const file = formatPath(filePath);
39
41
  collectTokenDefinitions(source, file, definitions, matchesKind, baseFontSize);
40
- collectTokenUses(source, file, uses, matchesKind);
42
+ // A token source token read for its `$type` or a camelCase name (`--gap-sm`, `--spacingXs`) counts as used too.
43
+ collectTokenUses(source, file, uses, (token) => matchesKind(token) || externalTokenDefinitions.has(token));
41
44
  }
42
45
 
43
46
  for (const entry of externalTokenDefinitions.values()) {
@@ -53,7 +56,10 @@ function collectTokenContract({
53
56
  }
54
57
 
55
58
  for (const finding of cssFindings) {
56
- addRawValue(rawValues, rawValueLocations, finding.value, finding);
59
+ // A missing-token finding's value is a token name, not a raw value.
60
+ if (finding.type !== 'missing-token') {
61
+ addRawValue(rawValues, rawValueLocations, finding.value, finding);
62
+ }
57
63
  }
58
64
 
59
65
  for (const finding of tailwindFindings) {
@@ -62,7 +68,9 @@ function collectTokenContract({
62
68
 
63
69
  const definedTokens = mapTokenEntries(definitions);
64
70
  const usedTokens = mapTokenEntries(uses);
65
- const missingTokens = usedTokens.filter(({ token }) => !definitions.has(token));
71
+ // A DTCG `$deprecated` token is not a scale step, but it is declared: using it is not a missing token.
72
+ const deprecatedTokens = new Set((tokenSourceReports || []).flatMap((source) => source.deprecated || []));
73
+ const missingTokens = usedTokens.filter(({ token }) => !definitions.has(token) && !deprecatedTokens.has(token));
66
74
  const unusedTokens = definedTokens.filter(({ token }) => !uses.has(token));
67
75
  const rawValueMatches = collectRawValueMatches(rawValues, definitions, baseFontSize);
68
76
  const conflictingTokens = collectConflictingTokens(definitions);
@@ -123,6 +131,79 @@ function collectTokenUses(source, file, uses, matchesKind) {
123
131
  }
124
132
  }
125
133
 
134
+ const MISSING_TOKEN_RULE = 'rhythmguard/missing-token';
135
+
136
+ /**
137
+ * One finding per `var()` of a missing token: a token the scanned
138
+ * stylesheets use and nothing defines. `missingTokens` is the token
139
+ * contract's list; a token an installed token package or a token source of
140
+ * another kind defines (`knownTokens`) is not missing. Comments are blanked
141
+ * first, so a commented-out declaration is not a finding.
142
+ */
143
+ function collectMissingTokenFindings({
144
+ cssFiles,
145
+ knownTokens = new Set(),
146
+ missingTokens,
147
+ readSource = (filePath) => fs.readFileSync(filePath, 'utf8'),
148
+ tokenKind,
149
+ }) {
150
+ const missing = new Set(missingTokens
151
+ .map(({ token }) => token)
152
+ .filter((token) => !knownTokens.has(token)));
153
+ if (missing.size === 0) {
154
+ return [];
155
+ }
156
+
157
+ const matchesKind = createTokenKindMatcher(tokenKind);
158
+ const findings = [];
159
+ for (const filePath of cssFiles) {
160
+ let source;
161
+ try {
162
+ source = readSource(filePath);
163
+ } catch {
164
+ // Unreadable since the scan (deleted, permissions): this pass reads only what it can.
165
+ continue;
166
+ }
167
+ const file = formatPath(filePath);
168
+ const text = blankComments(source, hasLineComments(file));
169
+ const varPattern = /var\(\s*(--[\w-]+)/g;
170
+ let match;
171
+ while ((match = varPattern.exec(text)) !== null) {
172
+ const token = match[1];
173
+ if (!missing.has(token) || !matchesKind(token)) {
174
+ continue;
175
+ }
176
+ const { column, line } = offsetToPosition(text, match.index);
177
+ findings.push({
178
+ column,
179
+ file,
180
+ line,
181
+ property: findDeclarationProperty(source, line, column),
182
+ rule: MISSING_TOKEN_RULE,
183
+ text: `Token "${token}" is used but not defined in any scanned stylesheet, token source or installed token package.`,
184
+ type: 'missing-token',
185
+ value: token,
186
+ });
187
+ }
188
+ }
189
+ return findings;
190
+ }
191
+
192
+ /** The source with block comments, and `//` line comments where the syntax has them, replaced by spaces of the same length. */
193
+ function blankComments(source, lineComments) {
194
+ const blank = (match) => match.replace(/[^\n]/g, ' ');
195
+ const blocked = source.replace(/\/\*[\s\S]*?\*\//g, blank);
196
+ // `//` after a colon is a URL (`https://`), not a comment.
197
+ return lineComments ? blocked.replace(/(^|[^:])\/\/[^\n]*/g, (match, lead) => `${lead}${blank(match.slice(lead.length))}`) : blocked;
198
+ }
199
+
200
+ /** 1-based line and column of a character offset. */
201
+ function offsetToPosition(text, offset) {
202
+ const before = text.slice(0, offset);
203
+ const line = before.split('\n').length;
204
+ return { column: offset - before.lastIndexOf('\n'), line };
205
+ }
206
+
126
207
  function addRawValue(rawValues, rawValueLocations, value, finding) {
127
208
  if (!value) {
128
209
  return;
@@ -232,23 +313,55 @@ function buildReport({
232
313
  dir,
233
314
  externalTokenDefinitions,
234
315
  includeMotion,
316
+ knownTokens = new Set(),
235
317
  linksOutsideRoot = [],
236
318
  motionFindings,
237
319
  nonAuthoredFiles = [],
238
320
  parseErrorFindings = [],
239
321
  readSource,
322
+ reportMissingTokens = false,
240
323
  scale,
241
324
  scanScope,
242
325
  scssFiles = 0,
243
326
  scssSkipped = 0,
244
327
  stylelintIgnored = 0,
328
+ stylelintMissing = 0,
245
329
  templateFiles,
246
330
  tailwindFindings,
247
331
  tokenCandidateMinCount,
248
332
  tokenKind,
249
333
  tokenSourceReports,
250
334
  tokenSourceWarnings,
335
+ unauditedFiles = new Set(),
251
336
  }) {
337
+ const tokenContract = collectTokenContract({
338
+ baseFontSize,
339
+ cssFiles,
340
+ cssFindings,
341
+ externalTokenDefinitions,
342
+ minCandidateCount: tokenCandidateMinCount,
343
+ readSource,
344
+ tailwindFindings,
345
+ tokenKind,
346
+ tokenSourceReports,
347
+ });
348
+
349
+ // With --report-missing-tokens, each var() of a token that no scanned
350
+ // stylesheet, token source or installed token package defines is a finding
351
+ // (ai-03). Off by default in 3.x, so the default findings do not grow.
352
+ if (reportMissingTokens) {
353
+ cssFindings = [
354
+ ...cssFindings,
355
+ ...collectMissingTokenFindings({
356
+ cssFiles: cssFiles.filter((file) => !unauditedFiles.has(file)),
357
+ knownTokens,
358
+ missingTokens: tokenContract.missingTokens,
359
+ readSource,
360
+ tokenKind,
361
+ }),
362
+ ];
363
+ }
364
+
252
365
  const offScaleValues = countByValue(cssFindings
253
366
  .filter((finding) => finding.type === 'off-scale' && finding.value)
254
367
  .map((finding) => finding.value));
@@ -273,9 +386,10 @@ function buildReport({
273
386
  ...tailwindFindings.map((finding) => finding.file),
274
387
  ])).slice(0, 10);
275
388
 
276
- // A stylesheet skipped for want of postcss-scss, or excluded by the project's
277
- // .stylelintignore, was not audited: it is neither scanned nor clean.
278
- const cssFilesScanned = Math.max(0, cssFiles.length - scssSkipped - stylelintIgnored);
389
+ // A stylesheet skipped for want of postcss-scss or of Stylelint itself, or
390
+ // excluded by the project's .stylelintignore, was not audited: it is neither
391
+ // scanned nor clean.
392
+ const cssFilesScanned = Math.max(0, cssFiles.length - scssSkipped - stylelintIgnored - stylelintMissing);
279
393
  const totalFiles = cssFilesScanned + templateFiles.length;
280
394
  const totalWarnings = cssFindings.length + motionFindings.length + tailwindFindings.length;
281
395
  const filesWithIssues = issueFiles.size;
@@ -284,17 +398,6 @@ function buildReport({
284
398
  parseErrorFiles: countFiles(parseErrorFindings),
285
399
  totalFiles,
286
400
  }));
287
- const tokenContract = collectTokenContract({
288
- baseFontSize,
289
- cssFiles,
290
- cssFindings,
291
- externalTokenDefinitions,
292
- minCandidateCount: tokenCandidateMinCount,
293
- readSource,
294
- tailwindFindings,
295
- tokenKind,
296
- tokenSourceReports,
297
- });
298
401
 
299
402
  return {
300
403
  config,
@@ -323,6 +426,8 @@ function buildReport({
323
426
  scssFiles,
324
427
  scssSkipped,
325
428
  stylelintIgnored,
429
+ // Stylesheets found in a project without Stylelint: class strings were audited, these were not.
430
+ stylelintMissing,
326
431
  // Vendored, minified or built stylesheets left out of the audit (#161).
327
432
  nonAuthoredSkipped: nonAuthoredFiles.length,
328
433
  nonAuthoredFiles,
@@ -419,10 +524,15 @@ function toAuditContractReport(report) {
419
524
  decisions: report.decisions || null,
420
525
  motion: report.motion,
421
526
  scale: {
527
+ // Set when class strings are checked against another scale than the
528
+ // stylesheets: Tailwind's default ladder when no project scale exists.
529
+ classStrings: report.scale && report.scale.classStrings ? report.scale.classStrings : null,
422
530
  cleanliness: report.scaleCleanliness,
423
531
  files: report.scale ? report.scale.files : [],
424
532
  offScaleProperties: report.offScaleProperties || {},
425
533
  offScaleValues: report.offScaleValues,
534
+ // The preset a fallback is: "tailwind" in a Tailwind project, else "rhythmic-4"; null otherwise.
535
+ preset: report.scale && report.scale.preset ? report.scale.preset : null,
426
536
  rejected: report.scale && report.scale.rejected ? report.scale.rejected : null,
427
537
  source: report.scale ? report.scale.source : 'default',
428
538
  tokenOpportunities: report.tokenOpportunities,
@@ -434,6 +544,8 @@ function toAuditContractReport(report) {
434
544
  scanned: report.scanned,
435
545
  schemaVersion: '2.0',
436
546
  summary: report.summary,
547
+ // Every loader warning of the run: token sources, the Tailwind config (cq-05, tf-02).
548
+ warnings: [...new Set(report.tokenSourceWarnings || [])],
437
549
  };
438
550
  }
439
551
 
@@ -523,7 +635,9 @@ module.exports = {
523
635
  AUDIT_JSON_SCHEMA,
524
636
  addRawValue,
525
637
  buildReport,
638
+ MISSING_TOKEN_RULE,
526
639
  collectConflictingTokens,
640
+ collectMissingTokenFindings,
527
641
  collectRawValueMatches,
528
642
  collectTokenContract,
529
643
  collectTokenDefinitions,
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The commands the quickstart, `init` and the audit's text footer print next,
5
+ * built from what the run scanned rather than written as literals, so each one
6
+ * works when pasted: the install line names every package the pasted config
7
+ * needs, the lint glob matches the stylesheets that were found, and the audit
8
+ * command repeats the run's own scale flags (dx-01, dx-05, dx-10, dx-11).
9
+ */
10
+ const path = require('node:path');
11
+
12
+ const { peerDependencies } = require('../../package.json');
13
+
14
+ const SAFE_DIRECTORY = /^[\w.@+-]+$/;
15
+
16
+ function shellQuote(value) {
17
+ return /^[\w./@%+=:,-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
18
+ }
19
+
20
+ /** `npm install` for the Stylelint path: Stylelint at the plugin's peer range, plus what the pasted config extends or parses with. */
21
+ function stylelintInstallLine({ scss = false, tailwindConfig = false } = {}) {
22
+ return [
23
+ 'npm install --save-dev',
24
+ // Double quotes: the range holds spaces and ||, and cmd.exe does not take single quotes.
25
+ `"stylelint@${peerDependencies.stylelint}"`,
26
+ 'stylelint-plugin-rhythmguard',
27
+ ...(tailwindConfig ? ['stylelint-config-tailwindcss'] : []),
28
+ ...(scss ? ['postcss-scss'] : []),
29
+ ].join(' ');
30
+ }
31
+
32
+ /** `npm install` for the class-string path, with the TypeScript parser when the snippet uses it. */
33
+ function eslintInstallLine({ typescript = false } = {}) {
34
+ return ['npm install --save-dev eslint eslint-plugin-rhythmguard', ...(typescript ? ['typescript-eslint'] : [])].join(' ');
35
+ }
36
+
37
+ /**
38
+ * The Stylelint glob for the stylesheets a run found: under their one top-level
39
+ * directory when they share it (`src/**\/*.css`), else from the root, with the
40
+ * extensions that occur (`*.{css,scss}`).
41
+ */
42
+ function lintGlob(cwd, cssFiles) {
43
+ const relative = cssFiles.map((file) => path.relative(cwd, file)).filter((file) => file && !file.startsWith('..'));
44
+ const extensions = [...new Set(relative.map((file) => path.extname(file).slice(1)).filter(Boolean))].sort();
45
+ const pattern = extensions.length > 1 ? `*.{${extensions.join(',')}}` : `*.${extensions[0] || 'css'}`;
46
+ const tops = new Set(relative.map((file) => (file.includes(path.sep) ? file.split(path.sep)[0] : '')));
47
+ const top = tops.size === 1 ? [...tops][0] : '';
48
+ // The glob is printed inside double quotes for pasting, where $(...) and
49
+ // backticks still expand, so a directory name goes in only when it is plain.
50
+ return top && SAFE_DIRECTORY.test(top) ? `${top}/**/${pattern}` : `**/${pattern}`;
51
+ }
52
+
53
+ /** `npx rhythmguard audit <dir>` with the scale flags of the run it describes. */
54
+ function auditCommand({ dir = '.', scale = null, tailwindConfig = null, tokenSources = [] } = {}) {
55
+ const scaleArg = Array.isArray(scale) ? scale.join(',') : scale;
56
+ return [
57
+ 'npx rhythmguard audit',
58
+ shellQuote(dir),
59
+ ...(scaleArg ? [`--scale ${shellQuote(String(scaleArg))}`] : []),
60
+ ...tokenSources.map((file) => `--token-source ${shellQuote(file)}`),
61
+ ...(tailwindConfig ? [`--tailwind-config ${shellQuote(tailwindConfig)}`] : []),
62
+ ].join(' ');
63
+ }
64
+
65
+ /**
66
+ * The audit command a CLI run should be repeated with: only the flags the user
67
+ * passed, since anything from .rhythmguardrc.json is read again anyway.
68
+ */
69
+ function auditCommandFromArgs(parsed) {
70
+ const passed = parsed.cliOptions || new Set();
71
+ return auditCommand({
72
+ dir: parsed.dir || '.',
73
+ scale: passed.has('scale') ? parsed.scale : null,
74
+ tailwindConfig: passed.has('tailwindConfigPath') ? parsed.tailwindConfigPath : null,
75
+ tokenSources: passed.has('tokenSources') ? parsed.tokenSources.map((entry) => (typeof entry === 'string' ? entry : entry.path)) : [],
76
+ });
77
+ }
78
+
79
+ module.exports = {
80
+ auditCommand,
81
+ auditCommandFromArgs,
82
+ eslintInstallLine,
83
+ lintGlob,
84
+ shellQuote,
85
+ stylelintInstallLine,
86
+ };
@@ -63,6 +63,7 @@ function nonAuthoredReason(relativePath, readSource) {
63
63
  try {
64
64
  source = readSource();
65
65
  } catch {
66
+ // Unreadable: no content to classify, so the file counts as authored.
66
67
  return null;
67
68
  }
68
69
  return isBuiltBundle(source) ? 'bundle' : null;
@@ -1,26 +1,62 @@
1
1
  'use strict';
2
2
 
3
- const { getAllFindings } = require('./baseline');
3
+ const { getAllFindings, isTokenDebtFinding } = require('./baseline');
4
+ const { newFindingsPhrase } = require('./render-utils');
5
+
6
+ /**
7
+ * GitHub shows at most 10 error and 10 warning annotations per step and drops
8
+ * the rest without a word, so the one line a pull request added was annotation
9
+ * 4,695 of 5,987 (ci-03). The summary comes first; with a baseline only the
10
+ * new findings are annotated, drift as errors and token debt as warnings;
11
+ * each type stops at the cap with a notice that says how many were left out.
12
+ * Arrays are walked, not spread:
13
+ * spreading 150,000 findings into push() overflowed the stack (cq-04).
14
+ */
15
+ const ANNOTATIONS_PER_TYPE = 10;
16
+
17
+ function annotation(level, finding, text) {
18
+ return `::${level} file=${escapeGithubProperty(finding.file)},line=${finding.line || 1},col=${finding.column || 1},title=${escapeGithubProperty(finding.rule || 'rhythmguard')}::${escapeGithubData(text)}`;
19
+ }
4
20
 
5
21
  function renderGithub(report) {
6
22
  const findings = getAllFindings(report);
7
- const lines = report.baseline
8
- ? [`::notice title=Rhythmguard audit::Since baseline: ${report.baseline.resolvedFindingsCount} resolved, ${report.baseline.newFindingsCount} new`]
9
- : [];
10
- // A stylesheet that failed to parse was not audited: an error on its line.
11
- lines.push(...((report.findings && report.findings.parseErrors) || []).map((finding) =>
12
- `::error file=${escapeGithubProperty(finding.file)},line=${finding.line || 1},col=${finding.column || 1},title=${escapeGithubProperty(finding.rule || 'CssSyntaxError')}::${escapeGithubData(`Not audited: ${finding.text || ''}`)}`,
13
- ));
14
- lines.push(...findings.map((finding) =>
15
- `::warning file=${escapeGithubProperty(finding.file)},line=${finding.line || 1},col=${finding.column || 1},title=${escapeGithubProperty(finding.rule || 'rhythmguard')}::${escapeGithubData(finding.text || '')}`,
16
- ));
23
+ const parseErrors = (report.findings && report.findings.parseErrors) || [];
24
+ const baseline = report.baseline || null;
17
25
  const findingWord = findings.length === 1 ? 'finding' : 'findings';
18
26
  const fileWord = report.filesWithIssues === 1 ? 'file' : 'files';
19
- lines.push(
20
- `::notice title=Rhythmguard audit::${escapeGithubData(
27
+ const lines = [
28
+ `::notice title=Rhythmguard audit::${escapeGithubData([
29
+ ...(baseline ? [`Since baseline: ${baseline.resolvedFindingsCount} resolved, ${newFindingsPhrase(baseline)}.`] : []),
21
30
  `${findings.length} ${findingWord} across ${report.filesWithIssues} ${fileWord}, ${report.scaleCleanliness}% scale cleanliness`,
22
- )}`,
23
- );
31
+ ].join(' '))}`,
32
+ ];
33
+
34
+ // Errors: stylesheets that could not be parsed, then (with a baseline) new findings.
35
+ const errors = [];
36
+ for (const finding of parseErrors) {
37
+ errors.push(annotation('error', { ...finding, rule: finding.rule || 'CssSyntaxError' }, `Not audited: ${finding.text || ''}`));
38
+ }
39
+ // New drift is an error. New token debt is a warning: it is not drift and
40
+ // fails no gate unless --fail-on-new-token-debt is set (dx-08).
41
+ const errorLines = [...errors];
42
+ const warningLines = [];
43
+ for (const finding of baseline ? baseline.newFindings || [] : findings) {
44
+ if (baseline && !isTokenDebtFinding(finding)) {
45
+ errorLines.push(annotation('error', finding, `New since the baseline: ${finding.text || ''}`));
46
+ } else {
47
+ warningLines.push(annotation('warning', finding, `${baseline ? 'New since the baseline: ' : ''}${finding.text || ''}`));
48
+ }
49
+ }
50
+
51
+ for (const group of [errorLines, warningLines]) {
52
+ for (const line of group.slice(0, ANNOTATIONS_PER_TYPE)) {
53
+ lines.push(line);
54
+ }
55
+ }
56
+ const left = Math.max(0, errorLines.length - ANNOTATIONS_PER_TYPE) + Math.max(0, warningLines.length - ANNOTATIONS_PER_TYPE);
57
+ if (left > 0) {
58
+ lines.push(`::notice title=Rhythmguard audit::${escapeGithubData(`${left} more not annotated: GitHub shows ${ANNOTATIONS_PER_TYPE} per type. The full list is in --format markdown or --format json.`)}`);
59
+ }
24
60
  return `${lines.join('\n')}\n`;
25
61
  }
26
62
 
@@ -40,6 +76,7 @@ function escapeGithubProperty(value) {
40
76
  }
41
77
 
42
78
  module.exports = {
79
+ ANNOTATIONS_PER_TYPE,
43
80
  escapeGithubData,
44
81
  escapeGithubProperty,
45
82
  renderGithub,
@@ -1,9 +1,14 @@
1
1
  'use strict';
2
2
 
3
3
  const { sortCountMap } = require('./contract');
4
- const { escapeMarkdown, markdownCode, tableCode } = require('./render-utils');
4
+ const { auditCommand } = require('./next-steps');
5
+ const { nothingAudited, nothingAuditedReasons } = require('./render-text');
6
+ const { escapeMarkdown, markdownCode, newFindingsPhrase, tableCode } = require('./render-utils');
5
7
 
6
8
  function describeScaleSource(scale) {
9
+ if (scale.rejected && scale.rejected.source === 'token-sources') {
10
+ return `${scale.source} (token sources gave no scale; see the warnings)`;
11
+ }
7
12
  if (scale.rejected) {
8
13
  return `${scale.source} (${scale.rejected.source} rejected: ${scale.rejected.reasons.join(', ')})`;
9
14
  }
@@ -12,13 +17,25 @@ function describeScaleSource(scale) {
12
17
  : scale.source;
13
18
  }
14
19
 
15
- function renderMarkdown(report) {
20
+ /**
21
+ * The report a pull request comment carries. GitHub rejects a comment over
22
+ * 65,536 characters, and on 300 stylesheets this reached 64,473 with the new
23
+ * finding at line 129 (ci-03): new findings now come first, and file lists are
24
+ * cut to five names.
25
+ */
26
+ function renderMarkdown(report, options = {}) {
16
27
  const lines = [
17
28
  '# Rhythmguard Design-System Audit',
18
29
  '',
19
- ...(report.baseline ? [`**Since baseline:** ${report.baseline.resolvedFindingsCount} resolved, ${report.baseline.newFindingsCount} new.`, ''] : []),
30
+ ...(report.baseline ? [`**Since baseline:** ${report.baseline.resolvedFindingsCount} resolved, ${newFindingsPhrase(report.baseline)}.`, ''] : []),
20
31
  `Directory: ${markdownCode(report.directory)}`,
21
32
  '',
33
+ ];
34
+ if (nothingAudited(report)) {
35
+ lines.push(`**Nothing was audited:** ${escapeMarkdown(nothingAuditedReasons(report).join('; '))}.`, '');
36
+ }
37
+ appendNewFindingsMarkdown(lines, report);
38
+ lines.push(
22
39
  '## Summary',
23
40
  '',
24
41
  '| Metric | Value |',
@@ -27,6 +44,7 @@ function renderMarkdown(report) {
27
44
  `| Template files scanned | ${report.templateFilesScanned} |`,
28
45
  ...(report.scanned && report.scanned.scssFiles > 0 ? [`| SCSS files scanned | ${report.scanned.scssFiles - report.scanned.scssSkipped} |`] : []),
29
46
  ...(report.scanned && report.scanned.scssSkipped > 0 ? [`| SCSS files skipped (install postcss-scss) | ${report.scanned.scssSkipped} |`] : []),
47
+ ...(report.scanned && report.scanned.stylelintMissing > 0 ? [`| Stylesheets not audited (Stylelint is not installed: \`npm install --save-dev stylelint\`) | ${report.scanned.stylelintMissing} |`] : []),
30
48
  ...(report.scanned && report.scanned.stylelintIgnored > 0 ? [`| Stylesheets ignored by .stylelintignore (not audited) | ${report.scanned.stylelintIgnored} |`] : []),
31
49
  ...(report.scanned && report.scanned.nonAuthoredSkipped > 0 ? [`| Non-authored stylesheets skipped (vendored, minified or built; --include-non-authored audits them) | ${report.scanned.nonAuthoredSkipped} |`] : []),
32
50
  ...(report.scanned && report.scanned.linksOutsideRoot > 0 ? [`| Symbolic links not followed (they point outside the scanned directory) | ${report.scanned.linksOutsideRoot} |`] : []),
@@ -34,11 +52,14 @@ function renderMarkdown(report) {
34
52
  `| Files with issues | ${report.filesWithIssues} |`,
35
53
  `| Total findings | ${report.totalWarnings} |`,
36
54
  `| Scale cleanliness | ${report.scaleCleanliness}% |`,
37
- ];
55
+ );
38
56
 
39
57
  if (report.scale) {
40
58
  lines.push(`| Scale | ${report.scale.values.join(', ')} |`);
41
59
  lines.push(`| Scale source | ${escapeMarkdown(describeScaleSource(report.scale))} |`);
60
+ if (report.scale.classStrings) {
61
+ lines.push(`| Class-string scale | ${escapeMarkdown(report.scale.classStrings.name)} |`);
62
+ }
42
63
  }
43
64
 
44
65
  if (report.decisions) {
@@ -92,7 +113,8 @@ function renderMarkdown(report) {
92
113
  if (report.totalWarnings === 0) {
93
114
  lines.push('- Keep Rhythmguard in CI to prevent new drift.');
94
115
  } else {
95
- lines.push('- Run deterministic autofix for CSS declarations where appropriate.');
116
+ const command = options.auditCommand || auditCommand({ dir: report.directory });
117
+ lines.push(`- Propose one decision per off-scale value with ${markdownCode(`${command} --plan`)}, then rewrite each decided value with ${markdownCode('npx rhythmguard fix <dir> --value <px> --to <step or token>')}. Snapping every value at once can move layout.`);
96
118
  lines.push('- Review Tailwind arbitrary spacing values with UX/design-system owners.');
97
119
  lines.push('- Convert repeated raw on-scale values into existing design tokens.');
98
120
  }
@@ -117,7 +139,7 @@ function appendParseErrorsMarkdown(lines, report) {
117
139
  lines.push('| File | Error |');
118
140
  lines.push('| --- | --- |');
119
141
  for (const finding of errors) {
120
- lines.push(`| ${tableCode(`${finding.file}:${finding.line}:${finding.column}`)} | ${escapeMarkdown(finding.text)} |`);
142
+ lines.push(`| ${tableCode(`${finding.file}:${finding.line}:${finding.column}`)} | ${tableCode(finding.text || '')} |`);
121
143
  }
122
144
  lines.push('');
123
145
  }
@@ -221,7 +243,7 @@ function appendTokenContractMarkdown(lines, tokenContract) {
221
243
  lines.push('| Token | Files |');
222
244
  lines.push('| --- | --- |');
223
245
  for (const entry of missingTokens.slice(0, 10)) {
224
- lines.push(`| ${tableCode(entry.token)} | ${tableCode(entry.files.join(', '))} |`);
246
+ lines.push(`| ${tableCode(entry.token)} | ${tableCode(fileList(entry.files))} |`);
225
247
  }
226
248
  lines.push('');
227
249
  }
@@ -243,7 +265,7 @@ function appendTokenContractMarkdown(lines, tokenContract) {
243
265
  lines.push('| Value | Count | Files |');
244
266
  lines.push('| --- | ---: | --- |');
245
267
  for (const entry of rawValueCandidates.slice(0, 10)) {
246
- lines.push(`| ${tableCode(entry.value)} | ${entry.count} | ${tableCode(entry.files.join(', '))} |`);
268
+ lines.push(`| ${tableCode(entry.value)} | ${entry.count} | ${tableCode(fileList(entry.files))} |`);
247
269
  }
248
270
  lines.push('');
249
271
  }
@@ -271,6 +293,34 @@ function appendTokenContractMarkdown(lines, tokenContract) {
271
293
  }
272
294
  }
273
295
 
296
+ const NEW_FINDINGS_SHOWN = 25;
297
+ const FILES_SHOWN = 5;
298
+
299
+ /** Five names and a count: a value repeated in 300 files made one table row of 6,900 characters. */
300
+ function fileList(files) {
301
+ const shown = files.slice(0, FILES_SHOWN).join(', ');
302
+ return files.length > FILES_SHOWN ? `${shown}, +${files.length - FILES_SHOWN} more` : shown;
303
+ }
304
+
305
+ function appendNewFindingsMarkdown(lines, report) {
306
+ const fresh = (report.baseline && report.baseline.newFindings) || [];
307
+ if (fresh.length === 0) {
308
+ return;
309
+ }
310
+ lines.push('## New Since the Baseline');
311
+ lines.push('');
312
+ lines.push('| Location | Finding |');
313
+ lines.push('| --- | --- |');
314
+ for (const finding of fresh.slice(0, NEW_FINDINGS_SHOWN)) {
315
+ // A code span: finding text can carry values from the project's source, and this goes into a PR comment.
316
+ lines.push(`| ${tableCode(`${finding.file}:${finding.line}`)} | ${tableCode(finding.text || '')} |`);
317
+ }
318
+ if (fresh.length > NEW_FINDINGS_SHOWN) {
319
+ lines.push(`| ${fresh.length - NEW_FINDINGS_SHOWN} more | see \`--format json\` |`);
320
+ }
321
+ lines.push('');
322
+ }
323
+
274
324
  function appendBaselineMarkdown(lines, report) {
275
325
  if (!report.baseline && !report.baselineWritten) {
276
326
  return;
@@ -288,15 +338,6 @@ function appendBaselineMarkdown(lines, report) {
288
338
  lines.push('');
289
339
  }
290
340
 
291
- if (report.baseline && report.baseline.newFindings.length > 0) {
292
- lines.push('| New finding | Location |');
293
- lines.push('| --- | --- |');
294
- for (const finding of report.baseline.newFindings.slice(0, 10)) {
295
- lines.push(`| ${tableCode(finding.text)} | ${tableCode(`${finding.file}:${finding.line}`)} |`);
296
- }
297
- lines.push('');
298
- }
299
-
300
341
  if (report.baselineWritten) {
301
342
  lines.push(`Baseline written: ${markdownCode(report.baselineWritten.file)}`);
302
343
  lines.push('');