@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
@@ -0,0 +1,163 @@
1
+ // Metadata classifiers for `security.process-exec` findings. They turn a process call's
2
+ // first argument and shell option into review hints without changing whether the rule fires.
3
+ import { escapeRegex } from "./findings-helpers.ts";
4
+
5
+ /** Closed command-source vocabulary used by process-exec grading and finding metadata. */
6
+ export type ProcessExecArgumentSource = "literal" | "process-exec-path" | "local-const" | "local-builder" | "parameter" | "member" | "template" | "unknown";
7
+
8
+ /** Typed process-exec classifier result used to grade and serialize finding metadata. */
9
+ export type ProcessExecMetadata = {
10
+ callName: string;
11
+ argumentSource: ProcessExecArgumentSource;
12
+ isShellEnabled: boolean;
13
+ };
14
+
15
+ // Stable scanner state for the first-argument boundary walk.
16
+ interface ArgumentScanState {
17
+ depth: number;
18
+ quote: string | undefined;
19
+ }
20
+
21
+ // Stable result of consuming one character in the first-argument scanner.
22
+ interface ArgumentScanStep {
23
+ state: ArgumentScanState;
24
+ skip: number;
25
+ isBoundary: boolean;
26
+ }
27
+
28
+ /**
29
+ * Builds non-suppressing metadata for a child-process finding.
30
+ *
31
+ * @param callName Matched process API name, for example `spawn` or `execSync`.
32
+ * @param rawSource Original source text used for literal and local-const classification.
33
+ * @param callStart Byte offset where the process call starts in the file.
34
+ * @param rawSegment Original source segment from call start through closing paren.
35
+ * @param codeSegment Masked source segment used to read the shell option safely.
36
+ * @returns Stable metadata describing command-source shape and shell mode.
37
+ */
38
+ export function processExecMetadata(callName: string, rawSource: string, callStart: number, rawSegment: string, codeSegment: string): ProcessExecMetadata {
39
+ const firstArgument = firstProcessCallArgument(rawSegment);
40
+ return {
41
+ callName,
42
+ argumentSource: processExecArgumentSource(rawSource, callStart, firstArgument),
43
+ isShellEnabled: processExecShellEnabled(callName, codeSegment),
44
+ };
45
+ }
46
+
47
+ // Extracts the first top-level call argument so commas inside arrays, objects, calls, or strings
48
+ // do not misclassify `spawn("node", ["script,arg"])` as a dynamic command.
49
+ function firstProcessCallArgument(rawSegment: string): string {
50
+ const argsText = rawSegment.slice(rawSegment.indexOf("(") + 1, rawSegment.lastIndexOf(")"));
51
+ return firstTopLevelArgument(argsText).trim();
52
+ }
53
+
54
+ // Walks one argument list with quote and nesting state. The invariant is deliberately narrow:
55
+ // find only the first top-level comma, because command-source classification does not need parsing.
56
+ function firstTopLevelArgument(argsText: string): string {
57
+ let state: ArgumentScanState = { depth: 0, quote: undefined };
58
+ for (let index = 0; index < argsText.length; index += 1) {
59
+ const step = argumentScanStep(argsText, index, state);
60
+ if (step.isBoundary) {
61
+ return argsText.slice(0, index);
62
+ }
63
+ state = step.state;
64
+ index += step.skip;
65
+ }
66
+ return argsText;
67
+ }
68
+
69
+ // Advances one character in the argument scan while keeping string escapes and nesting separate.
70
+ function argumentScanStep(argsText: string, index: number, state: ArgumentScanState): ArgumentScanStep {
71
+ const character = argsText[index] ?? "";
72
+ if (state.quote) {
73
+ return quotedArgumentScanStep(argsText, index, state, character);
74
+ }
75
+ if (isQuoteDelimiter(character)) {
76
+ return scanStep({ depth: state.depth, quote: character });
77
+ }
78
+ if (isOpeningDelimiter(character)) {
79
+ return scanStep({ depth: state.depth + 1, quote: undefined });
80
+ }
81
+ if (isClosingDelimiter(character)) {
82
+ return scanStep({ depth: Math.max(0, state.depth - 1), quote: undefined });
83
+ }
84
+ return scanStep(state, character === "," && state.depth === 0);
85
+ }
86
+
87
+ // Handles one quoted character; escaped characters skip the next byte so an escaped quote stays inside.
88
+ function quotedArgumentScanStep(argsText: string, index: number, state: ArgumentScanState, character: string): ArgumentScanStep {
89
+ if (character === "\\" && index + 1 < argsText.length) {
90
+ return scanStep(state, false, 1);
91
+ }
92
+ if (character === state.quote) {
93
+ return scanStep({ depth: state.depth, quote: undefined });
94
+ }
95
+ return scanStep(state);
96
+ }
97
+
98
+ // Builds the scan step object with explicit defaults so the main loop stays branch-light.
99
+ function scanStep(state: ArgumentScanState, isBoundary = false, skip = 0): ArgumentScanStep {
100
+ return { state, isBoundary, skip };
101
+ }
102
+
103
+ // Quote delimiters are all significant because shell-command strings commonly use any of them.
104
+ function isQuoteDelimiter(character: string): boolean {
105
+ return character === "\"" || character === "'" || character === "`";
106
+ }
107
+
108
+ // Nested call/array/object delimiters suppress comma boundaries until they close.
109
+ function isOpeningDelimiter(character: string): boolean {
110
+ return character === "(" || character === "[" || character === "{";
111
+ }
112
+
113
+ // Closing delimiters unwind nesting but never below zero, which keeps malformed snippets bounded.
114
+ function isClosingDelimiter(character: string): boolean {
115
+ return character === ")" || character === "]" || character === "}";
116
+ }
117
+
118
+ // Classifies the command operand for reviewer triage. This is advisory metadata only: every emitted
119
+ // process-exec finding still requires human review of the surrounding command construction.
120
+ function processExecArgumentSource(rawSource: string, callStart: number, firstArgument: string): ProcessExecArgumentSource {
121
+ if (firstArgument === "process.execPath") {
122
+ return "process-exec-path";
123
+ }
124
+ if (/^`/.test(firstArgument)) {
125
+ return /\$\{/.test(firstArgument) ? "template" : "literal";
126
+ }
127
+ if (/^["'][^"']*["']$/.test(firstArgument)) {
128
+ return "literal";
129
+ }
130
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(firstArgument)) {
131
+ return "local-builder";
132
+ }
133
+ const identifier = firstArgument.match(/^[A-Za-z_$][A-Za-z0-9_$]*$/)?.[0];
134
+ if (identifier) {
135
+ return hasConstLiteralCommandDeclaration(rawSource, callStart, identifier) ? "local-const" : "parameter";
136
+ }
137
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)+/.test(firstArgument)) {
138
+ return "member";
139
+ }
140
+ return "unknown";
141
+ }
142
+
143
+ // Looks backward from the call for a same-scope `const command = "fixed"` shape so reviewers can
144
+ // distinguish fixed command vectors from parameter-driven command names. The initializer must be
145
+ // wholly one quoted literal: `"echo " + input` also contains a quoted fragment, and grading that as
146
+ // fixed would drop a shell-enabled, input-derived command from warning to advisory.
147
+ function hasConstLiteralCommandDeclaration(rawSource: string, callStart: number, identifier: string): boolean {
148
+ const declaration = rawSource.slice(0, callStart).match(new RegExp(`\\bconst\\s+${escapeRegex(identifier)}\\s*=\\s*([^;]+);\\s*$`, "s"));
149
+ const initializer = (declaration?.[1] ?? "").trim();
150
+ return /^(?:"[^"\\]*"|'[^'\\]*')$/.test(initializer);
151
+ }
152
+
153
+ // Reports default shell semantics: exec/execSync imply a shell unless an explicit option says false,
154
+ // while spawn/execFile variants default to shell-disabled unless explicitly enabled.
155
+ function processExecShellEnabled(callName: string, codeSegment: string): boolean {
156
+ if (/\bshell\s*:\s*true\b/.test(codeSegment)) {
157
+ return true;
158
+ }
159
+ if (/\bshell\s*:\s*false\b/.test(codeSegment)) {
160
+ return false;
161
+ }
162
+ return callName === "exec" || callName === "execSync";
163
+ }
package/src/profiles.ts CHANGED
@@ -186,6 +186,20 @@ export function isKnownRuleId(ruleId: string): boolean {
186
186
  return KNOWN_RULE_IDS.has(ruleId);
187
187
  }
188
188
 
189
+ // Option keys a rule descriptor declares for `rules.<id>.options`, empty when the rule has none.
190
+ // Exported for config validation so `config.ts` keeps depending on this module, not `rules.ts`.
191
+ const RULE_OPTION_KEYS: ReadonlyMap<string, readonly string[]> = new Map(DESCRIPTORS.map((descriptor) => [descriptor.ruleId, descriptor.optionKeys ?? []]));
192
+
193
+ /**
194
+ * Returns the option keys a rule accepts under `rules.<id>.options`.
195
+ *
196
+ * @param ruleId Rule id already validated against the catalogue.
197
+ * @returns The declared option keys; an empty array means the rule accepts no options.
198
+ */
199
+ export function ruleOptionKeys(ruleId: string): readonly string[] {
200
+ return RULE_OPTION_KEYS.get(ruleId) ?? [];
201
+ }
202
+
189
203
  /**
190
204
  * Returns the built-in profile names in catalogue order for error messages and CLI hints.
191
205
  *
@@ -63,7 +63,7 @@ function analysePackageScripts(file: ConfigSourceFile, source: string, scripts:
63
63
  continue;
64
64
  }
65
65
  pushRemoteInstallScriptFinding(file, source, scriptName, scriptCommand, findings);
66
- pushLifecycleScriptFinding(file, source, scriptName, findings);
66
+ pushLifecycleScriptFinding(file, source, scriptName, scriptCommand, findings);
67
67
  }
68
68
  }
69
69
 
@@ -93,13 +93,12 @@ function pushRemoteInstallScriptFinding(file: ConfigSourceFile, source: string,
93
93
  }
94
94
 
95
95
  /*
96
- * Reports the stable `security.risky-lifecycle-script` finding for any preinstall/install/
97
- * postinstall/prepare/prepublish/prepublishOnly hook - these run automatically and even disabling
98
- * install scripts in npm config is not universally honoured. Flagged as `warning` rather than
99
- * `error` because some packages legitimately need them.
96
+ * Reports the stable `security.risky-lifecycle-script` finding for install-time and side-effectful
97
+ * publish hooks. Validation-only publish gates stay quiet, but install/prepare hooks stay visible
98
+ * because they run in broader contexts than an explicit release check.
100
99
  */
101
- function pushLifecycleScriptFinding(file: ConfigSourceFile, source: string, scriptName: string, findings: Finding[]): void {
102
- if (!isLifecycleScript(scriptName)) {
100
+ function pushLifecycleScriptFinding(file: ConfigSourceFile, source: string, scriptName: string, scriptCommand: string, findings: Finding[]): void {
101
+ if (!isLifecycleScript(scriptName) || isValidationOnlyLifecycleCommand(scriptName, scriptCommand)) {
103
102
  return;
104
103
  }
105
104
  findings.push(
@@ -112,14 +111,14 @@ function pushLifecycleScriptFinding(file: ConfigSourceFile, source: string, scri
112
111
  pillar: "security",
113
112
  confidence: "medium",
114
113
  symbol: scriptName,
115
- remediation: "Move setup behind an explicit command unless lifecycle execution is required.",
114
+ remediation: "Review whether lifecycle execution is required; keep install/publish side effects behind explicit commands when possible.",
116
115
  metadata: { scriptName },
117
116
  }),
118
117
  );
119
118
  }
120
119
 
121
120
  /*
122
- * Walks every dependency section in a stable, deterministic order. `runtimeDependency` flag
121
+ * Walks every dependency section in a stable, deterministic order. The `isRuntimeDependency` flag
123
122
  * separates devDependencies from the rest because the broad-version rule should only fire for
124
123
  * runtime drift.
125
124
  */
@@ -129,35 +128,38 @@ function analysePackageDependencies(file: ConfigSourceFile, source: string, pkg:
129
128
  if (!dependencies) {
130
129
  continue;
131
130
  }
132
- const runtimeDependency = section === "dependencies" || section === "optionalDependencies";
131
+ const isRuntimeDependency = section === "dependencies" || section === "optionalDependencies";
133
132
  for (const [packageName, value] of Object.entries(dependencies)) {
134
133
  if (isString(value)) {
135
- analysePackageDependency(file, source, section, packageName, value, runtimeDependency, findings);
134
+ analysePackageDependency(file, source, section, packageName, value, isRuntimeDependency, findings);
136
135
  }
137
136
  }
138
137
  }
139
138
  }
140
139
 
140
+ // Runs both per-dependency checks for one entry; the emission order is a stable contract.
141
141
  function analysePackageDependency(
142
142
  file: ConfigSourceFile,
143
143
  source: string,
144
144
  section: string,
145
145
  packageName: string,
146
146
  versionSpec: string,
147
- runtimeDependency: boolean,
147
+ isRuntimeDependency: boolean,
148
148
  findings: Finding[],
149
149
  ): void {
150
- pushUrlDependencyFinding(file, source, section, packageName, versionSpec, runtimeDependency, findings);
151
- pushBroadRuntimeDependencyFinding(file, source, section, packageName, versionSpec, runtimeDependency, findings);
150
+ pushUrlDependencyFinding(file, source, section, packageName, versionSpec, isRuntimeDependency, findings);
151
+ pushBroadRuntimeDependencyFinding(file, source, section, packageName, versionSpec, isRuntimeDependency, findings);
152
152
  }
153
153
 
154
+ // Flags URL/git/file version specs, which bypass registry auditing.
155
+ // Stable `security.url-dependency` contract: reports exactly one finding per offending spec.
154
156
  function pushUrlDependencyFinding(
155
157
  file: ConfigSourceFile,
156
158
  source: string,
157
159
  section: string,
158
160
  packageName: string,
159
161
  versionSpec: string,
160
- runtimeDependency: boolean,
162
+ isRuntimeDependency: boolean,
161
163
  findings: Finding[],
162
164
  ): void {
163
165
  if (!isUrlDependency(versionSpec)) {
@@ -174,21 +176,23 @@ function pushUrlDependencyFinding(
174
176
  confidence: "medium",
175
177
  symbol: packageName,
176
178
  remediation: "Prefer a registry package version that can be locked and audited.",
177
- metadata: { packageName, section, runtimeDependency },
179
+ metadata: { packageName, section, runtimeDependency: isRuntimeDependency },
178
180
  }),
179
181
  );
180
182
  }
181
183
 
184
+ // Flags broad runtime version ranges (`*`, `latest`, bare majors) under the stable
185
+ // `waste.broad-runtime-version` contract: reports runtime sections only; dev sections must stay exempt.
182
186
  function pushBroadRuntimeDependencyFinding(
183
187
  file: ConfigSourceFile,
184
188
  source: string,
185
189
  section: string,
186
190
  packageName: string,
187
191
  versionSpec: string,
188
- runtimeDependency: boolean,
192
+ isRuntimeDependency: boolean,
189
193
  findings: Finding[],
190
194
  ): void {
191
- if (!runtimeDependency || !isBroadRuntimeVersion(versionSpec)) {
195
+ if (!isRuntimeDependency || !isBroadRuntimeVersion(versionSpec)) {
192
196
  return;
193
197
  }
194
198
  findings.push(
@@ -405,6 +409,20 @@ function isLifecycleScript(scriptName: string): boolean {
405
409
  return ["preinstall", "install", "postinstall", "prepare", "prepublish", "prepublishOnly"].includes(scriptName);
406
410
  }
407
411
 
412
+ // Allows closed-list validation commands in publish hooks while rejecting shell composition.
413
+ function isValidationOnlyLifecycleCommand(scriptName: string, command: string): boolean {
414
+ if (!["prepublish", "prepublishOnly"].includes(scriptName)) {
415
+ return false;
416
+ }
417
+ const normalizedCommand = command.trim().replace(/\s+/g, " ");
418
+ if (/[;&|`$<>]/.test(normalizedCommand)) {
419
+ return false;
420
+ }
421
+ return VALIDATION_ONLY_LIFECYCLE_COMMANDS.has(normalizedCommand);
422
+ }
423
+
424
+ const VALIDATION_ONLY_LIFECYCLE_COMMANDS = new Set(["npm run check", "npm test", "npm run test", "npm run lint", "npm run typecheck", "npm run publish:check"]);
425
+
408
426
  // Recognises non-registry installs: full URLs, git+ssh, file:, and npm-hosting shortcuts.
