@blundergoat/gruff-ts 0.3.1 → 0.4.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 +19 -0
  2. package/CONTRIBUTING.md +1 -1
  3. package/README.md +20 -5
  4. package/SECURITY.md +1 -1
  5. package/docs/README.md +0 -1
  6. package/docs/agent-hook.md +14 -2
  7. package/docs/configuration.md +15 -0
  8. package/docs/reports-and-ci.md +21 -0
  9. package/docs/rules.md +22 -12
  10. package/package.json +17 -2
  11. package/src/analyser.ts +410 -122
  12. package/src/baseline-options.ts +90 -0
  13. package/src/blocks.ts +56 -9
  14. package/src/changed-regions.ts +46 -17
  15. package/src/cli-program.ts +103 -4
  16. package/src/cli.ts +3 -2
  17. package/src/constants.ts +1 -1
  18. package/src/dashboard.ts +1 -1
  19. package/src/dead-code-rules.ts +10 -3
  20. package/src/discovery.ts +27 -3
  21. package/src/findings.ts +2 -0
  22. package/src/hook-contract.ts +457 -0
  23. package/src/line-rules.ts +126 -19
  24. package/src/process-exec-metadata.ts +153 -0
  25. package/src/project-config-rules.ts +21 -8
  26. package/src/project-rules.ts +159 -42
  27. package/src/report-renderers.ts +3 -0
  28. package/src/rule-list.ts +1 -0
  29. package/src/rules.ts +5 -5
  30. package/src/sensitive-data-rules.ts +134 -12
  31. package/src/source-text.ts +47 -22
  32. package/src/static-analysis-redundant-rules.ts +46 -2
  33. package/src/types.ts +16 -1
  34. package/docs/releasing.md +0 -106
  35. package/fixtures/sample.ts +0 -21
  36. package/scripts/bump-version.sh +0 -210
  37. package/scripts/check.sh +0 -4
  38. package/scripts/dependency-install.sh +0 -96
  39. package/scripts/dependency-update.sh +0 -177
  40. package/scripts/npm-publish.sh +0 -258
  41. package/scripts/preflight-checks.sh +0 -395
  42. package/scripts/start-dev.sh +0 -8
  43. package/scripts/test-performance.sh +0 -695
  44. package/src/fixtures/rule-catalogue-security-doctrine.ts +0 -160
