@blundergoat/gruff-ts 0.4.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 +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  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 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  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 +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  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 +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  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 +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -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,86 +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[];
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.
59
+ diagnostics: HookDiagnostic[];
35
60
  suppressed: { count: number };
61
+ // The section 13a audit: one row per configured sensitive exclusion this run applied.
62
+ suppressions: HookSuppression[];
36
63
  ignored: { paths: SkippedPath[] };
37
- 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 };
79
+ }
80
+
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.
99
+ interface HookDiagnostic {
100
+ type: string;
101
+ severity: "info" | "warning" | "fatal";
102
+ message: string;
103
+ file?: string;
104
+ line?: number;
105
+ invalidatesRun?: false;
38
106
  }
39
107
 
40
- // A finding projected into the hook contract, with enum scope and non-null remediation, keyed for
41
- // 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.
42
110
  interface HookFinding {
43
111
  ruleId: string;
44
112
  pillar: string;
45
113
  severity: Severity;
114
+ confidence: Confidence;
46
115
  scope: HookScope;
47
116
  file: string;
48
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.
49
119
  endLine?: number;
120
+ // One-based match column, present when the scanner pinpointed the occurrence. Two secrets on one
121
+ // line share every other field, so this is the only thing that lets a consumer tell them apart.
122
+ column?: number;
50
123
  symbol: string | null;
124
+ // The 1-based declaration ordinal the identity hashed, and 0 when the finding names no symbol.
125
+ symbolOrdinal: number;
51
126
  message: string;
52
127
  remediation: string;
53
128
  metadata: Record<string, unknown>;
54
- 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;
55
133
  fingerprint: string;
56
134
  }
57
135
 
58
- // A gruff.baseline.v1 entry as read for new-only comparison; every field is optional because older
59
- // baselines predate stableIdentity.
60
- interface BaselineEntry {
61
- stableIdentity?: string;
62
- ruleId?: string;
63
- filePath?: string;
64
- symbol?: string;
65
- message?: string;
66
- }
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>;
67
138
 
68
- const HOOK_CONTRACT_VERSION = "gruff.hook.v1";
139
+ const HOOK_CONTRACT_VERSION = "gruff.hook.v2";
69
140
  const FILE_SCOPE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
70
141
  const PROJECT_SCOPE_RULE_IDS = new Set(["design.circular-import"]);
71
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 };
72
146
  const DESCRIPTORS = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor]));
73
-
74
- // Emits the gruff.hook.v1 capability handshake so a consumer can resolve flag names before a real
75
- // 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
+ */
76
156
  export function renderHookCapabilities(): string {
77
157
  return JSON.stringify({
78
158
  contractVersion: HOOK_CONTRACT_VERSION,
79
159
  analyzer: analyzerInfo(),
80
160
  supports: {
161
+ baseline: true,
162
+ baselineV3: true,
81
163
  changedRanges: true,
164
+ confidenceGate: true,
165
+ deepScanBudget: true,
166
+ // Producer advertisement only: diagnostics are always reported in-band; the advertised
167
+ // failOnDiagnostics flag is the explicit consumer request that changes exit semantics.
168
+ diagnostics: true,
82
169
  diff: true,
83
- baseline: true,
84
- scopeField: true,
85
- metadata: true,
86
- stableIdentity: true,
87
170
  ignoreReport: true,
171
+ metadata: true,
88
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",
89
183
  },
90
- flags: { changedRanges: "--changed-ranges", diff: "--diff", baseline: "--baseline" },
91
184
  flagOrder: "any" satisfies FlagOrder,
92
185
  }, null, 2) + "\n";
93
186
  }
94
187
 
