@blundergoat/gruff-ts 0.3.0 → 0.3.2

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.
@@ -0,0 +1,435 @@
1
+ // gruff.hook.v1 adapter: owns the agent-hook JSON shape without changing gruff.analysis.v2.
2
+ import { execFileSync } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { chdir, cwd } from "node:process";
7
+ import { tmpdir } from "node:os";
8
+ import { absolutize } from "./discovery.ts";
9
+ import { VERSION } from "./constants.ts";
10
+ import { ruleDescriptors } from "./rules.ts";
11
+ import type { AnalysisOptions, AnalysisReport, Finding, Severity, SkippedPath } from "./types.ts";
12
+
13
+ type HookScope = "line" | "symbol" | "file" | "project";
14
+ type FlagOrder = "any" | "flags-before-path";
15
+ type HookAnalysisRunner = (options: AnalysisOptions) => AnalysisReport;
16
+
17
+ // Inputs for one hook render: full-scan options, changed-region options, and optional baseline/diff
18
+ // bases used for new-only filtering.
19
+ interface HookReportInput {
20
+ currentOptions: AnalysisOptions;
21
+ scopedOptions: AnalysisOptions;
22
+ baselinePath?: string;
23
+ diffBase?: string;
24
+ hasChangedRegion: boolean;
25
+ }
26
+
27
+ // The gruff.hook.v1 envelope written to stdout; field names are the cross-analyzer contract.
28
+ interface HookReport {
29
+ contractVersion: "gruff.hook.v1";
30
+ analyzer: { name: "gruff-ts"; version: string };
31
+ findings: HookFinding[];
32
+ suppressed: { count: number };
33
+ ignored: { paths: SkippedPath[] };
34
+ config: { schemaOk: boolean; error: string | null };
35
+ }
36
+
37
+ // A finding projected into the hook contract, with enum scope and non-null remediation, keyed for
38
+ // new-only tracking by the stable identity and fingerprint.
39
+ interface HookFinding {
40
+ ruleId: string;
41
+ pillar: string;
42
+ severity: Severity;
43
+ scope: HookScope;
44
+ file: string;
45
+ line?: number;
46
+ endLine?: number;
47
+ symbol: string | null;
48
+ message: string;
49
+ remediation: string;
50
+ metadata: Record<string, unknown>;
51
+ stableIdentity: string;
52
+ fingerprint: string;
53
+ }
54
+
55
+ // A gruff.baseline.v1 entry as read for new-only comparison; every field is optional because older
56
+ // baselines predate stableIdentity.
57
+ interface BaselineEntry {
58
+ stableIdentity?: string;
59
+ ruleId?: string;
60
+ filePath?: string;
61
+ symbol?: string;
62
+ message?: string;
63
+ }
64
+
65
+ const HOOK_CONTRACT_VERSION = "gruff.hook.v1";
66
+ const FILE_SCOPE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
67
+ const PROJECT_SCOPE_RULE_IDS = new Set(["design.circular-import"]);
68
+ const SEVERITY_RANK: Record<Severity, number> = { error: 0, warning: 1, advisory: 2 };
69
+ const DESCRIPTORS = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor]));
70
+
71
+ // Emits the gruff.hook.v1 capability handshake so a consumer can resolve flag names before a real
72
+ // request; the advertised supports/flags object is the stable gruff.hook.v1 contract.
73
+ export function renderHookCapabilities(): string {
74
+ return JSON.stringify({
75
+ contractVersion: HOOK_CONTRACT_VERSION,
76
+ analyzer: analyzerInfo(),
77
+ supports: {
78
+ changedRanges: true,
79
+ diff: true,
80
+ baseline: true,
81
+ scopeField: true,
82
+ metadata: true,
83
+ stableIdentity: true,
84
+ ignoreReport: true,
85
+ newOnly: true,
86
+ },
87
+ flags: { changedRanges: "--changed-ranges", diff: "--diff", baseline: "--baseline" },
88
+ flagOrder: "any" satisfies FlagOrder,
89
+ }, null, 2) + "\n";
90
+ }
91
+
92
+ // Runs the analysis (twice when a changed region is requested) and projects it into the gruff.hook.v1
93
+ // envelope: scoped findings, suppressed count, ignored paths, and a schema-ok config block.
94
+ export function renderHookReport(runAnalyse: HookAnalysisRunner, input: HookReportInput): string {
95
+ const currentReport = runAnalyse(input.currentOptions);
96
+ const scopedReport = input.hasChangedRegion ? runAnalyse(input.scopedOptions) : currentReport;
97
+ const baseIdentities = hookBaseIdentities(runAnalyse, input, currentReport);
98
+ const findings = hookFindings(currentReport, scopedReport, input.hasChangedRegion, baseIdentities);
99
+ const suppressedCount = hookSuppressedCount(scopedReport, findings, input.hasChangedRegion);
100
+ return JSON.stringify(hookReport(scopedReport, findings, suppressedCount, true, null), null, 2) + "\n";
101
+ }
102
+
103
+ // Emits a gruff.hook.v1 envelope for an operational failure (config rejected, bad baseline, git
104
+ // error) so the consumer always receives JSON with config.error set instead of a crash.
105
+ export function renderHookConfigError(message: string, remediation: string): string {
106
+ const error = `${message}\nSuggested fix: ${remediation}`;
107
+ return JSON.stringify(hookReport(undefined, [], 0, false, error), null, 2) + "\n";
108
+ }
109
+
110
+ // Assembles the gruff.hook.v1 envelope (sorted findings, suppressed count, ignored paths, config)
111
+ // as the stable gruff.hook.v1 output contract.
112
+ function hookReport(report: AnalysisReport | undefined, findings: HookFinding[], suppressedCount: number, isSchemaOk: boolean, error: string | null): HookReport {
113
+ return {
114
+ contractVersion: HOOK_CONTRACT_VERSION,
115
+ analyzer: analyzerInfo(),
116
+ findings: sortHookFindings(findings),
117
+ suppressed: { count: suppressedCount },
118
+ ignored: { paths: report?.paths.skipped ?? [] },
119
+ config: { schemaOk: isSchemaOk, error },
120
+ };
121
+ }
122
+
123
+ // Analyzer identity block shared by the capability and report envelopes.
124
+ function analyzerInfo(): { name: "gruff-ts"; version: string } {
125
+ return { name: "gruff-ts", version: VERSION };
126
+ }
127
+
128
+ function hookFindings(
129
+ currentReport: AnalysisReport,
130
+ scopedReport: AnalysisReport,
131
+ hasChangedRegion: boolean,
132
+ baseIdentities: Set<string> | undefined,
133
+ ): HookFinding[] {
134
+ const scopedFindings = scopedReport.findings
135
+ .map(toHookFinding)
136
+ .filter((finding) => !hasChangedRegion || (finding.scope !== "file" && finding.scope !== "project"));
137
+ const withNewFileAndProject = hasChangedRegion && baseIdentities
138
+ ? [...scopedFindings, ...newFileAndProjectFindings(currentReport, scopedFindings, baseIdentities)]
139
+ : scopedFindings;
140
+ return baseIdentities ? withNewFileAndProject.filter((finding) => !baseIdentities.has(finding.stableIdentity)) : withNewFileAndProject;
141
+ }
142
+
143
+ // Collects file- and project-scope findings that are new since the base, excluding any already
144
+ // emitted, deduped by fingerprint.
145
+ function newFileAndProjectFindings(currentReport: AnalysisReport, scopedFindings: HookFinding[], baseIdentities: Set<string>): HookFinding[] {
146
+ const alreadyIncluded = new Set(scopedFindings.map((finding) => finding.fingerprint));
147
+ return currentReport.findings
148
+ .map(toHookFinding)
149
+ .filter((finding) => (finding.scope === "file" || finding.scope === "project") && !baseIdentities.has(finding.stableIdentity) && !alreadyIncluded.has(finding.fingerprint));
150
+ }
151
+
152
+ // Counts the file/project findings the hook drops under changed-region attribution, excluding any
153
+ // re-emitted as new, so the stable suppressed.count contract is never double-counted.
154
+ function hookSuppressedCount(scopedReport: AnalysisReport, emittedFindings: HookFinding[], hasChangedRegion: boolean): number {
155
+ if (!hasChangedRegion) {
156
+ return 0;
157
+ }
158
+ const emittedFingerprints = new Set(emittedFindings.map((finding) => finding.fingerprint));
159
+ const fileOrProjectAnchorResiduals = scopedReport.findings.filter((finding) => {
160
+ const scope = scopeForFinding(finding);
161
+ return (scope === "file" || scope === "project") && !emittedFingerprints.has(finding.fingerprint);
162
+ }).length;
163
+ return (scopedReport.suppressedCount ?? 0) + fileOrProjectAnchorResiduals;
164
+ }
165
+
166
+ // Projects an analyser Finding into the hook shape, attaching scope, remediation, and the stable
167
+ // identity plus fingerprint.
168
+ function toHookFinding(finding: Finding): HookFinding {
169
+ const scope = scopeForFinding(finding);
170
+ return {
171
+ ruleId: finding.ruleId,
172
+ pillar: finding.pillar,
173
+ severity: finding.severity,
174
+ scope,
175
+ file: finding.filePath,
176
+ ...(finding.line === undefined ? {} : { line: finding.line }),
177
+ ...(finding.endLine === undefined ? {} : { endLine: finding.endLine }),
178
+ symbol: finding.symbol ?? null,
179
+ message: finding.message,
180
+ remediation: finding.remediation ?? DESCRIPTORS.get(finding.ruleId)?.remediation ?? "Review and address this finding.",
181
+ metadata: hookMetadata(finding),
182
+ stableIdentity: hookStableIdentity(finding, scope),
183
+ fingerprint: finding.fingerprint,
184
+ };
185
+ }
186
+
187
+ // Classifies a finding as line/symbol/file/project scope; this choice drives changed-region
188
+ // attribution and the stable hook identity.
189
+ function scopeForFinding(finding: Finding): HookScope {
190
+ if (PROJECT_SCOPE_RULE_IDS.has(finding.ruleId)) {
191
+ return "project";
192
+ }
193
+ if (FILE_SCOPE_RULE_IDS.has(finding.ruleId)) {
194
+ return "file";
195
+ }
196
+ if (finding.symbol || (finding.endLine !== undefined && finding.line !== undefined && finding.endLine > finding.line)) {
197
+ return "symbol";
198
+ }
199
+ return "line";
200
+ }
201
+
202
+ // Returns normalized threshold metadata when the rule has one, else the finding's own metadata,
203
+ // keeping the contract's metadata shape stable.
204
+ function hookMetadata(finding: Finding): Record<string, unknown> {
205
+ const thresholdMetadata = thresholdMetadataFor(finding);
206
+ return thresholdMetadata ?? finding.metadata;
207
+ }
208
+
209
+ // Maps known threshold rules to a measured/threshold/unit triple so the hook exposes a stable,
210
+ // machine-readable measurement contract.
211
+ function thresholdMetadataFor(finding: Finding): Record<string, unknown> | undefined {
212
+ const metadata = finding.metadata;
213
+ switch (finding.ruleId) {
214
+ case "complexity.cognitive":
215
+ case "complexity.cyclomatic":
216
+ return metricMetadata(metadata.complexity, metadata.threshold, "points");
217
+ case "design.deep-relative-import":
218
+ return metricMetadata(metadata.parentSegments, metadata.maxParentSegments, "segments");
219
+ case "design.large-module-concentration":
220
+ return metricMetadata(metadata.sharePercent, metadata.maxSharePercent, "percent");
221
+ case "sensitive-data.hardcoded-env-value":
222
+ case "sensitive-data.high-entropy-string":
223
+ return metricMetadata(metadata.length, metadata.threshold, "characters");
224
+ case "size.file-length":
225
+ case "size.function-length":
226
+ return metricMetadata(metadata.lines, metadata.threshold, "lines");
227
+ case "size.parameter-count":
228
+ return metricMetadata(metadata.parameters, metadata.threshold, "parameters");
229
+ }
230
+ return undefined;
231
+ }
232
+
233
+ // Builds the normalized measurement object, or undefined when the measured/threshold pair is not
234
+ // numeric.
235
+ function metricMetadata(measured: unknown, threshold: unknown, unit: string): Record<string, unknown> | undefined {
236
+ return typeof measured === "number" && typeof threshold === "number"
237
+ ? { measured, threshold, unit, direction: "above" }
238
+ : undefined;
239
+ }
240
+
241
+ // Hashes (ruleId, filePath, scope component) into the 16-hex hook identity; line-insensitive so it
242
+ // stays the stable cross-edit key for new-only filtering.
243
+ function hookStableIdentity(finding: Finding, scope: HookScope): string {
244
+ const component = stableIdentityComponent(finding, scope);
245
+ return createHash("sha256")
246
+ .update([finding.ruleId, finding.filePath, component].join("\0"))
247
+ .digest("hex")
248
+ .slice(0, 16);
249
+ }
250
+
251
+ // Derives the per-occurrence component of the stable hook identity: scope token, symbol, or message.
252
+ function stableIdentityComponent(finding: { message: string; ruleId: string; symbol?: string }, scope: HookScope): string {
253
+ if (scope === "file") {
254
+ return scope;
255
+ }
256
+ if (scope === "project") {
257
+ // Project rules are value-insensitive on their measurement, but one file can anchor several
258
+ // distinct project findings: design.circular-import emits one finding per cycle and sorts each
259
+ // cycle to its alphabetically-first member, so `a -> b` and `a -> c` both anchor `a.ts`. The
260
+ // cycle path (carried in `symbol`) is the only discriminator; folding it in keeps distinct
261
+ // cycles distinct so baselining one never suppresses a genuinely new one. A project finding with
262
+ // no symbol falls back to the bare scope token, preserving its value-insensitive identity.
263
+ return finding.symbol && finding.symbol.length > 0 ? `project:${finding.symbol}` : scope;
264
+ }
265
+ if (finding.symbol && finding.symbol.length > 0) {
266
+ return `symbol:${finding.symbol}`;
267
+ }
268
+ // Symbol-less line findings (e.g. each hardcoded secret) key on the message so several same-rule
269
+ // findings in one file get distinct identities. A value-insensitive `metric:${scope}` token
270
+ // collapsed them all, letting one baselined finding suppress later new ones in the same file. The
271
+ // message carries the per-occurrence discriminator (redacted preview) and no line number, so it
272
+ // stays stable across surrounding edits. file scope above stays fully value-insensitive; project
273
+ // scope folds in the cycle symbol when one is present.
274
+ return `message:${finding.message}`;
275
+ }
276
+
277
+ // Builds the base identity set (from a baseline file and/or a diff base) that new-only filtering
278
+ // compares against by stable hook identity; undefined when neither source is requested.
279
+ function hookBaseIdentities(runAnalyse: HookAnalysisRunner, input: HookReportInput, currentReport: AnalysisReport): Set<string> | undefined {
280
+ const identities = new Set<string>();
281
+ if (input.baselinePath) {
282
+ for (const identity of stableIdentitiesFromBaseline(input.baselinePath)) {
283
+ identities.add(identity);
284
+ }
285
+ }
286
+ if (input.diffBase) {
287
+ for (const identity of stableIdentitiesFromDiffBase(runAnalyse, input.currentOptions, input.diffBase, currentReport)) {
288
+ identities.add(identity);
289
+ }
290
+ }
291
+ return identities.size > 0 || input.baselinePath || input.diffBase ? identities : undefined;
292
+ }
293
+
294
+ // Reads stable identities from a gruff.baseline.v1 file; the schema is the gruff.baseline.v1
295
+ // contract and the reader throws on any schemaVersion mismatch.
296
+ function stableIdentitiesFromBaseline(path: string): Set<string> {
297
+ const baselinePath = absolutize(cwd(), path);
298
+ const baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as { schemaVersion?: string; entries?: BaselineEntry[] };
299
+ if (baseline.schemaVersion !== "gruff.baseline.v1") {
300
+ throw new Error(`unsupported baseline schema in ${path}`);
301
+ }
302
+ return new Set((baseline.entries ?? []).flatMap(stableIdentityFromBaselineEntry));
303
+ }
304
+
305
+ // Resolves one baseline entry to hook identities: its stored identity, or a recomputed one from
306
+ // ruleId, filePath, and scope.
307
+ function stableIdentityFromBaselineEntry(entry: BaselineEntry): string[] {
308
+ if (typeof entry.stableIdentity === "string") {
309
+ return [entry.stableIdentity];
310
+ }
311
+ if (typeof entry.ruleId !== "string" || typeof entry.filePath !== "string") {
312
+ return [];
313
+ }
314
+ const scope = baselineScopeForRule(entry.ruleId);
315
+ const component = stableIdentityComponent({
316
+ ruleId: entry.ruleId,
317
+ message: entry.message ?? "",
318
+ ...(typeof entry.symbol === "string" ? { symbol: entry.symbol } : {}),
319
+ }, scope);
320
+ return [
321
+ createHash("sha256")
322
+ .update([entry.ruleId, entry.filePath, component].join("\0"))
323
+ .digest("hex")
324
+ .slice(0, 16),
325
+ ];
326
+ }
327
+
328
+ // Maps a rule id to its baseline scope so entries without a stored identity recompute the right
329
+ // component.
330
+ function baselineScopeForRule(ruleId: string): HookScope {
331
+ if (PROJECT_SCOPE_RULE_IDS.has(ruleId)) {
332
+ return "project";
333
+ }
334
+ if (FILE_SCOPE_RULE_IDS.has(ruleId)) {
335
+ return "file";
336
+ }
337
+ return "line";
338
+ }
339
+
340
+ function stableIdentitiesFromDiffBase(
341
+ runAnalyse: HookAnalysisRunner,
342
+ options: AnalysisOptions,
343
+ diffBase: string,
344
+ currentReport: AnalysisReport,
345
+ ): Set<string> {
346
+ const ref = diffBaseRef(diffBase);
347
+ if (ref === undefined) {
348
+ return new Set();
349
+ }
350
+ const files = [...new Set(currentReport.findings.map((finding) => finding.filePath))];
351
+ if (files.length === 0) {
352
+ return new Set();
353
+ }
354
+ const tempRoot = mkdtempSync(join(tmpdir(), "gruff-ts-hook-base-"));
355
+ const previous = cwd();
356
+ try {
357
+ const baseFiles = materializeBaseFiles(ref, files, tempRoot);
358
+ if (baseFiles.length === 0) {
359
+ return new Set();
360
+ }
361
+ chdir(tempRoot);
362
+ const baseReport = runAnalyse(baseAnalysisOptions(options, baseFiles, previous));
363
+ return new Set(baseReport.findings.map((finding) => hookStableIdentity(finding, scopeForFinding(finding))));
364
+ } finally {
365
+ chdir(previous);
366
+ rmSync(tempRoot, { recursive: true, force: true });
367
+ }
368
+ }
369
+
370
+ // Resolves a diff-base selector to the git rev whose blobs are the new-only base. "unstaged" diffs
371
+ // the worktree against the index, so its base is the index ("" rev -> `git show :path`); "-" (stdin
372
+ // patch) has no materializable base. Returns undefined only when no base can be replayed.
373
+ function diffBaseRef(diffBase: string): string | undefined {
374
+ if (diffBase === "-") {
375
+ return undefined;
376
+ }
377
+ if (diffBase === "unstaged") {
378
+ return "";
379
+ }
380
+ return diffBase === "working-tree" || diffBase === "staged" ? "HEAD" : diffBase;
381
+ }
382
+
383
+ // Writes each file's blob at the base ref into the temp dir via git; a blob missing at the ref is a
384
+ // recover path so that file's findings count as new (filesystem writes).
385
+ function materializeBaseFiles(ref: string, files: string[], root: string): string[] {
386
+ const materialized: string[] = [];
387
+ for (const file of files) {
388
+ try {
389
+ const source = execFileSync("git", ["show", `${ref}:${file}`], { encoding: "utf8" });
390
+ const target = join(root, file);
391
+ mkdirSync(dirname(target), { recursive: true });
392
+ writeFileSync(target, source);
393
+ materialized.push(file);
394
+ } catch {
395
+ // File is missing at the base ref, so every current finding in it is new.
396
+ }
397
+ }
398
+ return materialized;
399
+ }
400
+
401
+ // Builds the analysis options for the base-ref scan: drops changed-region flags and resolves the
402
+ // config path against the original root.
403
+ function baseAnalysisOptions(options: AnalysisOptions, paths: string[], originalRoot: string): AnalysisOptions {
404
+ return {
405
+ ...withoutChangedRegion(options),
406
+ paths,
407
+ ...(options.config ? { config: absolutize(originalRoot, options.config) } : defaultConfigPathOption(originalRoot, options)),
408
+ };
409
+ }
410
+
411
+ // Falls back to the project's default .gruff-ts.yaml for the base scan when one exists and config is
412
+ // not skipped.
413
+ function defaultConfigPathOption(originalRoot: string, options: AnalysisOptions): Partial<Pick<AnalysisOptions, "config">> {
414
+ const defaultConfigPath = join(originalRoot, ".gruff-ts.yaml");
415
+ return !options.shouldSkipConfig && existsSync(defaultConfigPath) ? { config: defaultConfigPath } : {};
416
+ }
417
+
418
+ // Strips every changed-region and baseline flag so the base-ref scan runs as a plain full scan,
419
+ // deterministic regardless of the original changed-region request.
420
+ function withoutChangedRegion(options: AnalysisOptions): AnalysisOptions {
421
+ const { baseline: _baseline, changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, generateBaseline: _generateBaseline, since: _since, ...rest } = options;
422
+ return { ...rest, shouldSkipBaseline: true };
423
+ }
424
+
425
+ // Orders findings by severity, then file, line, and rule id, giving the contract a deterministic,
426
+ // stable finding order.
427
+ function sortHookFindings(findings: HookFinding[]): HookFinding[] {
428
+ return [...findings].sort(
429
+ (left, right) =>
430
+ SEVERITY_RANK[left.severity] - SEVERITY_RANK[right.severity] ||
431
+ left.file.localeCompare(right.file) ||
432
+ (left.line ?? 0) - (right.line ?? 0) ||
433
+ left.ruleId.localeCompare(right.ruleId),
434
+ );
435
+ }
package/src/line-rules.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // detection and the block-rule parameter pass. Dead-code rules (unused imports, unreachable) are
5
5
  // invoked by the cli orchestrator before/after this module so the stable per-line emission order
