@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.
Files changed (45) hide show
  1. package/CHANGELOG.md +35 -11
  2. package/CONTRIBUTING.md +3 -3
  3. package/README.md +141 -183
  4. package/docs/README.md +23 -0
  5. package/docs/ci-integration.md +63 -0
  6. package/docs/{CONFIGURATION.md → configuration.md} +41 -20
  7. package/docs/dashboard.md +36 -0
  8. package/docs/output-formats.md +65 -0
  9. package/docs/{RELEASING.md → releasing.md} +17 -14
  10. package/docs/{REPORTS_AND_CI.md → reports-and-ci.md} +5 -2
  11. package/docs/rules.md +177 -0
  12. package/package.json +2 -2
  13. package/scripts/bump-version.sh +83 -18
  14. package/scripts/dependency-install.sh +96 -0
  15. package/scripts/dependency-update.sh +177 -0
  16. package/scripts/preflight-checks.sh +38 -0
  17. package/src/analyser.ts +9 -24
  18. package/src/blocks.ts +66 -12
  19. package/src/class-rules.ts +5 -6
  20. package/src/cli-program.ts +216 -39
  21. package/src/cli.ts +4 -1
  22. package/src/comment-rules.ts +2 -0
  23. package/src/config-load-error.ts +18 -0
  24. package/src/config-preservation.ts +64 -0
  25. package/src/config.ts +155 -29
  26. package/src/constants.ts +10 -2
  27. package/src/dashboard.ts +1 -1
  28. package/src/dead-code-rules.ts +62 -16
  29. package/src/doc-rules.ts +3 -3
  30. package/src/findings-helpers.ts +17 -0
  31. package/src/init-config.ts +308 -0
  32. package/src/line-rules.ts +64 -12
  33. package/src/naming-pushers.ts +7 -32
  34. package/src/pillar-summary.ts +129 -0
  35. package/src/project-config-rules.ts +1 -1
  36. package/src/report-html.ts +404 -0
  37. package/src/report-renderers.ts +210 -406
  38. package/src/rule-list.ts +65 -1
  39. package/src/rules.ts +36 -37
  40. package/src/safety-rules.ts +9 -4
  41. package/src/scoring.ts +41 -9
  42. package/src/test-block-rules.ts +43 -1
  43. package/src/test-fixtures.ts +13 -7
  44. package/src/text-scans.ts +1 -152
  45. package/src/types.ts +32 -6
