@blundergoat/gruff-ts 0.1.1 → 0.3.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 (52) hide show
  1. package/CHANGELOG.md +55 -19
  2. package/README.md +103 -35
  3. package/docs/README.md +2 -0
  4. package/docs/agent-hook.md +80 -0
  5. package/docs/ci-integration.md +16 -0
  6. package/docs/configuration.md +60 -3
  7. package/docs/dashboard.md +7 -0
  8. package/docs/output-formats.md +11 -1
  9. package/docs/philosophy.md +21 -0
  10. package/docs/releasing.md +12 -11
  11. package/docs/reports-and-ci.md +5 -2
  12. package/docs/rules.md +24 -15
  13. package/package.json +5 -5
  14. package/scripts/bump-version.sh +20 -4
  15. package/scripts/preflight-checks.sh +4 -41
  16. package/src/analyser.ts +47 -34
  17. package/src/blocks.ts +82 -75
  18. package/src/changed-regions.ts +390 -0
  19. package/src/check-ignore.ts +49 -0
  20. package/src/class-rules.ts +80 -33
  21. package/src/cli-program.ts +209 -51
  22. package/src/comment-rules.ts +4 -0
  23. package/src/config-load-error.ts +18 -0
  24. package/src/config-parse.ts +458 -0
  25. package/src/config-preservation.ts +64 -0
  26. package/src/config.ts +311 -428
  27. package/src/constants.ts +10 -2
  28. package/src/context-doc-rules.ts +2 -4
  29. package/src/dashboard.ts +8 -5
  30. package/src/dead-code-rules.ts +60 -14
  31. package/src/discovery.ts +88 -32
  32. package/src/doc-rules.ts +3 -3
  33. package/src/findings-helpers.ts +58 -5
  34. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  35. package/src/init-config.ts +94 -31
  36. package/src/line-rules.ts +58 -4
  37. package/src/naming-pushers.ts +42 -7
  38. package/src/pillar-summary.ts +129 -0
  39. package/src/profiles.ts +232 -0
  40. package/src/project-config-rules.ts +5 -5
  41. package/src/project-rules.ts +2 -1
  42. package/src/report-html.ts +404 -0
  43. package/src/report-renderers.ts +210 -397
  44. package/src/rule-list.ts +85 -1
  45. package/src/rules.ts +28 -27
  46. package/src/safety-rules.ts +22 -7
  47. package/src/scoring.ts +78 -8
  48. package/src/security-flow-rules.ts +533 -0
  49. package/src/sensitive-data-rules.ts +138 -2
  50. package/src/test-block-rules.ts +140 -7
  51. package/src/test-fixtures.ts +59 -13
  52. package/src/types.ts +108 -5
@@ -1,14 +1,14 @@
1
- // Text, HTML, SARIF, hotspot, and dashboard renderers for the stable analysis report.
1
+ // Text, SARIF, hotspot, markdown, GitHub, and summary renderers for the stable analysis report.
2
+ // HTML output and dashboard chrome live in `report-html.ts` so this module stays under the
3
+ // `size.file-length` threshold; both files source `buildPillarRows` + `grade` from
4
+ // `pillar-summary.ts` so the cross-format Pillars table stays byte-aligned.
2
5
  import type { AnalysisReport, Finding, OutputFormat, Severity } from "./types.ts";
6
+ import { OUTPUT_VOLUME_HINT_THRESHOLD } from "./constants.ts";
7
+ import { countRuleSeverities } from "./findings-helpers.ts";
8
+ import { buildPillarRows, type PillarRow } from "./pillar-summary.ts";
3
9
  import { ruleDescriptors } from "./rules.ts";
4
-
5
- const CYCLOMATIC_BUCKETS = [
6
- { label: "21+", minimum: 21 },
7
- { label: "16-20", minimum: 16 },
8
- { label: "11-15", minimum: 11 },
9
- { label: "6-10", minimum: 6 },
10
- { label: "1-5", minimum: 1 },
11
- ] as const;
10
+ import { renderHtml } from "./report-html.ts";
11
+ import { severityGradeBreakdown } from "./scoring.ts";
12
12
 
13
13
  /*
14
14
  * Format dispatcher. `hotspot` is emitted inline (smallest schema) while every other format has a
@@ -180,13 +180,18 @@ function sarifLevel(severity: Severity): "error" | "warning" | "note" {
180
180
  * durable machine output should use `analyse --format=json` instead.
181
181
  */
