mstro-app 0.4.44 → 0.4.46
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.
- package/README.md +15 -7
- package/dist/server/cli/headless/resilient-runner.d.ts +2 -1
- package/dist/server/cli/headless/resilient-runner.d.ts.map +1 -1
- package/dist/server/cli/headless/resilient-runner.js +2 -0
- package/dist/server/cli/headless/resilient-runner.js.map +1 -1
- package/dist/server/services/plan/composer.d.ts +2 -1
- package/dist/server/services/plan/composer.d.ts.map +1 -1
- package/dist/server/services/plan/composer.js +21 -2
- package/dist/server/services/plan/composer.js.map +1 -1
- package/dist/server/services/websocket/handler.js +1 -1
- package/dist/server/services/websocket/handler.js.map +1 -1
- package/dist/server/services/websocket/plan-board-handlers.d.ts.map +1 -1
- package/dist/server/services/websocket/plan-board-handlers.js +8 -2
- package/dist/server/services/websocket/plan-board-handlers.js.map +1 -1
- package/dist/server/services/websocket/quality-complexity.d.ts +1 -1
- package/dist/server/services/websocket/quality-complexity.d.ts.map +1 -1
- package/dist/server/services/websocket/quality-complexity.js +88 -59
- package/dist/server/services/websocket/quality-complexity.js.map +1 -1
- package/dist/server/services/websocket/quality-handlers.d.ts.map +1 -1
- package/dist/server/services/websocket/quality-handlers.js +4 -21
- package/dist/server/services/websocket/quality-handlers.js.map +1 -1
- package/dist/server/services/websocket/quality-linting.d.ts.map +1 -1
- package/dist/server/services/websocket/quality-linting.js +71 -50
- package/dist/server/services/websocket/quality-linting.js.map +1 -1
- package/dist/server/services/websocket/quality-persistence.d.ts +1 -1
- package/dist/server/services/websocket/quality-persistence.d.ts.map +1 -1
- package/dist/server/services/websocket/quality-service.d.ts +0 -4
- package/dist/server/services/websocket/quality-service.d.ts.map +1 -1
- package/dist/server/services/websocket/quality-service.js +40 -34
- package/dist/server/services/websocket/quality-service.js.map +1 -1
- package/dist/server/services/websocket/quality-tools.d.ts +13 -0
- package/dist/server/services/websocket/quality-tools.d.ts.map +1 -1
- package/dist/server/services/websocket/quality-tools.js +32 -0
- package/dist/server/services/websocket/quality-tools.js.map +1 -1
- package/dist/server/services/websocket/session-handlers.d.ts +3 -1
- package/dist/server/services/websocket/session-handlers.d.ts.map +1 -1
- package/dist/server/services/websocket/session-handlers.js +18 -2
- package/dist/server/services/websocket/session-handlers.js.map +1 -1
- package/dist/server/services/websocket/types.d.ts +2 -2
- package/dist/server/services/websocket/types.d.ts.map +1 -1
- package/dist/server/services/websocket/types.js +2 -2
- package/dist/server/services/websocket/types.js.map +1 -1
- package/package.json +21 -5
- package/server/cli/headless/resilient-runner.ts +5 -1
- package/server/services/plan/composer.ts +42 -1
- package/server/services/websocket/handler.ts +1 -1
- package/server/services/websocket/plan-board-handlers.ts +11 -2
- package/server/services/websocket/quality-complexity.ts +87 -51
- package/server/services/websocket/quality-handlers.ts +4 -18
- package/server/services/websocket/quality-linting.ts +74 -47
- package/server/services/websocket/quality-persistence.ts +1 -1
- package/server/services/websocket/quality-service.ts +44 -39
- package/server/services/websocket/quality-tools.ts +33 -0
- package/server/services/websocket/session-handlers.ts +19 -2
- package/server/services/websocket/types.ts +2 -2
- package/dist/server/services/websocket/quality-fix-agent.d.ts +0 -16
- package/dist/server/services/websocket/quality-fix-agent.d.ts.map +0 -1
- package/dist/server/services/websocket/quality-fix-agent.js +0 -181
- package/dist/server/services/websocket/quality-fix-agent.js.map +0 -1
- package/server/services/websocket/quality-fix-agent.ts +0 -216
|
@@ -4,9 +4,12 @@
|
|
|
4
4
|
import { extname } from 'node:path';
|
|
5
5
|
import { analyzeComplexity, analyzeFunctionLength } from './quality-complexity.js';
|
|
6
6
|
import { analyzeLinting } from './quality-linting.js';
|
|
7
|
-
import { collectSourceFiles, detectEcosystem, runCommand, type SourceFile } from './quality-tools.js';
|
|
7
|
+
import { chunkFileList, collectSourceFiles, detectEcosystem, filesByExt, runCommand, type SourceFile } from './quality-tools.js';
|
|
8
8
|
import { type CategoryPenalty, type CategoryScore, type Ecosystem, FILE_LENGTH_THRESHOLD, hasInstalledToolInCategory, type QualityFinding, type QualityResults, type ScanProgress, type ScoreBreakdown, TOTAL_STEPS } from './quality-types.js';
|
|
9
9
|
|
|
10
|
+
const NODE_FMT_EXTS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
|
|
11
|
+
const PY_FMT_EXTS = ['.py', '.pyi'];
|
|
12
|
+
|
|
10
13
|
export { detectEcosystem, detectTools, installTools } from './quality-tools.js';
|
|
11
14
|
// Re-export public API for backward compatibility
|
|
12
15
|
export type { CategoryPenalty, CategoryScore, QualityFinding, QualityResults, QualityTool, ScanProgress, ScoreBreakdown } from './quality-types.js';
|
|
@@ -27,34 +30,51 @@ function newFmtAccumulator(): FmtAccumulator {
|
|
|
27
30
|
}
|
|
28
31
|
|
|
29
32
|
async function fmtNode(dirPath: string, files: SourceFile[], acc: FmtAccumulator): Promise<void> {
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
for (const
|
|
37
|
-
|
|
38
|
-
|
|
33
|
+
const targets = filesByExt(files, NODE_FMT_EXTS);
|
|
34
|
+
if (targets.length === 0) return;
|
|
35
|
+
|
|
36
|
+
acc.totalFiles += targets.length;
|
|
37
|
+
const unformattedSet = new Set<string>();
|
|
38
|
+
|
|
39
|
+
for (const chunk of chunkFileList(targets)) {
|
|
40
|
+
const result = await runCommand('npx', ['prettier', '--check', ...chunk], dirPath);
|
|
41
|
+
acc.ran = true;
|
|
42
|
+
for (const line of result.stdout.split('\n')) {
|
|
43
|
+
if (!line.trim() || line.startsWith('Checking')) continue;
|
|
44
|
+
const rel = line.startsWith('/') ? line.replace(`${dirPath}/`, '') : line;
|
|
45
|
+
unformattedSet.add(rel.trim());
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
acc.passingFiles += Math.max(0, targets.length - unformattedSet.size);
|
|
50
|
+
for (const rel of unformattedSet) {
|
|
39
51
|
acc.findings.push({ severity: 'low', category: 'format', file: rel, line: null, title: 'File not formatted', description: 'Does not match Prettier formatting rules.' });
|
|
40
52
|
}
|
|
41
53
|
}
|
|
42
54
|
|
|
43
55
|
async function fmtPython(dirPath: string, files: SourceFile[], acc: FmtAccumulator): Promise<void> {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
acc.totalFiles +=
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
56
|
+
const targets = filesByExt(files, PY_FMT_EXTS);
|
|
57
|
+
if (targets.length === 0) return;
|
|
58
|
+
|
|
59
|
+
acc.totalFiles += targets.length;
|
|
60
|
+
let reformatCount = 0;
|
|
61
|
+
const findings: typeof acc.findings = [];
|
|
62
|
+
|
|
63
|
+
for (const chunk of chunkFileList(targets)) {
|
|
64
|
+
const result = await runCommand('black', ['--check', '--quiet', ...chunk], dirPath);
|
|
65
|
+
acc.ran = true;
|
|
66
|
+
if (result.exitCode === 0) continue;
|
|
67
|
+
|
|
68
|
+
const reformatLines = result.stderr.split('\n').filter((l) => l.includes('would reformat'));
|
|
69
|
+
reformatCount += reformatLines.length;
|
|
70
|
+
for (const line of reformatLines) {
|
|
71
|
+
const match = line.match(/would reformat (.+)/);
|
|
72
|
+
if (match) findings.push({ severity: 'low', category: 'format', file: match[1].trim(), line: null, title: 'File not formatted', description: 'Does not match Black formatting rules.' });
|
|
73
|
+
}
|
|
57
74
|
}
|
|
75
|
+
|
|
76
|
+
acc.passingFiles += Math.max(0, targets.length - reformatCount);
|
|
77
|
+
acc.findings.push(...findings);
|
|
58
78
|
}
|
|
59
79
|
|
|
60
80
|
async function fmtRust(dirPath: string, files: SourceFile[], acc: FmtAccumulator): Promise<void> {
|
|
@@ -223,21 +243,6 @@ export function computeFormulaScore(
|
|
|
223
243
|
};
|
|
224
244
|
}
|
|
225
245
|
|
|
226
|
-
/** @deprecated — use computeFormulaScore instead */
|
|
227
|
-
export function computeAiReviewScore(
|
|
228
|
-
findings: Array<{ severity: string }>,
|
|
229
|
-
totalLines: number,
|
|
230
|
-
): number {
|
|
231
|
-
if (findings.length === 0) return 100;
|
|
232
|
-
const effectiveKloc = Math.max(totalLines / 1000, 1.0);
|
|
233
|
-
const totalPenalty = findings.reduce(
|
|
234
|
-
(sum, f) => sum + (SEVERITY_WEIGHT[f.severity] ?? 2.0),
|
|
235
|
-
0,
|
|
236
|
-
);
|
|
237
|
-
const penaltyDensity = totalPenalty / effectiveKloc;
|
|
238
|
-
return Math.round(100 * Math.exp(-0.10 * penaltyDensity));
|
|
239
|
-
}
|
|
240
|
-
|
|
241
246
|
// ============================================================================
|
|
242
247
|
// Main Scan
|
|
243
248
|
// ============================================================================
|
|
@@ -278,7 +283,7 @@ export async function runQualityScan(
|
|
|
278
283
|
|
|
279
284
|
// Step 4: Analyze complexity (using real tools: Biome, ESLint, radon)
|
|
280
285
|
progress('Analyzing complexity', 4);
|
|
281
|
-
const complexityResult = await analyzeComplexity(dirPath, ecosystems, installedToolNames);
|
|
286
|
+
const complexityResult = await analyzeComplexity(dirPath, ecosystems, files, installedToolNames);
|
|
282
287
|
|
|
283
288
|
// Step 5: Check file lengths
|
|
284
289
|
progress('Checking file lengths', 5);
|
|
@@ -239,6 +239,39 @@ export async function collectSourceFiles(dirPath: string, rootPath: string): Pro
|
|
|
239
239
|
return files;
|
|
240
240
|
}
|
|
241
241
|
|
|
242
|
+
// ============================================================================
|
|
243
|
+
// File List Helpers
|
|
244
|
+
// ============================================================================
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Filter a SourceFile list by extension and return relative paths.
|
|
248
|
+
* Used to pass an explicit, git-ignored-filtered file list to external tools
|
|
249
|
+
* (prettier, biome, eslint, ...) so they don't walk ignored directories like
|
|
250
|
+
* web/dist or nested build outputs in monorepos.
|
|
251
|
+
*/
|
|
252
|
+
export function filesByExt(files: SourceFile[], exts: string[]): string[] {
|
|
253
|
+
const set = new Set(exts.map((e) => e.toLowerCase()));
|
|
254
|
+
const out: string[] = [];
|
|
255
|
+
for (const f of files) {
|
|
256
|
+
if (set.has(extname(f.path).toLowerCase())) out.push(f.relativePath);
|
|
257
|
+
}
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Split a file list into chunks so a single command invocation doesn't
|
|
263
|
+
* blow past ARG_MAX. macOS ARG_MAX is ~256KB; 400 paths at ~200 chars each
|
|
264
|
+
* leaves plenty of headroom.
|
|
265
|
+
*/
|
|
266
|
+
export function chunkFileList(paths: string[], size = 400): string[][] {
|
|
267
|
+
if (paths.length === 0) return [];
|
|
268
|
+
const chunks: string[][] = [];
|
|
269
|
+
for (let i = 0; i < paths.length; i += size) {
|
|
270
|
+
chunks.push(paths.slice(i, i + size));
|
|
271
|
+
}
|
|
272
|
+
return chunks;
|
|
273
|
+
}
|
|
274
|
+
|
|
242
275
|
// ============================================================================
|
|
243
276
|
// Command Runner
|
|
244
277
|
// ============================================================================
|
|
@@ -91,7 +91,13 @@ function getSession(ctx: HandlerContext, ws: WSContext, tabId: string): Improvis
|
|
|
91
91
|
|
|
92
92
|
export function buildOutputHistory(session: ImprovisationSessionManager): Array<Record<string, unknown>> {
|
|
93
93
|
const history = session.getHistory();
|
|
94
|
-
|
|
94
|
+
// Skip in-progress movements (durationMs == 0). Their state is replayed on
|
|
95
|
+
// the web via executionEvents; including them here would emit a bogus
|
|
96
|
+
// "Completed" marker and duplicate the user prompt that executionEvents
|
|
97
|
+
// is about to replay.
|
|
98
|
+
return history.movements
|
|
99
|
+
.filter((m) => (m.durationMs ?? 0) > 0)
|
|
100
|
+
.flatMap(convertMovementToLines);
|
|
95
101
|
}
|
|
96
102
|
|
|
97
103
|
export function setupSessionListeners(ctx: HandlerContext, session: ImprovisationSessionManager, ws: WSContext, tabId: string): void {
|
|
@@ -157,7 +163,7 @@ export function setupSessionListeners(ctx: HandlerContext, session: Improvisatio
|
|
|
157
163
|
}
|
|
158
164
|
|
|
159
165
|
/** Merge pre-uploaded files (from chunked upload) with any inline attachments */
|
|
160
|
-
function mergePreUploadedAttachments(ctx: HandlerContext, tabId: string, inlineAttachments?: FileAttachment[]): FileAttachment[] | undefined {
|
|
166
|
+
export function mergePreUploadedAttachments(ctx: HandlerContext, tabId: string, inlineAttachments?: FileAttachment[]): FileAttachment[] | undefined {
|
|
161
167
|
if (!ctx.fileUploadHandler) return inlineAttachments;
|
|
162
168
|
const preUploaded = ctx.fileUploadHandler.getAndClearCompletedUploads(tabId);
|
|
163
169
|
if (preUploaded.length === 0) return inlineAttachments;
|
|
@@ -200,6 +206,17 @@ export function handleSessionMessage(ctx: HandlerContext, ws: WSContext, msg: We
|
|
|
200
206
|
const effectiveDir = worktreeDir || session.getSessionInfo().workingDir;
|
|
201
207
|
const resolved = resolveSkillPrompt(rawPrompt, effectiveDir);
|
|
202
208
|
|
|
209
|
+
// Authoritative prompt-input clear for all connected devices. The
|
|
210
|
+
// submitter already cleared locally; this guarantees other devices
|
|
211
|
+
// clear even if the submitter's debounced syncPromptText never fires
|
|
212
|
+
// (e.g. mobile tab suspended after Send). Clients suppress this via
|
|
213
|
+
// locallyEditingTabs if the user is actively typing a new prompt.
|
|
214
|
+
ctx.broadcastToAll({
|
|
215
|
+
type: 'promptTextSync',
|
|
216
|
+
tabId,
|
|
217
|
+
data: { tabId, text: '' },
|
|
218
|
+
});
|
|
219
|
+
|
|
203
220
|
session.executePrompt(
|
|
204
221
|
resolved ? resolved.prompt : rawPrompt,
|
|
205
222
|
attachments,
|
|
@@ -42,7 +42,7 @@ const SessionSyncMessages = ['getActiveTabs', 'createTab', 'reorderTabs', 'syncT
|
|
|
42
42
|
|
|
43
43
|
const SettingsMessages = ['getSettings', 'updateSettings'] as const;
|
|
44
44
|
|
|
45
|
-
const QualityMessages = ['qualityDetectTools', 'qualityScan', 'qualityInstallTools', 'qualityCodeReview', '
|
|
45
|
+
const QualityMessages = ['qualityDetectTools', 'qualityScan', 'qualityInstallTools', 'qualityCodeReview', 'qualityLoadState', 'qualitySaveDirectories'] as const;
|
|
46
46
|
|
|
47
47
|
const FileUploadMessages = ['fileUploadStart', 'fileUploadChunk', 'fileUploadComplete', 'fileUploadCancel'] as const;
|
|
48
48
|
|
|
@@ -105,7 +105,7 @@ const SessionSyncResponseMessages = ['activeTabs', 'tabCreated', 'tabRemoved', '
|
|
|
105
105
|
|
|
106
106
|
const SettingsResponseMessages = ['settings', 'settingsUpdated'] as const;
|
|
107
107
|
|
|
108
|
-
const QualityResponseMessages = ['qualityToolsDetected', 'qualityScanProgress', 'qualityScanResults', 'qualityInstallProgress', 'qualityInstallComplete', 'qualityCodeReview', 'qualityCodeReviewProgress', 'qualityPostSession', '
|
|
108
|
+
const QualityResponseMessages = ['qualityToolsDetected', 'qualityScanProgress', 'qualityScanResults', 'qualityInstallProgress', 'qualityInstallComplete', 'qualityCodeReview', 'qualityCodeReviewProgress', 'qualityPostSession', 'qualityError', 'qualityStateLoaded'] as const;
|
|
109
109
|
|
|
110
110
|
const FileUploadResponseMessages = ['fileUploadAck', 'fileUploadReady', 'fileUploadError'] as const;
|
|
111
111
|
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { ToolUseEvent } from '../../cli/headless/types.js';
|
|
2
|
-
import type { HandlerContext } from './handler-context.js';
|
|
3
|
-
import type { QualityPersistence } from './quality-persistence.js';
|
|
4
|
-
import type { WSContext } from './types.js';
|
|
5
|
-
export interface FindingForFix {
|
|
6
|
-
severity: string;
|
|
7
|
-
category: string;
|
|
8
|
-
file: string;
|
|
9
|
-
line: number | null;
|
|
10
|
-
title: string;
|
|
11
|
-
description: string;
|
|
12
|
-
suggestion?: string;
|
|
13
|
-
}
|
|
14
|
-
export declare function createToolProgressCallback(ctx: HandlerContext, ws: WSContext, reportPath: string): (event: ToolUseEvent) => void;
|
|
15
|
-
export declare function handleFixIssues(ctx: HandlerContext, ws: WSContext, reportPath: string, dirPath: string, workingDir: string, section: string | undefined, findings: FindingForFix[], getPersistence: (dir: string) => QualityPersistence): Promise<void>;
|
|
16
|
-
//# sourceMappingURL=quality-fix-agent.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"quality-fix-agent.d.ts","sourceRoot":"","sources":["../../../../server/services/websocket/quality-fix-agent.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAI5C,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAYD,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,cAAc,EAAE,EAAE,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,IAEvF,OAAO,YAAY,UAmB5B;AAiDD,wBAAsB,eAAe,CACnC,GAAG,EAAE,cAAc,EACnB,EAAE,EAAE,SAAS,EACb,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,GAAG,SAAS,EAC3B,QAAQ,EAAE,aAAa,EAAE,EACzB,cAAc,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,kBAAkB,GAClD,OAAO,CAAC,IAAI,CAAC,CAiGf"}
|
|
@@ -1,181 +0,0 @@
|
|
|
1
|
-
// Copyright (c) 2025-present Mstro, Inc. All rights reserved.
|
|
2
|
-
// Licensed under the MIT License. See LICENSE file for details.
|
|
3
|
-
/**
|
|
4
|
-
* Quality Fix Agent — AI-powered issue fixing using Claude Code headless runner.
|
|
5
|
-
*
|
|
6
|
-
* Builds the fix prompt, runs the agent, re-scans, and persists updated results.
|
|
7
|
-
*/
|
|
8
|
-
import { ResilientRunner } from '../../cli/headless/resilient-runner.js';
|
|
9
|
-
import { loadSkillPrompt } from '../plan/agent-loader.js';
|
|
10
|
-
import { detectTools, runQualityScan } from './quality-service.js';
|
|
11
|
-
// ── Progress callback ─────────────────────────────────────────
|
|
12
|
-
const TOOL_MESSAGES = {
|
|
13
|
-
Read: 'Reading files to understand issues...',
|
|
14
|
-
Edit: 'Applying fixes...',
|
|
15
|
-
Write: 'Writing fixes...',
|
|
16
|
-
Grep: 'Searching for related code...',
|
|
17
|
-
Bash: 'Running verification...',
|
|
18
|
-
};
|
|
19
|
-
export function createToolProgressCallback(ctx, ws, reportPath) {
|
|
20
|
-
const seenTools = new Set();
|
|
21
|
-
return (event) => {
|
|
22
|
-
try {
|
|
23
|
-
if (event.type === 'tool_start' && event.toolName && !seenTools.has(event.toolName)) {
|
|
24
|
-
seenTools.add(event.toolName);
|
|
25
|
-
const message = TOOL_MESSAGES[event.toolName];
|
|
26
|
-
if (message) {
|
|
27
|
-
ctx.send(ws, { type: 'qualityFixProgress', data: { path: reportPath, message } });
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
if (event.type === 'tool_complete' && event.toolName === 'Edit' && event.completeInput?.file_path) {
|
|
31
|
-
ctx.send(ws, {
|
|
32
|
-
type: 'qualityFixProgress',
|
|
33
|
-
data: { path: reportPath, message: `Fixed ${String(event.completeInput.file_path).split('/').slice(-2).join('/')}` },
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
catch {
|
|
38
|
-
// WebSocket closed — progress lost but fix operation continues
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
}
|
|
42
|
-
function startFixHeartbeat(ctx, ws, reportPath, intervalMs = 30_000) {
|
|
43
|
-
let elapsed = 0;
|
|
44
|
-
const timer = setInterval(() => {
|
|
45
|
-
elapsed += intervalMs;
|
|
46
|
-
const mins = Math.floor(elapsed / 60_000);
|
|
47
|
-
const secs = Math.floor((elapsed % 60_000) / 1000);
|
|
48
|
-
const timeStr = mins > 0 ? `${mins}m ${secs}s` : `${secs}s`;
|
|
49
|
-
try {
|
|
50
|
-
ctx.send(ws, { type: 'qualityFixProgress', data: { path: reportPath, message: `Fixing issues (${timeStr} elapsed, still working...)` } });
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
// WebSocket closed — heartbeat lost but fix continues
|
|
54
|
-
}
|
|
55
|
-
}, intervalMs);
|
|
56
|
-
return () => clearInterval(timer);
|
|
57
|
-
}
|
|
58
|
-
// ── Prompt ────────────────────────────────────────────────────
|
|
59
|
-
function buildFixPrompt(findings, section) {
|
|
60
|
-
const filtered = section ? findings.filter((f) => f.category === section) : findings;
|
|
61
|
-
const sorted = filtered.sort((a, b) => {
|
|
62
|
-
const order = { critical: 0, high: 1, medium: 2, low: 3 };
|
|
63
|
-
return (order[a.severity] ?? 4) - (order[b.severity] ?? 4);
|
|
64
|
-
});
|
|
65
|
-
const issueList = sorted.slice(0, 30).map((f, i) => {
|
|
66
|
-
const loc = f.line ? `${f.file}:${f.line}` : f.file;
|
|
67
|
-
const parts = [`${i + 1}. [${f.severity.toUpperCase()}] ${loc} — ${f.title}`];
|
|
68
|
-
if (f.description)
|
|
69
|
-
parts.push(` ${f.description}`);
|
|
70
|
-
if (f.suggestion)
|
|
71
|
-
parts.push(` Suggestion: ${f.suggestion}`);
|
|
72
|
-
return parts.join('\n');
|
|
73
|
-
}).join('\n\n');
|
|
74
|
-
const fromSkill = loadSkillPrompt('fix-quality', {
|
|
75
|
-
issueList,
|
|
76
|
-
issueCount: String(sorted.length),
|
|
77
|
-
showCount: String(Math.min(30, sorted.length)),
|
|
78
|
-
});
|
|
79
|
-
if (fromSkill)
|
|
80
|
-
return fromSkill;
|
|
81
|
-
return `You are a code quality fix agent. Fix the following quality issues in the codebase.\n\n## Issues to Fix (${sorted.length} total, showing top ${Math.min(30, sorted.length)})\n\n${issueList}\n\nFix each issue by editing the relevant file. Work from most to least severe. Do NOT introduce new issues.`;
|
|
82
|
-
}
|
|
83
|
-
// ── Handler ───────────────────────────────────────────────────
|
|
84
|
-
const activeFixes = new Set();
|
|
85
|
-
export async function handleFixIssues(ctx, ws, reportPath, dirPath, workingDir, section, findings, getPersistence) {
|
|
86
|
-
if (activeFixes.has(dirPath)) {
|
|
87
|
-
ctx.send(ws, {
|
|
88
|
-
type: 'qualityError',
|
|
89
|
-
data: { path: reportPath, error: 'A fix operation is already running for this directory.' },
|
|
90
|
-
});
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
if (findings.length === 0) {
|
|
94
|
-
ctx.send(ws, {
|
|
95
|
-
type: 'qualityError',
|
|
96
|
-
data: { path: reportPath, error: 'No findings to fix.' },
|
|
97
|
-
});
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
activeFixes.add(dirPath);
|
|
101
|
-
const stopHeartbeat = startFixHeartbeat(ctx, ws, reportPath);
|
|
102
|
-
try {
|
|
103
|
-
try {
|
|
104
|
-
ctx.send(ws, {
|
|
105
|
-
type: 'qualityFixProgress',
|
|
106
|
-
data: { path: reportPath, message: 'Starting Claude Code to fix issues...' },
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
catch { /* WS closed */ }
|
|
110
|
-
const prompt = buildFixPrompt(findings, section);
|
|
111
|
-
const runner = new ResilientRunner({
|
|
112
|
-
workingDir: dirPath,
|
|
113
|
-
prompt,
|
|
114
|
-
policy: 'STANDARD',
|
|
115
|
-
stallWarningMs: 300_000,
|
|
116
|
-
stallKillMs: 1_200_000,
|
|
117
|
-
stallHardCapMs: 1_800_000,
|
|
118
|
-
toolUseCallback: createToolProgressCallback(ctx, ws, reportPath),
|
|
119
|
-
logLabel: 'code-review-fix',
|
|
120
|
-
});
|
|
121
|
-
await runner.run();
|
|
122
|
-
try {
|
|
123
|
-
ctx.send(ws, {
|
|
124
|
-
type: 'qualityFixProgress',
|
|
125
|
-
data: { path: reportPath, message: 'Fixes applied. Re-running quality checks...' },
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
catch { /* WS closed */ }
|
|
129
|
-
// Re-run quality scan after fixing
|
|
130
|
-
const { tools: detectedTools } = await detectTools(dirPath);
|
|
131
|
-
const installedToolNames = detectedTools.filter((t) => t.installed).map((t) => t.name);
|
|
132
|
-
const results = await runQualityScan(dirPath, (progress) => {
|
|
133
|
-
try {
|
|
134
|
-
ctx.send(ws, {
|
|
135
|
-
type: 'qualityScanProgress',
|
|
136
|
-
data: { path: reportPath, progress },
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
catch { /* WS closed */ }
|
|
140
|
-
}, installedToolNames);
|
|
141
|
-
// Persist before sending — results survive WebSocket drops
|
|
142
|
-
try {
|
|
143
|
-
const persistence = getPersistence(workingDir);
|
|
144
|
-
persistence.saveReport(reportPath, results);
|
|
145
|
-
persistence.appendHistory(results, reportPath);
|
|
146
|
-
}
|
|
147
|
-
catch {
|
|
148
|
-
// Persistence failure should not break the fix flow
|
|
149
|
-
}
|
|
150
|
-
const resultData = { path: reportPath, results };
|
|
151
|
-
try {
|
|
152
|
-
ctx.send(ws, { type: 'qualityFixComplete', data: resultData });
|
|
153
|
-
}
|
|
154
|
-
catch {
|
|
155
|
-
// WebSocket closed — save as pending for delivery on reconnect
|
|
156
|
-
const persistence = getPersistence(workingDir);
|
|
157
|
-
persistence.addPendingResult({
|
|
158
|
-
type: 'fixComplete',
|
|
159
|
-
path: reportPath,
|
|
160
|
-
data: resultData,
|
|
161
|
-
completedAt: new Date().toISOString(),
|
|
162
|
-
});
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
catch (error) {
|
|
166
|
-
try {
|
|
167
|
-
ctx.send(ws, {
|
|
168
|
-
type: 'qualityError',
|
|
169
|
-
data: { path: reportPath, error: error instanceof Error ? error.message : String(error) },
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
catch {
|
|
173
|
-
// WebSocket closed — error lost but operation tracked via activeOps
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
finally {
|
|
177
|
-
stopHeartbeat();
|
|
178
|
-
activeFixes.delete(dirPath);
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
//# sourceMappingURL=quality-fix-agent.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"quality-fix-agent.js","sourceRoot":"","sources":["../../../../server/services/websocket/quality-fix-agent.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,gEAAgE;AAEhE;;;;GAIG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAEzE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAG1D,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAenE,iEAAiE;AAEjE,MAAM,aAAa,GAA2B;IAC5C,IAAI,EAAE,uCAAuC;IAC7C,IAAI,EAAE,mBAAmB;IACzB,KAAK,EAAE,kBAAkB;IACzB,IAAI,EAAE,+BAA+B;IACrC,IAAI,EAAE,yBAAyB;CAChC,CAAC;AAEF,MAAM,UAAU,0BAA0B,CAAC,GAAmB,EAAE,EAAa,EAAE,UAAkB;IAC/F,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IACpC,OAAO,CAAC,KAAmB,EAAE,EAAE;QAC7B,IAAI,CAAC;YACH,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,IAAI,KAAK,CAAC,QAAQ,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACpF,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;gBAC9B,MAAM,OAAO,GAAG,aAAa,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AAE,IAAI,EAAE,oBAAoB,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QACjE,CAAC;QAAC,MAAM,CAAC;YACP,+DAA+D;YAC/D,MAAM,WAAW,GAAG,cAAc,CAAC,UAAU,CAAC,CAAC;YAC/C,WAAW,CAAC,gBAAgB,CAAC;gBAC3B,IAAI,EAAE,aAAa;gBACnB,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,UAAgD;gBACtD,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;aACtC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC;YACH,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE;gBACX,IAAI,EAAE,cAAc;gBACpB,IAAI,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;aAC1F,CAAC,CAAC;QACL,CAAC;QAAC,MAAM,CAAC;YACP,oEAAoE;QACtE,CAAC;IACH,CAAC;YAAS,CAAC;QACT,aAAa,EAAE,CAAC;QAChB,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC"}
|
|
@@ -1,216 +0,0 @@
|
|
|
1
|
-
// Copyright (c) 2025-present Mstro, Inc. All rights reserved.
|
|
2
|
-
// Licensed under the MIT License. See LICENSE file for details.
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Quality Fix Agent — AI-powered issue fixing using Claude Code headless runner.
|
|
6
|
-
*
|
|
7
|
-
* Builds the fix prompt, runs the agent, re-scans, and persists updated results.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import { ResilientRunner } from '../../cli/headless/resilient-runner.js';
|
|
11
|
-
import type { ToolUseEvent } from '../../cli/headless/types.js';
|
|
12
|
-
import { loadSkillPrompt } from '../plan/agent-loader.js';
|
|
13
|
-
import type { HandlerContext } from './handler-context.js';
|
|
14
|
-
import type { QualityPersistence } from './quality-persistence.js';
|
|
15
|
-
import { detectTools, runQualityScan } from './quality-service.js';
|
|
16
|
-
import type { WSContext } from './types.js';
|
|
17
|
-
|
|
18
|
-
// ── Types ─────────────────────────────────────────────────────
|
|
19
|
-
|
|
20
|
-
export interface FindingForFix {
|
|
21
|
-
severity: string;
|
|
22
|
-
category: string;
|
|
23
|
-
file: string;
|
|
24
|
-
line: number | null;
|
|
25
|
-
title: string;
|
|
26
|
-
description: string;
|
|
27
|
-
suggestion?: string;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// ── Progress callback ─────────────────────────────────────────
|
|
31
|
-
|
|
32
|
-
const TOOL_MESSAGES: Record<string, string> = {
|
|
33
|
-
Read: 'Reading files to understand issues...',
|
|
34
|
-
Edit: 'Applying fixes...',
|
|
35
|
-
Write: 'Writing fixes...',
|
|
36
|
-
Grep: 'Searching for related code...',
|
|
37
|
-
Bash: 'Running verification...',
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
export function createToolProgressCallback(ctx: HandlerContext, ws: WSContext, reportPath: string) {
|
|
41
|
-
const seenTools = new Set<string>();
|
|
42
|
-
return (event: ToolUseEvent) => {
|
|
43
|
-
try {
|
|
44
|
-
if (event.type === 'tool_start' && event.toolName && !seenTools.has(event.toolName)) {
|
|
45
|
-
seenTools.add(event.toolName);
|
|
46
|
-
const message = TOOL_MESSAGES[event.toolName];
|
|
47
|
-
if (message) {
|
|
48
|
-
ctx.send(ws, { type: 'qualityFixProgress', data: { path: reportPath, message } });
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
if (event.type === 'tool_complete' && event.toolName === 'Edit' && event.completeInput?.file_path) {
|
|
52
|
-
ctx.send(ws, {
|
|
53
|
-
type: 'qualityFixProgress',
|
|
54
|
-
data: { path: reportPath, message: `Fixed ${String(event.completeInput.file_path).split('/').slice(-2).join('/')}` },
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
} catch {
|
|
58
|
-
// WebSocket closed — progress lost but fix operation continues
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
function startFixHeartbeat(ctx: HandlerContext, ws: WSContext, reportPath: string, intervalMs = 30_000): () => void {
|
|
64
|
-
let elapsed = 0;
|
|
65
|
-
const timer = setInterval(() => {
|
|
66
|
-
elapsed += intervalMs;
|
|
67
|
-
const mins = Math.floor(elapsed / 60_000);
|
|
68
|
-
const secs = Math.floor((elapsed % 60_000) / 1000);
|
|
69
|
-
const timeStr = mins > 0 ? `${mins}m ${secs}s` : `${secs}s`;
|
|
70
|
-
try {
|
|
71
|
-
ctx.send(ws, { type: 'qualityFixProgress', data: { path: reportPath, message: `Fixing issues (${timeStr} elapsed, still working...)` } });
|
|
72
|
-
} catch {
|
|
73
|
-
// WebSocket closed — heartbeat lost but fix continues
|
|
74
|
-
}
|
|
75
|
-
}, intervalMs);
|
|
76
|
-
return () => clearInterval(timer);
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// ── Prompt ────────────────────────────────────────────────────
|
|
80
|
-
|
|
81
|
-
function buildFixPrompt(findings: FindingForFix[], section?: string): string {
|
|
82
|
-
const filtered = section ? findings.filter((f) => f.category === section) : findings;
|
|
83
|
-
const sorted = filtered.sort((a, b) => {
|
|
84
|
-
const order: Record<string, number> = { critical: 0, high: 1, medium: 2, low: 3 };
|
|
85
|
-
return (order[a.severity] ?? 4) - (order[b.severity] ?? 4);
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
const issueList = sorted.slice(0, 30).map((f, i) => {
|
|
89
|
-
const loc = f.line ? `${f.file}:${f.line}` : f.file;
|
|
90
|
-
const parts = [`${i + 1}. [${f.severity.toUpperCase()}] ${loc} — ${f.title}`];
|
|
91
|
-
if (f.description) parts.push(` ${f.description}`);
|
|
92
|
-
if (f.suggestion) parts.push(` Suggestion: ${f.suggestion}`);
|
|
93
|
-
return parts.join('\n');
|
|
94
|
-
}).join('\n\n');
|
|
95
|
-
|
|
96
|
-
const fromSkill = loadSkillPrompt('fix-quality', {
|
|
97
|
-
issueList,
|
|
98
|
-
issueCount: String(sorted.length),
|
|
99
|
-
showCount: String(Math.min(30, sorted.length)),
|
|
100
|
-
});
|
|
101
|
-
if (fromSkill) return fromSkill;
|
|
102
|
-
|
|
103
|
-
return `You are a code quality fix agent. Fix the following quality issues in the codebase.\n\n## Issues to Fix (${sorted.length} total, showing top ${Math.min(30, sorted.length)})\n\n${issueList}\n\nFix each issue by editing the relevant file. Work from most to least severe. Do NOT introduce new issues.`;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// ── Handler ───────────────────────────────────────────────────
|
|
107
|
-
|
|
108
|
-
const activeFixes = new Set<string>();
|
|
109
|
-
|
|
110
|
-
export async function handleFixIssues(
|
|
111
|
-
ctx: HandlerContext,
|
|
112
|
-
ws: WSContext,
|
|
113
|
-
reportPath: string,
|
|
114
|
-
dirPath: string,
|
|
115
|
-
workingDir: string,
|
|
116
|
-
section: string | undefined,
|
|
117
|
-
findings: FindingForFix[],
|
|
118
|
-
getPersistence: (dir: string) => QualityPersistence,
|
|
119
|
-
): Promise<void> {
|
|
120
|
-
if (activeFixes.has(dirPath)) {
|
|
121
|
-
ctx.send(ws, {
|
|
122
|
-
type: 'qualityError',
|
|
123
|
-
data: { path: reportPath, error: 'A fix operation is already running for this directory.' },
|
|
124
|
-
});
|
|
125
|
-
return;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
if (findings.length === 0) {
|
|
129
|
-
ctx.send(ws, {
|
|
130
|
-
type: 'qualityError',
|
|
131
|
-
data: { path: reportPath, error: 'No findings to fix.' },
|
|
132
|
-
});
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
activeFixes.add(dirPath);
|
|
137
|
-
const stopHeartbeat = startFixHeartbeat(ctx, ws, reportPath);
|
|
138
|
-
try {
|
|
139
|
-
try {
|
|
140
|
-
ctx.send(ws, {
|
|
141
|
-
type: 'qualityFixProgress',
|
|
142
|
-
data: { path: reportPath, message: 'Starting Claude Code to fix issues...' },
|
|
143
|
-
});
|
|
144
|
-
} catch { /* WS closed */ }
|
|
145
|
-
|
|
146
|
-
const prompt = buildFixPrompt(findings, section);
|
|
147
|
-
|
|
148
|
-
const runner = new ResilientRunner({
|
|
149
|
-
workingDir: dirPath,
|
|
150
|
-
prompt,
|
|
151
|
-
policy: 'STANDARD',
|
|
152
|
-
stallWarningMs: 300_000,
|
|
153
|
-
stallKillMs: 1_200_000,
|
|
154
|
-
stallHardCapMs: 1_800_000,
|
|
155
|
-
toolUseCallback: createToolProgressCallback(ctx, ws, reportPath),
|
|
156
|
-
logLabel: 'code-review-fix',
|
|
157
|
-
});
|
|
158
|
-
|
|
159
|
-
await runner.run();
|
|
160
|
-
|
|
161
|
-
try {
|
|
162
|
-
ctx.send(ws, {
|
|
163
|
-
type: 'qualityFixProgress',
|
|
164
|
-
data: { path: reportPath, message: 'Fixes applied. Re-running quality checks...' },
|
|
165
|
-
});
|
|
166
|
-
} catch { /* WS closed */ }
|
|
167
|
-
|
|
168
|
-
// Re-run quality scan after fixing
|
|
169
|
-
const { tools: detectedTools } = await detectTools(dirPath);
|
|
170
|
-
const installedToolNames = detectedTools.filter((t) => t.installed).map((t) => t.name);
|
|
171
|
-
|
|
172
|
-
const results = await runQualityScan(dirPath, (progress) => {
|
|
173
|
-
try {
|
|
174
|
-
ctx.send(ws, {
|
|
175
|
-
type: 'qualityScanProgress',
|
|
176
|
-
data: { path: reportPath, progress },
|
|
177
|
-
});
|
|
178
|
-
} catch { /* WS closed */ }
|
|
179
|
-
}, installedToolNames);
|
|
180
|
-
|
|
181
|
-
// Persist before sending — results survive WebSocket drops
|
|
182
|
-
try {
|
|
183
|
-
const persistence = getPersistence(workingDir);
|
|
184
|
-
persistence.saveReport(reportPath, results);
|
|
185
|
-
persistence.appendHistory(results, reportPath);
|
|
186
|
-
} catch {
|
|
187
|
-
// Persistence failure should not break the fix flow
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
const resultData = { path: reportPath, results };
|
|
191
|
-
try {
|
|
192
|
-
ctx.send(ws, { type: 'qualityFixComplete', data: resultData });
|
|
193
|
-
} catch {
|
|
194
|
-
// WebSocket closed — save as pending for delivery on reconnect
|
|
195
|
-
const persistence = getPersistence(workingDir);
|
|
196
|
-
persistence.addPendingResult({
|
|
197
|
-
type: 'fixComplete',
|
|
198
|
-
path: reportPath,
|
|
199
|
-
data: resultData as unknown as Record<string, unknown>,
|
|
200
|
-
completedAt: new Date().toISOString(),
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
} catch (error) {
|
|
204
|
-
try {
|
|
205
|
-
ctx.send(ws, {
|
|
206
|
-
type: 'qualityError',
|
|
207
|
-
data: { path: reportPath, error: error instanceof Error ? error.message : String(error) },
|
|
208
|
-
});
|
|
209
|
-
} catch {
|
|
210
|
-
// WebSocket closed — error lost but operation tracked via activeOps
|
|
211
|
-
}
|
|
212
|
-
} finally {
|
|
213
|
-
stopHeartbeat();
|
|
214
|
-
activeFixes.delete(dirPath);
|
|
215
|
-
}
|
|
216
|
-
}
|