Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions pkgs/github-ci/worker/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,19 @@ 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.

## GitHub mirror (#8580)

Fleet-repo `issues` / `pull_request` / `issue_comment` deliveries also
upsert the GitHub mirror in **fleet-queue** (`src/mirror.ts`; DDL in
`mirror.sql`): `github_mirror_issues` (title, body hash, state, labels,
assignees, comments count, latest agent-note pointer),
`github_mirror_pull_requests` (+ merged, draft, head/base), and
`github_mirror_meta` (per-repo staleness: `last_webhook_at` /
`last_webhook_event` stamped here; `last_backfill_at` stamped by the
backfill/repair sweep).

The mirror is a **read model**: rebuildable from GitHub at any time,
never a second truth. Staleness is reported, never gated on (#8575).
Mirror write failures are fatal (500 -> GitHub retries), matching the
ci_events policy.
67 changes: 67 additions & 0 deletions pkgs/github-ci/worker/mirror.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
-- GitHub mirror schema (#8580, fleet unification slice 2).
-- Home: the fleet-queue Turso database. The github-ci Worker ensures
-- these tables idempotently on every mirror write (src/mirror.ts
-- MIRROR_DDL mirrors this file); this file is the human-readable DDL
-- of record and the rebuild starting point.
--
-- The mirror is a READ MODEL: rebuildable from GitHub by the
-- backfill/repair sweep, never a second truth. github_mirror_meta
-- carries the staleness readout (last webhook, last successful
-- backfill) — it informs readers; it never gates work (#8575).

CREATE TABLE IF NOT EXISTS github_mirror_issues (
repo TEXT NOT NULL, number INTEGER NOT NULL,
title TEXT, body_hash TEXT, state TEXT,
labels TEXT NOT NULL DEFAULT '[]',
assignees TEXT NOT NULL DEFAULT '[]',
comments INTEGER NOT NULL DEFAULT 0,
comments_gh_updated_at TEXT,
latest_agent_note_id INTEGER, latest_agent_note_url TEXT,
author TEXT, html_url TEXT,
gh_created_at TEXT, gh_updated_at TEXT,
mirrored_at TEXT NOT NULL,
PRIMARY KEY (repo, number));

CREATE TABLE IF NOT EXISTS github_mirror_pull_requests (
repo TEXT NOT NULL, number INTEGER NOT NULL,
title TEXT, body_hash TEXT, state TEXT,
merged INTEGER NOT NULL DEFAULT 0,
draft INTEGER NOT NULL DEFAULT 0,
head_sha TEXT, head_ref TEXT, base_ref TEXT,
labels TEXT NOT NULL DEFAULT '[]',
assignees TEXT NOT NULL DEFAULT '[]',
comments INTEGER NOT NULL DEFAULT 0,
comments_gh_updated_at TEXT,
latest_agent_note_id INTEGER, latest_agent_note_url TEXT,
author TEXT, html_url TEXT,
gh_created_at TEXT, gh_updated_at TEXT,
mirrored_at TEXT NOT NULL,
PRIMARY KEY (repo, number));

CREATE TABLE IF NOT EXISTS github_mirror_meta (
repo TEXT PRIMARY KEY,
last_webhook_at TEXT, last_webhook_event TEXT,
last_backfill_at TEXT);

-- Deletion tombstones: an issues "deleted" delivery removes the
-- mirror row and records the deleted issue's updated_at here, so a
-- delayed pre-deletion snapshot or comment is absorbed by the
-- marker instead of resurrecting the row (the projector's
-- deletionBlocks rule; Codex P2 on PR #8604).
CREATE TABLE IF NOT EXISTS github_mirror_tombstones (
repo TEXT NOT NULL, number INTEGER NOT NULL,
gh_updated_at TEXT,
mirrored_at TEXT NOT NULL,
PRIMARY KEY (repo, number));

-- Deleted agent-note markers: an agent note's "deleted" delivery
-- clears the latest-note pointer AND records the comment id here, so
-- a delayed created/edited redelivery of the same comment cannot
-- resurrect the pointer through the empty-pointer branch (Codex P2
-- on PR #8604). A recreated note always has a new comment id, so a
-- marker never suppresses a live note.
CREATE TABLE IF NOT EXISTS github_mirror_deleted_notes (
repo TEXT NOT NULL, number INTEGER NOT NULL,
comment_id INTEGER NOT NULL,
mirrored_at TEXT NOT NULL,
PRIMARY KEY (repo, number, comment_id));
85 changes: 72 additions & 13 deletions pkgs/github-ci/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@
* - 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:<repo>' in
* fleet-queue.
* - pull_request / issues: append an agent event via the sink,
* set the agent_watermarks key 'dirty:<repo>' in fleet-queue,
* and upsert the #8580 GitHub mirror row (src/mirror.ts).
* - issue_comment: append an agent event, stamp the watermark,
* and refresh the mirror row's comments count / latest
* agent-note pointer.
* - ping: pong. Everything else: 202 ignored.
*/
import { Turso, iArg, tArg } from "./turso";
Expand All @@ -31,6 +34,7 @@ import {
stampDirtyWatermark,
type SinkEnv,
} from "./sink";
import { mirrorCommentEvent, mirrorIssueEvent, mirrorPrEvent } from "./mirror";

export interface Env extends SinkEnv {
GITHUB_WEBHOOK_SECRET: string;
Expand All @@ -46,8 +50,14 @@ async function hmacHex(secret: string, body: string): Promise<string> {
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("");
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 {
Expand All @@ -66,13 +76,18 @@ function json(body: unknown, status = 200): Response {

export default {
async fetch(req: Request, env: Env): Promise<Response> {
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 });
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 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 });
Expand Down Expand Up @@ -109,23 +124,57 @@ export default {
const ref = String(payload.ref ?? "");
const payloadDefaultBranch =
typeof repo.default_branch === "string" ? repo.default_branch : null;
await advanceSnapshot(env, repoName, after, ref, nowIso, payloadDefaultBranch);
await advanceSnapshot(
env,
repoName,
after,
ref,
nowIso,
payloadDefaultBranch,
);
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<string, unknown>;
const obj = (payload.pull_request ?? payload.issue ?? {}) as Record<
string,
unknown
>;
const action = String(payload.action ?? "");
const detail = {
repo: repoName,
action,
number: Number(obj.number ?? 0) || null,
title: (obj.title as string) ?? null,
label:
((payload.label as Record<string, unknown> | undefined)
?.name as string) ?? null,
};
await appendAgentEvent(env, eventType, detail);
await stampDirtyWatermark(env, repoName, eventType, nowIso);
// #8580: the mirror row is the read model; a failed write is
// fatal like the ci_events insert (500 -> GitHub retries).
if (eventType === "issues")
await mirrorIssueEvent(env, payload, repoName);
else await mirrorPrEvent(env, payload, repoName);
return json({ ok: true, repo: repoName, event: eventType });
}

// ------------------------------------------------ issue_comment ---
if (eventType === "issue_comment" && isFleet) {
const issue = (payload.issue ?? {}) as Record<string, unknown>;
const comment = (payload.comment ?? {}) as Record<string, unknown>;
const detail = {
repo: repoName,
action: String(payload.action ?? ""),
number: Number(issue.number ?? 0) || null,
comment_id: Number(comment.id ?? 0) || null,
};
await appendAgentEvent(env, "issue_comment", detail);
await stampDirtyWatermark(env, repoName, "issue_comment", nowIso);
await mirrorCommentEvent(env, payload, repoName);
return json({ ok: true, repo: repoName, event: eventType });
}

Expand All @@ -144,7 +193,10 @@ export default {
if (skipped) {
return json({ ok: true, skipped, repo: repoName, run_id: runId });
}
const platform = new Turso(env.TURSO_PLATFORM_URL, env.TURSO_PLATFORM_TOKEN);
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,
Expand Down Expand Up @@ -173,10 +225,17 @@ export default {
tArg(row.dedupe_key),
],
);
return json({ ok: true, repo: repoName, run_id: runId, conclusion: row.conclusion });
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}`);
console.error(
`github-ci worker failed (${eventType} ${repoName}): ${msg}`,
);
return new Response(`receiver failed: ${msg}`, { status: 500 });
}
},
Expand Down
Loading
Loading