182
182
  function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: string, top = 10): string {
183
- const pillarCounts = countBy(report.findings, (finding) => finding.pillar);
184
183
  const ruleCounts = countBy(report.findings, (finding) => finding.ruleId);
184
+ const pillarRows = buildPillarRows(report);
185
+ const breakdown = severityGradeBreakdown(report.findings);
185
186
  const lines = [
186
187
  `gruff-ts ${report.tool.version} summary`,
187
188
  `Path: ${pathLabel ?? report.run.projectRoot}`,
188
189
  ...(typeof elapsedMs === "number" ? [`Duration: ${formatSummaryDuration(elapsedMs)}`] : []),
189
- `Score: ${report.score.composite.toFixed(1)} (${report.score.grade})`,
190
+ `Composite: ${report.score.grade} (${report.score.composite.toFixed(1)})`,
191
+ ` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
192
+ ` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
193
+ ` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
194
+ ...renderComplexityClusterLines(report.findings, top),
190
195
  `Findings: ${report.summary.total} total, ${report.summary.error} error, ${report.summary.warning} warning, ${report.summary.advisory} advisory`,
191
196
  `Analysed files: ${report.paths.analysedFiles}`,
192
197
  ...(report.baseline ? [summaryBaselineLine(report.baseline)] : []),
@@ -194,31 +199,33 @@ function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: s
194
199
  if (report.diagnostics.length > 0) {
195
200
  lines.push("", "Diagnostics:", ...report.diagnostics.map(summaryDiagnosticLine));
196
201
  }
197
- lines.push("", "Per-pillar counts:");
198
- lines.push(...renderRankedCounts(pillarCounts, "No findings by pillar."));
202
+ lines.push("", ...renderPillarsBlock(pillarRows));
199
203
  lines.push("", `Top ${top} rules:`);
200
- lines.push(...renderRankedCounts(ruleCounts, "No rule findings.", top));
204
+ lines.push(...renderRankedRuleRows(report.findings, top));
201
205
  lines.push("", `Top ${top} file offenders:`);
202
206
  lines.push(
203
207
  ...(
204
208
  report.score.topOffenders.length === 0
205
209
  ? ["- No file offenders."]
206
- : report.score.topOffenders.slice(0, top).map((offender) => `- ${offender.filePath}: ${offender.findings} findings, score ${offender.score.toFixed(1)}`)
210
+ : report.score.topOffenders.slice(0, top).map((offender) => `- ${offender.filePath}: ${offender.findings} findings, quality ${offender.score.toFixed(1)}/100`)
207
211
  ),
208
212
  );
209
213
  return `${lines.join("\n")}\n`;
210
214
  }
211
215
 
212
216
  /*
213
- * Renders the stable public `gruff.summary.v1` JSON contract for the `summary --format=json` flow.
214
- * The schema shape (scope/score/findings/topRules/topOffenders) is part of that contract - downstream
215
- * CI integrations parse it, so field renames or removals are breaking changes for users.
217
+ * Renders the stable public `gruff.summary.v2` JSON contract for the `summary --format=json` flow.
218
+ * Phase 2 of the cross-port harmonisation replaces the flat `{pillar, count}` shape with rich
219
+ * per-pillar objects carrying grade, score, applicability, and per-severity counts (findings,
220
+ * advisory, warning, error). The schema-version string is bumped because downstream CI consumers
221
+ * parse this payload and the field-set is no longer compatible with v1; scope/score/topRules/
222
+ * topOffenders remain unchanged.
216
223
  */
217
224
  function renderSummaryJson(report: AnalysisReport, elapsedMs?: number, pathLabel?: string, top = 10): string {
218
- const pillarCounts = countBy(report.findings, (finding) => finding.pillar);
219
225
  const ruleCounts = countBy(report.findings, (finding) => finding.ruleId);
226
+ const pillarRows = buildPillarRows(report);
220
227
  const payload = {
221
- schemaVersion: "gruff.summary.v1",
228
+ schemaVersion: "gruff.summary.v2",
222
229
  tool: report.tool,
223
230
  scope: {
224
231
  paths: pathLabel ?? report.run.projectRoot,
@@ -232,7 +239,17 @@ function renderSummaryJson(report: AnalysisReport, elapsedMs?: number, pathLabel
232
239
  score: report.score,
233
240
  findings: report.summary,
234
241
  baseline: report.baseline,
235
- pillars: renderRankedCountRows(pillarCounts),
242
+ pillars: pillarRows.map((row) => ({
243
+ pillar: row.pillar,
244
+ grade: row.grade,
245
+ score: row.score,
246
+ penalty: row.penalty,
247
+ applicable: row.isApplicable,
248
+ findings: row.findings,
249
+ advisory: row.advisory,
250
+ warning: row.warning,
251
+ error: row.error,
252
+ })),
236
253
  topRules: renderRankedCountRows(ruleCounts, top),
237
254
  topOffenders: report.score.topOffenders.slice(0, top),
238
255
  };
@@ -274,6 +291,73 @@ function countBy<T extends string>(findings: Finding[], keyFor: (finding: Findin
274
291
  return counts;
275
292
  }
276
293
 
294
+ /*
295
+ * Text renderer for the `Pillars` block in `gruff-ts summary`. Column widths are computed from the
296
+ * actual data (max pillar-name length, max digits per severity column) with a 3-char minimum value
297
+ * width so single-digit cells still leave visual breathing room before the next column. This
298
+ * matches the cross-port canonical byte-for-byte layout: leading "Pillars" header, 2-space row
299
+ * indent, pillar name padded to max-name-width + 1 space, single-letter grade, 1-space separator,
300
+ * score right-aligned in 6 chars with 2 decimals, then findings/advisory/warning/error cells
301
+ * separated by 3 spaces and trimmed of trailing whitespace on the final column.
302
+ */
303
+ function renderPillarsBlock(rows: PillarRow[]): string[] {
304
+ if (rows.length === 0) {
305
+ return ["Pillars", " (none)"];
306
+ }
307
+ const nameWidth = Math.max(...rows.map((row) => row.pillar.length));
308
+ const findingsWidth = Math.max(3, ...rows.map((row) => String(row.findings).length));
309
+ const advisoryWidth = Math.max(3, ...rows.map((row) => String(row.advisory).length));
310
+ const warningWidth = Math.max(3, ...rows.map((row) => String(row.warning).length));
311
+ const errorWidth = Math.max(3, ...rows.map((row) => String(row.error).length));
312
+ const lines = ["Pillars"];
313
+ for (const row of rows) {
314
+ const name = row.pillar.padEnd(nameWidth);
315
+ const score = row.score.toFixed(2).padStart(6);
316
+ const findingsCell = `findings=${String(row.findings).padEnd(findingsWidth)}`;
317
+ const advisoryCell = `advisory=${String(row.advisory).padEnd(advisoryWidth)}`;
318
+ const warningCell = `warning=${String(row.warning).padEnd(warningWidth)}`;
319
+ const errorCell = `error=${String(row.error).padEnd(errorWidth)}`;
320
+ const line = ` ${name} ${row.grade} ${score} ${findingsCell} ${advisoryCell} ${warningCell} ${errorCell}`.replace(/\s+$/, "");
321
+ lines.push(line);
322
+ }
323
+ return lines;
324
+ }
325
+
326
+ /*
327
+ * Enriched top-N rules renderer. Replaces the plain `- <ruleId>: <count>` form with a per-severity
328
+ * split plus the rule's one-line description, so an operator triaging 1000+ findings can see
329
+ * whether the top entry is one error or four hundred advisories at a glance. Description text is
330
+ * truncated to `DESCRIPTION_BODY_LIMIT` characters with an ellipsis so the row stays legible at 100
331
+ * columns. Sort order is preserved (count DESC, ruleId ASC) to keep the row-at-position-[0] stable.
332
+ */
333
+ function renderRankedRuleRows(findings: Finding[], limit?: number): string[] {
334
+ const severities = countRuleSeverities(findings);
335
+ if (severities.size === 0) {
336
+ return ["- No rule findings."];
337
+ }
338
+ const descriptions = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor.description]));
339
+ const limited = [...severities.entries()]
340
+ .sort(([leftKey, leftCounts], [rightKey, rightCounts]) => rightCounts.total - leftCounts.total || leftKey.localeCompare(rightKey))
341
+ .slice(0, limit ?? severities.size);
342
+ return limited.map(([ruleId, counts]) => {
343
+ const description = truncateDescription(descriptions.get(ruleId) ?? "");
344
+ return `- ${ruleId}: ${counts.total} (${counts.error} err / ${counts.warning} warn / ${counts.advisory} adv) - ${description}`;
345
+ });
346
+ }
347
+
348
+ /*
349
+ * 60-char description budget that keeps the rule-row line under ~100 columns even with the longest
350
+ * ruleId and severity-split. The trailing ellipsis is a single Unicode glyph so terminals that
351
+ * don't render `...` still see the truncation marker.
352
+ */
353
+ const DESCRIPTION_BODY_LIMIT = 60;
354
+
355
+ // Applies the description budget to a single rule's description so each rule row in the summary
356
+ // Top-N block fits on one terminal line. Returns the input unchanged when already short.
357
+ function truncateDescription(text: string): string {
358
+ return text.length <= DESCRIPTION_BODY_LIMIT ? text : `${text.slice(0, DESCRIPTION_BODY_LIMIT).trimEnd()}…`;
359
+ }
360
+
277
361
  function renderRankedCounts<T extends string>(counts: Map<T, number>, emptyText: string, limit?: number): string[] {
278
362
  if (counts.size === 0) {
279
363
  return [`- ${emptyText}`];
@@ -296,9 +380,14 @@ function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?:
296
380
  * sorted into the stable order, so piping into `grep` produces deterministic results.
297
381
  */
298
382
  function renderText(report: AnalysisReport): string {
383
+ const breakdown = severityGradeBreakdown(report.findings);
299
384
  const lines = [
300
385
  `gruff-ts ${report.tool.version}`,
301
- `Score: ${report.score.composite.toFixed(1)} (${report.score.grade}) | Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error`,
386
+ `Composite: ${report.score.grade} (${report.score.composite.toFixed(1)}) | Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error`,
387
+ ` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
388
+ ` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
389
+ ` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
390
+ ...renderComplexityClusterLines(report.findings),
302
391
  `Analysed files: ${report.paths.analysedFiles}`,
303
392
  ];
304
393
  if (report.diagnostics.length > 0) {
@@ -307,410 +396,140 @@ function renderText(report: AnalysisReport): string {
307
396
  if (report.findings.length > 0) {
308
397
  lines.push("", "Findings:", ...report.findings.map((finding) => `- [${finding.severity}] ${finding.filePath}:${finding.line ?? 1} ${finding.ruleId} - ${finding.message}`));
309
398
  }
399
+ if (report.findings.length >= OUTPUT_VOLUME_HINT_THRESHOLD) {
400
+ lines.push("", `Tip: ${report.findings.length} findings is more than a flat list usefully shows. Try \`gruff-ts summary --top=20\` for a per-rule digest.`);
401
+ }
310
402
  return `${lines.join("\n")}\n`;
311
403
  }
312
404
 
313
- // Truncates to 50 findings because Markdown previews (PR comments, READMEs) start mangling longer
314
- // tables. The stable JSON or HTML renderers stay the canonical full-fidelity output.
405
+ /*
406
+ * Markdown renderer for the `gruff.analysis.v2` report. Truncates to 50 findings because Markdown
407
+ * previews (PR comments, READMEs) start mangling longer tables; the JSON and HTML renderers stay
408
+ * the canonical full-fidelity output. Public contract / invariant: the Pillars table is inserted
409
+ * between the severity counts and the per-finding list so CI logs and PR comment previews see it
410
+ * first, and it shares its row data and sort order with the text/JSON/HTML pillar renderers via
411
+ * `buildPillarRows` so all four surfaces stay deterministic and byte-aligned across runs.
412
+ */
315
413
  function renderMarkdown(report: AnalysisReport): string {
414
+ const breakdown = severityGradeBreakdown(report.findings);
316
415
  return [
317
416
  "# gruff-ts report",
318
417
  "",
319
- `Score: **${report.score.composite.toFixed(1)} (${report.score.grade})**`,
418
+ `Composite: **${report.score.grade} (${report.score.composite.toFixed(1)})**`,
419
+ `- Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
420
+ `- Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
421
+ `- Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
422
+ ...renderMarkdownComplexityClusterLines(report.findings),
320
423
  "",
321
424
  `Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error.`,
425
+ "",
426
+ ...renderMarkdownPillarsTable(buildPillarRows(report)),
427
+ "",
322
428
  ...report.findings.slice(0, 50).map((finding) => `- \`${finding.ruleId}\` \`${finding.filePath}\`:${finding.line ?? 1} - ${finding.message}`),
323
429
  ].join("\n");
324
430
  }
325
431
 
326
- // GitHub Actions `::workflow command` syntax. Public contract invariant: file/title properties
327
- // must be normalized and command-escaped before interpolation because commas and colons delimit the property list.
328
- function renderGithub(report: AnalysisReport): string {
329
- return report.findings
330
- .map((finding) => `::${githubLevel(finding.severity)} file=${escapeCommandProperty(githubAnnotationPath(finding.filePath))},line=${finding.line ?? 1},title=${escapeCommandProperty(finding.ruleId)}::${escapeCommand(finding.message)}`)
331
- .join("\n");
332
- }
333
-
334
- // GitHub annotation paths are repository-relative POSIX paths. Leading `./` and Windows
335
- // separators produce duplicate annotations for the same file, so normalize them once here.
336
- function githubAnnotationPath(filePath: string): string {
337
- return filePath.replaceAll("\\", "/").replace(/^(?:\.\/)+/, "");
338
- }
339
-
340
- // Extra metadata appended to dashboard-served HTML. Static-file consumers never see it because the
341
- // CLI calls `renderHtml` without this argument; only the dashboard route passes it in.
342
- interface DashboardRenderContext {
343
- projectRoot: string;
344
- scanPath: string;
345
- }
346
-
347
432
  /*
348
- * Self-contained HTML output (CSS inlined, no external assets) so reports can be archived or
349
- * emailed. The schema invariant: every Finding listed in the report must be reachable through
350
- * deep links - the on-page JS in `dashboardJs` relies on stable `data-path` attributes.
433
+ * Canonical 7-column Pillars table shared by the cross-port markdown contract. The header,
434
+ * separator (right-aligned numeric columns), and row format match the gruff-go markdown reporter
435
+ * byte-for-byte so downstream tooling (PR comment scrapers, dashboards parsing the markdown body)
436
+ * keys off a single shape. Row order is sourced from `buildPillarRows` (findings DESC, then pillar
437
+ * ASC); scores render with two decimals; pipes in pillar/grade cells are escaped so a future
438
+ * pillar/grade name containing `|` cannot break the table.
351
439
  */
352
- function renderHtml(report: AnalysisReport, dashboardContext?: DashboardRenderContext): string {
353
- const bodySections = [
354
- htmlMasthead(report),
355
- htmlDiagnostics(report),
356
- dashboardContext ? htmlDashboardContext(dashboardContext) : "",
357
- htmlVerdict(report),
358
- htmlPillars(report),
359
- htmlOffenders(report),
360
- htmlDistribution(report),
361
- htmlFindings(report),
362
- htmlFooter(report),
363
- ].join("\n");
364
- return `<!doctype html>
365
- <html lang="en-NZ">
366
- <head>
367
- <meta charset="utf-8">
368
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
369
- <title>gruff-ts report - ${escapeHtml(report.score.grade)}</title>
370
- <style>${htmlReportCss(report.diagnostics.length > 0)}</style>
371
- </head>
372
- <body>
373
- <main class="paper"><span class="corner-tr"></span><span class="corner-bl"></span>
374
- ${bodySections}
375
- </main>
376
- </body>
377
- </html>`;
378
- }
379
-
380
- // Top banner: path count, format, fail-on, schema version. The schemaVersion text is the
381
- // contract surface - operators eyeball it to confirm the report shape they expect.
382
- function htmlMasthead(report: AnalysisReport): string {
383
- const paths = report.paths.analysedFiles === 0 ? "." : `${report.paths.analysedFiles} analysed ${report.paths.analysedFiles === 1 ? "file" : "files"}`;
384
- return `<header class="masthead"><div class="brand"><div class="wordmark">gruff</div><div class="tagline">ts/js code quality - inspection report</div></div><div class="meta">${htmlMetaRow("paths", paths)}${htmlMetaRow("format", report.run.format)}${htmlMetaRow("fail", report.run.failOn)}${htmlMetaRow("schema", report.schemaVersion)}<div class="inspection-id">gruff-ts ${escapeHtml(report.tool.version)}</div></div></header>`;
385
- }
386
-
387
- // Single key/value row. Both inputs are escaped - they reach this function as user-influenced
388
- // strings (paths, format names) and would otherwise enable injection in archived reports.
389
- function htmlMetaRow(label: string, metaValue: string): string {
390
- const escapedLabel = escapeHtml(label);
391
- const escapedValue = escapeHtml(metaValue);
392
- return `<div><span class="label">${escapedLabel}</span><span class="val">${escapedValue}</span></div>`;
393
- }
394
-
395
- // Diagnostics are parse/IO failures, not normal findings. HTML renders them before score sections
396
- // because partial scans must remain visibly incomplete; omitting empty diagnostics is the stable contract.
397
- function htmlDiagnostics(report: AnalysisReport): string {
398
- if (report.diagnostics.length === 0) {
399
- return "";
440
+ function renderMarkdownPillarsTable(rows: PillarRow[]): string[] {
441
+ const lines = [
442
+ "## Pillars",
443
+ "",
444
+ "| Pillar | Grade | Score | Findings | Advisory | Warning | Error |",
445
+ "| --- | --- | ---: | ---: | ---: | ---: | ---: |",
446
+ ];
447
+ if (rows.length === 0) {
448
+ lines.push("| _(none)_ | | | | | | |");
449
+ return lines;
400
450
  }
401
- const diagnostics = report.diagnostics.map(htmlDiagnosticEntry).join("");
402
- return `<section class="diagnostics"><h2 class="section-head">diagnostics <span class="aside">run messages</span></h2><div class="diagnostic-list">${diagnostics}</div></section>`;
403
- }
404
-
405
- // HTML markup for one diagnostic entry. The `diagnostic-type`/`diagnostic-message`/`diagnostic-location`
406
- // span classes are part of the stable HTML report contract - the dashboard CSS and any downstream
407
- // scraping keys off them, so the structure here must stay invariant across renderer changes.
408
- function htmlDiagnosticEntry(diagnostic: AnalysisReport["diagnostics"][number]): string {
409
- const lineSuffix = diagnostic.line ? `:${diagnostic.line}` : "";
410
- const location = diagnostic.filePath
411
- ? `<span class="diagnostic-location">${escapeHtml(diagnostic.filePath)}${lineSuffix}</span>`
412
- : "";
413
- return `<div class="diagnostic"><span class="diagnostic-type">${escapeHtml(diagnostic.diagnosticType)}</span><span class="diagnostic-message">${escapeHtml(diagnostic.message)}</span>${location}</div>`;
414
- }
415
-
416
- // Dashboard-only banner that names the project root and scan path. Static reports never include
417
- // this; both inputs are user-controlled query parameters and are escaped before reaching HTML.
418
- function htmlDashboardContext(context: DashboardRenderContext): string {
419
- const escapedProjectRoot = escapeHtml(context.projectRoot);
420
- const escapedScanPath = escapeHtml(context.scanPath);
421
- return `<section class="dashboard-context"><h2 class="section-head">dashboard scan <span class="aside">local run</span></h2><div class="dashboard-context-grid"><div><span class="label">Project root</span><span class="val">${escapedProjectRoot}</span></div><div><span class="label">Path</span><span class="val">${escapedScanPath}</span></div></div></section>`;
422
- }
423
-
424
- /*
425
- * The grade stamp + four stat cards. The verdict shape is part of the stable visual contract that
426
- * the dashboard relies on for parity with static reports.
427
- */
428
- function htmlVerdict(report: AnalysisReport): string {
429
- const gradeCssClass = gradeClass(report.score.grade);
430
- const escapedGrade = escapeHtml(report.score.grade);
431
- const scoreText = report.score.composite.toFixed(1);
432
- const escapedSummary = escapeHtml(verdictSummary(report));
433
- const stats = `${htmlStat(String(report.summary.total), "findings", "")}${htmlStat(String(report.summary.error), "errors", "fail")}${htmlStat(String(report.summary.warning), "warnings", "warn")}${htmlStat(String(report.summary.advisory), "advisories", "note")}`;
434
- return `<section class="verdict"><div class="grade-stamp ${gradeCssClass}"><div class="grade-letter">${escapedGrade}</div><div class="grade-score">${scoreText} / 100</div></div><div class="verdict-body"><div class="verdict-headline">Inspection complete.<br><em>${escapedSummary}</em></div><div class="verdict-stats">${stats}</div></div></section>`;
435
- }
436
-
437
- // Headline sentence. Counts only warning/error findings - advisories are intentionally excluded
438
- // from the verdict text because they are below the stable "needs attention" threshold.
439
- function verdictSummary(report: AnalysisReport): string {
440
- const thresholdFindings = report.summary.warning + report.summary.error;
441
- if (thresholdFindings === 0) {
442
- return "No warning or error findings flagged.";
451
+ for (const row of rows) {
452
+ lines.push(
453
+ `| ${escapeMarkdownCell(row.pillar)} | ${escapeMarkdownCell(row.grade)} | ${row.score.toFixed(2)} | ${row.findings} | ${row.advisory} | ${row.warning} | ${row.error} |`,
454
+ );
443
455
  }
444
- const pillars = new Set(report.findings.filter((finding) => finding.severity === "warning" || finding.severity === "error").map((finding) => finding.pillar));
445
- return `${thresholdFindings} ${thresholdFindings === 1 ? "finding" : "findings"} at warning or error severity across ${pillars.size} ${pillars.size === 1 ? "pillar" : "pillars"}.`;
456
+ return lines;
446
457
  }
447
458
 
448
- // One stat card (number + label). `className` is a curated, non-escaped CSS class - callers must
449
- // not pass user input here or it would break the layout in archived reports.
450
- function htmlStat(number: string, label: string, className: string): string {
451
- const escapedClassName = escapeHtml(className);
452
- const escapedNumber = escapeHtml(number);
453
- const escapedLabel = escapeHtml(label);
454
- return `<div class="stat"><div class="num ${escapedClassName}">${escapedNumber}</div><div class="lbl">${escapedLabel}</div></div>`;
459
+ // Escapes the pipe character so a pillar/grade name containing `|` cannot terminate the table row.
460
+ // Markdown's table syntax has no other reserved cell characters - newlines are already impossible
461
+ // inside a single-line `lines.push` interpolation - so this single replacement is sufficient.
462
+ function escapeMarkdownCell(cell: string): string {
463
+ return cell.replaceAll("|", "\\|");
455
464
  }
456
465
 
457
- /*
458
- * Pillar score grid in the same order the analyser produced - the stable composite score is the
459
- * mean of these pillars (see `scoreReport`), so visual order matches the headline-grade derivation.
460
- */
461
- function htmlPillars(report: AnalysisReport): string {
462
- const items =
463
- report.score.pillars.length === 0
464
- ? '<div class="empty">No pillar findings.</div>'
465
- : report.score.pillars
466
- .map((pillar) => {
467
- const letter = grade(pillar.score);
468
- return `<div class="pillar"><div class="name">${escapeHtml(pillar.pillar)}</div><div class="grade ${gradeClass(letter)}">${letter}</div><div class="breakdown"><div class="row"><span class="key">score</span><span class="val">${pillar.score.toFixed(1)}</span></div><div class="row"><span class="key">findings</span><span class="val">${pillar.findings}</span></div></div></div>`;
469
- })
470
- .join("");
471
- return `<section class="pillars"><h2 class="section-head">pillar grades <span class="aside">weighted composite</span></h2><div class="pillar-grid">${items}</div></section>`;
472
- }
473
-
474
- // Top-10 offender table, ordered by ascending score (worst first). `scoreReport` returns the full
475
- // sorted list; summary and hotspot apply their own caps from the same source. The HTML report caps
476
- // at 10 rows so the visual layout stays stable regardless of project size - that 10 is the contract.
477
- function htmlOffenders(report: AnalysisReport): string {
478
- const rows =
479
- report.score.topOffenders.length === 0
480
- ? '<tr><td colspan="4">No offenders found.</td></tr>'
481
- : report.score.topOffenders
482
- .slice(0, 10)
483
- .map((file) => {
484
- const letter = grade(file.score);
485
- return `<tr><td class="file-path">${htmlLocation(file.filePath)}</td><td class="num">${file.score.toFixed(1)}</td><td class="num">${file.findings}</td><td class="num"><span class="grade-pill ${gradeClass(letter)}">${letter}</span></td></tr>`;
486
- })
487
- .join("");
488
- return `<section class="offenders"><h2 class="section-head">top offenders <span class="aside">sorted by score</span></h2><table class="offender-list"><thead><tr><th scope="col">file</th><th scope="col" class="num">score</th><th scope="col" class="num">findings</th><th scope="col" class="num">grade</th></tr></thead><tbody>${rows}</tbody></table></section>`;
466
+ // Render-only summary of overlapping complexity findings for one function symbol.
467
+ interface ComplexityCluster {
468
+ filePath: string;
469
+ symbol: string;
470
+ ruleIds: string[];
489
471
  }
490
472
 
491
- /*
492
- * Histogram of cyclomatic-complexity buckets. The 5 fixed buckets are part of the stable visual
493
- * vocabulary maintainers learn over time - adding a new bucket would invalidate that mental model.
494
- */
495
- function htmlDistribution(report: AnalysisReport): string {
496
- const distribution = cyclomaticDistribution(report);
497
- const max = Math.max(1, ...Object.values(distribution));
498
- const bars = Object.entries(distribution)
499
- .map(([label, count]) => {
500
- const height = Math.max(4, Math.round((count / max) * 100));
501
- const className = label === "16-20" || label === "21+" ? " fail" : label === "11-15" ? " warn" : "";
502
- return `<div class="bar${className}" style="height:${height}%;"><span class="count">${count}</span></div>`;
503
- })
504
- .join("");
505
- const axis = Object.keys(distribution)
506
- .map((label) => `<span>${escapeHtml(label)}</span>`)
507
- .join("");
508
- return `<section class="chart-section"><h2 class="section-head">distribution <span class="aside">cyclomatic complexity</span></h2><p class="chart-summary">${escapeHtml(cyclomaticSummary(distribution))}</p><div class="chart-card"><div class="title">cyclomatic complexity - flagged functions</div><div class="histogram">${bars}</div><div class="histogram-axis">${axis}</div></div></section>`;
509
- }
473
+ const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cognitive", "complexity.cyclomatic", "size.function-length"]);
510
474
 
511
- /*
512
- * Pre-seeded with zero counts for every bucket so the resulting record has a stable key order
513
- * in JSON dumps. Findings outside `complexity.cyclomatic` are ignored - see `cyclomaticFindingBucket`.
514
- */
515
- function cyclomaticDistribution(report: AnalysisReport): Record<string, number> {
516
- const distribution: Record<string, number> = { "1-5": 0, "6-10": 0, "11-15": 0, "16-20": 0, "21+": 0 };
517
- for (const finding of report.findings) {
518
- const bucket = cyclomaticFindingBucket(finding);
519
- if (bucket) {
520
- distribution[bucket] = (distribution[bucket] ?? 0) + 1;
521
- }
475
+ // Invariant: text output surfaces linked complexity clusters without changing JSON report shape.
476
+ function renderComplexityClusterLines(findings: Finding[], limit = 10): string[] {
477
+ const clusters = complexityClusters(findings).slice(0, limit);
478
+ if (clusters.length === 0) {
479
+ return [];
522
480
  }
523
- return distribution;
481
+ return [
482
+ "Correlated complexity clusters:",
483
+ ...clusters.map((cluster) => `- ${cluster.filePath}#${cluster.symbol}: ${cluster.ruleIds.length} linked findings (${cluster.ruleIds.join(", ")})`),
484
+ ];
524
485
  }
525
486
 
526
- // Extracts the cyclomatic number from the finding message because the metadata schema doesn't
527
- // expose it as a top-level field - coupling the renderer to the message text is acceptable here
528
- // because the message format is itself part of the stable rule contract.
529
- function cyclomaticFindingBucket(finding: Finding): string | undefined {
530
- if (finding.ruleId !== "complexity.cyclomatic") {
531
- return undefined;
487
+ // Invariant: markdown mirrors text complexity clusters without adding JSON fields.
488
+ function renderMarkdownComplexityClusterLines(findings: Finding[]): string[] {
489
+ const clusters = complexityClusters(findings);
490
+ if (clusters.length === 0) {
491
+ return [];
532
492
  }
533
- const match = finding.message.match(/cyclomatic complexity (\d+)/);
534
- const complexityValue = match?.[1] ? Number(match[1]) : undefined;
535
- return complexityValue === undefined ? undefined : cyclomaticBucket(complexityValue);
493
+ return [
494
+ "",
495
+ "## Correlated Complexity Clusters",
496
+ "",
497
+ ...clusters.map((cluster) => `- \`${cluster.filePath}#${cluster.symbol}\`: ${cluster.ruleIds.length} linked findings (${cluster.ruleIds.map((ruleId) => `\`${ruleId}\``).join(", ")})`),
498
+ ];
536
499
  }
537
500
 
538
- // Linear walk in descending-minimum order so the first match wins - required because `21+` and
539
- // `16-20` would otherwise both apply to a value of 25.
540
- function cyclomaticBucket(complexityValue: number): string | undefined {
541
- for (const bucket of CYCLOMATIC_BUCKETS) {
542
- if (complexityValue >= bucket.minimum) {
543
- return bucket.label;
501
+ // Groups correlated complexity findings by file and symbol so renderers can explain score overlap.
502
+ function complexityClusters(findings: Finding[]): ComplexityCluster[] {
503
+ const bySymbol = new Map<string, ComplexityCluster>();
504
+ for (const finding of findings) {
505
+ if (!finding.symbol || !CORRELATED_COMPLEXITY_RULE_IDS.has(finding.ruleId)) {
506
+ continue;
544
507
  }
508
+ const key = `${finding.filePath}\0${finding.symbol}`;
509
+ const cluster = bySymbol.get(key) ?? { filePath: finding.filePath, symbol: finding.symbol, ruleIds: [] };
510
+ if (!cluster.ruleIds.includes(finding.ruleId)) {
511
+ cluster.ruleIds.push(finding.ruleId);
512
+ }
513
+ bySymbol.set(key, cluster);
545
514
  }
546
- return undefined;
547
- }
548
-
549
- // One-line caption that quantifies how many functions exceed CC=10. The pluralisation handling
550
- // matters - "1 functions exceed" reads poorly enough that a reviewer would file it as a regression.
551
- function cyclomaticSummary(distribution: Record<string, number>): string {
552
- const moderate = distribution["11-15"] ?? 0;
553
- const high = distribution["16-20"] ?? 0;
554
- const severe = distribution["21+"] ?? 0;
555
- const exceeds = moderate + high + severe;
556
- return `${exceeds} ${exceeds === 1 ? "function" : "functions"} ${exceeds === 1 ? "exceeds" : "exceed"} CC 10 (${moderate} in 11-15, ${high} in 16-20, ${severe} at 21+).`;
557
- }
558
-
559
- // Caps the list at 250 entries because the inline-CSS report becomes painful to scroll past that.
560
- // The footer caveat shows "first 250 of N" so the truncation stable and visible.
561
- function htmlFindings(report: AnalysisReport): string {
562
- const findings =
563
- report.findings.length === 0
564
- ? '<div class="empty">No findings.</div>'
565
- : report.findings
566
- .slice(0, 250)
567
- .map(
568
- (finding) =>
569
- `<div class="finding"><div class="severity ${severityClass(finding.severity)}">${escapeHtml(finding.severity)}</div><div class="finding-body"><h3 class="rule">${escapeHtml(finding.ruleId)}</h3><div class="msg">${escapeHtml(finding.message)}</div><div class="loc"><code>${htmlLocation(finding.filePath, finding.line)}</code></div></div><div class="points"><b>${escapeHtml(finding.pillar)}</b></div></div>`,
570
- )
571
- .join("");
572
- const capped = report.findings.length > 250 ? ` <span class="aside">first 250 of ${report.findings.length}</span>` : ` <span class="aside">${report.findings.length} shown</span>`;
573
- return `<section class="findings"><h2 class="section-head">flagged findings${capped}</h2><div class="findings-list">${findings}</div></section>`;
574
- }
575
-
576
- /*
577
- * Page-bottom strip with tool version and schema string - those are the two stable identifiers a
578
- * reviewer can use to reproduce a historical report.
579
- */
580
- function htmlFooter(report: AnalysisReport): string {
581
- const escapedVersion = escapeHtml(report.tool.version);
582
- const escapedSchemaVersion = escapeHtml(report.schemaVersion);
583
- return `<footer class="footer"><div class="left">gruff-ts - v${escapedVersion}</div><div class="center">strong opinions, opinionated defaults</div><div class="right">schema - ${escapedSchemaVersion}</div></footer>`;
584
- }
585
-
586
- // Renders a keyboard-focusable location pill. `data-path` is what the dashboard JS keys off when
587
- // the user clicks to deep-link; both attributes go through `escapeHtml` because filePath is user-influenced.
588
- function htmlLocation(filePath: string, line?: number): string {
589
- const text = line === undefined ? filePath : `${filePath}:${line}`;
590
- return `<span class="loc-link" tabindex="0" data-path="${escapeHtml(text)}">${escapeHtml(text)}</span>`;
591
- }
592
-
593
- // CSS class suffix used by severity badges and grade letters. Returning a curated literal (never
594
- // arbitrary user text) is what keeps `htmlStat`/`htmlFinding` safe to interpolate without escaping.
595
- function severityClass(severity: Severity): string {
596
- return severity === "error" ? "fail" : severity === "warning" ? "warn" : "note";
597
- }
598
-
599
- // Constrains grade text to known CSS suffixes before interpolation. Unknown future grades degrade
600
- // to neutral styling instead of creating user-influenced class names.
601
- function gradeClass(gradeValue: string): string {
602
- const letter = gradeValue[0]?.toLowerCase() ?? "n";
603
- return ["a", "b", "c", "d", "f"].includes(letter) ? letter : "n";
604
- }
605
-
606
- // Single inline stylesheet for both static reports and dashboard-served pages. `shouldIncludeDiagnostics`
607
- // appends the diagnostic-section rules only when the report actually has them, keeping clean
608
- // reports leaner. Hand-maintained CSS - no preprocessor.
609
- function htmlReportCss(shouldIncludeDiagnostics: boolean): string {
610
- const baseCss = `:root{--ink:#0d0c0a;--ink-2:#161412;--ink-3:#1f1c19;--paper:#f3e9d2;--paper-dim:#b5ab94;--paper-mute:#7d735f;--rule:#2a2622;--forge:#e85d04;--grade-a:#7fa15a;--grade-b:#b8b450;--grade-c:#d08c36;--grade-d:#c2552b;--grade-f:#8b2828;--advisory:#b5ab94;--serif:Georgia,'Iowan Old Style',serif;--mono:'JetBrains Mono','IBM Plex Mono',ui-monospace,monospace}*{box-sizing:border-box;margin:0;padding:0}html{background:var(--ink);scrollbar-gutter:stable}body{font-family:var(--mono);color:var(--paper);background:var(--ink);min-height:100vh;line-height:1.5;font-size:14px;padding:48px 32px}.paper{max-width:1180px;margin:0 auto 24px;background:var(--ink-2);border:1px solid var(--rule);position:relative;padding:56px 64px 48px;scrollbar-gutter:stable}.corner-tr,.corner-bl,.paper:before,.paper:after{content:'';position:absolute;width:22px;height:22px;border:1px solid var(--forge)}.paper:before{top:12px;left:12px;border-right:0;border-bottom:0}.paper:after{bottom:12px;right:12px;border-left:0;border-top:0}.corner-tr{top:12px;right:12px;border-left:0;border-bottom:0}.corner-bl{bottom:12px;left:12px;border-right:0;border-top:0}.masthead{display:grid;grid-template-columns:1fr auto;gap:32px;padding-bottom:28px;border-bottom:1px solid var(--rule);align-items:end}.wordmark{font-family:var(--serif);font-weight:900;font-size:96px;line-height:.85;color:var(--paper);font-style:italic}.wordmark:after{content:'-ts';color:var(--forge);font-style:normal;font-size:.45em;margin-left:.15em;vertical-align:super}.tagline{margin-top:12px;font-size:11px;letter-spacing:0;color:var(--paper-mute);text-transform:uppercase}.meta{text-align:right;font-size:11px;color:var(--paper-dim);line-height:1.9}.label{color:var(--paper-mute);text-transform:uppercase;letter-spacing:0;margin-right:8px}.val{color:var(--paper)}.inspection-id{margin-top:10px;color:var(--forge);font-weight:700;font-size:12px;letter-spacing:0}.section-head{font-size:11px;letter-spacing:0;color:var(--paper-mute);text-transform:uppercase;padding-bottom:16px;margin-bottom:20px;border-bottom:1px solid var(--rule);display:flex;justify-content:space-between;align-items:baseline;font-family:var(--mono);font-weight:500;line-height:1.5}.section-head:before{content:'>';margin-right:10px;color:var(--forge);font-family:var(--serif);font-size:14px;font-style:italic}.aside{color:var(--paper-mute);font-size:10px;letter-spacing:0}.verdict{display:grid;grid-template-columns:auto 1fr;gap:56px;padding:48px 0;border-bottom:1px solid var(--rule);align-items:center}.grade-stamp{width:220px;height:220px;border:3px solid currentColor;color:var(--grade-b);display:flex;flex-direction:column;align-items:center;justify-content:center;transform:rotate(-4deg)}.grade-stamp.a,.grade.a,.grade-pill.a{color:var(--grade-a)}.grade-stamp.b,.grade.b,.grade-pill.b{color:var(--grade-b)}.grade-stamp.c,.grade.c,.grade-pill.c{color:var(--grade-c)}.grade-stamp.d,.grade.d,.grade-pill.d{color:var(--grade-d)}.grade-stamp.f,.grade.f,.grade-pill.f{color:var(--grade-f)}.grade-letter{font-family:var(--serif);font-style:italic;font-weight:900;font-size:112px;line-height:1}.grade-score{font-size:13px;letter-spacing:0}.verdict-body{display:flex;flex-direction:column;gap:18px}.verdict-headline{font-family:var(--serif);font-style:italic;font-weight:600;font-size:38px;line-height:1.15}.verdict-headline em{color:var(--forge)}.verdict-stats{display:grid;grid-template-columns:repeat(4,1fr);border-top:1px solid var(--rule);padding-top:20px}.stat{border-right:1px solid var(--rule);padding:0 18px}.stat:first-child{padding-left:0}.stat:last-child{border-right:0}.verdict-stats .num{font-family:var(--serif);font-weight:800;font-size:32px;line-height:1}.verdict-stats .num.warn{color:var(--grade-c)}.verdict-stats .num.fail{color:var(--grade-f)}.verdict-stats .num.note{color:var(--advisory)}.lbl{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);margin-top:8px}.pillars,.offenders,.chart-section{padding:48px 0;border-bottom:1px solid var(--rule)}.pillar-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:1px;background:var(--rule);border:1px solid var(--rule)}.pillar{background:var(--ink-2);padding:24px 20px;display:flex;flex-direction:column;gap:14px}.pillar .name{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute)}.pillar .grade{font-family:var(--serif);font-weight:800;font-style:italic;font-size:52px;line-height:.9}.breakdown{font-size:11px;color:var(--paper-dim);line-height:1.7}.row{display:flex;justify-content:space-between;gap:8px}.key{color:var(--paper-mute)}table{width:100%;border-collapse:collapse;font-size:13px;table-layout:auto;font-family:var(--mono)}th{text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);font-weight:500;padding:12px 14px 12px 0;border-bottom:1px solid var(--rule)}th:last-child,td:last-child{padding-right:0}th.num,td.num{text-align:right;padding-left:18px}td{padding:14px 14px 14px 0;border-bottom:1px solid var(--ink-3);color:var(--paper-dim);font-size:13px;font-family:var(--mono);font-weight:500;line-height:1.4}td.num{color:var(--paper);font-variant-numeric:tabular-nums}.file-path{color:var(--paper);font-weight:500}.grade-pill{display:inline-block;font-family:var(--serif);font-style:italic;font-weight:800;font-size:18px;line-height:1;padding:4px 10px;border:1.5px solid currentColor;min-width:36px;text-align:center}.chart-summary{color:var(--paper-dim);font-size:12px;margin:-6px 0 18px}.chart-card{border:1px solid var(--rule);padding:24px;background:var(--ink-3)}.title{font-size:10px;text-transform:uppercase;letter-spacing:0;color:var(--paper-mute);margin-bottom:24px}.histogram{display:flex;align-items:flex-end;gap:6px;height:180px;padding-bottom:20px;border-bottom:1px solid var(--rule)}.bar{flex:1;background:var(--forge);position:relative;min-height:4px}.bar.warn{background:var(--grade-c)}.bar.fail{background:var(--grade-f)}.bar .count{position:absolute;top:-22px;left:50%;transform:translateX(-50%);font-size:11px}.histogram-axis{display:flex;gap:6px;margin-top:8px;font-size:10px;color:var(--paper-mute)}.histogram-axis span{flex:1;text-align:center}.findings{padding:48px 0}.finding{display:grid;grid-template-columns:auto 1fr auto;gap:24px;padding:18px 0;border-bottom:1px solid var(--ink-3);align-items:start}.severity{font-size:9px;text-transform:uppercase;letter-spacing:0;padding:4px 10px;border:1px solid currentColor;margin-top:2px;min-width:76px;text-align:center}.severity.fail{color:var(--grade-f)}.severity.warn{color:var(--grade-c)}.severity.note{color:var(--paper-mute)}.rule{font-size:10px;color:var(--forge);text-transform:uppercase;letter-spacing:0;margin-bottom:6px;font-family:var(--mono);font-weight:700;line-height:1.5}.msg{font-family:var(--serif);font-weight:500;font-size:17px;color:var(--paper);line-height:1.4}.loc{font-size:11px;color:var(--paper-mute);margin-top:8px}.loc code{color:var(--paper-dim);background:var(--ink-3);padding:1px 6px;border:1px solid var(--rule)}.loc-link{color:inherit;text-decoration:none}.loc-link:focus-visible{outline:2px solid var(--forge);outline-offset:3px}.points{font-size:10px;color:var(--paper-mute);text-align:right;letter-spacing:0;min-width:96px;padding-left:12px}.empty{color:var(--paper-dim);font-size:12px}.footer{margin-top:48px;padding-top:24px;border-top:1px solid var(--rule);display:grid;grid-template-columns:1fr auto 1fr;gap:24px;align-items:center;font-size:10px;color:var(--paper-mute);letter-spacing:0;text-transform:uppercase}.center{font-family:var(--serif);font-style:italic;font-size:13px;color:var(--paper-dim);text-transform:none;letter-spacing:0}.right{text-align:right}@media(max-width:900px){body{padding:16px}.paper{padding:28px 20px}.wordmark{font-size:64px}.masthead,.verdict{grid-template-columns:1fr}.meta{text-align:left}.grade-stamp{margin:0 auto}.pillar-grid{grid-template-columns:repeat(2,1fr)}.verdict-stats{grid-template-columns:repeat(2,1fr);gap:16px}.stat{border-right:0;padding:0}.verdict-headline{font-size:28px}.footer{grid-template-columns:1fr}.center,.right{text-align:left}}@media(max-width:560px){.pillar-grid{grid-template-columns:1fr}.finding{grid-template-columns:1fr}.points{text-align:left;padding-left:0}.verdict-stats{grid-template-columns:1fr}.histogram{height:140px}}`;
611
- const reportCss = `${baseCss}.dashboard-context{padding:28px 0;border-bottom:1px solid var(--rule)}.dashboard-context-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}.dashboard-context-grid>div{border:1px solid var(--rule);background:var(--ink-3);padding:12px 14px}.dashboard-context .label{display:block;margin:0 0 6px}.dashboard-context .val{overflow-wrap:anywhere}@media(max-width:700px){.dashboard-context-grid{grid-template-columns:1fr}}@media(max-width:560px){.offender-list thead{display:none}.offender-list,.offender-list tbody,.offender-list tr,.offender-list td{display:block;width:100%}.offender-list tr{border-bottom:1px solid var(--ink-3);padding:10px 0}.offender-list td{border-bottom:0;padding:6px 0}.offender-list td.num{text-align:left;padding-left:0}}`;
612
- if (!shouldIncludeDiagnostics) {
613
- return reportCss;
614
- }
615
- return `${reportCss}.diagnostics{padding:28px 0 0}.diagnostic-list{display:grid;gap:10px}.diagnostic{display:grid;grid-template-columns:auto 1fr;gap:10px 14px;border:1px solid var(--rule);background:var(--ink-3);padding:12px 14px;color:var(--paper-dim);font-size:12px}.diagnostic-type{text-transform:uppercase;letter-spacing:0;color:var(--forge);font-size:10px}.diagnostic-location{grid-column:2;color:var(--paper-mute);font-size:11px}`;
616
- }
617
-
618
- // Top-level dashboard chrome: iframe that loads the scan + a slide-out controls panel. The iframe
619
- // arrangement is what lets the dashboard reload scans without losing the control form state.
620
- function dashboardHomeHtml(projectRoot: string, scanPath: string): string {
621
- const initialScan = dashboardScanUrl(projectRoot, scanPath);
622
- return `<!doctype html>
623
- <html lang="en">
624
- <head>
625
- <meta charset="utf-8">
626
- <meta name="viewport" content="width=device-width, initial-scale=1">
627
- <title>gruff-ts dashboard</title>
628
- <style>${dashboardCss()}</style>
629
- </head>
630
- <body>
631
- <iframe class="report-frame" name="report-frame" title="gruff-ts report" src="${escapeHtml(initialScan)}"></iframe>
632
- <button class="controls-toggle" type="button" aria-expanded="false" aria-controls="controls-panel" title="Dashboard controls">&#9881;</button>
633
- <aside class="controls-panel" id="controls-panel" hidden>
634
- <header class="controls-head">
635
- <h1>Dashboard controls</h1>
636
- <p>local scan settings</p>
637
- </header>
638
- <form class="scan-form" data-scan-form action="/scan" method="get" target="report-frame">
639
- <label>Project root <input name="projectRoot" value="${escapeHtml(projectRoot)}" autocomplete="off"></label>
640
- <label>Paths <input name="path" value="${escapeHtml(scanPath)}" autocomplete="off"></label>
641
- <div class="scan-state"><span>Status</span><strong data-scan-status>Loading report</strong></div>
642
- <div class="actions">
643
- <button class="secondary" type="button" data-refresh>Refresh</button>
644
- <button type="submit">Run scan</button>
645
- </div>
646
- </form>
647
- </aside>
648
- <script>${dashboardJs()}</script>
649
- </body>
650
- </html>`;
515
+ return [...bySymbol.values()]
516
+ .filter((cluster) => cluster.ruleIds.length >= 2)
517
+ .map((cluster) => ({ ...cluster, ruleIds: cluster.ruleIds.sort() }))
518
+ .sort((left, right) => right.ruleIds.length - left.ruleIds.length || left.filePath.localeCompare(right.filePath) || left.symbol.localeCompare(right.symbol));
651
519
  }
652
520
 
653
- // URLSearchParams handles encoding so the projectRoot/scanPath values are safe to embed in `src`.
654
- function dashboardScanUrl(projectRoot: string, scanPath: string): string {
655
- const params = new URLSearchParams({ projectRoot, path: scanPath });
656
- return `/scan?${params.toString()}`;
657
- }
658
-
659
- // Friendly failure page served when `renderDashboardScan` catches an analyser throw. All inputs
660
- // are escaped - `message` is the error text and could contain attacker-controlled file path fragments.
661
- function dashboardErrorHtml(message: string, projectRoot: string, scanPath: string): string {
662
- const escapedMessage = escapeHtml(message);
663
- const escapedProjectRoot = escapeHtml(projectRoot);
664
- const escapedScanPath = escapeHtml(scanPath);
665
- return `<!doctype html>
666
- <html lang="en-NZ">
667
- <head>
668
- <meta charset="utf-8">
669
- <meta name="viewport" content="width=device-width, initial-scale=1">
670
- <title>gruff-ts dashboard scan failed</title>
671
- <style>${dashboardCss()}</style>
672
- </head>
673
- <body class="error-page">
674
- <main class="scan-error">
675
- <h1>Scan failed</h1>
676
- <p>${escapedMessage}</p>
677
- <dl>
678
- <dt>Project root</dt><dd>${escapedProjectRoot}</dd>
679
- <dt>Paths</dt><dd>${escapedScanPath}</dd>
680
- </dl>
681
- </main>
682
- </body>
683
- </html>`;
684
- }
685
-
686
- // Inline stylesheet shared by the dashboard shell and its error page. Inlined (not linked) so the
687
- // dashboard works without separate asset routes - keeping it self-contained matters for offline use.
688
- function dashboardCss(): string {
689
- return `:root{color-scheme:dark;--ink:#0d0c0a;--ink-2:#161412;--panel:#1f1c19;--paper:#f3e9d2;--paper-dim:#b5ab94;--paper-mute:#7d735f;--rule:#2a2622;--forge:#e85d04;--forge-dark:#b94402;--mono:'JetBrains Mono','IBM Plex Mono',ui-monospace,monospace}*{box-sizing:border-box}html,body{height:100%;margin:0;background:var(--ink);color:var(--paper);font-family:var(--mono);font-size:14px;line-height:1.5}.report-frame{position:fixed;inset:0;width:100%;height:100%;border:0;background:var(--ink)}.controls-toggle{position:fixed;top:18px;right:18px;z-index:3;width:44px;height:44px;border:1px solid rgba(232,93,4,.75);border-radius:8px;background:var(--forge);color:#170b05;font:700 22px/1 var(--mono);display:grid;place-items:center;cursor:pointer;box-shadow:0 16px 36px rgba(0,0,0,.38)}.controls-toggle:hover,.controls-toggle:focus-visible{background:#ff7a1a;outline:2px solid rgba(243,233,210,.75);outline-offset:3px}.controls-panel{position:fixed;z-index:2;top:74px;right:18px;width:min(420px,calc(100vw - 36px));max-height:calc(100vh - 92px);overflow:auto;background:rgba(31,28,25,.98);border:1px solid var(--rule);border-radius:8px;padding:20px;box-shadow:0 24px 70px rgba(0,0,0,.5)}[hidden]{display:none!important}.controls-head{border-bottom:1px solid var(--rule);padding-bottom:14px;margin-bottom:16px}.controls-head h1{margin:0;font-size:18px;font-weight:800}.controls-head p{margin:4px 0 0;color:var(--paper-mute);font-size:12px;text-transform:uppercase}.scan-form{display:grid;gap:14px}.scan-form label{display:grid;gap:6px;color:var(--paper-dim);font-size:12px;text-transform:uppercase}.scan-form input{width:100%;font:inherit;color:var(--paper);background:var(--ink-2);border:1px solid var(--rule);border-radius:6px;padding:10px 11px;min-width:0}.scan-form input:focus{outline:2px solid var(--forge);outline-offset:2px}.scan-state{display:flex;justify-content:space-between;gap:12px;border:1px solid var(--rule);background:var(--ink-2);border-radius:6px;padding:10px 11px;color:var(--paper-mute)}.scan-state strong{color:var(--paper);font-weight:700;text-align:right}.actions{display:grid;grid-template-columns:1fr 1fr;gap:10px}.actions button{font:inherit;border:1px solid var(--forge);border-radius:6px;padding:10px 12px;background:var(--forge);color:#170b05;font-weight:800;cursor:pointer}.actions button.secondary{background:transparent;color:var(--paper);border-color:var(--rule)}.actions button:disabled{opacity:.6;cursor:wait}.scan-error{max-width:720px;margin:8vh auto;padding:48px;background:var(--panel);border:1px solid var(--rule);color:var(--paper)}.scan-error h1{margin:0 0 16px;font-size:28px}.scan-error p{color:var(--paper-dim);overflow-wrap:anywhere}.scan-error dl{display:grid;grid-template-columns:auto 1fr;gap:8px 16px;margin:24px 0 0}.scan-error dt{color:var(--paper-mute);text-transform:uppercase}.scan-error dd{margin:0;overflow-wrap:anywhere}@media(max-width:560px){.controls-toggle{top:12px;right:12px}.controls-panel{top:64px;right:12px;width:calc(100vw - 24px);max-height:calc(100vh - 76px);padding:16px}.actions{grid-template-columns:1fr}.scan-error{margin:0;min-height:100vh;padding:28px 20px}.scan-error dl{grid-template-columns:1fr}}`;
690
- }
691
-
692
- // Inline `<script>` body served with the dashboard shell. Updates the URL via history.replaceState
693
- // so a maintainer can copy the current scan's URL and reproduce it later without re-typing controls.
694
- function dashboardJs(): string {
695
- return `const form=document.querySelector("[data-scan-form]");const frame=document.querySelector(".report-frame");const toggle=document.querySelector(".controls-toggle");const panel=document.querySelector(".controls-panel");const refresh=document.querySelector("[data-refresh]");const status=document.querySelector("[data-scan-status]");function setOpen(open){panel.hidden=!open;toggle.setAttribute("aria-expanded",String(open));if(open){const input=form.querySelector("input");if(input){input.focus();}}}function params(){return new URLSearchParams(new FormData(form));}function runScan(){const query=params();status.textContent="Scanning";refresh.disabled=true;form.querySelector("button[type=submit]").disabled=true;frame.src="/scan?"+query.toString();history.replaceState(null,"","/?"+query.toString());}toggle.addEventListener("click",()=>setOpen(panel.hidden));document.addEventListener("keydown",(event)=>{if(event.key==="Escape"){setOpen(false);}});form.addEventListener("submit",(event)=>{event.preventDefault();runScan();});refresh.addEventListener("click",runScan);frame.addEventListener("load",()=>{status.textContent="Ready";refresh.disabled=false;form.querySelector("button[type=submit]").disabled=false;});`;
521
+ // GitHub Actions `::workflow command` syntax. Public contract invariant: file/title properties
522
+ // must be normalized and command-escaped before interpolation because commas and colons delimit the property list.
523
+ function renderGithub(report: AnalysisReport): string {
524
+ return report.findings
525
+ .map((finding) => `::${githubLevel(finding.severity)} file=${escapeCommandProperty(githubAnnotationPath(finding.filePath))},line=${finding.line ?? 1},title=${escapeCommandProperty(finding.ruleId)}::${escapeCommand(finding.message)}`)
526
+ .join("\n");
696
527
  }
697
528
 
698
- // Composite-score → letter grade conversion. 90/80/70/60 boundaries are part of the stable rule
699
- // surface; changing them would shift every historical report grade and the headline on the dashboard.
700
- function grade(score: number): string {
701
- if (score >= 90) {
702
- return "A";
703
- }
704
- if (score >= 80) {
705
- return "B";
706
- }
707
- if (score >= 70) {
708
- return "C";
709
- }
710
- if (score >= 60) {
711
- return "D";
712
- }
713
- return "F";
529
+ // GitHub annotation paths are repository-relative POSIX paths. Leading `./` and Windows
530
+ // separators produce duplicate annotations for the same file, so normalize them once here.
531
+ function githubAnnotationPath(filePath: string): string {
532
+ return filePath.replaceAll("\\", "/").replace(/^(?:\.\/)+/, "");
714
533
  }
715
534
 
716
535
  // Three GitHub annotation levels - gruff's "advisory" collapses to "notice" because Actions has
@@ -731,10 +550,4 @@ function escapeCommandProperty(propertyText: string): string {
731
550
  return escapeCommand(propertyText).replaceAll(":", "%3A").replaceAll(",", "%2C");
732
551
  }
733
552
 
734
- // Four-character HTML entity escape (`&`, `<`, `>`, `"`). `&` must be first so the other entities
735
- // don't get double-encoded; missing escapes here would enable script injection in archived reports.
736
- function escapeHtml(htmlText: string): string {
737
- return htmlText.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
738
- }
739
-
740
- export { dashboardErrorHtml, dashboardHomeHtml, grade, renderHtml, renderReport, renderSummary, renderSummaryJson };
553
+ export { renderReport, renderSummary, renderSummaryJson };