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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
|
import { and, eq, sql } from "drizzle-orm";
import { db } from "../../db";
import {
activityFeed,
pullRequests,
repositories,
users,
} from "../../db/schema";
import { healSuite } from "../gatetest-client";
import {
executeAgentRun,
startAgentRun,
type AgentExecutorContext,
} from "../agent-runtime";
export interface RunHealBotArgs {
repositoryId: string;
triggerBy?: string | null;
}
export interface RunHealBotResult {
ok: boolean;
summary: string;
runId: string | null;
}
export interface RunHealBotForAllResult {
started: number;
succeeded: number;
failed: number;
skipped: number;
}
const HEAL_BOT_COST_CENTS = 5;
const MAX_REPOS_PER_RUN = 50;
export const HEAL_BOT_SLUG = "agent-heal-bot";
export const HEAL_BOT_BOT_USERNAME = "agent-heal-bot[bot]";
interface RepoIdentity {
id: string;
name: string;
ownerUsername: string;
ownerId: string;
defaultBranch: string;
}
async function resolveRepoIdentity(
repositoryId: string
): Promise<RepoIdentity | null> {
try {
const rows = await db
.select({
id: repositories.id,
name: repositories.name,
ownerId: repositories.ownerId,
defaultBranch: repositories.defaultBranch,
ownerUsername: users.username,
})
.from(repositories)
.innerJoin(users, eq(users.id, repositories.ownerId))
.where(eq(repositories.id, repositoryId))
.limit(1);
const row = rows[0];
if (!row) return null;
return {
id: row.id,
name: row.name,
ownerId: row.ownerId,
defaultBranch: row.defaultBranch || "main",
ownerUsername: row.ownerUsername,
};
} catch (err) {
console.error("[heal-bot] resolveRepoIdentity:", err);
return null;
}
}
async function resolveHealBotAuthorId(
ownerId: string
): Promise<string | null> {
try {
const [bot] = await db
.select({ id: users.id })
.from(users)
.where(eq(users.username, HEAL_BOT_BOT_USERNAME))
.limit(1);
if (bot?.id) return bot.id;
} catch (err) {
console.error("[heal-bot] resolveHealBotAuthorId bot lookup:", err);
}
return ownerId;
}
async function listEligibleRepositoryIds(): Promise<string[]> {
let tableExists = false;
try {
const probe = (await db.execute(sql`
SELECT to_regclass('public.repo_agent_settings') AS reg
`)) as unknown as Array<Record<string, unknown>>;
const first = Array.isArray(probe) ? probe[0] : undefined;
tableExists = !!(first && first.reg);
} catch (err) {
console.error("[heal-bot] to_regclass probe failed:", err);
tableExists = false;
}
try {
if (tableExists) {
const rows = (await db.execute(sql`
SELECT r.id::text AS id
FROM repositories r
LEFT JOIN repo_agent_settings s
ON s.repository_id = r.id
WHERE r.is_archived = false
AND COALESCE(s.paused, false) = false
AND (
s.enabled_kinds IS NULL
OR s.enabled_kinds::text LIKE '%heal_bot%'
)
ORDER BY r.pushed_at DESC NULLS LAST, r.created_at DESC
LIMIT ${MAX_REPOS_PER_RUN}
`)) as unknown as Array<Record<string, unknown>>;
if (Array.isArray(rows)) {
return rows.map((r) => String(r.id)).filter(Boolean);
}
return [];
}
} catch (err) {
console.error(
"[heal-bot] listEligibleRepositoryIds (with settings) failed:",
err
);
}
try {
const rows = await db
.select({ id: repositories.id })
.from(repositories)
.where(eq(repositories.isArchived, false))
.limit(MAX_REPOS_PER_RUN);
return rows.map((r) => r.id).filter(Boolean);
} catch (err) {
console.error("[heal-bot] listEligibleRepositoryIds (fallback) failed:", err);
return [];
}
}
export function renderHealBotPrBody(findings: {
flakyFound: number;
deadFound: number;
coverageGapsFound: number;
headBranch: string;
baseBranch: string;
}): string {
const {
flakyFound,
deadFound,
coverageGapsFound,
headBranch,
baseBranch,
} = findings;
const total = flakyFound + deadFound + coverageGapsFound;
const lines: string[] = [];
lines.push(`Automated test-suite heal by GlueCron's heal-bot.`);
lines.push("");
lines.push(`**${total} repair${total === 1 ? "" : "s"}** queued on \`${headBranch}\` → \`${baseBranch}\`.`);
lines.push("");
lines.push("| Finding | Count |");
lines.push("| --- | ---: |");
lines.push(`| Flaky tests stabilised | ${flakyFound} |`);
lines.push(`| Dead / obsolete tests pruned | ${deadFound} |`);
lines.push(`| Coverage gaps newly covered | ${coverageGapsFound} |`);
lines.push("");
lines.push(
"Review carefully — the heal-bot never auto-merges. If a repair is wrong, close this PR and the bot will not retry the same branch."
);
lines.push("");
lines.push(`_Generated by ${HEAL_BOT_BOT_USERNAME}._`);
return lines.join("\n");
}
export function renderHealBotPrTitle(repairs: number): string {
return `chore(tests): heal-bot — ${repairs} repair${repairs === 1 ? "" : "s"}`;
}
export function buildHealBotSummary(params: {
flakyFound: number;
deadFound: number;
coverageGapsFound: number;
prNumber: number | null;
branchProduced: boolean;
}): string {
const { flakyFound, deadFound, coverageGapsFound, prNumber, branchProduced } =
params;
const total = flakyFound + deadFound + coverageGapsFound;
if (total === 0) return "suite healthy";
if (!branchProduced) {
return `${total} findings, no branch produced — Gatetest may need reconfiguration`;
}
const prLabel = prNumber !== null ? `#${prNumber}` : "(unknown PR)";
return `opened ${prLabel} (${flakyFound} flaky, ${deadFound} dead, ${coverageGapsFound} coverage)`;
}
export async function runHealBot(
args: RunHealBotArgs
): Promise<RunHealBotResult> {
if (!args || typeof args.repositoryId !== "string" || !args.repositoryId) {
return {
ok: false,
summary: "invalid args: missing repositoryId",
runId: null,
};
}
const trigger: "manual" | "scheduled" = args.triggerBy ? "manual" : "scheduled";
const run = await startAgentRun({
repositoryId: args.repositoryId,
kind: "heal_bot",
trigger,
triggerRef: "nightly",
});
if (!run) {
return {
ok: false,
summary: "could not open agent_runs row",
runId: null,
};
}
let finalSummary = "suite healthy";
await executeAgentRun(run.id, async (ctx: AgentExecutorContext) => {
await ctx.appendLog(
`[heal-bot] starting run for repo ${args.repositoryId} (trigger=${trigger})`
);
const identity = await resolveRepoIdentity(args.repositoryId);
if (!identity) {
await ctx.appendLog("[heal-bot] repository lookup failed; aborting");
finalSummary = "repo not found";
return { ok: false, summary: finalSummary };
}
const repoSlug = `${identity.ownerUsername}/${identity.name}`;
await ctx.appendLog(`[heal-bot] calling gatetest.healSuite for ${repoSlug}`);
const result = await healSuite({ repo: repoSlug });
await ctx.recordCost(0, 0, HEAL_BOT_COST_CENTS);
if (result.offline) {
await ctx.appendLog("[heal-bot] Gatetest offline; skipping.");
finalSummary = "gatetest offline; skipped";
return { ok: true, summary: finalSummary };
}
const total =
(result.flakyFound || 0) +
(result.deadFound || 0) +
(result.coverageGapsFound || 0);
await ctx.appendLog(
`[heal-bot] gatetest returned: flaky=${result.flakyFound}, dead=${result.deadFound}, coverage=${result.coverageGapsFound}, branch=${result.prDraftBranch ?? "(none)"}`
);
if (total === 0) {
finalSummary = buildHealBotSummary({
flakyFound: 0,
deadFound: 0,
coverageGapsFound: 0,
prNumber: null,
branchProduced: false,
});
return { ok: true, summary: finalSummary };
}
if (!result.prDraftBranch) {
finalSummary = buildHealBotSummary({
flakyFound: result.flakyFound,
deadFound: result.deadFound,
coverageGapsFound: result.coverageGapsFound,
prNumber: null,
branchProduced: false,
});
await ctx.appendLog(`[heal-bot] ${finalSummary}`);
return { ok: true, summary: finalSummary };
}
const authorId = await resolveHealBotAuthorId(identity.ownerId);
if (!authorId) {
await ctx.appendLog(
"[heal-bot] no viable author_id for PR; aborting PR insert"
);
finalSummary = "no author_id available; PR not opened";
return { ok: false, summary: finalSummary };
}
const title = renderHealBotPrTitle(total);
const body = renderHealBotPrBody({
flakyFound: result.flakyFound,
deadFound: result.deadFound,
coverageGapsFound: result.coverageGapsFound,
headBranch: result.prDraftBranch,
baseBranch: identity.defaultBranch,
});
let prNumber: number | null = null;
let prId: string | null = null;
try {
const [pr] = await db
.insert(pullRequests)
.values({
repositoryId: identity.id,
authorId,
title,
body,
baseBranch: identity.defaultBranch,
headBranch: result.prDraftBranch,
isDraft: false,
})
.returning();
prNumber = pr?.number ?? null;
prId = pr?.id ?? null;
} catch (err) {
await ctx.appendLog(
`[heal-bot] PR insert failed: ${(err as Error).message}`
);
finalSummary = `PR insert failed: ${(err as Error).message}`;
return { ok: false, summary: finalSummary };
}
if (prId) {
try {
await db.insert(activityFeed).values({
repositoryId: identity.id,
userId: authorId,
action: "pr_open",
targetType: "pr",
targetId: prId,
metadata: JSON.stringify({
agent: "heal_bot",
flakyFound: result.flakyFound,
deadFound: result.deadFound,
coverageGapsFound: result.coverageGapsFound,
}),
});
} catch (err) {
console.error("[heal-bot] activity_feed insert failed:", err);
}
}
finalSummary = buildHealBotSummary({
flakyFound: result.flakyFound,
deadFound: result.deadFound,
coverageGapsFound: result.coverageGapsFound,
prNumber,
branchProduced: true,
});
await ctx.appendLog(`[heal-bot] ${finalSummary}`);
return { ok: true, summary: finalSummary };
});
return { ok: true, summary: finalSummary, runId: run.id };
}
export async function runHealBotForAll(): Promise<RunHealBotForAllResult> {
const agg: RunHealBotForAllResult = {
started: 0,
succeeded: 0,
failed: 0,
skipped: 0,
};
let repoIds: string[] = [];
try {
repoIds = await listEligibleRepositoryIds();
} catch (err) {
console.error("[heal-bot] runHealBotForAll: listing failed:", err);
return agg;
}
if (repoIds.length === 0) {
console.log("[heal-bot] runHealBotForAll: no eligible repositories");
return agg;
}
console.log(
`[heal-bot] runHealBotForAll: scheduling ${repoIds.length} repo(s)`
);
for (const repositoryId of repoIds) {
agg.started++;
try {
const result = await runHealBot({ repositoryId });
if (result.ok) agg.succeeded++;
else agg.failed++;
console.log(
`[heal-bot] ${repositoryId}: ${result.ok ? "ok" : "fail"} — ${result.summary}`
);
} catch (err) {
agg.failed++;
console.error(`[heal-bot] ${repositoryId}: unexpected throw:`, err);
}
}
return agg;
}
export const __internal = {
HEAL_BOT_COST_CENTS,
MAX_REPOS_PER_RUN,
listEligibleRepositoryIds,
resolveRepoIdentity,
resolveHealBotAuthorId,
};
|