@blundergoat/gruff-ts 0.2.0 → 0.3.1

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 (48) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +81 -13
  3. package/docs/README.md +2 -0
  4. package/docs/agent-hook.md +80 -0
  5. package/docs/ci-integration.md +16 -0
  6. package/docs/configuration.md +21 -5
  7. package/docs/output-formats.md +10 -0
  8. package/docs/philosophy.md +21 -0
  9. package/docs/releasing.md +5 -5
  10. package/docs/rules.md +26 -18
  11. package/package.json +5 -5
  12. package/scripts/bump-version.sh +1 -1
  13. package/src/analyser.ts +48 -37
  14. package/src/blocks.ts +23 -70
  15. package/src/changed-regions.ts +390 -0
  16. package/src/check-ignore.ts +49 -0
  17. package/src/class-rules.ts +80 -33
  18. package/src/cli-program.ts +106 -12
  19. package/src/comment-rules.ts +5 -1
  20. package/src/config-parse.ts +458 -0
  21. package/src/config-preservation.ts +1 -1
  22. package/src/config.ts +215 -460
  23. package/src/constants.ts +1 -1
  24. package/src/context-doc-rules.ts +2 -4
  25. package/src/dashboard.ts +7 -4
  26. package/src/discovery.ts +88 -32
  27. package/src/findings-helpers.ts +41 -5
  28. package/src/findings.ts +10 -0
  29. package/src/fixture-purpose-rules.ts +7 -9
  30. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  31. package/src/init-config.ts +3 -0
  32. package/src/line-rules.ts +7 -5
  33. package/src/naming-pushers.ts +35 -6
  34. package/src/profiles.ts +231 -0
  35. package/src/project-config-rules.ts +5 -5
  36. package/src/project-rules.ts +6 -117
  37. package/src/report-html.ts +1 -1
  38. package/src/report-renderers.ts +98 -7
  39. package/src/rule-list.ts +23 -2
  40. package/src/rules.ts +11 -12
  41. package/src/safety-rules.ts +16 -6
  42. package/src/scoring.ts +43 -5
  43. package/src/security-flow-rules.ts +533 -0
  44. package/src/sensitive-data-rules.ts +138 -2
  45. package/src/static-analysis-redundant-rules.ts +411 -0
  46. package/src/test-block-rules.ts +115 -53
  47. package/src/test-fixtures.ts +50 -9
  48. package/src/types.ts +79 -2
