@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
package/src/config.ts CHANGED
@@ -1,90 +1,165 @@
1
- // Config loading, defaults, validation, merging, and profile resolution. The zero-dependency
2
- // YAML-subset parser, the file reader, and the value-narrowing helpers live in `config-parse.ts`.
1
+ // Resolves the project settings used by analyse, summary, report, and hook.
2
+ //
3
+ // Starts with built-in defaults and layers on settings from the user's project, profile, and command flags.
4
+ // Invalid settings produce a startup error before the user relies on the requested scan or exit gate.
3
5
  import { existsSync } from "node:fs";
4
- import { dirname, isAbsolute, join } from "node:path";
6
+ import { basename, dirname, isAbsolute, join } from "node:path";
5
7
  import { arrayValue, isString, objectValue, parseConfigFile, SUGGEST_EDIT_CONFIG, SUGGEST_INIT_FORCE } from "./config-parse.ts";
6
8
  import { ConfigLoadError } from "./config-load-error.ts";
7
- import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId } from "./profiles.ts";
8
- import type { AnalysisOptions, Config, FailThreshold, InlineProfileSpec, MinimumSeverityCommand, ProfileDefinition, ProfileRuleSetting, ProfileSpec, Severity } from "./types.ts";
9
+ import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId, ruleOptionKeys } from "./profiles.ts";
10
+ import { ruleDefaultEnabled } from "./rules.ts";
11
+ import { applyExecutionSelectors } from "./selectors.ts";
12
+ import { parseSensitiveExclusions } from "./sensitive-exclusions.ts";
13
+ import type { AnalysisOptions, Config, DeepScanBudgetOverride, FailThreshold, InlineProfileSpec, MinimumSeverityCommand, ProfileDefinition, ProfileRuleSetting, ProfileSpec, Severity } from "./types.ts";
9
14
 
15
+ // Represents one validated per-rule override before it joins the user's effective configuration.
16
+ //
17
+ // Optional fields preserve the difference between an omitted setting and an explicit value.
10
18
  type RuleOverride = Config["rules"] extends Map<string, infer RuleOverrideValue> ? RuleOverrideValue : never;
11
19
 
12
20
  const DEFAULT_CONFIG_FILES = [".gruff-ts.yaml", ".gruff.json", ".gruff.yaml", ".gruff.yml"] as const;
13
21
 
