@blundergoat/gruff-ts 0.2.0 → 0.3.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 (44) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +80 -12
  3. package/docs/README.md +2 -0
  4. package/docs/agent-hook.md +80 -0
  5. package/docs/ci-integration.md +16 -0
  6. package/docs/configuration.md +21 -2
  7. package/docs/output-formats.md +10 -0
  8. package/docs/philosophy.md +21 -0
  9. package/docs/releasing.md +5 -5
  10. package/docs/rules.md +24 -15
  11. package/package.json +5 -5
  12. package/scripts/bump-version.sh +1 -1
  13. package/src/analyser.ts +43 -30
  14. package/src/blocks.ts +20 -67
  15. package/src/changed-regions.ts +390 -0
  16. package/src/check-ignore.ts +49 -0
  17. package/src/class-rules.ts +80 -33
  18. package/src/cli-program.ts +105 -11
  19. package/src/comment-rules.ts +4 -0
  20. package/src/config-parse.ts +458 -0
  21. package/src/config-preservation.ts +1 -1
  22. package/src/config.ts +215 -460
  23. package/src/constants.ts +1 -1
  24. package/src/context-doc-rules.ts +2 -4
  25. package/src/dashboard.ts +7 -4
  26. package/src/discovery.ts +88 -32
  27. package/src/findings-helpers.ts +41 -5
  28. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  29. package/src/init-config.ts +3 -0
  30. package/src/naming-pushers.ts +35 -6
  31. package/src/profiles.ts +232 -0
  32. package/src/project-config-rules.ts +5 -5
  33. package/src/project-rules.ts +2 -1
  34. package/src/report-html.ts +1 -1
  35. package/src/report-renderers.ts +58 -0
  36. package/src/rule-list.ts +22 -1
  37. package/src/rules.ts +10 -10
  38. package/src/safety-rules.ts +16 -6
  39. package/src/scoring.ts +43 -5
  40. package/src/security-flow-rules.ts +533 -0
  41. package/src/sensitive-data-rules.ts +138 -2
  42. package/src/test-block-rules.ts +106 -15
  43. package/src/test-fixtures.ts +46 -8
  44. package/src/types.ts +78 -2
@@ -17,13 +17,14 @@ function analyseSensitiveData(file: SensitiveSourceFile, source: string, config:
17
17
  ["sensitive-data.aws-access-key", /AKIA[0-9A-Z]{16}/g, "AWS access key pattern detected."],
18
18
  ["sensitive-data.private-key", /BEGIN (RSA |OPENSSH |EC |DSA )?PRIVATE KEY/g, "Private key block detected."],
19
19
  ["sensitive-data.jwt-token", /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "JWT-looking token detected."],
20
- ["sensitive-data.database-url-password", /\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|amqp|amqps|mssql):\/\/[^\/\s:@]+:[^\/\s@]+@/g, "Database URL appears to include a password."],
20
+ ["sensitive-data.database-url-password", /\b(?:https?|postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|amqp|amqps|mssql):\/\/[^\/\s:@]+:[^\/\s@]+@/g, "URL appears to include embedded credentials."],
21
21
  [
22
22
  "sensitive-data.api-key-pattern",
23
23
  /\b(?:sk_live_[A-Za-z0-9_-]{12,}|sk_test_[A-Za-z0-9_-]{12,}|sk-proj-[A-Za-z0-9_-]{16,}|sk-ant-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|gh[ousr]_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{20,}|AIza[A-Za-z0-9_-]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+|https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+)\b/g,
24
24
  "API key pattern detected.",
25
25
  ],
26
26
  ["sensitive-data.pii-pattern", /\b\d{3}-\d{2}-\d{4}\b/g, "PII-like identifier pattern detected."],
27
+ ["sensitive-data.phi-pattern", /\b[1-9][ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY0-9]\d[ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY0-9]\d[ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY]\d\d\b/g, "Medicare Beneficiary Identifier (PHI) pattern detected."],
27
28
  ];
28
29
 
