@blundergoat/gruff-ts 0.3.2 → 0.5.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 +54 -1
  2. package/README.md +16 -6
  3. package/SECURITY.md +2 -1
  4. package/docs/README.md +1 -4
  5. package/docs/agent-hook.md +15 -3
  6. package/docs/configuration.md +47 -1
  7. package/docs/dashboard.md +3 -3
  8. package/docs/reports-and-ci.md +36 -0
  9. package/docs/rules.md +52 -37
  10. package/package.json +1 -1
  11. package/src/analyser.ts +540 -154
  12. package/src/baseline-options.ts +90 -0
  13. package/src/baseline.ts +39 -3
  14. package/src/blocks.ts +116 -77
  15. package/src/changed-regions.ts +80 -11
  16. package/src/class-rules.ts +226 -76
  17. package/src/cli-program.ts +65 -15
  18. package/src/cli.ts +4 -2
  19. package/src/comment-rules.ts +58 -13
  20. package/src/comment-scanner.ts +27 -0
  21. package/src/complexity-metrics.ts +244 -0
  22. package/src/config.ts +56 -16
  23. package/src/constants.ts +1 -1
  24. package/src/context-doc-rules.ts +9 -10
  25. package/src/dead-code-rules.ts +10 -3
  26. package/src/discovery.ts +66 -22
  27. package/src/doc-rules.ts +22 -53
  28. package/src/findings-helpers.ts +127 -1
  29. package/src/findings.ts +4 -0
  30. package/src/fixture-purpose-rules.ts +39 -5
  31. package/src/github-actions-rules.ts +24 -1
  32. package/src/hook-contract.ts +120 -27
  33. package/src/init-config.ts +15 -5
  34. package/src/line-rules.ts +175 -19
  35. package/src/naming-pushers.ts +26 -5
  36. package/src/parsed-script.ts +652 -0
  37. package/src/process-exec-metadata.ts +163 -0
  38. package/src/profiles.ts +14 -0
  39. package/src/project-config-rules.ts +36 -18
  40. package/src/project-rules.ts +159 -42
  41. package/src/public-exports.ts +220 -0
  42. package/src/report-renderers.ts +58 -4
  43. package/src/rules.ts +15 -15
  44. package/src/scoring.ts +13 -4
  45. package/src/security-flow-rules.ts +169 -24
  46. package/src/sensitive-data-rules.ts +256 -80
  47. package/src/source-text.ts +9 -26
  48. package/src/static-analysis-redundant-rules.ts +46 -2
  49. package/src/test-block-rules.ts +118 -14
  50. package/src/test-fixtures.ts +4 -1
  51. package/src/text-scans.ts +8 -1
  52. package/src/types.ts +17 -0
package/src/config.ts CHANGED
@@ -4,7 +4,7 @@ import { existsSync } from "node:fs";
4
4
  import { dirname, isAbsolute, join } from "node:path";
5
5
  import { arrayValue, isString, objectValue, parseConfigFile, SUGGEST_EDIT_CONFIG, SUGGEST_INIT_FORCE } from "./config-parse.ts";
6
6
  import { ConfigLoadError } from "./config-load-error.ts";
7
- import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId } from "./profiles.ts";
7
+ import { BUILT_IN_PROFILES, builtInProfileNames, DEFAULT_PROFILE_NAME, isKnownRuleId, ruleOptionKeys } from "./profiles.ts";
8
8
  import type { AnalysisOptions, Config, FailThreshold, InlineProfileSpec, MinimumSeverityCommand, ProfileDefinition, ProfileRuleSetting, ProfileSpec, Severity } from "./types.ts";
9
9
 
10
10
  type RuleOverride = Config["rules"] extends Map<string, infer RuleOverrideValue> ? RuleOverrideValue : never;
