@kakarot-ci/core 0.2.0 → 0.4.0

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 (102) hide show
  1. package/dist/cli/index.js +2289 -0
  2. package/dist/cli/index.js.map +7 -0
  3. package/dist/index.cjs +863 -101
  4. package/dist/index.cjs.map +4 -4
  5. package/dist/index.js +852 -100
  6. package/dist/index.js.map +4 -4
  7. package/dist/src/cli/index.d.ts +7 -0
  8. package/dist/src/cli/index.d.ts.map +1 -0
  9. package/dist/src/core/orchestrator.d.ts +32 -0
  10. package/dist/src/core/orchestrator.d.ts.map +1 -0
  11. package/dist/src/github/client.d.ts.map +1 -0
  12. package/dist/{index.d.ts → src/index.d.ts} +14 -0
  13. package/dist/src/index.d.ts.map +1 -0
  14. package/dist/src/llm/factory.d.ts.map +1 -0
  15. package/dist/src/llm/parser.d.ts.map +1 -0
  16. package/dist/src/llm/prompts/coverage-summary.d.ts +8 -0
  17. package/dist/src/llm/prompts/coverage-summary.d.ts.map +1 -0
  18. package/dist/src/llm/prompts/test-fix.d.ts.map +1 -0
  19. package/dist/src/llm/prompts/test-generation.d.ts.map +1 -0
  20. package/dist/src/llm/providers/anthropic.d.ts.map +1 -0
  21. package/dist/src/llm/providers/base.d.ts.map +1 -0
  22. package/dist/src/llm/providers/google.d.ts.map +1 -0
  23. package/dist/src/llm/providers/openai.d.ts.map +1 -0
  24. package/dist/{llm → src/llm}/test-generator.d.ts +7 -0
  25. package/dist/src/llm/test-generator.d.ts.map +1 -0
  26. package/dist/{types → src/types}/config.d.ts +9 -0
  27. package/dist/src/types/config.d.ts.map +1 -0
  28. package/dist/src/types/config.test.d.ts +2 -0
  29. package/dist/src/types/config.test.d.ts.map +1 -0
  30. package/dist/src/types/coverage.d.ts +40 -0
  31. package/dist/src/types/coverage.d.ts.map +1 -0
  32. package/dist/src/types/diff.d.ts.map +1 -0
  33. package/dist/src/types/github.d.ts.map +1 -0
  34. package/dist/src/types/llm.d.ts.map +1 -0
  35. package/dist/src/types/test-runner.d.ts +30 -0
  36. package/dist/src/types/test-runner.d.ts.map +1 -0
  37. package/dist/src/utils/ast-analyzer.d.ts.map +1 -0
  38. package/dist/src/utils/config-loader.d.ts +10 -0
  39. package/dist/src/utils/config-loader.d.ts.map +1 -0
  40. package/dist/src/utils/coverage-reader.d.ts +6 -0
  41. package/dist/src/utils/coverage-reader.d.ts.map +1 -0
  42. package/dist/src/utils/diff-parser.d.ts.map +1 -0
  43. package/dist/src/utils/diff-parser.test.d.ts +2 -0
  44. package/dist/src/utils/diff-parser.test.d.ts.map +1 -0
  45. package/dist/src/utils/logger.d.ts.map +1 -0
  46. package/dist/src/utils/package-manager-detector.d.ts +6 -0
  47. package/dist/src/utils/package-manager-detector.d.ts.map +1 -0
  48. package/dist/src/utils/package-manager-detector.test.d.ts +2 -0
  49. package/dist/src/utils/package-manager-detector.test.d.ts.map +1 -0
  50. package/dist/src/utils/test-file-path.d.ts +7 -0
  51. package/dist/src/utils/test-file-path.d.ts.map +1 -0
  52. package/dist/src/utils/test-file-path.test.d.ts +2 -0
  53. package/dist/src/utils/test-file-path.test.d.ts.map +1 -0
  54. package/dist/src/utils/test-file-writer.d.ts +8 -0
  55. package/dist/src/utils/test-file-writer.d.ts.map +1 -0
  56. package/dist/src/utils/test-runner/factory.d.ts +6 -0
  57. package/dist/src/utils/test-runner/factory.d.ts.map +1 -0
  58. package/dist/src/utils/test-runner/jest-runner.d.ts +5 -0
  59. package/dist/src/utils/test-runner/jest-runner.d.ts.map +1 -0
  60. package/dist/src/utils/test-runner/vitest-runner.d.ts +5 -0
  61. package/dist/src/utils/test-runner/vitest-runner.d.ts.map +1 -0
  62. package/dist/src/utils/test-target-extractor.d.ts.map +1 -0
  63. package/dist/vitest.config.d.ts +3 -0
  64. package/dist/vitest.config.d.ts.map +1 -0
  65. package/package.json +16 -4
  66. package/dist/github/client.d.ts.map +0 -1
  67. package/dist/index.d.ts.map +0 -1
  68. package/dist/llm/factory.d.ts.map +0 -1
  69. package/dist/llm/parser.d.ts.map +0 -1
  70. package/dist/llm/prompts/test-fix.d.ts.map +0 -1
  71. package/dist/llm/prompts/test-generation.d.ts.map +0 -1
  72. package/dist/llm/providers/anthropic.d.ts.map +0 -1
  73. package/dist/llm/providers/base.d.ts.map +0 -1
  74. package/dist/llm/providers/google.d.ts.map +0 -1
  75. package/dist/llm/providers/openai.d.ts.map +0 -1
  76. package/dist/llm/test-generator.d.ts.map +0 -1
  77. package/dist/types/config.d.ts.map +0 -1
  78. package/dist/types/diff.d.ts.map +0 -1
  79. package/dist/types/github.d.ts.map +0 -1
  80. package/dist/types/llm.d.ts.map +0 -1
  81. package/dist/utils/ast-analyzer.d.ts.map +0 -1
  82. package/dist/utils/config-loader.d.ts +0 -6
  83. package/dist/utils/config-loader.d.ts.map +0 -1
  84. package/dist/utils/diff-parser.d.ts.map +0 -1
  85. package/dist/utils/logger.d.ts.map +0 -1
  86. package/dist/utils/test-target-extractor.d.ts.map +0 -1
  87. /package/dist/{github → src/github}/client.d.ts +0 -0
  88. /package/dist/{llm → src/llm}/factory.d.ts +0 -0
  89. /package/dist/{llm → src/llm}/parser.d.ts +0 -0
  90. /package/dist/{llm → src/llm}/prompts/test-fix.d.ts +0 -0
  91. /package/dist/{llm → src/llm}/prompts/test-generation.d.ts +0 -0
  92. /package/dist/{llm → src/llm}/providers/anthropic.d.ts +0 -0
  93. /package/dist/{llm → src/llm}/providers/base.d.ts +0 -0
  94. /package/dist/{llm → src/llm}/providers/google.d.ts +0 -0
  95. /package/dist/{llm → src/llm}/providers/openai.d.ts +0 -0
  96. /package/dist/{types → src/types}/diff.d.ts +0 -0
  97. /package/dist/{types → src/types}/github.d.ts +0 -0
  98. /package/dist/{types → src/types}/llm.d.ts +0 -0
  99. /package/dist/{utils → src/utils}/ast-analyzer.d.ts +0 -0
  100. /package/dist/{utils → src/utils}/diff-parser.d.ts +0 -0
  101. /package/dist/{utils → src/utils}/logger.d.ts +0 -0
  102. /package/dist/{utils → src/utils}/test-target-extractor.d.ts +0 -0
