@blundergoat/gruff-ts 0.5.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 +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  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 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  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 +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  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 +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  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 +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
package/src/config.ts CHANGED
@@ -1,92 +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
9
  import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId, ruleOptionKeys } from "./profiles.ts";
8
- import type { AnalysisOptions, Config, FailThreshold, InlineProfileSpec, MinimumSeverityCommand, ProfileDefinition, ProfileRuleSetting, ProfileSpec, Severity } from "./types.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
55
  acceptedAbbreviations: new Set(["age", "app", "db", "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
56
  acceptedClassFilePairs: new Set(),
27
- acceptedCasingPairs: new Set(),
28
- 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"]),
29
- hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
30
57
  placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
31
- negativeBooleanAllowed: new Set(["nostore", "nofollow", "noreferrer", "noscript", "noindex"]),
32
- 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: [],
33
59
  minimumSeverity: new Map(),
34
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: [],
35
68
  };
36
69
  }
37
70
 
38
- // 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
+ */
39
79
  function absolutize(projectRoot: string, path: string): string {
40
80
  return isAbsolute(path) ? path : join(projectRoot, path);
41
81
  }
42
82
 
43
- // Reads the YAML config from disk (if any) and overlays user values onto `defaultConfig`. `shouldSkipConfig`
44
- // is the explicit opt-out; missing default file is silent (returns defaults) so projects without
45
- // `.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
+ */
46
91
  function loadConfig(projectRoot: string, options: AnalysisOptions): Config {
47
92
  const config = defaultConfig();
48
93
  const path = options.shouldSkipConfig ? undefined : selectedConfigPath(projectRoot, options);
49
- 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.
50
96
  if (path) {
51
- applyConfigValues(config, raw);
97
+ applyConfigValues(config, parsedConfig);
52
98
  }
53
- 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);
54
103
  return config;
55
104
  }
56
105
 
57
- /*
58
- * Applies the profile layer UNDER the top-level config sections. Precedence (highest first): the CLI
59
- * `--profile` flag, then a config-file `profile:` block, then the profile's own `extends:` chain, then
60
- * the built-in default `gruff.recommended`. The flattened profile only fills rules the top-level
61
- * `rules:` block did not already set, so an explicit per-rule override always wins over the profile.
62
- * When neither the flag nor the config names a profile this is a no-op, because the implicit default
63
- * `recommended` flattens to an empty delta - the contract that keeps `--profile recommended` and a
64
- * zero-config scan byte-identical. `--no-config` skips the file but the CLI `--profile` still applies.
65
- */
66
- function applyProfile(config: Config, options: AnalysisOptions, raw: Record<string, unknown>, projectRoot: string): void {
67
- const rawSpec = options.profile !== undefined ? options.profile : raw.profile;
68
- 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) {
69
128
  return;
70
129
  }
71
- 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));
72
133
  }
73
134
 
74
- // Lays a flattened profile under the already-applied top-level config: each rule the top-level
75
- // `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
+ */
76
143
  function applyProfileUnderlay(config: Config, definition: ProfileDefinition): void {
77
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.
78
146
  if (!config.rules.has(ruleId)) {
79
147
  config.rules.set(ruleId, profileRuleToConfig(setting));
80
148
  }
81
149
  }
150
+ // Empty profile ignores leave the user's current scan surface unchanged.
82
151
  if (definition.ignoredPaths.length > 0) {
83
152
  config.ignoredPaths = [...new Set([...config.ignoredPaths, ...definition.ignoredPaths])];
84
153
  }
85
154
  }
86
155
 