@@ -19,10 +19,12 @@ function defaultConfig(): Config {
19
19
  return {
20
20
  schemaVersion: "gruff-ts.config.v0.1",
21
21
  ignoredPaths: [],
22
- acceptedAbbreviations: new Set(["age", "app", "cb", "db", "fn", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
22
+ acceptedAbbreviations: new Set(["age", "app", "db", "fs", "id", "io", "key", "log", "max", "min", "now", "raw", "rx", "tx", "ui", "url"]),
23
23
  secretPreviews: new Set(),
24
24
  bannedGenericNames: new Set(["process", "handle", "doit", "run", "execute", "manage"]),
25
25
  acceptedBooleanNames: new Set(["all", "apply", "check", "dev", "enabled", "force", "fresh", "harness", "json", "ok", "verbose", "yes"]),
26
+ acceptedClassFilePairs: new Set(),
27
+ acceptedCasingPairs: new Set(),
26
28
  booleanPrefixes: new Set(["is", "has", "can", "should", "does", "did", "was", "will", "may", "in", "scan", "supports", "requires", "allow", "check", "enable", "exclude", "include", "omit", "skip", "with", "without"]),
27
29
  hungarianPrefixes: new Set(["str", "obj", "arr", "bool", "int", "num"]),
28
30
  placeholderNames: new Set(["foo", "bar", "baz", "tmp", "temp", "thing", "stuff", "data", "value", "item"]),
@@ -240,13 +242,14 @@ function inlineSpecFromObject(block: Record<string, unknown>): InlineProfileSpec
240
242
  }
241
243
 
242
244
  // Builds the per-rule settings map for an inline profile, reusing the same validation as the
243
- // top-level `rules:` block (`ruleConfigValue` throws on a non-numeric threshold or bad severity).
245
+ // top-level `rules:` block (`ruleConfigValue` throws on unknown/malformed fields; rule ids are
246
+ // validated by the profile resolver so direct and profile rules reject identically).
244
247
  function profileRulesFromBlock(rulesBlock: Record<string, unknown>): Record<string, ProfileRuleSetting> {
245
248
  const rules: Record<string, ProfileRuleSetting> = {};
246
249
  for (const [ruleId, value] of Object.entries(rulesBlock)) {
247
250
  const rule = objectValue(value);
248
251
  if (rule) {
249
- rules[ruleId] = ruleConfigValue(rule);
252
+ rules[ruleId] = ruleConfigValue(ruleId, rule);
250
253
  }
251
254
  }
252
255
  return rules;
@@ -347,7 +350,7 @@ function applyPathConfig(config: Config, raw: Record<string, unknown>): void {
347
350
  }
348
351
 
349
352
  // The allowlist section is the main lever users have for tuning gruff to their conventions.
350
- // `acceptedAbbreviations` and the seven naming lists are lowercased on import so case-insensitive
353
+ // `acceptedAbbreviations` and the naming lists are lowercased on import so case-insensitive
351
354
  // matching is the stable behaviour regardless of how users write entries.
352
355
  function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): void {
353
356
  const allowlists = objectValue(raw.allowlists);
@@ -358,6 +361,8 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
358
361
  config.secretPreviews = new Set(arrayValue(allowlists?.secretPreviews).filter(isString));
359
362
  applyNamingAllowlist(config, allowlists, "bannedGenericNames");
360
363
  applyNamingAllowlist(config, allowlists, "acceptedBooleanNames");
364
+ applyNamingAllowlist(config, allowlists, "acceptedClassFilePairs");
365
+ applyNamingAllowlist(config, allowlists, "acceptedCasingPairs");
361
366
  applyNamingAllowlist(config, allowlists, "booleanPrefixes");
362
367
  applyNamingAllowlist(config, allowlists, "hungarianPrefixes");
363
368
  applyNamingAllowlist(config, allowlists, "placeholderNames");
@@ -367,7 +372,7 @@ function applyAllowlistConfig(config: Config, raw: Record<string, unknown>): voi
367
372
 
368
373
  // Replaces the entire list when the user provides that key - there is no merge with defaults.
369
374
  // The "set the whole list" semantic is intentional so users can deliberately empty a list.
370
- function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "acceptedBooleanNames" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "negativeBooleanAllowed" | "knownAcronyms"): void {
375
+ function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown> | undefined, key: "bannedGenericNames" | "acceptedBooleanNames" | "acceptedClassFilePairs" | "acceptedCasingPairs" | "booleanPrefixes" | "hungarianPrefixes" | "placeholderNames" | "negativeBooleanAllowed" | "knownAcronyms"): void {
371
376
  if (!allowlists || !(key in allowlists)) {
372
377
  return;
373
378
  }
@@ -375,7 +380,8 @@ function applyNamingAllowlist(config: Config, allowlists: Record<string, unknown
375
380
  }
376
381
 
377
382
  // Per-rule overrides under the `rules:` key. Each entry can carry enabled / threshold / severity /
378
- // options - only the keys the user actually sets become overrides; unset keys fall through to defaults.
383
+ // options - only the keys the user actually sets become overrides; unset keys fall through to
384
+ // defaults. Throws ConfigLoadError on rule ids outside the catalogue and on malformed field values.
379
385
  function applyRuleConfig(config: Config, raw: Record<string, unknown>): void {
380
386
  const rules = objectValue(raw.rules);
381
387
  if (!rules) {
@@ -386,21 +392,44 @@ function applyRuleConfig(config: Config, raw: Record<string, unknown>): void {
386
392
  if (!rule) {
387
393
  continue;
388
394
  }
389
- config.rules.set(ruleId, ruleConfigValue(rule));
395
+ // A misspelled id would otherwise sit in the map as a silent no-op the user believes is policy.
396
+ if (!isKnownRuleId(ruleId)) {
397
+ throw new ConfigLoadError(
398
+ `Unknown rule id: ${JSON.stringify(ruleId)}.`,
399
+ "Use a rule id from `gruff-ts list-rules`; `rules:` keys must match the catalogue exactly.",
400
+ );
401
+ }
402
+ config.rules.set(ruleId, ruleConfigValue(ruleId, rule));
390
403
  }
391
404
  }
392
405
 
393
- // Builds one rule's override entry after `assertRuleThresholdConfig` has thrown on malformed input.
406
+ // Builds one rule's override entry after the field asserts have thrown on malformed input.
394
407
  // Validation happens before extraction so users see a useful error rather than a silently dropped key.
395
- function ruleConfigValue(rule: Record<string, unknown>): RuleOverride {
408
+ function ruleConfigValue(ruleId: string, rule: Record<string, unknown>): RuleOverride {
396
409
  assertRuleThresholdConfig(rule);
397
- const ruleOverride: RuleOverride = { options: numericConfigMap(rule.options) };
410
+ assertRuleEnabledConfig(rule);
411
+ const ruleOverride: RuleOverride = { options: validatedRuleOptions(ruleId, rule.options) };
398
412
  applyRuleEnabledConfig(ruleOverride, rule);
399
413
  applyRuleThresholdConfig(ruleOverride, rule);
400
414
  applyRuleSeverityConfig(ruleOverride, rule);
401
415
  return ruleOverride;
402
416
  }
403
417
 
418
+ /*
419
+ * Rejects non-boolean `enabled` values loudly. YAML 1.2 core scalars keep `no`/`off`/`yes`/`on` as
420
+ * strings (only `true`/`false` parse as booleans), so a user writing `enabled: no` previously got a
421
+ * silent no-op while believing the rule was off. Throws ConfigLoadError naming the offending value
422
+ * and the accepted forms; returns silently when the key is absent.
423
+ */
424
+ function assertRuleEnabledConfig(rule: Record<string, unknown>): void {
425
+ if ("enabled" in rule && typeof rule.enabled !== "boolean") {
426
+ throw new ConfigLoadError(
427
+ `Rule config key "enabled" must be true or false; got ${JSON.stringify(rule.enabled)}.`,
428
+ "YAML 1.2 treats `no`/`off`/`yes`/`on` as strings - write `enabled: true` or `enabled: false`.",
429
+ );
430
+ }
431
+ }
432
+
404
433
  /*
405
434
  * Validates individual `threshold` and `severity` types. Either, neither, or both may be present:
406
435
  * many rules have no `threshold` knob at all (security.eval-call, waste.any-type, etc.), so a
@@ -442,18 +471,29 @@ function applyRuleSeverityConfig(ruleOverride: RuleOverride, rule: Record<string
442
471
  }
443
472
  }
444
473
 
445
- // Rule options are typed as numeric (thresholds, line counts, etc.). Non-numeric entries are
446
- // silently dropped rather than thrown because allowing malformed YAML to abort a scan is too aggressive.
447
- function numericConfigMap(optionsValue: unknown): Map<string, number> {
474
+ /*
475
+ * Validates `rules.<id>.options` against the rule descriptor's declared option keys - a dropped
476
+ * option would otherwise convince the user a tuning applied when it did not. Rules without declared
477
+ * options reject every entry. Throws ConfigLoadError naming the rule and its accepted keys for
478
+ * unknown keys, and the offending value for non-numeric declared options.
479
+ */
480
+ function validatedRuleOptions(ruleId: string, optionsValue: unknown): Map<string, number> {
448
481
  const options = new Map<string, number>();
449
482
  const rawOptions = objectValue(optionsValue);
450
483
  if (!rawOptions) {
451
484
  return options;
452
485
  }
486
+ const acceptedKeys = ruleOptionKeys(ruleId);
453
487
  for (const [name, option] of Object.entries(rawOptions)) {
454
- if (typeof option === "number") {
455
- options.set(name, option);
488
+ // Reject unknown keys first so a typo is reported as the typo, not as a type error.
489
+ if (!acceptedKeys.includes(name)) {
490
+ const accepted = acceptedKeys.length > 0 ? `accepts options: ${acceptedKeys.join(", ")}` : "accepts no options";
491
+ throw new ConfigLoadError(`Unknown option ${JSON.stringify(name)} for rule ${ruleId}; the rule ${accepted}.`, SUGGEST_EDIT_CONFIG);
492
+ }
493
+ if (typeof option !== "number") {
494
+ throw new ConfigLoadError(`Rule config option ${JSON.stringify(name)} for ${ruleId} must be numeric; got ${JSON.stringify(option)}.`, SUGGEST_EDIT_CONFIG);
456
495
  }
496
+ options.set(name, option);
457
497
  }
458
498
  return options;
459
499
  }
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Shared release constants that keep CLI, reports, and rule catalogue output in sync.
2
- const VERSION = "0.3.2";
2
+ const VERSION = "0.5.0";
3
3
 
4
4
  /*
5
5
  * Threshold at which the `analyse` text renderer appends a one-line pointer to `gruff-ts summary`.
@@ -1,12 +1,12 @@
1
1
  // Context-doc rules: emit findings when a function or interface comment exists but does not
2
2
  // describe the WHY (complex control flow), side effects, error behavior, or public-contract
3
3
  // invariants the implementation carries. Each rule reports a stable, deterministic finding.
4
- import { type FunctionBlock, maxNestingDepth } from "./blocks.ts";
4
+ import { type FunctionBlock } from "./blocks.ts";
5
5
  import { type CommentRecord } from "./comment-scanner.ts";
6
+ import { baseComplexityMetrics } from "./complexity-metrics.ts";
6
7
  import { threshold } from "./config.ts";
7
8
  import { type SourceFile } from "./discovery.ts";
8
9
  import { makeFinding } from "./findings.ts";
9
- import { countMatches } from "./text-scans.ts";
10
10
  import type { Config, Finding } from "./types.ts";
11
11
 
12
12
  // Generic declaration shape used by both function and interface comment-quality rules so they can
@@ -147,23 +147,22 @@ function contextDocFinding(input: ContextDocFindingInput): Finding {
147
147
  });
148
148
  }
149
149
 
150
- // Composite gate: any one of size, cyclomatic, cognitive, or nesting depth crossing the
151
- // configured stable threshold qualifies a callable as "complex enough to need WHY context".
150
+ // Uses the same syntax measurement as complexity findings so a reviewer sees one consistent gate.
152
151
  function isComplexContextCandidate(block: FunctionBlock, config: Config): boolean {
153
- const cyclomatic = countMatches(block.codeBody, /\b(if|else if|switch|case|for|while|catch)\b|\?|&&|\|\|/g) + 1;
154
- const cognitive = cyclomatic + maxNestingDepth(block.codeBody);
152
+ // A legacy span-only caller cannot reparse here, so it receives the same neutral fallback as block rules.
153
+ const sharedComplexityMetrics = block.complexityMetrics ?? baseComplexityMetrics();
155
154
  return (
156
155
  block.lineCount > threshold(config, "size.function-length", 200) ||
157
- cyclomatic > threshold(config, "complexity.cyclomatic", 15) ||
158
- cognitive > threshold(config, "complexity.cognitive", 15) ||
159
- maxNestingDepth(block.codeBody) > 3
156
+ sharedComplexityMetrics.cyclomatic > threshold(config, "complexity.cyclomatic", 15) ||
157
+ sharedComplexityMetrics.cognitive > threshold(config, "complexity.cognitive", 15) ||
158
+ sharedComplexityMetrics.maximumControlFlowNesting > 3
160
159
  );
161
160
  }
162
161
 
163
162
  // Vocabulary list signalling "the comment explains why" - the missing-why rule passes when any
164
163
  // listed word appears. Adding entries here loosens the rule; removing them tightens it.
165
164
  function hasComplexWhyMarker(text: string): boolean {
166
- return /\b(?:because|why|intentional|tradeoff|compat|avoid|preserve)\b/i.test(text);
165
+ return /\b(?:because|why|intentional|trade-?off|compat(?:ibility|ible)?|avoid|preserve)\b|\b(?:due to|so that|in order to|required by)\b/i.test(text);
167
166
  }
168
167
 
169
168
  // Vocabulary for "comment names a side effect". Pairs with `SIDE_EFFECT_BODY_PATTERNS` - if the
@@ -7,13 +7,20 @@ import { escapeRegex, finding } from "./findings-helpers.ts";
7
7
  import { byteLine, countMatches } from "./text-scans.ts";
8
8
  import type { Finding } from "./types.ts";
9
9
 
10
- // Deliberately single-file and low confidence because private methods can still be reached by
11
- // tests, decorators, framework hooks, or string-based reflection; reports stable advisory findings because removal still needs human confirmation.
10
+ /*
11
+ * Single-file, low-confidence dead-code pass. Contract invariant: removal candidates stay advisory
12
+ * because tests, decorators, framework hooks, or reflection may still reach a private method. It
13
+ * reports findings only and never throws for malformed snippets. Why two evidence counts:
14
+ * declarations contribute to `name(` matches, while bare method references such as `items.map(this.double)`
15
+ * appear only as `this.name` / `this?.name`, and either shape is enough usage evidence to suppress
16
+ * the finding. The reference count requires a `this` receiver so unrelated properties that share
17
+ * the name (for example `settings.refresh`) cannot mask a genuinely unused private method.
18
+ */
12
19
  export function analyseDeadCode(file: SourceFile, source: string, findings: Finding[]): void {
13
20
  for (const match of source.matchAll(/\bprivate\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/g)) {
14
21
  const name = match[1] ?? "";
15
22
  const escaped = escapeRegex(name);
16
- if (countMatches(source, new RegExp(`${escaped}\\s*\\(`, "g")) <= 1) {
23
+ if (countMatches(source, new RegExp(`${escaped}\\s*\\(`, "g")) <= 1 && countMatches(source, new RegExp(`\\bthis\\??\\.${escaped}\\b`, "g")) === 0) {
17
24
  findings.push(
18
25
  makeFinding({
19
26
  ruleId: "dead-code.unused-private-method",
package/src/discovery.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  // Filesystem discovery, ignore-policy matching, and display-path normalization for deterministic scans.
2
2
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { basename, dirname, extname, isAbsolute, join, relative } from "node:path";
4
- import type { AnalysisOptions, Config, IgnoreSource, SkippedPath } from "./types.ts";
4
+ import type { AnalysisOptions, Config, IgnoreSource, ScanSurfaceNote, SkippedPath } from "./types.ts";
5
5
 
6
- // `absolutePath` is what `node:fs` operates on; `displayPath` is the project-relative POSIX form
7
- // embedded in findings and baselines. They must stay aligned - diverging them breaks fingerprint stability.
6
+ // `absolutePath` is what `node:fs` operates on; `displayPath` is project-relative inside the run
7
+ // root and absolute outside it. They must stay aligned - diverging them breaks fingerprint stability.
8
8
  export interface SourceFile {
9
9
  absolutePath: string;
10
10
  displayPath: string;
@@ -22,12 +22,15 @@ interface SourceDiscovery {
22
22
  // Public discovery result. `files` are sorted by display path and deduped; `ignoredPaths` (the
23
23
  // back-compatible string[] of excluded paths) and `skipped` (the same paths enriched with ignore
24
24
  // source + matched pattern) are sorted so reports stay deterministic even when the underlying
25
- // filesystem returns directory entries in arbitrary order.
25
+ // filesystem returns directory entries in arbitrary order. `notes` carries one entry per requested
26
+ // input that exists but contributed zero analysable files, so an all-skipped scan is never a
27
+ // silent zero-finding success.
26
28
  export interface SourceDiscoveryResult {
27
29
  files: SourceFile[];
28
30
  missingPaths: string[];
29
31
  ignoredPaths: string[];
30
32
  skipped: SkippedPath[];
33
+ notes: ScanSurfaceNote[];
31
34
  }
32
35
 
33
36
  // A single line from a `.gitignore`. The combination of `isAnchored`, `isDirectoryOnly`, and `hasSlash`
@@ -47,14 +50,35 @@ interface GitIgnoreRule {
47
50
  export function discoverSources(projectRoot: string, options: AnalysisOptions, config: Config): SourceDiscoveryResult {
48
51
  const discovery: SourceDiscovery = { files: [], missingPaths: [], skipped: new Map<string, SkippedPath>() };
49
52
  const inputs = options.paths.length > 0 ? options.paths : ["."];
53
+ const notes: ScanSurfaceNote[] = [];
50
54
 
51
55
  for (const input of inputs) {
56
+ const filesBefore = discovery.files.length;
57
+ const missingBefore = discovery.missingPaths.length;
58
+ const skippedBefore = discovery.skipped.size;
52
59
  discoverSourceInput(projectRoot, input, options, config, discovery);
60
+ if (discovery.missingPaths.length === missingBefore && discovery.files.length === filesBefore) {
61
+ notes.push(zeroFileInputNote(input, discovery.skipped.size - skippedBefore));
62
+ }
53
63
  }
54
64
 
55
65
  discovery.files.sort((left, right) => left.displayPath.localeCompare(right.displayPath));
56
66
  const skipped = [...discovery.skipped.values()].sort((left, right) => left.path.localeCompare(right.path));
57
- return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped };
67
+ return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped, notes };
68
+ }
69
+
70
+ // A requested input that exists but contributed no analysable files is a per-input note, never a
71
+ // diagnostic - exit codes stay unchanged. The skip count names the likely cause (parent gitignore
72
+ // or config ignore rules hiding the whole subtree) so the caller does not read 0 findings as clean.
73
+ function zeroFileInputNote(input: string, skippedCount: number): ScanSurfaceNote {
74
+ const cause = skippedCount > 0
75
+ ? `${skippedCount} path(s) under it were excluded by ignore rules`
76
+ : "it contains no analysable source files";
77
+ return {
78
+ noteType: "no-analysable-files",
79
+ path: input,
80
+ message: `Requested path '${input}' was not analysed: ${cause}. 0 findings here does not mean the path is clean.`,
81
+ };
58
82
  }
59
83
 
60
84
  // Resolves the input against `node:fs`. Missing inputs go into `missingPaths` so the CLI can
@@ -83,6 +107,8 @@ function discoverSourceInput(projectRoot: string, input: string, options: Analys
83
107
  walk(projectRoot, absolute, options, config, discovery.skipped, discovery.files, gitIgnoreRules);
84
108
  }
85
109
 
110
+ // Depth-first directory walk that applies ignore rules before recursing, because descending into
111
+ // an excluded subtree would waste reads; skips record source and pattern to avoid silent exclusions.
86
112
  function walk(
87
113
  projectRoot: string,
88
114
  directory: string,
@@ -110,26 +136,28 @@ function walk(
110
136
  }
111
137
  }
112
138
 
113
- // Single source of truth for which extensions count as scannable. Adding a new file kind here will
114
- // expand the rule set's reach across an entire project - coordinate with rule descriptors before changing.
139
+ /** Extensions parsed as code. Widening this reaches every rule that inspects script syntax. */
140
+ export const SCRIPT_FILE_EXTENSIONS: readonly string[] = ["ts", "tsx", "js", "jsx", "mjs", "cjs"];
141
+
142
+ /** Extensions read as config or text assets, which only the text-oriented rules inspect. */
143
+ export const TEXT_FILE_EXTENSIONS: readonly string[] = ["conf", "config", "env", "ini", "json", "toml", "xml", "yaml", "yml"];
144
+
145
+ /** Extensionless credential files that stay scannable without admitting every dotfile. */
146
+ export const EXACT_SECRET_TEXT_FILES: readonly string[] = [".npmrc", ".pypirc", ".envrc", ".netrc"];
147
+
148
+ // Single source of truth for which extensions count as scannable. Adding a new file kind to the
149
+ // lists above will expand the rule set's reach across an entire project - the scan surface is also
150
+ // stated in prose across seven documents, so `release-truth.test.ts` pins these lists literally.
115
151
  function pushSourceFile(projectRoot: string, absolutePath: string, files: SourceFile[]): void {
116
152
  const extension = extname(absolutePath).slice(1).toLowerCase();
117
153
  const name = basename(absolutePath);
118
- const isScript = ["ts", "tsx", "js", "jsx", "mjs", "cjs"].includes(extension);
119
- const isText =
120
- ["conf", "config", "env", "ini", "json", "toml", "xml", "yaml", "yml"].includes(extension) ||
121
- name.startsWith(".env") ||
122
- isExactSecretTextFile(name);
154
+ const isScript = SCRIPT_FILE_EXTENSIONS.includes(extension);
155
+ const isText = TEXT_FILE_EXTENSIONS.includes(extension) || name.startsWith(".env") || EXACT_SECRET_TEXT_FILES.includes(name);
123
156
  if (isScript || isText) {
124
157
  files.push({ absolutePath, displayPath: displayPath(projectRoot, absolutePath), isScript });
125
158
  }
126
159
  }
127
160
 
128
- // Exact extensionless secret files stay scannable without opening the door to every dotfile.
129
- function isExactSecretTextFile(name: string): boolean {
130
- return [".npmrc", ".pypirc", ".envrc", ".netrc"].includes(name);
131
- }
132
-
133
161
  // The default-ignore list is part of the documented schema contract: callers can override with
134
162
  // `--include-ignored`, but the list itself must not silently change between releases without notice.
135
163
  function isDefaultIgnoredDir(path: string): boolean {
@@ -551,11 +579,27 @@ export function absolutize(projectRoot: string, path: string): string {
551
579
  return isAbsolute(path) ? path : join(projectRoot, path);
552
580
  }
553
581
 
554
- // Project-relative form with forward slashes - the report contract uses POSIX-style display paths
555
- // on every platform. "" collapses to "." so the root has a stable label in findings.
556
- export function displayPath(projectRoot: string, path: string): string {
557
- const relativePath = relative(projectRoot, path).replaceAll("\\", "/");
558
- return relativePath === "" ? "." : relativePath;
582
+ /**
583
+ * Formats a scanned path for findings, diagnostics, and baselines.
584
+ * Paths inside the run root stay relative; outside paths are absolute so editor and CI links remain usable.
585
+ *
586
+ * @param projectRoot - working directory that anchors relative report paths
587
+ * @param inputPath - scanned path; an empty path addresses the run root itself
588
+ * @returns POSIX report path; `.` means the input is the run root
589
+ */
590
+ export function displayPath(projectRoot: string, inputPath: string): string {
591
+ // Relative CLI inputs are resolved from the run root before report formatting.
592
+ const absoluteInputPath = isAbsolute(inputPath) ? inputPath : join(projectRoot, inputPath);
593
+ const projectRelativePath = relative(projectRoot, absoluteInputPath).replaceAll("\\", "/");
594
+ // The run root itself needs a non-empty label in reports.
595
+ if (projectRelativePath === "") {
596
+ return ".";
597
+ }
598
+ // A relative escape cannot serve as an editor or CI link from the run root.
599
+ if (projectRelativePath === ".." || projectRelativePath.startsWith("../") || isAbsolute(projectRelativePath)) {
600
+ return absoluteInputPath.replaceAll("\\", "/");
601
+ }
602
+ return projectRelativePath;
559
603
  }
560
604
 
561
605
  // Escapes the standard regex metacharacters so untrusted patterns can be embedded literally.
package/src/doc-rules.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  // JSDoc and exported-declaration documentation rules. Covers `docs.missing-public-doc`,
2
2
  // `docs.missing-file-overview`, `docs.missing-interface-doc`, and the docblock rule pack
3
3
  // (stale/missing @param, missing @returns, useless docblock). Stable, deterministic emission order.
4
- import { parameterNames } from "./blocks.ts";
5
4
  import { commentTextAtLine, hasLeadingCommentBeforeLine } from "./comment-scanner.ts";
6
5
  import { type SourceFile } from "./discovery.ts";
7
6
  import { makeFinding } from "./findings.ts";
8
7
  import { normalizedIdentifier, splitIdentifierWords } from "./findings-helpers.ts";
8
+ import { documentedExportFunctions, type ParsedScript } from "./parsed-script.ts";
9
9
  import { byteLine } from "./text-scans.ts";
10
10
  import type { Finding } from "./types.ts";
11
11
 
@@ -134,11 +134,12 @@ export function interfaceDeclarations(source: string, codeSource: string): Expor
134
134
  }
135
135
 
136
136
  /*
137
- * Docblock rule pack. Walks every `/** … *\/ export function …` pair and fires four sub-rules per
138
- * block in a stable, deterministic emission order (stale-param → missing-param → missing-return → useless-docblock).
137
+ * Docblock rule pack. Walks every documented exported function from the shared syntax tree and
138
+ * fires four sub-rules per block in a stable, deterministic emission order
139
+ * (stale-param → missing-param → missing-return → useless-docblock).
139
140
  */
140
- export function analyseDocRules(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
141
- for (const documentedExport of documentedExportBlocks(source, codeSource)) {
141
+ export function analyseDocRules(file: SourceFile, findings: Finding[], parsed: ParsedScript): void {
142
+ for (const documentedExport of documentedExportBlocks(parsed)) {
142
143
  pushStaleParamFindings(file, documentedExport, findings);
143
144
  pushMissingParamFindings(file, documentedExport, findings);
144
145
  pushMissingReturnFinding(file, documentedExport, findings);
@@ -146,54 +147,22 @@ export function analyseDocRules(file: SourceFile, source: string, codeSource: st
146
147
  }
147
148
  }
148
149
 
149
- // Walks every `/** … */ export function …` pair in the source. Skips matches whose `export`
150
- // keyword is inside a string/regex by confirming it shows up in the masked code as well.
151
- function documentedExportBlocks(source: string, codeSource: string): DocumentedExportBlock[] {
152
- const blocks: DocumentedExportBlock[] = [];
153
- const documentedExport = /\/\*\*((?:(?!\*\/)[\s\S])*?)\*\/\s*export\s+function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)\s*(?::\s*([^\x7b\n]+))?/g;
154
- for (const match of source.matchAll(documentedExport)) {
155
- const block = documentedExportBlock(source, codeSource, match);
156
- if (block) {
157
- blocks.push(block);
158
- }
159
- }
160
- return blocks;
161
- }
162
-
163
- // Promotes a regex match into the structured block consumed by docblock rules. Returns undefined
164
- // when the matched `export` keyword is actually inside a string literal in the masked source.
165
- function documentedExportBlock(source: string, codeSource: string, match: RegExpMatchArray): DocumentedExportBlock | undefined {
166
- const matchStart = regexMatchStart(match);
167
- const exportIndex = source.indexOf("export", matchStart);
168
- if (!isDocumentedExportInCode(codeSource, exportIndex)) {
169
- return undefined;
170
- }
171
- const doc = regexGroup(match, 1);
172
- return {
173
- doc,
174
- name: regexGroup(match, 2),
175
- params: parameterNames(regexGroup(match, 3)).map((parameter) => parameter.name),
176
- paramTags: docParamTags(doc),
177
- line: byteLine(source, matchStart),
178
- returnType: regexGroup(match, 4).trim(),
179
- };
180
- }
181
-
182
- // `index ?? 0` adapter for the standard regex API - match.index is technically optional under
183
- // strict TypeScript even though every real match has it.
184
- function regexMatchStart(match: RegExpMatchArray): number {
185
- return match.index ?? 0;
186
- }
187
-
188
- // `match[index] ?? ""` adapter - keeps callers from sprinkling default-empty handling.
189
- function regexGroup(match: RegExpMatchArray, index: number): string {
190
- return match[index] ?? "";
191
- }
192
-
193
- // Confirms the captured `export` keyword is in real code, not inside a masked comment or string.
194
- // The mask preserves the first letter of code tokens, so checking for `e` is sufficient.
195
- function isDocumentedExportInCode(codeSource: string, exportIndex: number): boolean {
196
- return exportIndex >= 0 && codeSource[exportIndex] === "e";
150
+ /*
151
+ * Detection anchors on the syntax tree: parameter names are real AST parameters, so parenthesised
152
+ * types such as `(typeof X)[number]` cannot truncate the signature, prose containing `export`
153
+ * inside the docblock cannot suppress a block, and `export async function` plus generic and
154
+ * multi-line signatures are covered. The former regex fallback for parse-less callers is gone -
155
+ * every caller supplies the shared parse.
156
+ */
157
+ function documentedExportBlocks(parsed: ParsedScript): DocumentedExportBlock[] {
158
+ return documentedExportFunctions(parsed).map((documented) => ({
159
+ doc: documented.docText,
160
+ name: documented.name,
161
+ params: documented.parameterNames,
162
+ paramTags: docParamTags(documented.docText),
163
+ line: documented.line,
164
+ returnType: documented.returnTypeText,
165
+ }));
197
166
  }
198
167
 
199
168
  // Reports stale `@param` tags before missing ones because a rename should produce a stable pair:
@@ -3,9 +3,135 @@
3
3
  // on it without forming a cycle.
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { basename } from "node:path";
6
+ import { ruleSeverity } from "./config.ts";
6
7
  import type { SourceFile } from "./discovery.ts";
7
8
  import { makeFinding } from "./findings.ts";
8
- import type { Finding, Pillar, Severity } from "./types.ts";
9
+ import type { Config, Finding, Pillar, Severity } from "./types.ts";
10
+
11
+ // Splits only at top-level commas, then strips parameter-property modifiers and `...rest`.
12
+ // Destructured parameters remain intentionally invisible to per-parameter rules.
13
+ export function parameterNames(params: string): Array<{ name: string; raw: string }> {
14
+ return splitTopLevelParameters(params)
15
+ .map((parameter) => parameter.trim())
16
+ .filter(Boolean)
17
+ .map((raw) => {
18
+ const stripped = raw.replace(/^(?:(?:public|private|protected|readonly|override)\s+)*/, "").replace(/^\.\.\./, "");
19
+ const name = stripped.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\s*(?=[?:=]|$)/)?.[1] ?? "";
20
+ return { name, raw: stripped };
21
+ })
22
+ .filter((parameter) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parameter.name));
23
+ }
24
+
25
+ // Nesting and quote context for the parameter splitter. Kept as one mutable record so the
26
+ // per-character helpers stay small enough to read at a glance.
27
+ interface ParameterSplitState {
28
+ parenthesisDepth: number;
29
+ bracketDepth: number;
30
+ braceDepth: number;
31
+ angleDepth: number;
32
+ quote: string;
33
+ isEscaped: boolean;
34
+ }
35
+
36
+ // Parameter defaults and type expressions can contain their own commas. A small delimiter scanner
37
+ // keeps those nested commas attached, because adding another TypeScript parse to this hot path
38
+ // would cost more than the character walk saves.
39
+ function splitTopLevelParameters(params: string): string[] {
40
+ const parameters: string[] = [];
41
+ const state: ParameterSplitState = { parenthesisDepth: 0, bracketDepth: 0, braceDepth: 0, angleDepth: 0, quote: "", isEscaped: false };
42
+ let start = 0;
43
+ for (let index = 0; index < params.length; index += 1) {
44
+ const character = params[index] ?? "";
45
+ if (advanceParameterQuoteState(state, character)) {
46
+ continue;
47
+ }
48
+ if (character === "," && isTopLevelParameterPosition(state)) {
49
+ parameters.push(params.slice(start, index));
50
+ start = index + 1;
51
+ continue;
52
+ }
53
+ advanceParameterDepths(state, params, index, start);
54
+ }
55
+ parameters.push(params.slice(start));
56
+ return parameters;
57
+ }
58
+
59
+ // Consumes quote-context characters: inside a string nothing is structural, and a quote character
60
+ // opens string context. Returns false for ordinary characters so the caller keeps scanning.
61
+ function advanceParameterQuoteState(state: ParameterSplitState, character: string): boolean {
62
+ if (state.quote !== "") {
63
+ if (state.isEscaped) {
64
+ state.isEscaped = false;
65
+ } else if (character === "\\") {
66
+ state.isEscaped = true;
67
+ } else if (character === state.quote) {
68
+ state.quote = "";
69
+ }
70
+ return true;
71
+ }
72
+ if (character === '"' || character === "'" || character === "`") {
73
+ state.quote = character;
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+
79
+ // Tracks nesting for parentheses, brackets, braces, and guarded type-argument angles so commas
80
+ // inside them stay attached to their parameter.
81
+ function advanceParameterDepths(state: ParameterSplitState, params: string, index: number, start: number): void {
82
+ const character = params[index] ?? "";
83
+ if (character === "(") state.parenthesisDepth += 1;
84
+ else if (character === ")") state.parenthesisDepth = Math.max(0, state.parenthesisDepth - 1);
85
+ else if (character === "[") state.bracketDepth += 1;
86
+ else if (character === "]") state.bracketDepth = Math.max(0, state.bracketDepth - 1);
87
+ else if (character === "{") state.braceDepth += 1;
88
+ else if (character === "}") state.braceDepth = Math.max(0, state.braceDepth - 1);
89
+ else if (character === "<" && opensTypeArgumentList(params, index, start)) state.angleDepth += 1;
90
+ else if (character === ">" && state.angleDepth > 0 && params[index - 1] !== "=") state.angleDepth -= 1;
91
+ }
92
+
93
+ // A comma splits parameters only outside every nesting kind.
94
+ function isTopLevelParameterPosition(state: ParameterSplitState): boolean {
95
+ return state.parenthesisDepth === 0 && state.bracketDepth === 0 && state.braceDepth === 0 && state.angleDepth === 0;
96
+ }
97
+
98
+ // Treat `<...>` as type arguments in annotations, or in generic call/arrow defaults whose closing
99
+ // token is followed by `(`. Requiring that call boundary keeps comparison chains from swallowing
100
+ // a later parameter while preserving commas inside `factory<T, U>(...)` and `<T, U>(...) => ...`.
101
+ function opensTypeArgumentList(params: string, index: number, parameterStart: number): boolean {
102
+ const prefix = params.slice(parameterStart, index);
103
+ const previousCharacter = params[index - 1] ?? "";
104
+ const isTypeContext = prefix.includes(":") && !prefix.includes("=");
105
+ const followsTokenWithoutWhitespace = previousCharacter !== "" && !/\s/.test(previousCharacter);
106
+ const startsGenericArrowDefault = /=\s*$/.test(prefix);
107
+ if (!isTypeContext && !followsTokenWithoutWhitespace && !startsGenericArrowDefault) {
108
+ return false;
109
+ }
110
+ let depth = 1;
111
+ for (let cursor = index + 1; cursor < params.length; cursor += 1) {
112
+ const character = params[cursor] ?? "";
113
+ if (character === "<") depth += 1;
114
+ else if (character === ">" && params[cursor - 1] !== "=") {
115
+ depth -= 1;
116
+ if (depth === 0) {
117
+ const isFollowedByCallParameters = /^\s*\(/.test(params.slice(cursor + 1));
118
+ return isTypeContext || isFollowedByCallParameters;
119
+ }
120
+ }
121
+ }
122
+ return false;
123
+ }
124
+
125
+ /*
126
+ * Central severity-override pass: config `rules.<id>.severity` wins over the scanner's created
127
+ * severity for every rule family in one place, so a user's policy applies even to scanners that
128
+ * hardcode their descriptor literal; without an override the created severity stands.
129
+ * Invariant: the fingerprint hashes (ruleId, filePath, line, symbol), so overrides never churn identity.
130
+ */
131
+ export function applyConfiguredSeverity(config: Config, finding: Finding): Finding {
132
+ const severity = ruleSeverity(config, finding.ruleId, finding.severity);
133
+ return severity === finding.severity ? finding : { ...finding, severity };
134
+ }
9
135
 
10
136
  // Input bundle for `finding()` - the lowest-cost finding factory. Captures everything the caller
11
137
  // must supply for a line-anchored Finding; shared defaults (confidence "high", empty metadata)