package/dist/index.cjs CHANGED
@@ -32,25 +32,35 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
32
32
  var src_exports = {};
33
33
  __export(src_exports, {
34
34
  GitHubClient: () => GitHubClient,
35
+ JestRunner: () => JestRunner,
35
36
  KakarotConfigSchema: () => KakarotConfigSchema,
36
37
  TestGenerator: () => TestGenerator,
38
+ VitestRunner: () => VitestRunner,
37
39
  analyzeFile: () => analyzeFile,
40
+ buildCoverageSummaryPrompt: () => buildCoverageSummaryPrompt,
38
41
  buildTestFixPrompt: () => buildTestFixPrompt,
39
42
  buildTestGenerationPrompt: () => buildTestGenerationPrompt,
40
43
  createLLMProvider: () => createLLMProvider,
44
+ createTestRunner: () => createTestRunner,
41
45
  debug: () => debug,
46
+ detectPackageManager: () => detectPackageManager,
42
47
  error: () => error,
43
48
  extractTestTargets: () => extractTestTargets,
49
+ findProjectRoot: () => findProjectRoot,
44
50
  getChangedRanges: () => getChangedRanges,
51
+ getTestFilePath: () => getTestFilePath,
45
52
  info: () => info,
46
53
  initLogger: () => initLogger,
47
54
  loadConfig: () => loadConfig,
48
55
  parsePullRequestFiles: () => parsePullRequestFiles,
49
56
  parseTestCode: () => parseTestCode,
50
57
  progress: () => progress,
58
+ readCoverageReport: () => readCoverageReport,
59
+ runPullRequest: () => runPullRequest,
51
60
  success: () => success,
52
61
  validateTestCodeStructure: () => validateTestCodeStructure,
53
- warn: () => warn
62
+ warn: () => warn,
63
+ writeTestFiles: () => writeTestFiles
54
64
  });
55
65
  module.exports = __toCommonJS(src_exports);
56
66
 
