CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
Blame · Line-by-line history
post-receive.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.
| fc1817a | 1 | /** |
| 2 | * Post-receive hook logic. | |
| 2c34075 | 3 | * |
| 4 | * Called after every successful git push. This is gluecron's intelligence layer: | |
| 5 | * 1. Auto-repair — fix common issues and commit automatically | |
| 6 | * 2. Push analysis — detect breaking changes, security issues | |
| 7 | * 3. Health score — recompute repo health | |
| 8 | * 4. GateTest scan — external security scanning | |
| 9 | * 5. Crontech deploy — auto-deploy on push to main | |
| 10 | * 6. Webhooks — fire registered webhook URLs | |
| fc1817a | 11 | */ |
| 12 | ||
| ba93444 | 13 | import { createHmac } from "crypto"; |
| 3ef4c9d | 14 | import { and, eq } from "drizzle-orm"; |
| fc1817a | 15 | import { config } from "../lib/config"; |
| 2c34075 | 16 | import { autoRepair } from "../lib/autorepair"; |
| 170ddb2 | 17 | import { notifyGateTestOfPush } from "../lib/gate"; |
| 2c34075 | 18 | import { analyzePush, computeHealthScore } from "../lib/intelligence"; |
| 0316dbb | 19 | import { db } from "../db"; |
| 20 | import { deployments, repositories, users } from "../db/schema"; | |
| 21 | import { onDeployFailure } from "../lib/ai-incident"; | |
| a686079 | 22 | import { |
| 23 | commitsBetween, | |
| 24 | getDefaultBranch, | |
| 25 | getRepoPath, | |
| 26 | } from "../git/repository"; | |
| 27 | import { indexChangedFiles } from "../lib/semantic-index"; | |
| 6efae38 | 28 | import { scanDiffForIssues } from "../lib/ai-auto-issues"; |
| 4bbacbe | 29 | import { enqueuePreviewBuild } from "../lib/branch-previews"; |
| da3fc18 | 30 | import { scanDependencies } from "../lib/dependency-scanner"; |
| d199847 | 31 | import { runDocDriftCheckForRepo } from "../lib/ai-doc-updater"; |
| 783dd46 | 32 | import { |
| 33 | findTargetsForPush, | |
| 34 | finishDeployRow, | |
| 35 | resolveEnv, | |
| 36 | startDeployRow, | |
| 37 | } from "../lib/server-target-store"; | |
| 38 | import { deployToTarget } from "../lib/server-targets"; | |
| c9ed210 | 39 | import { fireCloudDeploys } from "../lib/cloud-deploy"; |
| 641aa42 | 40 | import { ensureRepoOnboarding } from "../lib/repo-onboarding"; |
| fc1817a | 41 | |
| 42 | interface PushRef { | |
| 43 | oldSha: string; | |
| 44 | newSha: string; | |
| 45 | refName: string; | |
| 46 | } | |
| 47 | ||
| 48 | export async function onPostReceive( | |
| 49 | owner: string, | |
| 50 | repo: string, | |
| 6efae38 | 51 | refs: PushRef[], |
| 52 | pusherUserId: string = "" | |
| fc1817a | 53 | ): Promise<void> { |
| 2c34075 | 54 | for (const ref of refs) { |
| 55 | if (ref.newSha.startsWith("0000")) continue; // Branch deletion | |
| 56 | const branchName = ref.refName.replace("refs/heads/", ""); | |
| fc1817a | 57 | |
| 2c34075 | 58 | // 1. Auto-repair (runs first, may create a new commit) |
| 59 | try { | |
| 60 | const repair = await autoRepair(owner, repo, branchName); | |
| 61 | if (repair.repaired) { | |
| 62 | console.log( | |
| 63 | `[autorepair] ${owner}/${repo}@${branchName}: ${repair.repairs.length} repairs committed` | |
| 64 | ); | |
| 65 | } | |
| 66 | } catch (err) { | |
| 67 | console.error(`[autorepair] error:`, err); | |
| 68 | } | |
| fc1817a | 69 | |
| 2c34075 | 70 | // 2. Push analysis |
| 71 | try { | |
| 72 | const analysis = await analyzePush(owner, repo, ref.oldSha, ref.newSha); | |
| 73 | console.log( | |
| 74 | `[push-analysis] ${owner}/${repo}: ${analysis.summary}` | |
| 75 | ); | |
| 76 | if (analysis.riskScore > 50) { | |
| 77 | console.warn( | |
| 78 | `[push-analysis] HIGH RISK push detected (score: ${analysis.riskScore})` | |
| 79 | ); | |
| 80 | } | |
| 81 | if (analysis.breakingChangeSignals.length > 0) { | |
| 82 | console.warn( | |
| 83 | `[push-analysis] Breaking changes: ${analysis.breakingChangeSignals.join("; ")}` | |
| 84 | ); | |
| 85 | } | |
| 86 | } catch (err) { | |
| 87 | console.error(`[push-analysis] error:`, err); | |
| 88 | } | |
| 89 | ||
| 90 | // 3. Health score (async, don't block) | |
| 91 | computeHealthScore(owner, repo).then((report) => { | |
| 92 | console.log( | |
| 93 | `[health] ${owner}/${repo}: ${report.grade} (${report.score}/100)` | |
| 94 | ); | |
| 95 | }).catch((err) => { | |
| 96 | console.error(`[health] error:`, err); | |
| 97 | }); | |
| 98 | } | |
| 99 | ||
| 170ddb2 | 100 | // 4. GateTest scan — fire-and-forget notification on every push. The |
| 101 | // helper short-circuits if `GATETEST_URL` is unset, so non-GateTest | |
| 102 | // deployments pay no overhead. Results flow back via the inbound | |
| 103 | // webhook at POST /api/hooks/gatetest. | |
| 104 | for (const ref of refs) { | |
| 105 | if (ref.newSha.startsWith("0000")) continue; | |
| 106 | notifyGateTestOfPush(owner, repo, ref.refName, ref.newSha).catch((err) => | |
| 107 | console.warn("[gatetest] notify error:", err) | |
| 108 | ); | |
| 109 | } | |
| 2c34075 | 110 | |
| a686079 | 111 | // 4b. Continuous semantic index — embed changed files on every push so |
| 112 | // /api/v2/.../semantic-search has fresh vectors. Fire-and-forget; | |
| 113 | // all failures are swallowed inside semantic-index.ts so a missing | |
| 114 | // pgvector extension or absent embeddings API key never breaks the | |
| 115 | // push path. Capped to MAX_FILES_PER_PUSH inside the lib. | |
| 116 | for (const ref of refs) { | |
| 117 | if (ref.newSha.startsWith("0000")) continue; | |
| 118 | void fireSemanticIndex(owner, repo, ref.oldSha, ref.newSha).catch((err) => | |
| 119 | console.warn("[semantic-index] dispatch error:", err) | |
| 120 | ); | |
| 121 | } | |
| 122 | ||
| 4bbacbe | 123 | // 4c. Per-branch preview URLs (migration 0062). Every push to a |
| 124 | // non-default branch enqueues a preview-build row. Gated on | |
| 125 | // repositories.preview_builds_enabled (default on) so owners can | |
| 126 | // opt out per-repo via repo-settings. Fire-and-forget; failures | |
| 127 | // never break the push path. | |
| 128 | void firePreviewBuilds(owner, repo, refs).catch((err) => | |
| 129 | console.warn("[branch-previews] dispatch error:", err) | |
| 130 | ); | |
| 131 | ||
| 6efae38 | 132 | // 4e. AI Auto-Issue Opener. Scans the diff for each pushed ref for |
| 133 | // TODO/FIXME/HACK comments, hardcoded secrets, SQL injection patterns, | |
| 134 | // and debug console.log calls. Opens one issue per finding type per | |
| 135 | // file (capped at MAX_ISSUES_PER_PUSH). Gated on AI_AUTO_ISSUES=1. | |
| 136 | // Fire-and-forget; never blocks the push path. | |
| 137 | for (const ref of refs) { | |
| 138 | if (ref.newSha.startsWith("0000")) continue; | |
| 139 | scanDiffForIssues(owner, repo, ref.oldSha, ref.newSha, pusherUserId).catch( | |
| 140 | (err) => console.warn("[ai-auto-issues] dispatch error:", err) | |
| 141 | ); | |
| 142 | } | |
| 143 | ||
| da3fc18 | 144 | // 4f. Dependency CVE scanner — when DEPENDENCY_SCAN_ENABLED=1, scan |
| 145 | // every push that touches a recognized manifest file (package.json, | |
| 146 | // requirements.txt, Cargo.toml, go.mod, Gemfile). Auto-opens issues | |
| 147 | // for critical/high findings and updates a weekly digest for | |
| 148 | // medium/low. Fire-and-forget; never blocks the push path. | |
| 149 | if (config.dependencyScanEnabled) { | |
| 150 | void fireDependencyScan(owner, repo, refs).catch((err) => | |
| 151 | console.warn("[dependency-scanner] dispatch error:", err) | |
| 152 | ); | |
| 153 | } | |
| 154 | ||
| d199847 | 155 | // 4d. AI-tracked documentation drift check (migration 0068). Walks the |
| 156 | // repo's markdown files for `<!-- gluecron:doc-track ... -->` | |
| 157 | // regions, hashes the referenced source, and opens a PR labelled | |
| 158 | // `ai:doc-update` when the prose drifts. Fire-and-forget; failures | |
| 159 | // are swallowed inside ai-doc-updater.ts so a missing anthropic key | |
| 160 | // or empty doc_tracking table never breaks the push. | |
| 161 | void fireDocDriftCheck(owner, repo).catch((err) => | |
| 162 | console.warn("[ai-doc-updater] dispatch error:", err) | |
| 163 | ); | |
| 164 | ||
| 641aa42 | 165 | // 4g. Smart empty states — repo onboarding. On the very first push to a |
| 166 | // repo's default branch (oldSha all-zeros), generate a README draft, | |
| 167 | // suggested labels, and gates.yml starter using Claude Sonnet. | |
| 168 | // Idempotent: ensureRepoOnboarding skips if a row already exists. | |
| 169 | // Fire-and-forget; never blocks the push path. | |
| 170 | void fireRepoOnboarding(owner, repo, refs).catch((err) => | |
| 171 | console.warn("[repo-onboarding] dispatch error:", err) | |
| 172 | ); | |
| 173 | ||
| ba93444 | 174 | // 5. Crontech deploy (BLK-016) — only fires for the configured Crontech repo |
| 175 | // (CRONTECH_REPO, default `ccantynz-alt/crontech`) on a push to its | |
| 176 | // default branch. The branch case (`Main` vs `main`) is determined by | |
| 177 | // the bare repo's HEAD, not hardcoded. | |
| 178 | if (`${owner}/${repo}` === config.crontechRepo) { | |
| a28cede | 179 | let defaultBranch = |
| 180 | (await getDefaultBranch(owner, repo).catch((err) => { | |
| 181 | console.warn( | |
| 182 | `[post-receive] getDefaultBranch failed for ${owner}/${repo}, defaulting to "main":`, | |
| 183 | err instanceof Error ? err.message : err | |
| 184 | ); | |
| 185 | return null; | |
| 186 | })) || "main"; | |
| ba93444 | 187 | const targetRef = `refs/heads/${defaultBranch}`; |
| 188 | const deployPush = refs.find( | |
| 189 | (r) => r.refName === targetRef && !r.newSha.startsWith("0000") | |
| 190 | ); | |
| 191 | if (deployPush) { | |
| 192 | let repositoryId = ""; | |
| 193 | try { | |
| 194 | const [row] = await db | |
| 195 | .select({ id: repositories.id }) | |
| 196 | .from(repositories) | |
| 197 | .innerJoin(users, eq(repositories.ownerId, users.id)) | |
| 198 | .where(and(eq(users.username, owner), eq(repositories.name, repo))) | |
| 199 | .limit(1); | |
| 200 | repositoryId = row?.id || ""; | |
| 201 | } catch { | |
| 202 | /* ignore */ | |
| 203 | } | |
| 204 | if (repositoryId) { | |
| 205 | triggerCrontechDeploy({ | |
| 206 | owner, | |
| 207 | repo, | |
| 208 | before: deployPush.oldSha, | |
| 209 | after: deployPush.newSha, | |
| 210 | ref: targetRef, | |
| 211 | branch: defaultBranch, | |
| 212 | repositoryId, | |
| 213 | }).catch((err: unknown) => console.error(`[crontech] error:`, err)); | |
| 214 | } | |
| 0316dbb | 215 | } |
| fc1817a | 216 | } |
| f2c00b4 | 217 | |
| 783dd46 | 218 | // 5b. Block ST — Server targets. After core post-receive work, fire |
| 219 | // deploys against any `server_targets` row whose | |
| 220 | // (watched_repository_id, watched_branch) matches a pushed ref. | |
| 221 | // Fire-and-forget; deploy results land in `server_target_deployments` | |
| 222 | // and the UI at /admin/servers/:id surfaces them. | |
| 223 | void fireServerTargetDeploys(owner, repo, refs).catch((err) => | |
| 224 | console.warn("[server-targets] dispatch error:", err) | |
| 225 | ); | |
| 226 | ||
| c9ed210 | 227 | // 5c. Cloud deploy integrations (migration 0077). Fire push-triggered |
| 228 | // deploys to Fly.io, Railway, Render, Vercel, Netlify, or a generic | |
| 229 | // webhook for any cloud_deploy_configs rows matching the pushed branch. | |
| 230 | // Fire-and-forget; all failures are swallowed so the push path is | |
| 231 | // never blocked. | |
| 232 | void fireCloudDeploys(owner, repo, refs).catch((err) => | |
| 233 | console.warn("[cloud-deploy] dispatch error:", err) | |
| 234 | ); | |
| 235 | ||
| f2c00b4 | 236 | // 6. BLOCK W — Self-host. When Gluecron.com itself receives a push to |
| 237 | // main, fire the local deploy via scripts/self-deploy.sh. The script | |
| 238 | // forks into the background, so this call returns immediately (git | |
| 239 | // push doesn't block). Gated on env SELF_HOST_REPO (set on the box) to | |
| 240 | // avoid firing on customer repos that happen to be named "Gluecron.com". | |
| 241 | const selfHostRepo = process.env.SELF_HOST_REPO; | |
| 242 | if (selfHostRepo && `${owner}/${repo}` === selfHostRepo) { | |
| 243 | const mainRef = refs.find( | |
| 244 | (r) => r.refName === "refs/heads/main" && !r.newSha.startsWith("0000") | |
| 245 | ); | |
| 246 | if (mainRef) { | |
| 247 | const scriptPath = | |
| 248 | process.env.GLUECRON_SELF_DEPLOY_SCRIPT || | |
| 249 | "/opt/gluecron/scripts/self-deploy.sh"; | |
| 250 | try { | |
| 251 | const child = __selfHostSpawn( | |
| 252 | [scriptPath, mainRef.oldSha, mainRef.newSha], | |
| 253 | { stdout: "ignore", stderr: "ignore", stdin: "ignore" } | |
| 254 | ); | |
| 255 | try { | |
| 256 | (child as any)?.unref?.(); | |
| 257 | } catch { | |
| 258 | /* unref optional */ | |
| 259 | } | |
| 260 | console.log( | |
| 261 | `[self-host] dispatched self-deploy for ${owner}/${repo}@${mainRef.newSha.slice(0, 7)}` | |
| 262 | ); | |
| 263 | } catch (err) { | |
| 264 | console.error(`[self-host] failed to spawn:`, err); | |
| 265 | } | |
| 266 | } | |
| 267 | } | |
| 268 | } | |
| 269 | ||
| 270 | // BLOCK W — DI seam so the test suite can capture the spawn call without | |
| 271 | // actually shelling out to /opt/gluecron/scripts/self-deploy.sh. Production | |
| 272 | // callers go straight to Bun.spawn. | |
| bf19c50 | 273 | const __defaultSelfHostSpawn: (cmd: string[], opts: any) => any = (cmd, opts) => |
| f2c00b4 | 274 | Bun.spawn(cmd, opts); |
| bf19c50 | 275 | let __selfHostSpawn: (cmd: string[], opts: any) => any = __defaultSelfHostSpawn; |
| 276 | /** | |
| 277 | * Test-only: replace the spawn impl. Pass `null` to reset to Bun.spawn. | |
| 278 | */ | |
| 279 | export function __setSelfHostSpawnForTests( | |
| 280 | fn: typeof __selfHostSpawn | null | |
| 281 | ): void { | |
| 282 | __selfHostSpawn = fn ?? __defaultSelfHostSpawn; | |
| fc1817a | 283 | } |
| 284 | ||
| 43cf9b0 | 285 | /** |
| ba93444 | 286 | * BLK-016 — outbound deploy webhook for Crontech's deploy-agent. |
| 43cf9b0 | 287 | * |
| ba93444 | 288 | * Wire contract (matches Crontech's `apps/api/src/webhooks/gluecron-push.ts`): |
| 43cf9b0 | 289 | * |
| ba93444 | 290 | * POST https://crontech.ai/api/webhooks/gluecron-push |
| 43cf9b0 | 291 | * Content-Type: application/json |
| ba93444 | 292 | * X-Gluecron-Signature: sha256=<hex(hmac-sha256(body, GLUECRON_WEBHOOK_SECRET))> |
| 43cf9b0 | 293 | * |
| 294 | * { | |
| ba93444 | 295 | * "event": "push", |
| 296 | * "repository": { "full_name": "ccantynz-alt/crontech" }, | |
| 297 | * "ref": "refs/heads/Main", | |
| 298 | * "after": "<40-hex commit SHA>", | |
| 299 | * "before": "<40-hex previous SHA>", | |
| 300 | * "pusher": { "name": "<author>", "email": "<email>" }, | |
| 301 | * "commits": [ { "id": "<sha>", "message": "<msg>", "timestamp": "<iso8601>" } ] | |
| 43cf9b0 | 302 | * } |
| 303 | * | |
| ba93444 | 304 | * The `after` SHA is the dedupe key on the receiver side (idempotent). |
| 43cf9b0 | 305 | * |
| ba93444 | 306 | * Delivery: at-least-once via exponential-backoff retry. Up to 5 attempts at |
| 307 | * delays 1s / 4s / 16s / 64s / 256s; first 2xx wins. If `GLUECRON_WEBHOOK_SECRET` | |
| 308 | * is unset the signature header is omitted and Crontech is expected to reject — | |
| 309 | * we still record the deploy row as failed. | |
| 43cf9b0 | 310 | */ |
| ba93444 | 311 | const RETRY_DELAYS_MS = [1_000, 4_000, 16_000, 64_000, 256_000]; |
| 312 | ||
| 313 | interface TriggerArgs { | |
| 314 | owner: string; | |
| 315 | repo: string; | |
| 316 | before: string; | |
| 317 | after: string; | |
| 318 | ref: string; | |
| 319 | branch: string; | |
| 320 | repositoryId: string; | |
| 321 | } | |
| 322 | ||
| 323 | interface TriggerOptions { | |
| 324 | fetchImpl?: typeof fetch; | |
| 325 | sleep?: (ms: number) => Promise<void>; | |
| 326 | retryDelaysMs?: number[]; | |
| 327 | now?: () => Date; | |
| 328 | } | |
| 329 | ||
| 330 | function signBody(body: string, secret: string): string | null { | |
| 331 | if (!secret) return null; | |
| 332 | return "sha256=" + createHmac("sha256", secret).update(body).digest("hex"); | |
| 333 | } | |
| 334 | ||
| 335 | async function buildPayload(args: TriggerArgs, now: Date): Promise<{ | |
| 336 | payload: Record<string, unknown>; | |
| 337 | pusherName: string; | |
| 338 | pusherEmail: string; | |
| 339 | }> { | |
| 340 | // Walk commits new since the last push. Cap at 50 like GitHub's webhook. | |
| 341 | // `before` may be all-zeros for a first push to the branch — commitsBetween | |
| 342 | // handles that by treating null `from` as "everything reachable from `to`". | |
| 343 | const fromSha = /^0+$/.test(args.before) ? null : args.before; | |
| 344 | let commits: Array<{ id: string; message: string; timestamp: string }> = []; | |
| 345 | let pusherName = "gluecron"; | |
| 346 | let pusherEmail = "noreply@gluecron.local"; | |
| 347 | try { | |
| 348 | const list = await commitsBetween(args.owner, args.repo, fromSha, args.after); | |
| 349 | commits = list.slice(0, 50).map((c) => ({ | |
| 350 | id: c.sha, | |
| 351 | message: c.message, | |
| 352 | timestamp: c.date, | |
| 353 | })); | |
| 354 | if (list[0]) { | |
| 355 | pusherName = list[0].author || pusherName; | |
| 356 | pusherEmail = list[0].authorEmail || pusherEmail; | |
| 357 | } | |
| 358 | } catch { | |
| 359 | /* ignore — payload still valid with empty commits[] */ | |
| 360 | } | |
| 361 | return { | |
| 362 | payload: { | |
| 363 | event: "push", | |
| 364 | repository: { full_name: `${args.owner}/${args.repo}` }, | |
| 365 | ref: args.ref, | |
| 366 | after: args.after, | |
| 367 | before: args.before, | |
| 368 | pusher: { name: pusherName, email: pusherEmail }, | |
| 369 | commits, | |
| 370 | // Ancillary fields — receiver may ignore but they're useful for logs: | |
| 371 | sent_at: now.toISOString(), | |
| 372 | source: "gluecron", | |
| 373 | }, | |
| 374 | pusherName, | |
| 375 | pusherEmail, | |
| 376 | }; | |
| 377 | } | |
| 378 | ||
| fc1817a | 379 | async function triggerCrontechDeploy( |
| ba93444 | 380 | args: TriggerArgs, |
| 381 | opts: TriggerOptions = {} | |
| fc1817a | 382 | ): Promise<void> { |
| ba93444 | 383 | const fetchImpl = opts.fetchImpl ?? fetch; |
| 384 | const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms))); | |
| 385 | const delays = opts.retryDelaysMs ?? RETRY_DELAYS_MS; | |
| 386 | const now = opts.now ?? (() => new Date()); | |
| 387 | ||
| 3ef4c9d | 388 | let deployId = ""; |
| fc1817a | 389 | try { |
| 3ef4c9d | 390 | const [row] = await db |
| 391 | .insert(deployments) | |
| 392 | .values({ | |
| ba93444 | 393 | repositoryId: args.repositoryId, |
| 3ef4c9d | 394 | environment: "production", |
| ba93444 | 395 | commitSha: args.after, |
| 396 | ref: args.ref, | |
| 3ef4c9d | 397 | status: "pending", |
| 398 | target: "crontech", | |
| 399 | }) | |
| 400 | .returning(); | |
| 401 | deployId = row?.id || ""; | |
| 402 | } catch { | |
| 403 | /* ignore */ | |
| fc1817a | 404 | } |
| 405 | ||
| ba93444 | 406 | const { payload } = await buildPayload(args, now()); |
| 407 | const body = JSON.stringify(payload); | |
| 408 | const signature = signBody(body, config.gluecronWebhookSecret); | |
| 409 | ||
| 410 | const headers: Record<string, string> = { | |
| 411 | "Content-Type": "application/json", | |
| 412 | "User-Agent": "gluecron-webhook/1", | |
| 413 | "X-Gluecron-Event": "push", | |
| 414 | "X-Gluecron-Delivery": cryptoRandomId(), | |
| 415 | }; | |
| 416 | if (signature) headers["X-Gluecron-Signature"] = signature; | |
| 417 | ||
| 418 | let lastStatus = 0; | |
| 419 | let lastError = ""; | |
| 420 | let success = false; | |
| 421 | ||
| 422 | // Up to delays.length + 1 attempts (initial try + each delay). | |
| 423 | const totalAttempts = delays.length + 1; | |
| 424 | for (let attempt = 0; attempt < totalAttempts; attempt++) { | |
| 425 | try { | |
| 426 | const response = await fetchImpl(config.crontechDeployUrl, { | |
| 427 | method: "POST", | |
| 428 | headers, | |
| 429 | body, | |
| 430 | }); | |
| 431 | lastStatus = response.status; | |
| 432 | console.log( | |
| 433 | `[crontech] attempt ${attempt + 1}/${totalAttempts} → ${lastStatus} for ${args.owner}/${args.repo}@${args.after.slice(0, 7)}` | |
| 434 | ); | |
| 435 | if (response.ok) { | |
| 436 | success = true; | |
| 437 | break; | |
| 438 | } | |
| 439 | // 4xx (except 408/429) is unrecoverable — stop retrying. | |
| 440 | if (response.status >= 400 && response.status < 500 && | |
| 441 | response.status !== 408 && response.status !== 429) { | |
| 442 | break; | |
| 443 | } | |
| 444 | } catch (err) { | |
| 445 | lastError = err instanceof Error ? err.message : String(err); | |
| 446 | console.error( | |
| 447 | `[crontech] attempt ${attempt + 1}/${totalAttempts} failed: ${lastError}` | |
| 448 | ); | |
| 3ef4c9d | 449 | } |
| ba93444 | 450 | const nextDelay = delays[attempt]; |
| 451 | if (nextDelay !== undefined && attempt < totalAttempts - 1) { | |
| 452 | await sleep(nextDelay); | |
| 1e162a8 | 453 | } |
| ba93444 | 454 | } |
| 455 | ||
| 456 | if (deployId) { | |
| 457 | try { | |
| 3ef4c9d | 458 | await db |
| 459 | .update(deployments) | |
| 460 | .set({ | |
| ba93444 | 461 | status: success ? "success" : "failed", |
| 462 | blockedReason: success | |
| 463 | ? null | |
| 464 | : (lastError ? lastError : `HTTP ${lastStatus}`), | |
| 3ef4c9d | 465 | completedAt: new Date(), |
| 466 | }) | |
| 467 | .where(eq(deployments.id, deployId)); | |
| ba93444 | 468 | } catch { |
| 469 | /* ignore */ | |
| 3ef4c9d | 470 | } |
| 471 | } | |
| 472 | ||
| ba93444 | 473 | if (!success && deployId) { |
| 474 | void onDeployFailure({ | |
| 475 | repositoryId: args.repositoryId, | |
| 476 | deploymentId: deployId, | |
| 477 | ref: args.ref, | |
| 478 | commitSha: args.after, | |
| 479 | target: "crontech", | |
| 480 | errorMessage: lastError || `HTTP ${lastStatus}`, | |
| 481 | }).catch((e) => console.error("[ai-incident]", e)); | |
| fc1817a | 482 | } |
| 483 | } | |
| 43cf9b0 | 484 | |
| ba93444 | 485 | function cryptoRandomId(): string { |
| 486 | // Short opaque delivery ID for log correlation. Not security-sensitive. | |
| 487 | const bytes = new Uint8Array(8); | |
| 488 | crypto.getRandomValues(bytes); | |
| 489 | return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(""); | |
| 490 | } | |
| 491 | ||
| a686079 | 492 | /** |
| 493 | * Resolve `owner/repo` to its DB repository.id and dispatch the | |
| 494 | * semantic-index update. Pulls the list of changed paths via | |
| 495 | * `git diff --name-only`, dropping any deletions (handled implicitly | |
| 496 | * because deleted blobs simply don't resolve in `indexChangedFiles`). | |
| 497 | * | |
| 498 | * Never throws — exhaust every external call inside a try/catch so the | |
| 499 | * push completes even if Postgres or the embedding API is down. | |
| 500 | */ | |
| 501 | async function fireSemanticIndex( | |
| 502 | owner: string, | |
| 503 | repo: string, | |
| 504 | oldSha: string, | |
| 505 | newSha: string | |
| 506 | ): Promise<void> { | |
| 507 | let repositoryId = ""; | |
| 508 | try { | |
| 509 | const [row] = await db | |
| 510 | .select({ id: repositories.id }) | |
| 511 | .from(repositories) | |
| 512 | .innerJoin(users, eq(repositories.ownerId, users.id)) | |
| 513 | .where(and(eq(users.username, owner), eq(repositories.name, repo))) | |
| 514 | .limit(1); | |
| 515 | repositoryId = row?.id || ""; | |
| 516 | } catch { | |
| 517 | return; | |
| 518 | } | |
| 519 | if (!repositoryId) return; | |
| 520 | ||
| 521 | let changedPaths: string[] = []; | |
| 522 | try { | |
| 523 | changedPaths = await listChangedPaths(owner, repo, oldSha, newSha); | |
| 524 | } catch { | |
| 525 | return; | |
| 526 | } | |
| 527 | if (!changedPaths.length) return; | |
| 528 | ||
| 529 | try { | |
| 530 | const out = await indexChangedFiles({ | |
| 531 | repositoryId, | |
| 532 | ownerName: owner, | |
| 533 | repoName: repo, | |
| 534 | commitSha: newSha, | |
| 535 | changedPaths, | |
| 536 | }); | |
| 537 | if (out.indexed > 0) { | |
| 538 | console.log( | |
| 539 | `[semantic-index] ${owner}/${repo}@${newSha.slice(0, 7)}: indexed ${out.indexed} file(s) via ${out.model}` | |
| 540 | ); | |
| 541 | } | |
| 542 | } catch (err) { | |
| 543 | console.warn("[semantic-index] indexChangedFiles error:", err); | |
| 544 | } | |
| 545 | } | |
| 546 | ||
| 547 | /** | |
| 548 | * Returns the list of files touched between `oldSha` and `newSha`. For | |
| 549 | * the initial push on a branch (oldSha all-zero) we walk every file in | |
| 550 | * the new tree via `git ls-tree -r`. Returns [] on any subprocess error. | |
| 551 | */ | |
| 552 | async function listChangedPaths( | |
| 553 | owner: string, | |
| 554 | repo: string, | |
| 555 | oldSha: string, | |
| 556 | newSha: string | |
| 557 | ): Promise<string[]> { | |
| 558 | const cwd = getRepoPath(owner, repo); | |
| 559 | const allZero = /^0+$/.test(oldSha); | |
| 560 | const cmd = allZero | |
| 561 | ? ["git", "ls-tree", "-r", "--name-only", newSha] | |
| 562 | : ["git", "diff", "--name-only", oldSha, newSha]; | |
| 563 | try { | |
| 564 | const proc = Bun.spawn(cmd, { | |
| 565 | cwd, | |
| 566 | stdout: "pipe", | |
| 567 | stderr: "pipe", | |
| 568 | }); | |
| 569 | const text = await new Response(proc.stdout).text(); | |
| 570 | await proc.exited; | |
| 571 | return text | |
| 572 | .split("\n") | |
| 573 | .map((s) => s.trim()) | |
| 574 | .filter((s) => s.length > 0); | |
| 575 | } catch { | |
| 576 | return []; | |
| 577 | } | |
| 578 | } | |
| 579 | ||
| 4bbacbe | 580 | /** |
| 581 | * Migration 0062 — fan out push refs to enqueuePreviewBuild for every | |
| 582 | * non-default branch on a `preview_builds_enabled` repo. | |
| 583 | * | |
| 584 | * Resolves the repo row once, fetches the default branch + opt-out flag, | |
| 585 | * then upserts one preview row per pushed ref that isn't the default. | |
| 586 | * Branch deletions (oldSha all-zero or newSha all-zero with oldSha set) | |
| 587 | * are skipped — they shouldn't create preview rows. Never throws. | |
| 588 | */ | |
| 589 | async function firePreviewBuilds( | |
| 590 | owner: string, | |
| 591 | repo: string, | |
| 592 | refs: PushRef[] | |
| 593 | ): Promise<void> { | |
| 594 | // Filter to live branch pushes only. | |
| 595 | const branchRefs = refs.filter( | |
| 596 | (r) => | |
| 597 | r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000") | |
| 598 | ); | |
| 599 | if (branchRefs.length === 0) return; | |
| 600 | ||
| 601 | let repoRow: { id: string; previewBuildsEnabled: boolean; defaultBranch: string } | null = null; | |
| 602 | try { | |
| 603 | const [row] = await db | |
| 604 | .select({ | |
| 605 | id: repositories.id, | |
| 606 | previewBuildsEnabled: repositories.previewBuildsEnabled, | |
| 607 | defaultBranch: repositories.defaultBranch, | |
| 608 | }) | |
| 609 | .from(repositories) | |
| 610 | .innerJoin(users, eq(repositories.ownerId, users.id)) | |
| 611 | .where(and(eq(users.username, owner), eq(repositories.name, repo))) | |
| 612 | .limit(1); | |
| 613 | repoRow = row || null; | |
| 614 | } catch { | |
| 615 | return; | |
| 616 | } | |
| 617 | if (!repoRow) return; | |
| 618 | if (!repoRow.previewBuildsEnabled) return; | |
| 619 | ||
| 620 | for (const ref of branchRefs) { | |
| 621 | const branchName = ref.refName.replace("refs/heads/", ""); | |
| 622 | if (branchName === repoRow.defaultBranch) continue; | |
| 623 | try { | |
| 624 | await enqueuePreviewBuild({ | |
| 625 | repositoryId: repoRow.id, | |
| 626 | ownerName: owner, | |
| 627 | repoName: repo, | |
| 628 | branchName, | |
| 629 | commitSha: ref.newSha, | |
| 630 | }); | |
| 631 | } catch (err) { | |
| 632 | console.warn( | |
| 633 | `[branch-previews] enqueue failed for ${owner}/${repo}@${branchName}:`, | |
| 634 | err instanceof Error ? err.message : err | |
| 635 | ); | |
| 636 | } | |
| 637 | } | |
| 638 | } | |
| 639 | ||
| d199847 | 640 | /** |
| 641 | * Migration 0068 — resolve `owner/repo` to its DB id and kick off the | |
| 642 | * doc-drift sweep (findTrackedDocs + proposeDocUpdate). Returns immediately | |
| 643 | * on missing repo or DB error — pushes never block. Never throws. | |
| 644 | */ | |
| 645 | async function fireDocDriftCheck(owner: string, repo: string): Promise<void> { | |
| 646 | let repositoryId = ""; | |
| 647 | try { | |
| 648 | const [row] = await db | |
| 649 | .select({ id: repositories.id }) | |
| 650 | .from(repositories) | |
| 651 | .innerJoin(users, eq(repositories.ownerId, users.id)) | |
| 652 | .where(and(eq(users.username, owner), eq(repositories.name, repo))) | |
| 653 | .limit(1); | |
| 654 | repositoryId = row?.id || ""; | |
| 655 | } catch { | |
| 656 | return; | |
| 657 | } | |
| 658 | if (!repositoryId) return; | |
| 659 | try { | |
| 660 | const out = await runDocDriftCheckForRepo(repositoryId); | |
| 661 | if (out.docs > 0 || out.proposed > 0) { | |
| 662 | console.log( | |
| 663 | `[ai-doc-updater] ${owner}/${repo}: docs=${out.docs} proposed=${out.proposed}` | |
| 664 | ); | |
| 665 | } | |
| 666 | } catch (err) { | |
| 667 | console.warn("[ai-doc-updater] runDocDriftCheckForRepo error:", err); | |
| 668 | } | |
| 669 | } | |
| 670 | ||
| 783dd46 | 671 | /** |
| 672 | * Block ST — fan out the push to any server targets that watch this | |
| 673 | * (repo, branch). One sequential deploy per target so a slow box can't | |
| 674 | * stall the next push, but multiple matching targets run in parallel. | |
| 675 | * Every failure is contained to its own deploy row + console warn — | |
| 676 | * nothing here can break the push path. | |
| 677 | */ | |
| 678 | async function fireServerTargetDeploys( | |
| 679 | owner: string, | |
| 680 | repo: string, | |
| 681 | refs: PushRef[] | |
| 682 | ): Promise<void> { | |
| 683 | const liveRefs = refs.filter( | |
| 684 | (r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000") | |
| 685 | ); | |
| 686 | if (liveRefs.length === 0) return; | |
| 687 | ||
| 688 | let repositoryId = ""; | |
| 689 | try { | |
| 690 | const [row] = await db | |
| 691 | .select({ id: repositories.id }) | |
| 692 | .from(repositories) | |
| 693 | .innerJoin(users, eq(repositories.ownerId, users.id)) | |
| 694 | .where(and(eq(users.username, owner), eq(repositories.name, repo))) | |
| 695 | .limit(1); | |
| 696 | repositoryId = row?.id || ""; | |
| 697 | } catch { | |
| 698 | return; | |
| 699 | } | |
| 700 | if (!repositoryId) return; | |
| 701 | ||
| 702 | await Promise.all( | |
| 703 | liveRefs.map(async (ref) => { | |
| 704 | const branch = ref.refName.replace("refs/heads/", ""); | |
| 705 | let targets; | |
| 706 | try { | |
| 707 | targets = await findTargetsForPush({ repositoryId, branch }); | |
| 708 | } catch { | |
| 709 | return; | |
| 710 | } | |
| 711 | if (!targets.length) return; | |
| 712 | ||
| 713 | await Promise.all( | |
| 714 | targets.map(async (target) => { | |
| 715 | try { | |
| 716 | const env = await resolveEnv(target.id); | |
| 717 | const deployId = await startDeployRow({ | |
| 718 | targetId: target.id, | |
| 719 | commitSha: ref.newSha, | |
| 720 | ref: ref.refName, | |
| 721 | triggerSource: "push", | |
| 722 | }); | |
| 723 | const result = await deployToTarget(target, { | |
| 724 | commitSha: ref.newSha, | |
| 725 | ref: ref.refName, | |
| 726 | env, | |
| 727 | }); | |
| 728 | if (deployId) { | |
| 729 | await finishDeployRow({ | |
| 730 | id: deployId, | |
| 731 | exitCode: result.exitCode, | |
| 732 | stdout: result.stdout, | |
| 733 | stderr: result.stderr, | |
| 734 | }); | |
| 735 | } | |
| 736 | console.log( | |
| 737 | `[server-targets] ${target.name} @ ${ref.newSha.slice(0, 7)}: exit ${result.exitCode}` | |
| 738 | ); | |
| 739 | } catch (err) { | |
| 740 | console.warn( | |
| 741 | `[server-targets] ${target.name}: deploy threw — ${err instanceof Error ? err.message : err}` | |
| 742 | ); | |
| 743 | } | |
| 744 | }) | |
| 745 | ); | |
| 746 | }) | |
| 747 | ); | |
| 748 | } | |
| 749 | ||
| da3fc18 | 750 | /** |
| 751 | * Fire-and-forget wrapper around scanDependencies for each pushed ref. | |
| 752 | * Resolves the repo DB row once, then runs the scanner on each live push. | |
| 753 | * Swallows all errors so a scanner failure never affects the push path. | |
| 754 | */ | |
| 755 | async function fireDependencyScan( | |
| 756 | owner: string, | |
| 757 | repo: string, | |
| 758 | refs: PushRef[] | |
| 759 | ): Promise<void> { | |
| 760 | const liveRefs = refs.filter( | |
| 761 | (r) => r.refName.startsWith("refs/heads/") && !r.newSha.startsWith("0000") | |
| 762 | ); | |
| 763 | if (liveRefs.length === 0) return; | |
| 764 | ||
| 765 | let repoRow: { id: string; ownerId: string } | null = null; | |
| 766 | try { | |
| 767 | const [row] = await db | |
| 768 | .select({ id: repositories.id, ownerId: repositories.ownerId }) | |
| 769 | .from(repositories) | |
| 770 | .innerJoin(users, eq(repositories.ownerId, users.id)) | |
| 771 | .where(and(eq(users.username, owner), eq(repositories.name, repo))) | |
| 772 | .limit(1); | |
| 773 | repoRow = row || null; | |
| 774 | } catch { | |
| 775 | return; | |
| 776 | } | |
| 777 | if (!repoRow) return; | |
| 778 | ||
| 779 | for (const ref of liveRefs) { | |
| 780 | try { | |
| 781 | const findings = await scanDependencies( | |
| 782 | repoRow.id, | |
| 783 | owner, | |
| 784 | repo, | |
| 785 | ref.newSha, | |
| 786 | ref.oldSha, | |
| 787 | repoRow.ownerId | |
| 788 | ); | |
| 789 | if (findings.length > 0) { | |
| 790 | console.log( | |
| 791 | `[dependency-scanner] ${owner}/${repo}@${ref.newSha.slice(0, 7)}: ${findings.length} finding(s)` | |
| 792 | ); | |
| 793 | } | |
| 794 | } catch (err) { | |
| 795 | console.warn( | |
| 796 | `[dependency-scanner] scan threw for ${owner}/${repo}@${ref.newSha.slice(0, 7)}:`, | |
| 797 | err instanceof Error ? err.message : err | |
| 798 | ); | |
| 799 | } | |
| 800 | } | |
| 801 | } | |
| 802 | ||
| 641aa42 | 803 | /** |
| 804 | * Migration 0088 — trigger repo onboarding on first push to the default branch. | |
| 805 | * Detects "first push" by checking whether oldSha is all-zeros on a push to | |
| 806 | * the repo's default branch (or any branch for a repo with no prior history). | |
| 807 | * Resolves the repo DB id, then calls ensureRepoOnboarding which is idempotent. | |
| 808 | * Never throws. | |
| 809 | */ | |
| 810 | async function fireRepoOnboarding( | |
| 811 | owner: string, | |
| 812 | repo: string, | |
| 813 | refs: PushRef[] | |
| 814 | ): Promise<void> { | |
| 815 | // Only fire on first push — oldSha all-zeros means the branch is brand-new. | |
| 816 | const firstPushRefs = refs.filter( | |
| 817 | (r) => r.refName.startsWith("refs/heads/") && /^0+$/.test(r.oldSha) && !r.newSha.startsWith("0000") | |
| 818 | ); | |
| 819 | if (firstPushRefs.length === 0) return; | |
| 820 | ||
| 821 | let repositoryId = ""; | |
| 822 | try { | |
| 823 | const [row] = await db | |
| 824 | .select({ id: repositories.id }) | |
| 825 | .from(repositories) | |
| 826 | .innerJoin(users, eq(repositories.ownerId, users.id)) | |
| 827 | .where(and(eq(users.username, owner), eq(repositories.name, repo))) | |
| 828 | .limit(1); | |
| 829 | repositoryId = row?.id || ""; | |
| 830 | } catch { | |
| 831 | return; | |
| 832 | } | |
| 833 | if (!repositoryId) return; | |
| 834 | ||
| 835 | await ensureRepoOnboarding(repositoryId, owner, repo); | |
| 836 | } | |
| 837 | ||
| 43cf9b0 | 838 | /** Test-only access to internal helpers. */ |
| a686079 | 839 | export const __test = { |
| 840 | triggerCrontechDeploy, | |
| 841 | signBody, | |
| 842 | buildPayload, | |
| 843 | RETRY_DELAYS_MS, | |
| 844 | listChangedPaths, | |
| 845 | fireSemanticIndex, | |
| 4bbacbe | 846 | firePreviewBuilds, |
| d199847 | 847 | fireDocDriftCheck, |
| 783dd46 | 848 | fireServerTargetDeploys, |
| da3fc18 | 849 | fireDependencyScan, |
| c9ed210 | 850 | fireCloudDeploys, |
| 641aa42 | 851 | fireRepoOnboarding, |
| a686079 | 852 | }; |