@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
@@ -119,14 +119,21 @@ function analyseGlobalStateMutation(file: SourceFile, block: FunctionBlock, body
119
119
  function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
120
120
  const checks: Array<[string, boolean, string]> = [
121
121
  ["test-quality.sleep-in-test", /\b(setTimeout|sleep|waitForTimeout)\s*\(/.test(body), "Test sleeps instead of synchronising on behaviour."],
122
- ["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic around assertions."],
122
+ ["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic that hides which iteration failed."],
123
123
  ["test-quality.conditional-logic", controlFlowContainsAssertion(body, /\b(?:if|switch)\b/g), "Test contains conditional logic around assertions."],
124
124
  ["test-quality.only-skip", /\.(only|skip)\s*\(/.test(body), "Focused or skipped test is committed."],
125
125
  ];
126
126
  for (const [ruleId, active, message] of checks) {
127
- if (active) {
128
- findings.push(blockFinding({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality" }));
127
+ if (!active) {
128
+ continue;
129
+ }
130
+ // Loop findings report at medium confidence: parametrized tests are a legitimate pattern and
131
+ // the label heuristic cannot see every message shape (multi-line assertion calls, helpers).
132
+ if (ruleId === "test-quality.loop-in-test") {
133
+ findings.push(blockFindingWithMetadata({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality", metadata: {} }));
134
+ continue;
129
135
  }
136
+ findings.push(blockFinding({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality" }));
130
137
  }
131
138
  }
132
139
 
@@ -144,32 +151,110 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
144
151
  if (isFixtureLoop(source, start, segment)) {
145
152
  continue;
146
153
  }
154
+ if (isLabeledCaseLoop(segment)) {
155
+ continue;
156
+ }
147
157
  return true;
148
158
  }
149
159
  return false;
150
160
  }
151
161
 
162
+ /*
163
+ * A data-driven loop whose assertions each carry a per-case template message referencing a
164
+ * loop-bound name keeps a failing row identifiable - the failure mode this rule exists to catch -
165
+ * so it opts out even when the case table is built dynamically. Multi-line assertion calls fall
166
+ * outside the statement split and stay reported; the rule's medium confidence reflects that.
167
+ */
168
+ function isLabeledCaseLoop(segment: string): boolean {
169
+ const parts = loopSegmentParts(segment);
170
+ if (!parts) {
171
+ return false;
172
+ }
173
+ const boundNames = loopBoundNames(parts.header);
174
+ if (boundNames.length === 0) {
175
+ return false;
176
+ }
177
+ const assertionStatements = parts.body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && hasAssertion(statement));
178
+ if (assertionStatements.length === 0) {
179
+ return false;
180
+ }
181
+ return assertionStatements.every((statement) => hasLoopCaseLabel(statement, boundNames));
182
+ }
183
+
184
+ // Identifier names bound by a for..of header - `for (const { name, input } of cases)` binds both.
185
+ // While-loops bind nothing here, so they never take the labeled opt-out.
186
+ function loopBoundNames(header: string): string[] {
187
+ const binding = header.match(/\b(?:const|let|var)\s+([^)]*?)\s+of\b/)?.[1] ?? "";
188
+ return [...binding.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)].map((match) => match[0] ?? "").filter(Boolean);
189
+ }
190
+
191
+ // The per-case label: a template interpolation in the assertion statement naming a bound
192
+ // identifier. Masked source keeps `${...}` expressions intact, so this works on codeBody.
193
+ function hasLoopCaseLabel(statement: string, boundNames: string[]): boolean {
194
+ for (const interpolation of statement.matchAll(/\$\{([^}]*)\}/g)) {
195
+ const expressionText = interpolation[1] ?? "";
196
+ if (boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(expressionText))) {
197
+ return true;
198
+ }
199
+ }
200
+ return false;
201
+ }
202
+
152
203
  // A "fixture loop" is the table-test pattern: iterable is an inline fixture OR a local const-bound
153
204
  // fixture table, AND every path through the body terminates in an assertion call. Guard branches
154
205
  // without assertions are allowed, but assertion-bearing branches still opt out.
155
206
  function isFixtureLoop(source: string, start: number, segment: string): boolean {
156
- const braceIndex = segment.indexOf("{");
157
- const header = braceIndex === -1 ? segment : segment.slice(0, braceIndex);
158
- if (!hasFixtureIterable(source, start, header)) {
207
+ const parts = loopSegmentParts(segment);
208
+ if (!parts || !hasFixtureIterable(source, start, parts.header)) {
159
209
  return false;
160
210
  }
161
- if (braceIndex === -1) {
211
+ if (hasUnsafeFixtureLoopBranch(source.slice(0, start + parts.bodyBraceIndex + 1), parts.body)) {
162
212
  return false;
163
213
  }
164
- const body = segment.slice(braceIndex + 1, segment.length - 1);
165
- if (hasUnsafeFixtureLoopBranch(source.slice(0, start + braceIndex + 1), body)) {
166
- return false;
167
- }
168
- const statements = body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement));
214
+ // Bare `void identifier` lines are lint pacifiers, not work, so they cannot be the loop's
215
+ // terminal action; `void call()` still counts as a real trailing statement.
216
+ const statements = parts.body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement) && !/^void\s+[A-Za-z_$][A-Za-z0-9_$]*$/.test(statement));
169
217
  const lastStatement = statements[statements.length - 1] ?? "";
170
218
  return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
171
219
  }
172
220
 
221
+ // Splits a loop segment into header and body at the body-opening brace, walking past the header's
222
+ // balanced parentheses first so that a destructured binding such as `for (const { name } of rows)`
223
+ // does not end the header at the destructuring brace. Braceless bodies return undefined.
224
+ function loopSegmentParts(segment: string): { header: string; body: string; bodyBraceIndex: number } | undefined {
225
+ const parenIndex = segment.indexOf("(");
226
+ if (parenIndex === -1) {
227
+ return undefined;
228
+ }
229
+ const headerCloseIndex = matchingHeaderCloseParen(segment, parenIndex);
230
+ if (headerCloseIndex === undefined) {
231
+ return undefined;
232
+ }
233
+ const bodyBraceIndex = segment.indexOf("{", headerCloseIndex);
234
+ if (bodyBraceIndex === -1) {
235
+ return undefined;
236
+ }
237
+ return { header: segment.slice(0, bodyBraceIndex), body: segment.slice(bodyBraceIndex + 1, segment.length - 1), bodyBraceIndex };
238
+ }
239
+
240
+ // Walks a header's parentheses to the close of the outermost group, tolerating nested calls such
241
+ // as `of Object.entries({ a: 1 })` inside the loop header.
242
+ function matchingHeaderCloseParen(segment: string, parenIndex: number): number | undefined {
243
+ let depth = 0;
244
+ for (let index = parenIndex; index < segment.length; index += 1) {
245
+ const character = segment[index];
246
+ if (character === "(") {
247
+ depth += 1;
248
+ } else if (character === ")") {
249
+ depth -= 1;
250
+ if (depth === 0) {
251
+ return index;
252
+ }
253
+ }
254
+ }
255
+ return undefined;
256
+ }
257
+
173
258
  // Fixture sweeps may carry invariant guards such as `if (expectedIds.has(case.id))`; other branches
174
259
  // still opt out because they can hide case-specific expectations inside the loop.
175
260
  function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string): boolean {
@@ -255,14 +340,33 @@ function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: stri
255
340
  // Captures the smallest control-flow segment so assertion detection does not scan the whole test.
256
341
  function controlFlowSegment(source: string, start: number): string {
257
342
  const lineEnd = source.indexOf("\n", start);
258
- const openBrace = source.indexOf("{", start);
259
- if (openBrace === -1 || (lineEnd !== -1 && openBrace > lineEnd)) {
343
+ const openBrace = controlFlowBodyBraceIndex(source, start, lineEnd);
344
+ if (openBrace === undefined) {
260
345
  return source.slice(start, lineEnd === -1 ? source.length : lineEnd);
261
346
  }
262
347
  const closeBrace = matchingCloseBrace(source, openBrace);
263
348
  return source.slice(start, closeBrace === undefined ? openBrace + 1 : closeBrace + 1);
264
349
  }
265
350
 
351
+ // Finds the body-opening brace for a control-flow keyword: the first `{` at parenthesis depth zero
352
+ // on the keyword's line. Braces inside the header parens - destructured bindings such as
353
+ // `for (const { name } of rows)` - belong to the header, not the body.
354
+ function controlFlowBodyBraceIndex(source: string, start: number, lineEnd: number): number | undefined {
355
+ const limit = lineEnd === -1 ? source.length : lineEnd;
356
+ let parenDepth = 0;
357
+ for (let index = start; index < limit; index += 1) {
358
+ const character = source[index];
359
+ if (character === "(") {
360
+ parenDepth += 1;
361
+ } else if (character === ")") {
362
+ parenDepth = Math.max(0, parenDepth - 1);
363
+ } else if (character === "{" && parenDepth === 0) {
364
+ return index;
365
+ }
366
+ }
367
+ return undefined;
368
+ }
369
+
266
370
  // Lightweight brace matcher for already-isolated test block text; enough to bound loop/if bodies.
267
371
  function matchingCloseBrace(source: string, openBrace: number): number | undefined {
268
372
  let depth = 0;
@@ -312,6 +312,9 @@ function catalogueCoverageFiles(): Record<string, string> {
312
312
  return {
313
313
  "src/catalogue.ts": catalogueRuntimeCoverageSource(),
314
314
  "src/dep.ts": `export const usedThing = "used";
315
+ `,
316
+ "src/helpers.ts": `/** Handles payment requests in the catalogue coverage project. */
317
+ export class PaymentController {}
315
318
  `,
316
319
  "src/catalogue.test.ts": catalogueTestCoverageSource(),
317
320
  "src/app/feature/controller.ts": `import { sharedHelper } from "../../../shared/helper";
@@ -417,7 +420,7 @@ const active = true;
417
420
  const xx = 1;
418
421
  const ctx = { request: 1 };
419
422
  const disableCache = true;
420
- const DATABASE_URL = "/health";
423
+ const rawURL = "/health";
421
424
  const databaseUrl = "/healthz";
422
425
  const project_path = "src";
423
426
  const projectPath = "src/index.ts";
package/src/text-scans.ts CHANGED
@@ -39,4 +39,11 @@ function byteLine(source: string, index: number): number {
39
39
  return line;
40
40
  }
41
41
 
42
- export { byteLine, countMatches, firstLine };
42
+ // One-based column of byte offset `index` on its line. Lets two matches on one line report
43
+ // distinct positions so neither occurrence is lost when their line-keyed identities collide.
44
+ function byteColumn(source: string, index: number): number {
45
+ const end = Math.max(0, index);
46
+ return end - source.lastIndexOf("\n", end - 1);
47
+ }
48
+
49
+ export { byteColumn, byteLine, countMatches, firstLine };
package/src/types.ts CHANGED
@@ -72,6 +72,8 @@ export interface Config {
72
72
  secretPreviews: Set<string>;
73
73
  bannedGenericNames: Set<string>;
74
74
  acceptedBooleanNames: Set<string>;
75
+ acceptedClassFilePairs: Set<string>;
76
+ acceptedCasingPairs: Set<string>;
75
77
  booleanPrefixes: Set<string>;
76
78
  hungarianPrefixes: Set<string>;
77
79
  placeholderNames: Set<string>;
@@ -169,6 +171,19 @@ export interface SkippedPath {
169
171
  pattern: string;
170
172
  }
171
173
 
174
+ /**
175
+ * Non-fatal scan-surface note (additive in 0.4.0, owner-approved): explains a scan whose surface
176
+ * differs from what the caller likely expected - a requested input that produced no analysable
177
+ * files (`no-analysable-files`), or a file whose deep script analysis was bounded by the scan
178
+ * budget (`bounded-deep-scan`), or bytes that are not parseable text (`non-text-file`). Notes never
179
+ * affect exit codes; `diagnostics` stays the surface that drives exit 2.
180
+ */
181
+ export interface ScanSurfaceNote {
182
+ noteType: "no-analysable-files" | "bounded-deep-scan" | "non-text-file";
183
+ path: string;
184
+ message: string;
185
+ }
186
+
172
187
  /**
173
188
  * Stable gruff.analysis.v2 report schema returned by analyse and JSON report commands.
174
189
  *
@@ -183,6 +198,8 @@ export interface AnalysisReport {
183
198
  summary: { advisory: number; warning: number; error: number; total: number };
184
199
  paths: { analysedFiles: number; ignoredPaths: string[]; skipped: SkippedPath[]; missingPaths: string[] };
185
200
  diagnostics: RunDiagnostic[];
201
+ /** Additive in 0.4.0: present only when at least one scan-surface note was produced. */
202
+ notes?: ScanSurfaceNote[];
186
203
  findings: Finding[];
187
204
  suppressedCount?: number;
188
205
  score: {