@eduardbar/drift 1.0.0 → 1.2.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 (105) hide show
  1. package/.github/actions/drift-scan/README.md +61 -0
  2. package/.github/actions/drift-scan/action.yml +65 -0
  3. package/.github/workflows/publish-vscode.yml +3 -1
  4. package/.github/workflows/review-pr.yml +61 -0
  5. package/AGENTS.md +53 -11
  6. package/README.md +106 -1
  7. package/dist/analyzer.d.ts +6 -2
  8. package/dist/analyzer.js +116 -3
  9. package/dist/badge.js +40 -22
  10. package/dist/ci.js +32 -18
  11. package/dist/cli.js +179 -6
  12. package/dist/diff.d.ts +0 -7
  13. package/dist/diff.js +26 -25
  14. package/dist/fix.d.ts +4 -0
  15. package/dist/fix.js +59 -47
  16. package/dist/git/trend.js +1 -0
  17. package/dist/git.d.ts +0 -9
  18. package/dist/git.js +25 -19
  19. package/dist/index.d.ts +7 -1
  20. package/dist/index.js +4 -0
  21. package/dist/map.d.ts +4 -0
  22. package/dist/map.js +191 -0
  23. package/dist/metrics.d.ts +4 -0
  24. package/dist/metrics.js +176 -0
  25. package/dist/plugins.d.ts +6 -0
  26. package/dist/plugins.js +74 -0
  27. package/dist/printer.js +20 -0
  28. package/dist/report.js +34 -0
  29. package/dist/reporter.js +85 -2
  30. package/dist/review.d.ts +15 -0
  31. package/dist/review.js +80 -0
  32. package/dist/rules/comments.d.ts +4 -0
  33. package/dist/rules/comments.js +45 -0
  34. package/dist/rules/complexity.d.ts +4 -0
  35. package/dist/rules/complexity.js +51 -0
  36. package/dist/rules/coupling.d.ts +4 -0
  37. package/dist/rules/coupling.js +19 -0
  38. package/dist/rules/magic.d.ts +4 -0
  39. package/dist/rules/magic.js +33 -0
  40. package/dist/rules/nesting.d.ts +5 -0
  41. package/dist/rules/nesting.js +82 -0
  42. package/dist/rules/phase0-basic.js +14 -7
  43. package/dist/rules/phase1-complexity.d.ts +6 -30
  44. package/dist/rules/phase1-complexity.js +7 -276
  45. package/dist/rules/phase2-crossfile.d.ts +0 -4
  46. package/dist/rules/phase2-crossfile.js +52 -39
  47. package/dist/rules/phase3-arch.d.ts +0 -8
  48. package/dist/rules/phase3-arch.js +26 -23
  49. package/dist/rules/phase3-configurable.d.ts +6 -0
  50. package/dist/rules/phase3-configurable.js +97 -0
  51. package/dist/rules/phase8-semantic.d.ts +0 -5
  52. package/dist/rules/phase8-semantic.js +30 -29
  53. package/dist/rules/promise.d.ts +4 -0
  54. package/dist/rules/promise.js +24 -0
  55. package/dist/saas.d.ts +83 -0
  56. package/dist/saas.js +321 -0
  57. package/dist/snapshot.d.ts +19 -0
  58. package/dist/snapshot.js +119 -0
  59. package/dist/types.d.ts +75 -0
  60. package/dist/utils.d.ts +2 -1
  61. package/dist/utils.js +1 -0
  62. package/docs/AGENTS.md +146 -0
  63. package/docs/PRD.md +157 -0
  64. package/package.json +1 -1
  65. package/packages/eslint-plugin-drift/src/index.ts +1 -1
  66. package/packages/vscode-drift/package.json +1 -1
  67. package/packages/vscode-drift/src/analyzer.ts +2 -0
  68. package/packages/vscode-drift/src/code-actions.ts +53 -0
  69. package/packages/vscode-drift/src/extension.ts +98 -63
  70. package/packages/vscode-drift/src/statusbar.ts +13 -5
  71. package/packages/vscode-drift/src/treeview.ts +2 -0
  72. package/src/analyzer.ts +144 -12
  73. package/src/badge.ts +38 -16
  74. package/src/ci.ts +38 -17
  75. package/src/cli.ts +206 -7
  76. package/src/diff.ts +36 -30
  77. package/src/fix.ts +77 -53
  78. package/src/git/trend.ts +3 -2
  79. package/src/git.ts +31 -22
  80. package/src/index.ts +31 -1
  81. package/src/map.ts +219 -0
  82. package/src/metrics.ts +200 -0
  83. package/src/plugins.ts +76 -0
  84. package/src/printer.ts +20 -0
  85. package/src/report.ts +35 -0
  86. package/src/reporter.ts +95 -2
  87. package/src/review.ts +98 -0
  88. package/src/rules/comments.ts +56 -0
  89. package/src/rules/complexity.ts +57 -0
  90. package/src/rules/coupling.ts +23 -0
  91. package/src/rules/magic.ts +38 -0
  92. package/src/rules/nesting.ts +88 -0
  93. package/src/rules/phase0-basic.ts +14 -7
  94. package/src/rules/phase1-complexity.ts +8 -302
  95. package/src/rules/phase2-crossfile.ts +68 -40
  96. package/src/rules/phase3-arch.ts +34 -30
  97. package/src/rules/phase3-configurable.ts +132 -0
  98. package/src/rules/phase8-semantic.ts +33 -29
  99. package/src/rules/promise.ts +29 -0
  100. package/src/saas.ts +433 -0
  101. package/src/snapshot.ts +175 -0
  102. package/src/types.ts +81 -1
  103. package/src/utils.ts +3 -1
  104. package/tests/new-features.test.ts +180 -0
  105. package/tests/saas-foundation.test.ts +107 -0
