@blundergoat/gruff-ts 0.3.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/README.md +16 -6
  3. package/SECURITY.md +2 -1
  4. package/docs/README.md +1 -4
  5. package/docs/agent-hook.md +15 -3
  6. package/docs/configuration.md +47 -1
  7. package/docs/dashboard.md +3 -3
  8. package/docs/reports-and-ci.md +36 -0
  9. package/docs/rules.md +52 -37
  10. package/package.json +1 -1
  11. package/src/analyser.ts +540 -154
  12. package/src/baseline-options.ts +90 -0
  13. package/src/baseline.ts +39 -3
  14. package/src/blocks.ts +116 -77
  15. package/src/changed-regions.ts +80 -11
  16. package/src/class-rules.ts +226 -76
  17. package/src/cli-program.ts +65 -15
  18. package/src/cli.ts +4 -2
  19. package/src/comment-rules.ts +58 -13
  20. package/src/comment-scanner.ts +27 -0
  21. package/src/complexity-metrics.ts +244 -0
  22. package/src/config.ts +56 -16
  23. package/src/constants.ts +1 -1
  24. package/src/context-doc-rules.ts +9 -10
  25. package/src/dead-code-rules.ts +10 -3
  26. package/src/discovery.ts +66 -22
  27. package/src/doc-rules.ts +22 -53
  28. package/src/findings-helpers.ts +127 -1
  29. package/src/findings.ts +4 -0
  30. package/src/fixture-purpose-rules.ts +39 -5
  31. package/src/github-actions-rules.ts +24 -1
  32. package/src/hook-contract.ts +120 -27
  33. package/src/init-config.ts +15 -5
  34. package/src/line-rules.ts +175 -19
  35. package/src/naming-pushers.ts +26 -5
  36. package/src/parsed-script.ts +652 -0
  37. package/src/process-exec-metadata.ts +163 -0
  38. package/src/profiles.ts +14 -0
  39. package/src/project-config-rules.ts +36 -18
  40. package/src/project-rules.ts +159 -42
  41. package/src/public-exports.ts +220 -0
  42. package/src/report-renderers.ts +58 -4
  43. package/src/rules.ts +15 -15
  44. package/src/scoring.ts +13 -4
  45. package/src/security-flow-rules.ts +169 -24
  46. package/src/sensitive-data-rules.ts +256 -80
  47. package/src/source-text.ts +9 -26
  48. package/src/static-analysis-redundant-rules.ts +46 -2
  49. package/src/test-block-rules.ts +118 -14
  50. package/src/test-fixtures.ts +4 -1
  51. package/src/text-scans.ts +8 -1
  52. package/src/types.ts +17 -0
@@ -3,8 +3,9 @@
3
3
  import { execFileSync } from "node:child_process";
4
4
  import { functionBlocks } from "./blocks.ts";
5
5
  import type { SourceFile } from "./discovery.ts";
6
+ import type { ParsedScript } from "./parsed-script.ts";
6
7
  import { maskNonCode } from "./source-text.ts";
7
- import type { AnalysisOptions, ChangedScopeMode, Finding } from "./types.ts";
8
+ import type { AnalysisOptions, ChangedScopeMode, Finding, RunDiagnostic } from "./types.ts";
8
9
 
9
10
  // Inclusive line range from a changed hunk or explicit `--changed-ranges` input.
