@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/rule-list.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Console command catalogue, shell completion scripts, and rule-list renderers for CLI surfaces.
2
2
  import { VERSION } from "./constants.ts";
3
3
  import { ruleDescriptors } from "./rules.ts";
4
+ import type { RuleDescriptor } from "./types.ts";
4
5
 
5
6
  type RuleListFormat = "text" | "json";
6
7
  type CompletionShell = "bash" | "fish" | "zsh";
@@ -48,6 +49,68 @@ function renderRuleList(format: RuleListFormat): string {
48
49
  return `${lines.join("\n")}\n`;
49
50
  }
50
51
 
52
+ /*
53
+ * Returns a single rule descriptor by ID, or undefined when the ID is not registered. Surfaced so
54
+ * the explain-mode renderer can dispatch on "is this a real rule?" without iterating the full
55
+ * catalogue at each render site. Stable contract: lookup keys match the public rule ID strings
56
+ * exactly; partial / case-insensitive matches are intentionally out of scope.
57
+ */
58
+ function getRuleDescriptor(ruleId: string): RuleDescriptor | undefined {
59
+ return ruleDescriptors().find((descriptor) => descriptor.ruleId === ruleId);
60
+ }
61
+
62
+ /*
63
+ * Single-rule detail renderer. Text format prints a labelled section with every populated field;
64
+ * JSON format wraps the descriptor in a tool envelope mirroring the multi-rule shape. Surfaces
65
+ * config keys (`rules.<ruleId>.{enabled,severity,threshold}`) and the option/allowlist hatches
66
+ * because operators looking up one rule shouldn't have to grep `src/config.ts` to find the
67
+ * override knobs they're about to tune.
68
+ */
69
+ function renderRuleDetail(descriptor: RuleDescriptor, format: RuleListFormat): string {
70
+ if (format === "json") {
71
+ return `${JSON.stringify({ tool: { name: "gruff-ts", version: VERSION }, rule: { ...descriptor, configKeys: ruleConfigKeys(descriptor) } }, null, 2)}\n`;
72
+ }
73
+ const lines = [
74
+ `Rule: ${descriptor.ruleId}`,
75
+ `Pillar: ${descriptor.pillar}`,
76
+ `Severity: ${descriptor.severity}`,
77
+ `Confidence: ${descriptor.confidence}`,
78
+ ...(typeof descriptor.threshold === "number" ? [`Threshold: ${descriptor.threshold}`] : []),
79
+ "",
80
+ `Description: ${descriptor.description}`,
81
+ "",
82
+ `Remediation: ${descriptor.remediation}`,
83
+ "",
84
+ ...ruleConfigKeyLines(descriptor),
85
+ ...(descriptor.optionKeys && descriptor.optionKeys.length > 0 ? ["", "Options:", ...descriptor.optionKeys.map((key) => ` rules.${descriptor.ruleId}.options.${key}`)] : []),
86
+ ...(descriptor.allowlistKeys && descriptor.allowlistKeys.length > 0 ? ["", "Allowlists:", ...descriptor.allowlistKeys.map((key) => ` allowlists.${key}`)] : []),
87
+ ];
88
+ return `${lines.join("\n")}\n`;
89
+ }
90
+
91
+ // Three baseline config-key entries shared by every rule: the enable toggle, the severity override,
92
+ // and (when present) the threshold override. Optional knobs (options / allowlists) get their own
93
+ // blocks in `renderRuleDetail` to keep this list focused on the always-applicable keys.
94
+ function ruleConfigKeyLines(descriptor: RuleDescriptor): string[] {
95
+ return [
96
+ "Config keys:",
97
+ ` rules.${descriptor.ruleId}.enabled (bool)`,
98
+ ` rules.${descriptor.ruleId}.severity (advisory|warning|error)`,
99
+ ...(typeof descriptor.threshold === "number" ? [` rules.${descriptor.ruleId}.threshold (int, default: ${descriptor.threshold})`] : []),
100
+ ];
101
+ }
102
+
103
+ // JSON representation of the same config-key list. Returned as a structured array so JSON consumers
104
+ // don't have to re-derive the shape from the text layout. Each entry carries the key path, the
105
+ // value's type vocabulary, and a default when one is known.
106
+ function ruleConfigKeys(descriptor: RuleDescriptor): Array<{ key: string; type: string; values?: readonly string[]; default?: number | boolean | string }> {
107
+ return [
108
+ { key: `rules.${descriptor.ruleId}.enabled`, type: "bool", default: true },
109
+ { key: `rules.${descriptor.ruleId}.severity`, type: "enum", values: ["advisory", "warning", "error"] as const, default: descriptor.severity },
110
+ ...(typeof descriptor.threshold === "number" ? [{ key: `rules.${descriptor.ruleId}.threshold`, type: "int", default: descriptor.threshold }] : []),
111
+ ];
112
+ }
113
+
51
114
  // The Symfony-style command catalogue shown for `gruff-ts`, `gruff-ts list`, and `gruff-ts help`.
