@blundergoat/gruff-ts 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +80 -12
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +21 -2
- package/docs/output-formats.md +10 -0
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +5 -5
- package/docs/rules.md +24 -15
- package/package.json +5 -5
- package/scripts/bump-version.sh +1 -1
- package/src/analyser.ts +43 -30
- package/src/blocks.ts +20 -67
- package/src/changed-regions.ts +390 -0
- package/src/check-ignore.ts +49 -0
- package/src/class-rules.ts +80 -33
- package/src/cli-program.ts +105 -11
- package/src/comment-rules.ts +4 -0
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +1 -1
- package/src/config.ts +215 -460
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +7 -4
- package/src/discovery.ts +88 -32
- package/src/findings-helpers.ts +41 -5
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +3 -0
- package/src/naming-pushers.ts +35 -6
- package/src/profiles.ts +232 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +2 -1
- package/src/report-html.ts +1 -1
- package/src/report-renderers.ts +58 -0
- package/src/rule-list.ts +22 -1
- package/src/rules.ts +10 -10
- package/src/safety-rules.ts +16 -6
- package/src/scoring.ts +43 -5
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/test-block-rules.ts +106 -15
- package/src/test-fixtures.ts +46 -8
- package/src/types.ts +78 -2
package/src/profiles.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// Built-in gruff profile presets: the named rule selections that `profile:` / `--profile` resolve.
|
|
2
|
+
// Each preset is a compact, fully readable definition - a reviewer scans all three in one pass.
|
|
3
|
+
// Profiles select rules by PILLAR (gruff's taxonomy is pillar-based) and layer explicit per-rule
|
|
4
|
+
// threshold tightenings on top; `src/config.ts`:`resolveProfile` expands these against
|
|
5
|
+
// `RULE_DESCRIPTORS` at config-load time and validates every rule-id reference. This module owns the
|
|
6
|
+
// canonical rule list (via `ruleDescriptors`) so `config.ts` need not import `rules.ts` directly.
|
|
7
|
+
import { ruleDescriptors } from "./rules.ts";
|
|
8
|
+
import type { Pillar, ProfileDefinition, ProfileRuleSetting, Severity } from "./types.ts";
|
|
9
|
+
|
|
10
|
+
// The eleven pillars listed explicitly so `recommended`/`strict` enable the whole catalogue without
|
|
11
|
+
// referencing an implicit "all rules" default - the selection is greppable here, not derived elsewhere.
|
|
12
|
+
const ALL_PILLARS: readonly Pillar[] = [
|
|
13
|
+
"complexity",
|
|
14
|
+
"dead-code",
|
|
15
|
+
"design",
|
|
16
|
+
"documentation",
|
|
17
|
+
"maintainability",
|
|
18
|
+
"modernisation",
|
|
19
|
+
"naming",
|
|
20
|
+
"security",
|
|
21
|
+
"sensitive-data",
|
|
22
|
+
"size",
|
|
23
|
+
"test-quality",
|
|
24
|
+
] as const;
|
|
25
|
+
|
|
26
|
+
// The name applied when neither the CLI flag nor the config file names a profile, and the implicit
|
|
27
|
+
// base for an inline `profile:` block that omits `extends:`. `recommended` flattens to an empty delta,
|
|
28
|
+
// so "no profile" and "profile: recommended" are behaviourally identical (the parity contract).
|
|
29
|
+
const DEFAULT_PROFILE_NAME = "gruff.recommended";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A built-in profile preset in its compact, readable source form. `enabledPillars` selects which
|
|
33
|
+
* pillars' rules fire; every rule outside that set is disabled. `thresholds` and `severities` are
|
|
34
|
+
* explicit per-rule tightenings layered on the enabled set. Keeping presets pillar-keyed (plus a
|
|
35
|
+
* short override list) means a reviewer reads the intent in one pass, and the rule-id references in
|
|
36
|
+
* `thresholds`/`severities` are validated against `RULE_DESCRIPTORS` when this module loads.
|
|
37
|
+
*/
|
|
38
|
+
export interface BuiltInProfile {
|
|
39
|
+
name: string;
|
|
40
|
+
description: string;
|
|
41
|
+
enabledPillars: readonly Pillar[];
|
|
42
|
+
thresholds: Readonly<Record<string, number>>;
|
|
43
|
+
severities: Readonly<Record<string, Severity>>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// One-line digest of a built-in profile for the `list-profiles` command. Carries the enabled/total
|
|
47
|
+
// rule counts and the pillar selection so operators can compare presets without resolving each one.
|
|
48
|
+
export interface ProfileSummary {
|
|
49
|
+
name: string;
|
|
50
|
+
description: string;
|
|
51
|
+
enabledRuleCount: number;
|
|
52
|
+
totalRuleCount: number;
|
|
53
|
+
enabledPillars: readonly Pillar[];
|
|
54
|
+
tightenedThresholdCount: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/*
|
|
58
|
+
* The three built-in presets in source form. This array IS the readable preset catalogue the kill
|
|
59
|
+
* criteria require: minimal (sanity/security only), recommended (current default behaviour, a no-op
|
|
60
|
+
* delta), strict (every pillar enabled with tightened size/complexity/secret thresholds). Strict only
|
|
61
|
+
* tightens thresholds - it enables no new rule, because recommended already enables the whole
|
|
62
|
+
* catalogue - so a strict scan reports at least as many findings as recommended, never fewer.
|
|
63
|
+
*/
|
|
64
|
+
const BUILT_IN_PROFILE_SPECS: readonly BuiltInProfile[] = [
|
|
65
|
+
{
|
|
66
|
+
name: "gruff.minimal",
|
|
67
|
+
description: "Security and sensitive-data rules only - the smallest sanity gate for adopting gruff incrementally.",
|
|
68
|
+
enabledPillars: ["security", "sensitive-data"],
|
|
69
|
+
thresholds: {},
|
|
70
|
+
severities: {},
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
name: "gruff.recommended",
|
|
74
|
+
description: "Every pillar at its default threshold and severity - identical to gruff's zero-config behaviour.",
|
|
75
|
+
enabledPillars: ALL_PILLARS,
|
|
76
|
+
thresholds: {},
|
|
77
|
+
severities: {},
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
name: "gruff.strict",
|
|
81
|
+
description: "Every pillar enabled with tightened size, complexity, and secret thresholds for high-bar repositories.",
|
|
82
|
+
enabledPillars: ALL_PILLARS,
|
|
83
|
+
thresholds: {
|
|
84
|
+
"complexity.cognitive": 10,
|
|
85
|
+
"complexity.cyclomatic": 10,
|
|
86
|
+
"design.deep-relative-import": 1,
|
|
87
|
+
"design.large-module-concentration": 40,
|
|
88
|
+
"size.file-length": 400,
|
|
89
|
+
"size.function-length": 60,
|
|
90
|
+
"size.parameter-count": 4,
|
|
91
|
+
"sensitive-data.hardcoded-env-value": 12,
|
|
92
|
+
"sensitive-data.high-entropy-string": 24,
|
|
93
|
+
"test-quality.setup-bloat": 8,
|
|
94
|
+
},
|
|
95
|
+
severities: {},
|
|
96
|
+
},
|
|
97
|
+
] as const;
|
|
98
|
+
|
|
99
|
+
// Canonical rule catalogue, captured once at module load. Sorted for determinism so flattened
|
|
100
|
+
// profiles and `list-profiles` output never churn between runs.
|
|
101
|
+
const DESCRIPTORS = ruleDescriptors();
|
|
102
|
+
|
|
103
|
+
// Every rule id gruff recognises. Exported so `config.ts` can reject a user profile that references a
|
|
104
|
+
// rule outside the catalogue at load time (a preset typo would otherwise silently no-op at scan time).
|
|
105
|
+
const KNOWN_RULE_IDS: ReadonlySet<string> = new Set(DESCRIPTORS.map((descriptor) => descriptor.ruleId));
|
|
106
|
+
|
|
107
|
+
// Map from rule id to its pillar, used when validating that a preset's threshold/severity override
|
|
108
|
+
// targets a rule inside one of the preset's enabled pillars (a dead override otherwise).
|
|
109
|
+
const RULE_PILLARS: ReadonlyMap<string, Pillar> = new Map(DESCRIPTORS.map((descriptor) => [descriptor.ruleId, descriptor.pillar]));
|
|
110
|
+
|
|
111
|
+
/*
|
|
112
|
+
* Expands one compact preset into a flattened ProfileDefinition: a rule-id keyed delta from the
|
|
113
|
+
* descriptor defaults. Rules outside the enabled pillars get an explicit `{ enabled: false }`; enabled
|
|
114
|
+
* rules with a threshold/severity override get that override; enabled rules at their default are
|
|
115
|
+
* OMITTED so the delta stays minimal and `recommended` flattens to an empty map (the parity contract).
|
|
116
|
+
* Throws if any override key is unknown or targets a disabled pillar - this is the load-time
|
|
117
|
+
* validation the kill criteria require.
|
|
118
|
+
*/
|
|
119
|
+
function profileDefinitionFromSpec(spec: BuiltInProfile): ProfileDefinition {
|
|
120
|
+
assertOverrideKeys(spec);
|
|
121
|
+
const enabledPillars = new Set<Pillar>(spec.enabledPillars);
|
|
122
|
+
const rules = new Map<string, ProfileRuleSetting>();
|
|
123
|
+
for (const descriptor of DESCRIPTORS) {
|
|
124
|
+
if (!enabledPillars.has(descriptor.pillar)) {
|
|
125
|
+
rules.set(descriptor.ruleId, { enabled: false });
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const setting = enabledRuleSetting(spec, descriptor.ruleId);
|
|
129
|
+
if (setting) {
|
|
130
|
+
rules.set(descriptor.ruleId, setting);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { name: spec.name, rules, ignoredPaths: [] };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Builds the override entry for an enabled rule, or undefined when the rule sits at its descriptor
|
|
137
|
+
// default (so the flattened delta omits it). Threshold and severity are independent optional knobs.
|
|
138
|
+
function enabledRuleSetting(spec: BuiltInProfile, ruleId: string): ProfileRuleSetting | undefined {
|
|
139
|
+
const threshold = spec.thresholds[ruleId];
|
|
140
|
+
const severity = spec.severities[ruleId];
|
|
141
|
+
if (threshold === undefined && severity === undefined) {
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
enabled: true,
|
|
146
|
+
...(threshold !== undefined ? { threshold } : {}),
|
|
147
|
+
...(severity !== undefined ? { severity } : {}),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/*
|
|
152
|
+
* Validates a preset's override keys at load time. Every key in `thresholds`/`severities` must be a
|
|
153
|
+
* real rule id (caught by `KNOWN_RULE_IDS`) and must live in one of the preset's enabled pillars - a
|
|
154
|
+
* threshold on a disabled rule would never fire and signals a preset authoring mistake. Throws a plain
|
|
155
|
+
* Error (not ConfigLoadError) because this is an internal contract on bundled presets, not user input.
|
|
156
|
+
*/
|
|
157
|
+
function assertOverrideKeys(spec: BuiltInProfile): void {
|
|
158
|
+
const enabledPillars = new Set<Pillar>(spec.enabledPillars);
|
|
159
|
+
for (const ruleId of [...Object.keys(spec.thresholds), ...Object.keys(spec.severities)]) {
|
|
160
|
+
const pillar = RULE_PILLARS.get(ruleId);
|
|
161
|
+
if (pillar === undefined) {
|
|
162
|
+
throw new Error(`Built-in profile "${spec.name}" references unknown rule id "${ruleId}". Every override key must be in RULE_DESCRIPTORS.`);
|
|
163
|
+
}
|
|
164
|
+
if (!enabledPillars.has(pillar)) {
|
|
165
|
+
throw new Error(`Built-in profile "${spec.name}" overrides "${ruleId}" but its pillar "${pillar}" is not enabled. The override would never fire.`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The bundled profile catalogue, keyed by name. Values are the flattened ProfileDefinitions that
|
|
172
|
+
* `resolveProfile` clones and overlays. Built once at module load, which is where preset rule-id
|
|
173
|
+
* references are validated - so an authoring mistake fails fast on import, never silently at scan time.
|
|
174
|
+
*/
|
|
175
|
+
export const BUILT_IN_PROFILES: ReadonlyMap<string, ProfileDefinition> = new Map(
|
|
176
|
+
BUILT_IN_PROFILE_SPECS.map((spec) => [spec.name, profileDefinitionFromSpec(spec)]),
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Reports whether a rule id is part of gruff's catalogue. Used by the profile resolver to reject a
|
|
181
|
+
* user profile that names a rule outside `RULE_DESCRIPTORS` before any scan runs.
|
|
182
|
+
*
|
|
183
|
+
* @param ruleId Candidate rule id from a user profile's `rules:` block.
|
|
184
|
+
* @returns True when the id is a known rule, false otherwise.
|
|
185
|
+
*/
|
|
186
|
+
export function isKnownRuleId(ruleId: string): boolean {
|
|
187
|
+
return KNOWN_RULE_IDS.has(ruleId);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Returns the built-in profile names in catalogue order for error messages and CLI hints.
|
|
192
|
+
*
|
|
193
|
+
* @returns The bundled profile names, e.g. `["gruff.minimal", "gruff.recommended", "gruff.strict"]`.
|
|
194
|
+
*/
|
|
195
|
+
export function builtInProfileNames(): string[] {
|
|
196
|
+
return BUILT_IN_PROFILE_SPECS.map((spec) => spec.name);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Builds the one-line digest of every built-in profile for the `list-profiles` command.
|
|
201
|
+
*
|
|
202
|
+
* @returns Per-profile summaries with enabled/total rule counts, pillar selection, and threshold count.
|
|
203
|
+
*/
|
|
204
|
+
export function profileSummaries(): ProfileSummary[] {
|
|
205
|
+
const totalRuleCount = DESCRIPTORS.length;
|
|
206
|
+
return BUILT_IN_PROFILE_SPECS.map((spec) => {
|
|
207
|
+
const definition = BUILT_IN_PROFILES.get(spec.name);
|
|
208
|
+
const disabledCount = definition ? countDisabledRules(definition) : 0;
|
|
209
|
+
return {
|
|
210
|
+
name: spec.name,
|
|
211
|
+
description: spec.description,
|
|
212
|
+
enabledRuleCount: totalRuleCount - disabledCount,
|
|
213
|
+
totalRuleCount,
|
|
214
|
+
enabledPillars: spec.enabledPillars,
|
|
215
|
+
tightenedThresholdCount: Object.keys(spec.thresholds).length,
|
|
216
|
+
};
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Counts the rules a flattened profile explicitly disables, so the enabled count is the catalogue
|
|
221
|
+
// size minus the disables (enabled-at-default rules are omitted from the delta and stay enabled).
|
|
222
|
+
function countDisabledRules(definition: ProfileDefinition): number {
|
|
223
|
+
let disabled = 0;
|
|
224
|
+
for (const setting of definition.rules.values()) {
|
|
225
|
+
if (setting.enabled === false) {
|
|
226
|
+
disabled += 1;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return disabled;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export { DEFAULT_PROFILE_NAME };
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { existsSync, statSync } from "node:fs";
|
|
3
3
|
import { basename, dirname as dirnamePath, isAbsolute, join } from "node:path";
|
|
4
4
|
import { platform } from "node:process";
|
|
5
|
-
import { isString, objectValue } from "./config.ts";
|
|
5
|
+
import { isString, objectValue } from "./config-parse.ts";
|
|
6
6
|
import { makeFinding } from "./findings.ts";
|
|
7
7
|
import { firstLine } from "./text-scans.ts";
|
|
8
8
|
import type { Finding } from "./types.ts";
|
|
@@ -166,7 +166,7 @@ function pushUrlDependencyFinding(
|
|
|
166
166
|
findings.push(
|
|
167
167
|
makeFinding({
|
|
168
168
|
ruleId: "security.url-dependency",
|
|
169
|
-
message: `Dependency \`${packageName}\` in \`${section}\` installs from a URL or
|
|
169
|
+
message: `Dependency \`${packageName}\` in \`${section}\` installs from a URL, git, or local file spec.`,
|
|
170
170
|
filePath: file.displayPath,
|
|
171
171
|
line: jsonKeyLine(source, packageName),
|
|
172
172
|
severity: "warning",
|
|
@@ -405,10 +405,10 @@ function isLifecycleScript(scriptName: string): boolean {
|
|
|
405
405
|
return ["preinstall", "install", "postinstall", "prepare", "prepublish", "prepublishOnly"].includes(scriptName);
|
|
406
406
|
}
|
|
407
407
|
|
|
408
|
-
// Recognises non-registry installs: full URLs, git+ssh, and
|
|
409
|
-
//
|
|
408
|
+
// Recognises non-registry installs: full URLs, git+ssh, file:, and npm-hosting shortcuts.
|
|
409
|
+
// These specs cannot be reproducibly locked the way registry versions can.
|
|
410
410
|
function isUrlDependency(versionSpec: string): boolean {
|
|
411
|
-
return /^(?:https?:\/\/|git(?:\+https?|\+ssh)?:\/\/|ssh:\/\/|github:|gitlab:|bitbucket:|git@[^:]+:[^/]+\/|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$)/i.test(versionSpec);
|
|
411
|
+
return /^(?:https?:\/\/|git(?:\+https?|\+ssh)?:\/\/|ssh:\/\/|github:|gitlab:|bitbucket:|file:|git@[^:]+:[^/]+\/|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$)/i.test(versionSpec);
|
|
412
412
|
}
|
|
413
413
|
|
|
414
414
|
// Catches `*`, `x`, `latest`, unbounded `>=` ranges, and OR-joined ranges. All let dependency
|
package/src/project-rules.ts
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// every rule pass shares. Pulls the project-index types and the rules that consume them out of cli.ts
|
|
4
4
|
// so the orchestrator stays lean.
|
|
5
5
|
import { basename, dirname as dirnamePath, extname, join } from "node:path";
|
|
6
|
-
import { isString
|
|
6
|
+
import { isString } from "./config-parse.ts";
|
|
7
|
+
import { optionNumber, ruleSeverity, threshold } from "./config.ts";
|
|
7
8
|
import { type SourceFile } from "./discovery.ts";
|
|
8
9
|
import { makeFinding } from "./findings.ts";
|
|
9
10
|
import { fileBaseName } from "./findings-helpers.ts";
|
package/src/report-html.ts
CHANGED
|
@@ -58,7 +58,7 @@ ${bodySections}
|
|
|
58
58
|
// contract surface - operators eyeball it to confirm the report shape they expect.
|
|
59
59
|
function htmlMasthead(report: AnalysisReport): string {
|
|
60
60
|
const paths = report.paths.analysedFiles === 0 ? "." : `${report.paths.analysedFiles} analysed ${report.paths.analysedFiles === 1 ? "file" : "files"}`;
|
|
61
|
-
return `<header class="masthead"><div class="brand"><div class="wordmark">gruff</div><div class="tagline">ts/js code
|
|
61
|
+
return `<header class="masthead"><div class="brand"><div class="wordmark">gruff</div><div class="tagline">ts/js code - inspected for human sign-off</div></div><div class="meta">${htmlMetaRow("paths", paths)}${htmlMetaRow("format", report.run.format)}${htmlMetaRow("fail", report.run.failOn)}${htmlMetaRow("schema", report.schemaVersion)}<div class="inspection-id">gruff-ts ${escapeHtml(report.tool.version)}</div></div></header>`;
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
// Single key/value row. Both inputs are escaped - they reach this function as user-influenced
|
package/src/report-renderers.ts
CHANGED
|
@@ -191,6 +191,7 @@ function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: s
|
|
|
191
191
|
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
192
192
|
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
193
193
|
` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
194
|
+
...renderComplexityClusterLines(report.findings, top),
|
|
194
195
|
`Findings: ${report.summary.total} total, ${report.summary.error} error, ${report.summary.warning} warning, ${report.summary.advisory} advisory`,
|
|
195
196
|
`Analysed files: ${report.paths.analysedFiles}`,
|
|
196
197
|
...(report.baseline ? [summaryBaselineLine(report.baseline)] : []),
|
|
@@ -386,6 +387,7 @@ function renderText(report: AnalysisReport): string {
|
|
|
386
387
|
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
387
388
|
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
388
389
|
` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
390
|
+
...renderComplexityClusterLines(report.findings),
|
|
389
391
|
`Analysed files: ${report.paths.analysedFiles}`,
|
|
390
392
|
];
|
|
391
393
|
if (report.diagnostics.length > 0) {
|
|
@@ -417,6 +419,7 @@ function renderMarkdown(report: AnalysisReport): string {
|
|
|
417
419
|
`- Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
418
420
|
`- Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
419
421
|
`- Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
422
|
+
...renderMarkdownComplexityClusterLines(report.findings),
|
|
420
423
|
"",
|
|
421
424
|
`Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error.`,
|
|
422
425
|
"",
|
|
@@ -460,6 +463,61 @@ function escapeMarkdownCell(cell: string): string {
|
|
|
460
463
|
return cell.replaceAll("|", "\\|");
|
|
461
464
|
}
|
|
462
465
|
|
|
466
|
+
// Render-only summary of overlapping complexity findings for one function symbol.
|
|
467
|
+
interface ComplexityCluster {
|
|
468
|
+
filePath: string;
|
|
469
|
+
symbol: string;
|
|
470
|
+
ruleIds: string[];
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cognitive", "complexity.cyclomatic", "size.function-length"]);
|
|
474
|
+
|
|
475
|
+
// Invariant: text output surfaces linked complexity clusters without changing JSON report shape.
|
|
476
|
+
function renderComplexityClusterLines(findings: Finding[], limit = 10): string[] {
|
|
477
|
+
const clusters = complexityClusters(findings).slice(0, limit);
|
|
478
|
+
if (clusters.length === 0) {
|
|
479
|
+
return [];
|
|
480
|
+
}
|
|
481
|
+
return [
|
|
482
|
+
"Correlated complexity clusters:",
|
|
483
|
+
...clusters.map((cluster) => `- ${cluster.filePath}#${cluster.symbol}: ${cluster.ruleIds.length} linked findings (${cluster.ruleIds.join(", ")})`),
|
|
484
|
+
];
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// Invariant: markdown mirrors text complexity clusters without adding JSON fields.
|
|
488
|
+
function renderMarkdownComplexityClusterLines(findings: Finding[]): string[] {
|
|
489
|
+
const clusters = complexityClusters(findings);
|
|
490
|
+
if (clusters.length === 0) {
|
|
491
|
+
return [];
|
|
492
|
+
}
|
|
493
|
+
return [
|
|
494
|
+
"",
|
|
495
|
+
"## Correlated Complexity Clusters",
|
|
496
|
+
"",
|
|
497
|
+
...clusters.map((cluster) => `- \`${cluster.filePath}#${cluster.symbol}\`: ${cluster.ruleIds.length} linked findings (${cluster.ruleIds.map((ruleId) => `\`${ruleId}\``).join(", ")})`),
|
|
498
|
+
];
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// Groups correlated complexity findings by file and symbol so renderers can explain score overlap.
|
|
502
|
+
function complexityClusters(findings: Finding[]): ComplexityCluster[] {
|
|
503
|
+
const bySymbol = new Map<string, ComplexityCluster>();
|
|
504
|
+
for (const finding of findings) {
|
|
505
|
+
if (!finding.symbol || !CORRELATED_COMPLEXITY_RULE_IDS.has(finding.ruleId)) {
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
const key = `${finding.filePath}\0${finding.symbol}`;
|
|
509
|
+
const cluster = bySymbol.get(key) ?? { filePath: finding.filePath, symbol: finding.symbol, ruleIds: [] };
|
|
510
|
+
if (!cluster.ruleIds.includes(finding.ruleId)) {
|
|
511
|
+
cluster.ruleIds.push(finding.ruleId);
|
|
512
|
+
}
|
|
513
|
+
bySymbol.set(key, cluster);
|
|
514
|
+
}
|
|
515
|
+
return [...bySymbol.values()]
|
|
516
|
+
.filter((cluster) => cluster.ruleIds.length >= 2)
|
|
517
|
+
.map((cluster) => ({ ...cluster, ruleIds: cluster.ruleIds.sort() }))
|
|
518
|
+
.sort((left, right) => right.ruleIds.length - left.ruleIds.length || left.filePath.localeCompare(right.filePath) || left.symbol.localeCompare(right.symbol));
|
|
519
|
+
}
|
|
520
|
+
|
|
463
521
|
// GitHub Actions `::workflow command` syntax. Public contract invariant: file/title properties
|
|
464
522
|
// must be normalized and command-escaped before interpolation because commas and colons delimit the property list.
|
|
465
523
|
function renderGithub(report: AnalysisReport): string {
|
package/src/rule-list.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Console command catalogue, shell completion scripts, and rule-list renderers for CLI surfaces.
|
|
2
2
|
import { VERSION } from "./constants.ts";
|
|
3
|
+
import { profileSummaries, type ProfileSummary } from "./profiles.ts";
|
|
3
4
|
import { ruleDescriptors } from "./rules.ts";
|
|
4
5
|
import type { RuleDescriptor } from "./types.ts";
|
|
5
6
|
|
|
@@ -24,6 +25,7 @@ const CONSOLE_COMMANDS = [
|
|
|
24
25
|
{ name: "help", description: "Display help for a command" },
|
|
25
26
|
{ name: "init", description: "Write the default .gruff-ts.yaml to the current directory." },
|
|
26
27
|
{ name: "list", description: "List commands" },
|
|
28
|
+
{ name: "list-profiles", description: "List the built-in gruff profiles." },
|
|
27
29
|
{ name: "list-rules", description: "List gruff rule metadata." },
|
|
28
30
|
{ name: "report", description: "Render a gruff report to stdout or a file." },
|
|
29
31
|
{
|
|
@@ -49,6 +51,25 @@ function renderRuleList(format: RuleListFormat): string {
|
|
|
49
51
|
return `${lines.join("\n")}\n`;
|
|
50
52
|
}
|
|
51
53
|
|
|
54
|
+
// Profile catalogue renderer. Mirrors renderRuleList: JSON is the integration surface for docs and
|
|
55
|
+
// audits, and row formatting lives in profileListRow. The text form is kept deliberately plain
|
|
56
|
+
// because it is only for terminal inspection and should not become a second schema.
|
|
57
|
+
function renderProfileList(format: RuleListFormat): string {
|
|
58
|
+
const summaries = profileSummaries();
|
|
59
|
+
if (format === "json") {
|
|
60
|
+
return `${JSON.stringify({ tool: { name: "gruff-ts", version: VERSION }, profiles: summaries }, null, 2)}\n`;
|
|
61
|
+
}
|
|
62
|
+
const header = ["gruff-ts " + VERSION + ` profiles (${summaries.length})`, ""];
|
|
63
|
+
return `${[...header, ...summaries.map(profileListRow)].join("\n")}\n`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// One text row per profile: name, enabled/total rule count, pillar count, an optional tightened-threshold
|
|
67
|
+
// count, and the description. The tightened-threshold segment only appears for presets that set one.
|
|
68
|
+
function profileListRow(summary: ProfileSummary): string {
|
|
69
|
+
const tightened = summary.tightenedThresholdCount > 0 ? ` | tightened thresholds: ${summary.tightenedThresholdCount}` : "";
|
|
70
|
+
return `${summary.name} | ${summary.enabledRuleCount}/${summary.totalRuleCount} rules | ${summary.enabledPillars.length} pillars${tightened} | ${summary.description}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
52
73
|
/*
|
|
53
74
|
* Returns a single rule descriptor by ID, or undefined when the ID is not registered. Surfaced so
|
|
54
75
|
* the explain-mode renderer can dispatch on "is this a real rule?" without iterating the full
|
|
@@ -240,4 +261,4 @@ function completionShell(shellName: unknown): CompletionShell {
|
|
|
240
261
|
}
|
|
241
262
|
|
|
242
263
|
export type { RuleListFormat, CompletionShell };
|
|
243
|
-
export { renderRuleList, renderRuleDetail, getRuleDescriptor, renderConsoleList, renderCompletionScript, completionShell };
|
|
264
|
+
export { renderRuleList, renderProfileList, renderRuleDetail, getRuleDescriptor, renderConsoleList, renderCompletionScript, completionShell };
|
package/src/rules.ts
CHANGED
|
@@ -3,12 +3,9 @@ import type { RuleDescriptor } from "./types.ts";
|
|
|
3
3
|
|
|
4
4
|
const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
5
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
|
-
{ 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." },
|
|
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 }, { 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
7
|
{ 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
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 },
|
|
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
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"] },
|
|
13
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." },
|
|
14
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." },
|
|
@@ -45,7 +42,7 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
45
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." },
|
|
46
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." },
|
|
47
44
|
{ 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
|
|
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: "Use prefixes such as is, has, can, should, or will. Or extend allowlists.booleanPrefixes / allowlists.acceptedBooleanNames for project-specific contract names.", allowlistKeys: ["booleanPrefixes", "acceptedBooleanNames"] },
|
|
49
46
|
{ 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." },
|
|
50
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"] },
|
|
51
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"] },
|
|
@@ -79,20 +76,23 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
79
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." },
|
|
80
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." },
|
|
81
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." },
|
|
82
|
-
{ ruleId: "security.
|
|
79
|
+
{ ruleId: "security.unsafe-deserialization", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input reaching unsafe deserialization or dynamic code-loading sinks.", remediation: "Use schema-bound parsers or validate and decode data without executing code." },
|
|
80
|
+
{ ruleId: "security.url-dependency", pillar: "security", severity: "warning", confidence: "medium", description: "Flags dependencies installed from URL, git, or local file specs.", remediation: "Prefer registry versions that can be locked and audited." },
|
|
83
81
|
{ ruleId: "security.weak-crypto", pillar: "security", severity: "warning", confidence: "high", description: "Flags weak crypto primitives such as md5, sha1, or createCipher.", remediation: "Use modern algorithms and authenticated encryption." },
|
|
84
|
-
{ ruleId: "
|
|
82
|
+
{ ruleId: "security.xxe-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external XML reaching parsers configured to expand entities.", remediation: "Disable external entity expansion and use hardened XML parser options." },
|
|
83
|
+
{ ruleId: "sensitive-data.api-key-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags vendor API key patterns including GitHub, GitLab, npm, Google API, Slack, Discord, and Stripe/OpenAI-style keys.", remediation: "Remove the secret and load it from a secure runtime source." },
|
|
85
84
|
{ 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." },
|
|
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." },
|
|
85
|
+
{ ruleId: "sensitive-data.database-url-password", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags database and HTTP(S) URLs that include passwords or embedded credentials.", remediation: "Move credentials into a secret store or runtime environment." },
|
|
86
|
+
{ ruleId: "sensitive-data.gcp-service-account-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags GCP service-account key files (type service_account alongside a private key).", remediation: "Remove the service-account key from source and rotate it; load credentials from a secure runtime source." },
|
|
87
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
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 },
|
|
89
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." },
|
|
90
|
-
{ ruleId: "sensitive-data.
|
|
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
|
+
{ 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." },
|
|
91
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." },
|
|
92
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. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 750 },
|
|
93
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 },
|
|
94
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 },
|
|
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 },
|
|
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." },
|
package/src/safety-rules.ts
CHANGED
|
@@ -12,7 +12,7 @@ import type { Finding } from "./types.ts";
|
|
|
12
12
|
export function analyseTypeSafetyLine(file: SourceFile, line: string, codeLine: string, lineNumber: number, findings: Finding[]): void {
|
|
13
13
|
pushTsDirectiveFinding(file, line, lineNumber, findings);
|
|
14
14
|
pushNonNullAssertionFindings(file, codeLine, lineNumber, findings);
|
|
15
|
-
pushDoubleCastFindings(file, codeLine, lineNumber, findings);
|
|
15
|
+
pushDoubleCastFindings(file, line, codeLine, lineNumber, findings);
|
|
16
16
|
pushExportedAnyFinding(file, codeLine, lineNumber, findings);
|
|
17
17
|
}
|
|
18
18
|
|
|
@@ -146,28 +146,38 @@ function pushNonNullAssertionFindings(file: SourceFile, codeLine: string, lineNu
|
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
// `as unknown as Foo` and `as any as Foo` double-cast patterns.
|
|
150
|
-
//
|
|
151
|
-
|
|
149
|
+
// `as unknown as Foo` and `as any as Foo` double-cast patterns. Why: the rationale branch keeps
|
|
150
|
+
// boundary casts visible without scoring a documented TS2352/validator hop like an unexplained
|
|
151
|
+
// bypass because typed parser migrations often land later; invariant: never throws and emits stable metadata.
|
|
152
|
+
function pushDoubleCastFindings(file: SourceFile, rawLine: string, codeLine: string, lineNumber: number, findings: Finding[]): void {
|
|
152
153
|
for (const match of codeLine.matchAll(/\bas\s+(unknown|any)\s+as\s+([^;,\n]+)/g)) {
|
|
153
154
|
const sourceType = match[1] ?? "";
|
|
154
155
|
const targetType = (match[2] ?? "").trim().replace(/[.)]+$/, "");
|
|
156
|
+
const hasRationale = hasDoubleCastTrustBoundaryRationale(rawLine);
|
|
155
157
|
findings.push(
|
|
156
158
|
makeFinding({
|
|
157
159
|
ruleId: "modernisation.double-cast",
|
|
158
160
|
message: `Double cast through \`${sourceType}\` bypasses structural type checks.`,
|
|
159
161
|
filePath: file.displayPath,
|
|
160
162
|
line: lineNumber,
|
|
161
|
-
severity: "warning",
|
|
163
|
+
severity: hasRationale ? "advisory" : "warning",
|
|
162
164
|
pillar: "modernisation",
|
|
163
165
|
confidence: "medium",
|
|
164
166
|
remediation: "Prefer a typed parser, type guard, or narrower assertion at the trust boundary.",
|
|
165
|
-
metadata: { sourceType, targetType },
|
|
167
|
+
metadata: { sourceType, targetType, ...(hasRationale ? { rationale: "trust-boundary" } : {}) },
|
|
166
168
|
}),
|
|
167
169
|
);
|
|
168
170
|
}
|
|
169
171
|
}
|
|
170
172
|
|
|
173
|
+
// Accepts only inline comments that name the trust boundary or validation reason for the cast.
|
|
174
|
+
function hasDoubleCastTrustBoundaryRationale(rawLine: string): boolean {
|
|
175
|
+
return (
|
|
176
|
+
/(?:\/\/|\/\*)/.test(rawLine) &&
|
|
177
|
+
/\b(?:trust boundary|external input|wire format|parser boundary|TS2352|unknown hop|validated|narrowed|type guard|schema)\b/i.test(rawLine)
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
171
181
|
/*
|
|
172
182
|
* `any` in an exported declaration's public surface. Only one finding per line because a single
|
|
173
183
|
* `export` with multiple any-typed fields is one design problem, not many. Reports the stable
|
package/src/scoring.ts
CHANGED
|
@@ -9,19 +9,20 @@ import type { AnalysisReport, FailThreshold, Finding, Pillar, Severity } from ".
|
|
|
9
9
|
function scoreReport(findings: Finding[]): AnalysisReport["score"] {
|
|
10
10
|
const byPillar = new Map<Pillar, Finding[]>();
|
|
11
11
|
const byFile = new Map<string, Finding[]>();
|
|
12
|
+
const penalties = scoringPenaltyMap(findings);
|
|
12
13
|
for (const finding of findings) {
|
|
13
14
|
byPillar.set(finding.pillar, [...(byPillar.get(finding.pillar) ?? []), finding]);
|
|
14
15
|
byFile.set(finding.filePath, [...(byFile.get(finding.filePath) ?? []), finding]);
|
|
15
16
|
}
|
|
16
17
|
const pillars = [...byPillar.entries()].map(([pillar, pillarFindings]) => {
|
|
17
|
-
const penalty = pillarFindings.reduce((sum, finding) => sum +
|
|
18
|
+
const penalty = pillarFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0);
|
|
18
19
|
return { pillar, score: Math.max(0, 100 - penalty), penalty, findings: pillarFindings.length };
|
|
19
20
|
});
|
|
20
21
|
const composite = pillars.length === 0 ? 100 : pillars.reduce((sum, pillar) => sum + pillar.score, 0) / pillars.length;
|
|
21
22
|
const topOffenders = [...byFile.entries()]
|
|
22
23
|
.map(([filePath, fileFindings]) => ({
|
|
23
24
|
filePath,
|
|
24
|
-
score: Math.max(0, 100 - fileFindings.reduce((sum, finding) => sum +
|
|
25
|
+
score: Math.max(0, 100 - fileFindings.reduce((sum, finding) => sum + findingPenalty(penalties, finding), 0)),
|
|
25
26
|
findings: fileFindings.length,
|
|
26
27
|
}))
|
|
27
28
|
.sort((left, right) => left.score - right.score);
|
|
@@ -71,13 +72,50 @@ function severityPenalty(severity: Severity): number {
|
|
|
71
72
|
return severity === "error" ? 8 : severity === "warning" ? 4 : 1.5;
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cognitive", "complexity.cyclomatic", "size.function-length"]);
|
|
76
|
+
|
|
77
|
+
// Correlated complexity findings describe one hard-to-review function.
|
|
78
|
+
// Invariant: detailed reports keep every rule finding while grade math splits one max-severity penalty.
|
|
79
|
+
function scoringPenaltyMap(findings: Finding[]): Map<Finding, number> {
|
|
80
|
+
const penalties = new Map<Finding, number>();
|
|
81
|
+
const clusters = new Map<string, Finding[]>();
|
|
82
|
+
for (const finding of findings) {
|
|
83
|
+
penalties.set(finding, severityPenalty(finding.severity));
|
|
84
|
+
const key = complexityClusterKey(finding);
|
|
85
|
+
if (key) {
|
|
86
|
+
clusters.set(key, [...(clusters.get(key) ?? []), finding]);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
for (const cluster of clusters.values()) {
|
|
90
|
+
if (cluster.length < 2) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const sharedPenalty = Math.max(...cluster.map((finding) => severityPenalty(finding.severity))) / cluster.length;
|
|
94
|
+
cluster.forEach((finding) => penalties.set(finding, sharedPenalty));
|
|
95
|
+
}
|
|
96
|
+
return penalties;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Invariant: line+symbol grouping prevents unrelated functions in the same file from sharing score relief.
|
|
100
|
+
function complexityClusterKey(finding: Finding): string | undefined {
|
|
101
|
+
if (!finding.symbol || !finding.line || !CORRELATED_COMPLEXITY_RULE_IDS.has(finding.ruleId)) {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
return `${finding.filePath}\0${finding.symbol}\0${finding.line}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Invariant: one finding uses one precomputed score penalty or the normal severity weight fallback.
|
|
108
|
+
function findingPenalty(penalties: ReadonlyMap<Finding, number>, finding: Finding): number {
|
|
109
|
+
return penalties.get(finding) ?? severityPenalty(finding.severity);
|
|
110
|
+
}
|
|
111
|
+
|
|
74
112
|
/*
|
|
75
113
|
* Per-severity grade breakdown for the human summary block. The composite headline alone hides the
|
|
76
114
|
* fact that an F can be driven entirely by advisories (goat-flow scan: F at 12.9 with 0 errors / 276
|
|
77
115
|
* 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
|
|
79
|
-
* matters:
|
|
80
|
-
*
|
|
116
|
+
* so the math stays consistent with how a single-rule pillar would score. The report-shape
|
|
117
|
+
* invariant matters: severity breakdowns and correlated complexity clustering must not add
|
|
118
|
+
* `gruff.analysis.v2` JSON fields, even when score values change.
|
|
81
119
|
*/
|
|
82
120
|
function severityGradeBreakdown(findings: Finding[]): {
|
|
83
121
|
error: { grade: string; score: number; count: number };
|