@@ -0,0 +1,231 @@
1
+ // Built-in gruff profile presets: the named rule selections that `profile:` / `--profile` resolve.
2
+ // Each preset is a compact, fully readable definition - a reviewer scans all three in one pass.
3
+ // Profiles select rules by PILLAR (gruff's taxonomy is pillar-based) and layer explicit per-rule
4
+ // threshold tightenings on top; `src/config.ts`:`resolveProfile` expands these against
5
+ // `RULE_DESCRIPTORS` at config-load time and validates every rule-id reference. This module owns the
6
+ // canonical rule list (via `ruleDescriptors`) so `config.ts` need not import `rules.ts` directly.
7
+ import { ruleDescriptors } from "./rules.ts";
8
+ import type { Pillar, ProfileDefinition, ProfileRuleSetting, Severity } from "./types.ts";
9
+
10
+ // The eleven pillars listed explicitly so `recommended`/`strict` enable the whole catalogue without
11
+ // referencing an implicit "all rules" default - the selection is greppable here, not derived elsewhere.
12
+ const ALL_PILLARS: readonly Pillar[] = [
13
+ "complexity",
14
+ "dead-code",
15
+ "design",
16
+ "documentation",
17
+ "maintainability",
18
+ "modernisation",
19
+ "naming",
20
+ "security",
21
+ "sensitive-data",
22
+ "size",
23
+ "test-quality",
24
+ ] as const;
25
+
26
+ // The name applied when neither the CLI flag nor the config file names a profile, and the implicit
27
+ // base for an inline `profile:` block that omits `extends:`. `recommended` flattens to an empty delta,
28
+ // so "no profile" and "profile: recommended" are behaviourally identical (the parity contract).
29
+ const DEFAULT_PROFILE_NAME = "gruff.recommended";
30
+
31
+ /**
32
+ * A built-in profile preset in its compact, readable source form. `enabledPillars` selects which
33
+ * pillars' rules fire; every rule outside that set is disabled. `thresholds` and `severities` are
34
+ * explicit per-rule tightenings layered on the enabled set. Keeping presets pillar-keyed (plus a
35
+ * short override list) means a reviewer reads the intent in one pass, and the rule-id references in
36
+ * `thresholds`/`severities` are validated against `RULE_DESCRIPTORS` when this module loads.
37
+ */
38
+ export interface BuiltInProfile {
39
+ name: string;
40
+ description: string;
41
+ enabledPillars: readonly Pillar[];
42
+ thresholds: Readonly<Record<string, number>>;
43
+ severities: Readonly<Record<string, Severity>>;
44
+ }
45
+
46
+ // One-line digest of a built-in profile for the `list-profiles` command. Carries the enabled/total
47
+ // rule counts and the pillar selection so operators can compare presets without resolving each one.
48
+ export interface ProfileSummary {
49
+ name: string;
50
+ description: string;
51
+ enabledRuleCount: number;
52
+ totalRuleCount: number;
53
+ enabledPillars: readonly Pillar[];
54
+ tightenedThresholdCount: number;
55
+ }
56
+
57
+ /*
58
+ * The three built-in presets in source form. This array IS the readable preset catalogue the kill
59
+ * criteria require: minimal (sanity/security only), recommended (current default behaviour, a no-op
60
+ * delta), strict (every pillar enabled with tightened size/complexity/secret thresholds). Strict only
61
+ * tightens thresholds - it enables no new rule, because recommended already enables the whole
62
+ * catalogue - so a strict scan reports at least as many findings as recommended, never fewer.
63
+ */
64
+ const BUILT_IN_PROFILE_SPECS: readonly BuiltInProfile[] = [
65
+ {
66
+ name: "gruff.minimal",
67
+ description: "Security and sensitive-data rules only - the smallest sanity gate for adopting gruff incrementally.",
68
+ enabledPillars: ["security", "sensitive-data"],
69
+ thresholds: {},
70
+ severities: {},
71
+ },
72
+ {
73
+ name: "gruff.recommended",
74
+ description: "Every pillar at its default threshold and severity - identical to gruff's zero-config behaviour.",
75
+ enabledPillars: ALL_PILLARS,
76
+ thresholds: {},
77
+ severities: {},
78
+ },
79
+ {
80
+ name: "gruff.strict",
81
+ description: "Every pillar enabled with tightened size, complexity, and secret thresholds for high-bar repositories.",
82
+ enabledPillars: ALL_PILLARS,
83
+ thresholds: {
84
+ "complexity.cognitive": 10,
85
+ "complexity.cyclomatic": 10,
86
+ "design.deep-relative-import": 1,
87
+ "design.large-module-concentration": 40,
88
+ "size.file-length": 400,
89
+ "size.function-length": 60,
90
+ "size.parameter-count": 4,
91
+ "sensitive-data.hardcoded-env-value": 12,
92
+ "sensitive-data.high-entropy-string": 24,
93
+ },
94
+ severities: {},
95
+ },
96
+ ] as const;
97
+
98
+ // Canonical rule catalogue, captured once at module load. Sorted for determinism so flattened
99
+ // profiles and `list-profiles` output never churn between runs.
100
+ const DESCRIPTORS = ruleDescriptors();
101
+
102
+ // Every rule id gruff recognises. Exported so `config.ts` can reject a user profile that references a
103
+ // rule outside the catalogue at load time (a preset typo would otherwise silently no-op at scan time).
104
+ const KNOWN_RULE_IDS: ReadonlySet<string> = new Set(DESCRIPTORS.map((descriptor) => descriptor.ruleId));
105
+
106
+ // Map from rule id to its pillar, used when validating that a preset's threshold/severity override
107
+ // targets a rule inside one of the preset's enabled pillars (a dead override otherwise).
108
+ const RULE_PILLARS: ReadonlyMap<string, Pillar> = new Map(DESCRIPTORS.map((descriptor) => [descriptor.ruleId, descriptor.pillar]));
109
+
110
+ /*
111
+ * Expands one compact preset into a flattened ProfileDefinition: a rule-id keyed delta from the
112
+ * descriptor defaults. Rules outside the enabled pillars get an explicit `{ enabled: false }`; enabled
113
+ * rules with a threshold/severity override get that override; enabled rules at their default are
114
+ * OMITTED so the delta stays minimal and `recommended` flattens to an empty map (the parity contract).
115
+ * Throws if any override key is unknown or targets a disabled pillar - this is the load-time
116
+ * validation the kill criteria require.
117
+ */
118
+ function profileDefinitionFromSpec(spec: BuiltInProfile): ProfileDefinition {
119
+ assertOverrideKeys(spec);
120
+ const enabledPillars = new Set<Pillar>(spec.enabledPillars);
121
+ const rules = new Map<string, ProfileRuleSetting>();
122
+ for (const descriptor of DESCRIPTORS) {
123
+ if (!enabledPillars.has(descriptor.pillar)) {
124
+ rules.set(descriptor.ruleId, { enabled: false });
125
+ continue;
126
+ }
127
+ const setting = enabledRuleSetting(spec, descriptor.ruleId);
128
+ if (setting) {
129
+ rules.set(descriptor.ruleId, setting);
130
+ }
131
+ }
132
+ return { name: spec.name, rules, ignoredPaths: [] };
133
+ }
134
+
135
+ // Builds the override entry for an enabled rule, or undefined when the rule sits at its descriptor
136
+ // default (so the flattened delta omits it). Threshold and severity are independent optional knobs.
137
+ function enabledRuleSetting(spec: BuiltInProfile, ruleId: string): ProfileRuleSetting | undefined {
138
+ const threshold = spec.thresholds[ruleId];
139
+ const severity = spec.severities[ruleId];
140
+ if (threshold === undefined && severity === undefined) {
141
+ return undefined;
142
+ }
143
+ return {
144
+ enabled: true,
145
+ ...(threshold !== undefined ? { threshold } : {}),
146
+ ...(severity !== undefined ? { severity } : {}),
147
+ };
148
+ }
149
+
150
+ /*
151
+ * Validates a preset's override keys at load time. Every key in `thresholds`/`severities` must be a
152
+ * real rule id (caught by `KNOWN_RULE_IDS`) and must live in one of the preset's enabled pillars - a
153
+ * threshold on a disabled rule would never fire and signals a preset authoring mistake. Throws a plain
154
+ * Error (not ConfigLoadError) because this is an internal contract on bundled presets, not user input.
155
+ */
156
+ function assertOverrideKeys(spec: BuiltInProfile): void {
157
+ const enabledPillars = new Set<Pillar>(spec.enabledPillars);
158
+ for (const ruleId of [...Object.keys(spec.thresholds), ...Object.keys(spec.severities)]) {
159
+ const pillar = RULE_PILLARS.get(ruleId);
160
+ if (pillar === undefined) {
161
+ throw new Error(`Built-in profile "${spec.name}" references unknown rule id "${ruleId}". Every override key must be in RULE_DESCRIPTORS.`);
162
+ }
163
+ if (!enabledPillars.has(pillar)) {
164
+ throw new Error(`Built-in profile "${spec.name}" overrides "${ruleId}" but its pillar "${pillar}" is not enabled. The override would never fire.`);
165
+ }
166
+ }
167
+ }
168
+
169
+ /**
170
+ * The bundled profile catalogue, keyed by name. Values are the flattened ProfileDefinitions that
171
+ * `resolveProfile` clones and overlays. Built once at module load, which is where preset rule-id
172
+ * references are validated - so an authoring mistake fails fast on import, never silently at scan time.
173
+ */
174
+ export const BUILT_IN_PROFILES: ReadonlyMap<string, ProfileDefinition> = new Map(
175
+ BUILT_IN_PROFILE_SPECS.map((spec) => [spec.name, profileDefinitionFromSpec(spec)]),
176
+ );
177
+
178
+ /**
179
+ * Reports whether a rule id is part of gruff's catalogue. Used by the profile resolver to reject a
180
+ * user profile that names a rule outside `RULE_DESCRIPTORS` before any scan runs.
181
+ *
182
+ * @param ruleId Candidate rule id from a user profile's `rules:` block.
183
+ * @returns True when the id is a known rule, false otherwise.
184
+ */
185
+ export function isKnownRuleId(ruleId: string): boolean {
186
+ return KNOWN_RULE_IDS.has(ruleId);
187
+ }
188
+
189
+ /**
190
+ * Returns the built-in profile names in catalogue order for error messages and CLI hints.
191
+ *
192
+ * @returns The bundled profile names, e.g. `["gruff.minimal", "gruff.recommended", "gruff.strict"]`.
193
+ */
194
+ export function builtInProfileNames(): string[] {
195
+ return BUILT_IN_PROFILE_SPECS.map((spec) => spec.name);
196
+ }
197
+
198
+ /**
199
+ * Builds the one-line digest of every built-in profile for the `list-profiles` command.
200
+ *
201
+ * @returns Per-profile summaries with enabled/total rule counts, pillar selection, and threshold count.
202
+ */
203
+ export function profileSummaries(): ProfileSummary[] {
204
+ const totalRuleCount = DESCRIPTORS.length;
205
+ return BUILT_IN_PROFILE_SPECS.map((spec) => {
206
+ const definition = BUILT_IN_PROFILES.get(spec.name);
207
+ const disabledCount = definition ? countDisabledRules(definition) : 0;
208
+ return {
209
+ name: spec.name,
210
+ description: spec.description,
211
+ enabledRuleCount: totalRuleCount - disabledCount,
212
+ totalRuleCount,
213
+ enabledPillars: spec.enabledPillars,
214
+ tightenedThresholdCount: Object.keys(spec.thresholds).length,
215
+ };
216
+ });
217
+ }
218
+
219
+ // Counts the rules a flattened profile explicitly disables, so the enabled count is the catalogue
220
+ // size minus the disables (enabled-at-default rules are omitted from the delta and stay enabled).
221
+ function countDisabledRules(definition: ProfileDefinition): number {
222
+ let disabled = 0;
223
+ for (const setting of definition.rules.values()) {
224
+ if (setting.enabled === false) {
225
+ disabled += 1;
226
+ }
227
+ }
228
+ return disabled;
229
+ }
230
+
231
+ export { DEFAULT_PROFILE_NAME };
@@ -2,7 +2,7 @@
2
2
  import { existsSync, statSync } from "node:fs";
