@blundergoat/gruff-ts 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,5 +1,7 @@
1
- // Renders the default .gruff-ts.yaml file from the rule descriptor registry so `gruff-ts init`
2
- // can drop a config into a fresh project that mirrors the analyser's effective defaults.
1
+ // Renders the starter `.gruff-ts.yaml` file from the rule descriptor registry when the user runs `gruff-ts init`.
2
+ //
3
+ // Gives a new project the analyser's effective defaults and preserves existing ignore paths, gates, and exclusions on `--force`.
4
+ // Also drives the interactive first-run init prompt before a terminal scan when no config file exists yet.
3
5
  import { existsSync, writeFileSync } from "node:fs";
4
6
  import { join } from "node:path";
5
7
  import { createInterface } from "node:readline/promises";
@@ -10,21 +12,18 @@ import type { FailThreshold, MinimumSeverityCommand, RuleDescriptor } from "./ty
10
12
 
11
13
  const DEFAULT_CONFIG_FILE_NAME = ".gruff-ts.yaml";
12
14
 
13
- // Default option values for rules with `optionKeys`. The source of truth is the
14
- // `optionNumber(config, ruleId, key, default)` call site in the rule implementation; mirroring
15
- // them here keeps `gruff-ts init` self-contained. `init-config.test.ts` asserts the values
16
- // here match the implementation defaults so drift fails the test suite, not user projects.
17
- const RULE_OPTION_DEFAULTS: Readonly<Record<string, Readonly<Record<string, number>>>> = {
15
+ // Default option values for rules declaring `optionKeys`, mirrored here so `gruff-ts init` stays self-contained.
16
+ // `init-config.test.ts` asserts parity with the live `optionNumber`/`optionBoolean` defaults in rule implementations.
17
+ const RULE_OPTION_DEFAULTS: Readonly<Record<string, Readonly<Record<string, number | boolean>>>> = {
18
18
  "design.large-module-concentration": { minFiles: 4, minLines: 80 },
19
- "naming.generic-parameter": { minCyclomatic: 8, minLineCount: 30, minParameters: 3 },
19
+ "docs.missing-param-tag": { everyCallable: true },
20
+ "docs.missing-return-tag": { everyCallable: true },
20
21
  };
21
22
 
22
- // Default starter list copied from `defaultConfig()` in config.ts. Generated separately because
23
- // the YAML form (a block sequence) is more reviewable than the inline `[...]` form a Set would emit.
24
- // Universal-programming abbreviations that earn their place across nearly any codebase; project-specific
25
- // vocabulary (domain acronyms) should be appended in the user's config rather than added here.
23
+ // Starter abbreviation allowlist copied from `defaultConfig()` in `config.ts`, emitted as a readable YAML block sequence.
24
+ // Project-specific domain acronyms belong in the repository's `.gruff-ts.yaml` rather than this universal starter list.
26
25
  const DEFAULT_ACCEPTED_ABBREVIATIONS: readonly string[] = [
27
- "age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url",
26
+ "age", "app", "db", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url",
28
27
  ];
29
28
 
30
29
  // Result of an init write attempt, including the no-clobber branch for existing config files.
@@ -33,16 +32,16 @@ interface InitResult {
33
32
  status: "written" | "overwritten" | "exists";
34
33
  }
35
34
 
36
- // Inputs the analyse/summary actions must collect before deciding whether to ask the user about
37
- // running `init`. Kept as an explicit shape so the predicate is testable without TTY mocking. All
38
- // three stream TTY states matter: stdin so the answer can be typed, stderr so the prompt is seen,
39
- // and stdout so a piped consumer (e.g. `... --format=json | jq`) does not block on hidden input.
35
+ // Inputs `analyse` and `summary` pass before deciding whether to prompt the user to run `gruff-ts init`.
36
+ //
37
+ // All three TTY flags matter so piped JSON commands (such as `--format=json | jq`) never block on an invisible interactive prompt.
40
38
  interface InitPromptContext {
41
39
  projectRoot: string;
42
40
  shouldSkipConfig: boolean;
43
41
  hasExplicitConfig: boolean;
44
42
  isInteractionAllowed: boolean;
45
43
  isOutputSuppressed: boolean;
44
+ isMachineFormat?: boolean;
46
45
  isStdinTty: boolean;
47
46
  isStdoutTty: boolean;
48
47
  isStderrTty: boolean;
@@ -50,45 +49,111 @@ interface InitPromptContext {
50
49
 
51
50
  /**
52
51
  * Bundle of values that survive an `init --force` regeneration. `paths.ignore` is preserved
53
- * verbatim, `minimumSeverity` is replayed entry-by-entry; the schemaVersion field is fixed for now
52
+ * verbatim, the per-command `failOn` gate is replayed entry-by-entry; the schemaVersion field is fixed for now
54
53
  * because there is only one supported version.
55
54
  */
56
55
  interface PreservedInitConfig {
57
56
  ignoredPaths: readonly string[];
58
- minimumSeverity: ReadonlyMap<MinimumSeverityCommand, FailThreshold>;
57
+ failOn: ReadonlyMap<MinimumSeverityCommand, FailThreshold>;
58
+ sensitiveExclusions: readonly PreservedSensitiveExclusionEntry[];
59
59
  }
60
60
 
61
- const EMPTY_PRESERVED_CONFIG: PreservedInitConfig = { ignoredPaths: [], minimumSeverity: new Map() };
61
+ // One reviewed suppression carried through regeneration, in the ratified key order.
62
+ interface PreservedSensitiveExclusionEntry {
63
+ rule: string;
64
+ path: string;
65
+ symbol?: string;
66
+ reason: string;
67
+ }
68
+
69
+ const EMPTY_PRESERVED_CONFIG: PreservedInitConfig = { ignoredPaths: [], failOn: new Map(), sensitiveExclusions: [] };
62
70
 
63
71
  /**
64
- * Render the default .gruff-ts.yaml content from the rule descriptor registry. Output order is
65
- * schemaVersion → minimumSeverity → paths → allowlists → rules so the highest-impact CI behaviour
66
- * (gating threshold per command) sits near the top of the file. Sections are separated by blank
67
- * lines for readability.
72
+ * Render the default .gruff-ts.yaml content from the rule descriptor registry. Output order is schemaVersion → failOn → paths → allowlists →
73
+ * sensitiveExclusions → rules so the highest-impact CI behaviour (gating threshold per command) sits near the top of the file. Sections are separated
74
+ * by blank lines for readability.
68
75
  *
69
- * @param ignoredPaths Optional `paths.ignore` entries to inject verbatim (block-sequence form).
70
- * The `gruff-ts init --force` flow forwards the existing file's entries so user-curated
71
- * exclusions survive regeneration; an empty list emits `ignore: []` for fresh projects.
72
- * @param preservedMinimumSeverity Optional carry-over of the existing config's `minimumSeverity:`
73
- * block. Empty Map falls back to canonical defaults (advisory / advisory / none).
76
+ * @param ignoredPaths - path exclusions kept by gruff-ts init --force. An empty list emits ignore: [].
77
+ * @param preservedFailOn - existing command gates. Missing entries default to advisory for analyse and none for summary and report.
78
+ * @param preservedSensitiveExclusions - existing reviewed suppressions, re-emitted below the guidance comments; an empty list emits only the comments
74
79
  * @returns A YAML document string terminated by a trailing newline.
75
80
  */
76
- function renderDefaultConfig(ignoredPaths: readonly string[] = [], preservedMinimumSeverity: ReadonlyMap<MinimumSeverityCommand, FailThreshold> = new Map()): string {
81
+ function renderDefaultConfig(
82
+ ignoredPaths: readonly string[] = [],
83
+ preservedFailOn: ReadonlyMap<MinimumSeverityCommand, FailThreshold> = new Map(),
84
+ preservedSensitiveExclusions: readonly PreservedSensitiveExclusionEntry[] = [],
85
+ ): string {
77
86
  return [
78
87
  renderSchemaVersionSection(),
79
88
  "",
80
- renderMinimumSeveritySection(preservedMinimumSeverity),
89
+ renderFailOnSection(preservedFailOn),
81
90
  "",
82
91
  renderPathsSection(ignoredPaths),
83
92
  "",
84
93
  renderAllowlistsSection(),
85
94
  "",
95
+ renderSensitiveExclusionsSection(preservedSensitiveExclusions),
96
+ "",
86
97
  renderRulesSection(),
87
98
  ].join("\n") + "\n";
88
99
  }
89
100
 
90
- // Required top-level schema-version field. Documented in ADR-004 because the introduction itself
91
- // is a pre-1.0 break - every existing config gains this line, no transitional shim.
101
+ /**
102
+ * Render the reviewed sensitive-data exclusions described in FAMILY-CONTRACT.md section 13a.
103
+ * Guidance stays commented so fresh projects suppress nothing here. Active entries come from prior manual review.
104
+ *
105
+ * @param preservedEntries - reviewed exclusions carried forward from the existing config
106
+ * @returns YAML section text with guidance and any preserved entries, or only commented guidance when the list is empty
107
+ */
108
+ function renderSensitiveExclusionsSection(preservedEntries: readonly PreservedSensitiveExclusionEntry[]): string {
109
+ const guidance = [
110
+ "# Reviewed suppressions for sensitive-data findings. Written by hand only - gruff never",
111
+ "# converts a detected value, a preview, or a finding message into an exclusion.",
112
+ "#",
113
+ "# Each entry names exactly one rule id and one project-relative path, and must carry a",
114
+ "# non-empty reason. `symbol:` narrows further where a rule stamps one. Nothing else is",
115
+ "# suppressed: the same rule in another file and another rule in the same file keep reporting.",
116
+ "# Every entry reports its own count in the report's `suppressions` array and in the text",
117
+ "# `Suppressed findings:` line, so a suppression is always visible in review.",
118
+ "#",
119
+ "# Test, fixture and example paths automatically suppress sensitive-data findings",
120
+ "# except sensitive-data.pii-test-fixture; real credentials there are skipped too.",
121
+ "# Add entries only for reviewed findings that still report.",
122
+ "# Use the finding's rule id and replace the path/reason placeholders.",
123
+ "# sensitiveExclusions:",
124
+ "# - rule: sensitive-data.aws-access-key",
125
+ "# path: <reviewed-project-relative-path>",
126
+ "# reason: <reviewed-rationale>",
127
+ ];
128
+ // Regeneration must never silently re-enable a finding a reviewer accepted in writing, so any
129
+ // existing entries are serialized as active YAML below the guidance comment.
130
+ if (preservedEntries.length === 0) {
131
+ return guidance.join("\n");
132
+ }
133
+ return [...guidance, "sensitiveExclusions:", ...preservedEntries.flatMap(renderPreservedExclusionEntry)].join("\n");
134
+ }
135
+
136
+ /**
137
+ * Format one preserved sensitive exclusion as block-sequence YAML lines in the expected key order.
138
+ * An entry without a symbol keeps that selector unset in the generated YAML.
139
+ *
140
+ * @param entry - reviewed exclusion containing rule, path, reason, and optional symbol
141
+ * @returns YAML lines for the entry in rule, path, optional symbol, and reason order
142
+ */
143
+ function renderPreservedExclusionEntry(entry: PreservedSensitiveExclusionEntry): string[] {
144
+ const lines = [` - rule: ${JSON.stringify(entry.rule)}`, ` path: ${JSON.stringify(entry.path)}`];
145
+ if (entry.symbol !== undefined) {
146
+ lines.push(` symbol: ${JSON.stringify(entry.symbol)}`);
147
+ }
148
+ lines.push(` reason: ${JSON.stringify(entry.reason)}`);
149
+ return lines;
150
+ }
151
+
152
+ /**
153
+ * Build the required top-level schema version field for the generated config.
154
+ *
155
+ * @returns YAML comment and `schemaVersion: gruff-ts.config.v0.1` line joined by a newline
156
+ */
92
157
  function renderSchemaVersionSection(): string {
93
158
  return [
94
159
  "# Config-schema version. Required as of gruff-ts 0.2.0. See ADR-004 (decision log).",
@@ -96,44 +161,42 @@ function renderSchemaVersionSection(): string {
96
161
  ].join("\n");
97
162
  }
98
163
 
99
- // Per-command --fail-on defaults. The canonical out-of-the-box values match the operator's "show
100
- // everything, fail on anything" philosophy. `dashboard` is intentionally NOT a valid key because
101
- // the dashboard subcommand has no --fail-on flag and accepting it would be a silent CI footgun.
102
- function renderMinimumSeveritySection(preserved: ReadonlyMap<MinimumSeverityCommand, FailThreshold>): string {
164
+ /**
165
+ * Build the `failOn` YAML section using preserved command thresholds when present.
166
+ * Missing analyse defaults to advisory; missing summary and report default to none. Dashboard has no entry.
167
+ *
168
+ * @param preserved - existing per-command fail thresholds recovered from a prior config
169
+ * @returns YAML header comments and `failOn:` block with analyse, summary, and report entries
170
+ */
171
+ function renderFailOnSection(preserved: ReadonlyMap<MinimumSeverityCommand, FailThreshold>): string {
103
172
  const header = [
104
173
  "# Per-command default for `--fail-on`. CLI flag > this block > binary default.",
105
174
  "# `dashboard` is intentionally NOT a valid key - it has no --fail-on flag. See ADR-004.",
175
+ "# `minimumSeverity:` is a different setting: one severity that hides quieter findings from the",
176
+ "# report without changing the score or the exit code.",
106
177
  "#",
107
178
  "# Values:",
108
179
  "# error - exit non-zero only when an error-severity finding fires (strictest gate).",
109
180
  "# warning - exit non-zero on warning or error findings (advisory findings pass).",
110
181
  "# advisory - exit non-zero on any finding at all (advisory, warning, or error).",
111
182
  "# none - never exit non-zero from findings (use for raw reporting / baseline generation).",
112
- "minimumSeverity:",
183
+ "failOn:",
113
184
  ];
114
185
  const entries: Array<[MinimumSeverityCommand, FailThreshold]> = [
115
186
  ["analyse", preserved.get("analyse") ?? "advisory"],
116
- ["summary", preserved.get("summary") ?? "advisory"],
187
+ ["summary", preserved.get("summary") ?? "none"],
117
188
  ["report", preserved.get("report") ?? "none"],
118
189
  ];
119
190
  return [...header, ...entries.map(([command, severity]) => ` ${command}: ${severity}`)].join("\n");
120
191
  }
121
192
 
122
193
  /**
123
- * Write the default config to `<projectRoot>/.gruff-ts.yaml`. Performs a filesystem write side
124
- * effect when no supported config exists, or when `shouldOverwrite` is true and `.gruff-ts.yaml`
125
- * is the incumbent. Refuses to clobber (no side effect) when ANY supported config file is present
126
- * (the four-name precedence list in `DEFAULT_CONFIG_FILES`), not just `.gruff-ts.yaml` -
127
- * otherwise `init` would silently create a higher-precedence file alongside an existing
128
- * `.gruff.yaml` / `.gruff.yml` / `.gruff.json` and quietly change the effective config. When
129
- * overwriting an existing `.gruff-ts.yaml`, the file's `paths.ignore` entries are preserved so
130
- * `init --force` does not erase project-specific recursive-scan exclusions.
194
+ * Writes .gruff-ts.yaml when no supported config exists or force is enabled.
195
+ * Uses DEFAULT_CONFIG_FILES precedence so the caller can name the blocking file or carry its settings forward on a forced write.
131
196
  *
132
- * @param projectRoot Directory to write the config file into.
133
- * @param shouldOverwrite Overwrite an existing config file when true.
134
- * @returns The resolved path and whether a file was written, overwritten, or skipped. When the
135
- * refusal is triggered by a non-canonical name, `path` points at that file so the caller's
136
- * error message names the actual blocker.
197
+ * @param projectRoot - directory to search for the incumbent config and write the canonical file
198
+ * @param shouldOverwrite - allows a canonical write even when a supported config already exists
199
+ * @returns the incumbent path with exists when skipped, or the canonical path with written or overwritten after a write
137
200
  */
138
201
  function writeDefaultConfig(projectRoot: string, shouldOverwrite: boolean): InitResult {
139
202
  const targetPath = join(projectRoot, DEFAULT_CONFIG_FILE_NAME);
@@ -142,23 +205,22 @@ function writeDefaultConfig(projectRoot: string, shouldOverwrite: boolean): Init
142
205
  return { path: existingConfigPath, status: "exists" };
143
206
  }
144
207
  const targetExists = existsSync(targetPath);
145
- // Preserve paths.ignore + minimumSeverity from whichever supported config exists, not just
146
- // `.gruff-ts.yaml` - otherwise `init --force` against a project with only
147
- // `.gruff.yaml`/`.yml`/`.json` would silently drop user-curated exclusions and command-specific
148
- // gating thresholds when generating the new canonical file.
208
+ // Carry forward paths.ignore, command gates, and reviewed sensitive exclusions so a forced write preserves the selected scan policy.
209
+ //
210
+ // An existing alias can supply that policy when the project has no canonical file.
211
+ // If the existing settings cannot be read, regeneration uses defaults.
149
212
  const preserved = existingConfigPath !== undefined ? readExistingPreservedConfig(existingConfigPath) : EMPTY_PRESERVED_CONFIG;
150
- writeFileSync(targetPath, renderDefaultConfig(preserved.ignoredPaths, preserved.minimumSeverity));
213
+ writeFileSync(targetPath, renderDefaultConfig(preserved.ignoredPaths, preserved.failOn, preserved.sensitiveExclusions));
151
214
  return { path: targetPath, status: targetExists ? "overwritten" : "written" };
152
215
  }
153
216
 
154
- /*
155
- * Recover the existing file's `paths.ignore` and `minimumSeverity` blocks before `init --force`
156
- * overwrites it. Uses the permissive extractor (not the strict validator) so a pre-0.2.0 config
157
- * without `schemaVersion` still hands its curated entries to the regenerated file - the strict
158
- * gate would throw on the missing field and silently drop the user's `paths.ignore`. The
159
- * try/catch swallows IO/parse errors and returns empty values so a malformed existing config
160
- * does not block regeneration; the user is opting into clobbering, but the documented contract
161
- * is that curated entries survive when readable.
217
+ /**
218
+ * Recover ignore paths, command gates, and reviewed sensitive exclusions from an existing config file.
219
+ * Uses the permissive extractor so configs without schemaVersion can retain their readable settings.
220
+ * Read or parse failures silently return empty settings because forced regeneration permits replacing unreadable content.
221
+ *
222
+ * @param existingConfigPath - path to the incumbent config file to read and extract settings from
223
+ * @returns recovered preserved config settings, or empty settings if extraction throws
162
224
  */
163
225
  function readExistingPreservedConfig(existingConfigPath: string): PreservedInitConfig {
164
226
  try {
@@ -168,14 +230,19 @@ function readExistingPreservedConfig(existingConfigPath: string): PreservedInitC
168
230
  }
169
231
  }
170
232
 
171
- // `paths.ignore` defaults to empty for fresh projects - discovery.ts already filters node_modules,
172
- // .git, etc. regardless of config. When `init --force` regenerates an existing config, the caller
173
- // forwards the existing entries so user-curated exclusions survive.
233
+ /**
234
+ * Build the `paths` YAML section with guidance comments and configured ignore patterns.
235
+ * With no supplied exclusions, it emits an empty ignore list because discovery already applies built-in ignores.
236
+ *
237
+ * @param ignoredPaths - existing path exclusions preserved so user entries survive forced regeneration
238
+ * @returns YAML `paths:` block containing either `ignore: []` or JSON-quoted ignore list entries
239
+ */
174
240
  function renderPathsSection(ignoredPaths: readonly string[]): string {
175
241
  const header = [
176
242
  "paths:",
177
243
  " # Recursive scans already respect .gitignore plus built-in default directories",
178
- " # such as .git, node_modules, dist, coverage, generated, tmp, and vendor.",
244
+ " # such as .git, node_modules, build, dist, coverage, and vendor.",
245
+ " # (.git, dist, and vendor are always skipped; node_modules, build, and coverage apply as fallback when no .gitignore governs.)",
179
246
  " # Add project-specific generated or local outputs here when Git does not ignore them.",
180
247
  " # Examples:",
181
248
  " # - \"out/**\"",
@@ -192,44 +259,34 @@ function renderPathsSection(ignoredPaths: readonly string[]): string {
192
259
  ].join("\n");
193
260
  }
194
261
 
195
- // `acceptedAbbreviations` is emitted as a block sequence for reviewability; the seven naming
196
- // allowlists below it stay commented out so users see the override knobs without changing defaults.
262
+ /**
263
+ * Build the starter YAML naming allowlists, listing the default abbreviations accepted in identifiers.
264
+ * The other naming allowlists stay commented so users can discover them without changing defaults.
265
+ *
266
+ * @returns YAML `allowlists:` section with `acceptedAbbreviations` and commented optional settings
267
+ */
197
268
  function renderAllowlistsSection(): string {
198
269
  return [
199
270
  "allowlists:",
271
+ " # Abbreviations listed here are accepted in identifiers without a naming finding.",
272
+ " # Replace this list with the short terms reviewers accept in this project.",
200
273
  " acceptedAbbreviations:",
201
274
  ...DEFAULT_ACCEPTED_ABBREVIATIONS.map((abbreviation) => ` - ${abbreviation}`),
202
- " secretPreviews: []",
203
- " # Names that trigger naming.generic-function. Each key replaces the built-in",
204
- " # default when present; an empty list disables that rule's blacklist branch.",
205
- " # Default: [process, handle, doit, run, execute, manage]",
206
- " # bannedGenericNames: [process, handle, doit, run, execute, manage]",
207
- " # Exact public/CLI/DTO boolean names accepted by naming.boolean-prefix.",
208
- " # Default: [all, apply, check, dev, enabled, force, fresh, harness, json, ok, verbose, yes]",
209
- " # acceptedBooleanNames: [all, apply, check, dev, enabled, force, fresh, harness, json, ok, verbose, yes]",
210
- " # Accepted prefixes for boolean identifiers. Names without one of these",
211
- " # prefixes trigger naming.boolean-prefix.",
212
- " # Default: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
213
- " # booleanPrefixes: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
214
- " # Hungarian type-style prefixes flagged by naming.hungarian-notation.",
215
- " # Default: [str, obj, arr, bool, int, num]",
216
- " # hungarianPrefixes: [str, obj, arr, bool, int, num]",
275
+ " # Exact fileBase:ClassName pairs accepted by naming.class-file-mismatch.",
276
+ " # Default: []",
277
+ " # acceptedClassFilePairs: [focusModeTranscript:TranscriptFocusController]",
217
278
  " # Placeholder words flagged as generic by naming.identifier-quality. The",
218
279
  " # numbered-suffix branch (foo1, value2) stays active even when this is empty.",
219
280
  " # Default: [foo, bar, baz, tmp, temp, thing, stuff, data, value, item]",
220
281
  " # placeholderNames: [foo, bar, baz, tmp, temp, thing, stuff, data, value, item]",
221
- " # Negative-framed boolean names that should NOT trigger naming.negative-boolean.",
222
- " # Defaults are HTTP-header conventions; add project terms as needed.",
223
- " # Default: [nostore, nofollow, noreferrer, noscript, noindex]",
224
- " # negativeBooleanAllowed: [nostore, nofollow, noreferrer, noscript, noindex]",
225
- " # Known acronyms whose mixed casings trigger naming.acronym-case. Stored",
226
- " # case-insensitively; match is against canonical lowercase.",
227
- " # Default: [url, http, https, id, xml, json, html, css, api, sql, db, io, ui, uuid, ip, tcp, udp, ast, cli, npm]",
228
- " # knownAcronyms: [url, http, https, id, xml, json, html, css, api, sql, db, io, ui, uuid, ip, tcp, udp, ast, cli, npm]",
229
282
  ].join("\n");
230
283
  }
231
284
 
232
- // Walks the registry in its canonical (sorted) order so the generated YAML is byte-stable.
285
+ /**
286
+ * Walk the rule registry in its canonical (sorted) order so the generated YAML is byte-stable.
287
+ *
288
+ * @returns YAML `rules:` section containing formatted entries for all registered rule descriptors
289
+ */
233
290
  function renderRulesSection(): string {
234
291
  const lines = ["rules:"];
235
292
  for (const descriptor of ruleDescriptors()) {
@@ -238,14 +295,18 @@ function renderRulesSection(): string {
238
295
  return lines.join("\n");
239
296
  }
240
297
 
241
- // One rule entry: a `# pillar/severity: description` comment line, the rule id, `enabled`, then
242
- // threshold/severity/options only when the descriptor declares them. Omitting absent keys keeps
243
- // the generated file aligned with the descriptor's actual contract.
298
+ /**
299
+ * Format YAML lines for a rule descriptor, including its description, id, and default enabled state.
300
+ * A numeric threshold adds threshold and severity; option fields come from RULE_OPTION_DEFAULTS when registered.
301
+ *
302
+ * @param descriptor - rule metadata entry from the registry to serialize
303
+ * @returns indented YAML comment and configuration lines for the rule
304
+ */
244
305
  function renderRuleEntry(descriptor: RuleDescriptor): string[] {
245
306
  const lines: string[] = [];
246
307
  lines.push(` # ${descriptor.pillar}/${descriptor.severity}: ${descriptor.description}`);
247
308
  lines.push(` ${descriptor.ruleId}:`);
248
- lines.push(" enabled: true");
309
+ lines.push(` enabled: ${descriptor.isEnabledByDefault !== false}`);
249
310
  if (typeof descriptor.threshold === "number") {
250
311
  lines.push(` threshold: ${descriptor.threshold}`);
251
312
  lines.push(` severity: ${descriptor.severity}`);
@@ -261,22 +322,18 @@ function renderRuleEntry(descriptor: RuleDescriptor): string[] {
261
322
  }
262
323
 
263
324
  /**
264
- * Decide whether the analyse/summary actions should prompt the user to run `init`.
325
+ * Decide whether analyse or summary may offer init when interaction is allowed and output is not suppressed.
326
+ * Requires no explicit config or opt-out, three TTY streams and no supported config file at the project root.
265
327
  *
266
- * Returns true only when every gate passes: interaction is allowed, output isn't suppressed, the
267
- * user hasn't already opted in (--config) or out (--no-config) of config loading, all three
268
- * standard streams are TTYs (stdin to type, stderr to display, stdout to confirm the run is not
269
- * piping machine output to a downstream consumer), and no supported config file is already
270
- * present at the project root.
271
- *
272
- * @param context CLI-collected state needed to make the decision.
328
+ * @param context - CLI flags, stream state and project root used to decide whether to prompt
273
329
  * @returns Whether the prompt should be shown.
274
330
  */
275
331
  function shouldPromptForInit(context: InitPromptContext): boolean {
276
332
  if (!context.isInteractionAllowed) {
277
333
  return false;
278
334
  }
279
- if (context.isOutputSuppressed) {
335
+ // Quiet runs and JSON, SARIF, GitHub or hotspot output never stop to ask, so automation reading stdout is not blocked.
336
+ if (context.isOutputSuppressed || context.isMachineFormat === true) {
280
337
  return false;
281
338
  }
282
339
  if (context.shouldSkipConfig || context.hasExplicitConfig) {
@@ -289,13 +346,11 @@ function shouldPromptForInit(context: InitPromptContext): boolean {
289
346
  }
290
347
 
291
348
  /**
292
- * Ask the user a yes/no question on stderr and return their answer.
293
- *
294
- * Defaults to "no" when the user just presses enter so the prompt is safe to dismiss. Reads from
295
- * stdin; closes the readline interface in a finally so a Ctrl-C exits cleanly.
349
+ * Ask the user a yes/no question on stderr, reading stdin; empty or other answers mean no.
350
+ * The readline interface closes when the question settles.
296
351
  *
297
- * @param question Prompt text written to stderr verbatim.
298
- * @returns True when the user typed y or yes (case-insensitive); false otherwise.
352
+ * @param question - prompt text written to stderr verbatim
353
+ * @returns true for a trimmed, case-insensitive y or yes; false for other answers
299
354
  */
300
355
  async function promptYesNo(question: string): Promise<boolean> {
301
356
  const readlineInterface = createInterface({ input: process.stdin, output: process.stderr });