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