@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
@@ -10,14 +10,17 @@ import { ConfigLoadError } from "./config-load-error.ts";
10
10
  import { loadConfig, minimumSeverityFor } from "./config.ts";
11
11
  import { VERSION } from "./constants.ts";
12
12
  import { startDashboard } from "./dashboard.ts";
13
- import { renderHookCapabilities, renderHookConfigError, renderHookReport } from "./hook-contract.ts";
13
+ import { hookRenderedDiagnosticsCount, renderHookCapabilities, renderHookConfigError, renderHookReport } from "./hook-contract.ts";
14
14
  import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
15
15
  import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
16
16
  import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderProfileList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
17
17
  import { exitFor } from "./scoring.ts";
18
18
  import type { AnalysisOptions, AnalysisReport, MinimumSeverityCommand } from "./types.ts";
19
19
 
20
- type AnalyseRunner = (options: AnalysisOptions) => AnalysisReport;
20
+ type HookAnalysisViews = { currentReport: AnalysisReport; scopedReport: AnalysisReport };
21
+ type AnalyseRunner = ((options: AnalysisOptions) => AnalysisReport) & {
22
+ hookViews?: (currentOptions: AnalysisOptions, scopedOptions: AnalysisOptions, hasChangedRegion: boolean) => HookAnalysisViews;
23
+ };
21
24
 
22
25
  // The `report` command intentionally rejects `--baseline` because its output is meant to reflect
23
26
  // raw findings; this flag lets `normalizeOptions` enforce that without per-command branching.
@@ -180,14 +183,14 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
180
183
  .option("--config <path>", "Path to a gruff YAML config file.")
181
184
  .option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
182
185
  .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
183
- .option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", "text")
184
- .option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
186
+ .option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", parseAnalyseFormat, "text")
187
+ .option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "advisory")
185
188
  .option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
186
189
  .option("--changed-ranges <ranges>", "Filter findings to changed regions, for example 3-3,8-10.")
187
190
  .option("--since <ref>", "Filter findings to regions changed against a git base ref.")
