@blundergoat/gruff-ts 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +55 -19
  2. package/README.md +103 -35
  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 +60 -3
  7. package/docs/dashboard.md +7 -0
  8. package/docs/output-formats.md +11 -1
  9. package/docs/philosophy.md +21 -0
  10. package/docs/releasing.md +12 -11
  11. package/docs/reports-and-ci.md +5 -2
  12. package/docs/rules.md +24 -15
  13. package/package.json +5 -5
  14. package/scripts/bump-version.sh +20 -4
  15. package/scripts/preflight-checks.sh +4 -41
  16. package/src/analyser.ts +47 -34
  17. package/src/blocks.ts +82 -75
  18. package/src/changed-regions.ts +390 -0
  19. package/src/check-ignore.ts +49 -0
  20. package/src/class-rules.ts +80 -33
  21. package/src/cli-program.ts +209 -51
  22. package/src/comment-rules.ts +4 -0
  23. package/src/config-load-error.ts +18 -0
  24. package/src/config-parse.ts +458 -0
  25. package/src/config-preservation.ts +64 -0
  26. package/src/config.ts +311 -428
  27. package/src/constants.ts +10 -2
  28. package/src/context-doc-rules.ts +2 -4
  29. package/src/dashboard.ts +8 -5
  30. package/src/dead-code-rules.ts +60 -14
  31. package/src/discovery.ts +88 -32
  32. package/src/doc-rules.ts +3 -3
  33. package/src/findings-helpers.ts +58 -5
  34. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  35. package/src/init-config.ts +94 -31
  36. package/src/line-rules.ts +58 -4
  37. package/src/naming-pushers.ts +42 -7
  38. package/src/pillar-summary.ts +129 -0
  39. package/src/profiles.ts +232 -0
  40. package/src/project-config-rules.ts +5 -5
  41. package/src/project-rules.ts +2 -1
  42. package/src/report-html.ts +404 -0
  43. package/src/report-renderers.ts +210 -397
  44. package/src/rule-list.ts +85 -1
  45. package/src/rules.ts +28 -27
  46. package/src/safety-rules.ts +22 -7
  47. package/src/scoring.ts +78 -8
  48. package/src/security-flow-rules.ts +533 -0
  49. package/src/sensitive-data-rules.ts +138 -2
  50. package/src/test-block-rules.ts +140 -7
  51. package/src/test-fixtures.ts +59 -13
  52. package/src/types.ts +108 -5
