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
|
import { sql } from "drizzle-orm";
import { db } from "../db";
import { mergeQueueEntries, repoDependencies } from "../db/schema";
import { syncAllDue } from "./mirrors";
import { peekHead } from "./merge-queue";
import { sendDigestsToAll } from "./email-digest";
import { scanRepositoryForAlerts } from "./advisories";
export interface AutopilotTaskResult {
name: string;
ok: boolean;
durationMs: number;
error?: string;
}
export interface AutopilotTickResult {
startedAt: string;
finishedAt: string;
tasks: AutopilotTaskResult[];
}
export interface AutopilotTask {
name: string;
run: () => Promise<void>;
}
export interface StartAutopilotOpts {
intervalMs?: number;
now?: () => number;
tasks?: AutopilotTask[];
}
export interface RunTickOpts {
tasks?: AutopilotTask[];
now?: () => number;
}
const DEFAULT_INTERVAL_MS = 5 * 60 * 1000;
const ADVISORY_RESCAN_BATCH = 5;
export function defaultTasks(): AutopilotTask[] {
return [
{
name: "mirror-sync",
run: async () => {
await syncAllDue();
},
},
{
name: "merge-queue",
run: async () => {
await processMergeQueues();
},
},
{
name: "weekly-digest",
run: async () => {
await sendDigestsToAll();
},
},
{
name: "advisory-rescan",
run: async () => {
await rescanAdvisoriesBatch(ADVISORY_RESCAN_BATCH);
},
},
];
}
async function processMergeQueues(): Promise<void> {
let distinct: Array<{ repositoryId: string; baseBranch: string }> = [];
try {
const rows = await db
.selectDistinct({
repositoryId: mergeQueueEntries.repositoryId,
baseBranch: mergeQueueEntries.baseBranch,
})
.from(mergeQueueEntries)
.where(sql`${mergeQueueEntries.state} IN ('queued','running')`);
distinct = rows;
} catch (err) {
console.error("[autopilot] merge-queue: distinct query failed:", err);
return;
}
for (const d of distinct) {
try {
const head = await peekHead(d.repositoryId, d.baseBranch);
if (head) {
console.log(
`[autopilot] merge queue depth head=${head.id.slice(0, 8)} repo=${d.repositoryId.slice(0, 8)} base=${d.baseBranch}`
);
}
} catch (err) {
console.error(
`[autopilot] merge-queue: peek failed for repo=${d.repositoryId}:`,
err
);
}
}
}
async function rescanAdvisoriesBatch(limit: number): Promise<void> {
let repoIds: string[] = [];
try {
const rows = await db
.selectDistinct({ repositoryId: repoDependencies.repositoryId })
.from(repoDependencies)
.limit(limit);
repoIds = rows.map((r) => r.repositoryId);
} catch (err) {
console.error("[autopilot] advisory-rescan: query failed:", err);
return;
}
for (const id of repoIds) {
try {
await scanRepositoryForAlerts(id);
} catch (err) {
console.error(
`[autopilot] advisory-rescan: scan failed for repo=${id}:`,
err
);
}
}
}
function resolveIntervalMs(optsMs?: number): number {
if (typeof optsMs === "number" && optsMs > 0) return optsMs;
const raw = process.env.AUTOPILOT_INTERVAL_MS;
if (raw) {
const parsed = Number(raw);
if (Number.isFinite(parsed) && parsed > 0) return parsed;
}
return DEFAULT_INTERVAL_MS;
}
export function startAutopilot(opts?: StartAutopilotOpts): { stop: () => void } {
if (process.env.AUTOPILOT_DISABLED === "1") {
return { stop: () => {} };
}
const intervalMs = resolveIntervalMs(opts?.intervalMs);
const tasks = opts?.tasks ?? defaultTasks();
let running = false;
const handle = setInterval(() => {
if (running) return;
running = true;
void runAutopilotTick({ tasks, now: opts?.now })
.catch(() => {
})
.finally(() => {
running = false;
});
}, intervalMs);
return {
stop: () => clearInterval(handle),
};
}
let lastTick: AutopilotTickResult | null = null;
let tickCount = 0;
export function getLastTick(): AutopilotTickResult | null {
return lastTick;
}
export function getTickCount(): number {
return tickCount;
}
export async function runAutopilotTick(
opts?: RunTickOpts
): Promise<AutopilotTickResult> {
const now = opts?.now ?? Date.now;
const tasks = opts?.tasks ?? defaultTasks();
const startedAt = new Date(now()).toISOString();
const results: AutopilotTaskResult[] = [];
for (const t of tasks) {
const t0 = now();
try {
await t.run();
results.push({ name: t.name, ok: true, durationMs: now() - t0 });
} catch (err) {
const message =
err instanceof Error ? err.message : String(err ?? "unknown error");
console.error(`[autopilot] ${t.name}: ${message}`);
results.push({
name: t.name,
ok: false,
durationMs: now() - t0,
error: message,
});
}
}
const finishedAt = new Date(now()).toISOString();
const totalMs = results.reduce((a, r) => a + r.durationMs, 0);
const okCount = results.filter((r) => r.ok).length;
console.log(
`[autopilot] tick ok tasks=${okCount}/${results.length} ms=${totalMs}`
);
const result: AutopilotTickResult = { startedAt, finishedAt, tasks: results };
lastTick = result;
tickCount += 1;
return result;
}
export const __test = {
resolveIntervalMs,
processMergeQueues,
rescanAdvisoriesBatch,
DEFAULT_INTERVAL_MS,
ADVISORY_RESCAN_BATCH,
};
|