@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
package/src/discovery.ts CHANGED
@@ -3,8 +3,8 @@ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { basename, dirname, extname, isAbsolute, join, relative } from "node:path";
4
4
  import type { AnalysisOptions, Config, IgnoreSource, ScanSurfaceNote, SkippedPath } from "./types.ts";
5
5
 
6
- // `absolutePath` is what `node:fs` operates on; `displayPath` is the project-relative POSIX form
7
- // embedded in findings and baselines. They must stay aligned - diverging them breaks fingerprint stability.
6
+ // `absolutePath` is what `node:fs` operates on; `displayPath` is project-relative inside the run
7
+ // root and absolute outside it. They must stay aligned - diverging them breaks fingerprint stability.
8
8
  export interface SourceFile {
9
9
  absolutePath: string;
10
10
  displayPath: string;
@@ -107,6 +107,8 @@ function discoverSourceInput(projectRoot: string, input: string, options: Analys
107
107
  walk(projectRoot, absolute, options, config, discovery.skipped, discovery.files, gitIgnoreRules);
108
108
  }
109
109
 
110
+ // Depth-first directory walk that applies ignore rules before recursing, because descending into
111
+ // an excluded subtree would waste reads; skips record source and pattern to avoid silent exclusions.
110
112
  function walk(
111
113
  projectRoot: string,
112
114
  directory: string,
@@ -134,26 +136,28 @@ function walk(
134
136
  }
135
137
  }
136
138
 
137
- // Single source of truth for which extensions count as scannable. Adding a new file kind here will
138
- // expand the rule set's reach across an entire project - coordinate with rule descriptors before changing.
139
+ /** Extensions parsed as code. Widening this reaches every rule that inspects script syntax. */
140
+ export const SCRIPT_FILE_EXTENSIONS: readonly string[] = ["ts", "tsx", "js", "jsx", "mjs", "cjs"];
141
+
142
+ /** Extensions read as config or text assets, which only the text-oriented rules inspect. */
143
+ export const TEXT_FILE_EXTENSIONS: readonly string[] = ["conf", "config", "env", "ini", "json", "toml", "xml", "yaml", "yml"];
144
+
145
+ /** Extensionless credential files that stay scannable without admitting every dotfile. */
146
+ export const EXACT_SECRET_TEXT_FILES: readonly string[] = [".npmrc", ".pypirc", ".envrc", ".netrc"];
147
+
148
+ // Single source of truth for which extensions count as scannable. Adding a new file kind to the
149
+ // lists above will expand the rule set's reach across an entire project - the scan surface is also
150
+ // stated in prose across seven documents, so `release-truth.test.ts` pins these lists literally.
139
151
  function pushSourceFile(projectRoot: string, absolutePath: string, files: SourceFile[]): void {
140
152
  const extension = extname(absolutePath).slice(1).toLowerCase();
141
153
  const name = basename(absolutePath);
142
- const isScript = ["ts", "tsx", "js", "jsx", "mjs", "cjs"].includes(extension);
143
- const isText =
144
- ["conf", "config", "env", "ini", "json", "toml", "xml", "yaml", "yml"].includes(extension) ||
145
- name.startsWith(".env") ||
146
- isExactSecretTextFile(name);
154
+ const isScript = SCRIPT_FILE_EXTENSIONS.includes(extension);
155
+ const isText = TEXT_FILE_EXTENSIONS.includes(extension) || name.startsWith(".env") || EXACT_SECRET_TEXT_FILES.includes(name);
147
156
  if (isScript || isText) {
148
157
  files.push({ absolutePath, displayPath: displayPath(projectRoot, absolutePath), isScript });
149
158
  }
150
159
  }
151
160
 
152
- // Exact extensionless secret files stay scannable without opening the door to every dotfile.
153
- function isExactSecretTextFile(name: string): boolean {
154
- return [".npmrc", ".pypirc", ".envrc", ".netrc"].includes(name);
155
- }
156
-
157
161
  // The default-ignore list is part of the documented schema contract: callers can override with
158
162
  // `--include-ignored`, but the list itself must not silently change between releases without notice.
159
163
  function isDefaultIgnoredDir(path: string): boolean {
@@ -575,11 +579,27 @@ export function absolutize(projectRoot: string, path: string): string {
575
579
  return isAbsolute(path) ? path : join(projectRoot, path);
576
580
  }
577
581
 
578
- // Project-relative form with forward slashes - the report contract uses POSIX-style display paths
579
- // on every platform. "" collapses to "." so the root has a stable label in findings.
580
- export function displayPath(projectRoot: string, path: string): string {
581
- const relativePath = relative(projectRoot, path).replaceAll("\\", "/");
582
- return relativePath === "" ? "." : relativePath;
582
+ /**
583
+ * Formats a scanned path for findings, diagnostics, and baselines.
584
+ * Paths inside the run root stay relative; outside paths are absolute so editor and CI links remain usable.
585
+ *
586
+ * @param projectRoot - working directory that anchors relative report paths
587
+ * @param inputPath - scanned path; an empty path addresses the run root itself
588
+ * @returns POSIX report path; `.` means the input is the run root
589
+ */
590
+ export function displayPath(projectRoot: string, inputPath: string): string {
591
+ // Relative CLI inputs are resolved from the run root before report formatting.
592
+ const absoluteInputPath = isAbsolute(inputPath) ? inputPath : join(projectRoot, inputPath);
593
+ const projectRelativePath = relative(projectRoot, absoluteInputPath).replaceAll("\\", "/");
594
+ // The run root itself needs a non-empty label in reports.
595
+ if (projectRelativePath === "") {
596
+ return ".";
597
+ }
598
+ // A relative escape cannot serve as an editor or CI link from the run root.
599
+ if (projectRelativePath === ".." || projectRelativePath.startsWith("../") || isAbsolute(projectRelativePath)) {
600
+ return absoluteInputPath.replaceAll("\\", "/");
601
+ }
602
+ return projectRelativePath;
583
603
  }
584
604
 
585
605
  // Escapes the standard regex metacharacters so untrusted patterns can be embedded literally.
package/src/doc-rules.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  // JSDoc and exported-declaration documentation rules. Covers `docs.missing-public-doc`,
2
2
  // `docs.missing-file-overview`, `docs.missing-interface-doc`, and the docblock rule pack
3
3
  // (stale/missing @param, missing @returns, useless docblock). Stable, deterministic emission order.
4
- import { parameterNames } from "./blocks.ts";
5
4
  import { commentTextAtLine, hasLeadingCommentBeforeLine } from "./comment-scanner.ts";
6
5
  import { type SourceFile } from "./discovery.ts";
7
6
  import { makeFinding } from "./findings.ts";
8
7
  import { normalizedIdentifier, splitIdentifierWords } from "./findings-helpers.ts";
8
+ import { documentedExportFunctions, type ParsedScript } from "./parsed-script.ts";
9
9
  import { byteLine } from "./text-scans.ts";
10
10
  import type { Finding } from "./types.ts";
11
11
 
@@ -134,11 +134,12 @@ export function interfaceDeclarations(source: string, codeSource: string): Expor
134
134
  }
135
135
 
136
136
  /*
137
- * Docblock rule pack. Walks every `/** … *\/ export function …` pair and fires four sub-rules per
138
- * block in a stable, deterministic emission order (stale-param → missing-param → missing-return → useless-docblock).
137
+ * Docblock rule pack. Walks every documented exported function from the shared syntax tree and
138
+ * fires four sub-rules per block in a stable, deterministic emission order
139
+ * (stale-param → missing-param → missing-return → useless-docblock).
139
140
  */
140
- export function analyseDocRules(file: SourceFile, source: string, codeSource: string, findings: Finding[]): void {
141
- for (const documentedExport of documentedExportBlocks(source, codeSource)) {
141
+ export function analyseDocRules(file: SourceFile, findings: Finding[], parsed: ParsedScript): void {
142
+ for (const documentedExport of documentedExportBlocks(parsed)) {
142
143
  pushStaleParamFindings(file, documentedExport, findings);
143
144
  pushMissingParamFindings(file, documentedExport, findings);
144
145
  pushMissingReturnFinding(file, documentedExport, findings);
@@ -146,54 +147,22 @@ export function analyseDocRules(file: SourceFile, source: string, codeSource: st
146
147
  }
147
148
  }
148
149
 
149
- // Walks every `/** … */ export function …` pair in the source. Skips matches whose `export`
150
- // keyword is inside a string/regex by confirming it shows up in the masked code as well.
151
- function documentedExportBlocks(source: string, codeSource: string): DocumentedExportBlock[] {
152
- const blocks: DocumentedExportBlock[] = [];
153
- const documentedExport = /\/\*\*((?:(?!\*\/)[\s\S])*?)\*\/\s*export\s+function\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(([^)]*)\)\s*(?::\s*([^\x7b\n]+))?/g;
154
- for (const match of source.matchAll(documentedExport)) {
155
- const block = documentedExportBlock(source, codeSource, match);
156
- if (block) {
157
- blocks.push(block);
158
- }
159
- }
160
- return blocks;
161
- }
162
-
163
- // Promotes a regex match into the structured block consumed by docblock rules. Returns undefined
164
- // when the matched `export` keyword is actually inside a string literal in the masked source.
165
- function documentedExportBlock(source: string, codeSource: string, match: RegExpMatchArray): DocumentedExportBlock | undefined {
166
- const matchStart = regexMatchStart(match);
167
- const exportIndex = source.indexOf("export", matchStart);
168
- if (!isDocumentedExportInCode(codeSource, exportIndex)) {
169
- return undefined;
170
- }
171
- const doc = regexGroup(match, 1);
172
- return {
173
- doc,
174
- name: regexGroup(match, 2),
175
- params: parameterNames(regexGroup(match, 3)).map((parameter) => parameter.name),
176
- paramTags: docParamTags(doc),
177
- line: byteLine(source, matchStart),
178
- returnType: regexGroup(match, 4).trim(),
179
- };
180
- }
181
-
182
- // `index ?? 0` adapter for the standard regex API - match.index is technically optional under
183
- // strict TypeScript even though every real match has it.
184
- function regexMatchStart(match: RegExpMatchArray): number {
185
- return match.index ?? 0;
186
- }
187
-
188
- // `match[index] ?? ""` adapter - keeps callers from sprinkling default-empty handling.
189
- function regexGroup(match: RegExpMatchArray, index: number): string {
190
- return match[index] ?? "";
191
- }
192
-
193
- // Confirms the captured `export` keyword is in real code, not inside a masked comment or string.
194
- // The mask preserves the first letter of code tokens, so checking for `e` is sufficient.
195
- function isDocumentedExportInCode(codeSource: string, exportIndex: number): boolean {
196
- return exportIndex >= 0 && codeSource[exportIndex] === "e";
150
+ /*
151
+ * Detection anchors on the syntax tree: parameter names are real AST parameters, so parenthesised
152
+ * types such as `(typeof X)[number]` cannot truncate the signature, prose containing `export`
153
+ * inside the docblock cannot suppress a block, and `export async function` plus generic and
154
+ * multi-line signatures are covered. The former regex fallback for parse-less callers is gone -
155
+ * every caller supplies the shared parse.
156
+ */
157
+ function documentedExportBlocks(parsed: ParsedScript): DocumentedExportBlock[] {
158
+ return documentedExportFunctions(parsed).map((documented) => ({
159
+ doc: documented.docText,
160
+ name: documented.name,
161
+ params: documented.parameterNames,
162
+ paramTags: docParamTags(documented.docText),
163
+ line: documented.line,
164
+ returnType: documented.returnTypeText,
165
+ }));
197
166
  }
198
167
 
199
168
  // Reports stale `@param` tags before missing ones because a rename should produce a stable pair:
@@ -3,9 +3,135 @@
3
3
  // on it without forming a cycle.
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { basename } from "node:path";
6
+ import { ruleSeverity } from "./config.ts";
6
7
  import type { SourceFile } from "./discovery.ts";
7
8
  import { makeFinding } from "./findings.ts";
8
- import type { Finding, Pillar, Severity } from "./types.ts";
9
+ import type { Config, Finding, Pillar, Severity } from "./types.ts";
10
+
11
+ // Splits only at top-level commas, then strips parameter-property modifiers and `...rest`.
12
+ // Destructured parameters remain intentionally invisible to per-parameter rules.
13
+ export function parameterNames(params: string): Array<{ name: string; raw: string }> {
14
+ return splitTopLevelParameters(params)
15
+ .map((parameter) => parameter.trim())
16
+ .filter(Boolean)
17
+ .map((raw) => {
18
+ const stripped = raw.replace(/^(?:(?:public|private|protected|readonly|override)\s+)*/, "").replace(/^\.\.\./, "");
19
+ const name = stripped.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\s*(?=[?:=]|$)/)?.[1] ?? "";
20
+ return { name, raw: stripped };
21
+ })
22
+ .filter((parameter) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(parameter.name));
23
+ }
24
+
25
+ // Nesting and quote context for the parameter splitter. Kept as one mutable record so the
26
+ // per-character helpers stay small enough to read at a glance.
27
+ interface ParameterSplitState {
28
+ parenthesisDepth: number;
29
+ bracketDepth: number;
30
+ braceDepth: number;
31
+ angleDepth: number;
32
+ quote: string;
33
+ isEscaped: boolean;
34
+ }
35
+
36
+ // Parameter defaults and type expressions can contain their own commas. A small delimiter scanner
37
+ // keeps those nested commas attached, because adding another TypeScript parse to this hot path
38
+ // would cost more than the character walk saves.
39
+ function splitTopLevelParameters(params: string): string[] {
40
+ const parameters: string[] = [];
41
+ const state: ParameterSplitState = { parenthesisDepth: 0, bracketDepth: 0, braceDepth: 0, angleDepth: 0, quote: "", isEscaped: false };
42
+ let start = 0;
43
+ for (let index = 0; index < params.length; index += 1) {
44
+ const character = params[index] ?? "";
45
+ if (advanceParameterQuoteState(state, character)) {
46
+ continue;
47
+ }
48
+ if (character === "," && isTopLevelParameterPosition(state)) {
49
+ parameters.push(params.slice(start, index));
50
+ start = index + 1;
51
+ continue;
52
+ }
53
+ advanceParameterDepths(state, params, index, start);
54
+ }
55
+ parameters.push(params.slice(start));
56
+ return parameters;
57
+ }
58
+
59
+ // Consumes quote-context characters: inside a string nothing is structural, and a quote character
60
+ // opens string context. Returns false for ordinary characters so the caller keeps scanning.
61
+ function advanceParameterQuoteState(state: ParameterSplitState, character: string): boolean {
62
+ if (state.quote !== "") {
63
+ if (state.isEscaped) {
64
+ state.isEscaped = false;
65
+ } else if (character === "\\") {
66
+ state.isEscaped = true;
67
+ } else if (character === state.quote) {
68
+ state.quote = "";
69
+ }
70
+ return true;
71
+ }
72
+ if (character === '"' || character === "'" || character === "`") {
73
+ state.quote = character;
74
+ return true;
75
+ }
76
+ return false;
77
+ }
78
+
79
+ // Tracks nesting for parentheses, brackets, braces, and guarded type-argument angles so commas
80
+ // inside them stay attached to their parameter.
81
+ function advanceParameterDepths(state: ParameterSplitState, params: string, index: number, start: number): void {
82
+ const character = params[index] ?? "";
83
+ if (character === "(") state.parenthesisDepth += 1;
84
+ else if (character === ")") state.parenthesisDepth = Math.max(0, state.parenthesisDepth - 1);
85
+ else if (character === "[") state.bracketDepth += 1;
86
+ else if (character === "]") state.bracketDepth = Math.max(0, state.bracketDepth - 1);
87
+ else if (character === "{") state.braceDepth += 1;
88
+ else if (character === "}") state.braceDepth = Math.max(0, state.braceDepth - 1);
89
+ else if (character === "<" && opensTypeArgumentList(params, index, start)) state.angleDepth += 1;
90
+ else if (character === ">" && state.angleDepth > 0 && params[index - 1] !== "=") state.angleDepth -= 1;
91
+ }
92
+
93
+ // A comma splits parameters only outside every nesting kind.
94
+ function isTopLevelParameterPosition(state: ParameterSplitState): boolean {
95
+ return state.parenthesisDepth === 0 && state.bracketDepth === 0 && state.braceDepth === 0 && state.angleDepth === 0;
96
+ }
97
+
98
+ // Treat `<...>` as type arguments in annotations, or in generic call/arrow defaults whose closing
99
+ // token is followed by `(`. Requiring that call boundary keeps comparison chains from swallowing
100
+ // a later parameter while preserving commas inside `factory<T, U>(...)` and `<T, U>(...) => ...`.
101
+ function opensTypeArgumentList(params: string, index: number, parameterStart: number): boolean {
102
+ const prefix = params.slice(parameterStart, index);
103
+ const previousCharacter = params[index - 1] ?? "";
104
+ const isTypeContext = prefix.includes(":") && !prefix.includes("=");
105
+ const followsTokenWithoutWhitespace = previousCharacter !== "" && !/\s/.test(previousCharacter);
106
+ const startsGenericArrowDefault = /=\s*$/.test(prefix);
107
+ if (!isTypeContext && !followsTokenWithoutWhitespace && !startsGenericArrowDefault) {
108
+ return false;
109
+ }
110
+ let depth = 1;
111
+ for (let cursor = index + 1; cursor < params.length; cursor += 1) {
112
+ const character = params[cursor] ?? "";
113
+ if (character === "<") depth += 1;
114
+ else if (character === ">" && params[cursor - 1] !== "=") {
115
+ depth -= 1;
116
+ if (depth === 0) {
117
+ const isFollowedByCallParameters = /^\s*\(/.test(params.slice(cursor + 1));
118
+ return isTypeContext || isFollowedByCallParameters;
119
+ }
120
+ }
121
+ }
122
+ return false;
123
+ }
124
+
125
+ /*
126
+ * Central severity-override pass: config `rules.<id>.severity` wins over the scanner's created
127
+ * severity for every rule family in one place, so a user's policy applies even to scanners that
128
+ * hardcode their descriptor literal; without an override the created severity stands.
129
+ * Invariant: the fingerprint hashes (ruleId, filePath, line, symbol), so overrides never churn identity.
130
+ */
131
+ export function applyConfiguredSeverity(config: Config, finding: Finding): Finding {
132
+ const severity = ruleSeverity(config, finding.ruleId, finding.severity);
133
+ return severity === finding.severity ? finding : { ...finding, severity };
134
+ }
9
135
 
10
136
  // Input bundle for `finding()` - the lowest-cost finding factory. Captures everything the caller
11
137
  // must supply for a line-anchored Finding; shared defaults (confidence "high", empty metadata)
package/src/findings.ts CHANGED
@@ -10,6 +10,9 @@ interface FindingInput {
10
10
  filePath: string;
11
11
  line?: number;
12
12
  endLine?: number;
13
+ // One-based match column. Deliberately NOT part of the fingerprint hash (ADR-017): it only
14
+ // discriminates same-line occurrences in report dedupe and enriches SARIF/JSON locations.
15
+ column?: number;
13
16
  severity: Severity;
14
17
  pillar: Pillar;
15
18
  confidence: Confidence;
@@ -32,6 +35,7 @@ function makeFinding(input: FindingInput): Finding {
32
35
  filePath: input.filePath,
33
36
  ...(input.line ? { line: input.line } : {}),
34
37
  ...(input.endLine ? { endLine: input.endLine } : {}),
38
+ ...(input.column ? { column: input.column } : {}),
35
39
  severity: input.severity,
36
40
  pillar: input.pillar,
37
41
  secondaryPillars: [],
@@ -2,7 +2,7 @@
2
2
  // pass - template-literal fixtures, generated array fixtures, and high-setup test blocks - then
3
3
  // reports `docs.fixture-purpose-missing` for each candidate without a nearby explanation comment.
4
4
  import { type FunctionBlock, setupLineCount } from "./blocks.ts";
5
- import { type CommentRecord } from "./comment-scanner.ts";
5
+ import { combinedContextLineComment, type CommentRecord } from "./comment-scanner.ts";
6
6
  import { type SourceFile } from "./discovery.ts";
7
7
  import { makeFinding } from "./findings.ts";
8
8
  import { isFixtureLikePath, isTestPath } from "./project-rules.ts";
@@ -50,14 +50,14 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
50
50
  findings.push(
51
51
  makeFinding({
52
52
  ruleId: "docs.fixture-purpose-missing",
53
- message: `Large fixture source near \`${candidate.symbol}\` is missing a purpose comment.`,
53
+ message: fixturePurposeMessage(candidate),
54
54
  filePath: file.displayPath,
55
55
  line: candidate.line,
56
56
  severity: "advisory",
57
57
  pillar: "documentation",
58
58
  confidence: "medium",
59
59
  symbol: candidate.symbol,
60
- remediation: "Add a nearby comment explaining what scanner path, regression, or fixture behavior this source covers.",
60
+ remediation: fixturePurposeRemediation(candidate),
61
61
  metadata: {
62
62
  targetKind: candidate.targetKind,
63
63
  fixtureLines: candidate.lineCount,
@@ -67,6 +67,24 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
67
67
  }
68
68
  }
69
69
 
70
+ // The finding is anchored where the accepted comment position is, so the message must name the
71
+ // construct at that anchor: the test declaration for setup candidates, the fixture otherwise.
72
+ function fixturePurposeMessage(candidate: FixturePurposeCandidate): string {
73
+ if (candidate.targetKind === "test-setup") {
74
+ return `Test \`${candidate.symbol}\` builds a large fixture setup without a purpose comment above the test.`;
75
+ }
76
+ return `Large fixture source near \`${candidate.symbol}\` is missing a purpose comment.`;
77
+ }
78
+
79
+ // The stated fix must be the fix that clears the finding: both texts name the accepted comment
80
+ // positions that `hasFixturePurposeComment` checks.
81
+ function fixturePurposeRemediation(candidate: FixturePurposeCandidate): string {
82
+ if (candidate.targetKind === "test-setup") {
83
+ return "Add a comment directly above the test declaration explaining what scanner path, regression, or fixture behavior this setup covers.";
84
+ }
85
+ return "Add a comment on or directly above the fixture explaining what scanner path, regression, or fixture behavior this source covers.";
86
+ }
87
+
70
88
  // Three candidate kinds collected in one pass: template-literal fixtures, generated array fixtures,
71
89
  // and test setup blocks. `occupiedLines` tracks the first two so the third doesn't double-report.
72
90
  function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[]): FixturePurposeCandidate[] {
@@ -289,13 +307,29 @@ function closingTemplateLiteralIndex(source: string, startIndex: number): number
289
307
 
290
308
  // Two acceptable positions: a comment on the candidate line itself, or one directly above with
291
309
  // nothing but blank lines in between. Anything farther away cannot be claimed as documentation.
310
+ // A stacked `//` header counts as one comment, so a purpose statement on an earlier line clears.
292
311
  function hasFixturePurposeComment(lines: string[], comments: CommentRecord[], line: number): boolean {
293
312
  const sameLine = comments.find((comment) => comment.line <= line && comment.endLine >= line);
294
- if (sameLine && hasFixturePurposeMarker(sameLine.text)) {
313
+ if (sameLine && isFixturePurposeComment(sameLine.text)) {
295
314
  return true;
296
315
  }
297
316
  const leading = leadingFixturePurposeComment(lines, comments, line);
298
- return Boolean(leading && hasFixturePurposeMarker(leading.text));
317
+ return Boolean(leading && isFixturePurposeComment(combinedContextLineComment(comments, leading).text));
318
+ }
319
+
320
+ // This word-count threshold accepts a comment as a purpose statement even without the vocabulary
321
+ // fast path, because grading wording by keyword list sent maintainers into rewrite loops when a
322
+ // genuine explanation missed the exact words. Shorter comments still need a vocabulary word.
323
+ const FIXTURE_PURPOSE_MIN_WORDS = 8;
324
+
325
+ // Either acceptance path used by `hasFixturePurposeComment`: vocabulary or substantive prose.
326
+ function isFixturePurposeComment(text: string): boolean {
327
+ return hasFixturePurposeMarker(text) || fixtureCommentWordCount(text) >= FIXTURE_PURPOSE_MIN_WORDS;
328
+ }
329
+
330
+ // Counts word-like tokens; punctuation-only fragments do not make a comment substantive.
331
+ function fixtureCommentWordCount(text: string): number {
332
+ return text.split(/\s+/).filter((token) => /[A-Za-z0-9]/.test(token)).length;
299
333
  }
300
334
 
301
335
  // Like `leadingCommentForLine` but with the fixture-specific blank-gap predicate that allows for
@@ -41,19 +41,38 @@ interface WorkflowCommand {
41
41
  line: WorkflowLine;
42
42
  }
43
43
 
44
+ // GitHub's 2026-07-12 workflow table defines the current write-capable keys below.
45
+ // `repository-projects` remains so users scanning legacy Enterprise workflows still see the risk.
44
46
  const WRITE_PERMISSION_SCOPES = new Set([
45
47
  "actions",
48
+ "artifact-metadata",
49
+ "attestations",
46
50
  "checks",
51
+ "code-quality",
47
52
  "contents",
48
53
  "deployments",
54
+ "discussions",
55
+ "id-token",
49
56
  "issues",
50
57
  "packages",
58
+ "pages",
51
59
  "pull-requests",
52
60
  "repository-projects",
53
61
  "security-events",
54
62
  "statuses",
55
63
  ]);
56
64
 
65
+ // These two scopes mint a short-lived OIDC token or a build attestation. Neither grants write access
66
+ // to any repository resource, and GitHub documents both as the recommended alternative to storing
67
+ // long-lived credentials, so a workflow that requests them is not over-permissioned. Reporting them
68
+ // pushed users away from keyless auth and toward the static secrets this pillar exists to remove.
69
+ // They still reach `broadPermissionSignal`, where a pull_request_target workflow hands that minting
70
+ // power to untrusted pull-request code.
71
+ const CAPABILITY_PERMISSION_SCOPES = new Set([
72
+ "attestations",
73
+ "id-token",
74
+ ]);
75
+
57
76
  // Stable rule contract: workflow-only checks ignore non-workflow YAML so example docs avoid findings.
58
77
  function analyseGithubActionsRules(file: SourceFile, source: string, findings: Finding[]): void {
59
78
  if (!isGithubWorkflowPath(file.displayPath)) {
@@ -196,10 +215,14 @@ function closeBlockWhenOutdented(state: IndentedBlockState, line: WorkflowLine):
196
215
  }
197
216
  }
198
217
 
199
- // Extracts selected write scopes that are broad enough to matter for workflow security.
218
+ // Extracts the write scopes that grant a repository resource, which is what this rule reports.
200
219
  function scopedWritePermission(line: WorkflowLine): string | undefined {
201
220
  const scoped = line.trimmed.match(/^([a-z-]+):\s*write\b/i);
202
221
  const scope = scoped?.[1] ?? "";
222
+ // A capability scope grants no repository resource, so requesting one is not a broad permission.
223
+ if (CAPABILITY_PERMISSION_SCOPES.has(scope)) {
224
+ return undefined;
225
+ }
203
226
  return WRITE_PERMISSION_SCOPES.has(scope) ? scope : undefined;
204
227
  }
205
228