@blundergoat/gruff-ts 0.4.0 → 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 (48) hide show
  1. package/CHANGELOG.md +41 -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 +14 -2
  6. package/docs/configuration.md +32 -1
  7. package/docs/dashboard.md +3 -3
  8. package/docs/reports-and-ci.md +15 -0
  9. package/docs/rules.md +35 -29
  10. package/package.json +1 -1
  11. package/src/analyser.ts +163 -53
  12. package/src/baseline.ts +39 -3
  13. package/src/blocks.ts +116 -77
  14. package/src/changed-regions.ts +59 -11
  15. package/src/class-rules.ts +226 -76
  16. package/src/cli-program.ts +61 -14
  17. package/src/cli.ts +1 -0
  18. package/src/comment-rules.ts +58 -13
  19. package/src/comment-scanner.ts +27 -0
  20. package/src/complexity-metrics.ts +244 -0
  21. package/src/config.ts +56 -16
  22. package/src/constants.ts +1 -1
  23. package/src/context-doc-rules.ts +9 -10
  24. package/src/discovery.ts +39 -19
  25. package/src/doc-rules.ts +22 -53
  26. package/src/findings-helpers.ts +127 -1
  27. package/src/findings.ts +4 -0
  28. package/src/fixture-purpose-rules.ts +39 -5
  29. package/src/github-actions-rules.ts +24 -1
  30. package/src/hook-contract.ts +85 -14
  31. package/src/init-config.ts +15 -5
  32. package/src/line-rules.ts +54 -5
  33. package/src/naming-pushers.ts +26 -5
  34. package/src/parsed-script.ts +652 -0
  35. package/src/process-exec-metadata.ts +16 -6
  36. package/src/profiles.ts +14 -0
  37. package/src/project-config-rules.ts +15 -10
  38. package/src/public-exports.ts +220 -0
  39. package/src/report-renderers.ts +55 -4
  40. package/src/rules.ts +11 -11
  41. package/src/scoring.ts +13 -4
  42. package/src/security-flow-rules.ts +169 -24
  43. package/src/sensitive-data-rules.ts +132 -78
  44. package/src/source-text.ts +4 -46
  45. package/src/test-block-rules.ts +118 -14
  46. package/src/test-fixtures.ts +4 -1
  47. package/src/text-scans.ts +8 -1
  48. package/src/types.ts +5 -3
@@ -2,7 +2,15 @@
2
2
  // first argument and shell option into review hints without changing whether the rule fires.
3
3
  import { escapeRegex } from "./findings-helpers.ts";
4
4
 
5
- type ProcessExecArgumentSource = "literal" | "process-exec-path" | "local-const" | "local-builder" | "parameter" | "member" | "template" | "unknown";
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
+ };
6
14
 
7
15
  // Stable scanner state for the first-argument boundary walk.
