@blundergoat/gruff-ts 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +20 -5
- package/SECURITY.md +1 -1
- package/docs/README.md +0 -1
- package/docs/agent-hook.md +14 -2
- package/docs/rules.md +4 -3
- package/package.json +17 -2
- package/src/analyser.ts +13 -1
- package/src/blocks.ts +56 -9
- package/src/changed-regions.ts +25 -17
- package/src/cli-program.ts +99 -3
- package/src/constants.ts +1 -1
- package/src/dashboard.ts +1 -1
- package/src/findings.ts +2 -0
- package/src/hook-contract.ts +435 -0
- package/src/rule-list.ts +1 -0
- package/src/sensitive-data-rules.ts +2 -2
- package/src/types.ts +1 -1
- package/docs/releasing.md +0 -106
- package/fixtures/sample.ts +0 -21
- package/scripts/bump-version.sh +0 -210
- package/scripts/check.sh +0 -4
- package/scripts/dependency-install.sh +0 -96
- package/scripts/dependency-update.sh +0 -177
- package/scripts/npm-publish.sh +0 -258
- package/scripts/preflight-checks.sh +0 -395
- package/scripts/start-dev.sh +0 -8
- package/scripts/test-performance.sh +0 -695
- package/src/fixtures/rule-catalogue-security-doctrine.ts +0 -160
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## v0.3.2 - 2026-06-09
|
|
4
|
+
|
|
5
|
+
- **Agent-hook contract v1** - adds `gruff-ts hook` and `gruff-ts hook --capabilities --format=json`, advertising `gruff.hook.v1` with `flagOrder:"any"`. Hook JSON uses the cross-analyzer contract fields (`file`, `scope`, `suppressed.count`, `ignored.paths`, `config.error`) with non-null remediation, stable hook identities, and machine-readable threshold metadata. Hook mode exits `0` when analysis runs, omits file/project-scope findings under changed-region attribution, and uses stable identity for baseline/diff new-only filtering (`--diff unstaged` compares against the index, `suppressed.count` never double-counts a re-emitted finding, and distinct project-scope findings such as separate import cycles anchored to one file keep distinct identities so baselining one never suppresses another). Operational failures (missing/malformed baseline, `--diff`/`--since` outside a git repo) report in-band as `config.error` with exit `2` rather than crashing. The conformance tests cover capabilities, scopes/enums, remediation, threshold metadata, stable identity across line/value changes (including multiple same-rule findings in one file and distinct import cycles sharing an anchor file), baseline and diff new-only, operational-failure JSON, flag ordering, advisory exit, ignored paths, and config-error JSON. Existing `analyse` / `summary` / `report` schema versions and exit semantics are unchanged. (`src/hook-contract.ts`, `src/cli-program.ts`, `src/hook-contract.test.ts`)
|
|
6
|
+
- **Changed-region symbol scope drops inherited file-wide findings** - `--changed-scope symbol` now suppresses file-wide and file-aggregate findings when the changed range does not touch their anchor/span, so inherited debt such as `size.file-length` is counted in `suppressedCount` instead of reported on unrelated edits. Use `--changed-scope file` for CI workflows that intentionally want every finding from a touched file, including deletion-only edits. Full scans still report every file-wide finding. No severity, threshold, rule-id, or pillar change. (`src/changed-regions.ts`, `src/changed-region-scope.test.ts`, `src/changed-region-contract.test.ts`)
|
|
7
|
+
- **Threshold findings expose reviewable measurements** - `size.file-length`, `size.function-length`, `size.parameter-count`, `complexity.cyclomatic`, `complexity.cognitive`, `sensitive-data.high-entropy-string`, and `sensitive-data.hardcoded-env-value` now carry additive `measured`/`threshold` measurement metadata, and block-anchored findings carry `endLine` spans so hook output can attribute symbol-scope findings without message parsing. `size.file-length` also gets finding-level remediation from the descriptor text. Existing fingerprints stay stable. (`src/analyser.ts`, `src/blocks.ts`, `src/findings.ts`, `src/sensitive-data-rules.ts`)
|
|
8
|
+
|
|
3
9
|
## v0.3.1 - 2026-06-03
|
|
4
10
|
|
|
5
11
|
- **JSON finding path alias and stable identity** - `analyse --format=json` and `report --format=json` now emit canonical `findings[].file` alongside the existing `findings[].filePath`; `filePath` is deprecated and will be removed in the next release. Findings also carry `stableIdentity`, a line-insensitive 16-hex identity for external diff tooling. Existing `fingerprint` values, baselines, SARIF fingerprints, dashboard data, and in-memory `filePath` consumers are unchanged.
|
package/CONTRIBUTING.md
CHANGED
|
@@ -47,7 +47,7 @@ The runtime lives under `src/`:
|
|
|
47
47
|
packs, fixtures, reports, and CLI surfaces.
|
|
48
48
|
|
|
49
49
|
Keep changes small and local. Do not add runtime dependencies beyond
|
|
50
|
-
`commander` and `
|
|
50
|
+
`commander`, `tsx`, and `typescript` unless that direction is explicitly accepted first.
|
|
51
51
|
|
|
52
52
|
## Rules For Rule Changes
|
|
53
53
|
|
package/README.md
CHANGED
|
@@ -20,11 +20,11 @@ Used as a hook on an agent's output, gruff-ts is a forcing function rather than
|
|
|
20
20
|
|
|
21
21
|
| Field | Value |
|
|
22
22
|
| --- | --- |
|
|
23
|
-
| Release line | Published `0.3.
|
|
23
|
+
| Release line | Published `0.3.2` package line |
|
|
24
24
|
| Runtime | Node.js `22+` |
|
|
25
25
|
| Package | `@blundergoat/gruff-ts` |
|
|
26
26
|
| Binary | `gruff-ts` |
|
|
27
|
-
| Rule catalogue |
|
|
27
|
+
| Rule catalogue | 120 rules across 11 pillars |
|
|
28
28
|
| Primary config | `.gruff-ts.yaml`; `.gruff.json`, `.gruff.yaml`, and `.gruff.yml` are fallback files |
|
|
29
29
|
| Analysis schema | `gruff.analysis.v2` |
|
|
30
30
|
| Baseline schema | `gruff.baseline.v1` |
|
|
@@ -223,7 +223,7 @@ Semantics:
|
|
|
223
223
|
|
|
224
224
|
## Rules And Pillars
|
|
225
225
|
|
|
226
|
-
The current catalogue contains
|
|
226
|
+
The current catalogue contains 120 rules:
|
|
227
227
|
|
|
228
228
|
| Pillar | Rules |
|
|
229
229
|
| --- | ---: |
|
|
@@ -237,12 +237,24 @@ The current catalogue contains 122 rules:
|
|
|
237
237
|
| `security` | 29 |
|
|
238
238
|
| `sensitive-data` | 10 |
|
|
239
239
|
| `size` | 3 |
|
|
240
|
-
| `test-quality` |
|
|
240
|
+
| `test-quality` | 14 |
|
|
241
241
|
|
|
242
242
|
Use `npx gruff-ts list-rules --format=json` for exact rule IDs, severities, confidence levels, remediation text, thresholds, and options.
|
|
243
243
|
|
|
244
244
|
## Baselines And Changed-Code Scans
|
|
245
245
|
|
|
246
|
+
For editor and coding-agent feedback, prefer the analyzer-owned hook contract:
|
|
247
|
+
|
|
248
|
+
```bash
|
|
249
|
+
npx gruff-ts hook --format=json --changed-ranges "3-3,8-10" src/foo.ts
|
|
250
|
+
npx gruff-ts hook --capabilities --format=json
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
`hook` emits `gruff.hook.v1` JSON with normalized `file`, `scope`, `suppressed.count`,
|
|
254
|
+
`ignored.paths`, non-null `remediation`, stable identities, and threshold metadata. Hook mode is
|
|
255
|
+
advisory: findings exit `0`; operational failures such as invalid config exit `2` and are reported
|
|
256
|
+
in `config.error`.
|
|
257
|
+
|
|
246
258
|
Baselines suppress reviewed findings by stable fingerprint:
|
|
247
259
|
|
|
248
260
|
```bash
|
|
@@ -268,6 +280,10 @@ npx gruff-ts analyse --format=json --since HEAD src/foo.ts
|
|
|
268
280
|
git diff | npx gruff-ts analyse --format=json --diff -
|
|
269
281
|
```
|
|
270
282
|
|
|
283
|
+
Use `--changed-scope file` when a CI workflow intentionally wants every finding from touched
|
|
284
|
+
files, including file-wide metrics such as `size.file-length`. The default `symbol` scope keeps
|
|
285
|
+
the coding-agent feedback focused on the changed line or enclosing declaration.
|
|
286
|
+
|
|
271
287
|
JSON output keeps the normal `findings` array and adds `suppressedCount` when changed-region filtering is active.
|
|
272
288
|
|
|
273
289
|
## Dashboard
|
|
@@ -316,7 +332,6 @@ Source lives under `src/`: `src/cli.ts` is the bootstrap, `src/cli-program.ts` o
|
|
|
316
332
|
- [Configuration](docs/configuration.md)
|
|
317
333
|
- [Rules catalogue](docs/rules.md)
|
|
318
334
|
- [Reports and CI](docs/reports-and-ci.md)
|
|
319
|
-
- [Release checklist](docs/releasing.md)
|
|
320
335
|
- [Contributing](CONTRIBUTING.md)
|
|
321
336
|
- [Security](SECURITY.md)
|
|
322
337
|
|
package/SECURITY.md
CHANGED
package/docs/README.md
CHANGED
|
@@ -11,7 +11,6 @@ Use these docs with the top-level README for the stable user-facing surface.
|
|
|
11
11
|
- [Output Formats](output-formats.md) - text, JSON, HTML, Markdown, GitHub annotations, hotspot, and SARIF.
|
|
12
12
|
- [CI Integration](ci-integration.md) - GitHub Actions, SARIF upload, baselines, and diff scans.
|
|
13
13
|
- [Dashboard](dashboard.md) - local dashboard flags and safety model.
|
|
14
|
-
- [Releasing](releasing.md) - release checks and packaging notes.
|
|
15
14
|
|
|
16
15
|
## Extra Docs
|
|
17
16
|
|
package/docs/agent-hook.md
CHANGED
|
@@ -6,12 +6,24 @@ gruff-ts is built to govern AI-generated code (see [Philosophy](philosophy.md) f
|
|
|
6
6
|
|
|
7
7
|
A coding agent will rewrite code until the checks pass. gruff-ts turns that into leverage: run it on the agent's change and gate on the result, so the agent has to resolve findings - add the missing doc comment, cut the unverifiable branching, drop the unsafe call, replace the mock-only test - before the change reaches you. What lands is already shaped for sign-off.
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
For CI-style gates, `analyse` owns the exit code:
|
|
10
10
|
|
|
11
11
|
- `0` - no finding met the `--fail-on` level; the change passes.
|
|
12
12
|
- `1` - at least one finding met `--fail-on`; the agent must fix and re-run.
|
|
13
13
|
- `2` - fatal (bad input, parse or config error); stop and surface it.
|
|
14
14
|
|
|
15
|
+
For editor or PostToolUse feedback, use the analyzer-owned hook contract instead:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
gruff-ts hook --format json --changed-ranges "12-40,88-90" src/foo.ts
|
|
19
|
+
gruff-ts hook --capabilities --format json
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`hook` emits `gruff.hook.v1` JSON with normalized `file`, `scope`, `suppressed.count`,
|
|
23
|
+
`ignored.paths`, non-null `remediation`, stable identities, and machine-readable threshold
|
|
24
|
+
metadata. Hook mode is advisory: findings exit `0`; config failures are returned in
|
|
25
|
+
`config.error` and exit `2`.
|
|
26
|
+
|
|
15
27
|
## Scan the change, not the repo
|
|
16
28
|
|
|
17
29
|
> **Goal:** govern only the code the agent changed, not the whole repo - so the agent resolves findings in its own diff and a clean change is never blocked by pre-existing findings elsewhere.
|
|
@@ -35,7 +47,7 @@ npx gruff-ts analyse --changed-ranges "12-40,88-90" src/foo.ts --fail-on=warning
|
|
|
35
47
|
git diff | npx gruff-ts analyse --diff - --fail-on=warning
|
|
36
48
|
```
|
|
37
49
|
|
|
38
|
-
Changed-region scans keep only findings attributable to the changed hunk or its enclosing symbol, so the agent fixes its own work instead of inheriting the whole backlog.
|
|
50
|
+
Changed-region scans keep only findings attributable to the changed hunk or its enclosing symbol, so the agent fixes its own work instead of inheriting the whole backlog. In `hook` mode, whole-file metrics such as `size.file-length` are omitted under changed-region attribution and counted in `suppressed.count`; they return only in full-scan hook output or when `--baseline` / `--diff` shows their stable identity is new. In `analyse`, use `--changed-scope file` for CI jobs that intentionally want every finding from a touched file.
|
|
39
51
|
|
|
40
52
|
## Respect the project's ignore policy
|
|
41
53
|
|
package/docs/rules.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Rules
|
|
2
2
|
|
|
3
|
-
`gruff-ts` exposes
|
|
3
|
+
`gruff-ts` exposes 120 rules across 11 pillars. This list is generated from the
|
|
4
4
|
public rule catalogue used by `gruff-ts list-rules`; severity, confidence,
|
|
5
5
|
thresholds, and option names are the defaults before project config overrides.
|
|
6
6
|
|
|
@@ -30,7 +30,7 @@ gruff-ts list-rules --format=json
|
|
|
30
30
|
- security: 29
|
|
31
31
|
- sensitive-data: 10
|
|
32
32
|
- size: 3
|
|
33
|
-
- test-quality:
|
|
33
|
+
- test-quality: 14
|
|
34
34
|
|
|
35
35
|
## Complexity
|
|
36
36
|
|
|
@@ -54,9 +54,10 @@ gruff-ts list-rules --format=json
|
|
|
54
54
|
- `docs.fixture-purpose-missing` (advisory; medium confidence): Flags large or scanner-relevant fixtures without a nearby purpose comment.
|
|
55
55
|
- `docs.magic-threshold-without-rationale` (advisory; medium confidence): Flags threshold-like numeric values without a nearby rationale comment.
|
|
56
56
|
- `docs.missing-error-behavior-doc` (advisory; medium confidence): Flags commented functions whose error behavior is not described.
|
|
57
|
+
- `docs.missing-exported-function-doc` (warning; medium confidence): Flags exported functions without a leading maintainer comment.
|
|
57
58
|
- `docs.missing-file-overview` (advisory; medium confidence): Flags source files without a top-of-file purpose comment.
|
|
58
|
-
- `docs.missing-function-doc` (advisory; medium confidence): Flags functions without a leading maintainer comment.
|
|
59
59
|
- `docs.missing-interface-doc` (advisory; medium confidence): Flags interfaces without a leading maintainer comment.
|
|
60
|
+
- `docs.missing-internal-function-doc` (advisory; medium confidence): Flags internal helper functions without a leading maintainer comment.
|
|
60
61
|
- `docs.missing-invariant-doc` (advisory; medium confidence): Flags commented declarations that own schema, fingerprint, baseline, or determinism contracts without saying so.
|
|
61
62
|
- `docs.missing-param-tag` (advisory; medium confidence): Flags documented exports with parameters missing @param tags.
|
|
62
63
|
- `docs.missing-public-doc` (advisory; medium confidence): Flags exported class, type, and enum APIs without a nearby doc comment.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blundergoat/gruff-ts",
|
|
3
|
-
"version": "0.3.
|
|
4
|
-
"description": "Governs AI-generated code so a human can verify it: a TypeScript/JavaScript static analyzer -
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "Governs AI-generated code so a human can verify it: a TypeScript/JavaScript static analyzer - 120 rules across 11 quality pillars, SARIF output, baselines, and a local dashboard.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Matthew Hansen (https://www.blundergoat.com/about)",
|
|
7
7
|
"homepage": "https://github.com/blundergoat/gruff-ts#readme",
|
|
@@ -36,6 +36,21 @@
|
|
|
36
36
|
"node": ">=22"
|
|
37
37
|
},
|
|
38
38
|
"type": "module",
|
|
39
|
+
"files": [
|
|
40
|
+
"bin/",
|
|
41
|
+
"src/",
|
|
42
|
+
"!src/**/*.test.ts",
|
|
43
|
+
"!src/fixtures/",
|
|
44
|
+
"docs/",
|
|
45
|
+
"!docs/releasing.md",
|
|
46
|
+
"!docs/coding-standards/",
|
|
47
|
+
"tsconfig.json",
|
|
48
|
+
"README.md",
|
|
49
|
+
"LICENSE",
|
|
50
|
+
"CHANGELOG.md",
|
|
51
|
+
"CONTRIBUTING.md",
|
|
52
|
+
"SECURITY.md"
|
|
53
|
+
],
|
|
39
54
|
"bin": {
|
|
40
55
|
"gruff-ts": "bin/gruff-ts"
|
|
41
56
|
},
|
package/src/analyser.ts
CHANGED
|
@@ -296,7 +296,19 @@ function analyseTextRules(file: SourceFile, source: string, config: Config, find
|
|
|
296
296
|
if (!isGeneratedLockfile(file.displayPath)) {
|
|
297
297
|
const fileLengthThreshold = threshold(config, "size.file-length", 750);
|
|
298
298
|
if (lines > fileLengthThreshold) {
|
|
299
|
-
findings.push(
|
|
299
|
+
findings.push(
|
|
300
|
+
makeFinding({
|
|
301
|
+
ruleId: "size.file-length",
|
|
302
|
+
message: `File has ${lines} lines, above the threshold of ${fileLengthThreshold}.`,
|
|
303
|
+
filePath: file.displayPath,
|
|
304
|
+
line: 1,
|
|
305
|
+
severity: ruleSeverity(config, "size.file-length", "warning"),
|
|
306
|
+
pillar: "size",
|
|
307
|
+
confidence: "high",
|
|
308
|
+
remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.",
|
|
309
|
+
metadata: { lines, threshold: fileLengthThreshold },
|
|
310
|
+
}),
|
|
311
|
+
);
|
|
300
312
|
}
|
|
301
313
|
}
|
|
302
314
|
|
package/src/blocks.ts
CHANGED
|
@@ -87,14 +87,26 @@ export interface BlockFindingWithMetadataArgs extends BlockFindingArgs {
|
|
|
87
87
|
// needing metadata or lower confidence go through `blockFindingWithMetadata` to keep the
|
|
88
88
|
// per-rule fingerprint shape stable.
|
|
89
89
|
export function blockFinding(args: BlockFindingArgs): Finding {
|
|
90
|
-
|
|
90
|
+
const endLine = args.block.startLine + args.block.lineCount - 1;
|
|
91
|
+
return makeFinding({ ruleId: args.ruleId, message: args.message, filePath: args.file.displayPath, line: args.block.startLine, endLine, severity: args.severity, pillar: args.pillar, confidence: "high", symbol: args.block.name });
|
|
91
92
|
}
|
|
92
93
|
|
|
93
94
|
// Block-anchored variant that ships rule-specific metadata. Confidence defaults to "medium"
|
|
94
95
|
// because metadata-carrying rules (e.g. test-quality magic-number) report measurements rather than
|
|
95
96
|
// definitive defects; the metadata payload is part of each rule's stable fingerprint contract.
|
|
96
97
|
export function blockFindingWithMetadata(args: BlockFindingWithMetadataArgs): Finding {
|
|
97
|
-
return makeFinding({
|
|
98
|
+
return makeFinding({
|
|
99
|
+
ruleId: args.ruleId,
|
|
100
|
+
message: args.message,
|
|
101
|
+
filePath: args.file.displayPath,
|
|
102
|
+
line: args.block.startLine,
|
|
103
|
+
endLine: args.block.startLine + args.block.lineCount - 1,
|
|
104
|
+
severity: args.severity,
|
|
105
|
+
pillar: args.pillar,
|
|
106
|
+
confidence: "medium",
|
|
107
|
+
symbol: args.block.name,
|
|
108
|
+
metadata: args.metadata,
|
|
109
|
+
});
|
|
98
110
|
}
|
|
99
111
|
|
|
100
112
|
// Computes cyclomatic and function-body once and threads them through the per-block rule pipeline.
|
|
@@ -134,7 +146,15 @@ export function analyseBlockRules(context: BlockRuleContext): void {
|
|
|
134
146
|
function pushFunctionLengthFinding(context: BlockRuleContext): void {
|
|
135
147
|
const functionLengthThreshold = threshold(context.config, "size.function-length", 200);
|
|
136
148
|
if (context.block.lineCount > functionLengthThreshold) {
|
|
137
|
-
context.findings.push(
|
|
149
|
+
context.findings.push(blockFindingWithMetadata({
|
|
150
|
+
ruleId: "size.function-length",
|
|
151
|
+
message: `Function \`${context.block.name}\` has ${context.block.lineCount} lines, above the threshold of ${functionLengthThreshold}.`,
|
|
152
|
+
file: context.file,
|
|
153
|
+
block: context.block,
|
|
154
|
+
severity: ruleSeverity(context.config, "size.function-length", "warning"),
|
|
155
|
+
pillar: "size",
|
|
156
|
+
metadata: { lines: context.block.lineCount, threshold: functionLengthThreshold },
|
|
157
|
+
}));
|
|
138
158
|
}
|
|
139
159
|
}
|
|
140
160
|
|
|
@@ -142,16 +162,34 @@ function pushFunctionLengthFinding(context: BlockRuleContext): void {
|
|
|
142
162
|
// already validated the signature shape upstream. Reports `size.parameter-count` when exceeded.
|
|
143
163
|
function pushParameterCountFinding(context: BlockRuleContext): void {
|
|
144
164
|
const params = context.block.params.split(",").map((value) => value.trim()).filter(Boolean).length;
|
|
145
|
-
|
|
146
|
-
|
|
165
|
+
const parameterCountThreshold = threshold(context.config, "size.parameter-count", 7);
|
|
166
|
+
if (params > parameterCountThreshold) {
|
|
167
|
+
context.findings.push(blockFindingWithMetadata({
|
|
168
|
+
ruleId: "size.parameter-count",
|
|
169
|
+
message: `Function \`${context.block.name}\` declares ${params} parameters.`,
|
|
170
|
+
file: context.file,
|
|
171
|
+
block: context.block,
|
|
172
|
+
severity: ruleSeverity(context.config, "size.parameter-count", "warning"),
|
|
173
|
+
pillar: "size",
|
|
174
|
+
metadata: { parameters: params, threshold: parameterCountThreshold },
|
|
175
|
+
}));
|
|
147
176
|
}
|
|
148
177
|
}
|
|
149
178
|
|
|
150
179
|
// Default threshold 15. Counts conditional keywords + boolean operators in the code body - see
|
|
151
180
|
// `blockRuleContext` for the pre-computed value. Reports `complexity.cyclomatic` when exceeded.
|
|
152
181
|
function pushCyclomaticFinding(context: BlockRuleContext): void {
|
|
153
|
-
|
|
154
|
-
|
|
182
|
+
const cyclomaticThreshold = threshold(context.config, "complexity.cyclomatic", 15);
|
|
183
|
+
if (context.cyclomatic > cyclomaticThreshold) {
|
|
184
|
+
context.findings.push(blockFindingWithMetadata({
|
|
185
|
+
ruleId: "complexity.cyclomatic",
|
|
186
|
+
message: `Function \`${context.block.name}\` has cyclomatic complexity ${context.cyclomatic}.`,
|
|
187
|
+
file: context.file,
|
|
188
|
+
block: context.block,
|
|
189
|
+
severity: ruleSeverity(context.config, "complexity.cyclomatic", "warning"),
|
|
190
|
+
pillar: "complexity",
|
|
191
|
+
metadata: { complexity: context.cyclomatic, threshold: cyclomaticThreshold },
|
|
192
|
+
}));
|
|
155
193
|
}
|
|
156
194
|
}
|
|
157
195
|
|
|
@@ -159,8 +197,17 @@ function pushCyclomaticFinding(context: BlockRuleContext): void {
|
|
|
159
197
|
// "deeply nested" intuition pure cyclomatic misses. Reports `complexity.cognitive` when exceeded.
|
|
160
198
|
function pushCognitiveFinding(context: BlockRuleContext): void {
|
|
161
199
|
const cognitive = context.cyclomatic + maxNestingDepth(context.block.codeBody);
|
|
162
|
-
|
|
163
|
-
|
|
200
|
+
const cognitiveThreshold = threshold(context.config, "complexity.cognitive", 15);
|
|
201
|
+
if (cognitive > cognitiveThreshold) {
|
|
202
|
+
context.findings.push(blockFindingWithMetadata({
|
|
203
|
+
ruleId: "complexity.cognitive",
|
|
204
|
+
message: `Function \`${context.block.name}\` has cognitive complexity ${cognitive}.`,
|
|
205
|
+
file: context.file,
|
|
206
|
+
block: context.block,
|
|
207
|
+
severity: ruleSeverity(context.config, "complexity.cognitive", "warning"),
|
|
208
|
+
pillar: "complexity",
|
|
209
|
+
metadata: { complexity: cognitive, threshold: cognitiveThreshold },
|
|
210
|
+
}));
|
|
164
211
|
}
|
|
165
212
|
}
|
|
166
213
|
|
package/src/changed-regions.ts
CHANGED
|
@@ -17,6 +17,9 @@ export interface ChangedRegionScope {
|
|
|
17
17
|
mode: ChangedScopeMode;
|
|
18
18
|
rangesByFile: Map<string, ChangedRange[]>;
|
|
19
19
|
wholeFiles: Set<string>;
|
|
20
|
+
// Every file that appears in the diff, including deletion-only files that contribute no target-side
|
|
21
|
+
// ranges. `file` scope keeps all findings in any changed file, so it consults this set, not ranges.
|
|
22
|
+
changedFiles: Set<string>;
|
|
20
23
|
explicitRanges?: ChangedRange[];
|
|
21
24
|
}
|
|
22
25
|
|
|
@@ -45,7 +48,7 @@ const FILE_WIDE_RULE_IDS = new Set(["design.large-module-concentration", "docs.m
|
|
|
45
48
|
// Builds the changed-region scope requested by CLI options. Throws on stdin diffs missing patch text.
|
|
46
49
|
export function changedRegionScope(options: AnalysisOptions): ChangedRegionScope | undefined {
|
|
47
50
|
if (options.changedRanges) {
|
|
48
|
-
return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
|
|
51
|
+
return { mode: options.changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set(), explicitRanges: parseChangedRanges(options.changedRanges) };
|
|
49
52
|
}
|
|
50
53
|
if (options.diffPatch !== undefined) {
|
|
51
54
|
return parseUnifiedDiff(options.diffPatch, options.changedScope);
|
|
@@ -84,7 +87,7 @@ export function filterChangedFindings(
|
|
|
84
87
|
return { findings: kept, suppressedCount };
|
|
85
88
|
}
|
|
86
89
|
|
|
87
|
-
// Keeps a finding when its own line
|
|
90
|
+
// Keeps a finding when its own line, enclosing declaration, or changed-file scope intersects the change.
|
|
88
91
|
function isFindingInChangedScope(
|
|
89
92
|
finding: Finding,
|
|
90
93
|
scope: ChangedRegionScope,
|
|
@@ -94,27 +97,29 @@ function isFindingInChangedScope(
|
|
|
94
97
|
if (scope.wholeFiles.has(finding.filePath)) {
|
|
95
98
|
return true;
|
|
96
99
|
}
|
|
100
|
+
// `file` scope keeps every finding in a changed file, so it must answer before the range check:
|
|
101
|
+
// a deletion-only edit produces no target-side ranges but still counts as touching the file.
|
|
102
|
+
if (scope.mode === "file") {
|
|
103
|
+
return scope.explicitRanges !== undefined || scope.changedFiles.has(finding.filePath);
|
|
104
|
+
}
|
|
97
105
|
const changedRanges = rangesForFindingFile(scope, finding.filePath);
|
|
98
106
|
if (changedRanges.length === 0) {
|
|
99
107
|
return false;
|
|
100
108
|
}
|
|
101
|
-
if (isFileWideFinding(finding) && (scope.rangesByFile.has(finding.filePath) || scope.explicitRanges)) {
|
|
102
|
-
return true;
|
|
103
|
-
}
|
|
104
109
|
const findingRange = { start: finding.line ?? 1, end: finding.endLine ?? finding.line ?? 1 };
|
|
105
110
|
if (overlapsAny(findingRange, changedRanges)) {
|
|
106
111
|
return true;
|
|
107
112
|
}
|
|
108
|
-
if (scope.mode
|
|
113
|
+
if (scope.mode !== "symbol" || isFileWideFinding(finding)) {
|
|
109
114
|
return false;
|
|
110
115
|
}
|
|
111
116
|
const declaration = enclosingDeclaration(finding, sources, declarationsByFile);
|
|
112
117
|
return declaration !== undefined && overlapsAny(declaration, changedRanges);
|
|
113
118
|
}
|
|
114
119
|
|
|
115
|
-
// Invariant: file-wide findings are line-1 anchors
|
|
120
|
+
// Invariant: file-wide findings are line-1 anchors with no declaration to widen through.
|
|
116
121
|
function isFileWideFinding(finding: Finding): boolean {
|
|
117
|
-
return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1
|
|
122
|
+
return FILE_WIDE_RULE_IDS.has(finding.ruleId) && finding.line === 1;
|
|
118
123
|
}
|
|
119
124
|
|
|
120
125
|
// Looks up explicit line ranges first because `--changed-ranges` applies to every selected file.
|
|
@@ -252,7 +257,7 @@ function gitDiffScope(mode: string, changedScope: ChangedScopeMode): ChangedRegi
|
|
|
252
257
|
|
|
253
258
|
// Parses a unified diff into file-level and hunk-level scope.
|
|
254
259
|
function parseUnifiedDiff(diffText: string, changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
255
|
-
const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
|
|
260
|
+
const scope: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
|
|
256
261
|
const state: DiffParseState = { currentFile: undefined, isNewFile: false, targetLine: undefined };
|
|
257
262
|
for (const line of diffText.split(/\r?\n/)) {
|
|
258
263
|
applyDiffLine(scope, state, line);
|
|
@@ -287,8 +292,11 @@ function applyTargetFileLine(scope: ChangedRegionScope, state: DiffParseState, l
|
|
|
287
292
|
const path = diffPath(line.slice(4));
|
|
288
293
|
state.currentFile = path === "/dev/null" ? undefined : path;
|
|
289
294
|
state.targetLine = undefined;
|
|
290
|
-
if (state.currentFile
|
|
291
|
-
scope.
|
|
295
|
+
if (state.currentFile) {
|
|
296
|
+
scope.changedFiles.add(state.currentFile);
|
|
297
|
+
if (state.isNewFile) {
|
|
298
|
+
scope.wholeFiles.add(state.currentFile);
|
|
299
|
+
}
|
|
292
300
|
}
|
|
293
301
|
return true;
|
|
294
302
|
}
|
|
@@ -337,17 +345,17 @@ function diffPath(rawPath: string): string {
|
|
|
337
345
|
|
|
338
346
|
// Treats untracked files as whole-file changed because git has no hunks for them yet.
|
|
339
347
|
function untrackedFileScope(changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
rangesByFile: new Map(),
|
|
343
|
-
wholeFiles: new Set(gitOutput(["ls-files", "--others", "--exclude-standard"]).split(/\r?\n/).filter(Boolean).map((path) => path.replaceAll("\\", "/"))),
|
|
344
|
-
};
|
|
348
|
+
const untracked = new Set(gitOutput(["ls-files", "--others", "--exclude-standard"]).split(/\r?\n/).filter(Boolean).map((path) => path.replaceAll("\\", "/")));
|
|
349
|
+
return { mode: changedScope, rangesByFile: new Map(), wholeFiles: untracked, changedFiles: new Set(untracked) };
|
|
345
350
|
}
|
|
346
351
|
|
|
347
352
|
// Unions staged, unstaged, and untracked scopes while whole-file changes dominate hunk ranges.
|
|
348
353
|
function mergeScopes(scopes: ChangedRegionScope[], changedScope: ChangedScopeMode): ChangedRegionScope {
|
|
349
|
-
const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set() };
|
|
354
|
+
const merged: ChangedRegionScope = { mode: changedScope, rangesByFile: new Map(), wholeFiles: new Set(), changedFiles: new Set() };
|
|
350
355
|
for (const scope of scopes) {
|
|
356
|
+
for (const file of scope.changedFiles) {
|
|
357
|
+
merged.changedFiles.add(file);
|
|
358
|
+
}
|
|
351
359
|
for (const file of scope.wholeFiles) {
|
|
352
360
|
merged.wholeFiles.add(file);
|
|
353
361
|
merged.rangesByFile.delete(file);
|
package/src/cli-program.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { ConfigLoadError } from "./config-load-error.ts";
|
|
|
10
10
|
import { loadConfig, minimumSeverityFor } from "./config.ts";
|
|
11
11
|
import { VERSION } from "./constants.ts";
|
|
12
12
|
import { startDashboard } from "./dashboard.ts";
|
|
13
|
+
import { renderHookCapabilities, renderHookConfigError, renderHookReport } from "./hook-contract.ts";
|
|
13
14
|
import { promptYesNo, shouldPromptForInit, writeDefaultConfig } from "./init-config.ts";
|
|
14
15
|
import { renderReport, renderSummary, renderSummaryJson } from "./report-renderers.ts";
|
|
15
16
|
import { completionShell, getRuleDescriptor, renderCompletionScript, renderConsoleList, renderProfileList, renderRuleDetail, renderRuleList, type RuleListFormat } from "./rule-list.ts";
|
|
@@ -101,7 +102,7 @@ function ansiEnabled(program: Command): boolean {
|
|
|
101
102
|
}
|
|
102
103
|
|
|
103
104
|
// `runAnalyse` is injected rather than imported to keep `cli-program.ts` off the analyser's
|
|
104
|
-
// dependency graph; see `.goat-flow/lessons/verification.md` on the original cli.ts ↔ cli-program.ts cycle.
|
|
105
|
+
// dependency graph; see `.goat-flow/learning-loop/lessons/verification.md` on the original cli.ts ↔ cli-program.ts cycle.
|
|
105
106
|
export function buildProgram(runAnalyse: AnalyseRunner): Command {
|
|
106
107
|
const program = new Command();
|
|
107
108
|
configureRootProgram(program);
|
|
@@ -109,6 +110,7 @@ export function buildProgram(runAnalyse: AnalyseRunner): Command {
|
|
|
109
110
|
registerCheckIgnoreCommand(program);
|
|
110
111
|
registerCompletionCommand(program);
|
|
111
112
|
registerDashboardCommand(program, runAnalyse);
|
|
113
|
+
registerHookCommand(program, runAnalyse);
|
|
112
114
|
registerInitCommand(program);
|
|
113
115
|
registerListCommand(program);
|
|
114
116
|
registerListProfilesCommand(program);
|
|
@@ -184,7 +186,7 @@ function registerAnalyseCommand(program: Command, runAnalyse: AnalyseRunner): vo
|
|
|
184
186
|
.option("--changed-ranges <ranges>", "Filter findings to changed regions, for example 3-3,8-10.")
|
|
185
187
|
.option("--since <ref>", "Filter findings to regions changed against a git base ref.")
|
|
186
188
|
.option("--diff [mode]", "Filter findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
|
|
187
|
-
.option("--changed-scope <scope>", "Changed-region scope: symbol or
|
|
189
|
+
.option("--changed-scope <scope>", "Changed-region scope: hunk, symbol, or file.", "symbol")
|
|
188
190
|
.option("--history-file <path>", "Append score trend history to this JSON file.")
|
|
189
191
|
.option("--baseline [path]", "Suppress findings that match a gruff baseline JSON file.")
|
|
190
192
|
.option("--generate-baseline [path]", "Write current findings to a gruff baseline JSON file.")
|
|
@@ -224,6 +226,59 @@ function registerCheckIgnoreCommand(program: Command): void {
|
|
|
224
226
|
});
|
|
225
227
|
}
|
|
226
228
|
|
|
229
|
+
// Dedicated agent-hook surface for gruff.hook.v1. It owns hook defaults (JSON, advisory exit, symbol
|
|
230
|
+
// attribution, no analysis baseline) and reports config failures in-band as config.error, exits 2.
|
|
231
|
+
function registerHookCommand(program: Command, runAnalyse: AnalyseRunner): void {
|
|
232
|
+
program
|
|
233
|
+
.command("hook")
|
|
234
|
+
.description("Run the gruff agent-hook contract and emit gruff.hook.v1 JSON.")
|
|
235
|
+
.argument("[paths...]", "Files or directories to analyse.")
|
|
236
|
+
.option("--format <format>", "Output format: json.", parseHookFormat, "json")
|
|
237
|
+
.option("--capabilities", "Print gruff.hook.v1 capability metadata and exit.")
|
|
238
|
+
.option("--config <path>", "Path to a gruff YAML config file.")
|
|
239
|
+
.option("--no-config", "Skip auto-applying the default .gruff-ts.yaml file for this run.")
|
|
240
|
+
.option("--profile <spec>", PROFILE_OPTION_DESCRIPTION)
|
|
241
|
+
.option("--include-ignored", "Include files under default and Git ignored paths; config ignores still apply.")
|
|
242
|
+
.option("--changed-ranges <ranges>", "Filter hook findings to changed regions, for example 3-3,8-10.")
|
|
243
|
+
.option("--since <ref>", "Filter hook findings to regions changed against a git base ref and compare against that ref.")
|
|
244
|
+
.option("--diff [mode]", "Filter hook findings to changed regions. Use working-tree, staged, unstaged, a base ref, or - for unified diff on stdin.")
|
|
245
|
+
.option("--baseline <path>", "Compare hook findings against a gruff baseline JSON file using stableIdentity.")
|
|
246
|
+
.action((paths: string[], rawOptions: Record<string, unknown>) => {
|
|
247
|
+
if (rawOptions.capabilities === true) {
|
|
248
|
+
writeCommandOutput(program, renderHookCapabilities());
|
|
249
|
+
process.exitCode = 0;
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
const scopedOptions = hookScopedOptions(paths, rawOptions);
|
|
254
|
+
const currentOptions = hookCurrentOptions(scopedOptions);
|
|
255
|
+
writeCommandOutput(program, renderHookReport(runAnalyse, {
|
|
256
|
+
currentOptions,
|
|
257
|
+
scopedOptions,
|
|
258
|
+
...hookBaselinePath(rawOptions),
|
|
259
|
+
...hookDiffBase(scopedOptions),
|
|
260
|
+
hasChangedRegion: hasHookChangedRegion(scopedOptions),
|
|
261
|
+
}));
|
|
262
|
+
process.exitCode = 0;
|
|
263
|
+
} catch (error) {
|
|
264
|
+
if (error instanceof ConfigLoadError) {
|
|
265
|
+
writeCommandOutput(program, renderHookConfigError(error.message, error.suggestion));
|
|
266
|
+
process.exitCode = 2;
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (error instanceof Error) {
|
|
270
|
+
// Keep gruff.hook.v1 machine-readable: baseline IO/parse/schema failures and git errors
|
|
271
|
+
// (--diff/--since outside a repo) report in-band as config.error with exit 2 instead of
|
|
272
|
+
// crashing with a raw stack and empty stdout, which would break the always-JSON contract.
|
|
273
|
+
writeCommandOutput(program, renderHookConfigError(error.message, "Check the --baseline path and schema, and run --diff/--since inside a git repository."));
|
|
274
|
+
process.exitCode = 2;
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
227
282
|
// Minimal AnalysisOptions for `check-ignore`: only the fields `loadConfig` and the ignore engine
|
|
228
283
|
// read. `--config` / `--no-config` resolve identically to `analyse`; `shouldIncludeIgnored` is false
|
|
229
284
|
// so default and gitignore matches are reported (config `paths.ignore` is reported regardless).
|
|
@@ -438,6 +493,15 @@ function parseSummaryFormat(rawFormat: string): "text" | "json" {
|
|
|
438
493
|
throw new InvalidArgumentError("must be text or json");
|
|
439
494
|
}
|
|
440
495
|
|
|
496
|
+
// Hook mode is a JSON-only contract. The parser is explicit so an unknown format value is caught
|
|
497
|
+
// before analysis: it throws InvalidArgumentError so commander reports a usage error.
|
|
498
|
+
function parseHookFormat(rawFormat: string): "json" {
|
|
499
|
+
if (rawFormat === "json") {
|
|
500
|
+
return rawFormat;
|
|
501
|
+
}
|
|
502
|
+
throw new InvalidArgumentError("must be json");
|
|
503
|
+
}
|
|
504
|
+
|
|
441
505
|
/*
|
|
442
506
|
* Commander argParser for `--top`-style numeric flags. Throws `InvalidArgumentError` on non-integer
|
|
443
507
|
* or negative input so commander reports a usage error and exits non-zero before the command runs.
|
|
@@ -481,7 +545,7 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
|
|
|
481
545
|
format,
|
|
482
546
|
failOn,
|
|
483
547
|
shouldIncludeIgnored: rawOptions.includeIgnored === true,
|
|
484
|
-
changedScope: stringChoice(rawOptions.changedScope, ["symbol", "hunk"], "symbol"),
|
|
548
|
+
changedScope: stringChoice(rawOptions.changedScope, ["symbol", "hunk", "file"], "symbol"),
|
|
485
549
|
...diffInput.options,
|
|
486
550
|
...changedRangesOption(rawOptions),
|
|
487
551
|
...sinceOption(rawOptions),
|
|
@@ -492,6 +556,38 @@ function normalizeOptions(paths: string[], rawOptions: Record<string, unknown>,
|
|
|
492
556
|
};
|
|
493
557
|
}
|
|
494
558
|
|
|
559
|
+
// Builds the scoped (changed-region) analysis options for the hook: JSON output, no fail-on gate,
|
|
560
|
+
// symbol scope, and no analysis baseline.
|
|
561
|
+
function hookScopedOptions(paths: string[], rawOptions: Record<string, unknown>): AnalysisOptions {
|
|
562
|
+
return normalizeOptions(
|
|
563
|
+
paths,
|
|
564
|
+
{ ...rawOptions, format: "json", failOn: "none", changedScope: "symbol", noBaseline: true },
|
|
565
|
+
{ shouldAllowBaselineFlag: false },
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// Strips changed-region selectors so the hook's full-scan pass sees the whole file, used for
|
|
570
|
+
// new-file and project-finding detection.
|
|
571
|
+
function hookCurrentOptions(options: AnalysisOptions): AnalysisOptions {
|
|
572
|
+
const { changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, since: _since, ...rest } = options;
|
|
573
|
+
return { ...rest, shouldSkipBaseline: true };
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// True when any changed-region selector (ranges, diff, since, stdin patch) is active for the run.
|
|
577
|
+
function hasHookChangedRegion(options: AnalysisOptions): boolean {
|
|
578
|
+
return Boolean(options.changedRanges || options.diff || options.since || options.diffPatch);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// Extracts the --baseline path for the hook's new-only filtering against the stable baseline contract.
|
|
582
|
+
function hookBaselinePath(rawOptions: Record<string, unknown>): Partial<{ baselinePath: string }> {
|
|
583
|
+
return typeof rawOptions.baseline === "string" ? { baselinePath: rawOptions.baseline } : {};
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// Picks the diff or since ref the hook compares against for new-only filtering, when one is set.
|
|
587
|
+
function hookDiffBase(options: AnalysisOptions): Partial<{ diffBase: string }> {
|
|
588
|
+
return options.diff ? { diffBase: options.diff } : options.since ? { diffBase: options.since } : {};
|
|
589
|
+
}
|
|
590
|
+
|
|
495
591
|
// Conditional spreads (not `config: undefined`) because `AnalysisOptions` runs under
|
|
496
592
|
// `exactOptionalPropertyTypes` - the absent and `undefined` cases are not interchangeable.
|
|
497
593
|
function configOption(rawOptions: Record<string, unknown>): Partial<Pick<AnalysisOptions, "config">> {
|
package/src/constants.ts
CHANGED
package/src/dashboard.ts
CHANGED
|
@@ -24,7 +24,7 @@ interface DashboardRouteInput {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
// Starts a loopback HTTP server. `analyse` is injected (not imported) to avoid a circular import
|
|
27
|
-
// back into `cli.ts`; see `.goat-flow/lessons/verification.md` on the dashboard import cycle.
|
|
27
|
+
// back into `cli.ts`; see `.goat-flow/learning-loop/lessons/verification.md` on the dashboard import cycle.
|
|
28
28
|
// Side effect: opens a listening socket and writes the URL to stdout unless `shouldWriteOutput` is false.
|
|
29
29
|
function startDashboard(host: string, port: number, projectRoot: string, analyse: DashboardAnalyse, shouldWriteOutput = true, profile?: string): void {
|
|
30
30
|
assertLoopbackHost(host);
|
package/src/findings.ts
CHANGED
|
@@ -9,6 +9,7 @@ interface FindingInput {
|
|
|
9
9
|
message: string;
|
|
10
10
|
filePath: string;
|
|
11
11
|
line?: number;
|
|
12
|
+
endLine?: number;
|
|
12
13
|
severity: Severity;
|
|
13
14
|
pillar: Pillar;
|
|
14
15
|
confidence: Confidence;
|
|
@@ -30,6 +31,7 @@ function makeFinding(input: FindingInput): Finding {
|
|
|
30
31
|
message: input.message,
|
|
31
32
|
filePath: input.filePath,
|
|
32
33
|
...(input.line ? { line: input.line } : {}),
|
|
34
|
+
...(input.endLine ? { endLine: input.endLine } : {}),
|
|
33
35
|
severity: input.severity,
|
|
34
36
|
pillar: input.pillar,
|
|
35
37
|
secondaryPillars: [],
|