95
- // Runs the analysis and projects it into the gruff.hook.v1 envelope: scoped findings, suppressed
96
- // 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
+ */
97
198
  export function renderHookReport(runAnalyse: HookAnalysisRunner, input: HookReportInput): string {
98
- const { currentReport, scopedReport } = hookAnalysisViews(runAnalyse, input);
99
- const baseIdentities = hookBaseIdentities(runAnalyse, input, currentReport);
100
- const findings = hookFindings(currentReport, scopedReport, input.hasChangedRegion, baseIdentities);
101
- const suppressedCount = hookSuppressedCount(scopedReport, findings, input.hasChangedRegion);
102
- return JSON.stringify(hookReport(scopedReport, findings, suppressedCount, true, null), null, 2) + "\n";
103
- }
104
-
105
- // 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
+ */
106
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.
107
219
  if (runAnalyse.hookViews) {
108
220
  return runAnalyse.hookViews(input.currentOptions, input.scopedOptions, input.hasChangedRegion);
109
221
  }
@@ -112,92 +224,442 @@ function hookAnalysisViews(runAnalyse: HookAnalysisRunner, input: HookReportInpu
112
224
  return { currentReport, scopedReport };
113
225
  }
114
226
 
115
- // Emits a gruff.hook.v1 envelope for an operational failure (config rejected, bad baseline, git
116
- // error) so the consumer always receives JSON with config.error set instead of a crash.
117
- export function renderHookConfigError(message: string, remediation: string): string {
118
- const error = `${message}\nSuggested fix: ${remediation}`;
119
- 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";
272
+ }
273
+
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 {
296
+ return {
297
+ contractVersion: HOOK_CONTRACT_VERSION,
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
+ };
120
307
  }
121
308
 
122
- // Assembles the gruff.hook.v1 envelope (sorted findings, suppressed count, ignored paths, config)
123
- // as the stable gruff.hook.v1 output contract.
124
- function hookReport(report: AnalysisReport | undefined, findings: HookFinding[], suppressedCount: number, isSchemaOk: boolean, error: string | null): HookReport {
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 {
125
320
  return {
126
321
  contractVersion: HOOK_CONTRACT_VERSION,
127
322
  analyzer: analyzerInfo(),
323
+ run,
128
324
  findings: sortHookFindings(findings),
325
+ diagnostics: report.diagnostics.map(toHookDiagnostic),
129
326
  suppressed: { count: suppressedCount },
130
- ignored: { paths: report?.paths.skipped ?? [] },
131
- config: { schemaOk: isSchemaOk, error },
327
+ suppressions: report.suppressions.map(toHookSuppression),
328
+ ignored: { paths: report.paths.skipped },
329
+ config: { schemaOk: true, error: null },
330
+ };
331
+ }
332
+
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 {
407
+ return {
408
+ type: diagnostic.diagnosticType,
409
+ severity: diagnostic.invalidatesRun === false ? "warning" : "fatal",
410
+ message: diagnostic.message,
411
+ ...(diagnostic.filePath === undefined ? {} : { file: diagnostic.filePath }),
412
+ ...(diagnostic.line === undefined ? {} : { line: diagnostic.line }),
413
+ ...(diagnostic.invalidatesRun === false ? { invalidatesRun: false as const } : {}),
132
414
  };
133
415
  }
134
416
 
135
- // Analyzer identity block shared by the capability and report envelopes.
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];
463
+ }
464
+
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
+ */
136
470
  function analyzerInfo(): { name: "gruff-ts"; version: string } {
137
471
  return { name: "gruff-ts", version: VERSION };
138
472
  }
139
473
 
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
+ */
140
484
  function hookFindings(
141
485
  currentReport: AnalysisReport,
142
486
  scopedReport: AnalysisReport,
143
- hasChangedRegion: boolean,
144
- baseIdentities: Set<string> | undefined,
145
- ): HookFinding[] {
146
- const scopedFindings = scopedReport.findings
147
- .map(toHookFinding)
148
- .filter((finding) => !hasChangedRegion || finding.scope !== "file");
149
- const withNewFileAndProject = hasChangedRegion && baseIdentities
150
- ? [...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)]
151
499
  : scopedFindings;