10
11
  export interface ChangedRange {
@@ -27,6 +28,7 @@ export interface ChangedRegionScope {
27
28
  interface SourceSnapshot {
28
29
  file: SourceFile;
29
30
  source: string;
31
+ parsed?: ParsedScript;
30
32
  }
31
33
 
32
34
  // Named source span used to keep symbol-scope findings when their declaration overlaps a hunk.
@@ -45,6 +47,10 @@ interface DiffParseState {
45
47
 
46
48
  const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
47
49
 
50
+ // Project-relationship rules anchor one canonical file but relate every member in `metadata.files`,
51
+ // so changed-region attribution must consult the member list, not only the anchor `filePath`.
52
+ const PROJECT_RELATIONSHIP_RULE_IDS = new Set(["design.circular-import"]);
53
+
48
54
  // Builds the changed-region scope requested by CLI options. Throws on stdin diffs missing patch text.
49
55
  export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope | undefined {
50
56
  if (options.changedRanges) {
@@ -65,7 +71,33 @@ export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope
65
71
  return undefined;
66
72
  }
67
73
 
74
+ // Diagnostic types that describe one analysed file's content or readability. Only these are
75
+ // file-scoped under diff filtering; operational diagnostics (missing paths, history errors) always
76
+ // stay, because they describe the request rather than an unchanged context file.
77
+ const FILE_CONTENT_DIAGNOSTIC_TYPES = new Set(["parse-error", "read-error"]);
78
+
79
+ /*
80
+ * Applies the file-scoped diagnostics policy to a changed-region run: a full scan keeps every
81
+ * diagnostic; explicit `--changed-ranges` keeps every diagnostic of each requested file (a syntax
82
+ * error breaks parsing of the whole file, so ranges never filter diagnostics); `--diff`/`--since`
83
+ * keeps only diagnostics from changed target files, so a pre-existing broken context file no
84
+ * longer fails a clean diff. Operational diagnostics are never dropped.
85
+ */
86
+ export function filterScopedDiagnostics(diagnostics: RunDiagnostic[], scope: ChangedRegionScope | undefined): RunDiagnostic[] {
87
+ if (!scope || scope.explicitRanges !== undefined) {
88
+ return diagnostics;
89
+ }
90
+ return diagnostics.filter((diagnostic) => {
91
+ // Operational diagnostics (missing-path, history-error) describe the request, not file content.
92
+ if (!diagnostic.filePath || !FILE_CONTENT_DIAGNOSTIC_TYPES.has(diagnostic.diagnosticType)) {
93
+ return true;
94
+ }
95
+ return scope.changedFiles.has(diagnostic.filePath) || scope.wholeFiles.has(diagnostic.filePath);
96
+ });
97
+ }
98
+
68
99
  // Applies changed-region filtering to findings and reports how many pre-existing findings dropped.
100
+ // Invariant: kept plus suppressedCount always equals the pre-filter total - the hook's arithmetic contract.
69
101
  export function filterChangedFindings(
70
102
  findings: Finding[],
71
103
  scope: ChangedRegionScope | undefined,
@@ -87,13 +119,17 @@ export function filterChangedFindings(
87
119
  return { findings: kept, suppressedCount };
88
120
  }
89
121
 
90
- // Keeps a finding when its own line, enclosing declaration, or changed-file scope intersects the change.
122
+ // Keeps a finding when its own line, enclosing declaration, or changed-file scope intersects the
123
+ // change. Invariant: findings outside the requested change must stay suppressed - the agent-gate contract.
91
124
  function isFindingInChangedScope(
92
125
  finding: Finding,
93
126
  scope: ChangedRegionScope,
94
127
  sources: Map<string, SourceSnapshot>,
95
128
  declarationsByFile: Map<string, DeclarationRegion[]>,
96
129
  ): boolean {
130
+ if (PROJECT_RELATIONSHIP_RULE_IDS.has(finding.ruleId)) {
131
+ return projectRelationshipTouchesChange(finding, scope);
132
+ }
97
133
  if (scope.wholeFiles.has(finding.filePath)) {
98
134
  return true;
99
135
  }
@@ -110,6 +146,18 @@ function isFindingInChangedScope(
110
146
  if (overlapsAny(findingRange, changedRanges)) {
111
147
  return true;
112
148
  }
149
+ return symbolScopeWidensFinding(finding, scope, sources, declarationsByFile, changedRanges);
150
+ }
151
+
152
+ // Symbol scope widens a finding through its enclosing declaration: an edit anywhere inside a
153
+ // callable keeps that callable's findings. Invariant: file-wide findings must never widen this way.
154
+ function symbolScopeWidensFinding(
155
+ finding: Finding,
156
+ scope: ChangedRegionScope,
157
+ sources: Map<string, SourceSnapshot>,
158
+ declarationsByFile: Map<string, DeclarationRegion[]>,
159
+ changedRanges: ChangedRange[],
160
+ ): boolean {
113
161
  if (scope.mode !== "symbol" || isFileWideFinding(finding)) {
114
162
  return false;
115
163
  }
@@ -122,12 +170,27 @@ function isFileWideFinding(finding: Finding): boolean {
122
170
  return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1;
123
171
  }
124
172
 
173
+ /*
174
+ * Keeps a project-relationship finding when any member file participates in the change, matching
175
+ * the documented contract "a project relationship that includes the requested file". Explicit
176
+ * `--changed-ranges` carry no per-file information (the ranges apply to every selected file), so
177
+ * they keep these findings by construction; narrow scans already filtered them to requested files.
178
+ */
179
+ function projectRelationshipTouchesChange(finding: Finding, scope: ChangedRegionScope): boolean {
180
+ if (scope.explicitRanges !== undefined) {
181
+ return true;
182
+ }
183
+ const files = Array.isArray(finding.metadata.files) ? finding.metadata.files : [finding.filePath];
184
+ return files.some((file) => typeof file === "string" && (scope.wholeFiles.has(file) || scope.changedFiles.has(file)));
185
+ }
186
+
125
187
  // Looks up explicit line ranges first because `--changed-ranges` applies to every selected file.
126
188
  function rangesForFindingFile(scope: ChangedRegionScope, filePath: string): ChangedRange[] {
127
189
  return scope.explicitRanges ?? scope.rangesByFile.get(filePath) ?? [];
128
190
  }
129
191
 
130
192
  // Resolves the narrowest declaration around a finding so symbol-scope mode can keep whole callables.
193
+ // Invariant: the smallest enclosing span wins, so sibling declarations never widen each other's findings.
131
194
  function enclosingDeclaration(
132
195
  finding: Finding,
133
196
  sources: Map<string, SourceSnapshot>,
@@ -139,7 +202,7 @@ function enclosingDeclaration(
139
202
  }
140
203
  let declarations = declarationsByFile.get(finding.filePath);
141
204
  if (!declarations) {
142
- declarations = declarationRegions(source.source);
205
+ declarations = declarationRegions(source.source, source.parsed);
143
206
  declarationsByFile.set(finding.filePath, declarations);
144
207
  }
145
208
  const line = finding.line ?? 1;
@@ -151,10 +214,10 @@ function enclosingDeclaration(
151
214
  }
152
215
 
153
216
  // Combines function and class/interface spans into one declaration inventory per source file.
154
- function declarationRegions(source: string): DeclarationRegion[] {
217
+ function declarationRegions(source: string, parsed?: ParsedScript): DeclarationRegion[] {
155
218
  const codeSource = maskNonCode(source);
156
219
  return [
157
- ...functionBlocks(source, codeSource).map((block) => ({
220
+ ...functionBlocks(source, codeSource, parsed).map((block) => ({
158
221
  name: block.name,
159
222
  start: block.startLine,
160
223
  end: block.startLine + block.lineCount - 1,
@@ -234,25 +297,31 @@ function parseChangedRange(rawRange: string): ChangedRange {
234
297
  return { start, end };
235
298
  }
236
299
 
237
- // Produces a changed-region scope from a named git diff mode or arbitrary git ref.
300
+ /*
301
+ * Produces a changed-region scope from a named git diff mode or arbitrary git ref. Every git diff
302
+ * runs in git's relative-path mode, so paths arrive relative to the analysis root (the process
303
+ * cwd) and match finding display paths even when the scan starts from a nested package directory
304
+ * inside the repository. Invariant: from the repo root that mode is a no-op, so root-run diffs
305
+ * are byte-identical to the previous behavior.
306
+ */
238
307
  function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegionScope {
239
308
  if (mode === "staged") {
240
- return parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
309
+ return parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff", "--relative"]), changedScope);
241
310
  }
242
311
  if (mode === "unstaged") {
243
- return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope);
312
+ return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--relative"]), changedScope);
244
313
  }
245
314
  if (mode === "working-tree") {
246
315
  return mergeScopes(
247
316
  [
248
- parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope),
249
- parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff"]), changedScope),
317
+ parseUnifiedDiff(gitOutput(["diff", "--cached", "--unified=0", "--no-color", "--no-ext-diff", "--relative"]), changedScope),
318
+ parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--relative"]), changedScope),
250
319
  untrackedFileScope(changedScope),
251
320
  ],
252
321
  changedScope,
253
322
  );
254
323
  }
255
- return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--end-of-options", mode]), changedScope);
324
+ return parseUnifiedDiff(gitOutput(["diff", "--unified=0", "--no-color", "--no-ext-diff", "--relative", "--end-of-options", mode]), changedScope);
256
325
  }
257
326
 
258
327
  // Parses a unified diff into file-level and hunk-level scope.
@@ -2,60 +2,119 @@
2
2
  // public-property + readonly candidates, inconsistent casing, acronym case, interface fields.
3
3
  // Pulls the declaration walkers and casing helpers out of cli.ts so the orchestrator just calls
4
4
  // the entry points.
5
- import { type FunctionBlock, parameterNames } from "./blocks.ts";
6
- import { type ExportedDeclaration, exportedDeclarations, pushMissingPublicDocFinding } from "./doc-rules.ts";
5
+ import { exportedDeclarations, pushMissingPublicDocFinding } from "./doc-rules.ts";
7
6
  import { type SourceFile } from "./discovery.ts";
8
7
  import { makeFinding } from "./findings.ts";
9
- import { fileBaseName, finding, normalizedIdentifier } from "./findings-helpers.ts";
8
+ import { fileBaseName, finding, normalizedIdentifier, parameterNames } from "./findings-helpers.ts";
10
9
  import { pushBooleanPrefixAt, pushNegativeBooleanAt, type NamingSurface } from "./naming-pushers.ts";
10
+ import { callableMatchPoints, declarationOwnershipPoints, type IdentifierOwner, type OwnedDeclarationPoint, type ParsedScript } from "./parsed-script.ts";
11
+ import { publicExportDeclarations, type PublicExportDeclaration } from "./public-exports.ts";
11
12
  import { byteLine } from "./text-scans.ts";
12
13
  import type { Config, Finding } from "./types.ts";
13
14
 
14
- // One identifier observation. `line` is the declaration line in the original source so the casing
15
- // and acronym rules can report a stable, reproducible location.
16
- interface DeclaredIdentifier {
15
+ /*
16
+ * One shared naming observation used by casing and acronym diagnostics. Name, line, and surface
17
+ * preserve the report rows users already saw, while syntax-derived owner fields explain which
18
+ * declaration or lexical scope the casing rule compares.
19
+ */
20
+ interface DeclaredIdentifier extends IdentifierOwner {
17
21
  name: string;
18
22
  line: number;
19
23
  surface: NamingSurface;
20
24
  }
21
25
 
22
- // Aggregates `const`/`let`/`var` declarations, callable parameters, and interface fields into a
23
- // single de-duplicated list. The naming rules walk this once instead of re-parsing the file.
24
- export function collectDeclaredIdentifiers(source: string, codeSource: string, blocks: FunctionBlock[]): DeclaredIdentifier[] {
26
+ const MODULE_NAMING_OWNER: IdentifierOwner = { ownerId: "module", ownerKind: "module" };
27
+
28
+ // Adds shared syntax owners to the existing text inventory, preserving every name/line/surface row.
29
+ // The casing and acronym rules receive one ordered inventory without another parse or AST walk.
30
+ export function collectDeclaredIdentifiers(source: string, codeSource: string, parsed: ParsedScript): DeclaredIdentifier[] {
25
31
  const inventory: DeclaredIdentifier[] = [];
26
- const seen = new Set<string>();
27
- const push = (name: string, line: number, surface: NamingSurface): void => {
28
- if (!name) return;
29
- const key = `${name}@${line}@${surface}`;
30
- if (seen.has(key)) return;
31
- seen.add(key);
32
- inventory.push({ name, line, surface });
32
+ const seenIdentifiers = new Set<string>();
33
+ // Records one identifier per (name, line, surface) so overlapping scans stay de-duplicated.
34
+ const recordIdentifier = (name: string, line: number, surface: NamingSurface, owner: IdentifierOwner): void => {
35
+ // Recovered or unsupported declarations can have no simple name, so users see no row for them.
36
+ if (!name) {
37
+ return;
38
+ }
39
+ const observationKey = `${name}@${line}@${surface}`;
40
+ // Overlapping syntax shapes must still produce only one acronym and casing observation.
41
+ if (seenIdentifiers.has(observationKey)) {
42
+ return;
43
+ }
44
+ seenIdentifiers.add(observationKey);
45
+ // Module and anonymous-function rows omit ownerName instead of exposing an undefined field.
46
+ inventory.push({
47
+ name,
48
+ line,
49
+ surface,
50
+ ownerId: owner.ownerId,
51
+ ownerKind: owner.ownerKind,
52
+ ...(owner.ownerName === undefined ? {} : { ownerName: owner.ownerName }),
53
+ });
33
54
  };
34
55
 
56
+ const declarationOwnership = declarationOwnershipPoints(parsed);
57
+ const variableOwners = declarationOwnerLookup(declarationOwnership.variableDeclarations);
58
+ const contractFieldOwners = declarationOwnerLookup(declarationOwnership.contractFields);
59
+ // The legacy text matcher remains authoritative so acronym inventory contents do not change.
35
60
  for (const match of codeSource.matchAll(/\b(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g)) {
36
- push(match[1] ?? "", byteLine(source, match.index ?? 0), "declaration");
61
+ // A recovered match without a capture becomes empty and is rejected by recordIdentifier.
62
+ const name = match[1] ?? "";
63
+ // A missing regex index is a recovered start-of-file match, so line one is the safe anchor.
64
+ const line = byteLine(source, match.index ?? 0);
65
+ // A legacy-only text token has no syntax declaration; module ownership preserves acronym input.
66
+ const declarationOwner = variableOwners.get(declarationOwnerKey(name, line)) ?? MODULE_NAMING_OWNER;
67
+ recordIdentifier(name, line, "declaration", declarationOwner);
37
68
  }
38
- for (const block of blocks) {
39
- for (const parameter of parameterNames(block.params)) {
40
- push(parameter.name, block.declarationLine, "parameter");
69
+ // Shared callable points retain one-block-per-line order and the existing parameter text policy.
70
+ for (const callable of callableMatchPoints(parsed)) {
71
+ // Every simple parameter belongs to the callable users see as its nearest naming boundary.
72
+ for (const parameter of parameterNames(callable.params)) {
73
+ recordIdentifier(parameter.name, callable.lineIndex + 1, "parameter", callable);
41
74
  }
42
75
  }
43
- for (const fieldMatch of collectInterfaceFieldDeclarations(source, codeSource)) {
44
- push(fieldMatch.name, fieldMatch.line, "interface-field");
76
+ // The existing contract walker remains last, preserving the shared inventory sequence exactly.
77
+ for (const field of collectInterfaceFieldDeclarations(source, codeSource)) {
78
+ // A recovered field without an AST point stays visible to acronym checks under module fallback.
79
+ const contractFieldOwner = contractFieldOwners.get(declarationOwnerKey(field.name, field.line)) ?? MODULE_NAMING_OWNER;
80
+ recordIdentifier(field.name, field.line, "interface-field", contractFieldOwner);
45
81
  }
46
82
  return inventory;
47
83
  }
48
84
 
49
- // Walks every interface body line and matches the field declaration regex. Used both for the
50
- // naming inventory (above) and for the per-field interface rules (boolean prefix, negative-boolean).
51
- function collectInterfaceFieldDeclarations(source: string, codeSource: string): DeclaredIdentifier[] {
85
+ // Indexes syntax owners by the legacy name/line tuple so text observations gain stable ownership.
86
+ function declarationOwnerLookup(declarations: OwnedDeclarationPoint[]): Map<string, IdentifierOwner> {
87
+ const owners = new Map<string, IdentifierOwner>();
88
+ // Source order wins when recovered syntax produces duplicate name/line rows, matching de-duplication.
89
+ for (const declaration of declarations) {
90
+ const ownerKey = declarationOwnerKey(declaration.name, declaration.line);
91
+ // The first syntax declaration is the same observation the legacy inventory retains.
92
+ if (!owners.has(ownerKey)) {
93
+ owners.set(ownerKey, declaration);
94
+ }
95
+ }
96
+ return owners;
97
+ }
98
+
99
+ // Builds the stable lookup tuple shared by syntax owner rows and legacy text observations.
100
+ function declarationOwnerKey(name: string, line: number): string {
101
+ return `${name}@${line}`;
102
+ }
103
+
104
+ // Walks existing interface/type body lines so owner enrichment cannot expand acronym coverage.
105
+ function collectInterfaceFieldDeclarations(source: string, codeSource: string): Array<{ name: string; line: number }> {
52
106
  const fieldRegex = /^[ \t]*(?:readonly\s+)?([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/;
53
- const out: DeclaredIdentifier[] = [];
107
+ const declarations: Array<{ name: string; line: number }> = [];
108
+ // Each direct body line retains the same source order and line anchor as previous reports.
54
109
  for (const { lineIndex, sourceLine } of walkInterfaceBodyLines(source, codeSource)) {
110
+ // A line without the supported field prefix produces an empty name and no inventory row.
55
111
  const name = sourceLine.match(fieldRegex)?.[1] ?? "";
56
- if (name) out.push({ name, line: lineIndex + 1, surface: "interface-field" });
112
+ // Unsupported or recovered field syntax has no user-facing identifier row.
113
+ if (name) {
114
+ declarations.push({ name, line: lineIndex + 1 });
115
+ }
57
116
  }
58
- return out;
117
+ return declarations;
59
118
  }
60
119
 
61
120
  // Strips separators only so `userId`, `user_id`, and `userID` collapse, while `adr013` and
@@ -66,14 +125,16 @@ function casingCanonicalKey(name: string): string {
66
125
  }
67
126
 
68
127
  /*
69
- * Groups identifiers by canonical key, then filters out boundary surfaces before reporting. The
70
- * split helper flow is intentional: the rule must preserve same-scope drift signal while refusing
71
- * to command rewrites of constants, DTO fields, or intentionally-unused `_` names. Error behavior:
72
- * never throws; it reports drift by appending findings only.
128
+ * Groups identifiers by owner and canonical key, then filters boundary surfaces before reporting.
129
+ * The split flow preserves drift inside one user-reviewed scope while refusing to command rewrites
130
+ * across DTO/UI contracts, functions, constants, or intentionally-unused `_` names. Error behavior:
131
+ * never throws; it appends findings only. Invariant: one owner-key group yields at most one finding.
73
132
  */
74
- export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredIdentifier[], findings: Finding[]): void {
133
+ export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredIdentifier[], config: Config, findings: Finding[]): void {
134
+ // Each owner-key group can produce at most one actionable diagnostic for the CLI user.
75
135
  for (const entries of declaredIdentifierGroups(inventory).values()) {
76
- const candidate = inconsistentCasingCandidate(entries);
136
+ const candidate = inconsistentCasingCandidate(entries, config.acceptedCasingPairs);
137
+ // A single spelling after boundary filtering means the reviewed scope is already consistent.
77
138
  if (!candidate) {
78
139
  continue;
79
140
  }
@@ -81,21 +142,33 @@ export function analyseInconsistentCasing(file: SourceFile, inventory: DeclaredI
81
142
  }
82
143
  }
83
144
 
84
- // Builds canonical-key groups once so the reporting pass can stay focused on rule semantics.
145
+ // Exact pair exemptions are case-insensitive but retain separators.
146
+ function isAcceptedCasingPair(first: DeclaredIdentifier, second: DeclaredIdentifier, acceptedPairs: Set<string>): boolean {
147
+ const forward = `${first.name}:${second.name}`.toLowerCase();
148
+ const reverse = `${second.name}:${first.name}`.toLowerCase();
149
+ return acceptedPairs.has(forward) || acceptedPairs.has(reverse);
150
+ }
151
+
152
+ // Builds owner-plus-canonical groups once so the reporting pass cannot compare unrelated surfaces.
85
153
  function declaredIdentifierGroups(inventory: DeclaredIdentifier[]): Map<string, DeclaredIdentifier[]> {
86
154
  const groups = new Map<string, DeclaredIdentifier[]>();
155
+ // Every inventory row keeps its existing source order inside its deterministic owner boundary.
87
156
  for (const entry of inventory) {
88
- const key = casingCanonicalKey(entry.name);
89
- if (!key) continue;
90
- const list = groups.get(key) ?? [];
157
+ const canonicalKey = casingCanonicalKey(entry.name);
158
+ // A recovered empty identifier has no comparison key and cannot help a user fix casing.
159
+ if (!canonicalKey) {
160
+ continue;
161
+ }
162
+ const ownerKey = `${entry.ownerId}\0${canonicalKey}`;
163
+ const list = groups.get(ownerKey) ?? [];
91
164
  list.push(entry);
92
- groups.set(key, list);
165
+ groups.set(ownerKey, list);
93
166
  }
94
167
  return groups;
95
168
  }
96
169
 
97
170
  // Invariant: returns the exact variant pair to report after boundary-aware suppression has run.
98
- function inconsistentCasingCandidate(entries: DeclaredIdentifier[]): { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] } | undefined {
171
+ function inconsistentCasingCandidate(entries: DeclaredIdentifier[], acceptedPairs: Set<string>): { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] } | undefined {
99
172
  const reportableEntries = casingReportableEntries(entries);
100
173
  const sameSurfaceEntries = sameCasingSurfaceEntries(reportableEntries);
101
174
  const surfaces = [...new Set(sameSurfaceEntries.map((entry) => entry.name))].sort();
@@ -103,27 +176,58 @@ function inconsistentCasingCandidate(entries: DeclaredIdentifier[]): { first: De
103
176
  return undefined;
104
177
  }
105
178
  const sorted = [...sameSurfaceEntries].sort((a, b) => a.line - b.line);
106
- const first = sorted[0];
107
- const second = sorted.find((entry, index) => index > 0 && entry.name !== first?.name);
108
- return first && second ? { first, second, surfaces } : undefined;
179
+ for (let firstIndex = 0; firstIndex < sorted.length; firstIndex += 1) {
180
+ const first = sorted[firstIndex];
181
+ if (!first) {
182
+ continue;
183
+ }
184
+ const second = sorted.find((entry, secondIndex) => secondIndex > firstIndex && entry.name !== first.name && !isAcceptedCasingPair(first, entry, acceptedPairs));
185
+ if (second) {
186
+ return { first, second, surfaces };
187
+ }
188
+ }
189
+ return undefined;
109
190
  }
110
191
 
111
192
  // Builds the stable finding after candidate selection so fingerprint shape stays in one place.
112
193
  function inconsistentCasingFinding(file: SourceFile, candidate: { first: DeclaredIdentifier; second: DeclaredIdentifier; surfaces: string[] }): Finding {
194
+ const ownerLabel = casingOwnerLabel(candidate.first);
113
195
  return makeFinding({
114
196
  ruleId: "naming.inconsistent-casing",
115
- message: `Identifier \`${candidate.second.name}\` shares a canonical key with \`${candidate.first.name}\` in the same file.`,
197
+ message: `Identifier \`${candidate.second.name}\` shares a canonical key with \`${candidate.first.name}\` within ${ownerLabel}.`,
116
198
  filePath: file.displayPath,
117
199
  line: candidate.second.line,
118
200
  severity: "advisory",
119
201
  pillar: "naming",
120
202
  confidence: "medium",
121
203
  symbol: candidate.second.name,
122
- remediation: "Choose one form and use it consistently within the file.",
123
- metadata: { variants: candidate.surfaces },
204
+ remediation: `Choose one form within ${ownerLabel}, or add the exact alias pair to allowlists.acceptedCasingPairs.`,
205
+ metadata: {
206
+ variants: candidate.surfaces,
207
+ ownerId: candidate.first.ownerId,
208
+ ownerKind: candidate.first.ownerKind,
209
+ ...(candidate.first.ownerName === undefined ? {} : { ownerName: candidate.first.ownerName }),
210
+ },
124
211
  });
125
212
  }
126
213
 
214
+ // Describes the comparison boundary in the same language a CLI user sees in source and reports.
215
+ function casingOwnerLabel(owner: IdentifierOwner): string {
216
+ switch (owner.ownerKind) {
217
+ case "module":
218
+ return "the module scope";
219
+ case "function":
220
+ // Anonymous callbacks still give users a precise lexical boundary without a made-up name.
221
+ return owner.ownerName ? `function \`${owner.ownerName}\`` : "the containing function";
222
+ case "interface":
223
+ // Recovered contract names are absent only on malformed source, where a neutral label is safer.
224
+ return `interface \`${owner.ownerName ?? "anonymous"}\``;
225
+ case "type-literal":
226
+ // Named aliases normally supply this label; malformed source falls back without throwing.
227
+ return `type literal \`${owner.ownerName ?? "anonymous"}\``;
228
+ }
229
+ }
230
+
127
231
  // `_event` is the standard intentionally-unused spelling; comparing it with `event` would tell an
128
232
  // agent to remove useful boundary information rather than fix casing drift.
129
233
  function casingReportableEntries(entries: DeclaredIdentifier[]): DeclaredIdentifier[] {
@@ -169,10 +273,13 @@ function acronymCaseClass(token: string): "upper" | "lower" | "title" {
169
273
  }
170
274
 
171
275
  /*
172
- * Reports when an acronym from `config.knownAcronyms` appears as all-caps plus another case form.
173
- * The all-caps gate exists because lower/title-only forms like `apiToken` beside `googleApiKey`
174
- * are idiomatic enough to avoid noisy findings. Like `analyseInconsistentCasing`, the finding
175
- * anchors on the second occurrence so the stable fingerprint sticks to the divergence.
276
+ * Reports when an acronym from `config.knownAcronyms` appears as all-caps plus another case form
277
+ * among names whose casing the author chose. SCREAMING_SNAKE constants and all-lower names are
278
+ * excluded because their convention fixes the acronym's case - a `RAW_HTML_TAGS` constant beside
279
+ * `startsHtmlBlock` is standard TypeScript, not drift. The all-caps gate exists because
280
+ * lower/title-only forms like `apiToken` beside `googleApiKey` are idiomatic enough to avoid
281
+ * noisy findings. Like `analyseInconsistentCasing`, the finding anchors on the second occurrence
282
+ * so the stable fingerprint sticks to the divergence.
176
283
  */
177
284
  export function analyseAcronymCase(file: SourceFile, inventory: DeclaredIdentifier[], config: Config, findings: Finding[]): void {
178
285
  const observed = new Map<string, Map<string, { name: string; line: number }>>();
@@ -184,9 +291,10 @@ export function analyseAcronymCase(file: SourceFile, inventory: DeclaredIdentifi
184
291
  }
185
292
  }
186
293
 
187
- // Adds one identifier's acronym tokens to the observed case map, skipping fixture-only constants.
294
+ // Adds one identifier's acronym tokens to the observed case map, skipping fixture-only constants
295
+ // and names whose acronym casing the convention already fixes.
188
296
  function recordAcronymCases(observed: Map<string, Map<string, { name: string; line: number }>>, config: Config, entry: DeclaredIdentifier): void {
189
- if (isFixtureIdentifier(entry.name)) {
297
+ if (isFixtureIdentifier(entry.name) || isConventionForcedAcronymCasing(entry.name)) {
190
298
  return;
191
299
  }
192
300
  for (const token of tokensForAcronymCheck(entry.name)) {
@@ -236,6 +344,13 @@ function isFixtureIdentifier(name: string): boolean {
236
344
  return /(?:^|[_-])fixture(?:[_-]|$)/i.test(name);
237
345
  }
238
346
 
347
+ // SCREAMING_SNAKE constants and all-lower names cannot choose an acronym casing - the convention
348
+ // fixes it - so they carry no drift signal against camelCase/PascalCase names, where the author
349
+ // does choose (`parsedHtml` versus `rawHTML`). Only chosen casings are compared file-wide.
350
+ function isConventionForcedAcronymCasing(name: string): boolean {
351
+ return isScreamingConstant(name) || name === name.toLowerCase();
352
+ }
353
+
239
354
  /*
240
355
  * Walks every interface field and runs two checks per boolean field: boolean prefix and
241
356
  * negative boolean. The stable ordering matches `pushBooleanPrefixAt` → `pushNegativeBooleanAt`
@@ -256,24 +371,32 @@ export function analyseInterfaceFields(file: SourceFile, source: string, codeSou
256
371
 
257
372
  const INTERFACE_HEADER_REGEX = /\b(?:export\s+)?(?:interface\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?(?:\s+extends\s+[^{]+)?|type\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s*<[^>]*>)?\s*=\s*)\s*\{/g;
258
373
 
374
+ // Streams the depth-1 member lines of every interface/type-literal body so the field rules see
375
+ // each declaration exactly once. Mapped types (`{ [K in ...] }`) are skipped - no field names there.
259
376
  function* walkInterfaceBodyLines(source: string, codeSource: string): Generator<{ lineIndex: number; sourceLine: string }> {
260
377
  const codeLines = codeSource.split(/\r?\n/);
261
378
  const sourceLines = source.split(/\r?\n/);
262
379
  for (const header of codeSource.matchAll(INTERFACE_HEADER_REGEX)) {
263
380
  const headerEnd = (header.index ?? 0) + header[0].length;
381
+ // An index-signature-first body is a mapped type, not a field list the naming rules can judge.
264
382
  if (codeSource.slice(headerEnd, headerEnd + 30).trimStart().startsWith("[")) {
265
383
  continue;
266
384
  }
267
- const headerLineIndex = byteLine(source, headerEnd - 1) - 1;
268
- const headerLine = codeLines[headerLineIndex] ?? "";
269
- let depth = 1 + countBraceChange(headerLine.slice(headerLine.lastIndexOf("{") + 1));
270
- for (let lineIndex = headerLineIndex + 1; depth > 0 && lineIndex < codeLines.length; lineIndex += 1) {
271
- const codeLine = codeLines[lineIndex] ?? "";
272
- if (depth === 1) {
273
- yield { lineIndex, sourceLine: sourceLines[lineIndex] ?? "" };
274
- }
275
- depth += countBraceChange(codeLine);
385
+ yield* interfaceBodyMemberLines(codeLines, sourceLines, byteLine(source, headerEnd - 1) - 1);
386
+ }
387
+ }
388
+
389
+ // Walks one body from its header line, yielding lines while brace depth stays at the member level.
390
+ function* interfaceBodyMemberLines(codeLines: string[], sourceLines: string[], headerLineIndex: number): Generator<{ lineIndex: number; sourceLine: string }> {
391
+ const headerLine = codeLines[headerLineIndex] ?? "";
392
+ let depth = 1 + countBraceChange(headerLine.slice(headerLine.lastIndexOf("{") + 1));
393
+ for (let lineIndex = headerLineIndex + 1; depth > 0 && lineIndex < codeLines.length; lineIndex += 1) {
394
+ const codeLine = codeLines[lineIndex] ?? "";
395
+ // Depth 1 means we are directly inside the declaration body, where the member lines live.
396
+ if (depth === 1) {
397
+ yield { lineIndex, sourceLine: sourceLines[lineIndex] ?? "" };
276
398
  }
399
+ depth += countBraceChange(codeLine);
277
400
  }
278
401
  }
279
402
 
@@ -295,32 +418,54 @@ function countBraceChange(text: string): number {
295
418
  * Three class-pillar rules in their stable, deterministic emission order: exported-declaration
296
419
  * docs and file-name mismatch, public-property, readonly candidates.
297
420
  */
298
- export function analyseClassRules(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
299
- analyseExportedDeclarations(file, source, codeSource, findings);
421
+ export function analyseClassRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
422
+ analyseExportedDeclarations(file, source, codeSource, config, findings, parsed);
300
423
  analysePublicProperties(file, source, codeSource, findings);
301
424
  analyseReadonlyCandidates(file, source, codeSource, findings);
302
425
  }
303
426
 
304
427
  /*
305
- * Two rules per exported declaration. Both fire from one walk so the file isn't re-scanned for
306
- * each rule. Reports the stable `docs.missing-public-doc` and `naming.class-file-mismatch`
307
- * findings per declaration.
428
+ * Keeps public-doc checks on direct exports, then evaluates class/file naming against the complete
429
+ * syntax inventory so reports cover default/re-export forms without changing the documentation contract.
308
430
  */
309
- function analyseExportedDeclarations(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
310
- for (const declaration of exportedDeclarations(source, codeSource)) {
431
+ function analyseExportedDeclarations(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
432
+ const directlyExportedDeclarations = exportedDeclarations(source, codeSource);
433
+ // Public-doc findings retain their existing direct-export policy and deterministic source order.
434
+ for (const declaration of directlyExportedDeclarations) {
311
435
  pushMissingPublicDocFinding(file, source, declaration, findings);
312
- pushClassFileMismatchFinding(file, declaration, findings);
313
436
  }
437
+ // Direct internal callers without a parse retain the legacy five-kind inventory; normal scans use syntax.
438
+ const modulePublicDeclarations = parsed
439
+ ? publicExportDeclarations(parsed)
440
+ : directlyExportedDeclarations.map((declaration) => ({ ...declaration, kind: declaration.kind as PublicExportDeclaration["kind"] }));
441
+ pushClassFileMismatchFinding(file, modulePublicDeclarations, config, findings);
314
442
  }
315
443
 
316
444
  /*
317
- * Compares normalised forms (lowercased, no underscores) so `UserProfile` and `user-profile.ts`
318
- * match. Reports the stable `naming.class-file-mismatch` finding when the exported class diverges
319
- * from the file name.
445
+ * Reports a normalized class/file mismatch only when one named class is the module's sole public
446
+ * declaration, keeping feature modules quiet while preserving the stable finding anchor.
320
447
  */
321
- function pushClassFileMismatchFinding(file: SourceFile, declaration: ExportedDeclaration, findings: Finding[]): void {
448
+ function pushClassFileMismatchFinding(file: SourceFile, publicDeclarations: PublicExportDeclaration[], config: Config, findings: Finding[]): void {
449
+ // Feature modules with a second public declaration do not claim one primary class-to-file convention.
450
+ if (publicDeclarations.length !== 1) {
451
+ return;
452
+ }
453
+ const declaration = publicDeclarations[0];
454
+ // Anonymous defaults and non-class exports have no named class for a user to align with the file.
455
+ if (!declaration || declaration.kind !== "class" || declaration.name === "default") {
456
+ return;
457
+ }
322
458
  const fileName = fileBaseName(file.displayPath);
323
- if (declaration.kind !== "class" || normalizedIdentifier(declaration.name) === normalizedIdentifier(fileName)) {
459
+ const acceptedPair = `${fileName}:${declaration.name}`.toLowerCase();
460
+ // Pair-level configuration preserves an intentional feature-file/class-role convention narrowly.
461
+ if (config.acceptedClassFilePairs.has(acceptedPair)) {
462
+ return;
463
+ }
464
+ // A normalized name match already lets a report user locate the class from the file name. An
465
+ // alias counts too: `export { Foo as Bar }` in `bar.ts` already advertises the matching name, so
466
+ // telling the reader to rename would undo an alignment they have made.
467
+ const publicNames = declaration.exportedName === undefined ? [declaration.name] : [declaration.name, declaration.exportedName];
468
+ if (publicNames.some((publicName) => normalizedIdentifier(publicName) === normalizedIdentifier(fileName))) {
324
469
  return;
325
470
  }
326
471
  findings.push(
@@ -333,8 +478,13 @@ function pushClassFileMismatchFinding(file: SourceFile, declaration: ExportedDec
333
478
  pillar: "naming",
334
479
  confidence: "medium",
335
480
  symbol: declaration.name,
336
- remediation: "Rename the class or file so the primary export is easy to locate.",
337
- metadata: { className: declaration.name, fileName },
481
+ remediation: "Rename the class or file, or add the exact fileBase:ClassName pair to allowlists.acceptedClassFilePairs.",
482
+ metadata: {
483
+ className: declaration.name,
484
+ fileName,
485
+ candidatePrimaryExport: true,
486
+ publicExports: publicDeclarations.map((publicDeclaration) => `${publicDeclaration.kind}:${publicDeclaration.name}`).sort(),
487
+ },
338
488
  }),
339
489
  );
340
490
  }