@blundergoat/gruff-ts 0.3.0 → 0.3.2

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.
@@ -10,6 +10,7 @@ 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
14
  import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
14
15
  import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
15
16
  import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderProfileList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
@@ -101,7 +102,7 @@ function ansiEnabled(program: Command): boolean {
101
102
  }
102
103
 
103
104
  // `runAnalyse` is injected rather than imported to keep `cli-program.ts` off the analyser's
104
- // dependency graph; see `.goat-flow/lessons/verification.md` on the original cli.ts ↔ cli-program.ts cycle.
105
+ // dependency graph; see `.goat-flow/learning-loop/lessons/verification.md` on the original cli.ts ↔ cli-program.ts cycle.
105
106
  export function buildProgram(runAnalyse: AnalyseRunner): Command {
106
107
  const program = new Command();
107
108
  configureRootProgram(program);
@@ -109,6 +110,7 @@ export function buildProgram(runAnalyse: AnalyseRunner): Command {
109
110
  registerCheckIgnoreCommand(program);
110
111
  registerCompletionCommand(program);
111
112
  registerDashboardCommand(program, runAnalyse);
113
+ registerHookCommand(program, runAnalyse);
112
114
  registerInitCommand(program);
113
115
  registerListCommand(program);
114
116
  registerListProfilesCommand(program);
@@ -126,7 +128,7 @@ function configureRootProgram(program: Command): void {
126
128
  .name("gruff-ts")
127
129
  .usage("command [options] [arguments]")
128
130
  .helpOption("-h, --help", "Display help for the given command. When no command is given display help for the list command")
129
- .version(VERSION, "-V, --version", "Display this application version")
131
+ .version(`gruff-ts ${VERSION}`, "-V, --version", "Display this application version")
130
132
  .option("--silent", "Do not output any message")
131
133
  .option("-q, --quiet", "Only errors are displayed. All other output is suppressed")
132
134
  .option("--ansi", "Force ANSI output")
@@ -184,7 +186,7 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
184
186
  .option("--changed-ranges <ranges>", "Filter findings to changed regions, for example 3-3,8-10.")
185
187
  .option("--since <ref>", "Filter findings to regions changed against a git base ref.")
186
188
  .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")
189
+ .option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", "symbol")
188
190
  .option("--history-file <path>", "Append score trend history to this JSON file.")
189
191
  .option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
190
192
  .option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
@@ -224,6 +226,59 @@ function registerCheckIgnoreCommand(program: Command): void {
224
226
  });
225
227
  }
226
228
 
229
+ // Dedicated agent-hook surface for gruff.hook.v1. It owns hook defaults (JSON, advisory exit, symbol
230
+ // attribution, no analysis baseline) and reports config failures in-band as config.error, exits 2.
231
+ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void {
232
+ program
233
+ .command("hook")
234
+ .description("Run the gruff agent-hook contract and emit gruff.hook.v1 JSON.")
235
+ .argument("[paths...]", "Files or directories to analyse.")
236
+ .option("--format <format>", "Output format: json.", parseHookFormat, "json")
237
+ .option("--capabilities", "Print gruff.hook.v1 capability metadata and exit.")
238
+ .option("--config <path>", "Path to a gruff YAML config file.")
239
+ .option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
240
+ .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
241
+ .option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
242
+ .option("--changed-ranges <ranges>", "Filter hook findings to changed regions, for example 3-3,8-10.")
243
+ .option("--since <ref>", "Filter hook findings to regions changed against a git base ref and compare against that ref.")
244
+ .option("--diff [mode]", "Filter hook findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
245
+ .option("--baseline <path>", "Compare hook findings against a gruff baseline JSON file using stableIdentity.")
246
+ .action((paths: string[], rawOptions: Record<string, unknown>) => {
247
+ if (rawOptions.capabilities === true) {
248
+ writeCommandOutput(program, renderHookCapabilities());
249
+ process.exitCode = 0;
250
+ return;
251
+ }
252
+ try {
253
+ const scopedOptions = hookScopedOptions(paths, rawOptions);
254
+ const currentOptions = hookCurrentOptions(scopedOptions);
255
+ writeCommandOutput(program, renderHookReport(runAnalyse, {
256
+ currentOptions,
257
+ scopedOptions,
258
+ ...hookBaselinePath(rawOptions),
259
+ ...hookDiffBase(scopedOptions),
260
+ hasChangedRegion: hasHookChangedRegion(scopedOptions),
261
+ }));
262
+ process.exitCode = 0;
263
+ } catch (error) {
264
+ if (error instanceof ConfigLoadError) {
265
+ writeCommandOutput(program, renderHookConfigError(error.message, error.suggestion));
266
+ process.exitCode = 2;
267
+ return;
268
+ }
269
+ if (error instanceof Error) {
270
+ // Keep gruff.hook.v1 machine-readable: baseline IO/parse/schema failures and git errors
271
+ // (--diff/--since outside a repo) report in-band as config.error with exit 2 instead of
272
+ // crashing with a raw stack and empty stdout, which would break the always-JSON contract.
273
+ writeCommandOutput(program, renderHookConfigError(error.message, "Check the --baseline path and schema, and run --diff/--since inside a git repository."));
274
+ process.exitCode = 2;
275
+ return;
276
+ }
277
+ throw error;
278
+ }
279
+ });
280
+ }
281
+
227
282
  // Minimal AnalysisOptions for `check-ignore`: only the fields `loadConfig` and the ignore engine
228
283
  // read. `--config` / `--no-config` resolve identically to `analyse`; `shouldIncludeIgnored` is false
229
284
  // so default and gitignore matches are reported (config `paths.ignore` is reported regardless).
@@ -438,6 +493,15 @@ function parseSummaryFormat(rawFormat: string): "text" | "json" {
438
493
  throw new InvalidArgumentError("must be text or json");
439
494
  }
440
495
 
496
+ // Hook mode is a JSON-only contract. The parser is explicit so an unknown format value is caught
497
+ // before analysis: it throws InvalidArgumentError so commander reports a usage error.
498
+ function parseHookFormat(rawFormat: string): "json" {
499
+ if (rawFormat === "json") {
500
+ return rawFormat;
501
+ }
502
+ throw new InvalidArgumentError("must be json");
503
+ }
504
+
441
505
  /*
442
506
  * Commander argParser for `--top`-style numeric flags. Throws `InvalidArgumentError` on non-integer
443
507
  * or negative input so commander reports a usage error and exits non-zero before the command runs.
@@ -481,7 +545,7 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
481
545
  format,
482
546
  failOn,
483
547
  shouldIncludeIgnored: rawOptions.includeIgnored === true,
484
- changedScope: stringChoice(rawOptions.changedScope, ["symbol", "hunk"], "symbol"),
548
+ changedScope: stringChoice(rawOptions.changedScope, ["symbol", "hunk", "file"], "symbol"),
485
549
  ...diffInput.options,
486
550
  ...changedRangesOption(rawOptions),
487
551
  ...sinceOption(rawOptions),
@@ -492,6 +556,38 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
492
556
  };
493
557
  }
494
558
 
559
+ // Builds the scoped (changed-region) analysis options for the hook: JSON output, no fail-on gate,
560
+ // symbol scope, and no analysis baseline.
561
+ function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
562
+ return normalizeOptions(
563
+ paths,
564
+ { ...rawOptions, format: "json", failOn: "none", changedScope: "symbol", noBaseline: true },
565
+ { shouldAllowBaselineFlag: false },
566
+ );
567
+ }
568
+
569
+ // Strips changed-region selectors so the hook's full-scan pass sees the whole file, used for
570
+ // new-file and project-finding detection.
571
+ function hookCurrentOptions(options: AnalysisOptions): AnalysisOptions {
572
+ const { changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, since: _since, ...rest } = options;
573
+ return { ...rest, shouldSkipBaseline: true };
574
+ }
575
+
576
+ // True when any changed-region selector (ranges, diff, since, stdin patch) is active for the run.
577
+ function hasHookChangedRegion(options: AnalysisOptions): boolean {
578
+ return Boolean(options.changedRanges || options.diff || options.since || options.diffPatch);
579
+ }
580
+
581
+ // Extracts the --baseline path for the hook's new-only filtering against the stable baseline contract.
582
+ function hookBaselinePath(rawOptions: Record<string, unknown>): Partial<{ baselinePath: string }> {
583
+ return typeof rawOptions.baseline === "string" ? { baselinePath: rawOptions.baseline } : {};
584
+ }
585
+
586
+ // Picks the diff or since ref the hook compares against for new-only filtering, when one is set.
587
+ function hookDiffBase(options: AnalysisOptions): Partial<{ diffBase: string }> {
588
+ return options.diff ? { diffBase: options.diff } : options.since ? { diffBase: options.since } : {};
589
+ }
590
+
495
591
  // Conditional spreads (not `config: undefined`) because `AnalysisOptions` runs under
496
592
  // `exactOptionalPropertyTypes` - the absent and `undefined` cases are not interchangeable.
497
593
  function configOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "config">> {
@@ -59,7 +59,7 @@ export function analyseCommentQualityRules(input: CommentQualityRuleInput): void
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);
62
- pushFixturePurposeFindings({ file, source, codeSource, lines, comments, blocks, config, findings });
62
+ pushFixturePurposeFindings({ file, source, codeSource, lines, comments, blocks, findings });
63
63
  }
64
64
 
65
65
  /*
package/src/constants.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Shared release constants that keep CLI, reports, and rule catalogue output in sync.
2
- const VERSION = "0.3.0";
2
+ const VERSION = "0.3.2";
3
3
 
4
4
  /*
5
5
  * Threshold at which the `analyse` text renderer appends a one-line pointer to `gruff-ts summary`.
package/src/dashboard.ts CHANGED
@@ -24,7 +24,7 @@ interface DashboardRouteInput {
24
24
  }
25
25
 
26
26
  // Starts a loopback HTTP server. `analyse` is injected (not imported) to avoid a circular import
27
- // back into `cli.ts`; see `.goat-flow/lessons/verification.md` on the dashboard import cycle.
27
+ // back into `cli.ts`; see `.goat-flow/learning-loop/lessons/verification.md` on the dashboard import cycle.
28
28
  // Side effect: opens a listening socket and writes the URL to stdout unless `shouldWriteOutput` is false.
29
29
  function startDashboard(host: string, port: number, projectRoot: string, analyse: DashboardAnalyse, shouldWriteOutput = true, profile?: string): void {
30
30
  assertLoopbackHost(host);
package/src/findings.ts CHANGED
@@ -9,6 +9,7 @@ interface FindingInput {
9
9
  message: string;
10
10
  filePath: string;
11
11
  line?: number;
12
+ endLine?: number;
12
13
  severity: Severity;
13
14
  pillar: Pillar;
14
15
  confidence: Confidence;
@@ -30,6 +31,7 @@ function makeFinding(input: FindingInput): Finding {
30
31
  message: input.message,
31
32
  filePath: input.filePath,
32
33
  ...(input.line ? { line: input.line } : {}),
34
+ ...(input.endLine ? { endLine: input.endLine } : {}),
33
35
  severity: input.severity,
34
36
  pillar: input.pillar,
35
37
  secondaryPillars: [],
@@ -39,7 +41,17 @@ function makeFinding(input: FindingInput): Finding {
39
41
  ...(input.remediation ? { remediation: input.remediation } : {}),
40
42
  metadata: input.metadata ?? {},
41
43
  fingerprint,
44
+ stableIdentity: stableIdentityFor(input),
42
45
  };
43
46
  }
44
47
 
48
+ // Stable, line-insensitive identity for external diff tooling; fingerprint remains line-sensitive.
49
+ function stableIdentityFor(input: FindingInput): string {
50
+ const symbolOrMessage = input.symbol && input.symbol.length > 0 ? input.symbol : input.message;
51
+ return createHash("sha256")
52
+ .update([input.ruleId, input.filePath, symbolOrMessage].join("\0"))
53
+ .digest("hex")
54
+ .slice(0, 16);
55
+ }
56
+
45
57
  export { makeFinding };
@@ -3,11 +3,10 @@
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
5
  import { type CommentRecord } from "./comment-scanner.ts";
6
- import { threshold } from "./config.ts";
7
6
  import { type SourceFile } from "./discovery.ts";
8
7
  import { makeFinding } from "./findings.ts";
9
8
  import { isFixtureLikePath, isTestPath } from "./project-rules.ts";
10
- import type { Config, Finding } from "./types.ts";
9
+ import type { Finding } from "./types.ts";
11
10
 
12
11
  // Below 12 lines, a fixture is short enough to read at a glance - requiring a purpose header
13
12
  // would just be noise; above this threshold, the next reader needs the intent spelled out.
@@ -34,18 +33,17 @@ export interface FixturePurposeInput {
34
33
  lines: string[];
35
34
  comments: CommentRecord[];
36
35
  blocks: FunctionBlock[];
37
- config: Config;
38
36
  findings: Finding[];
39
37
  }
40
38
 
41
39
  // Test/fixture paths only - gated up front so production source never reports fixture-purpose
42
40
  // findings. Reports the stable `docs.fixture-purpose-missing` finding for each candidate.
43
41
  export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
44
- const { file, source, codeSource, lines, comments, blocks, config, findings } = input;
42
+ const { file, source, codeSource, lines, comments, blocks, findings } = input;
45
43
  if (!isTestPath(file.displayPath) && !isFixtureLikePath(file.displayPath)) {
46
44
  return;
47
45
  }
48
- for (const candidate of fixturePurposeCandidates(source, codeSource, blocks, config)) {
46
+ for (const candidate of fixturePurposeCandidates(source, codeSource, blocks)) {
49
47
  if (hasFixturePurposeComment(lines, comments, candidate.line)) {
50
48
  continue;
51
49
  }
@@ -71,7 +69,7 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
71
69
 
72
70
  // Three candidate kinds collected in one pass: template-literal fixtures, generated array fixtures,
73
71
  // and test setup blocks. `occupiedLines` tracks the first two so the third doesn't double-report.
74
- function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[], config: Config): FixturePurposeCandidate[] {
72
+ function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[]): FixturePurposeCandidate[] {
75
73
  if (!hasFixturePurposeCandidateSignal(codeSource, blocks)) {
76
74
  return [];
77
75
  }
@@ -96,7 +94,7 @@ function fixturePurposeCandidates(source: string, codeSource: string, blocks: Fu
96
94
  }
97
95
  });
98
96
 
99
- for (const candidate of fixtureTestBlockCandidates(blocks, config, occupiedLines)) {
97
+ for (const candidate of fixtureTestBlockCandidates(blocks, occupiedLines)) {
100
98
  pushUniqueFixturePurposeCandidate(candidates, seen, candidate);
101
99
  }
102
100
 
@@ -178,14 +176,14 @@ function generatedFixtureCandidate(rawLine: string, codeLine: string, lineNumber
178
176
 
179
177
  // Test blocks with high setup-line counts AND a fixture-shape signal. Excludes blocks whose setup
180
178
  // already produced a template-literal or generated-array candidate at the same line.
181
- function fixtureTestBlockCandidates(blocks: FunctionBlock[], config: Config, occupiedLines: Set<number>): FixturePurposeCandidate[] {
179
+ function fixtureTestBlockCandidates(blocks: FunctionBlock[], occupiedLines: Set<number>): FixturePurposeCandidate[] {
182
180
  const candidates: FixturePurposeCandidate[] = [];
183
181
  for (const block of blocks) {
184
182
  if (!block.isTest || fixtureLineInsideBlock(block, occupiedLines)) {
185
183
  continue;
186
184
  }
187
185
  const setupLines = setupLineCount(block.codeBody);
188
- if (setupLines <= threshold(config, "test-quality.setup-bloat", 12) || !hasFixtureSetupSignal(block.codeBody)) {
186
+ if (setupLines <= FIXTURE_PURPOSE_MIN_LINES || !hasFixtureSetupSignal(block.codeBody)) {
189
187
  continue;
190
188
  }
191
189
  candidates.push({