@blundergoat/gruff-ts 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +55 -19
  2. package/README.md +103 -35
  3. package/docs/README.md +2 -0
  4. package/docs/agent-hook.md +80 -0
  5. package/docs/ci-integration.md +16 -0
  6. package/docs/configuration.md +60 -3
  7. package/docs/dashboard.md +7 -0
  8. package/docs/output-formats.md +11 -1
  9. package/docs/philosophy.md +21 -0
  10. package/docs/releasing.md +12 -11
  11. package/docs/reports-and-ci.md +5 -2
  12. package/docs/rules.md +24 -15
  13. package/package.json +5 -5
  14. package/scripts/bump-version.sh +20 -4
  15. package/scripts/preflight-checks.sh +4 -41
  16. package/src/analyser.ts +47 -34
  17. package/src/blocks.ts +82 -75
  18. package/src/changed-regions.ts +390 -0
  19. package/src/check-ignore.ts +49 -0
  20. package/src/class-rules.ts +80 -33
  21. package/src/cli-program.ts +209 -51
  22. package/src/comment-rules.ts +4 -0
  23. package/src/config-load-error.ts +18 -0
  24. package/src/config-parse.ts +458 -0
  25. package/src/config-preservation.ts +64 -0
  26. package/src/config.ts +311 -428
  27. package/src/constants.ts +10 -2
  28. package/src/context-doc-rules.ts +2 -4
  29. package/src/dashboard.ts +8 -5
  30. package/src/dead-code-rules.ts +60 -14
  31. package/src/discovery.ts +88 -32
  32. package/src/doc-rules.ts +3 -3
  33. package/src/findings-helpers.ts +58 -5
  34. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  35. package/src/init-config.ts +94 -31
  36. package/src/line-rules.ts +58 -4
  37. package/src/naming-pushers.ts +42 -7
  38. package/src/pillar-summary.ts +129 -0
  39. package/src/profiles.ts +232 -0
  40. package/src/project-config-rules.ts +5 -5
  41. package/src/project-rules.ts +2 -1
  42. package/src/report-html.ts +404 -0
  43. package/src/report-renderers.ts +210 -397
  44. package/src/rule-list.ts +85 -1
  45. package/src/rules.ts +28 -27
  46. package/src/safety-rules.ts +22 -7
  47. package/src/scoring.ts +78 -8
  48. package/src/security-flow-rules.ts +533 -0
  49. package/src/sensitive-data-rules.ts +138 -2
  50. package/src/test-block-rules.ts +140 -7
  51. package/src/test-fixtures.ts +59 -13
  52. package/src/types.ts +108 -5
@@ -3,9 +3,10 @@
3
3
  import { existsSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
6
- import { defaultConfigPath, loadConfig } from "./config.ts";
6
+ import { defaultConfigPath } from "./config.ts";
7
+ import { extractPreservedConfigFields } from "./config-preservation.ts";
7
8
  import { ruleDescriptors } from "./rules.ts";
8
- import type { RuleDescriptor } from "./types.ts";
9
+ import type { FailThreshold, MinimumSeverityCommand, RuleDescriptor } from "./types.ts";
9
10
 
10
11
  const DEFAULT_CONFIG_FILE_NAME = ".gruff-ts.yaml";
11
12
 
@@ -20,7 +21,11 @@ const RULE_OPTION_DEFAULTS: Readonly<Record<string, Readonly<Record<string, numb
20
21
 
21
22
  // Default starter list copied from `defaultConfig()` in config.ts. Generated separately because
22
23
  // the YAML form (a block sequence) is more reviewable than the inline `[...]` form a Set would emit.
23
- const DEFAULT_ACCEPTED_ABBREVIATIONS: readonly string[] = ["id", "db", "fs", "io", "ui", "tx", "rx"];
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
+ ];
24
29
 
25
30
  // Result of an init write attempt, including the no-clobber branch for existing config files.
