mstro-app 0.3.7 → 0.3.8

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 (51) hide show
  1. package/README.md +4 -8
  2. package/bin/mstro.js +54 -15
  3. package/dist/server/cli/headless/stall-assessor.d.ts.map +1 -1
  4. package/dist/server/cli/headless/stall-assessor.js +4 -1
  5. package/dist/server/cli/headless/stall-assessor.js.map +1 -1
  6. package/dist/server/cli/headless/tool-watchdog.d.ts.map +1 -1
  7. package/dist/server/cli/headless/tool-watchdog.js +8 -0
  8. package/dist/server/cli/headless/tool-watchdog.js.map +1 -1
  9. package/dist/server/index.js +0 -4
  10. package/dist/server/index.js.map +1 -1
  11. package/dist/server/mcp/bouncer-integration.d.ts +2 -0
  12. package/dist/server/mcp/bouncer-integration.d.ts.map +1 -1
  13. package/dist/server/mcp/bouncer-integration.js +55 -39
  14. package/dist/server/mcp/bouncer-integration.js.map +1 -1
  15. package/dist/server/mcp/bouncer-sandbox.d.ts +60 -0
  16. package/dist/server/mcp/bouncer-sandbox.d.ts.map +1 -0
  17. package/dist/server/mcp/bouncer-sandbox.js +182 -0
  18. package/dist/server/mcp/bouncer-sandbox.js.map +1 -0
  19. package/dist/server/mcp/security-patterns.d.ts +6 -12
  20. package/dist/server/mcp/security-patterns.d.ts.map +1 -1
  21. package/dist/server/mcp/security-patterns.js +197 -10
  22. package/dist/server/mcp/security-patterns.js.map +1 -1
  23. package/dist/server/services/websocket/handler.d.ts +0 -1
  24. package/dist/server/services/websocket/handler.d.ts.map +1 -1
  25. package/dist/server/services/websocket/handler.js +7 -2
  26. package/dist/server/services/websocket/handler.js.map +1 -1
  27. package/dist/server/services/websocket/quality-handlers.d.ts +4 -0
  28. package/dist/server/services/websocket/quality-handlers.d.ts.map +1 -0
  29. package/dist/server/services/websocket/quality-handlers.js +106 -0
  30. package/dist/server/services/websocket/quality-handlers.js.map +1 -0
  31. package/dist/server/services/websocket/quality-service.d.ts +54 -0
  32. package/dist/server/services/websocket/quality-service.d.ts.map +1 -0
  33. package/dist/server/services/websocket/quality-service.js +766 -0
  34. package/dist/server/services/websocket/quality-service.js.map +1 -0
  35. package/dist/server/services/websocket/session-handlers.d.ts.map +1 -1
  36. package/dist/server/services/websocket/session-handlers.js +23 -0
  37. package/dist/server/services/websocket/session-handlers.js.map +1 -1
  38. package/dist/server/services/websocket/types.d.ts +2 -2
  39. package/dist/server/services/websocket/types.d.ts.map +1 -1
  40. package/package.json +2 -1
  41. package/server/cli/headless/stall-assessor.ts +4 -1
  42. package/server/cli/headless/tool-watchdog.ts +8 -0
  43. package/server/index.ts +0 -4
  44. package/server/mcp/bouncer-integration.ts +66 -44
  45. package/server/mcp/bouncer-sandbox.ts +214 -0
  46. package/server/mcp/security-patterns.ts +206 -10
  47. package/server/services/websocket/handler.ts +7 -2
  48. package/server/services/websocket/quality-handlers.ts +140 -0
  49. package/server/services/websocket/quality-service.ts +922 -0
  50. package/server/services/websocket/session-handlers.ts +26 -0
  51. package/server/services/websocket/types.ts +14 -0
