@blundergoat/gruff-ts 0.5.0 → 0.6.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 (77) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
@@ -1,14 +1,20 @@
1
- // gruff.hook.v1 adapter: owns the agent-hook JSON shape without changing gruff.analysis.v2.
1
+ // Builds the JSON response that a coding agent receives from `gruff-ts hook`.
2
+ //
3
+ // Compares the user's edit with a Git base or reviewed baseline when one is supplied.
4
+ // Uses published findings and diagnostics to decide whether the edit can proceed.
2
5
  import { execFileSync } from "node:child_process";
3
6
  import { createHash } from "node:crypto";
4
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
8
  import { dirname, join } from "node:path";
6
9
  import { chdir, cwd } from "node:process";
7
10
  import { tmpdir } from "node:os";
8
- import { absolutize } from "./discovery.ts";
11
+ import { applyBaseline, BASELINE_SCHEMA_VERSION } from "./baseline-file.ts";
12
+ import { defaultConfigPath } from "./config.ts";
13
+ import { absolutize, displayPath } from "./discovery.ts";
9
14
  import { VERSION } from "./constants.ts";
15
+ import { BUILT_IN_PROFILES } from "./profiles.ts";
10
16
  import { ruleDescriptors } from "./rules.ts";
11
- import type { AnalysisOptions, AnalysisReport, Finding, Severity, SkippedPath } from "./types.ts";
17
+ import type { AnalysisOptions, AnalysisReport, Confidence, Finding, RunDiagnostic, Severity, SkippedPath, SuppressionSummary } from "./types.ts";
12
18
 
13
19
  type HookScope = "line" | "symbol" | "file" | "project";
14
20
  type FlagOrder = "any" | "flags-before-path";
@@ -24,104 +30,192 @@ interface HookReportInput {
24
30
  scopedOptions: AnalysisOptions;
25
31
  baselinePath?: string;
26
32
  diffBase?: string;
33
+ isDiffExplicitRef?: boolean;
27
34
  hasChangedRegion: boolean;
28
35
  }
29
36
 
30
- // The gruff.hook.v1 envelope written to stdout; field names are the cross-analyzer contract.
37
+ /*
38
+ * What the caller asked the hook to block on, read once the payload is built.
39
+ *
40
+ * Every field is a gate rather than a filter: nothing here changes what the agent is shown, only whether the
41
+ * edit is allowed to stand.
42
+ */
43
+ export interface HookExitGate {
44
+ failOn: Severity | "none";
45
+ minConfidence: Confidence;
46
+ shouldFailOnNew: boolean;
47
+ shouldFailOnDiagnostics: boolean;
48
+ }
49
+
50
+ // The gruff.hook.v2 envelope written to stdout; field names are the cross-analyzer contract.
31
51
  interface HookReport {
32
- contractVersion: "gruff.hook.v1";
52
+ contractVersion: "gruff.hook.v2";
33
53
  analyzer: { name: "gruff-ts"; version: string };
54
+ // Audit data a consumer needs to trust the verdict: what ran, over what, and against which baseline.
55
+ run: HookRun;
34
56
  findings: HookFinding[];
35
- // File-scoped parse/read diagnostics relevant to the analysed change, reported in-band. The
36
- // default hook exit stays 0; only an explicit --fail-on-diagnostics run turns these into exit 2.
57
+ // File-scoped parse/read diagnostics relevant to the analysed change, reported in-band. A parse diagnostic keeps
58
+ // the default hook exit at 0 unless --fail-on-diagnostics turns it into 1; a missing or unreadable input exits 2.
37
59
  diagnostics: HookDiagnostic[];
38
60
  suppressed: { count: number };
61
+ // The section 13a audit: one row per configured sensitive exclusion this run applied.
62
+ suppressions: HookSuppression[];
39
63
  ignored: { paths: SkippedPath[] };
40
- config: { schemaOk: boolean; error: string | null };
64
+ config: { schemaOk: boolean; error: HookConfigError | null };
65
+ }
66
+
67
+ /*
68
+ * What one hook run was asked to do, so a clean payload is never ambiguous.
69
+ *
70
+ * Without it a run that analysed nothing and a run that found nothing look identical on the wire.
71
+ * Stable contract: every field is present on every run, and `analysedFiles` reports zero rather than omitting itself.
72
+ */
73
+ interface HookRun {
74
+ mode: "changed-ranges" | "diff" | "since" | "full";
75
+ scope: "symbol" | "hunk" | "file";
76
+ paths: string[];
77
+ analysedFiles: number;
78
+ baseline: { applied: boolean; schemaVersion: string | null; path: string | null };
41
79
  }
42
80
 
43
- // One diagnostic projected into the hook contract: what kind of problem, where, and the message a
44
- // consumer can surface. `file`/`line` are absent for operational diagnostics with no anchor.
81
+ // A configuration failure the consumer can act on; never a bare string, so the fix is machine-readable too.
82
+ interface HookConfigError {
83
+ message: string;
84
+ remediation: string;
85
+ }
86
+
87
+ // One configured sensitive exclusion and what it removed from this run, per section 13a.
88
+ interface HookSuppression {
89
+ rule: string;
90
+ path: string;
91
+ symbol?: string;
92
+ reason: string;
93
+ suppressed: number;
94
+ source?: "built-in" | "inline" | "duplicate";
95
+ }
96
+
97
+ // One diagnostic projected into the hook contract: what kind of problem, how much it matters, where, and the
98
+ // message a consumer can surface. `file`/`line` are absent for operational diagnostics with no anchor.
45
99
  interface HookDiagnostic {
46
100
  type: string;
101
+ severity: "info" | "warning" | "fatal";
47
102
  message: string;
48
103
  file?: string;
49
104
  line?: number;
105
+ invalidatesRun?: false;
50
106
  }
51
107
 
52
- // A finding projected into the hook contract, with enum scope and non-null remediation, keyed for
53
- // new-only tracking by the stable identity and fingerprint.
108
+ // A finding projected into the hook contract, with enum scope and non-null remediation, named by the ratified
109
+ // family identity and keyed for new-only tracking by the port-local fingerprint.
54
110
  interface HookFinding {
55
111
  ruleId: string;
56
112
  pillar: string;
57
113
  severity: Severity;
114
+ confidence: Confidence;
58
115
  scope: HookScope;
59
116
  file: string;
60
117
  line?: number;
118
+ // The last line of the finding's span, equal to `line` for a single-line finding; a consumer cannot guess it.
61
119
  endLine?: number;
62
120
  // One-based match column, present when the scanner pinpointed the occurrence. Two secrets on one
63
121
  // line share every other field, so this is the only thing that lets a consumer tell them apart.
64
122
  column?: number;
65
123
  symbol: string | null;
124
+ // The 1-based declaration ordinal the identity hashed, and 0 when the finding names no symbol.
125
+ symbolOrdinal: number;
66
126
  message: string;
67
127
  remediation: string;
68
128
  metadata: Record<string, unknown>;
69
- stableIdentity: string;
129
+ // The ratified family identity, and null for a sensitive finding, which the identity contract never names.
130
+ stableIdentity: string | null;
131
+ // What an applied baseline made of this finding, and null when no baseline was applied.
132
+ baselineStatus: string | null;
70
133
  fingerprint: string;
71
134
  }
72
135
 
73
- // A gruff.baseline.v1 entry as read for new-only comparison; every field is optional because older
74
- // baselines predate stableIdentity.
75
- interface BaselineEntry {
76
- stableIdentity?: string;
77
- ruleId?: string;
78
- filePath?: string;
79
- symbol?: string;
80
- message?: string;
81
- }
136
+ // What a baseline made of each finding this run produced, so the payload can report a status per finding.
137
+ type HookBaselineStatuses = Map<string, string>;
82
138
 
83
- const HOOK_CONTRACT_VERSION = "gruff.hook.v1";
139
+ const HOOK_CONTRACT_VERSION = "gruff.hook.v2";
84
140
  const FILE_SCOPE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
85
141
  const PROJECT_SCOPE_RULE_IDS = new Set(["design.circular-import"]);
86
142
  const SEVERITY_RANK: Record<Severity, number> = { error: 0, warning: 1, advisory: 2 };
143
+ // Gate order, loosest last: a finding at or above the requested floor reaches the gate.
144
+ const SEVERITY_GATE_RANK: Record<Severity, number> = { error: 2, warning: 1, advisory: 0 };
145
+ const CONFIDENCE_GATE_RANK: Record<Confidence, number> = { high: 2, medium: 1, low: 0 };
87
146
  const DESCRIPTORS = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor]));