@@ -0,0 +1,232 @@
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
+ "test-quality.setup-bloat": 8,
94
+ },
95
+ severities: {},
96
+ },
97
+ ] as const;
98
+
99
+ // Canonical rule catalogue, captured once at module load. Sorted for determinism so flattened
100
+ // profiles and `list-profiles` output never churn between runs.
101
+ const DESCRIPTORS = ruleDescriptors();
102
+
103
+ // Every rule id gruff recognises. Exported so `config.ts` can reject a user profile that references a
104
+ // rule outside the catalogue at load time (a preset typo would otherwise silently no-op at scan time).
105
+ const KNOWN_RULE_IDS: ReadonlySet<string> = new Set(DESCRIPTORS.map((descriptor) => descriptor.ruleId));
106
+
107
+ // Map from rule id to its pillar, used when validating that a preset's threshold/severity override
108
+ // targets a rule inside one of the preset's enabled pillars (a dead override otherwise).
109
+ const RULE_PILLARS: ReadonlyMap<string, Pillar> = new Map(DESCRIPTORS.map((descriptor) => [descriptor.ruleId, descriptor.pillar]));
110
+
111
+ /*
112
+ * Expands one compact preset into a flattened ProfileDefinition: a rule-id keyed delta from the
113
+ * descriptor defaults. Rules outside the enabled pillars get an explicit `{ enabled: false }`; enabled
114
+ * rules with a threshold/severity override get that override; enabled rules at their default are
115
+ * OMITTED so the delta stays minimal and `recommended` flattens to an empty map (the parity contract).
116
+ * Throws if any override key is unknown or targets a disabled pillar - this is the load-time
117
+ * validation the kill criteria require.
118
+ */
119
+ function profileDefinitionFromSpec(spec: BuiltInProfile): ProfileDefinition {
120
+ assertOverrideKeys(spec);
121
+ const enabledPillars = new Set<Pillar>(spec.enabledPillars);
122
+ const rules = new Map<string, ProfileRuleSetting>();
123
+ for (const descriptor of DESCRIPTORS) {
124
+ if (!enabledPillars.has(descriptor.pillar)) {
125
+ rules.set(descriptor.ruleId, { enabled: false });
126
+ continue;
127
+ }
128
+ const setting = enabledRuleSetting(spec, descriptor.ruleId);
129
+ if (setting) {
130
+ rules.set(descriptor.ruleId, setting);
131
+ }
132
+ }
133
+ return { name: spec.name, rules, ignoredPaths: [] };
134
+ }
135
+
136
+ // Builds the override entry for an enabled rule, or undefined when the rule sits at its descriptor
137
+ // default (so the flattened delta omits it). Threshold and severity are independent optional knobs.
138
+ function enabledRuleSetting(spec: BuiltInProfile, ruleId: string): ProfileRuleSetting | undefined {
139
+ const threshold = spec.thresholds[ruleId];
140
+ const severity = spec.severities[ruleId];
141
+ if (threshold === undefined && severity === undefined) {
142
+ return undefined;
143
+ }
144
+ return {
145
+ enabled: true,
146
+ ...(threshold !== undefined ? { threshold } : {}),
147
+ ...(severity !== undefined ? { severity } : {}),
148
+ };
149
+ }
150
+
151
+ /*
152
+ * Validates a preset's override keys at load time. Every key in `thresholds`/`severities` must be a
153
+ * real rule id (caught by `KNOWN_RULE_IDS`) and must live in one of the preset's enabled pillars - a
154
+ * threshold on a disabled rule would never fire and signals a preset authoring mistake. Throws a plain
155
+ * Error (not ConfigLoadError) because this is an internal contract on bundled presets, not user input.
156
+ */
157
+ function assertOverrideKeys(spec: BuiltInProfile): void {
158
+ const enabledPillars = new Set<Pillar>(spec.enabledPillars);
159
+ for (const ruleId of [...Object.keys(spec.thresholds), ...Object.keys(spec.severities)]) {
160
+ const pillar = RULE_PILLARS.get(ruleId);
161
+ if (pillar === undefined) {
162
+ throw new Error(`Built-in profile "${spec.name}" references unknown rule id "${ruleId}". Every override key must be in RULE_DESCRIPTORS.`);
163
+ }
164
+ if (!enabledPillars.has(pillar)) {
165
+ throw new Error(`Built-in profile "${spec.name}" overrides "${ruleId}" but its pillar "${pillar}" is not enabled. The override would never fire.`);
166
+ }
167
+ }
168
+ }
169
+
170
+ /**
171
+ * The bundled profile catalogue, keyed by name. Values are the flattened ProfileDefinitions that
172
+ * `resolveProfile` clones and overlays. Built once at module load, which is where preset rule-id
173
+ * references are validated - so an authoring mistake fails fast on import, never silently at scan time.
174
+ */
175
+ export const BUILT_IN_PROFILES: ReadonlyMap<string, ProfileDefinition> = new Map(
176
+ BUILT_IN_PROFILE_SPECS.map((spec) => [spec.name, profileDefinitionFromSpec(spec)]),
177
+ );
178
+
179
+ /**
180
+ * Reports whether a rule id is part of gruff's catalogue. Used by the profile resolver to reject a
181
+ * user profile that names a rule outside `RULE_DESCRIPTORS` before any scan runs.
182
+ *
183
+ * @param ruleId Candidate rule id from a user profile's `rules:` block.
184
+ * @returns True when the id is a known rule, false otherwise.
185
+ */
186
+ export function isKnownRuleId(ruleId: string): boolean {
187
+ return KNOWN_RULE_IDS.has(ruleId);
188
+ }
189
+
190
+ /**
191
+ * Returns the built-in profile names in catalogue order for error messages and CLI hints.
192
+ *
193
+ * @returns The bundled profile names, e.g. `["gruff.minimal", "gruff.recommended", "gruff.strict"]`.
194
+ */
195
+ export function builtInProfileNames(): string[] {
196
+ return BUILT_IN_PROFILE_SPECS.map((spec) => spec.name);
197
+ }
198
+
199
+ /**
200
+ * Builds the one-line digest of every built-in profile for the `list-profiles` command.
201
+ *
202
+ * @returns Per-profile summaries with enabled/total rule counts, pillar selection, and threshold count.
203
+ */
204
+ export function profileSummaries(): ProfileSummary[] {
205
+ const totalRuleCount = DESCRIPTORS.length;
206
+ return BUILT_IN_PROFILE_SPECS.map((spec) => {
207
+ const definition = BUILT_IN_PROFILES.get(spec.name);
208
+ const disabledCount = definition ? countDisabledRules(definition) : 0;
209
+ return {
210
+ name: spec.name,
211
+ description: spec.description,
212
+ enabledRuleCount: totalRuleCount - disabledCount,
213
+ totalRuleCount,
214
+ enabledPillars: spec.enabledPillars,
215
+ tightenedThresholdCount: Object.keys(spec.thresholds).length,
216
+ };
217
+ });
218
+ }
219
+
220
+ // Counts the rules a flattened profile explicitly disables, so the enabled count is the catalogue
221
+ // size minus the disables (enabled-at-default rules are omitted from the delta and stay enabled).
222
+ function countDisabledRules(definition: ProfileDefinition): number {
223
+ let disabled = 0;
224
+ for (const setting of definition.rules.values()) {
225
+ if (setting.enabled === false) {
226
+ disabled += 1;
227
+ }
228
+ }
229
+ return disabled;
230
+ }
231
+
232
+ 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
@@ -3,7 +3,8 @@
3
3
  // every rule pass shares. Pulls the project-index types and the rules that consume them out of cli.ts
4
4
  // so the orchestrator stays lean.
5
5
  import { basename, dirname as dirnamePath, extname, join } from "node:path";
6
- import { isString, optionNumber, ruleSeverity, threshold } from "./config.ts";
6
+ import { isString } from "./config-parse.ts";
7
+ import { optionNumber, ruleSeverity, threshold } from "./config.ts";
7
8
  import { type SourceFile } from "./discovery.ts";
8
9
  import { makeFinding } from "./findings.ts";
9
10
  import { fileBaseName } from "./findings-helpers.ts";