87
- // Converts a profile rule setting into the loaded-config rule shape. `options` is always a map in the
88
- // config value, so an absent profile options field becomes an empty map. Conditional spreads keep the
89
- // 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
+ */
90
163
  function profileRuleToConfig(setting: ProfileRuleSetting): RuleOverride {
91
164
  return {
92
165
  ...(setting.enabled !== undefined ? { enabled: setting.enabled } : {}),
@@ -96,22 +169,14 @@ function profileRuleToConfig(setting: ProfileRuleSetting): RuleOverride {
96
169
  };
97
170
  }
98
171
 
99
- /*
100
- * Resolves a profile spec into a flattened ProfileDefinition (a delta from the descriptor defaults).
101
- * Documented precedence the callers depend on, highest first: the CLI `--profile` flag, the config
102
- * `profile:` block, the `extends:` base chain, and the built-in default `gruff.recommended`. This
103
- * function owns only the `extends:` flattening; `loadConfig` applies the result under the top-level
104
- * config sections via `applyProfileUnderlay`.
105
- *
106
- * Flattening is child-wins and deterministic: a child profile's per-rule fields override the parent's
107
- * same-rule fields (last assignment wins for a repeated key), and a child `ignoredPaths` array
108
- * replaces - does not concatenate - the parent's. `chain` carries the ordered, already-visited file
109
- * paths so a cycle (A extends B extends A) is rejected with a message naming both in order, instead of
110
- * recursing until the stack overflows.
111
- *
112
- * Throws ConfigLoadError on: a missing `extends:` file, a rule id not in RULE_DESCRIPTORS, or an
113
- * inheritance cycle. Every failure surfaces at config-load time, never at scan time. File paths only:
114
- * `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.
115
180
  */
116
181
  function resolveProfile(spec: ProfileSpec, projectRoot: string, chain: string[] = []): ProfileDefinition {
117
182
  if (typeof spec === "string") {
@@ -120,24 +185,38 @@ function resolveProfile(spec: ProfileSpec, projectRoot: string, chain: string[]
120
185
  return resolveInlineProfile(spec, projectRoot, chain);
121
186
  }
122
187
 
123
- // Resolves a string ref: a built-in name returns its bundled definition (terminal, no extends); any
124
- // other string is treated as a relative profile file path (no built-in match, no network, no shell).
125
- // The canonical built-in names are `gruff.minimal` / `gruff.recommended` / `gruff.strict`; the bare
126
- // short forms (`minimal`, `recommended`, `strict`) are accepted as aliases for CLI ergonomics, so a
127
- // 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
+ */
128
197
  function resolveProfileRef(ref: string, projectRoot: string, chain: string[]): ProfileDefinition {
129
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.
130
200
  if (builtIn) {
131
201
  return cloneProfileDefinition(builtIn);
132
202
  }
133
203
  return resolveProfileFile(ref, projectRoot, chain);
134
204
  }
135
205
 
136
- // Loads and resolves a profile file, treating its parsed top-level mapping as an inline profile
137
- // 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
+ */
138
216
  function resolveProfileFile(ref: string, projectRoot: string, chain: string[]): ProfileDefinition {
139
217
  const path = absolutize(projectRoot, ref);
140
218
  assertNoProfileCycle(path, chain);
219
+ // A missing user-selected file cannot safely fall back to a different profile.
141
220
  if (!existsSync(path)) {
142
221
  throw new ConfigLoadError(
143
222
  `Profile extends file not found: ${path}.`,
@@ -147,17 +226,31 @@ function resolveProfileFile(ref: string, projectRoot: string, chain: string[]):
147
226
  return resolveInlineProfile(inlineSpecFromObject(parseConfigFile(path)), dirname(path), [...chain, path]);
148
227
  }
149
228
 
150
- // Resolves the base (the `extends:` target, defaulting to gruff.recommended) and overlays this spec's
151
- // 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
+ */
152
238
  function resolveInlineProfile(spec: InlineProfileSpec, projectRoot: string, chain: string[]): ProfileDefinition {
153
239
  const base = resolveProfileRef(spec.extends ?? DEFAULT_PROFILE_NAME, projectRoot, chain);
154
240
  return overlayProfile(base, spec);
155
241
  }
156
242
 
157
- // Overlays a child inline spec on a resolved base. Per-rule fields merge (child wins field-by-field);
158
- // 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
+ */
159
251
  function overlayProfile(base: ProfileDefinition, spec: InlineProfileSpec): ProfileDefinition {
160
252
  const rules = new Map(base.rules);
253
+ // Each child rule may override only the fields the user supplied while retaining inherited fields.
161
254
  for (const [ruleId, setting] of Object.entries(spec.rules ?? {})) {
162
255
  assertKnownProfileRule(ruleId);
163
256
  rules.set(ruleId, mergeRuleSetting(rules.get(ruleId), setting));
@@ -166,22 +259,40 @@ function overlayProfile(base: ProfileDefinition, spec: InlineProfileSpec): Profi
166
259
  return { name: base.name, rules, ignoredPaths };
167
260
  }
168
261
 
169
- // Field-level child-wins merge for one rule's settings: spread the parent then the child so every key
170
- // the child sets (including `enabled: false`) overrides the parent while unset child keys inherit. Both
171
- // inputs are built with conditional spreads upstream, so neither carries explicit-undefined keys that
172
- // 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
+ */
173
270
  function mergeRuleSetting(parent: ProfileRuleSetting | undefined, child: ProfileRuleSetting): ProfileRuleSetting {
174
271
  return { ...parent, ...child };
175
272
  }
176
273
 
177
- // 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
+ */
178
281
  function cloneProfileDefinition(definition: ProfileDefinition): ProfileDefinition {
179
282
  return { name: definition.name, rules: new Map(definition.rules), ignoredPaths: [...definition.ignoredPaths] };
180
283
  }
181
284
 
182
- // Guards the `extends:` chain against cycles, naming the whole chain in visit order so the user can
183
- // 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
+ */
184
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.
185
296
  if (chain.includes(key)) {
186
297
  throw new ConfigLoadError(
187
298
  `Profile inheritance cycle detected: ${[...chain, key].join(" -> ")}.`,
@@ -190,9 +301,16 @@ function assertNoProfileCycle(key: string, chain: string[]): void {
190
301
  }
191
302
  }
192
303
 
193
- // Validates a user profile rule id against the catalogue so a typo never silently no-ops at scan
194
- // 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
+ */
195
312
  function assertKnownProfileRule(ruleId: string): void {
313
+ // A name outside the rule catalogue cannot produce the behavior the user requested.
196
314
  if (!isKnownRuleId(ruleId)) {
197
315
  throw new ConfigLoadError(
198
316
  `Unknown rule id in profile: ${JSON.stringify(ruleId)}.`,
@@ -201,16 +319,21 @@ function assertKnownProfileRule(ruleId: string): void {
201
319
  }
202
320
  }
203
321
 
204
- /*
205
- * Parses the raw `profile:` value (from YAML/JSON or the CLI flag) into a typed ProfileSpec. A string
206
- * is a built-in name or file path; a mapping is an inline spec. Throws ConfigLoadError on any other
207
- * 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.
208
329
  */
209
- function parseProfileSpec(rawSpec: unknown): ProfileSpec {
210
- if (typeof rawSpec === "string") {
211
- 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;
212
334
  }
213
- 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.
214
337
  if (!block) {
215
338
  throw new ConfigLoadError(
216
339
  "`profile:` must be a built-in name, a profile file path, or a mapping with `extends:` and overrides.",
@@ -220,178 +343,401 @@ function parseProfileSpec(rawSpec: unknown): ProfileSpec {
220
343
  return inlineSpecFromObject(block);
221
344
  }
222
345
 
223
- // Extracts the supported inline-profile keys (`extends`, `rules`, `ignoredPaths`) from a parsed
224
- // mapping; other keys such as a `schemaVersion` on a shared profile file are ignored so it reads the
225
- // 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
+ */
226
354
  function inlineSpecFromObject(block: Record<string, unknown>): InlineProfileSpec {
227
355
  const spec: InlineProfileSpec = {};
356
+ // A supplied base must name a built-in profile or local profile file.
228
357
  if ("extends" in block) {
358
+ // Non-string bases cannot resolve to the profile the user intended.
229
359
  if (!isString(block.extends)) {
230
360
  throw new ConfigLoadError("`profile.extends` must be a string: a built-in name or a relative profile file path.", SUGGEST_EDIT_CONFIG);
231
361
  }
232
362
  spec.extends = block.extends;
233
363
  }
234
364
  const rulesBlock = objectValue(block.rules);
365
+ // Without a rules mapping, the profile adds no rule overrides.
235
366
  if (rulesBlock) {
236
367
  spec.rules = profileRulesFromBlock(rulesBlock);
237
368
  }
369
+ // An ignoredPaths key replaces inherited ignores. A non-list value or a list without strings clears them.
238
370
  if ("ignoredPaths" in block) {
239
371
  spec.ignoredPaths = arrayValue(block.ignoredPaths).filter(isString);
240
372
  }
241
373
  return spec;
242
374
  }
243
375
 
244
- // Builds the per-rule settings map for an inline profile, reusing the same validation as the
245
- // top-level `rules:` block (`ruleConfigValue` throws on unknown/malformed fields; rule ids are
246
- // validated by the profile resolver so direct and profile rules reject identically).
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
+ */
247
384
  function profileRulesFromBlock(rulesBlock: Record<string, unknown>): Record<string, ProfileRuleSetting> {
248
385
  const rules: Record<string, ProfileRuleSetting> = {};
249
386
  for (const [ruleId, value] of Object.entries(rulesBlock)) {
250
387
  const rule = objectValue(value);
251
- if (rule) {
252
- rules[ruleId] = ruleConfigValue(ruleId, 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
+ );
253
394
  }
395
+ rules[ruleId] = ruleConfigValue(ruleId, rule);
254
396
  }
255
397
  return rules;
256
398
  }
257
399
 
258
- // Explicit `--config` wins; otherwise look for the first supported config at the project root. Returning
259
- // 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
+ */
260
408
  function selectedConfigPath(projectRoot: string, options: AnalysisOptions): string | undefined {
261
- return options.config ? absolutize(projectRoot, options.config) : defaultConfigPath(projectRoot);
409
+ return options.config ? absolutize(process.cwd(), options.config) : defaultConfigPath(projectRoot);
262
410
  }
263
411
 
264
- // Top-level sections applied in a fixed order: schemaVersion → minimumSeverity → paths → allowlists
265
- // → rules. schemaVersion runs first because every later parse depends on the contract version it
266
- // declares, and minimumSeverity runs next so CLI consumers reading it during normalizeOptions see
267
- // a populated map. Order does not affect correctness today but the stable application order keeps
268
- // later overrides predictable if interdependencies are added.
269
- function applyConfigValues(config: Config, raw: Record<string, unknown>): void {
270
- applySchemaVersionConfig(raw);
271
- applyMinimumSeverityConfig(config, raw);
272
- applyPathConfig(config, raw);
273
- applyAllowlistConfig(config, raw);
274
- 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);
275
432
  }
276
433
 
277
- /*
278
- * Validates the required `schemaVersion` top-level field. Pre-1.0 break: configs missing the field
279
- * or carrying any other version string are rejected (throws with a documented error listing the
280
- * supported version) because there is no migration shim under the no-legacy-compat contract. The
281
- * function does not mutate the loaded config because the only supported value matches
282
- * `defaultConfig().schemaVersion` already; future versions would extend the union and require a
283
- * write here. The schema invariant is fixed at `gruff-ts.config.v0.1`.
284
- */
285
- function applySchemaVersionConfig(raw: Record<string, unknown>): void {
286
- 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.
287
548
  if (schemaVersion === undefined) {
288
549
  throw new ConfigLoadError('Config must include `schemaVersion: gruff-ts.config.v0.1` at the top.', SUGGEST_INIT_FORCE);
289
550
  }
551
+ // Any other version is unsupported and must not be interpreted as the current schema.
290
552
  if (schemaVersion !== "gruff-ts.config.v0.1") {
291
553
  throw new ConfigLoadError(`Unsupported schemaVersion: ${JSON.stringify(schemaVersion)}. Supported: "gruff-ts.config.v0.1".`, SUGGEST_INIT_FORCE);
292
554
  }
293
555
  }
294
556
 
295
- // Parses the `minimumSeverity:` block into a Map keyed by command name. Validation throws on
296
- // `dashboard` specifically (no `--fail-on` flag exists for it), on unknown command keys, and on
297
- // every non-canonical value. Missing block is allowed - it just leaves the map empty so CLI
298
- // consumers fall through to the binary default.
299
- function applyMinimumSeverityConfig(config: Config, raw: Record<string, unknown>): void {
300
- const block = objectValue(raw.minimumSeverity);
301
- 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) {
302
569
  return;
303
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.
304
599
  for (const [commandName, value] of Object.entries(block)) {
305
- config.minimumSeverity.set(assertMinimumSeverityCommand(commandName), parseFailThresholdConfig(value));
600
+ config.minimumSeverity.set(assertGatedCommand(commandName), parseFailThresholdConfig(value));
306
601
  }
307
602
  }
308
603
 
309
- /*
310
- * Validates one `minimumSeverity:` map key. Throws on `dashboard` specifically because the
311
- * dashboard subcommand has no `--fail-on` flag; accepting the key would silently no-op and
312
- * operators would expect a gate that never fires. Throws on unknown commands so typos surface at
313
- * 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.
314
611
  */
315
- 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.
316
614
  if (commandName === "dashboard") {
317
- 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.");
318
616
  }
617
+ // These are the only commands whose user-facing exit status supports a configured minimum severity.
319
618
  if (commandName === "analyse" || commandName === "summary" || commandName === "report") {
320
619
  return commandName;
321
620
  }
322
- 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);
323
622
  }
324
623
 
325
- /*
326
- * Validates one `FailThreshold` value coming from YAML. Throws on every non-canonical value with a
327
- * clear error listing the four supported strings. `never` is rejected explicitly because earlier
328
- * cross-port drafts considered it as the off-switch value before the family converged on `none`;
329
- * 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.
330
631
  */
331
- function parseFailThresholdConfig(rawValue: unknown): FailThreshold {
332
- if (rawValue === "none" || rawValue === "advisory" || rawValue === "warning" || rawValue === "error") {
333
- 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;
334
636
  }
335
- 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);
336
638
  }
337
639
 
338
- // Per-command lookup used by the CLI precedence chain (CLI flag > config > binary default).
339
- // Returns undefined when the user did not configure that command so the caller can fall through
340
- // 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
+ */
341
648
  function minimumSeverityFor(config: Config, command: MinimumSeverityCommand): FailThreshold | undefined {
342
649
  return config.minimumSeverity.get(command);
343
650
  }
344
651
 
345
- // Replaces `ignoredPaths` with the user list. Non-string entries are silently dropped - invalid
346
- // YAML shapes should not abort the analysis run.
347
- function applyPathConfig(config: Config, raw: Record<string, unknown>): void {
348
- 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);
349
662
  config.ignoredPaths = arrayValue(paths?.ignore).filter(isString);
350
663
  }
351
664
 
352
- // The allowlist section is the main lever users have for tuning gruff to their conventions.
353
- // `acceptedAbbreviations` and the naming lists are lowercased on import so case-insensitive
354
- // matching is the stable behaviour regardless of how users write entries.
355
- function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): void {
356
- 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);
357
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.
358
678
  if (allowlists && "acceptedAbbreviations" in allowlists) {
359
679
  config.acceptedAbbreviations = new Set(abbreviations.map((value) => value.toLowerCase()));
360
680
  }
361
- config.secretPreviews = new Set(arrayValue(allowlists?.secretPreviews).filter(isString));
362
- applyNamingAllowlist(config, allowlists, "bannedGenericNames");
363
- applyNamingAllowlist(config, allowlists, "acceptedBooleanNames");
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
+ }
364
685
  applyNamingAllowlist(config, allowlists, "acceptedClassFilePairs");
365
- applyNamingAllowlist(config, allowlists, "acceptedCasingPairs");
366
- applyNamingAllowlist(config, allowlists, "booleanPrefixes");
367
- applyNamingAllowlist(config, allowlists, "hungarianPrefixes");
368
686
  applyNamingAllowlist(config, allowlists, "placeholderNames");
369
- applyNamingAllowlist(config, allowlists, "negativeBooleanAllowed");
370
- 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
+ }
371
691
  }
372
692
 
373
- // Replaces the entire list when the user provides that key - there is no merge with defaults.
374
- // The "set the whole list" semantic is intentional so users can deliberately empty a list.
375
- function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "acceptedBooleanNames" | "acceptedClassFilePairs" | "acceptedCasingPairs" | "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.
376
719
  if (!allowlists || !(key in allowlists)) {
377
720
  return;
378
721
  }
379
722
  config[key] = new Set(arrayValue(allowlists[key]).filter(isString).map((value) => value.toLowerCase()));
380
723
  }
381
724
 
382
- // Per-rule overrides under the `rules:` key. Each entry can carry enabled / threshold / severity /
383
- // options - only the keys the user actually sets become overrides; unset keys fall through to
384
- // defaults. Throws ConfigLoadError on rule ids outside the catalogue and on malformed field values.
385
- function applyRuleConfig(config: Config, raw: Record<string, unknown>): void {
386
- 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.
387
737
  if (!rules) {
388
738
  return;
389
739
  }
390
740
  for (const [ruleId, value] of Object.entries(rules)) {
391
- const rule = objectValue(value);
392
- if (!rule) {
393
- continue;
394
- }
395
741
  // A misspelled id would otherwise sit in the map as a silent no-op the user believes is policy.
396
742
  if (!isKnownRuleId(ruleId)) {
397
743
  throw new ConfigLoadError(
@@ -399,13 +745,35 @@ function applyRuleConfig(config: Config, raw: Record<string, unknown>): void {
399
745
  "Use a rule id from `gruff-ts list-rules`; `rules:` keys must match the catalogue exactly.",
400
746
  );
401
747
  }
748
+ const rule = objectValue(value);
749
+ // Reject shorthand scalars such as `size.function-length: false` instead of ignoring the override silently.
750
+ if (!rule) {
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
+ );
755
+ }
402
756
  config.rules.set(ruleId, ruleConfigValue(ruleId, rule));
403
757
  }
404
758
  }
405
759
 
406
- // Builds one rule's override entry after the field asserts have thrown on malformed input.
407
- // Validation happens before extraction so users see a useful error rather than a silently dropped key.
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
+ */
408
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}.`);
409
777
  assertRuleThresholdConfig(rule);
410
778
  assertRuleEnabledConfig(rule);
411
779
  const ruleOverride: RuleOverride = { options: validatedRuleOptions(ruleId, rule.options) };
@@ -415,13 +783,16 @@ function ruleConfigValue(ruleId: string, rule: Record<string, unknown>): RuleOve
415
783
  return ruleOverride;
416
784
  }
417
785
 
418
- /*
419
- * Rejects non-boolean `enabled` values loudly. YAML 1.2 core scalars keep `no`/`off`/`yes`/`on` as
420
- * strings (only `true`/`false` parse as booleans), so a user writing `enabled: no` previously got a
421
- * silent no-op while believing the rule was off. Throws ConfigLoadError naming the offending value
422
- * and the accepted forms; returns silently when the key is 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.
423
793
  */
424
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.
425
796
  if ("enabled" in rule && typeof rule.enabled !== "boolean") {
426
797
  throw new ConfigLoadError(
427
798
  `Rule config key "enabled" must be true or false; got ${JSON.stringify(rule.enabled)}.`,
@@ -430,79 +801,133 @@ function assertRuleEnabledConfig(rule: Record<string, unknown>): void {
430
801
  }
431
802
  }
432
803
 
433
- /*
434
- * Validates individual `threshold` and `severity` types. Either, neither, or both may be present:
435
- * many rules have no `threshold` knob at all (security.eval-call, waste.any-type, etc.), so a
436
- * "must be configured together" gate would block any severity-only override on those rules even
437
- * though `gruff-ts list-rules <id>` advertises `rules.<id>.severity` as a public knob. Each field
438
- * is independently optional and falls through to the descriptor default when absent.
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.
439
807
  *
440
- * Throws ConfigLoadError when `threshold` is present but non-numeric, or when `severity` is
441
- * present but not one of `advisory|warning|error`. Returns silently when both fields are absent
442
- * (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.
443
811
  */
444
812
  function assertRuleThresholdConfig(rule: Record<string, unknown>): void {
813
+ // A supplied threshold must be numeric to define a meaningful rule boundary for the user.
445
814
  if ("threshold" in rule && typeof rule.threshold !== "number") {
446
815
  throw new ConfigLoadError('Rule config key "threshold" must be numeric.', SUGGEST_EDIT_CONFIG);
447
816
  }
817
+ // A supplied severity must use the report severity names that --fail-on compares against.
448
818
  if ("severity" in rule && !isSeverity(rule.severity)) {
449
819
  throw new ConfigLoadError('Rule config key "severity" must be "advisory", "warning", or "error".', SUGGEST_EDIT_CONFIG);
450
820
  }
451
821
  }
452
822
 
453
- /** 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
+ */
454
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.
455
833
  if (typeof rule.enabled === "boolean") {
456
834
  ruleOverride.enabled = rule.enabled;
457
835
  }
458
836
  }
459
837
 
460
- /** 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
+ */
461
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.
462
847
  if (typeof rule.threshold === "number") {
463
848
  ruleOverride.threshold = rule.threshold;
464
849
  }
465
850
  }
466
851
 
467
- /** 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
+ */
468
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.
469
862
  if (isSeverity(rule.severity)) {
470
863
  ruleOverride.severity = rule.severity;
471
864
  }
472
865
  }
473
866
 
474
- /*
475
- * Validates `rules.<id>.options` against the rule descriptor's declared option keys - a dropped
476
- * option would otherwise convince the user a tuning applied when it did not. Rules without declared
477
- * options reject every entry. Throws ConfigLoadError naming the rule and its accepted keys for
478
- * unknown keys, and the offending value for non-numeric declared options.
479
- */
480
- function validatedRuleOptions(ruleId: string, optionsValue: unknown): Map<string, number> {
481
- const options = new Map<string, number>();
482
- const rawOptions = objectValue(optionsValue);
483
- 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) {
484
881
  return options;
485
882
  }
486
883
  const acceptedKeys = ruleOptionKeys(ruleId);
487
- for (const [name, option] of Object.entries(rawOptions)) {
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)) {
488
886
  // Reject unknown keys first so a typo is reported as the typo, not as a type error.
489
887
  if (!acceptedKeys.includes(name)) {
490
888
  const accepted = acceptedKeys.length > 0 ? `accepts options: ${acceptedKeys.join(", ")}` : "accepts no options";
491
889
  throw new ConfigLoadError(`Unknown option ${JSON.stringify(name)} for rule ${ruleId}; the rule ${accepted}.`, SUGGEST_EDIT_CONFIG);
492
890
  }
493
- if (typeof option !== "number") {
494
- throw new ConfigLoadError(`Rule config option ${JSON.stringify(name)} for ${ruleId} must be numeric; got ${JSON.stringify(option)}.`, SUGGEST_EDIT_CONFIG);
495
- }
496
- options.set(name, option);
891
+ options.set(name, ruleOptionValue(ruleId, name, option));
497
892
  }
498
893
  return options;
499
894
  }
500
895
 
501
- // Returns the first supported config path at the project root; undefined otherwise so
502
- // 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
+ */
503
926
  function defaultConfigPath(projectRoot: string): string | undefined {
927
+ // Config names are checked in documented priority order so users get a deterministic selection.
504
928
  for (const fileName of DEFAULT_CONFIG_FILES) {
505
929
  const candidate = join(projectRoot, fileName);
930
+ // Discovery selects one path. The loader handles reading and validation.
506
931
  if (existsSync(candidate)) {
507
932
  return candidate;
508
933
  }
@@ -510,34 +935,137 @@ function defaultConfigPath(projectRoot: string): string | undefined {
510
935
  return undefined;
511
936
  }
512
937
 
513
- // Rules are enabled by default - the absence of a config entry means "use the descriptor default",
514
- // 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
+ */
515
946
  function ruleEnabled(config: Config, ruleId: string): boolean {
516
- return config.rules.get(ruleId)?.enabled ?? true;
947
+ return config.rules.get(ruleId)?.enabled ?? ruleDefaultEnabled(ruleId);
517
948
  }
518
949
 
519
- // Resolves a threshold for the rule. Callers pass the descriptor default so this helper alone
520
- // 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
+ */
521
959
  function threshold(config: Config, ruleId: string, defaultValue: number): number {
522
960
  return config.rules.get(ruleId)?.threshold ?? defaultValue;
523
961
  }
524
962
 
525
- // Same shape as `threshold`. The descriptor default is the single source of truth for what severity
526
- // 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
+ */
527
972
  function ruleSeverity(config: Config, ruleId: string, defaultSeverity: Severity): Severity {
528
973
  return config.rules.get(ruleId)?.severity ?? defaultSeverity;
529
974
  }
530
975
 
531
- // Rule-specific numeric options (e.g., minLength for sensitive-data rules). Same default-fallback
532
- // 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
+ */
533
985
  function optionNumber(config: Config, ruleId: string, name: string, defaultValue: number): number {
534
- 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;
535
988
  }
536
989
 
537
- // Whitelist check used both by config validation (throws on bad values) and by `applyRuleSeverityConfig`.
538
- // The set of accepted strings is the public severity vocabulary; adding entries is a schema change.
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;
1002
+ }
1003
+
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
+ */
539
1011
  function isSeverity(configValue: unknown): configValue is Severity {
540
1012
  return configValue === "advisory" || configValue === "warning" || configValue === "error";
541
1013
  }
542
1014
 
543
- 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 };