88
-
89
- // Emits the gruff.hook.v1 capability handshake so a consumer can resolve flag names before a real
90
- // request; the advertised supports/flags object is the stable gruff.hook.v1 contract.
147
+ // Every number a finding's subject can carry after its symbol; the trailing group is the declaration ordinal.
148
+ const TRAILING_ORDINAL = /#(\d+)$/u;
149
+ const CONFIG_ERROR_REMEDIATION = "Fix the reported problem in .gruff-ts.yaml, or pass --no-config to run without it.";
150
+
151
+ /**
152
+ * Builds the `gruff.hook.v2` capability handshake so consumers can use its stable `supports` and `flags` fields before requesting analysis.
153
+ *
154
+ * @returns Pretty-printed JSON with a trailing newline advertising contract version, analyzer info, supported features, and CLI flags.
155
+ */
91
156
  export function renderHookCapabilities(): string {
92
157
  return JSON.stringify({
93
158
  contractVersion: HOOK_CONTRACT_VERSION,
94
159
  analyzer: analyzerInfo(),
95
160
  supports: {
96
- changedRanges: true,
97
- diff: true,
98
161
  baseline: true,
99
- scopeField: true,
100
- metadata: true,
101
- stableIdentity: true,
102
- ignoreReport: true,
103
- newOnly: true,
162
+ baselineV3: true,
163
+ changedRanges: true,
164
+ confidenceGate: true,
165
+ deepScanBudget: true,
104
166
  // Producer advertisement only: diagnostics are always reported in-band; the advertised
105
167
  // failOnDiagnostics flag is the explicit consumer request that changes exit semantics.
106
168
  diagnostics: true,
169
+ diff: true,
170
+ ignoreReport: true,
171
+ metadata: true,
172
+ newOnly: true,
173
+ scopeField: true,
174
+ stableIdentity: true,
175
+ },
176
+ flags: {
177
+ baseline: "--baseline",
178
+ changedRanges: "--changed-ranges",
179
+ deepScanBudget: "--deep-scan-budget",
180
+ diff: "--diff",
181
+ failOnDiagnostics: "--fail-on-diagnostics",
182
+ minConfidence: "--min-confidence",
107
183
  },
108
- flags: { changedRanges: "--changed-ranges", diff: "--diff", baseline: "--baseline", failOnDiagnostics: "--fail-on-diagnostics" },
109
184
  flagOrder: "any" satisfies FlagOrder,
110
185
  }, null, 2) + "\n";
111
186
  }
112
187
 