26
31
  interface InitResult {
@@ -44,15 +49,74 @@ interface InitPromptContext {
44
49
  }
45
50
 
46
51
  /**
47
- * Render the default .gruff-ts.yaml content from the rule descriptor registry.
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.
48
68
  *
49
- * @param ignoredPaths Optional `paths.ignore` entries to inject verbatim (block-sequence form). The
50
- * `gruff-ts init --force` flow forwards the existing file's entries so user-curated exclusions
51
- * survive regeneration; an empty list emits `ignore: []` for fresh projects.
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).
52
74
  * @returns A YAML document string terminated by a trailing newline.
53
75
  */
54
- function renderDefaultConfig(ignoredPaths: readonly string[] = []): string {
55
- return [renderPathsSection(ignoredPaths), "", renderAllowlistsSection(), "", renderRulesSection()].join("\n") + "\n";
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");
56
120
  }
57
121
 
58
122
  /**
@@ -78,33 +142,29 @@ function writeDefaultConfig(projectRoot: string, shouldOverwrite: boolean): Init
78
142
  return { path: existingConfigPath, status: "exists" };
79
143
  }
80
144
  const targetExists = existsSync(targetPath);
81
- // Preserve paths.ignore from whichever supported config exists, not just `.gruff-ts.yaml` -
82
- // otherwise `init --force` against a project with only `.gruff.yaml`/`.yml`/`.json` would
83
- // silently drop user-curated ignore entries when generating the new canonical file.
84
- const preservedIgnoredPaths = existingConfigPath !== undefined ? readExistingIgnoredPaths(projectRoot) : [];
85
- writeFileSync(targetPath, renderDefaultConfig(preservedIgnoredPaths));
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));
86
151
  return { path: targetPath, status: targetExists ? "overwritten" : "written" };
87
152
  }
88
153
 
89
154
  /*
90
- * Recover the existing file's `paths.ignore` block before `init --force` overwrites it. The
91
- * try/catch swallows YAML-parse errors and the fallback returns an empty list so a malformed
92
- * existing config does not block regeneration - the user is opting into clobbering, but the
93
- * documented contract is that curated ignore entries survive when readable.
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.
94
162
  */
95
- function readExistingIgnoredPaths(projectRoot: string): readonly string[] {
163
+ function readExistingPreservedConfig(existingConfigPath: string): PreservedInitConfig {
96
164
  try {
97
- const config = loadConfig(projectRoot, {
98
- paths: [],
99
- shouldSkipConfig: false,
100
- format: "text",
101
- failOn: "none",
102
- shouldIncludeIgnored: false,
103
- shouldSkipBaseline: true,
104
- });
105
- return config.ignoredPaths;
165
+ return extractPreservedConfigFields(existingConfigPath);
106
166
  } catch {
107
- return [];
167
+ return EMPTY_PRESERVED_CONFIG;
108
168
  }
109
169
  }
110
170
 
@@ -144,10 +204,13 @@ function renderAllowlistsSection(): string {
144
204
  " # default when present; an empty list disables that rule's blacklist branch.",
145
205
  " # Default: [process, handle, doit, run, execute, manage]",
146
206
  " # bannedGenericNames: [process, handle, doit, run, execute, manage]",
207
+ " # Exact public/CLI/DTO boolean names accepted by naming.boolean-prefix.",
208
+ " # Default: [all, apply, check, dev, enabled, force, fresh, harness, json, ok, verbose, yes]",
209
+ " # acceptedBooleanNames: [all, apply, check, dev, enabled, force, fresh, harness, json, ok, verbose, yes]",
147
210
  " # Accepted prefixes for boolean identifiers. Names without one of these",
148
211
  " # prefixes trigger naming.boolean-prefix.",
149
- " # Default: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires]",
150
- " # booleanPrefixes: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires]",
212
+ " # Default: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
213
+ " # booleanPrefixes: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
151
214
  " # Hungarian type-style prefixes flagged by naming.hungarian-notation.",
152
215
  " # Default: [str, obj, arr, bool, int, num]",
153
216
  " # hungarianPrefixes: [str, obj, arr, bool, int, num]",
package/src/line-rules.ts CHANGED
@@ -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,
@@ -281,10 +286,18 @@ function isSuppressedByPathContext(ruleId: string, displayPath: string): boolean
281
286
 
282
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
302
  }
290
303
  for (const name of destructuredLocalNames(context.codeLine)) {
@@ -293,6 +306,45 @@ function pushVariableNameFindings(context: LineRuleContext): void {
293
306
  }
294
307
  }
295
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
+
296
348
  // Walks `const { foo, bar: alias } = ...` patterns. Aliased names (the part after `:`) become the
297
349
  // local binding; defaults are stripped. Required because the naming rules check the local name only.
298
350
  function destructuredLocalNames(codeLine: string): string[] {
@@ -313,9 +365,11 @@ function destructuredLocalNames(codeLine: string): string[] {
313
365
  }
314
366
 
315
367
  // Thin wrapper that fills in `"declaration"` for the surface field. Same back-end as parameter
316
- // and destructure callers, which use their own surface labels.
317
- function pushShortVariableFinding(context: LineRuleContext, name: string): void {
318
- 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);
319
373
  }
320
374
 
321
375
 
@@ -46,7 +46,7 @@ export function pushNegativeBooleanAt(file: SourceFile, line: number, name: stri
46
46
  * `naming.boolean-prefix` finding.
47
47
  */
48
48
  export function pushBooleanPrefixAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface): void {
49
- if (hasBooleanPrefix(name, config.booleanPrefixes) || isAcceptedBooleanStateName(name)) {
49
+ if (hasBooleanPrefix(name, config.booleanPrefixes) || isAcceptedBooleanStateName(name) || isAcceptedContractBooleanName(name, config, surface)) {
50
50
  return;
51
51
  }
52
52
  findings.push(
@@ -67,18 +67,30 @@ export function pushBooleanPrefixAt(file: SourceFile, line: number, name: string
67
67
 
68
68
  const ACCEPTED_BOOLEAN_STATE_NAMES = new Set(["acknowledged", "exists", "validated", "detected", "resolved", "selected", "installed"]);
69
69
  const ACCEPTED_BOOLEAN_STATE_SUFFIXES = ["Available", "Required", "Validated", "Detected", "Resolved", "Selected", "Installed"];
70
-
71
70
  // Some booleans are state adjectives rather than predicate phrases. Keep this list deliberately
72
- // narrow so vague names such as `ready` or `enabled` still get the maintainability prompt.
71
+ // narrow so vague local names such as `ready` or `enabled` still get the maintainability prompt.
73
72
  function isAcceptedBooleanStateName(name: string): boolean {
74
73
  return ACCEPTED_BOOLEAN_STATE_NAMES.has(name.toLowerCase()) || ACCEPTED_BOOLEAN_STATE_SUFFIXES.some((suffix) => name.endsWith(suffix));
75
74
  }
76
75
 
76
+ // CLI option bags, DTOs, and schema fields often must expose exact external key names such as
77
+ // `verbose` or `ok`. Limit the exact-name exemption to contract fields so ordinary locals still
78
+ // need predicate-style names.
79
+ function isAcceptedContractBooleanName(name: string, config: Config, surface: NamingSurface): boolean {
80
+ return surface === "interface-field" && config.acceptedBooleanNames.has(name.toLowerCase());
81
+ }
82
+
77
83
  /*
78
84
  * Allows the standard `i`, `j`, `k` loop counters and anything on `acceptedAbbreviations`. Reports
79
85
  * `naming.short-variable` for any other one or two character name as a stable advisory finding.
86
+ * `loopBodyLineCount` is the for-of caller's signal: when the binding came from a `for (const X of
87
+ * Y) { … }` head and the body spans ≤ 10 lines, the rule suppresses the finding because the name's
88
+ * lifetime is locally obvious. Other call sites (declaration, parameter, destructure) pass undefined.
80
89
  */
81
- export function pushShortVariableAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface): void {
90
+ export function pushShortVariableAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface, loopBodyLineCount?: number): void {
91
+ if (loopBodyLineCount !== undefined && loopBodyLineCount <= 10) {
92
+ return;
93
+ }
82
94
  if (name.length > 2 || ["i", "j", "k"].includes(name) || config.acceptedAbbreviations.has(name.toLowerCase())) {
83
95
  return;
84
96
  }
@@ -125,18 +137,41 @@ export function pushIdentifierQualityAt(file: SourceFile, line: number, name: st
125
137
  }
126
138
 
127
139
  // Returns `"generic"` for low-information names from the configured set, `"numbered"` for
128
- // `foo1` / `bar2` style trailing-digit identifiers, or undefined when the name is acceptable.
129
- // The variant string lands in finding metadata so consumers can split the two failure modes.
140
+ // numbered placeholder stems such as `foo1` / `mock2`, or undefined when the name is acceptable.
141
+ // Domain tokens with meaningful digits (`adr020`, `step0`, `V110`) are not placeholder names.
130
142
  function identifierQualityVariant(name: string, placeholderNames: Set<string>): string | undefined {
131
143
  if (placeholderNames.has(name.toLowerCase())) {
132
144
  return "generic";
133
145
  }
134
- if (/^[A-Za-z_$]+[0-9]+$/.test(name)) {
146
+ const numbered = name.match(/^([A-Za-z_$]+)[0-9]+$/);
147
+ const numberedStem = numbered?.[1]?.toLowerCase() ?? "";
148
+ if (numberedStem && (placeholderNames.has(numberedStem) || NUMBERED_PLACEHOLDER_STEMS.has(numberedStem))) {
135
149
  return "numbered";
136
150
  }
137
151
  return undefined;
138
152
  }
139
153
 
154
+ const NUMBERED_PLACEHOLDER_STEMS = new Set([
155
+ "arg",
156
+ "bar",
157
+ "baz",
158
+ "data",
159
+ "fixture",
160
+ "foo",
161
+ "item",
162
+ "mock",
163
+ "obj",
164
+ "object",
165
+ "param",
166
+ "stub",
167
+ "temp",
168
+ "test",
169
+ "thing",
170
+ "tmp",
171
+ "value",
172
+ "var",
173
+ ]);
174
+
140
175
  const BOOLEAN_PREFIX_REGEX_CACHE = new WeakMap<Set<string>, RegExp | null>();
141
176
 
142
177
  // Tests the cached prefix regex from `booleanPrefixRegex`. A null regex (empty prefix set) is
@@ -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 };