@blundergoat/gruff-ts 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/CONTRIBUTING.md +1 -1
  3. package/README.md +20 -5
  4. package/SECURITY.md +1 -1
  5. package/docs/README.md +0 -1
  6. package/docs/agent-hook.md +14 -2
  7. package/docs/configuration.md +15 -0
  8. package/docs/reports-and-ci.md +21 -0
  9. package/docs/rules.md +22 -12
  10. package/package.json +17 -2
  11. package/src/analyser.ts +410 -122
  12. package/src/baseline-options.ts +90 -0
  13. package/src/blocks.ts +56 -9
  14. package/src/changed-regions.ts +46 -17
  15. package/src/cli-program.ts +103 -4
  16. package/src/cli.ts +3 -2
  17. package/src/constants.ts +1 -1
  18. package/src/dashboard.ts +1 -1
  19. package/src/dead-code-rules.ts +10 -3
  20. package/src/discovery.ts +27 -3
  21. package/src/findings.ts +2 -0
  22. package/src/hook-contract.ts +457 -0
  23. package/src/line-rules.ts +126 -19
  24. package/src/process-exec-metadata.ts +153 -0
  25. package/src/project-config-rules.ts +21 -8
  26. package/src/project-rules.ts +159 -42
  27. package/src/report-renderers.ts +3 -0
  28. package/src/rule-list.ts +1 -0
  29. package/src/rules.ts +5 -5
  30. package/src/sensitive-data-rules.ts +134 -12
  31. package/src/source-text.ts +47 -22
  32. package/src/static-analysis-redundant-rules.ts +46 -2
  33. package/src/types.ts +16 -1
  34. package/docs/releasing.md +0 -106
  35. package/fixtures/sample.ts +0 -21
  36. package/scripts/bump-version.sh +0 -210
  37. package/scripts/check.sh +0 -4
  38. package/scripts/dependency-install.sh +0 -96
  39. package/scripts/dependency-update.sh +0 -177
  40. package/scripts/npm-publish.sh +0 -258
  41. package/scripts/preflight-checks.sh +0 -395
  42. package/scripts/start-dev.sh +0 -8
  43. package/scripts/test-performance.sh +0 -695
  44. package/src/fixtures/rule-catalogue-security-doctrine.ts +0 -160
