diff --git a/pkgs/github-ci/worker/README.md b/pkgs/github-ci/worker/README.md new file mode 100644 index 0000000000..62d4b4efe7 --- /dev/null +++ b/pkgs/github-ci/worker/README.md @@ -0,0 +1,54 @@ +# github-ci Worker + +The GitHub webhook receiver (developing-today/code#5693), re-homed +off the Supabase Edge Function of the same name — the last Edge +Function on muse-dev2. Ported behavior-for-behavior from the Edge +Function (ACTIVE v8) so the two receivers can run side by side +during the dual-run diff period. + +## Shape + +- `src/index.ts` — HMAC-SHA256 gate (Web Crypto, same semantics as + the Edge Function), routing, workflow_run ingest. +- `src/policy.ts` — the v4 ingest policy as pure functions: + completed runs only, conclusion != skipped, raw payload kept + only for failures, dedupe_key `github::::`. +- `src/turso.ts` — minimal libSQL `/v2/pipeline` client with typed + args (no string interpolation). +- `src/sink.ts` — the #5690 agent-events sink (POST the queue + broker's `/events-append` when `EVENTS_BROKER_URL` is set; until + a public broker route exists — the broker is tailnet-only — the + Worker performs the sink's own INSERT into fleet-queue `events`), + plus the fleet-queue stores that replace PG `agent.repo_snapshots` + (`agent_repo_snapshots`) and `agent.watermarks` (`agent_watermarks`, + `dirty:` keys). + +## Writes (Turso only — no Postgres anywhere) + +- `workflow_run` → `ci_events` in **fleet-platform**, + `INSERT OR IGNORE` on `dedupe_key`, `id` unset (dedupe_key is + the identity; readers use `received_at`). +- Fleet-repo `push` → head_sha advance in `agent_repo_snapshots` + (fleet-queue) + a `push` sink event. +- Fleet-repo `pull_request` / `issues` → sink event + + `dirty:` watermark in `agent_watermarks` (fleet-queue). + +## Secrets (names only; set with `wrangler secret put`) + +`GITHUB_WEBHOOK_SECRET` (new value minted for this Worker, vaulted +in BWS as `cloudflare.github-ci-webhook-secret`; the org/App flip +rotates it again per #5693), `TURSO_PLATFORM_TOKEN` +(`turso.fleet-platform-rw-token`), `TURSO_QUEUE_TOKEN` +(`turso.fleet-queue-rw-token`). + +## Run + +```sh +npm install +npm test # vitest + @cloudflare/vitest-pool-workers +npm run deploy # wrangler deploy (fleet Cloudflare account) +``` + +Cutover state lives on #5693: deploy dark → replay smoke → one +repo-level dual-run webhook → (later, separately) org/App flip. +The Edge Function stays deployed as rollback until then. diff --git a/pkgs/github-ci/worker/package.json b/pkgs/github-ci/worker/package.json new file mode 100644 index 0000000000..1b2f825cd9 --- /dev/null +++ b/pkgs/github-ci/worker/package.json @@ -0,0 +1,20 @@ +{ + "name": "github-ci-worker", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "GitHub webhook receiver (#5693): workflow_run -> Turso ci_events only; fleet push/PR/issues -> agent events sink + fleet-queue snapshots/watermarks.", + "scripts": { + "deploy": "wrangler deploy", + "dev": "wrangler dev", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@cloudflare/vitest-pool-workers": "0.9.14", + "@cloudflare/workers-types": "^4.20251011.0", + "typescript": "^5.6.0", + "vitest": "^3.2.0", + "wrangler": "4.44.0" + } +} diff --git a/pkgs/github-ci/worker/src/index.ts b/pkgs/github-ci/worker/src/index.ts new file mode 100644 index 0000000000..999d180f17 --- /dev/null +++ b/pkgs/github-ci/worker/src/index.ts @@ -0,0 +1,173 @@ +/** + * github-ci Worker (#5693) — the GitHub webhook receiver, re-homed + * off the Supabase Edge Function of the same name (ACTIVE v8). + * + * Gate: HMAC-SHA256 over the raw body, X-Hub-Signature-256 header, + * verified with Web Crypto against GITHUB_WEBHOOK_SECRET — the same + * semantics as the Edge Function (which ran verify_jwt=false; the + * HMAC is the gate). + * + * Behavior (parity with the Edge Function, minus Postgres): + * - workflow_run (any repo): INSERT OR IGNORE into Turso + * fleet-platform ci_events ONLY, id unset (dedupe_key is the + * identity), v4 ingest policy: completed runs only, conclusion + * != skipped, raw payload kept only for failures. Fatal on + * failure (500 -> GitHub retries), as the EF's PG insert was. + * - Fleet repos only: + * - push: advance agent_repo_snapshots.head_sha in fleet-queue + * (default-branch pushes only), stamp fetch_source='webhook', + * append a 'push' agent event via the #5690 sink. + * - pull_request / issues: append an agent event via the sink + * and set the agent_watermarks key 'dirty:' in + * fleet-queue. + * - ping: pong. Everything else: 202 ignored. + */ +import { Turso, iArg, tArg } from "./turso"; +import { FLEET_REPOS, buildRunRow, skipReason } from "./policy"; +import { + advanceSnapshot, + appendAgentEvent, + queueNow, + stampDirtyWatermark, + type SinkEnv, +} from "./sink"; + +export interface Env extends SinkEnv { + GITHUB_WEBHOOK_SECRET: string; + TURSO_PLATFORM_URL: string; + TURSO_PLATFORM_TOKEN: string; +} + +async function hmacHex(secret: string, body: string): Promise { + const key = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body)); + return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +function timingSafeEqual(a: string, b: string): boolean { + if (a.length !== b.length) return false; + let out = 0; + for (let i = 0; i < a.length; i++) out |= a.charCodeAt(i) ^ b.charCodeAt(i); + return out === 0; +} + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +} + +export default { + async fetch(req: Request, env: Env): Promise { + if (req.method === "GET") return new Response("github-ci worker ok", { status: 200 }); + if (req.method !== "POST") return new Response("method not allowed", { status: 405 }); + + const raw = await req.text(); + const secret = env.GITHUB_WEBHOOK_SECRET ?? ""; + if (secret) { + const given = (req.headers.get("x-hub-signature-256") ?? "").replace("sha256=", ""); + const expected = await hmacHex(secret, raw); + if (!timingSafeEqual(given, expected)) { + return new Response("bad signature", { status: 401 }); + } + } + + let payload: Record; + try { + payload = JSON.parse(raw); + } catch { + return new Response("bad json", { status: 400 }); + } + + const eventType = req.headers.get("x-github-event") ?? "workflow_run"; + if (eventType === "ping") return new Response("pong", { status: 200 }); + + const repo = (payload.repository ?? {}) as Record; + const repoName = String(repo.full_name ?? "unknown"); + const isFleet = FLEET_REPOS.has(repoName); + const nowIso = new Date().toISOString(); + + try { + // ---------------------------------------------------------- push --- + if (eventType === "push" && isFleet) { + const after = String(payload.after ?? ""); + const ref = String(payload.ref ?? ""); + await advanceSnapshot(env, repoName, after, ref, nowIso); + await appendAgentEvent(env, "push", { repo: repoName, after, ref }); + return json({ ok: true, repo: repoName, after }); + } + + // ---------------------------------------- pull_request / issues --- + if ((eventType === "pull_request" || eventType === "issues") && isFleet) { + const obj = (payload.pull_request ?? payload.issue ?? {}) as Record; + const action = String(payload.action ?? ""); + const detail = { + repo: repoName, + action, + number: Number(obj.number ?? 0) || null, + title: (obj.title as string) ?? null, + }; + await appendAgentEvent(env, eventType, detail); + await stampDirtyWatermark(env, repoName, eventType, nowIso); + return json({ ok: true, repo: repoName, event: eventType }); + } + + if (eventType !== "workflow_run") { + return new Response(`ignored event ${eventType}`, { status: 202 }); + } + + // -------------------------------------------------- workflow_run --- + const { row, runId, action, conclusion } = buildRunRow( + payload, + repoName, + eventType, + queueNow(), + ); + const skipped = skipReason(action, conclusion); + if (skipped) { + return json({ ok: true, skipped, repo: repoName, run_id: runId }); + } + const platform = new Turso(env.TURSO_PLATFORM_URL, env.TURSO_PLATFORM_TOKEN); + await platform.execute( + `INSERT OR IGNORE INTO ci_events (received_at, source, event_type, + action, repo, workflow_name, workflow_id, run_id, run_attempt, + branch, sha, status, conclusion, actor, html_url, ci_started_at, + ci_updated_at, payload, dedupe_key) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + tArg(row.received_at), + tArg(row.source), + tArg(row.event_type), + tArg(row.action), + tArg(row.repo), + tArg(row.workflow_name), + iArg(row.workflow_id), + iArg(row.run_id), + iArg(row.run_attempt), + tArg(row.branch), + tArg(row.sha), + tArg(row.status), + tArg(row.conclusion), + tArg(row.actor), + tArg(row.html_url), + tArg(row.ci_started_at), + tArg(row.ci_updated_at), + tArg(row.payload), + tArg(row.dedupe_key), + ], + ); + return json({ ok: true, repo: repoName, run_id: runId, conclusion: row.conclusion }); + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + console.error(`github-ci worker failed (${eventType} ${repoName}): ${msg}`); + return new Response(`receiver failed: ${msg}`, { status: 500 }); + } + }, +}; diff --git a/pkgs/github-ci/worker/src/policy.ts b/pkgs/github-ci/worker/src/policy.ts new file mode 100644 index 0000000000..a5f13f607e --- /dev/null +++ b/pkgs/github-ci/worker/src/policy.ts @@ -0,0 +1,81 @@ +/** + * Pure ingest policy, ported 1:1 from the github-ci Edge Function + * (ACTIVE v8) so the two receivers are interchangeable during the + * #5693 dual-run diff period. + */ +export const FLEET_REPOS = new Set([ + "developing-today/code", + "developing-today/opencode", + "developing-today/openchamber", + "dezren39/nix", +]); + +export interface RunRow { + received_at: string; + source: string; + event_type: string; + action: string; + repo: string; + workflow_name: string | null; + workflow_id: number | null; + run_id: number | null; + run_attempt: number; + branch: string | null; + sha: string | null; + status: string | null; + conclusion: string | null; + actor: string | null; + html_url: string | null; + ci_started_at: string | null; + ci_updated_at: string | null; + payload: string; + dedupe_key: string; +} + +/** v4 ingest policy: store only completed runs, never skipped. */ +export function skipReason(action: string, conclusion: string | null): string | null { + if (action !== "completed") return "not_completed"; + if (conclusion === "skipped") return "skipped_conclusion"; + return null; +} + +export function dedupeKey(repo: string, runId: number | null, attempt: number, action: string): string { + return `github:${repo}:${runId}:${attempt}:${action}`; +} + +export function buildRunRow( + payload: Record, + repoName: string, + eventType: string, + receivedAt: string, +): { row: RunRow; runId: number | null; action: string; conclusion: string | null } { + const run = (payload.workflow_run ?? {}) as Record; + const runId = Number(run.id ?? 0) || null; + const attempt = Number(run.run_attempt ?? 1) || 1; + const action = String(payload.action ?? ""); + const conclusion = (run.conclusion as string | null) ?? null; + const row: RunRow = { + received_at: receivedAt, + source: "github", + event_type: eventType, + action, + repo: repoName, + workflow_name: (run.name as string) ?? null, + workflow_id: Number(run.workflow_id ?? 0) || null, + run_id: runId, + run_attempt: attempt, + branch: (run.head_branch as string) ?? null, + sha: (run.head_sha as string) ?? null, + status: (run.status as string) ?? null, + conclusion, + actor: ((run.actor as Record | undefined)?.login as string) ?? null, + html_url: (run.html_url as string) ?? null, + ci_started_at: (run.run_started_at as string) ?? (run.created_at as string) ?? null, + ci_updated_at: (run.updated_at as string) ?? null, + // v4 policy: raw payload kept only for failures (forensics); + // every other stored row carries an empty object. + payload: conclusion === "failure" ? JSON.stringify(payload) : "{}", + dedupe_key: dedupeKey(repoName, runId, attempt, action), + }; + return { row, runId, action, conclusion }; +} diff --git a/pkgs/github-ci/worker/src/sink.ts b/pkgs/github-ci/worker/src/sink.ts new file mode 100644 index 0000000000..085412709a --- /dev/null +++ b/pkgs/github-ci/worker/src/sink.ts @@ -0,0 +1,129 @@ +/** + * The agent-events sink (#5690) and the fleet-queue snapshot / + * watermark stores (#5693). + * + * Sink route: when EVENTS_BROKER_URL is configured, events are + * POSTed to the queue broker's /events-append verb — the sink's + * public face. The production broker today listens on the tailnet + * only, which a Cloudflare Worker cannot reach, so until a public + * broker route exists the Worker performs the sink write itself: + * the exact INSERT INTO events statement that the broker's + * /events-append verb executes (turso_queue.rs verb_events_append) + * and that the Edge Function's AGENT_EVENTS_SINK=turso path used. + * One sink, one table, one row shape (worker_id 'github-webhook', + * task_id NULL, whole-second Z timestamps) — never a third + * implementation with its own semantics. + */ +import { Turso, tArg } from "./turso"; + +export interface SinkEnv { + TURSO_QUEUE_URL: string; + TURSO_QUEUE_TOKEN: string; + EVENTS_BROKER_URL?: string; + EVENTS_BROKER_TOKEN?: string; +} + +/** Queue-backend timestamp format: whole seconds, Z (matches EF). */ +export function queueNow(d = new Date()): string { + return d.toISOString().replace(/\.\d{3}Z$/, "Z"); +} + +export async function appendAgentEvent( + env: SinkEnv, + kind: string, + detail: Record, +): Promise { + if (env.EVENTS_BROKER_URL) { + const res = await fetch(`${env.EVENTS_BROKER_URL.replace(/\/$/, "")}/events-append`, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(env.EVENTS_BROKER_TOKEN + ? { Authorization: `Bearer ${env.EVENTS_BROKER_TOKEN}` } + : {}), + }, + body: JSON.stringify({ worker_id: "github-webhook", kind, detail }), + }); + if (!res.ok) throw new Error(`events-append failed: HTTP ${res.status}`); + const out = (await res.json().catch(() => ({}))) as { ok?: boolean }; + if (out && out.ok === false) throw new Error("events-append failed: broker returned not-ok"); + return; + } + const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); + await q.execute( + "INSERT INTO events (worker_id, task_id, kind, detail, created_at) VALUES (?, NULL, ?, ?, ?)", + [tArg("github-webhook"), tArg(kind), tArg(JSON.stringify(detail)), tArg(queueNow())], + ); +} + +/** + * Advance agent_repo_snapshots.head_sha for a default-branch push + * (fleet-queue, the #5693 home for PG agent.repo_snapshots). + * Mirrors the Edge Function: side-branch pushes never move head; + * a missing row is inserted minimal (the fetcher fills the rest). + * Returns true when a snapshot row was written. + */ +export async function advanceSnapshot( + env: SinkEnv, + repo: string, + after: string, + ref: string, + nowIso: string, +): Promise { + const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); + const existing = await q.queryText( + "SELECT repo FROM agent_repo_snapshots WHERE repo = ?", + [tArg(repo)], + ); + const defBranch = existing + ? await q.queryText("SELECT default_branch FROM agent_repo_snapshots WHERE repo = ?", [ + tArg(repo), + ]) + : null; + const zeroSha = /^0+$/.test(after); + let head: string | null = null; + if (existing) { + if (!zeroSha && (!defBranch || ref === `refs/heads/${defBranch}`)) head = after; + } else if (!zeroSha && ref.startsWith("refs/heads/")) { + head = after; + } + if (!head && existing) return false; + if (head) { + await q.execute( + `INSERT INTO agent_repo_snapshots (repo, head_sha, fetched_at, fetch_source) + VALUES (?, ?, ?, 'webhook') + ON CONFLICT(repo) DO UPDATE SET head_sha = excluded.head_sha, + fetched_at = excluded.fetched_at, fetch_source = 'webhook'`, + [tArg(repo), tArg(head), tArg(nowIso)], + ); + } else { + await q.execute( + `INSERT INTO agent_repo_snapshots (repo, fetched_at, fetch_source) + VALUES (?, ?, 'webhook') + ON CONFLICT(repo) DO UPDATE SET fetched_at = excluded.fetched_at, + fetch_source = 'webhook'`, + [tArg(repo), tArg(nowIso)], + ); + } + return true; +} + +/** dirty: watermark into the fleet-queue watermark store. */ +export async function stampDirtyWatermark( + env: SinkEnv, + repo: string, + reason: string, + nowIso: string, +): Promise { + const q = new Turso(env.TURSO_QUEUE_URL, env.TURSO_QUEUE_TOKEN); + await q.execute( + `INSERT INTO agent_watermarks (key, value, updated_at) VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value, + updated_at = excluded.updated_at`, + [ + tArg(`dirty:${repo}`), + tArg(JSON.stringify({ reason, at: nowIso })), + tArg(nowIso), + ], + ); +} diff --git a/pkgs/github-ci/worker/src/turso.ts b/pkgs/github-ci/worker/src/turso.ts new file mode 100644 index 0000000000..c57cc68007 --- /dev/null +++ b/pkgs/github-ci/worker/src/turso.ts @@ -0,0 +1,77 @@ +/** + * Minimal libSQL HTTP client (the /v2/pipeline route every fleet + * Turso writer uses: the Edge Function mirror, fleet-fetch, the + * queue broker's Turso backend). Statements use typed args, never + * string interpolation. + */ +export type TursoArg = + | { type: "null" } + | { type: "text"; value: string } + | { type: "integer"; value: string }; + +export const tArg = (v: string | null | undefined): TursoArg => + v === null || v === undefined ? { type: "null" } : { type: "text", value: v }; +export const iArg = (v: number | null | undefined): TursoArg => + v === null || v === undefined || !Number.isFinite(v) + ? { type: "null" } + : { type: "integer", value: String(Math.trunc(v)) }; + +interface PipelineResult { + type: string; + error?: { message?: string }; + response?: { + result?: { + rows?: TursoArg[][]; + last_insert_rowid?: number; + }; + }; +} + +export class Turso { + constructor( + private url: string, + private token: string, + ) {} + + /** Run statements in one pipeline; throws on any error result. */ + async batch(stmts: { sql: string; args?: TursoArg[] }[]): Promise { + if (!this.url || !this.token) throw new Error("turso url/token unset"); + const res = await fetch(`${this.url}/v2/pipeline`, { + method: "POST", + headers: { + Authorization: `Bearer ${this.token}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + requests: [ + ...stmts.map((s) => ({ + type: "execute", + stmt: s.args ? { sql: s.sql, args: s.args } : { sql: s.sql }, + })), + { type: "close" }, + ], + }), + }); + if (!res.ok) throw new Error(`turso pipeline failed: HTTP ${res.status}`); + const out = (await res.json()) as { results?: PipelineResult[] }; + const failed = (out.results ?? []).find((r) => r.type === "error"); + if (failed) { + throw new Error(`turso pipeline failed: ${failed.error?.message ?? "pipeline error"}`); + } + return out.results ?? []; + } + + async execute(sql: string, args?: TursoArg[]): Promise { + const results = await this.batch([{ sql, args }]); + return results[0]; + } + + /** First column of first row as text, or null when no row. */ + async queryText(sql: string, args?: TursoArg[]): Promise { + const r = await this.execute(sql, args); + const rows = r.response?.result?.rows ?? []; + const first = rows[0]?.[0]; + if (!first || first.type === "null") return null; + return "value" in first ? String(first.value) : null; + } +} diff --git a/pkgs/github-ci/worker/test/policy.test.ts b/pkgs/github-ci/worker/test/policy.test.ts new file mode 100644 index 0000000000..3a1af721b6 --- /dev/null +++ b/pkgs/github-ci/worker/test/policy.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { buildRunRow, dedupeKey, skipReason } from "../src/policy"; + +const failurePayload = { + action: "completed", + workflow_run: { + id: 12345, + run_attempt: 2, + name: "CI", + workflow_id: 777, + head_branch: "main", + head_sha: "abc123", + status: "completed", + conclusion: "failure", + actor: { login: "dezren39" }, + html_url: "https://github.com/x/y/actions/runs/12345", + run_started_at: "2026-11-07T10:00:00Z", + updated_at: "2026-11-07T10:05:00Z", + }, + repository: { full_name: "developing-today/code" }, +}; + +describe("v4 ingest policy", () => { + it("stores completed non-skipped runs only", () => { + expect(skipReason("completed", "success")).toBeNull(); + expect(skipReason("completed", "failure")).toBeNull(); + expect(skipReason("requested", null)).toBe("not_completed"); + expect(skipReason("completed", "skipped")).toBe("skipped_conclusion"); + }); + it("dedupe key matches the Edge Function format", () => { + expect(dedupeKey("developing-today/code", 12345, 2, "completed")).toBe( + "github:developing-today/code:12345:2:completed", + ); + }); + it("keeps the raw payload only for failures", () => { + const fail = buildRunRow(failurePayload, "developing-today/code", "workflow_run", "2026-11-07T16:05:00Z"); + expect(fail.row.payload).toContain("workflow_run"); + expect(fail.row.dedupe_key).toBe("github:developing-today/code:12345:2:completed"); + const okPayload = structuredClone(failurePayload) as typeof failurePayload; + okPayload.workflow_run.conclusion = "success"; + const ok = buildRunRow(okPayload, "developing-today/code", "workflow_run", "2026-11-07T16:05:00Z"); + expect(ok.row.payload).toBe("{}"); + }); +}); diff --git a/pkgs/github-ci/worker/test/worker.test.ts b/pkgs/github-ci/worker/test/worker.test.ts new file mode 100644 index 0000000000..238bfe1b0d --- /dev/null +++ b/pkgs/github-ci/worker/test/worker.test.ts @@ -0,0 +1,137 @@ +import { createExecutionContext, env, fetchMock, waitOnExecutionContext } from "cloudflare:test"; +import { describe, expect, it, beforeAll, afterEach } from "vitest"; +import worker from "../src/index"; + +const SECRET = "test-webhook-secret"; +const PLATFORM = "https://fleet-platform-dezren39.aws-us-east-1.turso.io"; +const QUEUE = "https://fleet-queue-dezren39.aws-us-east-1.turso.io"; + +async function sign(body: string): Promise { + const key = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(SECRET), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body)); + return "sha256=" + [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +function tursoOk() { + return JSON.stringify({ + results: [{ type: "success", response: { type: "execute", result: { rows: [] } } }, { type: "success" }], + }); +} + +async function post(body: string, event: string, sig?: string): Promise { + const req = new Request("https://github-ci.test/", { + method: "POST", + headers: { + "x-github-event": event, + ...(sig ? { "x-hub-signature-256": sig } : {}), + }, + body, + }); + const ctx = createExecutionContext(); + const res = await worker.fetch(req, env as unknown as Parameters[1]); + await waitOnExecutionContext(ctx); + return res; +} + +const runPayload = JSON.stringify({ + action: "completed", + workflow_run: { + id: 999, + run_attempt: 1, + name: "CI", + workflow_id: 5, + head_branch: "main", + head_sha: "deadbeef", + status: "completed", + conclusion: "success", + actor: { login: "dezren39" }, + html_url: "https://example.invalid/run/999", + run_started_at: "2026-11-07T10:00:00Z", + updated_at: "2026-11-07T10:01:00Z", + }, + repository: { full_name: "developing-today/code" }, +}); + +beforeAll(() => { + fetchMock.activate(); + fetchMock.disableNetConnect(); +}); +afterEach(() => fetchMock.assertNoPendingInterceptors()); + +describe("github-ci worker", () => { + it("rejects a bad signature with 401", async () => { + const res = await post(runPayload, "workflow_run", "sha256=00"); + expect(res.status).toBe(401); + }); + + it("answers ping", async () => { + const body = JSON.stringify({ zen: "ok" }); + const res = await post(body, "ping", await sign(body)); + expect(res.status).toBe(200); + expect(await res.text()).toBe("pong"); + }); + + it("stores a completed workflow_run into ci_events via INSERT OR IGNORE, id unset", async () => { + let sqlSeen = ""; + fetchMock + .get(PLATFORM) + .intercept({ path: "/v2/pipeline", method: "POST" }) + .reply(200, (opts) => { + sqlSeen = String(opts.body); + return tursoOk(); + }); + const res = await post(runPayload, "workflow_run", await sign(runPayload)); + expect(res.status).toBe(200); + expect(sqlSeen).toContain("INSERT OR IGNORE INTO ci_events"); + expect(sqlSeen).not.toContain("INSERT OR IGNORE INTO ci_events (id"); + expect(sqlSeen).toContain("github:developing-today/code:999:1:completed"); + }); + + it("skips non-completed runs without touching Turso", async () => { + const p = JSON.stringify({ + action: "requested", + workflow_run: { id: 1, conclusion: null }, + repository: { full_name: "developing-today/code" }, + }); + const res = await post(p, "workflow_run", await sign(p)); + expect(res.status).toBe(200); + expect((await res.json()) as { skipped?: string }).toMatchObject({ skipped: "not_completed" }); + }); + + it("ignores unknown events with 202", async () => { + const p = JSON.stringify({ repository: { full_name: "developing-today/code" } }); + const res = await post(p, "star", await sign(p)); + expect(res.status).toBe(202); + }); + + it("push on a fleet repo advances the snapshot and appends a sink event", async () => { + const seen: string[] = []; + const queueMock = fetchMock.get(QUEUE); + // snapshot read (1 pipeline) + upsert (1) + event insert (1) + for (let i = 0; i < 3; i++) { + queueMock + .intercept({ path: "/v2/pipeline", method: "POST" }) + .reply(200, (opts) => { + seen.push(String(opts.body)); + return tursoOk(); + }); + } + const p = JSON.stringify({ + ref: "refs/heads/main", + after: "cafe1234", + repository: { full_name: "developing-today/code" }, + }); + const res = await post(p, "push", await sign(p)); + expect(res.status).toBe(200); + const all = seen.join("\n"); + expect(all).toContain("agent_repo_snapshots"); + expect(all).toContain("INSERT INTO events"); + expect(all).toContain("github-webhook"); + }); +}); diff --git a/pkgs/github-ci/worker/tsconfig.json b/pkgs/github-ci/worker/tsconfig.json new file mode 100644 index 0000000000..2f54dedc2b --- /dev/null +++ b/pkgs/github-ci/worker/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "forceConsistentCasingInFileNames": true, + "lib": [ + "ES2022" + ], + "module": "ESNext", + "moduleResolution": "bundler", + "noEmit": true, + "skipLibCheck": true, + "strict": true, + "target": "ES2022", + "types": [ + "@cloudflare/workers-types", + "@cloudflare/vitest-pool-workers" + ] + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts", + "vitest.config.ts" + ] +} \ No newline at end of file diff --git a/pkgs/github-ci/worker/vitest.config.ts b/pkgs/github-ci/worker/vitest.config.ts new file mode 100644 index 0000000000..4267c344b8 --- /dev/null +++ b/pkgs/github-ci/worker/vitest.config.ts @@ -0,0 +1,18 @@ +import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; + +export default defineWorkersConfig({ + test: { + poolOptions: { + workers: { + wrangler: { configPath: "./wrangler.toml" }, + miniflare: { + bindings: { + GITHUB_WEBHOOK_SECRET: "test-webhook-secret", + TURSO_PLATFORM_TOKEN: "test-platform-token", + TURSO_QUEUE_TOKEN: "test-queue-token", + }, + }, + }, + }, + }, +}); diff --git a/pkgs/github-ci/worker/wrangler.toml b/pkgs/github-ci/worker/wrangler.toml new file mode 100644 index 0000000000..7c27bf2aed --- /dev/null +++ b/pkgs/github-ci/worker/wrangler.toml @@ -0,0 +1,27 @@ +# github-ci Worker (#5693): the GitHub webhook receiver, re-homed off +# the Supabase Edge Function of the same name. Deployed to the fleet +# Cloudflare account. Dark until the #5693 cutover steps run: no +# webhook points here until a repo-level dual-run webhook is added. +# +# Secrets (wrangler secret put; values never in this file): +# GITHUB_WEBHOOK_SECRET HMAC gate; NEW value minted for this +# Worker, vaulted in BWS by name +# (cloudflare.github-ci-webhook-secret). +# The org/App flip rotates again (#5693). +# TURSO_PLATFORM_TOKEN turso.fleet-platform-rw-token (ci_events) +# TURSO_QUEUE_TOKEN turso.fleet-queue-rw-token (agent events, +# snapshots, watermarks) +name = "github-ci" +main = "src/index.ts" +compatibility_date = "2025-09-15" +workers_dev = true + +[vars] +TURSO_PLATFORM_URL = "https://fleet-platform-dezren39.aws-us-east-1.turso.io" +TURSO_QUEUE_URL = "https://fleet-queue-dezren39.aws-us-east-1.turso.io" +# EVENTS_BROKER_URL is intentionally unset: the queue broker +# (/events-append, #5690) listens on the tailnet only, which a Worker +# cannot reach. When a public broker route exists, set this var and +# the Worker POSTs there instead of writing the sink table directly; +# until then it performs the sink write itself (the exact INSERT the +# broker's /events-append verb and the Edge Function's turso sink do).