@swayamkothari/codepulse 0.0.0-stage → 0.1.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 (38) hide show
  1. package/README.md +240 -2
  2. package/bin/codepulse.js +6 -0
  3. package/package.json +60 -4
  4. package/src/analyzers/complexity/cognitive.js +170 -0
  5. package/src/analyzers/complexity/cyclomatic.js +96 -0
  6. package/src/analyzers/complexity/index.js +232 -0
  7. package/src/analyzers/dependencies/cycle-detector.js +107 -0
  8. package/src/analyzers/dependencies/graph-builder.js +118 -0
  9. package/src/analyzers/dependencies/import-extractor.js +85 -0
  10. package/src/analyzers/dependencies/index.js +152 -0
  11. package/src/analyzers/duplication/index.js +366 -0
  12. package/src/analyzers/duplication/normalizer.js +238 -0
  13. package/src/analyzers/index.js +9 -0
  14. package/src/analyzers/smells/index.js +213 -0
  15. package/src/cli/argument-parser.js +45 -0
  16. package/src/cli/commands/analyze.js +146 -0
  17. package/src/cli/commands/compare.js +121 -0
  18. package/src/cli/commands/history.js +91 -0
  19. package/src/cli/commands/init.js +51 -0
  20. package/src/cli/commands/rules.js +110 -0
  21. package/src/config/loader.js +142 -0
  22. package/src/config/validator.js +130 -0
  23. package/src/core/analyzer.js +198 -0
  24. package/src/core/file-filter.js +95 -0
  25. package/src/core/project-scanner.js +119 -0
  26. package/src/history/comparison-engine.js +86 -0
  27. package/src/history/snapshot-manager.js +190 -0
  28. package/src/index.js +16 -0
  29. package/src/reporters/html.js +313 -0
  30. package/src/reporters/json.js +45 -0
  31. package/src/reporters/terminal.js +197 -0
  32. package/src/rules/defaults.js +145 -0
  33. package/src/rules/registry.js +75 -0
  34. package/src/scoring/score-calculator.js +299 -0
  35. package/src/scoring/weights.js +53 -0
  36. package/src/utils/ast-utils.js +173 -0
  37. package/src/utils/file-utils.js +64 -0
  38. package/src/utils/logger.js +54 -0