6
6
  // stays a single contract.
7
+ import { ruleSeverity } from "./config.ts";
7
8
  import { type SourceFile } from "./discovery.ts";
8
9
  import { makeFinding } from "./findings.ts";
9
10
  import { escapeRegex, finding, isCommentedOutCode } from "./findings-helpers.ts";
@@ -256,13 +257,14 @@ function pushStringTimerFinding(context: LineRuleContext): void {
256
257
  }
257
258
  }
258
259
 
259
- // Runs the descriptor-driven line checks split into code-shape vs literal-aware. Literal checks
260
- // use `rawPatternStartsInCode` to confirm the match starts in real code, not inside a comment.
261
- // Reports each matching rule's stable line-anchored finding.
260
+ // Runs the descriptor-driven line checks split into code-shape vs literal-aware. Literal checks use
261
+ // `rawPatternStartsInCode` to confirm a match starts in real code, not inside a comment. Each finding's
262
+ // severity is resolved through `ruleSeverity`, so a project's per-rule `severity:` override applies.
263
+ // Reports each matching rule's stable, line-anchored finding; the descriptor severity is the default.
262
264
  function pushPatternCheckFindings(context: LineRuleContext): void {
263
265
  for (const check of context.codeChecks) {
264
266
  if (check.pattern.test(context.codeLine)) {
265
- context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: check.severity, pillar: check.pillar }));
267
+ context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar }));
266
268
  }
