@blundergoat/gruff-ts 0.1.1 → 0.2.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.
package/src/config.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  // Config loading and YAML-subset parsing for the analyzer's zero-dependency rule defaults.
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { extname, isAbsolute, join } from "node:path";
4
- import type { AnalysisOptions, Config, Severity } from "./types.ts";
4
+ import { ConfigLoadError } from "./config-load-error.ts";
5
+ import type { AnalysisOptions, Config, FailThreshold, MinimumSeverityCommand, Severity } from "./types.ts";
6
+
7
+ // Two common suggestion strings reused across the validators. Hoisted out so a future doc-link
8
+ // or wording tweak lands in one place instead of N throw sites.
9
+ const SUGGEST_INIT_FORCE = "Run `gruff-ts init --force` to regenerate the config from current defaults (preserves your `paths.ignore` and `minimumSeverity:` entries).";
10
+ const SUGGEST_EDIT_CONFIG = "Edit `.gruff-ts.yaml` to use a valid value, or run `gruff-ts init --force` to regenerate from defaults.";
5
11
 
6
12
  type RuleOverride = Config["rules"] extends Map<string, infer RuleOverrideValue> ? RuleOverrideValue : never;
7
13
 
@@ -26,17 +32,20 @@ const UNMATCHED_YAML_SCALAR: ParsedYamlScalar = { isMatched: false, value: undef
26
32
  // Built-in defaults applied before any user config overlays. The string lists here (accepted
27
33
  // abbreviations, banned generic names, boolean prefixes, …) are the stable rule contract - they
28
34
  // shape what every gruff scan emits by default and changing them shifts the public rule surface.
35
+ // schemaVersion is fixed at `gruff-ts.config.v0.1` as the schema invariant for this release.
29
36
  function defaultConfig(): Config {
30
37
  return {
38
+ schemaVersion: "gruff-ts.config.v0.1",
31
39
  ignoredPaths: [],
32
- acceptedAbbreviations: new Set(["id", "db", "fs", "io", "ui", "tx", "rx"]),
40
+ acceptedAbbreviations: new Set(["age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
33
41
  secretPreviews: new Set(),
34
42
  bannedGenericNames: new Set(["process", "handle", "doit", "run", "execute", "manage"]),
35
- booleanPrefixes: new Set(["is", "has", "can", "should", "does", "did", "was", "will", "may", "in", "scan", "supports", "requires"]),
43
+ 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"]),
36
44
  hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
37
45
  placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
38
46
  negativeBooleanAllowed: new Set(["nostore", "nofollow", "noreferrer", "noscript", "noindex"]),
39
47
  knownAcronyms: new Set(["url", "http", "https", "id", "xml", "json", "html", "css", "api", "sql", "db", "io", "ui", "uuid", "ip", "tcp", "udp", "ast", "cli", "npm"]),
48
+ minimumSeverity: new Map(),
40
49
  rules: new Map(),
41
50
  };
42
51
  }
@@ -69,15 +78,87 @@ function selectedConfigPath(projectRoot: string, options: AnalysisOptions): stri
69
78
  return options.config ? absolutize(projectRoot, options.config) : defaultConfigPath(projectRoot);
70
79
  }
71
80
 
72
- // Three top-level sections of the config schema applied in a fixed order: paths → allowlists →
73
- // rules. Order does not affect correctness today but the stable application order keeps later
74
- // overrides predictable if interdependencies are added.
81
+ // Top-level sections applied in a fixed order: schemaVersion → minimumSeverity → paths → allowlists
82
+ // → rules. schemaVersion runs first because every later parse depends on the contract version it
83
+ // declares, and minimumSeverity runs next so CLI consumers reading it during normalizeOptions see
84
+ // a populated map. Order does not affect correctness today but the stable application order keeps
85
+ // later overrides predictable if interdependencies are added.
75
86
  function applyConfigValues(config: Config, raw: Record<string, unknown>): void {
87
+ applySchemaVersionConfig(raw);
88
+ applyMinimumSeverityConfig(config, raw);
76
89
  applyPathConfig(config, raw);
77
90
  applyAllowlistConfig(config, raw);
78
91
  applyRuleConfig(config, raw);
79
92
  }
80
93
 
94
+ /*
95
+ * Validates the required `schemaVersion` top-level field. Pre-1.0 break: configs missing the field
96
+ * or carrying any other version string are rejected (throws with a documented error listing the
97
+ * supported version) because there is no migration shim under the no-legacy-compat contract. The
98
+ * function does not mutate the loaded config because the only supported value matches
99
+ * `defaultConfig().schemaVersion` already; future versions would extend the union and require a
100
+ * write here. The schema invariant is fixed at `gruff-ts.config.v0.1`.
101
+ */
102
+ function applySchemaVersionConfig(raw: Record<string, unknown>): void {
103
+ const schemaVersion = raw.schemaVersion;
104
+ if (schemaVersion === undefined) {
105
+ throw new ConfigLoadError('Config must include `schemaVersion: gruff-ts.config.v0.1` at the top.', SUGGEST_INIT_FORCE);
106
+ }
107
+ if (schemaVersion !== "gruff-ts.config.v0.1") {
108
+ throw new ConfigLoadError(`Unsupported schemaVersion: ${JSON.stringify(schemaVersion)}. Supported: "gruff-ts.config.v0.1".`, SUGGEST_INIT_FORCE);
109
+ }
110
+ }
111
+
112
+ // Parses the `minimumSeverity:` block into a Map keyed by command name. Validation throws on
113
+ // `dashboard` specifically (no `--fail-on` flag exists for it), on unknown command keys, and on
114
+ // every non-canonical value. Missing block is allowed - it just leaves the map empty so CLI
115
+ // consumers fall through to the binary default.
116
+ function applyMinimumSeverityConfig(config: Config, raw: Record<string, unknown>): void {
117
+ const block = objectValue(raw.minimumSeverity);
118
+ if (!block) {
119
+ return;
120
+ }
121
+ for (const [commandName, value] of Object.entries(block)) {
122
+ config.minimumSeverity.set(assertMinimumSeverityCommand(commandName), parseFailThresholdConfig(value));
123
+ }
124
+ }
125
+
126
+ /*
127
+ * Validates one `minimumSeverity:` map key. Throws on `dashboard` specifically because the
128
+ * dashboard subcommand has no `--fail-on` flag; accepting the key would silently no-op and
129
+ * operators would expect a gate that never fires. Throws on unknown commands so typos surface at
130
+ * load time instead of as silent CI footguns.
131
+ */
132
+ function assertMinimumSeverityCommand(commandName: string): MinimumSeverityCommand {
133
+ if (commandName === "dashboard") {
134
+ 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.");
135
+ }
136
+ if (commandName === "analyse" || commandName === "summary" || commandName === "report") {
137
+ return commandName;
138
+ }
139
+ throw new ConfigLoadError(`Unknown command in minimumSeverity: ${JSON.stringify(commandName)}. Valid keys: analyse, summary, report.`, SUGGEST_EDIT_CONFIG);
140
+ }
141
+
142
+ /*
143
+ * Validates one `FailThreshold` value coming from YAML. Throws on every non-canonical value with a
144
+ * clear error listing the four supported strings. `never` is rejected explicitly because earlier
145
+ * cross-port drafts considered it as the off-switch value before the family converged on `none`;
146
+ * guarding against drift back to `never` keeps the cross-port vocabulary aligned.
147
+ */
148
+ function parseFailThresholdConfig(rawValue: unknown): FailThreshold {
149
+ if (rawValue === "none" || rawValue === "advisory" || rawValue === "warning" || rawValue === "error") {
150
+ return rawValue;
151
+ }
152
+ throw new ConfigLoadError(`FailThreshold must be one of: advisory, warning, error, none. Got: ${JSON.stringify(rawValue)}.`, SUGGEST_EDIT_CONFIG);
153
+ }
154
+
155
+ // Per-command lookup used by the CLI precedence chain (CLI flag > config > binary default).
156
+ // Returns undefined when the user did not configure that command so the caller can fall through
157
+ // to the binary default. Exported so the CLI consumers in `cli-program.ts` can consult it.
158
+ function minimumSeverityFor(config: Config, command: MinimumSeverityCommand): FailThreshold | undefined {
159
+ return config.minimumSeverity.get(command);
160
+ }
161
+
81
162
  // Replaces `ignoredPaths` with the user list. Non-string entries are silently dropped - invalid
82
163
  // YAML shapes should not abort the analysis run.
83
164
  function applyPathConfig(config: Config, raw: Record<string, unknown>): void {
@@ -139,18 +220,23 @@ function ruleConfigValue(rule: Record<string, unknown>): RuleOverride {
139
220
  return ruleOverride;
140
221
  }
141
222
 
142
- /** Validates the public threshold/severity pair contract and throws before malformed rule options are parsed. */
223
+ /*
224
+ * Validates individual `threshold` and `severity` types. Either, neither, or both may be present:
225
+ * many rules have no `threshold` knob at all (security.eval-call, waste.any-type, etc.), so a
226
+ * "must be configured together" gate would block any severity-only override on those rules even
227
+ * though `gruff-ts list-rules <id>` advertises `rules.<id>.severity` as a public knob. Each field
228
+ * is independently optional and falls through to the descriptor default when absent.
229
+ *
230
+ * Throws ConfigLoadError when `threshold` is present but non-numeric, or when `severity` is
231
+ * present but not one of `advisory|warning|error`. Returns silently when both fields are absent
232
+ * (the common case for `enabled`-only or options-only overrides).
233
+ */
143
234
  function assertRuleThresholdConfig(rule: Record<string, unknown>): void {
144
- const hasThreshold = "threshold" in rule;
145
- const hasSeverity = "severity" in rule;
146
- if (hasThreshold && typeof rule.threshold !== "number") {
147
- throw new Error('Rule config key "threshold" must be numeric.');
148
- }
149
- if (hasSeverity && !isSeverity(rule.severity)) {
150
- throw new Error('Rule config key "severity" must be "advisory", "warning", or "error".');
235
+ if ("threshold" in rule && typeof rule.threshold !== "number") {
236
+ throw new ConfigLoadError('Rule config key "threshold" must be numeric.', SUGGEST_EDIT_CONFIG);
151
237
  }
152
- if (hasThreshold !== hasSeverity) {
153
- throw new Error('Rule config keys "threshold" and "severity" must be configured together.');
238
+ if ("severity" in rule && !isSeverity(rule.severity)) {
239
+ throw new ConfigLoadError('Rule config key "severity" must be "advisory", "warning", or "error".', SUGGEST_EDIT_CONFIG);
154
240
  }
155
241
  }
156
242
 
@@ -204,20 +290,62 @@ function defaultConfigPath(projectRoot: string): string | undefined {
204
290
  }
205
291
 
206
292
  /*
207
- * Reads YAML or JSON config and rejects unknown extensions. Throws on malformed input so the user
208
- * sees a concrete error rather than a silently-empty config.
293
+ * Reads YAML or JSON config and rejects unknown extensions. Raw IO failures (e.g. `--config <path>`
294
+ * pointing at a missing file) and JSON parse failures are rewrapped as ConfigLoadError so the CLI
295
+ * surface stays uniform - a bare ENOENT or SyntaxError would otherwise bypass the formatted
296
+ * "gruff-ts: config error" stderr path in `runWithConfigErrorHandling`.
297
+ *
298
+ * Throws ConfigLoadError when: the file is missing (ENOENT), the contents are not valid JSON, the
299
+ * YAML subset rejects the file (see parseYamlConfig), or the top-level value is not a mapping.
209
300
  */
210
301
  function parseConfigFile(path: string): Record<string, unknown> {
211
- const source = readFileSync(path, "utf8").replace(/^\uFEFF/, "");
302
+ const source = readConfigSource(path);
212
303
  const extension = extname(path).toLowerCase();
213
- const parsed = extension === ".yaml" || extension === ".yml" ? parseYamlConfig(source) : extension === ".json" ? (JSON.parse(source) as unknown) : undefined;
304
+ const parsed = parseConfigSource(source, extension, path);
214
305
  const config = objectValue(parsed);
215
306
  if (!config) {
216
- throw new Error(`Config file must contain an object with .yaml, .yml, or .json extension: ${path}`);
307
+ throw new ConfigLoadError(`Config file must contain an object with .yaml, .yml, or .json extension: ${path}`, SUGGEST_INIT_FORCE);
217
308
  }
218
309
  return config;
219
310
  }
220
311
 
312
+ /*
313
+ * Reads the raw config bytes. Explicit `--config <path>` skips the `defaultConfigPath` existence
314
+ * check, so a typo here would otherwise dump a raw Node stack. Throws ConfigLoadError on ENOENT
315
+ * with a user-actionable suggestion; rethrows every other filesystem error unchanged so an
316
+ * unexpected IO failure still surfaces its native stack for debugging.
317
+ */
318
+ function readConfigSource(path: string): string {
319
+ try {
320
+ return readFileSync(path, "utf8").replace(/^\uFEFF/, "");
321
+ } catch (error) {
322
+ if ((error as NodeJS.ErrnoException | null)?.code === "ENOENT") {
323
+ throw new ConfigLoadError(`Config file not found: ${path}.`, "Pass --config with an existing path, or omit the flag to use the default lookup.");
324
+ }
325
+ throw error;
326
+ }
327
+ }
328
+
329
+ // Routes to the YAML subset parser or the native JSON parser. Wraps `JSON.parse`'s SyntaxError so
330
+ // a malformed `.gruff.json` surfaces through the same ConfigLoadError channel as YAML failures
331
+ // (parseYamlConfig already throws ConfigLoadError on its own malformed inputs).
332
+ function parseConfigSource(source: string, extension: string, path: string): unknown {
333
+ if (extension === ".yaml" || extension === ".yml") {
334
+ return parseYamlConfig(source);
335
+ }
336
+ if (extension !== ".json") {
337
+ return undefined;
338
+ }
339
+ try {
340
+ return JSON.parse(source) as unknown;
341
+ } catch (error) {
342
+ if (error instanceof SyntaxError) {
343
+ throw new ConfigLoadError(`Config file is not valid JSON: ${error.message} (${path}).`, SUGGEST_EDIT_CONFIG);
344
+ }
345
+ throw error;
346
+ }
347
+ }
348
+
221
349
  // One non-blank, comment-stripped YAML line. `indent` is the column count (spaces only - tabs are
222
350
  // rejected upstream) and is the sole signal used to nest blocks. `content` is whitespace-trimmed.
223
351
  interface YamlLine {
@@ -242,7 +370,7 @@ function parseYamlConfig(source: string): Record<string, unknown> {
242
370
  const parsedDocument = parser.lines.length === 0 ? {} : parseYamlBlock(parser, parser.lines[0]?.indent ?? 0);
243
371
  const config = objectValue(parsedDocument);
244
372
  if (!config) {
245
- throw new Error("Config YAML must contain a mapping object.");
373
+ throw new ConfigLoadError("Config YAML must contain a mapping object.", SUGGEST_INIT_FORCE);
246
374
  }
247
375
  return config;
248
376
  }
@@ -333,7 +461,7 @@ function parseNestedYamlValue(parser: YamlParser, indent: number, fallback: unkn
333
461
  function yamlKeyValuePair(content: string): [string, string] {
334
462
  const pair = splitYamlKeyValue(content);
335
463
  if (!pair) {
336
- throw new Error(`Invalid YAML mapping line: "${content}".`);
464
+ throw new ConfigLoadError(`Invalid YAML mapping line: "${content}".`, SUGGEST_INIT_FORCE);
337
465
  }
338
466
  return pair;
339
467
  }
@@ -349,7 +477,7 @@ function isYamlArrayLine(line: YamlLine): boolean {
349
477
  */
350
478
  function assertYamlIndent(line: YamlLine, indent: number): void {
351
479
  if (line.indent > indent) {
352
- throw new Error(`Invalid YAML indentation near "${line.content}".`);
480
+ throw new ConfigLoadError(`Invalid YAML indentation near "${line.content}".`, SUGGEST_INIT_FORCE);
353
481
  }
354
482
  }
355
483
 
@@ -367,7 +495,7 @@ function yamlLines(source: string): YamlLine[] {
367
495
  }
368
496
  const indentText = withoutComment.match(/^\s*/)?.[0] ?? "";
369
497
  if (indentText.includes("\t")) {
370
- throw new Error("Tabs are not supported in gruff YAML config indentation.");
498
+ throw new ConfigLoadError("Tabs are not supported in gruff YAML config indentation.", SUGGEST_INIT_FORCE);
371
499
  }
372
500
  lines.push({ indent: indentText.length, content: withoutComment.trimStart() });
373
501
  }
@@ -617,4 +745,4 @@ function isSeverity(configValue: unknown): configValue is Severity {
617
745
  return configValue === "advisory" || configValue === "warning" || configValue === "error";
618
746
  }
619
747
 
620
- export { defaultConfigPath, isString, loadConfig, objectValue, optionNumber, ruleEnabled, ruleSeverity, threshold };
748
+ export { defaultConfigPath, isString, loadConfig, minimumSeverityFor, objectValue, optionNumber, parseConfigFile, ruleEnabled, ruleSeverity, threshold };
package/src/constants.ts CHANGED
@@ -1,4 +1,12 @@
1
1
  // Shared release constants that keep CLI, reports, and rule catalogue output in sync.
2
- const VERSION = "0.1.1";
2
+ const VERSION = "0.2.0";
3
3
 
4
- export { VERSION };
4
+ /*
5
+ * Threshold at which the `analyse` text renderer appends a one-line pointer to `gruff-ts summary`.
6
+ * Below 50 a flat list is still browsable; above 50 the operator hits scroll fatigue and needs the
7
+ * per-rule digest. Calibrated against the gruff-ts self-scan (~8 findings) and the goat-flow scan
8
+ * in 2026-05-25 feedback (1643 findings) - the threshold earns its keep at the cross-over.
9
+ */
10
+ const OUTPUT_VOLUME_HINT_THRESHOLD = 50;
11
+
12
+ export { OUTPUT_VOLUME_HINT_THRESHOLD, VERSION };
package/src/dashboard.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Loopback dashboard HTTP surface that renders live analyzer reports without exposing remote scans.
2
2
  import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
3
3
  import { chdir, cwd, stdout } from "node:process";
4
- import { dashboardErrorHtml, dashboardHomeHtml, renderHtml } from "./report-renderers.ts";
4
+ import { dashboardErrorHtml, dashboardHomeHtml, renderHtml } from "./report-html.ts";
5
5
  import type { AnalysisOptions, AnalysisReport } from "./types.ts";
6
6
 
7
7
  type DashboardAnalyse = (options: AnalysisOptions) => AnalysisReport;
@@ -31,29 +31,75 @@ export function analyseDeadCode(file: SourceFile, source: string, findings: Find
31
31
  }
32
32
  }
33
33
 
34
- // Line-by-line walker that resets the terminator flag at every `case:` / `default:` so dead-code
35
- // detection respects control-flow boundaries. Each line is walked once in source order, then
36
- // reports `waste.unreachable-code` with stable, deterministic fingerprint anchors.
34
+ /*
35
+ * Line-by-line walker that resets the terminator flag at every `case:` / `default:` because
36
+ * dead-code detection must respect control-flow boundaries. Each line is walked once in source
37
+ * order; the per-line state-machine update is extracted into `advanceUnreachableState` to keep
38
+ * this loop's branching low. Reports `waste.unreachable-code` with stable, deterministic
39
+ * fingerprint anchors so baselines and report snapshots round-trip without churn.
40
+ */
37
41
  export function analyseUnreachable(file: SourceFile, source: string, findings: Finding[]): void {
38
- let didPreviousTerminate = false;
39
- let isInConditionalBranch = false;
42
+ let state: UnreachableScanState = { didPreviousTerminate: false, conditionalParenDepth: 0, isConsequentPending: false };
40
43
  source.split(/\r?\n/).forEach((line, index) => {
41
44
  const trimmed = line.trim();
42
45
  const branchLabel = isBranchLabel(trimmed);
43
- if (branchLabel) {
44
- didPreviousTerminate = false;
45
- }
46
- if (isUnreachableStatement(trimmed, didPreviousTerminate, branchLabel)) {
46
+ const didPriorTerminate = branchLabel ? false : state.didPreviousTerminate;
47
+ if (isUnreachableStatement(trimmed, didPriorTerminate, branchLabel)) {
47
48
  findings.push(finding({ ruleId: "waste.unreachable-code", message: "Statement appears after a terminating statement.", file, line: index + 1, severity: "warning", pillar: "maintainability" }));
48
49
  }
49
- // A terminating statement inside a braceless conditional body does not unconditionally exit:
50
- // `if (x)\n return y;\nnextLine` - `nextLine` runs when `x` is falsy. Tracking the prior line's
51
- // conditional-opener shape suppresses the false positive on compact guard clauses.
52
- didPreviousTerminate = isTerminatingStatement(trimmed) && !isInConditionalBranch;
53
- isInConditionalBranch = isBracelessConditionalOpener(trimmed);
50
+ state = advanceUnreachableState(trimmed, { ...state, didPreviousTerminate: didPriorTerminate });
54
51
  });
55
52
  }
56
53
 
54
+ // Working state for the unreachable walker. Tracking these three fields together keeps the
55
+ // state-machine transitions explicit and lets the per-line update return a fresh value rather
56
+ // than mutating shared scope.
57
+ interface UnreachableScanState {
58
+ didPreviousTerminate: boolean;
59
+ conditionalParenDepth: number;
60
+ isConsequentPending: boolean;
61
+ }
62
+
63
+ /*
64
+ * Computes the next walker state from the current line. The conditional-context check (inside the
65
+ * predicate parens, or on the consequent line) drives whether a terminator on this line counts as
66
+ * unconditional. Branching is intentional here because the multi-line predicate has three discrete
67
+ * cases: opener line, inside-predicate continuation, and "no longer in a predicate." Splitting
68
+ * them inline would invariably reintroduce the npath the wrapper was trying to avoid.
69
+ */
70
+ function advanceUnreachableState(trimmed: string, state: UnreachableScanState): UnreachableScanState {
71
+ const isInConditionalBranch = state.conditionalParenDepth > 0 || state.isConsequentPending;
72
+ const didPreviousTerminate = isTerminatingStatement(trimmed) && !isInConditionalBranch;
73
+ if (isBracelessConditionalOpener(trimmed)) {
74
+ const balance = parenBalance(trimmed);
75
+ const conditionalParenDepth = balance > 0 ? balance : 0;
76
+ return { didPreviousTerminate, conditionalParenDepth, isConsequentPending: conditionalParenDepth === 0 };
77
+ }
78
+ if (state.conditionalParenDepth > 0) {
79
+ const conditionalParenDepth = Math.max(0, state.conditionalParenDepth + parenBalance(trimmed));
80
+ return { didPreviousTerminate, conditionalParenDepth, isConsequentPending: conditionalParenDepth === 0 };
81
+ }
82
+ return { didPreviousTerminate, conditionalParenDepth: 0, isConsequentPending: false };
83
+ }
84
+
85
+ // Net paren balance for one line of masked code (opens minus closes). String-literal parens are
86
+ // already blanked upstream by the masker, so the count is reliable for predicate-depth tracking.
87
+ function parenBalance(text: string): number {
88
+ return countChar(text, "(") - countChar(text, ")");
89
+ }
90
+
91
+ // Counts a single character's occurrences without allocating a match array. Used to balance parens
92
+ // across the lines of a multi-line conditional predicate in `analyseUnreachable`.
93
+ function countChar(text: string, character: string): number {
94
+ let count = 0;
95
+ for (const char of text) {
96
+ if (char === character) {
97
+ count += 1;
98
+ }
99
+ }
100
+ return count;
101
+ }
102
+
57
103
  // Detects single-line conditional/loop openers that begin a one-statement body (no `{`). The next
58
104
  // line is the conditional body, so any terminator there is conditional rather than unconditional.
59
105
  function isBracelessConditionalOpener(trimmed: string): boolean {
package/src/doc-rules.ts CHANGED
@@ -50,9 +50,9 @@ export function exportedDeclarations(source: string, codeSource: string): Export
50
50
  }
51
51
 
52
52
  /*
53
- * Skips functions and interfaces - those have dedicated rules (`docs.missing-function-doc`,
54
- * `docs.missing-interface-doc`). Reports the stable `docs.missing-public-doc` finding for
55
- * classes/types/enums without a leading JSDoc-style block comment.
53
+ * Skips functions and interfaces - those have dedicated rules (`docs.missing-exported-function-doc`,
54
+ * `docs.missing-internal-function-doc`, `docs.missing-interface-doc`). Reports the stable
55
+ * `docs.missing-public-doc` finding for classes/types/enums without a leading JSDoc-style block comment.
56
56
  */
57
57
  export function pushMissingPublicDocFinding(file: SourceFile, source: string, declaration: ExportedDeclaration, findings: Finding[]): void {
58
58
  if (declaration.kind === "function" || declaration.kind === "interface") {
@@ -106,3 +106,20 @@ export function isGenericName(name: string, bannedNames: Set<string>): boolean {
106
106
  export function escapeRegex(source: string): string {
107
107
  return source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
108
108
  }
109
+
110
+ /*
111
+ * Per-rule severity tally for the `summary` Top-N rules block. Walks the findings once and returns
112
+ * a deterministic Map keyed by ruleId carrying total / error / warning / advisory counts. Lets the
113
+ * renderer surface "412 (0 err / 0 warn / 412 adv)" rows without re-scanning findings per row. The
114
+ * count shape mirrors the `summary` schema invariant - total must equal err + warn + adv.
115
+ */
116
+ export function countRuleSeverities(findings: Finding[]): Map<string, { total: number; error: number; warning: number; advisory: number }> {
117
+ const counts = new Map<string, { total: number; error: number; warning: number; advisory: number }>();
118
+ for (const finding of findings) {
119
+ const entry = counts.get(finding.ruleId) ?? { total: 0, error: 0, warning: 0, advisory: 0 };
120
+ entry.total += 1;
121
+ entry[finding.severity] += 1;
122
+ counts.set(finding.ruleId, entry);
123
+ }
124
+ return counts;
125
+ }
@@ -3,9 +3,10 @@
3
3
  import { existsSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
6
- import { defaultConfigPath, loadConfig } from "./config.ts";
6
+ import { defaultConfigPath } from "./config.ts";
7
+ import { extractPreservedConfigFields } from "./config-preservation.ts";
7
8
  import { ruleDescriptors } from "./rules.ts";
8
- import type { RuleDescriptor } from "./types.ts";
9
+ import type { FailThreshold, MinimumSeverityCommand, RuleDescriptor } from "./types.ts";
9
10
 
10
11
  const DEFAULT_CONFIG_FILE_NAME = ".gruff-ts.yaml";
11
12
 
@@ -20,7 +21,11 @@ const RULE_OPTION_DEFAULTS: Readonly<Record<string, Readonly<Record<string, numb
20
21
 
21
22
  // Default starter list copied from `defaultConfig()` in config.ts. Generated separately because
22
23
  // the YAML form (a block sequence) is more reviewable than the inline `[...]` form a Set would emit.
23
- const DEFAULT_ACCEPTED_ABBREVIATIONS: readonly string[] = ["id", "db", "fs", "io", "ui", "tx", "rx"];
24
+ // Universal-programming abbreviations that earn their place across nearly any codebase; project-specific
25
+ // vocabulary (domain acronyms) should be appended in the user's config rather than added here.
26
+ const DEFAULT_ACCEPTED_ABBREVIATIONS: readonly string[] = [
27
+ "age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url",
28
+ ];
24
29
 
25
30
  // Result of an init write attempt, including the no-clobber branch for existing config files.
26
31
  interface InitResult {
@@ -44,15 +49,74 @@ interface InitPromptContext {
44
49
  }
45
50
 
46
51
  /**
47
- * Render the default .gruff-ts.yaml content from the rule descriptor registry.
52
+ * Bundle of values that survive an `init --force` regeneration. `paths.ignore` is preserved
53
+ * verbatim, `minimumSeverity` is replayed entry-by-entry; the schemaVersion field is fixed for now
54
+ * because there is only one supported version.
55
+ */
56
+ interface PreservedInitConfig {
57
+ ignoredPaths: readonly string[];
58
+ minimumSeverity: ReadonlyMap<MinimumSeverityCommand, FailThreshold>;
59
+ }
60
+
61
+ const EMPTY_PRESERVED_CONFIG: PreservedInitConfig = { ignoredPaths: [], minimumSeverity: new Map() };
62
+
63
+ /**
64
+ * Render the default .gruff-ts.yaml content from the rule descriptor registry. Output order is
65
+ * schemaVersion → minimumSeverity → paths → allowlists → rules so the highest-impact CI behaviour
66
+ * (gating threshold per command) sits near the top of the file. Sections are separated by blank
67
+ * lines for readability.
48
68
  *
49
- * @param ignoredPaths Optional `paths.ignore` entries to inject verbatim (block-sequence form). The
50
- * `gruff-ts init --force` flow forwards the existing file's entries so user-curated exclusions
51
- * survive regeneration; an empty list emits `ignore: []` for fresh projects.
69
+ * @param ignoredPaths Optional `paths.ignore` entries to inject verbatim (block-sequence form).
70
+ * The `gruff-ts init --force` flow forwards the existing file's entries so user-curated
71
+ * exclusions survive regeneration; an empty list emits `ignore: []` for fresh projects.
72
+ * @param preservedMinimumSeverity Optional carry-over of the existing config's `minimumSeverity:`
73
+ * block. Empty Map falls back to canonical defaults (advisory / advisory / none).
52
74
  * @returns A YAML document string terminated by a trailing newline.
53
75
  */
54
- function renderDefaultConfig(ignoredPaths: readonly string[] = []): string {
55
- return [renderPathsSection(ignoredPaths), "", renderAllowlistsSection(), "", renderRulesSection()].join("\n") + "\n";
76
+ function renderDefaultConfig(ignoredPaths: readonly string[] = [], preservedMinimumSeverity: ReadonlyMap<MinimumSeverityCommand, FailThreshold> = new Map()): string {
77
+ return [
78
+ renderSchemaVersionSection(),
79
+ "",
80
+ renderMinimumSeveritySection(preservedMinimumSeverity),
81
+ "",
82
+ renderPathsSection(ignoredPaths),
83
+ "",
84
+ renderAllowlistsSection(),
85
+ "",
86
+ renderRulesSection(),
87
+ ].join("\n") + "\n";
88
+ }
89
+
90
+ // Required top-level schema-version field. Documented in ADR-004 because the introduction itself
91
+ // is a pre-1.0 break - every existing config gains this line, no transitional shim.
92
+ function renderSchemaVersionSection(): string {
93
+ return [
94
+ "# Config-schema version. Required as of gruff-ts 0.2.0. See ADR-004 (decision log).",
95
+ "schemaVersion: gruff-ts.config.v0.1",
96
+ ].join("\n");
97
+ }
98
+
99
+ // Per-command --fail-on defaults. The canonical out-of-the-box values match the operator's "show
100
+ // everything, fail on anything" philosophy. `dashboard` is intentionally NOT a valid key because
101
+ // the dashboard subcommand has no --fail-on flag and accepting it would be a silent CI footgun.
102
+ function renderMinimumSeveritySection(preserved: ReadonlyMap<MinimumSeverityCommand, FailThreshold>): string {
103
+ const header = [
104
+ "# Per-command default for `--fail-on`. CLI flag > this block > binary default.",
105
+ "# `dashboard` is intentionally NOT a valid key - it has no --fail-on flag. See ADR-004.",
106
+ "#",
107
+ "# Values:",
108
+ "# error - exit non-zero only when an error-severity finding fires (strictest gate).",
109
+ "# warning - exit non-zero on warning or error findings (advisory findings pass).",
110
+ "# advisory - exit non-zero on any finding at all (advisory, warning, or error).",
111
+ "# none - never exit non-zero from findings (use for raw reporting / baseline generation).",
112
+ "minimumSeverity:",
113
+ ];
114
+ const entries: Array<[MinimumSeverityCommand, FailThreshold]> = [
115
+ ["analyse", preserved.get("analyse") ?? "advisory"],
116
+ ["summary", preserved.get("summary") ?? "advisory"],
117
+ ["report", preserved.get("report") ?? "none"],
118
+ ];
119
+ return [...header, ...entries.map(([command, severity]) => ` ${command}: ${severity}`)].join("\n");
56
120
  }
57
121
 
58
122
  /**
@@ -78,33 +142,29 @@ function writeDefaultConfig(projectRoot: string, shouldOverwrite: boolean): Init
78
142
  return { path: existingConfigPath, status: "exists" };
79
143
  }
80
144
  const targetExists = existsSync(targetPath);
81
- // Preserve paths.ignore from whichever supported config exists, not just `.gruff-ts.yaml` -
82
- // otherwise `init --force` against a project with only `.gruff.yaml`/`.yml`/`.json` would
83
- // silently drop user-curated ignore entries when generating the new canonical file.
84
- const preservedIgnoredPaths = existingConfigPath !== undefined ? readExistingIgnoredPaths(projectRoot) : [];
85
- writeFileSync(targetPath, renderDefaultConfig(preservedIgnoredPaths));
145
+ // Preserve paths.ignore + minimumSeverity from whichever supported config exists, not just
146
+ // `.gruff-ts.yaml` - otherwise `init --force` against a project with only
147
+ // `.gruff.yaml`/`.yml`/`.json` would silently drop user-curated exclusions and command-specific
148
+ // gating thresholds when generating the new canonical file.
149
+ const preserved = existingConfigPath !== undefined ? readExistingPreservedConfig(existingConfigPath) : EMPTY_PRESERVED_CONFIG;
150
+ writeFileSync(targetPath, renderDefaultConfig(preserved.ignoredPaths, preserved.minimumSeverity));
86
151
  return { path: targetPath, status: targetExists ? "overwritten" : "written" };
87
152
  }
88
153
 
89
154
  /*
90
- * Recover the existing file's `paths.ignore` block before `init --force` overwrites it. The
91
- * try/catch swallows YAML-parse errors and the fallback returns an empty list so a malformed
92
- * existing config does not block regeneration - the user is opting into clobbering, but the
93
- * documented contract is that curated ignore entries survive when readable.
155
+ * Recover the existing file's `paths.ignore` and `minimumSeverity` blocks before `init --force`
156
+ * overwrites it. Uses the permissive extractor (not the strict validator) so a pre-0.2.0 config
157
+ * without `schemaVersion` still hands its curated entries to the regenerated file - the strict
158
+ * gate would throw on the missing field and silently drop the user's `paths.ignore`. The
159
+ * try/catch swallows IO/parse errors and returns empty values so a malformed existing config
160
+ * does not block regeneration; the user is opting into clobbering, but the documented contract
161
+ * is that curated entries survive when readable.
94
162
  */
95
- function readExistingIgnoredPaths(projectRoot: string): readonly string[] {
163
+ function readExistingPreservedConfig(existingConfigPath: string): PreservedInitConfig {
96
164
  try {
97
- const config = loadConfig(projectRoot, {
98
- paths: [],
99
- shouldSkipConfig: false,
100
- format: "text",
101
- failOn: "none",
102
- shouldIncludeIgnored: false,
103
- shouldSkipBaseline: true,
104
- });
105
- return config.ignoredPaths;
165
+ return extractPreservedConfigFields(existingConfigPath);
106
166
  } catch {
107
- return [];
167
+ return EMPTY_PRESERVED_CONFIG;
108
168
  }
109
169
  }
110
170
 
@@ -146,8 +206,8 @@ function renderAllowlistsSection(): string {
146
206
  " # bannedGenericNames: [process, handle, doit, run, execute, manage]",
147
207
  " # Accepted prefixes for boolean identifiers. Names without one of these",
148
208
  " # prefixes trigger naming.boolean-prefix.",
149
- " # Default: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires]",
150
- " # booleanPrefixes: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires]",
209
+ " # Default: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
210
+ " # booleanPrefixes: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
151
211
  " # Hungarian type-style prefixes flagged by naming.hungarian-notation.",
152
212
  " # Default: [str, obj, arr, bool, int, num]",
153
213
  " # hungarianPrefixes: [str, obj, arr, bool, int, num]",