@@ -0,0 +1,153 @@
1
+ // Metadata classifiers for `security.process-exec` findings. They turn a process call's
2
+ // first argument and shell option into review hints without changing whether the rule fires.
3
+ import { escapeRegex } from "./findings-helpers.ts";
4
+
5
+ type ProcessExecArgumentSource = "literal" | "process-exec-path" | "local-const" | "local-builder" | "parameter" | "member" | "template" | "unknown";
6
+
7
+ // Stable scanner state for the first-argument boundary walk.
8
+ interface ArgumentScanState {
9
+ depth: number;
10
+ quote: string | undefined;
11
+ }
12
+
13
+ // Stable result of consuming one character in the first-argument scanner.
14
+ interface ArgumentScanStep {
15
+ state: ArgumentScanState;
16
+ skip: number;
17
+ isBoundary: boolean;
18
+ }
19
+
20
+ /**
21
+ * Builds non-suppressing metadata for a child-process finding.
22
+ *
23
+ * @param callName Matched process API name, for example `spawn` or `execSync`.
24
+ * @param rawSource Original source text used for literal and local-const classification.
25
+ * @param callStart Byte offset where the process call starts in the file.
26
+ * @param rawSegment Original source segment from call start through closing paren.
27
+ * @param codeSegment Masked source segment used to read the shell option safely.
28
+ * @returns Stable metadata describing command-source shape and shell mode.
29
+ */
30
+ export function processExecMetadata(callName: string, rawSource: string, callStart: number, rawSegment: string, codeSegment: string): Record<string, unknown> {
31
+ const firstArgument = firstProcessCallArgument(rawSegment);
32
+ return {
33
+ callName,
34
+ argumentSource: processExecArgumentSource(rawSource, callStart, firstArgument),
35
+ shellEnabled: processExecShellEnabled(callName, codeSegment),
36
+ };
37
+ }
38
+
39
+ // Extracts the first top-level call argument so commas inside arrays, objects, calls, or strings
40
+ // do not misclassify `spawn("node", ["script,arg"])` as a dynamic command.
41
+ function firstProcessCallArgument(rawSegment: string): string {
42
+ const argsText = rawSegment.slice(rawSegment.indexOf("(") + 1, rawSegment.lastIndexOf(")"));
43
+ return firstTopLevelArgument(argsText).trim();
44
+ }
45
+
46
+ // Walks one argument list with quote and nesting state. The invariant is deliberately narrow:
47
+ // find only the first top-level comma, because command-source classification does not need parsing.
48
+ function firstTopLevelArgument(argsText: string): string {
49
+ let state: ArgumentScanState = { depth: 0, quote: undefined };
50
+ for (let index = 0; index < argsText.length; index += 1) {
51
+ const step = argumentScanStep(argsText, index, state);
52
+ if (step.isBoundary) {
53
+ return argsText.slice(0, index);
54
+ }
55
+ state = step.state;
56
+ index += step.skip;
57
+ }
58
+ return argsText;
59
+ }
60
+
61
+ // Advances one character in the argument scan while keeping string escapes and nesting separate.
62
+ function argumentScanStep(argsText: string, index: number, state: ArgumentScanState): ArgumentScanStep {
63
+ const character = argsText[index] ?? "";
64
+ if (state.quote) {
65
+ return quotedArgumentScanStep(argsText, index, state, character);
66
+ }
67
+ if (isQuoteDelimiter(character)) {
68
+ return scanStep({ depth: state.depth, quote: character });
69
+ }
70
+ if (isOpeningDelimiter(character)) {
71
+ return scanStep({ depth: state.depth + 1, quote: undefined });
72
+ }
73
+ if (isClosingDelimiter(character)) {
74
+ return scanStep({ depth: Math.max(0, state.depth - 1), quote: undefined });
75
+ }
76
+ return scanStep(state, character === "," && state.depth === 0);
77
+ }
78
+
79
+ // Handles one quoted character; escaped characters skip the next byte so an escaped quote stays inside.
80
+ function quotedArgumentScanStep(argsText: string, index: number, state: ArgumentScanState, character: string): ArgumentScanStep {
81
+ if (character === "\\" && index + 1 < argsText.length) {
82
+ return scanStep(state, false, 1);
83
+ }
84
+ if (character === state.quote) {
85
+ return scanStep({ depth: state.depth, quote: undefined });
86
+ }
87
+ return scanStep(state);
88
+ }
89
+
90
+ // Builds the scan step object with explicit defaults so the main loop stays branch-light.
91
+ function scanStep(state: ArgumentScanState, isBoundary = false, skip = 0): ArgumentScanStep {
92
+ return { state, isBoundary, skip };
93
+ }
94
+
95
+ // Quote delimiters are all significant because shell-command strings commonly use any of them.
96
+ function isQuoteDelimiter(character: string): boolean {
97
+ return character === "\"" || character === "'" || character === "`";
98
+ }
99
+
100
+ // Nested call/array/object delimiters suppress comma boundaries until they close.
101
+ function isOpeningDelimiter(character: string): boolean {
102
+ return character === "(" || character === "[" || character === "{";
103
+ }
104
+
105
+ // Closing delimiters unwind nesting but never below zero, which keeps malformed snippets bounded.
106
+ function isClosingDelimiter(character: string): boolean {
107
+ return character === ")" || character === "]" || character === "}";
108
+ }
109
+
110
+ // Classifies the command operand for reviewer triage. This is advisory metadata only: every emitted
111
+ // process-exec finding still requires human review of the surrounding command construction.
112
+ function processExecArgumentSource(rawSource: string, callStart: number, firstArgument: string): ProcessExecArgumentSource {
113
+ if (firstArgument === "process.execPath") {
114
+ return "process-exec-path";
115
+ }
116
+ if (/^`/.test(firstArgument)) {
117
+ return /\$\{/.test(firstArgument) ? "template" : "literal";
118
+ }
119
+ if (/^["'][^"']*["']$/.test(firstArgument)) {
120
+ return "literal";
121
+ }
122
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(firstArgument)) {
123
+ return "local-builder";
124
+ }
125
+ const identifier = firstArgument.match(/^[A-Za-z_$][A-Za-z0-9_$]*$/)?.[0];
126
+ if (identifier) {
127
+ return hasConstLiteralCommandDeclaration(rawSource, callStart, identifier) ? "local-const" : "parameter";
128
+ }
129
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)+/.test(firstArgument)) {
130
+ return "member";
131
+ }
132
+ return "unknown";
133
+ }
134
+
135
+ // Looks backward from the call for a same-scope `const command = "fixed"` shape so reviewers can
136
+ // distinguish fixed command vectors from parameter-driven command names.
137
+ function hasConstLiteralCommandDeclaration(rawSource: string, callStart: number, identifier: string): boolean {
138
+ const declaration = rawSource.slice(0, callStart).match(new RegExp(`\\bconst\\s+${escapeRegex(identifier)}\\s*=\\s*([^;]+);\\s*$`, "s"));
139
+ const initializer = declaration?.[1] ?? "";
140
+ return /["'][^"']+["']/.test(initializer) && !/[`$()[\]{}]/.test(initializer);
141
+ }
142
+
143
+ // Reports default shell semantics: exec/execSync imply a shell unless an explicit option says false,
144
+ // while spawn/execFile variants default to shell-disabled unless explicitly enabled.
145
+ function processExecShellEnabled(callName: string, codeSegment: string): boolean {
146
+ if (/\bshell\s*:\s*true\b/.test(codeSegment)) {
147
+ return true;
148
+ }
149
+ if (/\bshell\s*:\s*false\b/.test(codeSegment)) {
150
+ return false;
151
+ }
152
+ return callName === "exec" || callName === "execSync";
153
+ }
@@ -63,7 +63,7 @@ function analysePackageScripts(file: ConfigSourceFile, source: string, scripts:
63
63
  continue;
64
64
  }