29
30
  for (const [ruleId, pattern, message] of patterns) {
@@ -36,6 +37,59 @@ function analyseSensitiveData(file: SensitiveSourceFile, source: string, config:
36
37
  analyseHardcodedEnvironmentValues(file, source, config, findings);
37
38
  analyseNpmAuthTokens(file, source, config, findings);
38
39
  analyseHighEntropyStrings(file, source, config, findings);
40
+ analysePhiLabelledIdentifiers(file, source, config, findings);
41
+ analysePaymentCardNumbers(file, source, config, findings);
42
+ analyseGcpServiceAccountKeys(file, source, config, findings);
43
+ }
44
+
45
+ // PHI beyond the MBI shape: medical-record-number assignments. Context-gated on an `MRN` / `medical
46
+ // record` label so bare integers stay clean; stable contract is one redacted finding per label.
47
+ function analysePhiLabelledIdentifiers(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
48
+ const lines = source.split(/\r?\n/);
49
+ for (const [index, line] of lines.entries()) {
50
+ const match = line.match(/\b(?:MRN|medical[\s_-]?record(?:[\s_-]?number)?)\b\s*[:=#]?\s*([0-9]{6,12})\b/i);
51
+ const medicalRecordNumber = match?.[1];
52
+ if (!medicalRecordNumber) {
53
+ continue;
54
+ }
55
+ pushSensitiveFinding(config, findings, file, "sensitive-data.phi-pattern", "Medical record number (PHI) detected.", index + 1, medicalRecordNumber, "high");
56
+ }
57
+ }
58
+
59
+ // GCP service-account key files carry `"type": "service_account"` next to a private key. Flag the file
60
+ // once, anchored on the type line; stable contract keeps raw key bodies covered by private-key.
61
+ function analyseGcpServiceAccountKeys(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
62
+ const typeMatch = source.match(/"type"\s*:\s*"service_account"/);
63
+ if (!typeMatch || !/"private_key"\s*:\s*"|BEGIN (?:RSA |OPENSSH |EC |DSA )?PRIVATE KEY/.test(source)) {
64
+ return;
65
+ }
66
+ const identifier = source.match(/"private_key_id"\s*:\s*"([^"]+)"/)?.[1]
67
+ ?? source.match(/"client_email"\s*:\s*"([^"]+)"/)?.[1]
68
+ ?? "service_account";
69
+ pushSensitiveFinding(config, findings, file, "sensitive-data.gcp-service-account-key", "GCP service-account key file detected.", byteLine(source, typeMatch.index ?? 0), identifier, "high");
70
+ }
71
+
72
+ // Payment-card PII detection is structural: candidate shape, known issuer prefix, length, and Luhn
73
+ // check must all pass before a stable redacted finding is emitted.
74
+ function analysePaymentCardNumbers(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
75
+ for (const match of source.matchAll(/\b(?:\d[ -]?){12,18}\d\b/g)) {
76
+ const rawCandidate = match[0] ?? "";
77
+ const cardNumber = normalizedPaymentCardNumber(rawCandidate);
78
+ if (!isPaymentCardNumber(cardNumber)) {
79
+ continue;
80
+ }
81
+ pushSensitiveFinding(
82
+ config,
83
+ findings,
84
+ file,
85
+ "sensitive-data.pii-pattern",
86
+ "Credit card number (PII) pattern detected.",
87
+ byteLine(source, match.index ?? 0),
88
+ rawCandidate,
89
+ "high",
90
+ { piiKind: "credit-card", digits: cardNumber.length },
91
+ );
92
+ }
39
93
  }
40
94
 
41
95
  // Stable redaction contract: parses `_authToken=` config lines even when values lack an npm_ prefix.
@@ -97,7 +151,7 @@ function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: st
97
151
  // stable across runs and prevent noisy regressions in node_modules-heavy projects.
98
152
  function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
99
153
  const minLength = threshold(config, "sensitive-data.high-entropy-string", 32);
100
- for (const match of source.matchAll(/(["'`])([A-Za-z0-9_+=./-]{32,})\1/g)) {
154
+ for (const match of source.matchAll(/(["'`])([A-Za-z0-9_+=./-]{24,})\1/g)) {
101
155
  const raw = match[2] ?? "";
102
156
  if (!isHighEntropySecretCandidate(raw, minLength)) {
103
157
  continue;
@@ -240,6 +294,88 @@ function hasKnownRepoPathSegment(candidateText: string): boolean {
240
294
  return /(?:^|\/)(?:\.goat-flow|src|test|tests|fixtures?|docs|scripts|bin|workflow|package(?:-lock)?\.json)(?:\/|$)/.test(candidateText);
241
295
  }
242
296
 
297
+ // Removes separators allowed in human-entered payment-card numbers before issuer and checksum checks.
298
+ function normalizedPaymentCardNumber(candidateText: string): string {
299
+ return candidateText.replace(/[ -]/g, "");
300
+ }
301
+
302
+ // Stable contract: only card-network-shaped values with a valid Luhn checksum are PII findings.
303
+ function isPaymentCardNumber(cardNumber: string): boolean {
304
+ return /^[0-9]+$/.test(cardNumber) && cardNumber.length >= 13 && cardNumber.length <= 19 && hasKnownPaymentCardPrefix(cardNumber) && passesLuhnCheck(cardNumber);
305
+ }
306
+
307
+ // Recognises common issuer prefixes by delegating per network because each one has different
308
+ // length and IIN-range rules; keeping those branches separate makes false-positive tuning safer.
309
+ function hasKnownPaymentCardPrefix(cardNumber: string): boolean {
310
+ return isVisaPaymentCard(cardNumber)
311
+ || isMastercardPaymentCard(cardNumber)
312
+ || isAmericanExpressPaymentCard(cardNumber)
313
+ || isDiscoverPaymentCard(cardNumber)
314
+ || isDinersPaymentCard(cardNumber)
315
+ || isJcbPaymentCard(cardNumber);
316
+ }
317
+
318
+ // Visa cards start with 4 and commonly use 13, 16, or 19 digits.
319
+ function isVisaPaymentCard(cardNumber: string): boolean {
320
+ return cardNumber.startsWith("4") && isPaymentCardLength(cardNumber, [13, 16, 19]);
321
+ }
322
+
323
+ // Mastercard cards use 51-55 and 2221-2720 IIN ranges with 16 digits.
324
+ function isMastercardPaymentCard(cardNumber: string): boolean {
325
+ const firstTwoDigits = Number(cardNumber.slice(0, 2));
326
+ const firstFourDigits = Number(cardNumber.slice(0, 4));
327
+ return (isInRange(firstTwoDigits, 51, 55) || isInRange(firstFourDigits, 2221, 2720)) && isPaymentCardLength(cardNumber, [16]);
328
+ }
329
+
330
+ // American Express cards use 34/37 prefixes with 15 digits.
331
+ function isAmericanExpressPaymentCard(cardNumber: string): boolean {
332
+ return (cardNumber.startsWith("34") || cardNumber.startsWith("37")) && isPaymentCardLength(cardNumber, [15]);
333
+ }
334
+
335
+ // Discover cards use 6011, 65, or 644-649 prefixes with 16 or 19 digits.
336
+ function isDiscoverPaymentCard(cardNumber: string): boolean {
337
+ const firstThreeDigits = Number(cardNumber.slice(0, 3));
338
+ return (cardNumber.startsWith("6011") || cardNumber.startsWith("65") || isInRange(firstThreeDigits, 644, 649)) && isPaymentCardLength(cardNumber, [16, 19]);
339
+ }
340
+
341
+ // Diners Club cards use 300-305, 36, 38, or 39 prefixes with 14 digits.
342
+ function isDinersPaymentCard(cardNumber: string): boolean {
343
+ const firstThreeDigits = Number(cardNumber.slice(0, 3));
344
+ return (isInRange(firstThreeDigits, 300, 305) || cardNumber.startsWith("36") || cardNumber.startsWith("38") || cardNumber.startsWith("39")) && isPaymentCardLength(cardNumber, [14]);
345
+ }
346
+
347
+ // JCB cards use 3528-3589 prefixes with 16-19 digits.
348
+ function isJcbPaymentCard(cardNumber: string): boolean {
349
+ const firstFourDigits = Number(cardNumber.slice(0, 4));
350
+ return isInRange(firstFourDigits, 3528, 3589) && isPaymentCardLength(cardNumber, [16, 17, 18, 19]);
351
+ }
352
+
353
+ // Network-specific length guard kept separate so the prefix table reads as data, not arithmetic.
354
+ function isPaymentCardLength(cardNumber: string, allowedLengths: number[]): boolean {
355
+ return allowedLengths.includes(cardNumber.length);
356
+ }
357
+
358
+ // Inclusive numeric range helper for issuer identification number ranges.
359
+ function isInRange(candidateNumber: number, minimum: number, maximum: number): boolean {
360
+ return candidateNumber >= minimum && candidateNumber <= maximum;
361
+ }
362
+
363
+ // Standard Luhn checksum over normalized digits; invalid checksum keeps long numeric identifiers quiet.
364
+ function passesLuhnCheck(cardNumber: string): boolean {
365
+ const digits = [...cardNumber].reverse().map((digit) => Number(digit));
366
+ const sum = digits.reduce((total, digit, index) => total + luhnDigitContribution(digit, index), 0);
367
+ return sum % 10 === 0;
368
+ }
369
+
370
+ // Doubles every second digit from the right and folds two-digit products per the Luhn algorithm.
371
+ function luhnDigitContribution(digit: number, indexFromRight: number): number {
372
+ if (indexFromRight % 2 === 0) {
373
+ return digit;
374
+ }
375
+ const doubled = digit * 2;
376
+ return doubled > 9 ? doubled - 9 : doubled;
377
+ }
378
+
243
379
  // All-hex strings - typical for SHA digests, content hashes, and tooling identifiers.
244
380
  function isHexDigest(candidateText: string): boolean {
245
381
  return /^[0-9a-f]+$/i.test(candidateText);
@@ -21,6 +21,7 @@ interface TestBlockCheck {
21
21
  interface MagicNumberAssertionPattern {
22
22
  pattern: RegExp;
23
23
  expressionIndex: number;
24
+ matcherIndex?: number;
24
25
  valueIndex: number;
25
26
  }
26
27
 
@@ -64,6 +65,9 @@ function assertionQualityChecks(block: FunctionBlock, body: string): TestBlockCh
64
65
  * `test-quality.magic-number-assertion` with stable literal metadata for downstream review tools.
65
66
  */
66
67
  function pushMagicNumberAssertionFindings(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
68
+ if (isConstantContractTestName(block.name)) {
69
+ return;
70
+ }
67
71
  for (const assertion of magicNumberAssertions(body)) {
68
72
  findings.push(
69
73
  blockFindingWithMetadata({
@@ -154,7 +158,7 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
154
158
  if (!hasAssertion(segment)) {
155
159
  continue;
156
160
  }
157
- if (isFixtureLoop(segment)) {
161
+ if (isFixtureLoop(source, start, segment)) {
158
162
  continue;
159
163
  }
160
164
  return true;
@@ -162,22 +166,20 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
162
166
  return false;
163
167
  }
164
168
 
165
- // A "fixture loop" is the table-test pattern: iterable is a literal array OR Object.entries/keys/
166
- // values of a literal, AND every path through the body terminates in an assertion call. Neither
167
- // applies to `while` loops or C-style `for (;;)`. Conservative on conditional bodies - the presence
168
- // of any `if`/`switch`/`case`/`default` inside the body opts out so a branch that doesn't assert
169
- // is not silently classified as a fixture loop.
170
- function isFixtureLoop(segment: string): boolean {
169
+ // A "fixture loop" is the table-test pattern: iterable is an inline fixture OR a local const-bound
170
+ // fixture table, AND every path through the body terminates in an assertion call. Guard branches
171
+ // without assertions are allowed, but assertion-bearing branches still opt out.
172
+ function isFixtureLoop(source: string, start: number, segment: string): boolean {
171
173
  const braceIndex = segment.indexOf("{");
172
174
  const header = braceIndex === -1 ? segment : segment.slice(0, braceIndex);
173
- if (!/\bof\s*\[/.test(header) && !/\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
175
+ if (!hasFixtureIterable(source, start, header)) {
174
176
  return false;
175
177
  }
176
178
  if (braceIndex === -1) {
177
179
  return false;
178
180
  }
179
181
  const body = segment.slice(braceIndex + 1, segment.length - 1);
180
- if (/\b(?:if|switch)\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
182
+ if (hasUnsafeFixtureLoopBranch(source.slice(0, start + braceIndex + 1), body)) {
181
183
  return false;
182
184
  }
183
185
  const statements = body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement));
@@ -185,6 +187,60 @@ function isFixtureLoop(segment: string): boolean {
185
187
  return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
186
188
  }
187
189
 
190
+ // Fixture sweeps may carry invariant guards such as `if (expectedIds.has(case.id))`; other branches
191
+ // still opt out because they can hide case-specific expectations inside the loop.
192
+ function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string): boolean {
193
+ if (/\bswitch\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
194
+ return true;
195
+ }
196
+ for (const match of body.matchAll(/\bif\b/g)) {
197
+ const start = match.index ?? 0;
198
+ const segment = controlFlowSegment(body, start);
199
+ const sourceBeforeCondition = `${sourceBeforeLoopBody}${body.slice(0, start)}`;
200
+ if (hasAssertion(segment) && !isInvariantAssertionConditional(sourceBeforeCondition, sourceBeforeCondition.length, segment)) {
201
+ return true;
202
+ }
203
+ }
204
+ return false;
205
+ }
206
+
207
+ // Inline fixture tables cover `for (... of [...])` and `Object.entries({ ... })`. Const-bound
208
+ // tables cover the common contract-test shape where the named case table is declared immediately
209
+ // before the sweep for readability.
210
+ function hasFixtureIterable(source: string, start: number, header: string): boolean {
211
+ if (/\bof\s*\[/.test(header) || /\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
212
+ return true;
213
+ }
214
+ const iterableName = header.match(/\bof\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/)?.[1] ?? "";
215
+ return iterableName !== "" && (isFixtureConstantIterableName(iterableName) || hasConstBoundFixtureIterable(source.slice(0, start), iterableName));
216
+ }
217
+
218
+ // Accepts const-bound fixture loops only when the iterable name and initializer both look like a
219
+ // deterministic case table or discovered fixture set.
220
+ function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: string): boolean {
221
+ if (!isFixtureIterableName(iterableName)) {
222
+ return false;
223
+ }
224
+ const assignment = sourceBeforeLoop.match(new RegExp(`\\bconst\\s+${escapeRegex(iterableName)}\\s*=\\s*([\\s\\S]*?);\\s*$`));
225
+ const initializer = assignment?.[1]?.trim() ?? "";
226
+ return initializer.startsWith("[") || /^Object\.(?:entries|keys|values)\s*\(/.test(initializer) || isFixtureDiscoveryCall(initializer);
227
+ }
228
+
229
+ // Limits const-bound loop suppression to table/sweep vocabulary rather than arbitrary arrays.
230
+ function isFixtureIterableName(name: string): boolean {
231
+ return /(?:agents|cases|checks|entries|examples|fixtures|files|ids|paths|records|scenarios|scores|snapshots)$/i.test(name);
232
+ }
233
+
234
+ // UPPER_CASE fixture constants such as HARNESS_CHECKS are named case tables even when imported.
235
+ function isFixtureConstantIterableName(name: string): boolean {
236
+ return /^[A-Z0-9_]+$/.test(name) && isFixtureIterableName(name);
237
+ }
238
+
239
+ // Recognises local fixture discovery calls used by contract sweeps without accepting unknown calls.
240
+ function isFixtureDiscoveryCall(initializer: string): boolean {
241
+ return /\b(?:glob|globSync|readdir|readdirSync|discover[A-Za-z0-9_$]*|find[A-Za-z0-9_$]*|list[A-Za-z0-9_$]*)\s*\(/.test(initializer);
242
+ }
243
+
188
244
  // Integration, contract, smoke, and performance tests naturally need more environment setup than
189
245
  // focused unit tests; keep the default strict for unit tests and double it for broad-flow suites.
190
246
  function setupBloatThreshold(file: SourceFile, config: Config): number {
@@ -203,13 +259,28 @@ function controlFlowContainsAssertion(source: string, pattern: RegExp): boolean
203
259
  for (const match of source.matchAll(pattern)) {
204
260
  const start = match.index ?? 0;
205
261
  const segment = controlFlowSegment(source, start);
206
- if (hasAssertion(segment)) {
262
+ if (hasAssertion(segment) && !isInvariantAssertionConditional(source, start, segment)) {
207
263
  return true;
208
264
  }
209
265
  }
210
266
  return false;
211
267
  }
212
268
 
269
+ // Accepts guard conditionals whose assertion proves a shared invariant rather than branch policy.
270
+ function isInvariantAssertionConditional(source: string, start: number, segment: string): boolean {
271
+ const condition = segment.slice(0, Math.max(0, segment.indexOf("{"))).trim();
272
+ return isFixtureMembershipGuard(source.slice(0, start), condition);
273
+ }
274
+
275
+ // Membership guards over const-bound fixtures keep invariant sweeps readable.
276
+ function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: string): boolean {
277
+ const guardTarget = condition.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\.(?:has|includes)\s*\(/)?.[1] ?? "";
278
+ if (!guardTarget) {
279
+ return false;
280
+ }
281
+ return new RegExp(`\\bconst\\s+${escapeRegex(guardTarget)}\\s*=\\s*(?:new\\s+Set\\s*\\(|\\[)`).test(sourceBeforeCondition);
282
+ }
283
+
213
284
  // Captures the smallest control-flow segment so assertion detection does not scan the whole test.
214
285
  function controlFlowSegment(source: string, start: number): string {
215
286
  const lineEnd = source.indexOf("\n", start);
@@ -313,31 +384,51 @@ function isNoThrowOnlyTest(source: string): boolean {
313
384
  }
314
385
 
315
386
  // Pulls every numeric expected value out of `expect(...).toBe(n)` and `assert.equal(actual, n)`
316
- // shapes. `-1`, `0`, `1` are excluded because they're universally idiomatic - the intent is to
317
- // avoid noise on neutral values and surface only literals whose meaning a maintainer must look up.
387
+ // shapes. Small cardinalities and length/count matchers are excluded because the literal often is
388
+ // the test contract; larger opaque values still surface for naming or rationale.
318
389
  function magicNumberAssertions(source: string): Array<{ value: number }> {
319
390
  return MAGIC_NUMBER_ASSERTION_PATTERNS.flatMap((candidate) => magicNumberAssertionMatches(source, candidate));
320
391
  }
321
392
 
322
393
  const MAGIC_NUMBER_ASSERTION_PATTERNS: MagicNumberAssertionPattern[] = [
323
- { pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*to(?:Be|Equal|HaveLength|HaveCount)\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1, valueIndex: 2 },
394
+ { pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*(to(?:Be|Equal|HaveLength|HaveCount))\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1, matcherIndex: 2, valueIndex: 3 },
324
395
  { pattern: /\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*(-?\d+(?:\.\d+)?)(?:\s*,|\s*\))/g, expressionIndex: 1, valueIndex: 2 },
325
396
  ];
326
397
 
327
398
  // Extracts reportable numeric literals for one assertion grammar while keeping HTTP statuses quiet.
328
399
  function magicNumberAssertionMatches(source: string, candidate: MagicNumberAssertionPattern): Array<{ value: number }> {
329
- const ignored = new Set([-1, 0, 1]);
330
400
  const results: Array<{ value: number }> = [];
331
401
  for (const match of source.matchAll(candidate.pattern)) {
332
402
  const expression = match[candidate.expressionIndex] ?? "";
403
+ const matcher = candidate.matcherIndex === undefined ? "" : match[candidate.matcherIndex] ?? "";
333
404
  const expectedNumber = Number(match[candidate.valueIndex] ?? "0");
334
- if (!ignored.has(expectedNumber) && !isHttpStatusAssertion(expression, expectedNumber)) {
405
+ if (!isIgnoredMagicNumberAssertion(expression, matcher, expectedNumber)) {
335
406
  results.push({ value: expectedNumber });
336
407
  }
337
408
  }
338
409
  return results;
339
410
  }
340
411
 
412
+ // Centralises the rule's non-findings so cardinal, count, and HTTP-status exemptions stay aligned.
413
+ function isIgnoredMagicNumberAssertion(expression: string, matcher: string, expectedNumber: number): boolean {
414
+ return isSmallCardinal(expectedNumber) || isLengthOrCountMatcher(matcher) || isHttpStatusAssertion(expression, expectedNumber);
415
+ }
416
+
417
+ // Small integer cardinals usually express the expected case count directly.
418
+ function isSmallCardinal(cardinal: number): boolean {
419
+ return Number.isInteger(cardinal) && cardinal >= -1 && cardinal <= 3;
420
+ }
421
+
422
+ // Length/count matchers already name the measurement, so the numeric literal is the assertion.
423
+ function isLengthOrCountMatcher(matcher: string): boolean {
424
+ return matcher === "toHaveLength" || matcher === "toHaveCount";
425
+ }
426
+
427
+ // Contract-named tests may assert the documented number directly; the name supplies the rationale.
428
+ function isConstantContractTestName(name: string): boolean {
429
+ return /\b(?:constant|threshold|limit|budget|default|contract)\b/i.test(name);
430
+ }
431
+
341
432
  // HTTP response status codes are intentionally numeric at assertion sites; naming every 200/404
342
433
  // would add ceremony without making the test clearer.
343
434
  function isHttpStatusAssertion(expression: string, expectedNumber: number): boolean {
@@ -7,12 +7,13 @@ import { tmpdir } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
8
  import { chdir, cwd } from "node:process";
9
9
  import { analyse } from "./cli.ts";
10
- import type { AnalysisReport } from "./cli.ts";
10
+ import type { AnalysisReport, ChangedScopeMode } from "./types.ts";
11
11
 
12
12
  export const REPO_ROOT = cwd();
13
13
  export const HIGH_ENTROPY_FIXTURE_VALUE = ["Zx7pQ9vLm3N8sT2r", "Y6wK1dF4gH5jC0bR2"].join("");
14
14
  export const API_TOKEN_FIXTURE_VALUE = ["rN7pQ4sV9xY2zA5b", "C8dG9hK2mN5pQ8sR1"].join("");
15
15
  export const DATABASE_URL_FIXTURE_VALUE = ["postgres://app:superSecret", "Password@db.internal/app"].join("");
16
+ export const URL_CREDENTIAL_FIXTURE_VALUE = ["https://agent:", "clientSecret42", "@example.test/api"].join("");
16
17
  export const OPENAI_KEY_FIXTURE_VALUE = ["sk-proj-AbCdEfGhIjKl", "MnOpQrStUvWxYz1234567890"].join("");
17
18
  export const GOOGLE_API_KEY_FIXTURE_VALUE = ["AIzaSyD3moKeyValue", "1234567890AbCdEf"].join("");
18
19
  export const SLACK_WEBHOOK_FIXTURE_VALUE = ["https://hooks.slack.com/services/T00000000", "B00000000", "abcdefghijklmnopqrstuvwx"].join("/");
@@ -22,6 +23,11 @@ export const DISCORD_WEBHOOK_FIXTURE_VALUE = [
22
23
  ].join("/");
23
24
  export const NPM_AUTH_TOKEN_FIXTURE_VALUE = ["npmAuthToken", "AbCdEfGhIjKlMnOp", "QrStUvWxYz123456"].join("");
24
25
  export const SSN_FIXTURE_VALUE = ["123", "45", "6789"].join("-");
26
+ export const CREDIT_CARD_FIXTURE_VALUE = ["4111", "1111", "1111", "1111"].join(" ");
27
+ export const INVALID_CREDIT_CARD_FIXTURE_VALUE = ["4111", "1111", "1111", "1112"].join(" ");
28
+ export const MBI_FIXTURE_VALUE = ["1EG4", "TE5", "MK73"].join("");
29
+ export const MRN_FIXTURE_VALUE = "00489912";
30
+ export const GCP_PRIVATE_KEY_ID_FIXTURE_VALUE = ["a1b2c3d4e5f6a7b8c9d0", "e1f2a3b4c5d6e7f8a9b0"].join("");
25
31
  export const AWS_ACCESS_KEY_FIXTURE_VALUE = ["AKIAABCDEFGH", "IJKLMNOP"].join("");
26
32
  export const PRIVATE_KEY_HEADER_FIXTURE_VALUE = ["-----BEGIN ", "PRIVATE KEY-----"].join("");
27
33
  export const POSTGRES_URL_FIXTURE_VALUE = ["postgres://user:sec", "ret@example.test/db"].join("");
@@ -35,10 +41,16 @@ export const COMMENTED_OUT_LEGACY_CALL = ["const", " disabledLegacy = runLegacyP
35
41
  export interface AnalyseProjectOptions {
36
42
  config?: Record<string, unknown>;
37
43
  configPath?: string;
44
+ profile?: string;
38
45
  executableFiles?: string[];
39
46
  shouldIncludeIgnored?: boolean;
40
47
  shouldSkipConfig?: boolean;
41
48
  paths?: string[];
49
+ diff?: string;
50
+ diffPatch?: string;
51
+ since?: string;
52
+ changedRanges?: string;
53
+ changedScope?: ChangedScopeMode;
42
54
  }
43
55
 
44
56
  // Adds a fixture filename override for single-source test scans.
@@ -58,7 +70,8 @@ export function analyseFixture(source: string, options: AnalyseFixtureOptions =
58
70
  );
59
71
  }
60
72
 
61
- // Creates a temporary project, runs analysis inside it, and removes the fixture tree. Performs the required filesystem or process side effect.
73
+ // Creates a temporary project, runs analysis inside it, and removes the fixture tree. It mutates the
74
+ // filesystem and process cwd; explicit options preserve absent-vs-undefined typing.
62
75
  export function analyseProject(files: Record<string, string>, options: AnalyseProjectOptions = {}) {
63
76
  const dir = mkdtempSync(join(tmpdir(), "gruff-ts-"));
64
77
  const previous = cwd();
@@ -90,21 +103,36 @@ export function setupAnalyseProjectDirectory(dir: string, files: Record<string,
90
103
 
91
104
  /**
92
105
  * Runs analyse after the fixture helper has switched into the temp project root, returning a stable report.
106
+ * The explicit option assembly preserves exact optional property types because absent and undefined differ.
93
107
  * @param options Normalized fixture scan options.
94
108
  * @returns The analysis report produced from the current temporary project.
95
109
  */
96
110
  export function analyseProjectInCurrentDirectory(options: AnalyseProjectOptions): AnalysisReport {
97
111
  return analyse({
98
112
  paths: options.paths ?? ["."],
99
- ...(typeof options.configPath === "string" ? { config: options.configPath } : {}),
100
113
  shouldSkipConfig: options.shouldSkipConfig ?? !(options.config || options.configPath),
101
114
  format: "json",
102
115
  failOn: "none",
103
116
  shouldIncludeIgnored: options.shouldIncludeIgnored ?? false,
117
+ changedScope: options.changedScope ?? "symbol",
104
118
  shouldSkipBaseline: true,
119
+ ...optionalFixtureScanFields(options),
105
120
  });
106
121
  }
107
122
 
123
+ // Assembles the optional scan fields with conditional spreads so each stays omitted (not undefined)
124
+ // under exactOptionalPropertyTypes, keeping analyseProjectInCurrentDirectory a flat literal.
125
+ function optionalFixtureScanFields(options: AnalyseProjectOptions): Partial<Pick<Parameters<typeof analyse>[0], "config" | "profile" | "diff" | "diffPatch" | "since" | "changedRanges">> {
126
+ return {
127
+ ...(typeof options.configPath === "string" ? { config: options.configPath } : {}),
128
+ ...(typeof options.profile === "string" ? { profile: options.profile } : {}),
129
+ ...(typeof options.diff === "string" ? { diff: options.diff } : {}),
130
+ ...(typeof options.diffPatch === "string" ? { diffPatch: options.diffPatch } : {}),
131
+ ...(typeof options.since === "string" ? { since: options.since } : {}),
132
+ ...(typeof options.changedRanges === "string" ? { changedRanges: options.changedRanges } : {}),
133
+ };
134
+ }
135
+
108
136
  /*
109
137
  * Serializes a test YAML config object from the root indentation level. Every fixture YAML is
110
138
  * stamped with the required `schemaVersion: gruff-ts.config.v0.1` field at the top (per ADR-004)
@@ -321,8 +349,15 @@ DATABASE_URL=${POSTGRES_URL_FIXTURE_VALUE}
321
349
  JWT_TOKEN=${JWT_FIXTURE_VALUE}
322
350
  OPENAI_API_KEY=${OPENAI_KEY_FIXTURE_VALUE}
323
351
  PATIENT_SSN=${SSN_FIXTURE_VALUE}
352
+ PATIENT_MBI=${MBI_FIXTURE_VALUE}
324
353
  API_TOKEN=${API_TOKEN_FIXTURE_VALUE}
325
354
  `,
355
+ "credentials/service-account.json": JSON.stringify({
356
+ type: "service_account",
357
+ private_key_id: GCP_PRIVATE_KEY_ID_FIXTURE_VALUE,
358
+ private_key: `${PRIVATE_KEY_HEADER_FIXTURE_VALUE}\nMIIfake\n-----END PRIVATE KEY-----\n`,
359
+ client_email: "svc@project.iam.gserviceaccount.com",
360
+ }),
326
361
  "package.json": JSON.stringify({
327
362
  scripts: {
328
363
  postinstall: "node scripts/setup.js",
@@ -339,7 +374,6 @@ API_TOKEN=${API_TOKEN_FIXTURE_VALUE}
339
374
  }),
340
375
  ".github/workflows/risky.yml": githubActionsCoverageWorkflowSource(),
341
376
  "bin/bad.js": "#!/usr/bin/env node\nconsole.log('ok');\n",
342
- "styles/component.css": ".one { color: red; }\n.two { color: blue; }\n.three { color: green; }\n.four { color: yellow; }\n",
343
377
  "tsconfig.json": JSON.stringify({
344
378
  compilerOptions: {
345
379
  strict: false,
@@ -383,8 +417,10 @@ const active = true;
383
417
  const xx = 1;
384
418
  const ctx = { request: 1 };
385
419
  const disableCache = true;
386
- const URL_PATH = "/health";
387
- const urlPath = "/healthz";
420
+ const DATABASE_URL = "/health";
421
+ const databaseUrl = "/healthz";
422
+ const project_path = "src";
423
+ const projectPath = "src/index.ts";
388
424
  const unsafeAny: any = {};
389
425
  const embeddedToken = "${HIGH_ENTROPY_FIXTURE_VALUE}";
390
426
  const maxRetryLimit = 12;
@@ -434,6 +470,10 @@ export function process(flag: boolean, userInput: string, userId: string, userId
434
470
  fetch(req.body.url);
435
471
  res.redirect(req.query.next);
436
472
  new RegExp(process.argv[2]);
473
+ const serializedPayload = req.body.serialized;
474
+ nodeSerialize.unserialize(serializedPayload);
475
+ const xmlPayload = req.body.xml;
476
+ libxmljs.parseXml(xmlPayload, { noent: true });
437
477
  Math.random();
438
478
  document.write(userInput);
439
479
  element.innerHTML = userInput;
@@ -614,12 +654,10 @@ function catalogueCoverageOptions(): AnalyseProjectOptions {
614
654
  rules: {
615
655
  "complexity.cognitive": { threshold: 3, severity: "warning" },
616
656
  "complexity.cyclomatic": { threshold: 2, severity: "warning" },
617
- "complexity.npath": { threshold: 2, severity: "warning" },
618
657
  "design.large-module-concentration": { threshold: 35, severity: "advisory", options: { minFiles: 4, minLines: 8 } },
619
658
  "size.file-length": { threshold: 8, severity: "warning" },
620
659
  "size.function-length": { threshold: 8, severity: "warning" },
621
660
  "size.parameter-count": { threshold: 3, severity: "warning" },
622
- "size.stylesheet-length": { threshold: 3, severity: "warning" },
623
661
  "test-quality.setup-bloat": { threshold: 2, severity: "advisory" },
624
662
  },
625
663
  },
package/src/types.ts CHANGED
@@ -24,15 +24,28 @@ export type OutputFormat = "text" | "json" | "html" | "markdown" | "github" | "h
24
24
  /** Minimum severity that causes a non-zero CLI exit. */
25
25
  export type FailThreshold = "none" | "advisory" | "warning" | "error";
26
26
 
27
+ /** Changed-region filter precision for diff-aware analysis. */
28
+ export type ChangedScopeMode = "symbol" | "hunk";
29
+
27
30
  /** Public options contract consumed by the analyzer core and CLI. */
28
31
  export interface AnalysisOptions {
29
32
  paths: string[];
30
33
  config?: string;
34
+ /**
35
+ * Named built-in profile (`gruff.minimal` / `gruff.recommended` / `gruff.strict`) or a path to a
36
+ * profile file, from the `--profile` CLI flag. Wins over a config-file `profile:` block. Absent
37
+ * means "fall back to the config-file profile, else the default `recommended` (a no-op delta)".
38
+ */
39
+ profile?: string;
31
40
  shouldSkipConfig: boolean;
32
41
  format: OutputFormat;
33
42
  failOn: FailThreshold;
34
43
  shouldIncludeIgnored: boolean;
35
44
  diff?: string;
45
+ since?: string;
46
+ changedRanges?: string;
47
+ changedScope: ChangedScopeMode;
48
+ diffPatch?: string;
36
49
  historyFile?: string;
37
50
  baseline?: string;
38
51
  generateBaseline?: string;
@@ -58,6 +71,7 @@ export interface Config {
58
71
  acceptedAbbreviations: Set<string>;
59
72
  secretPreviews: Set<string>;
60
73
  bannedGenericNames: Set<string>;
74
+ acceptedBooleanNames: Set<string>;
61
75
  booleanPrefixes: Set<string>;
62
76
  hungarianPrefixes: Set<string>;
63
77
  placeholderNames: Set<string>;
@@ -72,6 +86,46 @@ export interface Config {
72
86
  rules: Map<string, { enabled?: boolean; threshold?: number; severity?: Severity; options: Map<string, number> }>;
73
87
  }
74
88
 
89
+ /**
90
+ * One rule's settings inside a profile. Mirrors the per-rule knobs of the config `rules:` block
91
+ * (`enabled` defaults to true when omitted). `options` is optional here - built-in presets never set
92
+ * options - whereas the loaded `Config.rules` value always carries an (often empty) options map.
93
+ */
94
+ export interface ProfileRuleSetting {
95
+ enabled?: boolean;
96
+ threshold?: number;
97
+ severity?: Severity;
98
+ options?: Map<string, number>;
99
+ }
100
+
101
+ /**
102
+ * What a user writes for `profile:` (or passes to `--profile`): a built-in name / file path string,
103
+ * or an inline object that extends a base profile and layers per-rule and path overrides on top.
104
+ */
105
+ export type ProfileSpec = string | InlineProfileSpec;
106
+
107
+ /**
108
+ * The inline `profile:` object form. `extends` names the base (a built-in name or a relative file
109
+ * path; defaults to `gruff.recommended` when omitted); `rules` and `ignoredPaths` override the base
110
+ * with child-wins semantics - per-rule fields merge, and the `ignoredPaths` array replaces.
111
+ */
112
+ export interface InlineProfileSpec {
113
+ extends?: string;
114
+ rules?: Record<string, ProfileRuleSetting>;
115
+ ignoredPaths?: string[];
116
+ }
117
+
118
+ /**
119
+ * A fully resolved and flattened profile: the effective rule settings and ignored paths after the
120
+ * whole `extends:` chain has collapsed into one delta from the descriptor defaults. Enabled-at-default
121
+ * rules are omitted from `rules`, so `gruff.recommended` flattens to an empty map (the parity contract).
122
+ */
123
+ export interface ProfileDefinition {
124
+ name: string;
125
+ rules: Map<string, ProfileRuleSetting>;
126
+ ignoredPaths: string[];
127
+ }
128
+
75
129
  /** Stable analysis finding emitted by a rule. */
76
130
  export interface Finding {
77
131
  ruleId: string;
@@ -99,15 +153,37 @@ export interface RunDiagnostic {
99
153
  line?: number;
100
154
  }
101
155
 
102
- /** Stable gruff.analysis.v2 report schema returned by analyse and JSON report commands. */
156
+ /**
157
+ * Source that excluded a path from analysis. `config` (`paths.ignore`) is authoritative in every
158
+ * invocation mode - explicit file operands and diff/changed-region runs included - and is never
159
+ * overridden by `--include-ignored`. `gitignore` and `default` are discovery-walk ignores: they are
160
+ * suppressed by `--include-ignored` and bypassed for an explicitly supplied file operand (ADR-003).
161
+ */
162
+ export type IgnoreSource = "config" | "gitignore" | "default";
163
+
164
+ /** One path excluded from analysis, with the ignore source and the exact pattern that matched. */
165
+ export interface SkippedPath {
166
+ path: string;
167
+ source: IgnoreSource;
168
+ pattern: string;
169
+ }
170
+
171
+ /**
172
+ * Stable gruff.analysis.v2 report schema returned by analyse and JSON report commands.
173
+ *
174
+ * `paths.skipped` (added in 0.3.0, ADR-007) is an additive field: each entry carries the excluded
175
+ * `path`, the ignore `source`, and the matching `pattern`. `paths.ignoredPaths` is retained as the
176
+ * back-compatible `string[]` of the same paths, so existing v2 consumers keep working without change.
177
+ */
103
178
  export interface AnalysisReport {
104
179
  schemaVersion: "gruff.analysis.v2";
105
180
  tool: { name: "gruff-ts"; version: string };
106
181
  run: { projectRoot: string; format: OutputFormat; failOn: FailThreshold; generatedAt: string };
107
182
  summary: { advisory: number; warning: number; error: number; total: number };
108
- paths: { analysedFiles: number; ignoredPaths: string[]; missingPaths: string[] };
183
+ paths: { analysedFiles: number; ignoredPaths: string[]; skipped: SkippedPath[]; missingPaths: string[] };
109
184
  diagnostics: RunDiagnostic[];
110
185
  findings: Finding[];
186
+ suppressedCount?: number;
111
187
  score: {
112
188
  composite: number;
113
189
  grade: string;