@blundergoat/gruff-ts 0.1.0 → 0.2.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 +35 -11
- package/CONTRIBUTING.md +3 -3
- package/README.md +141 -183
- package/docs/README.md +23 -0
- package/docs/ci-integration.md +63 -0
- package/docs/{CONFIGURATION.md → configuration.md} +41 -20
- package/docs/dashboard.md +36 -0
- package/docs/output-formats.md +65 -0
- package/docs/{RELEASING.md → releasing.md} +17 -14
- package/docs/{REPORTS_AND_CI.md → reports-and-ci.md} +5 -2
- package/docs/rules.md +177 -0
- package/package.json +2 -2
- package/scripts/bump-version.sh +83 -18
- package/scripts/dependency-install.sh +96 -0
- package/scripts/dependency-update.sh +177 -0
- package/scripts/preflight-checks.sh +38 -0
- package/src/analyser.ts +9 -24
- package/src/blocks.ts +66 -12
- package/src/class-rules.ts +5 -6
- package/src/cli-program.ts +216 -39
- package/src/cli.ts +4 -1
- package/src/comment-rules.ts +2 -0
- package/src/config-load-error.ts +18 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +155 -29
- package/src/constants.ts +10 -2
- package/src/dashboard.ts +1 -1
- package/src/dead-code-rules.ts +62 -16
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +17 -0
- package/src/init-config.ts +308 -0
- package/src/line-rules.ts +64 -12
- package/src/naming-pushers.ts +7 -32
- package/src/pillar-summary.ts +129 -0
- package/src/project-config-rules.ts +1 -1
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +210 -406
- package/src/rule-list.ts +65 -1
- package/src/rules.ts +36 -37
- package/src/safety-rules.ts +9 -4
- package/src/scoring.ts +41 -9
- package/src/test-block-rules.ts +43 -1
- package/src/test-fixtures.ts +13 -7
- package/src/text-scans.ts +1 -152
- package/src/types.ts +32 -6
package/src/rule-list.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Console command catalogue, shell completion scripts, and rule-list renderers for CLI surfaces.
|
|
2
2
|
import { VERSION } from "./constants.ts";
|
|
3
3
|
import { ruleDescriptors } from "./rules.ts";
|
|
4
|
+
import type { RuleDescriptor } from "./types.ts";
|
|
4
5
|
|
|
5
6
|
type RuleListFormat = "text" | "json";
|
|
6
7
|
type CompletionShell = "bash" | "fish" | "zsh";
|
|
@@ -21,6 +22,7 @@ const CONSOLE_COMMANDS = [
|
|
|
21
22
|
{ name: "completion", description: "Dump the shell completion script" },
|
|
22
23
|
{ name: "dashboard", description: "Serve the local gruff dashboard." },
|
|
23
24
|
{ name: "help", description: "Display help for a command" },
|
|
25
|
+
{ name: "init", description: "Write the default .gruff-ts.yaml to the current directory." },
|
|
24
26
|
{ name: "list", description: "List commands" },
|
|
25
27
|
{ name: "list-rules", description: "List gruff rule metadata." },
|
|
26
28
|
{ name: "report", description: "Render a gruff report to stdout or a file." },
|
|
@@ -47,6 +49,68 @@ function renderRuleList(format: RuleListFormat): string {
|
|
|
47
49
|
return `${lines.join("\n")}\n`;
|
|
48
50
|
}
|
|
49
51
|
|
|
52
|
+
/*
|
|
53
|
+
* Returns a single rule descriptor by ID, or undefined when the ID is not registered. Surfaced so
|
|
54
|
+
* the explain-mode renderer can dispatch on "is this a real rule?" without iterating the full
|
|
55
|
+
* catalogue at each render site. Stable contract: lookup keys match the public rule ID strings
|
|
56
|
+
* exactly; partial / case-insensitive matches are intentionally out of scope.
|
|
57
|
+
*/
|
|
58
|
+
function getRuleDescriptor(ruleId: string): RuleDescriptor | undefined {
|
|
59
|
+
return ruleDescriptors().find((descriptor) => descriptor.ruleId === ruleId);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/*
|
|
63
|
+
* Single-rule detail renderer. Text format prints a labelled section with every populated field;
|
|
64
|
+
* JSON format wraps the descriptor in a tool envelope mirroring the multi-rule shape. Surfaces
|
|
65
|
+
* config keys (`rules.<ruleId>.{enabled,severity,threshold}`) and the option/allowlist hatches
|
|
66
|
+
* because operators looking up one rule shouldn't have to grep `src/config.ts` to find the
|
|
67
|
+
* override knobs they're about to tune.
|
|
68
|
+
*/
|
|
69
|
+
function renderRuleDetail(descriptor: RuleDescriptor, format: RuleListFormat): string {
|
|
70
|
+
if (format === "json") {
|
|
71
|
+
return `${JSON.stringify({ tool: { name: "gruff-ts", version: VERSION }, rule: { ...descriptor, configKeys: ruleConfigKeys(descriptor) } }, null, 2)}\n`;
|
|
72
|
+
}
|
|
73
|
+
const lines = [
|
|
74
|
+
`Rule: ${descriptor.ruleId}`,
|
|
75
|
+
`Pillar: ${descriptor.pillar}`,
|
|
76
|
+
`Severity: ${descriptor.severity}`,
|
|
77
|
+
`Confidence: ${descriptor.confidence}`,
|
|
78
|
+
...(typeof descriptor.threshold === "number" ? [`Threshold: ${descriptor.threshold}`] : []),
|
|
79
|
+
"",
|
|
80
|
+
`Description: ${descriptor.description}`,
|
|
81
|
+
"",
|
|
82
|
+
`Remediation: ${descriptor.remediation}`,
|
|
83
|
+
"",
|
|
84
|
+
...ruleConfigKeyLines(descriptor),
|
|
85
|
+
...(descriptor.optionKeys && descriptor.optionKeys.length > 0 ? ["", "Options:", ...descriptor.optionKeys.map((key) => ` rules.${descriptor.ruleId}.options.${key}`)] : []),
|
|
86
|
+
...(descriptor.allowlistKeys && descriptor.allowlistKeys.length > 0 ? ["", "Allowlists:", ...descriptor.allowlistKeys.map((key) => ` allowlists.${key}`)] : []),
|
|
87
|
+
];
|
|
88
|
+
return `${lines.join("\n")}\n`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Three baseline config-key entries shared by every rule: the enable toggle, the severity override,
|
|
92
|
+
// and (when present) the threshold override. Optional knobs (options / allowlists) get their own
|
|
93
|
+
// blocks in `renderRuleDetail` to keep this list focused on the always-applicable keys.
|
|
94
|
+
function ruleConfigKeyLines(descriptor: RuleDescriptor): string[] {
|
|
95
|
+
return [
|
|
96
|
+
"Config keys:",
|
|
97
|
+
` rules.${descriptor.ruleId}.enabled (bool)`,
|
|
98
|
+
` rules.${descriptor.ruleId}.severity (advisory|warning|error)`,
|
|
99
|
+
...(typeof descriptor.threshold === "number" ? [` rules.${descriptor.ruleId}.threshold (int, default: ${descriptor.threshold})`] : []),
|
|
100
|
+
];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// JSON representation of the same config-key list. Returned as a structured array so JSON consumers
|
|
104
|
+
// don't have to re-derive the shape from the text layout. Each entry carries the key path, the
|
|
105
|
+
// value's type vocabulary, and a default when one is known.
|
|
106
|
+
function ruleConfigKeys(descriptor: RuleDescriptor): Array<{ key: string; type: string; values?: readonly string[]; default?: number | boolean | string }> {
|
|
107
|
+
return [
|
|
108
|
+
{ key: `rules.${descriptor.ruleId}.enabled`, type: "bool", default: true },
|
|
109
|
+
{ key: `rules.${descriptor.ruleId}.severity`, type: "enum", values: ["advisory", "warning", "error"] as const, default: descriptor.severity },
|
|
110
|
+
...(typeof descriptor.threshold === "number" ? [{ key: `rules.${descriptor.ruleId}.threshold`, type: "int", default: descriptor.threshold }] : []),
|
|
111
|
+
];
|
|
112
|
+
}
|
|
113
|
+
|
|
50
114
|
// The Symfony-style command catalogue shown for `gruff-ts`, `gruff-ts list`, and `gruff-ts help`.
|
|
51
115
|
// `shouldUseAnsi` is autodetected by the caller from TTY and `--ansi` flags, never from this layer.
|
|
52
116
|
function renderConsoleList(shouldUseAnsi = false): string {
|
|
@@ -176,4 +240,4 @@ function completionShell(shellName: unknown): CompletionShell {
|
|
|
176
240
|
}
|
|
177
241
|
|
|
178
242
|
export type { RuleListFormat, CompletionShell };
|
|
179
|
-
export { renderRuleList, renderConsoleList, renderCompletionScript, completionShell };
|
|
243
|
+
export { renderRuleList, renderRuleDetail, getRuleDescriptor, renderConsoleList, renderCompletionScript, completionShell };
|
package/src/rules.ts
CHANGED
|
@@ -2,21 +2,22 @@
|
|
|
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 functions with high combined branch and nesting complexity.", remediation: "Split nested decisions into smaller named functions.", threshold: 15 },
|
|
6
|
-
{ ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with many independent branch paths.", remediation: "Reduce branching or move policy tables out of imperative code.", threshold: 15 },
|
|
7
|
-
{ ruleId: "complexity.npath", pillar: "complexity", severity: "warning", confidence: "medium", description: "Flags functions with high approximate NPath complexity.", remediation: "Break apart compound branch combinations.", threshold: 200 },
|
|
5
|
+
{ ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with high combined branch and nesting complexity.", 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: "Flags functions with many independent branch paths.", 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 },
|
|
7
|
+
{ ruleId: "complexity.npath", pillar: "complexity", severity: "warning", confidence: "medium", description: "Flags functions with high approximate NPath complexity.", remediation: "Break apart compound branch combinations. Or raise rules.complexity.npath.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 200 },
|
|
8
8
|
{ 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." },
|
|
9
9
|
{ ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags simple relative import cycles inside the discovered source set.", remediation: "Extract the shared contract or invert one dependency." },
|
|
10
|
-
{ 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.", threshold: 2 },
|
|
10
|
+
{ 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 },
|
|
11
11
|
{ ruleId: "design.god-function", pillar: "design", severity: "warning", confidence: "high", description: "Flags functions that are both long and complex.", remediation: "Split responsibilities into smaller functions." },
|
|
12
|
-
{ 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.", threshold: 55, optionKeys: ["minFiles", "minLines"] },
|
|
12
|
+
{ 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"] },
|
|
13
13
|
{ 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." },
|
|
14
14
|
{ 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." },
|
|
15
15
|
{ ruleId: "docs.fixture-purpose-missing", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags large or scanner-relevant fixtures without a nearby purpose comment.", remediation: "Explain what scanner path, regression, or fixture behavior the source covers." },
|
|
16
16
|
{ 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." },
|
|
17
17
|
{ 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." },
|
|
18
|
+
{ 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." },
|
|
18
19
|
{ ruleId: "docs.missing-file-overview", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags source files without a top-of-file purpose comment.", remediation: "Add a brief file overview before imports or declarations." },
|
|
19
|
-
{ ruleId: "docs.missing-function-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags functions without a leading maintainer comment.", remediation: "Add a short
|
|
20
|
+
{ ruleId: "docs.missing-internal-function-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags internal helper functions without a leading maintainer comment.", remediation: "Add a short comment explaining the helper's role; internal helpers are advisory, exported surface fires the warning variant." },
|
|
20
21
|
{ ruleId: "docs.missing-interface-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags interfaces without a leading maintainer comment.", remediation: "Add a short JSDoc or line comment explaining the interface contract." },
|
|
21
22
|
{ ruleId: "docs.missing-invariant-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented declarations that own schema, fingerprint, baseline, or determinism contracts without saying so.", remediation: "Document the invariant, contract, schema, fingerprint, or deterministic behavior." },
|
|
22
23
|
{ ruleId: "docs.missing-param-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags documented exports with parameters missing @param tags.", remediation: "Document every current parameter in the JSDoc." },
|
|
@@ -27,7 +28,6 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
27
28
|
{ 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." },
|
|
28
29
|
{ 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." },
|
|
29
30
|
{ 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." },
|
|
30
|
-
{ ruleId: "docs.todo-density", pillar: "documentation", severity: "advisory", confidence: "high", description: "Flags files with a high count of TODO/FIXME markers (opt-in, disabled by default).", remediation: "Resolve stale markers, link them to tracked work, or enable docs.todo-without-tracking for context-aware coverage.", threshold: 4 },
|
|
31
31
|
{ ruleId: "docs.todo-without-tracking", pillar: "documentation", severity: "advisory", confidence: "high", description: "Flags TODO, FIXME, HACK, and XXX comments without tracking context.", remediation: "Attach a tracking URL, issue id, owner, date, ADR, or .goat-flow task reference." },
|
|
32
32
|
{ 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." },
|
|
33
33
|
{ 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." },
|
|
@@ -44,17 +44,16 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
44
44
|
{ 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." },
|
|
45
45
|
{ 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." },
|
|
46
46
|
{ ruleId: "modernisation.var-declaration", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags var declarations.", remediation: "Use let or const with the narrowest useful scope." },
|
|
47
|
-
{ ruleId: "naming.
|
|
48
|
-
{ ruleId: "naming.
|
|
49
|
-
{ 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: "Use prefixes such as is, has, can, should, or will." },
|
|
47
|
+
{ ruleId: "naming.acronym-case", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags mixed casings of a known acronym in one file.", remediation: "Use one casing for each acronym throughout the file. Or extend allowlists.knownAcronyms with project-specific values.", allowlistKeys: ["knownAcronyms"] },
|
|
48
|
+
{ 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: "Use prefixes such as is, has, can, should, or will. Or extend allowlists.booleanPrefixes with project-specific values.", allowlistKeys: ["booleanPrefixes"] },
|
|
50
49
|
{ ruleId: "naming.class-file-mismatch", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags exported classes whose name differs from the file name.", remediation: "Rename the class or file so the primary export is easy to locate." },
|
|
51
|
-
{ 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." },
|
|
52
|
-
{ 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.", optionKeys: ["minCyclomatic", "minLineCount", "minParameters"] },
|
|
53
|
-
{ 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." },
|
|
54
|
-
{ 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." },
|
|
50
|
+
{ 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"] },
|
|
51
|
+
{ 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"] },
|
|
52
|
+
{ 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"] },
|
|
53
|
+
{ 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"] },
|
|
55
54
|
{ ruleId: "naming.inconsistent-casing", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags the same canonical identifier appearing in two different surface forms (for example CONSTANT_CASE and camelCase) in one file.", remediation: "Choose one form and use it consistently within the file." },
|
|
56
|
-
{ 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." },
|
|
57
|
-
{ 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." },
|
|
55
|
+
{ 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"] },
|
|
56
|
+
{ 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"] },
|
|
58
57
|
{ 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." },
|
|
59
58
|
{ ruleId: "security.disabled-tls-verification", pillar: "security", severity: "error", confidence: "high", description: "Flags code that disables TLS certificate verification.", remediation: "Remove the override and fix certificate trust at the source." },
|
|
60
59
|
{ ruleId: "security.document-write", pillar: "security", severity: "warning", confidence: "high", description: "Flags document.write usage.", remediation: "Use safe DOM APIs and encode untrusted content." },
|
|
@@ -85,15 +84,15 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
85
84
|
{ ruleId: "sensitive-data.api-key-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags vendor API key patterns.", remediation: "Remove the secret and load it from a secure runtime source." },
|
|
86
85
|
{ ruleId: "sensitive-data.aws-access-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags AWS access key looking values.", remediation: "Remove the key and rotate it immediately." },
|
|
87
86
|
{ ruleId: "sensitive-data.database-url-password", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags database URLs that include passwords.", remediation: "Move credentials into a secret store or runtime environment." },
|
|
88
|
-
{ ruleId: "sensitive-data.hardcoded-env-value", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags environment-style secret values committed in text.", remediation: "Load secret-like values from secure runtime configuration.", threshold: 16 },
|
|
89
|
-
{ ruleId: "sensitive-data.high-entropy-string", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags high-entropy string literals that may be secrets.", remediation: "Remove the value and load it from a secure runtime source.", threshold: 32 },
|
|
87
|
+
{ ruleId: "sensitive-data.hardcoded-env-value", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags environment-style secret values committed in text.", remediation: "Load secret-like values from secure runtime configuration. Or raise rules.sensitive-data.hardcoded-env-value.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 16 },
|
|
88
|
+
{ ruleId: "sensitive-data.high-entropy-string", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags high-entropy string literals that may be secrets.", remediation: "Remove the value and load it from a secure runtime source. Or raise rules.sensitive-data.high-entropy-string.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 32 },
|
|
90
89
|
{ ruleId: "sensitive-data.jwt-token", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags JWT-looking token literals.", remediation: "Remove the token and rotate the credential if real." },
|
|
91
90
|
{ ruleId: "sensitive-data.pii-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PII-like identifier patterns.", remediation: "Remove personal data from source and fixtures." },
|
|
92
91
|
{ 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: "warning", confidence: "high", description: "Flags files longer than the configured threshold.", remediation: "Split unrelated responsibilities into smaller files.", threshold: 750 },
|
|
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.", threshold: 200 },
|
|
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.", threshold: 7 },
|
|
96
|
-
{ ruleId: "size.stylesheet-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags stylesheets longer than the configured threshold.", remediation: "Split unrelated component styles into smaller files.", threshold: 1500 },
|
|
92
|
+
{ ruleId: "size.file-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags files longer than 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: 750 },
|
|
93
|
+
{ 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 },
|
|
94
|
+
{ 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 },
|
|
95
|
+
{ ruleId: "size.stylesheet-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags stylesheets longer than the configured threshold.", remediation: "Split unrelated component styles into smaller files. Or raise rules.size.stylesheet-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 1500 },
|
|
97
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." },
|
|
98
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." },
|
|
99
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." },
|
|
@@ -104,25 +103,25 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
104
103
|
{ ruleId: "test-quality.no-assertions", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests without apparent assertions.", remediation: "Add assertions for observable behavior." },
|
|
105
104
|
{ ruleId: "test-quality.no-throw-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only assert code does not throw.", remediation: "Assert the observable result or state change." },
|
|
106
105
|
{ 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." },
|
|
107
|
-
{ ruleId: "test-quality.setup-bloat", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags tests with too much setup before the first assertion.", remediation: "Extract builders or reduce fixture setup.", threshold: 12 },
|
|
106
|
+
{ ruleId: "test-quality.setup-bloat", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags tests with too much setup before the first assertion.", remediation: "Extract builders or reduce fixture setup. Or raise rules.test-quality.setup-bloat.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 12 },
|
|
108
107
|
{ 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." },
|
|
109
108
|
{ 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." },
|
|
110
109
|
{ 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." },
|
|
111
110
|
{ 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." },
|
|
112
|
-
{ ruleId: "waste.any-type", pillar: "
|
|
113
|
-
{ ruleId: "waste.broad-runtime-version", pillar: "
|
|
114
|
-
{ ruleId: "waste.commented-out-code", pillar: "
|
|
115
|
-
{ ruleId: "waste.console-log", pillar: "
|
|
116
|
-
{ ruleId: "waste.empty-function", pillar: "
|
|
117
|
-
{ ruleId: "waste.exported-any", pillar: "
|
|
118
|
-
{ ruleId: "waste.redundant-boolean-cast", pillar: "
|
|
119
|
-
{ ruleId: "waste.redundant-variable", pillar: "
|
|
120
|
-
{ ruleId: "waste.swallowed-catch", pillar: "
|
|
121
|
-
{ ruleId: "waste.useless-catch", pillar: "
|
|
122
|
-
{ ruleId: "waste.useless-return", pillar: "
|
|
123
|
-
{ ruleId: "waste.unreachable-code", pillar: "
|
|
124
|
-
{ ruleId: "waste.unused-import", pillar: "
|
|
125
|
-
{ ruleId: "waste.unused-parameter", pillar: "
|
|
111
|
+
{ ruleId: "waste.any-type", pillar: "maintainability", severity: "warning", confidence: "high", description: "Flags any type usage.", remediation: "Use unknown with validation or a precise type." },
|
|
112
|
+
{ ruleId: "waste.broad-runtime-version", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags broad runtime dependency version ranges.", remediation: "Use bounded semver ranges and lockfiles." },
|
|
113
|
+
{ ruleId: "waste.commented-out-code", pillar: "maintainability", severity: "advisory", confidence: "high", description: "Flags comments that appear to contain disabled code.", remediation: "Delete dead code or restore it behind a real feature path." },
|
|
114
|
+
{ ruleId: "waste.console-log", pillar: "maintainability", severity: "advisory", confidence: "high", description: "Flags console log/debug calls in source.", remediation: "Remove debug logging or route through structured logging." },
|
|
115
|
+
{ ruleId: "waste.empty-function", pillar: "maintainability", severity: "advisory", confidence: "high", description: "Flags functions with no executable body.", remediation: "Delete the function or add the missing implementation." },
|
|
116
|
+
{ ruleId: "waste.exported-any", pillar: "maintainability", severity: "warning", confidence: "medium", description: "Flags exported APIs exposing any.", remediation: "Use a named interface, unknown with validation, or precise generics." },
|
|
117
|
+
{ ruleId: "waste.redundant-boolean-cast", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags redundant boolean casts in condition expressions.", remediation: "Use the condition value directly or name the boolean conversion." },
|
|
118
|
+
{ ruleId: "waste.redundant-variable", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags variables returned immediately after assignment.", remediation: "Return the expression directly." },
|
|
119
|
+
{ ruleId: "waste.swallowed-catch", pillar: "maintainability", severity: "warning", confidence: "medium", description: "Flags empty catch blocks.", remediation: "Handle, report, rethrow, or document intentional ignore paths." },
|
|
120
|
+
{ ruleId: "waste.useless-catch", pillar: "maintainability", severity: "advisory", confidence: "high", description: "Flags catch blocks that only rethrow the caught value.", remediation: "Remove the catch block or add meaningful handling." },
|
|
121
|
+
{ ruleId: "waste.useless-return", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags terminal bare return statements in void functions.", remediation: "Remove the final return statement." },
|
|
122
|
+
{ ruleId: "waste.unreachable-code", pillar: "maintainability", severity: "warning", confidence: "high", description: "Flags statements after terminating statements.", remediation: "Delete unreachable code or restructure the control flow." },
|
|
123
|
+
{ ruleId: "waste.unused-import", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags named imports with no apparent usage.", remediation: "Remove unused imports." },
|
|
124
|
+
{ ruleId: "waste.unused-parameter", pillar: "maintainability", severity: "advisory", confidence: "medium", description: "Flags parameters with no apparent usage.", remediation: "Remove the parameter or prefix it with _ if intentional." },
|
|
126
125
|
];
|
|
127
126
|
|
|
128
127
|
/**
|
package/src/safety-rules.ts
CHANGED
|
@@ -38,7 +38,7 @@ export function analyseUselessCatches(file: SourceFile, source: string, findings
|
|
|
38
38
|
filePath: file.displayPath,
|
|
39
39
|
line: byteLine(source, match.index ?? 0),
|
|
40
40
|
severity: "advisory",
|
|
41
|
-
pillar: "
|
|
41
|
+
pillar: "maintainability",
|
|
42
42
|
confidence: "high",
|
|
43
43
|
remediation: "Remove the catch block or add meaningful handling.",
|
|
44
44
|
metadata: { binding },
|
|
@@ -67,7 +67,7 @@ export function analyseSwallowedCatches(file: SourceFile, rawSource: string, cod
|
|
|
67
67
|
filePath: file.displayPath,
|
|
68
68
|
line: byteLine(rawSource, match.index ?? 0),
|
|
69
69
|
severity: "warning",
|
|
70
|
-
pillar: "
|
|
70
|
+
pillar: "maintainability",
|
|
71
71
|
confidence: "medium",
|
|
72
72
|
remediation: "Handle the error explicitly, rethrow it, or document an intentional ignore path.",
|
|
73
73
|
metadata: { ...(binding ? { binding } : {}) },
|
|
@@ -86,11 +86,16 @@ function rawCatchBody(rawSource: string, codeSource: string, match: RegExpMatchA
|
|
|
86
86
|
|
|
87
87
|
// Comment-only catches are acceptable when the comment gives a rationale such as "already closed",
|
|
88
88
|
// "cache write failure is non-fatal", or "composition continues"; placeholders still surface.
|
|
89
|
+
// The bare-token alternatives (`ignore`, `ignored`, `cleanup`, `teardown`, `noop`, `no-op`) match
|
|
90
|
+
// the most common idioms for documented teardown swallows. `silent` is deliberately NOT included -
|
|
91
|
+
// real swallowed-error defects in goat-flow's dashboard-projects.ts use `/* silent */` and must
|
|
92
|
+
// continue to fire. Deferred-work markers are also excluded - that flavour of placeholder is not
|
|
93
|
+
// "intentional swallow."
|
|
89
94
|
function hasIntentionalCatchRationale(body: string): boolean {
|
|
90
95
|
return (
|
|
91
96
|
/(?:\/\/|\/\*)/.test(body) &&
|
|
92
97
|
(hasSuppressionRationale(body) ||
|
|
93
|
-
/\b(?:already (?:closed|dead|gone)|optional|best effort|missing|unreadable|not a directory|doesn't exist|not available|non-fatal|cache write failure|composition continues|try next location|server unavailable|must not affect|explicit launch|malformed messages|template missing|sets [A-Za-z_$][A-Za-z0-9_$]* = false|skip agents? that fail)\b/i.test(body))
|
|
98
|
+
/\b(?:already (?:closed|dead|gone)|optional|best effort|missing|unreadable|not a directory|doesn't exist|not available|non-fatal|cache write failure|composition continues|try next location|server unavailable|must not affect|explicit launch|malformed messages|template missing|sets [A-Za-z_$][A-Za-z0-9_$]* = false|skip agents? that fail|ignored?|cleanup|teardown|noop|no-op)\b/i.test(body))
|
|
94
99
|
);
|
|
95
100
|
}
|
|
96
101
|
|
|
@@ -180,7 +185,7 @@ function pushExportedAnyFinding(file: SourceFile, codeLine: string, lineNumber:
|
|
|
180
185
|
filePath: file.displayPath,
|
|
181
186
|
line: lineNumber,
|
|
182
187
|
severity: "warning",
|
|
183
|
-
pillar: "
|
|
188
|
+
pillar: "maintainability",
|
|
184
189
|
confidence: "medium",
|
|
185
190
|
symbol: exportedAny,
|
|
186
191
|
remediation: "Use a named interface, unknown plus validation, or a precise generic type.",
|
package/src/scoring.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Score, grade, and fail-on helpers derived from finding severities for reports and CLI exits.
|
|
2
|
-
import { grade } from "./
|
|
2
|
+
import { grade } from "./pillar-summary.ts";
|
|
3
3
|
import type { AnalysisReport, FailThreshold, Finding, Pillar, Severity } from "./types.ts";
|
|
4
4
|
|
|
5
|
-
// Builds the per-pillar and per-file score breakdown that ships in `gruff.analysis.
|
|
6
|
-
// score is the mean of pillar scores so adding a pillar shifts the headline number
|
|
7
|
-
//
|
|
5
|
+
// Builds the per-pillar and per-file score breakdown that ships in `gruff.analysis.v2`. The composite
|
|
6
|
+
// score is the mean of pillar scores so adding a pillar shifts the headline number. `topOffenders` is
|
|
7
|
+
// the full file list sorted worst-first; renderers cap it themselves (HTML/hotspot keep their 10-row
|
|
8
|
+
// UX, summary honours `--top`). The field shape is part of the `gruff.analysis.v2` schema contract.
|
|
8
9
|
function scoreReport(findings: Finding[]): AnalysisReport["score"] {
|
|
9
10
|
const byPillar = new Map<Pillar, Finding[]>();
|
|
10
11
|
const byFile = new Map<string, Finding[]>();
|
|
@@ -14,7 +15,7 @@ function scoreReport(findings: Finding[]): AnalysisReport["score"] {
|
|
|
14
15
|
}
|
|
15
16
|
const pillars = [...byPillar.entries()].map(([pillar, pillarFindings]) => {
|
|
16
17
|
const penalty = pillarFindings.reduce((sum, finding) => sum + severityPenalty(finding.severity), 0);
|
|
17
|
-
return { pillar, score: Math.max(0, 100 - penalty), findings: pillarFindings.length };
|
|
18
|
+
return { pillar, score: Math.max(0, 100 - penalty), penalty, findings: pillarFindings.length };
|
|
18
19
|
});
|
|
19
20
|
const composite = pillars.length === 0 ? 100 : pillars.reduce((sum, pillar) => sum + pillar.score, 0) / pillars.length;
|
|
20
21
|
const topOffenders = [...byFile.entries()]
|
|
@@ -23,13 +24,12 @@ function scoreReport(findings: Finding[]): AnalysisReport["score"] {
|
|
|
23
24
|
score: Math.max(0, 100 - fileFindings.reduce((sum, finding) => sum + severityPenalty(finding.severity), 0)),
|
|
24
25
|
findings: fileFindings.length,
|
|
25
26
|
}))
|
|
26
|
-
.sort((left, right) => left.score - right.score)
|
|
27
|
-
.slice(0, 10);
|
|
27
|
+
.sort((left, right) => left.score - right.score);
|
|
28
28
|
return { composite, grade: grade(composite), pillars, topOffenders };
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
// Severity tallies emitted in the report summary. The four-key shape (advisory/warning/error/total)
|
|
32
|
-
// is part of the `gruff.analysis.
|
|
32
|
+
// is part of the `gruff.analysis.v2` schema and consumers rely on `total` matching the array length.
|
|
33
33
|
function summarize(findings: Finding[]) {
|
|
34
34
|
return {
|
|
35
35
|
advisory: findings.filter((finding) => finding.severity === "advisory").length,
|
|
@@ -71,4 +71,36 @@ function severityPenalty(severity: Severity): number {
|
|
|
71
71
|
return severity === "error" ? 8 : severity === "warning" ? 4 : 1.5;
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
-
|
|
74
|
+
/*
|
|
75
|
+
* Per-severity grade breakdown for the human summary block. The composite headline alone hides the
|
|
76
|
+
* fact that an F can be driven entirely by advisories (goat-flow scan: F at 12.9 with 0 errors / 276
|
|
77
|
+
* warnings / 1367 advisories). Mirrors the existing pillar formula `100 - count * severityPenalty`
|
|
78
|
+
* so the math stays consistent with how a single-rule pillar would score. The schema invariant
|
|
79
|
+
* matters: the composite score and `gruff.analysis.v2` JSON shape stay byte-stable - only the
|
|
80
|
+
* human renderers surface this breakdown.
|
|
81
|
+
*/
|
|
82
|
+
function severityGradeBreakdown(findings: Finding[]): {
|
|
83
|
+
error: { grade: string; score: number; count: number };
|
|
84
|
+
warning: { grade: string; score: number; count: number };
|
|
85
|
+
advisory: { grade: string; score: number; count: number };
|
|
86
|
+
} {
|
|
87
|
+
const counts = { error: 0, warning: 0, advisory: 0 };
|
|
88
|
+
for (const finding of findings) {
|
|
89
|
+
counts[finding.severity] += 1;
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
error: severityBucket("error", counts.error),
|
|
93
|
+
warning: severityBucket("warning", counts.warning),
|
|
94
|
+
advisory: severityBucket("advisory", counts.advisory),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Single severity bucket using the same `score = max(0, 100 - count * penalty)` formula as the
|
|
99
|
+
// pillar reduce in `scoreReport`. Returns the bucket plus its grade letter so renderers don't have
|
|
100
|
+
// to import `grade` separately.
|
|
101
|
+
function severityBucket(severity: Severity, count: number): { grade: string; score: number; count: number } {
|
|
102
|
+
const score = Math.max(0, 100 - count * severityPenalty(severity));
|
|
103
|
+
return { grade: grade(score), score, count };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export { scoreReport, summarize, exitFor, severityGradeBreakdown };
|
package/src/test-block-rules.ts
CHANGED
|
@@ -132,7 +132,7 @@ function analyseSetupBloat(file: SourceFile, block: FunctionBlock, body: string,
|
|
|
132
132
|
function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
133
133
|
const checks: Array<[string, boolean, string]> = [
|
|
134
134
|
["test-quality.sleep-in-test", /\b(setTimeout|sleep|waitForTimeout)\s*\(/.test(body), "Test sleeps instead of synchronising on behaviour."],
|
|
135
|
-
["test-quality.loop-in-test",
|
|
135
|
+
["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic around assertions."],
|
|
136
136
|
["test-quality.conditional-logic", controlFlowContainsAssertion(body, /\b(?:if|switch)\b/g), "Test contains conditional logic around assertions."],
|
|
137
137
|
["test-quality.only-skip", /\.(only|skip)\s*\(/.test(body), "Focused or skipped test is committed."],
|
|
138
138
|
];
|
|
@@ -143,6 +143,48 @@ function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body
|
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
+
// Loop variant of `controlFlowContainsAssertion` that suppresses fixture loops (table-test pattern):
|
|
147
|
+
// loops over a literal array or `Object.entries|keys|values` of a literal where every code path
|
|
148
|
+
// inside the body reaches an assertion. The existing rule fires on ANY loop wrapping an assertion;
|
|
149
|
+
// this widens the precision so parametric coverage doesn't read as control-flow noise.
|
|
150
|
+
function controlFlowContainsNonFixtureLoop(source: string): boolean {
|
|
151
|
+
for (const match of source.matchAll(/\b(?:for|while)\b/g)) {
|
|
152
|
+
const start = match.index ?? 0;
|
|
153
|
+
const segment = controlFlowSegment(source, start);
|
|
154
|
+
if (!hasAssertion(segment)) {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (isFixtureLoop(segment)) {
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// A "fixture loop" is the table-test pattern: iterable is a literal array OR Object.entries/keys/
|
|
166
|
+
// values of a literal, AND every path through the body terminates in an assertion call. Neither
|
|
167
|
+
// applies to `while` loops or C-style `for (;;)`. Conservative on conditional bodies - the presence
|
|
168
|
+
// of any `if`/`switch`/`case`/`default` inside the body opts out so a branch that doesn't assert
|
|
169
|
+
// is not silently classified as a fixture loop.
|
|
170
|
+
function isFixtureLoop(segment: string): boolean {
|
|
171
|
+
const braceIndex = segment.indexOf("{");
|
|
172
|
+
const header = braceIndex === -1 ? segment : segment.slice(0, braceIndex);
|
|
173
|
+
if (!/\bof\s*\[/.test(header) && !/\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
if (braceIndex === -1) {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
const body = segment.slice(braceIndex + 1, segment.length - 1);
|
|
180
|
+
if (/\b(?:if|switch)\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
const statements = body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement));
|
|
184
|
+
const lastStatement = statements[statements.length - 1] ?? "";
|
|
185
|
+
return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
|
|
186
|
+
}
|
|
187
|
+
|
|
146
188
|
// Integration, contract, smoke, and performance tests naturally need more environment setup than
|
|
147
189
|
// focused unit tests; keep the default strict for unit tests and double it for broad-flow suites.
|
|
148
190
|
function setupBloatThreshold(file: SourceFile, config: Config): number {
|
package/src/test-fixtures.ts
CHANGED
|
@@ -105,9 +105,15 @@ export function analyseProjectInCurrentDirectory(options: AnalyseProjectOptions)
|
|
|
105
105
|
});
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
-
|
|
108
|
+
/*
|
|
109
|
+
* Serializes a test YAML config object from the root indentation level. Every fixture YAML is
|
|
110
|
+
* stamped with the required `schemaVersion: gruff-ts.config.v0.1` field at the top (per ADR-004)
|
|
111
|
+
* because the config loader throws when it's missing. The schema invariant is preserved by
|
|
112
|
+
* spreading the input object AFTER schemaVersion so callers can't accidentally override it; tests
|
|
113
|
+
* that need to assert against a missing schemaVersion must write the YAML by hand instead.
|
|
114
|
+
*/
|
|
109
115
|
export function yamlConfigFixture(configObject: Record<string, unknown>): string {
|
|
110
|
-
return yamlConfigObject(configObject, 0);
|
|
116
|
+
return yamlConfigObject({ schemaVersion: "gruff-ts.config.v0.1", ...configObject }, 0);
|
|
111
117
|
}
|
|
112
118
|
|
|
113
119
|
// Serializes nested config objects using the fixture YAML subset.
|
|
@@ -458,7 +464,7 @@ export function process(flag: boolean, userInput: string, userId: string, userId
|
|
|
458
464
|
try {
|
|
459
465
|
riskyWork();
|
|
460
466
|
} catch (error) {
|
|
461
|
-
//
|
|
467
|
+
// FIXME
|
|
462
468
|
}
|
|
463
469
|
if (flag) {
|
|
464
470
|
if (userId) {
|
|
@@ -588,8 +594,10 @@ ${"test"}("setup bloat and control flow", () => {
|
|
|
588
594
|
const three = buildThree();
|
|
589
595
|
if (one) {
|
|
590
596
|
for (const setupEntry of [one, two, three]) {
|
|
591
|
-
|
|
592
|
-
|
|
597
|
+
if (setupEntry) {
|
|
598
|
+
sleep(setupEntry);
|
|
599
|
+
assert.ok(setupEntry);
|
|
600
|
+
}
|
|
593
601
|
}
|
|
594
602
|
}
|
|
595
603
|
setTimeout(() => undefined, 1);
|
|
@@ -608,8 +616,6 @@ function catalogueCoverageOptions(): AnalyseProjectOptions {
|
|
|
608
616
|
"complexity.cyclomatic": { threshold: 2, severity: "warning" },
|
|
609
617
|
"complexity.npath": { threshold: 2, severity: "warning" },
|
|
610
618
|
"design.large-module-concentration": { threshold: 35, severity: "advisory", options: { minFiles: 4, minLines: 8 } },
|
|
611
|
-
"docs.todo-density": { enabled: true, threshold: 1, severity: "advisory" },
|
|
612
|
-
"naming.abbreviation": { enabled: true },
|
|
613
619
|
"size.file-length": { threshold: 8, severity: "warning" },
|
|
614
620
|
"size.function-length": { threshold: 8, severity: "warning" },
|
|
615
621
|
"size.parameter-count": { threshold: 3, severity: "warning" },
|