|
| 1 | +// Self-heal (flag-gated by GITTENSORY_PR_RECONCILIATION). A "PR opened" webhook that silently vanishes (no |
| 2 | +// error, no audit event, no trace anywhere — see reconcileOpenPullRequests's doc comment for the 2026-07-06 |
| 3 | +// incident that motivated this) previously wasn't caught until backfillRegisteredRepositories's opportunistic |
| 4 | +// resync, which skips any repo whose sync is "fresh" (up to 6 hours). This module runs a much tighter, dedicated |
| 5 | +// reconciliation on its own short cron cadence: list-diff GitHub's open PR numbers against the local table for |
| 6 | +// every acting-autonomy repo, and for any number GitHub has that the local table doesn't, immediately catch it |
| 7 | +// up (fetch full details, upsert, and enqueue a normal regate — the SAME pipeline a real webhook would have fed). |
| 8 | +// |
| 9 | +// Default OFF (like every other convergence capability) — flag-OFF this module is never invoked and the cron |
| 10 | +// enqueues no reconciliation job, byte-identical to today. |
| 11 | + |
| 12 | +import { githubRateLimitAdmissionKeyForToken } from "../github/client"; |
| 13 | +import { createInstallationToken } from "../github/app"; |
| 14 | +import { fetchLivePullRequest, reconcileOpenPullRequests } from "../github/backfill"; |
| 15 | +import { getRepository, listRepositories, upsertPullRequestFromGitHub } from "../db/repositories"; |
| 16 | +import { isAgentConfigured } from "../settings/autonomy"; |
| 17 | +import { resolveRepositorySettings } from "../settings/repository-settings"; |
| 18 | +import { incr } from "../selfhost/metrics"; |
| 19 | +import type { JobMessage } from "../types"; |
| 20 | +import { errorMessage } from "../utils/json"; |
| 21 | +import { isConvergenceRepoAllowed, listConvergenceRepos } from "./cutover-gate"; |
| 22 | + |
| 23 | +/** True when fast open-PR reconciliation is enabled. Flag-OFF (default) → the caller never invokes it, so the |
| 24 | + * cron enqueues no reconciliation job and the queue processor no-ops on a stale in-flight one. */ |
| 25 | +export function isPrReconciliationEnabled(env: { GITTENSORY_PR_RECONCILIATION?: string | undefined }): boolean { |
| 26 | + return /^(1|true|yes|on)$/i.test(env.GITTENSORY_PR_RECONCILIATION ?? ""); |
| 27 | +} |
| 28 | + |
| 29 | +/** The same acting-autonomy repo set fanOutAgentRegateSweepJobs sweeps (mirrors sweep-watchdog.ts's own copy of |
| 30 | + * this selection) — this reconciliation only makes sense for repos gittensory is actually reviewing. */ |
| 31 | +async function watchedRepos(env: Env): Promise<Array<{ fullName: string; installationId?: number }>> { |
| 32 | + const repositoriesByKey = new Map((await listRepositories(env)).map((repo) => [repo.fullName.toLowerCase(), repo])); |
| 33 | + const byKey = new Map<string, { fullName: string; installationId?: number }>(); |
| 34 | + for (const repo of repositoriesByKey.values()) |
| 35 | + byKey.set(repo.fullName.toLowerCase(), { fullName: repo.fullName, ...(typeof repo.installationId === "number" ? { installationId: repo.installationId } : {}) }); |
| 36 | + for (const fullName of listConvergenceRepos(env)) { |
| 37 | + const repo = repositoriesByKey.get(fullName.toLowerCase()); |
| 38 | + byKey.set(fullName.toLowerCase(), { |
| 39 | + fullName, |
| 40 | + ...(typeof repo?.installationId === "number" ? { installationId: repo.installationId } : {}), |
| 41 | + }); |
| 42 | + } |
| 43 | + const configured: Array<{ fullName: string; installationId?: number }> = []; |
| 44 | + for (const repo of byKey.values()) { |
| 45 | + try { |
| 46 | + const settings = await resolveRepositorySettings(env, repo.fullName); |
| 47 | + if (isConvergenceRepoAllowed(env, repo.fullName) || isAgentConfigured(settings.autonomy)) configured.push(repo); |
| 48 | + } catch { |
| 49 | + /* a settings blip on one repo must not abort the whole reconciliation scan */ |
| 50 | + } |
| 51 | + } |
| 52 | + return configured; |
| 53 | +} |
| 54 | + |
| 55 | +/** Catch up ONE missing PR number: fetch its full live payload, upsert it into the local table, and enqueue a |
| 56 | + * normal regate — the exact pipeline a real "PR opened" webhook would have fed it into, so it gets reviewed, |
| 57 | + * labeled, and gated exactly like any other PR. Best-effort: a fetch/upsert failure is logged and skipped (the |
| 58 | + * next reconciliation tick retries it; it is not lost by this catch-up failing). */ |
| 59 | +async function catchUpMissingPullRequest(env: Env, repoFullName: string, installationId: number, prNumber: number): Promise<void> { |
| 60 | + try { |
| 61 | + const token = (await createInstallationToken(env, installationId).catch(() => undefined)) ?? env.GITHUB_PUBLIC_TOKEN; |
| 62 | + const admissionKey = githubRateLimitAdmissionKeyForToken(env, token, installationId); |
| 63 | + const live = await fetchLivePullRequest(env, repoFullName, prNumber, token, admissionKey); |
| 64 | + if (!live) { |
| 65 | + console.error(JSON.stringify({ level: "error", event: "open_pr_reconciliation_catch_up_fetch_failed", repository: repoFullName, prNumber })); |
| 66 | + return; |
| 67 | + } |
| 68 | + await upsertPullRequestFromGitHub(env, repoFullName, live); |
| 69 | + const message: JobMessage = { type: "agent-regate-pr", deliveryId: `reconcile:${repoFullName}#${prNumber}`, repoFullName, prNumber, installationId }; |
| 70 | + await env.JOBS.send(message); |
| 71 | + } catch (error) { |
| 72 | + console.error(JSON.stringify({ level: "error", event: "open_pr_reconciliation_catch_up_failed", repository: repoFullName, prNumber, message: errorMessage(error).slice(0, 200) })); |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +export interface OpenPrDivergence { |
| 77 | + repoFullName: string; |
| 78 | + remoteOpenCount: number; |
| 79 | + localOpenCount: number; |
| 80 | + missingNumbers: number[]; |
| 81 | +} |
| 82 | + |
| 83 | +/** |
| 84 | + * The reconciliation scan, run on the cron tick. FAILS SAFE: a per-repo error is logged and the scan continues; |
| 85 | + * a top-level error is swallowed (this is best-effort self-heal, never a reason to fail the queue). Only an |
| 86 | + * INSTALLED repo (installationId present) is reconciled — a registered-but-uninstalled repo never gets a per-PR |
| 87 | + * fan-out regardless (#sweep-uninstalled-budget-waste), so reconciling it would just spend the shared |
| 88 | + * GITHUB_PUBLIC_TOKEN budget with no actionable outcome. Returns the divergences found (for tests / a caller |
| 89 | + * that wants to inspect them further). |
| 90 | + * |
| 91 | + * Caller MUST gate this on {@link isPrReconciliationEnabled} — it is invoked only from the flag-ON cron path, so |
| 92 | + * flag-OFF this function is never reached and the cron does zero new work. |
| 93 | + */ |
| 94 | +export async function runOpenPrReconciliation(env: Env): Promise<OpenPrDivergence[]> { |
| 95 | + const found: OpenPrDivergence[] = []; |
| 96 | + try { |
| 97 | + const repos = await watchedRepos(env); |
| 98 | + for (const repo of repos) { |
| 99 | + try { |
| 100 | + if (typeof repo.installationId !== "number") continue; |
| 101 | + const result = await reconcileOpenPullRequests(env, repo.fullName); |
| 102 | + if (result.missingNumbers.length === 0) continue; |
| 103 | + found.push({ repoFullName: repo.fullName, remoteOpenCount: result.remoteOpenCount, localOpenCount: result.localOpenCount, missingNumbers: result.missingNumbers }); |
| 104 | + incr("gittensory_open_pr_reconciliation_missing_total", { repo: repo.fullName }, result.missingNumbers.length); |
| 105 | + console.error( |
| 106 | + JSON.stringify({ |
| 107 | + level: "error", |
| 108 | + event: "open_pr_reconciliation_divergence", |
| 109 | + repository: repo.fullName, |
| 110 | + remoteOpenCount: result.remoteOpenCount, |
| 111 | + localOpenCount: result.localOpenCount, |
| 112 | + missingNumbers: result.missingNumbers, |
| 113 | + }), |
| 114 | + ); |
| 115 | + for (const prNumber of result.missingNumbers) await catchUpMissingPullRequest(env, repo.fullName, repo.installationId, prNumber); |
| 116 | + } catch (error) { |
| 117 | + console.error(JSON.stringify({ level: "error", event: "open_pr_reconciliation_repo_error", repository: repo.fullName, message: errorMessage(error).slice(0, 200) })); |
| 118 | + } |
| 119 | + } |
| 120 | + } catch (error) { |
| 121 | + console.error(JSON.stringify({ level: "error", event: "open_pr_reconciliation_error", message: errorMessage(error).slice(0, 200) })); |
| 122 | + } |
| 123 | + return found; |
| 124 | +} |
0 commit comments