CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
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 | /**
* Autopilot — self-sufficiency loop.
*
* Runs existing platform-maintenance tasks (mirror sync, merge queue progress,
* weekly digests, advisory rescans) on an interval so the host runs itself
* without an external cron. All sub-tasks are injected so tests can stub them
* without touching the DB; the default task set wires real helpers from the
* locked libs. Nothing here throws — every sub-task and the outer tick are
* try/caught so a single failure never blocks the others.
*/
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";
import { releaseExpiredWaitTimers } from "./environments";
import { runScheduledWorkflowsTick } from "./scheduled-workflows";
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;
/**
* Default task set. Each task is a thin wrapper around an existing locked
* helper — no gate/merge logic is duplicated here.
*/
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);
},
},
{
name: "wait-timer-release",
run: async () => {
await releaseExpiredWaitTimers();
},
},
{
name: "scheduled-workflows",
run: async () => {
await runScheduledWorkflowsTick();
},
},
];
}
/**
* Visits each distinct (repo, base_branch) that has queued rows and logs a
* stub depth line. The actual gate-running + merge happens in the pulls
* route; this tick is just a heartbeat so we can wire per-queue progress
* through without duplicating merge logic.
*/
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
);
}
}
}
/**
* Pick a small batch of repos that actually have dep rows and re-run
* advisory scan against them. Cheap — one SELECT DISTINCT with LIMIT.
*/
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
);
}
}
}
/** Resolve the tick interval from env → opts → default. */
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;
}
/**
* Start the recurring autopilot loop. No-op when AUTOPILOT_DISABLED=1.
* The first tick fires after `intervalMs`, not immediately, to keep boot
* fast. Returns a `stop()` that clears the interval.
*/
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(() => {
// runAutopilotTick already never throws, but belt-and-braces.
})
.finally(() => {
running = false;
});
}, intervalMs);
return {
stop: () => clearInterval(handle),
};
}
/** Last tick snapshot for observability. Module-level, swap-on-complete. */
let lastTick: AutopilotTickResult | null = null;
let tickCount = 0;
/** Return the most recent completed tick, or null if autopilot hasn't run yet. */
export function getLastTick(): AutopilotTickResult | null {
return lastTick;
}
/** Return the total number of completed ticks in this process. */
export function getTickCount(): number {
return tickCount;
}
/**
* Run one tick: invokes every sub-task with its own try/catch, records a
* per-task result, and emits a single summary line. Never throws.
*/
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;
}
/** Exposed for unit tests. */
export const __test = {
resolveIntervalMs,
processMergeQueues,
rescanAdvisoriesBatch,
DEFAULT_INTERVAL_MS,
ADVISORY_RESCAN_BATCH,
};
|