CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
Blame · Line-by-line history
autopilot.ts
Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.
| 2b821b7 | 1 | /** |
| 2 | * Autopilot — self-sufficiency loop. | |
| 3 | * | |
| 4 | * Runs existing platform-maintenance tasks (mirror sync, merge queue progress, | |
| 5 | * weekly digests, advisory rescans) on an interval so the host runs itself | |
| 6 | * without an external cron. All sub-tasks are injected so tests can stub them | |
| 7 | * without touching the DB; the default task set wires real helpers from the | |
| 8 | * locked libs. Nothing here throws — every sub-task and the outer tick are | |
| 9 | * try/caught so a single failure never blocks the others. | |
| 10 | */ | |
| 11 | ||
| 2b9055e | 12 | import { and, eq, gte, sql } from "drizzle-orm"; |
| 2b821b7 | 13 | import { db } from "../db"; |
| 2b9055e | 14 | import { |
| 15 | mergeQueueEntries, | |
| 16 | prComments, | |
| 17 | pullRequests, | |
| 18 | repoDependencies, | |
| 19 | repositories, | |
| 20 | users, | |
| 21 | } from "../db/schema"; | |
| 2b821b7 | 22 | import { syncAllDue } from "./mirrors"; |
| 23 | import { peekHead } from "./merge-queue"; | |
| 24 | import { sendDigestsToAll } from "./email-digest"; | |
| 25 | import { scanRepositoryForAlerts } from "./advisories"; | |
| a76d984 | 26 | import { releaseExpiredWaitTimers } from "./environments"; |
| 665c8bf | 27 | import { runScheduledWorkflowsTick } from "./scheduled-workflows"; |
| 2b9055e | 28 | import { |
| 29 | evaluateAutoMerge, | |
| 30 | recordAutoMergeAttempt, | |
| 31 | type AutoMergeContext, | |
| 32 | type AutoMergeDecision, | |
| 33 | } from "./auto-merge"; | |
| 34 | import { matchProtection } from "./branch-protection"; | |
| 35 | import { performMerge, type PerformMergeResult } from "./pr-merge"; | |
| 36 | import { audit } from "./notify"; | |
| 37 | import { runAiBuildTaskOnce } from "./ai-build-tasks"; | |
| 46d6165 | 38 | import { |
| 39 | sendSleepModeDigestForUser, | |
| 40 | SLEEP_MODE_USER_CAP_PER_TICK, | |
| 41 | SLEEP_MODE_COOLDOWN_HOURS, | |
| 42 | } from "./sleep-mode"; | |
| 534f04a | 43 | import { |
| 44 | runStalePrSweepOnce, | |
| 45 | runStaleIssueSweepOnce, | |
| 46 | } from "./stale-sweep"; | |
| 47 | import { computePrRiskForPullRequest } from "./pr-risk"; | |
| 48 | import { prRiskScores } from "../db/schema"; | |
| c63b860 | 49 | import { purgeScheduledAccounts } from "./account-deletion"; |
| cd4f63b | 50 | import { purgeExpiredPlaygroundAccounts } from "./playground"; |
| b1be050 | 51 | import { |
| 52 | runSyntheticChecks, | |
| 53 | persistChecks, | |
| 54 | latestStatusByCheck, | |
| 55 | type SyntheticCheckResult, | |
| 56 | } from "./synthetic-monitor"; | |
| e9aa4d8 | 57 | import { aiProactiveMonitorTick } from "./ai-proactive-monitor"; |
| 9336f45 | 58 | import { runCiHealerTick } from "./ai-ci-healer"; |
| a686079 | 59 | import { |
| 60 | runDailyStandupTaskOnce, | |
| 61 | runWeeklyStandupTaskOnce, | |
| 62 | } from "./ai-standup"; | |
| 950ef90 | 63 | import { runSpecToPrTaskOnce } from "./autopilot-spec-to-pr"; |
| 45f3b73 | 64 | import { runMigrationWatcherTaskOnce } from "./migration-assistant"; |
| 3c03977 | 65 | import { sweepStale as sweepStalePrLive } from "./pr-live"; |
| 424eb72 | 66 | import { runAutoReleaseNotesTaskOnce } from "./ai-release-notes"; |
| 1d4ff60 | 67 | import { runPrTestGeneratorTaskOnce } from "./autopilot-pr-test-generator"; |
| 79ed944 | 68 | import { runAdvancementScan } from "./advancement-scanner"; |
| 69 | import { expireOldSandboxes } from "./pr-sandbox"; | |
| 9b3a183 | 70 | import { expireIdleEnvs } from "./dev-env"; |
| 44ed968 | 71 | import { expireOldPreviews } from "./branch-previews"; |
| a7460bf | 72 | import { getBotUserIdOrFallback } from "./bot-user"; |
| f65f600 | 73 | import { runOnboardingDripTaskOnce } from "./onboarding-drip"; |
| b93fc3e | 74 | import { sendSmartDigestsToAll } from "./smart-digest"; |
| 2b821b7 | 75 | |
| 76 | export interface AutopilotTaskResult { | |
| 77 | name: string; | |
| 78 | ok: boolean; | |
| 79 | durationMs: number; | |
| 80 | error?: string; | |
| 81 | } | |
| 82 | ||
| 83 | export interface AutopilotTickResult { | |
| 84 | startedAt: string; | |
| 85 | finishedAt: string; | |
| 86 | tasks: AutopilotTaskResult[]; | |
| 87 | } | |
| 88 | ||
| 89 | export interface AutopilotTask { | |
| 90 | name: string; | |
| 91 | run: () => Promise<void>; | |
| 92 | } | |
| 93 | ||
| 94 | export interface StartAutopilotOpts { | |
| 95 | intervalMs?: number; | |
| 96 | now?: () => number; | |
| 97 | tasks?: AutopilotTask[]; | |
| 98 | } | |
| 99 | ||
| 100 | export interface RunTickOpts { | |
| 101 | tasks?: AutopilotTask[]; | |
| 102 | now?: () => number; | |
| 103 | } | |
| 104 | ||
| 105 | const DEFAULT_INTERVAL_MS = 5 * 60 * 1000; | |
| 106 | const ADVISORY_RESCAN_BATCH = 5; | |
| 2b9055e | 107 | /** K3 — recency window for auto-merge candidate selection. */ |
| 108 | const AUTO_MERGE_LOOKBACK_HOURS = 24; | |
| 109 | /** K3 — hard cap on PRs evaluated per tick (runaway protection). */ | |
| 110 | const AUTO_MERGE_MAX_PER_TICK = 50; | |
| 111 | /** K3 — stable marker for the auto-merge audit comment. */ | |
| 112 | const AUTO_MERGE_COMMENT_MARKER = "<!-- gluecron:auto-merge:v1 -->"; | |
| 534f04a | 113 | /** M3 — hard cap on PRs scored per tick (runaway protection). */ |
| 114 | const PR_RISK_RESCORE_MAX_PER_TICK = 20; | |
| 115 | /** M3 — recency window for the pr-risk-rescore sweep. */ | |
| 116 | const PR_RISK_RESCORE_LOOKBACK_HOURS = 1; | |
| e9aa4d8 | 117 | /** Proactive monitor cadence — Claude scans platform telemetry hourly. */ |
| 118 | const PROACTIVE_MONITOR_INTERVAL_MS = 60 * 60 * 1000; | |
| 119 | let _lastProactiveMonitorAt = 0; | |
| 950ef90 | 120 | /** Spec-to-PR cadence — autopilot scans `.gluecron/specs/*.md` every 2 minutes. */ |
| 121 | const SPEC_TO_PR_INTERVAL_MS = 2 * 60 * 1000; | |
| 122 | let _lastSpecToPrAt = 0; | |
| 45f3b73 | 123 | /** |
| 124 | * Migration watcher cadence. The lookup is cheap (registry calls per | |
| 125 | * declared dep) but we still throttle to every 6 hours so we don't hammer | |
| 126 | * npm and don't propose more than ~one PR per repo per day. | |
| 127 | */ | |
| 128 | const MIGRATION_WATCHER_INTERVAL_MS = 6 * 60 * 60 * 1000; | |
| 129 | let _lastMigrationWatcherAt = 0; | |
| 424eb72 | 130 | /** |
| 131 | * Auto-release-notes cadence. Cheap once tags are rare; we still throttle | |
| 132 | * to every 10 minutes so freshly-pushed tags (whose release row was just | |
| 133 | * created by `POST /:owner/:repo/releases`) get notes within ~one tick | |
| 134 | * without us scanning the table every 5 minutes. | |
| 135 | */ | |
| 136 | const AUTO_RELEASE_NOTES_INTERVAL_MS = 10 * 60 * 1000; | |
| 137 | let _lastAutoReleaseNotesAt = 0; | |
| 1d4ff60 | 138 | /** |
| 139 | * PR test generator cadence. Cheap when opted-in repos are quiet; the | |
| 140 | * task itself short-circuits via the per-PR `ai:added-tests` marker so | |
| 141 | * we never re-process the same PR. 5-minute cadence aligns with the | |
| 142 | * "freshly opened PR" window the task uses for candidate selection. | |
| 143 | */ | |
| 144 | const PR_TEST_GENERATOR_INTERVAL_MS = 5 * 60 * 1000; | |
| 145 | let _lastPrTestGeneratorAt = 0; | |
| 79ed944 | 146 | /** |
| 147 | * PR sandbox cleanup cadence (migration 0067). Runs every 30 minutes — | |
| 148 | * sandboxes default to a 4h TTL so finer-grained cleanup isn't needed, | |
| 149 | * and skipping most of the 5-min outer ticks keeps the loop cheap. | |
| 150 | */ | |
| 151 | const PR_SANDBOX_CLEANUP_INTERVAL_MS = 30 * 60 * 1000; | |
| 152 | let _lastPrSandboxCleanupAt = 0; | |
| 9b3a183 | 153 | /** |
| 154 | * Dev-env idle sweep cadence (migration 0072). Runs on every autopilot | |
| 155 | * tick (5 minutes) because per-env idle timeouts can be as short as a | |
| 156 | * few minutes — we don't want a 30-min cleanup window stranding a user | |
| 157 | * who set idle_minutes=5. The lib itself is a single SQL UPDATE so this | |
| 158 | * is cheap regardless of repo count. | |
| 159 | */ | |
| 160 | const DEV_ENV_IDLE_SWEEP_INTERVAL_MS = 5 * 60 * 1000; | |
| 161 | let _lastDevEnvIdleSweepAt = 0; | |
| f5ad215 | 162 | /** |
| 163 | * AI dependency auto-updater cadence (migration 0077). Once per day is | |
| 164 | * plenty — the task itself caps at 10 repos and 2 candidates per repo, | |
| 165 | * keeping npm registry traffic low. Skips when DEP_UPDATER_ENABLED env | |
| 166 | * flag is not set to "1". | |
| 167 | */ | |
| 168 | const DEP_UPDATE_SWEEP_INTERVAL_MS = 24 * 60 * 60 * 1000; | |
| 169 | let _lastDepUpdateSweepAt = 0; | |
| 79ed944 | 170 | /** |
| 171 | * Advancement scanner cadence. Designed to run weekly on Mondays at | |
| 172 | * 08:00 UTC. The task itself is the cheap gate (checks both day-of-week | |
| 173 | * and minimum interval since last run) so we don't bake any cron-style | |
| 174 | * triggers into the autopilot loop. Each tick (5min) probes the gate; | |
| 175 | * the gate is satisfied at most once per 6 days, keeping the cadence | |
| 176 | * effectively weekly even if Monday-08:00 happens to be missed. | |
| 177 | */ | |
| 178 | const ADVANCEMENT_SCAN_MIN_INTERVAL_MS = 6 * 24 * 60 * 60 * 1000; | |
| 179 | let _lastAdvancementScanAt = 0; | |
| 180 | /** Hour of day (UTC) the advancement scan prefers. Configurable via env. */ | |
| 181 | function advancementScanHourUtc(): number { | |
| 182 | const raw = process.env.ADVANCEMENT_SCAN_HOUR_UTC; | |
| 183 | if (!raw) return 8; | |
| 184 | const n = Number(raw); | |
| 185 | if (!Number.isFinite(n) || n < 0 || n > 23) return 8; | |
| 186 | return Math.floor(n); | |
| 187 | } | |
| 188 | /** Day of week (0=Sun..6=Sat, UTC) the advancement scan prefers. */ | |
| 189 | function advancementScanDayOfWeek(): number { | |
| 190 | const raw = process.env.ADVANCEMENT_SCAN_DOW_UTC; | |
| 191 | if (!raw) return 1; // Monday | |
| 192 | const n = Number(raw); | |
| 193 | if (!Number.isFinite(n) || n < 0 || n > 6) return 1; | |
| 194 | return Math.floor(n); | |
| 195 | } | |
| 2b821b7 | 196 | |
| b93fc3e | 197 | /** |
| 198 | * Smart-digest cadence. Designed to run once per day at 07:00 UTC. | |
| 199 | * The task itself checks `lastSmartDigestSentAt` per user (20h cooldown), | |
| 200 | * so even if the outer loop fires multiple times near 07:00, only one | |
| 201 | * digest is ever sent per day per user. | |
| 202 | */ | |
| 203 | const SMART_DIGEST_INTERVAL_MS = 22 * 60 * 60 * 1000; // 22h between outer checks | |
| 204 | let _lastSmartDigestAt = 0; | |
| 205 | ||
| 2b821b7 | 206 | /** |
| 207 | * Default task set. Each task is a thin wrapper around an existing locked | |
| 208 | * helper — no gate/merge logic is duplicated here. | |
| 209 | */ | |
| 210 | export function defaultTasks(): AutopilotTask[] { | |
| 211 | return [ | |
| 212 | { | |
| 213 | name: "mirror-sync", | |
| 214 | run: async () => { | |
| 215 | await syncAllDue(); | |
| 216 | }, | |
| 217 | }, | |
| 218 | { | |
| 219 | name: "merge-queue", | |
| 220 | run: async () => { | |
| 221 | await processMergeQueues(); | |
| 222 | }, | |
| 223 | }, | |
| 224 | { | |
| 225 | name: "weekly-digest", | |
| 226 | run: async () => { | |
| 227 | await sendDigestsToAll(); | |
| 228 | }, | |
| 229 | }, | |
| 230 | { | |
| 231 | name: "advisory-rescan", | |
| 232 | run: async () => { | |
| 233 | await rescanAdvisoriesBatch(ADVISORY_RESCAN_BATCH); | |
| 234 | }, | |
| 235 | }, | |
| a76d984 | 236 | { |
| 237 | name: "wait-timer-release", | |
| 238 | run: async () => { | |
| 239 | await releaseExpiredWaitTimers(); | |
| 240 | }, | |
| 241 | }, | |
| 665c8bf | 242 | { |
| 243 | name: "scheduled-workflows", | |
| 244 | run: async () => { | |
| 245 | await runScheduledWorkflowsTick(); | |
| 246 | }, | |
| 247 | }, | |
| 2b9055e | 248 | { |
| 249 | name: "auto-merge-sweep", | |
| 250 | run: async () => { | |
| 251 | await runAutoMergeSweep(); | |
| 252 | }, | |
| 253 | }, | |
| 254 | { | |
| 255 | name: "ai-build-from-issues", | |
| 256 | run: async () => { | |
| 257 | const summary = await runAiBuildTaskOnce(); | |
| 258 | console.log( | |
| 259 | `[autopilot] ai-build: queued=${summary.queued} skipped=${summary.skipped}` | |
| 260 | ); | |
| 261 | }, | |
| 262 | }, | |
| 46d6165 | 263 | { |
| 264 | name: "sleep-mode-digest", | |
| 265 | run: async () => { | |
| 266 | const summary = await runSleepModeDigestTaskOnce(); | |
| 267 | console.log( | |
| 268 | `[autopilot] sleep-mode-digest: sent=${summary.sent} skipped=${summary.skipped}` | |
| 269 | ); | |
| 270 | }, | |
| 271 | }, | |
| 534f04a | 272 | { |
| 273 | name: "stale-pr-sweep", | |
| 274 | run: async () => { | |
| 275 | // Two-stage gate: poke at 7d stale, close at 14d after poke | |
| 276 | // (when the repo opts in via `auto_close_stale_prs`). | |
| 277 | // Wrapped in try/catch so a finder crash never wedges the tick. | |
| 278 | try { | |
| 279 | const summary = await runStalePrSweepOnce(); | |
| 280 | console.log( | |
| 281 | `[autopilot] stale-pr-sweep: poked=${summary.poked} closed=${summary.closed}` | |
| 282 | ); | |
| 283 | } catch (err) { | |
| 284 | console.error("[autopilot] stale-pr-sweep: threw:", err); | |
| 285 | } | |
| 286 | }, | |
| 287 | }, | |
| 288 | { | |
| 289 | name: "stale-issue-sweep", | |
| 290 | run: async () => { | |
| 291 | // Mirror of stale-pr-sweep with the issue thresholds (30d/60d). | |
| 292 | try { | |
| 293 | const summary = await runStaleIssueSweepOnce(); | |
| 294 | console.log( | |
| 295 | `[autopilot] stale-issue-sweep: poked=${summary.poked} closed=${summary.closed}` | |
| 296 | ); | |
| 297 | } catch (err) { | |
| 298 | console.error("[autopilot] stale-issue-sweep: threw:", err); | |
| 299 | } | |
| 300 | }, | |
| 301 | }, | |
| 302 | { | |
| 303 | name: "pr-risk-rescore", | |
| 304 | run: async () => { | |
| 305 | const summary = await runPrRiskRescoreTaskOnce(); | |
| 306 | console.log( | |
| 307 | `[autopilot] pr-risk-rescore: scored=${summary.scored} skipped=${summary.skipped}` | |
| 308 | ); | |
| 309 | }, | |
| 310 | }, | |
| c63b860 | 311 | |
| 312 | { | |
| 313 | // Block P5 — Hard-delete users whose 30-day grace period expired. | |
| 314 | name: "account-purge", | |
| 315 | run: async () => { | |
| 316 | try { | |
| 317 | const summary = await purgeScheduledAccounts({ cap: 50 }); | |
| 318 | console.log( | |
| 319 | `[autopilot] account-purge: purged=${summary.purged} errors=${summary.errors}` | |
| 320 | ); | |
| 321 | } catch (err) { | |
| 322 | console.error("[autopilot] account-purge: threw:", err); | |
| 323 | } | |
| 324 | }, | |
| 325 | }, | |
| cd4f63b | 326 | { |
| 327 | // Block Q3 — Hard-delete anonymous playground accounts past their | |
| 328 | // 24h TTL. CASCADE handles repos, sessions, issues. Per-user | |
| 329 | // try/catch in the lib so one FK violation can't stall the queue. | |
| 330 | name: "playground-purge", | |
| 331 | run: async () => { | |
| 332 | try { | |
| 333 | const summary = await purgeExpiredPlaygroundAccounts({ cap: 50 }); | |
| 334 | console.log( | |
| 335 | `[autopilot] playground-purge: purged=${summary.purged} errors=${summary.errors}` | |
| 336 | ); | |
| 337 | } catch (err) { | |
| 338 | console.error("[autopilot] playground-purge: threw:", err); | |
| 339 | } | |
| 340 | }, | |
| 341 | }, | |
| e9aa4d8 | 342 | { |
| 343 | // Proactive AI monitor — hourly. Claude reads 24h of audit_log + | |
| 344 | // platformDeploys + workflowRuns and opens issues on anomalies | |
| 345 | // (degraded deploy times, recurring failures, suspicious audit | |
| 346 | // patterns). Skips when ANTHROPIC_API_KEY is unset (the lib | |
| 347 | // itself short-circuits, but the cadence gate avoids redundant | |
| 348 | // work on every 5-min tick too). | |
| 349 | name: "ai-proactive-monitor", | |
| 350 | run: async () => { | |
| 351 | if (!process.env.ANTHROPIC_API_KEY) return; | |
| 352 | const now = Date.now(); | |
| 353 | if (now - _lastProactiveMonitorAt < PROACTIVE_MONITOR_INTERVAL_MS) { | |
| 354 | return; | |
| 355 | } | |
| 356 | _lastProactiveMonitorAt = now; | |
| 357 | try { | |
| 358 | const summary = await aiProactiveMonitorTick(); | |
| 359 | console.log( | |
| 360 | `[autopilot] ai-proactive-monitor: opened=${summary.opened} considered=${summary.considered} dedup=${summary.skippedDedupe}` | |
| 361 | ); | |
| 362 | } catch (err) { | |
| 363 | console.error("[autopilot] ai-proactive-monitor: threw:", err); | |
| 364 | } | |
| 365 | }, | |
| 366 | }, | |
| 9336f45 | 367 | { |
| 368 | // AI CI Healer — autonomous CI failure → root-cause → patch PR loop. | |
| 369 | // Polls every tick (5 min) for failed workflow_runs that finished | |
| 370 | // at least HEAL_MIN_AGE_MS ago and haven't been processed yet. | |
| 950ef90 | 371 | // Skips when ANTHROPIC_API_KEY is unset. |
| 9336f45 | 372 | name: "ci-healer", |
| 373 | run: async () => { | |
| 374 | if (!process.env.ANTHROPIC_API_KEY) return; | |
| 375 | try { | |
| 376 | const summary = await runCiHealerTick(); | |
| 377 | console.log( | |
| 378 | `[autopilot] ci-healer: considered=${summary.considered} healed=${summary.healed} gaveUp=${summary.gaveUp} skipped=${summary.skipped}` | |
| 379 | ); | |
| 380 | } catch (err) { | |
| 381 | console.error("[autopilot] ci-healer: threw:", err); | |
| 382 | } | |
| 383 | }, | |
| 384 | }, | |
| 950ef90 | 385 | { |
| 386 | // Spec-to-PR autopilot — picks up `.gluecron/specs/*.md` files whose | |
| 387 | // front-matter status is `ready`, asks Claude to implement the spec, | |
| 388 | // opens a draft PR tagged `ai:spec-implementation`. Cadence-gated | |
| 389 | // to every 2 minutes. | |
| 390 | name: "spec-to-pr", | |
| 391 | run: async () => { | |
| 392 | if (!process.env.ANTHROPIC_API_KEY) return; | |
| 393 | const now = Date.now(); | |
| 394 | if (now - _lastSpecToPrAt < SPEC_TO_PR_INTERVAL_MS) return; | |
| 395 | _lastSpecToPrAt = now; | |
| 396 | try { | |
| 397 | const summary = await runSpecToPrTaskOnce(); | |
| 398 | console.log( | |
| 399 | `[autopilot] spec-to-pr: considered=${summary.considered} dispatched=${summary.dispatched} skipped=${summary.skipped} failed=${summary.failed}` | |
| 400 | ); | |
| 401 | } catch (err) { | |
| 402 | console.error("[autopilot] spec-to-pr: threw:", err); | |
| 403 | } | |
| 404 | }, | |
| 405 | }, | |
| b1be050 | 406 | { |
| 407 | // BLOCK S4 — Synthetic monitor. | |
| 408 | // | |
| 409 | // Runs the URL-only smoke suite (see src/lib/synthetic-monitor.ts), | |
| 410 | // records the outcome into `synthetic_checks`, and on a | |
| 411 | // green->red transition fires a webhook to MONITOR_ALERT_WEBHOOK_URL | |
| 412 | // (when configured) so the owner finds out instantly that the live | |
| 413 | // site is broken. Wrapped in try/catch — the monitor must never | |
| 414 | // wedge the tick. | |
| 415 | name: "synthetic-monitor", | |
| 416 | run: async () => { | |
| 417 | try { | |
| 418 | const summary = await runSyntheticMonitorTaskOnce(); | |
| 419 | console.log( | |
| 420 | `[autopilot] synthetic-monitor: green=${summary.green} red=${summary.red} transitions=${summary.transitions}` | |
| 421 | ); | |
| 422 | } catch (err) { | |
| 423 | console.error("[autopilot] synthetic-monitor: threw:", err); | |
| 424 | } | |
| 425 | }, | |
| 426 | }, | |
| 45f3b73 | 427 | { |
| 428 | // Migration watcher — scans each repo's package.json for deps that | |
| 429 | // are at least one major version behind and asks Claude to draft an | |
| 430 | // upgrade PR. Cadence-gated to every 6 hours; the lib itself | |
| 431 | // enforces a per-repo + per-{dep,version} 7-day dedupe so we never | |
| 432 | // re-propose the same migration twice in a single window. Skips | |
| 433 | // entirely when ANTHROPIC_API_KEY is unset OR the | |
| 434 | // MIGRATION_WATCHER_ENABLED env flag is off. | |
| 435 | name: "migration-watcher", | |
| 436 | run: async () => { | |
| 437 | if (!process.env.ANTHROPIC_API_KEY) return; | |
| 438 | const now = Date.now(); | |
| 439 | if (now - _lastMigrationWatcherAt < MIGRATION_WATCHER_INTERVAL_MS) { | |
| 440 | return; | |
| 441 | } | |
| 442 | _lastMigrationWatcherAt = now; | |
| 443 | try { | |
| 444 | const summary = await runMigrationWatcherTaskOnce(); | |
| 445 | console.log( | |
| 446 | `[autopilot] migration-watcher: considered=${summary.considered} proposed=${summary.proposed} throttled=${summary.skippedThrottle} disabled=${summary.skippedNotEnabled} errors=${summary.errors}` | |
| 447 | ); | |
| 448 | } catch (err) { | |
| 449 | console.error("[autopilot] migration-watcher: threw:", err); | |
| 450 | } | |
| 451 | }, | |
| 452 | }, | |
| a686079 | 453 | { |
| 454 | // AI Standup — daily Claude-generated team brief. | |
| 455 | // Fires at the user's configured UTC hour (default 09:00). Skips | |
| 456 | // entirely when ANTHROPIC_API_KEY is unset (the lib still has a | |
| 457 | // deterministic fallback, but we keep this task quiet unless the | |
| 458 | // operator has wired AI). Per-user dedupe via `hasStandupForToday`. | |
| 459 | name: "daily-standup", | |
| 460 | run: async () => { | |
| 461 | if (!process.env.ANTHROPIC_API_KEY) return; | |
| 462 | try { | |
| 463 | const summary = await runDailyStandupTaskOnce(); | |
| 464 | console.log( | |
| 465 | `[autopilot] daily-standup: sent=${summary.sent} skipped=${summary.skipped} errors=${summary.errors}` | |
| 466 | ); | |
| 467 | } catch (err) { | |
| 468 | console.error("[autopilot] daily-standup: threw:", err); | |
| 469 | } | |
| 470 | }, | |
| 471 | }, | |
| 3c03977 | 472 | { |
| 473 | // PR live co-editing — transition stale `pr_live_sessions` rows | |
| 474 | // to 'idle' (>60s) and 'left' (>5m) so the presence pill on the | |
| 475 | // PR detail page never claims a ghost user is still editing. | |
| 476 | // Cheap pure-SQL UPDATE; runs every tick. | |
| 477 | name: "pr-live-cleanup", | |
| 478 | run: async () => { | |
| 479 | try { | |
| 480 | const summary = await sweepStalePrLive(); | |
| 481 | if (summary.idled > 0 || summary.left > 0) { | |
| 482 | console.log( | |
| 483 | `[autopilot] pr-live-cleanup: idled=${summary.idled} left=${summary.left}` | |
| 484 | ); | |
| 485 | } | |
| 486 | } catch (err) { | |
| 487 | console.error("[autopilot] pr-live-cleanup: threw:", err); | |
| 488 | } | |
| 489 | }, | |
| 490 | }, | |
| a686079 | 491 | { |
| 492 | // AI Standup — weekly Claude-generated team brief. Mondays only. | |
| 493 | name: "weekly-standup", | |
| 494 | run: async () => { | |
| 495 | if (!process.env.ANTHROPIC_API_KEY) return; | |
| 496 | try { | |
| 497 | const summary = await runWeeklyStandupTaskOnce(); | |
| 498 | console.log( | |
| 499 | `[autopilot] weekly-standup: sent=${summary.sent} skipped=${summary.skipped} errors=${summary.errors}` | |
| 500 | ); | |
| 501 | } catch (err) { | |
| 502 | console.error("[autopilot] weekly-standup: threw:", err); | |
| 503 | } | |
| 504 | }, | |
| 505 | }, | |
| 1d4ff60 | 506 | { |
| 507 | // PR test generator — when a fresh PR opens against a repo that's | |
| 508 | // opted in (`autoGenerateTests=true`) and is not itself AI-generated, | |
| 509 | // ask Claude to write tests for the new code and push a commit onto | |
| 510 | // the same branch. Skips PRs without source-file changes; idempotent | |
| 511 | // via the `ai:added-tests` marker comment. Skips entirely when | |
| 512 | // ANTHROPIC_API_KEY is unset. | |
| 513 | name: "pr-test-generator", | |
| 514 | run: async () => { | |
| 515 | if (!process.env.ANTHROPIC_API_KEY) return; | |
| 516 | const now = Date.now(); | |
| 517 | if (now - _lastPrTestGeneratorAt < PR_TEST_GENERATOR_INTERVAL_MS) { | |
| 518 | return; | |
| 519 | } | |
| 520 | _lastPrTestGeneratorAt = now; | |
| 521 | try { | |
| 522 | const summary = await runPrTestGeneratorTaskOnce(); | |
| 523 | if (summary.considered > 0) { | |
| 524 | console.log( | |
| 525 | `[autopilot] pr-test-generator: considered=${summary.considered} dispatched=${summary.dispatched} skipped=${summary.skipped} failed=${summary.failed}` | |
| 526 | ); | |
| 527 | } | |
| 528 | } catch (err) { | |
| 529 | console.error("[autopilot] pr-test-generator: threw:", err); | |
| 530 | } | |
| 531 | }, | |
| 532 | }, | |
| 79ed944 | 533 | { |
| 534 | // Advancement scanner — weekly Claude-driven scan for "what we | |
| 535 | // should ship next". Probes: | |
| 536 | // 1. Newer Claude models vs the one wired in ai-client.ts | |
| 537 | // 2. Stack dependencies that are at least one major behind | |
| 538 | // 3. Self-improvement opportunities in the last 7d of telemetry | |
| 539 | // 4. Trending dev-platform features competitors shipped | |
| 540 | // Cadence-gated to Mondays 08:00 UTC (configurable via | |
| 541 | // ADVANCEMENT_SCAN_HOUR_UTC + ADVANCEMENT_SCAN_DOW_UTC) and | |
| 542 | // throttled to at most one scan per 6 days. Skips entirely when | |
| 543 | // ANTHROPIC_API_KEY is unset — the offline probes are still | |
| 544 | // useful but most of the value comes from the Claude calls. | |
| 545 | // The lib itself enforces per-finding (sha256 of title) dedupe | |
| 546 | // for 30 days so repeated runs never re-file the same advancement. | |
| 547 | name: "advancement-scanner", | |
| 548 | run: async () => { | |
| 549 | if (!process.env.ANTHROPIC_API_KEY) return; | |
| 550 | if (process.env.ADVANCEMENT_SCAN_DISABLED === "1") return; | |
| 551 | const now = new Date(); | |
| 552 | const nowMs = now.getTime(); | |
| 553 | const targetHour = advancementScanHourUtc(); | |
| 554 | const targetDow = advancementScanDayOfWeek(); | |
| 555 | const dueByCadence = | |
| 556 | nowMs - _lastAdvancementScanAt >= ADVANCEMENT_SCAN_MIN_INTERVAL_MS; | |
| 557 | const dueByClock = | |
| 558 | now.getUTCDay() === targetDow && | |
| 559 | now.getUTCHours() === targetHour; | |
| 560 | if (!dueByCadence || !dueByClock) return; | |
| 561 | _lastAdvancementScanAt = nowMs; | |
| 562 | try { | |
| 563 | const summary = await runAdvancementScan(); | |
| 564 | console.log( | |
| 565 | `[autopilot] advancement-scanner: findings=${summary.findings.length} issues=${summary.openedIssues} prs=${summary.openedPrs} dedup=${summary.skippedDedupe} errors=${summary.errors}` | |
| 566 | ); | |
| 567 | } catch (err) { | |
| 568 | console.error("[autopilot] advancement-scanner: threw:", err); | |
| 569 | } | |
| 570 | }, | |
| 571 | }, | |
| 424eb72 | 572 | { |
| 573 | // Auto-release-notes — backfills `releases.body` with Claude-generated | |
| 574 | // polished changelogs for any semver-tagged release whose body is | |
| 575 | // empty / too short. Cadence-gated to every 10 minutes; the lib | |
| 576 | // itself caps the per-tick batch and is no-op when no candidates | |
| 577 | // exist. Falls back to a deterministic bucketed summary when | |
| 578 | // ANTHROPIC_API_KEY is unset, so the body still ends up populated. | |
| 579 | name: "auto-release-notes", | |
| 580 | run: async () => { | |
| 581 | const now = Date.now(); | |
| 582 | if (now - _lastAutoReleaseNotesAt < AUTO_RELEASE_NOTES_INTERVAL_MS) { | |
| 583 | return; | |
| 584 | } | |
| 585 | _lastAutoReleaseNotesAt = now; | |
| 586 | try { | |
| 587 | const summary = await runAutoReleaseNotesTaskOnce(); | |
| 588 | if (summary.considered > 0 || summary.filled > 0) { | |
| 589 | console.log( | |
| 590 | `[autopilot] auto-release-notes: considered=${summary.considered} filled=${summary.filled} skipped=${summary.skipped} errors=${summary.errors}` | |
| 591 | ); | |
| 592 | } | |
| 593 | } catch (err) { | |
| 594 | console.error("[autopilot] auto-release-notes: threw:", err); | |
| 595 | } | |
| 596 | }, | |
| 597 | }, | |
| 79ed944 | 598 | { |
| 599 | // PR sandbox cleanup — migration 0067. Tears down every PR sandbox | |
| 600 | // whose `expires_at` has passed. Cadence-gated to every 30 minutes | |
| 601 | // so the every-5-min outer loop doesn't pay the cost on most ticks. | |
| 602 | // The lib itself is a pure SQL UPDATE — safe + cheap to call even | |
| 603 | // when there's nothing to do. | |
| 604 | name: "pr-sandbox-cleanup", | |
| 605 | run: async () => { | |
| 606 | const now = Date.now(); | |
| 607 | if (now - _lastPrSandboxCleanupAt < PR_SANDBOX_CLEANUP_INTERVAL_MS) { | |
| 608 | return; | |
| 609 | } | |
| 610 | _lastPrSandboxCleanupAt = now; | |
| 611 | try { | |
| 612 | const expired = await expireOldSandboxes(); | |
| 613 | if (expired > 0) { | |
| 614 | console.log(`[autopilot] pr-sandbox-cleanup: expired=${expired}`); | |
| 615 | } | |
| 616 | } catch (err) { | |
| 617 | console.error("[autopilot] pr-sandbox-cleanup: threw:", err); | |
| 618 | } | |
| 619 | }, | |
| 620 | }, | |
| 9b3a183 | 621 | { |
| 622 | // Dev-env idle sweep — migration 0072. Stops every dev env whose | |
| 623 | // `last_active_at + idle_minutes` has slipped into the past. Runs | |
| 624 | // on every tick (cadence-gated to 5min so a faster outer loop | |
| 625 | // doesn't hammer it). The lib itself is fail-soft + per-row idle | |
| 626 | // aware, so this is cheap + correct even when half the rows are | |
| 627 | // already 'stopped'. | |
| 628 | name: "dev-env-idle-sweep", | |
| 629 | run: async () => { | |
| 630 | const now = Date.now(); | |
| 631 | if (now - _lastDevEnvIdleSweepAt < DEV_ENV_IDLE_SWEEP_INTERVAL_MS) { | |
| 632 | return; | |
| 633 | } | |
| 634 | _lastDevEnvIdleSweepAt = now; | |
| 635 | try { | |
| 636 | const stopped = await expireIdleEnvs(); | |
| 637 | if (stopped > 0) { | |
| 638 | console.log(`[autopilot] dev-env-idle-sweep: stopped=${stopped}`); | |
| 639 | } | |
| 640 | } catch (err) { | |
| 641 | console.error("[autopilot] dev-env-idle-sweep: threw:", err); | |
| 642 | } | |
| 643 | }, | |
| 644 | }, | |
| 44ed968 | 645 | { |
| 646 | // Preview expiry — migration 0062. Flips every branch-preview row | |
| 647 | // whose `expires_at` is in the past to status='expired'. Runs on | |
| 648 | // every tick; the lib itself is a cheap SQL UPDATE and is a no-op | |
| 649 | // when there's nothing to expire, so this never adds meaningful | |
| 650 | // overhead. | |
| 651 | name: "preview-expiry", | |
| 652 | run: async () => { | |
| 653 | try { | |
| 654 | const expired = await expireOldPreviews(); | |
| 655 | if (expired > 0) { | |
| 656 | console.log(`[autopilot] preview-expiry: expired=${expired}`); | |
| 657 | } | |
| 658 | } catch (err) { | |
| 659 | console.error("[autopilot] preview-expiry: threw:", err); | |
| 660 | } | |
| 661 | }, | |
| 662 | }, | |
| f65f600 | 663 | { |
| 664 | // Onboarding drip — sends pending T+1d and T+3d drip emails to new | |
| 665 | // users. The T+0 "welcome" email is sent immediately at registration | |
| 666 | // via src/routes/auth.tsx. This task handles the delayed emails. | |
| 667 | // Idempotent via the per-user `onboarding_emails_sent` jsonb column | |
| b12f20d | 668 | // (migration 0081). Silently skips when email is not configured. |
| f65f600 | 669 | name: "onboarding-drip", |
| 670 | run: async () => { | |
| 671 | try { | |
| 672 | const summary = await runOnboardingDripTaskOnce(); | |
| 673 | if (summary.sent > 0 || summary.errors > 0) { | |
| 674 | console.log( | |
| 675 | `[autopilot] onboarding-drip: sent=${summary.sent} skipped=${summary.skipped} errors=${summary.errors}` | |
| 676 | ); | |
| 677 | } | |
| 678 | } catch (err) { | |
| 679 | console.error("[autopilot] onboarding-drip: threw:", err); | |
| 680 | } | |
| 681 | }, | |
| 682 | }, | |
| b93fc3e | 683 | { |
| 684 | // Smart morning digest — AI-curated daily developer queue. | |
| 685 | // Fires once per day at 07:00 UTC (or whenever the 22h outer gate | |
| 686 | // next opens after 07:00). Per-user 20h cooldown in sendSmartDigest | |
| 687 | // ensures no user receives more than one digest per day even if the | |
| 688 | // outer gate fires multiple times. Requires ANTHROPIC_API_KEY but | |
| 689 | // degrades gracefully to a rule-based prioritisation when unset. | |
| 690 | name: "smart-digest", | |
| 691 | run: async () => { | |
| 692 | const now = Date.now(); | |
| 693 | const nowDate = new Date(now); | |
| 694 | // Only fire at hour=7 UTC or if last run was >22h ago (catch-up) | |
| 695 | const isDigestHour = nowDate.getUTCHours() === 7; | |
| 696 | const pastCooldown = now - _lastSmartDigestAt >= SMART_DIGEST_INTERVAL_MS; | |
| 697 | if (!isDigestHour && !pastCooldown) return; | |
| 698 | _lastSmartDigestAt = now; | |
| 699 | try { | |
| 700 | await sendSmartDigestsToAll(); | |
| 701 | console.log("[autopilot] smart-digest: completed"); | |
| 702 | } catch (err) { | |
| 703 | console.error("[autopilot] smart-digest: threw:", err); | |
| 704 | } | |
| 705 | }, | |
| 706 | }, | |
| 2b821b7 | 707 | ]; |
| 708 | } | |
| 709 | ||
| b1be050 | 710 | // --------------------------------------------------------------------------- |
| 711 | // BLOCK S4 — synthetic-monitor task | |
| 712 | // --------------------------------------------------------------------------- | |
| 713 | ||
| 714 | export interface SyntheticMonitorTaskDeps { | |
| 715 | /** Override the suite runner (DI for tests). */ | |
| 716 | runChecks?: () => Promise<SyntheticCheckResult[]>; | |
| 717 | /** Override the persistence step (DI for tests). */ | |
| 718 | persist?: (results: SyntheticCheckResult[]) => Promise<void>; | |
| 719 | /** Override the previous-state loader (DI for tests). */ | |
| 720 | loadPrevious?: () => Promise<Record<string, SyntheticCheckResult>>; | |
| 721 | /** Override the webhook poster (DI for tests). */ | |
| 722 | postAlert?: (url: string, payload: unknown) => Promise<void>; | |
| 723 | /** Override the alert-webhook URL lookup (defaults to env). */ | |
| 724 | alertUrl?: () => string; | |
| 725 | } | |
| 726 | ||
| 727 | export interface SyntheticMonitorTaskSummary { | |
| 728 | green: number; | |
| 729 | red: number; | |
| 730 | yellow: number; | |
| 731 | transitions: number; | |
| 732 | } | |
| 733 | ||
| 734 | async function defaultPostAlert( | |
| 735 | url: string, | |
| 736 | payload: unknown | |
| 737 | ): Promise<void> { | |
| 738 | try { | |
| 739 | await fetch(url, { | |
| 740 | method: "POST", | |
| 741 | headers: { "Content-Type": "application/json" }, | |
| 742 | body: JSON.stringify(payload), | |
| 743 | }); | |
| 744 | } catch (err) { | |
| 745 | console.error("[autopilot] synthetic-monitor: alert webhook failed:", err); | |
| 746 | } | |
| 747 | } | |
| 748 | ||
| 749 | /** | |
| 750 | * One iteration of the synthetic-monitor task. Runs the checks, persists | |
| 751 | * them, compares against the prior state, and fires a webhook on each | |
| 752 | * green->red transition (red->red repeats stay quiet so we don't spam | |
| 753 | * the channel). Never throws. | |
| 754 | */ | |
| 755 | export async function runSyntheticMonitorTaskOnce( | |
| 756 | deps: SyntheticMonitorTaskDeps = {} | |
| 757 | ): Promise<SyntheticMonitorTaskSummary> { | |
| 758 | const runChecks = deps.runChecks ?? (() => runSyntheticChecks()); | |
| 759 | const persist = deps.persist ?? persistChecks; | |
| 760 | const loadPrevious = | |
| 761 | deps.loadPrevious ?? | |
| 762 | (async () => { | |
| 763 | const latest = await latestStatusByCheck(); | |
| 764 | // Strip the `checkedAt` from the result shape so the diff loop | |
| 765 | // compares the canonical SyntheticCheckResult fields only. | |
| 766 | const out: Record<string, SyntheticCheckResult> = {}; | |
| 767 | for (const [k, v] of Object.entries(latest)) { | |
| 768 | const { checkedAt: _unused, ...rest } = v; | |
| 769 | void _unused; | |
| 770 | out[k] = rest; | |
| 771 | } | |
| 772 | return out; | |
| 773 | }); | |
| 774 | const postAlert = deps.postAlert ?? defaultPostAlert; | |
| 775 | const alertUrl = | |
| 776 | deps.alertUrl ?? (() => process.env.MONITOR_ALERT_WEBHOOK_URL || ""); | |
| 777 | ||
| 778 | let previous: Record<string, SyntheticCheckResult> = {}; | |
| 779 | try { | |
| 780 | previous = await loadPrevious(); | |
| 781 | } catch (err) { | |
| 782 | console.error( | |
| 783 | "[autopilot] synthetic-monitor: loadPrevious threw:", | |
| 784 | err | |
| 785 | ); | |
| 786 | previous = {}; | |
| 787 | } | |
| 788 | ||
| 789 | const results = await runChecks(); | |
| 790 | await persist(results); | |
| 791 | ||
| 792 | let green = 0; | |
| 793 | let red = 0; | |
| 794 | let yellow = 0; | |
| 795 | let transitions = 0; | |
| 796 | const url = alertUrl(); | |
| 797 | ||
| 798 | for (const r of results) { | |
| 799 | if (r.status === "green") green += 1; | |
| 800 | else if (r.status === "red") red += 1; | |
| 801 | else yellow += 1; | |
| 802 | ||
| 803 | const prior = previous[r.name]; | |
| 804 | // green->red transition: prior was green (or absent and current is red | |
| 805 | // after a green is also a transition — but absent-before is treated as | |
| 806 | // green to avoid spamming on a fresh DB). We only alert on the | |
| 807 | // green->red edge so red->red doesn't re-fire. | |
| 808 | const priorWasGreen = !prior || prior.status === "green"; | |
| 809 | if (priorWasGreen && r.status === "red") { | |
| 810 | transitions += 1; | |
| 811 | if (url) { | |
| 812 | await postAlert(url, { | |
| 813 | check: r.name, | |
| 814 | status: r.status, | |
| 815 | statusCode: r.statusCode ?? null, | |
| 816 | durationMs: r.durationMs, | |
| 817 | error: r.error ?? null, | |
| 818 | checkedAt: new Date().toISOString(), | |
| 819 | }); | |
| 820 | } | |
| 821 | } | |
| 822 | } | |
| 823 | ||
| 824 | return { green, red, yellow, transitions }; | |
| 825 | } | |
| 826 | ||
| 46d6165 | 827 | // --------------------------------------------------------------------------- |
| 828 | // L1 — sleep-mode-digest | |
| 829 | // --------------------------------------------------------------------------- | |
| 830 | ||
| 831 | export interface SleepModeDigestCandidate { | |
| 832 | userId: string; | |
| 833 | digestHourUtc: number; | |
| e1fc7db | 834 | /** Independent cooldown anchor for the sleep-mode digest (migration 0077). */ |
| 835 | lastSleepDigestSentAt: Date | null; | |
| 46d6165 | 836 | } |
| 837 | ||
| 838 | export interface SleepModeDigestTaskDeps { | |
| 839 | /** Override the candidate finder. */ | |
| 840 | findCandidates?: (cap: number) => Promise<SleepModeDigestCandidate[]>; | |
| 841 | /** Override the send-one-user helper (DI for tests). */ | |
| 842 | sendOne?: (userId: string) => Promise<{ ok: boolean; reason?: string }>; | |
| 843 | /** Override the wall clock (DI for tests). */ | |
| 844 | now?: () => Date; | |
| 845 | /** Override the per-tick cap. */ | |
| 846 | cap?: number; | |
| 847 | /** Override the cooldown hours. */ | |
| 848 | cooldownHours?: number; | |
| 849 | } | |
| 850 | ||
| 851 | export interface SleepModeDigestTaskSummary { | |
| 852 | sent: number; | |
| 853 | skipped: number; | |
| 854 | } | |
| 855 | ||
| 856 | /** | |
| 857 | * Default candidate-finder. Returns enabled users whose | |
| e1fc7db | 858 | * `lastSleepDigestSentAt` is older than the cooldown OR null. The hour-match |
| 46d6165 | 859 | * filter is applied in JS by `runSleepModeDigestTaskOnce` so it stays |
| 860 | * timezone-independent of any SQL `extract(hour ...)` behaviour. | |
| e1fc7db | 861 | * Uses the dedicated `last_sleep_digest_sent_at` column (migration 0077) so |
| 862 | * the cooldown is independent of the weekly digest timer. | |
| 46d6165 | 863 | */ |
| 864 | async function defaultFindSleepModeCandidates( | |
| 865 | cap: number | |
| 866 | ): Promise<SleepModeDigestCandidate[]> { | |
| 867 | try { | |
| 868 | const rows = await db | |
| 869 | .select({ | |
| 870 | userId: users.id, | |
| 871 | digestHourUtc: users.sleepModeDigestHourUtc, | |
| e1fc7db | 872 | lastSleepDigestSentAt: users.lastSleepDigestSentAt, |
| 46d6165 | 873 | }) |
| 874 | .from(users) | |
| 875 | .where(eq(users.sleepModeEnabled, true)) | |
| 876 | .limit(cap); | |
| 877 | return rows.map((r) => ({ | |
| 878 | userId: r.userId, | |
| 879 | digestHourUtc: r.digestHourUtc, | |
| e1fc7db | 880 | lastSleepDigestSentAt: r.lastSleepDigestSentAt, |
| 46d6165 | 881 | })); |
| 882 | } catch (err) { | |
| 883 | console.error("[autopilot] sleep-mode-digest: candidate query failed:", err); | |
| 884 | return []; | |
| 885 | } | |
| 886 | } | |
| 887 | ||
| 888 | /** | |
| 889 | * One iteration of the sleep-mode-digest task. Never throws. | |
| 890 | * | |
| 891 | * Per-user filters (applied in JS so we can DI a clock): | |
| e1fc7db | 892 | * 1. `lastSleepDigestSentAt` is null OR older than cooldown (23h). |
| 46d6165 | 893 | * 2. `now.getUTCHours() === digestHourUtc` — fires once at the user's |
| 894 | * configured local UTC hour. | |
| 895 | * | |
| 896 | * Caps at `SLEEP_MODE_USER_CAP_PER_TICK` (100) users per tick. | |
| 897 | */ | |
| 898 | export async function runSleepModeDigestTaskOnce( | |
| 899 | deps: SleepModeDigestTaskDeps = {} | |
| 900 | ): Promise<SleepModeDigestTaskSummary> { | |
| 901 | const findCandidates = | |
| 902 | deps.findCandidates ?? defaultFindSleepModeCandidates; | |
| 903 | const sendOne = deps.sendOne ?? sendSleepModeDigestForUser; | |
| 904 | const now = deps.now ?? (() => new Date()); | |
| 905 | const cap = deps.cap ?? SLEEP_MODE_USER_CAP_PER_TICK; | |
| 906 | const cooldownHours = deps.cooldownHours ?? SLEEP_MODE_COOLDOWN_HOURS; | |
| 907 | ||
| 908 | let candidates: SleepModeDigestCandidate[] = []; | |
| 909 | try { | |
| 910 | candidates = await findCandidates(cap); | |
| 911 | } catch (err) { | |
| 912 | console.error("[autopilot] sleep-mode-digest: findCandidates threw:", err); | |
| 913 | return { sent: 0, skipped: 0 }; | |
| 914 | } | |
| 915 | ||
| 916 | const nowDate = now(); | |
| 917 | const currentHour = nowDate.getUTCHours(); | |
| 918 | const cooldownMs = cooldownHours * 60 * 60 * 1000; | |
| 919 | ||
| 920 | let sent = 0; | |
| 921 | let skipped = 0; | |
| 922 | ||
| 923 | for (const cand of candidates) { | |
| 924 | try { | |
| 925 | // Hour-match: must equal the user's configured UTC delivery hour. | |
| 926 | if (cand.digestHourUtc !== currentHour) { | |
| 927 | skipped += 1; | |
| 928 | continue; | |
| 929 | } | |
| 930 | // Cooldown: skip if we sent within the last cooldown window. | |
| 931 | if ( | |
| e1fc7db | 932 | cand.lastSleepDigestSentAt && |
| 933 | nowDate.getTime() - new Date(cand.lastSleepDigestSentAt).getTime() < | |
| 46d6165 | 934 | cooldownMs |
| 935 | ) { | |
| 936 | skipped += 1; | |
| 937 | continue; | |
| 938 | } | |
| 939 | const result = await sendOne(cand.userId); | |
| 940 | if (result.ok) sent += 1; | |
| 941 | else skipped += 1; | |
| 942 | } catch (err) { | |
| 943 | skipped += 1; | |
| 944 | console.error( | |
| 945 | `[autopilot] sleep-mode-digest: per-user failure for user=${cand.userId}:`, | |
| 946 | err | |
| 947 | ); | |
| 948 | } | |
| 949 | } | |
| 950 | ||
| 951 | return { sent, skipped }; | |
| 952 | } | |
| 953 | ||
| 534f04a | 954 | // --------------------------------------------------------------------------- |
| 955 | // M3 — pr-risk-rescore | |
| 956 | // --------------------------------------------------------------------------- | |
| 957 | ||
| 958 | export interface PrRiskRescoreCandidate { | |
| 959 | pullRequestId: string; | |
| 960 | headBranch: string; | |
| 961 | updatedAt: Date; | |
| 962 | } | |
| 963 | ||
| 964 | export interface PrRiskRescoreTaskDeps { | |
| 965 | /** Override candidate finder for tests. */ | |
| 966 | findCandidates?: ( | |
| 967 | lookbackHours: number, | |
| 968 | cap: number | |
| 969 | ) => Promise<PrRiskRescoreCandidate[]>; | |
| 970 | /** Override score computation for tests. */ | |
| 971 | scoreOne?: (prId: string) => Promise<{ ok: boolean }>; | |
| 972 | /** Override per-tick cap. */ | |
| 973 | cap?: number; | |
| 974 | /** Override lookback. */ | |
| 975 | lookbackHours?: number; | |
| 976 | } | |
| 977 | ||
| 978 | export interface PrRiskRescoreTaskSummary { | |
| 979 | scored: number; | |
| 980 | skipped: number; | |
| 981 | } | |
| 982 | ||
| 983 | /** | |
| 984 | * Default candidate-finder. Returns open, non-draft PRs from non-archived | |
| 985 | * repos whose `updated_at` falls inside the lookback window. The "scored | |
| 986 | * at all" filter is applied as a second pass via `defaultFilterNeedsScoring`. | |
| 987 | */ | |
| 988 | async function defaultFindPrRiskCandidates( | |
| 989 | lookbackHours: number, | |
| 990 | cap: number | |
| 991 | ): Promise<PrRiskRescoreCandidate[]> { | |
| 992 | const cutoff = new Date(Date.now() - lookbackHours * 60 * 60 * 1000); | |
| 993 | try { | |
| 994 | const rows = await db | |
| 995 | .select({ | |
| 996 | pullRequestId: pullRequests.id, | |
| 997 | headBranch: pullRequests.headBranch, | |
| 998 | updatedAt: pullRequests.updatedAt, | |
| 999 | }) | |
| 1000 | .from(pullRequests) | |
| 1001 | .innerJoin( | |
| 1002 | repositories, | |
| 1003 | eq(repositories.id, pullRequests.repositoryId) | |
| 1004 | ) | |
| 1005 | .where( | |
| 1006 | and( | |
| 1007 | eq(pullRequests.state, "open"), | |
| 1008 | eq(pullRequests.isDraft, false), | |
| 1009 | eq(repositories.isArchived, false), | |
| 1010 | gte(pullRequests.updatedAt, cutoff) | |
| 1011 | ) | |
| 1012 | ) | |
| 1013 | .orderBy(sql`${pullRequests.updatedAt} DESC`) | |
| 1014 | .limit(cap); | |
| 1015 | return rows.map((r) => ({ | |
| 1016 | pullRequestId: r.pullRequestId, | |
| 1017 | headBranch: r.headBranch, | |
| 1018 | updatedAt: r.updatedAt, | |
| 1019 | })); | |
| 1020 | } catch (err) { | |
| 1021 | console.error("[autopilot] pr-risk-rescore: candidate query failed:", err); | |
| 1022 | return []; | |
| 1023 | } | |
| 1024 | } | |
| 1025 | ||
| 1026 | /** | |
| 1027 | * Drop candidates that already have ANY cached score row. The unique | |
| 1028 | * constraint on (pull_request_id, commit_sha) handles the "score-the- | |
| 1029 | * same-SHA-twice" case at persist time; this filter just keeps the work | |
| 1030 | * list small enough to fit under the per-tick cap when many PRs are | |
| 1031 | * being pushed concurrently. | |
| 1032 | */ | |
| 1033 | async function defaultFilterNeedsScoring( | |
| 1034 | candidates: PrRiskRescoreCandidate[] | |
| 1035 | ): Promise<PrRiskRescoreCandidate[]> { | |
| 1036 | if (candidates.length === 0) return []; | |
| 1037 | try { | |
| 1038 | const rows = await db | |
| 1039 | .select({ pullRequestId: prRiskScores.pullRequestId }) | |
| 1040 | .from(prRiskScores); | |
| 1041 | const scoredIds = new Set(rows.map((r) => r.pullRequestId)); | |
| 1042 | return candidates.filter((c) => !scoredIds.has(c.pullRequestId)); | |
| 1043 | } catch (err) { | |
| 1044 | console.error("[autopilot] pr-risk-rescore: filter query failed:", err); | |
| 1045 | // Fail-open: better to score everything than silently skip. | |
| 1046 | return candidates; | |
| 1047 | } | |
| 1048 | } | |
| 1049 | ||
| 1050 | /** | |
| 1051 | * One iteration of the pr-risk-rescore task. Never throws. Compute risk | |
| 1052 | * for up to `cap` recently-touched open PRs that have no cached score | |
| 1053 | * yet, so reviewers usually see a populated card on first visit. | |
| 1054 | */ | |
| 1055 | export async function runPrRiskRescoreTaskOnce( | |
| 1056 | deps: PrRiskRescoreTaskDeps = {} | |
| 1057 | ): Promise<PrRiskRescoreTaskSummary> { | |
| 1058 | const findCandidates = deps.findCandidates ?? defaultFindPrRiskCandidates; | |
| 1059 | const scoreOne = | |
| 1060 | deps.scoreOne ?? | |
| 1061 | (async (prId: string) => { | |
| 1062 | try { | |
| 1063 | const result = await computePrRiskForPullRequest(prId); | |
| 1064 | return { ok: result !== null }; | |
| 1065 | } catch { | |
| 1066 | return { ok: false }; | |
| 1067 | } | |
| 1068 | }); | |
| 1069 | const cap = deps.cap ?? PR_RISK_RESCORE_MAX_PER_TICK; | |
| 1070 | const lookbackHours = | |
| 1071 | deps.lookbackHours ?? PR_RISK_RESCORE_LOOKBACK_HOURS; | |
| 1072 | ||
| 1073 | let candidates: PrRiskRescoreCandidate[] = []; | |
| 1074 | try { | |
| 1075 | candidates = await findCandidates(lookbackHours, cap); | |
| 1076 | } catch (err) { | |
| 1077 | console.error("[autopilot] pr-risk-rescore: findCandidates threw:", err); | |
| 1078 | return { scored: 0, skipped: 0 }; | |
| 1079 | } | |
| 1080 | ||
| 1081 | // Only score PRs missing a cached row. Skip filter when the caller | |
| 1082 | // injected a custom finder (tests pass already-filtered lists). | |
| 1083 | const needsScoring = | |
| 1084 | deps.findCandidates === undefined | |
| 1085 | ? await defaultFilterNeedsScoring(candidates) | |
| 1086 | : candidates; | |
| 1087 | ||
| 1088 | let scored = 0; | |
| 1089 | let skipped = 0; | |
| 1090 | for (const cand of needsScoring.slice(0, cap)) { | |
| 1091 | try { | |
| 1092 | const result = await scoreOne(cand.pullRequestId); | |
| 1093 | if (result.ok) scored += 1; | |
| 1094 | else skipped += 1; | |
| 1095 | } catch (err) { | |
| 1096 | skipped += 1; | |
| 1097 | console.error( | |
| 1098 | `[autopilot] pr-risk-rescore: per-PR failure for pr=${cand.pullRequestId}:`, | |
| 1099 | err | |
| 1100 | ); | |
| 1101 | } | |
| 1102 | } | |
| 1103 | if (needsScoring.length > cap) { | |
| 1104 | skipped += needsScoring.length - cap; | |
| 1105 | } | |
| 1106 | ||
| 1107 | return { scored, skipped }; | |
| 1108 | } | |
| 1109 | ||
| 2b9055e | 1110 | // --------------------------------------------------------------------------- |
| 1111 | // K3 — auto-merge-sweep | |
| 1112 | // --------------------------------------------------------------------------- | |
| 1113 | ||
| 1114 | interface SweepCandidate { | |
| 1115 | prId: string; | |
| 1116 | prNumber: number; | |
| 1117 | prTitle: string; | |
| 1118 | prBody: string | null; | |
| 1119 | baseBranch: string; | |
| 1120 | headBranch: string; | |
| 1121 | isDraft: boolean; | |
| 1122 | repositoryId: string; | |
| 1123 | authorUserId: string; | |
| 1124 | ownerUsername: string | null; | |
| 1125 | repoName: string; | |
| 1126 | state: string; | |
| 1127 | } | |
| 1128 | ||
| 1129 | export interface AutoMergeSweepDeps { | |
| 1130 | /** Inject candidate-finder for tests. */ | |
| 1131 | findCandidates?: (lookbackHours: number, limit: number) => Promise<SweepCandidate[]>; | |
| 1132 | /** Inject evaluator for tests. */ | |
| 1133 | evaluate?: (ctx: AutoMergeContext) => Promise<AutoMergeDecision>; | |
| 1134 | /** Inject the merge executor for tests. */ | |
| 1135 | merge?: (cand: SweepCandidate) => Promise<PerformMergeResult>; | |
| 1136 | /** Inject the audit-recording side-effect for tests. */ | |
| 1137 | recordAttempt?: ( | |
| 1138 | repoId: string, | |
| 1139 | prId: string, | |
| 1140 | decision: AutoMergeDecision | |
| 1141 | ) => Promise<void>; | |
| 1142 | /** Inject the audit/comment side-effects for the merged path (tests). */ | |
| 1143 | onMerged?: ( | |
| 1144 | cand: SweepCandidate, | |
| 1145 | result: PerformMergeResult | |
| 1146 | ) => Promise<void>; | |
| 1147 | /** Inject the audit side-effect for the merge-failed path (tests). */ | |
| 1148 | onMergeFailed?: (cand: SweepCandidate, error: string) => Promise<void>; | |
| 1149 | /** Inject the AI-key short-circuit signal for tests. */ | |
| 1150 | shouldShortCircuitAi?: (cand: SweepCandidate) => Promise<boolean>; | |
| 1151 | } | |
| 1152 | ||
| 1153 | export interface AutoMergeSweepSummary { | |
| 1154 | evaluated: number; | |
| 1155 | merged: number; | |
| 1156 | blocked: number; | |
| 1157 | } | |
| 1158 | ||
| 1159 | /** | |
| 1160 | * Default candidate-finder. Selects open, non-draft PRs from non-archived | |
| 1161 | * repos whose `updated_at` is within the lookback window. Joins repo + | |
| 1162 | * owner so the merge executor doesn't need extra round trips. Cap is | |
| 1163 | * enforced at the SQL layer. | |
| 1164 | */ | |
| 1165 | async function defaultFindAutoMergeCandidates( | |
| 1166 | lookbackHours: number, | |
| 1167 | limit: number | |
| 1168 | ): Promise<SweepCandidate[]> { | |
| 1169 | const cutoff = new Date(Date.now() - lookbackHours * 60 * 60 * 1000); | |
| 1170 | try { | |
| 1171 | const rows = await db | |
| 1172 | .select({ | |
| 1173 | prId: pullRequests.id, | |
| 1174 | prNumber: pullRequests.number, | |
| 1175 | prTitle: pullRequests.title, | |
| 1176 | prBody: pullRequests.body, | |
| 1177 | baseBranch: pullRequests.baseBranch, | |
| 1178 | headBranch: pullRequests.headBranch, | |
| 1179 | isDraft: pullRequests.isDraft, | |
| 1180 | repositoryId: pullRequests.repositoryId, | |
| 1181 | authorUserId: pullRequests.authorId, | |
| 1182 | ownerUsername: users.username, | |
| 1183 | repoName: repositories.name, | |
| 1184 | state: pullRequests.state, | |
| 1185 | }) | |
| 1186 | .from(pullRequests) | |
| 1187 | .innerJoin( | |
| 1188 | repositories, | |
| 1189 | eq(repositories.id, pullRequests.repositoryId) | |
| 1190 | ) | |
| 1191 | .leftJoin(users, eq(users.id, repositories.ownerId)) | |
| 1192 | .where( | |
| 1193 | and( | |
| 1194 | eq(pullRequests.state, "open"), | |
| 1195 | eq(pullRequests.isDraft, false), | |
| 1196 | eq(repositories.isArchived, false), | |
| 1197 | gte(pullRequests.updatedAt, cutoff) | |
| 1198 | ) | |
| 1199 | ) | |
| 1200 | .limit(limit); | |
| 1201 | return rows.map((r) => ({ | |
| 1202 | prId: r.prId, | |
| 1203 | prNumber: r.prNumber, | |
| 1204 | prTitle: r.prTitle, | |
| 1205 | prBody: r.prBody, | |
| 1206 | baseBranch: r.baseBranch, | |
| 1207 | headBranch: r.headBranch, | |
| 1208 | isDraft: r.isDraft, | |
| 1209 | repositoryId: r.repositoryId, | |
| 1210 | authorUserId: r.authorUserId, | |
| 1211 | ownerUsername: r.ownerUsername ?? null, | |
| 1212 | repoName: r.repoName, | |
| 1213 | state: r.state, | |
| 1214 | })); | |
| 1215 | } catch (err) { | |
| 1216 | console.error("[autopilot] auto-merge: candidate query failed:", err); | |
| 1217 | return []; | |
| 1218 | } | |
| 1219 | } | |
| 1220 | ||
| 1221 | /** | |
| 1222 | * Determine whether the matched branch_protection rule on this PR | |
| 1223 | * requires AI approval but no `ANTHROPIC_API_KEY` is configured. In that | |
| 1224 | * case the AI-approval check would inevitably fail downstream, so we | |
| 1225 | * short-circuit to a "blocked" decision without invoking `evaluateAutoMerge` | |
| 1226 | * — keeps the log readable and prevents misleading "AI review unavailable" | |
| 1227 | * lines in the audit trail. | |
| 1228 | */ | |
| 1229 | async function defaultShouldShortCircuitAi( | |
| 1230 | cand: SweepCandidate | |
| 1231 | ): Promise<boolean> { | |
| 1232 | if (process.env.ANTHROPIC_API_KEY) return false; | |
| 1233 | try { | |
| 1234 | const rule = await matchProtection(cand.repositoryId, cand.baseBranch); | |
| 1235 | return !!(rule && rule.requireAiApproval); | |
| 1236 | } catch { | |
| 1237 | return false; | |
| 1238 | } | |
| 1239 | } | |
| 1240 | ||
| 1241 | /** | |
| 1242 | * Default success-path: post an `auto_merge.merged` audit row + a stable | |
| 1243 | * marker comment on the PR so a partial-merge retry doesn't double-post. | |
| 1244 | * Both are best-effort; failures are logged not thrown. | |
| 1245 | */ | |
| 1246 | async function defaultOnMerged( | |
| 1247 | cand: SweepCandidate, | |
| 1248 | result: PerformMergeResult | |
| 1249 | ): Promise<void> { | |
| 1250 | try { | |
| 1251 | await audit({ | |
| 1252 | repositoryId: cand.repositoryId, | |
| 1253 | action: "auto_merge.merged", | |
| 1254 | targetType: "pull_request", | |
| 1255 | targetId: cand.prId, | |
| 1256 | metadata: { | |
| 1257 | prNumber: cand.prNumber, | |
| 1258 | baseBranch: cand.baseBranch, | |
| 1259 | headBranch: cand.headBranch, | |
| 1260 | closedIssueNumbers: result.closedIssueNumbers, | |
| 1261 | resolvedFiles: result.resolvedFiles, | |
| 1262 | }, | |
| 1263 | }); | |
| 1264 | } catch (err) { | |
| 1265 | console.error("[autopilot] auto-merge: merged audit failed:", err); | |
| 1266 | } | |
| 1267 | try { | |
| a7460bf | 1268 | const commentAuthorId = await getBotUserIdOrFallback(cand.authorUserId); |
| 2b9055e | 1269 | await db.insert(prComments).values({ |
| 1270 | pullRequestId: cand.prId, | |
| a7460bf | 1271 | authorId: commentAuthorId, |
| 2b9055e | 1272 | isAiReview: true, |
| 1273 | body: `${AUTO_MERGE_COMMENT_MARKER}\nAuto-merged by Gluecron autopilot — branch protection conditions satisfied.`, | |
| 1274 | }); | |
| 1275 | } catch (err) { | |
| 1276 | console.error("[autopilot] auto-merge: comment insert failed:", err); | |
| 1277 | } | |
| 1278 | } | |
| 1279 | ||
| 1280 | /** Default failure-path: only an audit row; no comment (we may retry). */ | |
| 1281 | async function defaultOnMergeFailed( | |
| 1282 | cand: SweepCandidate, | |
| 1283 | error: string | |
| 1284 | ): Promise<void> { | |
| 1285 | try { | |
| 1286 | await audit({ | |
| 1287 | repositoryId: cand.repositoryId, | |
| 1288 | action: "auto_merge.merge_failed", | |
| 1289 | targetType: "pull_request", | |
| 1290 | targetId: cand.prId, | |
| 1291 | metadata: { | |
| 1292 | prNumber: cand.prNumber, | |
| 1293 | baseBranch: cand.baseBranch, | |
| 1294 | headBranch: cand.headBranch, | |
| 1295 | error, | |
| 1296 | }, | |
| 1297 | }); | |
| 1298 | } catch (err) { | |
| 1299 | console.error("[autopilot] auto-merge: merge_failed audit failed:", err); | |
| 1300 | } | |
| 1301 | } | |
| 1302 | ||
| 1303 | /** | |
| 1304 | * Execute one sweep over recently-updated open PRs. For each, evaluate | |
| 1305 | * with K2's `evaluateAutoMerge`; on `merge: true`, call `performMerge` and | |
| 1306 | * record the merged/merge-failed audit row + comment. Always record the | |
| 1307 | * `auto_merge.evaluated` audit row via `recordAutoMergeAttempt`. | |
| 1308 | * | |
| 1309 | * Returns a counts summary that the autopilot prints as the tick log line. | |
| 1310 | * Never throws. | |
| 1311 | */ | |
| 1312 | export async function runAutoMergeSweep( | |
| 1313 | deps: AutoMergeSweepDeps = {} | |
| 1314 | ): Promise<AutoMergeSweepSummary> { | |
| 1315 | const findCandidates = deps.findCandidates ?? defaultFindAutoMergeCandidates; | |
| 1316 | const evaluate = | |
| 1317 | deps.evaluate ?? ((ctx) => evaluateAutoMerge(ctx, {})); | |
| 1318 | const merge = | |
| 1319 | deps.merge ?? | |
| 1320 | (async (cand) => { | |
| 1321 | if (!cand.ownerUsername) { | |
| 1322 | return { | |
| 1323 | ok: false, | |
| 1324 | error: "owner username unresolved", | |
| 1325 | closedIssueNumbers: [], | |
| 1326 | resolvedFiles: [], | |
| 1327 | }; | |
| 1328 | } | |
| 1329 | return performMerge({ | |
| 1330 | pr: { | |
| 1331 | id: cand.prId, | |
| 1332 | number: cand.prNumber, | |
| 1333 | title: cand.prTitle, | |
| 1334 | body: cand.prBody, | |
| 1335 | baseBranch: cand.baseBranch, | |
| 1336 | headBranch: cand.headBranch, | |
| 1337 | repositoryId: cand.repositoryId, | |
| 1338 | authorId: cand.authorUserId, | |
| 1339 | state: cand.state as "open", | |
| 1340 | isDraft: cand.isDraft, | |
| 1341 | }, | |
| 1342 | ownerName: cand.ownerUsername, | |
| 1343 | repoName: cand.repoName, | |
| 1344 | actorUserId: cand.authorUserId, | |
| 1345 | }); | |
| 1346 | }); | |
| 1347 | const recordAttempt = deps.recordAttempt ?? recordAutoMergeAttempt; | |
| 1348 | const onMerged = deps.onMerged ?? defaultOnMerged; | |
| 1349 | const onMergeFailed = deps.onMergeFailed ?? defaultOnMergeFailed; | |
| 1350 | const shouldShortCircuitAi = | |
| 1351 | deps.shouldShortCircuitAi ?? defaultShouldShortCircuitAi; | |
| 1352 | ||
| 1353 | let candidates: SweepCandidate[] = []; | |
| 1354 | try { | |
| 1355 | candidates = await findCandidates( | |
| 1356 | AUTO_MERGE_LOOKBACK_HOURS, | |
| 1357 | AUTO_MERGE_MAX_PER_TICK | |
| 1358 | ); | |
| 1359 | } catch (err) { | |
| 1360 | console.error("[autopilot] auto-merge: findCandidates threw:", err); | |
| 1361 | return { evaluated: 0, merged: 0, blocked: 0 }; | |
| 1362 | } | |
| 1363 | ||
| 1364 | let evaluated = 0; | |
| 1365 | let merged = 0; | |
| 1366 | let blocked = 0; | |
| 1367 | ||
| 1368 | for (const cand of candidates) { | |
| 1369 | try { | |
| 1370 | evaluated += 1; | |
| 1371 | ||
| 1372 | // AI-key short-circuit: if the rule requires AI approval and we have | |
| 1373 | // no key, treat as blocked without calling the evaluator (which would | |
| 1374 | // log a misleading "AI review unavailable"). | |
| 1375 | let decision: AutoMergeDecision; | |
| 1376 | if (await shouldShortCircuitAi(cand)) { | |
| 1377 | decision = { | |
| 1378 | merge: false, | |
| 1379 | reason: | |
| 1380 | "Branch protection requires AI approval but ANTHROPIC_API_KEY is unset.", | |
| 1381 | blocking: [ | |
| 1382 | "ANTHROPIC_API_KEY missing; AI approval cannot be sourced.", | |
| 1383 | ], | |
| 1384 | }; | |
| 1385 | } else { | |
| 1386 | decision = await evaluate({ | |
| 1387 | pullRequestId: cand.prId, | |
| 1388 | repositoryId: cand.repositoryId, | |
| 1389 | baseBranch: cand.baseBranch, | |
| 1390 | isDraft: cand.isDraft, | |
| 1391 | authorUserId: cand.authorUserId, | |
| 1392 | }); | |
| 1393 | } | |
| 1394 | ||
| 1395 | // Always record the evaluation, regardless of outcome. | |
| 1396 | try { | |
| 1397 | await recordAttempt(cand.repositoryId, cand.prId, decision); | |
| 1398 | } catch (err) { | |
| 1399 | console.error( | |
| 1400 | `[autopilot] auto-merge: recordAttempt failed for pr=${cand.prId}:`, | |
| 1401 | err | |
| 1402 | ); | |
| 1403 | } | |
| 1404 | ||
| 1405 | if (!decision.merge) { | |
| 1406 | blocked += 1; | |
| 1407 | continue; | |
| 1408 | } | |
| 1409 | ||
| 1410 | // Perform the actual merge. | |
| 1411 | const result = await merge(cand); | |
| 1412 | if (result.ok) { | |
| 1413 | merged += 1; | |
| 1414 | await onMerged(cand, result); | |
| 1415 | } else { | |
| 1416 | blocked += 1; | |
| 1417 | await onMergeFailed(cand, result.error || "unknown merge error"); | |
| 1418 | } | |
| 1419 | } catch (err) { | |
| 1420 | blocked += 1; | |
| 1421 | console.error( | |
| 1422 | `[autopilot] auto-merge: per-PR failure for pr=${cand.prId}:`, | |
| 1423 | err | |
| 1424 | ); | |
| 1425 | } | |
| 1426 | } | |
| 1427 | ||
| 1428 | console.log( | |
| 1429 | `[autopilot] auto-merge: evaluated=${evaluated} merged=${merged} blocked=${blocked}` | |
| 1430 | ); | |
| 1431 | ||
| 1432 | return { evaluated, merged, blocked }; | |
| 1433 | } | |
| 1434 | ||
| 2b821b7 | 1435 | /** |
| 1436 | * Visits each distinct (repo, base_branch) that has queued rows and logs a | |
| 1437 | * stub depth line. The actual gate-running + merge happens in the pulls | |
| 1438 | * route; this tick is just a heartbeat so we can wire per-queue progress | |
| 1439 | * through without duplicating merge logic. | |
| 1440 | */ | |
| 1441 | async function processMergeQueues(): Promise<void> { | |
| 1442 | let distinct: Array<{ repositoryId: string; baseBranch: string }> = []; | |
| 1443 | try { | |
| 1444 | const rows = await db | |
| 1445 | .selectDistinct({ | |
| 1446 | repositoryId: mergeQueueEntries.repositoryId, | |
| 1447 | baseBranch: mergeQueueEntries.baseBranch, | |
| 1448 | }) | |
| 1449 | .from(mergeQueueEntries) | |
| 1450 | .where(sql`${mergeQueueEntries.state} IN ('queued','running')`); | |
| 1451 | distinct = rows; | |
| 1452 | } catch (err) { | |
| 1453 | console.error("[autopilot] merge-queue: distinct query failed:", err); | |
| 1454 | return; | |
| 1455 | } | |
| 1456 | for (const d of distinct) { | |
| 1457 | try { | |
| 1458 | const head = await peekHead(d.repositoryId, d.baseBranch); | |
| 1459 | if (head) { | |
| 1460 | console.log( | |
| 1461 | `[autopilot] merge queue depth head=${head.id.slice(0, 8)} repo=${d.repositoryId.slice(0, 8)} base=${d.baseBranch}` | |
| 1462 | ); | |
| 1463 | } | |
| 1464 | } catch (err) { | |
| 1465 | console.error( | |
| 1466 | `[autopilot] merge-queue: peek failed for repo=${d.repositoryId}:`, | |
| 1467 | err | |
| 1468 | ); | |
| 1469 | } | |
| 1470 | } | |
| 1471 | } | |
| 1472 | ||
| 1473 | /** | |
| 1474 | * Pick a small batch of repos that actually have dep rows and re-run | |
| 1475 | * advisory scan against them. Cheap — one SELECT DISTINCT with LIMIT. | |
| 1476 | */ | |
| 1477 | async function rescanAdvisoriesBatch(limit: number): Promise<void> { | |
| 1478 | let repoIds: string[] = []; | |
| 1479 | try { | |
| 1480 | const rows = await db | |
| 1481 | .selectDistinct({ repositoryId: repoDependencies.repositoryId }) | |
| 1482 | .from(repoDependencies) | |
| 1483 | .limit(limit); | |
| 1484 | repoIds = rows.map((r) => r.repositoryId); | |
| 1485 | } catch (err) { | |
| 1486 | console.error("[autopilot] advisory-rescan: query failed:", err); | |
| 1487 | return; | |
| 1488 | } | |
| 1489 | for (const id of repoIds) { | |
| 1490 | try { | |
| 1491 | await scanRepositoryForAlerts(id); | |
| 1492 | } catch (err) { | |
| 1493 | console.error( | |
| 1494 | `[autopilot] advisory-rescan: scan failed for repo=${id}:`, | |
| 1495 | err | |
| 1496 | ); | |
| 1497 | } | |
| 1498 | } | |
| 1499 | } | |
| 1500 | ||
| 1501 | /** Resolve the tick interval from env → opts → default. */ | |
| 1502 | function resolveIntervalMs(optsMs?: number): number { | |
| 1503 | if (typeof optsMs === "number" && optsMs > 0) return optsMs; | |
| 1504 | const raw = process.env.AUTOPILOT_INTERVAL_MS; | |
| 1505 | if (raw) { | |
| 1506 | const parsed = Number(raw); | |
| 1507 | if (Number.isFinite(parsed) && parsed > 0) return parsed; | |
| 1508 | } | |
| 1509 | return DEFAULT_INTERVAL_MS; | |
| 1510 | } | |
| 1511 | ||
| 1512 | /** | |
| 1513 | * Start the recurring autopilot loop. No-op when AUTOPILOT_DISABLED=1. | |
| 1514 | * The first tick fires after `intervalMs`, not immediately, to keep boot | |
| 1515 | * fast. Returns a `stop()` that clears the interval. | |
| 1516 | */ | |
| 1517 | export function startAutopilot(opts?: StartAutopilotOpts): { stop: () => void } { | |
| 1518 | if (process.env.AUTOPILOT_DISABLED === "1") { | |
| 1519 | return { stop: () => {} }; | |
| 1520 | } | |
| 1521 | const intervalMs = resolveIntervalMs(opts?.intervalMs); | |
| 1522 | const tasks = opts?.tasks ?? defaultTasks(); | |
| 1523 | let running = false; | |
| 1524 | const handle = setInterval(() => { | |
| 1525 | if (running) return; | |
| 1526 | running = true; | |
| 1527 | void runAutopilotTick({ tasks, now: opts?.now }) | |
| 1528 | .catch(() => { | |
| 1529 | // runAutopilotTick already never throws, but belt-and-braces. | |
| 1530 | }) | |
| 1531 | .finally(() => { | |
| 1532 | running = false; | |
| 1533 | }); | |
| 1534 | }, intervalMs); | |
| 1535 | return { | |
| 1536 | stop: () => clearInterval(handle), | |
| 1537 | }; | |
| 1538 | } | |
| 1539 | ||
| 8e9f1d9 | 1540 | /** Last tick snapshot for observability. Module-level, swap-on-complete. */ |
| 1541 | let lastTick: AutopilotTickResult | null = null; | |
| 1542 | let tickCount = 0; | |
| 1543 | ||
| 1544 | /** Return the most recent completed tick, or null if autopilot hasn't run yet. */ | |
| 1545 | export function getLastTick(): AutopilotTickResult | null { | |
| 1546 | return lastTick; | |
| 1547 | } | |
| 1548 | ||
| 1549 | /** Return the total number of completed ticks in this process. */ | |
| 1550 | export function getTickCount(): number { | |
| 1551 | return tickCount; | |
| 1552 | } | |
| 1553 | ||
| 2b821b7 | 1554 | /** |
| 1555 | * Run one tick: invokes every sub-task with its own try/catch, records a | |
| 1556 | * per-task result, and emits a single summary line. Never throws. | |
| 1557 | */ | |
| 1558 | export async function runAutopilotTick( | |
| 1559 | opts?: RunTickOpts | |
| 1560 | ): Promise<AutopilotTickResult> { | |
| 1561 | const now = opts?.now ?? Date.now; | |
| 1562 | const tasks = opts?.tasks ?? defaultTasks(); | |
| 1563 | const startedAt = new Date(now()).toISOString(); | |
| 1564 | const results: AutopilotTaskResult[] = []; | |
| 1565 | for (const t of tasks) { | |
| 1566 | const t0 = now(); | |
| 1567 | try { | |
| 1568 | await t.run(); | |
| 1569 | results.push({ name: t.name, ok: true, durationMs: now() - t0 }); | |
| 1570 | } catch (err) { | |
| 1571 | const message = | |
| 1572 | err instanceof Error ? err.message : String(err ?? "unknown error"); | |
| 1573 | console.error(`[autopilot] ${t.name}: ${message}`); | |
| 1574 | results.push({ | |
| 1575 | name: t.name, | |
| 1576 | ok: false, | |
| 1577 | durationMs: now() - t0, | |
| 1578 | error: message, | |
| 1579 | }); | |
| 1580 | } | |
| 1581 | } | |
| 1582 | const finishedAt = new Date(now()).toISOString(); | |
| 1583 | const totalMs = results.reduce((a, r) => a + r.durationMs, 0); | |
| 1584 | const okCount = results.filter((r) => r.ok).length; | |
| 1585 | console.log( | |
| 1586 | `[autopilot] tick ok tasks=${okCount}/${results.length} ms=${totalMs}` | |
| 1587 | ); | |
| 8e9f1d9 | 1588 | const result: AutopilotTickResult = { startedAt, finishedAt, tasks: results }; |
| 1589 | lastTick = result; | |
| 1590 | tickCount += 1; | |
| 1591 | return result; | |
| 2b821b7 | 1592 | } |
| 1593 | ||
| 1594 | /** Exposed for unit tests. */ | |
| 1595 | export const __test = { | |
| 1596 | resolveIntervalMs, | |
| 1597 | processMergeQueues, | |
| 1598 | rescanAdvisoriesBatch, | |
| 1599 | DEFAULT_INTERVAL_MS, | |
| 1600 | ADVISORY_RESCAN_BATCH, | |
| 2b9055e | 1601 | AUTO_MERGE_LOOKBACK_HOURS, |
| 1602 | AUTO_MERGE_MAX_PER_TICK, | |
| 1603 | AUTO_MERGE_COMMENT_MARKER, | |
| 534f04a | 1604 | PR_RISK_RESCORE_MAX_PER_TICK, |
| 1605 | PR_RISK_RESCORE_LOOKBACK_HOURS, | |
| 2b9055e | 1606 | defaultFindAutoMergeCandidates, |
| 1607 | defaultOnMerged, | |
| 1608 | defaultOnMergeFailed, | |
| 1609 | defaultShouldShortCircuitAi, | |
| 534f04a | 1610 | defaultFindPrRiskCandidates, |
| 1611 | defaultFilterNeedsScoring, | |
| 2b821b7 | 1612 | }; |