65
65
  pushRemoteInstallScriptFinding(file, source, scriptName, scriptCommand, findings);
66
- pushLifecycleScriptFinding(file, source, scriptName, findings);
66
+ pushLifecycleScriptFinding(file, source, scriptName, scriptCommand, findings);
67
67
  }
68
68
  }
69
69
 
@@ -93,13 +93,12 @@ function pushRemoteInstallScriptFinding(file: ConfigSourceFile, source: string,
93
93
  }
94
94
 
95
95
  /*
96
- * Reports the stable `security.risky-lifecycle-script` finding for any preinstall/install/
97
- * postinstall/prepare/prepublish/prepublishOnly hook - these run automatically and even disabling
98
- * install scripts in npm config is not universally honoured. Flagged as `warning` rather than
99
- * `error` because some packages legitimately need them.
96
+ * Reports the stable `security.risky-lifecycle-script` finding for install-time and side-effectful
97
+ * publish hooks. Validation-only publish gates stay quiet, but install/prepare hooks stay visible
98
+ * because they run in broader contexts than an explicit release check.
100
99
  */
101
- function pushLifecycleScriptFinding(file: ConfigSourceFile, source: string, scriptName: string, findings: Finding[]): void {
102
- if (!isLifecycleScript(scriptName)) {
100
+ function pushLifecycleScriptFinding(file: ConfigSourceFile, source: string, scriptName: string, scriptCommand: string, findings: Finding[]): void {
101
+ if (!isLifecycleScript(scriptName) || isValidationOnlyLifecycleCommand(scriptName, scriptCommand)) {
103
102
  return;
104
103
  }
105
104
  findings.push(
@@ -112,7 +111,7 @@ function pushLifecycleScriptFinding(file: ConfigSourceFile, source: string, scri
112
111
  pillar: "security",
113
112
  confidence: "medium",
114
113
  symbol: scriptName,
115
- remediation: "Move setup behind an explicit command unless lifecycle execution is required.",
114
+ remediation: "Review whether lifecycle execution is required; keep install/publish side effects behind explicit commands when possible.",
116
115
  metadata: { scriptName },
117
116
  }),
118
117
  );
@@ -405,6 +404,20 @@ function isLifecycleScript(scriptName: string): boolean {
405
404
  return ["preinstall", "install", "postinstall", "prepare", "prepublish", "prepublishOnly"].includes(scriptName);
406
405
  }
407
406
 
407
+ // Allows closed-list validation commands in publish hooks while rejecting shell composition.
408
+ function isValidationOnlyLifecycleCommand(scriptName: string, command: string): boolean {
409
+ if (!["prepublish", "prepublishOnly"].includes(scriptName)) {
410
+ return false;
411
+ }
412
+ const normalizedCommand = command.trim().replace(/\s+/g, " ");
413
+ if (/[;&|`$<>]/.test(normalizedCommand)) {
414
+ return false;
415
+ }
416
+ return VALIDATION_ONLY_LIFECYCLE_COMMANDS.has(normalizedCommand);
417
+ }
418
+
419
+ const VALIDATION_ONLY_LIFECYCLE_COMMANDS = new Set(["npm run check", "npm test", "npm run test", "npm run lint", "npm run typecheck", "npm run publish:check"]);
420
+
408
421
  // Recognises non-registry installs: full URLs, git+ssh, file:, and npm-hosting shortcuts.
409
422
  // These specs cannot be reproducibly locked the way registry versions can.
410
423
  function isUrlDependency(versionSpec: string): boolean {
@@ -3,7 +3,7 @@
3
3
  // project-index types and the rules that consume them out of cli.ts so the orchestrator stays lean.
4
4
  import { dirname as dirnamePath, extname, join } from "node:path";
5
5
  import { isString } from "./config-parse.ts";
6
- import { optionNumber, ruleSeverity, threshold } from "./config.ts";
6
+ import { optionNumber, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
7
7
  import { type SourceFile } from "./discovery.ts";
8
8
  import { makeFinding } from "./findings.ts";
9
9
  import { fileBaseName } from "./findings-helpers.ts";
@@ -47,10 +47,10 @@ interface ImportStatement {
47
47
  line: number;
48
48
  }
49
49
 
50
- // Ordered list of files participating in a cycle. Order is significant - the first edge is the
51
- // anchor reported in the finding, so rotating the list would shift the finding's source line.
50
+ // Sorted SCC member list plus one deterministic closed cycle path for reviewer context.
52
51
  interface ImportCycle {
53
52
  files: string[];
53
+ representativeCycle: string[];
54
54
  }
55
55
 
56
56
  // Resolved thresholds passed into the large-module-concentration check. Holding them together
@@ -76,6 +76,12 @@ interface LargeModuleCandidate extends ModuleLineCount {
76
76
  thresholds: LargeModuleThresholds;
77
77
  }
78
78
 
79
+ // Optional switches for architecture analysis. The circular-import gate lets a caller build root
80
+ // graph context elsewhere without emitting duplicate SCC findings from the scoped index.
81
+ interface ArchitectureRuleOptions {
82
+ shouldSkipCircularImports?: boolean;
83
+ }
84
+
79
85
  // Sorts sources by display path so every cross-file rule sees the same order regardless of which
80
86
  // filesystem yielded what entries first - the stable input ordering is what keeps reports deterministic.
81
87
  export function buildProjectIndex(projectSources: ProjectSource[]): ProjectIndex {
@@ -91,12 +97,22 @@ export function buildProjectIndex(projectSources: ProjectSource[]): ProjectIndex
91
97
 
92
98
  // Three architecture rules, evaluated in their stable contract order: deep imports, cycles, then
93
99
  // large-module concentration. Reordering shuffles the deterministic fingerprint output.
94
- export function analyseArchitectureRules(index: ProjectIndex, config: Config, findings: Finding[]): void {
95
- analyseDeepRelativeImports(index, config, findings);
96
- analyseCircularImports(index, findings);
97
- analyseLargeModuleConcentration(index, config, findings);
100
+ export function analyseArchitectureRules(index: ProjectIndex, config: Config, findings: Finding[], options: ArchitectureRuleOptions = {}): void {
101
+ if (ruleEnabled(config, DEEP_RELATIVE_IMPORT_RULE_ID)) {
102
+ analyseDeepRelativeImports(index, config, findings);
103
+ }
104
+ if (!options.shouldSkipCircularImports && ruleEnabled(config, CIRCULAR_IMPORT_RULE_ID)) {
105
+ analyseCircularImportRule(index, findings);
106
+ }
107
+ if (ruleEnabled(config, LARGE_MODULE_CONCENTRATION_RULE_ID)) {
108
+ analyseLargeModuleConcentration(index, config, findings);
109
+ }
98
110
  }
99
111
 
112
+ const DEEP_RELATIVE_IMPORT_RULE_ID = "design.deep-relative-import";
113
+ export const CIRCULAR_IMPORT_RULE_ID = "design.circular-import";
114
+ const LARGE_MODULE_CONCENTRATION_RULE_ID = "design.large-module-concentration";
115
+
100
116
  /*
101
117
  * Reports imports that climb more than `maxParentSegments` `../` hops, anchored at the edge line
102
118
  * in the importing file. The double loop exists intentionally because `..` and `../foo` look
@@ -105,7 +121,7 @@ export function analyseArchitectureRules(index: ProjectIndex, config: Config, fi
105
121
  */
106
122
  function analyseDeepRelativeImports(index: ProjectIndex, config: Config, findings: Finding[]): void {
107
123
  const maxParentSegments = threshold(config, "design.deep-relative-import", 2);
108
- const severity = ruleSeverity(config, "design.deep-relative-import", "advisory");
124
+ const severity = ruleSeverity(config, DEEP_RELATIVE_IMPORT_RULE_ID, "advisory");
109
125
  for (const source of index.scriptSources) {
110
126
  const edges = index.importsByFile.get(source.file.displayPath) ?? [];
111
127
  for (const edge of edges) {
@@ -114,7 +130,7 @@ function analyseDeepRelativeImports(index: ProjectIndex, config: Config, finding
114
130
  }
115
131
  findings.push(
116
132
  makeFinding({
117
- ruleId: "design.deep-relative-import",
133
+ ruleId: DEEP_RELATIVE_IMPORT_RULE_ID,
118
134
  message: `Relative import \`${edge.specifier}\` climbs ${edge.parentSegments} directories.`,
119
135
  filePath: source.file.displayPath,
120
136
  line: edge.line,
@@ -131,10 +147,10 @@ function analyseDeepRelativeImports(index: ProjectIndex, config: Config, finding
131
147
  }
132
148
 
133
149
  /*
134
- * Reports one finding per detected cycle. The cycle list comes back already deterministic from
135
- * `importCycles`, so the resulting fingerprints are reproducible across runs.
150
+ * Reports one finding per strongly connected component in the runtime import graph. The component
151
+ * list comes back already deterministic from `importCycles`, so fingerprints are reproducible.
136
152
  */
137
- function analyseCircularImports(index: ProjectIndex, findings: Finding[]): void {
153
+ export function analyseCircularImportRule(index: ProjectIndex, findings: Finding[]): void {
138
154
  for (const cycle of importCycles(index)) {
139
155
  const finding = circularImportFinding(index, cycle);
140
156
  if (finding) {
@@ -154,7 +170,7 @@ function circularImportFinding(index: ProjectIndex, cycle: ImportCycle): Finding
154
170
  return undefined;
155
171
  }
156
172
  return makeFinding({
157
- ruleId: "design.circular-import",
173
+ ruleId: CIRCULAR_IMPORT_RULE_ID,
158
174
  message: `Import cycle detected among ${cycle.files.join(", ")}.`,
159
175
  filePath: anchorSource.file.displayPath,
160
176
  line: circularImportLine(index, anchorPath, cycle),
@@ -163,7 +179,7 @@ function circularImportFinding(index: ProjectIndex, cycle: ImportCycle): Finding
163
179
  confidence: "medium",
164
180
  symbol: cycle.files.join(" -> "),
165
181
  remediation: "Extract the shared contract or move one dependency behind an explicit boundary.",
166
- metadata: { files: cycle.files },
182
+ metadata: { files: cycle.files, representativeCycle: cycle.representativeCycle },
167
183
  });
168
184
  }
169
185
 
@@ -237,7 +253,7 @@ function productionModuleLineCounts(index: ProjectIndex): ModuleLineCount[] {
237
253
  // can see why the rule fired without re-running with the same config - keeps reports stable for audits.
238
254
  function largeModuleConcentrationFinding(candidate: LargeModuleCandidate, severity: Severity): Finding {
239
255
  return makeFinding({
240
- ruleId: "design.large-module-concentration",
256
+ ruleId: LARGE_MODULE_CONCENTRATION_RULE_ID,
241
257
  message: `Module \`${candidate.source.file.displayPath}\` contains ${candidate.sharePercent}% of production source lines.`,
242
258
  filePath: candidate.source.file.displayPath,
243
259
  line: 1,
@@ -366,42 +382,143 @@ function importPathCandidates(basePath: string): string[] {
366
382
  return [...candidates].map(normalizeDisplayPath);
367
383
  }
368
384
 
369
- // DFS over the import graph. Path length capped at 12 (see `visitImportCycle`) because beyond that
370
- // cycle detection becomes a search problem, not a useful signal. Output is sorted so report
371
- // ordering stays deterministic across runs.
385
+ // Tarjan SCC pass over the import graph. Components, members, and outgoing edges are sorted so
386
+ // one runtime import region yields one deterministic finding regardless of discovery order.
372
387
  function importCycles(index: ProjectIndex): ImportCycle[] {
373
- const cycles = new Map<string, string[]>();
374
- const paths = [...index.importsByFile.keys()].sort();
375
- for (const start of paths) {
376
- visitImportCycle(index, start, start, [start], new Set([start]), cycles);
377
- }
378
- return [...cycles.values()]
379
- .map((files) => ({ files }))
388
+ return stronglyConnectedImportComponents(index)
389
+ .map((files) => ({ files, representativeCycle: representativeCycle(index, files) }))
380
390
  .sort((left, right) => left.files.join("\0").localeCompare(right.files.join("\0")));
381
391
  }
382
392
 
383
- function visitImportCycle(
384
- index: ProjectIndex,
385
- start: string,
386
- current: string,
387
- path: string[],
388
- seen: Set<string>,
389
- cycles: Map<string, string[]>,
390
- ): void {
391
- const targets = [...new Set((index.importsByFile.get(current) ?? []).filter((edge) => !edge.isTypeOnly).map((edge) => edge.targetPath).filter(isString))].sort();
392
- for (const target of targets) {
393
- if (target === start && path.length > 1) {
394
- const files = [...path].sort();
395
- cycles.set(files.join("\0"), files);
393
+ // Mutable state for Tarjan's algorithm. Keeping it in one object makes the recursive visitor's
394
+ // signature small enough to audit.
395
+ interface StronglyConnectedState {
396
+ nextIndex: number;
397
+ indices: Map<string, number>;
398
+ lowLinks: Map<string, number>;
399
+ stack: string[];
400
+ onStack: Set<string>;
401
+ components: string[][];
402
+ }
403
+
404
+ // Finds strongly connected import components with Tarjan's algorithm, then normalizes component
405
+ // order so one runtime cycle produces stable report anchors and fingerprints.
406
+ function stronglyConnectedImportComponents(index: ProjectIndex): string[][] {
407
+ const state: StronglyConnectedState = {
408
+ nextIndex: 0,
409
+ indices: new Map(),
410
+ lowLinks: new Map(),
411
+ stack: [],
412
+ onStack: new Set(),
413
+ components: [],
414
+ };
415
+ for (const path of [...index.importsByFile.keys()].sort()) {
416
+ if (!state.indices.has(path)) {
417
+ visitStronglyConnectedImportComponent(index, path, state);
418
+ }
419
+ }
420
+ return state.components
421
+ .map((component) => [...component].sort())
422
+ .filter((component) => component.length > 1)
423
+ .sort((left, right) => left.join("\0").localeCompare(right.join("\0")));
424
+ }
425
+
426
+ // Visits one graph node and updates Tarjan indices, low-links, and the active stack in lockstep.
427
+ function visitStronglyConnectedImportComponent(index: ProjectIndex, path: string, state: StronglyConnectedState): void {
428
+ state.indices.set(path, state.nextIndex);
429
+ state.lowLinks.set(path, state.nextIndex);
430
+ state.nextIndex += 1;
431
+ state.stack.push(path);
432
+ state.onStack.add(path);
433
+
434
+ for (const target of circularImportTargets(index, path)) {
435
+ if (!state.indices.has(target)) {
436
+ visitStronglyConnectedImportComponent(index, target, state);
437
+ state.lowLinks.set(path, Math.min(lowLinkFor(state, path), lowLinkFor(state, target)));
396
438
  continue;
397
439
  }
398
- if (seen.has(target) || path.length >= 12) {
440
+ if (state.onStack.has(target)) {
441
+ state.lowLinks.set(path, Math.min(lowLinkFor(state, path), indexFor(state, target)));
442
+ }
443
+ }
444
+
445
+ if (lowLinkFor(state, path) !== indexFor(state, path)) {
446
+ return;
447
+ }
448
+ const component: string[] = [];
449
+ while (state.stack.length > 0) {
450
+ const member = state.stack.pop();
451
+ if (!member) {
452
+ break;
453
+ }
454
+ state.onStack.delete(member);
455
+ component.push(member);
456
+ if (member === path) {
457
+ break;
458
+ }
459
+ }
460
+ state.components.push(component);
461
+ }
462
+
463
+ // Reads a Tarjan discovery index; missing entries fall back to zero only for malformed graph edges.
464
+ function indexFor(state: StronglyConnectedState, path: string): number {
465
+ return state.indices.get(path) ?? 0;
466
+ }
467
+
468
+ // Reads a Tarjan low-link value; the fallback keeps partially indexed edges bounded.
469
+ function lowLinkFor(state: StronglyConnectedState, path: string): number {
470
+ return state.lowLinks.get(path) ?? 0;
471
+ }
472
+
473
+ // Stable runtime-cycle contract: returns sorted value imports only; type-only edges never count.
474
+ function circularImportTargets(index: ProjectIndex, path: string): string[] {
475
+ return [...new Set((index.importsByFile.get(path) ?? []).filter((edge) => !edge.isTypeOnly).map((edge) => edge.targetPath).filter(isString))].sort();
476
+ }
477
+
478
+ // Chooses one concrete closed path inside the SCC so the finding still shows a reviewable edge
479
+ // chain even though the primary output unit is the whole component.
480
+ function representativeCycle(index: ProjectIndex, files: string[]): string[] {
481
+ const anchor = files[0];
482
+ if (!anchor) {
483
+ return [];
484
+ }
485
+ const members = new Set(files);
486
+ for (const target of circularImportTargets(index, anchor).filter((candidate) => members.has(candidate))) {
487
+ const returnPath = pathBetweenComponentMembers(index, target, anchor, members);
488
+ if (returnPath) {
489
+ return [anchor, ...returnPath];
490
+ }
491
+ }
492
+ return files;
493
+ }
494
+
495
+ // Queue item for finding a representative path through one SCC.
496
+ interface ComponentPathSearch {
497
+ current: string;
498
+ path: string[];
499
+ }
500
+
501
+ // Breadth-first path search inside one SCC so the grouped finding can display a concrete cycle.
502
+ function pathBetweenComponentMembers(index: ProjectIndex, start: string, end: string, members: Set<string>): string[] | undefined {
503
+ const queue: ComponentPathSearch[] = [{ current: start, path: [start] }];
504
+ const visited = new Set([start]);
505
+ for (let queueIndex = 0; queueIndex < queue.length; queueIndex += 1) {
506
+ const searchState = queue[queueIndex];
507
+ if (!searchState) {
399
508
  continue;
400
509
  }
401
- seen.add(target);
402
- visitImportCycle(index, start, target, [...path, target], seen, cycles);
403
- seen.delete(target);
510
+ for (const target of circularImportTargets(index, searchState.current).filter((candidate) => members.has(candidate))) {
511
+ if (target === end) {
512
+ return [...searchState.path, target];
513
+ }
514
+ if (visited.has(target)) {
515
+ continue;
516
+ }
517
+ visited.add(target);
518
+ queue.push({ current: target, path: [...searchState.path, target] });
519
+ }
404
520
  }
521
+ return undefined;
405
522
  }
406
523
 
407
524
  // Production = not a test, not a `.d.ts`, not a fixture, not under `generated/`. Conservative on
@@ -426,6 +426,9 @@ function renderText(report: AnalysisReport): string {
426
426
  if (report.diagnostics.length > 0) {
427
427
  lines.push("", "Diagnostics:", ...report.diagnostics.map(summaryDiagnosticLine));
428
428
  }
429
+ if ((report.notes ?? []).length > 0) {
430
+ lines.push("", "Notes:", ...(report.notes ?? []).map((note) => `- ${note.noteType}: ${note.message} (${note.path})`));
431
+ }
429
432
  if (report.findings.length > 0) {
430
433
  lines.push("", "Findings:", ...report.findings.map((finding) => `- [${finding.severity}] ${finding.filePath}:${finding.line ?? 1} ${finding.ruleId} - ${finding.message}`));
431
434
  }
package/src/rule-list.ts CHANGED
@@ -23,6 +23,7 @@ const CONSOLE_COMMANDS = [
23
23
  { name: "completion", description: "Dump the shell completion script" },
24
24
  { name: "dashboard", description: "Serve the local gruff dashboard." },
25
25
  { name: "help", description: "Display help for a command" },
26
+ { name: "hook", description: "Run the gruff agent-hook contract." },
26
27
  { name: "init", description: "Write the default .gruff-ts.yaml to the current directory." },
27
28
  { name: "list", description: "List commands" },
28
29
  { name: "list-profiles", description: "List the built-in gruff profiles." },
package/src/rules.ts CHANGED
@@ -4,7 +4,7 @@ import type { RuleDescriptor } from "./types.ts";
4
4
  const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
5
5
  { ruleId: "complexity.cognitive", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with high combined branch and nesting complexity.", remediation: "Split nested decisions into smaller named functions. Or raise rules.complexity.cognitive.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 },
6
6
  { ruleId: "complexity.cyclomatic", pillar: "complexity", severity: "warning", confidence: "high", description: "Flags functions with many independent branch paths.", remediation: "Reduce branching or move policy tables out of imperative code. Or raise rules.complexity.cyclomatic.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 15 }, { ruleId: "dead-code.unused-private-method", pillar: "dead-code", severity: "advisory", confidence: "low", description: "Flags private methods without an apparent same-file call site.", remediation: "Remove the method or add a direct call site." },
7
- { ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags simple relative import cycles inside the discovered source set.", remediation: "Extract the shared contract or invert one dependency." },
7
+ { ruleId: "design.circular-import", pillar: "design", severity: "warning", confidence: "medium", description: "Flags strongly connected relative import components that include the scan surface.", remediation: "Extract the shared contract or invert one dependency." },
8
8
  { ruleId: "design.deep-relative-import", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags relative imports that climb too many parent directories.", remediation: "Move the shared module closer or add a local boundary. Or raise rules.design.deep-relative-import.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 2 },
9
9
  { ruleId: "design.large-module-concentration", pillar: "design", severity: "advisory", confidence: "medium", description: "Flags a production module that dominates project source lines.", remediation: "Split unrelated responsibilities once stable seams are visible. Or raise rules.design.large-module-concentration.threshold or tune minFiles, minLines under rules.design.large-module-concentration.options.", threshold: 55, optionKeys: ["minFiles", "minLines"] },
10
10
  { ruleId: "design.package-bin-missing", pillar: "design", severity: "warning", confidence: "high", description: "Flags package bin entries that point at missing files.", remediation: "Update the bin path or add the executable file." },
@@ -68,11 +68,11 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
68
68
  { ruleId: "security.new-function", pillar: "security", severity: "error", confidence: "high", description: "Flags Function constructor dynamic code execution.", remediation: "Replace dynamic construction with explicit functions or dispatch." },
69
69
  { ruleId: "security.open-redirect-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to redirect or navigation sinks.", remediation: "Redirect only to relative paths or destinations from an allowlist." },
70
70
  { ruleId: "security.path-traversal-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to filesystem path sinks.", remediation: "Validate paths against an allowlist and resolve them under a safe root." },
71
- { ruleId: "security.process-exec", pillar: "security", severity: "warning", confidence: "high", description: "Flags child-process execution calls.", remediation: "Validate arguments and prefer fixed command vectors." },
71
+ { ruleId: "security.process-exec", pillar: "security", severity: "warning", confidence: "high", description: "Flags child-process execution calls and annotates emitted findings with command-source and shell-mode hints.", remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled." },
72
72
  { ruleId: "security.proto-access", pillar: "security", severity: "warning", confidence: "medium", description: "Flags direct __proto__ access that can enable prototype pollution.", remediation: "Use Object.getPrototypeOf, Object.create(null), or validated keys." },
73
73
  { ruleId: "security.remote-install-script", pillar: "security", severity: "error", confidence: "medium", description: "Flags package scripts that pipe remote content to a shell.", remediation: "Vendor, pin, or remove remote shell execution." },
74
- { ruleId: "security.risky-lifecycle-script", pillar: "security", severity: "warning", confidence: "medium", description: "Flags package lifecycle scripts that run automatically.", remediation: "Move setup behind an explicit command when possible." },
75
- { ruleId: "security.sql-concatenation", pillar: "security", severity: "warning", confidence: "high", description: "Flags SQL text composed with runtime string interpolation.", remediation: "Use parameterized queries or query builders." },
74
+ { ruleId: "security.risky-lifecycle-script", pillar: "security", severity: "warning", confidence: "medium", description: "Flags install-time and side-effectful publish lifecycle scripts while allowing validation-only publish gates.", remediation: "Review whether lifecycle execution is required; keep install/publish side effects behind explicit commands when possible." },
75
+ { ruleId: "security.sql-concatenation", pillar: "security", severity: "warning", confidence: "high", description: "Flags SQL text composed with runtime interpolation or concatenation in query, execute, raw, or prepare calls.", remediation: "Use parameterized values, and keep dynamic identifiers constrained to trusted constants or explicit review." },
76
76
  { ruleId: "security.ssrf-candidate", pillar: "security", severity: "warning", confidence: "medium", description: "Flags external input sent to network request sinks.", remediation: "Validate destinations against an allowlist and block internal hosts." },
77
77
  { ruleId: "security.string-timer", pillar: "security", severity: "warning", confidence: "high", description: "Flags string callbacks passed to timers.", remediation: "Pass a function callback instead of source text." },
78
78
  { ruleId: "security.throw-non-error", pillar: "security", severity: "warning", confidence: "medium", description: "Flags thrown non-Error values.", remediation: "Throw an Error subclass with a clear message." },
@@ -104,7 +104,7 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
104
104
  { ruleId: "test-quality.only-skip", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags focused or skipped test markers.", remediation: "Remove .only and either enable or delete skipped tests." },
105
105
  { ruleId: "test-quality.sleep-in-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags sleeps in tests.", remediation: "Synchronize on behavior instead of wall-clock time." },
106
106
  { ruleId: "test-quality.snapshot-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that rely only on snapshots.", remediation: "Add targeted assertions for important behavior." },
107
- { ruleId: "test-quality.static-analysis-redundant-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that primarily assert code shape rather than behavior.", remediation: "Remove the redundant assertion, replace it with behavioral evidence, or document why runtime coverage matters." },
107
+ { ruleId: "test-quality.static-analysis-redundant-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that primarily assert code shape rather than behavior, with review guidance for importability sentinels.", remediation: "Remove redundant assertions, replace them with behavioral evidence, or document why runtime module-load coverage matters." },
108
108
  { ruleId: "test-quality.trivial-assertion", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tautological assertions.", remediation: "Assert a real result from the system under test." },
109
109
  { ruleId: "test-quality.unused-mock", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags mocks created but not used.", remediation: "Remove unused mocks or wire them into the behavior under test." },
110
110
  { ruleId: "waste.any-type", pillar: "maintainability", severity: "warning", confidence: "high", description: "Flags any type usage.", remediation: "Use unknown with validation or a precise type." },