14
- // Built-in defaults applied before any user config overlays. The string lists here (accepted
15
- // abbreviations, banned generic names, boolean prefixes, …) are the stable rule contract - they
16
- // shape what every gruff scan emits by default and changing them shifts the public rule surface.
17
- // schemaVersion is fixed at `gruff-ts.config.v0.1` as the schema invariant for this release.
22
+ /*
23
+ * Every key a `.gruff-ts.yaml` may carry, at the root and inside the two blocks that take a fixed set.
24
+ *
25
+ * A key outside these sets is refused rather than ignored: a misspelled `sensitivExclusions:` or `minimumSeverty:`
26
+ * that loads silently is a setting the user believes is in force and is not, which is the one configuration failure
27
+ * a reader cannot see by looking at their own file.
28
+ */
29
+ const KNOWN_ROOT_KEYS: ReadonlySet<string> = new Set([
30
+ "schemaVersion", "profile", "deepScanBudget", "minimumSeverity", "failOn", "paths", "allowlists", "rules", "sensitiveExclusions",
31
+ ]);
32
+ const KNOWN_PATHS_KEYS: ReadonlySet<string> = new Set(["ignore"]);
33
+ const KNOWN_ALLOWLISTS_KEYS: ReadonlySet<string> = new Set([
34
+ "acceptedAbbreviations", "acceptedClassFilePairs", "placeholderNames", "trackingTokens",
35
+ ]);
36
+ // Recognised separately so the loader can refuse it by name with section 5's explanation without advertising it as a valid key.
37
+ const REFUSED_ALLOWLISTS_KEYS: ReadonlySet<string> = new Set(["secretPreviews"]);
38
+ const LEGACY_SECRET_PREVIEWS_ERROR = 'Config key "allowlists.secretPreviews" is removed in 0.6.0: FAMILY-CONTRACT.md section 5 makes category markers unconditional, so the key authorises nothing; delete it from the configuration.';
39
+ const LEGACY_MINIMUM_SEVERITY_ERROR = 'Config key "minimumSeverity" is the display floor in 0.6.0 and takes one severity, not a per-command map; move the per-command exit gate to "failOn", which is the key that gates the exit code.';
40
+ // Pinned-corpus size and scan-cost measurements set these paired defaults because either line count
41
+ // or byte count can make deep parsing disproportionately expensive while ordinary source stays below both.
42
+ export const DEEP_SCAN_DEFAULT_MAX_LINES = 20_000;
43
+ export const DEEP_SCAN_DEFAULT_MAX_BYTES = 2_000_000;
44
+
45
+ /**
46
+ * Creates the complete zero-config behavior used when a user runs Gruff without custom settings.
47
+ * User and profile values may overlay these defaults later; the schema version remains fixed for this release.
48
+ *
49
+ * @returns Default configuration with built-in allowlists, empty rule overrides, and default deep-scan limits.
50
+ */
18
51
  function defaultConfig(): Config {
19
52
  return {
20
53
  schemaVersion: "gruff-ts.config.v0.1",
21
54
  ignoredPaths: [],
22
- acceptedAbbreviations: new Set(["age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
23
- secretPreviews: new Set(),
24
- bannedGenericNames: new Set(["process", "handle", "doit", "run", "execute", "manage"]),
25
- acceptedBooleanNames: new Set(["all", "apply", "check", "dev", "enabled", "force", "fresh", "harness", "json", "ok", "verbose", "yes"]),
26
- booleanPrefixes: new Set(["is", "has", "can", "should", "does", "did", "was", "will", "may", "in", "scan", "supports", "requires", "allow", "check", "enable", "exclude", "include", "omit", "skip", "with", "without"]),
27
- hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
55
+ acceptedAbbreviations: new Set(["age", "app", "db", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
56
+ acceptedClassFilePairs: new Set(),
28
57
  placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
29
- negativeBooleanAllowed: new Set(["nostore", "nofollow", "noreferrer", "noscript", "noindex"]),
30
- knownAcronyms: new Set(["url", "http", "https", "id", "xml", "json", "html", "css", "api", "sql", "db", "io", "ui", "uuid", "ip", "tcp", "udp", "ast", "cli", "npm"]),
58
+ trackingTokens: [],
31
59
  minimumSeverity: new Map(),
32
60
  rules: new Map(),
61
+ deepScanBudget: {
62
+ enabled: true,
63
+ maxLines: DEEP_SCAN_DEFAULT_MAX_LINES,
64
+ maxBytes: DEEP_SCAN_DEFAULT_MAX_BYTES,
65
+ override: "default",
66
+ },
67
+ sensitiveExclusions: [],
33
68
  };
34
69
  }
35
70
 
36
- // Anchors a relative CLI argument against the project root; absolute paths pass through unchanged.
71
+ /**
72
+ * Resolves a user-supplied config or profile path against the caller's base directory.
73
+ * Absolute paths remain unchanged so CLI and config-file references behave consistently.
74
+ *
75
+ * @param projectRoot - base directory used to anchor relative paths
76
+ * @param path - user-supplied config or profile path to resolve
77
+ * @returns Original path when absolute, or the path joined under `projectRoot`.
78
+ */
37
79
  function absolutize(projectRoot: string, path: string): string {
38
80
  return isAbsolute(path) ? path : join(projectRoot, path);
39
81
  }
40
82
 
41
- // Reads the YAML config from disk (if any) and overlays user values onto `defaultConfig`. `shouldSkipConfig`
42
- // is the explicit opt-out; missing default file is silent (returns defaults) so projects without
43
- // `.gruff-ts.yaml` work zero-config. Throws on malformed YAML - the caller surfaces it as a fatal CLI error.
83
+ /**
84
+ * Builds effective analysis settings by layering the config file, profile, CLI budget, and rule selectors over defaults.
85
+ * A missing default file leaves built-in settings in place; read, parse, and validation errors stop loading.
86
+ *
87
+ * @param projectRoot - workspace root that anchors config discovery and profile resolution
88
+ * @param options - CLI options that can choose or skip a config file, override the profile, set budget, and select rules
89
+ * @returns Effective analysis settings after all config sources and overrides are applied.
90
+ */
44
91
  function loadConfig(projectRoot: string, options: AnalysisOptions): Config {
45
92
  const config = defaultConfig();
46
93
  const path = options.shouldSkipConfig ? undefined : selectedConfigPath(projectRoot, options);
47
- const raw: Record<string, unknown> = path ? parseConfigFile(path) : {};
94
+ const parsedConfig: Record<string, unknown> = path ? parseConfigFile(path, options.config ?? basename(path)) : {};
95
+ // Schema and supported-key checks apply to selected files. Zero-config use needs no file.
48
96
  if (path) {
49
- applyConfigValues(config, raw);
97
+ applyConfigValues(config, parsedConfig);
50
98
  }
51
- applyProfile(config, options, raw, projectRoot);
99
+ applyProfile(config, options, parsedConfig, projectRoot, path);
100
+ applyDeepScanBudgetOverride(config, options.deepScanBudget);
101
+ // The execution selectors choose which rules run, so they narrow the catalogue last, after every other source.
102
+ applyExecutionSelectors(config, options.execution);
52
103
  return config;
53
104
  }
54
105
 
55
- /*
56
- * Applies the profile layer UNDER the top-level config sections. Precedence (highest first): the CLI
57
- * `--profile` flag, then a config-file `profile:` block, then the profile's own `extends:` chain, then
58
- * the built-in default `gruff.recommended`. The flattened profile only fills rules the top-level
59
- * `rules:` block did not already set, so an explicit per-rule override always wins over the profile.
60
- * When neither the flag nor the config names a profile this is a no-op, because the implicit default
61
- * `recommended` flattens to an empty delta - the contract that keeps `--profile recommended` and a
62
- * zero-config scan byte-identical. `--no-config` skips the file but the CLI `--profile` still applies.
63
- */
64
- function applyProfile(config: Config, options: AnalysisOptions, raw: Record<string, unknown>, projectRoot: string): void {
65
- const rawSpec = options.profile !== undefined ? options.profile : raw.profile;
66
- if (rawSpec === undefined) {
106
+ /**
107
+ * Fills missing rule entries in the effective config from the selected profile and merges its ignore paths.
108
+ * Selects the CLI profile before the parsed file's profile even when file loading is skipped; profile errors stop loading.
109
+ *
110
+ * @param config - effective configuration updated in place with profile rule defaults and ignore paths
111
+ * @param options - CLI options that may supply an overriding profile specification
112
+ * @param parsedConfig - parsed config file mapping that may declare a `profile` entry
113
+ * @param projectRoot - base directory used to resolve a CLI profile path when relative
114
+ * @param configPath - resolved config path anchoring relative `profile:` entries in that config, or undefined when none loaded
115
+ * @returns Nothing. Mutates `config` in place when a profile is configured, or leaves it unchanged when omitted.
116
+ */
117
+ function applyProfile(
118
+ config: Config,
119
+ options: AnalysisOptions,
120
+ parsedConfig: Record<string, unknown>,
121
+ projectRoot: string,
122
+ configPath: string | undefined,
123
+ ): void {
124
+ const usesCliProfile = options.profile !== undefined;
125
+ const configuredProfile = usesCliProfile ? options.profile : parsedConfig.profile;
126
+ // When both sources omit a profile, the current defaults and explicit settings carry forward.
127
+ if (configuredProfile === undefined) {
67
128
  return;
68
129
  }
69
- applyProfileUnderlay(config, resolveProfile(parseProfileSpec(rawSpec), projectRoot));
130
+ // A profile named inside a config file resolves relative to that config file's directory so `--config` and hook replay stay portable.
131
+ const baseDirectory = usesCliProfile || configPath === undefined ? projectRoot : dirname(configPath);
132
+ applyProfileUnderlay(config, resolveProfile(parseProfileSpec(configuredProfile), baseDirectory));
70
133
  }
71
134
 
72
- // Lays a flattened profile under the already-applied top-level config: each rule the top-level
73
- // `rules:` block did not set takes the profile's value; profile ignored paths union with `paths.ignore`.
135
+ /**
136
+ * Fills the effective config's missing rule entries from the resolved profile.
137
+ * Profile ignore paths join explicit ignores so either user choice keeps a path out of the scan.
138
+ *
139
+ * @param config - effective configuration updated in place with fallback rule entries and merged ignore paths
140
+ * @param definition - resolved profile supplying rule settings and ignore paths
141
+ * @returns Nothing. Mutates `config.rules` and `config.ignoredPaths` in place.
142
+ */
74
143
  function applyProfileUnderlay(config: Config, definition: ProfileDefinition): void {
75
144
  for (const [ruleId, setting] of definition.rules) {
145
+ // An existing rule entry came from the user's top-level config and must remain authoritative.
76
146
  if (!config.rules.has(ruleId)) {
77
147
  config.rules.set(ruleId, profileRuleToConfig(setting));
78
148
  }
79
149
  }
150
+ // Empty profile ignores leave the user's current scan surface unchanged.
80
151
  if (definition.ignoredPaths.length > 0) {
81
152
  config.ignoredPaths = [...new Set([...config.ignoredPaths, ...definition.ignoredPaths])];
82
153
  }
83
154
  }
84
155
 
85
- // Converts a profile rule setting into the loaded-config rule shape. `options` is always a map in the
86
- // config value, so an absent profile options field becomes an empty map. Conditional spreads keep the
87
- // absent-vs-undefined distinction required under exactOptionalPropertyTypes.
156
+ /**
157
+ * Converts one profile rule into the shape used during analysis.
158
+ * Omitted fields stay absent, while missing options become an empty map for callers that enumerate them.
159
+ *
160
+ * @param setting - validated rule setting from a resolved profile
161
+ * @returns Per-rule override preserving explicit fields and defaulting `options` to an empty map.
162
+ */
88
163
  function profileRuleToConfig(setting: ProfileRuleSetting): RuleOverride {
89
164
  return {
90
165
  ...(setting.enabled !== undefined ? { enabled: setting.enabled } : {}),
@@ -94,22 +169,14 @@ function profileRuleToConfig(setting: ProfileRuleSetting): RuleOverride {
94
169
  };
95
170
  }
96
171
 
97
- /*
98
- * Resolves a profile spec into a flattened ProfileDefinition (a delta from the descriptor defaults).
99
- * Documented precedence the callers depend on, highest first: the CLI `--profile` flag, the config
100
- * `profile:` block, the `extends:` base chain, and the built-in default `gruff.recommended`. This
101
- * function owns only the `extends:` flattening; `loadConfig` applies the result under the top-level
102
- * config sections via `applyProfileUnderlay`.
103
- *
104
- * Flattening is child-wins and deterministic: a child profile's per-rule fields override the parent's
105
- * same-rule fields (last assignment wins for a repeated key), and a child `ignoredPaths` array
106
- * replaces - does not concatenate - the parent's. `chain` carries the ordered, already-visited file
107
- * paths so a cycle (A extends B extends A) is rejected with a message naming both in order, instead of
108
- * recursing until the stack overflows.
109
- *
110
- * Throws ConfigLoadError on: a missing `extends:` file, a rule id not in RULE_DESCRIPTORS, or an
111
- * inheritance cycle. Every failure surfaces at config-load time, never at scan time. File paths only:
112
- * `extends:` never fetches a remote URL or runs a shell.
172
+ /**
173
+ * Resolves a built-in, file-backed, or inline profile, with child overrides taking precedence.
174
+ * Keeps references local and uses the visit chain to report invalid profiles or explain inheritance cycles.
175
+ *
176
+ * @param spec - parsed profile reference string or inline profile specification
177
+ * @param projectRoot - directory used to resolve initial relative file paths
178
+ * @param chain - ancestor profile paths visited so far for inheritance cycle detection
179
+ * @returns Effective profile definition after resolving bases and applying overrides.
113
180
  */
114
181
  function resolveProfile(spec: ProfileSpec, projectRoot: string, chain: string[] = []): ProfileDefinition {
115
182
  if (typeof spec === "string") {
@@ -118,24 +185,38 @@ function resolveProfile(spec: ProfileSpec, projectRoot: string, chain: string[]
118
185
  return resolveInlineProfile(spec, projectRoot, chain);
119
186
  }
120
187
 
121
- // Resolves a string ref: a built-in name returns its bundled definition (terminal, no extends); any
122
- // other string is treated as a relative profile file path (no built-in match, no network, no shell).
123
- // The canonical built-in names are `gruff.minimal` / `gruff.recommended` / `gruff.strict`; the bare
124
- // short forms (`minimal`, `recommended`, `strict`) are accepted as aliases for CLI ergonomics, so a
125
- // built-in always wins over a same-named extensionless file - point `--profile` at `./name` for a file.
188
+ /**
189
+ * Resolves a bundled profile name or a local file reference into a profile definition.
190
+ * Bundled names take precedence; file resolution uses the visit chain to detect cycles and can fail with a config error.
191
+ *
192
+ * @param ref - built-in profile name or path to a local profile file
193
+ * @param projectRoot - directory from which relative file references are resolved
194
+ * @param chain - ancestor profile paths visited so far for cycle detection
195
+ * @returns Cloned built-in preset or resolved file-backed profile definition.
196
+ */
126
197
  function resolveProfileRef(ref: string, projectRoot: string, chain: string[]): ProfileDefinition {
127
198
  const builtIn = BUILT_IN_PROFILES.get(ref) ?? BUILT_IN_PROFILES.get(`gruff.${ref}`);
199
+ // A bundled match receives its own rule map and ignore list so collection edits cannot alter the preset.
128
200
  if (builtIn) {
129
201
  return cloneProfileDefinition(builtIn);
130
202
  }
131
203
  return resolveProfileFile(ref, projectRoot, chain);
132
204
  }
133
205
 
134
- // Loads and resolves a profile file, treating its parsed top-level mapping as an inline profile
135
- // spec. A missing file or a cycle caught by the chain guard throws ConfigLoadError at load time.
206
+ /**
207
+ * Loads a local profile with its inherited settings resolved before analysis.
208
+ * Resolves `ref` from `projectRoot`, uses the file's directory for relative bases, and lets other filesystem read errors propagate.
209
+ *
210
+ * @param ref - local profile file path to read and resolve
211
+ * @param projectRoot - directory used to resolve `ref` when relative
212
+ * @param chain - ancestor profile paths tracked for cycle detection
213
+ * @returns Resolved profile definition with inherited bases applied.
214
+ * @throws {ConfigLoadError} - if a profile file is missing or invalid, or inheritance revisits a path in the chain.
215
+ */
136
216
  function resolveProfileFile(ref: string, projectRoot: string, chain: string[]): ProfileDefinition {
137
217
  const path = absolutize(projectRoot, ref);
138
218
  assertNoProfileCycle(path, chain);
219
+ // A missing user-selected file cannot safely fall back to a different profile.
139
220
  if (!existsSync(path)) {
140
221
  throw new ConfigLoadError(
141
222
  `Profile extends file not found: ${path}.`,
@@ -145,17 +226,31 @@ function resolveProfileFile(ref: string, projectRoot: string, chain: string[]):
145
226
  return resolveInlineProfile(inlineSpecFromObject(parseConfigFile(path)), dirname(path), [...chain, path]);
146
227
  }
147
228
 
148
- // Resolves the base (the `extends:` target, defaulting to gruff.recommended) and overlays this spec's
149
- // rule and path overrides on top with child-wins semantics.
229
+ /**
230
+ * Resolves an inline profile by applying its overrides onto the resolved base profile.
231
+ * Omitted `extends` selects the recommended profile; invalid base profiles or child rules stop loading with `ConfigLoadError`.
232
+ *
233
+ * @param spec - inline profile overrides and optional `extends` base reference
234
+ * @param projectRoot - directory containing the profile file for resolving relative bases
235
+ * @param chain - ancestor profile paths used to detect inheritance cycles
236
+ * @returns Profile definition combining the resolved base and inline overrides.
237
+ */
150
238
  function resolveInlineProfile(spec: InlineProfileSpec, projectRoot: string, chain: string[]): ProfileDefinition {
151
239
  const base = resolveProfileRef(spec.extends ?? DEFAULT_PROFILE_NAME, projectRoot, chain);
152
240
  return overlayProfile(base, spec);
153
241
  }
154
242
 
155
- // Overlays a child inline spec on a resolved base. Per-rule fields merge (child wins field-by-field);
156
- // the child `ignoredPaths` array replaces the base's when present, else the base's is inherited.
243
+ /**
244
+ * Builds a new profile with inline settings taking precedence over the resolved base field by field.
245
+ * A supplied ignore list replaces the base list while omission inherits it; throws `ConfigLoadError` for unknown child rule IDs.
246
+ *
247
+ * @param base - resolved base profile definition supplying inherited rules and ignore paths
248
+ * @param spec - inline profile overrides to apply on top of `base`
249
+ * @returns New profile definition with child overrides applied over `base`.
250
+ */
157
251
  function overlayProfile(base: ProfileDefinition, spec: InlineProfileSpec): ProfileDefinition {
158
252
  const rules = new Map(base.rules);
253
+ // Each child rule may override only the fields the user supplied while retaining inherited fields.
159
254
  for (const [ruleId, setting] of Object.entries(spec.rules ?? {})) {
160
255
  assertKnownProfileRule(ruleId);
161
256
  rules.set(ruleId, mergeRuleSetting(rules.get(ruleId), setting));
@@ -164,22 +259,40 @@ function overlayProfile(base: ProfileDefinition, spec: InlineProfileSpec): Profi
164
259
  return { name: base.name, rules, ignoredPaths };
165
260
  }
166
261
 
167
- // Field-level child-wins merge for one rule's settings: spread the parent then the child so every key
168
- // the child sets (including `enabled: false`) overrides the parent while unset child keys inherit. Both
169
- // inputs are built with conditional spreads upstream, so neither carries explicit-undefined keys that
170
- // would clobber an inherited value.
262
+ /**
263
+ * Merges one inherited rule setting with the user's child fields.
264
+ * Explicit false and zero values win, omitted fields continue to inherit, and no parent yields only child fields.
265
+ *
266
+ * @param parent - inherited rule setting from the base profile, when present
267
+ * @param child - child rule setting whose defined fields override `parent`
268
+ * @returns Combined rule setting with child fields overriding any inherited fields.
269
+ */
171
270
  function mergeRuleSetting(parent: ProfileRuleSetting | undefined, child: ProfileRuleSetting): ProfileRuleSetting {
172
271
  return { ...parent, ...child };
173
272
  }
174
273
 
175
- // Defensive copy so overlays never mutate a shared built-in definition's rule map or ignore list.
274
+ /**
275
+ * Copies a resolved profile with its own rule map and ignore list while inner rule settings remain shared.
276
+ * Use this for bundled profiles whose shared definitions must remain stable across commands.
277
+ *
278
+ * @param definition - profile definition whose collections are shallow-cloned
279
+ * @returns Cloned profile definition with independent `rules` map and `ignoredPaths` array.
280
+ */
176
281
  function cloneProfileDefinition(definition: ProfileDefinition): ProfileDefinition {
177
282
  return { name: definition.name, rules: new Map(definition.rules), ignoredPaths: [...definition.ignoredPaths] };
178
283
  }
179
284
 
180
- // Guards the `extends:` chain against cycles, naming the whole chain in visit order so the user can
181
- // see both ends of the loop. A revisited `key` throws ConfigLoadError before the recursion repeats.
285
+ /**
286
+ * Checks the profile path against the active resolution chain to prevent recursive loading from looping.
287
+ * Throws with the visit order so users can find and break the `extends` cycle.
288
+ *
289
+ * @param key - resolved profile path about to be loaded
290
+ * @param chain - ordered ancestor profile paths currently being resolved
291
+ * @returns Nothing. Completes when `key` is not already present in `chain`.
292
+ * @throws {ConfigLoadError} - when the key is already in the chain of profile paths being resolved.
293
+ */
182
294
  function assertNoProfileCycle(key: string, chain: string[]): void {
295
+ // A repeated path means the user's profile chain has returned to a file already being resolved.
183
296
  if (chain.includes(key)) {
184
297
  throw new ConfigLoadError(
185
298
  `Profile inheritance cycle detected: ${[...chain, key].join(" -> ")}.`,
@@ -188,9 +301,16 @@ function assertNoProfileCycle(key: string, chain: string[]): void {
188
301
  }
189
302
  }
190
303
 
191
- // Validates a user profile rule id against the catalogue so a typo never silently no-ops at scan
192
- // time: an id outside RULE_DESCRIPTORS throws ConfigLoadError at load time.
304
+ /**
305
+ * Checks a profile's rule identifier against the catalogue before it can affect analysis.
306
+ * Throws for unknown names so users do not mistake a typo for applied policy.
307
+ *
308
+ * @param ruleId - rule identifier configured in a profile's `rules` block
309
+ * @returns Nothing. Completes when `ruleId` exists in the rule catalogue.
310
+ * @throws {ConfigLoadError} - when the rule id is not in the gruff-ts rule catalogue.
311
+ */
193
312
  function assertKnownProfileRule(ruleId: string): void {
313
+ // A name outside the rule catalogue cannot produce the behavior the user requested.
194
314
  if (!isKnownRuleId(ruleId)) {
195
315
  throw new ConfigLoadError(
196
316
  `Unknown rule id in profile: ${JSON.stringify(ruleId)}.`,
@@ -199,16 +319,21 @@ function assertKnownProfileRule(ruleId: string): void {
199
319
  }
200
320
  }
201
321
 
202
- /*
203
- * Parses the raw `profile:` value (from YAML/JSON or the CLI flag) into a typed ProfileSpec. A string
204
- * is a built-in name or file path; a mapping is an inline spec. Throws ConfigLoadError on any other
205
- * shape so a malformed `profile:` block surfaces as a clean config error, not a downstream crash.
322
+ /**
323
+ * Converts the user's parsed profile value into a named/file reference or inline profile.
324
+ * An empty mapping leaves base selection to the profile resolver.
325
+ *
326
+ * @param configuredProfile - raw `profile` setting from CLI options or parsed config
327
+ * @returns Profile reference string or validated inline profile specification.
328
+ * @throws {ConfigLoadError} - for a value outside string or mapping, a non-string extends, or a rule mapping that fails field validation.
206
329
  */
207
- function parseProfileSpec(rawSpec: unknown): ProfileSpec {
208
- if (typeof rawSpec === "string") {
209
- return rawSpec;
330
+ function parseProfileSpec(configuredProfile: unknown): ProfileSpec {
331
+ // A string preserves the exact built-in name or local path the user selected.
332
+ if (typeof configuredProfile === "string") {
333
+ return configuredProfile;
210
334
  }
211
- const block = objectValue(rawSpec);
335
+ const block = objectValue(configuredProfile);
336
+ // A non-string value with another shape cannot identify a profile, so config loading stops.
212
337
  if (!block) {
213
338
  throw new ConfigLoadError(
214
339
  "`profile:` must be a built-in name, a profile file path, or a mapping with `extends:` and overrides.",
@@ -218,251 +343,591 @@ function parseProfileSpec(rawSpec: unknown): ProfileSpec {
218
343
  return inlineSpecFromObject(block);
219
344
  }
220
345
 
221
- // Extracts the supported inline-profile keys (`extends`, `rules`, `ignoredPaths`) from a parsed
222
- // mapping; other keys such as a `schemaVersion` on a shared profile file are ignored so it reads the
223
- // same as an embedded block. A bad `extends` type or malformed override throws ConfigLoadError here.
346
+ /**
347
+ * Extracts overrides from a parsed inline or file-backed profile mapping.
348
+ * Without an `extends` field, resolution uses the recommended profile; extra top-level fields have no effect.
349
+ *
350
+ * @param block - parsed key-value mapping representing an inline or file-backed profile
351
+ * @returns Validated inline profile specification with optional `extends`, `rules`, and `ignoredPaths`.
352
+ * @throws {ConfigLoadError} - when extends is supplied with a non-string value or a rule mapping fails field validation.
353
+ */
224
354
  function inlineSpecFromObject(block: Record<string, unknown>): InlineProfileSpec {
225
355
  const spec: InlineProfileSpec = {};
356
+ // A supplied base must name a built-in profile or local profile file.
226
357
  if ("extends" in block) {
358
+ // Non-string bases cannot resolve to the profile the user intended.
227
359
  if (!isString(block.extends)) {
228
360
  throw new ConfigLoadError("`profile.extends` must be a string: a built-in name or a relative profile file path.", SUGGEST_EDIT_CONFIG);
229
361
  }
230
362
  spec.extends = block.extends;
231
363
  }
232
364
  const rulesBlock = objectValue(block.rules);
365
+ // Without a rules mapping, the profile adds no rule overrides.
233
366
  if (rulesBlock) {
234
367
  spec.rules = profileRulesFromBlock(rulesBlock);
235
368
  }
369
+ // An ignoredPaths key replaces inherited ignores. A non-list value or a list without strings clears them.
236
370
  if ("ignoredPaths" in block) {
237
371
  spec.ignoredPaths = arrayValue(block.ignoredPaths).filter(isString);
238
372
  }
239
373
  return spec;
240
374
  }
241
375
 
242
- // Builds the per-rule settings map for an inline profile, reusing the same validation as the
243
- // top-level `rules:` block (`ruleConfigValue` throws on a non-numeric threshold or bad severity).
376
+ /**
377
+ * Extracts rule settings from the parsed profile `rules` mapping and rejects non-mapping values so typos never become silent no-ops.
378
+ * Shares field validation with direct config and propagates `ConfigLoadError` for invalid fields; rule IDs are checked during overlay.
379
+ *
380
+ * @param rulesBlock - parsed `rules` mapping from a profile definition
381
+ * @returns Record mapping rule identifiers to validated profile rule settings.
382
+ * @throws {ConfigLoadError} when a rule entry is not a mapping or fails field validation.
383
+ */
244
384
  function profileRulesFromBlock(rulesBlock: Record<string, unknown>): Record<string, ProfileRuleSetting> {
245
385
  const rules: Record<string, ProfileRuleSetting> = {};
246
386
  for (const [ruleId, value] of Object.entries(rulesBlock)) {
247
387
  const rule = objectValue(value);
248
- if (rule) {
249
- rules[ruleId] = ruleConfigValue(rule);
388
+ // Reject scalar or array rule entries such as `size.function-length: true` instead of silently ignoring the user's policy.
389
+ if (!rule) {
390
+ throw new ConfigLoadError(
391
+ `Invalid config for rule ${JSON.stringify(ruleId)}: expected a mapping with enabled, threshold, severity, or options.`,
392
+ SUGGEST_EDIT_CONFIG,
393
+ );
250
394
  }
395
+ rules[ruleId] = ruleConfigValue(ruleId, rule);
251
396
  }
252
397
  return rules;
253
398
  }
254
399
 
255
- // Explicit `--config` wins; otherwise look for the first supported config at the project root. Returning
256
- // undefined means "no config" - callers must treat that as "use defaults", not as an error.
400
+ /**
401
+ * Selects the explicit `--config` path or the first supported project-root config file.
402
+ * An explicit path resolves relative to the launch directory as scan targets are; no match selects zero-config behavior without error.
403
+ *
404
+ * @param projectRoot - workspace root searched when no explicit `--config` path is supplied
405
+ * @param options - CLI analysis options that may specify an explicit `config` path
406
+ * @returns Resolved path to the selected configuration file, or `undefined` when none applies.
407
+ */
257
408
  function selectedConfigPath(projectRoot: string, options: AnalysisOptions): string | undefined {
258
- return options.config ? absolutize(projectRoot, options.config) : defaultConfigPath(projectRoot);
409
+ return options.config ? absolutize(process.cwd(), options.config) : defaultConfigPath(projectRoot);
259
410
  }
260
411
 
261
- // Top-level sections applied in a fixed order: schemaVersion → minimumSeverity → paths → allowlists
262
- // → rules. schemaVersion runs first because every later parse depends on the contract version it
263
- // declares, and minimumSeverity runs next so CLI consumers reading it during normalizeOptions see
264
- // a populated map. Order does not affect correctness today but the stable application order keeps
265
- // later overrides predictable if interdependencies are added.
266
- function applyConfigValues(config: Config, raw: Record<string, unknown>): void {
267
- applySchemaVersionConfig(raw);
268
- applyMinimumSeverityConfig(config, raw);
269
- applyPathConfig(config, raw);
270
- applyAllowlistConfig(config, raw);
271
- applyRuleConfig(config, raw);
412
+ /**
413
+ * Updates the effective config from the parsed file before applying profiles and CLI overrides.
414
+ * Checks the schema and supported keys first, then validates each section; a `ConfigLoadError` stops loading on a rejected setting.
415
+ *
416
+ * @param config - effective configuration mutated in place with validated settings from the file
417
+ * @param parsedConfig - raw parsed configuration mapping to validate and apply
418
+ * @returns Nothing. Updates `config` in place across schema, keys, budget, severity, paths, allowlists, rules, and exclusions.
419
+ */
420
+ function applyConfigValues(config: Config, parsedConfig: Record<string, unknown>): void {
421
+ applySchemaVersionConfig(parsedConfig);
422
+ assertKnownKeys(parsedConfig, KNOWN_ROOT_KEYS, "");
423
+ assertKnownKeys(objectValue(parsedConfig.paths), KNOWN_PATHS_KEYS, "paths.");
424
+ assertKnownKeys(objectValue(parsedConfig.allowlists), KNOWN_ALLOWLISTS_KEYS, "allowlists.", REFUSED_ALLOWLISTS_KEYS);
425
+ applyDeepScanBudgetConfig(config, parsedConfig);
426
+ applyDisplayFloorConfig(config, parsedConfig);
427
+ applyFailOnConfig(config, parsedConfig);
428
+ applyPathConfig(config, parsedConfig);
429
+ applyAllowlistConfig(config, parsedConfig);
430
+ applyRuleConfig(config, parsedConfig);
431
+ config.sensitiveExclusions = parseSensitiveExclusions(parsedConfig);
272
432
  }
273
433
 
274
- /*
275
- * Validates the required `schemaVersion` top-level field. Pre-1.0 break: configs missing the field
276
- * or carrying any other version string are rejected (throws with a documented error listing the
277
- * supported version) because there is no migration shim under the no-legacy-compat contract. The
278
- * function does not mutate the loaded config because the only supported value matches
279
- * `defaultConfig().schemaVersion` already; future versions would extend the union and require a
280
- * write here. The schema invariant is fixed at `gruff-ts.config.v0.1`.
281
- */
282
- function applySchemaVersionConfig(raw: Record<string, unknown>): void {
283
- const schemaVersion = raw.schemaVersion;
434
+ /**
435
+ * Validates config key names before analysis because an ignored typo would leave a setting out of force.
436
+ * The error names the first rejected key and gives a stable, sorted list of accepted keys, excluding separately refused legacy keys.
437
+ *
438
+ * @param block - config mapping to validate. An omitted block is allowed.
439
+ * @param known - permitted unprefixed key names for the block
440
+ * @param prefix - config path prefix shown before key names in the diagnostic
441
+ * @param separatelyRefused - optional legacy keys deferred to a dedicated migration error; an empty set rejects every unknown key here
442
+ * @returns nothing. Validation continues for an omitted block or one whose keys are all recognised.
443
+ * @throws {ConfigLoadError} - the block contains a key outside the known set
444
+ */
445
+ function assertKnownKeys(
446
+ block: Record<string, unknown> | undefined,
447
+ known: ReadonlySet<string>,
448
+ prefix: string,
449
+ separatelyRefused: ReadonlySet<string> = new Set(),
450
+ ): void {
451
+ // A missing or non-mapping section supplies no keys here, so the caller can continue its other config checks.
452
+ if (!block) {
453
+ return;
454
+ }
455
+ const unknownKey = Object.keys(block).find((key) => !known.has(key) && !separatelyRefused.has(key));
456
+ if (unknownKey === undefined) {
457
+ return;
458
+ }
459
+ const rejected = JSON.stringify(prefix + unknownKey);
460
+ const accepted = [...known].sort().map((key) => prefix + key).join(", ");
461
+ throw new ConfigLoadError(`Unknown config key ${rejected}. Valid keys: ${accepted}.`, SUGGEST_EDIT_CONFIG);
462
+ }
463
+
464
+ /**
465
+ * Applies the user's configured line and byte limits before analysis so the report can explain any truncated checks.
466
+ * Omitted settings inherit the current budget; null values are invalid.
467
+ *
468
+ * @param config - effective configuration whose `deepScanBudget` is updated in place
469
+ * @param parsedConfig - parsed config mapping that may contain a `deepScanBudget` block
470
+ * @returns Nothing. Updates `config.deepScanBudget` in place when `deepScanBudget` is configured.
471
+ * @throws {ConfigLoadError} for an invalid budget mapping, unknown key, or invalid enabled flag or limit.
472
+ */
473
+ function applyDeepScanBudgetConfig(config: Config, parsedConfig: Record<string, unknown>): void {
474
+ const rawBudget = parsedConfig.deepScanBudget;
475
+ // A project with no budget block keeps the current limits.
476
+ if (rawBudget === undefined) {
477
+ return;
478
+ }
479
+ const budget = objectValue(rawBudget);
480
+ // An explicit null does not select a budget. Users who want unlimited analysis can set enabled to false.
481
+ if (!budget) {
482
+ throw new ConfigLoadError('Config key "deepScanBudget" must be a mapping.', SUGGEST_EDIT_CONFIG);
483
+ }
484
+ const allowedKeys = new Set(["enabled", "maxLines", "maxBytes"]);
485
+ const unknownKey = Object.keys(budget).find((key) => !allowedKeys.has(key));
486
+ // A typo such as maxLine could make a user think a limit is in effect when it was ignored.
487
+ if (unknownKey) {
488
+ throw new ConfigLoadError(`Unknown deepScanBudget key: ${JSON.stringify(unknownKey)}. Valid keys: enabled, maxLines, maxBytes.`, SUGGEST_EDIT_CONFIG);
489
+ }
490
+ // A user can change just the line or byte limit and keep the inherited enabled setting.
491
+ const enabled = budget.enabled === undefined ? config.deepScanBudget.enabled : budget.enabled;
492
+ // An explicit null or string gives the user an error with the accepted settings.
493
+ if (typeof enabled !== "boolean") {
494
+ throw new ConfigLoadError('Config key "deepScanBudget.enabled" must be true or false.', SUGGEST_EDIT_CONFIG);
495
+ }
496
+ const maxLines = positiveBudgetLimit(budget.maxLines, "maxLines", config.deepScanBudget.maxLines);
497
+ const maxBytes = positiveBudgetLimit(budget.maxBytes, "maxBytes", config.deepScanBudget.maxBytes);
498
+ config.deepScanBudget = { enabled, maxLines, maxBytes, override: "config" };
499
+ }
500
+
501
+ /**
502
+ * Validates a configured scan bound as a safe positive integer, or returns the caller's fallback when omitted.
503
+ *
504
+ * @param configuredLimit - raw limit value supplied under `deepScanBudget`
505
+ * @param key - limit key name (`maxLines` or `maxBytes`) reported in the config error
506
+ * @param fallback - inherited bound returned when `configuredLimit` is undefined
507
+ * @returns Validated positive integer limit, or `fallback` when omitted.
508
+ * @throws {ConfigLoadError} - when the limit is set but is not a number, not a safe integer, or not greater than zero.
509
+ */
510
+ function positiveBudgetLimit(configuredLimit: unknown, key: "maxLines" | "maxBytes", fallback: number): number {
511
+ if (configuredLimit === undefined) {
512
+ return fallback;
513
+ }
514
+ if (typeof configuredLimit !== "number" || !Number.isSafeInteger(configuredLimit) || configuredLimit <= 0) {
515
+ throw new ConfigLoadError(`Config key "deepScanBudget.${key}" must be a positive integer.`, SUGGEST_EDIT_CONFIG);
516
+ }
517
+ return configuredLimit;
518
+ }
519
+
520
+ /**
521
+ * Applies a CLI budget choice to the effective config; an absent choice leaves the existing budget in effect.
522
+ * Enabling sets both limits from the CLI, disabling retains the existing limits, and either choice records the CLI as source.
523
+ *
524
+ * @param config - effective configuration whose `deepScanBudget` is updated in place
525
+ * @param override - CLI budget override when supplied, or `undefined` to preserve existing settings
526
+ * @returns Nothing. Mutates `config.deepScanBudget` when `override` is present.
527
+ */
528
+ function applyDeepScanBudgetOverride(config: Config, override: DeepScanBudgetOverride | undefined): void {
529
+ if (!override) {
530
+ return;
531
+ }
532
+ config.deepScanBudget = override.enabled
533
+ ? { enabled: true, maxLines: override.maxLines, maxBytes: override.maxBytes, override: "cli" }
534
+ : { ...config.deepScanBudget, enabled: false, override: "cli" };
535
+ }
536
+
537
+ /**
538
+ * Checks the parsed configuration's required schema version before any user setting affects the scan.
539
+ * Throws with migration guidance for missing or unsupported versions; the supported value already matches the default config.
540
+ *
541
+ * @param parsedConfig - raw parsed configuration mapping expected to carry `schemaVersion`
542
+ * @returns Nothing. Completes when `schemaVersion` equals `"gruff-ts.config.v0.1"`.
543
+ * @throws {ConfigLoadError} - when schemaVersion is missing or is any value other than "gruff-ts.config.v0.1".
544
+ */
545
+ function applySchemaVersionConfig(parsedConfig: Record<string, unknown>): void {
546
+ const schemaVersion = parsedConfig.schemaVersion;
547
+ // A missing version leaves Gruff unable to know which configuration contract the user intended.
284
548
  if (schemaVersion === undefined) {
285
549
  throw new ConfigLoadError('Config must include `schemaVersion: gruff-ts.config.v0.1` at the top.', SUGGEST_INIT_FORCE);
286
550
  }
551
+ // Any other version is unsupported and must not be interpreted as the current schema.
287
552
  if (schemaVersion !== "gruff-ts.config.v0.1") {
288
553
  throw new ConfigLoadError(`Unsupported schemaVersion: ${JSON.stringify(schemaVersion)}. Supported: "gruff-ts.config.v0.1".`, SUGGEST_INIT_FORCE);
289
554
  }
290
555
  }
291
556
 
292
- // Parses the `minimumSeverity:` block into a Map keyed by command name. Validation throws on
293
- // `dashboard` specifically (no `--fail-on` flag exists for it), on unknown command keys, and on
294
- // every non-canonical value. Missing block is allowed - it just leaves the map empty so CLI
295
- // consumers fall through to the binary default.
296
- function applyMinimumSeverityConfig(config: Config, raw: Record<string, unknown>): void {
297
- const block = objectValue(raw.minimumSeverity);
298
- if (!block) {
557
+ /**
558
+ * Sets the report's display floor. Existing per-command gates must move to failOn to keep their build behavior.
559
+ *
560
+ * @param config - effective config whose display floor is updated
561
+ * @param parsedConfig - file settings that may supply a minimumSeverity value
562
+ * @returns - nothing. Updates the effective config in place when a valid floor is supplied.
563
+ * @throws {ConfigLoadError} - when minimumSeverity is a mapping or a supplied value other than advisory, warning, or error
564
+ */
565
+ function applyDisplayFloorConfig(config: Config, parsedConfig: Record<string, unknown>): void {
566
+ const configuredFloor = parsedConfig.minimumSeverity;
567
+ // An omitted key leaves the current display floor in effect.
568
+ if (configuredFloor === undefined) {
299
569
  return;
300
570
  }
571
+ if (objectValue(configuredFloor)) {
572
+ throw new ConfigLoadError(LEGACY_MINIMUM_SEVERITY_ERROR, "Rename the `minimumSeverity:` mapping to `failOn:`, and set `minimumSeverity:` to one severity if you also want a display floor.");
573
+ }
574
+ if (configuredFloor !== "advisory" && configuredFloor !== "warning" && configuredFloor !== "error") {
575
+ throw new ConfigLoadError(`Config key "minimumSeverity" must be one of: advisory, warning, error. Got: ${JSON.stringify(configuredFloor)}.`, SUGGEST_EDIT_CONFIG);
576
+ }
577
+ config.displayFloor = configuredFloor;
578
+ }
579
+
580
+ /**
581
+ * Loads a project's per-command exit gates so a developer and CI get the same result without repeating `--fail-on`.
582
+ *
583
+ * @param config - effective configuration whose `minimumSeverity` map receives validated command gates
584
+ * @param parsedConfig - parsed configuration mapping that may supply a `failOn` section
585
+ * @returns Nothing. Populates `config.minimumSeverity` in place for each configured command gate.
586
+ * @throws {ConfigLoadError} for a non-mapping, an unknown command, or an invalid threshold.
587
+ */
588
+ function applyFailOnConfig(config: Config, parsedConfig: Record<string, unknown>): void {
589
+ // Omitting failOn keeps the current command thresholds.
590
+ if (parsedConfig.failOn === undefined) {
591
+ return;
592
+ }
593
+ const block = objectValue(parsedConfig.failOn);
594
+ // A bare `failOn: warning` gives no command to gate. Ask the user to name one, such as analyse.
595
+ if (!block) {
596
+ throw new ConfigLoadError('Config key "failOn" must be a mapping of commands to thresholds.', SUGGEST_EDIT_CONFIG);
597
+ }
598
+ // Apply each gate so a project can fail analyse at warning while allowing summary to exit successfully.
301
599
  for (const [commandName, value] of Object.entries(block)) {
302
- config.minimumSeverity.set(assertMinimumSeverityCommand(commandName), parseFailThresholdConfig(value));
600
+ config.minimumSeverity.set(assertGatedCommand(commandName), parseFailThresholdConfig(value));
303
601
  }
304
602
  }
305
603
 
306
- /*
307
- * Validates one `minimumSeverity:` map key. Throws on `dashboard` specifically because the
308
- * dashboard subcommand has no `--fail-on` flag; accepting the key would silently no-op and
309
- * operators would expect a gate that never fires. Throws on unknown commands so typos surface at
310
- * load time instead of as silent CI footguns.
604
+ /**
605
+ * Checks a `failOn` command name to confirm it supports a configured exit threshold.
606
+ * Throws for `dashboard` and unknown names because they cannot provide the gate the configuration implies.
607
+ *
608
+ * @param commandName - command key read from the `failOn` configuration block
609
+ * @returns Unchanged `commandName` narrowed to the supported gated commands.
610
+ * @throws {ConfigLoadError} - when commandName is dashboard or any name other than analyse, summary, or report.
311
611
  */
312
- function assertMinimumSeverityCommand(commandName: string): MinimumSeverityCommand {
612
+ function assertGatedCommand(commandName: string): MinimumSeverityCommand {
613
+ // Dashboard has no --fail-on behavior, so accepting it would promise users a gate that cannot run.
313
614
  if (commandName === "dashboard") {
314
- throw new ConfigLoadError('Unknown command in minimumSeverity: "dashboard". The dashboard subcommand does not currently expose a --fail-on flag; configuring its threshold is not supported.', "Remove the `dashboard:` line from `minimumSeverity:` in `.gruff-ts.yaml`, or open an issue if dashboard should gate.");
615
+ throw new ConfigLoadError('Unknown command in failOn: "dashboard". The dashboard subcommand does not currently expose a --fail-on flag; configuring its threshold is not supported.', "Remove the `dashboard:` line from `failOn:` in `.gruff-ts.yaml`, or open an issue if dashboard should gate.");
315
616
  }
617
+ // These are the only commands whose user-facing exit status supports a configured minimum severity.
316
618
  if (commandName === "analyse" || commandName === "summary" || commandName === "report") {
317
619
  return commandName;
318
620
  }
319
- throw new ConfigLoadError(`Unknown command in minimumSeverity: ${JSON.stringify(commandName)}. Valid keys: analyse, summary, report.`, SUGGEST_EDIT_CONFIG);
621
+ throw new ConfigLoadError(`Unknown command in failOn: ${JSON.stringify(commandName)}. Valid keys: analyse, summary, report.`, SUGGEST_EDIT_CONFIG);
320
622
  }
321
623
 
322
- /*
323
- * Validates one `FailThreshold` value coming from YAML. Throws on every non-canonical value with a
324
- * clear error listing the four supported strings. `never` is rejected explicitly because earlier
325
- * cross-port drafts considered it as the off-switch value before the family converged on `none`;
326
- * guarding against drift back to `never` keeps the cross-port vocabulary aligned.
624
+ /**
625
+ * Validates a configured exit threshold against the CLI's accepted values.
626
+ * Unsupported values fail with the accepted choices instead of silently changing the user's CI gate.
627
+ *
628
+ * @param configuredThreshold - raw threshold value configured for a gated command
629
+ * @returns Validated fail threshold (`none`, `advisory`, `warning`, or `error`).
630
+ * @throws {ConfigLoadError} - when the configured threshold is not none, advisory, warning, or error.
327
631
  */
328
- function parseFailThresholdConfig(rawValue: unknown): FailThreshold {
329
- if (rawValue === "none" || rawValue === "advisory" || rawValue === "warning" || rawValue === "error") {
330
- return rawValue;
632
+ function parseFailThresholdConfig(configuredThreshold: unknown): FailThreshold {
633
+ // CLI resolution receives none as an explicit gate choice, distinct from an omitted threshold.
634
+ if (configuredThreshold === "none" || configuredThreshold === "advisory" || configuredThreshold === "warning" || configuredThreshold === "error") {
635
+ return configuredThreshold;
331
636
  }
332
- throw new ConfigLoadError(`FailThreshold must be one of: advisory, warning, error, none. Got: ${JSON.stringify(rawValue)}.`, SUGGEST_EDIT_CONFIG);
637
+ throw new ConfigLoadError(`FailThreshold must be one of: advisory, warning, error, none. Got: ${JSON.stringify(configuredThreshold)}.`, SUGGEST_EDIT_CONFIG);
333
638
  }
334
639
 
335
- // Per-command lookup used by the CLI precedence chain (CLI flag > config > binary default).
336
- // Returns undefined when the user did not configure that command so the caller can fall through
337
- // to the binary default. Exported so the CLI consumers in `cli-program.ts` can consult it.
640
+ /**
641
+ * Looks up the configured threshold for one command during CLI option resolution.
642
+ * Missing values mean the user did not override that command, so callers continue to the binary default.
643
+ *
644
+ * @param config - effective configuration holding per-command exit thresholds
645
+ * @param command - gated subcommand whose configured threshold is requested
646
+ * @returns Configured threshold for `command`, or `undefined` when unconfigured.
647
+ */
338
648
  function minimumSeverityFor(config: Config, command: MinimumSeverityCommand): FailThreshold | undefined {
339
649
  return config.minimumSeverity.get(command);
340
650
  }
341
651
 
342
- // Replaces `ignoredPaths` with the user list. Non-string entries are silently dropped - invalid
343
- // YAML shapes should not abort the analysis run.
344
- function applyPathConfig(config: Config, raw: Record<string, unknown>): void {
345
- const paths = objectValue(raw.paths);
652
+ /**
653
+ * Replaces the effective config's path exclusions with strings from the parsed `paths.ignore` list.
654
+ * A missing list, a non-list value, or a list with no strings clears these config-based exclusions.
655
+ *
656
+ * @param config - effective configuration whose `ignoredPaths` list is replaced in place
657
+ * @param parsedConfig - parsed configuration mapping that may contain `paths.ignore`
658
+ * @returns Nothing. Updates `config.ignoredPaths` in place.
659
+ */
660
+ function applyPathConfig(config: Config, parsedConfig: Record<string, unknown>): void {
661
+ const paths = objectValue(parsedConfig.paths);
346
662
  config.ignoredPaths = arrayValue(paths?.ignore).filter(isString);
347
663
  }
348
664
 
349
- // The allowlist section is the main lever users have for tuning gruff to their conventions.
350
- // `acceptedAbbreviations` and the seven naming lists are lowercased on import so case-insensitive
351
- // matching is the stable behaviour regardless of how users write entries.
352
- function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): void {
353
- const allowlists = objectValue(raw.allowlists);
665
+ /**
666
+ * Updates the effective config from parsed allowlists, lowercasing supplied naming values for matching.
667
+ * A present naming or tracking key replaces its setting (non-lists or stringless lists clear it); omitted keys keep theirs.
668
+ *
669
+ * @param config - effective configuration whose allowlist sets and tracking tokens are updated in place
670
+ * @param parsedConfig - parsed configuration mapping that may contain an `allowlists` section
671
+ * @returns Nothing. Mutates `config` allowlist sets and compiled `trackingTokens` in place.
672
+ * @throws {ConfigLoadError} - when allowlists.secretPreviews is present or a tracking token string is an invalid regular expression.
673
+ */
674
+ function applyAllowlistConfig(config: Config, parsedConfig: Record<string, unknown>): void {
675
+ const allowlists = objectValue(parsedConfig.allowlists);
354
676
  const abbreviations = arrayValue(allowlists?.acceptedAbbreviations).filter(isString);
677
+ // A supplied abbreviation list replaces the defaults, including when the user intentionally supplies an empty list.
355
678
  if (allowlists && "acceptedAbbreviations" in allowlists) {
356
679
  config.acceptedAbbreviations = new Set(abbreviations.map((value) => value.toLowerCase()));
357
680
  }
358
- config.secretPreviews = new Set(arrayValue(allowlists?.secretPreviews).filter(isString));
359
- applyNamingAllowlist(config, allowlists, "bannedGenericNames");
360
- applyNamingAllowlist(config, allowlists, "acceptedBooleanNames");
361
- applyNamingAllowlist(config, allowlists, "booleanPrefixes");
362
- applyNamingAllowlist(config, allowlists, "hungarianPrefixes");
681
+ // Even an empty legacy list stops loading because category redaction markers are unconditional.
682
+ if (allowlists && "secretPreviews" in allowlists) {
683
+ throw new ConfigLoadError(LEGACY_SECRET_PREVIEWS_ERROR, "Delete the `allowlists.secretPreviews:` entry from `.gruff-ts.yaml`; nothing replaces it.");
684
+ }
685
+ applyNamingAllowlist(config, allowlists, "acceptedClassFilePairs");
363
686
  applyNamingAllowlist(config, allowlists, "placeholderNames");
364
- applyNamingAllowlist(config, allowlists, "negativeBooleanAllowed");
365
- applyNamingAllowlist(config, allowlists, "knownAcronyms");
687
+ // Tracking tokens are project vocabulary, so none ship by default. Each supplied string becomes a case-insensitive pattern.
688
+ if (allowlists && "trackingTokens" in allowlists) {
689
+ config.trackingTokens = arrayValue(allowlists.trackingTokens).filter(isString).map((pattern) => trackingTokenPattern(pattern));
690
+ }
366
691
  }
367
692
 
368
- // Replaces the entire list when the user provides that key - there is no merge with defaults.
369
- // The "set the whole list" semantic is intentional so users can deliberately empty a list.
370
- function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "acceptedBooleanNames" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "negativeBooleanAllowed" | "knownAcronyms"): void {
693
+ /**
694
+ * Compiles a case-insensitive regular expression for a pattern from `allowlists.trackingTokens`.
695
+ *
696
+ * @param pattern - regular expression source text supplied in configuration
697
+ * @returns Case-insensitive regular expression built from `pattern`.
698
+ * @throws {ConfigLoadError} - Invalid syntax stops config loading and identifies the entry to fix or remove.
699
+ */
700
+ function trackingTokenPattern(pattern: string): RegExp {
701
+ try {
702
+ return new RegExp(pattern, "i");
703
+ } catch {
704
+ throw new ConfigLoadError(`Config key "allowlists.trackingTokens" holds an invalid regular expression: ${JSON.stringify(pattern)}.`, "Fix or remove that entry in `.gruff-ts.yaml`.");
705
+ }
706
+ }
707
+
708
+ /**
709
+ * Replaces the effective config's naming set for the selected key with lowercase strings from the parsed allowlists.
710
+ * A supplied value with no usable strings clears the selected set; missing sections or keys leave it untouched.
711
+ *
712
+ * @param config - effective configuration whose selected naming set is updated in place
713
+ * @param allowlists - parsed `allowlists` mapping, or `undefined` when omitted
714
+ * @param key - target naming allowlist field (`acceptedClassFilePairs` or `placeholderNames`)
715
+ * @returns Nothing. Replaces `config[key]` when `allowlists` explicitly contains `key`.
716
+ */
717
+ function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "acceptedClassFilePairs" | "placeholderNames"): void {
718
+ // If the section or selected key is missing, the current set stays in effect.
371
719
  if (!allowlists || !(key in allowlists)) {
372
720
  return;
373
721
  }
374
722
  config[key] = new Set(arrayValue(allowlists[key]).filter(isString).map((value) => value.toLowerCase()));
375
723
  }
376
724
 
377
- // Per-rule overrides under the `rules:` key. Each entry can carry enabled / threshold / severity /
378
- // options - only the keys the user actually sets become overrides; unset keys fall through to defaults.
379
- function applyRuleConfig(config: Config, raw: Record<string, unknown>): void {
380
- const rules = objectValue(raw.rules);
725
+ /**
726
+ * Applies per-rule overrides from the parsed `rules` mapping to the effective config.
727
+ * Rejects unknown rule IDs and non-mapping rule entries loudly so malformed settings never become silent no-ops.
728
+ *
729
+ * @param config - effective configuration whose `rules` map receives validated per-rule overrides
730
+ * @param parsedConfig - parsed configuration mapping that may supply a `rules` section
731
+ * @returns Nothing. Populates `config.rules` in place for each valid rule mapping.
732
+ * @throws {ConfigLoadError} when a rule entry is not a mapping, names an unknown rule, has an unknown key, or fails field validation.
733
+ */
734
+ function applyRuleConfig(config: Config, parsedConfig: Record<string, unknown>): void {
735
+ const rules = objectValue(parsedConfig.rules);
736
+ // Without a rules mapping, the effective config adds no file overrides from this section.
381
737
  if (!rules) {
382
738
  return;
383
739
  }
384
740
  for (const [ruleId, value] of Object.entries(rules)) {
741
+ // A misspelled id would otherwise sit in the map as a silent no-op the user believes is policy.
742
+ if (!isKnownRuleId(ruleId)) {
743
+ throw new ConfigLoadError(
744
+ `Unknown rule id: ${JSON.stringify(ruleId)}.`,
745
+ "Use a rule id from `gruff-ts list-rules`; `rules:` keys must match the catalogue exactly.",
746
+ );
747
+ }
385
748
  const rule = objectValue(value);
749
+ // Reject shorthand scalars such as `size.function-length: false` instead of ignoring the override silently.
386
750
  if (!rule) {
387
- continue;
751
+ throw new ConfigLoadError(
752
+ `Invalid config for rule ${JSON.stringify(ruleId)}: expected a mapping with enabled, threshold, severity, or options.`,
753
+ SUGGEST_EDIT_CONFIG,
754
+ );
388
755
  }
389
- config.rules.set(ruleId, ruleConfigValue(rule));
756
+ config.rules.set(ruleId, ruleConfigValue(ruleId, rule));
390
757
  }
391
758
  }
392
759
 
393
- // Builds one rule's override entry after `assertRuleThresholdConfig` has thrown on malformed input.
394
- // Validation happens before extraction so users see a useful error rather than a silently dropped key.
395
- function ruleConfigValue(rule: Record<string, unknown>): RuleOverride {
760
+ // Every key a rule block may carry; a sibling port's `thresholds:` map is not one of them.
761
+ const RULE_BLOCK_KEYS: ReadonlySet<string> = new Set(["enabled", "options", "severity", "threshold"]);
762
+
763
+ // Option keys that switch a rule on or off for a wider scope, such as the tag rules' `everyCallable`; every other option is numeric.
764
+ const BOOLEAN_RULE_OPTION_KEYS: ReadonlySet<string> = new Set(["everyCallable"]);
765
+
766
+ /**
767
+ * Builds an override from the supplied rule block; direct config and profiles share this field-validation path.
768
+ * Without an `options` mapping callers use option defaults; throws `ConfigLoadError` for unknown keys or invalid fields.
769
+ *
770
+ * @param ruleId - catalogue rule identifier used to select accepted options and identify errors
771
+ * @param rule - parsed mapping of rule override fields (`enabled`, `threshold`, `severity`, `options`)
772
+ * @returns Validated rule override containing explicit fields and validated option values.
773
+ */
774
+ function ruleConfigValue(ruleId: string, rule: Record<string, unknown>): RuleOverride {
775
+ // A key alongside threshold that gruff-ts does not read, such as a sibling port's spelling, is refused, not ignored.
776
+ assertKnownKeys(rule, RULE_BLOCK_KEYS, `rules.${ruleId}.`);
396
777
  assertRuleThresholdConfig(rule);
397
- const ruleOverride: RuleOverride = { options: numericConfigMap(rule.options) };
778
+ assertRuleEnabledConfig(rule);
779
+ const ruleOverride: RuleOverride = { options: validatedRuleOptions(ruleId, rule.options) };
398
780
  applyRuleEnabledConfig(ruleOverride, rule);
399
781
  applyRuleThresholdConfig(ruleOverride, rule);
400
782
  applyRuleSeverityConfig(ruleOverride, rule);
401
783
  return ruleOverride;
402
784
  }
403
785
 
404
- /*
405
- * Validates individual `threshold` and `severity` types. Either, neither, or both may be present:
406
- * many rules have no `threshold` knob at all (security.eval-call, waste.any-type, etc.), so a
407
- * "must be configured together" gate would block any severity-only override on those rules even
408
- * though `gruff-ts list-rules <id>` advertises `rules.<id>.severity` as a public knob. Each field
409
- * is independently optional and falls through to the descriptor default when absent.
786
+ /**
787
+ * Validates the rule block's explicit `enabled` setting before it can change the user's scan.
788
+ * Missing means inherit; throws on YAML words such as `no` because only `true` and `false` reliably control the rule.
789
+ *
790
+ * @param rule - parsed rule mapping to inspect for an `enabled` setting
791
+ * @returns Nothing. Completes when `enabled` is omitted or strictly a true/false flag.
792
+ * @throws {ConfigLoadError} - when the rule block sets enabled to a non-boolean value.
793
+ */
794
+ function assertRuleEnabledConfig(rule: Record<string, unknown>): void {
795
+ // A supplied non-boolean would otherwise look like a successful enable or disable choice while doing nothing.
796
+ if ("enabled" in rule && typeof rule.enabled !== "boolean") {
797
+ throw new ConfigLoadError(
798
+ `Rule config key "enabled" must be true or false; got ${JSON.stringify(rule.enabled)}.`,
799
+ "YAML 1.2 treats `no`/`off`/`yes`/`on` as strings - write `enabled: true` or `enabled: false`.",
800
+ );
801
+ }
802
+ }
803
+
804
+ /**
805
+ * Checks the rule block's optional `threshold` and `severity` overrides independently before analysis.
806
+ * Omitted fields keep their inherited settings; invalid overrides identify the exact field to correct.
410
807
  *
411
- * Throws ConfigLoadError when `threshold` is present but non-numeric, or when `severity` is
412
- * present but not one of `advisory|warning|error`. Returns silently when both fields are absent
413
- * (the common case for `enabled`-only or options-only overrides).
808
+ * @param rule - parsed rule mapping to inspect for `threshold` and `severity`
809
+ * @returns Nothing. Completes when supplied `threshold` and `severity` overrides are valid.
810
+ * @throws {ConfigLoadError} - when threshold is nonnumeric or severity is outside advisory, warning, and error.
414
811
  */
415
812
  function assertRuleThresholdConfig(rule: Record<string, unknown>): void {
813
+ // A supplied threshold must be numeric to define a meaningful rule boundary for the user.
416
814
  if ("threshold" in rule && typeof rule.threshold !== "number") {
417
815
  throw new ConfigLoadError('Rule config key "threshold" must be numeric.', SUGGEST_EDIT_CONFIG);
418
816
  }
817
+ // A supplied severity must use the report severity names that --fail-on compares against.
419
818
  if ("severity" in rule && !isSeverity(rule.severity)) {
420
819
  throw new ConfigLoadError('Rule config key "severity" must be "advisory", "warning", or "error".', SUGGEST_EDIT_CONFIG);
421
820
  }
422
821
  }
423
822
 
424
- /** Copies an explicit enabled override while preserving absent config keys. */
823
+ /**
824
+ * Copies an explicit `enabled` choice from the configured rule entry into the supplied rule override.
825
+ * Missing values preserve the profile or descriptor behavior the user already selected.
826
+ *
827
+ * @param ruleOverride - target override object updated in place
828
+ * @param rule - parsed rule mapping that may supply an explicit `enabled` flag
829
+ * @returns Nothing. Sets `ruleOverride.enabled` when `rule.enabled` is a true/false flag.
830
+ */
425
831
  function applyRuleEnabledConfig(ruleOverride: RuleOverride, rule: Record<string, unknown>): void {
832
+ // Only an explicit boolean represents a user choice to enable or disable the rule.
426
833
  if (typeof rule.enabled === "boolean") {
427
834
  ruleOverride.enabled = rule.enabled;
428
835
  }
429
836
  }
430
837
 
431
- /** Copies a numeric threshold after validation has proved the value is safe. */
838
+ /**
839
+ * Copies a numeric threshold from the configured rule entry into the supplied rule override.
840
+ *
841
+ * @param ruleOverride - target override object updated in place
842
+ * @param rule - parsed rule mapping that may supply a numeric `threshold`
843
+ * @returns Nothing. Sets `ruleOverride.threshold` when `rule.threshold` is numeric.
844
+ */
432
845
  function applyRuleThresholdConfig(ruleOverride: RuleOverride, rule: Record<string, unknown>): void {
846
+ // A missing or nonnumeric setting leaves the override untouched, preserving the inherited threshold when no override exists.
433
847
  if (typeof rule.threshold === "number") {
434
848
  ruleOverride.threshold = rule.threshold;
435
849
  }
436
850
  }
437
851
 
438
- /** Copies a severity override after validation has proved the value is supported. */
852
+ /**
853
+ * Copies a supported severity from the configured rule entry into the supplied rule override.
854
+ * Missing or unsupported values leave the inherited severity untouched.
855
+ *
856
+ * @param ruleOverride - target override object updated in place
857
+ * @param rule - parsed rule mapping that may supply a `severity` override
858
+ * @returns Nothing. Sets `ruleOverride.severity` when `rule.severity` is a valid severity.
859
+ */
439
860
  function applyRuleSeverityConfig(ruleOverride: RuleOverride, rule: Record<string, unknown>): void {
861
+ // Only a supported severity can change how the finding appears and affects exit thresholds.
440
862
  if (isSeverity(rule.severity)) {
441
863
  ruleOverride.severity = rule.severity;
442
864
  }
443
865
  }
444
866
 
445
- // Rule options are typed as numeric (thresholds, line counts, etc.). Non-numeric entries are
446
- // silently dropped rather than thrown because allowing malformed YAML to abort a scan is too aggressive.
447
- function numericConfigMap(optionsValue: unknown): Map<string, number> {
448
- const options = new Map<string, number>();
449
- const rawOptions = objectValue(optionsValue);
450
- if (!rawOptions) {
867
+ /**
868
+ * Validates options from `optionsValue` for `ruleId`, using that rule's public option catalogue.
869
+ * Undefined, null, arrays, and non-object values yield an empty map, leaving the rule's option defaults in use.
870
+ *
871
+ * @param ruleId - catalogue rule identifier whose accepted option keys are enforced
872
+ * @param optionsValue - raw `options` value supplied in a rule configuration block
873
+ * @returns Validated option map keyed by option name.
874
+ * @throws {ConfigLoadError} - when an option name is not one the rule accepts, or its value has the wrong type.
875
+ */
876
+ function validatedRuleOptions(ruleId: string, optionsValue: unknown): Map<string, number | boolean> {
877
+ const options = new Map<string, number | boolean>();
878
+ const configuredOptions = objectValue(optionsValue);
879
+ // No options mapping means this rule uses its documented option defaults.
880
+ if (!configuredOptions) {
451
881
  return options;
452
882
  }
453
- for (const [name, option] of Object.entries(rawOptions)) {
454
- if (typeof option === "number") {
455
- options.set(name, option);
883
+ const acceptedKeys = ruleOptionKeys(ruleId);
884
+ // Every supplied option must be both supported by the rule and of its type before analysis uses it.
885
+ for (const [name, option] of Object.entries(configuredOptions)) {
886
+ // Reject unknown keys first so a typo is reported as the typo, not as a type error.
887
+ if (!acceptedKeys.includes(name)) {
888
+ const accepted = acceptedKeys.length > 0 ? `accepts options: ${acceptedKeys.join(", ")}` : "accepts no options";
889
+ throw new ConfigLoadError(`Unknown option ${JSON.stringify(name)} for rule ${ruleId}; the rule ${accepted}.`, SUGGEST_EDIT_CONFIG);
456
890
  }
891
+ options.set(name, ruleOptionValue(ruleId, name, option));
457
892
  }
458
893
  return options;
459
894
  }
460
895
 
461
- // Returns the first supported config path at the project root; undefined otherwise so
462
- // callers can fall back to defaults without distinguishing "no config" from a real error.
896
+ /**
897
+ * Validates one rule option value using boolean or numeric checks selected by `name`.
898
+ *
899
+ * @param ruleId - catalogue rule identifier reported in error diagnostics
900
+ * @param name - option key selecting boolean switch validation or numeric validation
901
+ * @param option - raw configured option value for `name`
902
+ * @returns Unchanged `option` value once confirmed to match the expected type.
903
+ * @throws {ConfigLoadError} - when a switch is not a boolean, or a numeric option is not a number.
904
+ */
905
+ function ruleOptionValue(ruleId: string, name: string, option: unknown): number | boolean {
906
+ const isSwitch = BOOLEAN_RULE_OPTION_KEYS.has(name);
907
+ // A switch takes only true or false, so a YAML word such as yes cannot look like a choice that does nothing.
908
+ if (isSwitch && typeof option === "boolean") {
909
+ return option;
910
+ }
911
+ // A numeric option takes only a number, because nothing else can define the boundary the user intended.
912
+ if (!isSwitch && typeof option === "number") {
913
+ return option;
914
+ }
915
+ const expected = isSwitch ? "true or false" : "numeric";
916
+ throw new ConfigLoadError(`Rule config option ${JSON.stringify(name)} for ${ruleId} must be ${expected}; got ${JSON.stringify(option)}.`, SUGGEST_EDIT_CONFIG);
917
+ }
918
+
919
+ /**
920
+ * Finds the first existing candidate path under `projectRoot` for zero-argument config discovery.
921
+ * Returns `undefined` when no candidate exists, so loading starts from built-in defaults.
922
+ *
923
+ * @param projectRoot - workspace directory checked in deterministic priority order for default config files
924
+ * @returns Path to the first existing candidate config file, or `undefined` when none exists.
925
+ */
463
926
  function defaultConfigPath(projectRoot: string): string | undefined {
927
+ // Config names are checked in documented priority order so users get a deterministic selection.
464
928
  for (const fileName of DEFAULT_CONFIG_FILES) {
465
929
  const candidate = join(projectRoot, fileName);
930
+ // Discovery selects one path. The loader handles reading and validation.
466
931
  if (existsSync(candidate)) {
467
932
  return candidate;
468
933
  }
@@ -470,34 +935,137 @@ function defaultConfigPath(projectRoot: string): string | undefined {
470
935
  return undefined;
471
936
  }
472
937
 
473
- // Rules are enabled by default - the absence of a config entry means "use the descriptor default",
474
- // which is the documented contract for how unset rules behave.
938
+ /**
939
+ * Determines whether one rule should run for the user's scan.
940
+ * If the effective config has no enabled override for the rule, it runs unless its descriptor disables it by default.
941
+ *
942
+ * @param config - effective analysis configuration holding per-rule overrides
943
+ * @param ruleId - catalogue rule identifier to query
944
+ * @returns Whether `ruleId` is enabled for the scan.
945
+ */
475
946
  function ruleEnabled(config: Config, ruleId: string): boolean {
476
- return config.rules.get(ruleId)?.enabled ?? true;
947
+ return config.rules.get(ruleId)?.enabled ?? ruleDefaultEnabled(ruleId);
477
948
  }
478
949
 
479
- // Resolves a threshold for the rule. Callers pass the descriptor default so this helper alone
480
- // determines whether config can override - keeps every rule's threshold lookup uniform.
950
+ /**
951
+ * Looks up the configured threshold for one rule or falls back to the caller's documented default.
952
+ * Rules use this during analysis so omitted user settings behave consistently.
953
+ *
954
+ * @param config - effective analysis configuration holding per-rule overrides
955
+ * @param ruleId - catalogue rule identifier to query
956
+ * @param defaultValue - fallback limit used when no threshold override is configured
957
+ * @returns Configured threshold for `ruleId`, or `defaultValue` when omitted.
958
+ */
481
959
  function threshold(config: Config, ruleId: string, defaultValue: number): number {
482
960
  return config.rules.get(ruleId)?.threshold ?? defaultValue;
483
961
  }
484
962
 
485
- // Same shape as `threshold`. The descriptor default is the single source of truth for what severity
486
- // a rule emits when the user has no config entry.
963
+ /**
964
+ * Looks up the configured severity for one rule or falls back to the descriptor default shown to users.
965
+ * Rules use this when building findings so report severity and exit behavior stay aligned.
966
+ *
967
+ * @param config - effective analysis configuration holding per-rule overrides
968
+ * @param ruleId - catalogue rule identifier to query
969
+ * @param defaultSeverity - fallback severity used when no override is configured
970
+ * @returns Effective severity for `ruleId`.
971
+ */
487
972
  function ruleSeverity(config: Config, ruleId: string, defaultSeverity: Severity): Severity {
488
973
  return config.rules.get(ruleId)?.severity ?? defaultSeverity;
489
974
  }
490
975
 
491
- // Rule-specific numeric options (e.g., minLength for sensitive-data rules). Same default-fallback
492
- // pattern as `threshold` so rules can be configured without forcing every field to be set.
976
+ /**
977
+ * Looks up the named numeric option for the selected rule in the effective config.
978
+ *
979
+ * @param config - effective analysis configuration holding per-rule overrides
980
+ * @param ruleId - catalogue rule identifier to query
981
+ * @param name - option key to read from the rule's validated options map
982
+ * @param defaultValue - fallback value returned when the option is missing or has another type
983
+ * @returns Configured option value for `name`, or `defaultValue` when absent or of another type.
984
+ */
493
985
  function optionNumber(config: Config, ruleId: string, name: string, defaultValue: number): number {
494
- return config.rules.get(ruleId)?.options.get(name) ?? defaultValue;
986
+ const option = config.rules.get(ruleId)?.options.get(name);
987
+ return typeof option === "number" ? option : defaultValue;
988
+ }
989
+
990
+ /**
991
+ * Looks up a named switch for the selected rule in the effective config, such as `everyCallable` for a tag rule.
992
+ *
993
+ * @param config - effective analysis configuration holding per-rule overrides
994
+ * @param ruleId - catalogue rule identifier to query
995
+ * @param name - option key to read from the rule's validated options map
996
+ * @param isOnByDefault - fallback flag returned when the option is missing or has another type
997
+ * @returns Configured switch state for `name`, or `isOnByDefault` when absent or of another type.
998
+ */
999
+ function optionBoolean(config: Config, ruleId: string, name: string, isOnByDefault: boolean): boolean {
1000
+ const option = config.rules.get(ruleId)?.options.get(name);
1001
+ return typeof option === "boolean" ? option : isOnByDefault;
495
1002
  }
496
1003
 
497
- // Whitelist check used both by config validation (throws on bad values) and by `applyRuleSeverityConfig`.
498
- // The set of accepted strings is the public severity vocabulary; adding entries is a schema change.
1004
+ /**
1005
+ * Checks whether a parsed config value belongs to the public severity vocabulary (`advisory`, `warning`, or `error`).
1006
+ * Load-time validation and rule application share this guard so users see one consistent set of accepted values.
1007
+ *
1008
+ * @param configValue - raw configuration value to test against the supported severity names
1009
+ * @returns Whether `configValue` is a valid severity name.
1010
+ */
499
1011
  function isSeverity(configValue: unknown): configValue is Severity {
500
1012
  return configValue === "advisory" || configValue === "warning" || configValue === "error";
501
1013
  }
502
1014
 
503
- export { defaultConfigPath, loadConfig, minimumSeverityFor, optionNumber, resolveProfile, ruleEnabled, ruleSeverity, threshold };
1015
+ /**
1016
+ * Validates an already-parsed configuration mapping against the 0.6.0 config loader, including inline and built-in `profile:` blocks.
1017
+ *
1018
+ * Used by `migrate-config` so migrated output is guaranteed loadable before it is written.
1019
+ * When `baseDirectory` is supplied, relative file-backed profile references are resolved on disk too.
1020
+ *
1021
+ * @param parsedConfig - parsed YAML or JSON config object to validate
1022
+ * @param baseDirectory - optional folder for resolving file-backed profiles; when omitted, only built-in names and file-shaped paths are checked
1023
+ * @returns Nothing. Completes when every key, profile, rule override, allowlist, and sensitive exclusion passes 0.6.0 validation.
1024
+ * @throws {ConfigLoadError} - when any key, profile, rule id, option, allowlist, or sensitive exclusion would be rejected by `loadConfig`.
1025
+ */
1026
+ function validateParsedConfig(parsedConfig: Record<string, unknown>, baseDirectory?: string): void {
1027
+ applyConfigValues(defaultConfig(), parsedConfig);
1028
+ // A migrated `profile:` must still name a real profile, or the migrated file would fail when the user next runs a scan.
1029
+ if (parsedConfig.profile !== undefined) {
1030
+ validateProfileValue(parseProfileSpec(parsedConfig.profile), baseDirectory);
1031
+ }
1032
+ }
1033
+
1034
+ /**
1035
+ * Validates a parsed `profile:` specification against built-in presets, rule IDs, and optionally on-disk file references.
1036
+ *
1037
+ * @param spec - parsed string or inline profile specification from configuration
1038
+ * @param baseDirectory - optional folder for resolving file-backed profiles; when omitted, on-disk profile files cannot be opened
1039
+ * @returns Nothing. Throws when the profile references an unknown preset/rule or fails resolution.
1040
+ * @throws {ConfigLoadError} - when a rule ID, built-in profile name, or referenced profile file is invalid.
1041
+ */
1042
+ function validateProfileValue(spec: ProfileSpec, baseDirectory: string | undefined): void {
1043
+ // When the config's folder is known, resolve the profile exactly as a scan would, including profile files on disk.
1044
+ if (baseDirectory !== undefined) {
1045
+ resolveProfile(spec, baseDirectory);
1046
+ return;
1047
+ }
1048
+ // An inline profile can override rules; each one must be a rule ID this version knows.
1049
+ if (typeof spec === "object") {
1050
+ // The first unknown rule ID stops the migration with a config error.
1051
+ for (const ruleId of Object.keys(spec.rules ?? {})) {
1052
+ assertKnownProfileRule(ruleId);
1053
+ }
1054
+ }
1055
+ const ref = typeof spec === "string" ? spec : spec.extends;
1056
+ // An inline profile without `extends:` has no base profile to check.
1057
+ if (ref === undefined) {
1058
+ return;
1059
+ }
1060
+ const isBuiltIn = BUILT_IN_PROFILES.has(ref) || BUILT_IN_PROFILES.has(`gruff.${ref}`);
1061
+ const looksLikeFilePath = /[\\/]|(?:\.ya?ml|\.json)$/iu.test(ref);
1062
+ // Without a folder to resolve files against, accept only a built-in name or a value shaped like a profile file path.
1063
+ if (!isBuiltIn && !looksLikeFilePath) {
1064
+ throw new ConfigLoadError(
1065
+ `Unknown profile: ${JSON.stringify(ref)}.`,
1066
+ `Use a built-in profile name (${builtInProfileNames().join(", ")}) or point at an existing .yaml/.yml/.json profile file.`,
1067
+ );
1068
+ }
1069
+ }
1070
+
1071
+ export { defaultConfigPath, loadConfig, minimumSeverityFor, optionBoolean, optionNumber, resolveProfile, ruleEnabled, ruleSeverity, threshold, validateParsedConfig };