267
269
  }
268
270
  for (const check of context.literalChecks) {
@@ -270,7 +272,7 @@ function pushPatternCheckFindings(context: LineRuleContext): void {
270
272
  continue;
271
273
  }
272
274
  if (rawPatternStartsInCode(context.line, context.codeLine, check.globalPattern ?? check.pattern)) {
273
- context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: check.severity, pillar: check.pillar }));
275
+ context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar }));
274
276
  }
275
277
  }
276
278
  }
package/src/profiles.ts CHANGED
@@ -90,7 +90,6 @@ const BUILT_IN_PROFILE_SPECS: readonly BuiltInProfile[] = [
90
90
  "size.parameter-count": 4,
91
91
  "sensitive-data.hardcoded-env-value": 12,
92
92
  "sensitive-data.high-entropy-string": 24,
93
- "test-quality.setup-bloat": 8,
94
93
  },
95
94
  severities: {},
96
95
  },
@@ -1,23 +1,14 @@
1
- // Cross-file architecture rules (deep imports, cycles, large-module concentration), test-adequacy
2
- // (missing-nearby-test), and the path-classification helpers (isTestPath, isFixtureLikePath, etc.)
3
- // every rule pass shares. Pulls the project-index types and the rules that consume them out of cli.ts
4
- // so the orchestrator stays lean.
5
- import { basename, dirname as dirnamePath, extname, join } from "node:path";
1
+ // Cross-file architecture rules (deep imports, cycles, large-module concentration) and the
2
+ // path-classification helpers (isTestPath, isFixtureLikePath, etc.) every rule pass shares. Pulls the
3
+ // project-index types and the rules that consume them out of cli.ts so the orchestrator stays lean.
4
+ import { dirname as dirnamePath, extname, join } from "node:path";
6
5
  import { isString } from "./config-parse.ts";
