forked from BeOnAuto/auto-engineer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunSlice.ts
More file actions
384 lines (335 loc) · 13.3 KB
/
runSlice.ts
File metadata and controls
384 lines (335 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import path from 'path';
import fg from 'fast-glob';
import { generateTextWithAI, getAvailableProviders } from '@auto-engineer/ai-gateway';
import { readFile, writeFile, access } from 'fs/promises';
import { execa } from 'execa';
import { SYSTEM_PROMPT } from '../prompts/systemPrompt.js';
import { extractCodeBlock } from '../utils/extractCodeBlock.js';
import { runTests } from './runTests';
const availableProviders = getAvailableProviders();
const AI_PROVIDER = availableProviders[0];
if (availableProviders.length === 0) {
console.error(
'❌ No AI providers configured. Please set one of: OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY, or XAI_API_KEY',
);
process.exit(1);
}
type TestAndTypecheckResult = {
success: boolean;
failedTestFiles: string[];
failedTypecheckFiles: string[];
testErrors: string;
typecheckErrors: string;
};
export type VitestAssertionResult = {
status: string;
fullName: string;
failureMessages?: string[];
};
export type VitestTestResult = {
file: string;
name?: string;
status: string;
assertionResults: VitestAssertionResult[];
};
export async function runSlice(sliceDir: string, flow: string): Promise<void> {
const sliceName = path.basename(sliceDir);
console.log(`✏️ Implementing slice: ${sliceName} for flow: ${flow}`);
const contextFiles = await loadContextFiles(sliceDir);
const filesToImplement = findFilesToImplement(contextFiles);
for (const [targetFile] of filesToImplement) {
await implementFileFromAI(sliceDir, targetFile, contextFiles);
}
const result = await runTestsAndTypecheck(sliceDir);
reportTestAndTypecheckResults(sliceDir, flow, result);
if (result.success) {
console.log(`✅ All tests and checks passed on first attempt.`);
return;
}
await retryFailedFiles(sliceDir, flow, result);
if (result.failedTestFiles.length > 0) {
await retryFailedTests(sliceDir, flow, result);
}
}
async function retryFailedFiles(sliceDir: string, flow: string, initialResult: TestAndTypecheckResult) {
let contextFiles = await loadContextFiles(sliceDir);
let result = initialResult;
for (let attempt = 1; attempt <= 5; attempt++) {
if (result.failedTypecheckFiles.length === 0) {
console.log(`✅ Typecheck issues resolved after attempt ${attempt - 1}`);
break;
}
console.log(`🔁 Typecheck retry attempt ${attempt} for ${result.failedTypecheckFiles.length} files...`);
contextFiles = await loadContextFiles(sliceDir);
for (const filePath of result.failedTypecheckFiles) {
const fileName = path.basename(filePath);
const retryPrompt = buildRetryPrompt(fileName, contextFiles, result.testErrors, result.typecheckErrors);
console.log(`🔧 Retrying typecheck error in ${fileName} in flow ${flow}...`);
const aiOutput = await generateTextWithAI(retryPrompt, AI_PROVIDER);
const cleanedCode = extractCodeBlock(aiOutput);
await writeFile(path.join(sliceDir, fileName), cleanedCode, 'utf-8');
console.log(`♻️ Updated ${fileName} to fix typecheck errors`);
}
result = await runTestsAndTypecheck(sliceDir);
reportTestAndTypecheckResults(sliceDir, flow, result);
}
if (result.failedTypecheckFiles.length > 0) {
console.log(`⚠️ Fixing tests caused typecheck errors. Retrying typecheck fixes...`);
const typecheckOnlyResult = {
...result,
testErrors: '', // Clear test errors since we're only fixing typecheck
failedTestFiles: [], // Clear failed test files
};
result = await retryFailedFiles(sliceDir, path.basename(sliceDir), typecheckOnlyResult);
// After fixing typecheck, re-run everything to get fresh results
const freshResult = await runTestsAndTypecheck(sliceDir);
reportTestAndTypecheckResults(sliceDir, flow, freshResult);
result = freshResult;
if (result.failedTestFiles.length === 0) {
console.log(`✅ All test issues resolved after fixing type errors.`);
}
}
return result;
}
async function loadContextFiles(sliceDir: string): Promise<Record<string, string>> {
const files = await fg(['*.ts'], { cwd: sliceDir });
const context: Record<string, string> = {};
for (const file of files) {
const absPath = path.join(sliceDir, file);
context[file] = await readFile(absPath, 'utf-8');
}
return context;
}
function findFilesToImplement(contextFiles: Record<string, string>) {
return Object.entries(contextFiles).filter(
([, content]) => content.includes('TODO:') || content.includes('IMPLEMENTATION INSTRUCTIONS'),
);
}
function buildInitialPrompt(targetFile: string, context: Record<string, string>): string {
return `
${SYSTEM_PROMPT}
---
📄 Target file to implement: ${targetFile}
${context[targetFile]}
---
🧠 Other files in the same slice:
${Object.entries(context)
.filter(([name]) => name !== targetFile)
.map(([name, content]) => `// File: ${name}\n${content}`)
.join('\n\n')}
---
Return only the whole updated file of ${targetFile}. Do not remove existing imports or types that are still referenced or required in the file. The file returned has to be production ready.
`.trim();
}
function buildRetryPrompt(
targetFile: string,
context: Record<string, string>,
testErrors: string,
typeErrors: string,
): string {
return `
${SYSTEM_PROMPT}
---
The previous implementation of ${targetFile} caused test or type-check failures.
📄 File to fix: ${targetFile}
${context[targetFile]}
🧠 Other files in the same slice:
${Object.entries(context)
.filter(([name]) => name !== targetFile)
.map(([name, content]) => `// File: ${name}\n${content}`)
.join('\n\n')}
🧪 Test errors:
${testErrors || 'None'}
📐 Typecheck errors:
${typeErrors || 'None'}
---
Return only the corrected full contents of ${targetFile}, no commentary, no markdown.
`.trim();
}
async function implementFileFromAI(sliceDir: string, targetFile: string, contextFiles: Record<string, string>) {
const filePath = path.join(sliceDir, targetFile);
const prompt = buildInitialPrompt(targetFile, contextFiles);
console.log(`🔮 Analysing and Implementing ${targetFile}`);
const aiOutput = await generateTextWithAI(prompt, AI_PROVIDER);
//console.log('AI output:', aiOutput);
const cleanedCode = extractCodeBlock(aiOutput);
await writeFile(filePath, cleanedCode, 'utf-8');
console.log(`♻ Implemented ${targetFile}`);
}
export async function runTestsAndTypecheck(sliceDir: string): Promise<TestAndTypecheckResult> {
const rootDir = await findProjectRoot(sliceDir);
const testResult = await runTests(sliceDir, rootDir);
const typecheckResult = await runTypecheck(sliceDir, rootDir);
return {
success: testResult.success && typecheckResult.success,
failedTestFiles: testResult.failedTestFiles,
failedTypecheckFiles: typecheckResult.failedTypecheckFiles,
testErrors: testResult.testErrors,
typecheckErrors: typecheckResult.typecheckErrors,
};
}
async function retryFailedTests(sliceDir: string, flow: string, result: TestAndTypecheckResult) {
let contextFiles = await loadContextFiles(sliceDir);
for (let attempt = 1; attempt <= 5; attempt++) {
if (result.failedTestFiles.length === 0) {
console.log(`✅ Test failures resolved after attempt ${attempt - 1}`);
break;
}
console.log(`🔁 Test retry attempt ${attempt} for ${result.failedTestFiles.length} files...`);
const smartPrompt = `
${SYSTEM_PROMPT}
---
🧪 The current implementation has test failures.
📄 Test errors:
${result.testErrors || 'None'}
🧠 Full slice context:
${Object.entries(contextFiles)
.map(([name, content]) => `// File: ${name}\n${content}`)
.join('\n\n')}
---
Please return the full corrected content of a single file (not a test file) that should be updated to fix the failing tests.
Use this format:
\`\`\`ts
// File: <fileName>.ts
<corrected code>
\`\`\`
No commentary or markdown outside the code block.
`.trim();
console.log('🔮 Asking AI to suggest a fix for test failures...');
const aiOutput = await generateTextWithAI(smartPrompt, AI_PROVIDER);
const cleaned = extractCodeBlock(aiOutput);
const match = cleaned.match(/^\/\/ File: (.+?)\n([\s\S]*)/m);
if (!match) {
console.warn(`⚠️ Skipping retry. AI output didn't match expected format.`);
break;
}
const [, fileName, code] = match;
const absPath = path.join(sliceDir, fileName.trim());
console.log('🔧 Applying AI fix to:', absPath);
await writeFile(absPath, code.trim(), 'utf-8');
console.log(`♻️ Updated ${fileName.trim()} to fix tests`);
contextFiles = await loadContextFiles(sliceDir);
result = await runTestsAndTypecheck(sliceDir);
reportTestAndTypecheckResults(sliceDir, flow, result);
// If test fix introduced a new type error, handle it before continuing
if (result.failedTypecheckFiles.length > 0) {
console.log(`⚠️ Fixing tests caused typecheck errors. Retrying typecheck fixes...`);
result = await retryFailedFiles(sliceDir, flow, result);
if (result.failedTestFiles.length === 0) {
console.log(`✅ All test issues resolved after fixing type errors.`);
break;
}
}
contextFiles = await loadContextFiles(sliceDir);
}
if (result.failedTestFiles.length > 0) {
console.error(`❌ Some test failures remain after retry attempts.`);
for (const file of result.failedTestFiles) {
console.log(` - ${path.relative(sliceDir, file)}`);
}
}
}
async function runTypecheck(sliceDir: string, rootDir: string) {
try {
const result = await execa('npx', ['tsc', '--noEmit'], {
cwd: rootDir,
stdio: 'pipe',
reject: false,
});
const output = (result.stdout ?? '') + (result.stderr ?? '');
if (result.exitCode !== 0 || output.includes('error')) {
return await processTypecheckOutput(output, sliceDir, rootDir);
}
return { success: true, typecheckErrors: '', failedTypecheckFiles: [] };
} catch (err: unknown) {
const execaErr = err as { stdout?: string; stderr?: string };
const output = (execaErr.stdout ?? '') + (execaErr.stderr ?? '');
console.error('TypeScript execution error:', output);
const files = await fg(['*.ts'], { cwd: sliceDir, absolute: true });
return { success: false, typecheckErrors: output, failedTypecheckFiles: files };
}
}
function getTypecheckPatterns(): RegExp[] {
return [
/^([^:]+\.ts)\(\d+,\d+\): error/gm,
/error TS\d+: (.+) '([^']+\.ts)'/gm,
/^([^:]+\.ts):\d+:\d+\s+-\s+error/gm,
];
}
function extractFailedFiles(output: string, patterns: RegExp[], rootDir: string, sliceDir?: string): string[] {
const failedFiles = new Set<string>();
for (const pattern of patterns) {
for (const match of output.matchAll(pattern)) {
const filePath = match[1] ? path.resolve(rootDir, match[1]) : '';
const notNodeModules = !filePath.includes('node_modules');
const inSlice = sliceDir === undefined || filePath.startsWith(sliceDir);
if (notNodeModules && inSlice) {
failedFiles.add(filePath);
}
}
}
return Array.from(failedFiles);
}
async function processTypecheckOutput(output: string, sliceDir: string, rootDir: string) {
const relativePath = path.relative(rootDir, sliceDir);
const filtered = output
.split('\n')
.filter((line) => {
const hasError = line.includes('error TS') || line.includes('): error');
const notNodeModules = !line.includes('node_modules');
const hasSlicePath = line.includes(relativePath) || line.includes(sliceDir);
return hasError && notNodeModules && hasSlicePath;
})
.join('\n');
if (filtered.trim() === '') {
return { success: true, typecheckErrors: '', failedTypecheckFiles: [] };
}
const failedFiles = await processTypecheckFailure(filtered, rootDir, sliceDir);
return {
success: false,
typecheckErrors: filtered,
failedTypecheckFiles: failedFiles,
};
}
async function processTypecheckFailure(output: string, rootDir: string, sliceDir: string): Promise<string[]> {
const patterns = getTypecheckPatterns();
let failed = extractFailedFiles(output, patterns, rootDir, sliceDir);
if (failed.length === 0 && output.includes('error')) {
failed = await fg(['*.ts'], { cwd: sliceDir, absolute: true });
}
return failed;
}
async function findProjectRoot(startDir: string): Promise<string> {
let dir = startDir;
while (dir !== path.dirname(dir)) {
try {
await access(path.join(dir, 'package.json'));
return dir;
} catch {
dir = path.dirname(dir);
}
}
throw new Error('❌ Could not find project root');
}
function reportTestAndTypecheckResults(sliceDir: string, flow: string, result: TestAndTypecheckResult) {
const sliceName = path.basename(sliceDir);
if (result.success) {
console.log(`✅ All Tests and checks passed for: ${sliceName} in flow ${flow}`);
return;
}
console.error(`❌ ${sliceName} in floe ${flow} failed tests or type-checks.`);
if (result.failedTestFiles.length) {
const files = result.failedTestFiles.map((f) => path.relative(sliceDir, f));
console.log(`🧪 Failed test files: ${files.join(', ')}`);
if (result.testErrors) {
console.log(`📝 Test errors:\n${result.testErrors}`);
}
}
if (result.failedTypecheckFiles.length) {
const files = result.failedTypecheckFiles.map((f) => path.relative(sliceDir, f));
console.log(`📐 Failed typecheck files: ${files.join(', ')}`);
if (result.typecheckErrors) {
console.log(`📝 Typecheck errors:\n${result.typecheckErrors}`);
}
}
}