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
|
import { and, eq, ilike, sql } from "drizzle-orm";
import { db } from "../db";
import {
issueComments,
issueLabels,
issues,
labels,
pullRequests,
repositories,
users,
} from "../db/schema";
import { extractClosingRefsMulti } from "./close-keywords";
import { buildSpecFromIssue } from "../routes/specs";
export const AI_BUILD_MARKER = "<!-- gluecron:ai-build:v1 -->";
const DEFAULT_MAX_ISSUES_PER_TICK = 20;
export interface AiBuildCandidate {
issueId: string;
issueNumber: number;
issueTitle: string;
issueBody: string | null;
repositoryId: string;
authorUserId: string;
ownerUsername: string | null;
repoName: string;
defaultBranch: string;
}
export interface SpecDispatcher {
(args: {
repoId: string;
spec: string;
baseRef: string;
userId: string;
}): Promise<{ ok: true; prNumber: number } | { ok: false; error: string }>;
}
export interface AiBuildTaskDeps {
findCandidates?: (limit: number) => Promise<AiBuildCandidate[]>;
hasDispatchMarker?: (issueId: string) => Promise<boolean>;
hasOpenLinkedPr?: (
repositoryId: string,
issueNumber: number
) => Promise<boolean>;
dispatcher?: SpecDispatcher;
postMarkerComment?: (
issueId: string,
authorUserId: string,
body: string
) => Promise<void>;
maxIssuesPerTick?: number;
}
export interface AiBuildTaskSummary {
queued: number;
skipped: number;
}
async function defaultFindCandidates(
limit: number
): Promise<AiBuildCandidate[]> {
try {
const rows = await db
.select({
issueId: issues.id,
issueNumber: issues.number,
issueTitle: issues.title,
issueBody: issues.body,
repositoryId: issues.repositoryId,
authorUserId: issues.authorId,
ownerUsername: users.username,
repoName: repositories.name,
defaultBranch: repositories.defaultBranch,
})
.from(issues)
.innerJoin(repositories, eq(repositories.id, issues.repositoryId))
.leftJoin(users, eq(users.id, repositories.ownerId))
.innerJoin(issueLabels, eq(issueLabels.issueId, issues.id))
.innerJoin(labels, eq(labels.id, issueLabels.labelId))
.where(
and(
eq(issues.state, "open"),
eq(repositories.isArchived, false),
ilike(labels.name, "ai:build")
)
)
.limit(limit);
return rows.map((r) => ({
issueId: r.issueId,
issueNumber: r.issueNumber,
issueTitle: r.issueTitle,
issueBody: r.issueBody,
repositoryId: r.repositoryId,
authorUserId: r.authorUserId,
ownerUsername: r.ownerUsername ?? null,
repoName: r.repoName,
defaultBranch: r.defaultBranch || "main",
}));
} catch (err) {
console.error("[autopilot] ai-build: candidate query failed:", err);
return [];
}
}
async function defaultHasDispatchMarker(issueId: string): Promise<boolean> {
try {
const rows = await db
.select({ id: issueComments.id })
.from(issueComments)
.where(
and(
eq(issueComments.issueId, issueId),
sql`${issueComments.body} LIKE ${"%" + AI_BUILD_MARKER + "%"}`
)
)
.limit(1);
return rows.length > 0;
} catch {
return true;
}
}
async function defaultHasOpenLinkedPr(
repositoryId: string,
issueNumber: number
): Promise<boolean> {
try {
const rows = await db
.select({ title: pullRequests.title, body: pullRequests.body })
.from(pullRequests)
.where(
and(
eq(pullRequests.repositoryId, repositoryId),
eq(pullRequests.state, "open")
)
);
for (const r of rows) {
const refs = extractClosingRefsMulti([r.title, r.body]);
if (refs.includes(issueNumber)) return true;
}
return false;
} catch {
return false;
}
}
async function defaultDispatcher(args: {
repoId: string;
spec: string;
baseRef: string;
userId: string;
}): Promise<{ ok: true; prNumber: number } | { ok: false; error: string }> {
try {
const mod: any = await import("./spec-to-pr");
const fn = mod && (mod.createSpecPR || mod.default?.createSpecPR);
if (typeof fn !== "function") {
return { ok: false, error: "createSpecPR not exported by spec-to-pr.ts" };
}
const res = await fn(args);
if (res && res.ok) return { ok: true, prNumber: res.prNumber };
return {
ok: false,
error: (res && "error" in res && res.error) || "unknown error",
};
} catch (err) {
return {
ok: false,
error: err instanceof Error ? err.message : String(err),
};
}
}
async function defaultPostMarkerComment(
issueId: string,
authorUserId: string,
body: string
): Promise<void> {
try {
await db.insert(issueComments).values({
issueId,
authorId: authorUserId,
body,
});
} catch (err) {
console.error("[autopilot] ai-build: marker insert failed:", err);
}
}
export async function runAiBuildTaskOnce(
deps: AiBuildTaskDeps = {}
): Promise<AiBuildTaskSummary> {
const limit = deps.maxIssuesPerTick ?? DEFAULT_MAX_ISSUES_PER_TICK;
const findCandidates = deps.findCandidates ?? defaultFindCandidates;
const hasDispatchMarker = deps.hasDispatchMarker ?? defaultHasDispatchMarker;
const hasOpenLinkedPr = deps.hasOpenLinkedPr ?? defaultHasOpenLinkedPr;
const dispatcher = deps.dispatcher ?? defaultDispatcher;
const postMarkerComment = deps.postMarkerComment ?? defaultPostMarkerComment;
let candidates: AiBuildCandidate[] = [];
try {
candidates = await findCandidates(limit);
} catch (err) {
console.error("[autopilot] ai-build: findCandidates threw:", err);
return { queued: 0, skipped: 0 };
}
let queued = 0;
let skipped = 0;
for (const cand of candidates) {
try {
if (!cand.ownerUsername) {
skipped += 1;
continue;
}
if (await hasOpenLinkedPr(cand.repositoryId, cand.issueNumber)) {
skipped += 1;
continue;
}
if (await hasDispatchMarker(cand.issueId)) {
skipped += 1;
continue;
}
const spec = buildSpecFromIssue({
number: cand.issueNumber,
title: cand.issueTitle,
body: cand.issueBody,
});
await postMarkerComment(
cand.issueId,
cand.authorUserId,
`${AI_BUILD_MARKER}\nQueued an AI-build off this issue's spec. The PR (if any) will reference this issue via "Closes #${cand.issueNumber}".`
);
try {
const res = await dispatcher({
repoId: cand.repositoryId,
spec,
baseRef: cand.defaultBranch,
userId: cand.authorUserId,
});
if (!res.ok) {
console.error(
`[autopilot] ai-build: dispatcher failed for issue=${cand.issueId}: ${res.error}`
);
}
} catch (err) {
console.error(
`[autopilot] ai-build: dispatcher threw for issue=${cand.issueId}:`,
err
);
}
queued += 1;
} catch (err) {
console.error(
`[autopilot] ai-build: per-issue failure for issue=${cand.issueId}:`,
err
);
skipped += 1;
}
}
return { queued, skipped };
}
export const __test = {
defaultFindCandidates,
defaultHasDispatchMarker,
defaultHasOpenLinkedPr,
defaultDispatcher,
defaultPostMarkerComment,
DEFAULT_MAX_ISSUES_PER_TICK,
};
|