@@ -0,0 +1,90 @@
1
+ // Baseline option handling for `analyse`: chooses explicit/default baselines, applies
2
+ // suppression, and writes generated baselines while preserving the report metadata shape.
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { applyBaseline, DEFAULT_BASELINE, writeBaseline } from "./baseline.ts";
6
+ import { absolutize, displayPath } from "./discovery.ts";
7
+ import type { AnalysisOptions, AnalysisReport, Finding } from "./types.ts";
8
+
9
+ /*
10
+ * Result of applying a baseline (suppression) or generating a new one. The optional `baseline`
11
+ * matches the `gruff.analysis.v2` schema's baseline metadata - present only when a baseline file
12
+ * was actually used or generated, so the report stays stable across baseline-disabled runs.
13
+ */
14
+ export interface BaselineApplication {
15
+ findings: Finding[];
16
+ baseline?: NonNullable<AnalysisReport["baseline"]>;
17
+ }
18
+
19
+ // Resolved baseline path plus the provenance string emitted in the report. `source` distinguishes
20
+ // "explicit" (--baseline flag) from "default" (auto-discovered gruff-baseline.json).
21
+ interface BaselineSelection {
22
+ path: string;
23
+ source: string;
24
+ }
25
+
26
+ /*
27
+ * Three-way baseline dispatcher. `--generate-baseline` wins (writes a new file, returns findings
28
+ * unchanged); `--no-baseline` skips entirely; otherwise look for an explicit or default baseline.
29
+ * The stable identity tuple (fingerprint, ruleId, filePath) drives suppression matching.
30
+ */
31
+ export function applyBaselineOptions(projectRoot: string, options: AnalysisOptions, findings: Finding[]): BaselineApplication {
32
+ if (options.generateBaseline) {
33
+ return generateBaselineResult(projectRoot, options.generateBaseline, findings);
34
+ }
35
+
36
+ if (options.shouldSkipBaseline) {
37
+ return { findings };
38
+ }
39
+
40
+ const selected = selectedBaseline(projectRoot, options);
41
+ if (!selected) {
42
+ return { findings };
43
+ }
44
+
45
+ return applySelectedBaseline(projectRoot, selected, findings);
46
+ }
47
+
48
+ /*
49
+ * Writes the baseline file via writeBaseline and returns the report-shaped metadata. `suppressed: 0`
50
+ * because generation does not filter findings - every current finding is captured in the stable baseline.
51
+ */
52
+ function generateBaselineResult(projectRoot: string, baselineFile: string, findings: Finding[]): BaselineApplication {
53
+ const baselinePath = absolutize(projectRoot, baselineFile);
54
+ writeBaseline(baselinePath, findings);
55
+ return {
56
+ findings,
57
+ baseline: {
58
+ path: displayPath(projectRoot, baselinePath),
59
+ source: "generated",
60
+ suppressed: 0,
61
+ generated: true,
62
+ },
63
+ };
64
+ }
65
+
66
+ // Loads the baseline file and filters findings whose identity tuple matches. `suppressed` is
67
+ // computed from the size delta so the stable baseline report metadata stays accurate.
68
+ function applySelectedBaseline(projectRoot: string, selected: BaselineSelection, findings: Finding[]): BaselineApplication {
69
+ const before = findings.length;
70
+ const filteredFindings = applyBaseline(selected.path, findings);
71
+ return {
72
+ findings: filteredFindings,
73
+ baseline: {
74
+ path: displayPath(projectRoot, selected.path),
75
+ source: selected.source,
76
+ suppressed: before - filteredFindings.length,
77
+ generated: false,
78
+ },
79
+ };
80
+ }
81
+
82
+ // Picks an explicit `--baseline` path first, then the conventional `gruff-baseline.json` at the
83
+ // project root. Returning undefined means "no baseline" - the stable contract preserves report shape.
84
+ function selectedBaseline(projectRoot: string, options: AnalysisOptions): BaselineSelection | undefined {
85
+ if (options.baseline) {
86
+ return { path: absolutize(projectRoot, options.baseline), source: "explicit" };
87
+ }
88
+ const defaultBaseline = join(projectRoot, DEFAULT_BASELINE);
89
+ return existsSync(defaultBaseline) ? { path: defaultBaseline, source: "default" } : undefined;
90
+ }
package/src/blocks.ts CHANGED
@@ -87,14 +87,26 @@ export interface BlockFindingWithMetadataArgs extends BlockFindingArgs {
87
87
  // needing metadata or lower confidence go through `blockFindingWithMetadata` to keep the
88
88
  // per-rule fingerprint shape stable.
89
89
  export function blockFinding(args: BlockFindingArgs): Finding {
90
- return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, severity: args.severity, pillar: args.pillar, confidence: "high", symbol: args.block.name });
90
+ const endLine = args.block.startLine + args.block.lineCount - 1;
91
+ return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, endLine, severity: args.severity, pillar: args.pillar, confidence: "high", symbol: args.block.name });
91
92
  }
92
93
 
93
94
  // Block-anchored variant that ships rule-specific metadata. Confidence defaults to "medium"
94
95
  // because metadata-carrying rules (e.g. test-quality magic-number) report measurements rather than
95
96
  // definitive defects; the metadata payload is part of each rule's stable fingerprint contract.
96
97
  export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Finding {
97
- return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, severity: args.severity, pillar: args.pillar, confidence: "medium", symbol: args.block.name, metadata: args.metadata });
98
+ return makeFinding({
99
+ ruleId: args.ruleId,
100
+ message: args.message,
101
+ filePath: args.file.displayPath,
102
+ line: args.block.startLine,
103
+ endLine: args.block.startLine + args.block.lineCount - 1,
104
+ severity: args.severity,
105
+ pillar: args.pillar,
106
+ confidence: "medium",
107
+ symbol: args.block.name,
108
+ metadata: args.metadata,
109
+ });
98
110
  }
99
111
 
100
112
  // Computes cyclomatic and function-body once and threads them through the per-block rule pipeline.