package/dist/git.js CHANGED
@@ -12,22 +12,23 @@ import { randomUUID } from 'node:crypto';
12
12
  *
13
13
  * Throws if the directory is not a git repo or the ref is invalid.
14
14
  */
15
- export function extractFilesAtRef(projectPath, ref) {
16
- // Verify git repo
15
+ function verifyGitRepo(projectPath) {
17
16
  try {
18
17
  execSync('git rev-parse --git-dir', { cwd: projectPath, stdio: 'pipe' });
19
18
  }
20
19
  catch {
21
20
  throw new Error(`Not a git repository: ${projectPath}`);
22
21
  }
23
- // Verify ref exists
22
+ }
23
+ function verifyRefExists(projectPath, ref) {
24
24
  try {
25
25
  execSync(`git rev-parse --verify ${ref}`, { cwd: projectPath, stdio: 'pipe' });
26
26
  }
27
27
  catch {
28
28
  throw new Error(`Invalid git ref: '${ref}'. Run 'git log --oneline' to see available commits.`);
29
29
  }
30
- // List all .ts files tracked at this ref (excluding .d.ts)
30
+ }
31
+ function listTsFilesAtRef(projectPath, ref) {
31
32
  let fileList;
32
33
  try {
33
34
  fileList = execSync(`git ls-tree -r --name-only ${ref}`, { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' });
@@ -35,30 +36,35 @@ export function extractFilesAtRef(projectPath, ref) {
35
36
  catch {
36
37
  throw new Error(`Failed to list files at ref '${ref}'`);
37
38
  }
38
- const tsFiles = fileList
39
+ return fileList
39
40
  .split('\n')
40
41
  .map(f => f.trim())
41
42
  .filter(f => (f.endsWith('.ts') || f.endsWith('.tsx') || f.endsWith('.js') || f.endsWith('.jsx')) && !f.endsWith('.d.ts'));
43
+ }
44
+ function extractFile(projectPath, ref, filePath, tempDir) {
45
+ let content;
46
+ try {
47
+ content = execSync(`git show ${ref}:${filePath}`, { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' });
48
+ }
49
+ catch {
50
+ return;
51
+ }
52
+ const destPath = join(tempDir, filePath.split('/').join(sep));
53
+ const destDir = destPath.substring(0, destPath.lastIndexOf(sep));
54
+ mkdirSync(destDir, { recursive: true });
55
+ writeFileSync(destPath, content, 'utf-8');
56
+ }
57
+ export function extractFilesAtRef(projectPath, ref) {
58
+ verifyGitRepo(projectPath);
59
+ verifyRefExists(projectPath, ref);
60
+ const tsFiles = listTsFilesAtRef(projectPath, ref);
42
61
  if (tsFiles.length === 0) {
43
62
  throw new Error(`No TypeScript files found at ref '${ref}'`);
44
63
  }
45
- // Create temp directory
46
64
  const tempDir = join(tmpdir(), `drift-diff-${randomUUID()}`);
47
65
  mkdirSync(tempDir, { recursive: true });
48
- // Extract each file
49
66
  for (const filePath of tsFiles) {
50
- let content;
51
- try {
52
- content = execSync(`git show ${ref}:${filePath}`, { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' });
53
- }
54
- catch {
55
- // File may not exist at this ref — skip
56
- continue;
57
- }
58
- const destPath = join(tempDir, filePath.split('/').join(sep));
59
- const destDir = destPath.substring(0, destPath.lastIndexOf(sep));
60
- mkdirSync(destDir, { recursive: true });
61
- writeFileSync(destPath, content, 'utf-8');
67
+ extractFile(projectPath, ref, filePath, tempDir);
62
68
  }
63
69
  return tempDir;
64
70
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  export { analyzeProject, analyzeFile, RULE_WEIGHTS } from './analyzer.js';
2
2
  export { buildReport, formatMarkdown } from './reporter.js';
3
3
  export { computeDiff } from './diff.js';
4
- export type { DriftReport, FileReport, DriftIssue, DriftDiff, FileDiff, DriftConfig } from './types.js';
4
+ export { generateReview, formatReviewMarkdown } from './review.js';
5
+ export { generateArchitectureMap, generateArchitectureSvg } from './map.js';
6
+ export type { DriftReport, FileReport, DriftIssue, DriftDiff, FileDiff, DriftConfig, RepoQualityScore, MaintenanceRiskMetrics, DriftPlugin, DriftPluginRule, } from './types.js';
7
+ export { loadHistory, saveSnapshot } from './snapshot.js';
8
+ export type { SnapshotEntry, SnapshotHistory } from './snapshot.js';
9
+ export { DEFAULT_SAAS_POLICY, defaultSaasStorePath, resolveSaasPolicy, ingestSnapshotFromReport, getSaasSummary, generateSaasDashboardHtml, } from './saas.js';
10
+ export type { SaasPolicy, SaasStore, SaasSummary, SaasSnapshot, IngestOptions, } from './saas.js';
5
11
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,4 +1,8 @@
1
1
  export { analyzeProject, analyzeFile, RULE_WEIGHTS } from './analyzer.js';
2
2
  export { buildReport, formatMarkdown } from './reporter.js';
3
3
  export { computeDiff } from './diff.js';
4
+ export { generateReview, formatReviewMarkdown } from './review.js';
5
+ export { generateArchitectureMap, generateArchitectureSvg } from './map.js';
6
+ export { loadHistory, saveSnapshot } from './snapshot.js';
7
+ export { DEFAULT_SAAS_POLICY, defaultSaasStorePath, resolveSaasPolicy, ingestSnapshotFromReport, getSaasSummary, generateSaasDashboardHtml, } from './saas.js';
4
8
  //# sourceMappingURL=index.js.map
package/dist/map.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { DriftConfig } from './types.js';
2
+ export declare function generateArchitectureSvg(targetPath: string, config?: DriftConfig): string;
3
+ export declare function generateArchitectureMap(targetPath: string, outputFile?: string, config?: DriftConfig): string;
4
+ //# sourceMappingURL=map.d.ts.map
package/dist/map.js ADDED
@@ -0,0 +1,191 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import { resolve, relative } from 'node:path';
3
+ import { Project } from 'ts-morph';
4
+ import { detectLayerViolations } from './rules/phase3-arch.js';
5
+ import { RULE_WEIGHTS } from './analyzer.js';
6
+ function detectLayer(relPath) {
7
+ const normalized = relPath.replace(/\\/g, '/').replace(/^\.\//, '');
8
+ const first = normalized.split('/')[0] || 'root';
9
+ return first;
10
+ }
11
+ function esc(value) {
12
+ return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
13
+ }
14
+ export function generateArchitectureSvg(targetPath, config) {
15
+ const project = new Project({
16
+ skipAddingFilesFromTsConfig: true,
17
+ compilerOptions: { allowJs: true, jsx: 1 },
18
+ });
19
+ project.addSourceFilesAtPaths([
20
+ `${targetPath}/**/*.ts`,
21
+ `${targetPath}/**/*.tsx`,
22
+ `${targetPath}/**/*.js`,
23
+ `${targetPath}/**/*.jsx`,
24
+ `!${targetPath}/**/node_modules/**`,
25
+ `!${targetPath}/**/dist/**`,
26
+ `!${targetPath}/**/.next/**`,
27
+ `!${targetPath}/**/*.d.ts`,
28
+ ]);
29
+ const layers = new Map();
30
+ const edges = new Map();
31
+ const layerAdjacency = new Map();
32
+ const fileImportGraph = new Map();
33
+ for (const file of project.getSourceFiles()) {
34
+ const filePath = file.getFilePath();
35
+ const rel = relative(targetPath, filePath).replace(/\\/g, '/');
36
+ const layerName = detectLayer(rel);
37
+ if (!layers.has(layerName))
38
+ layers.set(layerName, { name: layerName, files: new Set() });
39
+ layers.get(layerName).files.add(rel);
40
+ if (!fileImportGraph.has(filePath))
41
+ fileImportGraph.set(filePath, new Set());
42
+ for (const decl of file.getImportDeclarations()) {
43
+ const imported = decl.getModuleSpecifierSourceFile();
44
+ if (!imported)
45
+ continue;
46
+ fileImportGraph.get(filePath).add(imported.getFilePath());
47
+ const importedRel = relative(targetPath, imported.getFilePath()).replace(/\\/g, '/');
48
+ const importedLayer = detectLayer(importedRel);
49
+ if (importedLayer === layerName)
50
+ continue;
51
+ const key = `${layerName}->${importedLayer}`;
52
+ edges.set(key, (edges.get(key) ?? 0) + 1);
53
+ if (!layerAdjacency.has(layerName))
54
+ layerAdjacency.set(layerName, new Set());
55
+ layerAdjacency.get(layerName).add(importedLayer);
56
+ }
57
+ }
58
+ const cycleEdges = detectCycleEdges(layerAdjacency);
59
+ const violationEdges = new Set();
60
+ if (config?.layers && config.layers.length > 0) {
61
+ const violations = detectLayerViolations(fileImportGraph, config.layers, targetPath, RULE_WEIGHTS);
62
+ for (const issues of violations.values()) {
63
+ for (const issue of issues) {
64
+ const match = issue.message.match(/Layer '([^']+)' must not import from layer '([^']+)'/);
65
+ if (!match)
66
+ continue;
67
+ const from = match[1];
68
+ const to = match[2];
69
+ violationEdges.add(`${from}->${to}`);
70
+ if (!layers.has(from))
71
+ layers.set(from, { name: from, files: new Set() });
72
+ if (!layers.has(to))
73
+ layers.set(to, { name: to, files: new Set() });
74
+ }
75
+ }
76
+ }
77
+ const edgeList = [...edges.entries()].map(([key, count]) => {
78
+ const [from, to] = key.split('->');
79
+ const kind = violationEdges.has(key)
80
+ ? 'violation'
81
+ : cycleEdges.has(key)
82
+ ? 'cycle'
83
+ : 'normal';
84
+ return { key, from, to, count, kind };
85
+ });
86
+ for (const key of violationEdges) {
87
+ if (edges.has(key))
88
+ continue;
89
+ const [from, to] = key.split('->');
90
+ edgeList.push({ key, from, to, count: 1, kind: 'violation' });
91
+ }
92
+ const layerList = [...layers.values()].sort((a, b) => a.name.localeCompare(b.name));
93
+ const width = 960;
94
+ const rowHeight = 90;
95
+ const height = Math.max(180, layerList.length * rowHeight + 120);
96
+ const boxWidth = 240;
97
+ const boxHeight = 50;
98
+ const left = 100;
99
+ const boxes = layerList.map((layer, index) => {
100
+ const y = 60 + index * rowHeight;
101
+ return {
102
+ ...layer,
103
+ x: left,
104
+ y,
105
+ };
106
+ });
107
+ const boxByName = new Map(boxes.map((box) => [box.name, box]));
108
+ const lines = edgeList.map((edge) => {
109
+ const a = boxByName.get(edge.from);
110
+ const b = boxByName.get(edge.to);
111
+ if (!a || !b)
112
+ return '';
113
+ const startX = a.x + boxWidth;
114
+ const startY = a.y + boxHeight / 2;
115
+ const endX = b.x;
116
+ const endY = b.y + boxHeight / 2;
117
+ const stroke = edge.kind === 'violation'
118
+ ? '#ef4444'
119
+ : edge.kind === 'cycle'
120
+ ? '#f59e0b'
121
+ : '#64748b';
122
+ const widthPx = edge.kind === 'normal' ? 2 : 3;
123
+ return `
124
+ <line x1="${startX}" y1="${startY}" x2="${endX}" y2="${endY}" stroke="${stroke}" stroke-width="${widthPx}" marker-end="url(#arrow)" data-edge="${esc(edge.key)}" data-kind="${edge.kind}" />
125
+ <text x="${(startX + endX) / 2}" y="${(startY + endY) / 2 - 4}" fill="#94a3b8" font-size="11" text-anchor="middle">${edge.count}</text>`;
126
+ }).join('');
127
+ const nodes = boxes.map((box) => `
128
+ <g>
129
+ <rect x="${box.x}" y="${box.y}" width="${boxWidth}" height="${boxHeight}" rx="8" fill="#0f172a" stroke="#334155" />
130
+ <text x="${box.x + 12}" y="${box.y + 22}" fill="#e2e8f0" font-size="13" font-family="monospace">${esc(box.name)}</text>
131
+ <text x="${box.x + 12}" y="${box.y + 38}" fill="#94a3b8" font-size="11" font-family="monospace">${box.files.size} file(s)</text>
132
+ </g>`).join('');
133
+ const cycleCount = edgeList.filter((edge) => edge.kind === 'cycle').length;
134
+ const violationCount = edgeList.filter((edge) => edge.kind === 'violation').length;
135
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
136
+ <defs>
137
+ <marker id="arrow" markerWidth="10" markerHeight="10" refX="6" refY="3" orient="auto">
138
+ <path d="M0,0 L0,6 L7,3 z" fill="#64748b"/>
139
+ </marker>
140
+ </defs>
141
+ <rect x="0" y="0" width="${width}" height="${height}" fill="#020617" />
142
+ <text x="28" y="34" fill="#f8fafc" font-size="16" font-family="monospace">drift architecture map</text>
143
+ <text x="28" y="54" fill="#94a3b8" font-size="11" font-family="monospace">Layers inferred from top-level directories</text>
144
+ <text x="28" y="72" fill="#94a3b8" font-size="11" font-family="monospace">Cycle edges: ${cycleCount} | Layer violations: ${violationCount}</text>
145
+ <line x1="520" y1="66" x2="560" y2="66" stroke="#f59e0b" stroke-width="3" /><text x="567" y="69" fill="#94a3b8" font-size="11" font-family="monospace">cycle</text>
146
+ <line x1="630" y1="66" x2="670" y2="66" stroke="#ef4444" stroke-width="3" /><text x="677" y="69" fill="#94a3b8" font-size="11" font-family="monospace">violation</text>
147
+ ${lines}
148
+ ${nodes}
149
+ </svg>`;
150
+ }
151
+ function detectCycleEdges(adjacency) {
152
+ const visited = new Set();
153
+ const inStack = new Set();
154
+ const stack = [];
155
+ const cycleEdges = new Set();
156
+ function dfs(node) {
157
+ visited.add(node);
158
+ inStack.add(node);
159
+ stack.push(node);
160
+ for (const neighbor of adjacency.get(node) ?? []) {
161
+ if (!visited.has(neighbor)) {
162
+ dfs(neighbor);
163
+ continue;
164
+ }
165
+ if (!inStack.has(neighbor))
166
+ continue;
167
+ const startIndex = stack.indexOf(neighbor);
168
+ if (startIndex >= 0) {
169
+ for (let i = startIndex; i < stack.length - 1; i++) {
170
+ cycleEdges.add(`${stack[i]}->${stack[i + 1]}`);
171
+ }
172
+ }
173
+ cycleEdges.add(`${node}->${neighbor}`);
174
+ }
175
+ stack.pop();
176
+ inStack.delete(node);
177
+ }
178
+ for (const node of adjacency.keys()) {
179
+ if (!visited.has(node))
180
+ dfs(node);
181
+ }
182
+ return cycleEdges;
183
+ }
184
+ export function generateArchitectureMap(targetPath, outputFile = 'architecture.svg', config) {
185
+ const resolvedTarget = resolve(targetPath);
186
+ const svg = generateArchitectureSvg(resolvedTarget, config);
187
+ const outPath = resolve(outputFile);
188
+ writeFileSync(outPath, svg, 'utf8');
189
+ return outPath;
190
+ }
191
+ //# sourceMappingURL=map.js.map
@@ -0,0 +1,4 @@
1
+ import type { DriftReport, FileReport, MaintenanceRiskMetrics, RepoQualityScore } from './types.js';
2
+ export declare function computeRepoQuality(targetPath: string, files: FileReport[]): RepoQualityScore;
3
+ export declare function computeMaintenanceRisk(report: DriftReport): MaintenanceRiskMetrics;
4
+ //# sourceMappingURL=metrics.d.ts.map
@@ -0,0 +1,176 @@
1
+ import { existsSync, readdirSync, statSync } from 'node:fs';
2
+ import { execSync } from 'node:child_process';
3
+ import { join, relative } from 'node:path';
4
+ const ARCH_RULES = new Set([
5
+ 'circular-dependency',
6
+ 'layer-violation',
7
+ 'cross-boundary-import',
8
+ 'controller-no-db',
9
+ 'service-no-http',
10
+ ]);
11
+ const COMPLEXITY_RULES = new Set([
12
+ 'large-file',
13
+ 'large-function',
14
+ 'high-complexity',
15
+ 'deep-nesting',
16
+ 'too-many-params',
17
+ 'max-function-lines',
18
+ ]);
19
+ const AI_RULES = new Set([
20
+ 'over-commented',
21
+ 'hardcoded-config',
22
+ 'inconsistent-error-handling',
23
+ 'unnecessary-abstraction',
24
+ 'naming-inconsistency',
25
+ 'comment-contradiction',
26
+ 'ai-code-smell',
27
+ ]);
28
+ function clamp(value, min, max) {
29
+ return Math.max(min, Math.min(max, value));
30
+ }
31
+ function listFilesRecursively(root) {
32
+ if (!existsSync(root))
33
+ return [];
34
+ const out = [];
35
+ const stack = [root];
36
+ while (stack.length > 0) {
37
+ const current = stack.pop();
38
+ const entries = readdirSync(current);
39
+ for (const entry of entries) {
40
+ const full = join(current, entry);
41
+ const stat = statSync(full);
42
+ if (stat.isDirectory()) {
43
+ if (entry === 'node_modules' || entry === 'dist' || entry === '.git' || entry === '.next' || entry === 'build') {
44
+ continue;
45
+ }
46
+ stack.push(full);
47
+ }
48
+ else {
49
+ out.push(full);
50
+ }
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+ function hasNearbyTest(targetPath, filePath) {
56
+ const rel = relative(targetPath, filePath).replace(/\\/g, '/');
57
+ const noExt = rel.replace(/\.[^.]+$/, '');
58
+ const candidates = [
59
+ `${noExt}.test.ts`,
60
+ `${noExt}.test.tsx`,
61
+ `${noExt}.spec.ts`,
62
+ `${noExt}.spec.tsx`,
63
+ `${noExt}.test.js`,
64
+ `${noExt}.spec.js`,
65
+ ];
66
+ return candidates.some((candidate) => existsSync(join(targetPath, candidate)));
67
+ }
68
+ function getCommitTouchCount(targetPath, filePath) {
69
+ try {
70
+ const rel = relative(targetPath, filePath).replace(/\\/g, '/');
71
+ const output = execSync(`git rev-list --count HEAD -- "${rel}"`, {
72
+ cwd: targetPath,
73
+ encoding: 'utf8',
74
+ stdio: ['pipe', 'pipe', 'pipe'],
75
+ }).trim();
76
+ return Number(output) || 0;
77
+ }
78
+ catch {
79
+ return 0;
80
+ }
81
+ }
82
+ function qualityFromIssues(totalFiles, issues, rules) {
83
+ const count = issues.filter((issue) => rules.has(issue.rule)).length;
84
+ if (totalFiles === 0)
85
+ return 100;
86
+ return clamp(100 - Math.round((count / totalFiles) * 20), 0, 100);
87
+ }
88
+ export function computeRepoQuality(targetPath, files) {
89
+ const allIssues = files.flatMap((file) => file.issues);
90
+ const sourceFiles = files.filter((file) => !file.path.endsWith('package.json'));
91
+ const totalFiles = Math.max(sourceFiles.length, 1);
92
+ const testingCandidates = listFilesRecursively(targetPath).filter((filePath) => /\.(ts|tsx|js|jsx)$/.test(filePath) &&
93
+ !/\.test\.|\.spec\./.test(filePath) &&
94
+ !filePath.includes('node_modules'));
95
+ const withoutTests = testingCandidates.filter((filePath) => !hasNearbyTest(targetPath, filePath)).length;
96
+ const testing = testingCandidates.length === 0
97
+ ? 100
98
+ : clamp(100 - Math.round((withoutTests / testingCandidates.length) * 100), 0, 100);
99
+ const dimensions = {
100
+ architecture: qualityFromIssues(totalFiles, allIssues, ARCH_RULES),
101
+ complexity: qualityFromIssues(totalFiles, allIssues, COMPLEXITY_RULES),
102
+ 'ai-patterns': qualityFromIssues(totalFiles, allIssues, AI_RULES),
103
+ testing,
104
+ };
105
+ const overall = Math.round((dimensions.architecture +
106
+ dimensions.complexity +
107
+ dimensions['ai-patterns'] +
108
+ dimensions.testing) / 4);
109
+ return { overall, dimensions };
110
+ }
111
+ export function computeMaintenanceRisk(report) {
112
+ const allFiles = report.files;
113
+ const hotspots = allFiles
114
+ .map((file) => {
115
+ const complexityIssues = file.issues.filter((issue) => issue.rule === 'high-complexity' ||
116
+ issue.rule === 'deep-nesting' ||
117
+ issue.rule === 'large-function' ||
118
+ issue.rule === 'max-function-lines').length;
119
+ const changeFrequency = getCommitTouchCount(report.targetPath, file.path);
120
+ const hasTests = hasNearbyTest(report.targetPath, file.path);
121
+ const reasons = [];
122
+ let risk = 0;
123
+ if (complexityIssues > 0) {
124
+ risk += Math.min(40, complexityIssues * 10);
125
+ reasons.push('high complexity signals');
126
+ }
127
+ if (!hasTests) {
128
+ risk += 25;
129
+ reasons.push('no nearby tests');
130
+ }
131
+ if (changeFrequency >= 8) {
132
+ risk += 20;
133
+ reasons.push('frequently changed file');
134
+ }
135
+ if (file.score >= 50) {
136
+ risk += 15;
137
+ reasons.push('high drift score');
138
+ }
139
+ return {
140
+ file: file.path,
141
+ driftScore: file.score,
142
+ complexityIssues,
143
+ hasNearbyTests: hasTests,
144
+ changeFrequency,
145
+ risk: clamp(risk, 0, 100),
146
+ reasons,
147
+ };
148
+ })
149
+ .filter((hotspot) => hotspot.risk > 0)
150
+ .sort((a, b) => b.risk - a.risk)
151
+ .slice(0, 10);
152
+ const highComplexityFiles = hotspots.filter((hotspot) => hotspot.complexityIssues > 0).length;
153
+ const filesWithoutNearbyTests = hotspots.filter((hotspot) => !hotspot.hasNearbyTests).length;
154
+ const frequentChangeFiles = hotspots.filter((hotspot) => hotspot.changeFrequency >= 8).length;
155
+ const score = hotspots.length === 0
156
+ ? 0
157
+ : Math.round(hotspots.reduce((sum, hotspot) => sum + hotspot.risk, 0) / hotspots.length);
158
+ const level = score >= 75
159
+ ? 'critical'
160
+ : score >= 55
161
+ ? 'high'
162
+ : score >= 30
163
+ ? 'medium'
164
+ : 'low';
165
+ return {
166
+ score,
167
+ level,
168
+ hotspots,
169
+ signals: {
170
+ highComplexityFiles,
171
+ filesWithoutNearbyTests,
172
+ frequentChangeFiles,
173
+ },
174
+ };
175
+ }
176
+ //# sourceMappingURL=metrics.js.map
@@ -0,0 +1,6 @@
1
+ import type { PluginLoadError, LoadedPlugin } from './types.js';
2
+ export declare function loadPlugins(projectRoot: string, pluginIds: string[] | undefined): {
3
+ plugins: LoadedPlugin[];
4
+ errors: PluginLoadError[];
5
+ };
6
+ //# sourceMappingURL=plugins.d.ts.map
@@ -0,0 +1,74 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ const require = createRequire(import.meta.url);
5
+ function isPluginShape(value) {
6
+ if (!value || typeof value !== 'object')
7
+ return false;
8
+ const candidate = value;
9
+ if (typeof candidate.name !== 'string')
10
+ return false;
11
+ if (!Array.isArray(candidate.rules))
12
+ return false;
13
+ return candidate.rules.every((rule) => rule &&
14
+ typeof rule === 'object' &&
15
+ typeof rule.name === 'string' &&
16
+ typeof rule.detect === 'function');
17
+ }
18
+ function normalizePluginExport(mod) {
19
+ if (isPluginShape(mod))
20
+ return mod;
21
+ if (mod && typeof mod === 'object' && 'default' in mod) {
22
+ const maybeDefault = mod.default;
23
+ if (isPluginShape(maybeDefault))
24
+ return maybeDefault;
25
+ }
26
+ return undefined;
27
+ }
28
+ function resolvePluginSpecifier(projectRoot, pluginId) {
29
+ if (pluginId.startsWith('.') || pluginId.startsWith('/')) {
30
+ const abs = isAbsolute(pluginId) ? pluginId : resolve(projectRoot, pluginId);
31
+ if (existsSync(abs))
32
+ return abs;
33
+ if (existsSync(`${abs}.js`))
34
+ return `${abs}.js`;
35
+ if (existsSync(`${abs}.cjs`))
36
+ return `${abs}.cjs`;
37
+ if (existsSync(`${abs}.mjs`))
38
+ return `${abs}.mjs`;
39
+ if (existsSync(`${abs}.ts`))
40
+ return `${abs}.ts`;
41
+ return abs;
42
+ }
43
+ return pluginId;
44
+ }
45
+ export function loadPlugins(projectRoot, pluginIds) {
46
+ if (!pluginIds || pluginIds.length === 0) {
47
+ return { plugins: [], errors: [] };
48
+ }
49
+ const loaded = [];
50
+ const errors = [];
51
+ for (const pluginId of pluginIds) {
52
+ const resolved = resolvePluginSpecifier(projectRoot, pluginId);
53
+ try {
54
+ const mod = require(resolved);
55
+ const plugin = normalizePluginExport(mod);
56
+ if (!plugin) {
57
+ errors.push({
58
+ pluginId,
59
+ message: `Invalid plugin contract in '${pluginId}'. Expected: { name, rules[] }`,
60
+ });
61
+ continue;
62
+ }
63
+ loaded.push({ id: pluginId, plugin });
64
+ }
65
+ catch (error) {
66
+ errors.push({
67
+ pluginId,
68
+ message: error instanceof Error ? error.message : String(error),
69
+ });
70
+ }
71
+ }
72
+ return { plugins: loaded, errors };
73
+ }
74
+ //# sourceMappingURL=plugins.js.map
package/dist/printer.js CHANGED
@@ -111,6 +111,26 @@ function formatFixSuggestion(issue) {
111
111
  'Pick one naming convention (camelCase for variables/functions, PascalCase for types)',
112
112
  'Rename snake_case identifiers to camelCase to match TypeScript conventions',
113
113
  ],
114
+ 'controller-no-db': [
115
+ 'Move DB access to a service/repository and inject it into the controller',
116
+ 'Keep controllers focused on transport and orchestration only',
117
+ ],
118
+ 'service-no-http': [
119
+ 'Move HTTP concerns to adapters/clients and keep services framework-agnostic',
120
+ 'Inject interfaces for outbound calls instead of calling fetch/express directly',
121
+ ],
122
+ 'max-function-lines': [
123
+ 'Split the function into smaller units with clear responsibilities',
124
+ 'Extract branch-heavy chunks into dedicated helpers',
125
+ ],
126
+ 'ai-code-smell': [
127
+ 'Address the listed AI-smell signals in this file before adding more code',
128
+ 'Prioritize consistency: naming, error handling, and abstraction level',
129
+ ],
130
+ 'plugin-error': [
131
+ 'Fix or remove the failing plugin in drift.config.*',
132
+ 'Validate plugin contract: export { name, rules[] } and detector functions',
133
+ ],
114
134
  };
115
135
  return suggestions[issue.rule] ?? ['Review and fix manually'];
116
136
  }
package/dist/report.js CHANGED
@@ -638,6 +638,8 @@ export function generateHtmlReport(report) {
638
638
  const projColor = scoreColor(report.totalScore);
639
639
  const projLabel = scoreLabel(report.totalScore);
640
640
  const projGrade = scoreGrade(report.totalScore);
641
+ const quality = report.quality;
642
+ const risk = report.maintenanceRisk;
641
643
  const filesWithIssues = report.files.filter(f => f.issues.length > 0).length;
642
644
  // ── Top rules for sidebar ──────────────────────────────────────────────
643
645
  const topRules = Object.entries(report.summary.byRule)
@@ -648,6 +650,16 @@ export function generateHtmlReport(report) {
648
650
  <span class="rule-name">${escapeHtml(rule)}</span>
649
651
  <span class="rule-count">${count}</span>
650
652
  </button>`).join('');
653
+ const hotspotsHtml = risk.hotspots.length === 0
654
+ ? '<div class="empty-state" style="padding:0.8rem">No hotspots detected.</div>'
655
+ : risk.hotspots.slice(0, 5).map((hotspot) => `
656
+ <div class="issue-row" style="grid-template-columns: 62px 1fr;grid-template-rows:auto auto;">
657
+ <span class="issue-line">R${hotspot.risk}</span>
658
+ <div class="issue-rule-msg">
659
+ <span class="issue-rule">hotspot</span>
660
+ <span class="issue-msg">${escapeHtml(hotspot.file)} (${hotspot.reasons.join(', ')})</span>
661
+ </div>
662
+ </div>`).join('');
651
663
  // ── File sections ──────────────────────────────────────────────────────
652
664
  const fileSections = report.files
653
665
  .filter(f => f.issues.length > 0)
@@ -755,6 +767,21 @@ export function generateHtmlReport(report) {
755
767
  </div>
756
768
  </div>
757
769
 
770
+ <div class="sidebar-block">
771
+ <div class="sidebar-label">Repo Quality</div>
772
+ <div style="font-size:1.1rem;font-weight:700;color:${scoreColor(100 - quality.overall)}">${quality.overall}/100</div>
773
+ <div style="font-size:0.72rem;color:var(--muted)">Architecture ${quality.dimensions.architecture} · Complexity ${quality.dimensions.complexity}</div>
774
+ <div style="font-size:0.72rem;color:var(--muted)">AI patterns ${quality.dimensions['ai-patterns']} · Testing ${quality.dimensions.testing}</div>
775
+ </div>
776
+
777
+ <div class="sidebar-block">
778
+ <div class="sidebar-label">Maintenance Risk</div>
779
+ <div style="font-size:1.1rem;font-weight:700;color:${scoreColor(risk.score)}">${risk.score}/100 (${risk.level.toUpperCase()})</div>
780
+ <div style="font-size:0.72rem;color:var(--muted)">High complexity: ${risk.signals.highComplexityFiles}</div>
781
+ <div style="font-size:0.72rem;color:var(--muted)">No tests: ${risk.signals.filesWithoutNearbyTests}</div>
782
+ <div style="font-size:0.72rem;color:var(--muted)">Frequent changes: ${risk.signals.frequentChangeFiles}</div>
783
+ </div>
784
+
758
785
  <!-- Severity filters -->
759
786
  <div class="sidebar-block">
760
787
  <div class="sidebar-label">Severity</div>
@@ -804,6 +831,13 @@ export function generateHtmlReport(report) {
804
831
  <div class="main-header">
805
832
  <span id="issue-counter" style="color:var(--muted);font-size:0.75rem">Loading…</span>
806
833
  </div>
834
+ <section class="file-section" open>
835
+ <summary>
836
+ <span class="file-name">Risk hotspots</span>
837
+ <span class="file-score" style="color:${scoreColor(risk.score)}">${risk.score}/100</span>
838
+ </summary>
839
+ <div class="issues-list">${hotspotsHtml}</div>
840
+ </section>
807
841
  ${fileSections || noIssues}
808
842
  </main>
809
843