113
- // Runs the analysis and projects it into the gruff.hook.v1 envelope: scoped findings, suppressed
114
- // count, ignored paths, and a schema-ok config block.
188
+ /**
189
+ * Builds the hook response from the findings the integration can act on for this edit.
190
+ *
191
+ * Invariant: the response includes the selected findings and the audits the hook gate will use for this edit.
192
+ * Side effects: replaying a Git base uses a temporary directory and briefly changes the working directory.
193
+ *
194
+ * @param runAnalyse - analysis runner used to obtain the report views and replay an available diff base
195
+ * @param input - hook request. No diff base skips replay. No baseline skips filtering by reviewed findings.
196
+ * @returns newline-terminated JSON with findings and run details. Null baseline statuses mean the user supplied no baseline.
197
+ */
115
198
  export function renderHookReport(runAnalyse: HookAnalysisRunner, input: HookReportInput): string {
116
- const { currentReport, scopedReport } = hookAnalysisViews(runAnalyse, input);
117
- const baseIdentities = hookBaseIdentities(runAnalyse, input, currentReport);
118
- const findings = hookFindings(currentReport, scopedReport, input.hasChangedRegion, baseIdentities);
119
- const suppressedCount = hookSuppressedCount(scopedReport, findings, input.hasChangedRegion);
120
- return JSON.stringify(hookReport(scopedReport, findings, suppressedCount, true, null), null, 2) + "\n";
121
- }
122
-
123
- // Selects the optimized hook view when available, otherwise falls back to one or two analyse calls.
199
+ const views = hookAnalysisViews(runAnalyse, input);
200
+ const { currentReport, scopedReport } = views;
201
+ const statuses = hookBaselineStatuses(views, input.baselinePath);
202
+ const baseIdentities = hookDiffBaseIdentities(runAnalyse, input, currentReport);
203
+ const kept = hookFindings(currentReport, scopedReport, input, baseIdentities, statuses);
204
+ const suppressedCount = hookSuppressedCount(scopedReport, kept, input.hasChangedRegion);
205
+ // A finding with no matching status stays new when the user supplied a baseline. Otherwise it has no review status.
206
+ const findings = kept.map((finding) => toHookFinding(finding, statuses.get(hookOccurrenceKey(finding)) ?? (input.baselinePath === undefined ? null : "new")));
207
+ return JSON.stringify(hookReport(scopedReport, findings, suppressedCount, hookRun(scopedReport, input)), null, 2) + "\n";
208
+ }
209
+
210
+ /**
211
+ * Collects full-scan and edit-scoped analysis views so hook filtering can compare both views.
212
+ *
213
+ * @param runAnalyse - Analysis runner or pre-bundled dual-view provider used to execute the scans.
214
+ * @param input - Hook request containing full-scan options, scoped options, and whether a change selector is active.
215
+ * @returns Current full-scan and scoped analysis reports; without a change selector, both views describe the full scan.
216
+ */
124
217
  function hookAnalysisViews(runAnalyse: HookAnalysisRunner, input: HookReportInput): HookAnalysisViews {
218
+ // The CLI runner supplies both views from one scan so the user sees a consistent result.
125
219
  if (runAnalyse.hookViews) {
126
220
  return runAnalyse.hookViews(input.currentOptions, input.scopedOptions, input.hasChangedRegion);
127
221
  }
@@ -130,116 +224,442 @@ function hookAnalysisViews(runAnalyse: HookAnalysisRunner, input: HookReportInpu
130
224
  return { currentReport, scopedReport };
131
225
  }
132
226
 
133
- // Emits a gruff.hook.v1 envelope for an operational failure (config rejected, bad baseline, git
134
- // error) so the consumer always receives JSON with config.error set instead of a crash.
135
- export function renderHookConfigError(message: string, remediation: string): string {
136
- const error = `${message}\nSuggested fix: ${remediation}`;
137
- return JSON.stringify(hookReport(undefined, [], 0, false, error), null, 2) + "\n";
227
+ /**
228
+ * Applies the review file produced by `analyse --generate-baseline` before narrowing to the edit.
229
+ * Counting reviews across the full scan keeps an unchanged occurrence elsewhere from hiding a new one in the edit.
230
+ *
231
+ * @param views - Current and scoped reports whose findings need baseline classification.
232
+ * @param baselinePath - Caller-selected baseline path, resolved from the working directory. Omission leaves the run unclassified.
233
+ * @returns Statuses keyed by finding. A missing application status defaults to new. An omitted path yields an empty map.
234
+ * @throws If the named baseline cannot be read or fails format, schema, or port validation.
235
+ */
236
+ function hookBaselineStatuses(views: HookAnalysisViews, baselinePath: string | undefined): HookBaselineStatuses {
237
+ const statuses: HookBaselineStatuses = new Map();
238
+ // With no baseline named, no finding carries a status a consumer could misread as reviewed.
239
+ if (baselinePath === undefined) {
240
+ return statuses;
241
+ }
242
+ const resolved = absolutize(cwd(), baselinePath);
243
+ const findings = views.currentReport.findings;
244
+ const application = applyBaseline(resolved, findings);
245
+ // A matching occurrence keeps the outcome of the original review. An unclassified occurrence stays visible as new.
246
+ findings.forEach((finding, index) => {
247
+ statuses.set(hookOccurrenceKey(finding), application.statuses[index] ?? "new");
248
+ });
249
+ return statuses;
250
+ }
251
+
252
+ /**
253
+ * Builds an occurrence lookup key for baseline matching.
254
+ * Invariant: one occurrence keeps the same key in both views, while different columns distinguish multiple matches on one line.
255
+ *
256
+ * @param finding - Finding whose fingerprint and optional column identify the occurrence.
257
+ * @returns Null-delimited key pairing the finding fingerprint with its column or an empty suffix when absent.
258
+ */
259
+ function hookOccurrenceKey(finding: Finding): string {
260
+ return `${finding.fingerprint}\0${finding.column ?? ""}`;
261
+ }
262
+
263
+ /**
264
+ * Build an envelope for a fatal hook failure. The CLI exits with code 2 and writes the envelope unless stdout is suppressed.
265
+ *
266
+ * @param diagnosticType - category assigned to the sole fatal diagnostic
267
+ * @param message - failure detail shown in the diagnostic
268
+ * @returns newline-terminated hook JSON with empty findings, suppression rows, and ignored paths, plus default run and config fields
269
+ */
270
+ export function renderHookFatal(diagnosticType: string, message: string): string {
271
+ return JSON.stringify(fatalReport(diagnosticType, message), null, 2) + "\n";
138
272
  }
139
273
 
140
- // Assembles the gruff.hook.v1 envelope (sorted findings, diagnostics, suppressed count, ignored
141
- // paths, config) as the stable gruff.hook.v1 output contract.
142
- function hookReport(report: AnalysisReport | undefined, findings: HookFinding[], suppressedCount: number, isSchemaOk: boolean, error: string | null): HookReport {
274
+ /**
275
+ * Formats a configuration failure payload with the loader's message in both the fatal diagnostic and `config.error`, and `schemaOk` set to false.
276
+ *
277
+ * @param message - Configuration failure message recorded in the diagnostic and config error object.
278
+ * @param remediation - Actionable fix guidance; defaults to general advice so callers without a specific fix can still tell the user what to try.
279
+ * @returns Newline-terminated `gruff.hook.v2` JSON string for the fatal config error envelope.
280
+ */
281
+ export function renderHookConfigError(message: string, remediation: string = CONFIG_ERROR_REMEDIATION): string {
282
+ const report = fatalReport("config", message);
283
+ report.config = { schemaOk: false, error: { message, remediation } };
284
+ return JSON.stringify(report, null, 2) + "\n";
285
+ }
286
+
287
+ /**
288
+ * Builds a fatal hook envelope so the caller has a payload to publish before exit 2.
289
+ * The stable contract retains the required envelope fields, with no findings or analysed files.
290
+ *
291
+ * @param diagnosticType - Category assigned to the sole fatal diagnostic entry.
292
+ * @param message - Failure description surfaced on the fatal diagnostic.
293
+ * @returns Envelope containing one fatal diagnostic and empty findings, suppressions, and ignored paths.
294
+ */
295
+ function fatalReport(diagnosticType: string, message: string): HookReport {
143
296
  return {
144
297
  contractVersion: HOOK_CONTRACT_VERSION,
145
298
  analyzer: analyzerInfo(),
299
+ run: { mode: "full", scope: "file", paths: [], analysedFiles: 0, baseline: { applied: false, schemaVersion: null, path: null } },
300
+ findings: [],
301
+ diagnostics: [{ type: diagnosticType, severity: "fatal", message }],
302
+ suppressed: { count: 0 },
303
+ suppressions: [],
304
+ ignored: { paths: [] },
305
+ config: { schemaOk: true, error: null },
306
+ };
307
+ }
308
+
309
+ /**
310
+ * Assembles the `gruff.hook.v2` envelope for a completed analysis, keeping findings in stable order.
311
+ * The analysis report supplies diagnostics, the exclusion audit, and skipped paths.
312
+ *
313
+ * @param report - Completed scoped analysis report providing diagnostics, suppressions, and skipped paths.
314
+ * @param findings - Visible hook findings to sort and include in the payload.
315
+ * @param suppressedCount - Total count of suppressed findings for the run.
316
+ * @param run - Run audit metadata describing mode, scope, paths, and baseline application.
317
+ * @returns Completed hook envelope with `schemaOk: true` and sorted findings.
318
+ */
319
+ function hookReport(report: AnalysisReport, findings: HookFinding[], suppressedCount: number, run: HookRun): HookReport {
320
+ return {
321
+ contractVersion: HOOK_CONTRACT_VERSION,
322
+ analyzer: analyzerInfo(),
323
+ run,
146
324
  findings: sortHookFindings(findings),
147
- diagnostics: (report?.diagnostics ?? []).map(toHookDiagnostic),
325
+ diagnostics: report.diagnostics.map(toHookDiagnostic),
148
326
  suppressed: { count: suppressedCount },
149
- ignored: { paths: report?.paths.skipped ?? [] },
150
- config: { schemaOk: isSchemaOk, error },
327
+ suppressions: report.suppressions.map(toHookSuppression),
328
+ ignored: { paths: report.paths.skipped },
329
+ config: { schemaOk: true, error: null },
151
330
  };
152
331
  }
153
332
 
154
- // Projects one run diagnostic into the hook contract's shape; never throws - absent anchors are omitted.
155
- function toHookDiagnostic(diagnostic: { diagnosticType: string; message: string; filePath?: string; line?: number }): HookDiagnostic {
333
+ /**
334
+ * Builds the run audit so consumers can see what ran and whether a review baseline was applied.
335
+ * Empty scoped paths report as `"."`; without a baseline, `applied` is false with null schema version and path.
336
+ *
337
+ * @param report - Analysis report supplying the project root and analysed-file count.
338
+ * @param input - Hook request supplying selectors, scoped paths, and optional baseline path.
339
+ * @returns Run audit detailing mode, scope, target paths, analysed-file count, and baseline metadata.
340
+ */
341
+ function hookRun(report: AnalysisReport, input: HookReportInput): HookRun {
342
+ const applied = input.baselinePath !== undefined;
343
+ return {
344
+ mode: hookRunMode(input),
345
+ // Every changed-region hook run widens a changed line to its declaration; a full run reads whole files.
346
+ scope: input.hasChangedRegion ? "symbol" : "file",
347
+ paths: input.scopedOptions.paths.length === 0 ? ["."] : [...input.scopedOptions.paths],
348
+ analysedFiles: report.paths.analysedFiles,
349
+ baseline: {
350
+ applied,
351
+ schemaVersion: applied ? BASELINE_SCHEMA_VERSION : null,
352
+ path: applied ? displayPath(report.run.projectRoot, absolutize(cwd(), input.baselinePath ?? "")) : null,
353
+ },
354
+ };
355
+ }
356
+
357
+ /**
358
+ * Names which region selector chose the work so a consumer can tell a targeted run from a whole-tree one.
359
+ * Follows the exact precedence of `changedRegionScope` (`changedRanges`, `diffPatch`, `since`, `diff`) so mode never disagrees with scope.
360
+ *
361
+ * @param input - Hook request whose scoped options determine the active selection mode.
362
+ * @returns `"changed-ranges"`, `"diff"`, `"since"`, or `"full"` in selector precedence order.
363
+ */
364
+ function hookRunMode(input: HookReportInput): HookRun["mode"] {
365
+ // Explicit ranges are the narrowest selector and win when more than one is given; presence decides, not truthiness.
366
+ if (input.scopedOptions.changedRanges !== undefined) {
367
+ return "changed-ranges";
368
+ }
369
+ // An explicit patch on stdin (even an empty one) takes precedence over Git refs, matching `changedRegionScope`.
370
+ if (input.scopedOptions.diffPatch !== undefined) {
371
+ return "diff";
372
+ }
373
+ if (input.scopedOptions.since) {
374
+ return "since";
375
+ }
376
+ return input.scopedOptions.diff ? "diff" : "full";
377
+ }
378
+
379
+ /**
380
+ * Projects a scan suppression summary into a hook audit row.
381
+ * An empty path list yields an empty path, and a null symbol or undefined source is omitted.
382
+ *
383
+ * @param summary - Suppression summary entry emitted by the analysis run.
384
+ * @returns Hook suppression row with a single path, optional symbol and source, reason, and count.
385
+ */
386
+ function toHookSuppression(summary: SuppressionSummary): HookSuppression {
387
+ return {
388
+ rule: summary.rule,
389
+ // Section 13a gives each entry exactly one path; the native audit carries it in a list shape.
390
+ path: summary.paths[0] ?? "",
391
+ ...(summary.symbol === null ? {} : { symbol: summary.symbol }),
392
+ reason: summary.reason,
393
+ suppressed: summary.suppressed,
394
+ // Built-in, inline and duplicate rows retain their source; configured rows omit it.
395
+ ...(summary.source === undefined ? {} : { source: summary.source }),
396
+ };
397
+ }
398
+
399
+ /**
400
+ * Projects a run diagnostic into the hook contract without throwing, omitting unavailable file and line anchors.
401
+ * In the hook contract, an explicit `invalidatesRun` value of false means warning, while unset or true means fatal.
402
+ *
403
+ * @param diagnostic - Run diagnostic from the analysis report.
404
+ * @returns Hook diagnostic with mapped severity, message, and optional file, line, and `invalidatesRun` fields.
405
+ */
406
+ function toHookDiagnostic(diagnostic: RunDiagnostic): HookDiagnostic {
156
407
  return {
157
408
  type: diagnostic.diagnosticType,
409
+ severity: diagnostic.invalidatesRun === false ? "warning" : "fatal",
158
410
  message: diagnostic.message,
159
411
  ...(diagnostic.filePath === undefined ? {} : { file: diagnostic.filePath }),
160
412
  ...(diagnostic.line === undefined ? {} : { line: diagnostic.line }),
413
+ ...(diagnostic.invalidatesRun === false ? { invalidatesRun: false as const } : {}),
161
414
  };
162
415
  }
163
416
 
164
- // Counts the diagnostics in a rendered gruff.hook.v1 envelope so the CLI can apply the explicit
165
- // --fail-on-diagnostics exit policy without re-running analysis or duplicating envelope knowledge.
166
- export function hookRenderedDiagnosticsCount(renderedEnvelope: string): number {
167
- const payload = JSON.parse(renderedEnvelope) as { diagnostics?: unknown[] };
168
- return Array.isArray(payload.diagnostics) ? payload.diagnostics.length : 0;
417
+ /**
418
+ * Decide whether to block the edit using the same hook contract entries the agent sees.
419
+ * Missing or non-array lists count as empty so they add no gate entries.
420
+ *
421
+ * @param renderedEnvelope - published hook envelope as JSON
422
+ * @param gate - thresholds and options that determine which published entries block the edit
423
+ * @returns 2 for a missing or unreadable target, 1 when a published entry reaches the gate, or 0 when the edit can proceed
424
+ * @throws SyntaxError - if the envelope is invalid JSON
425
+ */
426
+ export function hookExitCode(renderedEnvelope: string, gate: HookExitGate): number {
427
+ const payload = JSON.parse(renderedEnvelope) as { findings?: HookFinding[]; diagnostics?: HookDiagnostic[] };
428
+ const diagnostics = Array.isArray(payload.diagnostics) ? payload.diagnostics : [];
429
+ // An editor may request a file that was just deleted or that it cannot read. The hook cannot approve an edit it could not scan.
430
+ // Parse errors stay in-band: the file was read, and FAMILY-CONTRACT.md reserves exit 2 for a run that did not happen.
431
+ if (diagnostics.some((diagnostic) => diagnostic.type === "missing-path" || diagnostic.type === "read-error")) {
432
+ return 2;
433
+ }
434
+ // When the diagnostic gate is enabled, any published diagnostic blocks the edit regardless of the finding thresholds.
435
+ if (gate.shouldFailOnDiagnostics && diagnostics.length > 0) {
436
+ return 1;
437
+ }
438
+ // When there are no published findings, only diagnostics can block the edit.
439
+ const findings = Array.isArray(payload.findings) ? payload.findings : [];
440
+ return findings.some((finding) => reachesHookGate(finding, gate)) ? 1 : 0;
441
+ }
442
+
443
+ /**
444
+ * Decides whether a published finding blocks the edit under the user's review or severity settings.
445
+ * Invariant: `--fail-on none` disables severity gating while leaving an explicitly requested review gate active.
446
+ *
447
+ * @param finding - Published hook finding evaluated against the gate.
448
+ * @param gate - Configured severity, confidence, and new-only blocking thresholds.
449
+ * @returns True if the finding triggers the review gate or meets both severity and confidence floors; otherwise false.
450
+ */
451
+ function reachesHookGate(finding: HookFinding, gate: HookExitGate): boolean {
452
+ // The review gate blocks unreviewed findings, including those that cannot be recorded. Null means the user supplied no baseline.
453
+ if (gate.shouldFailOnNew && finding.baselineStatus !== null && finding.baselineStatus !== "unchanged") {
454
+ return true;
455
+ }
456
+ // The user can turn off severity gating while still blocking findings that lack a review.
457
+ if (gate.failOn === "none") {
458
+ return false;
459
+ }
460
+ const severity = SEVERITY_GATE_RANK[finding.severity] ?? 0;
461
+ const confidence = CONFIDENCE_GATE_RANK[finding.confidence] ?? CONFIDENCE_GATE_RANK.high;
462
+ return severity >= SEVERITY_GATE_RANK[gate.failOn] && confidence >= CONFIDENCE_GATE_RANK[gate.minConfidence];
169
463
  }
170
464
 
171
- // Analyzer identity block shared by the capability and report envelopes.
465
+ /**
466
+ * Builds the analyzer identity block shared by the capability and report envelopes.
467
+ *
468
+ * @returns Object identifying the analyzer name (`"gruff-ts"`) and current `VERSION`.
469
+ */
172
470
  function analyzerInfo(): { name: "gruff-ts"; version: string } {
173
471
  return { name: "gruff-ts", version: VERSION };
174
472
  }
175
473
 
176
- // Builds the hook finding list: changed-region scoping drops inherited file findings, then
177
- // new-only filtering re-admits file/project findings absent from the base identities.
178
- // Invariant: suppressed.count arithmetic must stay exact across both filtering stages.
474
+ /**
475
+ * Build the findings to publish, using prior coverage to distinguish inherited issues from findings the hook can attribute to this edit.
476
+ *
477
+ * @param currentReport - full scan that supplies file and project candidates for re-admission
478
+ * @param scopedReport - scoped scan that supplies the initial candidates
479
+ * @param input - hook request that supplies changed-region mode and whether a baseline was named
480
+ * @param baseIdentities - stable match-key counts from the diff base, or undefined to skip diff-base filtering
481
+ * @param statuses - baseline classifications. An empty map leaves the published list unfiltered by review.
482
+ * @returns the findings shown to the user after scope and review filtering. An empty list means none remain to publish.
483
+ */
179
484
  function hookFindings(
180
485
  currentReport: AnalysisReport,
181
486
  scopedReport: AnalysisReport,
182
- hasChangedRegion: boolean,
183
- baseIdentities: Set<string> | undefined,
184
- ): HookFinding[] {
185
- const scopedFindings = scopedReport.findings
186
- .map(toHookFinding)
187
- .filter((finding) => !hasChangedRegion || finding.scope !== "file");
188
- const withNewFileAndProject = hasChangedRegion && baseIdentities
189
- ? [...scopedFindings, ...newFileAndProjectFindings(currentReport, scopedFindings, baseIdentities)]
487
+ input: HookReportInput,
488
+ baseIdentities: Map<string, number> | undefined,
489
+ statuses: HookBaselineStatuses,
490
+ ): Finding[] {
491
+ const hasChangedRegion = input.hasChangedRegion;
492
+ // In changed-region mode, a whole-file issue needs a prior base before the hook can attribute it to the edit.
493
+ // A named baseline or a replayed diff base lets the hook reconsider whole-file findings.
494
+ const hasPriorBase = baseIdentities !== undefined || input.baselinePath !== undefined;
495
+ const scopedFindings = scopedReport.findings.filter((finding) => !hasChangedRegion || scopeForFinding(finding) !== "file");
496
+ const covered = baseCoveredOccurrences(currentReport, baseIdentities);
497
+ const withNewFileAndProject = hasChangedRegion && hasPriorBase
498
+ ? [...scopedFindings, ...newFileAndProjectFindings(currentReport, scopedFindings, covered)]
190
499
  : scopedFindings;
191
- return baseIdentities
192
- ? withNewFileAndProject.filter((finding) => !baselineMatchIdentities(finding).some((identity) => baseIdentities.has(identity)))
500
+ // Without replay counts, there is no earlier Git snapshot to match against the current edit.
501
+ const afterNewOnly = baseIdentities
502
+ ? withNewFileAndProject.filter((finding) => !spendCoveredOccurrence(covered, finding))
193
503
  : withNewFileAndProject;
194
- }
195
-
196
- // Collects file- and project-scope findings that are new since the base, excluding any already
197
- // emitted, deduped by fingerprint.
198
- function newFileAndProjectFindings(currentReport: AnalysisReport, scopedFindings: HookFinding[], baseIdentities: Set<string>): HookFinding[] {
504
+ // A finding marked unchanged has already been reviewed against the baseline, so it stays out of the published list.
505
+ return afterNewOnly.filter((finding) => statuses.get(hookOccurrenceKey(finding)) !== "unchanged");
506
+ }
507
+
508
+ /**
509
+ * Selects file-scope and project-scope findings in `currentReport` absent from `scopedFindings` and not covered by the base.
510
+ * Mutates `covered` to spend one count per eligible match so that repeated occurrences compare correctly.
511
+ *
512
+ * @param currentReport - Full-scan report providing candidate file and project findings.
513
+ * @param scopedFindings - Findings already selected from the scoped scan, used to avoid duplicates.
514
+ * @param covered - Remaining base-covered counts keyed by fingerprint; decremented in place for covered matches.
515
+ * @returns Newly attributable file and project findings from the current full scan.
516
+ */
517
+ function newFileAndProjectFindings(currentReport: AnalysisReport, scopedFindings: Finding[], covered: Map<string, number>): Finding[] {
199
518
  const alreadyIncluded = new Set(scopedFindings.map((finding) => finding.fingerprint));
200
- return currentReport.findings
201
- .map(toHookFinding)
202
- .filter((finding) => (finding.scope === "file" || finding.scope === "project") && !baseIdentities.has(finding.stableIdentity) && !alreadyIncluded.has(finding.fingerprint));
519
+ return currentReport.findings.filter((finding) => {
520
+ const scope = scopeForFinding(finding);
521
+ if ((scope !== "file" && scope !== "project") || alreadyIncluded.has(finding.fingerprint)) {
522
+ return false;
523
+ }
524
+ // A base that already held this occurrence says this edit did not introduce it, so it stays suppressed.
525
+ return !spendCoveredOccurrence(covered, finding);
526
+ });
527
+ }
528
+
529
+ /**
530
+ * Tallies how many current findings are covered by the diff base per occurrence key (fingerprint plus column).
531
+ * For each stable hook match key, spends at most its base count in line and column order so same-line findings keep separate credits.
532
+ *
533
+ * @param currentReport - Full-scan report whose findings are matched against the base counts.
534
+ * @param baseCounts - Occurrence counts from the diff base keyed by stable hook match key, or undefined when unavailable.
535
+ * @returns Counts of covered current findings keyed by occurrence key, or an empty map when base counts are missing.
536
+ */
537
+ function baseCoveredOccurrences(currentReport: AnalysisReport, baseCounts: Map<string, number> | undefined): Map<string, number> {
538
+ const covered = new Map<string, number>();
539
+ if (baseCounts === undefined) {
540
+ return covered;
541
+ }
542
+ const remaining = new Map(baseCounts);
543
+ const byLine = [...currentReport.findings].sort((left, right) => (left.line ?? 0) - (right.line ?? 0) || (left.column ?? 0) - (right.column ?? 0));
544
+ for (const finding of byLine) {
545
+ const key = hookMatchKey(finding);
546
+ const count = remaining.get(key) ?? 0;
547
+ // A key the base never held, or whose base occurrences are spent, leaves this occurrence new.
548
+ if (count === 0) {
549
+ continue;
550
+ }
551
+ remaining.set(key, count - 1);
552
+ const occurrenceKey = hookOccurrenceKey(finding);
553
+ covered.set(occurrenceKey, (covered.get(occurrenceKey) ?? 0) + 1);
554
+ }
555
+ return covered;
203
556
  }
204
557
 
205
- // Counts the file/project findings the hook drops under changed-region attribution, excluding any
206
- // re-emitted as new, so the stable suppressed.count contract is never double-counted.
207
- function hookSuppressedCount(scopedReport: AnalysisReport, emittedFindings: HookFinding[], hasChangedRegion: boolean): number {
558
+ /**
559
+ * Consumes one covered occurrence for a finding's occurrence key, mutating the caller's coverage map when nonzero.
560
+ * The stable contract lets each covered occurrence hide one finding across file/project re-admission and the new-only filter.
561
+ *
562
+ * @param covered - Remaining base-covered occurrence counts keyed by occurrence key; decremented on match.
563
+ * @param finding - Finding whose occurrence key is checked against the remaining covered count.
564
+ * @returns True after spending one occurrence when the count is nonzero; false if missing or exhausted.
565
+ */
566
+ function spendCoveredOccurrence(covered: Map<string, number>, finding: Finding): boolean {
567
+ const occurrenceKey = hookOccurrenceKey(finding);
568
+ const count = covered.get(occurrenceKey) ?? 0;
569
+ if (count === 0) {
570
+ return false;
571
+ }
572
+ covered.set(occurrenceKey, count - 1);
573
+ return true;
574
+ }
575
+
576
+ /**
577
+ * Computes the stable `suppressed.count` total for changed-region runs by combining scoped suppressions with unemitted file/project findings.
578
+ * Excludes findings re-admitted from outside the scoped view so a newly published file or project finding is never also counted as suppressed.
579
+ *
580
+ * @param scopedReport - Scoped analysis report supplying `suppressedCount` and candidate anchor findings.
581
+ * @param emittedFindings - Findings actually published in the hook response.
582
+ * @param hasChangedRegion - Whether the hook run narrowed analysis to a changed region.
583
+ * @returns Net count of suppressed findings for the changed-region view, or zero for a full scan.
584
+ */
585
+ function hookSuppressedCount(scopedReport: AnalysisReport, emittedFindings: Finding[], hasChangedRegion: boolean): number {
208
586
  if (!hasChangedRegion) {
209
587
  return 0;
210
588
  }
211
- const emittedFingerprints = new Set(emittedFindings.map((finding) => finding.fingerprint));
589
+ const scopedKeys = new Set(scopedReport.findings.map(hookOccurrenceKey));
590
+ const emittedKeys = new Set(emittedFindings.map(hookOccurrenceKey));
591
+ // Findings absent from `scopedReport.findings` were counted in `scopedReport.suppressedCount`; subtract any that replay or baseline re-admitted.
592
+ const reAdmittedFromSuppressed = emittedFindings.filter((finding) => !scopedKeys.has(hookOccurrenceKey(finding))).length;
212
593
  const fileOrProjectAnchorResiduals = scopedReport.findings.filter((finding) => {
213
594
  const scope = scopeForFinding(finding);
214
- return (scope === "file" || scope === "project") && !emittedFingerprints.has(finding.fingerprint);
595
+ return (scope === "file" || scope === "project") && !emittedKeys.has(hookOccurrenceKey(finding));
215
596
  }).length;
216
- return (scopedReport.suppressedCount ?? 0) + fileOrProjectAnchorResiduals;
597
+ return Math.max(0, (scopedReport.suppressedCount ?? 0) - reAdmittedFromSuppressed + fileOrProjectAnchorResiduals);
217
598
  }
218
599
 
219
- // Projects an analyser Finding into the hook shape, attaching scope, remediation, and the stable
220
- // identity plus fingerprint.
221
- function toHookFinding(finding: Finding): HookFinding {
222
- const scope = scopeForFinding(finding);
600
+ /**
601
+ * Projects an internal finding into a `HookFinding` row for the hook contract, with normalized lines, remediation, metadata, and review status.
602
+ * Contract: omits missing columns and lines when start line is absent; missing symbols, `stableIdentity`, and unclassified statuses are null.
603
+ *
604
+ * @param finding - Internal finding produced by the analyzer.
605
+ * @param baselineStatus - Review status from an applied baseline, or null when no baseline was applied.
606
+ * @returns Hook finding row with 0 ordinal when unstored and rule descriptor or generic fallback remediation.
607
+ */
608
+ function toHookFinding(finding: Finding, baselineStatus: string | null): HookFinding {
609
+ const endLine = endLineFor(finding);
223
610
  return {
224
611
  ruleId: finding.ruleId,
225
612
  pillar: finding.pillar,
226
613
  severity: finding.severity,
227
- scope,
614
+ confidence: finding.confidence,
615
+ scope: scopeForFinding(finding),
228
616
  file: finding.filePath,
229
617
  ...(finding.line === undefined ? {} : { line: finding.line }),
230
- ...(finding.endLine === undefined ? {} : { endLine: finding.endLine }),
618
+ ...(endLine === undefined ? {} : { endLine }),
231
619
  ...(finding.column === undefined ? {} : { column: finding.column }),
232
620
  symbol: finding.symbol ?? null,
621
+ symbolOrdinal: symbolOrdinalOf(finding),
233
622
  message: finding.message,
234
623
  remediation: finding.remediation ?? DESCRIPTORS.get(finding.ruleId)?.remediation ?? "Review and address this finding.",
235
624
  metadata: hookMetadata(finding),
236
- stableIdentity: hookStableIdentity(finding, scope),
625
+ stableIdentity: finding.baselineIdentity ?? null,
626
+ baselineStatus,
237
627
  fingerprint: finding.fingerprint,
238
628
  };
239
629
  }
240
630
 
241
- // Classifies a finding as line/symbol/file/project scope; this choice drives changed-region
242
- // attribution and the stable hook identity.
631
+ /**
632
+ * Computes the finding's span end for the stable hook contract, falling back to start line when `endLine` is absent or earlier.
633
+ *
634
+ * @param finding - Finding whose optional `line` and `endLine` define the span.
635
+ * @returns Validated end line number, or undefined when the finding has no start line so the hook omits the span end.
636
+ */
637
+ function endLineFor(finding: Finding): number | undefined {
638
+ if (finding.line === undefined) {
639
+ return undefined;
640
+ }
641
+ return finding.endLine !== undefined && finding.endLine >= finding.line ? finding.endLine : finding.line;
642
+ }
643
+
644
+ /**
645
+ * Extracts the declaration ordinal the ratified identity hashed so a consumer can recompute that identity.
646
+ * The identity contract uses 0 when the finding has no stored subject or its subject has no ordinal suffix.
647
+ *
648
+ * @param finding - Finding whose optional `baselineSubject` may carry a trailing `#<ordinal>` suffix.
649
+ * @returns Parsed 1-based declaration ordinal, or 0 when absent.
650
+ */
651
+ function symbolOrdinalOf(finding: Finding): number {
652
+ const trailing = finding.baselineSubject === undefined ? null : TRAILING_ORDINAL.exec(finding.baselineSubject);
653
+ return trailing === null ? 0 : Number(trailing[1]);
654
+ }
655
+
656
+ /**
657
+ * Classifies a finding as line, symbol, file, or project scope to drive changed-region attribution and the port-local hook match key.
658
+ * Stable contract: one finding always lands in one scope, so changed-region attribution is deterministic.
659
+ *
660
+ * @param finding - Finding whose rule ID, symbol, and line span determine its scope.
661
+ * @returns Deterministic scope classification (`"project"`, `"file"`, `"symbol"`, or `"line"`).
662
+ */
243
663
  function scopeForFinding(finding: Finding): HookScope {
244
664
  if (PROJECT_SCOPE_RULE_IDS.has(finding.ruleId)) {
245
665
  return "project";
@@ -253,28 +673,35 @@ function scopeForFinding(finding: Finding): HookScope {
253
673
  return "line";
254
674
  }
255
675
 
256
- // Returns normalized threshold metadata when the rule has one, else the finding's own metadata,
257
- // keeping the contract's metadata shape stable.
676
+ /**
677
+ * Returns the hook contract's threshold metadata for a supported rule with a numeric measurement and limit, preserving `limitBand` when present.
678
+ * Otherwise returns the finding's original metadata.
679
+ *
680
+ * @param finding - Finding whose rule ID and metadata are inspected for threshold mapping.
681
+ * @returns Normalized threshold metadata (including `limitBand` if string-valued), or the finding's original metadata otherwise.
682
+ */
258
683
  function hookMetadata(finding: Finding): Record<string, unknown> {
259
684
  const thresholdMetadata = thresholdMetadataFor(finding);
685
+ // The hook contract keeps the limit band beside the measurement (FAMILY-CONTRACT.md section 12, The band key).
686
+ if (thresholdMetadata && typeof finding.metadata.limitBand === "string") {
687
+ return { ...thresholdMetadata, limitBand: finding.metadata.limitBand };
688
+ }
260
689
  return thresholdMetadata ?? finding.metadata;
261
690
  }
262
691
 
263
- // Maps known threshold rules to a measured/threshold/unit triple so the hook exposes a stable,
264
- // machine-readable measurement contract.
692
+ /**
693
+ * Maps a finding's rule ID and metadata to a stable hook measurement with its threshold, unit, and direction.
694
+ *
695
+ * @param finding - Finding providing the rule ID and raw metric values.
696
+ * @returns Normalized threshold metadata object, or undefined when the rule has no mapping or either numeric value is unavailable.
697
+ */
265
698
  function thresholdMetadataFor(finding: Finding): Record<string, unknown> | undefined {
266
699
  const metadata = finding.metadata;
267
700
  switch (finding.ruleId) {
268
- case "complexity.cognitive":
269
701
  case "complexity.cyclomatic":
270
702
  return metricMetadata(metadata.complexity, metadata.threshold, "points");
271
- case "design.deep-relative-import":
272
- return metricMetadata(metadata.parentSegments, metadata.maxParentSegments, "segments");
273
703
  case "design.large-module-concentration":
274
704
  return metricMetadata(metadata.sharePercent, metadata.maxSharePercent, "percent");
275
- case "sensitive-data.hardcoded-env-value":
276
- case "sensitive-data.high-entropy-string":
277
- return metricMetadata(metadata.length, metadata.threshold, "characters");
278
705
  case "size.file-length":
279
706
  case "size.function-length":
280
707
  return metricMetadata(metadata.lines, metadata.threshold, "lines");
@@ -284,173 +711,135 @@ function thresholdMetadataFor(finding: Finding): Record<string, unknown> | undef
284
711
  return undefined;
285
712
  }
286
713
 
287
- // Builds the normalized measurement object, or undefined when the measured/threshold pair is not
288
- // numeric.
714
+ /**
715
+ * Builds a normalized threshold metadata record with direction `"above"` when both numeric values are present.
716
+ *
717
+ * @param measured - Observed numeric value from the finding's metadata.
718
+ * @param threshold - Configured numeric comparison limit from the finding's metadata.
719
+ * @param unit - Unit label describing both `measured` and `threshold` (such as `"lines"` or `"points"`).
720
+ * @returns Metadata containing `measured`, `threshold`, `unit`, and `direction: "above"`, or undefined unless both inputs are numbers.
721
+ */
289
722
  function metricMetadata(measured: unknown, threshold: unknown, unit: string): Record<string, unknown> | undefined {
290
723
  return typeof measured === "number" && typeof threshold === "number"
291
724
  ? { measured, threshold, unit, direction: "above" }
292
725
  : undefined;
293
726
  }
294
727
 
295
- // Hashes (ruleId, filePath, scope component) into the 16-hex hook identity; line-insensitive so it
296
- // stays the stable cross-edit key for new-only filtering.
297
- function hookStableIdentity(finding: Finding, scope: HookScope): string {
298
- return identityHash(finding.ruleId, finding.filePath, stableIdentityComponent(finding, scope));
299
- }
300
-
301
- // The one place the 16-hex identity is derived, so every caller hashes the same tuple.
302
- function identityHash(ruleId: string, filePath: string, component: string): string {
728
+ /**
729
+ * Build a stable key for matching findings against a base replay so edits above a finding do not make it look new.
730
+ * The published stableIdentity is computed separately.
731
+ *
732
+ * @param finding - occurrence whose rule, path, and scope component identify it for replay matching
733
+ * @returns the 16-character hexadecimal hook match key
734
+ */
735
+ function hookMatchKey(finding: Finding): string {
736
+ const scope = scopeForFinding(finding);
303
737
  return createHash("sha256")
304
- .update([ruleId, filePath, component].join("\0"))
738
+ .update([finding.ruleId, finding.filePath, matchKeyComponent(finding, scope)].join("\0"))
305
739
  .digest("hex")
306
740
  .slice(0, 16);
307
741
  }
308
742
 
309
- // Identities one emitted finding answers to when matched against a base set. gruff.baseline.v1
310
- // stores no column, so a baseline recomputes the column-free key; a finding that now reports a
311
- // column must still recognise it, or every previously accepted secret comes back on the next run.
312
- // Same-line occurrences share that older key, which is the baseline limitation ADR-017 documents:
313
- // accepting one accepts every secret on its line. The wire identity stays column-aware, so a
314
- // consumer tracking findings by identity still sees the two occurrences as separate.
315
- function baselineMatchIdentities(finding: HookFinding): string[] {
316
- if (finding.column === undefined) {
317
- return [finding.stableIdentity];
318
- }
319
- const columnFreeComponent = stableIdentityComponent({
320
- message: finding.message,
321
- ruleId: finding.ruleId,
322
- ...(finding.symbol === null ? {} : { symbol: finding.symbol }),
323
- }, finding.scope);
324
- return [finding.stableIdentity, identityHash(finding.ruleId, finding.file, columnFreeComponent)];
325
- }
326
-
327
- // Derives the per-occurrence component of the stable hook identity: scope token, symbol, or message
328
- // plus match column.
329
- function stableIdentityComponent(finding: { message: string; ruleId: string; symbol?: string; column?: number }, scope: HookScope): string {
743
+ /**
744
+ * Builds a stable match-key component from `finding` according to `scope` so occurrences can be matched across edits.
745
+ * File and unsymboled project scopes share a token; symboled entries use the symbol, and unsymboled line entries fall back to message and column.
746
+ *
747
+ * @param finding - Finding contributing symbol, message, and optional column.
748
+ * @param scope - Classified hook scope determining which fields identify the occurrence.
749
+ * @returns Scope-specific string component hashed into the hook match key.
750
+ */
751
+ function matchKeyComponent(finding: Finding, scope: HookScope): string {
330
752
  if (scope === "file") {
331
753
  return scope;
332
754
  }
333
755
  if (scope === "project") {
334
- // Project rules are value-insensitive on their measurement, but component-level findings still
335
- // need a stable occurrence key. design.circular-import carries the canonical sorted SCC member
336
- // list in `symbol`; folding it in keeps independent components distinct without line sensitivity.
756
+ // Project matching ignores measured values.
757
+ // The canonical member list in the design.circular-import symbol distinguishes cycles without relying on line numbers.
337
758
  return finding.symbol && finding.symbol.length > 0 ? `project:${finding.symbol}` : scope;
338
759
  }
339
760
  if (finding.symbol && finding.symbol.length > 0) {
340
761
  return `symbol:${finding.symbol}`;
341
762
  }
342
- // Symbol-less line findings (e.g. each hardcoded secret) key on the message so several same-rule
343
- // findings in one file get distinct identities. A value-insensitive `metric:${scope}` token
344
- // collapsed them all, letting one baselined finding suppress later new ones in the same file. file
345
- // scope above stays fully value-insensitive; project scope folds in a canonical symbol when present.
763
+ // For occurrences without a symbol, differing messages distinguish matches of the same rule in a file.
346
764
  const messageComponent = `message:${finding.message}`;
347
- // The redacted preview alone stopped separating occurrences once short secrets became fully
348
- // masked: two 20-character keys on one line produce the same preview, so the same message. The
349
- // match column separates them and names no line, so an edit above the finding still keeps the
350
- // identity stable. Scanners that report a whole line supply no column and keep the older key.
765
+ // Fully masked matches on one line can share a message, so the column distinguishes them without using the line number.
766
+ // Without a column, the message is the whole component.
351
767
  return finding.column === undefined ? messageComponent : `${messageComponent}\0column:${finding.column}`;
352
768
  }
353
769
 
354
- // Builds the base identity set (from a baseline file and/or a diff base) that new-only filtering
355
- // compares against by stable hook identity; undefined when neither source is requested.
356
- function hookBaseIdentities(runAnalyse: HookAnalysisRunner, input: HookReportInput, currentReport: AnalysisReport): Set<string> | undefined {
357
- const identities = new Set<string>();
358
- if (input.baselinePath) {
359
- for (const identity of stableIdentitiesFromBaseline(input.baselinePath)) {
360
- identities.add(identity);
361
- }
362
- }
363
- if (input.diffBase) {
364
- for (const identity of stableIdentitiesFromDiffBase(runAnalyse, input.currentOptions, input.diffBase, currentReport)) {
365
- identities.add(identity);
366
- }
367
- }
368
- return identities.size > 0 || input.baselinePath || input.diffBase ? identities : undefined;
369
- }
370
-
371
- // Reads stable identities from a gruff.baseline.v1 file; the schema is the gruff.baseline.v1
372
- // contract and the reader throws on any schemaVersion mismatch.
373
- function stableIdentitiesFromBaseline(path: string): Set<string> {
374
- const baselinePath = absolutize(cwd(), path);
375
- const baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as { schemaVersion?: string; entries?: BaselineEntry[] };
376
- if (baseline.schemaVersion !== "gruff.baseline.v1") {
377
- throw new Error(`unsupported baseline schema in ${path}`);
378
- }
379
- return new Set((baseline.entries ?? []).flatMap(stableIdentityFromBaselineEntry));
380
- }
381
-
382
- // Resolves one baseline entry to hook identities: its stored identity, or a recomputed one from
383
- // ruleId, filePath, and scope. The recomputed key carries no column because gruff.baseline.v1 stores
384
- // none; `baselineMatchIdentities` is what lets a column-bearing finding still match it.
385
- function stableIdentityFromBaselineEntry(entry: BaselineEntry): string[] {
386
- if (typeof entry.stableIdentity === "string") {
387
- return [entry.stableIdentity];
388
- }
389
- if (typeof entry.ruleId !== "string" || typeof entry.filePath !== "string") {
390
- return [];
391
- }
392
- const scope = baselineScopeForRule(entry.ruleId);
393
- const component = stableIdentityComponent({
394
- ruleId: entry.ruleId,
395
- message: entry.message ?? "",
396
- ...(typeof entry.symbol === "string" ? { symbol: entry.symbol } : {}),
397
- }, scope);
398
- return [
399
- createHash("sha256")
400
- .update([entry.ruleId, entry.filePath, component].join("\0"))
401
- .digest("hex")
402
- .slice(0, 16),
403
- ];
404
- }
405
-
406
- // Maps a rule id to its baseline scope so entries without a stored identity recompute the right
407
- // component.
408
- function baselineScopeForRule(ruleId: string): HookScope {
409
- if (PROJECT_SCOPE_RULE_IDS.has(ruleId)) {
410
- return "project";
411
- }
412
- if (FILE_SCOPE_RULE_IDS.has(ruleId)) {
413
- return "file";
770
+ /**
771
+ * Computes stable match-key counts from the diff base using scan settings from `input` on paths from `currentReport`.
772
+ * Replay spawns Git, writes a temporary tree, and temporarily changes the process working directory.
773
+ *
774
+ * @param runAnalyse - Analysis runner used to scan materialized base files.
775
+ * @param input - Hook request supplying `diffBase` and `currentOptions`.
776
+ * @param currentReport - Current scan report supplying file paths to replay.
777
+ * @returns Match-key count map (empty map still lets the hook reconsider whole-file findings), or undefined when `diffBase` is absent.
778
+ */
779
+ function hookDiffBaseIdentities(runAnalyse: HookAnalysisRunner, input: HookReportInput, currentReport: AnalysisReport): Map<string, number> | undefined {
780
+ if (input.diffBase === undefined) {
781
+ return undefined;
414
782
  }
415
- return "line";
416
- }
417
-
418
- // Replays the diff base ref and returns its findings' stable hook identities for new-only filtering.
419
- // Writes a temp tree, spawns git to materialize base files, and must clean both up afterward.
420
- function stableIdentitiesFromDiffBase(
783
+ return keysFromDiffBase(runAnalyse, input.currentOptions, input.diffBase, currentReport, input.isDiffExplicitRef === true);
784
+ }
785
+
786
+ /**
787
+ * Replays the diff base so new-only filtering can compare stable hook keys by occurrence count.
788
+ * Spawns Git and writes a temporary tree. Changes into it for analysis, then restores the working directory and removes the tree in finally.
789
+ *
790
+ * @param runAnalyse - runner that scans the materialized base files
791
+ * @param options - current scan settings from which to build the replay options
792
+ * @param diffBase - diff selector that identifies the revision or index to replay
793
+ * @param currentReport - current findings that identify which file paths to replay
794
+ * @param isExplicitRef - true when `diffBase` came from `--since` or `--diff-base` and names a Git revision directly
795
+ * @returns Counts by hook match key, an empty map when no base files or findings exist, or undefined when the selector has no replayable Git base.
796
+ */
797
+ function keysFromDiffBase(
421
798
  runAnalyse: HookAnalysisRunner,
422
799
  options: AnalysisOptions,
423
800
  diffBase: string,
424
801
  currentReport: AnalysisReport,
425
- ): Set<string> {
426
- const ref = diffBaseRef(diffBase);
802
+ isExplicitRef = false,
803
+ ): Map<string, number> | undefined {
804
+ const ref = diffBaseRef(diffBase, isExplicitRef);
805
+ // A patch read from stdin has no Git revision to replay, so return undefined to avoid falsely enabling file-wide re-admission.
427
806
  if (ref === undefined) {
428
- return new Set();
807
+ return undefined;
429
808
  }
430
809
  const files = [...new Set(currentReport.findings.flatMap(findingBasePaths))];
810
+ // With no current finding paths, the agent has nothing to compare with the base.
431
811
  if (files.length === 0) {
432
- return new Set();
812
+ return new Map();
433
813
  }
434
814
  const tempRoot = mkdtempSync(join(tmpdir(), "gruff-ts-hook-base-"));
435
815
  const previous = cwd();
816
+ const projectRoot = currentReport.run.projectRoot;
436
817
  try {
437
- const baseFiles = materializeBaseFiles(ref, files, tempRoot);
818
+ const baseFiles = materializeBaseFiles(ref, files, tempRoot, projectRoot);
819
+ // New files may exist only in the current checkout, leaving no prior occurrences to spend.
438
820
  if (baseFiles.length === 0) {
439
- return new Set();
821
+ return new Map();
440
822
  }
823
+ const baseOptions = baseAnalysisOptions(options, baseFiles, projectRoot);
441
824
  chdir(tempRoot);
442
- const baseReport = runAnalyse(baseAnalysisOptions(options, baseFiles, previous));
443
- return new Set(baseReport.findings.map((finding) => hookStableIdentity(finding, scopeForFinding(finding))));
825
+ const baseReport = runAnalyse(baseOptions);
826
+ const counts = new Map<string, number>();
827
+ // Each prior match covers one occurrence so a duplicate introduced by this edit can still appear.
828
+ for (const key of baseReport.findings.map(hookMatchKey)) {
829
+ counts.set(key, (counts.get(key) ?? 0) + 1);
830
+ }
831
+ return counts;
444
832
  } finally {
445
833
  chdir(previous);
446
834
  rmSync(tempRoot, { recursive: true, force: true });
447
835
  }
448
836
  }
449
837
 
450
- /*
451
- * A finding's base context is its anchor plus any project-relationship members from
452
- * `metadata.files`. Contract invariant: without every SCC member at the base ref, the replay
453
- * cannot reconstruct the cycle identity and a pre-existing cycle would be reported as new.
838
+ /**
839
+ * Select replay paths so that the base scan can reconstruct the complete import cycle for stable matching.
840
+ *
841
+ * @param finding - current occurrence whose file and recorded member paths identify the replay inputs
842
+ * @returns the finding's file path plus string paths in metadata.files, or just its file path when no members qualify
454
843
  */
455
844
  function findingBasePaths(finding: Finding): string[] {
456
845
  const memberFiles = finding.metadata.files;
@@ -460,63 +849,100 @@ function findingBasePaths(finding: Finding): string[] {
460
849
  return [finding.filePath, ...memberFiles.filter((file): file is string => typeof file === "string")];
461
850
  }
462
851
 
463
- // Resolves a diff-base selector to the git rev whose blobs are the new-only base. "unstaged" diffs
464
- // the worktree against the index, so its base is the index ("" rev -> `git show :path`); "-" (stdin
465
- // patch) has no materializable base. Returns undefined only when no base can be replayed.
466
- function diffBaseRef(diffBase: string): string | undefined {
852
+ /**
853
+ * Maps a diff-base selector to the Git revision to replay for new-only filtering.
854
+ *
855
+ * An explicit ref passes through as given, and a stdin patch (`"-"`) has no base to replay.
856
+ * Otherwise working-tree and staged use `HEAD`, unstaged uses the index (`""`), and any other value passes through.
857
+ *
858
+ * @param diffBase - Diff selector supplied to the hook request.
859
+ * @param isExplicitRef - true when `diffBase` came from `--since` or `--diff-base`, so even `staged` names a Git ref, not a mode
860
+ * @returns Git revision string for `git show`, empty string for the index, or undefined for a stdin patch.
861
+ */
862
+ function diffBaseRef(diffBase: string, isExplicitRef = false): string | undefined {
863
+ // A pasted patch supplies changed lines but no Git snapshot for inherited findings.
467
864
  if (diffBase === "-") {
468
865
  return undefined;
469
866
  }
867
+ // A ref from --since or --diff-base is replayed as given, even a branch named staged or unstaged.
868
+ if (isExplicitRef) {
869
+ return diffBase;
870
+ }
871
+ // For unstaged edits, the user's staged file contents are the comparison point.
470
872
  if (diffBase === "unstaged") {
471
873
  return "";
472
874
  }
473
875
  return diffBase === "working-tree" || diffBase === "staged" ? "HEAD" : diffBase;
474
876
  }
475
877
 
476
- // Writes each file's blob at the base ref into the temp dir via git; a blob missing at the ref is a
477
- // recover path so that file's findings count as new (filesystem writes).
478
- function materializeBaseFiles(ref: string, files: string[], root: string): string[] {
878
+ /**
879
+ * Recreates the selected files from Git so the hook can compare what the user had before the edit.
880
+ * Side effects: spawns `git show` and writes available files into the temporary comparison directory.
881
+ *
882
+ * @param ref - Git revision or empty string for the index from which to read prior file contents.
883
+ * @param files - Relative file paths to materialize from the base snapshot.
884
+ * @param root - Temporary comparison directory receiving the materialized files.
885
+ * @param projectRoot - Repository root used as the working directory for `git show`.
886
+ * @returns Relative paths of files that existed in the base snapshot and were written to `root`.
887
+ */
888
+ function materializeBaseFiles(ref: string, files: string[], root: string, projectRoot: string): string[] {
479
889
  const materialized: string[] = [];
890
+ // Replay the prior versions of files associated with current findings, including related import-cycle files.
480
891
  for (const file of files) {
481
892
  try {
482
- const source = execFileSync("git", ["show", `${ref}:${file}`], { encoding: "utf8" });
893
+ const source = execFileSync("git", ["show", "--end-of-options", `${ref}:./${file}`], { cwd: projectRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
483
894
  const target = join(root, file);
484
895
  mkdirSync(dirname(target), { recursive: true });
485
896
  writeFileSync(target, source);
486
897
  materialized.push(file);
487
898
  } catch {
488
- // File is missing at the base ref, so every current finding in it is new.
899
+ // For example, a file created in this edit does not exist at HEAD, so there is no earlier match to apply.
489
900
  }
490
901
  }
491
902
  return materialized;
492
903
  }
493
904
 
494
- // Builds the analysis options for the base-ref scan: drops changed-region flags and resolves the
495
- // config path against the original root.
905
+ /**
906
+ * Derives base-scan options from `options`, targeting `paths` while disabling baseline and changed-region selection.
907
+ * Resolves explicit config and non-built-in profile paths before `chdir(tempRoot)` so replay loads the same rules.
908
+ *
909
+ * @param options - Original full-scan analysis options.
910
+ * @param paths - Materialized base file paths to analyse.
911
+ * @param originalRoot - Original project root used to locate a default config file or resolve a relative profile path.
912
+ * @returns Analysis options configured for a deterministic full scan of the materialized base files.
913
+ */
496
914
  function baseAnalysisOptions(options: AnalysisOptions, paths: string[], originalRoot: string): AnalysisOptions {
915
+ // Resolve settings from the launch directory before entering the temporary directory. With no selected config, use defaults.
916
+ const config = options.config ? absolutize(cwd(), options.config) : options.shouldSkipConfig ? undefined : defaultConfigPath(originalRoot);
917
+ const profile = options.profile !== undefined && !BUILT_IN_PROFILES.has(options.profile) && !BUILT_IN_PROFILES.has(`gruff.${options.profile}`)
918
+ ? absolutize(cwd(), options.profile)
919
+ : options.profile;
497
920
  return {
498
921
  ...withoutChangedRegion(options),
499
922
  paths,
500
- ...(options.config ? { config: absolutize(originalRoot, options.config) } : defaultConfigPathOption(originalRoot, options)),
923
+ ...(config === undefined ? {} : { config }),
924
+ ...(profile === undefined ? {} : { profile }),
501
925
  };
502
926
  }
503
927
 
504
- // Falls back to the project's default .gruff-ts.yaml for the base scan when one exists and config is
505
- // not skipped.
506
- function defaultConfigPathOption(originalRoot: string, options: AnalysisOptions): Partial<Pick<AnalysisOptions, "config">> {
507
- const defaultConfigPath = join(originalRoot, ".gruff-ts.yaml");
508
- return !options.shouldSkipConfig && existsSync(defaultConfigPath) ? { config: defaultConfigPath } : {};
509
- }
510
-
511
- // Strips every changed-region and baseline flag so the base-ref scan runs as a plain full scan,
512
- // deterministic regardless of the original changed-region request.
928
+ /**
929
+ * Copies `options` for a deterministic full base-ref scan, dropping changed-region selectors and baseline flags.
930
+ * Sets `shouldSkipBaseline` to true so default baseline lookup is disabled too.
931
+ *
932
+ * @param options - Analysis options from which `changedRanges`, `diff`, `diffPatch`, `since`, `baseline`, and `generateBaseline` are stripped.
933
+ * @returns Cloned options object configured to run a full scan without baseline lookup.
934
+ */
513
935
  function withoutChangedRegion(options: AnalysisOptions): AnalysisOptions {
514
- const { baseline: _baseline, changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, generateBaseline: _generateBaseline, since: _since, ...rest } = options;
936
+ const { baseline: _baseline, changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, generateBaseline: _generateBaseline, isDiffExplicitRef: _isDiffExplicitRef, since: _since, ...rest } = options;
515
937
  return { ...rest, shouldSkipBaseline: true };
516
938
  }
517
939
 
518
- // Orders findings by severity, then file, line, and rule id, giving the contract a deterministic,
519
- // stable finding order.
940
+ /**
941
+ * Sorts a copy of the supplied hook findings in stable severity, file, line, and rule ID order.
942
+ *
943
+ * @param findings - Hook findings to order; a finding without a line sorts as line 0.
944
+ * @returns New array of hook findings ordered deterministically.
945
+ */
520
946
  function sortHookFindings(findings: HookFinding[]): HookFinding[] {
521
947
  return [...findings].sort(
522
948
  (left, right) =>