188
191
  .option("--diff [mode]", "Filter findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
189
- .option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", "symbol")
190
- .option("--history-file <path>", "Append score trend history to this JSON file.")
192
+ .option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", parseChangedScope, "symbol")
193
+ .option("--history-file <path>", "Append score trend history to this JSON file (full scans only; incompatible with --diff, --since, and --changed-ranges).")
191
194
  .option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
192
195
  .option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
193
196
  .option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
@@ -243,6 +246,7 @@ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void
243
246
  .option("--since <ref>", "Filter hook findings to regions changed against a git base ref and compare against that ref.")
244
247
  .option("--diff [mode]", "Filter hook findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
245
248
  .option("--baseline <path>", "Compare hook findings against a gruff baseline JSON file using stableIdentity.")
249
+ .option("--fail-on-diagnostics", "Exit 2 when parse/read diagnostics affect the analysed change; the default reports them in-band with exit 0.")
246
250
  .action((paths: string[], rawOptions: Record<string, unknown>) => {
247
251
  if (rawOptions.capabilities === true) {
248
252
  writeCommandOutput(program, renderHookCapabilities());
@@ -252,14 +256,17 @@ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void
252
256
  try {
253
257
  const scopedOptions = hookScopedOptions(paths, rawOptions);
254
258
  const currentOptions = hookCurrentOptions(scopedOptions);
255
- writeCommandOutput(program, renderHookReport(runAnalyse, {
259
+ const rendered = renderHookReport(runAnalyse, {
256
260
  currentOptions,
257
261
  scopedOptions,
258
262
  ...hookBaselinePath(rawOptions),
259
263
  ...hookDiffBase(scopedOptions),
260
264
  hasChangedRegion: hasHookChangedRegion(scopedOptions),
261
- }));
262
- process.exitCode = 0;
265
+ });
266
+ writeCommandOutput(program, rendered);
267
+ // Explicit consumer request (gruff.hook.v1): only --fail-on-diagnostics turns in-band
268
+ // diagnostics into exit 2; every other successful hook run keeps the documented exit 0.
269
+ process.exitCode = rawOptions.failOnDiagnostics === true && hookRenderedDiagnosticsCount(rendered) > 0 ? 2 : 0;
263
270
  } catch (error) {
264
271
  if (error instanceof ConfigLoadError) {
265
272
  writeCommandOutput(program, renderHookConfigError(error.message, error.suggestion));
@@ -317,6 +324,7 @@ function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner):
317
324
  .option("--port <port>", "Port to bind.", "8767")
318
325
  .option("--project-root <path>", "Default project root.", ".")
319
326
  .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
327
+ .option("--scan-timeout <seconds>", "Accepted for cross-port compatibility; not implemented in gruff-ts.")
320
328
  .action(async (rawOptions: Record<string, unknown>) => {
321
329
  const projectRoot = resolve(String(rawOptions.projectRoot ?? "."));
322
330
  await maybePromptInitConfig(program, projectRoot, { shouldSkipConfig: false, hasExplicitConfig: false });
@@ -415,12 +423,12 @@ function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): voi
415
423
  .command("report")
416
424
  .description("Render a gruff report to stdout or a file.")
417
425
  .argument("[paths...]", "Files or directories to analyse.")
418
- .option("--format <format>", "Report format: html or json.", "html")
426
+ .option("--format <format>", "Report format: html or json.", parseReportFormat, "html")
419
427
  .option("--output <path>", "Write report to a file.")
420
428
  .option("--config <path>", "Path to a gruff YAML config file.")
421
429
  .option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
422
430
  .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
423
- .option("--fail-on <severity>", "Finding severity that fails the run.", "none")
431
+ .option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "none")
424
432
  .option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
425
433
  .option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
426
434
  .action(async (paths: string[], rawOptions: Record<string, unknown>, command: Command) => {
@@ -454,10 +462,10 @@ function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): vo
454
462
  .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
455
463
  .option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
456
464
  .option("--top <n>", "How many top rules and file offenders to list.", parseNonNegativeInteger, 10)
457
- .option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
465
+ .option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", parseFailOn, "advisory")
458
466
  .option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
459
467
  .option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
460
- .option("--history-file <path>", "Append score trend history to this JSON file.")
468
+ .option("--history-file <path>", "Append score trend history to this JSON file (full scans only; incompatible with --diff).")
461
469
  .option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
462
470
  .option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
463
471
  .option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
@@ -502,6 +510,27 @@ function parseHookFormat(rawFormat: string): "json" {
502
510
  throw new InvalidArgumentError("must be json");
503
511
  }
504
512
 
513
+ /*
514
+ * Builds a commander argParser for one constrained-choice option. Governance controls (format,
515
+ * failure severity, diff scope) must reject a misspelled value as a usage error before analysis
516
+ * starts - a silent fallback would let CI pass under semantics the caller never asked for.
517
+ */
518
+ function parseChoiceOf(choices: readonly string[]): (rawValue: string) => string {
519
+ // Validates one raw CLI value against the documented set; throws InvalidArgumentError otherwise.
520
+ return (rawValue: string): string => {
521
+ // A value outside the documented set is a caller mistake, never a silent default.
522
+ if (choices.includes(rawValue)) {
523
+ return rawValue;
524
+ }
525
+ throw new InvalidArgumentError(`must be one of: ${choices.join(", ")}`);
526
+ };
527
+ }
528
+
529
+ const parseAnalyseFormat = parseChoiceOf(["text", "json", "html", "markdown", "github", "hotspot", "sarif"]);
530
+ const parseReportFormat = parseChoiceOf(["html", "json"]);
531
+ const parseFailOn = parseChoiceOf(["none", "advisory", "warning", "error"]);
532
+ const parseChangedScope = parseChoiceOf(["symbol", "hunk", "file"]);
533
+
505
534
  /*
506
535
  * Commander argParser for `--top`-style numeric flags. Throws `InvalidArgumentError` on non-integer
507
536
  * or negative input so commander reports a usage error and exits non-zero before the command runs.
@@ -527,6 +556,7 @@ function summaryPathLabel(paths: string[], projectRoot: string): string {
527
556
  // two CLI invocations producing identical AnalysisOptions must produce identical, stable findings -
528
557
  // adding new fields here without folding them into that hash is a deterministic-output regression.
529
558
  function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>, context: NormalizeContext): AnalysisOptions {
559
+ assertFullScanHistoryOptions(rawOptions);
530
560
  const format = stringChoice(rawOptions.format, ["text", "json", "html", "markdown", "github", "hotspot", "sarif"], "text");
531
561
  const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "advisory");
532
562
  const diffInput = diffOption(paths, rawOptions);
@@ -556,6 +586,24 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
556
586
  };
557
587
  }
558
588
 
589
+ /*
590
+ * Rejects a history path paired with any changed-region selector before analysis or rendering.
591
+ * Throws ConfigLoadError so analyse and summary emit the same exit-2 guidance with no stdout.
592
+ */
593
+ function assertFullScanHistoryOptions(rawOptions: Record<string, unknown>): void {
594
+ const hasChangedRegionSelector = rawOptions.diff === true
595
+ || typeof rawOptions.diff === "string"
596
+ || typeof rawOptions.since === "string"
597
+ || typeof rawOptions.changedRanges === "string";
598
+ // A filtered request would mix partial scores into the full-project trend users review.
599
+ if (typeof rawOptions.historyFile === "string" && hasChangedRegionSelector) {
600
+ throw new ConfigLoadError(
601
+ "`--history-file` requires a full scan and cannot be combined with `--diff`, `--since`, or `--changed-ranges`.",
602
+ "Remove the changed-region option, or omit `--history-file` for this filtered scan.",
603
+ );
604
+ }
605
+ }
606
+
559
607
  // Builds the scoped (changed-region) analysis options for the hook: JSON output, no fail-on gate,
560
608
  // symbol scope, and no analysis baseline.
561
609
  function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
@@ -651,8 +699,10 @@ function generateBaselineOption(rawOptions: Record<string, unknown>): Partial<Pi
651
699
  return rawOptions.generateBaseline === true ? { generateBaseline: DEFAULT_BASELINE } : {};
652
700
  }
653
701
 
654
- function stringChoice<T extends string>(value: unknown, choices: readonly T[], fallback: T): T {
655
- return typeof value === "string" && choices.includes(value as T) ? (value as T) : fallback;
702
+ // Last-resort choice normalizer for programmatic option bags; the CLI surfaces validate the same
703
+ // sets at parse time, so this fallback only guards direct `normalizeOptions` callers.
704
+ function stringChoice<T extends string>(rawValue: unknown, choices: readonly T[], fallback: T): T {
705
+ return typeof rawValue === "string" && choices.includes(rawValue as T) ? (rawValue as T) : fallback;
656
706
  }
657
707
 
658
708
  /*
package/src/cli.ts CHANGED
@@ -3,14 +3,16 @@
3
3
  // analyse pipeline itself lives in `./analyser.ts`; this file is just bootstrap plus re-exports.
4
4
  import { argv } from "node:process";
5
5
  import { pathToFileURL } from "node:url";
6
- import { analyse } from "./analyser.ts";
6
+ import { analyse, analyseHookReports } from "./analyser.ts";
7
7
  import { buildProgram as buildCliProgram } from "./cli-program.ts";
8
8
  import { absolutize, displayPath } from "./discovery.ts";
9
9
  import { renderReport } from "./report-renderers.ts";
10
10
  import { ruleDescriptors } from "./rules.ts";
11
11
  export type { AnalysisReport, Finding, OutputFormat, Pillar, RuleDescriptor, Severity } from "./types.ts";
12
12
 
13
- const buildProgram = (): ReturnType<typeof buildCliProgram> => buildCliProgram(analyse);
13
+ const analyseRunner = Object.assign(analyse, { hookViews: analyseHookReports });
14
+ // Builds the commander program with the optimized hook-view runner already attached.
15
+ const buildProgram = (): ReturnType<typeof buildCliProgram> => buildCliProgram(analyseRunner);
14
16
 
15
17
  if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
16
18
  // Action handlers in cli-program.ts are async (await maybePromptInitConfig). parseAsync is
@@ -6,7 +6,7 @@ import { existsSync } from "node:fs";
6
6
  import { dirname as dirnamePath, resolve } from "node:path";
7
7
  import { cwd } from "node:process";
8
8
  import { type FunctionBlock } from "./blocks.ts";
9
- import { type CommentRecord } from "./comment-scanner.ts";
9
+ import { combinedContextLineComment, type CommentRecord } from "./comment-scanner.ts";
10
10
  import { type SourceFile } from "./discovery.ts";
11
11
  import { type ExportedDeclaration, interfaceDeclarations } from "./doc-rules.ts";
12
12
  import { type CommentedDeclaration, pushDeclarationContextFindings, pushFunctionContextFindings } from "./context-doc-rules.ts";
@@ -55,7 +55,7 @@ export function analyseCommentQualityRules(input: CommentQualityRuleInput): void
55
55
  const lines = source.split(/\r?\n/);
56
56
  const declarations = commentedDeclarations(blocks, interfaceDeclarations(source, codeSource));
57
57
 
58
- analyseStandaloneCommentQuality(file, comments, DESCRIPTOR_IDS, CLI_FLAGS, findings);
58
+ analyseStandaloneCommentQuality(file, source, comments, DESCRIPTOR_IDS, CLI_FLAGS, findings);
59
59
  analyseCommentedDeclarationQuality(file, lines, comments, declarations, findings);
60
60
  analyseFunctionContextCommentQuality({ file, lines, comments, blocks, config, findings });
61
61
  pushMagicThresholdFindings(file, lines, codeSource, comments, findings);
@@ -67,9 +67,9 @@ export function analyseCommentQualityRules(input: CommentQualityRuleInput): void
67
67
  * stale CLI flag refs) that run on every comment regardless of whether it documents a declaration.
68
68
  * Stable, deterministic emission order across the five sub-checks.
69
69
  */
70
- function analyseStandaloneCommentQuality(file: SourceFile, comments: CommentRecord[], ruleIdSet: Set<string>, optionFlagSet: Set<string>, findings: Finding[]): void {
70
+ function analyseStandaloneCommentQuality(file: SourceFile, source: string, comments: CommentRecord[], ruleIdSet: Set<string>, optionFlagSet: Set<string>, findings: Finding[]): void {
71
71
  for (const comment of comments) {
72
- pushTodoWithoutTrackingFinding(file, comment, findings);
72
+ pushTodoWithoutTrackingFinding(file, source, comment, findings);
73
73
  pushSuppressionWithoutRationaleFinding(file, comment, findings);
74
74
  pushStaleFileReferenceFindings(file, comment, findings);
75
75
  pushStaleRuleReferenceFindings(file, comment, ruleIdSet, findings);
@@ -91,7 +91,7 @@ function analyseCommentedDeclarationQuality(file: SourceFile, lines: string[], c
91
91
  pushStaleDeclarationCommentFinding(file, comment, declaration, findings);
92
92
  pushRestatingSignatureCommentFinding(file, comment, declaration, findings);
93
93
  if (!isRestatingSignatureComment(comment.text, declaration.name, declaration.kind)) {
94
- pushDeclarationContextFindings(file, lines, declaration, comment, findings);
94
+ pushDeclarationContextFindings(file, lines, declaration, combinedContextLineComment(comments, comment), findings);
95
95
  }
96
96
  }
97
97
  }
@@ -105,7 +105,7 @@ function analyseFunctionContextCommentQuality(input: FunctionContextCommentQuali
105
105
  if (!comment || isRestatingSignatureComment(comment.text, block.name, "function")) {
106
106
  continue;
107
107
  }
108
- pushFunctionContextFindings(file, block, comment, config, findings);
108
+ pushFunctionContextFindings(file, block, combinedContextLineComment(comments, comment), config, findings);
109
109
  }
110
110
  }
111
111
 
@@ -125,8 +125,8 @@ function commentedDeclarations(blocks: FunctionBlock[], interfaces: ExportedDecl
125
125
  * preserved in stable metadata so consumers can group by marker kind. Reports the stable
126
126
  * untracked-task-marker finding when no tracking reference is attached.
127
127
  */
128
- function pushTodoWithoutTrackingFinding(file: SourceFile, comment: CommentRecord, findings: Finding[]): void {
129
- const marker = todoMarker(comment.text);
128
+ function pushTodoWithoutTrackingFinding(file: SourceFile, source: string, comment: CommentRecord, findings: Finding[]): void {
129
+ const marker = todoMarker(source, comment);
130
130
  if (!marker || hasTodoTracking(comment.text)) {
131
131
  return;
132
132
  }
@@ -146,9 +146,52 @@ function pushTodoWithoutTrackingFinding(file: SourceFile, comment: CommentRecord
146
146
  }
147
147
 
148
148
  // Four canonical task-marker words, returned in uppercase so the finding message reads consistently
149
- // regardless of how the maintainer wrote them.
150
- function todoMarker(text: string): string | undefined {
151
- return text.match(/\b(TODO|FIXME|HACK|XXX)\b/i)?.[1]?.toUpperCase();
149
+ // regardless of how the maintainer wrote them. A marker must INTRODUCE a comment body line - prose
150
+ // that merely mentions a marker word (quoted, backticked, or mid-sentence) stays quiet.
151
+ function todoMarker(source: string, comment: CommentRecord): string | undefined {
152
+ for (const line of commentBodyLines(source, comment)) {
153
+ const marker = leadingTodoMarker(line);
154
+ if (marker) {
155
+ return marker;
156
+ }
157
+ }
158
+ return undefined;
159
+ }
160
+
161
+ // One body line per physical comment line: the trimmed `//` text, or each block-comment line with
162
+ // its `*` decoration stripped. Lines inside ``` fences are dropped so marker examples shown in
163
+ // doc comments cannot become findings.
164
+ function commentBodyLines(source: string, comment: CommentRecord): string[] {
165
+ if (comment.kind === "line") {
166
+ return [comment.text];
167
+ }
168
+ const body = source.slice(comment.startIndex + 2, Math.max(comment.startIndex + 2, comment.endIndex - 1));
169
+ const lines: string[] = [];
170
+ let isInsideFence = false;
171
+ for (const rawLine of body.split(/\r?\n/)) {
172
+ const line = rawLine.replace(/^[ \t]*\*[ \t]?/, "").trim();
173
+ if (line.startsWith("```")) {
174
+ isInsideFence = !isInsideFence;
175
+ continue;
176
+ }
177
+ if (!isInsideFence) {
178
+ lines.push(line);
179
+ }
180
+ }
181
+ return lines;
182
+ }
183
+
184
+ // Leading-marker grammar: optional list bullet, the marker word, then a delimiter real markers use
185
+ // (":", "(", "-", whitespace, or end of line). Any other next character - a quote, slash, or
186
+ // backtick - means the line talks ABOUT a marker instead of being one.
187
+ function leadingTodoMarker(line: string): string | undefined {
188
+ const match = line.match(/^(?:(?:[-*>]|\d+[.)])\s+)?(TODO|FIXME|HACK|XXX)\b(.*)$/i);
189
+ const marker = match?.[1];
190
+ if (!marker) {
191
+ return undefined;
192
+ }
193
+ const rest = match?.[2] ?? "";
194
+ return rest === "" || /^[\s:(-]/.test(rest) ? marker.toUpperCase() : undefined;
152
195
  }
153
196
 
154
197
  const TODO_TRACKING_PATTERNS = [
@@ -296,6 +339,7 @@ function knownCliFlags(): Set<string> {
296
339
  "--changed-ranges",
297
340
  "--changed-scope",
298
341
  "--fail-on",
342
+ "--fail-on-diagnostics",
299
343
  "--force",
300
344
  "--format",
301
345
  "--generate-baseline",
@@ -487,14 +531,15 @@ function isCommonSafeNumber(numericLiteral: string): boolean {
487
531
  }
488
532
 
489
533
  // Two acceptable positions for the explanatory comment: same line as the constant, or directly
490
- // above with a blank-line gap. Mirrors `hasFixturePurposeComment` adjacency rules.
534
+ // above with a blank-line gap. Mirrors `hasFixturePurposeComment` adjacency rules, including
535
+ // reading a stacked `//` header as one comment so rationale on an earlier line counts.
491
536
  function hasNearbyThresholdRationale(lines: string[], comments: CommentRecord[], line: number): boolean {
492
537
  const sameLine = comments.find((comment) => comment.line <= line && comment.endLine >= line);
493
538
  if (sameLine && hasThresholdRationaleMarker(sameLine.text)) {
494
539
  return true;
495
540
  }
496
541
  const leading = leadingCommentForLine(lines, comments, line);
497
- return Boolean(leading && hasThresholdRationaleMarker(leading.text));
542
+ return Boolean(leading && hasThresholdRationaleMarker(combinedContextLineComment(comments, leading).text));
498
543
  }
499
544
 
500
545
  // Vocabulary used by the magic-threshold rule. A numeric constant followed by a comment containing
@@ -281,6 +281,33 @@ function normalizedBlockCommentText(text: string): string {
281
281
  .trim();
282
282
  }
283
283
 
284
+ // Reads a contiguous `//` run as one maintainer comment while keeping the final record's anchor.
285
+ // Rules that accept a leading comment use this so a purpose or context statement on an earlier
286
+ // line of a stacked header still counts; block comments pass through unchanged.
287
+ export function combinedContextLineComment(comments: CommentRecord[], finalComment: CommentRecord): CommentRecord {
288
+ if (finalComment.kind !== "line") {
289
+ return finalComment;
290
+ }
291
+ const finalIndex = comments.indexOf(finalComment);
292
+ if (finalIndex < 0) {
293
+ return finalComment;
294
+ }
295
+ let firstIndex = finalIndex;
296
+ while (firstIndex > 0) {
297
+ const previous = comments[firstIndex - 1];
298
+ const current = comments[firstIndex];
299
+ if (!previous || !current || previous.kind !== "line" || previous.endLine + 1 !== current.line) {
300
+ break;
301
+ }
302
+ firstIndex -= 1;
303
+ }
304
+ const text = comments
305
+ .slice(firstIndex, finalIndex + 1)
306
+ .map((comment) => comment.text)
307
+ .join(" ");
308
+ return { ...finalComment, text };
309
+ }
310
+
284
311
  // String-input wrapper around `hasLeadingCommentBeforeLines`. Keeps call sites that already hold
285
312
  // a split line array from re-splitting on every lookup.
286
313
  export function hasLeadingCommentBeforeLine(source: string, line: number): boolean {
@@ -0,0 +1,244 @@
1
+ // Syntax-aware complexity measurement for each callable discovered by the shared script parse.
2
+ // It turns real decision nodes into the values shown in CLI and JSON findings while leaving
3
+ // defaulting, optional access, presentation objects, and ordinary blocks out of the score.
4
+ // Nested callable ownership follows the same M07 block inventory, so every body counts once.
5
+ import { createRequire } from "node:module";
6
+
7
+ // TypeScript is CommonJS at runtime; this module only walks nodes from the existing shared parse.
8
+ const require = createRequire(import.meta.url);
9
+ const typescriptSyntax = require("typescript") as typeof import("typescript");
10
+
11
+ // Syntax node identity links measurements to the callable inventory from the shared parser.
12
+ // Nodes never leave the internal scan pipeline or appear in JSON and UI report payloads.
13
+ // Equality is object identity within one parse, which preserves single ownership.
14
+ type TypeScriptNode = import("typescript").Node;
15
+
16
+ /**
17
+ * Stable per-kind decision counts attached to complexity findings for report consumers.
18
+ * Every key is always present, including zero values, so JSON comparisons stay deterministic.
19
+ * `maxNesting` describes control-flow nesting only, never object or callback braces.
20
+ */
21
+ export interface ComplexityBreakdown {
22
+ if: number;
23
+ loop: number;
24
+ catch: number;
25
+ case: number;
26
+ ternary: number;
27
+ logicalAnd: number;
28
+ logicalOr: number;
29
+ maxNesting: number;
30
+ }
31
+
32
+ /**
33
+ * One callable's shared complexity result used by both findings and documentation checks.
34
+ * Cyclomatic starts at one; cognitive adds maximum control-flow nesting to that value.
35
+ * A CLI user reaches these measurements when a configured threshold produces a finding.
36
+ */
37
+ export interface ComplexityMetrics {
38
+ cyclomatic: number;
39
+ cognitive: number;
40
+ maximumControlFlowNesting: number;
41
+ breakdown: ComplexityBreakdown;
42
+ }
43
+
44
+ /**
45
+ * Mutable counters used only during one syntax-tree walk for one reported callable.
46
+ * The accumulator is converted to an immutable report-shaped result after traversal.
47
+ * No state survives between files or CLI scans.
48
+ */
49
+ interface ComplexityAccumulator {
50
+ ifCount: number;
51
+ loopCount: number;
52
+ catchCount: number;
53
+ caseCount: number;
54
+ ternaryCount: number;
55
+ logicalAndCount: number;
56
+ logicalOrCount: number;
57
+ maximumControlFlowNesting: number;
58
+ }
59
+
60
+ /**
61
+ * Context threaded through the recursive walk so nested callable bodies keep one owner.
62
+ * `callableNode` is the block being measured; `ownedCallableNodes` are sibling report blocks.
63
+ * The shared accumulator becomes metadata visible to report and hook consumers.
64
+ */
65
+ interface ComplexityWalkContext {
66
+ callableNode: TypeScriptNode;
67
+ ownedCallableNodes: ReadonlySet<TypeScriptNode>;
68
+ accumulator: ComplexityAccumulator;
69
+ }
70
+
71
+ // Returns the base measurement used only when a caller has no parsed script, such as a legacy span probe.
72
+ export function baseComplexityMetrics(): ComplexityMetrics {
73
+ return {
74
+ cyclomatic: 1,
75
+ cognitive: 1,
76
+ maximumControlFlowNesting: 0,
77
+ breakdown: emptyBreakdown(),
78
+ };
79
+ }
80
+
81
+ // Measures one parsed callable without reparsing the source or walking another reported callable.
82
+ // It reports one deterministic breakdown to CLI complexity findings and documentation checks.
83
+ export function complexityMetrics(callableNode: TypeScriptNode, ownedCallableNodes: ReadonlySet<TypeScriptNode>): ComplexityMetrics {
84
+ const accumulator: ComplexityAccumulator = {
85
+ ifCount: 0,
86
+ loopCount: 0,
87
+ catchCount: 0,
88
+ caseCount: 0,
89
+ ternaryCount: 0,
90
+ logicalAndCount: 0,
91
+ logicalOrCount: 0,
92
+ maximumControlFlowNesting: 0,
93
+ };
94
+ const context: ComplexityWalkContext = { callableNode, ownedCallableNodes, accumulator };
95
+ // The root callable owns its parameters and body; separately reported nested callables are pruned below.
96
+ callableNode.forEachChild((child) => walkComplexityNode(child, 0, context));
97
+ const decisionCount = accumulator.ifCount
98
+ + accumulator.loopCount
99
+ + accumulator.catchCount
100
+ + accumulator.caseCount
101
+ + accumulator.ternaryCount
102
+ + accumulator.logicalAndCount
103
+ + accumulator.logicalOrCount;
104
+ const cyclomatic = decisionCount + 1;
105
+ const breakdown: ComplexityBreakdown = {
106
+ if: accumulator.ifCount,
107
+ loop: accumulator.loopCount,
108
+ catch: accumulator.catchCount,
109
+ case: accumulator.caseCount,
110
+ ternary: accumulator.ternaryCount,
111
+ logicalAnd: accumulator.logicalAndCount,
112
+ logicalOr: accumulator.logicalOrCount,
113
+ maxNesting: accumulator.maximumControlFlowNesting,
114
+ };
115
+ return {
116
+ cyclomatic,
117
+ cognitive: cyclomatic + accumulator.maximumControlFlowNesting,
118
+ maximumControlFlowNesting: accumulator.maximumControlFlowNesting,
119
+ breakdown,
120
+ };
121
+ }
122
+
123
+ // Walks one node using the counting law, carrying only control-flow depth between syntax children.
124
+ function walkComplexityNode(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
125
+ // When M07 reports a nested callable separately, its body belongs to that report block, not this parent.
126
+ if (node !== context.callableNode && context.ownedCallableNodes.has(node)) {
127
+ return;
128
+ }
129
+ // A user's if statement adds one decision and one control-flow nesting level.
130
+ if (typescriptSyntax.isIfStatement(node)) {
131
+ walkIfStatement(node, controlFlowDepth, context);
132
+ return;
133
+ }
134
+ // Every loop form adds one decision and one control-flow nesting level.
135
+ if (isLoopStatement(node)) {
136
+ context.accumulator.loopCount += 1;
137
+ walkNestedControlFlow(node, controlFlowDepth, context);
138
+ return;
139
+ }
140
+ // A switch adds nesting for its choices but no decision beyond its non-default cases.
141
+ if (typescriptSyntax.isSwitchStatement(node)) {
142
+ walkNestedControlFlow(node, controlFlowDepth, context);
143
+ return;
144
+ }
145
+ // Catch represents one recovery path and one control-flow nesting level.
146
+ if (typescriptSyntax.isCatchClause(node)) {
147
+ context.accumulator.catchCount += 1;
148
+ walkNestedControlFlow(node, controlFlowDepth, context);
149
+ return;
150
+ }
151
+ // Each explicit case adds a decision; default and the case wrapper add no nesting.
152
+ if (typescriptSyntax.isCaseClause(node)) {
153
+ context.accumulator.caseCount += 1;
154
+ walkChildrenAtDepth(node, controlFlowDepth, context);
155
+ return;
156
+ }
157
+ // A conditional expression adds one decision and one control-flow nesting level.
158
+ if (typescriptSyntax.isConditionalExpression(node)) {
159
+ context.accumulator.ternaryCount += 1;
160
+ walkNestedControlFlow(node, controlFlowDepth, context);
161
+ return;
162
+ }
163
+ // Logical operators count as decisions but do not deepen control flow.
164
+ if (typescriptSyntax.isBinaryExpression(node)) {
165
+ walkBinaryExpression(node, controlFlowDepth, context);
166
+ return;
167
+ }
168
+ // Optional access, nullish coalescing, ordinary blocks, and presentation syntax keep the same depth.
169
+ walkChildrenAtDepth(node, controlFlowDepth, context);
170
+ }
171
+
172
+ // Counts an if and keeps an `else if` at peer depth while ordinary else bodies stay nested.
173
+ function walkIfStatement(node: import("typescript").IfStatement, controlFlowDepth: number, context: ComplexityWalkContext): void {
174
+ context.accumulator.ifCount += 1;
175
+ const nestedDepth = enterControlFlow(controlFlowDepth, context.accumulator);
176
+ walkComplexityNode(node.expression, nestedDepth, context);
177
+ walkComplexityNode(node.thenStatement, nestedDepth, context);
178
+ // A source without an else branch has no further control-flow subtree for the user to review.
179
+ if (!node.elseStatement) {
180
+ return;
181
+ }
182
+ // An `else if` is another peer decision, not an extra nesting layer created by AST parentage.
183
+ if (typescriptSyntax.isIfStatement(node.elseStatement)) {
184
+ walkComplexityNode(node.elseStatement, controlFlowDepth, context);
185
+ return;
186
+ }
187
+ walkComplexityNode(node.elseStatement, nestedDepth, context);
188
+ }
189
+
190
+ // Counts each logical binary node once; all other binary operators, including `??`, stay neutral.
191
+ function walkBinaryExpression(node: import("typescript").BinaryExpression, controlFlowDepth: number, context: ComplexityWalkContext): void {
192
+ // A user's logical AND adds one decision without changing nesting depth.
193
+ if (node.operatorToken.kind === typescriptSyntax.SyntaxKind.AmpersandAmpersandToken) {
194
+ context.accumulator.logicalAndCount += 1;
195
+ }
196
+ // A user's logical OR adds one decision without changing nesting depth.
197
+ if (node.operatorToken.kind === typescriptSyntax.SyntaxKind.BarBarToken) {
198
+ context.accumulator.logicalOrCount += 1;
199
+ }
200
+ walkChildrenAtDepth(node, controlFlowDepth, context);
201
+ }
202
+
203
+ // Enters one control construct, records the deepest user-visible level, and walks its children there.
204
+ function walkNestedControlFlow(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
205
+ const nestedDepth = enterControlFlow(controlFlowDepth, context.accumulator);
206
+ walkChildrenAtDepth(node, nestedDepth, context);
207
+ }
208
+
209
+ // Visits every syntax child at an unchanged depth so punctuation and ordinary braces stay free.
210
+ function walkChildrenAtDepth(node: TypeScriptNode, controlFlowDepth: number, context: ComplexityWalkContext): void {
211
+ // Every child stays with the nearest reported callable unless the ownership guard prunes it.
212
+ node.forEachChild((child) => walkComplexityNode(child, controlFlowDepth, context));
213
+ }
214
+
215
+ // Advances and records control-flow depth for an if, loop, switch, catch, or ternary.
216
+ function enterControlFlow(controlFlowDepth: number, accumulator: ComplexityAccumulator): number {
217
+ const nestedDepth = controlFlowDepth + 1;
218
+ accumulator.maximumControlFlowNesting = Math.max(accumulator.maximumControlFlowNesting, nestedDepth);
219
+ return nestedDepth;
220
+ }
221
+
222
+ // Recognizes every loop syntax counted by the public complexity policy.
223
+ function isLoopStatement(node: TypeScriptNode): boolean {
224
+ return typescriptSyntax.isForStatement(node)
225
+ || typescriptSyntax.isForInStatement(node)
226
+ || typescriptSyntax.isForOfStatement(node)
227
+ || typescriptSyntax.isWhileStatement(node)
228
+ || typescriptSyntax.isDoStatement(node);
229
+ }
230
+
231
+ // Builds the fixed zero-valued metadata shape used when a source has no decisions.
232
+ // It never throws because no source or parser state is read here.
233
+ function emptyBreakdown(): ComplexityBreakdown {
234
+ return {
235
+ if: 0,
236
+ loop: 0,
237
+ catch: 0,
238
+ case: 0,
239
+ ternary: 0,
240
+ logicalAnd: 0,
241
+ logicalOr: 0,
242
+ maxNesting: 0,
243
+ };
244
+ }