@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
@@ -1,17 +1,18 @@
1
1
  // Commander CLI shell wiring that keeps option normalization and stdout behavior outside the analyzer.
2
2
  import { Command, Help, InvalidArgumentError } from "commander";
3
- import { writeFileSync } from "node:fs";
3
+ import { readFileSync, writeFileSync } from "node:fs";
4
4
  import { resolve } from "node:path";
5
5
  import { performance } from "node:perf_hooks";
6
6
  import { cwd } from "node:process";
7
7
  import { DEFAULT_BASELINE } from "./baseline.ts";
8
+ import { checkIgnore, checkIgnoreExitCode, renderCheckIgnore, type CheckIgnoreFormat } from "./check-ignore.ts";
8
9
  import { ConfigLoadError } from "./config-load-error.ts";
9
10
  import { loadConfig, minimumSeverityFor } from "./config.ts";
10
11
  import { VERSION } from "./constants.ts";
11
12
  import { startDashboard } from "./dashboard.ts";
12
13
  import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
13
14
  import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
14
- import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
15
+ import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderProfileList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
15
16
  import { exitFor } from "./scoring.ts";
16
17
  import type { AnalysisOptions, AnalysisReport, MinimumSeverityCommand } from "./types.ts";
17
18
 
@@ -23,6 +24,10 @@ interface NormalizeContext {
23
24
  shouldAllowBaselineFlag: boolean;
24
25
  }
25
26
 
27
+ // Shared `--profile` flag help for analyse/report/summary/dashboard. The value is a built-in profile
28
+ // name or a profile file path; it overrides any config-file `profile:` block (CLI wins, per ADR-010).
29
+ const PROFILE_OPTION_DESCRIPTION = "Apply a built-in profile (gruff.minimal, gruff.recommended, gruff.strict) or a profile file path. Overrides a config-file profile:.";
30
+
26
31
  // Honours `--silent`/`--quiet` before writing to stdout. Always appends a trailing newline so piped
27
32
  // callers (e.g., `gruff-ts analyse | jq`) see a complete line even when a renderer forgot one.
28
33
  function writeCommandOutput(program: Command, output: string): void {
@@ -101,10 +106,12 @@ export function buildProgram(runAnalyse: AnalyseRunner): Command {
101
106
  const program = new Command();
102
107
  configureRootProgram(program);
103
108
  registerAnalyseCommand(program, runAnalyse);
109
+ registerCheckIgnoreCommand(program);
104
110
  registerCompletionCommand(program);
105
111
  registerDashboardCommand(program, runAnalyse);
106
112
  registerInitCommand(program);
107
113
  registerListCommand(program);
114
+ registerListProfilesCommand(program);
108
115
  registerListRulesCommand(program);
109
116
  registerReportCommand(program, runAnalyse);
110
117
  registerSummaryCommand(program, runAnalyse);
@@ -170,10 +177,14 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
170
177
  .argument("[paths...]", "Files or directories to analyse.")
171
178
  .option("--config <path>", "Path to a gruff YAML config file.")
172
179
  .option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
180
+ .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
173
181
  .option("--format <format>", "Output format: text, json, html, markdown, github, hotspot, or sarif.", "text")
174
182
  .option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
175
183
  .option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
176
- .option("--diff [mode]", "Filter findings to changed files. Use working-tree, staged, unstaged, or a base ref.")
184
+ .option("--changed-ranges <ranges>", "Filter findings to changed regions, for example 3-3,8-10.")
185
+ .option("--since <ref>", "Filter findings to regions changed against a git base ref.")
186
+ .option("--diff [mode]", "Filter findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
187
+ .option("--changed-scope <scope>", "Changed-region scope: symbol or hunk.", "symbol")
177
188
  .option("--history-file <path>", "Append score trend history to this JSON file.")
178
189
  .option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
179
190
  .option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
@@ -190,6 +201,45 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
190
201
  });
191
202
  }
192
203
 
