forked from vercel/next-evals-oss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude-code-cli.ts
More file actions
executable file
·390 lines (320 loc) · 10.6 KB
/
claude-code-cli.ts
File metadata and controls
executable file
·390 lines (320 loc) · 10.6 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
385
386
387
388
389
390
#!/usr/bin/env bun
import fs from "fs/promises";
import path from "path";
import {
type ClaudeCodeResult,
runClaudeCodeEval,
} from "./lib/claude-code-runner";
// Simple argument parser for Bun compatibility
function parseCliArgs(args: string[]) {
const values: Record<string, any> = {};
const positionals: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === "-h" || arg === "--help") {
values.help = true;
} else if (arg === "-a" || arg === "--all") {
values.all = true;
} else if (arg === "-v" || arg === "--verbose") {
values.verbose = true;
} else if (arg === "--debug") {
values.debug = true;
} else if (arg === "-e" || arg === "--eval") {
values.eval = args[++i];
} else if (arg === "-t" || arg === "--timeout") {
values.timeout = args[++i];
} else if (arg === "--api-key") {
values["api-key"] = args[++i];
} else if (arg === "--output-file") {
values["output-file"] = args[++i];
} else if (!arg.startsWith("-")) {
positionals.push(arg);
}
}
return { values, positionals };
}
const { values, positionals } = parseCliArgs(process.argv.slice(2));
function showHelp() {
console.log(`
Claude Code Evals CLI
Usage:
claude-code-cli.ts [options] [eval-path]
Options:
-h, --help Show this help message
-e, --eval <path> Run a specific eval by path
-a, --all Run all evals with Claude Code
-v, --verbose Show detailed logs during eval execution
--debug Persist output folders for debugging (don't clean up)
-t, --timeout <ms> Timeout in milliseconds (default: 600000 = 10 minutes)
--api-key <key> Anthropic API key (or use ANTHROPIC_API_KEY env var)
--output-file <path> Write results to JSON file (only with --all)
Examples:
# Run a specific eval
bun claude-code-cli.ts --eval 001-server-component
# Run eval by positional argument
bun claude-code-cli.ts 001-server-component
# Run with verbose output and custom timeout
bun claude-code-cli.ts --eval 001-server-component --verbose --timeout 600000
# Run all evals
bun claude-code-cli.ts --all
# Debug mode - keep output folders for inspection
bun claude-code-cli.ts --eval 001-server-component --debug
# Write results to JSON file when running all evals
bun claude-code-cli.ts --all --output-file results.json
`);
}
async function getAllEvals(): Promise<string[]> {
const evalsDir = path.join(process.cwd(), "evals");
const entries = await fs.readdir(evalsDir, { withFileTypes: true });
const evals: string[] = [];
for (const entry of entries) {
if (entry.isDirectory() && /^\d+/.test(entry.name)) {
const evalPath = path.join(evalsDir, entry.name);
// Check if it has both input/ directory and prompt.md
const hasInput = await fs
.stat(path.join(evalPath, "input"))
.then((s) => s.isDirectory())
.catch(() => false);
const hasPrompt = await fs
.stat(path.join(evalPath, "prompt.md"))
.then((s) => s.isFile())
.catch(() => false);
if (hasInput && hasPrompt) {
evals.push(entry.name);
}
}
}
return evals.sort();
}
function formatDuration(ms: number): string {
if (ms < 1000) {
return `${Math.round(ms)}ms`;
} else {
const seconds = ms / 1000;
return `${seconds.toFixed(1)}s`;
}
}
function displayResult(evalPath: string, result: ClaudeCodeResult) {
console.log("\n📊 Claude Code Results:");
console.log("═".repeat(80));
const evalColWidth = Math.max(25, evalPath.length);
const header = `| ${"Eval".padEnd(
evalColWidth
)} | Result | Build | Lint | Tests | Duration |`;
const separator = `|${"-".repeat(
evalColWidth + 2
)}|------------|-------|-------|-------|----------|`;
console.log(header);
console.log(separator);
const name = evalPath.padEnd(evalColWidth);
const build = result.buildSuccess ? "✅" : "❌";
const lint = result.lintSuccess ? "✅" : "❌";
const tests = result.testSuccess ? "✅" : "❌";
const allPassed =
result.buildSuccess && result.lintSuccess && result.testSuccess;
const resultStatus = allPassed ? "✅ PASS" : "❌ FAIL";
const duration = formatDuration(result.duration);
console.log(
`| ${name} | ${resultStatus.padEnd(
10
)} | ${build} | ${lint} | ${tests} | ${duration.padEnd(8)} |`
);
console.log("═".repeat(80));
if (!allPassed || !result.success) {
console.log("\n❌ Error Details:");
console.log("─".repeat(80));
if (result.error) {
console.log(`Claude Code Error: ${result.error}`);
}
if (!result.buildSuccess && result.buildOutput) {
console.log(`Build Error:\n${result.buildOutput.slice(-1000)}`);
}
if (!result.lintSuccess && result.lintOutput) {
console.log(`Lint Error:\n${result.lintOutput.slice(-1000)}`);
}
if (!result.testSuccess && result.testOutput) {
console.log(`Test Error:\n${result.testOutput.slice(-1000)}`);
}
}
console.log("═".repeat(80));
}
function displayResultsTable(
results: { evalPath: string; result: ClaudeCodeResult }[]
) {
const totalTests = results.length;
console.log(`\n📊 Claude Code Results Summary (${totalTests} Tests):`);
console.log("═".repeat(120));
const header = `| ${"Eval".padEnd(
25
)} | Result | Build | Lint | Tests | Duration |`;
const separator = `|${"-".repeat(
27
)}|------------|-------|-------|-------|----------|`;
console.log(header);
console.log(separator);
const failedEvals: Array<{
evalPath: string;
buildError?: string;
lintError?: string;
testError?: string;
claudeError?: string;
}> = [];
let passedEvals = 0;
for (const { evalPath, result } of results) {
const name = evalPath.padEnd(25);
const build = result.buildSuccess ? "✅" : "❌";
const lint = result.lintSuccess ? "✅" : "❌";
const tests = result.testSuccess ? "✅" : "❌";
const allPassed =
result.success &&
result.buildSuccess &&
result.lintSuccess &&
result.testSuccess;
const resultStatus = allPassed ? "✅ PASS" : "❌ FAIL";
const duration = formatDuration(result.duration);
if (allPassed) {
passedEvals++;
}
console.log(
`| ${name} | ${resultStatus.padEnd(
10
)} | ${build} | ${lint} | ${tests} | ${duration.padEnd(8)} |`
);
// Collect errors for failed evals
if (!allPassed) {
const errors: any = { evalPath };
if (result.error) {
errors.claudeError = result.error;
}
if (!result.buildSuccess && result.buildOutput) {
errors.buildError = result.buildOutput.slice(-500);
}
if (!result.lintSuccess && result.lintOutput) {
errors.lintError = result.lintOutput.slice(-500);
}
if (!result.testSuccess && result.testOutput) {
errors.testError = result.testOutput.slice(-500);
}
failedEvals.push(errors);
}
}
console.log("═".repeat(120));
// Summary stats
console.log(`\n📈 Summary: ${passedEvals}/${totalTests} evals passed`);
// Display error summaries
if (failedEvals.length > 0) {
console.log("\n❌ Error Summaries:");
console.log("─".repeat(120));
for (const failed of failedEvals) {
console.log(`\n${failed.evalPath}:`);
if (failed.claudeError) {
console.log(` Claude Code: ${failed.claudeError}`);
}
if (failed.buildError) {
console.log(` Build: ${failed.buildError}`);
}
if (failed.lintError) {
console.log(` Lint: ${failed.lintError}`);
}
if (failed.testError) {
console.log(` Tests: ${failed.testError}`);
}
}
}
}
async function main() {
if (values.help) {
showHelp();
return;
}
const evalOptions = {
verbose: values.verbose || false,
debug: values.debug || false,
timeout: values.timeout ? parseInt(values.timeout) : 600000, // 10 minutes default
// apiKey,
};
if (values.all) {
const allEvals = await getAllEvals();
console.log(`Running ${allEvals.length} evals with Claude Code...\n`);
const results: { evalPath: string; result: ClaudeCodeResult }[] = [];
for (const evalPath of allEvals) {
try {
console.log(`🚀 Running ${evalPath}...`);
const result = await runClaudeCodeEval(evalPath, evalOptions);
results.push({ evalPath, result });
const status =
result.success &&
result.buildSuccess &&
result.lintSuccess &&
result.testSuccess
? "✅ PASS"
: "❌ FAIL";
console.log(
`${status} ${evalPath} (${formatDuration(result.duration)})`
);
} catch (error) {
const errorResult: ClaudeCodeResult = {
success: false,
output: "",
error: error instanceof Error ? error.message : String(error),
duration: 0,
};
results.push({ evalPath, result: errorResult });
console.log(`❌ FAIL ${evalPath} - ${errorResult.error}`);
}
}
displayResultsTable(results);
// Write all results to file if outputFile is specified
if (values["output-file"]) {
try {
await fs.writeFile(
values["output-file"],
JSON.stringify(results, null, 2),
"utf-8"
);
console.log(`\n📝 All results written to: ${values["output-file"]}`);
} catch (error) {
console.error(
`⚠️ Failed to write results to file: ${
error instanceof Error ? error.message : String(error)
}`
);
}
}
return;
}
const evalPath = values.eval || positionals[0];
if (!evalPath) {
console.error(
"❌ Error: No eval specified. Use --eval <path>, provide a positional argument, or use --all"
);
console.log("\nAvailable evals:");
const allEvals = await getAllEvals();
// biome-ignore lint/suspicious/useIterableCallbackReturn: cautious
allEvals.forEach((evalName) => console.log(` ${evalName}`));
process.exit(1);
}
console.log(`🚀 Running Claude Code eval: ${evalPath}`);
try {
const result = await runClaudeCodeEval(evalPath, evalOptions);
displayResult(evalPath, result);
const success =
result.success &&
result.buildSuccess &&
result.lintSuccess &&
result.testSuccess;
process.exit(success ? 0 : 1);
} catch (error) {
console.error(
`❌ Error: ${error instanceof Error ? error.message : String(error)}`
);
process.exit(1);
}
}
// @ts-expect-error
if (import.meta.main) {
main().catch((error) => {
console.error("Unexpected error:", error);
process.exit(1);
});
}