@blundergoat/gruff-ts 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
package/src/constants.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
// Shared release constants that keep CLI,
|
|
2
|
-
|
|
1
|
+
// Shared release constants that keep CLI version output, JSON envelopes, and text report hints aligned.
|
|
2
|
+
//
|
|
3
|
+
// `VERSION` must match `package.json`; `OUTPUT_VOLUME_HINT_THRESHOLD` controls when `analyse` suggests `gruff-ts summary`.
|
|
4
|
+
const VERSION = "0.6.0";
|
|
3
5
|
|
|
4
6
|
/*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* in 2026-05-25 feedback (1643 findings) - the threshold earns its keep at the cross-over.
|
|
7
|
+
* Finding count at which `analyse --format text` appends a one-line pointer to `gruff-ts summary`.
|
|
8
|
+
*
|
|
9
|
+
* Below 50 findings a flat terminal list stays easy to scan; above 50 the per-rule digest avoids scroll fatigue.
|
|
9
10
|
*/
|
|
10
11
|
const OUTPUT_VOLUME_HINT_THRESHOLD = 50;
|
|
11
12
|
|
package/src/context-doc-rules.ts
CHANGED
|
@@ -31,19 +31,32 @@ type ContextDocFindingInput = ContextDocFindingDetails & {
|
|
|
31
31
|
comment: CommentRecord;
|
|
32
32
|
};
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
/**
|
|
35
|
+
* Evaluates `block` against rationale, side-effect, error, and invariant documentation checks and records any gaps.
|
|
36
|
+
*
|
|
37
|
+
* @param file - Source file whose display path anchors each emitted finding.
|
|
38
|
+
* @param block - Parsed function block whose body, name, and metrics are inspected.
|
|
39
|
+
* @param comment - Leading comment record providing the review text and finding line number.
|
|
40
|
+
* @param config - Active analyzer configuration supplying complexity thresholds.
|
|
41
|
+
* @param findings - Mutable report list where stable context-doc findings are appended.
|
|
42
|
+
* @returns Nothing. Appends stable findings for each missing context class to `findings`.
|
|
43
|
+
*/
|
|
37
44
|
export function pushFunctionContextFindings(file: SourceFile, block: FunctionBlock, comment: CommentRecord, config: Config, findings: Finding[]): void {
|
|
38
45
|
for (const detail of functionContextDocFindings(block, comment.text, config)) {
|
|
39
46
|
findings.push(contextDocFinding({ file, comment, ...detail }));
|
|
40
47
|
}
|
|
41
48
|
}
|
|
42
49
|
|
|
43
|
-
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
50
|
+
/**
|
|
51
|
+
* Records an invariant-doc finding when an interface declaration signals a public contract that `comment` leaves unmarked.
|
|
52
|
+
* Other declaration kinds are ignored, and the caller skips signature-restatement comments to avoid duplicate findings.
|
|
53
|
+
*
|
|
54
|
+
* @param file - Source file whose display path anchors the finding.
|
|
55
|
+
* @param lines - Full file lines used to slice the interface declaration block.
|
|
56
|
+
* @param declaration - Commented declaration metadata checked for interface kind and contract signals.
|
|
57
|
+
* @param comment - Leading comment record supplying the review text and finding line.
|
|
58
|
+
* @param findings - Mutable report list receiving any `docs.missing-invariant-doc` finding.
|
|
59
|
+
* @returns Nothing. Appends an invariant-doc finding to `findings` only when an interface signals an undocumented contract.
|
|
47
60
|
*/
|
|
48
61
|
export function pushDeclarationContextFindings(file: SourceFile, lines: string[], declaration: CommentedDeclaration, comment: CommentRecord, findings: Finding[]): void {
|
|
49
62
|
if (declaration.kind !== "interface") {
|
|
@@ -61,8 +74,14 @@ export function pushDeclarationContextFindings(file: SourceFile, lines: string[]
|
|
|
61
74
|
);
|
|
62
75
|
}
|
|
63
76
|
|
|
64
|
-
|
|
65
|
-
|
|
77
|
+
/**
|
|
78
|
+
* Collects context-doc finding details for `block` by checking `commentText` against complexity, side-effect, error, and invariant rules.
|
|
79
|
+
*
|
|
80
|
+
* @param block - Parsed function block whose name, body, and complexity metrics are inspected.
|
|
81
|
+
* @param commentText - Raw comment text evaluated for rationale, side-effect, `@throws`, and invariant markers.
|
|
82
|
+
* @param config - Active analyzer configuration providing configurable complexity thresholds.
|
|
83
|
+
* @returns Finding detail entries for each detected documentation gap, or an empty array when none apply.
|
|
84
|
+
*/
|
|
66
85
|
function functionContextDocFindings(block: FunctionBlock, commentText: string, config: Config): ContextDocFindingDetails[] {
|
|
67
86
|
const details: ContextDocFindingDetails[] = [];
|
|
68
87
|
const body = block.codeBody;
|
|
@@ -85,15 +104,30 @@ function functionContextDocFindings(block: FunctionBlock, commentText: string, c
|
|
|
85
104
|
return details;
|
|
86
105
|
}
|
|
87
106
|
|
|
88
|
-
|
|
107
|
+
/**
|
|
108
|
+
* Evaluates `block` against configurable length and cyclomatic limits plus fixed cognitive and nesting limits for missing rationale docs.
|
|
109
|
+
* Skips test-case callbacks because test files already use `docs.fixture-purpose-missing` for setup rationale.
|
|
110
|
+
*
|
|
111
|
+
* @param block - Function block checked for test status, complexity eligibility, and symbol name.
|
|
112
|
+
* @param commentText - Leading comment text inspected for accepted rationale markers.
|
|
113
|
+
* @param config - Active analyzer configuration supplying length and cyclomatic thresholds.
|
|
114
|
+
* @returns Missing-why finding details when `commentText` lacks a rationale marker for a complex block, or `undefined` otherwise.
|
|
115
|
+
*/
|
|
89
116
|
function complexFunctionContextDocFinding(block: FunctionBlock, commentText: string, config: Config): ContextDocFindingDetails | undefined {
|
|
90
|
-
if (!isComplexContextCandidate(block, config) || hasComplexWhyMarker(commentText)) {
|
|
117
|
+
if (block.isTest || !isComplexContextCandidate(block, config) || hasComplexWhyMarker(commentText, block.name)) {
|
|
91
118
|
return undefined;
|
|
92
119
|
}
|
|
93
120
|
return contextDocDetails(block.name, "docs.missing-why-for-complex-code", `Complex function \`${block.name}\` has a comment, but it does not explain why the control flow exists.`, "Explain the tradeoff, compatibility reason, or invariant behind the complex control flow.", "complex-code");
|
|
94
121
|
}
|
|
95
122
|
|
|
96
|
-
|
|
123
|
+
/**
|
|
124
|
+
* Checks whether a function with observable side-effect signals lacks a side-effect marker in its comment.
|
|
125
|
+
*
|
|
126
|
+
* @param block - Function block supplying the declaration name for signal and finding metadata.
|
|
127
|
+
* @param body - Masked function body searched for filesystem, process, environment, or server mutations.
|
|
128
|
+
* @param commentText - Leading comment text checked for side-effect vocabulary.
|
|
129
|
+
* @returns Missing-side-effect finding details when an effect signal exists without a marker, or `undefined` otherwise.
|
|
130
|
+
*/
|
|
97
131
|
function sideEffectContextDocFinding(block: FunctionBlock, body: string, commentText: string): ContextDocFindingDetails | undefined {
|
|
98
132
|
if (!hasSideEffectSignal(block.name, body) || hasSideEffectMarker(commentText)) {
|
|
99
133
|
return undefined;
|
|
@@ -101,15 +135,28 @@ function sideEffectContextDocFinding(block: FunctionBlock, body: string, comment
|
|
|
101
135
|
return contextDocDetails(block.name, "docs.missing-side-effect-doc", `Function \`${block.name}\` performs side effects that its comment does not describe.`, "Name the observable side effect such as filesystem, process, environment, or network mutation.", "side-effect");
|
|
102
136
|
}
|
|
103
137
|
|
|
104
|
-
|
|
138
|
+
/**
|
|
139
|
+
* Checks whether a function whose body contains a word-boundary `throw` lacks an `@throws` tag in its comment.
|
|
140
|
+
*
|
|
141
|
+
* @param block - Function block supplying the symbol name for any emitted finding details.
|
|
142
|
+
* @param body - Function code body tested for `throw` at word boundaries.
|
|
143
|
+
* @param commentText - Leading comment text inspected for an `@throws` marker.
|
|
144
|
+
* @returns Missing-error-behavior finding details when `body` throws without an `@throws` tag, or `undefined` otherwise.
|
|
145
|
+
*/
|
|
105
146
|
function errorBehaviorContextDocFinding(block: FunctionBlock, body: string, commentText: string): ContextDocFindingDetails | undefined {
|
|
106
|
-
if (
|
|
147
|
+
if (!/\bthrow\b/.test(body) || /@throws\b/.test(commentText)) {
|
|
107
148
|
return undefined;
|
|
108
149
|
}
|
|
109
|
-
return contextDocDetails(block.name, "docs.missing-error-behavior-doc", `Function \`${block.name}\`
|
|
150
|
+
return contextDocDetails(block.name, "docs.missing-error-behavior-doc", `Function \`${block.name}\` throws, but its comment has no @throws tag.`, "Add an @throws tag that names each error the function throws and when.", "error-behavior");
|
|
110
151
|
}
|
|
111
152
|
|
|
112
|
-
|
|
153
|
+
/**
|
|
154
|
+
* Checks whether a function signaling a public contract lacks an invariant marker in its comment.
|
|
155
|
+
*
|
|
156
|
+
* @param block - Function block whose name and body are checked for contract signals.
|
|
157
|
+
* @param commentText - Leading comment text checked for invariant or contract markers.
|
|
158
|
+
* @returns Missing-invariant finding details when a contract signal has no marker, or `undefined` otherwise.
|
|
159
|
+
*/
|
|
113
160
|
function invariantContextDocFinding(block: FunctionBlock, commentText: string): ContextDocFindingDetails | undefined {
|
|
114
161
|
if (!hasInvariantFunctionSignal(block) || hasInvariantMarker(commentText)) {
|
|
115
162
|
return undefined;
|
|
@@ -117,8 +164,16 @@ function invariantContextDocFinding(block: FunctionBlock, commentText: string):
|
|
|
117
164
|
return contextDocDetails(block.name, "docs.missing-invariant-doc", `Function \`${block.name}\` maintains a public contract that its comment does not describe.`, "Document the schema, fingerprint, baseline, sorting, or determinism invariant.", "invariant");
|
|
118
165
|
}
|
|
119
166
|
|
|
120
|
-
|
|
121
|
-
|
|
167
|
+
/**
|
|
168
|
+
* Builds the rule-specific detail payload shared by all context-doc findings.
|
|
169
|
+
*
|
|
170
|
+
* @param symbol - Declaration name attached to the finding.
|
|
171
|
+
* @param ruleId - Context-doc rule identifier selected for the gap.
|
|
172
|
+
* @param message - Human-readable summary explaining the missing documentation.
|
|
173
|
+
* @param remediation - Actionable repair advice shown to the developer.
|
|
174
|
+
* @param contextClass - Missing-context discriminator stored in `metadata.contextClass`.
|
|
175
|
+
* @returns Structured finding details containing the supplied fields and `contextClass` metadata.
|
|
176
|
+
*/
|
|
122
177
|
function contextDocDetails(symbol: string, ruleId: string, message: string, remediation: string, contextClass: string): ContextDocFindingDetails {
|
|
123
178
|
return {
|
|
124
179
|
symbol,
|
|
@@ -129,8 +184,12 @@ function contextDocDetails(symbol: string, ruleId: string, message: string, reme
|
|
|
129
184
|
};
|
|
130
185
|
}
|
|
131
186
|
|
|
132
|
-
|
|
133
|
-
|
|
187
|
+
/**
|
|
188
|
+
* Materializes a stable advisory documentation finding anchored at the reviewed comment's line.
|
|
189
|
+
*
|
|
190
|
+
* @param input - Bundle containing the source file, comment record, symbol, rule ID, message, remediation, and metadata.
|
|
191
|
+
* @returns Stable `Finding` record in the documentation pillar with advisory severity and medium confidence.
|
|
192
|
+
*/
|
|
134
193
|
function contextDocFinding(input: ContextDocFindingInput): Finding {
|
|
135
194
|
const { file, comment, symbol, ruleId, message, remediation, metadata } = input;
|
|
136
195
|
return makeFinding({
|
|
@@ -147,38 +206,79 @@ function contextDocFinding(input: ContextDocFindingInput): Finding {
|
|
|
147
206
|
});
|
|
148
207
|
}
|
|
149
208
|
|
|
150
|
-
//
|
|
209
|
+
// The cognitive-complexity limit that marks a callable complex enough to need a "why" comment. 15 is the retired
|
|
210
|
+
// `complexity.cognitive` rule's default, so default scans keep the same gate; no profile or config value moves it.
|
|
211
|
+
const COMPLEX_CONTEXT_COGNITIVE_LIMIT = 15;
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Determines whether `block` crosses any complexity threshold that requires a rationale comment.
|
|
215
|
+
*
|
|
216
|
+
* @param block - Function block providing line count and optional complexity metrics (falling back to baseline metrics if absent).
|
|
217
|
+
* @param config - Active analyzer configuration supplying `size.function-length` and `complexity.cyclomatic` limits.
|
|
218
|
+
* @returns `true` if `block` exceeds a configured length or cyclomatic limit, the fixed cognitive limit, or nesting depth 3.
|
|
219
|
+
*/
|
|
151
220
|
function isComplexContextCandidate(block: FunctionBlock, config: Config): boolean {
|
|
152
221
|
// A legacy span-only caller cannot reparse here, so it receives the same neutral fallback as block rules.
|
|
153
222
|
const sharedComplexityMetrics = block.complexityMetrics ?? baseComplexityMetrics();
|
|
154
223
|
return (
|
|
155
|
-
block.
|
|
224
|
+
block.codeLineCount > threshold(config, "size.function-length", 200) ||
|
|
156
225
|
sharedComplexityMetrics.cyclomatic > threshold(config, "complexity.cyclomatic", 15) ||
|
|
157
|
-
sharedComplexityMetrics.cognitive >
|
|
226
|
+
sharedComplexityMetrics.cognitive > COMPLEX_CONTEXT_COGNITIVE_LIMIT ||
|
|
158
227
|
sharedComplexityMetrics.maximumControlFlowNesting > 3
|
|
159
228
|
);
|
|
160
229
|
}
|
|
161
230
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Checks whether `text` contains an accepted rationale marker for the callable named `functionName`.
|
|
233
|
+
* Direct markers pass alone; constraint markers also require at least four word occurrences absent from `functionName`.
|
|
234
|
+
*
|
|
235
|
+
* @param text - Comment text evaluated for direct or constraint-based rationale phrasing.
|
|
236
|
+
* @param functionName - Callable name whose words are excluded when counting extra words for constraint markers.
|
|
237
|
+
* @returns `true` when `text` matches a direct rationale marker or a constraint marker with enough extra prose words.
|
|
238
|
+
*/
|
|
239
|
+
function hasComplexWhyMarker(text: string, functionName: string): boolean {
|
|
240
|
+
if (/\b(?:because|why|intentional|trade-?off|compat(?:ibility|ible)?|avoid|preserve)\b|\b(?:due to|so that|in order to|required by)\b/i.test(text)) {
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
return /\b(?:must|never|always|only|otherwise|instead|unless|since|cannot|to avoid|to keep|needs to)\b/i.test(text) && saysMoreThanTheName(text, functionName);
|
|
166
244
|
}
|
|
167
245
|
|
|
168
|
-
//
|
|
169
|
-
//
|
|
170
|
-
|
|
171
|
-
|
|
246
|
+
// Threshold of extra words, beyond the function name's own, before a constraint word counts as rationale: four,
|
|
247
|
+
// because a one-line paraphrase of a function name rarely adds that many.
|
|
248
|
+
const RATIONALE_MINIMUM_EXTRA_WORDS = 4;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Checks whether comment prose (excluding tag lines such as `@param`) adds enough vocabulary beyond `functionName`.
|
|
252
|
+
* Serves as a prerequisite for accepting constraint words as rationale instead of a bare name paraphrase.
|
|
253
|
+
*
|
|
254
|
+
* @param text - Raw comment text whose non-tag lines are tokenized into lowercase words.
|
|
255
|
+
* @param functionName - CamelCase or delimited callable name split into words excluded from the extra-word count.
|
|
256
|
+
* @returns `true` when the prose contains at least `RATIONALE_MINIMUM_EXTRA_WORDS` words absent from `functionName`.
|
|
257
|
+
*/
|
|
258
|
+
function saysMoreThanTheName(text: string, functionName: string): boolean {
|
|
259
|
+
const nameWords = new Set(functionName.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean));
|
|
260
|
+
const prose = text.split("\n").filter((line) => !/^\s*(?:\*\s*)?@/.test(line)).join(" ");
|
|
261
|
+
const extraWords = (prose.toLowerCase().match(/[a-z][a-z'-]*/g) ?? []).filter((word) => !nameWords.has(word));
|
|
262
|
+
return extraWords.length >= RATIONALE_MINIMUM_EXTRA_WORDS;
|
|
172
263
|
}
|
|
173
264
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
265
|
+
/**
|
|
266
|
+
* Checks whether `text` contains a whole-word side-effect marker, regardless of case.
|
|
267
|
+
* A side-effect signal with no matching marker qualifies for the missing-side-effect finding.
|
|
268
|
+
*
|
|
269
|
+
* @param text - Comment text searched for side-effect verbs and target keywords.
|
|
270
|
+
* @returns `true` when `text` names an observable side effect such as writes, reads, mutates, spawns, network, filesystem, or environment.
|
|
271
|
+
*/
|
|
272
|
+
function hasSideEffectMarker(text: string): boolean {
|
|
273
|
+
return /\b(?:writes|reads|persists|mutates|starts|spawns|network|filesystem|environment)\b/i.test(text);
|
|
178
274
|
}
|
|
179
275
|
|
|
180
|
-
|
|
181
|
-
|
|
276
|
+
/**
|
|
277
|
+
* Checks whether the supplied comment text contains a word that counts as a public contract marker.
|
|
278
|
+
*
|
|
279
|
+
* @param text - Comment text tested case-insensitively for contract and invariant vocabulary.
|
|
280
|
+
* @returns `true` when `text` includes an accepted invariant, contract, schema, fingerprint, or determinism marker.
|
|
281
|
+
*/
|
|
182
282
|
function hasInvariantMarker(text: string): boolean {
|
|
183
283
|
return /\b(?:invariant|contract|must|stable|deterministic|schema|fingerprint)\b/i.test(text);
|
|
184
284
|
}
|
|
@@ -187,43 +287,71 @@ const SIDE_EFFECT_BODY_PATTERNS = [
|
|
|
187
287
|
/\b(?:writeFile(?:Sync)?|appendFile(?:Sync)?|mkdir(?:Sync)?|rm(?:Sync)?|rename(?:Sync)?|createWriteStream)\s*\(/,
|
|
188
288
|
/\bprocess\.chdir\s*\(/,
|
|
189
289
|
/\bprocess\.env\.[A-Za-z0-9_]+\s*=/,
|
|
190
|
-
/\b(?:exec|execFile|spawn)(?:Sync)?\s*\(/,
|
|
191
290
|
/\b(?:response|res)\.(?:write|end|setHeader|writeHead)\s*\(/,
|
|
192
291
|
/\bcreateServer\s*\(|\.listen\s*\(/,
|
|
193
292
|
] as const;
|
|
194
293
|
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
294
|
+
/**
|
|
295
|
+
* Determines whether a callable has externally observable side effects via body patterns or naming conventions.
|
|
296
|
+
* Checks `SIDE_EFFECT_BODY_PATTERNS`, process execution calls, and `write`/`recordHistory`/`startDashboard` name prefixes.
|
|
297
|
+
*
|
|
298
|
+
* @param name - Callable identifier checked against side-effect-implying name prefixes.
|
|
299
|
+
* @param body - Masked function body searched for filesystem, process, environment, or HTTP/server calls.
|
|
300
|
+
* @returns `true` when either a body call pattern or a matching name prefix signals an external effect.
|
|
301
|
+
*/
|
|
198
302
|
function hasSideEffectSignal(name: string, body: string): boolean {
|
|
199
|
-
return SIDE_EFFECT_BODY_PATTERNS.some((pattern) => pattern.test(body)) || /^(?:write|recordHistory|startDashboard)\b/.test(name);
|
|
303
|
+
return SIDE_EFFECT_BODY_PATTERNS.some((pattern) => pattern.test(body)) || hasProcessExecutionCall(body) || /^(?:write|recordHistory|startDashboard)\b/.test(name);
|
|
200
304
|
}
|
|
201
305
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
306
|
+
/**
|
|
307
|
+
* Detects child-process execution calls inside masked function body text so literal contents cannot count as process calls.
|
|
308
|
+
* Matches `exec`, `execFile`, or `spawn` (including `Sync` forms) when unprefixed or qualified with `child_process`, `childProcess`, or `cp`.
|
|
309
|
+
*
|
|
310
|
+
* @param body - Masked function body searched while excluding member calls such as `/re/.exec(line)`.
|
|
311
|
+
* @returns `true` for a qualifying process-execution call, or `false` when no match qualifies.
|
|
312
|
+
*/
|
|
313
|
+
function hasProcessExecutionCall(body: string): boolean {
|
|
314
|
+
for (const match of body.matchAll(/\b(?:(child_process|childProcess|cp)\.)?(?:exec|execFile|spawn)(?:Sync)?\s*\(/g)) {
|
|
315
|
+
if (match[1] !== undefined || body[(match.index ?? 0) - 1] !== ".") {
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return false;
|
|
206
320
|
}
|
|
207
321
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
322
|
+
/**
|
|
323
|
+
* Searches both the callable name and body for vocabulary tied to the analyser's stable contracts.
|
|
324
|
+
* Matches terms such as `fingerprint`, `schemaVersion`, `baseline`, `AnalysisReport`, `Finding`, `deterministic`, `dedupe`, and `sort`.
|
|
325
|
+
*
|
|
326
|
+
* @param block - Function block supplying the symbol name and code body to scan.
|
|
327
|
+
* @returns `true` on a case-insensitive contract signal match so the caller can check the comment for an invariant marker.
|
|
328
|
+
*/
|
|
211
329
|
function hasInvariantFunctionSignal(block: FunctionBlock): boolean {
|
|
212
330
|
const signalText = [block.name, block.codeBody].join("\n");
|
|
213
331
|
return /\b(?:fingerprint|schemaVersion|baseline|AnalysisReport|Finding|stable sort|deterministic|dedupe|sort)\b/i.test(signalText);
|
|
214
332
|
}
|
|
215
333
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
334
|
+
/**
|
|
335
|
+
* Checks whether `declaration.name` or its interface block text contains public-contract vocabulary.
|
|
336
|
+
* A match makes the interface eligible for an invariant-documentation check.
|
|
337
|
+
*
|
|
338
|
+
* @param lines - Full file lines from which the interface declaration block is extracted.
|
|
339
|
+
* @param declaration - Interface declaration metadata providing the name and starting line number.
|
|
340
|
+
* @returns `true` when the interface name or body references contract terms such as `fingerprint`, `baseline`, `report`, or `deterministic`.
|
|
341
|
+
*/
|
|
219
342
|
function hasInvariantInterfaceSignal(lines: string[], declaration: CommentedDeclaration): boolean {
|
|
220
343
|
const blockText = declarationBlockText(lines, declaration.line);
|
|
221
344
|
const signalText = `${declaration.name}\n${blockText}`;
|
|
222
345
|
return /\b(?:fingerprint|schemaVersion|baseline|report|Finding|AnalysisReport|Baseline|stable|deterministic)\b/i.test(signalText);
|
|
223
346
|
}
|
|
224
347
|
|
|
225
|
-
|
|
226
|
-
|
|
348
|
+
/**
|
|
349
|
+
* Collects declaration lines starting at `line` until the closing `}` line for interface vocabulary checks.
|
|
350
|
+
*
|
|
351
|
+
* @param lines - Full array of source lines for the file.
|
|
352
|
+
* @param line - One-based line number where the declaration starts.
|
|
353
|
+
* @returns Joined slice of lines from `line` through the first trimmed `}` line, inclusive.
|
|
354
|
+
*/
|
|
227
355
|
function declarationBlockText(lines: string[], line: number): string {
|
|
228
356
|
const start = Math.max(0, line - 1);
|
|
229
357
|
const collected: string[] = [];
|
package/src/dashboard.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
// Loopback
|
|
1
|
+
// Loopback-only HTTP server powering `gruff-ts dashboard` on `127.0.0.1:8767`.
|
|
2
|
+
//
|
|
3
|
+
// Runs live analyses on request and renders the interactive HTML control panel via `report-html.ts`.
|
|
4
|
+
// Binds exclusively to a loopback host by default so unauthenticated callers cannot trigger remote directory scans.
|
|
2
5
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
3
6
|
import { chdir, cwd, stdout } from "node:process";
|
|
4
7
|
import { dashboardErrorHtml, dashboardHomeHtml, renderHtml } from "./report-html.ts";
|
|
5
|
-
import type { AnalysisOptions, AnalysisReport } from "./types.ts";
|
|
8
|
+
import type { AnalysisOptions, AnalysisReport, DeepScanBudgetOverride } from "./types.ts";
|
|
6
9
|
|
|
7
10
|
type DashboardAnalyse = (options: AnalysisOptions) => AnalysisReport;
|
|
8
11
|
|
|
@@ -13,6 +16,7 @@ interface DashboardContext {
|
|
|
13
16
|
port: number;
|
|
14
17
|
projectRoot: string;
|
|
15
18
|
profile?: string;
|
|
19
|
+
deepScanBudget?: DeepScanBudgetOverride;
|
|
16
20
|
}
|
|
17
21
|
|
|
18
22
|
// Per-request projectRoot + scanPath. Sourced from `?projectRoot` and `?path` query parameters and
|
|
@@ -23,12 +27,28 @@ interface DashboardRouteInput {
|
|
|
23
27
|
scanPath: string;
|
|
24
28
|
}
|
|
25
29
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Starts the loopback dashboard. Inject analyse to avoid the CLI import cycle documented in .goat-flow/learning-loop/lessons/verification.md.
|
|
32
|
+
*
|
|
33
|
+
* @param host - loopback address to bind. Use 127.0.0.1 or localhost.
|
|
34
|
+
* @param port - port for the HTTP listener
|
|
35
|
+
* @param projectRoot - default project directory for dashboard scans
|
|
36
|
+
* @param analyse - callback that produces the analysis report for a dashboard scan
|
|
37
|
+
* @param shouldWriteOutput - whether to write the listening URL to stdout. Defaults to true.
|
|
38
|
+
* @param profile - optional analysis profile forwarded to dashboard scans
|
|
39
|
+
* @param deepScanBudget - optional deep-scan budget override forwarded to dashboard scans
|
|
40
|
+
* @returns nothing. Side effect: opens the listener and writes its URL to stdout when output is enabled.
|
|
41
|
+
* @throws {Error} - the host is neither 127.0.0.1 nor localhost
|
|
42
|
+
*/
|
|
43
|
+
function startDashboard(host: string, port: number, projectRoot: string, analyse: DashboardAnalyse, shouldWriteOutput = true, profile?: string, deepScanBudget?: DeepScanBudgetOverride): void {
|
|
30
44
|
assertLoopbackHost(host);
|
|
31
|
-
const context: DashboardContext = {
|
|
45
|
+
const context: DashboardContext = {
|
|
46
|
+
host,
|
|
47
|
+
port,
|
|
48
|
+
projectRoot,
|
|
49
|
+
...(profile !== undefined ? { profile } : {}),
|
|
50
|
+
...(deepScanBudget !== undefined ? { deepScanBudget } : {}),
|
|
51
|
+
};
|
|
32
52
|
const server = createServer((request, response) => handleDashboardRequest(context, analyse, request, response));
|
|
33
53
|
server.listen(port, host, () => {
|
|
34
54
|
if (shouldWriteOutput) {
|
|
@@ -37,17 +57,31 @@ function startDashboard(host: string, port: number, projectRoot: string, analyse
|
|
|
37
57
|
});
|
|
38
58
|
}
|
|
39
59
|
|
|
40
|
-
|
|
41
|
-
|
|
60
|
+
/**
|
|
61
|
+
* Validates the requested bind host before the listener opens. The dashboard accepts filesystem paths from query strings,
|
|
62
|
+
* so loopback binding is its safety boundary.
|
|
63
|
+
*
|
|
64
|
+
* @param host - bind host address checked against 127.0.0.1 or localhost
|
|
65
|
+
* @returns Nothing. Completes normally when host is a permitted loopback address.
|
|
66
|
+
* @throws {Error} - when the host is anything other than 127.0.0.1 or localhost.
|
|
67
|
+
*/
|
|
42
68
|
function assertLoopbackHost(host: string): void {
|
|
43
69
|
if (host !== "127.0.0.1" && host !== "localhost") {
|
|
44
70
|
throw new Error("Dashboard host must be 127.0.0.1 or localhost.");
|
|
45
71
|
}
|
|
46
72
|
}
|
|
47
73
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
74
|
+
/**
|
|
75
|
+
* Routes dashboard HTTP requests for `/health`, `/scan`, `/`, and fallback 404 responses, writing the result to response.
|
|
76
|
+
* Health and home responses use no-store; scans run analyse with context's profile and budget and return HTML with no-store.
|
|
77
|
+
* A missing request URL selects home; unrecognized paths return 404 without a cache-control override.
|
|
78
|
+
*
|
|
79
|
+
* @param context - server configuration supplying host, port, default project root, profile, and deep-scan budget
|
|
80
|
+
* @param analyse - callback used to execute analysis on `/scan` requests
|
|
81
|
+
* @param request - incoming HTTP request whose URL selects the route and query inputs
|
|
82
|
+
* @param response - outgoing HTTP response written with status, headers, and body
|
|
83
|
+
* @returns Nothing. Writes the routed text or HTML response to response and ends it.
|
|
84
|
+
*/
|
|
51
85
|
function handleDashboardRequest(context: DashboardContext, analyse: DashboardAnalyse, request: IncomingMessage, response: ServerResponse): void {
|
|
52
86
|
const url = new URL(request.url ?? "/", `http://${context.host}:${context.port}`);
|
|
53
87
|
if (url.pathname === "/health") {
|
|
@@ -55,7 +89,7 @@ function handleDashboardRequest(context: DashboardContext, analyse: DashboardAna
|
|
|
55
89
|
return;
|
|
56
90
|
}
|
|
57
91
|
if (url.pathname === "/scan") {
|
|
58
|
-
renderDashboardScan(response, dashboardRouteInput(url, context.projectRoot), analyse, context.profile);
|
|
92
|
+
renderDashboardScan(response, dashboardRouteInput(url, context.projectRoot), analyse, context.profile, context.deepScanBudget);
|
|
59
93
|
return;
|
|
60
94
|
}
|
|
61
95
|
if (url.pathname !== "/") {
|
|
@@ -66,8 +100,15 @@ function handleDashboardRequest(context: DashboardContext, analyse: DashboardAna
|
|
|
66
100
|
writeHtmlResponse(response, 200, dashboardHomeHtml(input.root, input.scanPath));
|
|
67
101
|
}
|
|
68
102
|
|
|
69
|
-
|
|
70
|
-
|
|
103
|
+
/**
|
|
104
|
+
* Extracts the project root and scan path from the dashboard URL for the home and scan routes.
|
|
105
|
+
* Missing projectRoot uses the supplied launch root; missing path uses "." within the selected root, while empty values pass through.
|
|
106
|
+
* The scan route passes the root to chdir and the path to analyse under the DashboardRouteInput loopback trust assumption.
|
|
107
|
+
*
|
|
108
|
+
* @param url - parsed request URL containing optional `projectRoot` and `path` query parameters
|
|
109
|
+
* @param projectRoot - default launch root used when the `projectRoot` query parameter is absent
|
|
110
|
+
* @returns Route input object with `root` and `scanPath` resolved from query parameters or defaults.
|
|
111
|
+
*/
|
|
71
112
|
function dashboardRouteInput(url: URL, projectRoot: string): DashboardRouteInput {
|
|
72
113
|
return {
|
|
73
114
|
root: url.searchParams.get("projectRoot") ?? projectRoot,
|
|
@@ -75,10 +116,20 @@ function dashboardRouteInput(url: URL, projectRoot: string): DashboardRouteInput
|
|
|
75
116
|
};
|
|
76
117
|
}
|
|
77
118
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
119
|
+
/**
|
|
120
|
+
* Runs an HTML analysis scan in `input.root` and writes the rendered report or a 500 error page to response.
|
|
121
|
+
* A failed directory switch, scan, render, or write is reported in the 500 page; omitted optional overrides leave those choices to analyse.
|
|
122
|
+
* Attempts to restore the working directory in `finally` so later requests inherit a stable environment.
|
|
123
|
+
*
|
|
124
|
+
* @param response - outgoing HTTP response written with the 200 report HTML or 500 error HTML
|
|
125
|
+
* @param input - route target specifying the working directory `root` and `scanPath` to analyse
|
|
126
|
+
* @param analyse - callback that executes the HTML-formatted analysis against `input.scanPath`
|
|
127
|
+
* @param profile - optional analysis profile forwarded when defined
|
|
128
|
+
* @param deepScanBudget - optional deep-scan budget override forwarded when defined
|
|
129
|
+
* @returns Nothing. Writes the HTML scan or error response and restores the previous working directory.
|
|
130
|
+
* @throws {Error} - when reading or restoring the working directory fails, or writing the error page throws.
|
|
131
|
+
*/
|
|
132
|
+
function renderDashboardScan(response: ServerResponse, input: DashboardRouteInput, analyse: DashboardAnalyse, profile?: string, deepScanBudget?: DeepScanBudgetOverride): void {
|
|
82
133
|
const previous = cwd();
|
|
83
134
|
try {
|
|
84
135
|
chdir(input.root);
|
|
@@ -86,6 +137,7 @@ function renderDashboardScan(response: ServerResponse, input: DashboardRouteInpu
|
|
|
86
137
|
paths: [input.scanPath],
|
|
87
138
|
shouldSkipConfig: false,
|
|
88
139
|
...(profile !== undefined ? { profile } : {}),
|
|
140
|
+
...(deepScanBudget !== undefined ? { deepScanBudget } : {}),
|
|
89
141
|
format: "html",
|
|
90
142
|
failOn: "none",
|
|
91
143
|
shouldIncludeIgnored: false,
|
|
@@ -100,15 +152,28 @@ function renderDashboardScan(response: ServerResponse, input: DashboardRouteInpu
|
|
|
100
152
|
}
|
|
101
153
|
}
|
|
102
154
|
|
|
103
|
-
|
|
104
|
-
|
|
155
|
+
/**
|
|
156
|
+
* Writes body as UTF-8 HTML to response with statusCode and uses no-store so proxies do not serve stale findings to the maintainer.
|
|
157
|
+
*
|
|
158
|
+
* @param response - outgoing HTTP response to write headers and body to
|
|
159
|
+
* @param statusCode - HTTP status code sent in the response head
|
|
160
|
+
* @param body - UTF-8 HTML payload written before ending the response
|
|
161
|
+
* @returns Nothing. Writes the HTML headers and body to response, then ends it.
|
|
162
|
+
*/
|
|
105
163
|
function writeHtmlResponse(response: ServerResponse, statusCode: number, body: string): void {
|
|
106
164
|
response.writeHead(statusCode, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
107
165
|
response.end(body);
|
|
108
166
|
}
|
|
109
167
|
|
|
110
|
-
|
|
111
|
-
|
|
168
|
+
/**
|
|
169
|
+
* Writes body as UTF-8 plain text to response with statusCode, optionally disabling caching for health probes.
|
|
170
|
+
*
|
|
171
|
+
* @param response - outgoing HTTP response to write headers and body to
|
|
172
|
+
* @param statusCode - HTTP status code sent in the response head
|
|
173
|
+
* @param body - UTF-8 plain-text payload written before ending the response
|
|
174
|
+
* @param shouldUseNoStore - adds `cache-control: no-store` when true (for health probes) and leaves cache policy unset when false (for 404)
|
|
175
|
+
* @returns Nothing. Writes the plain-text headers and body to response, then ends it.
|
|
176
|
+
*/
|
|
112
177
|
function writeTextResponse(response: ServerResponse, statusCode: number, body: string, shouldUseNoStore: boolean): void {
|
|
113
178
|
response.writeHead(statusCode, { "content-type": "text/plain; charset=utf-8", ...(shouldUseNoStore ? { "cache-control": "no-store" } : {}) });
|
|
114
179
|
response.end(body);
|