204
+ // Reports whether gruff would exclude each path from analysis, with the matching ignore source and
205
+ // pattern, using the exact engine `analyse` uses (no second glob implementation) and performing no
206
+ // analysis. Built for coding-agent hooks: gate the changed-file list before scanning. Exit codes
207
+ // mirror `git check-ignore` (0 = at least one ignored, 1 = none); a config error surfaces as 2 via
208
+ // `runWithConfigErrorHandling`.
209
+ function registerCheckIgnoreCommand(program: Command): void {
210
+ program
211
+ .command("check-ignore")
212
+ .description("Report whether gruff would ignore each path (config, gitignore, or default), with the matching source and pattern. Runs no analysis.")
213
+ .argument("<paths...>", "Paths to check against the ignore rules.")
214
+ .option("--config <path>", "Path to a gruff YAML config file.")
215
+ .option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
216
+ .option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
217
+ .action(async (paths: string[], rawOptions: Record<string, unknown>) => {
218
+ await runWithConfigErrorHandling(() => {
219
+ const results = checkIgnore(paths, checkIgnoreOptions(paths, rawOptions));
220
+ const format: CheckIgnoreFormat = rawOptions.format === "json" ? "json" : "text";
221
+ writeCommandOutput(program, renderCheckIgnore(results, format));
222
+ process.exitCode = checkIgnoreExitCode(results);
223
+ });
224
+ });
225
+ }
226
+
227
+ // Minimal AnalysisOptions for `check-ignore`: only the fields `loadConfig` and the ignore engine
228
+ // read. `--config` / `--no-config` resolve identically to `analyse`; `shouldIncludeIgnored` is false
229
+ // so default and gitignore matches are reported (config `paths.ignore` is reported regardless).
230
+ function checkIgnoreOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
231
+ return {
232
+ paths,
233
+ ...configOption(rawOptions),
234
+ shouldSkipConfig: rawOptions.config === false || rawOptions.noConfig === true,
235
+ format: "json",
236
+ failOn: "none",
237
+ shouldIncludeIgnored: false,
238
+ changedScope: "symbol",
239
+ shouldSkipBaseline: true,
240
+ };
241
+ }
242
+
193
243
  // Emits the static completion script for the requested shell. Does not touch the filesystem or
194
244
  // run a scan - callers pipe the output into their shell config themselves.
195
245
  function registerCompletionCommand(program: Command): void {
@@ -211,10 +261,12 @@ function registerDashboardCommand(program: Command, runAnalyse: AnalyseRunner):
211
261
  .option("--host <host>", "Host to bind.", "127.0.0.1")
212
262
  .option("--port <port>", "Port to bind.", "8767")
213
263
  .option("--project-root <path>", "Default project root.", ".")
264
+ .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
214
265
  .action(async (rawOptions: Record<string, unknown>) => {
215
266
  const projectRoot = resolve(String(rawOptions.projectRoot ?? "."));
216
267
  await maybePromptInitConfig(program, projectRoot, { shouldSkipConfig: false, hasExplicitConfig: false });
217
- startDashboard(String(rawOptions.host ?? "127.0.0.1"), Number(rawOptions.port ?? 8767), projectRoot, runAnalyse, !outputSuppressed(program));
268
+ const profile = typeof rawOptions.profile === "string" ? rawOptions.profile : undefined;
269
+ startDashboard(String(rawOptions.host ?? "127.0.0.1"), Number(rawOptions.port ?? 8767), projectRoot, runAnalyse, !outputSuppressed(program), profile);
218
270
  });
219
271
  }
220
272
 
@@ -261,6 +313,20 @@ function registerListCommand(program: Command): void {
261
313
  });
262
314
  }
263
315
 
316
+ // Read-only profile catalogue dump mirroring `list-rules`: text for humans, JSON for docs and audits.
317
+ // `--format` is validated by `parseSummaryFormat`, so an unsupported value fails fast as a usage error
318
+ // instead of silently coercing - the half-and-half coercion trap documented in footguns/schema-and-cli.md.
319
+ function registerListProfilesCommand(program: Command): void {
320
+ program
321
+ .command("list-profiles")
322
+ .description("List the built-in gruff profiles with their rule-count summary.")
323
+ .option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
324
+ .action((rawOptions: Record<string, unknown>) => {
325
+ const format: RuleListFormat = rawOptions.format === "json" ? "json" : "text";
326
+ writeCommandOutput(program, renderProfileList(format));
327
+ });
328
+ }
329
+
264
330
  // Read-only catalogue dump. JSON is the canonical form consumed by docs builds; text is for humans.
265
331
  // `--format` is validated by `parseSummaryFormat`; unsupported values fail fast as a usage error.
266
332
  // Optional `<ruleId>` positional switches to single-rule detail mode (M08): no-arg behaviour stays
@@ -298,6 +364,7 @@ function registerReportCommand(program: Command, runAnalyse: AnalyseRunner): voi
298
364
  .option("--output <path>", "Write report to a file.")
299
365
  .option("--config <path>", "Path to a gruff YAML config file.")
300
366
  .option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
367
+ .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
301
368
  .option("--fail-on <severity>", "Finding severity that fails the run.", "none")
302
369
  .option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
303
370
  .option("--no-baseline", "Skip auto-applying the default baseline file for this run.")
@@ -329,6 +396,7 @@ function registerSummaryCommand(program: Command, runAnalyse: AnalyseRunner): vo
329
396
  .argument("[paths...]", "Files or directories to analyse.")
330
397
  .option("--config <path>", "Path to a gruff YAML config file.")
331
398
  .option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
399
+ .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
332
400
  .option("--format <format>", "Output format: text or json.", parseSummaryFormat, "text")
333
401
  .option("--top <n>", "How many top rules and file offenders to list.", parseNonNegativeInteger, 10)
334
402
  .option("--fail-on <severity>", "Finding severity that fails the run: advisory, warning, error, or none.", "advisory")