@@ -0,0 +1,145 @@
1
+ import { registerRule } from './registry.js';
2
+
3
+ let _registered = false;
4
+
5
+ /**
6
+ * Register all built-in rules. Safe to call multiple times (idempotent).
7
+ */
8
+ export function registerDefaultRules() {
9
+ if (_registered) return;
10
+ _registered = true;
11
+
12
+ // ── Complexity ───────────────────────────────────────────────────────────
13
+
14
+ registerRule({
15
+ id: 'complexity/cyclomatic',
16
+ name: 'Cyclomatic Complexity',
17
+ description: 'Functions with high cyclomatic complexity are difficult to test and maintain. Each branch (if, &&, ||, ??, for, while, catch, ternary) adds 1.',
18
+ category: 'complexity',
19
+ severity: 'high',
20
+ defaultOptions: { threshold: 10 },
21
+ });
22
+
23
+ registerRule({
24
+ id: 'complexity/cognitive',
25
+ name: 'Cognitive Complexity',
26
+ description: 'Measures how hard a function is to understand, penalising nesting more heavily than raw branch count.',
27
+ category: 'complexity',
28
+ severity: 'high',
29
+ defaultOptions: { threshold: 15 },
30
+ });
31
+
32
+ registerRule({
33
+ id: 'complexity/nesting-depth',
34
+ name: 'Deep Nesting',
35
+ description: 'Deeply nested control structures (if/for/while/try) are hard to read and test.',
36
+ category: 'complexity',
37
+ severity: 'medium',
38
+ defaultOptions: { threshold: 4 },
39
+ });
40
+
41
+ registerRule({
42
+ id: 'complexity/parameters',
43
+ name: 'Too Many Parameters',
44
+ description: 'Functions with many parameters are harder to call correctly and test exhaustively.',
45
+ category: 'complexity',
46
+ severity: 'medium',
47
+ defaultOptions: { threshold: 5 },
48
+ });
49
+
50
+ registerRule({
51
+ id: 'complexity/function-length',
52
+ name: 'Function Too Long',
53
+ description: 'Very long functions often do too many things and should be decomposed.',
54
+ category: 'complexity',
55
+ severity: 'medium',
56
+ defaultOptions: { threshold: 50 },
57
+ });
58
+
59
+ // ── Code Smells ───────────────────────────────────────────────────────────
60
+
61
+ registerRule({
62
+ id: 'smell/large-file',
63
+ name: 'Large File',
64
+ description: 'Files exceeding the line threshold often violate the single-responsibility principle.',
65
+ category: 'smell',
66
+ severity: 'medium',
67
+ defaultOptions: { threshold: 500 },
68
+ });
69
+
70
+ registerRule({
71
+ id: 'smell/magic-numbers',
72
+ name: 'Magic Numbers',
73
+ description: 'Numeric literals embedded directly in logic are hard to understand and change safely.',
74
+ category: 'smell',
75
+ severity: 'low',
76
+ defaultOptions: { ignore: [0, 1, -1, 2, 100] },
77
+ });
78
+
79
+ registerRule({
80
+ id: 'smell/empty-catch',
81
+ name: 'Empty Catch Block',
82
+ description: 'Catch blocks with no handling silently swallow errors, making debugging very hard.',
83
+ category: 'smell',
84
+ severity: 'high',
85
+ defaultOptions: {},
86
+ });
87
+
88
+ registerRule({
89
+ id: 'smell/unused-vars',
90
+ name: 'Unused Variables',
91
+ description: 'Variables declared but never referenced clutter the codebase and may indicate bugs.',
92
+ category: 'smell',
93
+ severity: 'medium',
94
+ defaultOptions: { ignorePattern: '^_' },
95
+ });
96
+
97
+ // ── Dependencies ──────────────────────────────────────────────────────────
98
+
99
+ registerRule({
100
+ id: 'dependency/circular',
101
+ name: 'Circular Dependency',
102
+ description: 'Circular imports can cause module initialisation failures and tightly couple unrelated files.',
103
+ category: 'dependency',
104
+ severity: 'high',
105
+ defaultOptions: {},
106
+ });
107
+
108
+ registerRule({
109
+ id: 'dependency/too-many-imports',
110
+ name: 'Too Many Dependencies',
111
+ description: 'Files that import an excessive number of other files may have too many responsibilities.',
112
+ category: 'dependency',
113
+ severity: 'low',
114
+ defaultOptions: { threshold: 15 },
115
+ });
116
+
117
+ // ── Duplication ───────────────────────────────────────────────────────────
118
+
119
+ registerRule({
120
+ id: 'duplication/block',
121
+ name: 'Duplicate Code Block',
122
+ description: 'Identical or structurally similar code blocks found in multiple locations should be extracted into shared utilities.',
123
+ category: 'duplication',
124
+ severity: 'medium',
125
+ defaultOptions: { minLines: 6, similarityThreshold: 0.9 },
126
+ });
127
+
128
+ // ── Hygiene ───────────────────────────────────────────────────────────────
129
+
130
+ registerRule({
131
+ id: 'hygiene/console-log',
132
+ name: 'Console Log Statement',
133
+ description: 'console.log / console.debug left in production code is usually unintentional.',
134
+ category: 'hygiene',
135
+ severity: 'low',
136
+ defaultOptions: { allow: ['console.error', 'console.warn'] },
137
+ });
138
+ }
139
+
140
+ /**
141
+ * Reset registration state (for use in tests only).
142
+ */
143
+ export function _resetDefaultRules() {
144
+ _registered = false;
145
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Central rule registry.
3
+ *
4
+ * Rule schema:
5
+ * {
6
+ * id: string — unique, e.g. 'complexity/cyclomatic'
7
+ * name: string — human-readable
8
+ * description: string
9
+ * category: string — 'complexity' | 'duplication' | 'smell' | 'dependency' | 'hygiene'
10
+ * severity: string — 'critical' | 'high' | 'medium' | 'low'
11
+ * defaultOptions: object — rule-specific tunables
12
+ * enabled: boolean
13
+ * }
14
+ */
15
+
16
+ const _rules = new Map();
17
+
18
+ export function registerRule(rule) {
19
+ if (!rule.id) throw new Error('Rule must have an id');
20
+ if (!rule.category) throw new Error(`Rule "${rule.id}" must have a category`);
21
+ if (!rule.severity) throw new Error(`Rule "${rule.id}" must have a severity`);
22
+ _rules.set(rule.id, { enabled: true, defaultOptions: {}, ...rule });
23
+ }
24
+
25
+ export function getRule(id) {
26
+ return _rules.get(id) ?? null;
27
+ }
28
+
29
+ export function getAllRules() {
30
+ return [..._rules.values()];
31
+ }
32
+
33
+ export function getRulesByCategory(category) {
34
+ return [..._rules.values()].filter(r => r.category === category);
35
+ }
36
+
37
+ export function isEnabled(id) {
38
+ return _rules.get(id)?.enabled !== false;
39
+ }
40
+
41
+ /**
42
+ * Apply user config overrides. Called once during startup after rules are registered.
43
+ *
44
+ * Config format:
45
+ * rules: {
46
+ * 'complexity/cyclomatic': 'off',
47
+ * 'smell/magic-numbers': { severity: 'high', options: { ignore: [0, 1] } }
48
+ * }
49
+ */
50
+ export function applyRulesConfig(rulesConfig) {
51
+ if (!rulesConfig || typeof rulesConfig !== 'object') return;
52
+
53
+ for (const [id, config] of Object.entries(rulesConfig)) {
54
+ const rule = _rules.get(id);
55
+ if (!rule) continue;
56
+
57
+ if (config === 'off' || config === false) {
58
+ rule.enabled = false;
59
+ continue;
60
+ }
61
+
62
+ if (typeof config === 'object') {
63
+ if (config.enabled === false) rule.enabled = false;
64
+ if (config.severity) rule.severity = config.severity;
65
+ if (config.options) rule.defaultOptions = { ...rule.defaultOptions, ...config.options };
66
+ }
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Reset the registry (useful in tests).
72
+ */
73
+ export function clearRegistry() {
74
+ _rules.clear();
75
+ }
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Score Calculator
3
+ *
4
+ * Converts analysis findings and per-file metrics into five sub-scores
5
+ * (0–100 each) and one weighted overall score.
6
+ *
7
+ * Every score is fully traceable: the returned object explains what data
8
+ * drove it and which thresholds applied.
9
+ *
10
+ * Sub-score domains:
11
+ * complexity — cyclomatic / cognitive / nesting violations
12
+ * duplication — % of codebase duplicated
13
+ * maintainability — file size, function length, parameter count smells
14
+ * dependencies — circular deps, excessive coupling
15
+ * hygiene — unused vars, empty catches, magic numbers, console.log
16
+ */
17
+
18
+ import { SEVERITY_WEIGHT, scoreLabel, resolveWeights } from './weights.js';
19
+
20
+ // ── Helpers ────────────────────────────────────────────────────────────────
21
+
22
+ function clamp(n) { return Math.max(0, Math.min(100, Math.round(n))); }
23
+
24
+ function issuesByRule(issues, ruleIds) {
25
+ const set = new Set(Array.isArray(ruleIds) ? ruleIds : [ruleIds]);
26
+ return issues.filter(i => set.has(i.ruleId));
27
+ }
28
+
29
+ function weightedPenalty(issues) {
30
+ return issues.reduce((sum, i) => sum + (SEVERITY_WEIGHT[i.severity] ?? 1), 0);
31
+ }
32
+
33
+ function makeScore(score, reasons, raw = {}) {
34
+ return { score: clamp(score), label: scoreLabel(clamp(score)), reasons, raw };
35
+ }
36
+
37
+ // ── Complexity sub-score ───────────────────────────────────────────────────
38
+ //
39
+ // Operates directly on per-function metrics collected by the complexity
40
+ // analyzer, so it is independent of threshold choices in the rules.
41
+ //
42
+ // Algorithm:
43
+ // For each function, compute a "badness" value in [0, 1]:
44
+ // cyclomatic: badness += min(1.0, excess / threshold)
45
+ // cognitive: badness += min(1.0, excess / threshold)
46
+ // nesting: badness += min(0.5, excess / threshold)
47
+ // Average badness across all functions.
48
+ // score = 100 × (1 − averageBadness)
49
+
50
+ function scoreComplexity(result, config) {
51
+ const fnMetrics = result.files.flatMap(f => f.metrics?.functions ?? []);
52
+
53
+ if (fnMetrics.length === 0) {
54
+ return makeScore(100, ['No functions found — nothing to score.'], { functionCount: 0 });
55
+ }
56
+
57
+ const cyclomaticThreshold = config?.thresholds?.cyclomaticComplexity ?? 10;
58
+ const cognitiveThreshold = config?.thresholds?.cognitiveComplexity ?? 15;
59
+ const nestingThreshold = config?.thresholds?.nestingDepth ?? 4;
60
+
61
+ let totalBadness = 0;
62
+ let ccViolations = 0, cogViolations = 0, nestViolations = 0;
63
+ let maxCC = 0, maxCog = 0, maxNest = 0;
64
+
65
+ for (const fn of fnMetrics) {
66
+ let badness = 0;
67
+
68
+ if ((fn.cyclomatic ?? 0) > cyclomaticThreshold) {
69
+ badness += Math.min(1.0, (fn.cyclomatic - cyclomaticThreshold) / cyclomaticThreshold);
70
+ ccViolations++;
71
+ }
72
+ if ((fn.cognitive ?? 0) > cognitiveThreshold) {
73
+ badness += Math.min(1.0, (fn.cognitive - cognitiveThreshold) / cognitiveThreshold);
74
+ cogViolations++;
75
+ }
76
+ if ((fn.nesting ?? 0) > nestingThreshold) {
77
+ badness += Math.min(0.5, (fn.nesting - nestingThreshold) / nestingThreshold);
78
+ nestViolations++;
79
+ }
80
+
81
+ totalBadness += Math.min(1, badness);
82
+ maxCC = Math.max(maxCC, fn.cyclomatic ?? 0);
83
+ maxCog = Math.max(maxCog, fn.cognitive ?? 0);
84
+ maxNest = Math.max(maxNest, fn.nesting ?? 0);
85
+ }
86
+
87
+ const avgBadness = totalBadness / fnMetrics.length;
88
+ const score = 100 * (1 - avgBadness);
89
+ const pct = (n) => Math.round((n / fnMetrics.length) * 100);
90
+
91
+ const reasons = [];
92
+ if (ccViolations > 0)
93
+ reasons.push(`${ccViolations}/${fnMetrics.length} functions (${pct(ccViolations)}%) exceed cyclomatic complexity threshold (>${cyclomaticThreshold}). Max: ${maxCC}.`);
94
+ if (cogViolations > 0)
95
+ reasons.push(`${cogViolations}/${fnMetrics.length} functions (${pct(cogViolations)}%) exceed cognitive complexity threshold (>${cognitiveThreshold}). Max: ${maxCog}.`);
96
+ if (nestViolations > 0)
97
+ reasons.push(`${nestViolations}/${fnMetrics.length} functions (${pct(nestViolations)}%) have nesting depth above threshold (>${nestingThreshold}). Max: ${maxNest}.`);
98
+ if (reasons.length === 0)
99
+ reasons.push(`All ${fnMetrics.length} functions are within complexity thresholds.`);
100
+
101
+ return makeScore(score, reasons, { functionCount: fnMetrics.length, ccViolations, cogViolations, nestViolations, maxCC, maxCog, maxNest, avgBadness: +avgBadness.toFixed(3) });
102
+ }
103
+
104
+ // ── Duplication sub-score ──────────────────────────────────────────────────
105
+ //
106
+ // Uses the duplication percentage attached by the duplication analyzer.
107
+ // Curve: score = 100 − dupPercent × 2.0
108
+ // 0 % dup → 100
109
+ // 10 % dup → 80
110
+ // 25 % dup → 50
111
+ // 50 % dup → 0
112
+
113
+ function scoreDuplication(result) {
114
+ const dupPercent = _getFirstMetric(result, 'duplicationPercent') ?? 0;
115
+ const dupFindings = issuesByRule(result.issues, 'duplication/block');
116
+
117
+ const score = 100 - dupPercent * 2.0;
118
+ const reasons = [];
119
+
120
+ if (dupPercent === 0 && dupFindings.length === 0) {
121
+ reasons.push('No duplicate code blocks detected.');
122
+ } else {
123
+ if (dupPercent > 0)
124
+ reasons.push(`Approximately ${dupPercent}% of project lines are duplicated.`);
125
+ if (dupFindings.length > 0)
126
+ reasons.push(`${dupFindings.length} duplicate code block${dupFindings.length !== 1 ? 's' : ''} detected.`);
127
+ }
128
+
129
+ return makeScore(score, reasons, { duplicationPercent: dupPercent, duplicateBlocks: dupFindings.length });
130
+ }
131
+
132
+ // ── Maintainability sub-score ──────────────────────────────────────────────
133
+ //
134
+ // Covers: file size (smell/large-file), function length (complexity/function-length),
135
+ // and parameter excess (complexity/parameters).
136
+ //
137
+ // Penalty = weighted issues / max(1, filesAnalyzed + functionCount)
138
+ // score = 100 − penalty × 10 (capped at 0)
139
+ // Calibrated so ~1 high-severity issue per 2 files ≈ score 75.
140
+
141
+ function scoreMaintainability(result) {
142
+ const relevantRules = [
143
+ 'smell/large-file',
144
+ 'complexity/function-length',
145
+ 'complexity/parameters',
146
+ ];
147
+ const relevant = issuesByRule(result.issues, relevantRules);
148
+ const penalty = weightedPenalty(relevant);
149
+
150
+ const fnCount = result.files.reduce((s, f) => s + (f.metrics?.functionCount ?? 0), 0);
151
+ const fileCount = result.filesAnalyzed ?? 1;
152
+ const units = Math.max(1, fileCount + fnCount);
153
+
154
+ const normalised = penalty / units;
155
+ const score = 100 - normalised * 10;
156
+
157
+ const reasons = [];
158
+ const largeFiles = issuesByRule(result.issues, 'smell/large-file').length;
159
+ const longFns = issuesByRule(result.issues, 'complexity/function-length').length;
160
+ const tooManyP = issuesByRule(result.issues, 'complexity/parameters').length;
161
+
162
+ if (largeFiles > 0) reasons.push(`${largeFiles} file${largeFiles !== 1 ? 's' : ''} exceed the line-count threshold.`);
163
+ if (longFns > 0) reasons.push(`${longFns} function${longFns !== 1 ? 's' : ''} are excessively long.`);
164
+ if (tooManyP > 0) reasons.push(`${tooManyP} function${tooManyP !== 1 ? 's' : ''} have too many parameters.`);
165
+ if (reasons.length === 0) reasons.push('No maintainability issues detected.');
166
+
167
+ return makeScore(score, reasons, { largeFiles, longFunctions: longFns, tooManyParams: tooManyP, penalty, units });
168
+ }
169
+
170
+ // ── Dependencies sub-score ─────────────────────────────────────────────────
171
+ //
172
+ // Deductions:
173
+ // Each circular dependency cycle costs 15 points (max 60 total).
174
+ // Each too-many-imports file costs 3 points (max 20 total).
175
+ // Floor: 0.
176
+
177
+ function scoreDependencies(result) {
178
+ const cycleFindings = issuesByRule(result.issues, 'dependency/circular');
179
+ const tooManyFindings = issuesByRule(result.issues, 'dependency/too-many-imports');
180
+
181
+ const cyclePenalty = Math.min(60, cycleFindings.length * 15);
182
+ const couplingPenalty = Math.min(20, tooManyFindings.length * 3);
183
+ const score = 100 - cyclePenalty - couplingPenalty;
184
+
185
+ const reasons = [];
186
+ if (cycleFindings.length > 0)
187
+ reasons.push(`${cycleFindings.length} circular dependenc${cycleFindings.length !== 1 ? 'ies' : 'y'} detected. Each costs −15 points.`);
188
+ if (tooManyFindings.length > 0)
189
+ reasons.push(`${tooManyFindings.length} file${tooManyFindings.length !== 1 ? 's' : ''} import too many local modules.`);
190
+ if (reasons.length === 0)
191
+ reasons.push('No dependency issues detected.');
192
+
193
+ return makeScore(score, reasons, { cycles: cycleFindings.length, tooManyImports: tooManyFindings.length, cyclePenalty, couplingPenalty });
194
+ }
195
+
196
+ // ── Hygiene sub-score ──────────────────────────────────────────────────────
197
+ //
198
+ // Rules: smell/unused-vars, smell/empty-catch, smell/magic-numbers,
199
+ // hygiene/console-log
200
+ //
201
+ // Density = weighted_issues / (totalLines / 100)
202
+ // (issues per 100 lines)
203
+ // score = 100 − density × 5
204
+ // Calibrated so 4 high-severity issues per 100 lines ≈ score 40.
205
+
206
+ function scoreHygiene(result) {
207
+ const hygieneRules = [
208
+ 'smell/unused-vars',
209
+ 'smell/empty-catch',
210
+ 'smell/magic-numbers',
211
+ 'hygiene/console-log',
212
+ ];
213
+ const hygieneIssues = issuesByRule(result.issues, hygieneRules);
214
+ const totalLines = result.metrics?.totalLines ?? 1;
215
+
216
+ const penalty = weightedPenalty(hygieneIssues);
217
+ const density = penalty / Math.max(1, totalLines / 100); // per 100 lines
218
+ const score = 100 - density * 5;
219
+
220
+ const countBy = hygieneRules.reduce((acc, id) => {
221
+ acc[id] = issuesByRule(result.issues, id).length;
222
+ return acc;
223
+ }, {});
224
+
225
+ const reasons = [];
226
+ if (countBy['smell/empty-catch'] > 0)
227
+ reasons.push(`${countBy['smell/empty-catch']} empty catch block${countBy['smell/empty-catch'] !== 1 ? 's' : ''} silently swallow errors.`);
228
+ if (countBy['smell/unused-vars'] > 0)
229
+ reasons.push(`${countBy['smell/unused-vars']} unused variable${countBy['smell/unused-vars'] !== 1 ? 's' : ''} declared.`);
230
+ if (countBy['smell/magic-numbers'] > 0)
231
+ reasons.push(`${countBy['smell/magic-numbers']} magic number literal${countBy['smell/magic-numbers'] !== 1 ? 's' : ''}.`);
232
+ if (countBy['hygiene/console-log'] > 0)
233
+ reasons.push(`${countBy['hygiene/console-log']} console.log statement${countBy['hygiene/console-log'] !== 1 ? 's' : ''} in production code.`);
234
+ if (reasons.length === 0)
235
+ reasons.push('No hygiene issues detected.');
236
+
237
+ return makeScore(score, reasons, { totalLines, density: +density.toFixed(3), issueCounts: countBy });
238
+ }
239
+
240
+ // ── Main entry point ───────────────────────────────────────────────────────
241
+
242
+ /**
243
+ * Calculate all scores for an analysis result.
244
+ *
245
+ * @param {object} result — the full object returned by Analyzer.analyze()
246
+ * @param {object} config — the merged codepulse config
247
+ * @returns {object} — scores object attached to result.scores
248
+ */
249
+ export function calculateScores(result, config) {
250
+ const weights = resolveWeights(config?.scoring?.weights);
251
+
252
+ const complexity = scoreComplexity(result, config);
253
+ const duplication = scoreDuplication(result);
254
+ const maintainability = scoreMaintainability(result);
255
+ const dependencies = scoreDependencies(result);
256
+ const hygiene = scoreHygiene(result);
257
+
258
+ const overall = clamp(
259
+ complexity.score * weights.complexity +
260
+ duplication.score * weights.duplication +
261
+ maintainability.score * weights.maintainability +
262
+ dependencies.score * weights.dependencies +
263
+ hygiene.score * weights.hygiene
264
+ );
265
+
266
+ // Identify the weakest dimension for the actionable summary
267
+ const breakdown = { complexity, duplication, maintainability, dependencies, hygiene };
268
+ const weakest = Object.entries(breakdown).sort(([, a], [, b]) => a.score - b.score)[0][0];
269
+
270
+ return {
271
+ overall,
272
+ label: scoreLabel(overall),
273
+ breakdown,
274
+ weights,
275
+ weakest,
276
+ // Human-readable top recommendation
277
+ recommendation: _topRecommendation(weakest, breakdown[weakest]),
278
+ };
279
+ }
280
+
281
+ // ── Helpers ────────────────────────────────────────────────────────────────
282
+
283
+ function _getFirstMetric(result, key) {
284
+ for (const f of result.files) {
285
+ if (f.metrics?.[key] !== undefined) return f.metrics[key];
286
+ }
287
+ return undefined;
288
+ }
289
+
290
+ function _topRecommendation(weakest, subScore) {
291
+ const map = {
292
+ complexity: 'Focus on reducing cyclomatic and cognitive complexity in your most complex functions.',
293
+ duplication: 'Eliminate duplicate code blocks by extracting shared logic into reusable utilities.',
294
+ maintainability: 'Break up large files and long functions into smaller, focused modules.',
295
+ dependencies: 'Resolve circular dependencies by extracting shared code into a neutral module.',
296
+ hygiene: 'Clean up unused variables, empty catch blocks, and magic numbers.',
297
+ };
298
+ return map[weakest] ?? 'Review the most critical issues highlighted above.';
299
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Default scoring weights and helper constants.
3
+ *
4
+ * Weights must sum to 1.0. They can be overridden in codepulse.config.js:
5
+ * scoring: { weights: { complexity: 0.4, duplication: 0.1, … } }
6
+ */
7
+
8
+ export const DEFAULT_WEIGHTS = {
9
+ complexity: 0.30,
10
+ duplication: 0.20,
11
+ maintainability: 0.25,
12
+ dependencies: 0.15,
13
+ hygiene: 0.10,
14
+ };
15
+
16
+ /** Penalty multiplier per severity level. */
17
+ export const SEVERITY_WEIGHT = {
18
+ critical: 4,
19
+ high: 3,
20
+ medium: 2,
21
+ low: 1,
22
+ };
23
+
24
+ /** Human-readable grade labels mapped from score bands. */
25
+ export const SCORE_LABELS = [
26
+ { min: 90, label: 'Excellent' },
27
+ { min: 80, label: 'Good' },
28
+ { min: 70, label: 'Fair' },
29
+ { min: 60, label: 'Needs Attention' },
30
+ { min: 50, label: 'Poor' },
31
+ { min: 0, label: 'Critical' },
32
+ ];
33
+
34
+ export function scoreLabel(score) {
35
+ for (const { min, label } of SCORE_LABELS) {
36
+ if (score >= min) return label;
37
+ }
38
+ return 'Critical';
39
+ }
40
+
41
+ /**
42
+ * Validate and normalise a user-supplied weights object.
43
+ * Missing keys are filled from defaults; the result is re-normalised to sum=1.
44
+ */
45
+ export function resolveWeights(userWeights) {
46
+ const merged = { ...DEFAULT_WEIGHTS, ...(userWeights ?? {}) };
47
+ const total = Object.values(merged).reduce((s, v) => s + v, 0);
48
+ if (Math.abs(total - 1) < 0.001) return merged;
49
+
50
+ // Silently re-normalise rather than crashing
51
+ const factor = 1 / total;
52
+ return Object.fromEntries(Object.entries(merged).map(([k, v]) => [k, +(v * factor).toFixed(4)]));
53
+ }