@blundergoat/gruff-ts 0.4.0 → 0.6.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 (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
package/src/analyser.ts CHANGED
@@ -1,36 +1,46 @@
1
- // Analyser pipeline: walks discovered sources, runs every rule pass (complexity, dead-code, design,
2
- // documentation, maintainability, modernisation, naming, security, sensitive-data, size, test-quality),
3
- // aggregates findings into the `gruff.analysis.v2` schema, and exposes `analyse` to the CLI shell.
4
- import { Buffer } from "node:buffer";
5
- import { readFileSync } from "node:fs";
1
+ // File overview: Builds the analysis report used by the CLI, dashboard, and coding-agent hook.
2
+ //
3
+ // A command such as `gruff-ts analyse src --diff staged` still reads project context before selecting findings from staged changes.
4
+ // This module also applies reviewed findings from a baseline and records history after a valid full scan.
5
+ import { Buffer, isUtf8 } from "node:buffer";
6
+ import { readFileSync, statSync } from "node:fs";
6
7
  import { cwd } from "node:process";
7
- import { basename } from "node:path";
8
- import { dedupeFindings, recordHistory } from "./baseline.ts";
8
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
9
+ import { recordHistory, sortedUniqueFindings } from "./baseline.ts";
10
+ import { declarationPositionFromSpans, findingIdentities, type DeclarationSpan } from "./baseline-identity.ts";
9
11
  import { applyBaselineOptions, type BaselineApplication } from "./baseline-options.ts";
10
- import { changedRegionScope, filterChangedFindings } from "./changed-regions.ts";
11
- import { loadConfig, optionNumber, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
12
+ import { CHANGED_REGION_DIAGNOSTIC_TYPE, ChangedRegionError, changedRegionScope, filterChangedFindings, filterScopedDiagnostics, type ChangedRegionScope } from "./changed-regions.ts";
13
+ import { loadConfig, optionBoolean, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
14
+ import { applyInlineSuppressions, isInlineSuppressionRelevantRule } from "./inline-suppressions.ts";
15
+ import { applyBuiltInTestPathSkip, partitionSensitiveExclusions } from "./sensitive-exclusions.ts";
12
16
  import { VERSION } from "./constants.ts";
13
17
  import { absolutize, discoverSources, displayPath, type SourceFile } from "./discovery.ts";
14
18
  import { makeFinding } from "./findings.ts";
15
- import { finding } from "./findings-helpers.ts";
16
- import { commentRecords } from "./comment-scanner.ts";
17
- import { analyseArchitectureRules, analyseCircularImportRule, buildProjectIndex, CIRCULAR_IMPORT_RULE_ID, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
18
- import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks, parameterNames } from "./blocks.ts";
19
- import { analyseClassRules, analyseAcronymCase, analyseInconsistentCasing, analyseInterfaceFields, collectDeclaredIdentifiers } from "./class-rules.ts";
19
+ import { applyConfiguredSeverity, finding, parameterNames } from "./findings-helpers.ts";
20
+ import { commentRecords, type CommentRecord } from "./comment-scanner.ts";
21
+ import { catalogueConfidence } from "./rules.ts";
22
+ import { analyseArchitectureRules, analyseCircularImportRule, buildProjectIndex, CIRCULAR_IMPORT_RULE_ID, extractImportStatements, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
23
+ import { analyseBlockMeasures, analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks, measuredOnlyFunctionBlocks } from "./blocks.ts";
24
+ import { bandedFields, LOWER_BAND_FILE, SPLIT_FILE } from "./limit-band.ts";
25
+ import { analyseClassRules } from "./class-rules.ts";
20
26
  import { analyseDeadCode, analyseUnreachable, analyseUnusedImports } from "./dead-code-rules.ts";
21
27
  import { analyseCommentQualityRules } from "./comment-rules.ts";
22
28
  import { analyseDocRules, analyseFileOverviewDoc, analyseInterfaceDocs } from "./doc-rules.ts";
23
29
  import { analyseLineRules } from "./line-rules.ts";
24
30
  import { analyseSecurityFlow } from "./security-flow-rules.ts";
25
- import { pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
31
+ import { pushIdentifierQualityAt, pushShortVariableAt } from "./naming-pushers.ts";
26
32
  import { analyseTestBlock } from "./test-block-rules.ts";
33
+ import { analyseDuplicateTestGroups } from "./duplicate-test-group-rules.ts";
27
34
  import { analyseGithubActionsRules } from "./github-actions-rules.ts";
28
35
  import { analyseProjectConfigRules } from "./project-config-rules.ts";
36
+ import { BUILT_IN_PROFILES } from "./profiles.ts";
29
37
  import { ruleDescriptors } from "./rules.ts";
30
38
  import { scoreReport, summarize } from "./scoring.ts";
39
+ import { isExecutionRequested } from "./selectors.ts";
31
40
  import { analyseSensitiveData } from "./sensitive-data-rules.ts";
32
- import { maskNonCode, maskTemplateLiteralBodies, parseDiagnostics } from "./source-text.ts";
33
- import type { AnalysisOptions, AnalysisReport, Config, Finding, Pillar, RunDiagnostic, ScanSurfaceNote, SkippedPath } from "./types.ts";
41
+ import { codeLineFlags, maskDecorators, parseScript, type ParsedScript } from "./parsed-script.ts";
42
+ import { maskNonCode, maskTemplateLiteralBodies } from "./source-text.ts";
43
+ import type { AnalysisOptions, AnalysisReport, Config, Finding, OutputFormat, Pillar, RunDiagnostic, ScanSurfaceNote, SkippedPath, SuppressedFinding, SuppressionSummary } from "./types.ts";
34
44
 
35
45
  /*
36
46
  * Internal hook view contract: both reports come from one current-tree scan so full-file and
@@ -42,102 +52,380 @@ export interface HookAnalysisReports {
42
52
  }
43
53
 
44
54
  /**
45
- * Analyse the configured paths and return the stable gruff.analysis.v2 report contract.
55
+ * Build a report for an `analyse`, `summary`, or `report` request.
56
+ * Invariant: an invalid scan or any changed-region scan is excluded from the user's full-scan score history.
46
57
  *
47
- * @param options Normalised analysis options from the CLI or direct callers.
48
- * @returns Versioned report with fingerprinted findings, diagnostics, paths, and score data.
58
+ * @param requestedOptions - paths, rules, and scan scope. An empty path list scans the launch directory. Omit history to skip writing it.
59
+ * @returns A report ready for the caller's formatter. An unreadable changed scope returns a diagnostic and an empty findings list.
60
+ * @throws ConfigLoadError for invalid configuration. Unexpected scope errors propagate to the caller.
49
61
  */
50
- export function analyse(options: AnalysisOptions): AnalysisReport {
62
+ export function analyse(requestedOptions: AnalysisOptions): AnalysisReport {
63
+ const options = targetsFromLaunchDirectory(requestedOptions);
51
64
  const preparation = prepareAnalysis(options);
52
- const changedScope = changedRegionScope(options);
53
- const run = completeAnalysis(preparation, options);
65
+ let changedScope: ChangedRegionScope | undefined;
66
+ try {
67
+ changedScope = changedRegionScope(options, preparation.projectRoot);
68
+ } catch (error) {
69
+ // A typo in `--changed-ranges` or a missing Git ref can be reported as an invalid scan before writing a baseline.
70
+ if (!(error instanceof ChangedRegionError)) {
71
+ throw error;
72
+ }
73
+ return failedRunReport(preparation.projectRoot, options.format, CHANGED_REGION_DIAGNOSTIC_TYPE, error.message);
74
+ }
75
+ const run = completeAnalysis(preparation, options, "diagnose", changedScope);
54
76
  const changedResult = filterChangedFindings(run.baselineResult.findings, changedScope, run.scanned.sources);
55
77
 
56
- if (options.historyFile) {
57
- recordHistory(run.projectRoot, options.historyFile, changedResult.findings, run.diagnostics);
78
+ // Generation uses the full scan, so errors anywhere in that scan must stay visible.
79
+ const diagnostics = options.generateBaseline ? run.diagnostics : filterScopedDiagnostics(run.diagnostics, changedScope);
80
+ const suppressedFindings = filterChangedSuppressedFindings(run.suppressedFindings, changedScope, run.scanned.sources);
81
+ const baseline = run.baselineResult.baseline;
82
+ // When a baseline was applied, `--fail-on-new` counts only unreviewed findings that remain in the requested scope.
83
+ const scopedBaseline = {
84
+ ...run.baselineResult,
85
+ findings: changedResult.findings,
86
+ ...(changedScope !== undefined && baseline && !baseline.generated
87
+ ? { baseline: { ...baseline, newFindings: changedResult.findings.length } }
88
+ : {}),
89
+ };
90
+ const report = reportFromRun({ ...run, diagnostics, suppressedFindings }, options, scopedBaseline, changedResult.suppressedCount);
91
+ // An invalid baseline, a changed-region scan, or a partial-catalogue scan cannot add a point to the user's full-scan trend history.
92
+ if (
93
+ options.historyFile
94
+ && changedScope === undefined
95
+ && !(options.execution && isExecutionRequested(options.execution))
96
+ && !diagnostics.some((diagnostic) => diagnostic.invalidatesRun !== false)
97
+ ) {
98
+ recordHistory(run.projectRoot, options.historyFile, report.score, report.findings.length, diagnostics);
58
99
  }
100
+ return report;
101
+ }
59
102
 
60
- return reportFromRun(run, options, { ...run.baselineResult, findings: changedResult.findings }, changedResult.suppressedCount);
103
+ /**
104
+ * Filters inline-suppressed SARIF records to the active changed-region scope while keeping whole-scan suppression audit rows untouched.
105
+ * Invariant: preserves the input order and returns the original list unchanged when unscoped or empty.
106
+ *
107
+ * @param suppressedFindings - full-scan inline/duplicate suppressed findings retained for SARIF output
108
+ * @param scope - active changed-region scope, or undefined for a full scan
109
+ * @param sources - retained source/AST snapshots used to evaluate symbol-level changed-region membership
110
+ * @returns Suppressed findings inside `scope`, or the original list unchanged when unscoped or empty.
111
+ */
112
+ function filterChangedSuppressedFindings(
113
+ suppressedFindings: SuppressedFinding[],
114
+ scope: ChangedRegionScope | undefined,
115
+ sources: Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>,
116
+ ): SuppressedFinding[] {
117
+ if (scope === undefined || suppressedFindings.length === 0) {
118
+ return suppressedFindings;
119
+ }
120
+ const kept = new Set(filterChangedFindings(suppressedFindings.map((entry) => entry.finding), scope, sources).findings);
121
+ return suppressedFindings.filter((entry) => kept.has(entry.finding));
61
122
  }
62
123
 
63
- // Builds the hook's full and changed-region reports from one scan. The diff-base replay still uses
64
- // the ordinary runner because it analyses different file contents.
124
+ /**
125
+ * Build the full and changed-region views the hook needs to distinguish a new finding from one already covered by a baseline.
126
+ * Both views use one read of the user's files. With no change selector, both fields point to that full scan.
127
+ *
128
+ * @param currentOptions - full-scan options resolved from the launch directory
129
+ * @param scopedOptions - change-scoped options providing the diff or range selector and formatting choices
130
+ * @param hasChangedRegion - true when scopedOptions selects a changed region; false skips scope resolution
131
+ * @returns Both reports sharing one file scan; when hasChangedRegion is false, scopedReport aliases currentReport.
132
+ */
65
133
  export function analyseHookReports(currentOptions: AnalysisOptions, scopedOptions: AnalysisOptions, hasChangedRegion: boolean): HookAnalysisReports {
66
- const run = completeAnalysis(prepareAnalysis(currentOptions), currentOptions);
134
+ currentOptions = targetsFromLaunchDirectory(currentOptions);
135
+ scopedOptions = targetsFromLaunchDirectory(scopedOptions);
136
+ // A hook without `--diff`, `--since`, or `--changed-ranges` has no narrower view to resolve.
137
+ const scopedChangedScope = hasChangedRegion ? changedRegionScope(scopedOptions, projectRootFromTargets(scopedOptions.paths)) : undefined;
138
+ const run = completeAnalysis(prepareAnalysis(currentOptions), currentOptions, "throw", scopedChangedScope);
67
139
  const currentReport = reportFromRun(run, currentOptions, run.baselineResult);
140
+ // An unscoped hook presents the same findings it uses for baseline comparison.
68
141
  if (!hasChangedRegion) {
69
142
  return { currentReport, scopedReport: currentReport };
70
143
  }
71
- const scopedChangedScope = changedRegionScope(scopedOptions);
72
144
  const scopedChangedResult = filterChangedFindings(run.baselineResult.findings, scopedChangedScope, run.scanned.sources);
73
- const scopedReport = reportFromRun(run, scopedOptions, { ...run.baselineResult, findings: scopedChangedResult.findings }, scopedChangedResult.suppressedCount);
145
+ const scopedSuppressedFindings = filterChangedSuppressedFindings(run.suppressedFindings, scopedChangedScope, run.scanned.sources);
146
+ // Same file-scoped diagnostics policy as diff-scoped analyse, so both surfaces agree.
147
+ const scopedReport = reportFromRun(
148
+ { ...run, diagnostics: filterScopedDiagnostics(run.diagnostics, scopedChangedScope), suppressedFindings: scopedSuppressedFindings },
149
+ scopedOptions,
150
+ { ...run.baselineResult, findings: scopedChangedResult.findings },
151
+ scopedChangedResult.suppressedCount,
152
+ );
74
153
  return { currentReport, scopedReport };
75
154
  }
76
155
 
77
- // Loads config and discovers inputs once so direct analysis and hook reuse share the same setup.
156
+ /**
157
+ * Choose the directory that owns the user's scan configuration, Git diff, and report paths.
158
+ * Use the launch directory for local targets and the common parent for targets outside it.
159
+ *
160
+ * @param paths - Scan targets resolved from the launch directory; an empty list selects the launch directory.
161
+ * @returns The launch directory or a common ancestor. A lone missing external target uses its parent so JSON can name the missing file.
162
+ * @throws When targets cannot share a filesystem root.
163
+ */
164
+ export function projectRootFromTargets(paths: string[]): string {
165
+ const launchDirectory = cwd();
166
+
167
+ // No target was named, so the directory the command ran from is the project.
168
+ if (paths.length === 0) {
169
+ return launchDirectory;
170
+ }
171
+
172
+ let common: string | null = null;
173
+ // A later usable target can widen the common directory because the root must contain every usable target.
174
+ for (const path of paths) {
175
+ const absolute = resolve(launchDirectory, path);
176
+ let directory = absolute;
177
+ try {
178
+ // A file contributes its containing directory because reported paths need a directory anchor.
179
+ if (!statSync(absolute).isDirectory()) {
180
+ directory = dirname(absolute);
181
+ }
182
+ } catch {
183
+ // A typo such as `analyse ../app/mising.ts` keeps a project-relative diagnostic. A missing file in a list cannot move its root.
184
+ if (paths.length !== 1) {
185
+ continue;
186
+ }
187
+ directory = dirname(absolute);
188
+ }
189
+
190
+ // The first target sets the starting answer; later ones can only widen it.
191
+ if (common === null) {
192
+ common = directory;
193
+ continue;
194
+ }
195
+ // Expand the root until all usable targets can share one project-relative report.
196
+ while (!isSameOrDescendant(directory, common)) {
197
+ const parent = dirname(common);
198
+ // Reaching a filesystem root without containing this target means no single root can anchor both paths.
199
+ if (parent === common) {
200
+ throw new Error("scan targets do not share a filesystem root");
201
+ }
202
+ common = parent;
203
+ }
204
+ }
205
+
206
+ // Keep the launch directory when no target was usable or their shared root is inside it, preserving config and baseline anchoring.
207
+ if (common === null || isSameOrDescendant(common, launchDirectory)) {
208
+ return launchDirectory;
209
+ }
210
+ return common;
211
+ }
212
+
213
+ /**
214
+ * Invariant: explicit paths keep their launch-directory meaning when a target selects a different project root.
215
+ * For example, `analyse ../app --baseline reviewed.json` still reads `reviewed.json` from the launch directory.
216
+ *
217
+ * @param options - Scan options with paths from the command line. Omitted baseline and history options stay omitted.
218
+ * @returns The original options for a local scan, or a copy with absolute targets and baseline and history paths pointing to the same files.
219
+ */
220
+ function targetsFromLaunchDirectory(options: AnalysisOptions): AnalysisOptions {
221
+ const launchDirectory = cwd();
222
+ const projectRoot = projectRootFromTargets(options.paths);
223
+ // Inside the launch directory the root and the operands already agree, so they are passed on exactly as typed.
224
+ if (projectRoot === launchDirectory) {
225
+ return options;
226
+ }
227
+ /**
228
+ * Re-anchor a launch-directory path option against projectRoot while keeping absolute paths untouched.
229
+ *
230
+ * @param path - file path supplied relative to launchDirectory or as an absolute path
231
+ * @returns Path unchanged when absolute, or relative to projectRoot when resolved from launchDirectory.
232
+ */
233
+ const fromRoot = (path: string): string => (isAbsolute(path) ? path : relative(projectRoot, resolve(launchDirectory, path)));
234
+ // Keep a relative CLI `--profile` file path anchored to the launch directory, while leaving built-in profile names untouched.
235
+ const anchoredProfile = options.profile !== undefined && !BUILT_IN_PROFILES.has(options.profile) && !BUILT_IN_PROFILES.has(`gruff.${options.profile}`)
236
+ ? fromRoot(options.profile)
237
+ : options.profile;
238
+ return {
239
+ ...options,
240
+ paths: options.paths.map((path) => resolve(launchDirectory, path)),
241
+ ...(anchoredProfile !== undefined ? { profile: anchoredProfile } : {}),
242
+ ...(options.baseline ? { baseline: fromRoot(options.baseline) } : {}),
243
+ ...(options.generateBaseline ? { generateBaseline: fromRoot(options.generateBaseline) } : {}),
244
+ ...(options.migrateBaseline ? { migrateBaseline: fromRoot(options.migrateBaseline) } : {}),
245
+ ...(options.historyFile ? { historyFile: fromRoot(options.historyFile) } : {}),
246
+ };
247
+ }
248
+
249
+ /**
250
+ * Check whether a target is inside a launch or scan directory using native path separators.
251
+ * Use this before accepting multiple targets so `/work/apidocs` is treated as a sibling of `/work/api`.
252
+ *
253
+ * @param candidate - Directory being tested.
254
+ * @param ancestor - Directory that may contain it.
255
+ * @returns True when candidate is the ancestor or sits inside it.
256
+ */
257
+ function isSameOrDescendant(candidate: string, ancestor: string): boolean {
258
+ const fromAncestor = relative(ancestor, candidate);
259
+ return !isAbsolute(fromAncestor) && fromAncestor !== ".." && !fromAncestor.startsWith(`..${sep}`);
260
+ }
261
+
262
+ /**
263
+ * Resolve project inputs and configuration needed before scanning files.
264
+ *
265
+ * @param options - scan options specifying target paths, config overrides, and discovery settings
266
+ * @returns The project root, loaded config, discovered inputs, and an empty diagnostic array selected by options for a scan.
267
+ */
78
268
  function prepareAnalysis(options: AnalysisOptions): AnalysisPreparation {
79
- const projectRoot = cwd();
269
+ const projectRoot = projectRootFromTargets(options.paths);
80
270
  const config = loadConfig(projectRoot, options);
81
271
  const diagnostics: RunDiagnostic[] = [];
82
272
  const discovery = discoverSources(projectRoot, options, config);
83
273
  return { projectRoot, config, diagnostics, discovery };
84
274
  }
85
275
 
86
- // Runs per-file and project-level rules before applying baseline suppression; finding order remains stable.
87
- function completeAnalysis(preparation: AnalysisPreparation, options: AnalysisOptions): AnalysisRun {
276
+ /**
277
+ * Give a finding its rule's catalogue confidence, so list-rules, the hook gate and the score read one value. A rule helper's
278
+ * default must not override the catalogue. The fingerprint and stable identity do not include confidence, so both stay unchanged.
279
+ *
280
+ * @param finding - scanner result for a rule the catalogue normally lists
281
+ * @returns the same finding when its confidence already matches, a copy carrying the catalogue confidence otherwise, or the
282
+ * finding unchanged for a rule id the catalogue does not list
283
+ */
284
+ function withCatalogueConfidence(finding: Finding): Finding {
285
+ const confidence = catalogueConfidence(finding.ruleId);
286
+ return confidence === undefined || confidence === finding.confidence ? finding : { ...finding, confidence };
287
+ }
288
+
289
+ /**
290
+ * Run the checks for the user's resolved project and apply its exclusions and baseline.
291
+ * Invariant: assign baseline identities before filtering so the hook and SARIF can refer to the same finding.
292
+ *
293
+ * @param preparation - project scope, discovery and config, with the caller's diagnostic array to append to
294
+ * @param options - scope and baseline choices. An unset baseline path lets the scan use the project's default when enabled.
295
+ * @param unusableBaseline - `throw` lets the hook report a refusal. `diagnose` keeps findings and adds a fatal baseline diagnostic.
296
+ * @param changedScope - optional changed-region scope indicating which files need retained source and AST snapshots for symbol expansion
297
+ * @returns Findings, diagnostics, and suppression counts for rendering. An empty findings list can still have diagnostics.
298
+ * @throws {BaselineFileError} - a baseline file failure in throw mode.
299
+ */
300
+ function completeAnalysis(
301
+ preparation: AnalysisPreparation,
302
+ options: AnalysisOptions,
303
+ unusableBaseline: "throw" | "diagnose" = "throw",
304
+ changedScope?: ChangedRegionScope,
305
+ ): AnalysisRun {
88
306
  const { projectRoot, config, diagnostics, discovery } = preparation;
89
307
  pushMissingPathDiagnostics(discovery.missingPaths, diagnostics);
90
308
 
91
- const scanned = scanDiscoveredSources(discovery.files, config, diagnostics);
309
+ const scanned = scanDiscoveredSources(discovery.files, config, diagnostics, changedScope);
92
310
  const allFindings = sortedUniqueFindings([
93
311
  ...scanned.findings,
94
312
  ...analyseProjectIndex(projectRoot, options, discovery.files, scanned.projectSources, config).filter((finding) => ruleEnabled(config, finding.ruleId)),
95
- ]);
96
- const baselineResult = applyBaselineOptions(projectRoot, options, allFindings);
313
+ ].map((finding) => applyConfiguredSeverity(config, withCatalogueConfidence(finding))));
314
+ // An approved sensitive exclusion removes the finding from the report and gate, but its audit count still covers the full scan.
315
+ const excluded = partitionSensitiveExclusions(allFindings, config.sensitiveExclusions);
316
+ // A configured entry claims its findings first, so its count stays what the user wrote it for.
317
+ const testPathSkipped = applyBuiltInTestPathSkip(excluded.findings, excluded.suppressions);
318
+ // Assign baseline identities before filtering so hiding one declaration cannot renumber another in SARIF or the hook.
319
+ const spans = scanned.declarationSpans;
320
+ const namedFindings = withBaselineIdentities(testPathSkipped.findings, spans);
321
+ // Apply inline suppressions to findings with identities so SARIF can still identify a suppressed result.
322
+ const inline = applyInlineSuppressions(namedFindings, testPathSkipped.suppressions, scanned.sources);
323
+ // A missing file or parse error makes `--generate-baseline` unsafe because it would save a partial review.
324
+ const baselineResult = options.generateBaseline && diagnostics.some((diagnostic) => diagnostic.invalidatesRun !== false)
325
+ ? { findings: inline.findings, diagnostics: [] }
326
+ : applyBaselineOptions(projectRoot, options, inline.findings, spans, unusableBaseline);
327
+ // A baseline collision records a non-fatal diagnostic and leaves every finding with that identity visible.
328
+ diagnostics.push(...baselineResult.diagnostics);
97
329
  const notes = [...discovery.notes, ...scanned.notes];
98
- return { projectRoot, discovery, diagnostics, scanned, baselineResult, notes };
330
+ // A selective scan scores only pillars backed by enabled rules. Omitting selectors keeps the normal score denominator.
331
+ const evaluatedPillars = options.execution && isExecutionRequested(options.execution)
332
+ ? ruleDescriptors().filter((rule) => ruleEnabled(config, rule.ruleId)).map((rule) => rule.pillar)
333
+ : undefined;
334
+ return { projectRoot, discovery, diagnostics, scanned, baselineResult, notes, evaluatedPillars, suppressions: inline.suppressions, suppressedFindings: inline.suppressed };
99
335
  }
100
336
 
101
- // Converts a completed run into a stable report contract or changed-region projection.
337
+ /**
338
+ * Builds the analysis report from the findings selected for this command.
339
+ * Invariant: suppression audit counts cover the full scan, even when the report shows only the requested changes.
340
+ *
341
+ * @param run - completed scan supplying discovery totals, diagnostics, notes and suppression records
342
+ * @param options - request inputs and threshold. No explicit inputs are shown as "." for a project scan.
343
+ * @param baselineResult - the selected findings and any baseline details. No baseline leaves out the review section.
344
+ * @param suppressedCount - number of findings omitted by changed-region filtering. Omit it to leave the field out of the report.
345
+ * @returns Native report state with the supplied findings, scan totals, and any baseline or changed-region count supplied.
346
+ */
102
347
  function reportFromRun(run: AnalysisRun, options: AnalysisOptions, baselineResult: BaselineApplication, suppressedCount?: number): AnalysisReport {
103
- return buildAnalysisReport(run.projectRoot, options, run.discovery, run.diagnostics, baselineResult, run.notes, suppressedCount);
104
- }
105
-
106
- function buildAnalysisReport(
107
- projectRoot: string,
108
- options: AnalysisOptions,
109
- discovery: DiscoverySummary,
110
- diagnostics: RunDiagnostic[],
111
- baselineResult: BaselineApplication,
112
- notes: ScanSurfaceNote[],
113
- suppressedCount?: number,
114
- ): AnalysisReport {
115
348
  const findings = baselineResult.findings;
116
349
  return {
117
- schemaVersion: "gruff.analysis.v2",
350
+ schemaVersion: "gruff.analysis.v3",
118
351
  tool: { name: "gruff-ts", version: VERSION },
119
352
  run: {
120
- projectRoot,
353
+ projectRoot: run.projectRoot,
121
354
  format: options.format,
122
355
  failOn: options.failOn,
123
356
  generatedAt: new Date().toISOString(),
357
+ // Record explicit inputs as absolute paths so they keep their launch-directory meaning if the project root differs.
358
+ // With no explicit input, a single dot denotes the default project scan.
359
+ inputs: options.paths.length === 0 ? ["."] : options.paths.map((path) => resolve(cwd(), path)),
360
+ ...(options.config === undefined ? {} : { config: resolve(cwd(), options.config) }),
361
+ ...(options.shouldIncludeIgnored ? { includeIgnored: true as const } : {}),
124
362
  },
125
363
  summary: summarize(findings),
126
364
  paths: {
127
- analysedFiles: discovery.files.length,
128
- ignoredPaths: discovery.ignoredPaths,
129
- skipped: discovery.skipped,
130
- missingPaths: discovery.missingPaths,
365
+ analysedFiles: run.discovery.files.length,
366
+ ignoredPaths: run.discovery.ignoredPaths,
367
+ skipped: run.discovery.skipped,
368
+ missingPaths: run.discovery.missingPaths,
131
369
  },
132
- diagnostics,
133
- ...(notes.length === 0 ? {} : { notes }),
370
+ diagnostics: run.diagnostics,
371
+ ...(run.notes.length === 0 ? {} : { notes: run.notes }),
372
+ suppressions: run.suppressions,
373
+ suppressedFindings: run.suppressedFindings,
134
374
  findings,
135
375
  ...(suppressedCount === undefined ? {} : { suppressedCount }),
136
- score: scoreReport(findings),
376
+ // Score uses evaluated script files. The analysed file count also includes text assets that received raw-text checks.
377
+ score: scoreReport(findings, run.scanned.evaluatedFiles, run.evaluatedPillars),
137
378
  ...(baselineResult.baseline ? { baseline: baselineResult.baseline } : {}),
138
379
  };
139
380
  }
140
381
 
382
+ // The type every port publishes when it cannot load the configuration it was given.
383
+ export const CONFIG_ERROR_DIAGNOSTIC_TYPE = "config-error";
384
+
385
+ // The type every port publishes when it refuses the targets it was given, such as several outside the launch directory.
386
+ export const TARGET_ERROR_DIAGNOSTIC_TYPE = "target-error";
387
+
388
+ /**
389
+ * Identify a multi-target request that violates the launch-directory boundary so the caller can refuse it before reporting.
390
+ * A single external target is allowed; every target in a multi-target request must stay inside the launch directory.
391
+ *
392
+ * @param paths - Scan targets resolved from the launch directory for this boundary check.
393
+ * @returns The first outside target in a multi-target request, or null when no request boundary is violated.
394
+ */
395
+ export function targetOutsideLaunchDirectory(paths: string[]): string | null {
396
+ // A single target, or none, always has a root the run can report against.
397
+ if (paths.length < 2) {
398
+ return null;
399
+ }
400
+ const launchDirectory = cwd();
401
+ // Multi-target requests are refused as soon as any operand lies outside the launch directory.
402
+ return paths.find((path) => !isSameOrDescendant(resolve(launchDirectory, path), launchDirectory)) ?? null;
403
+ }
404
+
405
+ /**
406
+ * Build a stable gruff.analysis.v3 report for a run refused before discovery so machine consumers can read the failure.
407
+ *
408
+ * @param projectRoot - project path to record for the refused run
409
+ * @param format - requested output format to record in run metadata
410
+ * @param diagnosticType - category that identifies why the run was refused
411
+ * @param message - explanation to include in the diagnostic
412
+ * @returns A report with one run diagnostic, zero analysed files and no findings.
413
+ */
414
+ export function failedRunReport(projectRoot: string, format: OutputFormat, diagnosticType: string, message: string): AnalysisReport {
415
+ return {
416
+ schemaVersion: "gruff.analysis.v3",
417
+ tool: { name: "gruff-ts", version: VERSION },
418
+ // Use the analyse default threshold because the caller handles the refusal status separately.
419
+ run: { projectRoot, format, failOn: "advisory", generatedAt: new Date().toISOString() },
420
+ summary: summarize([]),
421
+ paths: { analysedFiles: 0, ignoredPaths: [], skipped: [], missingPaths: [] },
422
+ diagnostics: [{ diagnosticType, message }],
423
+ suppressions: [],
424
+ findings: [],
425
+ score: scoreReport([], 0),
426
+ };
427
+ }
428
+
141
429
  // Subset of discovery output that survives diff filtering. Held as its own type so the diff
142
430
  // filter can mutate `files` in place without exposing the whole `SourceDiscoveryResult` shape.
143
431
  interface DiscoverySummary {
@@ -150,11 +438,13 @@ interface DiscoverySummary {
150
438
 
151
439
  // Output of the per-file scan pass - both the findings produced and the cached source bodies that
152
440
  // later project-level rules need to operate against the deterministic stable shape used by baselines.
153
- // Contract invariant: `notes` records bounded deep scans without changing finding order.
441
+ // Contract invariant: `notes` records non-text scan-surface changes without changing finding order.
154
442
  interface SourceScanResult {
155
443
  findings: Finding[];
444
+ evaluatedFiles: number;
156
445
  projectSources: ProjectSource[];
157
- sources: Map<string, { file: SourceFile; source: string }>;
446
+ sources: Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>;
447
+ declarationSpans: Map<string, DeclarationSpan[]>;
158
448
  notes: ScanSurfaceNote[];
159
449
  }
160
450
 
@@ -167,19 +457,31 @@ interface AnalysisPreparation {
167
457
  discovery: DiscoverySummary;
168
458
  }
169
459
 
170
- // Completed scan state before final report rendering. The baseline result is carried separately so
171
- // changed-region filtering can project findings without losing baseline metadata.
460
+ // Completed scan state before final report rendering. Stable contract: the baseline result is
461
+ // carried separately so changed-region filtering can project findings without losing baseline
462
+ // metadata, and the suppression rows stay whole-scan counts rather than a projection of them.
172
463
  interface AnalysisRun {
173
464
  projectRoot: string;
174
465
  discovery: DiscoverySummary;
175
466
  diagnostics: RunDiagnostic[];
176
467
  scanned: SourceScanResult;
468
+ evaluatedPillars: Pillar[] | undefined;
177
469
  baselineResult: BaselineApplication;
178
470
  notes: ScanSurfaceNote[];
471
+ // Configured sensitive-exclusion rows, then built-in test-path and section 13c rows, counted over the full scan
472
+ // so a changed-region projection cannot understate what a suppression actually hid.
473
+ suppressions: SuppressionSummary[];
474
+ // Findings section 13c removed, kept so SARIF can show each as suppressed.
475
+ suppressedFindings: SuppressedFinding[];
179
476
  }
180
477
 
181
- // Emits a `missing-path` diagnostic per path that the user requested but discovery could not
182
- // resolve. Diagnostics force a non-zero exit (see `exitFor`); never throws - partial scans should still report.
478
+ /**
479
+ * Record a run-invalidating diagnostic for every unresolved target path so callers report missing inputs.
480
+ *
481
+ * @param missingPaths - requested target paths that discovery could not resolve
482
+ * @param diagnostics - caller's diagnostic array mutated by appending one missing-path entry per item
483
+ * @returns Nothing. Appends one diagnostic per missing path to diagnostics, forcing exit 2; an empty list adds nothing.
484
+ */
183
485
  function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiagnostic[]): void {
184
486
  for (const missingPath of missingPaths) {
185
487
  diagnostics.push({
@@ -190,31 +492,73 @@ function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiag
190
492
  }
191
493
  }
192
494
 
193
- /*
194
- * Per-file read + scan loop. Reports read failures as diagnostics because CLI users need partial
195
- * results from the rest of the tree, but the stable discovered-file order still feeds project-index
196
- * snapshots before the final canonical sort. Changing that contract can churn graph-rule anchors.
495
+ /**
496
+ * Read and scan inputs in stable discovery order so that project-index snapshots keep their graph anchors.
497
+ * Record failures caught during a file's read or scan as read-error diagnostics so the remaining files can still be checked.
498
+ * Computes declaration spans per file so parsed syntax trees can be garbage-collected immediately on large repositories.
499
+ *
500
+ * @param files - discovered inputs in a stable order. An empty list leaves the scan with no files to score.
501
+ * @param config - scan budget, rule settings and project-source selection settings
502
+ * @param diagnostics - caller's array for budget, parser and caught file-scan diagnostics
503
+ * @param changedScope - optional changed-region scope naming files that must retain source and parsed ASTs after per-file analysis
504
+ * @returns Findings, retained project snapshots, minimal retained sources, per-file declaration spans, and notes for skipped non-text inputs.
197
505
  */
198
- function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics: RunDiagnostic[]): SourceScanResult {
506
+ function scanDiscoveredSources(
507
+ files: SourceFile[],
508
+ config: Config,
509
+ diagnostics: RunDiagnostic[],
510
+ changedScope?: ChangedRegionScope,
511
+ ): SourceScanResult {
199
512
  const findings: Finding[] = [];
513
+ let evaluatedFiles = 0;
200
514
  const projectSources: ProjectSource[] = [];
201
- const sources = new Map<string, { file: SourceFile; source: string }>();
515
+ const sources = new Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>();
516
+ const spansByFile = new Map<string, DeclarationSpan[]>();
202
517
  const notes: ScanSurfaceNote[] = [];
518
+ // Check each supported input so one unreadable file can be diagnosed without discarding the other files' findings.
203
519
  for (const file of files) {
204
520
  try {
205
- const source = readFileSync(file.absolutePath, "utf8");
206
- sources.set(file.displayPath, { file, source });
207
- const budgetNote = deepScanBudgetNote(file, source);
208
- if (budgetNote) {
209
- notes.push(budgetNote);
521
+ const fileBytes = readFileSync(file.absolutePath);
522
+ // Non-text bytes cannot produce trustworthy findings; the note explains why the file was skipped.
523
+ if (!isUtf8(fileBytes) || fileBytes.includes(0)) {
524
+ notes.push({
525
+ noteType: "non-text-file",
526
+ path: file.displayPath,
527
+ message: "File was skipped before parsing because it contains invalid UTF-8 or NUL bytes.",
528
+ });
529
+ continue;
530
+ }
531
+ const source = fileBytes.toString("utf8");
532
+ const budgetDiagnostic = deepScanBudgetDiagnostic(file, source, config);
533
+ // Over-budget scripts skip parsing and project snapshots but still get enabled text checks. Other scripts share one parse.
534
+ const parsed = budgetDiagnostic ? undefined : parseScript(file, source);
535
+ // The user can still see text findings from a script that exceeds the deep-scan budget.
536
+ if (budgetDiagnostic) {
537
+ diagnostics.push(budgetDiagnostic);
210
538
  } else {
539
+ // Retain files that can contribute to cross-file findings such as import cycles.
211
540
  if (shouldRetainProjectSource(file, source)) {
212
- projectSources.push(projectSource(file, source));
541
+ projectSources.push(projectSource(file, source, parsed));
542
+ }
543
+ if (parsed) {
544
+ spansByFile.set(file.displayPath, fileDeclarationSpans(source, parsed));
213
545
  }
214
- diagnostics.push(...parseDiagnostics(file, source));
546
+ diagnostics.push(...(parsed?.diagnostics ?? []));
547
+ }
548
+ const fileFindings = analyseSource(file, source, config, budgetDiagnostic === undefined, parsed);
549
+ findings.push(...fileFindings);
550
+ // Retain full AST snapshots only for files needed by changed-region symbol expansion, and raw text only when inline suppression applies.
551
+ if (shouldRetainParsedForChangedScope(file.displayPath, changedScope)) {
552
+ sources.set(file.displayPath, { file, source, ...(parsed ? { parsed } : {}) });
553
+ } else if (fileFindings.some((entry) => isInlineSuppressionRelevantRule(entry.ruleId))) {
554
+ sources.set(file.displayPath, { file, source });
555
+ }
556
+ // Text assets can produce findings, but only evaluated scripts contribute to the file count used for scoring.
557
+ if (file.isScript) {
558
+ evaluatedFiles += 1;
215
559
  }
216
- findings.push(...analyseSource(file, source, config, budgetNote === undefined));
217
560
  } catch (error) {
561
+ // A file deleted during the scan produces a diagnostic. Findings from other files remain available.
218
562
  diagnostics.push({
219
563
  diagnosticType: "read-error",
220
564
  message: `Unable to read file: ${String(error)}`,
@@ -223,76 +567,205 @@ function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics:
223
567
  });
224
568
  }
225
569
  }
226
- return { findings, projectSources, sources, notes };
570
+ return { findings, evaluatedFiles, projectSources, sources, declarationSpans: spansByFile, notes };
571
+ }
572
+
573
+ /**
574
+ * Reports whether a file's source and parsed syntax tree must stay cached after per-file analysis for changed-region symbol expansion.
575
+ *
576
+ * @param filePath - project-relative display path of the scanned file
577
+ * @param changedScope - optional changed-region scope active for this run
578
+ * @returns True when `changedScope` uses explicit ranges or lists `filePath` as a changed file; false for full scans and untouched files.
579
+ */
580
+ function shouldRetainParsedForChangedScope(filePath: string, changedScope: ChangedRegionScope | undefined): boolean {
581
+ if (changedScope === undefined) {
582
+ return false;
583
+ }
584
+ return changedScope.explicitRanges !== undefined || changedScope.changedFiles.has(filePath);
585
+ }
586
+
587
+ /**
588
+ * Attach baseline identities and subjects before filtering so that SARIF and baseline matching share the same stable fingerprint identity.
589
+ *
590
+ * @param findings - findings to name together before any reporting view narrows the list
591
+ * @param spansByFile - parsed declaration spans used to assign positions and ordinals
592
+ * @returns A new array in input order. Findings with identities gain native identity and subject fields, and unnamed findings stay unchanged.
593
+ */
594
+ function withBaselineIdentities(findings: Finding[], spansByFile: Map<string, DeclarationSpan[]>): Finding[] {
595
+ const identities = findingIdentities(findings, declarationPositionFromSpans(spansByFile));
596
+ return findings.map((finding, index) => {
597
+ const named = identities[index];
598
+ // Publishing the subject beside the identity is what lets the hook state the ordinal instead of re-deriving it.
599
+ return named === undefined ? finding : { ...finding, baselineIdentity: named.identity, baselineSubject: named.subject };
600
+ });
601
+ }
602
+
603
+ /**
604
+ * Collects declaration spans for one parsed script so a baseline can distinguish same-named functions in one file
605
+ * without keeping the full TypeScript AST alive across the entire repository scan.
606
+ *
607
+ * @param source - raw UTF-8 source text of the script
608
+ * @param parsed - shared parsed syntax tree for the script
609
+ * @returns Declaration spans covering named functions, methods, callable bindings, and measured-only inline callables.
610
+ */
611
+ function fileDeclarationSpans(source: string, parsed: ParsedScript): DeclarationSpan[] {
612
+ const blocks = functionBlocks(source, source, parsed);
613
+ // Keep positions for measured inline functions too, so two functions named `<iife>` can have separate baseline entries.
614
+ const measuredOnly = measuredOnlyFunctionBlocks(source, maskNonCode(source), parsed);
615
+ return keepColumnsOnSharedLines([...blocks, ...measuredOnly].map((block) => blockDeclarationSpan(block, parsed)));
616
+ }
617
+
618
+ /**
619
+ * Drops column bounds from every span that shares no line with a same-named span, so ordinary declarations keep line-only baseline positions.
620
+ * Only two functions with one name on one line, such as `[{ run: () => 1 }, { run: () => 2 }]`, need columns to keep separate entries.
621
+ *
622
+ * @param spans - every declaration span found in one file, possibly carrying start and end columns
623
+ * @returns The same spans in order; columns survive only where a same-named span starts or ends on a shared line
624
+ */
625
+ function keepColumnsOnSharedLines(spans: DeclarationSpan[]): DeclarationSpan[] {
626
+ const spansByName = new Map<string, DeclarationSpan[]>();
627
+ for (const span of spans) {
628
+ spansByName.set(span.name, [...(spansByName.get(span.name) ?? []), span]);
629
+ }
630
+ return spans.map((span) => {
631
+ const spanLines = [span.startLine, span.endLine];
632
+ const sharesLine = (spansByName.get(span.name) ?? []).some((other) => other !== span
633
+ && (spanLines.includes(other.startLine) || spanLines.includes(other.endLine)));
634
+ // Two same-named declarations sharing a line keep their columns so each gets its own baseline entry.
635
+ if (sharesLine) {
636
+ return span;
637
+ }
638
+ // A declaration alone on its lines is told apart by line alone, so dropping columns keeps existing baseline entries stable.
639
+ const { startColumn: _startColumn, endColumn: _endColumn, ...lineOnly } = span;
640
+ return lineOnly;
641
+ });
642
+ }
643
+
644
+ /**
645
+ * Builds the baseline span for one function, adding 1-based start and end columns when the syntax tree has them.
646
+ * Columns keep two same-named functions on one line apart, so each keeps its own baseline entry.
647
+ *
648
+ * @param block - discovered function or callable block; when `callableNode` is absent, only line bounds are returned
649
+ * @param parsed - shared parsed syntax tree owning the block's AST offsets
650
+ * @returns Declaration span with line bounds, plus 1-based start/end columns when `callableNode` is present.
651
+ */
652
+ function blockDeclarationSpan(block: FunctionBlock, parsed: ParsedScript): DeclarationSpan {
653
+ const endLine = block.startLine + block.lineCount - 1;
654
+ const span: DeclarationSpan = { name: block.name, startLine: block.startLine, endLine };
655
+ // A block found without a syntax node keeps line-only bounds, so its baseline entry is ranked by line alone.
656
+ if (block.callableNode === undefined) {
657
+ return span;
658
+ }
659
+ const anchorNode = declarationAnchorNode(block.callableNode);
660
+ const startPos = parsed.sourceFile.getLineAndCharacterOfPosition(anchorNode.getStart(parsed.sourceFile));
661
+ const endPos = parsed.sourceFile.getLineAndCharacterOfPosition(block.callableNode.getEnd());
662
+ // Preserve column precision when the declaration starts on the span's own opening line; leading JSDoc/decorators begin at column 1.
663
+ span.startColumn = startPos.line + 1 === block.startLine ? startPos.character + 1 : 1;
664
+ // Record the end column only when the syntax node ends on the block's last line, so a mismatch never narrows the span.
665
+ if (endPos.line + 1 === endLine) {
666
+ // The syntax node's end is just past its last character, so that offset is already the last character's 1-based column.
667
+ span.endColumn = endPos.character;
668
+ }
669
+ return span;
227
670
  }
228
671
 
229
- // Scan budget for deep (masking, block-parsing, AST-walking) script analysis. Copied perf-test
230
- // fixtures of 100k+ lines time out whole scans, so files above either bound keep text-level rules.
231
- const DEEP_SCAN_MAX_LINES = 20_000; // Budget limit: bounds copied perf fixtures before deep passes.
232
- const DEEP_SCAN_MAX_BYTES = 2_000_000; // Budget limit: catches minified/long-line scripts too.
672
+ /**
673
+ * Widens an arrow or function expression to the variable or property it is assigned to.
674
+ * Findings reported on that name then still fall inside the function's span.
675
+ *
676
+ * @param callableNode - parsed AST node for the callable body
677
+ * @returns The owning variable/property declaration node when it directly wraps `callableNode`, otherwise `callableNode`.
678
+ */
679
+ function declarationAnchorNode(callableNode: import("typescript").Node): import("typescript").Node {
680
+ const parent = callableNode.parent;
681
+ // A function assigned to a variable or property starts at its name, which is where findings about it are reported.
682
+ if (parent !== undefined && "initializer" in parent && parent.initializer === callableNode) {
683
+ return parent;
684
+ }
685
+ return callableNode;
686
+ }
233
687
 
234
- // Returns the bounded-deep-scan note when a script file exceeds the budget, undefined otherwise.
235
- // The file still counts as analysed - silence is the failure mode this guard exists to remove.
236
- function deepScanBudgetNote(file: SourceFile, source: string): ScanSurfaceNote | undefined {
237
- if (!file.isScript) {
688
+ /**
689
+ * Check whether a script exceeds the configured line or byte limits for deep syntax analysis.
690
+ *
691
+ * @param file - candidate input whose script classification and display path guide budget enforcement
692
+ * @param source - UTF-8 source text measured for line count and byte length
693
+ * @param config - scan configuration supplying deepScanBudget thresholds and enabled state
694
+ * @returns A non-fatal diagnostic requesting skipped deep checks, or undefined for non-scripts,
695
+ * a disabled budget, or sources within both limits.
696
+ */
697
+ function deepScanBudgetDiagnostic(file: SourceFile, source: string, config: Config): RunDiagnostic | undefined {
698
+ const budget = config.deepScanBudget;
699
+ if (!file.isScript || !budget.enabled) {
238
700
  return undefined;
239
701
  }
240
702
  const lines = lineCount(source);
241
703
  const bytes = Buffer.byteLength(source, "utf8");
242
- if (lines <= DEEP_SCAN_MAX_LINES && bytes <= DEEP_SCAN_MAX_BYTES) {
704
+ if (lines <= budget.maxLines && bytes <= budget.maxBytes) {
243
705
  return undefined;
244
706
  }
245
707
  return {
246
- noteType: "bounded-deep-scan",
247
- path: file.displayPath,
248
- message: `File exceeds the deep-scan budget (${lines} lines, ${bytes} bytes; limits ${DEEP_SCAN_MAX_LINES} lines / ${DEEP_SCAN_MAX_BYTES} bytes). Text-level rules (size, sensitive-data, config) still ran; deep script analysis was skipped.`,
708
+ diagnosticType: "bounded-deep-scan",
709
+ filePath: file.displayPath,
710
+ line: 1,
711
+ invalidatesRun: false,
712
+ message: `path=${file.displayPath}; lines=${lines}; bytes=${bytes}; maxLines=${budget.maxLines}; maxBytes=${budget.maxBytes}; override=${budget.override}. Text-level rules (size, sensitive-data, config) still ran; masking, block parsing, AST walking, and other deep script analysis were skipped.`,
249
713
  };
250
714
  }
251
715
 
252
- // Retains production files for exported-surface checks, tests for central-suite import coverage,
253
- // and import/export candidates for graph edges. Dropping any class here makes a project rule blind.
716
+ /**
717
+ * Decide whether a scanned file belongs in the project index for exported-surface, test-coverage, and graph rules.
718
+ *
719
+ * @param file - discovered file providing script classification and display path
720
+ * @param source - file text inspected for potential import or export syntax candidates
721
+ * @returns True for script files that are production code, tests, or import/export candidates; false for non-scripts or unrelated scripts.
722
+ */
254
723
  function shouldRetainProjectSource(file: SourceFile, source: string): boolean {
255
724
  return file.isScript && (isProductionSourcePath(file.displayPath) || isTestPath(file.displayPath) || hasImportSyntaxCandidate(source));
256
725
  }
257
726
 
258
- // Stores the raw line view and, only when needed, a template-masked line view. The conditional mask
259
- // avoids paying lexer cost for files that cannot affect import edges while keeping fixtures invisible.
260
- function projectSource(file: SourceFile, source: string): ProjectSource {
261
- const lines = source.split(/\r?\n/);
262
- const templateMaskedLines = hasImportSyntaxCandidate(source) ? maskTemplateLiteralBodies(source).split(/\r?\n/) : lines;
263
- return { file, lines, templateMaskedLines };
727
+ /**
728
+ * Build compact project-index data for a retained script, pre-extracting import statements from template-masked lines
729
+ * so template fixture text cannot become graph edges and large scans do not retain full file line arrays.
730
+ *
731
+ * @param file - retained source file metadata
732
+ * @param source - raw UTF-8 source text scanned for import statements and code lines
733
+ * @param parsed - optional script parse used to exclude decorator text from the code-line count; without it, decorator-only lines count
734
+ * @returns Compact ProjectSource carrying pre-extracted import statements and substantive code-line count.
735
+ */
736
+ function projectSource(file: SourceFile, source: string, parsed?: ParsedScript): ProjectSource {
737
+ const statements = hasImportSyntaxCandidate(source) ? extractImportStatements(maskTemplateLiteralBodies(source).split(/\r?\n/)) : [];
738
+ return { file, importStatements: statements, codeLineCount: codeLineFlags(source, parsed).filter(Boolean).length };
264
739
  }
265
740
 
266
- // Cheap prefilter for files that might contain real import/export edges or fixture strings that
267
- // mention them. False positives are acceptable; false negatives would drop graph edges.
741
+ /**
742
+ * Cheap prefilter for files that might contain real import/export edges or fixture strings that mention them.
743
+ * False positives are acceptable; false negatives would drop graph edges.
744
+ *
745
+ * @param source - raw source text checked for import or from substrings
746
+ * @returns True when source contains `import` or `from`; false otherwise.
747
+ */
268
748
  function hasImportSyntaxCandidate(source: string): boolean {
269
749
  return source.includes("import") || source.includes("from");
270
750
  }
271
751
 
272
- // Canonical finding ordering: (filePath, line, ruleId, message). The same tuple is part of the
273
- // stable baseline matching contract, so changing the comparator would churn every existing baseline.
274
- function sortedUniqueFindings(findings: Finding[]): Finding[] {
275
- findings.sort(
276
- (left, right) =>
277
- left.filePath.localeCompare(right.filePath) ||
278
- (left.line ?? 0) - (right.line ?? 0) ||
279
- left.ruleId.localeCompare(right.ruleId) ||
280
- left.message.localeCompare(right.message),
281
- );
282
- return dedupeFindings(findings);
283
- }
284
-
285
- // Per-file rule pipeline. Text rules run on every file (including config/yaml); TypeScript rules
286
- // run only on scripts within the deep-scan budget. Fixed order is part of the stable fingerprint
287
- // contract. Generated/copied files keep every security and sensitive-data finding but drop
288
- // documentation and naming findings - generated code is not maintainer-authored source, so pushing
289
- // doc/naming work at a human reviewer is unactionable noise.
290
- // Contract invariant: doc/naming skips must not suppress safety pillars or change rule order.
291
- function analyseSource(file: SourceFile, source: string, config: Config, isWithinDeepScanBudget: boolean): Finding[] {
752
+ /**
753
+ * Run the text pass first and preserve stable rule order. Generated sources skip documentation and naming findings to avoid noise.
754
+ *
755
+ * @param file - input path and script classification used by the rule passes
756
+ * @param source - original file text to check and inspect for generated markers
757
+ * @param config - selects rules and supplies their settings
758
+ * @param isWithinDeepScanBudget - allows deeper rules for scripts small enough to scan
759
+ * @param parsed - shared script parse when available for syntax-backed checks
760
+ * @returns Enabled findings in emission order. Generated input retains eligible safety findings under the same filtering contract.
761
+ */
762
+ function analyseSource(file: SourceFile, source: string, config: Config, isWithinDeepScanBudget: boolean, parsed?: ParsedScript): Finding[] {
292
763
  const findings: Finding[] = [];
293
- analyseTextRules(file, source, config, findings);
764
+ // Size and documentation rules share one comment scan so code-only line counts do not add a second pass.
765
+ const comments = file.isScript && (ruleEnabled(config, "size.file-length") || isAnyRuleEnabled(config, COMMENT_QUALITY_RULE_IDS)) ? commentRecords(source) : [];
766
+ analyseTextRules(file, source, comments, config, findings, parsed);
294
767
  if (file.isScript && isWithinDeepScanBudget) {
295
- analyseTypeScriptRules(file, source, config, findings);
768
+ analyseTypeScriptRules(file, source, comments, config, findings, parsed);
296
769
  }
297
770
  const isGenerated = isGeneratedSource(source);
298
771
  return findings.filter((finding) => ruleEnabled(config, finding.ruleId) && !(isGenerated && GENERATED_SKIPPED_PILLARS.has(finding.pillar)));
@@ -303,18 +776,28 @@ function analyseSource(file: SourceFile, source: string, config: Config, isWithi
303
776
  // test-quality...) still applies - a generated file can leak a real credential.
304
777
  const GENERATED_SKIPPED_PILLARS = new Set<Pillar>(["documentation", "naming"]);
305
778
 
306
- // Marker-based generated/copied classification over the file's opening lines. Deliberately
307
- // requires an explicit marker rather than path hints - a `fixtures/` path alone must never change
308
- // rule behaviour, and `isDefaultIgnoredDir` stays the only directory-level exclusion surface.
779
+ /**
780
+ * Marker-based generated or copied classification over the file's opening lines. Deliberately requires an
781
+ * explicit marker rather than path hints so a `fixtures/` path alone must never change rule behaviour,
782
+ * and `classifyIgnore` in discovery.ts stays the only directory-level exclusion surface.
783
+ *
784
+ * @param source - file text whose first 10 lines are tested for generated or copied markers
785
+ * @returns True when any opening line matches a generated or copied header marker; false otherwise.
786
+ */
309
787
  function isGeneratedSource(source: string): boolean {
310
788
  return source.split(/\r?\n/, 10).some((line) => /AUTO-?GENERATED|@generated\b|GENERATED FILE|Code generated|Generated by|DO NOT EDIT|Copied from/i.test(line));
311
789
  }
312
790
 
313
- /*
314
- * Cross-file rule pipeline. Contract invariant: scoped runs keep `paths.analysedFiles` scoped while
315
- * circular-import may build root graph context so cycles through requested files stay visible. It
316
- * swallows hidden root-context read failures in `graphProjectSources` so unrelated unreadable files
317
- * do not break a narrow scan.
791
+ /**
792
+ * Run cross-file checks after per-file analysis. Root graph context keeps cycles through requested files visible while preserving report scope.
793
+ * Unreadable files encountered while gathering root graph context are skipped so a scoped scan can continue.
794
+ *
795
+ * @param projectRoot - root for deciding and discovering circular-import context
796
+ * @param options - requested scope and discovery settings for root context
797
+ * @param scopedFiles - discovered files whose paths define which root cycles to keep
798
+ * @param projectSources - scanned source snapshots for the scoped project index
799
+ * @param config - enables cross-file rules and supplies their settings
800
+ * @returns Cross-file findings under the scoped reporting contract, or an empty list if no pass runs or produces a finding.
318
801
  */
319
802
  function analyseProjectIndex(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[], projectSources: ProjectSource[], config: Config): Finding[] {
320
803
  const shouldUseRootCircularContext = ruleEnabled(config, CIRCULAR_IMPORT_RULE_ID) && shouldBuildRootCircularContext(projectRoot, options, scopedFiles);
@@ -334,16 +817,21 @@ function analyseProjectIndex(projectRoot: string, options: AnalysisOptions, scop
334
817
  }
335
818
 
336
819
  const PROJECT_INDEX_RULE_IDS = [
337
- "design.deep-relative-import",
338
820
  CIRCULAR_IMPORT_RULE_ID,
339
821
  "design.large-module-concentration",
340
822
  ] as const;
341
823
  const SCOPED_PROJECT_INDEX_RULE_IDS = [
342
- "design.deep-relative-import",
343
824
  "design.large-module-concentration",
344
825
  ] as const;
345
826
 
346
- // Root graph context is needed only for narrow path operands; full-root scans already have context.
827
+ /**
828
+ * Determine whether a scoped scan needs extra graph context rooted at projectRoot to find cycles through scopedFiles.
829
+ *
830
+ * @param projectRoot - project root directory used to resolve requested target paths
831
+ * @param options - scan options whose explicit path operands determine if the scan is already root-wide
832
+ * @param scopedFiles - files discovered for the requested targets
833
+ * @returns True when scopedFiles and explicit paths are non-empty and none resolve to projectRoot; false otherwise.
834
+ */
347
835
  function shouldBuildRootCircularContext(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[]): boolean {
348
836
  if (scopedFiles.length === 0 || options.paths.length === 0) {
349
837
  return false;
@@ -351,33 +839,55 @@ function shouldBuildRootCircularContext(projectRoot: string, options: AnalysisOp
351
839
  return options.paths.every((input) => displayPath(projectRoot, absolutize(projectRoot, input)) !== ".");
352
840
  }
353
841
 
354
- // Builds stable circular-import findings from the repository root, then filters back to requested files.
842
+ /**
843
+ * Read root graph context so that a scoped scan can detect a cycle passing through files outside the request.
844
+ *
845
+ * @param projectRoot - root directory for graph discovery
846
+ * @param options - discovery settings to keep while clearing the requested path operands
847
+ * @param scopedFiles - requested files whose display paths qualify a cycle for the report
848
+ * @param config - discovery and project-source settings for the root scan
849
+ * @returns Stable circular-import findings touching a requested file, or an empty list if no cycle qualifies.
850
+ */
355
851
  function rootCircularImportFindings(projectRoot: string, options: AnalysisOptions, scopedFiles: SourceFile[], config: Config): Finding[] {
356
852
  const requestedFiles = new Set(scopedFiles.map((file) => file.displayPath));
357
853
  const rootDiscovery = discoverSources(projectRoot, { ...options, paths: [] }, config);
358
- const rootProjectSources = graphProjectSources(rootDiscovery.files);
854
+ const rootProjectSources = graphProjectSources(rootDiscovery.files, config);
359
855
  const findings: Finding[] = [];
360
856
  analyseCircularImportRule(buildProjectIndex(rootProjectSources), findings);
361
857
  return findings.filter((finding) => circularImportFindingTouchesRequestedFile(finding, requestedFiles));
362
858
  }
363
859
 
364
- // Reads just the root files needed for import graph context and swallows unrelated read failures.
365
- function graphProjectSources(files: SourceFile[]): ProjectSource[] {
860
+ /**
861
+ * Read root-context candidates from files and collect retained script snapshots that satisfy the deep-scan budget.
862
+ * Unreadable or unprocessable candidates are skipped; the primary scoped scan owns requested-file diagnostics.
863
+ *
864
+ * @param files - discovered root-level source candidates to read from disk
865
+ * @param config - scan configuration supplying deep-scan budget limits
866
+ * @returns Retained project-index snapshots for readable, within-budget scripts.
867
+ */
868
+ function graphProjectSources(files: SourceFile[], config: Config): ProjectSource[] {
366
869
  const projectSources: ProjectSource[] = [];
367
870
  for (const file of files) {
368
871
  try {
369
872
  const source = readFileSync(file.absolutePath, "utf8");
370
- if (!deepScanBudgetNote(file, source) && shouldRetainProjectSource(file, source)) {
873
+ if (!deepScanBudgetDiagnostic(file, source, config) && shouldRetainProjectSource(file, source)) {
371
874
  projectSources.push(projectSource(file, source));
372
875
  }
373
876
  } catch {
374
- // ignore hidden root-context read failures; scoped scans still report requested-file errors.
877
+ // Root context is supplemental; the primary scan reports requested-file failures, so this pass adds no duplicate diagnostic.
375
878
  }
376
879
  }
377
880
  return projectSources;
378
881
  }
379
882
 
380
- // Contract filter: root-context circular findings survive only when the SCC contains a requested file.
883
+ /**
884
+ * Check whether a circular-import finding lists a requested display path among its cycle members.
885
+ * The scope contract falls back to the finding's path for a missing or non-array list; empty arrays and non-string members never match.
886
+ *
887
+ * @param finding - circular-import finding whose `metadata.files` or `filePath` is inspected
888
+ * @param requestedFiles - set of display paths belonging to the scoped request
889
+ * @returns True when at least one cycle member path is in requestedFiles; false otherwise.
890
+ */
381
891
  function circularImportFindingTouchesRequestedFile(finding: Finding, requestedFiles: Set<string>): boolean {
382
892
  const files = Array.isArray(finding.metadata.files) ? finding.metadata.files : [finding.filePath];
383
893
  return files.some((file) => typeof file === "string" && requestedFiles.has(file));
@@ -396,7 +906,6 @@ const SIZE_RULE_IDS = ruleIdsForPillar("size");
396
906
  const TEST_QUALITY_RULE_IDS = ruleIdsForPillar("test-quality");
397
907
 
398
908
  const GITHUB_ACTIONS_RULE_IDS = [
399
- "security.github-actions-broad-permissions",
400
909
  "security.github-actions-pull-request-target",
401
910
  "security.github-actions-remote-shell",
402
911
  "security.github-actions-secrets-in-pr",
@@ -405,32 +914,28 @@ const GITHUB_ACTIONS_RULE_IDS = [
405
914
 
406
915
  const PROJECT_CONFIG_RULE_IDS = [
407
916
  "security.remote-install-script",
408
- "security.risky-lifecycle-script",
409
917
  "security.url-dependency",
410
918
  "waste.broad-runtime-version",
411
919
  "design.package-bin-missing",
412
920
  "design.package-bin-not-executable",
413
921
  ] as const;
414
922
 
415
- const BLOCK_RULE_IDS = [
923
+ // The size and complexity block rules, the only rules that also run on the measure-only callable forms.
924
+ const BLOCK_MEASURE_RULE_IDS = [
416
925
  "size.function-length",
417
926
  "size.parameter-count",
418
927
  "complexity.cyclomatic",
419
- "complexity.cognitive",
420
- "naming.generic-function",
928
+ ] as const;
929
+
930
+ const BLOCK_RULE_IDS = [
931
+ ...BLOCK_MEASURE_RULE_IDS,
421
932
  "docs.missing-exported-function-doc",
422
933
  "docs.missing-internal-function-doc",
423
- "waste.empty-function",
424
- "waste.unused-parameter",
425
- "waste.redundant-variable",
426
934
  "waste.useless-return",
427
935
  ] as const;
428
936
 
429
937
  const PARAMETER_NAMING_RULE_IDS = [
430
- "naming.boolean-prefix",
431
- "naming.generic-parameter",
432
938
  "naming.identifier-quality",
433
- "naming.negative-boolean",
434
939
  "naming.short-variable",
435
940
  ] as const;
436
941
 
@@ -438,41 +943,26 @@ const DOCBLOCK_RULE_IDS = [
438
943
  "docs.missing-param-tag",
439
944
  "docs.missing-return-tag",
440
945
  "docs.stale-param-tag",
441
- "docs.useless-docblock",
442
- ] as const;
443
-
444
- const INTERFACE_FIELD_RULE_IDS = [
445
- "naming.boolean-prefix",
446
- "naming.negative-boolean",
447
946
  ] as const;
448
947
 
449
948
  // Every rule id `analyseCommentQualityRules` can emit - including `docs.fixture-purpose-missing`
450
949
  // via `pushFixturePurposeFindings` - so the group gate never silences an enabled rule.
451
950
  const COMMENT_QUALITY_RULE_IDS = [
452
951
  "docs.fixture-purpose-missing",
453
- "docs.magic-threshold-without-rationale",
454
952
  "docs.missing-error-behavior-doc",
455
953
  "docs.missing-invariant-doc",
456
954
  "docs.missing-side-effect-doc",
457
955
  "docs.missing-why-for-complex-code",
458
- "docs.stale-comment",
459
956
  "docs.suppression-without-rationale",
460
957
  "docs.todo-without-tracking",
461
- "docs.useless-docblock",
462
958
  ] as const;
463
959
 
464
960
  const CLASS_RULE_IDS = [
465
961
  "docs.missing-public-doc",
466
962
  "naming.class-file-mismatch",
467
- "modernisation.public-property",
468
963
  "modernisation.readonly-property-candidate",
469
964
  ] as const;
470
965
 
471
- const IDENTIFIER_INVENTORY_RULE_IDS = [
472
- "naming.acronym-case",
473
- "naming.inconsistent-casing",
474
- ] as const;
475
-
476
966
  const SECURITY_FLOW_RULE_IDS = [
477
967
  "security.dynamic-regexp",
478
968
  "security.open-redirect-candidate",
@@ -494,7 +984,6 @@ const BLOCK_DEPENDENT_RULE_IDS = [
494
984
  ...PARAMETER_NAMING_RULE_IDS,
495
985
  ...TEST_QUALITY_RULE_IDS,
496
986
  ...COMMENT_QUALITY_RULE_IDS,
497
- ...IDENTIFIER_INVENTORY_RULE_IDS,
498
987
  ];
499
988
 
500
989
  const TYPESCRIPT_RULE_IDS = [
@@ -509,7 +998,11 @@ const TYPESCRIPT_RULE_IDS = [
509
998
  ...TEST_QUALITY_RULE_IDS,
510
999
  ];
511
1000
 
512
- // Groups rule ids from the public catalogue once so broad pass gates stay aligned with profiles.
1001
+ /**
1002
+ * Group rule ids from the public catalogue once so broad pass gates stay aligned with profiles.
1003
+ *
1004
+ * @returns Read-only map from each pillar to its catalogue rule ids.
1005
+ */
513
1006
  function ruleIdsByPillar(): ReadonlyMap<Pillar, readonly string[]> {
514
1007
  const byPillar = new Map<Pillar, string[]>();
515
1008
  for (const descriptor of ruleDescriptors()) {
@@ -520,44 +1013,64 @@ function ruleIdsByPillar(): ReadonlyMap<Pillar, readonly string[]> {
520
1013
  return byPillar;
521
1014
  }
522
1015
 
523
- // Looks up a precomputed pillar group; missing groups are empty so callers can stay branch-free.
1016
+ /**
1017
+ * Look up a precomputed pillar group from the catalogue index; missing groups are empty so callers stay branch-free.
1018
+ *
1019
+ * @param pillar - quality pillar whose registered rule ids are requested
1020
+ * @returns Array of rule ids for pillar, or an empty array when the pillar has none.
1021
+ */
524
1022
  function ruleIdsForPillar(pillar: Pillar): readonly string[] {
525
1023
  return RULE_IDS_BY_PILLAR.get(pillar) ?? [];
526
1024
  }
527
1025
 
528
- // Checks a rule-id group through the resolved config map so profiles and explicit overrides share one gate.
1026
+ /**
1027
+ * Check whether at least one rule in a group is active under the resolved configuration.
1028
+ *
1029
+ * @param config - scan configuration including profile defaults and explicit rule overrides
1030
+ * @param ruleIds - candidate rule identifiers to test
1031
+ * @returns True when any id in ruleIds is enabled by config; false when none are enabled or ruleIds is empty.
1032
+ */
529
1033
  function isAnyRuleEnabled(config: Config, ruleIds: readonly string[]): boolean {
530
1034
  return ruleIds.some((ruleId) => ruleEnabled(config, ruleId));
531
1035
  }
532
1036
 
533
- /*
534
- * Per-file text-pillar rules run before script-only rules because config, workflow, and
535
- * secret surfaces are not TypeScript. The order is a stable baseline contract: reshuffling these
536
- * checks changes same-line finding order for machine reports.
1037
+ /**
1038
+ * Check source text before deeper script passes so that text inputs are covered too. Keep the rule order stable for tied findings.
1039
+ *
1040
+ * @param file - input path for findings and script classification for the size check
1041
+ * @param source - raw text to measure or check for sensitive data, workflow and configuration issues
1042
+ * @param comments - comment records used to count substantive script lines
1043
+ * @param config - enables checks and supplies the size threshold and severity
1044
+ * @param findings - caller's array to append results to
1045
+ * @param parsed - shared script parse used to exclude decorator text. Without it, decorator-only lines count.
1046
+ * @returns Nothing. Appends size findings when enabled and text findings from each group with at least one enabled rule.
537
1047
  */
538
- function analyseTextRules(file: SourceFile, source: string, config: Config, findings: Finding[]): void {
539
- const lines = lineCount(source);
540
- if (ruleEnabled(config, "size.file-length") && !isGeneratedLockfile(file.displayPath)) {
541
- const fileLengthThreshold = threshold(config, "size.file-length", 750);
1048
+ function analyseTextRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[], parsed?: ParsedScript): void {
1049
+ // The file-length threshold applies to scripts because it measures code size. Other inputs still receive enabled text checks.
1050
+ // The size bands follow FAMILY-CONTRACT.md section 12 under Size and complexity findings in two bands.
1051
+ if (file.isScript && ruleEnabled(config, "size.file-length")) {
1052
+ const lines = substantiveLineCount(source, comments, parsed);
1053
+ const fileLengthThreshold = threshold(config, "size.file-length", 1000);
542
1054
  if (lines > fileLengthThreshold) {
1055
+ const band = bandedFields(lines, fileLengthThreshold, ruleSeverity(config, "size.file-length", "error"), LOWER_BAND_FILE, SPLIT_FILE);
543
1056
  findings.push(
544
1057
  makeFinding({
545
1058
  ruleId: "size.file-length",
546
- message: `File has ${lines} lines, above the threshold of ${fileLengthThreshold}.`,
1059
+ message: `File has ${lines} substantive lines, above the threshold of ${fileLengthThreshold}.`,
547
1060
  filePath: file.displayPath,
548
1061
  line: 1,
549
- severity: ruleSeverity(config, "size.file-length", "warning"),
1062
+ severity: band.severity,
550
1063
  pillar: "size",
551
1064
  confidence: "high",
552
- remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.",
553
- metadata: { lines, threshold: fileLengthThreshold },
1065
+ remediation: band.remediation,
1066
+ metadata: { lines, threshold: fileLengthThreshold, limitBand: band.limitBand },
554
1067
  }),
555
1068
  );
556
1069
  }
557
1070
  }
558
1071
 
559
1072
  if (isAnyRuleEnabled(config, SENSITIVE_DATA_RULE_IDS)) {
560
- analyseSensitiveData(file, source, config, findings);
1073
+ analyseSensitiveData(file, source, findings);
561
1074
  }
562
1075
  if (isAnyRuleEnabled(config, GITHUB_ACTIONS_RULE_IDS)) {
563
1076
  analyseGithubActionsRules(file, source, findings);
@@ -567,7 +1080,63 @@ function analyseTextRules(file: SourceFile, source: string, config: Config, find
567
1080
  }
568
1081
  }
569
1082
 
570
- // Counts the same logical lines as `source.split(/\r?\n/)` without allocating the full line array.
1083
+ /**
1084
+ * Count nonblank lines after masking recorded comments and, when available, decorators, while skipping `#!` lines.
1085
+ * String text otherwise counts.
1086
+ *
1087
+ * @param source - raw script text to measure
1088
+ * @param comments - recorded comment spans replaced with spaces before counting
1089
+ * @param parsed - optional script parse enabling decorator masking; without it, decorator-only lines count
1090
+ * @returns Count of substantive lines, or 0 for empty source.
1091
+ */
1092
+ function substantiveLineCount(source: string, comments: CommentRecord[], parsed?: ParsedScript): number {
1093
+ const withoutComments = maskRecordedComments(source, comments);
1094
+ // Mask only the decorator spans so code sharing a line with a decorator still counts.
1095
+ // See FAMILY-CONTRACT.md section 12 under Code lines in every line count.
1096
+ const withoutDecorators = parsed ? maskDecorators(withoutComments, parsed) : withoutComments;
1097
+ return withoutDecorators
1098
+ .split(/\r?\n/)
1099
+ .filter((line) => isSubstantiveLine(line))
1100
+ .length;
1101
+ }
1102
+
1103
+ /**
1104
+ * Replace comment text with spaces while retaining newlines and UTF-16 offsets from CommentRecord.
1105
+ *
1106
+ * @param source - original script text
1107
+ * @param comments - ordered comment spans whose non-newline characters are masked
1108
+ * @returns Source text with recorded comments blanked out and line structure preserved.
1109
+ */
1110
+ function maskRecordedComments(source: string, comments: CommentRecord[]): string {
1111
+ let cursor = 0;
1112
+ let masked = "";
1113
+ for (const comment of comments) {
1114
+ const end = comment.kind === "block" ? Math.min(source.length, comment.endIndex + 1) : comment.endIndex;
1115
+ masked += source.slice(cursor, comment.startIndex);
1116
+ masked += source.slice(comment.startIndex, end).replace(/[^\r\n]/g, " ");
1117
+ cursor = end;
1118
+ }
1119
+ return masked + source.slice(cursor);
1120
+ }
1121
+
1122
+ /**
1123
+ * Test whether a line contributes to substantive code length.
1124
+ * A blank line and a `#!` interpreter line are free; a TypeScript private field such as `#count = 0;` still counts.
1125
+ *
1126
+ * @param line - single comment-masked and decorator-masked source line
1127
+ * @returns True when the trimmed line is non-empty and does not start with `#!`; false otherwise.
1128
+ */
1129
+ function isSubstantiveLine(line: string): boolean {
1130
+ const trimmed = line.trim();
1131
+ return trimmed !== "" && !trimmed.startsWith("#!");
1132
+ }
1133
+
1134
+ /**
1135
+ * Count logical lines in source without allocating a split array.
1136
+ *
1137
+ * @param source - text whose newline characters are counted
1138
+ * @returns Logical line count, where empty source is 1 and each trailing newline adds 1.
1139
+ */
571
1140
  function lineCount(source: string): number {
572
1141
  let count = 1;
573
1142
  for (let index = 0; index < source.length; index += 1) {
@@ -578,60 +1147,96 @@ function lineCount(source: string): number {
578
1147
  return count;
579
1148
  }
580
1149
 
581
- // Exact-name match against the five major package managers. Lockfiles routinely break size and
582
- // sensitive-data thresholds without being meaningful project code, so they get excluded by file rules.
583
- function isGeneratedLockfile(path: string): boolean {
584
- const name = basename(path);
585
- return name === "package-lock.json" || name === "npm-shrinkwrap.json" || name === "yarn.lock" || name === "pnpm-lock.yaml" || name === "bun.lockb";
586
- }
587
-
588
- /*
589
- * TypeScript-only rule pipeline. Masks comments and literals once, parses callable blocks once,
590
- * then walks every rule pack in a stable, deterministic order so reports and baselines remain reproducible.
1150
+ /**
1151
+ * Run enabled script checks in a stable order so that reports remain reproducible. Skip passes that require a parse when it is unavailable.
1152
+ *
1153
+ * @param file - script being checked and the path used in its findings
1154
+ * @param source - original script text used by lexical and text checks
1155
+ * @param comments - comment locations and text available to comment quality checks
1156
+ * @param config - selects rule passes and their settings
1157
+ * @param findings - caller's array to append script findings to
1158
+ * @param parsed - shared script parse when available for syntax-backed checks
1159
+ * @returns Nothing. Appends findings from enabled passes to the caller's array.
591
1160
  */
592
- function analyseTypeScriptRules(file: SourceFile, source: string, config: Config, findings: Finding[]): void {
1161
+ function analyseTypeScriptRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[], parsed?: ParsedScript): void {
593
1162
  if (!isAnyRuleEnabled(config, TYPESCRIPT_RULE_IDS)) {
594
1163
  return;
595
1164
  }
596
1165
  const codeSource = maskNonCode(source);
597
- const blocks = isAnyRuleEnabled(config, BLOCK_DEPENDENT_RULE_IDS) ? functionBlocks(source, codeSource) : [];
1166
+ const blocks = isAnyRuleEnabled(config, BLOCK_DEPENDENT_RULE_IDS) ? functionBlocks(source, codeSource, parsed) : [];
598
1167
  runRulePass(config, "docs.missing-file-overview", () => analyseFileOverviewDoc(file, source, findings));
599
1168
  analyseBlocks(file, source, codeSource, blocks, config, findings);
600
- runRulePass(config, "waste.unused-import", () => analyseUnusedImports(file, codeSource, source, findings));
601
- runRuleGroupPass(config, LINE_RULE_IDS, () => analyseLineRules(file, source, codeSource, config, findings));
602
- runRuleGroupPass(config, SECURITY_FLOW_RULE_IDS, () => analyseSecurityFlow(file, source, findings));
1169
+ runRulePass(config, "test-quality.duplicate-test-body", () => {
1170
+ if (parsed) {
1171
+ analyseDuplicateTestGroups(file, parsed, findings);
1172
+ }
1173
+ });
1174
+ // Callables only the size and complexity rules measure; the documentation and naming rules never see them.
1175
+ runRuleGroupPass(config, BLOCK_MEASURE_RULE_IDS, () => {
1176
+ if (parsed) {
1177
+ for (const block of measuredOnlyFunctionBlocks(source, codeSource, parsed)) {
1178
+ analyseBlockMeasures(blockRuleContext(file, block, config, findings));
1179
+ }
1180
+ }
1181
+ });
1182
+ runRulePass(config, "waste.unused-import", () => analyseUnusedImports(file, codeSource, source, findings, parsed));
1183
+ runRuleGroupPass(config, LINE_RULE_IDS, () => analyseLineRules(file, source, codeSource, config, findings, parsed));
1184
+ runRuleGroupPass(config, SECURITY_FLOW_RULE_IDS, () => analyseSecurityFlow(file, source, findings, parsed?.sourceFile));
603
1185
  runRulePass(config, "waste.unreachable-code", () => analyseUnreachable(file, codeSource, findings));
604
- runRuleGroupPass(config, DOCBLOCK_RULE_IDS, () => analyseDocRules(file, source, codeSource, findings));
1186
+ // Without a parse, skip docblock checks because they need reliable callable signatures.
1187
+ runRuleGroupPass(config, DOCBLOCK_RULE_IDS, () => {
1188
+ if (parsed) {
1189
+ analyseDocRules(file, findings, parsed, {
1190
+ isParamTagEveryCallable: optionBoolean(config, "docs.missing-param-tag", "everyCallable", true),
1191
+ isReturnTagEveryCallable: optionBoolean(config, "docs.missing-return-tag", "everyCallable", true),
1192
+ });
1193
+ }
1194
+ });
605
1195
  runRulePass(config, "docs.missing-interface-doc", () => analyseInterfaceDocs(file, source, codeSource, findings));
606
- runRuleGroupPass(config, INTERFACE_FIELD_RULE_IDS, () => analyseInterfaceFields(file, source, codeSource, config, findings));
607
- runRuleGroupPass(config, COMMENT_QUALITY_RULE_IDS, () => analyseCommentQualityRules({ file, source, codeSource, blocks, comments: commentRecords(source), config, findings }));
608
- runRuleGroupPass(config, CLASS_RULE_IDS, () => analyseClassRules(file, source, codeSource, findings));
1196
+ runRuleGroupPass(config, COMMENT_QUALITY_RULE_IDS, () => analyseCommentQualityRules({ file, source, codeSource, blocks, comments, config, findings }));
1197
+ runRuleGroupPass(config, CLASS_RULE_IDS, () => analyseClassRules(file, source, codeSource, config, findings, parsed));
609
1198
  runRulePass(config, "dead-code.unused-private-method", () => analyseDeadCode(file, codeSource, findings));
610
- runRuleGroupPass(config, IDENTIFIER_INVENTORY_RULE_IDS, () => {
611
- const inventory = collectDeclaredIdentifiers(source, codeSource, blocks);
612
- runRulePass(config, "naming.inconsistent-casing", () => analyseInconsistentCasing(file, inventory, findings));
613
- runRulePass(config, "naming.acronym-case", () => analyseAcronymCase(file, inventory, config, findings));
614
- });
615
1199
  }
616
1200
 
617
- // Runs a single-rule pass only when that exact resolved rule id is enabled.
1201
+ /**
1202
+ * Gate a single-rule pass on its enablement in config so disabled rules incur no execution cost.
1203
+ *
1204
+ * @param config - resolved scan configuration tested for rule enablement
1205
+ * @param ruleId - identifier of the rule guarded by this pass
1206
+ * @param action - callback executed only when config enables ruleId
1207
+ * @returns Nothing. Invokes action when ruleId is enabled; otherwise does nothing.
1208
+ */
618
1209
  function runRulePass(config: Config, ruleId: string, action: () => void): void {
619
1210
  if (ruleEnabled(config, ruleId)) {
620
1211
  action();
621
1212
  }
622
1213
  }
623
1214
 
624
- // Runs a shared pass only when at least one rule it can emit is enabled.
1215
+ /**
1216
+ * Gate a multi-rule pass so it runs only when at least one rule in the group is enabled.
1217
+ *
1218
+ * @param config - resolved scan configuration tested against the rule group
1219
+ * @param ruleIds - rule identifiers belonging to the pass
1220
+ * @param action - callback executed only when at least one id in ruleIds is enabled
1221
+ * @returns Nothing. Invokes action if any rule in ruleIds is enabled; otherwise does nothing.
1222
+ */
625
1223
  function runRuleGroupPass(config: Config, ruleIds: readonly string[], action: () => void): void {
626
1224
  if (isAnyRuleEnabled(config, ruleIds)) {
627
1225
  action();
628
1226
  }
629
1227
  }
630
1228
 
631
- // One pass over the file's parsed callables. The naming and test-block fanouts are dispatched
632
- // separately so blocks.ts can stay independent of the naming-pusher and test-block-rule modules;
633
- // the per-rule emission order from `analyseBlockRules` is the stable fingerprint contract every
634
- // Finding depends on for deterministic baseline matching.
1229
+ /**
1230
+ * Dispatch enabled rules for each parsed callable. Keep emission order stable because the report sort can preserve it for tied findings.
1231
+ *
1232
+ * @param file - source file whose path identifies the findings
1233
+ * @param source - original source text for test checks
1234
+ * @param codeSource - source with comments and literals masked for test checks
1235
+ * @param blocks - parsed callables to check
1236
+ * @param config - selects enabled rule groups and their settings
1237
+ * @param findings - caller's array to append rule results to
1238
+ * @returns Nothing. Appends enabled block, parameter naming and test findings to the caller's array.
1239
+ */
635
1240
  function analyseBlocks(file: SourceFile, source: string, codeSource: string, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
636
1241
  const shouldAnalyseBlockRules = isAnyRuleEnabled(config, BLOCK_RULE_IDS);
637
1242
  const shouldAnalyseParameterNaming = isAnyRuleEnabled(config, PARAMETER_NAMING_RULE_IDS);
@@ -652,30 +1257,72 @@ function analyseBlocks(file: SourceFile, source: string, codeSource: string, blo
652
1257
  }
653
1258
  }
654
1259
 
655
- /*
656
- * Per-parameter naming-rule fanout. Each parameter is checked for short-name / placeholder forms;
657
- * typed booleans get the extra prefix and negative-name checks. Reports findings to the shared sink.
1260
+ /**
1261
+ * The naming contract exempts local bindings, tests, recognized comparator pairs, and `TestContext` `t` parameters from short-name checks.
1262
+ * Placeholder checks still cover every parameter.
1263
+ *
1264
+ * @param context - callable and location to check, configured rules, and destination findings array
1265
+ * @returns Nothing. Appends applicable parameter-name findings to the caller's array.
658
1266
  */
659
1267
  function pushParameterNamingFindings(context: BlockRuleContext): void {
660
1268
  const line = context.block.declarationLine;
661
1269
  const params = parameterNames(context.block.params);
1270
+ const hasLocallyBoundParameters = isLocallyBoundParameterOwner(context.block);
1271
+ const isTestSourceFile = isTestPath(context.file.displayPath);
662
1272
  for (const parameter of params) {
663
- if (!isComparatorShortParameter(context, params, parameter.name)) {
1273
+ if (!hasLocallyBoundParameters && !isComparatorShortParameter(context, params, parameter.name) && !isTestContextShortParameter(parameter, isTestSourceFile)) {
664
1274
  pushShortVariableAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
665
1275
  }
666
1276
  pushIdentifierQualityAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
667
- if (isBooleanParameter(parameter.raw)) {
668
- pushBooleanPrefixAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
669
- pushNegativeBooleanAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
670
- }
671
- if (isGenericParameterCandidate(context, params.length, parameter.name)) {
672
- pushGenericParameterAt(context.file, line, parameter.name, context.findings);
673
- }
674
1277
  }
675
1278
  }
676
1279
 
677
- // `(a, b)` is a conventional comparator pair when the callable is explicitly shaped like sorting.
678
- // Keep the exemption narrow so arbitrary two-parameter helpers still need domain names.
1280
+ /**
1281
+ * Recognizes the standard `node:test` context parameter `t` so test helpers are not flagged as too short.
1282
+ * Matches when the parameter is named `t` and either lives in a test file or carries a `TestContext` type annotation.
1283
+ *
1284
+ * @param parameter - parsed parameter name and raw declaration text from the callable signature
1285
+ * @param isTestSourceFile - true when the enclosing file matches `isTestPath`
1286
+ * @returns True when parameter `t` qualifies for the test-context exemption; false for every other parameter.
1287
+ */
1288
+ function isTestContextShortParameter(parameter: { name: string; raw: string }, isTestSourceFile: boolean): boolean {
1289
+ if (parameter.name !== "t") {
1290
+ return false;
1291
+ }
1292
+ return isTestSourceFile || /:\s*(?:import\([^)]+\)\.)?(?:[A-Za-z_$][A-Za-z0-9_$]*\.)?TestContext\b/.test(parameter.raw);
1293
+ }
1294
+
1295
+ /**
1296
+ * Determine whether a callable's parameters are exempt from short-name checks as a test callback or local binding.
1297
+ * Exported bindings, declarations, methods, and unrecognized binding syntax remain covered.
1298
+ *
1299
+ * @param block - parsed function or callback block inspected for test status, export flag, and const/let binding
1300
+ * @returns True when block is a test callback or non-exported const/let-bound callable; false otherwise.
1301
+ */
1302
+ function isLocallyBoundParameterOwner(block: FunctionBlock): boolean {
1303
+ if (block.isTest) {
1304
+ return true;
1305
+ }
1306
+ // An exported binding is the cross-file API this exemption exists to keep covered, so
1307
+ // `export const transform = (x) => ...` is judged like `export function transform(x)`.
1308
+ if (block.isExported) {
1309
+ return false;
1310
+ }
1311
+ const declarationOffset = block.declarationLine - block.startLine;
1312
+ const declarationLine = block.codeBody.split(/\r?\n/)[declarationOffset] ?? "";
1313
+ const bindingName = declarationLine.match(/\b(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/)?.[1];
1314
+ return bindingName === block.name;
1315
+ }
1316
+
1317
+ /**
1318
+ * Check whether a parameter name qualifies for the conventional comparator exemption for the callable in context.
1319
+ * params must contain exactly `a` then `b`, and the callable's name or body must match comparator heuristics.
1320
+ *
1321
+ * @param context - callable block rule context supplying the enclosing callable's name and body
1322
+ * @param params - ordered parameter descriptors parsed from the callable signature
1323
+ * @param name - parameter name being evaluated for exemption
1324
+ * @returns True when name is `a` or `b` in an `(a, b)` comparator callable; false otherwise.
1325
+ */
679
1326
  function isComparatorShortParameter(context: BlockRuleContext, params: Array<{ name: string; raw: string }>, name: string): boolean {
680
1327
  const names = params.map((parameter) => parameter.name);
681
1328
  if (names.length !== 2 || names[0] !== "a" || names[1] !== "b" || (name !== "a" && name !== "b")) {
@@ -684,8 +1331,14 @@ function isComparatorShortParameter(context: BlockRuleContext, params: Array<{ n
684
1331
  return isComparatorCallable(context.block.name, context.block.codeBody);
685
1332
  }
686
1333
 
687
- // Comparator-shaped callables are either named for ordering (`compare*`, `*Comparator`, `byName`) or
688
- // their body performs the standard locale/numeric ordering expression over both parameters.
1334
+ /**
1335
+ * Test whether a callable's name or body matches comparator heuristics permitting conventional `(a, b)` parameters.
1336
+ * A dotted localeCompare matches with or without whitespace before the opening parenthesis, regardless of receiver or arguments.
1337
+ *
1338
+ * @param name - callable identifier tested against compare/Comparator/by naming prefixes
1339
+ * @param codeBody - comment-masked callable body tested for localeCompare or subtraction/comparison returns
1340
+ * @returns True when name or codeBody matches comparator heuristics; false otherwise.
1341
+ */
689
1342
  function isComparatorCallable(name: string, codeBody: string): boolean {
690
1343
  return (
691
1344
  /^(?:compare[A-Z0-9_]?|.*Comparator$|by[A-Z])/.test(name) ||
@@ -694,52 +1347,3 @@ function isComparatorCallable(name: string, codeBody: string): boolean {
694
1347
  /\breturn\s+b\b[\s\S]*?(?:-\s*a\b|[<>]=?\s*a\b)/.test(codeBody)
695
1348
  );
696
1349
  }
697
-
698
- // Generic-parameter rule is context-gated: only fires when the surrounding function is itself
699
- // large enough to deserve attention (long, complex, or many parameters). Keeps noise down on
700
- // trivial helpers that legitimately accept a `value` argument.
701
- function isGenericParameterCandidate(context: BlockRuleContext, paramCount: number, name: string): boolean {
702
- if (!context.config.placeholderNames.has(name.toLowerCase())) {
703
- return false;
704
- }
705
- const minParameters = optionNumber(context.config, "naming.generic-parameter", "minParameters", 3);
706
- const minLineCount = optionNumber(context.config, "naming.generic-parameter", "minLineCount", 30);
707
- const minCyclomatic = optionNumber(context.config, "naming.generic-parameter", "minCyclomatic", 8);
708
- return (
709
- paramCount >= minParameters ||
710
- context.block.lineCount >= minLineCount ||
711
- context.cyclomatic >= minCyclomatic
712
- );
713
- }
714
-
715
- // Only called after `isGenericParameterCandidate` has gated the placeholder check on the function's
716
- // complexity and length - reaching this helper means the rule decided the finding is wanted.
717
- // Reports the stable `naming.generic-parameter` finding.
718
- function pushGenericParameterAt(file: SourceFile, line: number, name: string, findings: Finding[]): void {
719
- findings.push(
720
- makeFinding({
721
- ruleId: "naming.generic-parameter",
722
- message: `Parameter \`${name}\` uses a placeholder name in a function that meets context-gating thresholds.`,
723
- filePath: file.displayPath,
724
- line,
725
- severity: "advisory",
726
- pillar: "naming",
727
- confidence: "medium",
728
- symbol: name,
729
- remediation: "Use a name that describes the parameter's role.",
730
- metadata: { identifierName: name, surface: "parameter" },
731
- }),
732
- );
733
- }
734
-
735
- // Two positive cases: explicit `: boolean` annotation, or a default value of `true`/`false`.
736
- // Explicit `as` casts are rejected so generic-call sites don't trip the boolean-name checks.
737
- function isBooleanParameter(raw: string): boolean {
738
- if (/:\s*boolean\b/.test(raw)) {
739
- return true;
740
- }
741
- if (/\bas\b/.test(raw)) {
742
- return false;
743
- }
744
- return /=\s*(?:true|false)\s*$/.test(raw);
745
- }