@@ -397,21 +465,26 @@ function summaryPathLabel(paths: string[], projectRoot: string): string {
397
465
  function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>, context: NormalizeContext): AnalysisOptions {
398
466
  const format = stringChoice(rawOptions.format, ["text", "json", "html", "markdown", "github", "hotspot", "sarif"], "text");
399
467
  const failOn = stringChoice(rawOptions.failOn, ["none", "advisory", "warning", "error"], "advisory");
468
+ const diffInput = diffOption(paths, rawOptions);
400
469
  const baselineValue = rawOptions.baseline;
401
470
  const shouldSkipBaseline =
402
471
  !context.shouldAllowBaselineFlag ||
403
472
  baselineValue === false ||
404
473
  rawOptions.noBaseline === true;
405
474
  return {
406
- paths,
475
+ paths: diffInput.paths,
407
476
  ...configOption(rawOptions),
477
+ ...profileOption(rawOptions),
408
478
  shouldSkipConfig:
409
479
  rawOptions.config === false ||
410
480
  rawOptions.noConfig === true,
411
481
  format,
412
482
  failOn,
413
483
  shouldIncludeIgnored: rawOptions.includeIgnored === true,
414
- ...diffOption(rawOptions),
484
+ changedScope: stringChoice(rawOptions.changedScope, ["symbol", "hunk"], "symbol"),
485
+ ...diffInput.options,
486
+ ...changedRangesOption(rawOptions),
487
+ ...sinceOption(rawOptions),
415
488
  ...historyFileOption(rawOptions),
416
489
  ...baselineOption(baselineValue, context),
417
490
  ...generateBaselineOption(rawOptions),
@@ -425,13 +498,34 @@ function configOption(rawOptions: Record<string, unknown>): Partial<Pick<Analysi
425
498
  return typeof rawOptions.config === "string" ? { config: rawOptions.config } : {};
426
499
  }
427
500
 
428
- // `--diff` without an argument means "working-tree". A boolean `true` arrives when Commander parsed
429
- // the flag standalone; an explicit string keeps whatever ref the user passed (e.g., `main`).
430
- function diffOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "diff">> {
501
+ // Same conditional-spread discipline for `--profile`: an absent flag must stay absent (not undefined)
502
+ // so `loadConfig` falls back to the config-file `profile:` block rather than seeing an explicit CLI value.
503
+ function profileOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "profile">> {
504
+ return typeof rawOptions.profile === "string" ? { profile: rawOptions.profile } : {};
505
+ }
506
+
507
+ // `--diff` without an argument means "working-tree". `--diff -` is accepted even when Commander
508
+ // treats `-` as a positional path, so stdin-diff callers can use the documented spacing form.
509
+ function diffOption(paths: string[], rawOptions: Record<string, unknown>): { paths: string[]; options: Partial<Pick<AnalysisOptions, "diff" | "diffPatch">> } {
431
510
  if (typeof rawOptions.diff === "string") {
432
- return { diff: rawOptions.diff };
511
+ return rawOptions.diff === "-"
512
+ ? { paths, options: { diff: "-", diffPatch: readFileSync(0, "utf8") } }
513
+ : { paths, options: { diff: rawOptions.diff } };
433
514
  }
434
- return rawOptions.diff === true ? { diff: "working-tree" } : {};
515
+ if (rawOptions.diff === true && paths[0] === "-") {
516
+ return { paths: paths.slice(1), options: { diff: "-", diffPatch: readFileSync(0, "utf8") } };
517
+ }
518
+ return rawOptions.diff === true ? { paths, options: { diff: "working-tree" } } : { paths, options: {} };
519
+ }
520
+
521
+ // Preserves absence for `changedRanges`; setting it to undefined would change exact optional typing.
522
+ function changedRangesOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "changedRanges">> {
523
+ return typeof rawOptions.changedRanges === "string" ? { changedRanges: rawOptions.changedRanges } : {};
524
+ }
525
+
526
+ // Preserves absence for `since` so direct callers can distinguish no ref from an explicit ref.
527
+ function sinceOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "since">> {
528
+ return typeof rawOptions.since === "string" ? { since: rawOptions.since } : {};
435
529
  }
436
530
 
437
531
  // Conditional spread keeps `historyFile` absent rather than `undefined` under exactOptionalPropertyTypes.
@@ -293,6 +293,8 @@ function knownCliFlags(): Set<string> {
293
293
  "--baseline",
294
294
  "--config",
295
295
  "--diff",
296
+ "--changed-ranges",
297
+ "--changed-scope",
296
298
  "--fail-on",
297
299
  "--force",
298
300
  "--format",
@@ -307,9 +309,11 @@ function knownCliFlags(): Set<string> {
307
309
  "--no-interaction",
308
310
  "--output",
309
311
  "--port",
312
+ "--profile",
310
313
  "--project-root",
311
314
  "--quiet",
312
315
  "--silent",
316
+ "--since",
313
317
  "--top",
314
318
  "--verbose",
315
319
  "--version",