152
- return baseIdentities ? withNewFileAndProject.filter((finding) => !baseIdentities.has(finding.stableIdentity)) : withNewFileAndProject;
153
- }
154
-
155
- // Collects file- and project-scope findings that are new since the base, excluding any already
156
- // emitted, deduped by fingerprint.
157
- function newFileAndProjectFindings(currentReport: AnalysisReport, scopedFindings: HookFinding[], baseIdentities: Set<string>): HookFinding[] {
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))
503
+ : withNewFileAndProject;
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[] {
158
518
  const alreadyIncluded = new Set(scopedFindings.map((finding) => finding.fingerprint));
159
- return currentReport.findings
160
- .map(toHookFinding)
161
- .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;
162
556
  }
163
557
 
164
- // Counts the file/project findings the hook drops under changed-region attribution, excluding any
165
- // re-emitted as new, so the stable suppressed.count contract is never double-counted.
166
- 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 {
167
586
  if (!hasChangedRegion) {
168
587
  return 0;
169
588
  }
170
- 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;
171
593
  const fileOrProjectAnchorResiduals = scopedReport.findings.filter((finding) => {
172
594
  const scope = scopeForFinding(finding);
173
- return (scope === "file" || scope === "project") && !emittedFingerprints.has(finding.fingerprint);
595
+ return (scope === "file" || scope === "project") && !emittedKeys.has(hookOccurrenceKey(finding));
174
596
  }).length;
175
- return (scopedReport.suppressedCount ?? 0) + fileOrProjectAnchorResiduals;
597
+ return Math.max(0, (scopedReport.suppressedCount ?? 0) - reAdmittedFromSuppressed + fileOrProjectAnchorResiduals);
176
598
  }
177
599
 
178
- // Projects an analyser Finding into the hook shape, attaching scope, remediation, and the stable
179
- // identity plus fingerprint.
180
- function toHookFinding(finding: Finding): HookFinding {
181
- 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);
182
610
  return {
183
611
  ruleId: finding.ruleId,
184
612
  pillar: finding.pillar,
185
613
  severity: finding.severity,
186
- scope,
614
+ confidence: finding.confidence,
615
+ scope: scopeForFinding(finding),
187
616
  file: finding.filePath,
188
617
  ...(finding.line === undefined ? {} : { line: finding.line }),
189
- ...(finding.endLine === undefined ? {} : { endLine: finding.endLine }),
618
+ ...(endLine === undefined ? {} : { endLine }),
619
+ ...(finding.column === undefined ? {} : { column: finding.column }),
190
620
  symbol: finding.symbol ?? null,
621
+ symbolOrdinal: symbolOrdinalOf(finding),
191
622
  message: finding.message,
192
623
  remediation: finding.remediation ?? DESCRIPTORS.get(finding.ruleId)?.remediation ?? "Review and address this finding.",
193
624
  metadata: hookMetadata(finding),
194
- stableIdentity: hookStableIdentity(finding, scope),
625
+ stableIdentity: finding.baselineIdentity ?? null,
626
+ baselineStatus,
195
627
  fingerprint: finding.fingerprint,
196
628
  };
197
629
  }
198
630
 