8
16
  interface ArgumentScanState {
@@ -27,12 +35,12 @@ interface ArgumentScanStep {
27
35
  * @param codeSegment Masked source segment used to read the shell option safely.
28
36
  * @returns Stable metadata describing command-source shape and shell mode.
29
37
  */
30
- export function processExecMetadata(callName: string, rawSource: string, callStart: number, rawSegment: string, codeSegment: string): Record<string, unknown> {
38
+ export function processExecMetadata(callName: string, rawSource: string, callStart: number, rawSegment: string, codeSegment: string): ProcessExecMetadata {
31
39
  const firstArgument = firstProcessCallArgument(rawSegment);
32
40
  return {
33
41
  callName,
34
42
  argumentSource: processExecArgumentSource(rawSource, callStart, firstArgument),
35
- shellEnabled: processExecShellEnabled(callName, codeSegment),
43
+ isShellEnabled: processExecShellEnabled(callName, codeSegment),
36
44
  };
37
45
  }
38
46
 
@@ -133,11 +141,13 @@ function processExecArgumentSource(rawSource: string, callStart: number, firstAr
133
141
  }
134
142
 
135
143
  // Looks backward from the call for a same-scope `const command = "fixed"` shape so reviewers can
136
- // distinguish fixed command vectors from parameter-driven command names.
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.
137
147
  function hasConstLiteralCommandDeclaration(rawSource: string, callStart: number, identifier: string): boolean {
138
148
  const declaration = rawSource.slice(0, callStart).match(new RegExp(`\\bconst\\s+${escapeRegex(identifier)}\\s*=\\s*([^;]+);\\s*$`, "s"));
139
- const initializer = declaration?.[1] ?? "";
140
- return /["'][^"']+["']/.test(initializer) && !/[`$()[\]{}]/.test(initializer);
149
+ const initializer = (declaration?.[1] ?? "").trim();
150
+ return /^(?:"[^"\\]*"|'[^'\\]*')$/.test(initializer);
141
151
  }
142
152
 
143
153
  // Reports default shell semantics: exec/execSync imply a shell unless an explicit option says false,
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
  *
@@ -118,7 +118,7 @@ function pushLifecycleScriptFinding(file: ConfigSourceFile, source: string, scri
118
118
  }
119
119
 
120
120
  /*
121
- * Walks every dependency section in a stable, deterministic order. `runtimeDependency` flag
121
+ * Walks every dependency section in a stable, deterministic order. The `isRuntimeDependency` flag
122
122
  * separates devDependencies from the rest because the broad-version rule should only fire for
123
123
  * runtime drift.
124
124
  */
@@ -128,35 +128,38 @@ function analysePackageDependencies(file: ConfigSourceFile, source: string, pkg:
128
128
  if (!dependencies) {
129
129
  continue;
130
130
  }
131
- const runtimeDependency = section === "dependencies" || section === "optionalDependencies";
131
+ const isRuntimeDependency = section === "dependencies" || section === "optionalDependencies";
132
132
  for (const [packageName, value] of Object.entries(dependencies)) {
133
133
  if (isString(value)) {
134
- analysePackageDependency(file, source, section, packageName, value, runtimeDependency, findings);
134
+ analysePackageDependency(file, source, section, packageName, value, isRuntimeDependency, findings);
135
135
  }
136
136
  }
137
137
  }
138
138
  }
139
139
 
140
+ // Runs both per-dependency checks for one entry; the emission order is a stable contract.
140
141
  function analysePackageDependency(
141
142
  file: ConfigSourceFile,
142
143
  source: string,
143
144
  section: string,
144
145
  packageName: string,
145
146
  versionSpec: string,
146
- runtimeDependency: boolean,
147
+ isRuntimeDependency: boolean,
147
148
  findings: Finding[],
148
149
  ): void {
149
- pushUrlDependencyFinding(file, source, section, packageName, versionSpec, runtimeDependency, findings);
150
- 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);
151
152
  }
152
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.
153
156
  function pushUrlDependencyFinding(
154
157
  file: ConfigSourceFile,
155
158
  source: string,
156
159
  section: string,
157
160
  packageName: string,
158
161
  versionSpec: string,
159
- runtimeDependency: boolean,
162
+ isRuntimeDependency: boolean,
160
163
  findings: Finding[],
161
164
  ): void {
162
165
  if (!isUrlDependency(versionSpec)) {
@@ -173,21 +176,23 @@ function pushUrlDependencyFinding(
173
176
  confidence: "medium",
174
177
  symbol: packageName,
175
178
  remediation: "Prefer a registry package version that can be locked and audited.",
176
- metadata: { packageName, section, runtimeDependency },
179
+ metadata: { packageName, section, runtimeDependency: isRuntimeDependency },
177
180
  }),
178
181
  );
179
182
  }
180
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.
181
186
  function pushBroadRuntimeDependencyFinding(
182
187
  file: ConfigSourceFile,
183
188
  source: string,
184
189
  section: string,
185
190
  packageName: string,
186
191
  versionSpec: string,
187
- runtimeDependency: boolean,
192
+ isRuntimeDependency: boolean,
188
193
  findings: Finding[],
189
194
  ): void {
190
- if (!runtimeDependency || !isBroadRuntimeVersion(versionSpec)) {
195
+ if (!isRuntimeDependency || !isBroadRuntimeVersion(versionSpec)) {
191
196
  return;
192
197
  }
193
198
  findings.push(
@@ -0,0 +1,220 @@
1
+ // Syntax-backed public-export inventory for naming diagnostics. It reads the shared parsed
2
+ // script, resolves direct, default, and bottom re-export forms to one declaration list, and never
3
+ // parses a user's file again. The class/file rule reaches this module when deciding whether a
4
+ // mismatched class is the only public declaration a CLI or report user needs to locate.
5
+ import { createRequire } from "node:module";
6
+ import type { ParsedScript } from "./parsed-script.ts";
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const typescriptSyntax = require("typescript") as typeof import("typescript");
10
+
11
+ type TsSourceFile = import("typescript").SourceFile;
12
+ type TsStatement = import("typescript").Statement;
13
+ type TsExportDeclaration = import("typescript").ExportDeclaration;
14
+ type TsExportAssignment = import("typescript").ExportAssignment;
15
+
16
+ /*
17
+ * Stable declaration categories shown inside class/file finding metadata. `default` and
18
+ * `re-export` represent public values whose local declaration kind is unavailable without type
19
+ * checking, so report users still see why a class was not treated as the sole export.
20
+ */
21
+ export type PublicExportKind = "class" | "interface" | "type" | "enum" | "function" | "default" | "re-export";
22
+
23
+ /*
24
+ * One deterministic public declaration from the user's module. Resolved local re-exports retain
25
+ * the local kind, name, and declaration line; unresolved external/default values use the export
26
+ * statement line so the inventory remains complete without a semantic program.
27
+ * `exportedName` is present only when an alias renames the declaration on its way out, because the
28
+ * name a consumer imports is the one a naming rule about the public surface has to judge.
29
+ */
30
+ export interface PublicExportDeclaration {
31
+ kind: PublicExportKind;
32
+ name: string;
33
+ line: number;
34
+ exportedName?: string;
35
+ }
36
+
37
+ /*
38
+ * The five named declaration forms already covered by the public-doc scan. Keeping this syntax
39
+ * set explicit prevents value exports from silently widening the class/file policy beyond the
40
+ * module shapes named in the rule's user documentation.
41
+ */
42
+ type SupportedDeclaration =
43
+ | import("typescript").ClassDeclaration
44
+ | import("typescript").InterfaceDeclaration
45
+ | import("typescript").TypeAliasDeclaration
46
+ | import("typescript").EnumDeclaration
47
+ | import("typescript").FunctionDeclaration;
48
+
49
+ /**
50
+ * Builds the stable sorted public-declaration contract used by class/file naming diagnostics.
51
+ * @param parsed Shared parse for the user's script; callers never pass null or undefined.
52
+ * @returns Sorted declarations; an empty array means the module exposes none of the supported forms.
53
+ */
54
+ export function publicExportDeclarations(parsed: ParsedScript): PublicExportDeclaration[] {
55
+ const localDeclarations = localDeclarationIndex(parsed.sourceFile);
56
+ const publicDeclarations = new Map<string, PublicExportDeclaration>();
57
+ // A second top-level pass can resolve bottom exports because every local declaration is indexed first.
58
+ for (const statement of parsed.sourceFile.statements) {
59
+ collectDirectExport(parsed.sourceFile, statement, publicDeclarations);
60
+ // Export declarations cover named, namespace, wildcard, local, and external re-export syntax.
61
+ if (typescriptSyntax.isExportDeclaration(statement)) {
62
+ collectNamedOrExternalExport(parsed.sourceFile, statement, localDeclarations, publicDeclarations);
63
+ }
64
+ // Export assignments cover `export default LocalName` and expression-valued defaults.
65
+ if (typescriptSyntax.isExportAssignment(statement)) {
66
+ collectExportAssignment(parsed.sourceFile, statement, localDeclarations, publicDeclarations);
67
+ }
68
+ }
69
+ return [...publicDeclarations.values()].sort(comparePublicDeclarations);
70
+ }
71
+
72
+ // Indexes supported top-level declarations before export statements are resolved. Empty source
73
+ // produces an empty map, which means a later external re-export remains explicitly unresolved.
74
+ function localDeclarationIndex(sourceFile: TsSourceFile): Map<string, PublicExportDeclaration> {
75
+ const declarations = new Map<string, PublicExportDeclaration>();
76
+ // Bottom-of-file exports need declarations from the entire module, including later source lines.
77
+ for (const statement of sourceFile.statements) {
78
+ const declaration = supportedDeclaration(sourceFile, statement);
79
+ // Anonymous default declarations have no local name for another export statement to reference.
80
+ if (!declaration || declaration.name === "default") {
81
+ continue;
82
+ }
83
+ const existingDeclaration = declarations.get(declaration.name);
84
+ // A merged class is the runtime value a bottom export exposes; otherwise retain the earliest
85
+ // declaration anchor for deterministic output.
86
+ if (!existingDeclaration || declaration.kind === "class" && existingDeclaration.kind !== "class") {
87
+ declarations.set(declaration.name, declaration);
88
+ }
89
+ }
90
+ return declarations;
91
+ }
92
+
93
+ // Adds a supported declaration only when the user exported it on its declaration line.
94
+ function collectDirectExport(sourceFile: TsSourceFile, statement: TsStatement, publicDeclarations: Map<string, PublicExportDeclaration>): void {
95
+ const declaration = supportedDeclaration(sourceFile, statement);
96
+ // Local-only declarations are indexed for possible bottom exports but are not public yet.
97
+ if (!declaration || !hasModifier(statement, typescriptSyntax.SyntaxKind.ExportKeyword)) {
98
+ return;
99
+ }
100
+ addPublicDeclaration(publicDeclarations, declaration);
101
+ }
102
+
103
+ // Resolves one export declaration to local declaration facts when possible, otherwise records the
104
+ // external public name. This is what keeps class selection syntax-independent for CLI users.
105
+ function collectNamedOrExternalExport(sourceFile: TsSourceFile, statement: TsExportDeclaration, localDeclarations: Map<string, PublicExportDeclaration>, publicDeclarations: Map<string, PublicExportDeclaration>): void {
106
+ const exportLine = sourceLine(sourceFile, statement);
107
+ const exportClause = statement.exportClause;
108
+ // A wildcard still exposes another module surface even though syntax alone cannot name each item.
109
+ if (!exportClause) {
110
+ addPublicDeclaration(publicDeclarations, { kind: "re-export", name: "*", line: exportLine });
111
+ return;
112
+ }
113
+ // Namespace exports have one explicit public name, such as `export * as tools`.
114
+ if (typescriptSyntax.isNamespaceExport(exportClause)) {
115
+ addPublicDeclaration(publicDeclarations, { kind: "re-export", name: exportClause.name.text, line: exportLine });
116
+ return;
117
+ }
118
+ // Each named export is one public declaration unless it resolves to the same local declaration.
119
+ for (const exportSpecifier of exportClause.elements) {
120
+ // An alias resolves through its local source name; an unaliased export uses its public name.
121
+ const localName = (exportSpecifier.propertyName ?? exportSpecifier.name).text;
122
+ const publicName = exportSpecifier.name.text;
123
+ const localDeclaration = statement.moduleSpecifier ? undefined : localDeclarations.get(localName);
124
+ // External or unresolved names remain visible as re-exports so they still prevent sole-class advice.
125
+ addPublicDeclaration(publicDeclarations, localDeclaration
126
+ // A rename keeps the local kind and anchor but records the name consumers actually import.
127
+ ? { ...localDeclaration, ...(publicName === localDeclaration.name ? {} : { exportedName: publicName }) }
128
+ : { kind: "re-export", name: publicName, line: exportLine });
129
+ }
130
+ }
131
+
132
+ // Resolves an identifier-valued default/export-equals assignment to its declaration. Expression
133
+ // defaults remain one explicit public item because the user still exported a second module value.
134
+ function collectExportAssignment(sourceFile: TsSourceFile, statement: TsExportAssignment, localDeclarations: Map<string, PublicExportDeclaration>, publicDeclarations: Map<string, PublicExportDeclaration>): void {
135
+ const localDeclaration = typescriptSyntax.isIdentifier(statement.expression) ? localDeclarations.get(statement.expression.text) : undefined;
136
+ // A named local class exported as default must retain its class name and declaration anchor.
137
+ if (localDeclaration) {
138
+ addPublicDeclaration(publicDeclarations, localDeclaration);
139
+ return;
140
+ }
141
+ const unresolvedExport = statement.isExportEquals
142
+ ? { kind: "re-export" as const, name: "export=", line: sourceLine(sourceFile, statement) }
143
+ : { kind: "default" as const, name: "default", line: sourceLine(sourceFile, statement) };
144
+ addPublicDeclaration(publicDeclarations, unresolvedExport);
145
+ }
146
+
147
+ // Projects a supported top-level syntax node into the user-visible kind, name, and line tuple.
148
+ // Undefined means the statement is outside the class/interface/type/enum/function policy surface.
149
+ function supportedDeclaration(sourceFile: TsSourceFile, statement: TsStatement): PublicExportDeclaration | undefined {
150
+ // Other top-level statements, such as imports and exported constants, do not enter this policy slice.
151
+ if (!isSupportedDeclaration(statement)) {
152
+ return undefined;
153
+ }
154
+ const kind = supportedDeclarationKind(statement);
155
+ // Named declarations retain their symbol; anonymous defaults use one stable placeholder.
156
+ const name = statement.name?.text ?? (hasModifier(statement, typescriptSyntax.SyntaxKind.DefaultKeyword) ? "default" : undefined);
157
+ // A non-default anonymous declaration has no stable symbol a class/file finding could present.
158
+ if (!name) {
159
+ return undefined;
160
+ }
161
+ return { kind, name, line: sourceLine(sourceFile, statement) };
162
+ }
163
+
164
+ // Narrows top-level syntax to the declaration forms named by the class/file rule policy.
165
+ function isSupportedDeclaration(statement: TsStatement): statement is SupportedDeclaration {
166
+ return typescriptSyntax.isClassDeclaration(statement)
167
+ || typescriptSyntax.isInterfaceDeclaration(statement)
168
+ || typescriptSyntax.isTypeAliasDeclaration(statement)
169
+ || typescriptSyntax.isEnumDeclaration(statement)
170
+ || typescriptSyntax.isFunctionDeclaration(statement);
171
+ }
172
+
173
+ // Converts a narrowed syntax declaration to the stable lowercase metadata category.
174
+ function supportedDeclarationKind(declaration: SupportedDeclaration): Exclude<PublicExportKind, "default" | "re-export"> {
175
+ // The class check comes first because it is the only kind eligible for the eventual finding.
176
+ if (typescriptSyntax.isClassDeclaration(declaration)) {
177
+ return "class";
178
+ }
179
+ // Interfaces and type aliases remain distinct so users can understand a multi-export contract surface.
180
+ if (typescriptSyntax.isInterfaceDeclaration(declaration)) {
181
+ return "interface";
182
+ }
183
+ if (typescriptSyntax.isTypeAliasDeclaration(declaration)) {
184
+ return "type";
185
+ }
186
+ // Enums keep their own category so a report explains why a module is multi-public.
187
+ if (typescriptSyntax.isEnumDeclaration(declaration)) {
188
+ return "enum";
189
+ }
190
+ return "function";
191
+ }
192
+
193
+ // Reads one modifier without assuming every statement kind exposes a modifier array.
194
+ function hasModifier(statement: TsStatement, modifierKind: import("typescript").SyntaxKind): boolean {
195
+ // Statement kinds without modifier storage behave as an empty modifier list for the user.
196
+ const modifiers = typescriptSyntax.canHaveModifiers(statement) ? typescriptSyntax.getModifiers(statement) : undefined;
197
+ return modifiers?.some((modifier) => modifier.kind === modifierKind) === true;
198
+ }
199
+
200
+ // Adds one declaration by stable kind/name key. Repeated aliases and merged declarations stay one
201
+ // public item, with the earliest source anchor retained for deterministic user output.
202
+ function addPublicDeclaration(publicDeclarations: Map<string, PublicExportDeclaration>, declaration: PublicExportDeclaration): void {
203
+ const key = `${declaration.kind}:${declaration.name}`;
204
+ const existingDeclaration = publicDeclarations.get(key);
205
+ // The first source occurrence is the clearest anchor when aliases expose the same declaration twice.
206
+ if (!existingDeclaration || declaration.line < existingDeclaration.line) {
207
+ publicDeclarations.set(key, declaration);
208
+ }
209
+ }
210
+
211
+ // Converts a syntax start offset to the one-based source line shown in findings and metadata probes.
212
+ function sourceLine(sourceFile: TsSourceFile, statement: TsStatement): number {
213
+ return sourceFile.getLineAndCharacterOfPosition(statement.getStart(sourceFile)).line + 1;
214
+ }
215
+
216
+ // Sorts by the serialized kind:name value, then line as a deterministic tie-breaker.
217
+ function comparePublicDeclarations(left: PublicExportDeclaration, right: PublicExportDeclaration): number {
218
+ const labelOrder = `${left.kind}:${left.name}`.localeCompare(`${right.kind}:${right.name}`);
219
+ return labelOrder || left.line - right.line;
220
+ }
@@ -41,7 +41,8 @@ type JsonAnalysisReport = Omit<AnalysisReport, "findings" | "score"> & {
41
41
  score: Omit<AnalysisReport["score"], "topOffenders"> & { topOffenders: JsonTopOffender[] };
42
42
  };
43
43
 
44
- // JSON boundary adapter: canonical `file` is emitted while legacy `filePath` stays for one release.
44
+ // JSON boundary adapter: canonical `file` is emitted while legacy `filePath` remains until the
45
+ // coordinated family JSON unification; a port-local removal would break existing report users.
45
46
  // Stable `gruff.analysis.v2` contract line kept adjacent to the function for the doc-context rule.
46
47
  function toJsonReport(report: AnalysisReport): JsonAnalysisReport {
47
48
  return {
@@ -314,6 +315,7 @@ function formatSummaryDuration(elapsedMs: number): string {
314
315
  return `${(bounded / 1000).toFixed(2)}s`;
315
316
  }
316
317
 
318
+ // Tallies findings under the caller-supplied key; iteration order stays deterministic for renderers.
317
319
  function countBy<T extends string>(findings: Finding[], keyFor: (finding: Finding) => T): Map<T, number> {
318
320
  const counts = new Map<T, number>();
319
321
  for (const finding of findings) {
@@ -390,6 +392,7 @@ function truncateDescription(text: string): string {
390
392
  return text.length <= DESCRIPTION_BODY_LIMIT ? text : `${text.slice(0, DESCRIPTION_BODY_LIMIT).trimEnd()}…`;
391
393
  }
392
394
 
395
+ // Renders a count map as ranked text bullets; the (count DESC, key ASC) ordering is deterministic.
393
396
  function renderRankedCounts<T extends string>(counts: Map<T, number>, emptyText: string, limit?: number): string[] {
394
397
  if (counts.size === 0) {
395
398
  return [`- ${emptyText}`];
@@ -400,6 +403,7 @@ function renderRankedCounts<T extends string>(counts: Map<T, number>, emptyText:
400
403
  .map(([key, count]) => `- ${key}: ${count}`);
401
404
  }
402
405
 
406
+ // Structured variant of `renderRankedCounts` for JSON consumers; the same deterministic ordering.
403
407
  function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?: number): Array<{ name: T; count: number }> {
404
408
  return [...counts.entries()]
405
409
  .sort(([leftKey, leftCount], [rightKey, rightCount]) => rightCount - leftCount || leftKey.localeCompare(rightKey))
@@ -448,6 +452,10 @@ function renderText(report: AnalysisReport): string {
448
452
  */
449
453
  function renderMarkdown(report: AnalysisReport): string {
450
454
  const breakdown = severityGradeBreakdown(report.findings);
455
+ // A repository controls each displayed value; a missing line keeps the historic line-1 fallback.
456
+ const findingRows = report.findings
457
+ .slice(0, 50)
458
+ .map((finding) => `- ${markdownInlineCode(finding.ruleId)} ${markdownInlineCode(finding.filePath)}:${finding.line ?? 1} - ${escapeMarkdownFindingMessage(finding.message)}`);
451
459
  return [
452
460
  "# gruff-ts report",
453
461
  "",
@@ -461,7 +469,7 @@ function renderMarkdown(report: AnalysisReport): string {
461
469
  "",
462
470
  ...renderMarkdownPillarsTable(buildPillarRows(report)),
463
471
  "",
464
- ...report.findings.slice(0, 50).map((finding) => `- \`${finding.ruleId}\` \`${finding.filePath}\`:${finding.line ?? 1} - ${finding.message}`),
472
+ ...findingRows,
465
473
  ].join("\n");
466
474
  }
467
475
 
@@ -499,6 +507,38 @@ function escapeMarkdownCell(cell: string): string {
499
507
  return cell.replaceAll("|", "\\|");
500
508
  }
501
509
 
510
+ // Wraps a repository-controlled label in a CommonMark code span for PR and issue reports.
511
+ // A fence longer than the label's longest backtick run keeps the label inside one span.
512
+ function markdownInlineCode(reportLabel: string): string {
513
+ const singleLineLabel = reportLabel.replace(/[\r\n]+/g, " ");
514
+ // An empty analyzer label still needs content so Markdown does not merge its two fences.
515
+ const visibleLabel = singleLineLabel.length === 0 ? " " : singleLineLabel;
516
+ const fenceLength = Math.max(1, ...Array.from(visibleLabel.matchAll(/`+/g), (match) => match[0].length + 1));
517
+ const fence = "`".repeat(fenceLength);
518
+ // Edge backticks need padding so CommonMark can distinguish label content from the fence.
519
+ const paddedLabel = visibleLabel.startsWith("`") || visibleLabel.endsWith("`") ? ` ${visibleLabel} ` : visibleLabel;
520
+ return `${fence}${paddedLabel}${fence}`;
521
+ }
522
+
523
+ // Escapes repository-controlled finding prose before a reviewer sees the Markdown report.
524
+ // Line breaks collapse so a message cannot start a new heading, list, or HTML block.
525
+ function escapeMarkdownFindingMessage(findingMessage: string): string {
526
+ return findingMessage
527
+ .replace(/[\r\n]+/g, " ")
528
+ .replaceAll("&", "&amp;")
529
+ .replaceAll("<", "&lt;")
530
+ .replaceAll(">", "&gt;")
531
+ .replaceAll("\\", "\\\\")
532
+ .replaceAll("`", "\\`")
533
+ .replaceAll("*", "\\*")
534
+ .replaceAll("_", "\\_")
535
+ .replaceAll("[", "\\[")
536
+ .replaceAll("]", "\\]")
537
+ .replaceAll("|", "\\|")
538
+ .replaceAll("#", "\\#")
539
+ .replaceAll("~", "\\~");
540
+ }
541
+
502
542
  // Render-only summary of overlapping complexity findings for one function symbol.
503
543
  interface ComplexityCluster {
504
544
  filePath: string;
@@ -523,18 +563,29 @@ function renderComplexityClusterLines(findings: Finding[], limit = 10): string[]
523
563
  // Invariant: markdown mirrors text complexity clusters without adding JSON fields.
524
564
  function renderMarkdownComplexityClusterLines(findings: Finding[]): string[] {
525
565
  const clusters = complexityClusters(findings);
566
+ // A scan with no overlapping complexity findings should not show an empty review section.
526
567
  if (clusters.length === 0) {
527
568
  return [];
528
569
  }
570
+ // Repository paths and symbols stay inside one code span in the reviewer's cluster list.
571
+ const clusterRows = clusters.map(renderMarkdownComplexityClusterRow);
529
572
  return [
530
573
  "",
531
574
  "## Correlated Complexity Clusters",
532
575
  "",
533
- ...clusters.map((cluster) => `- \`${cluster.filePath}#${cluster.symbol}\`: ${cluster.ruleIds.length} linked findings (${cluster.ruleIds.map((ruleId) => `\`${ruleId}\``).join(", ")})`),
576
+ ...clusterRows,
534
577
  ];
535
578
  }
536
579
 
537
- // Groups correlated complexity findings by file and symbol so renderers can explain score overlap.
580
+ // Formats one correlated cluster for the Markdown list a reviewer sees in pull-request output.
581
+ function renderMarkdownComplexityClusterRow(cluster: ComplexityCluster): string {
582
+ const clusterLabel = `${cluster.filePath}#${cluster.symbol}`;
583
+ // Every linked rule remains its own code span so a reviewer can copy its exact identifier.
584
+ const linkedRuleLabels = cluster.ruleIds.map((ruleId) => markdownInlineCode(ruleId)).join(", ");
585
+ return `- ${markdownInlineCode(clusterLabel)}: ${cluster.ruleIds.length} linked findings (${linkedRuleLabels})`;
586
+ }
587
+
588
+ // Invariant: groups findings by file and symbol so every renderer explains score overlap consistently.
538
589
  function complexityClusters(findings: Finding[]): ComplexityCluster[] {
539
590
  const bySymbol = new Map<string, ComplexityCluster>();
540
591
  for (const finding of findings) {
package/src/rules.ts CHANGED
@@ -2,14 +2,14 @@
2
2
  import type { RuleDescriptor } from "./types.ts";
3
3
 
4
4
  const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
5
- { ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with high combined branch and nesting complexity.", remediation: "Split nested decisions into smaller named functions. Or raise rules.complexity.cognitive.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 },
6
- { ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with many independent branch paths.", remediation: "Reduce branching or move policy tables out of imperative code. Or raise rules.complexity.cyclomatic.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 }, { ruleId: "dead-code.unused-private-method", pillar: "dead-code", severity: "advisory", confidence: "low", description: "Flags private methods without an apparent same-file call site.", remediation: "Remove the method or add a direct call site." },
5
+ { ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags syntax-aware decisions plus nested if, loop, switch, catch, and ternary depth; object and callback braces add no nesting.", remediation: "Split nested decisions into smaller named functions. Or raise rules.complexity.cognitive.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 },
6
+ { ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "Counts a base path plus if, loop, catch, non-default case, ternary, &&, and || nodes; switch, default, ??, optional chains, and non-null assertions add zero.", remediation: "Reduce branching or move policy tables out of imperative code. Or raise rules.complexity.cyclomatic.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 }, { ruleId: "dead-code.unused-private-method", pillar: "dead-code", severity: "advisory", confidence: "low", description: "Flags private methods without an apparent same-file call site.", remediation: "Remove the method or add a direct call site." },
7
7
  { ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags strongly connected relative import components that include the scan surface.", remediation: "Extract the shared contract or invert one dependency." },
8
8
  { ruleId: "design.deep-relative-import", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags relative imports that climb too many parent directories.", remediation: "Move the shared module closer or add a local boundary. Or raise rules.design.deep-relative-import.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 2 },
9
9
  { ruleId: "design.large-module-concentration", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags a production module that dominates project source lines.", remediation: "Split unrelated responsibilities once stable seams are visible. Or raise rules.design.large-module-concentration.threshold or tune minFiles, minLines under rules.design.large-module-concentration.options.", threshold: 55, optionKeys: ["minFiles", "minLines"] },
10
10
  { ruleId: "design.package-bin-missing", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin entries that point at missing files.", remediation: "Update the bin path or add the executable file." },
11
11
  { ruleId: "design.package-bin-not-executable", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin targets that are not executable.", remediation: "Make the bin target executable and keep its shebang valid." },
12
- { ruleId: "docs.fixture-purpose-missing", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags large or scanner-relevant fixtures without a nearby purpose comment.", remediation: "Explain what scanner path, regression, or fixture behavior the source covers." },
12
+ { ruleId: "docs.fixture-purpose-missing", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags large or scanner-relevant fixtures without a nearby purpose comment.", remediation: "Add a comment on or directly above the fixture (or above the test declaration) explaining what scanner path, regression, or fixture behavior it covers." },
13
13
  { ruleId: "docs.magic-threshold-without-rationale", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags threshold-like numeric values without a nearby rationale comment.", remediation: "Explain the threshold, limit, budget, or default near the value." },
14
14
  { ruleId: "docs.missing-error-behavior-doc", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags commented functions whose error behavior is not described.", remediation: "Document thrown errors, diagnostics, exits, reports, or recovery behavior." },
15
15
  { ruleId: "docs.missing-exported-function-doc", pillar: "documentation", severity: "warning", confidence: "medium", description: "Flags exported functions without a leading maintainer comment.", remediation: "Add a JSDoc or line comment explaining the exported API's contract, since public surface has a higher cost of omission." },
@@ -25,7 +25,7 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
25
25
  { ruleId: "docs.stale-comment", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags comments that reference missing files, unknown rules, stale CLI flags, or the wrong declaration.", remediation: "Update the comment or add historical context explaining why it remains useful." },
26
26
  { ruleId: "docs.stale-param-tag", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags @param tags for parameters no longer in the signature.", remediation: "Remove stale tags or update the function signature." },
27
27
  { ruleId: "docs.suppression-without-rationale", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags lint, formatter, coverage, or tool suppressions without a maintainer rationale.", remediation: "Explain why the suppression is intentional, a false positive, or tracked elsewhere." },
28
- { ruleId: "docs.todo-without-tracking", pillar: "documentation", severity: "advisory", confidence: "high", description: "Flags TODO, FIXME, HACK, and XXX comments without tracking context.", remediation: "Attach a tracking URL, issue id, owner, date, ADR, or .goat-flow task reference." },
28
+ { ruleId: "docs.todo-without-tracking", pillar: "documentation", severity: "advisory", confidence: "high", description: "Flags comments introduced by a TODO, FIXME, HACK, or XXX marker without tracking context; prose that only mentions a marker word stays quiet.", remediation: "Attach a tracking URL, issue id, owner, date, ADR, or .goat-flow task reference." },
29
29
  { ruleId: "docs.useless-docblock", pillar: "documentation", severity: "advisory", confidence: "medium", description: "Flags comments or docblocks that only restate the symbol name.", remediation: "Replace the comment with useful contract or behavior detail." },
30
30
  { ruleId: "modernisation.date-now-candidate", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags verbose current-time expressions that can use Date.now().", remediation: "Use Date.now() for current epoch milliseconds." },
31
31
  { ruleId: "modernisation.double-cast", pillar: "modernisation", severity: "warning", confidence: "medium", description: "Flags casts through unknown or any into another type.", remediation: "Use a parser, type guard, or narrower assertion." },
@@ -41,14 +41,14 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
41
41
  { ruleId: "modernisation.tsconfig-index-safety-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without noUncheckedIndexedAccess enabled.", remediation: "Enable noUncheckedIndexedAccess unless migration is blocked." },
42
42
  { ruleId: "modernisation.tsconfig-strict-disabled", pillar: "modernisation", severity: "warning", confidence: "high", description: "Flags tsconfig files without strict mode enabled.", remediation: "Enable strict unless migration is blocked." },
43
43
  { ruleId: "modernisation.var-declaration", pillar: "modernisation", severity: "advisory", confidence: "high", description: "Flags var declarations.", remediation: "Use let or const with the narrowest useful scope." },
44
- { ruleId: "naming.acronym-case", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags mixed casings of a known acronym in one file.", remediation: "Use one casing for each acronym throughout the file. Or extend allowlists.knownAcronyms with project-specific values.", allowlistKeys: ["knownAcronyms"] },
45
- { ruleId: "naming.boolean-prefix", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean names without intent-revealing prefixes on declarations, function parameters (typed `: boolean` or with `= true|false` default), and interface/type-literal fields.", remediation: "Use prefixes such as is, has, can, should, or will. Or extend allowlists.booleanPrefixes / allowlists.acceptedBooleanNames for project-specific contract names.", allowlistKeys: ["booleanPrefixes", "acceptedBooleanNames"] },
46
- { ruleId: "naming.class-file-mismatch", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags exported classes whose name differs from the file name.", remediation: "Rename the class or file so the primary export is easy to locate." },
44
+ { ruleId: "naming.acronym-case", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags a known acronym cased inconsistently across a file's chosen-case names; SCREAMING_SNAKE constants and all-lower names are convention-forced and exempt.", remediation: "Use one casing for each acronym throughout the file. Or extend allowlists.knownAcronyms with project-specific values.", allowlistKeys: ["knownAcronyms"] },
45
+ { ruleId: "naming.boolean-prefix", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean names without intent-revealing prefixes on declarations, function parameters (typed `: boolean` or with `= true|false` default), and interface/type-literal fields.", remediation: "Rename local booleans with an intent prefix. For contract fields, rename or map the key at serialization, or replace allowlists.acceptedBooleanNames with a complete list that includes it.", allowlistKeys: ["booleanPrefixes", "acceptedBooleanNames"] },
46
+ { ruleId: "naming.class-file-mismatch", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags a sole public class whose name differs from the file name.", remediation: "Rename the class or file, or add the exact fileBase:ClassName pair to allowlists.acceptedClassFilePairs.", allowlistKeys: ["acceptedClassFilePairs"] },
47
47
  { ruleId: "naming.generic-function", pillar: "naming", severity: "advisory", confidence: "high", description: "Flags generic function names that hide intent.", remediation: "Name the domain action instead of a generic operation. Or remove the name from allowlists.bannedGenericNames if your project does not consider it generic.", allowlistKeys: ["bannedGenericNames"] },
48
48
  { ruleId: "naming.generic-parameter", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder parameter names in multi-parameter, long, exported, or complex functions.", remediation: "Use a name that describes the parameter's role. Or tune minCyclomatic, minLineCount, minParameters under rules.naming.generic-parameter.options.", optionKeys: ["minCyclomatic", "minLineCount", "minParameters"] },
49
49
  { ruleId: "naming.hungarian-notation", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags identifiers named after storage type prefixes.", remediation: "Name the domain concept instead of the storage type. Or remove the prefix from allowlists.hungarianPrefixes if your project does not consider it Hungarian-style.", allowlistKeys: ["hungarianPrefixes"] },
50
50
  { ruleId: "naming.identifier-quality", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags placeholder or numbered identifiers on declarations, function parameters, and destructured locals.", remediation: "Use names that explain domain role or intent. Or remove the name from allowlists.placeholderNames if your project considers it valid.", allowlistKeys: ["placeholderNames"] },
51
- { ruleId: "naming.inconsistent-casing", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags the same canonical identifier appearing in two different surface forms (for example CONSTANT_CASE and camelCase) in one file.", remediation: "Choose one form and use it consistently within the file." },
51
+ { ruleId: "naming.inconsistent-casing", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags one canonical identifier appearing in different forms within the same module, function, interface, or named type-literal owner.", remediation: "Choose one form within the owner, or add an exact alias pair to allowlists.acceptedCasingPairs.", allowlistKeys: ["acceptedCasingPairs"] },
52
52
  { ruleId: "naming.negative-boolean", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags boolean identifiers framed as a negation on declarations, parameters, and interface fields.", remediation: "Invert the framing so callers do not read a double negation. Or extend allowlists.negativeBooleanAllowed with project-specific values.", allowlistKeys: ["negativeBooleanAllowed"] },
53
53
  { ruleId: "naming.short-variable", pillar: "naming", severity: "advisory", confidence: "medium", description: "Flags very short variable names outside common loop counters; covers declarations, function parameters, and destructured locals.", remediation: "Use a name that describes the domain role. Or extend allowlists.acceptedAbbreviations with project-specific values.", allowlistKeys: ["acceptedAbbreviations"] },
54
54
  { ruleId: "security.async-foreach", pillar: "security", severity: "warning", confidence: "medium", description: "Flags async callbacks passed to forEach.", remediation: "Use for...of with await, Promise.all, or an explicit queue." },
@@ -68,7 +68,7 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
68
68
  { ruleId: "security.new-function", pillar: "security", severity: "error", confidence: "high", description: "Flags Function constructor dynamic code execution.", remediation: "Replace dynamic construction with explicit functions or dispatch." },
69
69
  { ruleId: "security.open-redirect-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to redirect or navigation sinks.", remediation: "Redirect only to relative paths or destinations from an allowlist." },
70
70
  { ruleId: "security.path-traversal-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to filesystem path sinks.", remediation: "Validate paths against an allowlist and resolve them under a safe root." },
71
- { ruleId: "security.process-exec", pillar: "security", severity: "warning", confidence: "high", description: "Flags child-process execution calls and annotates emitted findings with command-source and shell-mode hints.", remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled." },
71
+ { ruleId: "security.process-exec", pillar: "security", severity: "warning", confidence: "high", description: "Flags child-process execution calls, grading severity from command-source and shell-mode evidence: warning only when a shell-enabled call takes a dynamic command.", remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled." },
72
72
  { ruleId: "security.proto-access", pillar: "security", severity: "warning", confidence: "medium", description: "Flags direct __proto__ access that can enable prototype pollution.", remediation: "Use Object.getPrototypeOf, Object.create(null), or validated keys." },
73
73
  { ruleId: "security.remote-install-script", pillar: "security", severity: "error", confidence: "medium", description: "Flags package scripts that pipe remote content to a shell.", remediation: "Vendor, pin, or remove remote shell execution." },
74
74
  { ruleId: "security.risky-lifecycle-script", pillar: "security", severity: "warning", confidence: "medium", description: "Flags install-time and side-effectful publish lifecycle scripts while allowing validation-only publish gates.", remediation: "Review whether lifecycle execution is required; keep install/publish side effects behind explicit commands when possible." },
@@ -90,13 +90,13 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
90
90
  { ruleId: "sensitive-data.phi-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PHI identifiers such as Medicare (MBI) and medical record numbers.", remediation: "Remove protected health information from source and fixtures." },
91
91
  { ruleId: "sensitive-data.pii-pattern", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags PII-like identifier patterns including SSN-shaped values and Luhn-valid payment cards.", remediation: "Remove personal data from source and fixtures." },
92
92
  { ruleId: "sensitive-data.private-key", pillar: "sensitive-data", severity: "error", confidence: "high", description: "Flags private key block markers.", remediation: "Remove the key material and rotate affected credentials." },
93
- { ruleId: "size.file-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags files longer than the configured threshold.", remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 750 },
93
+ { ruleId: "size.file-length", pillar: "size", severity: "error", confidence: "high", description: "Flags files whose substantive nonblank, non-comment line count exceeds the configured threshold.", remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 1000 },
94
94
  { ruleId: "size.function-length", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions longer than the configured threshold.", remediation: "Extract named helpers or split workflows. Or raise rules.size.function-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 200 },
95
95
  { ruleId: "size.parameter-count", pillar: "size", severity: "warning", confidence: "high", description: "Flags functions with too many parameters.", remediation: "Group related options or reduce the function's responsibility. Or raise rules.size.parameter-count.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 7 },
96
96
  { ruleId: "test-quality.conditional-logic", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests with conditional logic.", remediation: "Split branch-specific expectations into separate tests." },
97
97
  { ruleId: "test-quality.exception-type-only", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only assert exception type.", remediation: "Assert message, code, or observable behavior as well." },
98
98
  { ruleId: "test-quality.global-state-mutation", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests mutating process or global runtime state.", remediation: "Isolate state changes and restore them around the test." },
99
- { ruleId: "test-quality.loop-in-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags loops inside test bodies.", remediation: "Use table tests or separate named cases." },
99
+ { ruleId: "test-quality.loop-in-test", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags test-body loops whose assertions do not identify the failing iteration.", remediation: "Add a per-case message to looped assertions, or use a fixture table or separate named cases." },
100
100
  { ruleId: "test-quality.magic-number-assertion", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags assertions against unexplained numeric literals.", remediation: "Name expected values or assert domain-specific outcomes." },
101
101
  { ruleId: "test-quality.mock-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only verify mock interaction.", remediation: "Assert observable behavior in addition to collaboration." },
102
102
  { ruleId: "test-quality.no-assertions", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests without apparent assertions.", remediation: "Add assertions for observable behavior." },