@@ -59,12 +69,15 @@ var import_zod = require("zod");
59
69
  var KakarotConfigSchema = import_zod.z.object({
60
70
  apiKey: import_zod.z.string(),
61
71
  githubToken: import_zod.z.string().optional(),
72
+ githubOwner: import_zod.z.string().optional(),
73
+ githubRepo: import_zod.z.string().optional(),
62
74
  provider: import_zod.z.enum(["openai", "anthropic", "google"]).optional(),
63
75
  model: import_zod.z.string().optional(),
64
76
  maxTokens: import_zod.z.number().int().min(1).max(1e5).optional(),
65
77
  temperature: import_zod.z.number().min(0).max(2).optional(),
66
78
  fixTemperature: import_zod.z.number().min(0).max(2).optional(),
67
79
  maxFixAttempts: import_zod.z.number().int().min(0).max(5).default(3),
80
+ framework: import_zod.z.enum(["jest", "vitest"]),
68
81
  testLocation: import_zod.z.enum(["separate", "co-located"]).default("separate"),
69
82
  testDirectory: import_zod.z.string().default("__tests__"),
70
83
  testFilePattern: import_zod.z.string().default("*.test.ts"),
@@ -78,8 +91,8 @@ var KakarotConfigSchema = import_zod.z.object({
78
91
  });
79
92
 
80
93
  // src/utils/config-loader.ts
81
- var import_fs = require("fs");
82
- var import_path = require("path");
94
+ var import_cosmiconfig = require("cosmiconfig");
95
+ var import_find_up = require("find-up");
83
96
 
84
97
  // src/utils/logger.ts
85
98
  var debugMode = false;
@@ -134,108 +147,70 @@ function progress(step, total, message, ...args) {
134
147
  }
135
148
 
136
149
  // src/utils/config-loader.ts
137
- function findProjectRoot(startPath) {
138
- const start = startPath ?? process.cwd();
139
- let current = start;
140
- let previous = null;
141
- while (current !== previous) {
142
- if ((0, import_fs.existsSync)((0, import_path.join)(current, "package.json"))) {
143
- return current;
144
- }
145
- previous = current;
146
- current = (0, import_path.dirname)(current);
147
- }
148
- return start;
149
- }
150
- async function loadTypeScriptConfig(root) {
151
- const configPath = (0, import_path.join)(root, "kakarot.config.ts");
152
- if (!(0, import_fs.existsSync)(configPath)) {
153
- return null;
154
- }
155
- try {
156
- const configModule = await import(configPath);
157
- return configModule.default || configModule.config || null;
158
- } catch (err) {
159
- error(`Failed to load kakarot.config.ts: ${err instanceof Error ? err.message : String(err)}`);
160
- return null;
161
- }
162
- }
163
- async function loadJavaScriptConfig(root) {
164
- const configPath = (0, import_path.join)(root, ".kakarot-ci.config.js");
165
- if (!(0, import_fs.existsSync)(configPath)) {
166
- return null;
167
- }
168
- try {
169
- const configModule = await import(configPath);
170
- return configModule.default || configModule.config || null;
171
- } catch (err) {
172
- error(`Failed to load .kakarot-ci.config.js: ${err instanceof Error ? err.message : String(err)}`);
173
- return null;
174
- }
175
- }
176
- function loadJsonConfig(root) {
177
- const configPath = (0, import_path.join)(root, ".kakarot-ci.config.json");
178
- if (!(0, import_fs.existsSync)(configPath)) {
179
- return null;
180
- }
181
- try {
182
- const content = (0, import_fs.readFileSync)(configPath, "utf-8");
183
- return JSON.parse(content);
184
- } catch (err) {
185
- error(`Failed to load .kakarot-ci.config.json: ${err instanceof Error ? err.message : String(err)}`);
186
- return null;
187
- }
188
- }
189
- function loadPackageJsonConfig(root) {
190
- const packagePath = (0, import_path.join)(root, "package.json");
191
- if (!(0, import_fs.existsSync)(packagePath)) {
192
- return null;
193
- }
194
- try {
195
- const content = (0, import_fs.readFileSync)(packagePath, "utf-8");
196
- const pkg = JSON.parse(content);
197
- return pkg.kakarotCi || null;
198
- } catch (err) {
199
- error(`Failed to load package.json: ${err instanceof Error ? err.message : String(err)}`);
200
- return null;
201
- }
202
- }
203
- function mergeEnvConfig(config) {
204
- const merged = { ...config };
205
- if (!merged.apiKey && process.env.KAKAROT_API_KEY) {
206
- merged.apiKey = process.env.KAKAROT_API_KEY;
207
- }
208
- if (!merged.githubToken && process.env.GITHUB_TOKEN) {
209
- merged.githubToken = process.env.GITHUB_TOKEN;
150
+ async function findProjectRoot(startPath) {
151
+ const packageJsonPath = await (0, import_find_up.findUp)("package.json", {
152
+ cwd: startPath ?? process.cwd()
153
+ });
154
+ if (packageJsonPath) {
155
+ const { dirname: dirname2 } = await import("path");
156
+ return dirname2(packageJsonPath);
210
157
  }
211
- return merged;
158
+ return startPath ?? process.cwd();
212
159
  }
213
160
  async function loadConfig() {
214
- const projectRoot = findProjectRoot();
215
- let config = null;
216
- config = await loadTypeScriptConfig(projectRoot);
217
- if (config) {
218
- return KakarotConfigSchema.parse(mergeEnvConfig(config));
219
- }
220
- config = await loadJavaScriptConfig(projectRoot);
221
- if (config) {
222
- return KakarotConfigSchema.parse(mergeEnvConfig(config));
223
- }
224
- config = loadJsonConfig(projectRoot);
225
- if (config) {
226
- return KakarotConfigSchema.parse(mergeEnvConfig(config));
227
- }
228
- config = loadPackageJsonConfig(projectRoot);
229
- if (config) {
230
- return KakarotConfigSchema.parse(mergeEnvConfig(config));
231
- }
232
- const envConfig = mergeEnvConfig({});
161
+ const explorer = (0, import_cosmiconfig.cosmiconfig)("kakarot", {
162
+ searchPlaces: [
163
+ "kakarot.config.ts",
164
+ "kakarot.config.js",
165
+ ".kakarot-ci.config.ts",
166
+ ".kakarot-ci.config.js",
167
+ ".kakarot-ci.config.json",
168
+ "package.json"
169
+ ],
170
+ loaders: {
171
+ ".ts": async (filepath) => {
172
+ try {
173
+ const configModule = await import(filepath);
174
+ return configModule.default || configModule.config || null;
175
+ } catch (err) {
176
+ error(`Failed to load TypeScript config: ${err instanceof Error ? err.message : String(err)}`);
177
+ return null;
178
+ }
179
+ }
180
+ }
181
+ });
233
182
  try {
234
- return KakarotConfigSchema.parse(envConfig);
183
+ const result = await explorer.search();
184
+ let config = {};
185
+ if (result?.config) {
186
+ config = result.config;
187
+ }
188
+ if (!result || result.filepath?.endsWith("package.json")) {
189
+ const packageJsonPath = await (0, import_find_up.findUp)("package.json");
190
+ if (packageJsonPath) {
191
+ const { readFileSync: readFileSync2 } = await import("fs");
192
+ try {
193
+ const pkg = JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
194
+ if (pkg.kakarotCi) {
195
+ config = { ...config, ...pkg.kakarotCi };
196
+ }
197
+ } catch {
198
+ }
199
+ }
200
+ }
201
+ if (!config.apiKey && process.env.KAKAROT_API_KEY) {
202
+ config.apiKey = process.env.KAKAROT_API_KEY;
203
+ }
204
+ if (!config.githubToken && process.env.GITHUB_TOKEN) {
205
+ config.githubToken = process.env.GITHUB_TOKEN;
206
+ }
207
+ return KakarotConfigSchema.parse(config);
235
208
  } catch (err) {
236
- error(
237
- "Missing required apiKey. Provide it via:\n - Config file (kakarot.config.ts, .kakarot-ci.config.js/json, or package.json)\n - Environment variable: KAKAROT_API_KEY"
238
- );
209
+ if (err instanceof Error && err.message.includes("apiKey")) {
210
+ error(
211
+ "Missing required apiKey. Provide it via:\n - Config file (kakarot.config.ts, .kakarot-ci.config.js/json, or package.json)\n - Environment variable: KAKAROT_API_KEY"
212
+ );
213
+ }
239
214
  throw err;
240
215
  }
241
216
  }
@@ -841,6 +816,30 @@ async function extractTestTargets(files, githubClient, prHeadRef, config) {
841
816
  return targets;
842
817
  }
843
818
 
819
+ // src/utils/test-file-path.ts
820
+ function getTestFilePath(target, config) {
821
+ const sourcePath = target.filePath;
822
+ const lastSlashIndex = sourcePath.lastIndexOf("/");
823
+ const dir = lastSlashIndex >= 0 ? sourcePath.substring(0, lastSlashIndex) : "";
824
+ const baseName = sourcePath.substring(lastSlashIndex + 1).replace(/\.(ts|tsx|js|jsx)$/, "");
825
+ let ext;
826
+ if (sourcePath.endsWith(".tsx"))
827
+ ext = "tsx";
828
+ else if (sourcePath.endsWith(".jsx"))
829
+ ext = "jsx";
830
+ else if (sourcePath.endsWith(".ts"))
831
+ ext = "ts";
832
+ else
833
+ ext = "js";
834
+ const testExt = ext === "tsx" || ext === "ts" ? "ts" : "js";
835
+ if (config.testLocation === "co-located") {
836
+ return dir ? `${dir}/${baseName}.test.${testExt}` : `${baseName}.test.${testExt}`;
837
+ } else {
838
+ const testFileName = config.testFilePattern.replace("*", baseName);
839
+ return `${config.testDirectory}/${testFileName}`;
840
+ }
841
+ }
842
+
844
843
  // src/llm/providers/base.ts
845
844
  var BaseLLMProvider = class {
846
845
  constructor(apiKey, model, defaultOptions) {
@@ -1412,28 +1411,791 @@ var TestGenerator = class {
1412
1411
  throw err;
1413
1412
  }
1414
1413
  }
1414
+ /**
1415
+ * Generate a human-readable coverage summary
1416
+ */
1417
+ async generateCoverageSummary(messages) {
1418
+ try {
1419
+ const response = await this.provider.generate(messages, {
1420
+ temperature: 0.3,
1421
+ maxTokens: 500
1422
+ });
1423
+ return response.content;
1424
+ } catch (err) {
1425
+ error(`Failed to generate coverage summary: ${err instanceof Error ? err.message : String(err)}`);
1426
+ throw err;
1427
+ }
1428
+ }
1415
1429
  };
1430
+
1431
+ // src/utils/package-manager-detector.ts
1432
+ var import_fs = require("fs");
1433
+ var import_path = require("path");
1434
+ function detectPackageManager(projectRoot) {
1435
+ if ((0, import_fs.existsSync)((0, import_path.join)(projectRoot, "pnpm-lock.yaml"))) {
1436
+ return "pnpm";
1437
+ }
1438
+ if ((0, import_fs.existsSync)((0, import_path.join)(projectRoot, "yarn.lock"))) {
1439
+ return "yarn";
1440
+ }
1441
+ if ((0, import_fs.existsSync)((0, import_path.join)(projectRoot, "package-lock.json"))) {
1442
+ return "npm";
1443
+ }
1444
+ return "npm";
1445
+ }
1446
+
1447
+ // src/utils/test-runner/jest-runner.ts
1448
+ var import_child_process = require("child_process");
1449
+ var import_util = require("util");
1450
+ var execAsync = (0, import_util.promisify)(import_child_process.exec);
1451
+ var JestRunner = class {
1452
+ async runTests(options) {
1453
+ const { testFiles, packageManager, projectRoot, coverage } = options;
1454
+ debug(`Running Jest tests for ${testFiles.length} file(s)`);
1455
+ const testFilesArg = testFiles.map((f) => `"${f}"`).join(" ");
1456
+ const coverageFlag = coverage ? "--coverage --coverageReporters=json" : "--no-coverage";
1457
+ const cmd = `${packageManager} test -- --json ${coverageFlag} ${testFilesArg}`;
1458
+ try {
1459
+ const { stdout, stderr } = await execAsync(cmd, {
1460
+ cwd: projectRoot,
1461
+ maxBuffer: 10 * 1024 * 1024
1462
+ // 10MB
1463
+ });
1464
+ if (stderr && !stderr.includes("PASS") && !stderr.includes("FAIL")) {
1465
+ debug(`Jest stderr: ${stderr}`);
1466
+ }
1467
+ const result = JSON.parse(stdout);
1468
+ return testFiles.map((testFile, index) => {
1469
+ const testResult = result.testResults[index] || result.testResults[0];
1470
+ const failures = [];
1471
+ if (testResult) {
1472
+ for (const assertion of testResult.assertionResults) {
1473
+ if (assertion.status === "failed" && assertion.failureMessages.length > 0) {
1474
+ const failureMessage = assertion.failureMessages[0];
1475
+ failures.push({
1476
+ testName: assertion.title,
1477
+ message: failureMessage,
1478
+ stack: failureMessage
1479
+ });
1480
+ }
1481
+ }
1482
+ }
1483
+ return {
1484
+ success: result.numFailedTests === 0,
1485
+ testFile,
1486
+ passed: result.numPassedTests,
1487
+ failed: result.numFailedTests,
1488
+ total: result.numTotalTests,
1489
+ duration: 0,
1490
+ // Jest JSON doesn't include duration per file
1491
+ failures
1492
+ };
1493
+ });
1494
+ } catch (err) {
1495
+ if (err && typeof err === "object" && "stdout" in err) {
1496
+ try {
1497
+ const result = JSON.parse(err.stdout);
1498
+ return testFiles.map((testFile) => {
1499
+ const failures = [];
1500
+ for (const testResult of result.testResults) {
1501
+ for (const assertion of testResult.assertionResults) {
1502
+ if (assertion.status === "failed" && assertion.failureMessages.length > 0) {
1503
+ failures.push({
1504
+ testName: assertion.title,
1505
+ message: assertion.failureMessages[0],
1506
+ stack: assertion.failureMessages[0]
1507
+ });
1508
+ }
1509
+ }
1510
+ }
1511
+ return {
1512
+ success: result.numFailedTests === 0,
1513
+ testFile,
1514
+ passed: result.numPassedTests,
1515
+ failed: result.numFailedTests,
1516
+ total: result.numTotalTests,
1517
+ duration: 0,
1518
+ failures
1519
+ };
1520
+ });
1521
+ } catch (parseErr) {
1522
+ error(`Failed to parse Jest output: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`);
1523
+ throw err;
1524
+ }
1525
+ }
1526
+ error(`Jest test execution failed: ${err instanceof Error ? err.message : String(err)}`);
1527
+ throw err;
1528
+ }
1529
+ }
1530
+ };
1531
+
1532
+ // src/utils/test-runner/vitest-runner.ts
1533
+ var import_child_process2 = require("child_process");
1534
+ var import_util2 = require("util");
1535
+ var execAsync2 = (0, import_util2.promisify)(import_child_process2.exec);
1536
+ var VitestRunner = class {
1537
+ async runTests(options) {
1538
+ const { testFiles, packageManager, projectRoot, coverage } = options;
1539
+ debug(`Running Vitest tests for ${testFiles.length} file(s)`);
1540
+ const testFilesArg = testFiles.map((f) => `"${f}"`).join(" ");
1541
+ const coverageFlag = coverage ? "--coverage" : "";
1542
+ const cmd = `${packageManager} test -- --reporter=json ${coverageFlag} ${testFilesArg}`;
1543
+ try {
1544
+ const { stdout, stderr } = await execAsync2(cmd, {
1545
+ cwd: projectRoot,
1546
+ maxBuffer: 10 * 1024 * 1024
1547
+ // 10MB
1548
+ });
1549
+ if (stderr && !stderr.includes("PASS") && !stderr.includes("FAIL")) {
1550
+ debug(`Vitest stderr: ${stderr}`);
1551
+ }
1552
+ const lines = stdout.trim().split("\n");
1553
+ const jsonLine = lines[lines.length - 1];
1554
+ if (!jsonLine || !jsonLine.startsWith("{")) {
1555
+ throw new Error("No valid JSON output from Vitest");
1556
+ }
1557
+ const result = JSON.parse(jsonLine);
1558
+ return testFiles.map((testFile, index) => {
1559
+ const testResult = result.testResults[index] || result.testResults[0];
1560
+ const failures = [];
1561
+ if (testResult) {
1562
+ for (const assertion of testResult.assertionResults) {
1563
+ if (assertion.status === "failed" && assertion.failureMessages.length > 0) {
1564
+ const failureMessage = assertion.failureMessages[0];
1565
+ failures.push({
1566
+ testName: assertion.title,
1567
+ message: failureMessage,
1568
+ stack: failureMessage
1569
+ });
1570
+ }
1571
+ }
1572
+ }
1573
+ return {
1574
+ success: result.numFailedTests === 0,
1575
+ testFile,
1576
+ passed: result.numPassedTests,
1577
+ failed: result.numFailedTests,
1578
+ total: result.numTotalTests,
1579
+ duration: 0,
1580
+ // Vitest JSON doesn't include duration per file
1581
+ failures
1582
+ };
1583
+ });
1584
+ } catch (err) {
1585
+ if (err && typeof err === "object" && "stdout" in err) {
1586
+ try {
1587
+ const lines = err.stdout.trim().split("\n");
1588
+ const jsonLine = lines[lines.length - 1];
1589
+ if (jsonLine && jsonLine.startsWith("{")) {
1590
+ const result = JSON.parse(jsonLine);
1591
+ return testFiles.map((testFile) => {
1592
+ const failures = [];
1593
+ for (const testResult of result.testResults) {
1594
+ for (const assertion of testResult.assertionResults) {
1595
+ if (assertion.status === "failed" && assertion.failureMessages.length > 0) {
1596
+ failures.push({
1597
+ testName: assertion.title,
1598
+ message: assertion.failureMessages[0],
1599
+ stack: assertion.failureMessages[0]
1600
+ });
1601
+ }
1602
+ }
1603
+ }
1604
+ return {
1605
+ success: result.numFailedTests === 0,
1606
+ testFile,
1607
+ passed: result.numPassedTests,
1608
+ failed: result.numFailedTests,
1609
+ total: result.numTotalTests,
1610
+ duration: 0,
1611
+ failures
1612
+ };
1613
+ });
1614
+ }
1615
+ } catch (parseErr) {
1616
+ error(`Failed to parse Vitest output: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`);
1617
+ throw err;
1618
+ }
1619
+ }
1620
+ error(`Vitest test execution failed: ${err instanceof Error ? err.message : String(err)}`);
1621
+ throw err;
1622
+ }
1623
+ }
1624
+ };
1625
+
1626
+ // src/utils/test-runner/factory.ts
1627
+ function createTestRunner(framework) {
1628
+ switch (framework) {
1629
+ case "jest":
1630
+ return new JestRunner();
1631
+ case "vitest":
1632
+ return new VitestRunner();
1633
+ default:
1634
+ throw new Error(`Unsupported test framework: ${framework}`);
1635
+ }
1636
+ }
1637
+
1638
+ // src/utils/test-file-writer.ts
1639
+ var import_fs2 = require("fs");
1640
+ var import_path2 = require("path");
1641
+ function writeTestFiles(testFiles, projectRoot) {
1642
+ const writtenPaths = [];
1643
+ for (const [relativePath, fileData] of testFiles.entries()) {
1644
+ const fullPath = (0, import_path2.join)(projectRoot, relativePath);
1645
+ const dir = (0, import_path2.dirname)(fullPath);
1646
+ if (!(0, import_fs2.existsSync)(dir)) {
1647
+ (0, import_fs2.mkdirSync)(dir, { recursive: true });
1648
+ debug(`Created directory: ${dir}`);
1649
+ }
1650
+ (0, import_fs2.writeFileSync)(fullPath, fileData.content, "utf-8");
1651
+ writtenPaths.push(relativePath);
1652
+ debug(`Wrote test file: ${relativePath}`);
1653
+ }
1654
+ return writtenPaths;
1655
+ }
1656
+
1657
+ // src/utils/coverage-reader.ts
1658
+ var import_fs3 = require("fs");
1659
+ var import_path3 = require("path");
1660
+ function parseJestCoverage(data) {
1661
+ const files = [];
1662
+ let totalStatements = 0;
1663
+ let coveredStatements = 0;
1664
+ let totalBranches = 0;
1665
+ let coveredBranches = 0;
1666
+ let totalFunctions = 0;
1667
+ let coveredFunctions = 0;
1668
+ let totalLines = 0;
1669
+ let coveredLines = 0;
1670
+ for (const [filePath, coverage] of Object.entries(data)) {
1671
+ const statementCounts = Object.values(coverage.statements);
1672
+ const branchCounts = Object.values(coverage.branches);
1673
+ const functionCounts = Object.values(coverage.functions);
1674
+ const lineCounts = Object.values(coverage.lines);
1675
+ const fileStatements = {
1676
+ total: statementCounts.length,
1677
+ covered: statementCounts.filter((c) => c > 0).length,
1678
+ percentage: statementCounts.length > 0 ? statementCounts.filter((c) => c > 0).length / statementCounts.length * 100 : 100
1679
+ };
1680
+ const fileBranches = {
1681
+ total: branchCounts.length,
1682
+ covered: branchCounts.filter((c) => c > 0).length,
1683
+ percentage: branchCounts.length > 0 ? branchCounts.filter((c) => c > 0).length / branchCounts.length * 100 : 100
1684
+ };
1685
+ const fileFunctions = {
1686
+ total: functionCounts.length,
1687
+ covered: functionCounts.filter((c) => c > 0).length,
1688
+ percentage: functionCounts.length > 0 ? functionCounts.filter((c) => c > 0).length / functionCounts.length * 100 : 100
1689
+ };
1690
+ const fileLines = {
1691
+ total: lineCounts.length,
1692
+ covered: lineCounts.filter((c) => c > 0).length,
1693
+ percentage: lineCounts.length > 0 ? lineCounts.filter((c) => c > 0).length / lineCounts.length * 100 : 100
1694
+ };
1695
+ files.push({
1696
+ path: filePath,
1697
+ metrics: {
1698
+ statements: fileStatements,
1699
+ branches: fileBranches,
1700
+ functions: fileFunctions,
1701
+ lines: fileLines
1702
+ }
1703
+ });
1704
+ totalStatements += fileStatements.total;
1705
+ coveredStatements += fileStatements.covered;
1706
+ totalBranches += fileBranches.total;
1707
+ coveredBranches += fileBranches.covered;
1708
+ totalFunctions += fileFunctions.total;
1709
+ coveredFunctions += fileFunctions.covered;
1710
+ totalLines += fileLines.total;
1711
+ coveredLines += fileLines.covered;
1712
+ }
1713
+ return {
1714
+ total: {
1715
+ statements: {
1716
+ total: totalStatements,
1717
+ covered: coveredStatements,
1718
+ percentage: totalStatements > 0 ? coveredStatements / totalStatements * 100 : 100
1719
+ },
1720
+ branches: {
1721
+ total: totalBranches,
1722
+ covered: coveredBranches,
1723
+ percentage: totalBranches > 0 ? coveredBranches / totalBranches * 100 : 100
1724
+ },
1725
+ functions: {
1726
+ total: totalFunctions,
1727
+ covered: coveredFunctions,
1728
+ percentage: totalFunctions > 0 ? coveredFunctions / totalFunctions * 100 : 100
1729
+ },
1730
+ lines: {
1731
+ total: totalLines,
1732
+ covered: coveredLines,
1733
+ percentage: totalLines > 0 ? coveredLines / totalLines * 100 : 100
1734
+ }
1735
+ },
1736
+ files
1737
+ };
1738
+ }
1739
+ function parseVitestCoverage(data) {
1740
+ return parseJestCoverage(data);
1741
+ }
1742
+ function readCoverageReport(projectRoot, framework) {
1743
+ const coveragePath = (0, import_path3.join)(projectRoot, "coverage", "coverage-final.json");
1744
+ if (!(0, import_fs3.existsSync)(coveragePath)) {
1745
+ debug(`Coverage file not found at ${coveragePath}`);
1746
+ return null;
1747
+ }
1748
+ try {
1749
+ const content = (0, import_fs3.readFileSync)(coveragePath, "utf-8");
1750
+ const data = JSON.parse(content);
1751
+ if (framework === "jest") {
1752
+ return parseJestCoverage(data);
1753
+ } else {
1754
+ return parseVitestCoverage(data);
1755
+ }
1756
+ } catch (err) {
1757
+ warn(`Failed to read coverage report: ${err instanceof Error ? err.message : String(err)}`);
1758
+ return null;
1759
+ }
1760
+ }
1761
+
1762
+ // src/llm/prompts/coverage-summary.ts
1763
+ function buildCoverageSummaryPrompt(coverageReport, testResults, functionsTested, coverageDelta) {
1764
+ const systemPrompt = `You are a technical writer specializing in test coverage reports. Your task is to generate a clear, concise, and actionable summary of test coverage metrics.
1765
+
1766
+ Requirements:
1767
+ 1. Use clear, professional language
1768
+ 2. Highlight key metrics (lines, branches, functions, statements)
1769
+ 3. Mention which functions were tested
1770
+ 4. If coverage delta is provided, explain the change
1771
+ 5. Provide actionable insights or recommendations
1772
+ 6. Format as markdown suitable for GitHub PR comments
1773
+ 7. Keep it concise (2-3 paragraphs max)`;
1774
+ const totalTests = testResults.reduce((sum, r) => sum + r.total, 0);
1775
+ const passedTests = testResults.reduce((sum, r) => sum + r.passed, 0);
1776
+ const failedTests = testResults.reduce((sum, r) => sum + r.failed, 0);
1777
+ const userPrompt = `Generate a human-readable test coverage summary with the following information:
1778
+
1779
+ **Coverage Metrics:**
1780
+ - Lines: ${coverageReport.total.lines.percentage.toFixed(1)}% (${coverageReport.total.lines.covered}/${coverageReport.total.lines.total})
1781
+ - Branches: ${coverageReport.total.branches.percentage.toFixed(1)}% (${coverageReport.total.branches.covered}/${coverageReport.total.branches.total})
1782
+ - Functions: ${coverageReport.total.functions.percentage.toFixed(1)}% (${coverageReport.total.functions.covered}/${coverageReport.total.functions.total})
1783
+ - Statements: ${coverageReport.total.statements.percentage.toFixed(1)}% (${coverageReport.total.statements.covered}/${coverageReport.total.statements.total})
1784
+
1785
+ **Test Results:**
1786
+ - Total tests: ${totalTests}
1787
+ - Passed: ${passedTests}
1788
+ - Failed: ${failedTests}
1789
+
1790
+ **Functions Tested:**
1791
+ ${functionsTested.length > 0 ? functionsTested.map((f) => `- ${f}`).join("\n") : "None"}
1792
+
1793
+ ${coverageDelta ? `**Coverage Changes:**
1794
+ - Lines: ${coverageDelta.lines > 0 ? "+" : ""}${coverageDelta.lines.toFixed(1)}%
1795
+ - Branches: ${coverageDelta.branches > 0 ? "+" : ""}${coverageDelta.branches.toFixed(1)}%
1796
+ - Functions: ${coverageDelta.functions > 0 ? "+" : ""}${coverageDelta.functions.toFixed(1)}%
1797
+ - Statements: ${coverageDelta.statements > 0 ? "+" : ""}${coverageDelta.statements.toFixed(1)}%
1798
+ ` : ""}
1799
+
1800
+ Generate a concise, professional summary that explains what was tested and the coverage achieved.`;
1801
+ return [
1802
+ { role: "system", content: systemPrompt },
1803
+ { role: "user", content: userPrompt }
1804
+ ];
1805
+ }
1806
+
1807
+ // src/core/orchestrator.ts
1808
+ async function runPullRequest(context) {
1809
+ const config = await loadConfig();
1810
+ initLogger(config);
1811
+ info(`Processing PR #${context.prNumber} for ${context.owner}/${context.repo}`);
1812
+ const githubToken = context.githubToken || config.githubToken;
1813
+ if (!githubToken) {
1814
+ throw new Error("GitHub token is required. Provide it via config.githubToken or context.githubToken");
1815
+ }
1816
+ const githubClient = new GitHubClient({
1817
+ token: githubToken,
1818
+ owner: context.owner,
1819
+ repo: context.repo
1820
+ });
1821
+ const pr = await githubClient.getPullRequest(context.prNumber);
1822
+ if (pr.state !== "open") {
1823
+ warn(`PR #${context.prNumber} is ${pr.state}, skipping test generation`);
1824
+ return {
1825
+ targetsProcessed: 0,
1826
+ testsGenerated: 0,
1827
+ testsFailed: 0,
1828
+ testFiles: [],
1829
+ errors: []
1830
+ };
1831
+ }
1832
+ info(`PR: ${pr.title} (${pr.head.ref} -> ${pr.base.ref})`);
1833
+ const prFiles = await githubClient.listPullRequestFiles(context.prNumber);
1834
+ if (prFiles.length === 0) {
1835
+ info("No files changed in this PR");
1836
+ return {
1837
+ targetsProcessed: 0,
1838
+ testsGenerated: 0,
1839
+ testsFailed: 0,
1840
+ testFiles: [],
1841
+ errors: []
1842
+ };
1843
+ }
1844
+ info(`Found ${prFiles.length} file(s) changed in PR`);
1845
+ const prHeadRef = pr.head.sha;
1846
+ const targets = await extractTestTargets(
1847
+ prFiles,
1848
+ githubClient,
1849
+ prHeadRef,
1850
+ config
1851
+ );
1852
+ if (targets.length === 0) {
1853
+ info("No test targets found in changed files");
1854
+ return {
1855
+ targetsProcessed: 0,
1856
+ testsGenerated: 0,
1857
+ testsFailed: 0,
1858
+ testFiles: [],
1859
+ errors: []
1860
+ };
1861
+ }
1862
+ const limitedTargets = targets.slice(0, config.maxTestsPerPR);
1863
+ if (targets.length > limitedTargets.length) {
1864
+ warn(`Limiting to ${config.maxTestsPerPR} test targets (found ${targets.length})`);
1865
+ }
1866
+ info(`Found ${limitedTargets.length} test target(s)`);
1867
+ const framework = config.framework;
1868
+ info(`Using test framework: ${framework}`);
1869
+ const testGenerator = new TestGenerator({
1870
+ apiKey: config.apiKey,
1871
+ provider: config.provider,
1872
+ model: config.model,
1873
+ maxTokens: config.maxTokens,
1874
+ maxFixAttempts: config.maxFixAttempts,
1875
+ temperature: config.temperature,
1876
+ fixTemperature: config.fixTemperature
1877
+ });
1878
+ let testFiles = /* @__PURE__ */ new Map();
1879
+ const errors = [];
1880
+ let testsGenerated = 0;
1881
+ let testsFailed = 0;
1882
+ for (let i = 0; i < limitedTargets.length; i++) {
1883
+ const target = limitedTargets[i];
1884
+ progress(i + 1, limitedTargets.length, `Generating test for ${target.functionName}`);
1885
+ try {
1886
+ const testFilePath = getTestFilePath(target, config);
1887
+ let existingTestFile;
1888
+ const testFileExists = await githubClient.fileExists(prHeadRef, testFilePath);
1889
+ if (testFileExists) {
1890
+ try {
1891
+ const fileContents = await githubClient.getFileContents(prHeadRef, testFilePath);
1892
+ existingTestFile = fileContents.content;
1893
+ debug(`Found existing test file at ${testFilePath}`);
1894
+ } catch (err) {
1895
+ debug(`Could not fetch existing test file ${testFilePath}: ${err instanceof Error ? err.message : String(err)}`);
1896
+ }
1897
+ } else {
1898
+ debug(`No existing test file at ${testFilePath}, will create new file`);
1899
+ }
1900
+ const result = await testGenerator.generateTest({
1901
+ target: {
1902
+ filePath: target.filePath,
1903
+ functionName: target.functionName,
1904
+ functionType: target.functionType,
1905
+ code: target.code,
1906
+ context: target.context
1907
+ },
1908
+ framework,
1909
+ existingTestFile
1910
+ });
1911
+ if (!testFiles.has(testFilePath)) {
1912
+ const baseContent = existingTestFile || "";
1913
+ testFiles.set(testFilePath, { content: baseContent, targets: [] });
1914
+ }
1915
+ const fileData = testFiles.get(testFilePath);
1916
+ if (fileData.content) {
1917
+ fileData.content += "\n\n" + result.testCode;
1918
+ } else {
1919
+ fileData.content = result.testCode;
1920
+ }
1921
+ fileData.targets.push(target.functionName);
1922
+ testsGenerated++;
1923
+ info(`\u2713 Generated test for ${target.functionName}`);
1924
+ } catch (err) {
1925
+ const errorMessage = err instanceof Error ? err.message : String(err);
1926
+ error(`\u2717 Failed to generate test for ${target.functionName}: ${errorMessage}`);
1927
+ errors.push({
1928
+ target: `${target.filePath}:${target.functionName}`,
1929
+ error: errorMessage
1930
+ });
1931
+ testsFailed++;
1932
+ }
1933
+ }
1934
+ const projectRoot = await findProjectRoot();
1935
+ const packageManager = detectPackageManager(projectRoot);
1936
+ info(`Detected package manager: ${packageManager}`);
1937
+ if (testFiles.size > 0) {
1938
+ const writtenPaths = writeTestFiles(testFiles, projectRoot);
1939
+ info(`Wrote ${writtenPaths.length} test file(s) to disk`);
1940
+ const testRunner = createTestRunner(framework);
1941
+ const finalTestFiles = await runTestsAndFix(
1942
+ testRunner,
1943
+ testFiles,
1944
+ writtenPaths,
1945
+ framework,
1946
+ packageManager,
1947
+ projectRoot,
1948
+ testGenerator,
1949
+ config.maxFixAttempts
1950
+ );
1951
+ testFiles = finalTestFiles;
1952
+ }
1953
+ const summary = {
1954
+ targetsProcessed: limitedTargets.length,
1955
+ testsGenerated,
1956
+ testsFailed,
1957
+ testFiles: Array.from(testFiles.entries()).map(([path, data]) => ({
1958
+ path,
1959
+ targets: data.targets
1960
+ })),
1961
+ errors
1962
+ };
1963
+ if (testFiles.size > 0) {
1964
+ const testRunner = createTestRunner(framework);
1965
+ const writtenPaths = Array.from(testFiles.keys());
1966
+ info("Running tests with coverage...");
1967
+ const finalTestResults = await testRunner.runTests({
1968
+ testFiles: writtenPaths,
1969
+ framework,
1970
+ packageManager,
1971
+ projectRoot,
1972
+ coverage: true
1973
+ });
1974
+ const coverageReport = readCoverageReport(projectRoot, framework);
1975
+ if (coverageReport) {
1976
+ info(`Coverage collected: ${coverageReport.total.lines.percentage.toFixed(1)}% lines`);
1977
+ summary.coverageReport = coverageReport;
1978
+ summary.testResults = finalTestResults;
1979
+ } else {
1980
+ warn("Could not read coverage report");
1981
+ }
1982
+ }
1983
+ if (config.enableAutoCommit && testFiles.size > 0) {
1984
+ await commitTests(
1985
+ githubClient,
1986
+ pr,
1987
+ Array.from(testFiles.entries()).map(([path, data]) => ({
1988
+ path,
1989
+ content: data.content
1990
+ })),
1991
+ config,
1992
+ summary
1993
+ );
1994
+ }
1995
+ if (config.enablePRComments) {
1996
+ await postPRComment(githubClient, context.prNumber, summary, framework, testGenerator);
1997
+ }
1998
+ success(`Completed: ${testsGenerated} test(s) generated, ${testsFailed} failed`);
1999
+ return summary;
2000
+ }
2001
+ async function runTestsAndFix(testRunner, testFiles, testFilePaths, framework, packageManager, projectRoot, testGenerator, maxFixAttempts) {
2002
+ const currentTestFiles = new Map(testFiles);
2003
+ let attempt = 0;
2004
+ while (attempt < maxFixAttempts) {
2005
+ info(`Running tests (attempt ${attempt + 1}/${maxFixAttempts})`);
2006
+ const results = await testRunner.runTests({
2007
+ testFiles: testFilePaths,
2008
+ framework,
2009
+ packageManager,
2010
+ projectRoot,
2011
+ coverage: false
2012
+ });
2013
+ const allPassed = results.every((r) => r.success);
2014
+ if (allPassed) {
2015
+ success(`All tests passed on attempt ${attempt + 1}`);
2016
+ return currentTestFiles;
2017
+ }
2018
+ const failures = [];
2019
+ for (const result of results) {
2020
+ if (!result.success && result.failures.length > 0) {
2021
+ failures.push({ testFile: result.testFile, result });
2022
+ }
2023
+ }
2024
+ info(`Found ${failures.length} failing test file(s), attempting fixes...`);
2025
+ let fixedAny = false;
2026
+ for (const { testFile, result } of failures) {
2027
+ const testFileContent = currentTestFiles.get(testFile)?.content;
2028
+ if (!testFileContent) {
2029
+ warn(`Could not find content for test file: ${testFile}`);
2030
+ continue;
2031
+ }
2032
+ const firstFailure = result.failures[0];
2033
+ if (!firstFailure)
2034
+ continue;
2035
+ try {
2036
+ const fixedResult = await testGenerator.fixTest({
2037
+ testCode: testFileContent,
2038
+ errorMessage: firstFailure.message,
2039
+ testOutput: firstFailure.stack,
2040
+ originalCode: "",
2041
+ // We'd need to pass this from the target
2042
+ framework,
2043
+ attempt: attempt + 1,
2044
+ maxAttempts: maxFixAttempts
2045
+ });
2046
+ currentTestFiles.set(testFile, {
2047
+ content: fixedResult.testCode,
2048
+ targets: currentTestFiles.get(testFile)?.targets || []
2049
+ });
2050
+ const { writeFileSync: writeFileSync2 } = await import("fs");
2051
+ const { join: join4 } = await import("path");
2052
+ writeFileSync2(join4(projectRoot, testFile), fixedResult.testCode, "utf-8");
2053
+ fixedAny = true;
2054
+ info(`\u2713 Fixed test file: ${testFile}`);
2055
+ } catch (err) {
2056
+ error(`Failed to fix test file ${testFile}: ${err instanceof Error ? err.message : String(err)}`);
2057
+ }
2058
+ }
2059
+ if (!fixedAny) {
2060
+ warn(`Could not fix any failing tests on attempt ${attempt + 1}`);
2061
+ break;
2062
+ }
2063
+ attempt++;
2064
+ }
2065
+ if (attempt >= maxFixAttempts) {
2066
+ warn(`Reached maximum fix attempts (${maxFixAttempts}), some tests may still be failing`);
2067
+ }
2068
+ return currentTestFiles;
2069
+ }
2070
+ async function commitTests(githubClient, pr, testFiles, config, summary) {
2071
+ info(`Committing ${testFiles.length} test file(s)`);
2072
+ try {
2073
+ if (config.commitStrategy === "branch-pr") {
2074
+ const branchName = `kakarot-ci/tests-pr-${pr.number}`;
2075
+ const baseSha = await githubClient.createBranch(branchName, pr.head.ref);
2076
+ await githubClient.commitFiles({
2077
+ files: testFiles.map((file) => ({
2078
+ path: file.path,
2079
+ content: file.content
2080
+ })),
2081
+ message: `test: add unit tests for PR #${pr.number}
2082
+
2083
+ Generated ${summary.testsGenerated} test(s) for ${summary.targetsProcessed} function(s)`,
2084
+ branch: branchName,
2085
+ baseSha
2086
+ });
2087
+ const testPR = await githubClient.createPullRequest(
2088
+ `test: Add unit tests for PR #${pr.number}`,
2089
+ `This PR contains automatically generated unit tests for PR #${pr.number}.
2090
+
2091
+ - ${summary.testsGenerated} test(s) generated
2092
+ - ${summary.targetsProcessed} function(s) tested
2093
+ - ${testFiles.length} test file(s) created/updated`,
2094
+ branchName,
2095
+ pr.head.ref
2096
+ );
2097
+ success(`Created PR #${testPR.number} with generated tests`);
2098
+ } else {
2099
+ await githubClient.commitFiles({
2100
+ files: testFiles.map((file) => ({
2101
+ path: file.path,
2102
+ content: file.content
2103
+ })),
2104
+ message: `test: add unit tests
2105
+
2106
+ Generated ${summary.testsGenerated} test(s) for ${summary.targetsProcessed} function(s)`,
2107
+ branch: pr.head.ref,
2108
+ baseSha: pr.head.sha
2109
+ });
2110
+ success(`Committed ${testFiles.length} test file(s) to ${pr.head.ref}`);
2111
+ }
2112
+ } catch (err) {
2113
+ error(`Failed to commit tests: ${err instanceof Error ? err.message : String(err)}`);
2114
+ throw err;
2115
+ }
2116
+ }
2117
+ async function postPRComment(githubClient, prNumber, summary, framework, testGenerator) {
2118
+ let comment = `## \u{1F9EA} Kakarot CI Test Generation Summary
2119
+
2120
+ **Framework:** ${framework}
2121
+ **Targets Processed:** ${summary.targetsProcessed}
2122
+ **Tests Generated:** ${summary.testsGenerated}
2123
+ **Failures:** ${summary.testsFailed}
2124
+
2125
+ ### Test Files
2126
+ ${summary.testFiles.length > 0 ? summary.testFiles.map((f) => `- \`${f.path}\` (${f.targets.length} test(s))`).join("\n") : "No test files generated"}
2127
+
2128
+ ${summary.errors.length > 0 ? `### Errors
2129
+ ${summary.errors.map((e) => `- \`${e.target}\`: ${e.error}`).join("\n")}` : ""}`;
2130
+ if (summary.coverageReport && summary.testResults) {
2131
+ try {
2132
+ const functionsTested = summary.testFiles.flatMap((f) => f.targets);
2133
+ const messages = buildCoverageSummaryPrompt(
2134
+ summary.coverageReport,
2135
+ summary.testResults,
2136
+ functionsTested
2137
+ );
2138
+ const coverageSummary = await testGenerator.generateCoverageSummary(messages);
2139
+ comment += `
2140
+
2141
+ ## \u{1F4CA} Coverage Summary
2142
+
2143
+ ${coverageSummary}`;
2144
+ } catch (err) {
2145
+ warn(`Failed to generate coverage summary: ${err instanceof Error ? err.message : String(err)}`);
2146
+ const cov = summary.coverageReport.total;
2147
+ comment += `
2148
+
2149
+ ## \u{1F4CA} Coverage Summary
2150
+
2151
+ - **Lines:** ${cov.lines.percentage.toFixed(1)}% (${cov.lines.covered}/${cov.lines.total})
2152
+ - **Branches:** ${cov.branches.percentage.toFixed(1)}% (${cov.branches.covered}/${cov.branches.total})
2153
+ - **Functions:** ${cov.functions.percentage.toFixed(1)}% (${cov.functions.covered}/${cov.functions.total})
2154
+ - **Statements:** ${cov.statements.percentage.toFixed(1)}% (${cov.statements.covered}/${cov.statements.total})`;
2155
+ }
2156
+ }
2157
+ comment += `
2158
+
2159
+ ---
2160
+ *Generated by [Kakarot CI](https://github.com/kakarot-ci)*`;
2161
+ try {
2162
+ await githubClient.commentPR(prNumber, comment);
2163
+ info("Posted PR comment with test generation summary");
2164
+ } catch (err) {
2165
+ warn(`Failed to post PR comment: ${err instanceof Error ? err.message : String(err)}`);
2166
+ }
2167
+ }
1416
2168
  // Annotate the CommonJS export names for ESM import in node:
1417
2169
  0 && (module.exports = {
1418
2170
  GitHubClient,
2171
+ JestRunner,
1419
2172
  KakarotConfigSchema,
1420
2173
  TestGenerator,
2174
+ VitestRunner,
1421
2175
  analyzeFile,
2176
+ buildCoverageSummaryPrompt,
1422
2177
  buildTestFixPrompt,
1423
2178
  buildTestGenerationPrompt,
1424
2179
  createLLMProvider,
2180
+ createTestRunner,
1425
2181
  debug,
2182
+ detectPackageManager,
1426
2183
  error,
1427
2184
  extractTestTargets,
2185
+ findProjectRoot,
1428
2186
  getChangedRanges,
2187
+ getTestFilePath,
1429
2188
  info,
1430
2189
  initLogger,
1431
2190
  loadConfig,
1432
2191
  parsePullRequestFiles,
1433
2192
  parseTestCode,
1434
2193
  progress,
2194
+ readCoverageReport,
2195
+ runPullRequest,
1435
2196
  success,
1436
2197
  validateTestCodeStructure,
1437
- warn
2198
+ warn,
2199
+ writeTestFiles
1438
2200
  });
1439
2201
  //# sourceMappingURL=index.cjs.map