|
| 1 | +// Self-heal (flag-gated by GITTENSORY_SWEEP_WATCHDOG). The scheduled regate sweep (fanOutAgentRegateSweepJobs / |
| 2 | +// sweepRepoRegate, src/queue/processors.ts) advances every acting-autonomy repo's `last_regated_at` marker on |
| 3 | +// every successful sweep tick. When the sweep stops advancing that marker for a repo — a stalled cron, a wedged |
| 4 | +// per-repo failure that keeps recurring, a rate-limit floor that never clears — nothing in the system previously |
| 5 | +// noticed on its own; the 2026-07-06 incident stayed silent for hours until a human queried the database. This |
| 6 | +// watchdog closes that gap: it runs the SAME repo-selection the sweep itself uses, and for any repo with open |
| 7 | +// PRs whose sweep marker hasn't advanced within the staleness window, it (a) emits a structured Sentry-visible |
| 8 | +// log, and (b) re-enqueues a single targeted `agent-regate-sweep` for just that repo — the same message shape |
| 9 | +// the normal fan-out sends, so this is a pure "nudge," never a bypass of the sweep's own gating/dedup logic. |
| 10 | +// |
| 11 | +// Default OFF (like every other *-wire-adjacent convergence capability) — flag-OFF this module is never invoked |
| 12 | +// and the cron enqueues no watchdog job, byte-identical to today. |
| 13 | + |
| 14 | +import { countOpenPullRequests, getLatestRegatedAt, listRepositories } from "../db/repositories"; |
| 15 | +import { isAgentConfigured } from "../settings/autonomy"; |
| 16 | +import { resolveRepositorySettings } from "../settings/repository-settings"; |
| 17 | +import type { JobMessage } from "../types"; |
| 18 | +import { errorMessage, nowIso } from "../utils/json"; |
| 19 | +import { isConvergenceRepoAllowed, listConvergenceRepos } from "./cutover-gate"; |
| 20 | + |
| 21 | +/** True when the sweep-liveness watchdog is enabled. Flag-OFF (default) → the caller never invokes it, so the |
| 22 | + * cron enqueues no watchdog job and the queue processor no-ops on a stale in-flight one (defense-in-depth, |
| 23 | + * mirrors isOpsEnabled). */ |
| 24 | +export function isSweepWatchdogEnabled(env: { GITTENSORY_SWEEP_WATCHDOG?: string | undefined }): boolean { |
| 25 | + return /^(1|true|yes|on)$/i.test(env.GITTENSORY_SWEEP_WATCHDOG ?? ""); |
| 26 | +} |
| 27 | + |
| 28 | +/** A repo's sweep is stale when it has open PRs to regate but its last-regated marker either never advanced or |
| 29 | + * hasn't advanced within the staleness window. A repo with NO open PRs is never stale — there is nothing for |
| 30 | + * the sweep to do, so a `null` marker there means "nothing to regate," not "the sweep stopped working." */ |
| 31 | +export const SWEEP_STALENESS_THRESHOLD_MS = 45 * 60 * 1000; |
| 32 | + |
| 33 | +export function isSweepStale(input: { openPullRequestCount: number; lastRegatedAt: string | null; nowMs: number }): boolean { |
| 34 | + if (input.openPullRequestCount === 0) return false; |
| 35 | + const lastMs = input.lastRegatedAt ? Date.parse(input.lastRegatedAt) : NaN; |
| 36 | + if (!Number.isFinite(lastMs)) return true; |
| 37 | + return input.nowMs - lastMs > SWEEP_STALENESS_THRESHOLD_MS; |
| 38 | +} |
| 39 | + |
| 40 | +/** The same acting-autonomy repo set fanOutAgentRegateSweepJobs sweeps: the convergence allowlist |
| 41 | + * (GITTENSORY_REVIEW_REPOS) union the webhook-registered repos with acting autonomy, deduped case-insensitively. |
| 42 | + * Deliberately mirrors that function's own selection so the watchdog can never watch a DIFFERENT set of repos |
| 43 | + * than the sweep actually covers. */ |
| 44 | +async function watchedRepos(env: Env): Promise<Array<{ fullName: string; installationId?: number }>> { |
| 45 | + const repositoriesByKey = new Map((await listRepositories(env)).map((repo) => [repo.fullName.toLowerCase(), repo])); |
| 46 | + const byKey = new Map<string, { fullName: string; installationId?: number }>(); |
| 47 | + for (const repo of repositoriesByKey.values()) |
| 48 | + byKey.set(repo.fullName.toLowerCase(), { fullName: repo.fullName, ...(typeof repo.installationId === "number" ? { installationId: repo.installationId } : {}) }); |
| 49 | + for (const fullName of listConvergenceRepos(env)) { |
| 50 | + const repo = repositoriesByKey.get(fullName.toLowerCase()); |
| 51 | + byKey.set(fullName.toLowerCase(), { |
| 52 | + fullName, |
| 53 | + ...(typeof repo?.installationId === "number" ? { installationId: repo.installationId } : {}), |
| 54 | + }); |
| 55 | + } |
| 56 | + const configured: Array<{ fullName: string; installationId?: number }> = []; |
| 57 | + for (const repo of byKey.values()) { |
| 58 | + try { |
| 59 | + const settings = await resolveRepositorySettings(env, repo.fullName); |
| 60 | + if (isConvergenceRepoAllowed(env, repo.fullName) || isAgentConfigured(settings.autonomy)) configured.push(repo); |
| 61 | + } catch { |
| 62 | + /* a settings blip on one repo must not abort the whole watchdog scan */ |
| 63 | + } |
| 64 | + } |
| 65 | + return configured; |
| 66 | +} |
| 67 | + |
| 68 | +export interface StaleSweepRepo { |
| 69 | + repoFullName: string; |
| 70 | + installationId?: number | undefined; |
| 71 | + openPullRequestCount: number; |
| 72 | + lastRegatedAt: string | null; |
| 73 | + ageMs: number; |
| 74 | +} |
| 75 | + |
| 76 | +/** |
| 77 | + * The watchdog scan, run on the cron tick. FAILS SAFE: a per-repo error is logged and the scan continues; a |
| 78 | + * top-level error is swallowed (this is best-effort self-heal, never a reason to fail the queue). Only an |
| 79 | + * INSTALLED repo (installationId present) gets a self-heal re-enqueue — a registered-but-uninstalled repo never |
| 80 | + * gets a per-PR fan-out regardless (#sweep-uninstalled-budget-waste), so re-enqueuing its sweep would just spend |
| 81 | + * the shared GITHUB_PUBLIC_TOKEN budget on a sweep that can never act. Returns the stale repos found (for tests / |
| 82 | + * a caller that wants to act further). |
| 83 | + * |
| 84 | + * Caller MUST gate this on {@link isSweepWatchdogEnabled} — it is invoked only from the flag-ON cron path, so |
| 85 | + * flag-OFF this function is never reached and the cron does zero new work. |
| 86 | + */ |
| 87 | +export async function runSweepLivenessWatchdog(env: Env): Promise<StaleSweepRepo[]> { |
| 88 | + const found: StaleSweepRepo[] = []; |
| 89 | + const nowMs = Date.parse(nowIso()); |
| 90 | + try { |
| 91 | + const repos = await watchedRepos(env); |
| 92 | + for (const repo of repos) { |
| 93 | + try { |
| 94 | + if (typeof repo.installationId !== "number") continue; |
| 95 | + const [openPullRequestCount, lastRegatedAt] = await Promise.all([countOpenPullRequests(env, repo.fullName), getLatestRegatedAt(env, repo.fullName)]); |
| 96 | + if (!isSweepStale({ openPullRequestCount, lastRegatedAt, nowMs })) continue; |
| 97 | + const lastMs = lastRegatedAt ? Date.parse(lastRegatedAt) : NaN; |
| 98 | + const ageMs = Number.isFinite(lastMs) ? nowMs - lastMs : Number.POSITIVE_INFINITY; |
| 99 | + found.push({ repoFullName: repo.fullName, installationId: repo.installationId, openPullRequestCount, lastRegatedAt, ageMs }); |
| 100 | + console.error( |
| 101 | + JSON.stringify({ |
| 102 | + level: "error", |
| 103 | + event: "sweep_liveness_stale", |
| 104 | + repository: repo.fullName, |
| 105 | + openPullRequestCount, |
| 106 | + lastRegatedAt, |
| 107 | + ageMs: Number.isFinite(ageMs) ? ageMs : null, |
| 108 | + }), |
| 109 | + ); |
| 110 | + const message: JobMessage = { type: "agent-regate-sweep", requestedBy: "schedule", repoFullName: repo.fullName, installationId: repo.installationId }; |
| 111 | + await env.JOBS.send(message).catch((error) => { |
| 112 | + console.error(JSON.stringify({ level: "error", event: "sweep_liveness_reenqueue_failed", repository: repo.fullName, error: errorMessage(error) })); |
| 113 | + }); |
| 114 | + } catch (error) { |
| 115 | + console.error(JSON.stringify({ level: "error", event: "sweep_liveness_repo_error", repository: repo.fullName, message: errorMessage(error).slice(0, 200) })); |
| 116 | + } |
| 117 | + } |
| 118 | + } catch (error) { |
| 119 | + console.error(JSON.stringify({ level: "error", event: "sweep_liveness_error", message: errorMessage(error).slice(0, 200) })); |
| 120 | + } |
| 121 | + return found; |
| 122 | +} |
0 commit comments