7
6
  import { optionNumber, ruleSeverity, threshold } from "./config.ts";
8
7
  import { type SourceFile } from "./discovery.ts";
9
8
  import { makeFinding } from "./findings.ts";
10
9
  import { fileBaseName } from "./findings-helpers.ts";
11
- import { byteLine } from "./text-scans.ts";
12
10
  import type { Config, Finding, Severity } from "./types.ts";
13
11
 
14
- // First exported callable/value in a production file. Missing-nearby-test only needs this compact
15
- // surface, so the project index does not retain full source bodies after per-file analysis.
16
- export interface ProjectExportedSurface {
17
- symbol: string;
18
- line: number;
19
- }
20
-
21
12
  // Read-once snapshot of a discovered file. Lines are cached because cross-file project rules
22
13
  // scan each source repeatedly - splitting once amortises the cost across rule passes.
23
14
  // `templateMaskedLines` mirrors `lines` but blanks out `` ` `` template-literal body characters
@@ -27,7 +18,6 @@ export interface ProjectSource {
27
18
  file: SourceFile;
28
19
  lines: string[];
29
20
  templateMaskedLines: string[];
30
- exportedSurface?: ProjectExportedSurface;
31
21
  }
32
22
 
33
23
  // Project-wide aggregate built once per scan and reused by every architecture rule (cycle detection,