@@ -0,0 +1,308 @@
1
+ // Renders the default .gruff-ts.yaml file from the rule descriptor registry so `gruff-ts init`
2
+ // can drop a config into a fresh project that mirrors the analyser's effective defaults.
3
+ import { existsSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { defaultConfigPath } from "./config.ts";
7
+ import { extractPreservedConfigFields } from "./config-preservation.ts";
8
+ import { ruleDescriptors } from "./rules.ts";
9
+ import type { FailThreshold, MinimumSeverityCommand, RuleDescriptor } from "./types.ts";
10
+
11
+ const DEFAULT_CONFIG_FILE_NAME = ".gruff-ts.yaml";
12
+
13
+ // Default option values for rules with `optionKeys`. The source of truth is the
14
+ // `optionNumber(config, ruleId, key, default)` call site in the rule implementation; mirroring
15
+ // them here keeps `gruff-ts init` self-contained. `init-config.test.ts` asserts the values
16
+ // here match the implementation defaults so drift fails the test suite, not user projects.
17
+ const RULE_OPTION_DEFAULTS: Readonly<Record<string, Readonly<Record<string, number>>>> = {
18
+ "design.large-module-concentration": { minFiles: 4, minLines: 80 },
19
+ "naming.generic-parameter": { minCyclomatic: 8, minLineCount: 30, minParameters: 3 },
20
+ };
21
+
22
+ // Default starter list copied from `defaultConfig()` in config.ts. Generated separately because
23
+ // the YAML form (a block sequence) is more reviewable than the inline `[...]` form a Set would emit.
24
+ // Universal-programming abbreviations that earn their place across nearly any codebase; project-specific
25
+ // vocabulary (domain acronyms) should be appended in the user's config rather than added here.
26
+ const DEFAULT_ACCEPTED_ABBREVIATIONS: readonly string[] = [
27
+ "age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url",
28
+ ];
29
+
30
+ // Result of an init write attempt, including the no-clobber branch for existing config files.
31
+ interface InitResult {
32
+ path: string;
33
+ status: "written" | "overwritten" | "exists";
34
+ }
35
+
36
+ // Inputs the analyse/summary actions must collect before deciding whether to ask the user about
37
+ // running `init`. Kept as an explicit shape so the predicate is testable without TTY mocking. All
38
+ // three stream TTY states matter: stdin so the answer can be typed, stderr so the prompt is seen,
39
+ // and stdout so a piped consumer (e.g. `... --format=json | jq`) does not block on hidden input.
40
+ interface InitPromptContext {
41
+ projectRoot: string;
42
+ shouldSkipConfig: boolean;
43
+ hasExplicitConfig: boolean;
44
+ isInteractionAllowed: boolean;
45
+ isOutputSuppressed: boolean;
46
+ isStdinTty: boolean;
47
+ isStdoutTty: boolean;
48
+ isStderrTty: boolean;
49
+ }
50
+
51
+ /**
52
+ * Bundle of values that survive an `init --force` regeneration. `paths.ignore` is preserved
53
+ * verbatim, `minimumSeverity` is replayed entry-by-entry; the schemaVersion field is fixed for now
54
+ * because there is only one supported version.
55
+ */
56
+ interface PreservedInitConfig {
57
+ ignoredPaths: readonly string[];
58
+ minimumSeverity: ReadonlyMap<MinimumSeverityCommand, FailThreshold>;
59
+ }
60
+
61
+ const EMPTY_PRESERVED_CONFIG: PreservedInitConfig = { ignoredPaths: [], minimumSeverity: new Map() };
62
+
63
+ /**
64
+ * Render the default .gruff-ts.yaml content from the rule descriptor registry. Output order is
65
+ * schemaVersion → minimumSeverity → paths → allowlists → rules so the highest-impact CI behaviour
66
+ * (gating threshold per command) sits near the top of the file. Sections are separated by blank
67
+ * lines for readability.
68
+ *
69
+ * @param ignoredPaths Optional `paths.ignore` entries to inject verbatim (block-sequence form).
70
+ * The `gruff-ts init --force` flow forwards the existing file's entries so user-curated
71
+ * exclusions survive regeneration; an empty list emits `ignore: []` for fresh projects.
72
+ * @param preservedMinimumSeverity Optional carry-over of the existing config's `minimumSeverity:`
73
+ * block. Empty Map falls back to canonical defaults (advisory / advisory / none).
74
+ * @returns A YAML document string terminated by a trailing newline.
75
+ */
76
+ function renderDefaultConfig(ignoredPaths: readonly string[] = [], preservedMinimumSeverity: ReadonlyMap<MinimumSeverityCommand, FailThreshold> = new Map()): string {
77
+ return [
78
+ renderSchemaVersionSection(),
79
+ "",
80
+ renderMinimumSeveritySection(preservedMinimumSeverity),
81
+ "",
82
+ renderPathsSection(ignoredPaths),
83
+ "",
84
+ renderAllowlistsSection(),
85
+ "",
86
+ renderRulesSection(),
87
+ ].join("\n") + "\n";
88
+ }
89
+
90
+ // Required top-level schema-version field. Documented in ADR-004 because the introduction itself
91
+ // is a pre-1.0 break - every existing config gains this line, no transitional shim.
92
+ function renderSchemaVersionSection(): string {
93
+ return [
94
+ "# Config-schema version. Required as of gruff-ts 0.2.0. See ADR-004 (decision log).",
95
+ "schemaVersion: gruff-ts.config.v0.1",
96
+ ].join("\n");
97
+ }
98
+
99
+ // Per-command --fail-on defaults. The canonical out-of-the-box values match the operator's "show
100
+ // everything, fail on anything" philosophy. `dashboard` is intentionally NOT a valid key because
101
+ // the dashboard subcommand has no --fail-on flag and accepting it would be a silent CI footgun.
102
+ function renderMinimumSeveritySection(preserved: ReadonlyMap<MinimumSeverityCommand, FailThreshold>): string {
103
+ const header = [
104
+ "# Per-command default for `--fail-on`. CLI flag > this block > binary default.",
105
+ "# `dashboard` is intentionally NOT a valid key - it has no --fail-on flag. See ADR-004.",
106
+ "#",
107
+ "# Values:",
108
+ "# error - exit non-zero only when an error-severity finding fires (strictest gate).",
109
+ "# warning - exit non-zero on warning or error findings (advisory findings pass).",
110
+ "# advisory - exit non-zero on any finding at all (advisory, warning, or error).",
111
+ "# none - never exit non-zero from findings (use for raw reporting / baseline generation).",
112
+ "minimumSeverity:",
113
+ ];
114
+ const entries: Array<[MinimumSeverityCommand, FailThreshold]> = [
115
+ ["analyse", preserved.get("analyse") ?? "advisory"],
116
+ ["summary", preserved.get("summary") ?? "advisory"],
117
+ ["report", preserved.get("report") ?? "none"],
118
+ ];
119
+ return [...header, ...entries.map(([command, severity]) => ` ${command}: ${severity}`)].join("\n");
120
+ }
121
+
122
+ /**
123
+ * Write the default config to `<projectRoot>/.gruff-ts.yaml`. Performs a filesystem write side
124
+ * effect when no supported config exists, or when `shouldOverwrite` is true and `.gruff-ts.yaml`
125
+ * is the incumbent. Refuses to clobber (no side effect) when ANY supported config file is present
126
+ * (the four-name precedence list in `DEFAULT_CONFIG_FILES`), not just `.gruff-ts.yaml` -
127
+ * otherwise `init` would silently create a higher-precedence file alongside an existing
128
+ * `.gruff.yaml` / `.gruff.yml` / `.gruff.json` and quietly change the effective config. When
129
+ * overwriting an existing `.gruff-ts.yaml`, the file's `paths.ignore` entries are preserved so
130
+ * `init --force` does not erase project-specific recursive-scan exclusions.
131
+ *
132
+ * @param projectRoot Directory to write the config file into.
133
+ * @param shouldOverwrite Overwrite an existing config file when true.
134
+ * @returns The resolved path and whether a file was written, overwritten, or skipped. When the
135
+ * refusal is triggered by a non-canonical name, `path` points at that file so the caller's
136
+ * error message names the actual blocker.
137
+ */
138
+ function writeDefaultConfig(projectRoot: string, shouldOverwrite: boolean): InitResult {
139
+ const targetPath = join(projectRoot, DEFAULT_CONFIG_FILE_NAME);
140
+ const existingConfigPath = defaultConfigPath(projectRoot);
141
+ if (existingConfigPath !== undefined && !shouldOverwrite) {
142
+ return { path: existingConfigPath, status: "exists" };
143
+ }
144
+ const targetExists = existsSync(targetPath);
145
+ // Preserve paths.ignore + minimumSeverity from whichever supported config exists, not just
146
+ // `.gruff-ts.yaml` - otherwise `init --force` against a project with only
147
+ // `.gruff.yaml`/`.yml`/`.json` would silently drop user-curated exclusions and command-specific
148
+ // gating thresholds when generating the new canonical file.
149
+ const preserved = existingConfigPath !== undefined ? readExistingPreservedConfig(existingConfigPath) : EMPTY_PRESERVED_CONFIG;
150
+ writeFileSync(targetPath, renderDefaultConfig(preserved.ignoredPaths, preserved.minimumSeverity));
151
+ return { path: targetPath, status: targetExists ? "overwritten" : "written" };
152
+ }
153
+
154
+ /*
155
+ * Recover the existing file's `paths.ignore` and `minimumSeverity` blocks before `init --force`
156
+ * overwrites it. Uses the permissive extractor (not the strict validator) so a pre-0.2.0 config
157
+ * without `schemaVersion` still hands its curated entries to the regenerated file - the strict
158
+ * gate would throw on the missing field and silently drop the user's `paths.ignore`. The
159
+ * try/catch swallows IO/parse errors and returns empty values so a malformed existing config
160
+ * does not block regeneration; the user is opting into clobbering, but the documented contract
161
+ * is that curated entries survive when readable.
162
+ */
163
+ function readExistingPreservedConfig(existingConfigPath: string): PreservedInitConfig {
164
+ try {
165
+ return extractPreservedConfigFields(existingConfigPath);
166
+ } catch {
167
+ return EMPTY_PRESERVED_CONFIG;
168
+ }
169
+ }
170
+
171
+ // `paths.ignore` defaults to empty for fresh projects - discovery.ts already filters node_modules,
172
+ // .git, etc. regardless of config. When `init --force` regenerates an existing config, the caller
173
+ // forwards the existing entries so user-curated exclusions survive.
174
+ function renderPathsSection(ignoredPaths: readonly string[]): string {
175
+ const header = [
176
+ "paths:",
177
+ " # Recursive scans already respect .gitignore plus built-in default directories",
178
+ " # such as .git, node_modules, dist, coverage, generated, tmp, and vendor.",
179
+ " # Add project-specific generated or local outputs here when Git does not ignore them.",
180
+ " # Examples:",
181
+ " # - \"out/**\"",
182
+ " # - \".next/**\"",
183
+ " # - \"src/generated/**\"",
184
+ ];
185
+ if (ignoredPaths.length === 0) {
186
+ return [...header, " ignore: []"].join("\n");
187
+ }
188
+ return [
189
+ ...header,
190
+ " ignore:",
191
+ ...ignoredPaths.map((ignoredPath) => ` - ${JSON.stringify(ignoredPath)}`),
192
+ ].join("\n");
193
+ }
194
+
195
+ // `acceptedAbbreviations` is emitted as a block sequence for reviewability; the seven naming
196
+ // allowlists below it stay commented out so users see the override knobs without changing defaults.
197
+ function renderAllowlistsSection(): string {
198
+ return [
199
+ "allowlists:",
200
+ " acceptedAbbreviations:",
201
+ ...DEFAULT_ACCEPTED_ABBREVIATIONS.map((abbreviation) => ` - ${abbreviation}`),
202
+ " secretPreviews: []",
203
+ " # Names that trigger naming.generic-function. Each key replaces the built-in",
204
+ " # default when present; an empty list disables that rule's blacklist branch.",
205
+ " # Default: [process, handle, doit, run, execute, manage]",
206
+ " # bannedGenericNames: [process, handle, doit, run, execute, manage]",
207
+ " # Accepted prefixes for boolean identifiers. Names without one of these",
208
+ " # prefixes trigger naming.boolean-prefix.",
209
+ " # Default: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
210
+ " # booleanPrefixes: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
211
+ " # Hungarian type-style prefixes flagged by naming.hungarian-notation.",
212
+ " # Default: [str, obj, arr, bool, int, num]",
213
+ " # hungarianPrefixes: [str, obj, arr, bool, int, num]",
214
+ " # Placeholder words flagged as generic by naming.identifier-quality. The",
215
+ " # numbered-suffix branch (foo1, value2) stays active even when this is empty.",
216
+ " # Default: [foo, bar, baz, tmp, temp, thing, stuff, data, value, item]",
217
+ " # placeholderNames: [foo, bar, baz, tmp, temp, thing, stuff, data, value, item]",
218
+ " # Negative-framed boolean names that should NOT trigger naming.negative-boolean.",
219
+ " # Defaults are HTTP-header conventions; add project terms as needed.",
220
+ " # Default: [nostore, nofollow, noreferrer, noscript, noindex]",
221
+ " # negativeBooleanAllowed: [nostore, nofollow, noreferrer, noscript, noindex]",
222
+ " # Known acronyms whose mixed casings trigger naming.acronym-case. Stored",
223
+ " # case-insensitively; match is against canonical lowercase.",
224
+ " # Default: [url, http, https, id, xml, json, html, css, api, sql, db, io, ui, uuid, ip, tcp, udp, ast, cli, npm]",
225
+ " # knownAcronyms: [url, http, https, id, xml, json, html, css, api, sql, db, io, ui, uuid, ip, tcp, udp, ast, cli, npm]",
226
+ ].join("\n");
227
+ }
228
+
229
+ // Walks the registry in its canonical (sorted) order so the generated YAML is byte-stable.
230
+ function renderRulesSection(): string {
231
+ const lines = ["rules:"];
232
+ for (const descriptor of ruleDescriptors()) {
233
+ lines.push(...renderRuleEntry(descriptor));
234
+ }
235
+ return lines.join("\n");
236
+ }
237
+
238
+ // One rule entry: a `# pillar/severity: description` comment line, the rule id, `enabled`, then
239
+ // threshold/severity/options only when the descriptor declares them. Omitting absent keys keeps
240
+ // the generated file aligned with the descriptor's actual contract.
241
+ function renderRuleEntry(descriptor: RuleDescriptor): string[] {
242
+ const lines: string[] = [];
243
+ lines.push(` # ${descriptor.pillar}/${descriptor.severity}: ${descriptor.description}`);
244
+ lines.push(` ${descriptor.ruleId}:`);
245
+ lines.push(" enabled: true");
246
+ if (typeof descriptor.threshold === "number") {
247
+ lines.push(` threshold: ${descriptor.threshold}`);
248
+ lines.push(` severity: ${descriptor.severity}`);
249
+ }
250
+ const optionDefaults = RULE_OPTION_DEFAULTS[descriptor.ruleId];
251
+ if (optionDefaults) {
252
+ lines.push(" options:");
253
+ for (const [key, value] of Object.entries(optionDefaults)) {
254
+ lines.push(` ${key}: ${value}`);
255
+ }
256
+ }
257
+ return lines;
258
+ }
259
+
260
+ /**
261
+ * Decide whether the analyse/summary actions should prompt the user to run `init`.
262
+ *
263
+ * Returns true only when every gate passes: interaction is allowed, output isn't suppressed, the
264
+ * user hasn't already opted in (--config) or out (--no-config) of config loading, all three
265
+ * standard streams are TTYs (stdin to type, stderr to display, stdout to confirm the run is not
266
+ * piping machine output to a downstream consumer), and no supported config file is already
267
+ * present at the project root.
268
+ *
269
+ * @param context CLI-collected state needed to make the decision.
270
+ * @returns Whether the prompt should be shown.
271
+ */
272
+ function shouldPromptForInit(context: InitPromptContext): boolean {
273
+ if (!context.isInteractionAllowed) {
274
+ return false;
275
+ }
276
+ if (context.isOutputSuppressed) {
277
+ return false;
278
+ }
279
+ if (context.shouldSkipConfig || context.hasExplicitConfig) {
280
+ return false;
281
+ }
282
+ if (!context.isStdinTty || !context.isStdoutTty || !context.isStderrTty) {
283
+ return false;
284
+ }
285
+ return defaultConfigPath(context.projectRoot) === undefined;
286
+ }
287
+
288
+ /**
289
+ * Ask the user a yes/no question on stderr and return their answer.
290
+ *
291
+ * Defaults to "no" when the user just presses enter so the prompt is safe to dismiss. Reads from
292
+ * stdin; closes the readline interface in a finally so a Ctrl-C exits cleanly.
293
+ *
294
+ * @param question Prompt text written to stderr verbatim.
295
+ * @returns True when the user typed y or yes (case-insensitive); false otherwise.
296
+ */
297
+ async function promptYesNo(question: string): Promise<boolean> {
298
+ const readlineInterface = createInterface({ input: process.stdin, output: process.stderr });
299
+ try {
300
+ const answer = await readlineInterface.question(question);
301
+ return /^(y|yes)$/i.test(answer.trim());
302
+ } finally {
303
+ readlineInterface.close();
304
+ }
305
+ }
306
+
307
+ export type { InitPromptContext, InitResult };
308
+ export { DEFAULT_CONFIG_FILE_NAME, RULE_OPTION_DEFAULTS, promptYesNo, renderDefaultConfig, shouldPromptForInit, writeDefaultConfig };
package/src/line-rules.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  import { type SourceFile } from "./discovery.ts";
8
8
  import { makeFinding } from "./findings.ts";
9
9
  import { escapeRegex, finding, isCommentedOutCode } from "./findings-helpers.ts";
10
- import { type NamingSurface, pushAbbreviationAt, pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
10
+ import { type NamingSurface, pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
11
11
  import { analyseReliabilityLine, analyseSwallowedCatches, analyseTypeSafetyLine, analyseUselessCatches } from "./safety-rules.ts";
12
12
  import { analyseSecurityFlowLine } from "./security-flow-rules.ts";
13
13
  import { codeLineForMatching } from "./source-text.ts";
@@ -33,6 +33,10 @@ interface LineRuleContext {
33
33
  file: SourceFile;
34
34
  line: string;
35
35
  codeLine: string;
36
+ // Full masked source as one array per line, indexed 0-based. Exposed so per-line rules that need
37
+ // forward look-ahead (for-of body brace-balancing in `pushVariableNameFindings`) can scan beyond
38
+ // the current line without re-splitting the source.
39
+ codeLines: readonly string[];
36
40
  lineNumber: number;
37
41
  config: Config;
38
42
  findings: Finding[];
@@ -57,6 +61,7 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
57
61
  file,
58
62
  line: "",
59
63
  codeLine: "",
64
+ codeLines,
60
65
  lineNumber: 0,
61
66
  config,
62
67
  findings,
@@ -104,7 +109,7 @@ function codeLineChecks(): LineRuleCheck[] {
104
109
  { ruleId: "security.inner-html", pattern: /\.innerHTML\s*=(?!\s*(?:""|''))|\bdangerouslySetInnerHTML\b/, message: "HTML injection sink can introduce XSS.", severity: "warning", pillar: "security" },
105
110
  { ruleId: "security.proto-access", pattern: /\.__proto__\b/, message: "Direct __proto__ access can enable prototype pollution.", severity: "warning", pillar: "security" },
106
111
  { ruleId: "security.document-write", pattern: /\bdocument\.write\s*\(/, message: "document.write() can introduce injection risks.", severity: "warning", pillar: "security" },
107
- { ruleId: "waste.redundant-boolean-cast", pattern: /\b(?:if|while)\s*\(\s*(?:!!\s*[A-Za-z_$][A-Za-z0-9_$.]*|Boolean\s*\()/, message: "Condition contains a redundant boolean cast.", severity: "advisory", pillar: "waste" },
112
+ { ruleId: "waste.redundant-boolean-cast", pattern: /\b(?:if|while)\s*\(\s*(?:!!\s*[A-Za-z_$][A-Za-z0-9_$.]*|Boolean\s*\()/, message: "Condition contains a redundant boolean cast.", severity: "advisory", pillar: "maintainability" },
108
113
  ];
109
114
  }
110
115
 
@@ -120,8 +125,8 @@ function literalLineChecks(): LineRuleCheck[] {
120
125
  { ruleId: "security.sql-concatenation", pattern: /\b(?:query|execute|raw)\s*\(\s*(?:`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)[^`]*\$\{|["'][^"']*(?:SELECT|INSERT|UPDATE|DELETE)[^"']*["']\s*\+)/i, message: "SQL text is composed with runtime string interpolation.", severity: "warning", pillar: "security" },
121
126
  { ruleId: "modernisation.date-now-candidate", pattern: /\bnew\s+Date\s*\(\s*\)\s*\.getTime\s*\(\s*\)|\bNumber\s*\(\s*new\s+Date\s*\(\s*\)\s*\)/, message: "Current-time expression can use Date.now().", severity: "advisory", pillar: "modernisation" },
122
127
  { ruleId: "modernisation.object-spread-candidate", pattern: /\bObject\.assign\s*\(\s*\{\s*\}\s*,/, message: "Object.assign clone can usually use object spread.", severity: "advisory", pillar: "modernisation" },
123
- { ruleId: "waste.console-log", pattern: /\bconsole\.(log|debug)\s*\(/, message: "console logging is committed in source.", severity: "advisory", pillar: "waste" },
124
- { ruleId: "waste.any-type", pattern: /:\s*any\b|as\s+any\b/, message: "any weakens TypeScript's type guarantees.", severity: "warning", pillar: "waste" },
128
+ { ruleId: "waste.console-log", pattern: /\bconsole\.(log|debug)\s*\(/, message: "console logging is committed in source.", severity: "advisory", pillar: "maintainability" },
129
+ { ruleId: "waste.any-type", pattern: /:\s*any\b|as\s+any\b/, message: "any weakens TypeScript's type guarantees.", severity: "warning", pillar: "maintainability" },
125
130
  { ruleId: "modernisation.var-declaration", pattern: /\bvar\s+[A-Za-z_$]/, message: "var declaration should usually be let or const.", severity: "advisory", pillar: "modernisation" },
126
131
  ];
127
132
  return checks.map(withGlobalPattern);
@@ -143,7 +148,7 @@ function withGlobalPattern(check: LineRuleCheck): LineRuleCheck {
143
148
  */
144
149
  function pushCommentedOutCodeFinding(context: LineRuleContext): void {
145
150
  if (isCommentedOutCode(context.line)) {
146
- context.findings.push(finding({ ruleId: "waste.commented-out-code", message: "Comment appears to contain disabled source code.", file: context.file, line: context.lineNumber, severity: "advisory", pillar: "waste" }));
151
+ context.findings.push(finding({ ruleId: "waste.commented-out-code", message: "Comment appears to contain disabled source code.", file: context.file, line: context.lineNumber, severity: "advisory", pillar: "maintainability" }));
147
152
  }
148
153
  }
149
154
 
@@ -279,22 +284,67 @@ function isSuppressedByPathContext(ruleId: string, displayPath: string): boolean
279
284
  return /(?:^|\/)(?:scripts|bin)\//.test(displayPath) || /(?:^|\/)cli[/.]/i.test(displayPath) || /(?:^|\/)server[/.]/i.test(displayPath);
280
285
  }
281
286
 
282
- // Per-line variable-name pass that runs short/identifier-quality/abbreviation checks on both
287
+ // Per-line variable-name pass that runs short/identifier-quality checks on both
283
288
  // regular `const`/`let` declarations and destructured names. Reports any findings produced.
289
+ // Single-character for-of bindings whose body is ≤ 10 lines are idiomatic (e.g. `for (const f of
290
+ // files) { write(f); }`) and skip the short-variable check; longer bodies still flag. The
291
+ // exemption is gated on a real `of` token after the binding so C-style `for (let i = 0; …)` and
292
+ // `for (const k in obj)` headers stay covered by the rule.
284
293
  function pushVariableNameFindings(context: LineRuleContext): void {
285
294
  for (const match of context.codeLine.matchAll(context.variables)) {
286
295
  const name = match[1] ?? "";
287
- pushShortVariableFinding(context, name);
296
+ const matchText = match[0] ?? "";
297
+ const headerTail = context.codeLine.slice((match.index ?? 0) + matchText.length);
298
+ const isForOfHeader = matchText.startsWith("for") && /^\s+of\b/.test(headerTail);
299
+ const loopBodyLineCount = isForOfHeader ? forOfBodyLineSpan(context.codeLines, context.lineNumber - 1) : undefined;
300
+ pushShortVariableFinding(context, name, loopBodyLineCount);
288
301
  pushIdentifierQualityFinding(context, name);
289
- pushAbbreviationAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration");
290
302
  }
291
303
  for (const name of destructuredLocalNames(context.codeLine)) {
292
304
  pushShortVariableAt(context.file, context.lineNumber, name, context.config, context.findings, "destructure");
293
305
  pushIdentifierQualityAt(context.file, context.lineNumber, name, context.config, context.findings, "destructure");
294
- pushAbbreviationAt(context.file, context.lineNumber, name, context.config, context.findings, "destructure");
295
306
  }
296
307
  }
297
308
 
309
+ /*
310
+ * Counts the line span of a for-of body starting at the opener line index. Brace-less
311
+ * single-statement bodies return 1 because the body is trivially short. When the opener has `{`,
312
+ * brace-balance tracking finds the matching `}` and returns the line count from `{` to `}`
313
+ * inclusive. The walker uses the masked codeLines so braces inside string literals are blanked
314
+ * out; this avoids the false "balanced" claim a raw-source walker would make on template strings.
315
+ * A 50-line scan window guards against unterminated scans because malformed input must not stall
316
+ * the whole-file walker; an unbalanced result returns Infinity so a long-but-unclosed for-of
317
+ * still fires the rule rather than getting silently exempted.
318
+ */
319
+ function forOfBodyLineSpan(codeLines: readonly string[], openerLineIndex: number): number {
320
+ const maxLines = 50;
321
+ const end = Math.min(codeLines.length, openerLineIndex + maxLines);
322
+ let state: ForOfBraceScanState = { depth: 0, bodyOpenerLine: -1 };
323
+ for (let i = openerLineIndex; i < end; i += 1) {
324
+ state = advanceForOfBraceScan(state, codeLines[i] ?? "", i);
325
+ if (state.bodyOpenerLine !== -1 && state.depth <= 0) {
326
+ return i - state.bodyOpenerLine + 1;
327
+ }
328
+ }
329
+ return state.bodyOpenerLine === -1 ? 1 : Infinity;
330
+ }
331
+
332
+ // Working state for the per-line brace scan. Returning a fresh value each line keeps the outer
333
+ // loop's npath low and the transition rules explicit.
334
+ interface ForOfBraceScanState {
335
+ depth: number;
336
+ bodyOpenerLine: number;
337
+ }
338
+
339
+ // Per-line brace-balance update. Records the first line that introduced a `{` so the caller can
340
+ // compute the body span when the balancing `}` lands.
341
+ function advanceForOfBraceScan(state: ForOfBraceScanState, line: string, lineIndex: number): ForOfBraceScanState {
342
+ const opens = (line.match(/\{/g) ?? []).length;
343
+ const closes = (line.match(/\}/g) ?? []).length;
344
+ const bodyOpenerLine = opens > 0 && state.bodyOpenerLine === -1 ? lineIndex : state.bodyOpenerLine;
345
+ return { depth: state.depth + opens - closes, bodyOpenerLine };
346
+ }
347
+
298
348
  // Walks `const { foo, bar: alias } = ...` patterns. Aliased names (the part after `:`) become the
299
349
  // local binding; defaults are stripped. Required because the naming rules check the local name only.
300
350
  function destructuredLocalNames(codeLine: string): string[] {
@@ -315,9 +365,11 @@ function destructuredLocalNames(codeLine: string): string[] {
315
365
  }
316
366
 
317
367
  // Thin wrapper that fills in `"declaration"` for the surface field. Same back-end as parameter
318
- // and destructure callers, which use their own surface labels.
319
- function pushShortVariableFinding(context: LineRuleContext, name: string): void {
320
- pushShortVariableAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration");
368
+ // and destructure callers, which use their own surface labels. `loopBodyLineCount` is forwarded so
369
+ // the underlying rule can apply the for-of short-body exemption when the declaration came from a
370
+ // `for (const X of …)` head.
371
+ function pushShortVariableFinding(context: LineRuleContext, name: string, loopBodyLineCount?: number): void {
372
+ pushShortVariableAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration", loopBodyLineCount);
321
373
  }
322
374
 
323
375
 
@@ -77,8 +77,14 @@ function isAcceptedBooleanStateName(name: string): boolean {
77
77
  /*
78
78
  * Allows the standard `i`, `j`, `k` loop counters and anything on `acceptedAbbreviations`. Reports
79
79
  * `naming.short-variable` for any other one or two character name as a stable advisory finding.
80
+ * `loopBodyLineCount` is the for-of caller's signal: when the binding came from a `for (const X of
81
+ * Y) { … }` head and the body spans ≤ 10 lines, the rule suppresses the finding because the name's
82
+ * lifetime is locally obvious. Other call sites (declaration, parameter, destructure) pass undefined.
80
83
  */
81
- export function pushShortVariableAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface): void {
84
+ export function pushShortVariableAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface, loopBodyLineCount?: number): void {
85
+ if (loopBodyLineCount !== undefined && loopBodyLineCount <= 10) {
86
+ return;
87
+ }
82
88
  if (name.length > 2 || ["i", "j", "k"].includes(name) || config.acceptedAbbreviations.has(name.toLowerCase())) {
83
89
  return;
84
90
  }
@@ -124,37 +130,6 @@ export function pushIdentifierQualityAt(file: SourceFile, line: number, name: st
124
130
  );
125
131
  }
126
132
 
127
- /*
128
- * Reports `naming.abbreviation` when the name is on `abbreviationDenylist` and not on the user's
129
- * `acceptedAbbreviations` allowlist. `surface` distinguishes parameter / variable / interface-field
130
- * - same stable rule contract, different metadata, so consumers can filter on origin.
131
- */
132
- export function pushAbbreviationAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface): void {
133
- if (config.rules.get("naming.abbreviation")?.enabled !== true) {
134
- return;
135
- }
136
- if (config.acceptedAbbreviations.has(name.toLowerCase())) {
137
- return;
138
- }
139
- if (!config.abbreviationDenylist.has(name.toLowerCase())) {
140
- return;
141
- }
142
- findings.push(
143
- makeFinding({
144
- ruleId: "naming.abbreviation",
145
- message: `Identifier \`${name}\` uses an opaque abbreviation.`,
146
- filePath: file.displayPath,
147
- line,
148
- severity: "advisory",
149
- pillar: "naming",
150
- confidence: "medium",
151
- symbol: name,
152
- remediation: "Use the full domain term or add the abbreviation to allowlists.acceptedAbbreviations.",
153
- metadata: { identifierName: name, surface },
154
- }),
155
- );
156
- }
157
-
158
133
  // Returns `"generic"` for low-information names from the configured set, `"numbered"` for
159
134
  // `foo1` / `bar2` style trailing-digit identifiers, or undefined when the name is acceptable.
160
135
  // The variant string lands in finding metadata so consumers can split the two failure modes.
@@ -0,0 +1,129 @@
1
+ /*
2
+ * Shared pillar-row construction + grade helper. Lives in its own module so the text/markdown
3
+ * renderers (`report-renderers.ts`), the HTML renderer (`report-html.ts`), and the score builder
4
+ * (`scoring.ts`) can all source the same `buildPillarRows` and `grade` logic without forming a
5
+ * dependency cycle between the renderer modules. Every row this module emits feeds the cross-port
6
+ * `gruff.summary.v2` Pillars table contract, so the schema invariant - findings DESC, pillar ASC,
7
+ * and a clean A/100 fallback per pillar - must stay byte-stable across runs.
8
+ */
9
+ import { ruleDescriptors } from "./rules.ts";
10
+ import type { AnalysisReport, Finding, Pillar } from "./types.ts";
11
+
12
+ // Aggregated per-pillar row used by every renderer. `applicable` is derived from the rule
13
+ // catalogue rather than the live findings so the row set stays stable across runs (a pillar with
14
+ // zero findings today is still applicable). `grade` is derived from `score` via the shared
15
+ // `grade()` helper so historical pillar scores keep their existing grade letters.
16
+ interface PillarRow {
17
+ pillar: Pillar;
18
+ grade: string;
19
+ score: number;
20
+ penalty: number;
21
+ isApplicable: boolean;
22
+ findings: number;
23
+ advisory: number;
24
+ warning: number;
25
+ error: number;
26
+ }
27
+
28
+ // Per-pillar severity tally - one entry per pillar that produced at least one finding. Renderers
29
+ // see these counts indirectly through `buildPillarRows`; the type is exported only so other
30
+ // modules in this package can name it when consuming `countSeverityByPillar`.
31
+ interface PillarSeverityCounts {
32
+ advisory: number;
33
+ warning: number;
34
+ error: number;
35
+ }
36
+
37
+ /*
38
+ * Builds the canonical cross-port pillar row list shared by `gruff.summary.v2` text, JSON, and
39
+ * HTML renderers. The shape is intentionally a single deterministic list - one row per applicable
40
+ * pillar even when the run has zero findings - because cross-port consumers diff this output
41
+ * byte-for-byte and a missing row would read as a contract drift. Pillars without findings default
42
+ * to a clean A/100 row to preserve that invariant. Sort order is `findings DESC, pillar ASC` to
43
+ * keep the public Pillars-table contract deterministic across runs.
44
+ */
45
+ function buildPillarRows(report: AnalysisReport): PillarRow[] {
46
+ const scoreByPillar = new Map(report.score.pillars.map((entry) => [entry.pillar, entry] as const));
47
+ const severityByPillar = countSeverityByPillar(report.findings);
48
+ const rows: PillarRow[] = [...applicablePillarSet()].map((pillar) => buildPillarRow(pillar, scoreByPillar.get(pillar), severityByPillar.get(pillar)));
49
+ rows.sort(comparePillarRows);
50
+ return rows;
51
+ }
52
+
53
+ // Tallies advisory/warning/error counts per pillar from the live findings list. Returning a Map
54
+ // rather than mutating an accumulator keeps `buildPillarRows` linear and easy to read; this is
55
+ // the deterministic per-pillar tally feeding the public Pillars-table schema.
56
+ function countSeverityByPillar(findings: Finding[]): Map<Pillar, PillarSeverityCounts> {
57
+ const severityByPillar = new Map<Pillar, PillarSeverityCounts>();
58
+ for (const finding of findings) {
59
+ const counts = severityByPillar.get(finding.pillar) ?? { advisory: 0, warning: 0, error: 0 };
60
+ counts[finding.severity] += 1;
61
+ severityByPillar.set(finding.pillar, counts);
62
+ }
63
+ return severityByPillar;
64
+ }
65
+
66
+ /*
67
+ * Assembles one PillarRow from the optional analyser score entry and optional severity tally.
68
+ * Defaults preserve the clean A/100 row contract when a pillar produced no findings, keeping the
69
+ * `gruff.summary.v2` per-pillar shape deterministic across runs. Invariant: `findings` is derived
70
+ * from the severity tally (not `scoreEntry.findings`) so the row's total and its per-severity
71
+ * columns share a single source and can never disagree - the Finding list is the schema's single
72
+ * source of truth for what was actually reported in this run.
73
+ */
74
+ function buildPillarRow(pillar: Pillar, scoreEntry: AnalysisReport["score"]["pillars"][number] | undefined, severities: PillarSeverityCounts | undefined): PillarRow {
75
+ const score = scoreEntry?.score ?? 100;
76
+ const counts = severities ?? { advisory: 0, warning: 0, error: 0 };
77
+ return {
78
+ pillar,
79
+ grade: grade(score),
80
+ score,
81
+ penalty: scoreEntry?.penalty ?? 0,
82
+ isApplicable: true,
83
+ findings: counts.advisory + counts.warning + counts.error,
84
+ advisory: counts.advisory,
85
+ warning: counts.warning,
86
+ error: counts.error,
87
+ };
88
+ }
89
+
90
+ // Findings DESC, then pillar ASC. Extracted so the cross-port sort contract lives in one place and
91
+ // any tweak (e.g. a stable secondary key) only has to land here.
92
+ function comparePillarRows(leftRow: PillarRow, rightRow: PillarRow): number {
93
+ if (leftRow.findings !== rightRow.findings) {
94
+ return rightRow.findings - leftRow.findings;
95
+ }
96
+ return leftRow.pillar.localeCompare(rightRow.pillar);
97
+ }
98
+
99
+ // Pillar applicability is sourced from the rule catalogue: a pillar is applicable when at least
100
+ // one rule declares it. This keeps the cross-port `gruff.summary.v2` contract stable - every
101
+ // pillar that *could* fire shows up even when the current run produced zero findings for it.
102
+ function applicablePillarSet(): Set<Pillar> {
103
+ const pillars = new Set<Pillar>();
104
+ for (const descriptor of ruleDescriptors()) {
105
+ pillars.add(descriptor.pillar);
106
+ }
107
+ return pillars;
108
+ }
109
+
110
+ // Composite-score → letter grade conversion. 90/80/70/60 boundaries are part of the stable rule
111
+ // surface; changing them would shift every historical report grade and the headline on the dashboard.
112
+ function grade(score: number): string {
113
+ if (score >= 90) {
114
+ return "A";
115
+ }
116
+ if (score >= 80) {
117
+ return "B";
118
+ }
119
+ if (score >= 70) {
120
+ return "C";
121
+ }
122
+ if (score >= 60) {
123
+ return "D";
124
+ }
125
+ return "F";
126
+ }
127
+
128
+ export { buildPillarRows, grade };
129
+ export type { PillarRow, PillarSeverityCounts };
@@ -198,7 +198,7 @@ function pushBroadRuntimeDependencyFinding(
198
198
  filePath: file.displayPath,
199
199
  line: jsonKeyLine(source, packageName),
200
200
  severity: "advisory",
201
- pillar: "waste",
201
+ pillar: "maintainability",
202
202
  confidence: "medium",
203
203
  symbol: packageName,
204
204
  remediation: "Use a bounded semver range and rely on the lockfile for repeatable installs.",