@blundergoat/gruff-ts 0.4.0 → 0.6.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 (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,22 +1,21 @@
1
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.
2
+ * Shared pillar-row construction and grade helper for CLI text, Markdown, HTML, and dashboard reports.
3
+ *
4
+ * Lives in its own module so renderers (`report-renderers.ts`, `report-html.ts`) and scoring (`scoring.ts`) share one implementation without cycles:
5
+ * - preserves the cross-port human Pillars table sort order (findings descending, then pillar ascending);
6
+ * - keeps unevaluated pillars (`score: null`) explicitly labeled `n/a` instead of reporting a synthetic `A/100`.
8
7
  */
9
8
  import { ruleDescriptors } from "./rules.ts";
10
9
  import type { AnalysisReport, Finding, Pillar } from "./types.ts";
11
10
 
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.
11
+ // Aggregated per-pillar row shared across text, Markdown, and HTML renderers.
12
+ //
13
+ // `isApplicable` comes from the rule catalogue so a clean pillar with zero findings still appears in the Pillars table.
14
+ // `score` is `null` (with `grade: "n/a"`) when the report explicitly marks the pillar unevaluated, such as a zero-file scan.
16
15
  interface PillarRow {
17
16
  pillar: Pillar;
18
17
  grade: string;
19
- score: number;
18
+ score: number | null;
20
19
  penalty: number;
21
20
  isApplicable: boolean;
22
21
  findings: number;
@@ -25,22 +24,19 @@ interface PillarRow {
25
24
  error: number;
26
25
  }
27
26
 
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`.
27
+ // Per-pillar severity tally for pillars with at least one finding; exported for consumers of `countSeverityByPillar`.
31
28
  interface PillarSeverityCounts {
32
29
  advisory: number;
33
30
  warning: number;
34
31
  error: number;
35
32
  }
36
33
 
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.
34
+ /**
35
+ * Builds the shared pillar summary for text, Markdown, and HTML reports.
36
+ * Keeps one row per applicable pillar even when there are no findings so consecutive runs compare the same table shape.
37
+ *
38
+ * @param report - analysis report supplying pillar scores and findings to tally by severity; an empty findings list still emits every pillar
39
+ * @returns Deterministic rows in findings DESC, pillar ASC order. Unevaluated null scores keep `n/a`; absent entries default to A/100.
44
40
  */
45
41
  function buildPillarRows(report: AnalysisReport): PillarRow[] {
46
42
  const scoreByPillar = new Map(report.score.pillars.map((entry) => [entry.pillar, entry] as const));
@@ -50,11 +46,16 @@ function buildPillarRows(report: AnalysisReport): PillarRow[] {
50
46
  return rows;
51
47
  }
52
48
 
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.
49
+ /**
50
+ * Tallies severity counts by pillar from the report's findings for the stable Pillars table schema.
51
+ * A pillar with no findings has no map entry, so the row builder supplies its zero counts.
52
+ *
53
+ * @param findings - reported findings whose pillar and severity values are tallied; an empty array yields an empty map
54
+ * @returns Map of per-pillar advisory, warning, and error counts for pillars with at least one finding.
55
+ */
56
56
  function countSeverityByPillar(findings: Finding[]): Map<Pillar, PillarSeverityCounts> {
57
57
  const severityByPillar = new Map<Pillar, PillarSeverityCounts>();
58
+ // Accumulate each finding under its primary pillar so summary severities match the report's finding list.
58
59
  for (const finding of findings) {
59
60
  const counts = severityByPillar.get(finding.pillar) ?? { advisory: 0, warning: 0, error: 0 };
60
61
  counts[finding.severity] += 1;
@@ -63,20 +64,22 @@ function countSeverityByPillar(findings: Finding[]): Map<Pillar, PillarSeverityC
63
64
  return severityByPillar;
64
65
  }
65
66
 
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.
67
+ /**
68
+ * Builds the summary row for one applicable pillar; stable contract derives the total from the same tally as its severity columns.
69
+ * Preserves an explicit `null` score as `n/a` when nothing was evaluated; falls back to `A/100` when a partial fixture omits the entry.
70
+ *
71
+ * @param pillar - pillar to label in the summary table
72
+ * @param scoreEntry - score and penalty for that pillar; `score: null` renders `n/a`, while `undefined` defaults to 100 and 0
73
+ * @param severities - reported findings by severity for that pillar; `undefined` means zero findings in every severity bucket
74
+ * @returns The applicable pillar's row with its grade, score (or `null` when unevaluated), penalty, and finding counts.
73
75
  */
74
76
  function buildPillarRow(pillar: Pillar, scoreEntry: AnalysisReport["score"]["pillars"][number] | undefined, severities: PillarSeverityCounts | undefined): PillarRow {
75
- const score = scoreEntry?.score ?? 100;
77
+ // Distinguish an explicit unevaluated `null` (0 evaluated files) from an omitted entry in a partial fixture.
78
+ const score = scoreEntry === undefined ? 100 : scoreEntry.score;
76
79
  const counts = severities ?? { advisory: 0, warning: 0, error: 0 };
77
80
  return {
78
81
  pillar,
79
- grade: grade(score),
82
+ grade: score === null ? "n/a" : grade(score),
80
83
  score,
81
84
  penalty: scoreEntry?.penalty ?? 0,
82
85
  isApplicable: true,
@@ -87,8 +90,13 @@ function buildPillarRow(pillar: Pillar, scoreEntry: AnalysisReport["score"]["pil
87
90
  };
88
91
  }
89
92
 
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.
93
+ /**
94
+ * Compares two pillar rows for descending finding count, then ascending pillar name in the shared renderer order.
95
+ *
96
+ * @param leftRow - first pillar row to compare
97
+ * @param rightRow - second pillar row to compare
98
+ * @returns negative when leftRow sorts first, zero for equal keys, and positive when rightRow sorts first
99
+ */
92
100
  function comparePillarRows(leftRow: PillarRow, rightRow: PillarRow): number {
93
101
  if (leftRow.findings !== rightRow.findings) {
94
102
  return rightRow.findings - leftRow.findings;
@@ -96,9 +104,12 @@ function comparePillarRows(leftRow: PillarRow, rightRow: PillarRow): number {
96
104
  return leftRow.pillar.localeCompare(rightRow.pillar);
97
105
  }
98
106
 
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.
107
+ /**
108
+ * Collects applicable pillars from the rule catalogue so the cross-port human table stays stable.
109
+ * Every pillar that could fire appears even when the current run produced no findings for it.
110
+ *
111
+ * @returns set of pillars represented by the registered rule descriptors
112
+ */
102
113
  function applicablePillarSet(): Set<Pillar> {
103
114
  const pillars = new Set<Pillar>();
104
115
  for (const descriptor of ruleDescriptors()) {
@@ -107,8 +118,13 @@ function applicablePillarSet(): Set<Pillar> {
107
118
  return pillars;
108
119
  }
109
120
 
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.
121
+ /**
122
+ * Converts a composite or pillar score to a letter grade using the stable 90, 80, 70, and 60 thresholds.
123
+ * Changing a threshold changes grades only for scores that cross the revised boundary.
124
+ *
125
+ * @param score - composite or pillar score to convert to a letter grade
126
+ * @returns letter grade A through D at or above 90, 80, 70, and 60 respectively, or F below 60
127
+ */
112
128
  function grade(score: number): string {
113
129
  if (score >= 90) {
114
130
  return "A";
package/src/profiles.ts CHANGED
@@ -1,14 +1,12 @@
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.
1
+ // Built-in gruff profile presets resolved by `profile:` in config and `--profile` on the CLI.
2
+ //
3
+ // Each preset is pillar-keyed with optional per-rule threshold or severity tightenings so a maintainer can read all three in one pass:
4
+ // - `resolveProfile` in `src/config.ts` expands presets against `RULE_DESCRIPTORS` and validates every rule-id reference;
5
+ // - this module owns the canonical rule catalogue view so `config.ts` stays decoupled from `rules.ts`.
7
6
  import { ruleDescriptors } from "./rules.ts";
8
7
  import type { Pillar, ProfileDefinition, ProfileRuleSetting, Severity } from "./types.ts";
9
8
 
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.
9
+ // Eleven pillars listed explicitly so `recommended` and `strict` stay greppable here instead of deriving an implicit "all rules" default.
12
10
  const ALL_PILLARS: readonly Pillar[] = [
13
11
  "complexity",
14
12
  "dead-code",
@@ -23,17 +21,15 @@ const ALL_PILLARS: readonly Pillar[] = [
23
21
  "test-quality",
24
22
  ] as const;
25
23
 
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).
24
+ // Default preset applied when neither the CLI nor config names a profile, and the implicit base when an inline `profile:` omits `extends:`.
25
+ // `gruff.recommended` flattens to an empty delta so zero-config scans and `profile: recommended` behave identically.
29
26
  const DEFAULT_PROFILE_NAME = "gruff.recommended";
30
27
 
31
28
  /**
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.
29
+ * Compact source form of a built-in profile preset before expansion against the rule catalogue.
30
+ *
31
+ * `enabledPillars` selects which pillars fire (disabling all others); `thresholds` and `severities` layer explicit tightenings on top.
32
+ * Every rule ID in `thresholds` or `severities` is validated against `RULE_DESCRIPTORS` when this module loads.
37
33
  */
38
34
  export interface BuiltInProfile {
39
35
  name: string;
@@ -43,8 +39,7 @@ export interface BuiltInProfile {
43
39
  severities: Readonly<Record<string, Severity>>;
44
40
  }
45
41
 
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.
42
+ // One-line digest of a built-in profile shown by `gruff-ts list-profiles` so operators can compare presets without expanding them.
48
43
  export interface ProfileSummary {
49
44
  name: string;
50
45
  description: string;
@@ -55,11 +50,12 @@ export interface ProfileSummary {
55
50
  }
56
51
 
57
52
  /*
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.
53
+ * The three built-in presets shipped with gruff-ts, validated against the live rule catalogue on import.
54
+ *
55
+ * Strict only tightens thresholds and enables no extra off-by-default rules, so it never reports fewer findings than recommended:
56
+ * - `gruff.minimal`: security and sensitive-data pillars only;
57
+ * - `gruff.recommended`: zero-config parity across every pillar;
58
+ * - `gruff.strict`: every pillar with tightened size and design thresholds.
63
59
  */
64
60
  const BUILT_IN_PROFILE_SPECS: readonly BuiltInProfile[] = [
65
61
  {
@@ -78,42 +74,33 @@ const BUILT_IN_PROFILE_SPECS: readonly BuiltInProfile[] = [
78
74
  },
79
75
  {
80
76
  name: "gruff.strict",
81
- description: "Every pillar enabled with tightened size, complexity, and secret thresholds for high-bar repositories.",
77
+ description: "Every pillar enabled with tightened size and design thresholds for high-bar repositories.",
82
78
  enabledPillars: ALL_PILLARS,
83
79
  thresholds: {
84
- "complexity.cognitive": 10,
85
- "complexity.cyclomatic": 10,
86
- "design.deep-relative-import": 1,
87
80
  "design.large-module-concentration": 40,
88
81
  "size.file-length": 400,
89
82
  "size.function-length": 60,
90
83
  "size.parameter-count": 4,
91
- "sensitive-data.hardcoded-env-value": 12,
92
- "sensitive-data.high-entropy-string": 24,
93
84
  },
94
85
  severities: {},
95
86
  },
96
87
  ] as const;
97
88
 
98
- // Canonical rule catalogue, captured once at module load. Sorted for determinism so flattened
99
- // profiles and `list-profiles` output never churn between runs.
89
+ // Canonical rule catalogue captured once at module load in deterministic order so flattened profiles and `list-profiles` never churn.
100
90
  const DESCRIPTORS = ruleDescriptors();
101
91
 
102
- // Every rule id gruff recognises. Exported so `config.ts` can reject a user profile that references a
103
- // rule outside the catalogue at load time (a preset typo would otherwise silently no-op at scan time).
92
+ // Every rule ID gruff recognises; used by `config.ts` and `selectors.ts` to reject typos before scanning.
104
93
  const KNOWN_RULE_IDS: ReadonlySet<string> = new Set(DESCRIPTORS.map((descriptor) => descriptor.ruleId));
105
94
 
106
- // Map from rule id to its pillar, used when validating that a preset's threshold/severity override
107
- // targets a rule inside one of the preset's enabled pillars (a dead override otherwise).
95
+ // Rule-to-pillar lookup used to reject dead preset overrides targeting a rule whose pillar the preset left disabled.
108
96
  const RULE_PILLARS: ReadonlyMap<string, Pillar> = new Map(DESCRIPTORS.map((descriptor) => [descriptor.ruleId, descriptor.pillar]));
109
97
 
110
- /*
111
- * Expands one compact preset into a flattened ProfileDefinition: a rule-id keyed delta from the
112
- * descriptor defaults. Rules outside the enabled pillars get an explicit `{ enabled: false }`; enabled
113
- * rules with a threshold/severity override get that override; enabled rules at their default are
114
- * OMITTED so the delta stays minimal and `recommended` flattens to an empty map (the parity contract).
115
- * Throws if any override key is unknown or targets a disabled pillar - this is the load-time
116
- * validation the kill criteria require.
98
+ /**
99
+ * Builds a bundled preset's profile delta so that applying it limits the scan to the selected pillars.
100
+ *
101
+ * @param spec - bundled preset supplying the profile name, enabled pillars and rule overrides
102
+ * @returns the named profile delta with disabled rules outside those pillars, threshold or severity overrides within them and no ignored paths
103
+ * @throws {Error} - if an override names an unknown rule or a rule whose pillar the preset does not enable
117
104
  */
118
105
  function profileDefinitionFromSpec(spec: BuiltInProfile): ProfileDefinition {
119
106
  assertOverrideKeys(spec);
@@ -132,8 +119,13 @@ function profileDefinitionFromSpec(spec: BuiltInProfile): ProfileDefinition {
132
119
  return { name: spec.name, rules, ignoredPaths: [] };
133
120
  }
134
121
 
135
- // Builds the override entry for an enabled rule, or undefined when the rule sits at its descriptor
136
- // default (so the flattened delta omits it). Threshold and severity are independent optional knobs.
122
+ /**
123
+ * Builds the enabled override for a rule using threshold and severity overrides from the preset.
124
+ *
125
+ * @param spec - built-in preset supplying threshold and severity override maps
126
+ * @param ruleId - catalogue rule id to look up in the preset's overrides
127
+ * @returns the enabled rule setting with configured overrides, or undefined when neither is set so the flattened profile omits that rule
128
+ */
137
129
  function enabledRuleSetting(spec: BuiltInProfile, ruleId: string): ProfileRuleSetting | undefined {
138
130
  const threshold = spec.thresholds[ruleId];
139
131
  const severity = spec.severities[ruleId];
@@ -147,11 +139,12 @@ function enabledRuleSetting(spec: BuiltInProfile, ruleId: string): ProfileRuleSe
147
139
  };
148
140
  }
149
141
 
150
- /*
151
- * Validates a preset's override keys at load time. Every key in `thresholds`/`severities` must be a
152
- * real rule id (caught by `KNOWN_RULE_IDS`) and must live in one of the preset's enabled pillars - a
153
- * threshold on a disabled rule would never fire and signals a preset authoring mistake. Throws a plain
154
- * Error (not ConfigLoadError) because this is an internal contract on bundled presets, not user input.
142
+ /**
143
+ * Validates bundled preset overrides at load time; failures throw Error rather than ConfigLoadError.
144
+ *
145
+ * @param spec - preset whose override keys must name catalogue rules in its enabled pillars
146
+ * @returns - nothing after validating the preset's override keys
147
+ * @throws {Error} - when an override names an unknown rule or a rule outside the preset's enabled pillars
155
148
  */
156
149
  function assertOverrideKeys(spec: BuiltInProfile): void {
157
150
  const enabledPillars = new Set<Pillar>(spec.enabledPillars);
@@ -167,48 +160,82 @@ function assertOverrideKeys(spec: BuiltInProfile): void {
167
160
  }
168
161
 
169
162
  /**
170
- * The bundled profile catalogue, keyed by name. Values are the flattened ProfileDefinitions that
171
- * `resolveProfile` clones and overlays. Built once at module load, which is where preset rule-id
172
- * references are validated - so an authoring mistake fails fast on import, never silently at scan time.
163
+ * Bundled profile catalogue built once at module load so invalid preset rule IDs fail fast on import instead of silently no-opping at scan time.
164
+ * `resolveProfile` clones and overlays entries from this map.
173
165
  */
174
166
  export const BUILT_IN_PROFILES: ReadonlyMap<string, ProfileDefinition> = new Map(
175
167
  BUILT_IN_PROFILE_SPECS.map((spec) => [spec.name, profileDefinitionFromSpec(spec)]),
176
168
  );
177
169
 
178
170
  /**
179
- * Reports whether a rule id is part of gruff's catalogue. Used by the profile resolver to reject a
180
- * user profile that names a rule outside `RULE_DESCRIPTORS` before any scan runs.
171
+ * Reports whether a rule ID exists in gruff's live rule catalogue.
172
+ * Used by config loading and CLI selectors to reject typos and retired IDs before scanning.
181
173
  *
182
- * @param ruleId Candidate rule id from a user profile's `rules:` block.
183
- * @returns True when the id is a known rule, false otherwise.
174
+ * @param ruleId - candidate rule ID from a config, profile, or CLI selector
175
+ * @returns True when `ruleId` is in the active catalogue; false otherwise.
184
176
  */
185
177
  export function isKnownRuleId(ruleId: string): boolean {
186
178
  return KNOWN_RULE_IDS.has(ruleId);
187
179
  }
188
180
 
181
+ /**
182
+ * Returns the pillar a rule id belongs to, for config sections that accept only one pillar's rules.
183
+ * Reuses the preset-validation map so pillar-scoped config checks read the same canonical catalogue.
184
+ *
185
+ * @param ruleId - candidate rule id from a user's configuration
186
+ * @returns - the rule's pillar, or undefined when the id is outside the catalogue
187
+ */
188
+ export function rulePillar(ruleId: string): Pillar | undefined {
189
+ return RULE_PILLARS.get(ruleId);
190
+ }
191
+
192
+ /**
193
+ * Reports whether a configured value is a pillar name rather than a rule id.
194
+ * Sensitive exclusion validation uses this check to report a pillar name where one exact rule id is required.
195
+ *
196
+ * @param candidate - value the user wrote where a rule id is required
197
+ * @returns - true when the value names one of gruff's pillars
198
+ */
199
+ export function isPillarName(candidate: string): boolean {
200
+ return ALL_PILLARS.some((pillar) => pillar === candidate);
201
+ }
202
+
203
+ // Option keys a rule descriptor declares for `rules.<id>.options`, empty when the rule has none.
204
+ // Exported for config validation so `config.ts` keeps depending on this module, not `rules.ts`.
205
+ const RULE_OPTION_KEYS: ReadonlyMap<string, readonly string[]> = new Map(DESCRIPTORS.map((descriptor) => [descriptor.ruleId, descriptor.optionKeys ?? []]));
206
+
207
+ /**
208
+ * Returns the option keys accepted in a rule's options configuration.
209
+ *
210
+ * @param ruleId - rule id already validated against the catalogue
211
+ * @returns - the declared option keys, or an empty array for an unknown rule or a rule with no options
212
+ */
213
+ export function ruleOptionKeys(ruleId: string): readonly string[] {
214
+ return RULE_OPTION_KEYS.get(ruleId) ?? [];
215
+ }
216
+
189
217
  /**
190
218
  * Returns the built-in profile names in catalogue order for error messages and CLI hints.
191
219
  *
192
- * @returns The bundled profile names, e.g. `["gruff.minimal", "gruff.recommended", "gruff.strict"]`.
220
+ * @returns - bundled profile names in catalogue order
193
221
  */
194
222
  export function builtInProfileNames(): string[] {
195
223
  return BUILT_IN_PROFILE_SPECS.map((spec) => spec.name);
196
224
  }
197
225
 
198
226
  /**
199
- * Builds the one-line digest of every built-in profile for the `list-profiles` command.
227
+ * Collects the built-in profile summaries used by the text and JSON formats of list-profiles.
200
228
  *
201
- * @returns Per-profile summaries with enabled/total rule counts, pillar selection, and threshold count.
229
+ * @returns - per-profile summaries with enabled/total rule counts, pillar selection, and threshold count
202
230
  */
203
231
  export function profileSummaries(): ProfileSummary[] {
204
232
  const totalRuleCount = DESCRIPTORS.length;
205
233
  return BUILT_IN_PROFILE_SPECS.map((spec) => {
206
234
  const definition = BUILT_IN_PROFILES.get(spec.name);
207
- const disabledCount = definition ? countDisabledRules(definition) : 0;
208
235
  return {
209
236
  name: spec.name,
210
237
  description: spec.description,
211
- enabledRuleCount: totalRuleCount - disabledCount,
238
+ enabledRuleCount: countEnabledRules(definition),
212
239
  totalRuleCount,
213
240
  enabledPillars: spec.enabledPillars,
214
241
  tightenedThresholdCount: Object.keys(spec.thresholds).length,
@@ -216,16 +243,15 @@ export function profileSummaries(): ProfileSummary[] {
216
243
  });
217
244
  }
218
245
 
219
- // Counts the rules a flattened profile explicitly disables, so the enabled count is the catalogue
220
- // size minus the disables (enabled-at-default rules are omitted from the delta and stay enabled).
221
- function countDisabledRules(definition: ProfileDefinition): number {
222
- let disabled = 0;
223
- for (const setting of definition.rules.values()) {
224
- if (setting.enabled === false) {
225
- disabled += 1;
226
- }
227
- }
228
- return disabled;
246
+ /**
247
+ * Counts enabled rules for a flattened profile, using descriptor defaults for unset rules or when no profile is supplied.
248
+ * A rule that ships off by default counts only when the profile explicitly enables it.
249
+ *
250
+ * @param definition - flattened profile definition to inspect, or undefined to evaluate catalogue defaults
251
+ * @returns total number of rules in the catalogue that are enabled for the profile
252
+ */
253
+ function countEnabledRules(definition: ProfileDefinition | undefined): number {
254
+ return DESCRIPTORS.filter((descriptor) => definition?.rules.get(descriptor.ruleId)?.enabled ?? descriptor.isEnabledByDefault !== false).length;
229
255
  }
230
256
 
231
257
  export { DEFAULT_PROFILE_NAME };