52
115
  // `shouldUseAnsi` is autodetected by the caller from TTY and `--ansi` flags, never from this layer.
53
116
  function renderConsoleList(shouldUseAnsi = false): string {
@@ -177,4 +240,4 @@ function completionShell(shellName: unknown): CompletionShell {
177
240
  }
178
241
 
179
242
  export type { RuleListFormat, CompletionShell };
180
- export { renderRuleList, renderConsoleList, renderCompletionScript, completionShell };
243
+ export { renderRuleList, renderRuleDetail, getRuleDescriptor, renderConsoleList, renderCompletionScript, completionShell };
package/src/rules.ts CHANGED
@@ -2,21 +2,22 @@
2
2
  import type { RuleDescriptor } from "./types.ts";
3
3
 
4
4
  const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
5
- { ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with high combined branch and nesting complexity.", remediation: "Split nested decisions into smaller named functions.", threshold: 15 },
6
- { ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with many independent branch paths.", remediation: "Reduce branching or move policy tables out of imperative code.", threshold: 15 },
7
- { ruleId: "complexity.npath", pillar: "complexity", severity: "warning", confidence: "medium", description: "Flags functions with high approximate NPath complexity.", remediation: "Break apart compound branch combinations.", threshold: 200 },
5
+ { ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with high combined branch and nesting complexity.", remediation: "Split nested decisions into smaller named functions. Or raise rules.complexity.cognitive.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 },
6
+ { ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with many independent branch paths.", remediation: "Reduce branching or move policy tables out of imperative code. Or raise rules.complexity.cyclomatic.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 },
7
+ { ruleId: "complexity.npath", pillar: "complexity", severity: "warning", confidence: "medium", description: "Flags functions with high approximate NPath complexity.", remediation: "Break apart compound branch combinations. Or raise rules.complexity.npath.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 200 },
8
8
  { ruleId: "dead-code.unused-private-method", pillar: "dead-code", severity: "advisory", confidence: "low", description: "Flags private methods without an apparent same-file call site.", remediation: "Remove the method or add a direct call site." },
9
9
  { ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags simple relative import cycles inside the discovered source set.", remediation: "Extract the shared contract or invert one dependency." },
10
- { ruleId: "design.deep-relative-import", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags relative imports that climb too many parent directories.", remediation: "Move the shared module closer or add a local boundary.", threshold: 2 },
10
+ { ruleId: "design.deep-relative-import", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags relative imports that climb too many parent directories.", remediation: "Move the shared module closer or add a local boundary. Or raise rules.design.deep-relative-import.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 2 },
11
11
  { ruleId: "design.god-function", pillar: "design", severity: "warning", confidence: "high", description: "Flags functions that are both long and complex.", remediation: "Split responsibilities into smaller functions." },
12
- { ruleId: "design.large-module-concentration", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags a production module that dominates project source lines.", remediation: "Split unrelated responsibilities once stable seams are visible.", threshold: 55, optionKeys: ["minFiles", "minLines"] },
12
+ { ruleId: "design.large-module-concentration", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags a production module that dominates project source lines.", remediation: "Split unrelated responsibilities once stable seams are visible. Or raise rules.design.large-module-concentration.threshold or tune minFiles, minLines under rules.design.large-module-concentration.options.", threshold: 55, optionKeys: ["minFiles", "minLines"] },
13
13
  { ruleId: "design.package-bin-missing", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin entries that point at missing files.", remediation: "Update the bin path or add the executable file." },
14
14
  { ruleId: "design.package-bin-not-executable", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin targets that are not executable.", remediation: "Make the bin target executable and keep its shebang valid." },
15
15
  { ruleId: "docs.fixture-purpose-missing", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags large or scanner-relevant fixtures without a nearby purpose comment.", remediation: "Explain what scanner path, regression, or fixture behavior the source covers." },
16
16
  { ruleId: "docs.magic-threshold-without-rationale", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags threshold-like numeric values without a nearby rationale comment.", remediation: "Explain the threshold, limit, budget, or default near the value." },
17
17
  { ruleId: "docs.missing-error-behavior-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented functions whose error behavior is not described.", remediation: "Document thrown errors, diagnostics, exits, reports, or recovery behavior." },
18
+ { ruleId: "docs.missing-exported-function-doc", pillar: "documentation", severity: "warning", confidence: "medium", description: "Flags exported functions without a leading maintainer comment.", remediation: "Add a JSDoc or line comment explaining the exported API's contract, since public surface has a higher cost of omission." },
18
19
  { ruleId: "docs.missing-file-overview", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags source files without a top-of-file purpose comment.", remediation: "Add a brief file overview before imports or declarations." },
19
- { ruleId: "docs.missing-function-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags functions without a leading maintainer comment.", remediation: "Add a short JSDoc or line comment explaining the function's purpose." },
20
+ { ruleId: "docs.missing-internal-function-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags internal helper functions without a leading maintainer comment.", remediation: "Add a short comment explaining the helper's role; internal helpers are advisory, exported surface fires the warning variant." },
20
21
  { ruleId: "docs.missing-interface-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags interfaces without a leading maintainer comment.", remediation: "Add a short JSDoc or line comment explaining the interface contract." },
21
22
  { ruleId: "docs.missing-invariant-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented declarations that own schema, fingerprint, baseline, or determinism contracts without saying so.", remediation: "Document the invariant, contract, schema, fingerprint, or deterministic behavior." },
22
23
  { ruleId: "docs.missing-param-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags documented exports with parameters missing @param tags.", remediation: "Document every current parameter in the JSDoc." },
@@ -43,16 +44,16 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
43
44
  { ruleId: "modernisation.tsconfig-index-safety-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without noUncheckedIndexedAccess enabled.", remediation: "Enable noUncheckedIndexedAccess unless migration is blocked." },
44
45
  { ruleId: "modernisation.tsconfig-strict-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without strict mode enabled.", remediation: "Enable strict unless migration is blocked." },
45
46
  { ruleId: "modernisation.var-declaration", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags var declarations.", remediation: "Use let or const with the narrowest useful scope." },
46
- { ruleId: "naming.acronym-case", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags mixed casings of a known acronym in one file.", remediation: "Use one casing for each acronym throughout the file." },
47
- { ruleId: "naming.boolean-prefix", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean names without intent-revealing prefixes on declarations, function parameters (typed `: boolean` or with `= true|false` default), and interface/type-literal fields.", remediation: "Use prefixes such as is, has, can, should, or will." },
47
+ { ruleId: "naming.acronym-case", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags mixed casings of a known acronym in one file.", remediation: "Use one casing for each acronym throughout the file. Or extend allowlists.knownAcronyms with project-specific values.", allowlistKeys: ["knownAcronyms"] },
48
+ { ruleId: "naming.boolean-prefix", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean names without intent-revealing prefixes on declarations, function parameters (typed `: boolean` or with `= true|false` default), and interface/type-literal fields.", remediation: "Use prefixes such as is, has, can, should, or will. Or extend allowlists.booleanPrefixes with project-specific values.", allowlistKeys: ["booleanPrefixes"] },
48
49
  { ruleId: "naming.class-file-mismatch", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags exported classes whose name differs from the file name.", remediation: "Rename the class or file so the primary export is easy to locate." },
49
- { ruleId: "naming.generic-function", pillar: "naming", severity: "advisory", confidence: "high", description: "Flags generic function names that hide intent.", remediation: "Name the domain action instead of a generic operation." },
50
- { ruleId: "naming.generic-parameter", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder parameter names in multi-parameter, long, exported, or complex functions.", remediation: "Use a name that describes the parameter's role.", optionKeys: ["minCyclomatic", "minLineCount", "minParameters"] },
51
- { ruleId: "naming.hungarian-notation", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags identifiers named after storage type prefixes.", remediation: "Name the domain concept instead of the storage type." },
52
- { ruleId: "naming.identifier-quality", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder or numbered identifiers on declarations, function parameters, and destructured locals.", remediation: "Use names that explain domain role or intent." },
50
+ { ruleId: "naming.generic-function", pillar: "naming", severity: "advisory", confidence: "high", description: "Flags generic function names that hide intent.", remediation: "Name the domain action instead of a generic operation. Or remove the name from allowlists.bannedGenericNames if your project does not consider it generic.", allowlistKeys: ["bannedGenericNames"] },
51
+ { ruleId: "naming.generic-parameter", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder parameter names in multi-parameter, long, exported, or complex functions.", remediation: "Use a name that describes the parameter's role. Or tune minCyclomatic, minLineCount, minParameters under rules.naming.generic-parameter.options.", optionKeys: ["minCyclomatic", "minLineCount", "minParameters"] },
52
+ { ruleId: "naming.hungarian-notation", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags identifiers named after storage type prefixes.", remediation: "Name the domain concept instead of the storage type. Or remove the prefix from allowlists.hungarianPrefixes if your project does not consider it Hungarian-style.", allowlistKeys: ["hungarianPrefixes"] },
53
+ { ruleId: "naming.identifier-quality", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder or numbered identifiers on declarations, function parameters, and destructured locals.", remediation: "Use names that explain domain role or intent. Or remove the name from allowlists.placeholderNames if your project considers it valid.", allowlistKeys: ["placeholderNames"] },
53
54
  { ruleId: "naming.inconsistent-casing", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags the same canonical identifier appearing in two different surface forms (for example CONSTANT_CASE and camelCase) in one file.", remediation: "Choose one form and use it consistently within the file." },
54
- { ruleId: "naming.negative-boolean", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean identifiers framed as a negation on declarations, parameters, and interface fields.", remediation: "Invert the framing so callers do not read a double negation." },
55
- { ruleId: "naming.short-variable", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags very short variable names outside common loop counters; covers declarations, function parameters, and destructured locals.", remediation: "Use a name that describes the domain role." },
55
+ { ruleId: "naming.negative-boolean", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean identifiers framed as a negation on declarations, parameters, and interface fields.", remediation: "Invert the framing so callers do not read a double negation. Or extend allowlists.negativeBooleanAllowed with project-specific values.", allowlistKeys: ["negativeBooleanAllowed"] },
56
+ { ruleId: "naming.short-variable", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags very short variable names outside common loop counters; covers declarations, function parameters, and destructured locals.", remediation: "Use a name that describes the domain role. Or extend allowlists.acceptedAbbreviations with project-specific values.", allowlistKeys: ["acceptedAbbreviations"] },
56
57
  { ruleId: "security.async-foreach", pillar: "security", severity: "warning", confidence: "medium", description: "Flags async callbacks passed to forEach.", remediation: "Use for...of with await, Promise.all, or an explicit queue." },
57
58
  { ruleId: "security.disabled-tls-verification", pillar: "security", severity: "error", confidence: "high", description: "Flags code that disables TLS certificate verification.", remediation: "Remove the override and fix certificate trust at the source." },
58
59
  { ruleId: "security.document-write", pillar: "security", severity: "warning", confidence: "high", description: "Flags document.write usage.", remediation: "Use safe DOM APIs and encode untrusted content." },
@@ -83,15 +84,15 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
83
84
  { ruleId: "sensitive-data.api-key-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags vendor API key patterns.", remediation: "Remove the secret and load it from a secure runtime source." },
84
85
  { ruleId: "sensitive-data.aws-access-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags AWS access key looking values.", remediation: "Remove the key and rotate it immediately." },
85
86
  { ruleId: "sensitive-data.database-url-password", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags database URLs that include passwords.", remediation: "Move credentials into a secret store or runtime environment." },
86
- { ruleId: "sensitive-data.hardcoded-env-value", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags environment-style secret values committed in text.", remediation: "Load secret-like values from secure runtime configuration.", threshold: 16 },
87
- { ruleId: "sensitive-data.high-entropy-string", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags high-entropy string literals that may be secrets.", remediation: "Remove the value and load it from a secure runtime source.", threshold: 32 },
87
+ { ruleId: "sensitive-data.hardcoded-env-value", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags environment-style secret values committed in text.", remediation: "Load secret-like values from secure runtime configuration. Or raise rules.sensitive-data.hardcoded-env-value.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 16 },
88
+ { ruleId: "sensitive-data.high-entropy-string", pillar: "sensitive-data", severity: "error", confidence: "medium", description: "Flags high-entropy string literals that may be secrets.", remediation: "Remove the value and load it from a secure runtime source. Or raise rules.sensitive-data.high-entropy-string.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 32 },
88
89
  { ruleId: "sensitive-data.jwt-token", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags JWT-looking token literals.", remediation: "Remove the token and rotate the credential if real." },
89
90
  { ruleId: "sensitive-data.pii-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PII-like identifier patterns.", remediation: "Remove personal data from source and fixtures." },
90
91
  { ruleId: "sensitive-data.private-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags private key block markers.", remediation: "Remove the key material and rotate affected credentials." },
91
- { ruleId: "size.file-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags files longer than the configured threshold.", remediation: "Split unrelated responsibilities into smaller files.", threshold: 750 },
92
- { ruleId: "size.function-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions longer than the configured threshold.", remediation: "Extract named helpers or split workflows.", threshold: 200 },
93
- { ruleId: "size.parameter-count", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions with too many parameters.", remediation: "Group related options or reduce the function's responsibility.", threshold: 7 },
94
- { ruleId: "size.stylesheet-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags stylesheets longer than the configured threshold.", remediation: "Split unrelated component styles into smaller files.", threshold: 1500 },
92
+ { ruleId: "size.file-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags files longer than the configured threshold.", remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 750 },
93
+ { ruleId: "size.function-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions longer than the configured threshold.", remediation: "Extract named helpers or split workflows. Or raise rules.size.function-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 200 },
94
+ { ruleId: "size.parameter-count", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions with too many parameters.", remediation: "Group related options or reduce the function's responsibility. Or raise rules.size.parameter-count.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 7 },
95
+ { ruleId: "size.stylesheet-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags stylesheets longer than the configured threshold.", remediation: "Split unrelated component styles into smaller files. Or raise rules.size.stylesheet-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 1500 },
95
96
  { ruleId: "test-quality.conditional-logic", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests with conditional logic.", remediation: "Split branch-specific expectations into separate tests." },
96
97
  { ruleId: "test-quality.exception-type-only", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only assert exception type.", remediation: "Assert message, code, or observable behavior as well." },
97
98
  { ruleId: "test-quality.global-state-mutation", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests mutating process or global runtime state.", remediation: "Isolate state changes and restore them around the test." },
@@ -102,7 +103,7 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
102
103
  { ruleId: "test-quality.no-assertions", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests without apparent assertions.", remediation: "Add assertions for observable behavior." },
103
104
  { ruleId: "test-quality.no-throw-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only assert code does not throw.", remediation: "Assert the observable result or state change." },
104
105
  { ruleId: "test-quality.only-skip", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags focused or skipped test markers.", remediation: "Remove .only and either enable or delete skipped tests." },
105
- { ruleId: "test-quality.setup-bloat", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags tests with too much setup before the first assertion.", remediation: "Extract builders or reduce fixture setup.", threshold: 12 },
106
+ { ruleId: "test-quality.setup-bloat", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags tests with too much setup before the first assertion.", remediation: "Extract builders or reduce fixture setup. Or raise rules.test-quality.setup-bloat.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 12 },
106
107
  { ruleId: "test-quality.sleep-in-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags sleeps in tests.", remediation: "Synchronize on behavior instead of wall-clock time." },
107
108
  { ruleId: "test-quality.snapshot-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that rely only on snapshots.", remediation: "Add targeted assertions for important behavior." },
108
109
  { ruleId: "test-quality.trivial-assertion", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tautological assertions.", remediation: "Assert a real result from the system under test." },
@@ -86,11 +86,16 @@ function rawCatchBody(rawSource: string, codeSource: string, match: RegExpMatchA
86
86
 
87
87
  // Comment-only catches are acceptable when the comment gives a rationale such as "already closed",
88
88
  // "cache write failure is non-fatal", or "composition continues"; placeholders still surface.
89
+ // The bare-token alternatives (`ignore`, `ignored`, `cleanup`, `teardown`, `noop`, `no-op`) match
90
+ // the most common idioms for documented teardown swallows. `silent` is deliberately NOT included -
91
+ // real swallowed-error defects in goat-flow's dashboard-projects.ts use `/* silent */` and must
92
+ // continue to fire. Deferred-work markers are also excluded - that flavour of placeholder is not
93
+ // "intentional swallow."
89
94
  function hasIntentionalCatchRationale(body: string): boolean {
90
95
  return (
91
96
  /(?:\/\/|\/\*)/.test(body) &&
92
97
  (hasSuppressionRationale(body) ||
93
- /\b(?:already (?:closed|dead|gone)|optional|best effort|missing|unreadable|not a directory|doesn't exist|not available|non-fatal|cache write failure|composition continues|try next location|server unavailable|must not affect|explicit launch|malformed messages|template missing|sets [A-Za-z_$][A-Za-z0-9_$]* = false|skip agents? that fail)\b/i.test(body))
98
+ /\b(?:already (?:closed|dead|gone)|optional|best effort|missing|unreadable|not a directory|doesn't exist|not available|non-fatal|cache write failure|composition continues|try next location|server unavailable|must not affect|explicit launch|malformed messages|template missing|sets [A-Za-z_$][A-Za-z0-9_$]* = false|skip agents? that fail|ignored?|cleanup|teardown|noop|no-op)\b/i.test(body))
94
99
  );
95
100
  }
96
101
 
package/src/scoring.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  // Score, grade, and fail-on helpers derived from finding severities for reports and CLI exits.
2
- import { grade } from "./report-renderers.ts";
2
+ import { grade } from "./pillar-summary.ts";
3
3
  import type { AnalysisReport, FailThreshold, Finding, Pillar, Severity } from "./types.ts";
4
4
 
5
- // Builds the per-pillar and per-file score breakdown that ships in `gruff.analysis.v1`. The composite
5
+ // Builds the per-pillar and per-file score breakdown that ships in `gruff.analysis.v2`. The composite
6
6
  // score is the mean of pillar scores so adding a pillar shifts the headline number. `topOffenders` is
7
7
  // the full file list sorted worst-first; renderers cap it themselves (HTML/hotspot keep their 10-row
8
- // UX, summary honours `--top`). The field shape is part of the `gruff.analysis.v1` schema contract.
8
+ // UX, summary honours `--top`). The field shape is part of the `gruff.analysis.v2` schema contract.
9
9
  function scoreReport(findings: Finding[]): AnalysisReport["score"] {
10
10
  const byPillar = new Map<Pillar, Finding[]>();
11
11
  const byFile = new Map<string, Finding[]>();
@@ -15,7 +15,7 @@ function scoreReport(findings: Finding[]): AnalysisReport["score"] {
15
15
  }
16
16
  const pillars = [...byPillar.entries()].map(([pillar, pillarFindings]) => {
17
17
  const penalty = pillarFindings.reduce((sum, finding) => sum + severityPenalty(finding.severity), 0);
18
- return { pillar, score: Math.max(0, 100 - penalty), findings: pillarFindings.length };
18
+ return { pillar, score: Math.max(0, 100 - penalty), penalty, findings: pillarFindings.length };
19
19
  });
20
20
  const composite = pillars.length === 0 ? 100 : pillars.reduce((sum, pillar) => sum + pillar.score, 0) / pillars.length;
21
21
  const topOffenders = [...byFile.entries()]
@@ -29,7 +29,7 @@ function scoreReport(findings: Finding[]): AnalysisReport["score"] {
29
29
  }
30
30
 
31
31
  // Severity tallies emitted in the report summary. The four-key shape (advisory/warning/error/total)
32
- // is part of the `gruff.analysis.v1` schema and consumers rely on `total` matching the array length.
32
+ // is part of the `gruff.analysis.v2` schema and consumers rely on `total` matching the array length.
33
33
  function summarize(findings: Finding[]) {
34
34
  return {
35
35
  advisory: findings.filter((finding) => finding.severity === "advisory").length,
@@ -71,4 +71,36 @@ function severityPenalty(severity: Severity): number {
71
71
  return severity === "error" ? 8 : severity === "warning" ? 4 : 1.5;
72
72
  }
73
73
 
74
- export { scoreReport, summarize, exitFor };
74
+ /*
75
+ * Per-severity grade breakdown for the human summary block. The composite headline alone hides the
76
+ * fact that an F can be driven entirely by advisories (goat-flow scan: F at 12.9 with 0 errors / 276
77
+ * warnings / 1367 advisories). Mirrors the existing pillar formula `100 - count * severityPenalty`
78
+ * so the math stays consistent with how a single-rule pillar would score. The schema invariant
79
+ * matters: the composite score and `gruff.analysis.v2` JSON shape stay byte-stable - only the
80
+ * human renderers surface this breakdown.
81
+ */
82
+ function severityGradeBreakdown(findings: Finding[]): {
83
+ error: { grade: string; score: number; count: number };
84
+ warning: { grade: string; score: number; count: number };
85
+ advisory: { grade: string; score: number; count: number };
86
+ } {
87
+ const counts = { error: 0, warning: 0, advisory: 0 };
88
+ for (const finding of findings) {
89
+ counts[finding.severity] += 1;
90
+ }
91
+ return {
92
+ error: severityBucket("error", counts.error),
93
+ warning: severityBucket("warning", counts.warning),
94
+ advisory: severityBucket("advisory", counts.advisory),
95
+ };
96
+ }
97
+
98
+ // Single severity bucket using the same `score = max(0, 100 - count * penalty)` formula as the
99
+ // pillar reduce in `scoreReport`. Returns the bucket plus its grade letter so renderers don't have
100
+ // to import `grade` separately.
101
+ function severityBucket(severity: Severity, count: number): { grade: string; score: number; count: number } {
102
+ const score = Math.max(0, 100 - count * severityPenalty(severity));
103
+ return { grade: grade(score), score, count };
104
+ }
105
+
106
+ export { scoreReport, summarize, exitFor, severityGradeBreakdown };
@@ -132,7 +132,7 @@ function analyseSetupBloat(file: SourceFile, block: FunctionBlock, body: string,
132
132
  function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
133
133
  const checks: Array<[string, boolean, string]> = [
134
134
  ["test-quality.sleep-in-test", /\b(setTimeout|sleep|waitForTimeout)\s*\(/.test(body), "Test sleeps instead of synchronising on behaviour."],
135
- ["test-quality.loop-in-test", controlFlowContainsAssertion(body, /\b(?:for|while)\b/g), "Test contains loop logic around assertions."],
135
+ ["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic around assertions."],
136
136
  ["test-quality.conditional-logic", controlFlowContainsAssertion(body, /\b(?:if|switch)\b/g), "Test contains conditional logic around assertions."],
137
137
  ["test-quality.only-skip", /\.(only|skip)\s*\(/.test(body), "Focused or skipped test is committed."],
138
138
  ];
@@ -143,6 +143,48 @@ function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body
143
143
  }
144
144
  }
145
145
 
146
+ // Loop variant of `controlFlowContainsAssertion` that suppresses fixture loops (table-test pattern):
147
+ // loops over a literal array or `Object.entries|keys|values` of a literal where every code path
148
+ // inside the body reaches an assertion. The existing rule fires on ANY loop wrapping an assertion;
149
+ // this widens the precision so parametric coverage doesn't read as control-flow noise.
150
+ function controlFlowContainsNonFixtureLoop(source: string): boolean {
151
+ for (const match of source.matchAll(/\b(?:for|while)\b/g)) {
152
+ const start = match.index ?? 0;
153
+ const segment = controlFlowSegment(source, start);
154
+ if (!hasAssertion(segment)) {
155
+ continue;
156
+ }
157
+ if (isFixtureLoop(segment)) {
158
+ continue;
159
+ }
160
+ return true;
161
+ }
162
+ return false;
163
+ }
164
+
165
+ // A "fixture loop" is the table-test pattern: iterable is a literal array OR Object.entries/keys/
166
+ // values of a literal, AND every path through the body terminates in an assertion call. Neither
167
+ // applies to `while` loops or C-style `for (;;)`. Conservative on conditional bodies - the presence
168
+ // of any `if`/`switch`/`case`/`default` inside the body opts out so a branch that doesn't assert
169
+ // is not silently classified as a fixture loop.
170
+ function isFixtureLoop(segment: string): boolean {
171
+ const braceIndex = segment.indexOf("{");
172
+ const header = braceIndex === -1 ? segment : segment.slice(0, braceIndex);
173
+ if (!/\bof\s*\[/.test(header) && !/\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
174
+ return false;
175
+ }
176
+ if (braceIndex === -1) {
177
+ return false;
178
+ }
179
+ const body = segment.slice(braceIndex + 1, segment.length - 1);
180
+ if (/\b(?:if|switch)\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
181
+ return false;
182
+ }
183
+ const statements = body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement));
184
+ const lastStatement = statements[statements.length - 1] ?? "";
185
+ return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
186
+ }
187
+
146
188
  // Integration, contract, smoke, and performance tests naturally need more environment setup than
147
189
  // focused unit tests; keep the default strict for unit tests and double it for broad-flow suites.
148
190
  function setupBloatThreshold(file: SourceFile, config: Config): number {
@@ -105,9 +105,15 @@ export function analyseProjectInCurrentDirectory(options: AnalyseProjectOptions)
105
105
  });
106
106
  }
107
107
 
108
- // Serializes a test YAML config object from the root indentation level.
108
+ /*
109
+ * Serializes a test YAML config object from the root indentation level. Every fixture YAML is
110
+ * stamped with the required `schemaVersion: gruff-ts.config.v0.1` field at the top (per ADR-004)
111
+ * because the config loader throws when it's missing. The schema invariant is preserved by
112
+ * spreading the input object AFTER schemaVersion so callers can't accidentally override it; tests
113
+ * that need to assert against a missing schemaVersion must write the YAML by hand instead.
114
+ */
109
115
  export function yamlConfigFixture(configObject: Record<string, unknown>): string {
110
- return yamlConfigObject(configObject, 0);
116
+ return yamlConfigObject({ schemaVersion: "gruff-ts.config.v0.1", ...configObject }, 0);
111
117
  }
112
118
 
113
119
  // Serializes nested config objects using the fixture YAML subset.
@@ -458,7 +464,7 @@ export function process(flag: boolean, userInput: string, userId: string, userId
458
464
  try {
459
465
  riskyWork();
460
466
  } catch (error) {
461
- // ignored
467
+ // FIXME
462
468
  }
463
469
  if (flag) {
464
470
  if (userId) {
@@ -588,8 +594,10 @@ ${"test"}("setup bloat and control flow", () => {
588
594
  const three = buildThree();
589
595
  if (one) {
590
596
  for (const setupEntry of [one, two, three]) {
591
- sleep(setupEntry);
592
- assert.ok(setupEntry);
597
+ if (setupEntry) {
598
+ sleep(setupEntry);
599
+ assert.ok(setupEntry);
600
+ }
593
601
  }
594
602
  }
595
603
  setTimeout(() => undefined, 1);
package/src/types.ts CHANGED
@@ -39,8 +39,21 @@ export interface AnalysisOptions {
39
39
  shouldSkipBaseline: boolean;
40
40
  }
41
41
 
42
- /** Loaded analyzer configuration derived from optional gruff config files. */
42
+ /** Command keys that participate in the `minimumSeverity:` config block. `dashboard` is omitted on purpose - it has no `--fail-on` flag and accepting it as a key would silently no-op. See ADR-004. */
43
+ export type MinimumSeverityCommand = "analyse" | "summary" | "report";
44
+
45
+ /**
46
+ * Loaded analyzer configuration derived from optional gruff config files. The schema invariant is
47
+ * that `schemaVersion` is fixed at the supported version and every field has a defined default in
48
+ * `defaultConfig()` so consumers can rely on the shape without per-field guards.
49
+ */
43
50
  export interface Config {
51
+ /**
52
+ * Required top-level config-schema version. Pre-1.0 break: every `.gruff-ts.yaml` must declare
53
+ * `schemaVersion: gruff-ts.config.v0.1` or loading throws. Lives in the `gruff-ts.config.*`
54
+ * namespace, distinct from the output schemas (`gruff.analysis.v2`, etc.). See ADR-004.
55
+ */
56
+ schemaVersion: "gruff-ts.config.v0.1";
44
57
  ignoredPaths: string[];
45
58
  acceptedAbbreviations: Set<string>;
46
59
  secretPreviews: Set<string>;
@@ -50,6 +63,12 @@ export interface Config {
50
63
  placeholderNames: Set<string>;
51
64
  negativeBooleanAllowed: Set<string>;
52
65
  knownAcronyms: Set<string>;
66
+ /**
67
+ * Per-command default for `--fail-on`. Precedence: CLI flag > this map > binary default.
68
+ * `dashboard` is intentionally not a valid key (no `--fail-on` flag exists for it); the parser
69
+ * rejects `dashboard` with a documented error. See ADR-004.
70
+ */
71
+ minimumSeverity: Map<MinimumSeverityCommand, FailThreshold>;
53
72
  rules: Map<string, { enabled?: boolean; threshold?: number; severity?: Severity; options: Map<string, number> }>;
54
73
  }
55
74
 
@@ -80,9 +99,9 @@ export interface RunDiagnostic {
80
99
  line?: number;
81
100
  }
82
101
 
83
- /** Stable gruff.analysis.v1 report schema returned by analyse and JSON report commands. */
102
+ /** Stable gruff.analysis.v2 report schema returned by analyse and JSON report commands. */
84
103
  export interface AnalysisReport {
85
- schemaVersion: "gruff.analysis.v1";
104
+ schemaVersion: "gruff.analysis.v2";
86
105
  tool: { name: "gruff-ts"; version: string };
87
106
  run: { projectRoot: string; format: OutputFormat; failOn: FailThreshold; generatedAt: string };
88
107
  summary: { advisory: number; warning: number; error: number; total: number };
@@ -92,7 +111,7 @@ export interface AnalysisReport {
92
111
  score: {
93
112
  composite: number;
94
113
  grade: string;
95
- pillars: Array<{ pillar: Pillar; score: number; findings: number }>;
114
+ pillars: Array<{ pillar: Pillar; score: number; penalty: number; findings: number }>;
96
115
  topOffenders: Array<{ filePath: string; score: number; findings: number }>;
97
116
  };
98
117
  baseline?: { path: string; source: string; suppressed: number; generated: boolean };
@@ -108,5 +127,13 @@ export interface RuleDescriptor {
108
127
  remediation: string;
109
128
  threshold?: number;
110
129
  optionKeys?: readonly string[];
130
+ /**
131
+ * Names of `allowlists.*` keys in `.gruff-ts.yaml` that override or extend the rule's
132
+ * behaviour. Mirrors the `optionKeys` shape but targets the cross-pillar allowlist surface
133
+ * (e.g. `naming.boolean-prefix` consults `allowlists.booleanPrefixes`). Surfaced in the
134
+ * `list-rules --format=json` payload and the per-rule remediation text so operators don't
135
+ * have to grep `.gruff-ts.yaml` and `src/config.ts` to find the override knob.
136
+ */
137
+ allowlistKeys?: readonly string[];
111
138
  fixtureExemption?: string;
112
139
  }