@blundergoat/gruff-ts 0.3.2 → 0.5.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.
- package/CHANGELOG.md +54 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +15 -3
- package/docs/configuration.md +47 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +36 -0
- package/docs/rules.md +52 -37
- package/package.json +1 -1
- package/src/analyser.ts +540 -154
- package/src/baseline-options.ts +90 -0
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +80 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +65 -15
- package/src/cli.ts +4 -2
- package/src/comment-rules.ts +58 -13
- package/src/comment-scanner.ts +27 -0
- package/src/complexity-metrics.ts +244 -0
- package/src/config.ts +56 -16
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +9 -10
- package/src/dead-code-rules.ts +10 -3
- package/src/discovery.ts +66 -22
- package/src/doc-rules.ts +22 -53
- package/src/findings-helpers.ts +127 -1
- package/src/findings.ts +4 -0
- package/src/fixture-purpose-rules.ts +39 -5
- package/src/github-actions-rules.ts +24 -1
- package/src/hook-contract.ts +120 -27
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +175 -19
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +163 -0
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +36 -18
- package/src/project-rules.ts +159 -42
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +58 -4
- package/src/rules.ts +15 -15
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +256 -80
- package/src/source-text.ts +9 -26
- package/src/static-analysis-redundant-rules.ts +46 -2
- package/src/test-block-rules.ts +118 -14
- package/src/test-fixtures.ts +4 -1
- package/src/text-scans.ts +8 -1
- package/src/types.ts +17 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Syntax-backed public-export inventory for naming diagnostics. It reads the shared parsed
|
|
2
|
+
// script, resolves direct, default, and bottom re-export forms to one declaration list, and never
|
|
3
|
+
// parses a user's file again. The class/file rule reaches this module when deciding whether a
|
|
4
|
+
// mismatched class is the only public declaration a CLI or report user needs to locate.
|
|
5
|
+
import { createRequire } from "node:module";
|
|
6
|
+
import type { ParsedScript } from "./parsed-script.ts";
|
|
7
|
+
|
|
8
|
+
const require = createRequire(import.meta.url);
|
|
9
|
+
const typescriptSyntax = require("typescript") as typeof import("typescript");
|
|
10
|
+
|
|
11
|
+
type TsSourceFile = import("typescript").SourceFile;
|
|
12
|
+
type TsStatement = import("typescript").Statement;
|
|
13
|
+
type TsExportDeclaration = import("typescript").ExportDeclaration;
|
|
14
|
+
type TsExportAssignment = import("typescript").ExportAssignment;
|
|
15
|
+
|
|
16
|
+
/*
|
|
17
|
+
* Stable declaration categories shown inside class/file finding metadata. `default` and
|
|
18
|
+
* `re-export` represent public values whose local declaration kind is unavailable without type
|
|
19
|
+
* checking, so report users still see why a class was not treated as the sole export.
|
|
20
|
+
*/
|
|
21
|
+
export type PublicExportKind = "class" | "interface" | "type" | "enum" | "function" | "default" | "re-export";
|
|
22
|
+
|
|
23
|
+
/*
|
|
24
|
+
* One deterministic public declaration from the user's module. Resolved local re-exports retain
|
|
25
|
+
* the local kind, name, and declaration line; unresolved external/default values use the export
|
|
26
|
+
* statement line so the inventory remains complete without a semantic program.
|
|
27
|
+
* `exportedName` is present only when an alias renames the declaration on its way out, because the
|
|
28
|
+
* name a consumer imports is the one a naming rule about the public surface has to judge.
|
|
29
|
+
*/
|
|
30
|
+
export interface PublicExportDeclaration {
|
|
31
|
+
kind: PublicExportKind;
|
|
32
|
+
name: string;
|
|
33
|
+
line: number;
|
|
34
|
+
exportedName?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/*
|
|
38
|
+
* The five named declaration forms already covered by the public-doc scan. Keeping this syntax
|
|
39
|
+
* set explicit prevents value exports from silently widening the class/file policy beyond the
|
|
40
|
+
* module shapes named in the rule's user documentation.
|
|
41
|
+
*/
|
|
42
|
+
type SupportedDeclaration =
|
|
43
|
+
| import("typescript").ClassDeclaration
|
|
44
|
+
| import("typescript").InterfaceDeclaration
|
|
45
|
+
| import("typescript").TypeAliasDeclaration
|
|
46
|
+
| import("typescript").EnumDeclaration
|
|
47
|
+
| import("typescript").FunctionDeclaration;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Builds the stable sorted public-declaration contract used by class/file naming diagnostics.
|
|
51
|
+
* @param parsed Shared parse for the user's script; callers never pass null or undefined.
|
|
52
|
+
* @returns Sorted declarations; an empty array means the module exposes none of the supported forms.
|
|
53
|
+
*/
|
|
54
|
+
export function publicExportDeclarations(parsed: ParsedScript): PublicExportDeclaration[] {
|
|
55
|
+
const localDeclarations = localDeclarationIndex(parsed.sourceFile);
|
|
56
|
+
const publicDeclarations = new Map<string, PublicExportDeclaration>();
|
|
57
|
+
// A second top-level pass can resolve bottom exports because every local declaration is indexed first.
|
|
58
|
+
for (const statement of parsed.sourceFile.statements) {
|
|
59
|
+
collectDirectExport(parsed.sourceFile, statement, publicDeclarations);
|
|
60
|
+
// Export declarations cover named, namespace, wildcard, local, and external re-export syntax.
|
|
61
|
+
if (typescriptSyntax.isExportDeclaration(statement)) {
|
|
62
|
+
collectNamedOrExternalExport(parsed.sourceFile, statement, localDeclarations, publicDeclarations);
|
|
63
|
+
}
|
|
64
|
+
// Export assignments cover `export default LocalName` and expression-valued defaults.
|
|
65
|
+
if (typescriptSyntax.isExportAssignment(statement)) {
|
|
66
|
+
collectExportAssignment(parsed.sourceFile, statement, localDeclarations, publicDeclarations);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return [...publicDeclarations.values()].sort(comparePublicDeclarations);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Indexes supported top-level declarations before export statements are resolved. Empty source
|
|
73
|
+
// produces an empty map, which means a later external re-export remains explicitly unresolved.
|
|
74
|
+
function localDeclarationIndex(sourceFile: TsSourceFile): Map<string, PublicExportDeclaration> {
|
|
75
|
+
const declarations = new Map<string, PublicExportDeclaration>();
|
|
76
|
+
// Bottom-of-file exports need declarations from the entire module, including later source lines.
|
|
77
|
+
for (const statement of sourceFile.statements) {
|
|
78
|
+
const declaration = supportedDeclaration(sourceFile, statement);
|
|
79
|
+
// Anonymous default declarations have no local name for another export statement to reference.
|
|
80
|
+
if (!declaration || declaration.name === "default") {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const existingDeclaration = declarations.get(declaration.name);
|
|
84
|
+
// A merged class is the runtime value a bottom export exposes; otherwise retain the earliest
|
|
85
|
+
// declaration anchor for deterministic output.
|
|
86
|
+
if (!existingDeclaration || declaration.kind === "class" && existingDeclaration.kind !== "class") {
|
|
87
|
+
declarations.set(declaration.name, declaration);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return declarations;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Adds a supported declaration only when the user exported it on its declaration line.
|
|
94
|
+
function collectDirectExport(sourceFile: TsSourceFile, statement: TsStatement, publicDeclarations: Map<string, PublicExportDeclaration>): void {
|
|
95
|
+
const declaration = supportedDeclaration(sourceFile, statement);
|
|
96
|
+
// Local-only declarations are indexed for possible bottom exports but are not public yet.
|
|
97
|
+
if (!declaration || !hasModifier(statement, typescriptSyntax.SyntaxKind.ExportKeyword)) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
addPublicDeclaration(publicDeclarations, declaration);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Resolves one export declaration to local declaration facts when possible, otherwise records the
|
|
104
|
+
// external public name. This is what keeps class selection syntax-independent for CLI users.
|
|
105
|
+
function collectNamedOrExternalExport(sourceFile: TsSourceFile, statement: TsExportDeclaration, localDeclarations: Map<string, PublicExportDeclaration>, publicDeclarations: Map<string, PublicExportDeclaration>): void {
|
|
106
|
+
const exportLine = sourceLine(sourceFile, statement);
|
|
107
|
+
const exportClause = statement.exportClause;
|
|
108
|
+
// A wildcard still exposes another module surface even though syntax alone cannot name each item.
|
|
109
|
+
if (!exportClause) {
|
|
110
|
+
addPublicDeclaration(publicDeclarations, { kind: "re-export", name: "*", line: exportLine });
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
// Namespace exports have one explicit public name, such as `export * as tools`.
|
|
114
|
+
if (typescriptSyntax.isNamespaceExport(exportClause)) {
|
|
115
|
+
addPublicDeclaration(publicDeclarations, { kind: "re-export", name: exportClause.name.text, line: exportLine });
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
// Each named export is one public declaration unless it resolves to the same local declaration.
|
|
119
|
+
for (const exportSpecifier of exportClause.elements) {
|
|
120
|
+
// An alias resolves through its local source name; an unaliased export uses its public name.
|
|
121
|
+
const localName = (exportSpecifier.propertyName ?? exportSpecifier.name).text;
|
|
122
|
+
const publicName = exportSpecifier.name.text;
|
|
123
|
+
const localDeclaration = statement.moduleSpecifier ? undefined : localDeclarations.get(localName);
|
|
124
|
+
// External or unresolved names remain visible as re-exports so they still prevent sole-class advice.
|
|
125
|
+
addPublicDeclaration(publicDeclarations, localDeclaration
|
|
126
|
+
// A rename keeps the local kind and anchor but records the name consumers actually import.
|
|
127
|
+
? { ...localDeclaration, ...(publicName === localDeclaration.name ? {} : { exportedName: publicName }) }
|
|
128
|
+
: { kind: "re-export", name: publicName, line: exportLine });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Resolves an identifier-valued default/export-equals assignment to its declaration. Expression
|
|
133
|
+
// defaults remain one explicit public item because the user still exported a second module value.
|
|
134
|
+
function collectExportAssignment(sourceFile: TsSourceFile, statement: TsExportAssignment, localDeclarations: Map<string, PublicExportDeclaration>, publicDeclarations: Map<string, PublicExportDeclaration>): void {
|
|
135
|
+
const localDeclaration = typescriptSyntax.isIdentifier(statement.expression) ? localDeclarations.get(statement.expression.text) : undefined;
|
|
136
|
+
// A named local class exported as default must retain its class name and declaration anchor.
|
|
137
|
+
if (localDeclaration) {
|
|
138
|
+
addPublicDeclaration(publicDeclarations, localDeclaration);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const unresolvedExport = statement.isExportEquals
|
|
142
|
+
? { kind: "re-export" as const, name: "export=", line: sourceLine(sourceFile, statement) }
|
|
143
|
+
: { kind: "default" as const, name: "default", line: sourceLine(sourceFile, statement) };
|
|
144
|
+
addPublicDeclaration(publicDeclarations, unresolvedExport);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Projects a supported top-level syntax node into the user-visible kind, name, and line tuple.
|
|
148
|
+
// Undefined means the statement is outside the class/interface/type/enum/function policy surface.
|
|
149
|
+
function supportedDeclaration(sourceFile: TsSourceFile, statement: TsStatement): PublicExportDeclaration | undefined {
|
|
150
|
+
// Other top-level statements, such as imports and exported constants, do not enter this policy slice.
|
|
151
|
+
if (!isSupportedDeclaration(statement)) {
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
const kind = supportedDeclarationKind(statement);
|
|
155
|
+
// Named declarations retain their symbol; anonymous defaults use one stable placeholder.
|
|
156
|
+
const name = statement.name?.text ?? (hasModifier(statement, typescriptSyntax.SyntaxKind.DefaultKeyword) ? "default" : undefined);
|
|
157
|
+
// A non-default anonymous declaration has no stable symbol a class/file finding could present.
|
|
158
|
+
if (!name) {
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
return { kind, name, line: sourceLine(sourceFile, statement) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Narrows top-level syntax to the declaration forms named by the class/file rule policy.
|
|
165
|
+
function isSupportedDeclaration(statement: TsStatement): statement is SupportedDeclaration {
|
|
166
|
+
return typescriptSyntax.isClassDeclaration(statement)
|
|
167
|
+
|| typescriptSyntax.isInterfaceDeclaration(statement)
|
|
168
|
+
|| typescriptSyntax.isTypeAliasDeclaration(statement)
|
|
169
|
+
|| typescriptSyntax.isEnumDeclaration(statement)
|
|
170
|
+
|| typescriptSyntax.isFunctionDeclaration(statement);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Converts a narrowed syntax declaration to the stable lowercase metadata category.
|
|
174
|
+
function supportedDeclarationKind(declaration: SupportedDeclaration): Exclude<PublicExportKind, "default" | "re-export"> {
|
|
175
|
+
// The class check comes first because it is the only kind eligible for the eventual finding.
|
|
176
|
+
if (typescriptSyntax.isClassDeclaration(declaration)) {
|
|
177
|
+
return "class";
|
|
178
|
+
}
|
|
179
|
+
// Interfaces and type aliases remain distinct so users can understand a multi-export contract surface.
|
|
180
|
+
if (typescriptSyntax.isInterfaceDeclaration(declaration)) {
|
|
181
|
+
return "interface";
|
|
182
|
+
}
|
|
183
|
+
if (typescriptSyntax.isTypeAliasDeclaration(declaration)) {
|
|
184
|
+
return "type";
|
|
185
|
+
}
|
|
186
|
+
// Enums keep their own category so a report explains why a module is multi-public.
|
|
187
|
+
if (typescriptSyntax.isEnumDeclaration(declaration)) {
|
|
188
|
+
return "enum";
|
|
189
|
+
}
|
|
190
|
+
return "function";
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Reads one modifier without assuming every statement kind exposes a modifier array.
|
|
194
|
+
function hasModifier(statement: TsStatement, modifierKind: import("typescript").SyntaxKind): boolean {
|
|
195
|
+
// Statement kinds without modifier storage behave as an empty modifier list for the user.
|
|
196
|
+
const modifiers = typescriptSyntax.canHaveModifiers(statement) ? typescriptSyntax.getModifiers(statement) : undefined;
|
|
197
|
+
return modifiers?.some((modifier) => modifier.kind === modifierKind) === true;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Adds one declaration by stable kind/name key. Repeated aliases and merged declarations stay one
|
|
201
|
+
// public item, with the earliest source anchor retained for deterministic user output.
|
|
202
|
+
function addPublicDeclaration(publicDeclarations: Map<string, PublicExportDeclaration>, declaration: PublicExportDeclaration): void {
|
|
203
|
+
const key = `${declaration.kind}:${declaration.name}`;
|
|
204
|
+
const existingDeclaration = publicDeclarations.get(key);
|
|
205
|
+
// The first source occurrence is the clearest anchor when aliases expose the same declaration twice.
|
|
206
|
+
if (!existingDeclaration || declaration.line < existingDeclaration.line) {
|
|
207
|
+
publicDeclarations.set(key, declaration);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Converts a syntax start offset to the one-based source line shown in findings and metadata probes.
|
|
212
|
+
function sourceLine(sourceFile: TsSourceFile, statement: TsStatement): number {
|
|
213
|
+
return sourceFile.getLineAndCharacterOfPosition(statement.getStart(sourceFile)).line + 1;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Sorts by the serialized kind:name value, then line as a deterministic tie-breaker.
|
|
217
|
+
function comparePublicDeclarations(left: PublicExportDeclaration, right: PublicExportDeclaration): number {
|
|
218
|
+
const labelOrder = `${left.kind}:${left.name}`.localeCompare(`${right.kind}:${right.name}`);
|
|
219
|
+
return labelOrder || left.line - right.line;
|
|
220
|
+
}
|
package/src/report-renderers.ts
CHANGED
|
@@ -41,7 +41,8 @@ type JsonAnalysisReport = Omit<AnalysisReport, "findings" | "score"> & {
|
|
|
41
41
|
score: Omit<AnalysisReport["score"], "topOffenders"> & { topOffenders: JsonTopOffender[] };
|
|
42
42
|
};
|
|
43
43
|
|
|
44
|
-
// JSON boundary adapter: canonical `file` is emitted while legacy `filePath`
|
|
44
|
+
// JSON boundary adapter: canonical `file` is emitted while legacy `filePath` remains until the
|
|
45
|
+
// coordinated family JSON unification; a port-local removal would break existing report users.
|
|
45
46
|
// Stable `gruff.analysis.v2` contract line kept adjacent to the function for the doc-context rule.
|
|
46
47
|
function toJsonReport(report: AnalysisReport): JsonAnalysisReport {
|
|
47
48
|
return {
|
|
@@ -314,6 +315,7 @@ function formatSummaryDuration(elapsedMs: number): string {
|
|
|
314
315
|
return `${(bounded / 1000).toFixed(2)}s`;
|
|
315
316
|
}
|
|
316
317
|
|
|
318
|
+
// Tallies findings under the caller-supplied key; iteration order stays deterministic for renderers.
|
|
317
319
|
function countBy<T extends string>(findings: Finding[], keyFor: (finding: Finding) => T): Map<T, number> {
|
|
318
320
|
const counts = new Map<T, number>();
|
|
319
321
|
for (const finding of findings) {
|
|
@@ -390,6 +392,7 @@ function truncateDescription(text: string): string {
|
|
|
390
392
|
return text.length <= DESCRIPTION_BODY_LIMIT ? text : `${text.slice(0, DESCRIPTION_BODY_LIMIT).trimEnd()}…`;
|
|
391
393
|
}
|
|
392
394
|
|
|
395
|
+
// Renders a count map as ranked text bullets; the (count DESC, key ASC) ordering is deterministic.
|
|
393
396
|
function renderRankedCounts<T extends string>(counts: Map<T, number>, emptyText: string, limit?: number): string[] {
|
|
394
397
|
if (counts.size === 0) {
|
|
395
398
|
return [`- ${emptyText}`];
|
|
@@ -400,6 +403,7 @@ function renderRankedCounts<T extends string>(counts: Map<T, number>, emptyText:
|
|
|
400
403
|
.map(([key, count]) => `- ${key}: ${count}`);
|
|
401
404
|
}
|
|
402
405
|
|
|
406
|
+
// Structured variant of `renderRankedCounts` for JSON consumers; the same deterministic ordering.
|
|
403
407
|
function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?: number): Array<{ name: T; count: number }> {
|
|
404
408
|
return [...counts.entries()]
|
|
405
409
|
.sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey))
|
|
@@ -426,6 +430,9 @@ function renderText(report: AnalysisReport): string {
|
|
|
426
430
|
if (report.diagnostics.length > 0) {
|
|
427
431
|
lines.push("", "Diagnostics:", ...report.diagnostics.map(summaryDiagnosticLine));
|
|
428
432
|
}
|
|
433
|
+
if ((report.notes ?? []).length > 0) {
|
|
434
|
+
lines.push("", "Notes:", ...(report.notes ?? []).map((note) => `- ${note.noteType}: ${note.message} (${note.path})`));
|
|
435
|
+
}
|
|
429
436
|
if (report.findings.length > 0) {
|
|
430
437
|
lines.push("", "Findings:", ...report.findings.map((finding) => `- [${finding.severity}] ${finding.filePath}:${finding.line ?? 1} ${finding.ruleId} - ${finding.message}`));
|
|
431
438
|
}
|
|
@@ -445,6 +452,10 @@ function renderText(report: AnalysisReport): string {
|
|
|
445
452
|
*/
|
|
446
453
|
function renderMarkdown(report: AnalysisReport): string {
|
|
447
454
|
const breakdown = severityGradeBreakdown(report.findings);
|
|
455
|
+
// A repository controls each displayed value; a missing line keeps the historic line-1 fallback.
|
|
456
|
+
const findingRows = report.findings
|
|
457
|
+
.slice(0, 50)
|
|
458
|
+
.map((finding) => `- ${markdownInlineCode(finding.ruleId)} ${markdownInlineCode(finding.filePath)}:${finding.line ?? 1} - ${escapeMarkdownFindingMessage(finding.message)}`);
|
|
448
459
|
return [
|
|
449
460
|
"# gruff-ts report",
|
|
450
461
|
"",
|
|
@@ -458,7 +469,7 @@ function renderMarkdown(report: AnalysisReport): string {
|
|
|
458
469
|
"",
|
|
459
470
|
...renderMarkdownPillarsTable(buildPillarRows(report)),
|
|
460
471
|
"",
|
|
461
|
-
...
|
|
472
|
+
...findingRows,
|
|
462
473
|
].join("\n");
|
|
463
474
|
}
|
|
464
475
|
|
|
@@ -496,6 +507,38 @@ function escapeMarkdownCell(cell: string): string {
|
|
|
496
507
|
return cell.replaceAll("|", "\\|");
|
|
497
508
|
}
|
|
498
509
|
|
|
510
|
+
// Wraps a repository-controlled label in a CommonMark code span for PR and issue reports.
|
|
511
|
+
// A fence longer than the label's longest backtick run keeps the label inside one span.
|
|
512
|
+
function markdownInlineCode(reportLabel: string): string {
|
|
513
|
+
const singleLineLabel = reportLabel.replace(/[\r\n]+/g, " ");
|
|
514
|
+
// An empty analyzer label still needs content so Markdown does not merge its two fences.
|
|
515
|
+
const visibleLabel = singleLineLabel.length === 0 ? " " : singleLineLabel;
|
|
516
|
+
const fenceLength = Math.max(1, ...Array.from(visibleLabel.matchAll(/`+/g), (match) => match[0].length + 1));
|
|
517
|
+
const fence = "`".repeat(fenceLength);
|
|
518
|
+
// Edge backticks need padding so CommonMark can distinguish label content from the fence.
|
|
519
|
+
const paddedLabel = visibleLabel.startsWith("`") || visibleLabel.endsWith("`") ? ` ${visibleLabel} ` : visibleLabel;
|
|
520
|
+
return `${fence}${paddedLabel}${fence}`;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// Escapes repository-controlled finding prose before a reviewer sees the Markdown report.
|
|
524
|
+
// Line breaks collapse so a message cannot start a new heading, list, or HTML block.
|
|
525
|
+
function escapeMarkdownFindingMessage(findingMessage: string): string {
|
|
526
|
+
return findingMessage
|
|
527
|
+
.replace(/[\r\n]+/g, " ")
|
|
528
|
+
.replaceAll("&", "&")
|
|
529
|
+
.replaceAll("<", "<")
|
|
530
|
+
.replaceAll(">", ">")
|
|
531
|
+
.replaceAll("\\", "\\\\")
|
|
532
|
+
.replaceAll("`", "\\`")
|
|
533
|
+
.replaceAll("*", "\\*")
|
|
534
|
+
.replaceAll("_", "\\_")
|
|
535
|
+
.replaceAll("[", "\\[")
|
|
536
|
+
.replaceAll("]", "\\]")
|
|
537
|
+
.replaceAll("|", "\\|")
|
|
538
|
+
.replaceAll("#", "\\#")
|
|
539
|
+
.replaceAll("~", "\\~");
|
|
540
|
+
}
|
|
541
|
+
|
|
499
542
|
// Render-only summary of overlapping complexity findings for one function symbol.
|
|
500
543
|
interface ComplexityCluster {
|
|
501
544
|
filePath: string;
|
|
@@ -520,18 +563,29 @@ function renderComplexityClusterLines(findings: Finding[], limit = 10): string[]
|
|
|
520
563
|
// Invariant: markdown mirrors text complexity clusters without adding JSON fields.
|
|
521
564
|
function renderMarkdownComplexityClusterLines(findings: Finding[]): string[] {
|
|
522
565
|
const clusters = complexityClusters(findings);
|
|
566
|
+
// A scan with no overlapping complexity findings should not show an empty review section.
|
|
523
567
|
if (clusters.length === 0) {
|
|
524
568
|
return [];
|
|
525
569
|
}
|
|
570
|
+
// Repository paths and symbols stay inside one code span in the reviewer's cluster list.
|
|
571
|
+
const clusterRows = clusters.map(renderMarkdownComplexityClusterRow);
|
|
526
572
|
return [
|
|
527
573
|
"",
|
|
528
574
|
"## Correlated Complexity Clusters",
|
|
529
575
|
"",
|
|
530
|
-
...
|
|
576
|
+
...clusterRows,
|
|
531
577
|
];
|
|
532
578
|
}
|
|
533
579
|
|
|
534
|
-
//
|
|
580
|
+
// Formats one correlated cluster for the Markdown list a reviewer sees in pull-request output.
|
|
581
|
+
function renderMarkdownComplexityClusterRow(cluster: ComplexityCluster): string {
|
|
582
|
+
const clusterLabel = `${cluster.filePath}#${cluster.symbol}`;
|
|
583
|
+
// Every linked rule remains its own code span so a reviewer can copy its exact identifier.
|
|
584
|
+
const linkedRuleLabels = cluster.ruleIds.map((ruleId) => markdownInlineCode(ruleId)).join(", ");
|
|
585
|
+
return `- ${markdownInlineCode(clusterLabel)}: ${cluster.ruleIds.length} linked findings (${linkedRuleLabels})`;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// Invariant: groups findings by file and symbol so every renderer explains score overlap consistently.
|
|
535
589
|
function complexityClusters(findings: Finding[]): ComplexityCluster[] {
|
|
536
590
|
const bySymbol = new Map<string, ComplexityCluster>();
|
|
537
591
|
for (const finding of findings) {
|
package/src/rules.ts
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
import type { RuleDescriptor } from "./types.ts";
|
|
3
3
|
|
|
4
4
|
const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
5
|
-
{ ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags
|
|
6
|
-
{ ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "
|
|
7
|
-
{ ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags
|
|
5
|
+
{ ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags syntax-aware decisions plus nested if, loop, switch, catch, and ternary depth; object and callback braces add no nesting.", remediation: "Split nested decisions into smaller named functions. Or raise rules.complexity.cognitive.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 },
|
|
6
|
+
{ ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "Counts a base path plus if, loop, catch, non-default case, ternary, &&, and || nodes; switch, default, ??, optional chains, and non-null assertions add zero.", remediation: "Reduce branching or move policy tables out of imperative code. Or raise rules.complexity.cyclomatic.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 }, { ruleId: "dead-code.unused-private-method", pillar: "dead-code", severity: "advisory", confidence: "low", description: "Flags private methods without an apparent same-file call site.", remediation: "Remove the method or add a direct call site." },
|
|
7
|
+
{ ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags strongly connected relative import components that include the scan surface.", remediation: "Extract the shared contract or invert one dependency." },
|
|
8
8
|
{ ruleId: "design.deep-relative-import", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags relative imports that climb too many parent directories.", remediation: "Move the shared module closer or add a local boundary. Or raise rules.design.deep-relative-import.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 2 },
|
|
9
9
|
{ ruleId: "design.large-module-concentration", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags a production module that dominates project source lines.", remediation: "Split unrelated responsibilities once stable seams are visible. Or raise rules.design.large-module-concentration.threshold or tune minFiles, minLines under rules.design.large-module-concentration.options.", threshold: 55, optionKeys: ["minFiles", "minLines"] },
|
|
10
10
|
{ ruleId: "design.package-bin-missing", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin entries that point at missing files.", remediation: "Update the bin path or add the executable file." },
|
|
11
11
|
{ ruleId: "design.package-bin-not-executable", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin targets that are not executable.", remediation: "Make the bin target executable and keep its shebang valid." },
|
|
12
|
-
{ ruleId: "docs.fixture-purpose-missing", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags large or scanner-relevant fixtures without a nearby purpose comment.", remediation: "
|
|
12
|
+
{ ruleId: "docs.fixture-purpose-missing", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags large or scanner-relevant fixtures without a nearby purpose comment.", remediation: "Add a comment on or directly above the fixture (or above the test declaration) explaining what scanner path, regression, or fixture behavior it covers." },
|
|
13
13
|
{ ruleId: "docs.magic-threshold-without-rationale", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags threshold-like numeric values without a nearby rationale comment.", remediation: "Explain the threshold, limit, budget, or default near the value." },
|
|
14
14
|
{ ruleId: "docs.missing-error-behavior-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented functions whose error behavior is not described.", remediation: "Document thrown errors, diagnostics, exits, reports, or recovery behavior." },
|
|
15
15
|
{ ruleId: "docs.missing-exported-function-doc", pillar: "documentation", severity: "warning", confidence: "medium", description: "Flags exported functions without a leading maintainer comment.", remediation: "Add a JSDoc or line comment explaining the exported API's contract, since public surface has a higher cost of omission." },
|
|
@@ -25,7 +25,7 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
25
25
|
{ ruleId: "docs.stale-comment", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags comments that reference missing files, unknown rules, stale CLI flags, or the wrong declaration.", remediation: "Update the comment or add historical context explaining why it remains useful." },
|
|
26
26
|
{ ruleId: "docs.stale-param-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags @param tags for parameters no longer in the signature.", remediation: "Remove stale tags or update the function signature." },
|
|
27
27
|
{ ruleId: "docs.suppression-without-rationale", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags lint, formatter, coverage, or tool suppressions without a maintainer rationale.", remediation: "Explain why the suppression is intentional, a false positive, or tracked elsewhere." },
|
|
28
|
-
{ ruleId: "docs.todo-without-tracking", pillar: "documentation", severity: "advisory", confidence: "high", description: "Flags TODO, FIXME, HACK,
|
|
28
|
+
{ ruleId: "docs.todo-without-tracking", pillar: "documentation", severity: "advisory", confidence: "high", description: "Flags comments introduced by a TODO, FIXME, HACK, or XXX marker without tracking context; prose that only mentions a marker word stays quiet.", remediation: "Attach a tracking URL, issue id, owner, date, ADR, or .goat-flow task reference." },
|
|
29
29
|
{ ruleId: "docs.useless-docblock", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags comments or docblocks that only restate the symbol name.", remediation: "Replace the comment with useful contract or behavior detail." },
|
|
30
30
|
{ ruleId: "modernisation.date-now-candidate", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags verbose current-time expressions that can use Date.now().", remediation: "Use Date.now() for current epoch milliseconds." },
|
|
31
31
|
{ ruleId: "modernisation.double-cast", pillar: "modernisation", severity: "warning", confidence: "medium", description: "Flags casts through unknown or any into another type.", remediation: "Use a parser, type guard, or narrower assertion." },
|
|
@@ -41,14 +41,14 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
41
41
|
{ ruleId: "modernisation.tsconfig-index-safety-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without noUncheckedIndexedAccess enabled.", remediation: "Enable noUncheckedIndexedAccess unless migration is blocked." },
|
|
42
42
|
{ ruleId: "modernisation.tsconfig-strict-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without strict mode enabled.", remediation: "Enable strict unless migration is blocked." },
|
|
43
43
|
{ ruleId: "modernisation.var-declaration", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags var declarations.", remediation: "Use let or const with the narrowest useful scope." },
|
|
44
|
-
{ ruleId: "naming.acronym-case", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags
|
|
45
|
-
{ ruleId: "naming.boolean-prefix", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean names without intent-revealing prefixes on declarations, function parameters (typed `: boolean` or with `= true|false` default), and interface/type-literal fields.", remediation: "
|
|
46
|
-
{ ruleId: "naming.class-file-mismatch", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags
|
|
44
|
+
{ ruleId: "naming.acronym-case", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags a known acronym cased inconsistently across a file's chosen-case names; SCREAMING_SNAKE constants and all-lower names are convention-forced and exempt.", remediation: "Use one casing for each acronym throughout the file. Or extend allowlists.knownAcronyms with project-specific values.", allowlistKeys: ["knownAcronyms"] },
|
|
45
|
+
{ ruleId: "naming.boolean-prefix", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean names without intent-revealing prefixes on declarations, function parameters (typed `: boolean` or with `= true|false` default), and interface/type-literal fields.", remediation: "Rename local booleans with an intent prefix. For contract fields, rename or map the key at serialization, or replace allowlists.acceptedBooleanNames with a complete list that includes it.", allowlistKeys: ["booleanPrefixes", "acceptedBooleanNames"] },
|
|
46
|
+
{ ruleId: "naming.class-file-mismatch", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags a sole public class whose name differs from the file name.", remediation: "Rename the class or file, or add the exact fileBase:ClassName pair to allowlists.acceptedClassFilePairs.", allowlistKeys: ["acceptedClassFilePairs"] },
|
|
47
47
|
{ ruleId: "naming.generic-function", pillar: "naming", severity: "advisory", confidence: "high", description: "Flags generic function names that hide intent.", remediation: "Name the domain action instead of a generic operation. Or remove the name from allowlists.bannedGenericNames if your project does not consider it generic.", allowlistKeys: ["bannedGenericNames"] },
|
|
48
48
|
{ ruleId: "naming.generic-parameter", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder parameter names in multi-parameter, long, exported, or complex functions.", remediation: "Use a name that describes the parameter's role. Or tune minCyclomatic, minLineCount, minParameters under rules.naming.generic-parameter.options.", optionKeys: ["minCyclomatic", "minLineCount", "minParameters"] },
|
|
49
49
|
{ ruleId: "naming.hungarian-notation", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags identifiers named after storage type prefixes.", remediation: "Name the domain concept instead of the storage type. Or remove the prefix from allowlists.hungarianPrefixes if your project does not consider it Hungarian-style.", allowlistKeys: ["hungarianPrefixes"] },
|
|
50
50
|
{ ruleId: "naming.identifier-quality", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder or numbered identifiers on declarations, function parameters, and destructured locals.", remediation: "Use names that explain domain role or intent. Or remove the name from allowlists.placeholderNames if your project considers it valid.", allowlistKeys: ["placeholderNames"] },
|
|
51
|
-
{ ruleId: "naming.inconsistent-casing", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags
|
|
51
|
+
{ ruleId: "naming.inconsistent-casing", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags one canonical identifier appearing in different forms within the same module, function, interface, or named type-literal owner.", remediation: "Choose one form within the owner, or add an exact alias pair to allowlists.acceptedCasingPairs.", allowlistKeys: ["acceptedCasingPairs"] },
|
|
52
52
|
{ ruleId: "naming.negative-boolean", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean identifiers framed as a negation on declarations, parameters, and interface fields.", remediation: "Invert the framing so callers do not read a double negation. Or extend allowlists.negativeBooleanAllowed with project-specific values.", allowlistKeys: ["negativeBooleanAllowed"] },
|
|
53
53
|
{ ruleId: "naming.short-variable", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags very short variable names outside common loop counters; covers declarations, function parameters, and destructured locals.", remediation: "Use a name that describes the domain role. Or extend allowlists.acceptedAbbreviations with project-specific values.", allowlistKeys: ["acceptedAbbreviations"] },
|
|
54
54
|
{ ruleId: "security.async-foreach", pillar: "security", severity: "warning", confidence: "medium", description: "Flags async callbacks passed to forEach.", remediation: "Use for...of with await, Promise.all, or an explicit queue." },
|
|
@@ -68,11 +68,11 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
68
68
|
{ ruleId: "security.new-function", pillar: "security", severity: "error", confidence: "high", description: "Flags Function constructor dynamic code execution.", remediation: "Replace dynamic construction with explicit functions or dispatch." },
|
|
69
69
|
{ ruleId: "security.open-redirect-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to redirect or navigation sinks.", remediation: "Redirect only to relative paths or destinations from an allowlist." },
|
|
70
70
|
{ ruleId: "security.path-traversal-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to filesystem path sinks.", remediation: "Validate paths against an allowlist and resolve them under a safe root." },
|
|
71
|
-
{ ruleId: "security.process-exec", pillar: "security", severity: "warning", confidence: "high", description: "Flags child-process execution calls.", remediation: "
|
|
71
|
+
{ ruleId: "security.process-exec", pillar: "security", severity: "warning", confidence: "high", description: "Flags child-process execution calls, grading severity from command-source and shell-mode evidence: warning only when a shell-enabled call takes a dynamic command.", remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled." },
|
|
72
72
|
{ ruleId: "security.proto-access", pillar: "security", severity: "warning", confidence: "medium", description: "Flags direct __proto__ access that can enable prototype pollution.", remediation: "Use Object.getPrototypeOf, Object.create(null), or validated keys." },
|
|
73
73
|
{ ruleId: "security.remote-install-script", pillar: "security", severity: "error", confidence: "medium", description: "Flags package scripts that pipe remote content to a shell.", remediation: "Vendor, pin, or remove remote shell execution." },
|
|
74
|
-
{ ruleId: "security.risky-lifecycle-script", pillar: "security", severity: "warning", confidence: "medium", description: "Flags
|
|
75
|
-
{ ruleId: "security.sql-concatenation", pillar: "security", severity: "warning", confidence: "high", description: "Flags SQL text composed with runtime
|
|
74
|
+
{ ruleId: "security.risky-lifecycle-script", pillar: "security", severity: "warning", confidence: "medium", description: "Flags install-time and side-effectful publish lifecycle scripts while allowing validation-only publish gates.", remediation: "Review whether lifecycle execution is required; keep install/publish side effects behind explicit commands when possible." },
|
|
75
|
+
{ ruleId: "security.sql-concatenation", pillar: "security", severity: "warning", confidence: "high", description: "Flags SQL text composed with runtime interpolation or concatenation in query, execute, raw, or prepare calls.", remediation: "Use parameterized values, and keep dynamic identifiers constrained to trusted constants or explicit review." },
|
|
76
76
|
{ ruleId: "security.ssrf-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to network request sinks.", remediation: "Validate destinations against an allowlist and block internal hosts." },
|
|
77
77
|
{ ruleId: "security.string-timer", pillar: "security", severity: "warning", confidence: "high", description: "Flags string callbacks passed to timers.", remediation: "Pass a function callback instead of source text." },
|
|
78
78
|
{ ruleId: "security.throw-non-error", pillar: "security", severity: "warning", confidence: "medium", description: "Flags thrown non-Error values.", remediation: "Throw an Error subclass with a clear message." },
|
|
@@ -90,13 +90,13 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
90
90
|
{ ruleId: "sensitive-data.phi-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PHI identifiers such as Medicare (MBI) and medical record numbers.", remediation: "Remove protected health information from source and fixtures." },
|
|
91
91
|
{ ruleId: "sensitive-data.pii-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PII-like identifier patterns including SSN-shaped values and Luhn-valid payment cards.", remediation: "Remove personal data from source and fixtures." },
|
|
92
92
|
{ ruleId: "sensitive-data.private-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags private key block markers.", remediation: "Remove the key material and rotate affected credentials." },
|
|
93
|
-
{ ruleId: "size.file-length", pillar: "size", severity: "
|
|
93
|
+
{ ruleId: "size.file-length", pillar: "size", severity: "error", confidence: "high", description: "Flags files whose substantive nonblank, non-comment line count exceeds the configured threshold.", remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 1000 },
|
|
94
94
|
{ ruleId: "size.function-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions longer than the configured threshold.", remediation: "Extract named helpers or split workflows. Or raise rules.size.function-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 200 },
|
|
95
95
|
{ ruleId: "size.parameter-count", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions with too many parameters.", remediation: "Group related options or reduce the function's responsibility. Or raise rules.size.parameter-count.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 7 },
|
|
96
96
|
{ ruleId: "test-quality.conditional-logic", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests with conditional logic.", remediation: "Split branch-specific expectations into separate tests." },
|
|
97
97
|
{ ruleId: "test-quality.exception-type-only", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only assert exception type.", remediation: "Assert message, code, or observable behavior as well." },
|
|
98
98
|
{ ruleId: "test-quality.global-state-mutation", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests mutating process or global runtime state.", remediation: "Isolate state changes and restore them around the test." },
|
|
99
|
-
{ ruleId: "test-quality.loop-in-test", pillar: "test-quality", severity: "advisory", confidence: "
|
|
99
|
+
{ ruleId: "test-quality.loop-in-test", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags test-body loops whose assertions do not identify the failing iteration.", remediation: "Add a per-case message to looped assertions, or use a fixture table or separate named cases." },
|
|
100
100
|
{ ruleId: "test-quality.magic-number-assertion", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags assertions against unexplained numeric literals.", remediation: "Name expected values or assert domain-specific outcomes." },
|
|
101
101
|
{ ruleId: "test-quality.mock-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only verify mock interaction.", remediation: "Assert observable behavior in addition to collaboration." },
|
|
102
102
|
{ ruleId: "test-quality.no-assertions", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests without apparent assertions.", remediation: "Add assertions for observable behavior." },
|
|
@@ -104,7 +104,7 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
104
104
|
{ ruleId: "test-quality.only-skip", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags focused or skipped test markers.", remediation: "Remove .only and either enable or delete skipped tests." },
|
|
105
105
|
{ ruleId: "test-quality.sleep-in-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags sleeps in tests.", remediation: "Synchronize on behavior instead of wall-clock time." },
|
|
106
106
|
{ ruleId: "test-quality.snapshot-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that rely only on snapshots.", remediation: "Add targeted assertions for important behavior." },
|
|
107
|
-
{ ruleId: "test-quality.static-analysis-redundant-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that primarily assert code shape rather than behavior.", remediation: "Remove
|
|
107
|
+
{ ruleId: "test-quality.static-analysis-redundant-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that primarily assert code shape rather than behavior, with review guidance for importability sentinels.", remediation: "Remove redundant assertions, replace them with behavioral evidence, or document why runtime module-load coverage matters." },
|
|
108
108
|
{ ruleId: "test-quality.trivial-assertion", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tautological assertions.", remediation: "Assert a real result from the system under test." },
|
|
109
109
|
{ ruleId: "test-quality.unused-mock", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags mocks created but not used.", remediation: "Remove unused mocks or wire them into the behavior under test." },
|
|
110
110
|
{ ruleId: "waste.any-type", pillar: "maintainability", severity: "warning", confidence: "high", description: "Flags any type usage.", remediation: "Use unknown with validation or a precise type." },
|
package/src/scoring.ts
CHANGED
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
// Score, grade, and fail-on helpers derived from finding severities for reports and CLI exits.
|
|
2
2
|
import { grade } from "./pillar-summary.ts";
|
|
3
|
+
import { ruleDescriptors } from "./rules.ts";
|
|
3
4
|
import type { AnalysisReport, FailThreshold, Finding, Pillar, Severity } from "./types.ts";
|
|
4
5
|
|
|
6
|
+
// Every pillar that has at least one rule behind it. The composite averages over this whole set,
|
|
7
|
+
// because averaging only finding-bearing pillars let a pillar vanish from the mean the moment its
|
|
8
|
+
// last finding was fixed - lowering the headline score for finishing a pillar.
|
|
9
|
+
const SCOREABLE_PILLARS: readonly Pillar[] = [...new Set(ruleDescriptors().map((descriptor) => descriptor.pillar))];
|
|
10
|
+
|
|
5
11
|
// Builds the per-pillar and per-file score breakdown that ships in `gruff.analysis.v2`. The composite
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
12
|
+
// is the mean over every rule-backed pillar, with a clean pillar counting as 100, so removing a
|
|
13
|
+
// finding can never decrease it. The `pillars` array still lists only finding-bearing pillars -
|
|
14
|
+
// its shape is part of the `gruff.analysis.v2` schema contract. `topOffenders` is the full file
|
|
15
|
+
// list sorted worst-first; renderers cap it themselves (HTML/hotspot 10 rows, summary `--top`).
|
|
9
16
|
function scoreReport(findings: Finding[]): AnalysisReport["score"] {
|
|
10
17
|
const byPillar = new Map<Pillar, Finding[]>();
|
|
11
18
|
const byFile = new Map<string, Finding[]>();
|
|
@@ -18,7 +25,9 @@ function scoreReport(findings: Finding[]): AnalysisReport["score"] {
|
|
|
18
25
|
const penalty = pillarFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0);
|
|
19
26
|
return { pillar, score: Math.max(0, 100 - penalty), penalty, findings: pillarFindings.length };
|
|
20
27
|
});
|
|
21
|
-
const
|
|
28
|
+
const scoredPillarTotal = pillars.reduce((sum, pillar) => sum + pillar.score, 0);
|
|
29
|
+
const cleanPillarCount = Math.max(0, SCOREABLE_PILLARS.length - pillars.length);
|
|
30
|
+
const composite = SCOREABLE_PILLARS.length === 0 ? 100 : (scoredPillarTotal + 100 * cleanPillarCount) / SCOREABLE_PILLARS.length;
|
|
22
31
|
const topOffenders = [...byFile.entries()]
|
|
23
32
|
.map(([filePath, fileFindings]) => ({
|
|
24
33
|
filePath,
|