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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
|
import { and, eq } from "drizzle-orm";
import { mkdtemp, rm, writeFile } from "fs/promises";
import { join } from "path";
import { tmpdir } from "os";
import { db } from "../db";
import {
gateRuns,
pullRequests,
prComments,
repositories,
users,
repoCollaborators,
} from "../db/schema";
import { getRepoPath } from "../git/repository";
import { getBotUserIdOrFallback } from "./bot-user";
import {
getAnthropic,
isAiAvailable,
MODEL_SONNET,
extractText,
parseJsonResponse,
} from "./ai-client";
export interface AutofixResult {
prNumber: number;
repoId: string;
gateRunId: string;
patch: string;
explanation: string;
confidence: "high" | "medium" | "low";
affectedFiles: string[];
}
interface ClaudeAutofixResponse {
patch: string;
explanation: string;
confidence: "high" | "medium" | "low";
affectedFiles: string[];
}
export const CI_AUTOFIX_MARKER = "<!-- gluecron:ci-autofix:v1 -->";
const MAX_DIFF_BYTES = 80 * 1024;
const MAX_LOG_BYTES = 3 * 1024;
const MAX_FILE_BYTES = 10 * 1024;
const MAX_TEST_FILES = 3;
async function spawnGit(
args: string[],
cwd: string
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
const proc = Bun.spawn(["git", ...args], {
cwd,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
]);
const exitCode = await proc.exited;
return { stdout, stderr, exitCode };
}
function truncate(s: string, maxBytes: number): string {
const buf = Buffer.from(s, "utf8");
if (buf.length <= maxBytes) return s;
return buf.slice(0, maxBytes).toString("utf8") + "\n[truncated]";
}
function parseErrorLog(errorLog: string): {
testFiles: string[];
errorSummary: string;
} {
const lines = errorLog.split("\n");
const filePatterns = [
/(?:^|\s)([\w./\-]+\.(?:test|spec)\.[jt]sx?)/gm,
/(?:^|\s)([\w./\-]+_test\.py)/gm,
/(?:^FAIL\s+)([\w./\-]+)/gm,
];
const filesSet = new Set<string>();
for (const pattern of filePatterns) {
let m: RegExpExecArray | null;
pattern.lastIndex = 0;
while ((m = pattern.exec(errorLog)) !== null) {
const path = m[1].trim();
if (path && !path.startsWith("-") && !path.startsWith("+")) {
filesSet.add(path);
}
}
}
const errorSummary = truncate(errorLog, MAX_LOG_BYTES);
return {
testFiles: Array.from(filesSet).slice(0, MAX_TEST_FILES),
errorSummary,
};
}
export async function triggerCiAutofix(gateRunId: string): Promise<void> {
if (!isAiAvailable()) return;
try {
await _runAutofix(gateRunId);
} catch (err) {
console.error(
"[ci-autofix] crashed:",
err instanceof Error ? err.message : err
);
}
}
async function _runAutofix(gateRunId: string): Promise<void> {
const [gateRun] = await db
.select()
.from(gateRuns)
.where(eq(gateRuns.id, gateRunId))
.limit(1);
if (!gateRun) return;
if (gateRun.status !== "failed") return;
if (!gateRun.pullRequestId) return;
const [pr] = await db
.select()
.from(pullRequests)
.where(eq(pullRequests.id, gateRun.pullRequestId))
.limit(1);
if (!pr) return;
const [repoRow] = await db
.select({
id: repositories.id,
name: repositories.name,
diskPath: repositories.diskPath,
ownerUsername: users.username,
})
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(eq(repositories.id, gateRun.repositoryId))
.limit(1);
if (!repoRow) return;
const idempotencyMarker = `<!-- gluecron:ci-autofix:run:${gateRunId} -->`;
const existing = await db
.select({ id: prComments.id })
.from(prComments)
.where(
and(
eq(prComments.pullRequestId, gateRun.pullRequestId),
eq(prComments.isAiReview, true)
)
)
.limit(50);
for (const row of existing) {
const [full] = await db
.select({ body: prComments.body })
.from(prComments)
.where(eq(prComments.id, row.id))
.limit(1);
if (full?.body?.includes(idempotencyMarker)) return;
}
const repoDir = getRepoPath(repoRow.ownerUsername, repoRow.name);
const diffResult = await spawnGit(
["diff", `${pr.baseBranch}...${pr.headBranch}`],
repoDir
);
const prDiff = truncate(diffResult.stdout, MAX_DIFF_BYTES);
if (!prDiff.trim()) return;
const errorLog = gateRun.summary || gateRun.details || "";
const { testFiles, errorSummary } = parseErrorLog(
typeof errorLog === "string" ? errorLog : JSON.stringify(errorLog)
);
let testFileContent = "";
for (const filePath of testFiles) {
const showResult = await spawnGit(
["show", `${pr.headBranch}:${filePath}`],
repoDir
);
if (showResult.exitCode === 0 && showResult.stdout) {
const content = truncate(showResult.stdout, MAX_FILE_BYTES);
testFileContent += `\n\n--- ${filePath} ---\n${content}`;
}
}
const client = getAnthropic();
const prompt = `You are a senior engineer fixing a CI failure.
PR diff (what changed):
${prDiff}
Failing test output:
${errorSummary}
Test file content:${testFileContent || "\n(no test files detected)"}
Produce a minimal unified diff patch that fixes the CI failure. The patch must:
1. Be valid unified diff format (--- a/file, +++ b/file, @@ lines)
2. Fix only what's needed — no refactoring
3. Not modify the test itself unless the test expectation is genuinely wrong
Return JSON: {"patch": "...", "explanation": "...", "confidence": "high|medium|low", "affectedFiles": ["..."]}`;
const message = await client.messages.create({
model: MODEL_SONNET,
max_tokens: 4096,
messages: [{ role: "user", content: prompt }],
});
const rawText = extractText(message);
const parsed = parseJsonResponse<ClaudeAutofixResponse>(rawText);
if (!parsed || !parsed.patch || !parsed.explanation) return;
if (parsed.confidence === "low") return;
const commentBody = buildAutofixComment(
parsed,
idempotencyMarker,
gateRunId
);
const botAuthorId = await getBotUserIdOrFallback(repoRow.id);
if (!botAuthorId) return;
await db.insert(prComments).values({
pullRequestId: gateRun.pullRequestId,
authorId: botAuthorId,
body: commentBody,
isAiReview: true,
});
}
function buildAutofixComment(
result: ClaudeAutofixResponse,
idempotencyMarker: string,
gateRunId: string
): string {
const confidenceBadge =
result.confidence === "high"
? "🟢 High confidence"
: result.confidence === "medium"
? "🟡 Medium confidence"
: "🔴 Low confidence";
return `${CI_AUTOFIX_MARKER}
${idempotencyMarker}
## 🔧 AI Auto-Fix
${result.explanation}
**Confidence:** ${confidenceBadge}
\`\`\`diff
${result.patch}
\`\`\`
<details><summary>Apply this fix</summary>
Copy the patch above or click **Apply Fix** to commit it automatically.
<form method="post" action="/api/pr-comments/COMMENT_ID/apply-autofix" style="display:inline">
<button type="submit" style="margin-top:8px;padding:6px 14px;background:#6c63ff;color:#fff;border:none;border-radius:6px;cursor:pointer">
⚡ Apply Fix
</button>
</form>
</details>
<sub>Gate run: <code>${gateRunId}</code> · Affected files: ${result.affectedFiles.join(", ") || "see patch above"}</sub>`;
}
export async function applyAutofix(
prCommentId: string,
userId: string
): Promise<{ branchName: string }> {
const [comment] = await db
.select({
id: prComments.id,
pullRequestId: prComments.pullRequestId,
body: prComments.body,
isAiReview: prComments.isAiReview,
})
.from(prComments)
.where(eq(prComments.id, prCommentId))
.limit(1);
if (!comment) throw new Error("Comment not found");
if (!comment.body.includes(CI_AUTOFIX_MARKER)) {
throw new Error("Not an autofix comment");
}
const [pr] = await db
.select()
.from(pullRequests)
.where(eq(pullRequests.id, comment.pullRequestId))
.limit(1);
if (!pr) throw new Error("PR not found");
const [repoRow] = await db
.select({
id: repositories.id,
name: repositories.name,
ownerId: repositories.ownerId,
ownerUsername: users.username,
})
.from(repositories)
.innerJoin(users, eq(repositories.ownerId, users.id))
.where(eq(repositories.id, pr.repositoryId))
.limit(1);
if (!repoRow) throw new Error("Repository not found");
const isOwner = repoRow.ownerId === userId;
if (!isOwner) {
const [collab] = await db
.select({ id: repoCollaborators.id })
.from(repoCollaborators)
.where(
and(
eq(repoCollaborators.repositoryId, repoRow.id),
eq(repoCollaborators.userId, userId)
)
)
.limit(1);
if (!collab) throw new Error("Forbidden: no write access");
}
const patchMatch = comment.body.match(/```diff\n([\s\S]*?)```/);
if (!patchMatch) throw new Error("No patch found in comment");
const patch = patchMatch[1];
const branchName = `fix/autofix-${Date.now()}`;
const repoDir = getRepoPath(repoRow.ownerUsername, repoRow.name);
const headSha = await spawnGit(
["rev-parse", pr.headBranch],
repoDir
);
if (headSha.exitCode !== 0) throw new Error("Cannot resolve head branch");
await spawnGit(
["branch", branchName, headSha.stdout.trim()],
repoDir
);
const tmpDir = await mkdtemp(join(tmpdir(), "autofix-"));
try {
const wtResult = await spawnGit(
["worktree", "add", tmpDir, branchName],
repoDir
);
if (wtResult.exitCode !== 0) {
throw new Error(`git worktree add failed: ${wtResult.stderr}`);
}
const patchFile = join(tmpDir, "autofix.patch");
await writeFile(patchFile, patch, "utf8");
const applyResult = await spawnGit(
["apply", "--index", patchFile],
tmpDir
);
if (applyResult.exitCode !== 0) {
throw new Error(`git apply failed: ${applyResult.stderr}`);
}
const commitResult = await spawnGit(
[
"commit",
"-m",
"fix: apply AI autofix for CI failure",
"--author",
"gluecron[bot] <bot@gluecron.com>",
],
tmpDir
);
if (commitResult.exitCode !== 0) {
throw new Error(`git commit failed: ${commitResult.stderr}`);
}
await spawnGit(
["push", repoDir, `HEAD:refs/heads/${branchName}`],
tmpDir
);
} finally {
await spawnGit(["worktree", "remove", "--force", tmpDir], repoDir).catch(
() => {}
);
await rm(tmpDir, { recursive: true, force: true }).catch(() => {});
}
return { branchName };
}
|