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
|
import { and, eq, like } from "drizzle-orm";
import { join } from "path";
import { db } from "../db";
import { pullRequests, repositories, users } from "../db/schema";
import { getBlob, getTreeRecursive } from "../git/repository";
import {
AI_SPEC_PR_MARKER,
parseFrontMatter,
runSpecToPr,
type RunSpecToPrResult,
} from "./spec-to-pr";
const DEFAULT_MAX_SPECS_PER_TICK = 10;
const DEFAULT_MAX_SPECS_PER_REPO = 3;
export interface SpecToPrCandidate {
repositoryId: string;
ownerName: string;
repoName: string;
defaultBranch: string;
specPath: string;
}
export interface SpecToPrDispatcher {
(args: {
repositoryId: string;
specPath: string;
baseSha?: string;
}): Promise<RunSpecToPrResult>;
}
export interface SpecToPrTaskDeps {
findCandidates?: (
limit: number,
perRepoLimit: number
) => Promise<SpecToPrCandidate[]>;
hasOpenLinkedPr?: (
repositoryId: string,
specPath: string
) => Promise<boolean>;
dispatcher?: SpecToPrDispatcher;
maxSpecsPerTick?: number;
maxSpecsPerRepo?: number;
}
export interface SpecToPrTaskSummary {
considered: number;
dispatched: number;
skipped: number;
failed: number;
}
async function defaultFindCandidates(
limit: number,
perRepoLimit: number
): Promise<SpecToPrCandidate[]> {
let repoRows: Array<{
id: string;
name: string;
defaultBranch: string;
ownerName: string | null;
}>;
try {
repoRows = await db
.select({
id: repositories.id,
name: repositories.name,
defaultBranch: repositories.defaultBranch,
ownerName: users.username,
})
.from(repositories)
.innerJoin(users, eq(users.id, repositories.ownerId))
.where(eq(repositories.isArchived, false))
.limit(200);
} catch (err) {
console.error("[autopilot] spec-to-pr: repo query failed:", err);
return [];
}
const out: SpecToPrCandidate[] = [];
for (const repo of repoRows) {
if (out.length >= limit) break;
if (!repo.ownerName) continue;
const defaultBranch = repo.defaultBranch || "main";
let specPaths: string[] = [];
try {
const tree = await getTreeRecursive(repo.ownerName, repo.name, defaultBranch, 5000);
if (!tree) continue;
specPaths = tree.tree
.filter(
(e) =>
e.type === "blob" &&
e.path.startsWith(".gluecron/specs/") &&
e.path.toLowerCase().endsWith(".md")
)
.map((e) => e.path)
.slice(0, perRepoLimit * 5);
} catch (err) {
console.warn(
`[autopilot] spec-to-pr: tree scan failed for ${repo.ownerName}/${repo.name}:`,
err instanceof Error ? err.message : err
);
continue;
}
let perRepo = 0;
for (const path of specPaths) {
if (perRepo >= perRepoLimit) break;
if (out.length >= limit) break;
try {
const blob = await getBlob(
repo.ownerName,
repo.name,
defaultBranch,
path
);
if (!blob || blob.isBinary) continue;
const parsed = parseFrontMatter(blob.content);
const status = (parsed.frontMatter.status || "").toLowerCase();
if (status !== "ready") continue;
out.push({
repositoryId: repo.id,
ownerName: repo.ownerName,
repoName: repo.name,
defaultBranch,
specPath: path,
});
perRepo += 1;
} catch (err) {
console.warn(
`[autopilot] spec-to-pr: blob read failed for ${repo.ownerName}/${repo.name}:${path}:`,
err instanceof Error ? err.message : err
);
}
}
}
return out;
}
async function defaultHasOpenLinkedPr(
repositoryId: string,
specPath: string
): Promise<boolean> {
try {
const rows = await db
.select({ id: pullRequests.id })
.from(pullRequests)
.where(
and(
eq(pullRequests.repositoryId, repositoryId),
like(pullRequests.body, `%${AI_SPEC_PR_MARKER}%`),
like(pullRequests.body, `%${specPath}%`)
)
)
.limit(1);
return rows.length > 0;
} catch {
return false;
}
}
async function defaultDispatcher(args: {
repositoryId: string;
specPath: string;
baseSha?: string;
}): Promise<RunSpecToPrResult> {
try {
return await runSpecToPr(args);
} catch (err) {
return {
ok: false,
error: err instanceof Error ? err.message : String(err),
};
}
}
export async function runSpecToPrTaskOnce(
deps: SpecToPrTaskDeps = {}
): Promise<SpecToPrTaskSummary> {
if (process.env.AUTOPILOT_DISABLED === "1") {
return { considered: 0, dispatched: 0, skipped: 0, failed: 0 };
}
if (!process.env.ANTHROPIC_API_KEY) {
return { considered: 0, dispatched: 0, skipped: 0, failed: 0 };
}
const limit = deps.maxSpecsPerTick ?? DEFAULT_MAX_SPECS_PER_TICK;
const perRepoLimit = deps.maxSpecsPerRepo ?? DEFAULT_MAX_SPECS_PER_REPO;
const findCandidates = deps.findCandidates ?? defaultFindCandidates;
const hasOpenLinkedPr = deps.hasOpenLinkedPr ?? defaultHasOpenLinkedPr;
const dispatcher = deps.dispatcher ?? defaultDispatcher;
let candidates: SpecToPrCandidate[] = [];
try {
candidates = await findCandidates(limit, perRepoLimit);
} catch (err) {
console.error("[autopilot] spec-to-pr: findCandidates threw:", err);
return { considered: 0, dispatched: 0, skipped: 0, failed: 0 };
}
let dispatched = 0;
let skipped = 0;
let failed = 0;
for (const cand of candidates) {
try {
if (await hasOpenLinkedPr(cand.repositoryId, cand.specPath)) {
skipped += 1;
continue;
}
const result = await dispatcher({
repositoryId: cand.repositoryId,
specPath: cand.specPath,
});
if (result.ok) {
dispatched += 1;
} else {
failed += 1;
console.warn(
`[autopilot] spec-to-pr: dispatch failed for ${cand.ownerName}/${cand.repoName}:${cand.specPath}: ${result.error}`
);
}
} catch (err) {
failed += 1;
console.error(
`[autopilot] spec-to-pr: per-spec failure for ${cand.specPath}:`,
err
);
}
}
return {
considered: candidates.length,
dispatched,
skipped,
failed,
};
}
export function repoDiskPath(ownerName: string, repoName: string): string {
const base = process.env.GIT_REPOS_PATH || "./repos";
return join(base, ownerName, `${repoName}.git`);
}
export const __test = {
defaultFindCandidates,
defaultHasOpenLinkedPr,
defaultDispatcher,
DEFAULT_MAX_SPECS_PER_TICK,
DEFAULT_MAX_SPECS_PER_REPO,
};
|