@@ -134,7 +146,15 @@ export function analyseBlockRules(context: BlockRuleContext): void {
134
146
  function pushFunctionLengthFinding(context: BlockRuleContext): void {
135
147
  const functionLengthThreshold = threshold(context.config, "size.function-length", 200);
136
148
  if (context.block.lineCount > functionLengthThreshold) {
137
- context.findings.push(blockFinding({ ruleId: "size.function-length", message: `Function \`${context.block.name}\` has ${context.block.lineCount} lines, above the threshold of ${functionLengthThreshold}.`, file: context.file, block: context.block, severity: ruleSeverity(context.config, "size.function-length", "warning"), pillar: "size" }));
149
+ context.findings.push(blockFindingWithMetadata({
150
+ ruleId: "size.function-length",
151
+ message: `Function \`${context.block.name}\` has ${context.block.lineCount} lines, above the threshold of ${functionLengthThreshold}.`,
152
+ file: context.file,
153
+ block: context.block,
154
+ severity: ruleSeverity(context.config, "size.function-length", "warning"),
155
+ pillar: "size",
156
+ metadata: { lines: context.block.lineCount, threshold: functionLengthThreshold },
157
+ }));
138
158
  }
139
159
  }
140
160
 
@@ -142,16 +162,34 @@ function pushFunctionLengthFinding(context: BlockRuleContext): void {
142
162
  // already validated the signature shape upstream. Reports `size.parameter-count` when exceeded.
143
163
  function pushParameterCountFinding(context: BlockRuleContext): void {
144
164
  const params = context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
145
- if (params > threshold(context.config, "size.parameter-count", 7)) {
146
- context.findings.push(blockFinding({ ruleId: "size.parameter-count", message: `Function \`${context.block.name}\` declares ${params} parameters.`, file: context.file, block: context.block, severity: ruleSeverity(context.config, "size.parameter-count", "warning"), pillar: "size" }));
165
+ const parameterCountThreshold = threshold(context.config, "size.parameter-count", 7);
166
+ if (params > parameterCountThreshold) {
167
+ context.findings.push(blockFindingWithMetadata({
168
+ ruleId: "size.parameter-count",
169
+ message: `Function \`${context.block.name}\` declares ${params} parameters.`,
170
+ file: context.file,
171
+ block: context.block,
172
+ severity: ruleSeverity(context.config, "size.parameter-count", "warning"),
173
+ pillar: "size",
174
+ metadata: { parameters: params, threshold: parameterCountThreshold },
175
+ }));
147
176
  }
148
177
  }
149
178
 
150
179
  // Default threshold 15. Counts conditional keywords + boolean operators in the code body - see
151
180
  // `blockRuleContext` for the pre-computed value. Reports `complexity.cyclomatic` when exceeded.
152
181
  function pushCyclomaticFinding(context: BlockRuleContext): void {
153
- if (context.cyclomatic > threshold(context.config, "complexity.cyclomatic", 15)) {
154
- context.findings.push(blockFinding({ ruleId: "complexity.cyclomatic", message: `Function \`${context.block.name}\` has cyclomatic complexity ${context.cyclomatic}.`, file: context.file, block: context.block, severity: ruleSeverity(context.config, "complexity.cyclomatic", "warning"), pillar: "complexity" }));
182
+ const cyclomaticThreshold = threshold(context.config, "complexity.cyclomatic", 15);
183
+ if (context.cyclomatic > cyclomaticThreshold) {
184
+ context.findings.push(blockFindingWithMetadata({
185
+ ruleId: "complexity.cyclomatic",
186
+ message: `Function \`${context.block.name}\` has cyclomatic complexity ${context.cyclomatic}.`,
187
+ file: context.file,
188
+ block: context.block,
189
+ severity: ruleSeverity(context.config, "complexity.cyclomatic", "warning"),
190
+ pillar: "complexity",
191
+ metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold },
192
+ }));
155
193
  }
156
194
  }
157
195
 
@@ -159,8 +197,17 @@ function pushCyclomaticFinding(context: BlockRuleContext): void {
159
197
  // "deeply nested" intuition pure cyclomatic misses. Reports `complexity.cognitive` when exceeded.
160
198
  function pushCognitiveFinding(context: BlockRuleContext): void {
161
199
  const cognitive = context.cyclomatic + maxNestingDepth(context.block.codeBody);
162
- if (cognitive > threshold(context.config, "complexity.cognitive", 15)) {
163
- context.findings.push(blockFinding({ ruleId: "complexity.cognitive", message: `Function \`${context.block.name}\` has cognitive complexity ${cognitive}.`, file: context.file, block: context.block, severity: ruleSeverity(context.config, "complexity.cognitive", "warning"), pillar: "complexity" }));
200
+ const cognitiveThreshold = threshold(context.config, "complexity.cognitive", 15);
201
+ if (cognitive > cognitiveThreshold) {
202
+ context.findings.push(blockFindingWithMetadata({
203
+ ruleId: "complexity.cognitive",
204
+ message: `Function \`${context.block.name}\` has cognitive complexity ${cognitive}.`,
205
+ file: context.file,
206
+ block: context.block,
207
+ severity: ruleSeverity(context.config, "complexity.cognitive", "warning"),
208
+ pillar: "complexity",
209
+ metadata: { complexity: cognitive, threshold: cognitiveThreshold },
210
+ }));
164
211
  }
165
212
  }
166
213
 
@@ -17,6 +17,9 @@ export interface ChangedRegionScope {
17
17
  mode: ChangedScopeMode;
18
18
  rangesByFile: Map<string, ChangedRange[]>;
19
19
  wholeFiles: Set<string>;
20
+ // Every file that appears in the diff, including deletion-only files that contribute no target-side
21
+ // ranges. `file` scope keeps all findings in any changed file, so it consults this set, not ranges.
22
+ changedFiles: Set<string>;
20
23
  explicitRanges?: ChangedRange[];
21
24
  }
22
25
 
@@ -42,10 +45,14 @@ interface DiffParseState {
42
45
 
43
46
  const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
44
47
 
48
+ // Project-relationship rules anchor one canonical file but relate every member in `metadata.files`,
49
+ // so changed-region attribution must consult the member list, not only the anchor `filePath`.
50
+ const PROJECT_RELATIONSHIP_RULE_IDS = new Set(["design.circular-import"]);
51
+
45
52
  // Builds the changed-region scope requested by CLI options. Throws on stdin diffs missing patch text.
46
53
  export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope | undefined {
47
54
  if (options.changedRanges) {
48
- return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
55
+ return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
49
56
  }
50
57
  if (options.diffPatch !== undefined) {
51
58
  return parseUnifiedDiff(options.diffPatch, options.changedScope);
@@ -84,37 +91,56 @@ export function filterChangedFindings(
84
91
  return { findings: kept, suppressedCount };
85
92
  }
86
93
 
87
- // Keeps a finding when its own line or enclosing declaration intersects the changed scope.
94
+ // Keeps a finding when its own line, enclosing declaration, or changed-file scope intersects the change.
88
95
  function isFindingInChangedScope(
89
96
  finding: Finding,
90
97
  scope: ChangedRegionScope,
91
98
  sources: Map<string, SourceSnapshot>,
92
99
  declarationsByFile: Map<string, DeclarationRegion[]>,
93
100
  ): boolean {
101
+ if (PROJECT_RELATIONSHIP_RULE_IDS.has(finding.ruleId)) {
102
+ return projectRelationshipTouchesChange(finding, scope);
103
+ }
94
104
  if (scope.wholeFiles.has(finding.filePath)) {
95
105
  return true;
96
106
  }
107
+ // `file` scope keeps every finding in a changed file, so it must answer before the range check:
108
+ // a deletion-only edit produces no target-side ranges but still counts as touching the file.
109
+ if (scope.mode === "file") {
110
+ return scope.explicitRanges !== undefined || scope.changedFiles.has(finding.filePath);
111
+ }
97
112
  const changedRanges = rangesForFindingFile(scope, finding.filePath);
98
113
  if (changedRanges.length === 0) {
99
114
  return false;
100
115
  }
101
- if (isFileWideFinding(finding) && (scope.rangesByFile.has(finding.filePath) || scope.explicitRanges)) {
102
- return true;
103
- }
104
116
  const findingRange = { start: finding.line ?? 1, end: finding.endLine ?? finding.line ?? 1 };
105
117
  if (overlapsAny(findingRange, changedRanges)) {
106
118
  return true;
107
119
  }
108
- if (scope.mode === "hunk") {
120
+ if (scope.mode !== "symbol" || isFileWideFinding(finding)) {
109
121
  return false;
110
122
  }
111
123
  const declaration = enclosingDeclaration(finding, sources, declarationsByFile);
112
124
  return declaration !== undefined && overlapsAny(declaration, changedRanges);
113
125
  }
114
126
 
115
- // Invariant: file-wide findings are line-1 anchors kept when any hunk changes the file.
127
+ // Invariant: file-wide findings are line-1 anchors with no declaration to widen through.
116
128
  function isFileWideFinding(finding: Finding): boolean {
117
- return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1 && finding.symbol === undefined;
129
+ return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1;
130
+ }
131
+
132
+ /*
133
+ * Keeps a project-relationship finding when any member file participates in the change, matching
134
+ * the documented contract "a project relationship that includes the requested file". Explicit
135
+ * `--changed-ranges` carry no per-file information (the ranges apply to every selected file), so
136
+ * they keep these findings by construction; narrow scans already filtered them to requested files.
137
+ */
138
+ function projectRelationshipTouchesChange(finding: Finding, scope: ChangedRegionScope): boolean {
139
+ if (scope.explicitRanges !== undefined) {
140
+ return true;
141
+ }
142
+ const files = Array.isArray(finding.metadata.files) ? finding.metadata.files : [finding.filePath];
143
+ return files.some((file) => typeof file === "string" && (scope.wholeFiles.has(file) || scope.changedFiles.has(file)));
118
144
  }
119
145
 
120
146
  // Looks up explicit line ranges first because `--changed-ranges` applies to every selected file.
@@ -252,7 +278,7 @@ function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegi
252
278
 
253
279
  // Parses a unified diff into file-level and hunk-level scope.
254
280
  function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): ChangedRegionScope {
255
- const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
281
+ const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
256
282
  const state: DiffParseState = { currentFile: undefined, isNewFile: false, targetLine: undefined };
257
283
  for (const line of diffText.split(/\r?\n/)) {
258
284
  applyDiffLine(scope, state, line);
@@ -287,8 +313,11 @@ function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, l
287
313
  const path = diffPath(line.slice(4));
288
314
  state.currentFile = path === "/dev/null" ? undefined : path;
289
315
  state.targetLine = undefined;
290
- if (state.currentFile && state.isNewFile) {
291
- scope.wholeFiles.add(state.currentFile);
316
+ if (state.currentFile) {
317
+ scope.changedFiles.add(state.currentFile);
318
+ if (state.isNewFile) {
319
+ scope.wholeFiles.add(state.currentFile);
320
+ }
292
321
  }
293
322
  return true;
294
323
  }
@@ -337,17 +366,17 @@ function diffPath(rawPath: string): string {
337
366
 
338
367
  // Treats untracked files as whole-file changed because git has no hunks for them yet.
339
368
  function untrackedFileScope(changedScope: ChangedScopeMode): ChangedRegionScope {
340
- return {
341
- mode: changedScope,
342
- rangesByFile: new Map(),
343
- wholeFiles: new Set(gitOutput(["ls-files", "--others", "--exclude-standard"]).split(/\r?\n/).filter(Boolean).map((path) => path.replaceAll("\\", "/"))),
344
- };
369
+ const untracked = new Set(gitOutput(["ls-files", "--others", "--exclude-standard"]).split(/\r?\n/).filter(Boolean).map((path) => path.replaceAll("\\", "/")));
370
+ return { mode: changedScope, rangesByFile: new Map(), wholeFiles: untracked, changedFiles: new Set(untracked) };
345
371
  }
346
372
 
347
373
  // Unions staged, unstaged, and untracked scopes while whole-file changes dominate hunk ranges.
348
374
  function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMode): ChangedRegionScope {
349
- const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
375
+ const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
350
376
  for (const scope of scopes) {
377
+ for (const file of scope.changedFiles) {
378
+ merged.changedFiles.add(file);
379
+ }
351
380
  for (const file of scope.wholeFiles) {
352
381
  merged.wholeFiles.add(file);
353
382
  merged.rangesByFile.delete(file);
@@ -10,13 +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
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";
16
17
  import { exitFor } from "./scoring.ts";
17
18
  import type { AnalysisOptions, AnalysisReport, MinimumSeverityCommand } from "./types.ts";
18
19
 
19
- 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
+ };
20
24
 
21
25
  // The `report` command intentionally rejects `--baseline` because its output is meant to reflect
22
26
  // raw findings; this flag lets `normalizeOptions` enforce that without per-command branching.
@@ -101,7 +105,7 @@ function ansiEnabled(program: Command): boolean {
101
105
  }
102
106
 
103
107
  // `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.
108
+ // dependency graph; see `.goat-flow/learning-loop/lessons/verification.md` on the original cli.ts ↔ cli-program.ts cycle.
105
109
  export function buildProgram(runAnalyse: AnalyseRunner): Command {
106
110
  const program = new Command();
107
111
  configureRootProgram(program);
@@ -109,6 +113,7 @@ export function buildProgram(runAnalyse: AnalyseRunner): Command {
109
113
  registerCheckIgnoreCommand(program);
110
114
  registerCompletionCommand(program);
111
115
  registerDashboardCommand(program, runAnalyse);
116
+ registerHookCommand(program, runAnalyse);
112
117
  registerInitCommand(program);
113
118
  registerListCommand(program);
114
119
  registerListProfilesCommand(program);
@@ -184,7 +189,7 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
184
189
  .option("--changed-ranges <ranges>", "Filter findings to changed regions, for example 3-3,8-10.")
185
190
  .option("--since <ref>", "Filter findings to regions changed against a git base ref.")
186
191
  .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")
192
+ .option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", "symbol")
188
193
  .option("--history-file <path>", "Append score trend history to this JSON file.")
189
194
  .option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
190
195
  .option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
@@ -224,6 +229,59 @@ function registerCheckIgnoreCommand(program: Command): void {
224
229
  });
225
230
  }
226
231
 
232
+ // Dedicated agent-hook surface for gruff.hook.v1. It owns hook defaults (JSON, advisory exit, symbol
233
+ // attribution, no analysis baseline) and reports config failures in-band as config.error, exits 2.
234
+ function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void {
235
+ program
236
+ .command("hook")
237
+ .description("Run the gruff agent-hook contract and emit gruff.hook.v1 JSON.")
238
+ .argument("[paths...]", "Files or directories to analyse.")
239
+ .option("--format <format>", "Output format: json.", parseHookFormat, "json")
240
+ .option("--capabilities", "Print gruff.hook.v1 capability metadata and exit.")
241
+ .option("--config <path>", "Path to a gruff YAML config file.")
242
+ .option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
243
+ .option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
244
+ .option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
245
+ .option("--changed-ranges <ranges>", "Filter hook findings to changed regions, for example 3-3,8-10.")
246
+ .option("--since <ref>", "Filter hook findings to regions changed against a git base ref and compare against that ref.")
247
+ .option("--diff [mode]", "Filter hook findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
248
+ .option("--baseline <path>", "Compare hook findings against a gruff baseline JSON file using stableIdentity.")
249
+ .action((paths: string[], rawOptions: Record<string, unknown>) => {
250
+ if (rawOptions.capabilities === true) {
251
+ writeCommandOutput(program, renderHookCapabilities());
252
+ process.exitCode = 0;
253
+ return;
254
+ }
255
+ try {
256
+ const scopedOptions = hookScopedOptions(paths, rawOptions);
257
+ const currentOptions = hookCurrentOptions(scopedOptions);
258
+ writeCommandOutput(program, renderHookReport(runAnalyse, {
259
+ currentOptions,
260
+ scopedOptions,
261
+ ...hookBaselinePath(rawOptions),
262
+ ...hookDiffBase(scopedOptions),
263
+ hasChangedRegion: hasHookChangedRegion(scopedOptions),
264
+ }));
265
+ process.exitCode = 0;
266
+ } catch (error) {
267
+ if (error instanceof ConfigLoadError) {
268
+ writeCommandOutput(program, renderHookConfigError(error.message, error.suggestion));
269
+ process.exitCode = 2;
270
+ return;
271
+ }
272
+ if (error instanceof Error) {
273
+ // Keep gruff.hook.v1 machine-readable: baseline IO/parse/schema failures and git errors
274
+ // (--diff/--since outside a repo) report in-band as config.error with exit 2 instead of
275
+ // crashing with a raw stack and empty stdout, which would break the always-JSON contract.
276
+ writeCommandOutput(program, renderHookConfigError(error.message, "Check the --baseline path and schema, and run --diff/--since inside a git repository."));
277
+ process.exitCode = 2;
278
+ return;
279
+ }
280
+ throw error;
281
+ }
282
+ });
283
+ }
284
+
227
285
  // Minimal AnalysisOptions for `check-ignore`: only the fields `loadConfig` and the ignore engine
228
286
  // read. `--config` / `--no-config` resolve identically to `analyse`; `shouldIncludeIgnored` is false
229
287
  // so default and gitignore matches are reported (config `paths.ignore` is reported regardless).
@@ -438,6 +496,15 @@ function parseSummaryFormat(rawFormat: string): "text" | "json" {
438
496
  throw new InvalidArgumentError("must be text or json");
439
497
  }
440
498
 
499
+ // Hook mode is a JSON-only contract. The parser is explicit so an unknown format value is caught
500
+ // before analysis: it throws InvalidArgumentError so commander reports a usage error.
501
+ function parseHookFormat(rawFormat: string): "json" {
502
+ if (rawFormat === "json") {
503
+ return rawFormat;
504
+ }
505
+ throw new InvalidArgumentError("must be json");
506
+ }
507
+
441
508
  /*
442
509
  * Commander argParser for `--top`-style numeric flags. Throws `InvalidArgumentError` on non-integer
443
510
  * or negative input so commander reports a usage error and exits non-zero before the command runs.
@@ -481,7 +548,7 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
481
548
  format,
482
549
  failOn,
483
550
  shouldIncludeIgnored: rawOptions.includeIgnored === true,
484
- changedScope: stringChoice(rawOptions.changedScope, ["symbol", "hunk"], "symbol"),
551
+ changedScope: stringChoice(rawOptions.changedScope, ["symbol", "hunk", "file"], "symbol"),
485
552
  ...diffInput.options,
486
553
  ...changedRangesOption(rawOptions),
487
554
  ...sinceOption(rawOptions),
@@ -492,6 +559,38 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
492
559
  };
493
560
  }
494
561
 
562
+ // Builds the scoped (changed-region) analysis options for the hook: JSON output, no fail-on gate,
563
+ // symbol scope, and no analysis baseline.
564
+ function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
565
+ return normalizeOptions(
566
+ paths,
567
+ { ...rawOptions, format: "json", failOn: "none", changedScope: "symbol", noBaseline: true },
568
+ { shouldAllowBaselineFlag: false },
569
+ );
570
+ }
571
+
572
+ // Strips changed-region selectors so the hook's full-scan pass sees the whole file, used for
573
+ // new-file and project-finding detection.
574
+ function hookCurrentOptions(options: AnalysisOptions): AnalysisOptions {
575
+ const { changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, since: _since, ...rest } = options;
576
+ return { ...rest, shouldSkipBaseline: true };
577
+ }
578
+
579
+ // True when any changed-region selector (ranges, diff, since, stdin patch) is active for the run.
580
+ function hasHookChangedRegion(options: AnalysisOptions): boolean {
581
+ return Boolean(options.changedRanges || options.diff || options.since || options.diffPatch);
582
+ }
583
+
584
+ // Extracts the --baseline path for the hook's new-only filtering against the stable baseline contract.
585
+ function hookBaselinePath(rawOptions: Record<string, unknown>): Partial<{ baselinePath: string }> {
586
+ return typeof rawOptions.baseline === "string" ? { baselinePath: rawOptions.baseline } : {};
587
+ }
588
+
589
+ // Picks the diff or since ref the hook compares against for new-only filtering, when one is set.
590
+ function hookDiffBase(options: AnalysisOptions): Partial<{ diffBase: string }> {
591
+ return options.diff ? { diffBase: options.diff } : options.since ? { diffBase: options.since } : {};
592
+ }
593
+
495
594
  // Conditional spreads (not `config: undefined`) because `AnalysisOptions` runs under
496
595
  // `exactOptionalPropertyTypes` - the absent and `undefined` cases are not interchangeable.
497
596
  function configOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "config">> {
package/src/cli.ts CHANGED
@@ -3,14 +3,15 @@
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
+ const buildProgram = (): ReturnType<typeof buildCliProgram> => buildCliProgram(analyseRunner);
14
15
 
15
16
  if (import.meta.url === pathToFileURL(argv[1] ?? "").href) {
16
17
  // Action handlers in cli-program.ts are async (await maybePromptInitConfig). parseAsync is
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.1";
2
+ const VERSION = "0.4.0";
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);
@@ -7,13 +7,20 @@ import { escapeRegex, finding } from "./findings-helpers.ts";
7
7
  import { byteLine, countMatches } from "./text-scans.ts";
8
8
  import type { Finding } from "./types.ts";
9
9
 
10
- // Deliberately single-file and low confidence because private methods can still be reached by
11
- // tests, decorators, framework hooks, or string-based reflection; reports stable advisory findings because removal still needs human confirmation.
10
+ /*
11
+ * Single-file, low-confidence dead-code pass. Contract invariant: removal candidates stay advisory
12
+ * because tests, decorators, framework hooks, or reflection may still reach a private method. It
13
+ * reports findings only and never throws for malformed snippets. Why two evidence counts:
14
+ * declarations contribute to `name(` matches, while bare method references such as `items.map(this.double)`
15
+ * appear only as `this.name` / `this?.name`, and either shape is enough usage evidence to suppress
16
+ * the finding. The reference count requires a `this` receiver so unrelated properties that share
17
+ * the name (for example `settings.refresh`) cannot mask a genuinely unused private method.
18
+ */
12
19
  export function analyseDeadCode(file: SourceFile, source: string, findings: Finding[]): void {
13
20
  for (const match of source.matchAll(/\bprivate\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/g)) {
14
21
  const name = match[1] ?? "";
15
22
  const escaped = escapeRegex(name);
16
- if (countMatches(source, new RegExp(`${escaped}\\s*\\(`, "g")) <= 1) {
23
+ if (countMatches(source, new RegExp(`${escaped}\\s*\\(`, "g")) <= 1 && countMatches(source, new RegExp(`\\bthis\\??\\.${escaped}\\b`, "g")) === 0) {
17
24
  findings.push(
18
25
  makeFinding({
19
26
  ruleId: "dead-code.unused-private-method",
package/src/discovery.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Filesystem discovery, ignore-policy matching, and display-path normalization for deterministic scans.
2
2
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { basename, dirname, extname, isAbsolute, join, relative } from "node:path";
4
- import type { AnalysisOptions, Config, IgnoreSource, SkippedPath } from "./types.ts";
4
+ import type { AnalysisOptions, Config, IgnoreSource, ScanSurfaceNote, SkippedPath } from "./types.ts";
5
5
 
6
6
  // `absolutePath` is what `node:fs` operates on; `displayPath` is the project-relative POSIX form
7
7
  // embedded in findings and baselines. They must stay aligned - diverging them breaks fingerprint stability.
@@ -22,12 +22,15 @@ interface SourceDiscovery {
22
22
  // Public discovery result. `files` are sorted by display path and deduped; `ignoredPaths` (the
23
23
  // back-compatible string[] of excluded paths) and `skipped` (the same paths enriched with ignore
24
24
  // source + matched pattern) are sorted so reports stay deterministic even when the underlying
25
- // filesystem returns directory entries in arbitrary order.
25
+ // filesystem returns directory entries in arbitrary order. `notes` carries one entry per requested
26
+ // input that exists but contributed zero analysable files, so an all-skipped scan is never a
27
+ // silent zero-finding success.
26
28
  export interface SourceDiscoveryResult {
27
29
  files: SourceFile[];
28
30
  missingPaths: string[];
29
31
  ignoredPaths: string[];
30
32
  skipped: SkippedPath[];
33
+ notes: ScanSurfaceNote[];
31
34
  }
32
35
 
33
36
  // A single line from a `.gitignore`. The combination of `isAnchored`, `isDirectoryOnly`, and `hasSlash`
@@ -47,14 +50,35 @@ interface GitIgnoreRule {
47
50
  export function discoverSources(projectRoot: string, options: AnalysisOptions, config: Config): SourceDiscoveryResult {
48
51
  const discovery: SourceDiscovery = { files: [], missingPaths: [], skipped: new Map<string, SkippedPath>() };
49
52
  const inputs = options.paths.length > 0 ? options.paths : ["."];
53
+ const notes: ScanSurfaceNote[] = [];
50
54
 
51
55
  for (const input of inputs) {
56
+ const filesBefore = discovery.files.length;
57
+ const missingBefore = discovery.missingPaths.length;
58
+ const skippedBefore = discovery.skipped.size;
52
59
  discoverSourceInput(projectRoot, input, options, config, discovery);
60
+ if (discovery.missingPaths.length === missingBefore && discovery.files.length === filesBefore) {
61
+ notes.push(zeroFileInputNote(input, discovery.skipped.size - skippedBefore));
62
+ }
53
63
  }
54
64
 
55
65
  discovery.files.sort((left, right) => left.displayPath.localeCompare(right.displayPath));
56
66
  const skipped = [...discovery.skipped.values()].sort((left, right) => left.path.localeCompare(right.path));
57
- return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped };
67
+ return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped, notes };
68
+ }
69
+
70
+ // A requested input that exists but contributed no analysable files is a per-input note, never a
71
+ // diagnostic - exit codes stay unchanged. The skip count names the likely cause (parent gitignore
72
+ // or config ignore rules hiding the whole subtree) so the caller does not read 0 findings as clean.
73
+ function zeroFileInputNote(input: string, skippedCount: number): ScanSurfaceNote {
74
+ const cause = skippedCount > 0
75
+ ? `${skippedCount} path(s) under it were excluded by ignore rules`
76
+ : "it contains no analysable source files";
77
+ return {
78
+ noteType: "no-analysable-files",
79
+ path: input,
80
+ message: `Requested path '${input}' was not analysed: ${cause}. 0 findings here does not mean the path is clean.`,
81
+ };
58
82
  }
59
83
 
60
84
  // Resolves the input against `node:fs`. Missing inputs go into `missingPaths` so the CLI can
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: [],