409
427
  // These specs cannot be reproducibly locked the way registry versions can.
410
428
  function isUrlDependency(versionSpec: string): boolean {
@@ -3,7 +3,7 @@
3
3
  // project-index types and the rules that consume them out of cli.ts so the orchestrator stays lean.
4
4
  import { dirname as dirnamePath, extname, join } from "node:path";
5
5
  import { isString } from "./config-parse.ts";
6
- import { optionNumber, ruleSeverity, threshold } from "./config.ts";
6
+ import { optionNumber, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
7
7
  import { type SourceFile } from "./discovery.ts";
8
8
  import { makeFinding } from "./findings.ts";
9
9
  import { fileBaseName } from "./findings-helpers.ts";
@@ -47,10 +47,10 @@ interface ImportStatement {
47
47
  line: number;
48
48
  }
49
49
 
50
- // Ordered list of files participating in a cycle. Order is significant - the first edge is the
51
- // anchor reported in the finding, so rotating the list would shift the finding's source line.
50
+ // Sorted SCC member list plus one deterministic closed cycle path for reviewer context.
52
51
  interface ImportCycle {
53
52
  files: string[];
53
+ representativeCycle: string[];
54
54
  }
55
55
 
56
56
  // Resolved thresholds passed into the large-module-concentration check. Holding them together
@@ -76,6 +76,12 @@ interface LargeModuleCandidate extends ModuleLineCount {
76
76
  thresholds: LargeModuleThresholds;
77
77
  }
78
78
 
79
+ // Optional switches for architecture analysis. The circular-import gate lets a caller build root
80
+ // graph context elsewhere without emitting duplicate SCC findings from the scoped index.
81
+ interface ArchitectureRuleOptions {
82
+ shouldSkipCircularImports?: boolean;
83
+ }
84
+
79
85
  // Sorts sources by display path so every cross-file rule sees the same order regardless of which
80
86
  // filesystem yielded what entries first - the stable input ordering is what keeps reports deterministic.
81
87
  export function buildProjectIndex(projectSources: ProjectSource[]): ProjectIndex {
@@ -91,12 +97,22 @@ export function buildProjectIndex(projectSources: ProjectSource[]): ProjectIndex
91
97
 
92
98
  // Three architecture rules, evaluated in their stable contract order: deep imports, cycles, then
93
99
  // large-module concentration. Reordering shuffles the deterministic fingerprint output.
94
- export function analyseArchitectureRules(index: ProjectIndex, config: Config, findings: Finding[]): void {
95
- analyseDeepRelativeImports(index, config, findings);
96
- analyseCircularImports(index, findings);
97
- analyseLargeModuleConcentration(index, config, findings);
100
+ export function analyseArchitectureRules(index: ProjectIndex, config: Config, findings: Finding[], options: ArchitectureRuleOptions = {}): void {
101
+ if (ruleEnabled(config, DEEP_RELATIVE_IMPORT_RULE_ID)) {
102
+ analyseDeepRelativeImports(index, config, findings);
103
+ }
104
+ if (!options.shouldSkipCircularImports && ruleEnabled(config, CIRCULAR_IMPORT_RULE_ID)) {
105
+ analyseCircularImportRule(index, findings);
106
+ }
107
+ if (ruleEnabled(config, LARGE_MODULE_CONCENTRATION_RULE_ID)) {
108
+ analyseLargeModuleConcentration(index, config, findings);
109
+ }
98
110
  }
99
111
 
112
+ const DEEP_RELATIVE_IMPORT_RULE_ID = "design.deep-relative-import";
113
+ export const CIRCULAR_IMPORT_RULE_ID = "design.circular-import";
114
+ const LARGE_MODULE_CONCENTRATION_RULE_ID = "design.large-module-concentration";
115
+
100
116
  /*
101
117
  * Reports imports that climb more than `maxParentSegments` `../` hops, anchored at the edge line
102
118
  * in the importing file. The double loop exists intentionally because `..` and `../foo` look
@@ -105,7 +121,7 @@ export function analyseArchitectureRules(index: ProjectIndex, config: Config, fi
105
121
  */
106
122
  function analyseDeepRelativeImports(index: ProjectIndex, config: Config, findings: Finding[]): void {
107
123
  const maxParentSegments = threshold(config, "design.deep-relative-import", 2);
108
- const severity = ruleSeverity(config, "design.deep-relative-import", "advisory");
124
+ const severity = ruleSeverity(config, DEEP_RELATIVE_IMPORT_RULE_ID, "advisory");
109
125
  for (const source of index.scriptSources) {
110
126
  const edges = index.importsByFile.get(source.file.displayPath) ?? [];
111
127
  for (const edge of edges) {
@@ -114,7 +130,7 @@ function analyseDeepRelativeImports(index: ProjectIndex, config: Config, finding
114
130
  }
115
131
  findings.push(
116
132
  makeFinding({
117
- ruleId: "design.deep-relative-import",
133
+ ruleId: DEEP_RELATIVE_IMPORT_RULE_ID,
118
134
  message: `Relative import \`${edge.specifier}\` climbs ${edge.parentSegments} directories.`,
119
135
  filePath: source.file.displayPath,
120
136
  line: edge.line,
@@ -131,10 +147,10 @@ function analyseDeepRelativeImports(index: ProjectIndex, config: Config, finding
131
147
  }
132
148
 
133
149
  /*
134
- * Reports one finding per detected cycle. The cycle list comes back already deterministic from
135
- * `importCycles`, so the resulting fingerprints are reproducible across runs.
150
+ * Reports one finding per strongly connected component in the runtime import graph. The component
151
+ * list comes back already deterministic from `importCycles`, so fingerprints are reproducible.
136
152
  */
137
- function analyseCircularImports(index: ProjectIndex, findings: Finding[]): void {
153
+ export function analyseCircularImportRule(index: ProjectIndex, findings: Finding[]): void {
138
154
  for (const cycle of importCycles(index)) {
139
155
  const finding = circularImportFinding(index, cycle);
140
156
  if (finding) {
@@ -154,7 +170,7 @@ function circularImportFinding(index: ProjectIndex, cycle: ImportCycle): Finding
154
170
  return undefined;
155
171
  }
156
172
  return makeFinding({
157
- ruleId: "design.circular-import",
173
+ ruleId: CIRCULAR_IMPORT_RULE_ID,
158
174
  message: `Import cycle detected among ${cycle.files.join(", ")}.`,
159
175
  filePath: anchorSource.file.displayPath,
160
176
  line: circularImportLine(index, anchorPath, cycle),
@@ -163,7 +179,7 @@ function circularImportFinding(index: ProjectIndex, cycle: ImportCycle): Finding
163
179
  confidence: "medium",
164
180
  symbol: cycle.files.join(" -> "),
165
181
  remediation: "Extract the shared contract or move one dependency behind an explicit boundary.",
166
- metadata: { files: cycle.files },
182
+ metadata: { files: cycle.files, representativeCycle: cycle.representativeCycle },
167
183
  });
168
184
  }
169
185
 
@@ -237,7 +253,7 @@ function productionModuleLineCounts(index: ProjectIndex): ModuleLineCount[] {
237
253
  // can see why the rule fired without re-running with the same config - keeps reports stable for audits.
238
254
  function largeModuleConcentrationFinding(candidate: LargeModuleCandidate, severity: Severity): Finding {
239
255
  return makeFinding({
240
- ruleId: "design.large-module-concentration",
256
+ ruleId: LARGE_MODULE_CONCENTRATION_RULE_ID,
241
257
  message: `Module \`${candidate.source.file.displayPath}\` contains ${candidate.sharePercent}% of production source lines.`,
242
258
  filePath: candidate.source.file.displayPath,
243
259
  line: 1,
@@ -366,42 +382,143 @@ function importPathCandidates(basePath: string): string[] {
366
382
  return [...candidates].map(normalizeDisplayPath);
367
383
  }
368
384
 
369
- // DFS over the import graph. Path length capped at 12 (see `visitImportCycle`) because beyond that
370
- // cycle detection becomes a search problem, not a useful signal. Output is sorted so report
371
- // ordering stays deterministic across runs.
385
+ // Tarjan SCC pass over the import graph. Components, members, and outgoing edges are sorted so
386
+ // one runtime import region yields one deterministic finding regardless of discovery order.
372
387
  function importCycles(index: ProjectIndex): ImportCycle[] {
373
- const cycles = new Map<string, string[]>();
374
- const paths = [...index.importsByFile.keys()].sort();
375
- for (const start of paths) {
376
- visitImportCycle(index, start, start, [start], new Set([start]), cycles);
377
- }
378
- return [...cycles.values()]
379
- .map((files) => ({ files }))
388
+ return stronglyConnectedImportComponents(index)
389
+ .map((files) => ({ files, representativeCycle: representativeCycle(index, files) }))
380
390
  .sort((left, right) => left.files.join("\0").localeCompare(right.files.join("\0")));
381
391
  }
382
392
 
383
- function visitImportCycle(
384
- index: ProjectIndex,
385
- start: string,
386
- current: string,
387
- path: string[],
388
- seen: Set<string>,
389
- cycles: Map<string, string[]>,
390
- ): void {
391
- const targets = [...new Set((index.importsByFile.get(current) ?? []).filter((edge) => !edge.isTypeOnly).map((edge) => edge.targetPath).filter(isString))].sort();
392
- for (const target of targets) {
393
- if (target === start && path.length > 1) {
394
- const files = [...path].sort();
395
- cycles.set(files.join("\0"), files);
393
+ // Mutable state for Tarjan's algorithm. Keeping it in one object makes the recursive visitor's
394
+ // signature small enough to audit.
395
+ interface StronglyConnectedState {
396
+ nextIndex: number;
397
+ indices: Map<string, number>;
398
+ lowLinks: Map<string, number>;
399
+ stack: string[];
400
+ onStack: Set<string>;
401
+ components: string[][];
402
+ }
403
+
404
+ // Finds strongly connected import components with Tarjan's algorithm, then normalizes component
405
+ // order so one runtime cycle produces stable report anchors and fingerprints.
406
+ function stronglyConnectedImportComponents(index: ProjectIndex): string[][] {
407
+ const state: StronglyConnectedState = {
408
+ nextIndex: 0,
409
+ indices: new Map(),
410
+ lowLinks: new Map(),
411
+ stack: [],
412
+ onStack: new Set(),
413
+ components: [],
414
+ };
415
+ for (const path of [...index.importsByFile.keys()].sort()) {
416
+ if (!state.indices.has(path)) {
417
+ visitStronglyConnectedImportComponent(index, path, state);
418
+ }
419
+ }
420
+ return state.components
421
+ .map((component) => [...component].sort())
422
+ .filter((component) => component.length > 1)
423
+ .sort((left, right) => left.join("\0").localeCompare(right.join("\0")));
424
+ }
425
+
426
+ // Visits one graph node and updates Tarjan indices, low-links, and the active stack in lockstep.
427
+ function visitStronglyConnectedImportComponent(index: ProjectIndex, path: string, state: StronglyConnectedState): void {
428
+ state.indices.set(path, state.nextIndex);
429
+ state.lowLinks.set(path, state.nextIndex);
430
+ state.nextIndex += 1;
431
+ state.stack.push(path);
432
+ state.onStack.add(path);
433
+
434
+ for (const target of circularImportTargets(index, path)) {
435
+ if (!state.indices.has(target)) {
436
+ visitStronglyConnectedImportComponent(index, target, state);
437
+ state.lowLinks.set(path, Math.min(lowLinkFor(state, path), lowLinkFor(state, target)));
396
438
  continue;
397
439
  }
398
- if (seen.has(target) || path.length >= 12) {
440
+ if (state.onStack.has(target)) {
441
+ state.lowLinks.set(path, Math.min(lowLinkFor(state, path), indexFor(state, target)));
442
+ }
443
+ }
444
+
445
+ if (lowLinkFor(state, path) !== indexFor(state, path)) {
446
+ return;
447
+ }
448
+ const component: string[] = [];
449
+ while (state.stack.length > 0) {
450
+ const member = state.stack.pop();
451
+ if (!member) {
452
+ break;
453
+ }
454
+ state.onStack.delete(member);
455
+ component.push(member);
456
+ if (member === path) {
457
+ break;
458
+ }
459
+ }
460
+ state.components.push(component);
461
+ }
462
+
463
+ // Reads a Tarjan discovery index; missing entries fall back to zero only for malformed graph edges.
464
+ function indexFor(state: StronglyConnectedState, path: string): number {
465
+ return state.indices.get(path) ?? 0;
466
+ }
467
+
468
+ // Reads a Tarjan low-link value; the fallback keeps partially indexed edges bounded.
469
+ function lowLinkFor(state: StronglyConnectedState, path: string): number {
470
+ return state.lowLinks.get(path) ?? 0;
471
+ }
472
+
473
+ // Stable runtime-cycle contract: returns sorted value imports only; type-only edges never count.
474
+ function circularImportTargets(index: ProjectIndex, path: string): string[] {
475
+ return [...new Set((index.importsByFile.get(path) ?? []).filter((edge) => !edge.isTypeOnly).map((edge) => edge.targetPath).filter(isString))].sort();
476
+ }
477
+
478
+ // Chooses one concrete closed path inside the SCC so the finding still shows a reviewable edge
479
+ // chain even though the primary output unit is the whole component.
480
+ function representativeCycle(index: ProjectIndex, files: string[]): string[] {
481
+ const anchor = files[0];
482
+ if (!anchor) {
483
+ return [];
484
+ }
485
+ const members = new Set(files);
486
+ for (const target of circularImportTargets(index, anchor).filter((candidate) => members.has(candidate))) {
487
+ const returnPath = pathBetweenComponentMembers(index, target, anchor, members);
488
+ if (returnPath) {
489
+ return [anchor, ...returnPath];
490
+ }
491
+ }
492
+ return files;
493
+ }
494
+
495
+ // Queue item for finding a representative path through one SCC.
496
+ interface ComponentPathSearch {
497
+ current: string;
498
+ path: string[];
499
+ }
500
+
501
+ // Breadth-first path search inside one SCC so the grouped finding can display a concrete cycle.
502
+ function pathBetweenComponentMembers(index: ProjectIndex, start: string, end: string, members: Set<string>): string[] | undefined {
503
+ const queue: ComponentPathSearch[] = [{ current: start, path: [start] }];
504
+ const visited = new Set([start]);
505
+ for (let queueIndex = 0; queueIndex < queue.length; queueIndex += 1) {
506
+ const searchState = queue[queueIndex];
507
+ if (!searchState) {
399
508
  continue;
400
509
  }
401
- seen.add(target);
402
- visitImportCycle(index, start, target, [...path, target], seen, cycles);
403
- seen.delete(target);
510
+ for (const target of circularImportTargets(index, searchState.current).filter((candidate) => members.has(candidate))) {
511
+ if (target === end) {
512
+ return [...searchState.path, target];
513
+ }
514
+ if (visited.has(target)) {
515
+ continue;
516
+ }
517
+ visited.add(target);
518
+ queue.push({ current: target, path: [...searchState.path, target] });
519
+ }
404
520
  }
521
+ return undefined;
405
522
  }
406
523
 
407
524
  // Production = not a test, not a `.d.ts`, not a fixture, not under `generated/`. Conservative on