@@ -0,0 +1,922 @@
1
+ // Copyright (c) 2025-present Mstro, Inc. All rights reserved.
2
+ // Licensed under the MIT License. See LICENSE file for details.
3
+
4
+ import { spawn } from 'node:child_process';
5
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
6
+ import { extname, join, relative } from 'node:path';
7
+
8
+ // ============================================================================
9
+ // Types
10
+ // ============================================================================
11
+
12
+ export interface QualityTool {
13
+ name: string;
14
+ installed: boolean;
15
+ installCommand: string;
16
+ category: 'linter' | 'formatter' | 'complexity' | 'general';
17
+ }
18
+
19
+ export interface CategoryScore {
20
+ name: string;
21
+ score: number;
22
+ weight: number;
23
+ effectiveWeight: number;
24
+ available: boolean;
25
+ issueCount?: number;
26
+ details?: Record<string, unknown>;
27
+ }
28
+
29
+ export interface QualityFinding {
30
+ severity: 'critical' | 'high' | 'medium' | 'low';
31
+ category: string;
32
+ file: string;
33
+ line: number | null;
34
+ title: string;
35
+ description: string;
36
+ suggestion?: string;
37
+ }
38
+
39
+ export interface QualityResults {
40
+ overall: number;
41
+ grade: string;
42
+ categories: CategoryScore[];
43
+ findings: QualityFinding[];
44
+ codeReview: QualityFinding[];
45
+ analyzedFiles: number;
46
+ totalLines: number;
47
+ timestamp: string;
48
+ ecosystem: string[];
49
+ }
50
+
51
+ export interface ScanProgress {
52
+ step: string;
53
+ current: number;
54
+ total: number;
55
+ }
56
+
57
+ type Ecosystem = 'node' | 'python' | 'rust' | 'go' | 'unknown';
58
+
59
+ interface ToolSpec {
60
+ name: string;
61
+ check: string[];
62
+ category: QualityTool['category'];
63
+ installCmd: string;
64
+ }
65
+
66
+ // ============================================================================
67
+ // Constants
68
+ // ============================================================================
69
+
70
+ const ECOSYSTEM_TOOLS: Record<Ecosystem, ToolSpec[]> = {
71
+ node: [
72
+ { name: 'eslint', check: ['npx', 'eslint', '--version'], category: 'linter', installCmd: 'npm install -D eslint' },
73
+ { name: 'biome', check: ['npx', '@biomejs/biome', '--version'], category: 'linter', installCmd: 'npm install -D @biomejs/biome' },
74
+ { name: 'prettier', check: ['npx', 'prettier', '--version'], category: 'formatter', installCmd: 'npm install -D prettier' },
75
+ { name: 'typescript', check: ['npx', 'tsc', '--version'], category: 'general', installCmd: 'npm install -D typescript' },
76
+ ],
77
+ python: [
78
+ { name: 'ruff', check: ['ruff', '--version'], category: 'linter', installCmd: 'pip install ruff' },
79
+ { name: 'black', check: ['black', '--version'], category: 'formatter', installCmd: 'pip install black' },
80
+ { name: 'radon', check: ['radon', '--version'], category: 'complexity', installCmd: 'pip install radon' },
81
+ ],
82
+ rust: [
83
+ { name: 'clippy', check: ['cargo', 'clippy', '--version'], category: 'linter', installCmd: 'rustup component add clippy' },
84
+ { name: 'rustfmt', check: ['rustfmt', '--version'], category: 'formatter', installCmd: 'rustup component add rustfmt' },
85
+ ],
86
+ go: [
87
+ { name: 'golangci-lint', check: ['golangci-lint', '--version'], category: 'linter', installCmd: 'go install github.com/golangci-lint/golangci-lint/cmd/golangci-lint@latest' },
88
+ { name: 'gofmt', check: ['gofmt', '-h'], category: 'formatter', installCmd: '(built-in with Go)' },
89
+ ],
90
+ unknown: [],
91
+ };
92
+
93
+ const SOURCE_EXTENSIONS = new Set([
94
+ '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',
95
+ '.py', '.pyi',
96
+ '.rs',
97
+ '.go',
98
+ '.java', '.kt',
99
+ '.cs',
100
+ '.rb',
101
+ '.php',
102
+ '.swift',
103
+ '.c', '.cpp', '.h', '.hpp',
104
+ ]);
105
+
106
+ const IGNORE_DIRS = new Set([
107
+ 'node_modules', '.git', 'dist', 'build', '.next', '__pycache__',
108
+ 'target', 'vendor', '.venv', 'venv', '.tox', 'coverage',
109
+ '.mstro', '.cache', '.turbo', '.output',
110
+ ]);
111
+
112
+ const FILE_LENGTH_THRESHOLD = 300;
113
+ const FUNCTION_LENGTH_THRESHOLD = 50;
114
+ const TOTAL_STEPS = 7;
115
+
116
+ // ============================================================================
117
+ // Ecosystem Detection
118
+ // ============================================================================
119
+
120
+ export function detectEcosystem(dirPath: string): Ecosystem[] {
121
+ const ecosystems: Ecosystem[] = [];
122
+ try {
123
+ const files = readdirSync(dirPath);
124
+ if (files.includes('package.json')) ecosystems.push('node');
125
+ if (files.includes('pyproject.toml') || files.includes('setup.py') || files.includes('requirements.txt')) ecosystems.push('python');
126
+ if (files.includes('Cargo.toml')) ecosystems.push('rust');
127
+ if (files.includes('go.mod')) ecosystems.push('go');
128
+ } catch {
129
+ // Directory not readable
130
+ }
131
+ if (ecosystems.length === 0) ecosystems.push('unknown');
132
+ return ecosystems;
133
+ }
134
+
135
+ // ============================================================================
136
+ // Tool Detection
137
+ // ============================================================================
138
+
139
+ async function checkToolInstalled(check: string[], cwd: string): Promise<boolean> {
140
+ return new Promise((resolve) => {
141
+ const proc = spawn(check[0], check.slice(1), {
142
+ cwd,
143
+ stdio: ['ignore', 'pipe', 'pipe'],
144
+ timeout: 10000,
145
+ });
146
+ proc.on('close', (code) => resolve(code === 0));
147
+ proc.on('error', () => resolve(false));
148
+ });
149
+ }
150
+
151
+ export async function detectTools(dirPath: string): Promise<{ tools: QualityTool[]; ecosystem: string[] }> {
152
+ const ecosystems = detectEcosystem(dirPath);
153
+ const tools: QualityTool[] = [];
154
+
155
+ for (const eco of ecosystems) {
156
+ const specs = ECOSYSTEM_TOOLS[eco] || [];
157
+ for (const spec of specs) {
158
+ const installed = await checkToolInstalled(spec.check, dirPath);
159
+ tools.push({
160
+ name: spec.name,
161
+ installed,
162
+ installCommand: spec.installCmd,
163
+ category: spec.category,
164
+ });
165
+ }
166
+ }
167
+
168
+ return { tools, ecosystem: ecosystems };
169
+ }
170
+
171
+ // ============================================================================
172
+ // Tool Installation
173
+ // ============================================================================
174
+
175
+ export async function installTools(
176
+ dirPath: string,
177
+ toolNames?: string[],
178
+ ): Promise<{ tools: QualityTool[]; ecosystem: string[] }> {
179
+ const { tools } = await detectTools(dirPath);
180
+ const toInstall = tools.filter((t) => !t.installed && (!toolNames || toolNames.includes(t.name)));
181
+
182
+ for (const tool of toInstall) {
183
+ if (tool.installCommand.startsWith('(')) continue; // built-in, skip
184
+ const parts = tool.installCommand.split(' ');
185
+ await runCommand(parts[0], parts.slice(1), dirPath);
186
+ }
187
+
188
+ // Re-detect after install
189
+ return detectTools(dirPath);
190
+ }
191
+
192
+ // ============================================================================
193
+ // File Scanning
194
+ // ============================================================================
195
+
196
+ interface SourceFile {
197
+ path: string;
198
+ relativePath: string;
199
+ lines: number;
200
+ content: string;
201
+ }
202
+
203
+ function tryStatSync(path: string): ReturnType<typeof statSync> | null {
204
+ try { return statSync(path); } catch { return null; }
205
+ }
206
+
207
+ function tryReadFile(path: string): string | null {
208
+ try { return readFileSync(path, 'utf-8'); } catch { return null; }
209
+ }
210
+
211
+ function tryReaddirSync(dir: string): string[] | null {
212
+ try { return readdirSync(dir); } catch { return null; }
213
+ }
214
+
215
+ function tryReadSourceFile(fullPath: string, rootPath: string): SourceFile | null {
216
+ const content = tryReadFile(fullPath);
217
+ if (!content) return null;
218
+ return {
219
+ path: fullPath,
220
+ relativePath: relative(rootPath, fullPath),
221
+ lines: content.split('\n').length,
222
+ content,
223
+ };
224
+ }
225
+
226
+ function processEntry(entry: string, dir: string, rootPath: string, stack: string[], files: SourceFile[]): void {
227
+ if (IGNORE_DIRS.has(entry)) return;
228
+ const fullPath = join(dir, entry);
229
+ const stat = tryStatSync(fullPath);
230
+ if (!stat) return;
231
+
232
+ if (stat.isDirectory()) { stack.push(fullPath); return; }
233
+ if (!stat.isFile() || !SOURCE_EXTENSIONS.has(extname(entry).toLowerCase())) return;
234
+
235
+ const sourceFile = tryReadSourceFile(fullPath, rootPath);
236
+ if (sourceFile) files.push(sourceFile);
237
+ }
238
+
239
+ function collectSourceFiles(dirPath: string, rootPath: string): SourceFile[] {
240
+ const files: SourceFile[] = [];
241
+ const stack = [dirPath];
242
+
243
+ while (stack.length > 0) {
244
+ const dir = stack.pop()!;
245
+ const entries = tryReaddirSync(dir);
246
+ if (!entries) continue;
247
+
248
+ for (const entry of entries) {
249
+ processEntry(entry, dir, rootPath, stack, files);
250
+ }
251
+ }
252
+
253
+ return files;
254
+ }
255
+
256
+ // ============================================================================
257
+ // Command Runner
258
+ // ============================================================================
259
+
260
+ function runCommand(cmd: string, args: string[], cwd: string): Promise<{ stdout: string; stderr: string; exitCode: number }> {
261
+ return new Promise((resolve) => {
262
+ const proc = spawn(cmd, args, {
263
+ cwd,
264
+ stdio: ['ignore', 'pipe', 'pipe'],
265
+ timeout: 120000,
266
+ });
267
+ let stdout = '';
268
+ let stderr = '';
269
+ proc.stdout?.on('data', (d: Buffer) => { stdout += d.toString(); });
270
+ proc.stderr?.on('data', (d: Buffer) => { stderr += d.toString(); });
271
+ proc.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? 1 }));
272
+ proc.on('error', (err) => resolve({ stdout: '', stderr: err.message, exitCode: 1 }));
273
+ });
274
+ }
275
+
276
+ // ============================================================================
277
+ // Linting Analysis
278
+ // ============================================================================
279
+
280
+ interface LintAccumulator {
281
+ errors: number;
282
+ warnings: number;
283
+ findings: QualityFinding[];
284
+ ran: boolean;
285
+ }
286
+
287
+ function newLintAccumulator(): LintAccumulator {
288
+ return { errors: 0, warnings: 0, findings: [], ran: false };
289
+ }
290
+
291
+ function biomeSeverity(severity: string): QualityFinding['severity'] {
292
+ if (severity === 'error') return 'high';
293
+ if (severity === 'warning') return 'medium';
294
+ return 'low';
295
+ }
296
+
297
+ function processBiomeDiagnostic(d: Record<string, unknown>, acc: LintAccumulator): void {
298
+ const sev = biomeSeverity(d.severity as string);
299
+ if (d.severity === 'error') acc.errors++;
300
+ else acc.warnings++;
301
+ const location = d.location as Record<string, unknown> | undefined;
302
+ const span = (location?.span as Record<string, unknown>) ?? {};
303
+ const start = (span.start as Record<string, unknown>) ?? {};
304
+ const message = d.message as Record<string, unknown> | string | undefined;
305
+ acc.findings.push({
306
+ severity: sev,
307
+ category: 'linting',
308
+ file: (location?.path as string) || '',
309
+ line: (start.line as number) ?? null,
310
+ title: (d.category as string) || 'Lint issue',
311
+ description: (typeof message === 'object' ? (message?.text as string) : message) || '',
312
+ });
313
+ }
314
+
315
+ function parseBiomeDiagnostics(stdout: string, acc: LintAccumulator): void {
316
+ const parsed = JSON.parse(stdout);
317
+ if (!parsed.diagnostics) return;
318
+ for (const d of parsed.diagnostics) {
319
+ processBiomeDiagnostic(d, acc);
320
+ }
321
+ }
322
+
323
+ async function lintWithBiome(dirPath: string, acc: LintAccumulator): Promise<void> {
324
+ const result = await runCommand('npx', ['@biomejs/biome', 'lint', '--reporter=json', '.'], dirPath);
325
+ if (result.exitCode > 1) return;
326
+
327
+ acc.ran = true;
328
+ try {
329
+ parseBiomeDiagnostics(result.stdout, acc);
330
+ } catch {
331
+ // JSON parse failed, try line counting
332
+ acc.errors += (result.stdout.match(/error/gi) || []).length;
333
+ acc.warnings += (result.stdout.match(/warning/gi) || []).length;
334
+ acc.ran = acc.errors > 0 || acc.warnings > 0 || result.exitCode === 0;
335
+ }
336
+ }
337
+
338
+ async function lintWithEslint(dirPath: string, acc: LintAccumulator): Promise<void> {
339
+ const result = await runCommand('npx', ['eslint', '--format=json', '.'], dirPath);
340
+ acc.ran = true;
341
+ try {
342
+ const parsed = JSON.parse(result.stdout);
343
+ for (const file of parsed) {
344
+ for (const msg of file.messages || []) {
345
+ if (msg.severity === 2) acc.errors++;
346
+ else acc.warnings++;
347
+ acc.findings.push({
348
+ severity: msg.severity === 2 ? 'high' : 'medium',
349
+ category: 'linting',
350
+ file: relative(dirPath, file.filePath),
351
+ line: msg.line ?? null,
352
+ title: msg.ruleId || 'Lint issue',
353
+ description: msg.message,
354
+ });
355
+ }
356
+ }
357
+ } catch {
358
+ acc.errors += (result.stderr.match(/error/gi) || []).length;
359
+ acc.warnings += (result.stderr.match(/warning/gi) || []).length;
360
+ }
361
+ }
362
+
363
+ async function lintNode(dirPath: string, acc: LintAccumulator): Promise<void> {
364
+ const biomeConfig = existsSync(join(dirPath, 'biome.json')) || existsSync(join(dirPath, 'biome.jsonc'));
365
+ if (biomeConfig) {
366
+ await lintWithBiome(dirPath, acc);
367
+ } else {
368
+ await lintWithEslint(dirPath, acc);
369
+ }
370
+ }
371
+
372
+ async function lintPython(dirPath: string, acc: LintAccumulator): Promise<void> {
373
+ const result = await runCommand('ruff', ['check', '--output-format=json', '.'], dirPath);
374
+ if (result.exitCode > 1) return;
375
+
376
+ acc.ran = true;
377
+ try {
378
+ const parsed = JSON.parse(result.stdout);
379
+ for (const item of parsed) {
380
+ const sev = item.code?.startsWith('E') ? 'high' : 'medium';
381
+ if (sev === 'high') acc.errors++;
382
+ else acc.warnings++;
383
+ acc.findings.push({
384
+ severity: sev,
385
+ category: 'linting',
386
+ file: item.filename ? relative(dirPath, item.filename) : '',
387
+ line: item.location?.row ?? null,
388
+ title: item.code || 'Lint issue',
389
+ description: item.message || '',
390
+ });
391
+ }
392
+ } catch { /* ignore */ }
393
+ }
394
+
395
+ function processClippyMessage(msg: Record<string, unknown>, acc: LintAccumulator): void {
396
+ if (msg.reason !== 'compiler-message' || !msg.message) return;
397
+ const message = msg.message as Record<string, unknown>;
398
+ const level = message.level as string;
399
+ if (level === 'error') acc.errors++;
400
+ else if (level === 'warning') acc.warnings++;
401
+ const spans = message.spans as Array<Record<string, unknown>> | undefined;
402
+ const span = spans?.[0];
403
+ const code = message.code as Record<string, unknown> | undefined;
404
+ acc.findings.push({
405
+ severity: level === 'error' ? 'high' : 'medium',
406
+ category: 'linting',
407
+ file: (span?.file_name as string) || '',
408
+ line: (span?.line_start as number) ?? null,
409
+ title: (code?.code as string) || 'Clippy',
410
+ description: (message.message as string) || '',
411
+ });
412
+ }
413
+
414
+ function parseClippyOutput(stdout: string, acc: LintAccumulator): void {
415
+ for (const line of stdout.split('\n')) {
416
+ try {
417
+ const msg = JSON.parse(line);
418
+ processClippyMessage(msg, acc);
419
+ } catch { /* not JSON line */ }
420
+ }
421
+ }
422
+
423
+ async function lintRust(dirPath: string, acc: LintAccumulator): Promise<void> {
424
+ const result = await runCommand('cargo', ['clippy', '--message-format=json', '--', '-W', 'clippy::all'], dirPath);
425
+ if (result.exitCode > 1) return;
426
+
427
+ acc.ran = true;
428
+ parseClippyOutput(result.stdout, acc);
429
+ }
430
+
431
+ function computeLintScore(totalErrors: number, totalWarnings: number, totalLines: number): number {
432
+ const kloc = Math.max(totalLines / 1000, 1);
433
+ const penaltyRaw = totalErrors * 10 + totalWarnings * 3;
434
+ const penaltyPerKloc = penaltyRaw / kloc;
435
+
436
+ let score: number;
437
+ if (penaltyPerKloc === 0) score = 100;
438
+ else if (penaltyPerKloc <= 5) score = 100 - penaltyPerKloc * 2;
439
+ else if (penaltyPerKloc <= 20) score = 90 - (penaltyPerKloc - 5) * 2;
440
+ else if (penaltyPerKloc <= 50) score = 60 - (penaltyPerKloc - 20) * 1.5;
441
+ else score = Math.max(0, 15 - (penaltyPerKloc - 50) * 0.3);
442
+
443
+ return Math.round(Math.max(0, Math.min(100, score)));
444
+ }
445
+
446
+ async function analyzeLinting(
447
+ dirPath: string,
448
+ ecosystems: Ecosystem[],
449
+ files: SourceFile[],
450
+ ): Promise<{ score: number; findings: QualityFinding[]; available: boolean; issueCount: number }> {
451
+ const acc = newLintAccumulator();
452
+
453
+ if (ecosystems.includes('node')) await lintNode(dirPath, acc);
454
+ if (ecosystems.includes('python')) await lintPython(dirPath, acc);
455
+ if (ecosystems.includes('rust')) await lintRust(dirPath, acc);
456
+
457
+ if (!acc.ran) {
458
+ return { score: 0, findings: [], available: false, issueCount: 0 };
459
+ }
460
+
461
+ const totalLines = files.reduce((sum, f) => sum + f.lines, 0);
462
+ const score = computeLintScore(acc.errors, acc.warnings, totalLines);
463
+
464
+ return {
465
+ score,
466
+ findings: acc.findings.slice(0, 100),
467
+ available: true,
468
+ issueCount: acc.errors + acc.warnings,
469
+ };
470
+ }
471
+
472
+ // ============================================================================
473
+ // Formatting Analysis
474
+ // ============================================================================
475
+
476
+ async function analyzeFormatting(
477
+ dirPath: string,
478
+ ecosystems: Ecosystem[],
479
+ files: SourceFile[],
480
+ ): Promise<{ score: number; available: boolean; issueCount: number }> {
481
+ let totalFiles = 0;
482
+ let passingFiles = 0;
483
+ let ran = false;
484
+
485
+ if (ecosystems.includes('node')) {
486
+ const result = await runCommand('npx', ['prettier', '--check', '.'], dirPath);
487
+ ran = true;
488
+ // prettier --check outputs filenames of unformatted files to stdout
489
+ const unformatted = result.stdout.split('\n').filter((l) => l.trim() && !l.startsWith('Checking'));
490
+ const nodeFiles = files.filter((f) => ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].includes(extname(f.path)));
491
+ totalFiles += nodeFiles.length;
492
+ passingFiles += Math.max(0, nodeFiles.length - unformatted.length);
493
+ }
494
+
495
+ if (ecosystems.includes('python')) {
496
+ const result = await runCommand('black', ['--check', '--quiet', '.'], dirPath);
497
+ ran = true;
498
+ const pyFiles = files.filter((f) => ['.py', '.pyi'].includes(extname(f.path)));
499
+ totalFiles += pyFiles.length;
500
+ if (result.exitCode === 0) {
501
+ passingFiles += pyFiles.length;
502
+ } else {
503
+ const wouldReformat = (result.stderr.match(/would reformat/gi) || []).length;
504
+ passingFiles += Math.max(0, pyFiles.length - wouldReformat);
505
+ }
506
+ }
507
+
508
+ if (ecosystems.includes('rust')) {
509
+ const result = await runCommand('cargo', ['fmt', '--check'], dirPath);
510
+ ran = true;
511
+ const rsFiles = files.filter((f) => extname(f.path) === '.rs');
512
+ totalFiles += rsFiles.length;
513
+ if (result.exitCode === 0) passingFiles += rsFiles.length;
514
+ }
515
+
516
+ if (!ran || totalFiles === 0) {
517
+ return { score: 0, available: false, issueCount: 0 };
518
+ }
519
+
520
+ const score = Math.round((passingFiles / totalFiles) * 100);
521
+ return { score, available: true, issueCount: totalFiles - passingFiles };
522
+ }
523
+
524
+ // ============================================================================
525
+ // File Length Analysis
526
+ // ============================================================================
527
+
528
+ function analyzeFileLength(files: SourceFile[]): { score: number; findings: QualityFinding[]; issueCount: number } {
529
+ if (files.length === 0) return { score: 100, findings: [], issueCount: 0 };
530
+
531
+ const findings: QualityFinding[] = [];
532
+ let totalScore = 0;
533
+
534
+ for (const file of files) {
535
+ const ratio = Math.max(1, file.lines / FILE_LENGTH_THRESHOLD);
536
+ const fileScore = 100 / ratio ** 1.5;
537
+ totalScore += fileScore;
538
+
539
+ if (file.lines > FILE_LENGTH_THRESHOLD) {
540
+ findings.push({
541
+ severity: file.lines > FILE_LENGTH_THRESHOLD * 3 ? 'high' : file.lines > FILE_LENGTH_THRESHOLD * 2 ? 'medium' : 'low',
542
+ category: 'file-length',
543
+ file: file.relativePath,
544
+ line: null,
545
+ title: `File has ${file.lines} lines (threshold: ${FILE_LENGTH_THRESHOLD})`,
546
+ description: `This file exceeds the recommended length of ${FILE_LENGTH_THRESHOLD} lines by ${file.lines - FILE_LENGTH_THRESHOLD} lines.`,
547
+ });
548
+ }
549
+ }
550
+
551
+ const score = Math.round(totalScore / files.length);
552
+ return { score: Math.min(100, score), findings: findings.slice(0, 50), issueCount: findings.length };
553
+ }
554
+
555
+ // ============================================================================
556
+ // Function Length Analysis
557
+ // ============================================================================
558
+
559
+ interface FunctionInfo {
560
+ name: string;
561
+ file: string;
562
+ startLine: number;
563
+ lines: number;
564
+ }
565
+
566
+ // Match function declarations, arrow functions assigned to const/let, and methods
567
+ const JS_FUNC_PATTERN = /^(\s*)(export\s+)?(async\s+)?function\s+(\w+)|^(\s*)(export\s+)?(const|let|var)\s+(\w+)\s*=\s*(async\s+)?\(|^(\s*)(public|private|protected)?\s*(async\s+)?(\w+)\s*\(/;
568
+
569
+ function countBraceDeltas(line: string): number {
570
+ let delta = 0;
571
+ for (const ch of line) {
572
+ if (ch === '{') delta++;
573
+ else if (ch === '}') delta--;
574
+ }
575
+ return delta;
576
+ }
577
+
578
+ function matchJsFuncStart(line: string): { name: string; indent: number } | null {
579
+ const match = JS_FUNC_PATTERN.exec(line);
580
+ if (!match) return null;
581
+ const name = match[4] || match[8] || match[13] || 'anonymous';
582
+ const indent = (match[1] || match[5] || match[10] || '').length;
583
+ return { name, indent };
584
+ }
585
+
586
+ function extractJsFunctions(file: SourceFile): FunctionInfo[] {
587
+ const functions: FunctionInfo[] = [];
588
+ const lines = file.content.split('\n');
589
+ let braceDepth = 0;
590
+ let currentFunc: { name: string; startLine: number; indent: number } | null = null;
591
+ let funcStartBraceDepth = 0;
592
+
593
+ for (let i = 0; i < lines.length; i++) {
594
+ if (!currentFunc) {
595
+ const funcStart = matchJsFuncStart(lines[i]);
596
+ if (funcStart) {
597
+ currentFunc = { name: funcStart.name, startLine: i + 1, indent: funcStart.indent };
598
+ funcStartBraceDepth = braceDepth;
599
+ }
600
+ }
601
+
602
+ braceDepth += countBraceDeltas(lines[i]);
603
+
604
+ if (currentFunc && braceDepth <= funcStartBraceDepth && i > currentFunc.startLine - 1) {
605
+ functions.push({
606
+ name: currentFunc.name,
607
+ file: file.relativePath,
608
+ startLine: currentFunc.startLine,
609
+ lines: i + 1 - currentFunc.startLine + 1,
610
+ });
611
+ currentFunc = null;
612
+ }
613
+ }
614
+
615
+ return functions;
616
+ }
617
+
618
+ function extractPyFunctions(file: SourceFile): FunctionInfo[] {
619
+ const functions: FunctionInfo[] = [];
620
+ const lines = file.content.split('\n');
621
+ const defPattern = /^(\s*)(async\s+)?def\s+(\w+)/;
622
+ let currentFunc: { name: string; startLine: number; indent: number } | null = null;
623
+
624
+ for (let i = 0; i < lines.length; i++) {
625
+ const match = defPattern.exec(lines[i]);
626
+ if (match) {
627
+ if (currentFunc) {
628
+ functions.push({
629
+ name: currentFunc.name,
630
+ file: file.relativePath,
631
+ startLine: currentFunc.startLine,
632
+ lines: i - currentFunc.startLine + 1,
633
+ });
634
+ }
635
+ currentFunc = { name: match[3], startLine: i + 1, indent: match[1].length };
636
+ } else if (currentFunc && lines[i].trim() && !lines[i].startsWith(' '.repeat(currentFunc.indent + 1)) && !lines[i].startsWith('\t')) {
637
+ functions.push({
638
+ name: currentFunc.name,
639
+ file: file.relativePath,
640
+ startLine: currentFunc.startLine,
641
+ lines: i - currentFunc.startLine + 1,
642
+ });
643
+ currentFunc = null;
644
+ }
645
+ }
646
+ if (currentFunc) {
647
+ functions.push({
648
+ name: currentFunc.name,
649
+ file: file.relativePath,
650
+ startLine: currentFunc.startLine,
651
+ lines: lines.length - currentFunc.startLine + 1,
652
+ });
653
+ }
654
+
655
+ return functions;
656
+ }
657
+
658
+ function extractFunctions(file: SourceFile): FunctionInfo[] {
659
+ const ext = extname(file.path).toLowerCase();
660
+ if (['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].includes(ext)) return extractJsFunctions(file);
661
+ if (['.py', '.pyi'].includes(ext)) return extractPyFunctions(file);
662
+ return [];
663
+ }
664
+
665
+ function analyzeFunctionLength(files: SourceFile[]): { score: number; findings: QualityFinding[]; issueCount: number } {
666
+ const allFunctions: FunctionInfo[] = [];
667
+ for (const file of files) {
668
+ allFunctions.push(...extractFunctions(file));
669
+ }
670
+
671
+ if (allFunctions.length === 0) return { score: 100, findings: [], issueCount: 0 };
672
+
673
+ const findings: QualityFinding[] = [];
674
+ let totalScore = 0;
675
+
676
+ for (const func of allFunctions) {
677
+ const ratio = Math.max(1, func.lines / FUNCTION_LENGTH_THRESHOLD);
678
+ const funcScore = 100 / ratio ** 1.5;
679
+ totalScore += funcScore;
680
+
681
+ if (func.lines > FUNCTION_LENGTH_THRESHOLD) {
682
+ findings.push({
683
+ severity: func.lines > FUNCTION_LENGTH_THRESHOLD * 3 ? 'high' : func.lines > FUNCTION_LENGTH_THRESHOLD * 2 ? 'medium' : 'low',
684
+ category: 'function-length',
685
+ file: func.file,
686
+ line: func.startLine,
687
+ title: `${func.name}() has ${func.lines} lines (threshold: ${FUNCTION_LENGTH_THRESHOLD})`,
688
+ description: `Function "${func.name}" exceeds the recommended length by ${func.lines - FUNCTION_LENGTH_THRESHOLD} lines.`,
689
+ });
690
+ }
691
+ }
692
+
693
+ const score = Math.round(totalScore / allFunctions.length);
694
+ return { score: Math.min(100, score), findings: findings.slice(0, 50), issueCount: findings.length };
695
+ }
696
+
697
+ // ============================================================================
698
+ // Cyclomatic Complexity (Heuristic)
699
+ // ============================================================================
700
+
701
+ function countCyclomaticComplexity(funcContent: string): number {
702
+ let cc = 1; // base
703
+ cc += (funcContent.match(/\bif\b/g) || []).length;
704
+ cc += (funcContent.match(/\belse\s+if\b/g) || []).length;
705
+ cc += (funcContent.match(/\bfor\b/g) || []).length;
706
+ cc += (funcContent.match(/\bwhile\b/g) || []).length;
707
+ cc += (funcContent.match(/\bcase\b/g) || []).length;
708
+ cc += (funcContent.match(/\bcatch\b/g) || []).length;
709
+ cc += (funcContent.match(/&&|\|\|/g) || []).length;
710
+ cc += (funcContent.match(/\?\s*[^:]/g) || []).length; // ternary
711
+ return cc;
712
+ }
713
+
714
+ function complexityToScore(cc: number): number {
715
+ if (cc <= 5) return 100;
716
+ if (cc <= 10) return 100 - (cc - 5) * 5;
717
+ if (cc <= 15) return 75 - (cc - 10) * 5;
718
+ if (cc <= 20) return 50 - (cc - 15) * 5;
719
+ return Math.max(0, 25 - (cc - 20) * 2.5);
720
+ }
721
+
722
+ function getFuncContent(file: SourceFile, func: FunctionInfo): string {
723
+ return file.content.split('\n').slice(func.startLine - 1, func.startLine - 1 + func.lines).join('\n');
724
+ }
725
+
726
+ function complexitySeverity(cc: number): QualityFinding['severity'] {
727
+ if (cc > 20) return 'high';
728
+ if (cc > 15) return 'medium';
729
+ return 'low';
730
+ }
731
+
732
+ interface ComplexityAccumulator {
733
+ weightedScore: number;
734
+ weight: number;
735
+ findings: QualityFinding[];
736
+ }
737
+
738
+ function analyzeFunc(file: SourceFile, func: FunctionInfo, acc: ComplexityAccumulator): void {
739
+ const funcContent = getFuncContent(file, func);
740
+ const cc = countCyclomaticComplexity(funcContent);
741
+ const funcScore = complexityToScore(cc);
742
+
743
+ acc.weightedScore += funcScore * func.lines;
744
+ acc.weight += func.lines;
745
+
746
+ if (cc > 10) {
747
+ acc.findings.push({
748
+ severity: complexitySeverity(cc),
749
+ category: 'complexity',
750
+ file: func.file,
751
+ line: func.startLine,
752
+ title: `${func.name}() has cyclomatic complexity ${cc}`,
753
+ description: `Complexity of ${cc} exceeds the recommended threshold of 10. Consider refactoring into smaller functions.`,
754
+ });
755
+ }
756
+ }
757
+
758
+ function analyzeComplexity(files: SourceFile[]): { score: number; findings: QualityFinding[]; issueCount: number } {
759
+ const acc: ComplexityAccumulator = { weightedScore: 0, weight: 0, findings: [] };
760
+
761
+ for (const file of files) {
762
+ const functions = extractFunctions(file);
763
+ for (const func of functions) {
764
+ analyzeFunc(file, func, acc);
765
+ }
766
+ }
767
+
768
+ if (acc.weight === 0) return { score: 100, findings: [], issueCount: 0 };
769
+
770
+ const score = Math.round(acc.weightedScore / acc.weight);
771
+ return { score: Math.min(100, score), findings: acc.findings.slice(0, 50), issueCount: acc.findings.length };
772
+ }
773
+
774
+ // ============================================================================
775
+ // Scoring
776
+ // ============================================================================
777
+
778
+ function computeGrade(score: number): string {
779
+ if (score >= 90) return 'A';
780
+ if (score >= 80) return 'B';
781
+ if (score >= 70) return 'C';
782
+ if (score >= 60) return 'D';
783
+ return 'F';
784
+ }
785
+
786
+ interface CategoryWeights {
787
+ linting: number;
788
+ formatting: number;
789
+ complexity: number;
790
+ fileLength: number;
791
+ functionLength: number;
792
+ }
793
+
794
+ const DEFAULT_WEIGHTS: CategoryWeights = {
795
+ linting: 0.30,
796
+ formatting: 0.15,
797
+ complexity: 0.25,
798
+ fileLength: 0.15,
799
+ functionLength: 0.15,
800
+ };
801
+
802
+ function computeOverallScore(categories: CategoryScore[]): number {
803
+ const available = categories.filter((c) => c.available);
804
+ if (available.length === 0) return 0;
805
+
806
+ const totalWeight = available.reduce((sum, c) => sum + c.weight, 0);
807
+ let weighted = 0;
808
+ for (const cat of available) {
809
+ const effectiveWeight = cat.weight / totalWeight;
810
+ cat.effectiveWeight = effectiveWeight;
811
+ weighted += cat.score * effectiveWeight;
812
+ }
813
+
814
+ return Math.round(Math.max(0, Math.min(100, weighted)));
815
+ }
816
+
817
+ // ============================================================================
818
+ // Main Scan
819
+ // ============================================================================
820
+
821
+ export type ProgressCallback = (progress: ScanProgress) => void;
822
+
823
+ export async function runQualityScan(
824
+ dirPath: string,
825
+ onProgress?: ProgressCallback,
826
+ ): Promise<QualityResults> {
827
+ const ecosystems = detectEcosystem(dirPath);
828
+
829
+ const progress = (step: string, current: number) => {
830
+ onProgress?.({ step, current, total: TOTAL_STEPS });
831
+ };
832
+
833
+ // Step 1: Collect source files
834
+ progress('Collecting source files', 1);
835
+ const files = collectSourceFiles(dirPath, dirPath);
836
+
837
+ // Step 2: Run linting
838
+ progress('Running linters', 2);
839
+ const lintResult = await analyzeLinting(dirPath, ecosystems, files);
840
+
841
+ // Step 3: Check formatting
842
+ progress('Checking formatting', 3);
843
+ const fmtResult = await analyzeFormatting(dirPath, ecosystems, files);
844
+
845
+ // Step 4: Analyze complexity
846
+ progress('Analyzing complexity', 4);
847
+ const complexityResult = analyzeComplexity(files);
848
+
849
+ // Step 5: Check file lengths
850
+ progress('Checking file lengths', 5);
851
+ const fileLengthResult = analyzeFileLength(files);
852
+
853
+ // Step 6: Check function lengths
854
+ progress('Checking function lengths', 6);
855
+ const funcLengthResult = analyzeFunctionLength(files);
856
+
857
+ // Step 7: Compute scores
858
+ progress('Computing scores', 7);
859
+
860
+ const categories: CategoryScore[] = [
861
+ {
862
+ name: 'Linting',
863
+ score: lintResult.score,
864
+ weight: DEFAULT_WEIGHTS.linting,
865
+ effectiveWeight: DEFAULT_WEIGHTS.linting,
866
+ available: lintResult.available,
867
+ issueCount: lintResult.issueCount,
868
+ },
869
+ {
870
+ name: 'Formatting',
871
+ score: fmtResult.score,
872
+ weight: DEFAULT_WEIGHTS.formatting,
873
+ effectiveWeight: DEFAULT_WEIGHTS.formatting,
874
+ available: fmtResult.available,
875
+ issueCount: fmtResult.issueCount,
876
+ },
877
+ {
878
+ name: 'Complexity',
879
+ score: complexityResult.score,
880
+ weight: DEFAULT_WEIGHTS.complexity,
881
+ effectiveWeight: DEFAULT_WEIGHTS.complexity,
882
+ available: true,
883
+ issueCount: complexityResult.issueCount,
884
+ },
885
+ {
886
+ name: 'File Length',
887
+ score: fileLengthResult.score,
888
+ weight: DEFAULT_WEIGHTS.fileLength,
889
+ effectiveWeight: DEFAULT_WEIGHTS.fileLength,
890
+ available: true,
891
+ issueCount: fileLengthResult.issueCount,
892
+ },
893
+ {
894
+ name: 'Function Length',
895
+ score: funcLengthResult.score,
896
+ weight: DEFAULT_WEIGHTS.functionLength,
897
+ effectiveWeight: DEFAULT_WEIGHTS.functionLength,
898
+ available: true,
899
+ issueCount: funcLengthResult.issueCount,
900
+ },
901
+ ];
902
+
903
+ const overall = computeOverallScore(categories);
904
+ const allFindings = [
905
+ ...lintResult.findings,
906
+ ...complexityResult.findings,
907
+ ...fileLengthResult.findings,
908
+ ...funcLengthResult.findings,
909
+ ];
910
+
911
+ return {
912
+ overall,
913
+ grade: computeGrade(overall),
914
+ categories,
915
+ findings: allFindings.slice(0, 200),
916
+ codeReview: [],
917
+ analyzedFiles: files.length,
918
+ totalLines: files.reduce((sum, f) => sum + f.lines, 0),
919
+ timestamp: new Date().toISOString(),
920
+ ecosystem: ecosystems,
921
+ };
922
+ }