3
3
  import { basename, dirname as dirnamePath, isAbsolute, join } from "node:path";
4
4
  import { platform } from "node:process";
5
- import { isString, objectValue } from "./config.ts";
5
+ import { isString, objectValue } from "./config-parse.ts";
6
6
  import { makeFinding } from "./findings.ts";
7
7
  import { firstLine } from "./text-scans.ts";
8
8
  import type { Finding } from "./types.ts";
@@ -166,7 +166,7 @@ function pushUrlDependencyFinding(
166
166
  findings.push(
167
167
  makeFinding({
168
168
  ruleId: "security.url-dependency",
169
- message: `Dependency \`${packageName}\` in \`${section}\` installs from a URL or git spec.`,
169
+ message: `Dependency \`${packageName}\` in \`${section}\` installs from a URL, git, or local file spec.`,
170
170
  filePath: file.displayPath,
171
171
  line: jsonKeyLine(source, packageName),
172
172
  severity: "warning",
@@ -405,10 +405,10 @@ function isLifecycleScript(scriptName: string): boolean {
405
405
  return ["preinstall", "install", "postinstall", "prepare", "prepublish", "prepublishOnly"].includes(scriptName);
406
406
  }
407
407
 
408
- // Recognises non-registry installs: full URLs, git+ssh, and the github:/gitlab:/bitbucket: shortcuts
409
- // npm supports. These specs cannot be reproducibly locked the way registry versions can.
408
+ // Recognises non-registry installs: full URLs, git+ssh, file:, and npm-hosting shortcuts.
409
+ // These specs cannot be reproducibly locked the way registry versions can.
410
410
  function isUrlDependency(versionSpec: string): boolean {
411
- return /^(?:https?:\/\/|git(?:\+https?|\+ssh)?:\/\/|ssh:\/\/|github:|gitlab:|bitbucket:|git@[^:]+:[^/]+\/|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$)/i.test(versionSpec);
411
+ return /^(?:https?:\/\/|git(?:\+https?|\+ssh)?:\/\/|ssh:\/\/|github:|gitlab:|bitbucket:|file:|git@[^:]+:[^/]+\/|[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$)/i.test(versionSpec);
412
412
  }
413
413
 
414
414
  // Catches `*`, `x`, `latest`, unbounded `>=` ranges, and OR-joined ranges. All let dependency
@@ -1,22 +1,14 @@
1
- // Cross-file architecture rules (deep imports, cycles, large-module concentration), test-adequacy
2
- // (missing-nearby-test), and the path-classification helpers (isTestPath, isFixtureLikePath, etc.)
3
- // every rule pass shares. Pulls the project-index types and the rules that consume them out of cli.ts
4
- // so the orchestrator stays lean.
5
- import { basename, dirname as dirnamePath, extname, join } from "node:path";
6
- import { isString, optionNumber, ruleSeverity, threshold } from "./config.ts";
1
+ // Cross-file architecture rules (deep imports, cycles, large-module concentration) and the
2
+ // path-classification helpers (isTestPath, isFixtureLikePath, etc.) every rule pass shares. Pulls the
3
+ // project-index types and the rules that consume them out of cli.ts so the orchestrator stays lean.
4
+ import { dirname as dirnamePath, extname, join } from "node:path";
5
+ import { isString } from "./config-parse.ts";
6
+ import { optionNumber, ruleSeverity, threshold } from "./config.ts";
7
7
  import { type SourceFile } from "./discovery.ts";
8
8
  import { makeFinding } from "./findings.ts";
9
9
  import { fileBaseName } from "./findings-helpers.ts";
10
- import { byteLine } from "./text-scans.ts";
11
10
  import type { Config, Finding, Severity } from "./types.ts";
12
11
 
13
- // First exported callable/value in a production file. Missing-nearby-test only needs this compact
14
- // surface, so the project index does not retain full source bodies after per-file analysis.
15
- export interface ProjectExportedSurface {
16
- symbol: string;
17
- line: number;
18
- }
19
-
20
12
  // Read-once snapshot of a discovered file. Lines are cached because cross-file project rules
21
13
  // scan each source repeatedly - splitting once amortises the cost across rule passes.
22
14
  // `templateMaskedLines` mirrors `lines` but blanks out `` ` `` template-literal body characters
@@ -26,7 +18,6 @@ export interface ProjectSource {
26
18
  file: SourceFile;
27
19
  lines: string[];
28
20
  templateMaskedLines: string[];
29
- exportedSurface?: ProjectExportedSurface;
30
21
  }
31
22
 
32
23
  // Project-wide aggregate built once per scan and reused by every architecture rule (cycle detection,
@@ -106,12 +97,6 @@ export function analyseArchitectureRules(index: ProjectIndex, config: Config, fi
106
97
  analyseLargeModuleConcentration(index, config, findings);
107
98
  }
108
99
 
109
- // Container for test-adequacy rules. Just one rule today; existing as a stable shape so additions
110
- // inherit the same project-index contract without each touching the entry point.
111
- export function analyseTestAdequacyRules(index: ProjectIndex, findings: Finding[]): void {
112
- analyseMissingNearbyTests(index, findings);
113
- }
114
-
115
100
  /*
116
101
  * Reports imports that climb more than `maxParentSegments` `../` hops, anchored at the edge line
117
102
  * in the importing file. The double loop exists intentionally because `..` and `../foo` look
@@ -425,102 +410,6 @@ export function isProductionSourcePath(path: string): boolean {
425
410
  return !isTestPath(path) && !isDeclarationPath(path) && !isFixtureLikePath(path) && !path.split("/").includes("generated");
426
411
  }
427
412
 
428
- /*
429
- * Reports exported callables whose file has no neighbouring `.test.ts` / `.spec.ts`. The stable
430
- * neighbour rules (`hasNearbyTest`) define what counts - false positives are likelier than missed
431
- * cases, so the rule is intentionally conservative.
432
- */
433
- function analyseMissingNearbyTests(index: ProjectIndex, findings: Finding[]): void {
434
- const testSources = index.scriptSources.filter((source) => isTestPath(source.file.displayPath));
435
- const testPaths = new Set(testSources.map((source) => source.file.displayPath));
436
- for (const source of index.scriptSources.filter((candidate) => isProductionSourcePath(candidate.file.displayPath))) {
437
- const exported = source.exportedSurface;
438
- if (!exported || hasNearbyTest(source.file.displayPath, testPaths) || hasCentralTestImport(source.file.displayPath, testSources, index.importsByFile)) {
439
- continue;
440
- }
441
- findings.push(
442
- makeFinding({
443
- ruleId: "test-quality.missing-nearby-test",
444
- message: `Exported source file \`${source.file.displayPath}\` has no nearby test file.`,
445
- filePath: source.file.displayPath,
446
- line: exported.line,
447
- severity: "advisory",
448
- pillar: "test-quality",
449
- confidence: "medium",
450
- symbol: exported.symbol,
451
- remediation: "Add a focused test beside the source file or under a nearby __tests__/tests directory.",
452
- metadata: { expectedTestBase: fileBaseName(source.file.displayPath) },
453
- }),
454
- );
455
- }
456
- }
457
-
458
- // Centralized `test/unit` or `test/integration` suites often import the source directly instead
459
- // of matching filenames. Treat that import edge as nearby enough to avoid layout false positives.
460
- function hasCentralTestImport(sourcePath: string, testSources: ProjectSource[], importsByFile: Map<string, ImportEdge[]>): boolean {
461
- return testSources.some((testSource) => (importsByFile.get(testSource.file.displayPath) ?? []).some((edge) => edge.targetPath === sourcePath));
462
- }
463
-
464
- // Returns the first exported callable/value seen - one finding per file is sufficient because
465
- // the rule's signal is "this file ships an API surface", not "every export is untested".
466
- export function exportedSurface(source: string): ProjectExportedSurface | undefined {
467
- const match = source.match(/\bexport\s+(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|enum|const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/);
468
- if (!match?.[1]) {
469
- return undefined;
470
- }
471
- return { symbol: match[1], line: byteLine(source, match.index ?? 0) };
472
- }
473
-
474
- // True when a same-name test file exists alongside the source, in a sibling `__tests__`/`tests`
475
- // directory, or anywhere under a top-level `test`/`tests` tree. Mirrors common project layouts;
476
- // expanding this list widens what counts as "tested".
477
- function hasNearbyTest(sourcePath: string, testPaths: Set<string>): boolean {
478
- const sourceBase = stripSourceExtension(sourcePath);
479
- const sourceName = basename(sourceBase);
480
- const sourceDir = displayDir(sourcePath);
481
- const nearbyDirs = new Set([sourceDir, joinDisplay(sourceDir, "__tests__"), joinDisplay(sourceDir, "tests"), "test", "tests"]);
482
- for (const testPath of testPaths) {
483
- const testBase = stripTestMarker(stripSourceExtension(testPath));
484
- if (basename(testBase) !== sourceName) {
485
- continue;
486
- }
487
- if (testBase === sourceBase || nearbyDirs.has(displayDir(testPath)) || isTopLevelTestPath(testPath)) {
488
- return true;
489
- }
490
- }
491
- return false;
492
- }
493
-
494
- // Top-level `test/` and `tests/` trees are common central suite layouts. This helper is separate
495
- // from `isTestPath` because nearby-test matching still requires basename agreement.
496
- function isTopLevelTestPath(path: string): boolean {
497
- return path.startsWith("test/") || path.startsWith("tests/");
498
- }
499
-
500
- // Drops the trailing `.ts`/`.tsx`/`.js`/`.jsx`/`.mts`/`.cjs`/`.mjs` extension so source-and-test
501
- // filename comparison is extension-agnostic. Used together with `stripTestMarker`.
502
- function stripSourceExtension(path: string): string {
503
- return path.replace(/\.[cm]?[tj]sx?$/, "");
504
- }
505
-
506
- // Drops the conventional `.test` / `.spec` suffix before comparing a test path to a source path.
507
- function stripTestMarker(path: string): string {
508
- return path.replace(/\.(?:test|spec)$/, "");
509
- }
510
-
511
- // Collapses a path's directory portion to the empty string at the project root so
512
- // `hasNearbyTest`'s nearbyDirs lookup uses one canonical key for root-level files.
513
- function displayDir(path: string): string {
514
- const dir = normalizeDisplayPath(dirnamePath(path));
515
- return dir === "." ? "" : dir;
516
- }
517
-
518
- // POSIX-style join that handles the empty-prefix case so `joinDisplay("", "x")` returns `"x"`,
519
- // not `"/x"` - needed for paths that live directly at the project root.
520
- function joinDisplay(left: string, right: string): string {
521
- return left ? `${left}/${right}` : right;
522
- }
523
-
524
413
  // `__tests__/` and `tests/` directories, plus `.test.ts` / `.spec.ts` filename suffix. The same
525
414
  // patterns drive the production-source filter, so adding a layout here widens every test-aware rule.
526
415
  export function isTestPath(path: string): boolean {
@@ -58,7 +58,7 @@ ${bodySections}
58
58
  // contract surface - operators eyeball it to confirm the report shape they expect.
59
59
  function htmlMasthead(report: AnalysisReport): string {
60
60
  const paths = report.paths.analysedFiles === 0 ? "." : `${report.paths.analysedFiles} analysed ${report.paths.analysedFiles === 1 ? "file" : "files"}`;
61
- return `<header class="masthead"><div class="brand"><div class="wordmark">gruff</div><div class="tagline">ts/js code quality - inspection report</div></div><div class="meta">${htmlMetaRow("paths", paths)}${htmlMetaRow("format", report.run.format)}${htmlMetaRow("fail", report.run.failOn)}${htmlMetaRow("schema", report.schemaVersion)}<div class="inspection-id">gruff-ts ${escapeHtml(report.tool.version)}</div></div></header>`;
61
+ return `<header class="masthead"><div class="brand"><div class="wordmark">gruff</div><div class="tagline">ts/js code - inspected for human sign-off</div></div><div class="meta">${htmlMetaRow("paths", paths)}${htmlMetaRow("format", report.run.format)}${htmlMetaRow("fail", report.run.failOn)}${htmlMetaRow("schema", report.schemaVersion)}<div class="inspection-id">gruff-ts ${escapeHtml(report.tool.version)}</div></div></header>`;
62
62
  }
63
63
 
64
64
  // Single key/value row. Both inputs are escaped - they reach this function as user-influenced
@@ -18,7 +18,7 @@ import { severityGradeBreakdown } from "./scoring.ts";
18
18
  function renderReport(report: AnalysisReport, format: OutputFormat): string {
19
19
  switch (format) {
20
20
  case "json":
21
- return JSON.stringify(report, null, 2);
21
+ return JSON.stringify(toJsonReport(report), null, 2);
22
22
  case "html":
23
23
  return renderHtml(report);
24
24
  case "markdown":
@@ -34,6 +34,38 @@ function renderReport(report: AnalysisReport, format: OutputFormat): string {
34
34
  }
35
35
  }
36
36
 
37
+ type JsonFinding = Finding & { file: string };
38
+ type JsonTopOffender = AnalysisReport["score"]["topOffenders"][number] & { file: string };
39
+ type JsonAnalysisReport = Omit<AnalysisReport, "findings" | "score"> & {
40
+ findings: JsonFinding[];
41
+ score: Omit<AnalysisReport["score"], "topOffenders"> & { topOffenders: JsonTopOffender[] };
42
+ };
43
+
44
+ // JSON boundary adapter: canonical `file` is emitted while legacy `filePath` stays for one release.
45
+ // Stable `gruff.analysis.v2` contract line kept adjacent to the function for the doc-context rule.
46
+ function toJsonReport(report: AnalysisReport): JsonAnalysisReport {
47
+ return {
48
+ ...report,
49
+ findings: report.findings.map(jsonFinding),
50
+ score: {
51
+ ...report.score,
52
+ topOffenders: report.score.topOffenders.map(jsonTopOffender),
53
+ },
54
+ };
55
+ }
56
+
57
+ // Maps one Finding into the JSON contract without mutating the native in-memory finding object.
58
+ function jsonFinding(finding: Finding): JsonFinding {
59
+ const { ruleId, message, filePath, ...rest } = finding;
60
+ return { ruleId, message, file: filePath, filePath, ...rest };
61
+ }
62
+
63
+ // Maps one top offender into the JSON contract while preserving the legacy filePath alias.
64
+ function jsonTopOffender(offender: AnalysisReport["score"]["topOffenders"][number]): JsonTopOffender {
65
+ const { filePath, ...rest } = offender;
66
+ return { file: filePath, filePath, ...rest };
67
+ }
68
+
37
69
  /*
38
70
  * SARIF 2.1.0 output for GitHub code-scanning uploads. Kept as one large object literal because
39
71
  * the SARIF schema demands a specific shape - splitting it up obscures which fields are required.
@@ -187,11 +219,12 @@ function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: s
187
219
  `gruff-ts ${report.tool.version} summary`,
188
220
  `Path: ${pathLabel ?? report.run.projectRoot}`,
189
221
  ...(typeof elapsedMs === "number" ? [`Duration: ${formatSummaryDuration(elapsedMs)}`] : []),
190
- `Composite: ${report.score.grade} (${report.score.composite.toFixed(1)})`,
222
+ `Composite: ${report.score.grade} (${report.score.composite.toFixed(2)} / 100)`,
223
+ `Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
191
224
  ` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
192
225
  ` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
193
226
  ` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
194
- `Findings: ${report.summary.total} total, ${report.summary.error} error, ${report.summary.warning} warning, ${report.summary.advisory} advisory`,
227
+ ...renderComplexityClusterLines(report.findings, top),
195
228
  `Analysed files: ${report.paths.analysedFiles}`,
196
229
  ...(report.baseline ? [summaryBaselineLine(report.baseline)] : []),
197
230
  ];
@@ -381,11 +414,13 @@ function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?:
381
414
  function renderText(report: AnalysisReport): string {
382
415
  const breakdown = severityGradeBreakdown(report.findings);
383
416
  const lines = [
384
- `gruff-ts ${report.tool.version}`,
385
- `Composite: ${report.score.grade} (${report.score.composite.toFixed(1)}) | Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error`,
417
+ `gruff-ts ${report.tool.version} analyse`,
418
+ `Composite: ${report.score.grade} (${report.score.composite.toFixed(2)} / 100)`,
419
+ `Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
386
420
  ` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
387
421
  ` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
388
422
  ` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
423
+ ...renderComplexityClusterLines(report.findings),
389
424
  `Analysed files: ${report.paths.analysedFiles}`,
390
425
  ];
391
426
  if (report.diagnostics.length > 0) {
@@ -413,12 +448,13 @@ function renderMarkdown(report: AnalysisReport): string {
413
448
  return [
414
449
  "# gruff-ts report",
415
450
  "",
416
- `Composite: **${report.score.grade} (${report.score.composite.toFixed(1)})**`,
451
+ `Composite: **${report.score.grade} (${report.score.composite.toFixed(2)} / 100)**`,
417
452
  `- Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
418
453
  `- Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
419
454
  `- Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
455
+ ...renderMarkdownComplexityClusterLines(report.findings),
420
456
  "",
421
- `Findings: ${report.summary.advisory} advisory, ${report.summary.warning} warning, ${report.summary.error} error.`,
457
+ `Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
422
458
  "",
423
459
  ...renderMarkdownPillarsTable(buildPillarRows(report)),
424
460
  "",
@@ -460,6 +496,61 @@ function escapeMarkdownCell(cell: string): string {
460
496
  return cell.replaceAll("|", "\\|");
461
497
  }
462
498
 
499
+ // Render-only summary of overlapping complexity findings for one function symbol.
500
+ interface ComplexityCluster {
501
+ filePath: string;
502
+ symbol: string;
503
+ ruleIds: string[];
504
+ }
505
+
506
+ const CORRELATED_COMPLEXITY_RULE_IDS = new Set(["complexity.cognitive", "complexity.cyclomatic", "size.function-length"]);
507
+
508
+ // Invariant: text output surfaces linked complexity clusters without changing JSON report shape.
509
+ function renderComplexityClusterLines(findings: Finding[], limit = 10): string[] {
510
+ const clusters = complexityClusters(findings).slice(0, limit);
511
+ if (clusters.length === 0) {
512
+ return [];
513
+ }
514
+ return [
515
+ "Correlated complexity clusters:",
516
+ ...clusters.map((cluster) => `- ${cluster.filePath}#${cluster.symbol}: ${cluster.ruleIds.length} linked findings (${cluster.ruleIds.join(", ")})`),
517
+ ];
518
+ }
519
+
520
+ // Invariant: markdown mirrors text complexity clusters without adding JSON fields.
521
+ function renderMarkdownComplexityClusterLines(findings: Finding[]): string[] {
522
+ const clusters = complexityClusters(findings);
523
+ if (clusters.length === 0) {
524
+ return [];
525
+ }
526
+ return [
527
+ "",
528
+ "## Correlated Complexity Clusters",
529
+ "",
530
+ ...clusters.map((cluster) => `- \`${cluster.filePath}#${cluster.symbol}\`: ${cluster.ruleIds.length} linked findings (${cluster.ruleIds.map((ruleId) => `\`${ruleId}\``).join(", ")})`),
531
+ ];
532
+ }
533
+
534
+ // Groups correlated complexity findings by file and symbol so renderers can explain score overlap.
535
+ function complexityClusters(findings: Finding[]): ComplexityCluster[] {
536
+ const bySymbol = new Map<string, ComplexityCluster>();
537
+ for (const finding of findings) {
538
+ if (!finding.symbol || !CORRELATED_COMPLEXITY_RULE_IDS.has(finding.ruleId)) {
539
+ continue;
540
+ }
541
+ const key = `${finding.filePath}\0${finding.symbol}`;
542
+ const cluster = bySymbol.get(key) ?? { filePath: finding.filePath, symbol: finding.symbol, ruleIds: [] };
543
+ if (!cluster.ruleIds.includes(finding.ruleId)) {
544
+ cluster.ruleIds.push(finding.ruleId);
545
+ }
546
+ bySymbol.set(key, cluster);
547
+ }
548
+ return [...bySymbol.values()]
549
+ .filter((cluster) => cluster.ruleIds.length >= 2)
550
+ .map((cluster) => ({ ...cluster, ruleIds: cluster.ruleIds.sort() }))
551
+ .sort((left, right) => right.ruleIds.length - left.ruleIds.length || left.filePath.localeCompare(right.filePath) || left.symbol.localeCompare(right.symbol));
552
+ }
553
+
463
554
  // GitHub Actions `::workflow command` syntax. Public contract invariant: file/title properties
464
555
  // must be normalized and command-escaped before interpolation because commas and colons delimit the property list.
465
556
  function renderGithub(report: AnalysisReport): string {
package/src/rule-list.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // Console command catalogue, shell completion scripts, and rule-list renderers for CLI surfaces.
2
2
  import { VERSION } from "./constants.ts";
3
+ import { profileSummaries, type ProfileSummary } from "./profiles.ts";
3
4
  import { ruleDescriptors } from "./rules.ts";
4
5
  import type { RuleDescriptor } from "./types.ts";
5
6
 
@@ -24,6 +25,7 @@ const CONSOLE_COMMANDS = [
24
25
  { name: "help", description: "Display help for a command" },
25
26
  { name: "init", description: "Write the default .gruff-ts.yaml to the current directory." },
26
27
  { name: "list", description: "List commands" },
28
+ { name: "list-profiles", description: "List the built-in gruff profiles." },
27
29
  { name: "list-rules", description: "List gruff rule metadata." },
28
30
  { name: "report", description: "Render a gruff report to stdout or a file." },
29
31
  {
@@ -49,6 +51,25 @@ function renderRuleList(format: RuleListFormat): string {
49
51
  return `${lines.join("\n")}\n`;
50
52
  }
51
53
 
54
+ // Profile catalogue renderer. Mirrors renderRuleList: JSON is the integration surface for docs and
55
+ // audits, and row formatting lives in profileListRow. The text form is kept deliberately plain
56
+ // because it is only for terminal inspection and should not become a second schema.
57
+ function renderProfileList(format: RuleListFormat): string {
58
+ const summaries = profileSummaries();
59
+ if (format === "json") {
60
+ return `${JSON.stringify({ tool: { name: "gruff-ts", version: VERSION }, profiles: summaries }, null, 2)}\n`;
61
+ }
62
+ const header = ["gruff-ts " + VERSION + ` profiles (${summaries.length})`, ""];
63
+ return `${[...header, ...summaries.map(profileListRow)].join("\n")}\n`;
64
+ }
65
+
66
+ // One text row per profile: name, enabled/total rule count, pillar count, an optional tightened-threshold
67
+ // count, and the description. The tightened-threshold segment only appears for presets that set one.
68
+ function profileListRow(summary: ProfileSummary): string {
69
+ const tightened = summary.tightenedThresholdCount > 0 ? ` | tightened thresholds: ${summary.tightenedThresholdCount}` : "";
70
+ return `${summary.name} | ${summary.enabledRuleCount}/${summary.totalRuleCount} rules | ${summary.enabledPillars.length} pillars${tightened} | ${summary.description}`;
71
+ }
72
+
52
73
  /*
53
74
  * Returns a single rule descriptor by ID, or undefined when the ID is not registered. Surfaced so
54
75
  * the explain-mode renderer can dispatch on "is this a real rule?" without iterating the full
@@ -131,7 +152,7 @@ function renderConsoleList(shouldUseAnsi = false): string {
131
152
  formatConsoleRow("-v|vv|vvv, --verbose", "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug", 22, shouldUseAnsi),
132
153
  "",
133
154
  ansiWrap("Available commands:", ANSI_YELLOW, shouldUseAnsi),
134
- ...CONSOLE_COMMANDS.map((command) => formatConsoleRow(command.name, command.description, 12, shouldUseAnsi)),
155
+ ...CONSOLE_COMMANDS.map((command) => formatConsoleRow(command.name, command.description, 15, shouldUseAnsi)),
135
156
  ].join("\n") + "\n";
136
157
  }
137
158
 
@@ -240,4 +261,4 @@ function completionShell(shellName: unknown): CompletionShell {
240
261
  }
241
262
 
242
263
  export type { RuleListFormat, CompletionShell };
243
- export { renderRuleList, renderRuleDetail, getRuleDescriptor, renderConsoleList, renderCompletionScript, completionShell };
264
+ export { renderRuleList, renderProfileList, renderRuleDetail, getRuleDescriptor, renderConsoleList, renderCompletionScript, completionShell };