@@ -107,12 +97,6 @@ export function analyseArchitectureRules(index: ProjectIndex, config: Config, fi
107
97
  analyseLargeModuleConcentration(index, config, findings);
108
98
  }
109
99
 
110
- // Container for test-adequacy rules. Just one rule today; existing as a stable shape so additions
111
- // inherit the same project-index contract without each touching the entry point.
112
- export function analyseTestAdequacyRules(index: ProjectIndex, findings: Finding[]): void {
113
- analyseMissingNearbyTests(index, findings);
114
- }
115
-
116
100
  /*
117
101
  * Reports imports that climb more than `maxParentSegments` `../` hops, anchored at the edge line
118
102
  * in the importing file. The double loop exists intentionally because `..` and `../foo` look
@@ -426,102 +410,6 @@ export function isProductionSourcePath(path: string): boolean {
426
410
  return !isTestPath(path) && !isDeclarationPath(path) && !isFixtureLikePath(path) && !path.split("/").includes("generated");
427
411
  }
428
412
 
429
- /*
430
- * Reports exported callables whose file has no neighbouring `.test.ts` / `.spec.ts`. The stable
431
- * neighbour rules (`hasNearbyTest`) define what counts - false positives are likelier than missed
432
- * cases, so the rule is intentionally conservative.
433
- */
434
- function analyseMissingNearbyTests(index: ProjectIndex, findings: Finding[]): void {
435
- const testSources = index.scriptSources.filter((source) => isTestPath(source.file.displayPath));
436
- const testPaths = new Set(testSources.map((source) => source.file.displayPath));
437
- for (const source of index.scriptSources.filter((candidate) => isProductionSourcePath(candidate.file.displayPath))) {
438
- const exported = source.exportedSurface;
439
- if (!exported || hasNearbyTest(source.file.displayPath, testPaths) || hasCentralTestImport(source.file.displayPath, testSources, index.importsByFile)) {
440
- continue;
441
- }
442
- findings.push(
443
- makeFinding({
444
- ruleId: "test-quality.missing-nearby-test",
445
- message: `Exported source file \`${source.file.displayPath}\` has no nearby test file.`,
446
- filePath: source.file.displayPath,
447
- line: exported.line,
448
- severity: "advisory",
449
- pillar: "test-quality",
450
- confidence: "medium",
451
- symbol: exported.symbol,
452
- remediation: "Add a focused test beside the source file or under a nearby __tests__/tests directory.",
453
- metadata: { expectedTestBase: fileBaseName(source.file.displayPath) },
454
- }),
455
- );
456
- }
457
- }
458
-
459
- // Centralized `test/unit` or `test/integration` suites often import the source directly instead
460
- // of matching filenames. Treat that import edge as nearby enough to avoid layout false positives.
461
- function hasCentralTestImport(sourcePath: string, testSources: ProjectSource[], importsByFile: Map<string, ImportEdge[]>): boolean {
462
- return testSources.some((testSource) => (importsByFile.get(testSource.file.displayPath) ?? []).some((edge) => edge.targetPath === sourcePath));
463
- }
464
-
465
- // Returns the first exported callable/value seen - one finding per file is sufficient because
466
- // the rule's signal is "this file ships an API surface", not "every export is untested".
467
- export function exportedSurface(source: string): ProjectExportedSurface | undefined {
468
- const match = source.match(/\bexport\s+(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|enum|const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/);
469
- if (!match?.[1]) {
470
- return undefined;
471
- }
472
- return { symbol: match[1], line: byteLine(source, match.index ?? 0) };
473
- }
474
-
475
- // True when a same-name test file exists alongside the source, in a sibling `__tests__`/`tests`
476
- // directory, or anywhere under a top-level `test`/`tests` tree. Mirrors common project layouts;
477
- // expanding this list widens what counts as "tested".
478
- function hasNearbyTest(sourcePath: string, testPaths: Set<string>): boolean {
479
- const sourceBase = stripSourceExtension(sourcePath);
480
- const sourceName = basename(sourceBase);
481
- const sourceDir = displayDir(sourcePath);
482
- const nearbyDirs = new Set([sourceDir, joinDisplay(sourceDir, "__tests__"), joinDisplay(sourceDir, "tests"), "test", "tests"]);
483
- for (const testPath of testPaths) {
484
- const testBase = stripTestMarker(stripSourceExtension(testPath));
485
- if (basename(testBase) !== sourceName) {
486
- continue;
487
- }
488
- if (testBase === sourceBase || nearbyDirs.has(displayDir(testPath)) || isTopLevelTestPath(testPath)) {
489
- return true;
490
- }
491
- }
492
- return false;
493
- }
494
-
495
- // Top-level `test/` and `tests/` trees are common central suite layouts. This helper is separate
496
- // from `isTestPath` because nearby-test matching still requires basename agreement.
497
- function isTopLevelTestPath(path: string): boolean {
498
- return path.startsWith("test/") || path.startsWith("tests/");
499
- }
500
-
501
- // Drops the trailing `.ts`/`.tsx`/`.js`/`.jsx`/`.mts`/`.cjs`/`.mjs` extension so source-and-test
502
- // filename comparison is extension-agnostic. Used together with `stripTestMarker`.
503
- function stripSourceExtension(path: string): string {
504
- return path.replace(/\.[cm]?[tj]sx?$/, "");
505
- }
506
-
507
- // Drops the conventional `.test` / `.spec` suffix before comparing a test path to a source path.
508
- function stripTestMarker(path: string): string {
509
- return path.replace(/\.(?:test|spec)$/, "");
510
- }
511
-
512
- // Collapses a path's directory portion to the empty string at the project root so
513
- // `hasNearbyTest`'s nearbyDirs lookup uses one canonical key for root-level files.
514
- function displayDir(path: string): string {
515
- const dir = normalizeDisplayPath(dirnamePath(path));
516
- return dir === "." ? "" : dir;
517
- }
518
-
519
- // POSIX-style join that handles the empty-prefix case so `joinDisplay("", "x")` returns `"x"`,
520
- // not `"/x"` - needed for paths that live directly at the project root.
521
- function joinDisplay(left: string, right: string): string {
522
- return left ? `${left}/${right}` : right;
523
- }
524
-
525
413
  // `__tests__/` and `tests/` directories, plus `.test.ts` / `.spec.ts` filename suffix. The same
526
414
  // patterns drive the production-source filter, so adding a layout here widens every test-aware rule.
527
415
  export function isTestPath(path: string): boolean {