199
- // Classifies a finding as line/symbol/file/project scope; this choice drives changed-region
200
- // 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
+ */
201
663
  function scopeForFinding(finding: Finding): HookScope {
202
664
  if (PROJECT_SCOPE_RULE_IDS.has(finding.ruleId)) {
203
665
  return "project";
@@ -211,28 +673,35 @@ function scopeForFinding(finding: Finding): HookScope {
211
673
  return "line";
212
674
  }
213
675
 
214
- // Returns normalized threshold metadata when the rule has one, else the finding's own metadata,
215
- // 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
+ */
216
683
  function hookMetadata(finding: Finding): Record<string, unknown> {
217
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
+ }
218
689
  return thresholdMetadata ?? finding.metadata;
219
690
  }
220
691
 
221
- // Maps known threshold rules to a measured/threshold/unit triple so the hook exposes a stable,
222
- // 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
+ */
223
698
  function thresholdMetadataFor(finding: Finding): Record<string, unknown> | undefined {
224
699
  const metadata = finding.metadata;
225
700
  switch (finding.ruleId) {
226
- case "complexity.cognitive":
227
701
  case "complexity.cyclomatic":
228
702
  return metricMetadata(metadata.complexity, metadata.threshold, "points");
229
- case "design.deep-relative-import":
230
- return metricMetadata(metadata.parentSegments, metadata.maxParentSegments, "segments");
231
703
  case "design.large-module-concentration":
232
704
  return metricMetadata(metadata.sharePercent, metadata.maxSharePercent, "percent");
233
- case "sensitive-data.hardcoded-env-value":
234
- case "sensitive-data.high-entropy-string":
235
- return metricMetadata(metadata.length, metadata.threshold, "characters");
236
705
  case "size.file-length":
237
706
  case "size.function-length":
238
707
  return metricMetadata(metadata.lines, metadata.threshold, "lines");
@@ -242,144 +711,135 @@ function thresholdMetadataFor(finding: Finding): Record<string, unknown> | undef
242
711
  return undefined;
243
712
  }
244
713
 
245
- // Builds the normalized measurement object, or undefined when the measured/threshold pair is not
246
- // 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
+ */
247
722
  function metricMetadata(measured: unknown, threshold: unknown, unit: string): Record<string, unknown> | undefined {
248
723
  return typeof measured === "number" && typeof threshold === "number"
249
724
  ? { measured, threshold, unit, direction: "above" }
250
725
  : undefined;
251
726
  }
252
727
 
253
- // Hashes (ruleId, filePath, scope component) into the 16-hex hook identity; line-insensitive so it
254
- // stays the stable cross-edit key for new-only filtering.
255
- function hookStableIdentity(finding: Finding, scope: HookScope): string {
256
- const component = stableIdentityComponent(finding, scope);
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);
257
737
  return createHash("sha256")
258
- .update([finding.ruleId, finding.filePath, component].join("\0"))
738
+ .update([finding.ruleId, finding.filePath, matchKeyComponent(finding, scope)].join("\0"))
259
739
  .digest("hex")
260
740
  .slice(0, 16);
261
741
  }
262
742
 
263
- // Derives the per-occurrence component of the stable hook identity: scope token, symbol, or message.
264
- function stableIdentityComponent(finding: { message: string; ruleId: string; symbol?: string }, 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 {
265
752
  if (scope === "file") {
266
753
  return scope;
267
754
  }
268
755
  if (scope === "project") {
269
- // Project rules are value-insensitive on their measurement, but component-level findings still
270
- // need a stable occurrence key. design.circular-import carries the canonical sorted SCC member
271
- // 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.
272
758
  return finding.symbol && finding.symbol.length > 0 ? `project:${finding.symbol}` : scope;
273
759
  }
274
760
  if (finding.symbol && finding.symbol.length > 0) {
275
761
  return `symbol:${finding.symbol}`;
276
762
  }
277
- // Symbol-less line findings (e.g. each hardcoded secret) key on the message so several same-rule
278
- // findings in one file get distinct identities. A value-insensitive `metric:${scope}` token
279
- // collapsed them all, letting one baselined finding suppress later new ones in the same file. The
280
- // message carries the per-occurrence discriminator (redacted preview) and no line number, so it
281
- // stays stable across surrounding edits. file scope above stays fully value-insensitive; project
282
- // scope folds in a canonical symbol when one is present.
283
- return `message:${finding.message}`;
284
- }
285
-
286
- // Builds the base identity set (from a baseline file and/or a diff base) that new-only filtering
287
- // compares against by stable hook identity; undefined when neither source is requested.
288
- function hookBaseIdentities(runAnalyse: HookAnalysisRunner, input: HookReportInput, currentReport: AnalysisReport): Set<string> | undefined {
289
- const identities = new Set<string>();
290
- if (input.baselinePath) {
291
- for (const identity of stableIdentitiesFromBaseline(input.baselinePath)) {
292
- identities.add(identity);
293
- }
294
- }
295
- if (input.diffBase) {
296
- for (const identity of stableIdentitiesFromDiffBase(runAnalyse, input.currentOptions, input.diffBase, currentReport)) {
297
- identities.add(identity);
298
- }
299
- }
300
- return identities.size > 0 || input.baselinePath || input.diffBase ? identities : undefined;
301
- }
302
-
303
- // Reads stable identities from a gruff.baseline.v1 file; the schema is the gruff.baseline.v1
304
- // contract and the reader throws on any schemaVersion mismatch.
305
- function stableIdentitiesFromBaseline(path: string): Set<string> {
306
- const baselinePath = absolutize(cwd(), path);
307
- const baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as { schemaVersion?: string; entries?: BaselineEntry[] };
308
- if (baseline.schemaVersion !== "gruff.baseline.v1") {
309
- throw new Error(`unsupported baseline schema in ${path}`);
310
- }
311
- return new Set((baseline.entries ?? []).flatMap(stableIdentityFromBaselineEntry));
312
- }
313
-
314
- // Resolves one baseline entry to hook identities: its stored identity, or a recomputed one from
315
- // ruleId, filePath, and scope.
316
- function stableIdentityFromBaselineEntry(entry: BaselineEntry): string[] {
317
- if (typeof entry.stableIdentity === "string") {
318
- return [entry.stableIdentity];
319
- }
320
- if (typeof entry.ruleId !== "string" || typeof entry.filePath !== "string") {
321
- return [];
322
- }
323
- const scope = baselineScopeForRule(entry.ruleId);
324
- const component = stableIdentityComponent({
325
- ruleId: entry.ruleId,
326
- message: entry.message ?? "",
327
- ...(typeof entry.symbol === "string" ? { symbol: entry.symbol } : {}),
328
- }, scope);
329
- return [
330
- createHash("sha256")
331
- .update([entry.ruleId, entry.filePath, component].join("\0"))
332
- .digest("hex")
333
- .slice(0, 16),
334
- ];
335
- }
336
-
337
- // Maps a rule id to its baseline scope so entries without a stored identity recompute the right
338
- // component.
339
- function baselineScopeForRule(ruleId: string): HookScope {
340
- if (PROJECT_SCOPE_RULE_IDS.has(ruleId)) {
341
- return "project";
342
- }
343
- if (FILE_SCOPE_RULE_IDS.has(ruleId)) {
344
- return "file";
763
+ // For occurrences without a symbol, differing messages distinguish matches of the same rule in a file.
764
+ const messageComponent = `message:${finding.message}`;
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.
767
+ return finding.column === undefined ? messageComponent : `${messageComponent}\0column:${finding.column}`;
768
+ }
769
+
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;
345
782
  }
346
- return "line";
347
- }
348
-
349
- 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(
350
798
  runAnalyse: HookAnalysisRunner,
351
799
  options: AnalysisOptions,
352
800
  diffBase: string,
353
801
  currentReport: AnalysisReport,
354
- ): Set<string> {
355
- 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.
356
806
  if (ref === undefined) {
357
- return new Set();
807
+ return undefined;
358
808
  }
359
809
  const files = [...new Set(currentReport.findings.flatMap(findingBasePaths))];
810
+ // With no current finding paths, the agent has nothing to compare with the base.
360
811
  if (files.length === 0) {
361
- return new Set();
812
+ return new Map();
362
813
  }
363
814
  const tempRoot = mkdtempSync(join(tmpdir(), "gruff-ts-hook-base-"));
364
815
  const previous = cwd();
816
+ const projectRoot = currentReport.run.projectRoot;
365
817
  try {
366
- 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.
367
820
  if (baseFiles.length === 0) {
368
- return new Set();
821
+ return new Map();
369
822
  }
823
+ const baseOptions = baseAnalysisOptions(options, baseFiles, projectRoot);
370
824
  chdir(tempRoot);
371
- const baseReport = runAnalyse(baseAnalysisOptions(options, baseFiles, previous));
372
- 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;
373
832
  } finally {
374
833
  chdir(previous);
375
834
  rmSync(tempRoot, { recursive: true, force: true });
376
835
  }
377
836
  }
378
837
 
379
- /*
380
- * A finding's base context is its anchor plus any project-relationship members from
381
- * `metadata.files`. Contract invariant: without every SCC member at the base ref, the replay
382
- * 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
383
843
  */
384
844
  function findingBasePaths(finding: Finding): string[] {
385
845
  const memberFiles = finding.metadata.files;
@@ -389,63 +849,100 @@ function findingBasePaths(finding: Finding): string[] {
389
849
  return [finding.filePath, ...memberFiles.filter((file): file is string => typeof file === "string")];
390
850
  }
391
851
 
392
- // Resolves a diff-base selector to the git rev whose blobs are the new-only base. "unstaged" diffs
393
- // the worktree against the index, so its base is the index ("" rev -> `git show :path`); "-" (stdin
394
- // patch) has no materializable base. Returns undefined only when no base can be replayed.
395
- 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.
396
864
  if (diffBase === "-") {
397
865
  return undefined;
398
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.
399
872
  if (diffBase === "unstaged") {
400
873
  return "";
401
874
  }
402
875
  return diffBase === "working-tree" || diffBase === "staged" ? "HEAD" : diffBase;
403
876
  }
404
877
 
405
- // Writes each file's blob at the base ref into the temp dir via git; a blob missing at the ref is a
406
- // recover path so that file's findings count as new (filesystem writes).
407
- 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[] {
408
889
  const materialized: string[] = [];
890
+ // Replay the prior versions of files associated with current findings, including related import-cycle files.
409
891
  for (const file of files) {
410
892
  try {
411
- 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"] });
412
894
  const target = join(root, file);
413
895
  mkdirSync(dirname(target), { recursive: true });
414
896
  writeFileSync(target, source);
415
897
  materialized.push(file);
416
898
  } catch {
417
- // 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.
418
900
  }
419
901
  }
420
902
  return materialized;
421
903
  }
422
904
 
423
- // Builds the analysis options for the base-ref scan: drops changed-region flags and resolves the
424
- // 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
+ */
425
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;
426
920
  return {
427
921
  ...withoutChangedRegion(options),
428
922
  paths,
429
- ...(options.config ? { config: absolutize(originalRoot, options.config) } : defaultConfigPathOption(originalRoot, options)),
923
+ ...(config === undefined ? {} : { config }),
924
+ ...(profile === undefined ? {} : { profile }),
430
925
  };
431
926
  }
432
927
 
433
- // Falls back to the project's default .gruff-ts.yaml for the base scan when one exists and config is
434
- // not skipped.
435
- function defaultConfigPathOption(originalRoot: string, options: AnalysisOptions): Partial<Pick<AnalysisOptions, "config">> {
436
- const defaultConfigPath = join(originalRoot, ".gruff-ts.yaml");
437
- return !options.shouldSkipConfig && existsSync(defaultConfigPath) ? { config: defaultConfigPath } : {};
438
- }
439
-
440
- // Strips every changed-region and baseline flag so the base-ref scan runs as a plain full scan,
441
- // 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
+ */
442
935
  function withoutChangedRegion(options: AnalysisOptions): AnalysisOptions {
443
- 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;
444
937
  return { ...rest, shouldSkipBaseline: true };
445
938
  }
446
939
 
447
- // Orders findings by severity, then file, line, and rule id, giving the contract a deterministic,
448
- // 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
+ */
449
946
  function sortHookFindings(findings: HookFinding[]): HookFinding[] {
450
947
  return [...findings].sort(
451
948
  (left, right) =>