Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat: close issues from merged GitHub pull requests (#120)

Carl Mercier48f4d0eeee5c
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 9a87bb9b..ddbeda42 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -15,6 +15,7 @@ import { setMcpApp } from './mcp/app-ref';
import { internalAgentRunRoutes } from './ai-agents/internal-routes';
import { internalNotificationRoutes } from './notifications/internal-routes';
import { internalTelegramRoutes } from './telegram/internal-routes';
+import { githubWebhookRoutes } from './github/routes';
// The assembled Elysia app, without `.listen()`. `index.ts` imports this and
// binds the port; tests import it and pass it to Eden Treaty to drive routes in
@@ -79,6 +80,10 @@ export const app = new Elysia()
{ name: 'Share', description: 'Public read-only sharing of issues and views' },
{ name: 'Actions', description: 'Project automation actions' },
{ name: 'Webhooks', description: 'Outgoing webhook subscriptions' },
+ {
+ name: 'GitHub',
+ description: 'GitHub integration: inbound PR webhook and its per-project settings',
+ },
{ name: 'Agent Schedules', description: 'Recurring tasks for internal agents' },
{ name: 'Dashboards', description: 'Saved analytics dashboards' },
{ name: 'Note boards', description: 'Freeform canvases of sticky notes' },
@@ -147,6 +152,8 @@ export const app = new Elysia()
.use(internalTelegramRoutes)
// Test receiver for inspecting webhook deliveries (unauthenticated, dev aid).
.use(webhookTestRoutes)
+ // Inbound GitHub webhook receiver (authenticated by its per-project secret).
+ .use(githubWebhookRoutes)
// Planner API: projects, issues, and their dependent entities.
.use(planner);
diff --git a/apps/api/src/github/__tests__/integration/github-webhook.test.ts b/apps/api/src/github/__tests__/integration/github-webhook.test.ts
new file mode 100644
index 00000000..22de0f5c
--- /dev/null
+++ b/apps/api/src/github/__tests__/integration/github-webhook.test.ts
@@ -0,0 +1,391 @@
+import { createHmac } from 'node:crypto';
+import { describe, it, expect, beforeEach } from 'bun:test';
+import { app } from '../../../app';
+import { authedApi, type Api } from '../../../__tests__/helpers/app';
+import { signUpTestUser } from '../../../__tests__/helpers/auth';
+import { resetDb } from '../../../__tests__/helpers/db';
+
+// The inbound GitHub webhook: a signed pull_request delivery moves the issues its
+// magic words name, through the same path a user's move takes (activity entries,
+// feed). Settings come from the planner routes; the delivery itself is
+// unauthenticated and verified by signature alone.
+
+interface Setup {
+ asOwner: Api;
+ webhookId: string;
+ secret: string;
+ columns: { id: number; stateType: string; name: string }[];
+}
+
+async function setupProject(): Promise<Setup> {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ const view = await asOwner.projects({ projectKey: 'MKT' }).get();
+ const settings = await asOwner.projects({ projectKey: 'MKT' }).settings.github.get();
+ await asOwner.projects({ projectKey: 'MKT' }).settings.github.patch({ enabled: true });
+ return {
+ asOwner,
+ webhookId: settings.data!.webhookId,
+ secret: settings.data!.secret!,
+ columns: view.data!.columns,
+ };
+}
+
+function createIssue(client: Api, columnId: number, title = 'Task') {
+ return client.projects({ projectKey: 'MKT' }).issues.post({ columnId, title });
+}
+
+// A minimal pull_request payload with the fields the handler reads.
+function prPayload(overrides: {
+ action?: string;
+ merged?: boolean;
+ draft?: boolean;
+ baseRef?: string;
+ title?: string;
+ body?: string;
+}) {
+ return {
+ action: overrides.action ?? 'closed',
+ pull_request: {
+ number: 42,
+ title: overrides.title ?? 'Some change',
+ body: overrides.body ?? null,
+ html_url: 'https://github.com/acme/site/pull/42',
+ merged: overrides.merged ?? true,
+ draft: overrides.draft ?? false,
+ base: { ref: overrides.baseRef ?? 'main' },
+ },
+ repository: { full_name: 'acme/site', default_branch: 'main' },
+ };
+}
+
+// Delivers a payload to the receiver, signed like GitHub signs it. Uses a raw
+// Request so the signature is computed over the exact bytes sent.
+async function deliver(
+ webhookId: string,
+ secret: string,
+ payload: unknown,
+ {
+ event = 'pull_request',
+ signature,
+ deliveryId,
+ }: { event?: string; signature?: string; deliveryId?: string } = {},
+) {
+ const body = JSON.stringify(payload);
+ const sig = signature ?? `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`;
+ const res = await app.handle(
+ new Request(`http://localhost/webhooks/github/${webhookId}`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-github-event': event,
+ 'x-hub-signature-256': sig,
+ 'x-github-delivery': deliveryId ?? crypto.randomUUID(),
+ },
+ body,
+ }),
+ );
+ return { status: res.status, data: (await res.json().catch(() => null)) as unknown };
+}
+
+async function issueState(client: Api, issueId: number) {
+ const res = await client.issues({ issueId }).get();
+ return res.data!;
+}
+
+describe('GitHub webhook', () => {
+ beforeEach(async () => {
+ await resetDb();
+ });
+
+ it('closes the issue named by a closing magic word when the PR merges', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+ const done = columns.find((c) => c.stateType === 'completed')!;
+
+ const res = await deliver(
+ webhookId,
+ secret,
+ prPayload({ body: `Fixes MKT-${issue.sequenceNumber}` }),
+ );
+ expect(res.status).toBe(200);
+ expect(res.data).toMatchObject({ handled: 'merged' });
+
+ const after = await issueState(asOwner, issue.id);
+ expect(after.columnId).toBe(done.id);
+
+ const feed = await asOwner.issues({ issueId: issue.id }).feed.get({ query: {} });
+ const items = feed.data!.items;
+ const prEntry = items.find((i: { action: string | null }) => i.action === 'github_pr');
+ expect(prEntry).toMatchObject({
+ actorName: 'GitHub',
+ subject: 'merged',
+ fromText: 'acme/site#42',
+ toText: 'https://github.com/acme/site/pull/42',
+ });
+ const statusEntry = items.find((i: { action: string | null }) => i.action === 'status');
+ expect(statusEntry).toMatchObject({ actorName: 'GitHub', toText: done.name });
+ });
+
+ it('moves the issue to the configured merge column', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const canceled = columns.find((c) => c.stateType === 'canceled')!;
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .settings.github.patch({ onMergeColumnId: canceled.id });
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+
+ await deliver(webhookId, secret, prPayload({ title: `Closes MKT-${issue.sequenceNumber}` }));
+ const after = await issueState(asOwner, issue.id);
+ expect(after.columnId).toBe(canceled.id);
+ });
+
+ it('rejects a delivery with a bad signature', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+
+ const res = await deliver(
+ webhookId,
+ secret,
+ prPayload({ body: `Fixes MKT-${issue.sequenceNumber}` }),
+ {
+ signature: 'sha256=' + '0'.repeat(64),
+ },
+ );
+ expect(res.status).toBe(401);
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(columns[0].id);
+ });
+
+ it('returns 404 for an unknown webhook id', async () => {
+ await setupProject();
+ const res = await deliver('0'.repeat(32), 'irrelevant', prPayload({}));
+ expect(res.status).toBe(404);
+ });
+
+ it('ignores a merge into a non-default branch', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+
+ const res = await deliver(
+ webhookId,
+ secret,
+ prPayload({ body: `Fixes MKT-${issue.sequenceNumber}`, baseRef: 'develop' }),
+ );
+ expect(res.data).toMatchObject({ handled: 'ignored' });
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(columns[0].id);
+ });
+
+ it('ignores a closed-without-merge PR', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+
+ const res = await deliver(
+ webhookId,
+ secret,
+ prPayload({ body: `Fixes MKT-${issue.sequenceNumber}`, merged: false }),
+ );
+ expect(res.data).toMatchObject({ handled: 'ignored' });
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(columns[0].id);
+ });
+
+ it('leaves an issue named by skip alone', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+
+ await deliver(
+ webhookId,
+ secret,
+ prPayload({ body: `Fixes MKT-${issue.sequenceNumber}\nskip MKT-${issue.sequenceNumber}` }),
+ );
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(columns[0].id);
+ });
+
+ it('leaves an already-closed issue in its column', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const canceled = columns.find((c) => c.stateType === 'canceled')!;
+ const issue = (await createIssue(asOwner, canceled.id)).data!;
+
+ await deliver(webhookId, secret, prPayload({ body: `Fixes MKT-${issue.sequenceNumber}` }));
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(canceled.id);
+ });
+
+ it('does nothing while the integration is disabled', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ await asOwner.projects({ projectKey: 'MKT' }).settings.github.patch({ enabled: false });
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+
+ const res = await deliver(
+ webhookId,
+ secret,
+ prPayload({ body: `Fixes MKT-${issue.sequenceNumber}` }),
+ );
+ expect(res.data).toMatchObject({ handled: 'disabled' });
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(columns[0].id);
+ });
+
+ it('moves a backlog issue to the configured column when a PR opens', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const started = columns.find((c) => c.stateType === 'started')!;
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .settings.github.patch({ onOpenColumnId: started.id });
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+
+ const res = await deliver(
+ webhookId,
+ secret,
+ prPayload({ action: 'opened', merged: false, body: `Refs MKT-${issue.sequenceNumber}` }),
+ );
+ expect(res.data).toMatchObject({ handled: 'opened' });
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(started.id);
+ });
+
+ it('links but does not move on PR open when no column is configured', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+
+ await deliver(
+ webhookId,
+ secret,
+ prPayload({ action: 'opened', merged: false, body: `Refs MKT-${issue.sequenceNumber}` }),
+ );
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(columns[0].id);
+ const feed = await asOwner.issues({ issueId: issue.id }).feed.get({ query: {} });
+ const prEntry = feed.data!.items.find(
+ (i: { action: string | null }) => i.action === 'github_pr',
+ );
+ expect(prEntry).toMatchObject({ actorName: 'GitHub', subject: 'opened' });
+ });
+
+ it('does not demote a started issue on PR open', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const started = columns.find((c) => c.stateType === 'started')!;
+ const backlogish = columns.find(
+ (c) => c.stateType === 'backlog' || c.stateType === 'unstarted',
+ )!;
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .settings.github.patch({ onOpenColumnId: backlogish.id });
+ const issue = (await createIssue(asOwner, started.id)).data!;
+
+ await deliver(
+ webhookId,
+ secret,
+ prPayload({ action: 'opened', merged: false, body: `Fixes MKT-${issue.sequenceNumber}` }),
+ );
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(started.id);
+ });
+
+ it('hides the secret from a member who may read but not edit integrations', async () => {
+ const { asOwner } = await setupProject();
+ // A custom role with integrations read only, assigned to an invited member.
+ const catalog = await asOwner.projects({ projectKey: 'MKT' }).roles.get();
+ const emptyMatrix = Object.fromEntries(
+ Object.keys(catalog.data![0].permissions).map((r) => [
+ r,
+ { create: false, edit: false, read: false, delete: false },
+ ]),
+ );
+ const role = await asOwner.projects({ projectKey: 'MKT' }).roles.post({
+ name: 'Integrations viewer',
+ permissions: {
+ ...emptyMatrix,
+ integrations: { create: false, edit: false, read: true, delete: false },
+ },
+ });
+ const viewer = await signUpTestUser({ name: 'Viewer' });
+ const invite = await asOwner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: viewer.email, role: 'member' });
+ const asViewer = authedApi(viewer.cookie);
+ await asViewer.invites({ token: invite.data!.token }).accept.post();
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .members({ userId: viewer.userId })
+ .patch({ role: 'member', roleId: role.data!.id });
+
+ const forViewer = await asViewer.projects({ projectKey: 'MKT' }).settings.github.get();
+ expect(forViewer.status).toBe(200);
+ expect(forViewer.data!.secret).toBeNull();
+
+ const forOwner = await asOwner.projects({ projectKey: 'MKT' }).settings.github.get();
+ expect(typeof forOwner.data!.secret).toBe('string');
+
+ const patchAttempt = await asViewer
+ .projects({ projectKey: 'MKT' })
+ .settings.github.patch({ enabled: false });
+ expect(patchAttempt.status).toBe(403);
+ });
+
+ it('a delivery stamps telemetry without touching the rest of the settings', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const canceled = columns.find((c) => c.stateType === 'canceled')!;
+ await asOwner
+ .projects({ projectKey: 'MKT' })
+ .settings.github.patch({ onMergeColumnId: canceled.id });
+
+ await deliver(webhookId, secret, prPayload({}));
+
+ const after = await asOwner.projects({ projectKey: 'MKT' }).settings.github.get();
+ expect(after.data).toMatchObject({
+ enabled: true,
+ secret,
+ onMergeColumnId: canceled.id,
+ lastEventRepo: 'acme/site',
+ });
+ expect(after.data!.lastEventAt).not.toBeNull();
+ });
+
+ it('processes a replayed delivery id only once', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+ const done = columns.find((c) => c.stateType === 'completed')!;
+ const payload = prPayload({ body: `Fixes MKT-${issue.sequenceNumber}` });
+
+ const first = await deliver(webhookId, secret, payload, { deliveryId: 'guid-1' });
+ expect(first.data).toMatchObject({ handled: 'merged' });
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(done.id);
+
+ // The user reopens the issue; replaying the same delivery must not re-close it.
+ await asOwner.issues({ issueId: issue.id }).patch({ columnId: columns[0].id });
+ const replay = await deliver(webhookId, secret, payload, { deliveryId: 'guid-1' });
+ expect(replay.data).toMatchObject({ handled: 'duplicate' });
+ expect((await issueState(asOwner, issue.id)).columnId).toBe(columns[0].id);
+ });
+
+ it('does not copy the GitHub settings into a project copy', async () => {
+ const { asOwner } = await setupProject();
+ const copy = await asOwner
+ .projects({ projectKey: 'MKT' })
+ .copy.post({ key: 'CPY', name: 'Copy', include: { configuration: true } });
+ expect(copy.status).toBe(201);
+
+ const source = await asOwner.projects({ projectKey: 'MKT' }).settings.github.get();
+ const copied = await asOwner.projects({ projectKey: 'CPY' }).settings.github.get();
+ expect(copied.data!.enabled).toBe(false);
+ expect(copied.data!.webhookId).not.toBe(source.data!.webhookId);
+ expect(copied.data!.secret).not.toBe(source.data!.secret);
+ });
+
+ it('regenerating the secret invalidates the old one', async () => {
+ const { asOwner, webhookId, secret, columns } = await setupProject();
+ const issue = (await createIssue(asOwner, columns[0].id)).data!;
+ const regenerated = await asOwner.projects({ projectKey: 'MKT' }).settings.github.secret.post();
+ expect(regenerated.data!.secret).not.toBe(secret);
+
+ const stale = await deliver(
+ webhookId,
+ secret,
+ prPayload({ body: `Fixes MKT-${issue.sequenceNumber}` }),
+ );
+ expect(stale.status).toBe(401);
+
+ const fresh = await deliver(
+ webhookId,
+ regenerated.data!.secret!,
+ prPayload({ body: `Fixes MKT-${issue.sequenceNumber}` }),
+ );
+ expect(fresh.status).toBe(200);
+ });
+});
diff --git a/apps/api/src/github/__tests__/unit/magic-words.test.ts b/apps/api/src/github/__tests__/unit/magic-words.test.ts
new file mode 100644
index 00000000..5c9561e7
--- /dev/null
+++ b/apps/api/src/github/__tests__/unit/magic-words.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect } from 'bun:test';
+import { parseMagicWords } from '../../magic-words';
+
+const ids = (refs: { key: string; sequenceNumber: number }[]) =>
+ refs.map((r) => `${r.key}-${r.sequenceNumber}`);
+
+describe('parseMagicWords', () => {
+ it('parses a closing word with one identifier', () => {
+ const parsed = parseMagicWords('Fixes MKT-42');
+ expect(ids(parsed.closes)).toEqual(['MKT-42']);
+ expect(parsed.references).toEqual([]);
+ });
+
+ it('parses every closing word inflection', () => {
+ for (const word of ['close', 'closes', 'fixed', 'resolving', 'completes', 'implemented']) {
+ const parsed = parseMagicWords(`${word} MKT-1`);
+ expect(ids(parsed.closes)).toEqual(['MKT-1']);
+ }
+ });
+
+ it('parses several identifiers after one word', () => {
+ const parsed = parseMagicWords('Closes MKT-1, MKT-2 and MKT-3');
+ expect(ids(parsed.closes)).toEqual(['MKT-1', 'MKT-2', 'MKT-3']);
+ });
+
+ it('parses non-closing words as references', () => {
+ const parsed = parseMagicWords('Related to MKT-7 and refs MKT-8');
+ expect(parsed.closes).toEqual([]);
+ expect(ids(parsed.references)).toEqual(['MKT-7', 'MKT-8']);
+ });
+
+ it('is case-insensitive and uppercases the key', () => {
+ const parsed = parseMagicWords('FIXES mkt-9');
+ expect(ids(parsed.closes)).toEqual(['MKT-9']);
+ });
+
+ it('accepts an optional colon after the word', () => {
+ const parsed = parseMagicWords('Closes: MKT-4');
+ expect(ids(parsed.closes)).toEqual(['MKT-4']);
+ });
+
+ it('drops identifiers named by skip/ignore anywhere in the text', () => {
+ const parsed = parseMagicWords('Fixes MKT-1 and MKT-2.\n\nskip MKT-2');
+ expect(ids(parsed.closes)).toEqual(['MKT-1']);
+ });
+
+ it('counts an identifier as closing when both word kinds name it', () => {
+ const parsed = parseMagicWords('Refs MKT-5. Fixes MKT-5');
+ expect(ids(parsed.closes)).toEqual(['MKT-5']);
+ expect(parsed.references).toEqual([]);
+ });
+
+ it('ignores identifiers without a magic word', () => {
+ const parsed = parseMagicWords('See MKT-6 for context');
+ expect(parsed.closes).toEqual([]);
+ expect(parsed.references).toEqual([]);
+ });
+
+ it('ignores a magic word inside another word', () => {
+ const parsed = parseMagicWords('prefixes MKT-3');
+ expect(parsed.closes).toEqual([]);
+ });
+
+ it('handles multi-word phrases with flexible whitespace', () => {
+ const parsed = parseMagicWords('part of MKT-11');
+ expect(ids(parsed.references)).toEqual(['MKT-11']);
+ });
+
+ it('dedupes repeated identifiers', () => {
+ const parsed = parseMagicWords('Fixes MKT-1. Closes MKT-1');
+ expect(ids(parsed.closes)).toEqual(['MKT-1']);
+ });
+});
diff --git a/apps/api/src/github/handler.ts b/apps/api/src/github/handler.ts
new file mode 100644
index 00000000..7d57d3d8
--- /dev/null
+++ b/apps/api/src/github/handler.ts
@@ -0,0 +1,114 @@
+import { getIssueBySequence, updateIssue } from '../issues/store';
+import { recordActivity, type ActivityActor } from '../issues/activity';
+import { parseMagicWords, type IssueRef } from './magic-words';
+import { columnStateTypes, firstCompletedColumnId, type GithubSettings } from './store';
+
+// Applies a GitHub pull_request delivery to the project's issues:
+// - a PR merged into the repository's default branch moves the issues named by a
+// closing magic word to the configured (or first completed) column;
+// - a PR opened (non-draft) links every issue it mentions, and moves the ones
+// still in a backlog/unstarted column to the configured column, when one is set.
+// Every move goes through updateIssue, so the status activity entry, outgoing
+// webhooks, subtask automation, and notifications fire as for a user's move.
+
+const GITHUB_ACTOR: ActivityActor = { system: 'GitHub' };
+const CLOSED_STATE_TYPES = ['completed', 'canceled'];
+
+// The payload's PR URL is rendered as a link in the feed; only http(s) is stored
+// so a crafted delivery cannot plant a javascript: (or other scheme) href.
+function httpUrl(url: string): string | null {
+ try {
+ return ['http:', 'https:'].includes(new URL(url).protocol) ? url : null;
+ } catch {
+ return null;
+ }
+}
+
+// The slice of GitHub's pull_request event payload this handler reads.
+export interface PullRequestPayload {
+ action: string;
+ pull_request: {
+ number: number;
+ title: string;
+ body: string | null;
+ html_url: string;
+ merged: boolean;
+ draft: boolean;
+ base: { ref: string };
+ };
+ repository: { full_name: string; default_branch: string };
+}
+
+export type PullRequestOutcome = 'merged' | 'opened' | 'ignored';
+
+export async function handlePullRequestEvent(
+ project: { id: number; key: string },
+ settings: GithubSettings,
+ payload: PullRequestPayload,
+): Promise<PullRequestOutcome> {
+ const pr = payload.pull_request;
+ const parsed = parseMagicWords(`${pr.title}\n${pr.body ?? ''}`);
+ const projectKey = project.key.toUpperCase();
+ const inProject = (refs: IssueRef[]) => refs.filter((r) => r.key === projectKey);
+ const prEntry = (subject: string) => ({
+ action: 'github_pr',
+ subject,
+ fromText: `${payload.repository.full_name}#${pr.number}`,
+ toText: httpUrl(pr.html_url),
+ });
+
+ if (payload.action === 'closed' && pr.merged) {
+ if (pr.base.ref !== payload.repository.default_branch) return 'ignored';
+ const targetId = await mergeTargetColumnId(project.id, settings);
+ if (targetId == null) return 'ignored';
+ for (const ref of inProject(parsed.closes)) {
+ const issue = await getIssueBySequence(project.id, ref.sequenceNumber);
+ if (!issue || issue.archivedAt) continue;
+ const stateType = (await columnStateTypes([issue.columnId])).get(issue.columnId);
+ if (stateType && CLOSED_STATE_TYPES.includes(stateType)) continue;
+ await recordActivity(issue.id, [prEntry('merged')], GITHUB_ACTOR);
+ await updateIssue(issue.id, { columnId: targetId }, GITHUB_ACTOR);
+ }
+ return 'merged';
+ }
+
+ if (payload.action === 'opened' && !pr.draft) {
+ const targetId = await openTargetColumnId(settings);
+ for (const ref of inProject([...parsed.closes, ...parsed.references])) {
+ const issue = await getIssueBySequence(project.id, ref.sequenceNumber);
+ if (!issue || issue.archivedAt) continue;
+ await recordActivity(issue.id, [prEntry('opened')], GITHUB_ACTOR);
+ if (targetId == null || issue.columnId === targetId) continue;
+ const stateType = (await columnStateTypes([issue.columnId])).get(issue.columnId);
+ // Only pull work forward: an issue already started or closed stays put.
+ // The guard makes that atomic — a user moving the issue between this read
+ // and the write wins over the automation.
+ if (stateType === 'backlog' || stateType === 'unstarted')
+ await updateIssue(issue.id, { columnId: targetId }, GITHUB_ACTOR, {
+ onlyIfColumnId: issue.columnId,
+ });
+ }
+ return 'opened';
+ }
+
+ return 'ignored';
+}
+
+// The configured merge target if it still exists, else the first completed column.
+async function mergeTargetColumnId(
+ projectId: number,
+ settings: GithubSettings,
+): Promise<number | null> {
+ const configured = settings.onMergeColumnId;
+ if (configured != null && (await columnStateTypes([configured])).has(configured))
+ return configured;
+ return firstCompletedColumnId(projectId);
+}
+
+// The configured open target if it still exists; null means the automation is off.
+async function openTargetColumnId(settings: GithubSettings): Promise<number | null> {
+ const configured = settings.onOpenColumnId;
+ if (configured != null && (await columnStateTypes([configured])).has(configured))
+ return configured;
+ return null;
+}
diff --git a/apps/api/src/github/magic-words.ts b/apps/api/src/github/magic-words.ts
new file mode 100644
index 00000000..58392569
--- /dev/null
+++ b/apps/api/src/github/magic-words.ts
@@ -0,0 +1,104 @@
+// The magic-word grammar for linking pull requests to issues, copying Linear's:
+// a magic word followed by one or more issue identifiers ("Fixes MKT-42",
+// "Closes MKT-1, MKT-2 and MKT-3"). Closing words move the issue to the closed
+// state when the PR merges; non-closing words only link. "skip"/"ignore" before
+// an identifier suppresses both for that identifier anywhere in the text.
+
+const CLOSING_WORDS = [
+ 'close',
+ 'closes',
+ 'closed',
+ 'closing',
+ 'fix',
+ 'fixes',
+ 'fixed',
+ 'fixing',
+ 'resolve',
+ 'resolves',
+ 'resolved',
+ 'resolving',
+ 'complete',
+ 'completes',
+ 'completed',
+ 'completing',
+ 'implement',
+ 'implements',
+ 'implemented',
+ 'implementing',
+];
+
+const NON_CLOSING_WORDS = [
+ 'ref',
+ 'refs',
+ 'references',
+ 'part of',
+ 'related to',
+ 'relates to',
+ 'contributes to',
+ 'toward',
+ 'towards',
+];
+
+const SKIP_WORDS = ['skip', 'ignore'];
+
+export interface IssueRef {
+ key: string;
+ sequenceNumber: number;
+}
+
+export interface ParsedMagicWords {
+ // Identifiers named by a closing word — closed when the PR merges.
+ closes: IssueRef[];
+ // Identifiers named by a non-closing word — linked but never closed.
+ references: IssueRef[];
+}
+
+const IDENTIFIER = String.raw`[A-Za-z][A-Za-z0-9]*-\d+`;
+// One or more identifiers after a magic word, separated by commas and/or "and".
+const IDENTIFIER_LIST = String.raw`${IDENTIFIER}(?:\s*(?:,|and|,\s*and)\s+${IDENTIFIER})*`;
+
+// Longest phrase first, so "relates to" wins over a hypothetical "relates".
+const ALL_WORDS = [...SKIP_WORDS, ...CLOSING_WORDS, ...NON_CLOSING_WORDS].sort(
+ (a, b) => b.length - a.length,
+);
+const MAGIC_RE = new RegExp(
+ String.raw`(?<=^|[^A-Za-z0-9])(${ALL_WORDS.join('|').replace(/ /g, String.raw`\s+`)})\s*:?\s+(${IDENTIFIER_LIST})(?![A-Za-z0-9-])`,
+ 'gi',
+);
+const IDENTIFIER_RE = new RegExp(IDENTIFIER, 'g');
+
+function toRef(identifier: string): IssueRef {
+ const dash = identifier.lastIndexOf('-');
+ return {
+ key: identifier.slice(0, dash).toUpperCase(),
+ sequenceNumber: Number(identifier.slice(dash + 1)),
+ };
+}
+
+const refId = (ref: IssueRef) => `${ref.key}-${ref.sequenceNumber}`;
+
+// Parses PR title + description text. An identifier under a skip word never
+// appears in the result; one named by both a closing and a non-closing word
+// counts as closing.
+export function parseMagicWords(text: string): ParsedMagicWords {
+ const closes = new Map<string, IssueRef>();
+ const references = new Map<string, IssueRef>();
+ const skipped = new Set<string>();
+
+ for (const match of text.matchAll(MAGIC_RE)) {
+ const word = match[1].toLowerCase().replace(/\s+/g, ' ');
+ const refs = (match[2].match(IDENTIFIER_RE) ?? []).map(toRef);
+ for (const ref of refs) {
+ if (SKIP_WORDS.includes(word)) skipped.add(refId(ref));
+ else if (CLOSING_WORDS.includes(word)) closes.set(refId(ref), ref);
+ else references.set(refId(ref), ref);
+ }
+ }
+
+ for (const id of skipped) {
+ closes.delete(id);
+ references.delete(id);
+ }
+ for (const id of closes.keys()) references.delete(id);
+ return { closes: [...closes.values()], references: [...references.values()] };
+}
diff --git a/apps/api/src/github/routes.ts b/apps/api/src/github/routes.ts
new file mode 100644
index 00000000..6f46bce6
--- /dev/null
+++ b/apps/api/src/github/routes.ts
@@ -0,0 +1,138 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+import { Elysia, t } from 'elysia';
+import { guards } from '../shared/guards';
+import { authContext } from '../shared/auth-context';
+import { checkPermission } from '../shared/access';
+import { HttpError } from '../shared/lib';
+import { getProjectById } from '../projects/store';
+import { handlePullRequestEvent, type PullRequestPayload } from './handler';
+import {
+ claimGithubDelivery,
+ findProjectByGithubWebhookId,
+ getOrCreateGithubSettings,
+ recordGithubEvent,
+ regenerateGithubSecret,
+ updateGithubSettings,
+} from './store';
+
+// GitHub's HMAC over the raw request body, sent as "sha256=<hex>".
+function signatureValid(secret: string, rawBody: string, header: string | undefined): boolean {
+ if (!header?.startsWith('sha256=')) return false;
+ const given = Buffer.from(header.slice('sha256='.length), 'hex');
+ const expected = createHmac('sha256', secret).update(rawBody).digest();
+ return given.length === expected.length && timingSafeEqual(given, expected);
+}
+
+// Inbound webhook receiver. Unauthenticated (GitHub carries no session) and
+// mounted on the root app: the per-project secret verified against
+// X-Hub-Signature-256 is the authentication. The body is parsed as text so the
+// signature is computed over the exact bytes GitHub signed.
+export const githubWebhookRoutes = new Elysia({
+ name: 'github-webhook',
+ detail: { tags: ['GitHub'] },
+}).post(
+ '/webhooks/github/:webhookId',
+ async ({ params, body, headers }) => {
+ const found = await findProjectByGithubWebhookId(params.webhookId);
+ if (!found) throw new HttpError(404, 'Unknown webhook');
+ if (!signatureValid(found.settings.secret, body, headers['x-hub-signature-256']))
+ throw new HttpError(401, 'Invalid signature');
+
+ let payload: unknown;
+ try {
+ payload = JSON.parse(body);
+ } catch {
+ throw new HttpError(400, 'Invalid JSON payload');
+ }
+ const repo = (payload as { repository?: { full_name?: string } }).repository?.full_name;
+ if (repo) await recordGithubEvent(found.projectId, repo);
+
+ const event = headers['x-github-event'];
+ if (event !== 'pull_request') return { ok: true, handled: 'ignored' };
+ if (!found.settings.enabled) return { ok: true, handled: 'disabled' };
+ // GitHub sends a unique GUID per delivery and reuses it on redelivery; a
+ // GUID seen before means a replay, which must not repeat its side effects.
+ const deliveryId = headers['x-github-delivery'];
+ if (deliveryId && !(await claimGithubDelivery(found.projectId, deliveryId)))
+ return { ok: true, handled: 'duplicate' };
+ const project = await getProjectById(found.projectId);
+ if (!project) throw new HttpError(404, 'Unknown webhook');
+ const handled = await handlePullRequestEvent(
+ project,
+ found.settings,
+ payload as PullRequestPayload,
+ );
+ return { ok: true, handled };
+ },
+ {
+ parse: 'text',
+ body: t.String(),
+ params: t.Object({ webhookId: t.String() }),
+ response: {
+ 200: t.Object({ ok: t.Boolean(), handled: t.String() }),
+ },
+ detail: {
+ summary: 'Receive a GitHub webhook',
+ description:
+ 'Receive a repository webhook delivery, verify its X-Hub-Signature-256, and apply ' +
+ 'the pull request automations to the issues its magic words name.',
+ },
+ },
+);
+
+// The GitHub settings DTO (GithubSettings from the store). Unlike outgoing
+// webhook secrets, this secret authorizes issue moves through the receiver, so
+// it is shown only to members with integrations edit access; read-only callers
+// get null.
+const GithubSettingsResponse = t.Object({
+ enabled: t.Boolean(),
+ webhookId: t.String(),
+ secret: t.Nullable(t.String()),
+ onMergeColumnId: t.Nullable(t.Number()),
+ onOpenColumnId: t.Nullable(t.Number()),
+ lastEventAt: t.Nullable(t.String()),
+ lastEventRepo: t.Nullable(t.String()),
+});
+
+export const githubSettingsRoutes = new Elysia({
+ name: 'github-settings',
+ detail: { tags: ['GitHub'] },
+})
+ .use(authContext)
+ .use(guards)
+ .get(
+ '/projects/:projectKey/settings/github',
+ async ({ project, user }) => {
+ const settings = await getOrCreateGithubSettings(project.id);
+ const canEdit = await checkPermission(project.id, user, 'integrations', 'edit');
+ return { ...settings, secret: canEdit ? settings.secret : null };
+ },
+ {
+ permission: ['integrations', 'read'],
+ response: { 200: GithubSettingsResponse },
+ detail: { summary: "Get a project's GitHub integration settings" },
+ },
+ )
+ .patch(
+ '/projects/:projectKey/settings/github',
+ ({ project, body }) => updateGithubSettings(project.id, body),
+ {
+ permission: ['integrations', 'edit'],
+ body: t.Object({
+ enabled: t.Optional(t.Boolean()),
+ onMergeColumnId: t.Optional(t.Nullable(t.Number())),
+ onOpenColumnId: t.Optional(t.Nullable(t.Number())),
+ }),
+ response: { 200: GithubSettingsResponse },
+ detail: { summary: "Update a project's GitHub integration settings" },
+ },
+ )
+ .post(
+ '/projects/:projectKey/settings/github/secret',
+ ({ project }) => regenerateGithubSecret(project.id),
+ {
+ permission: ['integrations', 'edit'],
+ response: { 200: GithubSettingsResponse },
+ detail: { summary: "Regenerate a project's GitHub webhook secret" },
+ },
+ );
diff --git a/apps/api/src/github/store.ts b/apps/api/src/github/store.ts
new file mode 100644
index 00000000..b954c769
--- /dev/null
+++ b/apps/api/src/github/store.ts
@@ -0,0 +1,213 @@
+import { randomBytes } from 'node:crypto';
+import { db, projectColumn, projectSetting } from '@repo/db';
+import { and, asc, eq, inArray, sql } from 'drizzle-orm';
+import { decryptSecret, encryptSecret, type EncryptedSecret } from '@repo/crypto';
+import { HttpError } from '../shared/lib';
+import { getProjectSetting } from '../settings/store';
+
+// The GitHub integration config for a project, stored in project_setting under
+// GITHUB_SETTING_KEY. `webhookId` routes an incoming delivery to the project (it is the
+// unguessable path segment of the payload URL); `secret` signs deliveries
+// (X-Hub-Signature-256) and is encrypted at rest. `onMergeColumnId` is the column
+// a closed issue moves to when a linked PR merges (null = the project's first
+// completed column); `onOpenColumnId` is where an issue moves when a linked PR is
+// opened (null = no action). lastEventAt/lastEventRepo show the settings page
+// that deliveries arrive.
+
+// Exported for the project copier, which must not clone this setting: the copy
+// would carry the source's secret and webhook id (a credential disclosure to the
+// copy's owner, and ambiguous inbound routing).
+export const GITHUB_SETTING_KEY = 'github';
+
+interface StoredGithubSettings {
+ enabled: boolean;
+ webhookId: string;
+ secret: EncryptedSecret;
+ onMergeColumnId: number | null;
+ onOpenColumnId: number | null;
+ lastEventAt: string | null;
+ lastEventRepo: string | null;
+ // Ring buffer of the last processed X-GitHub-Delivery GUIDs (newest last,
+ // capped at RECENT_DELIVERIES_CAP). Written only by claimGithubDelivery.
+ recentDeliveries?: string[];
+}
+
+export interface GithubSettings {
+ enabled: boolean;
+ webhookId: string;
+ secret: string;
+ onMergeColumnId: number | null;
+ onOpenColumnId: number | null;
+ lastEventAt: string | null;
+ lastEventRepo: string | null;
+}
+
+function toDto(stored: StoredGithubSettings): GithubSettings {
+ const { recentDeliveries: _internal, ...rest } = stored;
+ return { ...rest, secret: decryptSecret(stored.secret) };
+}
+
+// Reads the project's GitHub settings, creating a disabled config with a fresh
+// webhook id and secret on first read — the settings page needs both to show
+// before the user has saved anything.
+export async function getOrCreateGithubSettings(projectId: number): Promise<GithubSettings> {
+ const stored = await getProjectSetting<StoredGithubSettings>(projectId, GITHUB_SETTING_KEY);
+ if (stored) return toDto(stored);
+ const fresh: StoredGithubSettings = {
+ enabled: false,
+ webhookId: randomBytes(16).toString('hex'),
+ secret: encryptSecret(`ghs_${randomBytes(24).toString('hex')}`),
+ onMergeColumnId: null,
+ onOpenColumnId: null,
+ lastEventAt: null,
+ lastEventRepo: null,
+ };
+ // Concurrent first reads race to insert; the loser keeps the winner's row so
+ // both callers return the credentials that are actually stored.
+ await db
+ .insert(projectSetting)
+ .values({ projectId, key: GITHUB_SETTING_KEY, value: fresh })
+ .onConflictDoNothing();
+ const winner = await getProjectSetting<StoredGithubSettings>(projectId, GITHUB_SETTING_KEY);
+ return toDto(winner ?? fresh);
+}
+
+// Merges the given fields into the stored jsonb in one UPDATE, so concurrent
+// writers (a settings edit, a secret rotation, a delivery stamping telemetry)
+// can never clobber each other's fields with a stale read.
+async function mergeGithubSettings(
+ projectId: number,
+ fields: Partial<StoredGithubSettings>,
+): Promise<void> {
+ await db
+ .update(projectSetting)
+ .set({
+ value: sql`${projectSetting.value} || ${JSON.stringify(fields)}::jsonb`,
+ updatedAt: sql`now()`,
+ })
+ .where(
+ and(eq(projectSetting.projectId, projectId), eq(projectSetting.key, GITHUB_SETTING_KEY)),
+ );
+}
+
+export async function updateGithubSettings(
+ projectId: number,
+ patch: { enabled?: boolean; onMergeColumnId?: number | null; onOpenColumnId?: number | null },
+): Promise<GithubSettings> {
+ await assertProjectColumn(projectId, patch.onMergeColumnId);
+ await assertProjectColumn(projectId, patch.onOpenColumnId);
+ await getOrCreateGithubSettings(projectId);
+ const fields: Partial<StoredGithubSettings> = {};
+ if (patch.enabled !== undefined) fields.enabled = patch.enabled;
+ if (patch.onMergeColumnId !== undefined) fields.onMergeColumnId = patch.onMergeColumnId;
+ if (patch.onOpenColumnId !== undefined) fields.onOpenColumnId = patch.onOpenColumnId;
+ if (Object.keys(fields).length > 0) await mergeGithubSettings(projectId, fields);
+ return getOrCreateGithubSettings(projectId);
+}
+
+export async function regenerateGithubSecret(projectId: number): Promise<GithubSettings> {
+ await getOrCreateGithubSettings(projectId);
+ await mergeGithubSettings(projectId, {
+ secret: encryptSecret(`ghs_${randomBytes(24).toString('hex')}`),
+ });
+ return getOrCreateGithubSettings(projectId);
+}
+
+// Resolves an incoming delivery's webhook id to its project. The id is stored
+// inside the jsonb value, so this scans the 'github' settings rows by expression.
+export async function findProjectByGithubWebhookId(
+ webhookId: string,
+): Promise<{ projectId: number; settings: GithubSettings } | null> {
+ const rows = await db
+ .select({ projectId: projectSetting.projectId, value: projectSetting.value })
+ .from(projectSetting)
+ .where(
+ and(
+ eq(projectSetting.key, GITHUB_SETTING_KEY),
+ sql`${projectSetting.value}->>'webhookId' = ${webhookId}`,
+ ),
+ );
+ if (!rows[0]) return null;
+ return { projectId: rows[0].projectId, settings: toDto(rows[0].value as StoredGithubSettings) };
+}
+
+// How many processed delivery GUIDs the ring buffer keeps. GitHub retries and
+// manual redeliveries arrive close to the original, so a small window is
+// enough; a replay also requires a validly signed body.
+const RECENT_DELIVERIES_CAP = 50;
+
+// Claims an X-GitHub-Delivery GUID for processing by appending it to the
+// recentDeliveries ring buffer. Returns false when the GUID is already in the
+// buffer (a replay or a GitHub redelivery), in which case the caller must not
+// act on it again. Check and append are one UPDATE, so two concurrent claims of
+// the same GUID cannot both win.
+export async function claimGithubDelivery(projectId: number, deliveryId: string): Promise<boolean> {
+ const recent = sql`COALESCE(${projectSetting.value}->'recentDeliveries', '[]'::jsonb)`;
+ const claimed = await db
+ .update(projectSetting)
+ .set({
+ value: sql`jsonb_set(${projectSetting.value}, '{recentDeliveries}', (
+ SELECT COALESCE(jsonb_agg(elem ORDER BY ord), '[]'::jsonb)
+ FROM (
+ SELECT elem, ord
+ FROM jsonb_array_elements(${recent} || to_jsonb(${deliveryId}::text)) WITH ORDINALITY AS t(elem, ord)
+ ORDER BY ord DESC
+ LIMIT ${RECENT_DELIVERIES_CAP}
+ ) latest
+ ))`,
+ updatedAt: sql`now()`,
+ })
+ .where(
+ and(
+ eq(projectSetting.projectId, projectId),
+ eq(projectSetting.key, GITHUB_SETTING_KEY),
+ sql`NOT (${recent} ? ${deliveryId}::text)`,
+ ),
+ )
+ .returning({ projectId: projectSetting.projectId });
+ return claimed.length > 0;
+}
+
+// Stamps the settings with the delivery that just arrived. Touches only the two
+// telemetry fields, so a delivery can never revert a concurrent settings edit.
+export async function recordGithubEvent(projectId: number, repo: string): Promise<void> {
+ await mergeGithubSettings(projectId, {
+ lastEventAt: new Date().toISOString(),
+ lastEventRepo: repo,
+ });
+}
+
+async function assertProjectColumn(
+ projectId: number,
+ columnId: number | null | undefined,
+): Promise<void> {
+ if (columnId == null) return;
+ const rows = await db
+ .select({ id: projectColumn.id })
+ .from(projectColumn)
+ .where(and(eq(projectColumn.id, columnId), eq(projectColumn.projectId, projectId)));
+ if (!rows[0]) throw new HttpError(400, 'Unknown column');
+}
+
+// The project's first completed-type column — the default close target.
+export async function firstCompletedColumnId(projectId: number): Promise<number | null> {
+ const rows = await db
+ .select({ id: projectColumn.id })
+ .from(projectColumn)
+ .where(and(eq(projectColumn.projectId, projectId), eq(projectColumn.stateType, 'completed')))
+ .orderBy(asc(projectColumn.position))
+ .limit(1);
+ return rows[0]?.id ?? null;
+}
+
+// The stateType of each existing column among the given ids. A deleted column is
+// simply absent, which is how callers detect a stale configured target.
+export async function columnStateTypes(columnIds: number[]): Promise<Map<number, string>> {
+ const ids = [...new Set(columnIds)];
+ if (ids.length === 0) return new Map();
+ const rows = await db
+ .select({ id: projectColumn.id, stateType: projectColumn.stateType })
+ .from(projectColumn)
+ .where(inArray(projectColumn.id, ids));
+ return new Map(rows.map((r) => [r.id, r.stateType]));
+}
diff --git a/apps/api/src/issues/activity.ts b/apps/api/src/issues/activity.ts
index f3de283b..db09098d 100644
--- a/apps/api/src/issues/activity.ts
+++ b/apps/api/src/issues/activity.ts
@@ -330,21 +330,30 @@ export interface ActivityInput {
toText?: string | null;
}
+// The actor behind a write: the session user's id (a member or an agent's bot
+// user), null/undefined for an anonymous system write, or a named system actor
+// ({ system: 'GitHub' }) whose name is stored as the entry's actor_name without a
+// user behind it.
+export type ActivityActor = string | null | undefined | { system: string };
+
+// The user id of an actor, or null when it is a system write.
+export function actorId(actor: ActivityActor): string | null {
+ return typeof actor === 'string' ? actor : null;
+}
+
// What a write runs on: the pool, or the transaction the caller is inside.
type Executor = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];
-// Records the given events for an issue. actorUserId is the session user behind
-// the write (a member or an agent's bot user); it is null for a system write with
-// no user. actor_name is snapshotted from that user so the entry survives the user
-// being renamed or deleted.
+// Records the given events for an issue. actor_name is snapshotted from the actor
+// so the entry survives the user being renamed or deleted.
export async function recordActivity(
issueId: number,
events: ActivityInput[],
- actorUserId?: string | null,
+ actor?: ActivityActor,
): Promise<{ id: number; action: string | null }[]> {
return recordActivityEntries(
events.map((event) => ({ issueId, event })),
- actorUserId,
+ actor,
);
}
@@ -354,11 +363,11 @@ export async function recordActivity(
export async function recordActivityForIssues(
issueIds: number[],
event: ActivityInput,
- actorUserId?: string | null,
+ actor?: ActivityActor,
): Promise<void> {
await recordActivityEntries(
issueIds.map((issueId) => ({ issueId, event })),
- actorUserId,
+ actor,
);
}
@@ -368,14 +377,19 @@ export async function recordActivityForIssues(
// transaction. The actor name snapshot is a sub-select, so this stays one query.
export async function recordActivityEntries(
entries: { issueId: number; event: ActivityInput }[],
- actorUserId?: string | null,
+ actor?: ActivityActor,
on: Executor = db,
): Promise<{ id: number; action: string | null }[]> {
if (!entries.length) return [];
- const resolvedActorId = actorUserId ?? null;
- const actorName = resolvedActorId
- ? sql<string | null>`(select ${user.name} from ${user} where ${user.id} = ${resolvedActorId})`
- : null;
+ const resolvedActorId = actorId(actor);
+ const actorName =
+ actor && typeof actor === 'object'
+ ? actor.system
+ : resolvedActorId
+ ? sql<
+ string | null
+ >`(select ${user.name} from ${user} where ${user.id} = ${resolvedActorId})`
+ : null;
return on
.insert(issueActivity)
.values(
@@ -467,7 +481,7 @@ export interface IssueSnapshot {
export async function logIssueUpdate(
before: IssueSnapshot,
after: IssueSnapshot,
- actorUserId?: string | null,
+ actor?: ActivityActor,
): Promise<void> {
const events: ActivityInput[] = [];
if (before.title !== after.title)
@@ -516,7 +530,7 @@ export async function logIssueUpdate(
events.push({ action: 'start_date', fromText: before.startDate, toText: after.startDate });
if (before.dueDate !== after.dueDate)
events.push({ action: 'due_date', fromText: before.dueDate, toText: after.dueDate });
- const inserted = await recordActivity(after.id, events, actorUserId);
+ const inserted = await recordActivity(after.id, events, actor);
// Inbox notifications for the two events with a dedicated notification type: a new
// assignee, and a status change. Both link back to their activity row.
@@ -532,7 +546,7 @@ export async function logIssueUpdate(
await notifyIssueChange({
projectId: row.projectId,
issueId: after.id,
- actorUserId: actorUserId ?? null,
+ actorUserId: actorId(actor),
assignedUserId: assigneeChanged ? after.assigneeUserId : null,
assignedActivityId: idByAction.get('assignee') ?? null,
statusChanged,
diff --git a/apps/api/src/issues/automation.ts b/apps/api/src/issues/automation.ts
index d7f9a26d..27ae4124 100644
--- a/apps/api/src/issues/automation.ts
+++ b/apps/api/src/issues/automation.ts
@@ -3,6 +3,7 @@ import { and, eq, inArray, isNull } from 'drizzle-orm';
import { getSubtaskAutomationSettings } from '../projects/store';
import { listSubtasks } from './subtasks';
import { updateIssue, type IssueRow } from './store';
+import type { ActivityActor } from './activity';
// The subtask automations a column change triggers, both off unless the project
// turns them on (projects/store.ts). A closed issue is one sitting in a column
@@ -18,7 +19,7 @@ const CLOSED_STATE_TYPES = ['completed', 'canceled'];
export async function applySubtaskAutomation(
after: IssueRow,
- actorUserId?: string | null,
+ actorUserId?: ActivityActor,
): Promise<void> {
const settings = await getSubtaskAutomationSettings(after.projectId);
if (!settings.completeParent && !settings.closeSubtasks) return;
@@ -38,7 +39,7 @@ export async function applySubtaskAutomation(
async function completeParent(
parentId: number,
subtask: IssueRow,
- actorUserId?: string | null,
+ actorUserId?: ActivityActor,
): Promise<void> {
const siblingColumnIds = (await listSubtasks(parentId))
.filter((s) => !s.archived && s.id !== subtask.id)
@@ -52,7 +53,7 @@ async function completeParent(
}
// Moves the issue's still-open subtasks into the column it was just closed in.
-async function closeSubtasks(parent: IssueRow, actorUserId?: string | null): Promise<void> {
+async function closeSubtasks(parent: IssueRow, actorUserId?: ActivityActor): Promise<void> {
const subtasks = (await listSubtasks(parent.id)).filter((s) => !s.archived);
const closed = await closedColumnIds(subtasks.map((s) => s.columnId));
for (const subtask of subtasks)
diff --git a/apps/api/src/issues/store.ts b/apps/api/src/issues/store.ts
index 0830efcd..698a4955 100644
--- a/apps/api/src/issues/store.ts
+++ b/apps/api/src/issues/store.ts
@@ -39,6 +39,8 @@ import {
recordActivityEntries,
logIssueUpdate,
labelNames,
+ actorId,
+ type ActivityActor,
type ActivityInput,
type IssueSnapshot,
} from './activity';
@@ -865,7 +867,7 @@ async function recordParentChange(
childId: number,
before: number | null,
after: number | null,
- actorUserId?: string | null,
+ actor?: ActivityActor,
): Promise<void> {
const names = await identifiers(
[childId, before, after].filter((id): id is number => id !== null),
@@ -885,7 +887,7 @@ async function recordParentChange(
entries.push({ issueId: before, event: { action: 'subtask_remove', fromText: child } });
if (after !== null)
entries.push({ issueId: after, event: { action: 'subtask_add', toText: child } });
- await recordActivityEntries(entries, actorUserId);
+ await recordActivityEntries(entries, actor);
}
export interface IssuePatch {
@@ -904,10 +906,15 @@ export interface IssuePatch {
dueDate?: string | null;
}
+// opts.onlyIfColumnId makes the write conditional: it applies only while the
+// issue still sits in that column, so an automation acting on a state it read
+// earlier cannot overwrite a concurrent move. A failed guard writes nothing and
+// returns the current row.
export async function updateIssue(
id: number,
patch: IssuePatch,
- actorUserId?: string | null,
+ actor?: ActivityActor,
+ opts?: { onlyIfColumnId?: number },
): Promise<IssueRow | null> {
const before = await loadSnapshot(id);
if (!before) return null;
@@ -937,23 +944,27 @@ export async function updateIssue(
const changed = Object.keys(set).length > 0;
if (changed) {
set.updatedAt = sql`now()` as unknown as Date;
- await db.update(issue).set(set).where(eq(issue.id, id));
+ const guard =
+ opts?.onlyIfColumnId == null
+ ? eq(issue.id, id)
+ : and(eq(issue.id, id), eq(issue.columnId, opts.onlyIfColumnId));
+ const updated = await db.update(issue).set(set).where(guard).returning({ id: issue.id });
+ if (updated.length === 0) return getIssue(id);
}
const after = await getIssue(id);
if (after) {
- await logIssueUpdate(before, snapshot(after), actorUserId);
+ await logIssueUpdate(before, snapshot(after), actor);
if (before.parentId !== after.parentId)
- await recordParentChange(id, before.parentId, after.parentId, actorUserId);
+ await recordParentChange(id, before.parentId, after.parentId, actor);
if (changed) {
await emitWebhookEvent(after.projectId, 'issue.updated', after);
// Granular events fire in addition to issue.updated when their field changed.
if (before.assigneeUserId !== after.assigneeUserId)
await emitWebhookEvent(after.projectId, 'issue.assigned', after);
- if (before.delegateUserId !== after.delegateUserId)
- await enqueueDelegateRun(after, actorUserId);
+ if (before.delegateUserId !== after.delegateUserId) await enqueueDelegateRun(after, actor);
if (before.columnId !== after.columnId) {
await emitWebhookEvent(after.projectId, 'issue.state_changed', after);
- await applySubtaskAutomation(after, actorUserId);
+ await applySubtaskAutomation(after, actor);
}
}
}
@@ -964,9 +975,9 @@ export async function updateIssue(
// run so it can act on the issue. Skipped when the agent delegated to itself (an
// agent setting itself off). The LLM call happens later in the poller, so the write
// is never blocked on it.
-async function enqueueDelegateRun(after: IssueRow, actorUserId?: string | null): Promise<void> {
+async function enqueueDelegateRun(after: IssueRow, actor?: ActivityActor): Promise<void> {
const delegate = after.delegateUserId;
- if (!delegate || delegate === actorUserId) return;
+ if (!delegate || delegate === actorId(actor)) return;
const agent = await getAssignTriggerAgent(delegate);
if (!agent) return;
await enqueueAgentRun({
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index 70bb6002..cf6e8d40 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -22,6 +22,7 @@ import { viewRoutes } from './views/routes';
import { shareRoutes } from './share/routes';
import { actionRoutes } from './actions/routes';
import { webhookRoutes } from './webhooks/routes';
+import { githubSettingsRoutes } from './github/routes';
import { dashboardRoutes } from './dashboards/routes';
import { noteBoardRoutes } from './note-boards/routes';
import { analyticsRoutes } from './analytics/routes';
@@ -93,6 +94,7 @@ export const planner = new Elysia({ name: 'planner' })
.use(shareRoutes)
.use(actionRoutes)
.use(webhookRoutes)
+ .use(githubSettingsRoutes)
.use(agentScheduleRoutes)
.use(dashboardRoutes)
.use(noteBoardRoutes)
diff --git a/apps/api/src/projects/copy.ts b/apps/api/src/projects/copy.ts
index 2b5bfd0e..fa01df67 100644
--- a/apps/api/src/projects/copy.ts
+++ b/apps/api/src/projects/copy.ts
@@ -22,6 +22,7 @@ import { eq, inArray } from 'drizzle-orm';
import { iso } from '../shared/lib';
import { defaultMemberPermissions } from '../shared/permissions';
import { DEFAULT_COLUMNS, type ProjectRow } from './store';
+import { GITHUB_SETTING_KEY } from '../github/store';
import { listAgents, createAgent, type NewAgentInput } from '../ai-agents/store';
import {
listSkills,
@@ -527,13 +528,18 @@ export async function copyProject(
// Project settings key/value rows (the Configuration section's subtask
// automations and auto-archive thresholds, and any other project-scoped
- // setting). Copied verbatim.
+ // setting). Copied verbatim, except the GitHub integration: its value holds
+ // the webhook secret and routing id (the copy's owner must not receive the
+ // source's credential, and a duplicated id would make inbound routing
+ // ambiguous) plus column ids of the source project. The copy starts
+ // unconfigured instead.
if (inc.configuration) {
const settingRows = await tx
.select()
.from(projectSetting)
.where(eq(projectSetting.projectId, sourceProjectId));
for (const s of settingRows) {
+ if (s.key === GITHUB_SETTING_KEY) continue;
await tx.insert(projectSetting).values({ projectId: proj.id, key: s.key, value: s.value });
}
}
diff --git a/apps/api/src/shared/access.ts b/apps/api/src/shared/access.ts
index d9cfe111..5773882a 100644
--- a/apps/api/src/shared/access.ts
+++ b/apps/api/src/shared/access.ts
@@ -103,6 +103,21 @@ export async function assertPermission(
}
}
+// Whether the user may perform the action, without throwing. For field-level
+// shaping inside a handler that is already access-gated (e.g. redacting a
+// secret for callers who may read but not edit).
+export async function checkPermission(
+ projectId: number,
+ user: AuthUser | undefined | null,
+ resource: PermissionResource,
+ action: PermissionAction,
+): Promise<boolean> {
+ if (!user) return false;
+ const ctx = await getMemberContext(projectId, user.id);
+ if (!ctx) return false;
+ return ctx.role === 'owner' || hasPermission(ctx.permissions, resource, action);
+}
+
// Resolves the :projectKey path param to a project and asserts the given
// permission in one step. Wrapped by the permission guard. Throws 404 for an
// unknown project and 403 when the permission is missing.
diff --git a/apps/web/src/app/project/[projectKey]/settings/github/page.tsx b/apps/web/src/app/project/[projectKey]/settings/github/page.tsx
new file mode 100644
index 00000000..753d66cf
--- /dev/null
+++ b/apps/web/src/app/project/[projectKey]/settings/github/page.tsx
@@ -0,0 +1,5 @@
+import SettingsGithubPage from '@/features/settings/SettingsGithubPage';
+
+export default function Page() {
+ return <SettingsGithubPage />;
+}
diff --git a/apps/web/src/features/issue/utils/activityText.tsx b/apps/web/src/features/issue/utils/activityText.tsx
index e9bddc04..68310f01 100644
--- a/apps/web/src/features/issue/utils/activityText.tsx
+++ b/apps/web/src/features/issue/utils/activityText.tsx
@@ -8,6 +8,7 @@ import {
CircleDot,
CirclePlus,
FileText,
+ GitPullRequest,
Link2,
ListChecks,
ListTree,
@@ -54,6 +55,7 @@ export const ACTION_ICON: Record<ActivityAction, LucideIcon> = {
field: Pencil,
archived: Archive,
restored: ArchiveRestore,
+ github_pr: GitPullRequest,
};
const fmtDate = (v: string | null) => (v ? formatDate(v) : '');
@@ -211,6 +213,25 @@ export function describeActivity(a: FeedItem): { line: ReactNode; popover?: stri
return { line: 'archived the issue' };
case 'restored':
return { line: 'restored the issue' };
+ case 'github_pr': {
+ // fromText is "owner/repo#42", toText the PR's URL on GitHub.
+ const pr = a.toText ? (
+ <a
+ href={a.toText}
+ target="_blank"
+ rel="noreferrer"
+ className="text-foreground/70 underline underline-offset-2 hover:text-foreground"
+ >
+ {a.fromText}
+ </a>
+ ) : (
+ strong(a.fromText)
+ );
+ return {
+ line:
+ a.subject === 'merged' ? <>merged pull request {pr}</> : <>opened pull request {pr}</>,
+ };
+ }
default:
return { line: a.action };
}
diff --git a/apps/web/src/features/settings/SettingsGithubPage.tsx b/apps/web/src/features/settings/SettingsGithubPage.tsx
new file mode 100644
index 00000000..97880b58
--- /dev/null
+++ b/apps/web/src/features/settings/SettingsGithubPage.tsx
@@ -0,0 +1,30 @@
+'use client';
+
+import { useShell } from '@/context/shellContext';
+import { settingsSection } from '@/utils/settingsSections';
+import SectionPageView from '@/components/common/page/SectionPageView';
+import RequirePermission from '@/components/common/permissions/RequirePermission';
+import { SettingsResourceProvider } from './context/settingsPermission';
+import SettingsGithub from './components/github/SettingsGithub';
+
+const section = settingsSection('github');
+
+// The GitHub settings page (/project/:projectKey/settings/github).
+export default function SettingsGithubPage() {
+ const { project } = useShell();
+ if (!project) return null;
+ return (
+ <SectionPageView
+ title={section.label}
+ description={section.description}
+ wide
+ widthClassName="min-w-[600px] max-w-[60%]"
+ >
+ <SettingsResourceProvider resource={section.resource}>
+ <RequirePermission resource={section.resource} action="read">
+ <SettingsGithub project={project} />
+ </RequirePermission>
+ </SettingsResourceProvider>
+ </SectionPageView>
+ );
+}
diff --git a/apps/web/src/features/settings/components/github/GithubAutomationsCard.tsx b/apps/web/src/features/settings/components/github/GithubAutomationsCard.tsx
new file mode 100644
index 00000000..85cc2a02
--- /dev/null
+++ b/apps/web/src/features/settings/components/github/GithubAutomationsCard.tsx
@@ -0,0 +1,60 @@
+import type { Column, GithubSettings } from '@/lib/api';
+import SettingsCard from '@/components/common/page/SettingsCard';
+import SettingsSection from '@/components/common/page/SettingsSection';
+import SettingsRow from '@/components/common/page/SettingsRow';
+import GithubColumnSelect from './GithubColumnSelect';
+
+// The pull request automations: which state a linked issue moves to when the PR
+// merges into the default branch, and (optionally) when it is opened.
+export default function GithubAutomationsCard({
+ columns,
+ settings,
+ editable,
+ onChange,
+}: {
+ columns: Column[];
+ settings: GithubSettings;
+ editable: boolean;
+ onChange: (patch: { onMergeColumnId?: number | null; onOpenColumnId?: number | null }) => void;
+}) {
+ return (
+ <SettingsSection
+ title="Pull request automations"
+ description={
+ 'Write a magic word and an issue ID in a pull request title or description, like ' +
+ '“Closes KEY-123”. Close, fix, resolve, complete, and implement close the issue when ' +
+ 'the PR merges. Ref, part of, and related to link it without closing. Write ' +
+ '“skip KEY-123” to leave an issue out.'
+ }
+ >
+ <SettingsCard className="divide-y divide-border/60">
+ <SettingsRow
+ title="When a linked PR is merged"
+ description="The issue moves to this state when the PR merges into the default branch."
+ control={
+ <GithubColumnSelect
+ columns={columns}
+ value={settings.onMergeColumnId}
+ noneLabel="First completed state"
+ readOnly={!editable}
+ onChange={(id) => onChange({ onMergeColumnId: id })}
+ />
+ }
+ />
+ <SettingsRow
+ title="When a linked PR is opened"
+ description="Only moves issues that haven't been started. Issues in progress or closed stay where they are."
+ control={
+ <GithubColumnSelect
+ columns={columns}
+ value={settings.onOpenColumnId}
+ noneLabel="No action"
+ readOnly={!editable}
+ onChange={(id) => onChange({ onOpenColumnId: id })}
+ />
+ }
+ />
+ </SettingsCard>
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/features/settings/components/github/GithubCliCommand.tsx b/apps/web/src/features/settings/components/github/GithubCliCommand.tsx
new file mode 100644
index 00000000..e8739e0e
--- /dev/null
+++ b/apps/web/src/features/settings/components/github/GithubCliCommand.tsx
@@ -0,0 +1,53 @@
+import { toast } from 'sonner';
+import { Button } from '@/components/ui/button';
+
+// A copyable `gh` command that registers the repository webhook in one step. The
+// payload URL and secret are already inlined; only <owner>/<repo> is left to
+// replace. The secret stays masked on screen (like the manual tab's field); only
+// the copied text carries the real value.
+export default function GithubCliCommand({
+ payloadUrl,
+ secret,
+}: {
+ payloadUrl: string;
+ secret: string;
+}) {
+ const command = (secretText: string) =>
+ [
+ 'gh api repos/<owner>/<repo>/hooks',
+ "-f name=web -F active=true -f 'events[]=pull_request'",
+ `-f 'config[url]=${payloadUrl}' -f 'config[content_type]=json' -f 'config[secret]=${secretText}'`,
+ ].join(' \\\n ');
+
+ async function copy() {
+ await navigator.clipboard.writeText(command(secret));
+ toast.success('Command copied. Replace <owner>/<repo>, then run it.');
+ }
+
+ return (
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between">
+ <p className="text-xs text-muted-foreground">
+ Requires the{' '}
+ <a
+ href="https://cli.github.com/"
+ target="_blank"
+ rel="noreferrer"
+ className="text-foreground/70 underline underline-offset-2 hover:text-foreground"
+ >
+ GitHub CLI
+ </a>
+ . Copy this command, replace{' '}
+ <code className="rounded bg-muted px-1 py-0.5">{'<owner>/<repo>'}</code> with your
+ repository, and run it in a terminal.
+ </p>
+ <Button variant="outline" size="sm" onClick={() => void copy()}>
+ Copy
+ </Button>
+ </div>
+ <pre className="overflow-x-auto rounded-md bg-muted px-3 py-2 font-mono text-xs whitespace-pre">
+ {command('•'.repeat(24) + secret.slice(-4))}
+ </pre>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/github/GithubColumnSelect.tsx b/apps/web/src/features/settings/components/github/GithubColumnSelect.tsx
new file mode 100644
index 00000000..8b5ef432
--- /dev/null
+++ b/apps/web/src/features/settings/components/github/GithubColumnSelect.tsx
@@ -0,0 +1,54 @@
+import { CircleDashed } from 'lucide-react';
+import type { Column } from '@/lib/api';
+import { colorDot } from '@/components/common/fields/colorDot';
+import { Pill } from '@/components/common/fields/Pill';
+import PopoverPick from '@/components/common/fields/PopoverPick';
+
+// A state select with a null option — the automation target where null means the
+// labelled default ("First completed state") or off ("No action").
+export default function GithubColumnSelect({
+ columns,
+ value,
+ noneLabel,
+ readOnly,
+ onChange,
+}: {
+ columns: Column[];
+ value: number | null;
+ noneLabel: string;
+ readOnly?: boolean;
+ onChange: (id: number | null) => void;
+}) {
+ const column = value == null ? undefined : columns.find((c) => c.id === value);
+ return (
+ <PopoverPick
+ readOnly={readOnly}
+ trigger={
+ <Pill active={column != null}>
+ {column ? colorDot(column.color) : <CircleDashed />}
+ <span className="whitespace-nowrap">{column?.name ?? noneLabel}</span>
+ </Pill>
+ }
+ inputPlaceholder="Change state…"
+ emptyText="No state."
+ items={[
+ {
+ key: 'none',
+ search: noneLabel,
+ icon: <CircleDashed />,
+ label: noneLabel,
+ selected: value == null,
+ onSelect: () => onChange(null),
+ },
+ ...columns.map((c) => ({
+ key: String(c.id),
+ search: c.name,
+ icon: colorDot(c.color),
+ label: c.name,
+ selected: c.id === value,
+ onSelect: () => onChange(c.id),
+ })),
+ ]}
+ />
+ );
+}
diff --git a/apps/web/src/features/settings/components/github/GithubConnectionCard.tsx b/apps/web/src/features/settings/components/github/GithubConnectionCard.tsx
new file mode 100644
index 00000000..1fac1144
--- /dev/null
+++ b/apps/web/src/features/settings/components/github/GithubConnectionCard.tsx
@@ -0,0 +1,90 @@
+import { formatDistanceToNow, parseISO } from 'date-fns';
+import { toast } from 'sonner';
+import { API_URL, type GithubSettings } from '@/lib/api';
+import SettingsCard from '@/components/common/page/SettingsCard';
+import SettingsSection from '@/components/common/page/SettingsSection';
+import SettingsRow from '@/components/common/page/SettingsRow';
+import { Button } from '@/components/ui/button';
+import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
+import { useRegenerateGithubSecret } from '../../services/settings.service';
+import GithubCopyField from './GithubCopyField';
+import GithubCliCommand from './GithubCliCommand';
+
+// The Connection block: how to register the webhook on the GitHub repository —
+// one command with the GitHub CLI, or the values to paste into GitHub's webhook
+// form — plus the most recent delivery.
+export default function GithubConnectionCard({
+ projectKey,
+ settings,
+ editable,
+}: {
+ projectKey: string;
+ settings: GithubSettings;
+ editable: boolean;
+}) {
+ const regenerate = useRegenerateGithubSecret(projectKey);
+ const payloadUrl = `${API_URL}/webhooks/github/${settings.webhookId}`;
+
+ async function regenerateSecret() {
+ await regenerate.mutateAsync();
+ toast.success('New secret created. Update it in your GitHub webhook too.');
+ }
+
+ return (
+ <SettingsSection title="Connection" description="Connect a GitHub repository to this project.">
+ <SettingsCard className="divide-y divide-border/60">
+ {settings.secret == null ? (
+ <p className="p-4 text-xs text-muted-foreground">
+ Only members who can edit integrations can see the connection details.
+ </p>
+ ) : (
+ <Tabs defaultValue="cli" className="p-4">
+ <TabsList variant="line">
+ <TabsTrigger value="cli">GitHub CLI</TabsTrigger>
+ <TabsTrigger value="manual">Manual</TabsTrigger>
+ </TabsList>
+ <TabsContent value="cli" className="mt-4">
+ <GithubCliCommand payloadUrl={payloadUrl} secret={settings.secret} />
+ </TabsContent>
+ <TabsContent value="manual" className="mt-4 space-y-4">
+ <GithubCopyField label="Payload URL" value={payloadUrl} />
+ <GithubCopyField
+ label="Webhook secret"
+ value={settings.secret}
+ masked
+ action={
+ editable ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={regenerate.isPending}
+ onClick={() => void regenerateSecret()}
+ >
+ Regenerate
+ </Button>
+ ) : undefined
+ }
+ />
+ <p className="text-xs text-muted-foreground">
+ In your GitHub repository, open <b>Settings → Webhooks → Add webhook</b>. Paste the
+ payload URL and secret, set the content type to{' '}
+ <code className="rounded bg-muted px-1 py-0.5">application/json</code>, and choose
+ only the <b>Pull requests</b> event.
+ </p>
+ </TabsContent>
+ </Tabs>
+ )}
+ <SettingsRow
+ title="Last delivery"
+ description={
+ settings.lastEventAt
+ ? `Received ${formatDistanceToNow(parseISO(settings.lastEventAt), { addSuffix: true })}` +
+ (settings.lastEventRepo ? ` from ${settings.lastEventRepo}` : '')
+ : 'Nothing received yet.'
+ }
+ control={<span />}
+ />
+ </SettingsCard>
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/features/settings/components/github/GithubCopyField.tsx b/apps/web/src/features/settings/components/github/GithubCopyField.tsx
new file mode 100644
index 00000000..256b09dc
--- /dev/null
+++ b/apps/web/src/features/settings/components/github/GithubCopyField.tsx
@@ -0,0 +1,44 @@
+import { useState } from 'react';
+import { toast } from 'sonner';
+import type { ReactNode } from 'react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+
+// A labelled read-only value with a copy button: the payload URL and secret the
+// user pastes into GitHub's webhook form. `masked` hides the value until copied.
+export default function GithubCopyField({
+ label,
+ value,
+ masked = false,
+ action,
+}: {
+ label: string;
+ value: string;
+ masked?: boolean;
+ action?: ReactNode;
+}) {
+ const [revealed, setRevealed] = useState(false);
+
+ async function copy() {
+ await navigator.clipboard.writeText(value);
+ toast.success(`${label} copied`);
+ }
+
+ return (
+ <div className="space-y-1.5">
+ <div className="text-xs font-medium">{label}</div>
+ <div className="flex items-center gap-2">
+ <Input
+ readOnly
+ className="font-mono text-xs"
+ value={masked && !revealed ? '•'.repeat(24) + value.slice(-4) : value}
+ onFocus={() => setRevealed(true)}
+ />
+ <Button variant="outline" size="sm" onClick={() => void copy()}>
+ Copy
+ </Button>
+ {action}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/github/SettingsGithub.tsx b/apps/web/src/features/settings/components/github/SettingsGithub.tsx
new file mode 100644
index 00000000..26646088
--- /dev/null
+++ b/apps/web/src/features/settings/components/github/SettingsGithub.tsx
@@ -0,0 +1,53 @@
+import type { ProjectDetail } from '@/lib/api';
+import ListSkeleton from '@/components/common/skeleton/ListSkeleton';
+import SettingsCard from '@/components/common/page/SettingsCard';
+import SettingsRow from '@/components/common/page/SettingsRow';
+import { Switch } from '@/components/ui/switch';
+import { usePermissions } from '@/hooks/usePermissions';
+import { useGithubSettingsQuery, useUpdateGithubSettings } from '../../services/settings.service';
+import GithubConnectionCard from './GithubConnectionCard';
+import GithubAutomationsCard from './GithubAutomationsCard';
+
+// The GitHub settings tab: a master switch, and — while it is on — the webhook
+// connection and the pull request automations. Every control writes immediately;
+// there is no form-level save.
+export default function SettingsGithub({ project }: { project: ProjectDetail }) {
+ const projectKey = project.project.key;
+ const { can } = usePermissions();
+ const settingsQuery = useGithubSettingsQuery(projectKey);
+ const updateSettings = useUpdateGithubSettings(projectKey);
+
+ if (settingsQuery.isPending || !settingsQuery.data)
+ return <ListSkeleton rows={3} rowClassName="h-16" />;
+
+ const settings = settingsQuery.data;
+ const editable = can('integrations', 'edit');
+ return (
+ <div className="space-y-10">
+ <SettingsCard>
+ <SettingsRow
+ title="Enable GitHub integration"
+ description="A pull request that mentions an issue, like “Closes KEY-123”, is linked to it."
+ control={
+ <Switch
+ checked={settings.enabled}
+ disabled={!editable}
+ onCheckedChange={(enabled) => updateSettings.mutate({ enabled })}
+ />
+ }
+ />
+ </SettingsCard>
+ {settings.enabled && (
+ <>
+ <GithubConnectionCard projectKey={projectKey} settings={settings} editable={editable} />
+ <GithubAutomationsCard
+ columns={project.columns}
+ settings={settings}
+ editable={editable}
+ onChange={(patch) => updateSettings.mutate(patch)}
+ />
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/services/settings.service.ts b/apps/web/src/features/settings/services/settings.service.ts
index 83663924..f3ca4127 100644
--- a/apps/web/src/features/settings/services/settings.service.ts
+++ b/apps/web/src/features/settings/services/settings.service.ts
@@ -143,6 +143,31 @@ export function useUpdateSubtaskAutomation(projectKey: string) {
});
}
+// GitHub section: the inbound webhook connection and its PR automations.
+export function useGithubSettingsQuery(projectKey: string) {
+ return useQuery({
+ queryKey: qk.githubSettings(projectKey),
+ queryFn: () => api.getGithubSettings(projectKey),
+ });
+}
+
+export function useUpdateGithubSettings(projectKey: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (patch: Parameters<typeof api.updateGithubSettings>[1]) =>
+ api.updateGithubSettings(projectKey, patch),
+ onSuccess: (data) => qc.setQueryData(qk.githubSettings(projectKey), data),
+ });
+}
+
+export function useRegenerateGithubSecret(projectKey: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: () => api.regenerateGithubSecret(projectKey),
+ onSuccess: (data) => qc.setQueryData(qk.githubSettings(projectKey), data),
+ });
+}
+
// General section: which optional sections the project shows. The current state
// comes with the project payload (getProject), so a write only invalidates it —
// the navigation and the sections themselves read it from there.
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 2ad85663..e8574a9d 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -587,6 +587,23 @@ export interface SubtaskAutomationSettings {
closeSubtasks: boolean;
}
+// Per-project GitHub integration settings. webhookId is the path segment of the
+// payload URL registered on the GitHub repository; secret signs its deliveries
+// and is null for members who may read but not edit integrations. onMergeColumnId
+// is where an issue closed by a merged PR moves (null = the first completed
+// state); onOpenColumnId is where an issue moves when a linked PR is opened
+// (null = no action). lastEventAt/lastEventRepo reflect the most recent delivery
+// received.
+export interface GithubSettings {
+ enabled: boolean;
+ webhookId: string;
+ secret: string | null;
+ onMergeColumnId: number | null;
+ onOpenColumnId: number | null;
+ lastEventAt: string | null;
+ lastEventRepo: string | null;
+}
+
// Which optional sections a project shows. All on by default; turning one off
// hides its navigation entry and its section, keeping the rows behind it.
export interface ProjectFeatures {
@@ -1327,7 +1344,8 @@ export type ActivityAction =
| 'checklist_item_remove'
| 'field'
| 'archived'
- | 'restored';
+ | 'restored'
+ | 'github_pr';
// One entry in an issue's timeline. kind selects which payload fields are set:
// a 'comment' carries body; an 'activity' carries action/subject/fromText/toText.
@@ -2771,6 +2789,22 @@ export const api = {
body: JSON.stringify(input),
}),
+ // The GitHub integration (integrations: read to view, edit to change).
+ getGithubSettings: (projectKey: string) =>
+ request<GithubSettings>(`/projects/${projectKey}/settings/github`),
+ updateGithubSettings: (
+ projectKey: string,
+ patch: { enabled?: boolean; onMergeColumnId?: number | null; onOpenColumnId?: number | null },
+ ) =>
+ request<GithubSettings>(`/projects/${projectKey}/settings/github`, {
+ method: 'PATCH',
+ body: JSON.stringify(patch),
+ }),
+ regenerateGithubSecret: (projectKey: string) =>
+ request<GithubSettings>(`/projects/${projectKey}/settings/github/secret`, {
+ method: 'POST',
+ }),
+
// Notification provider credentials (danger_zone: read to view, edit to change).
getNotificationSettings: (projectKey: string) =>
request<NotificationSettings>(`/projects/${projectKey}/notification-settings`),
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index 65b9243f..9e009275 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -17,6 +17,8 @@ export const qk = {
// Configuration settings section).
autoArchive: (projectKey: string) => ['autoArchive', projectKey] as const,
subtaskAutomation: (projectKey: string) => ['subtaskAutomation', projectKey] as const,
+ // The project's GitHub integration settings (the GitHub settings section).
+ githubSettings: (projectKey: string) => ['githubSettings', projectKey] as const,
// A project's notification delivery settings (the Notifications section).
notificationSettings: (projectKey: string) => ['notificationSettings', projectKey] as const,
notificationPreferences: (projectKey: string) => ['notificationPreferences', projectKey] as const,
diff --git a/apps/web/src/utils/settingsSections.ts b/apps/web/src/utils/settingsSections.ts
index 31bffcbc..ac2e9b88 100644
--- a/apps/web/src/utils/settingsSections.ts
+++ b/apps/web/src/utils/settingsSections.ts
@@ -4,6 +4,7 @@ import {
BookText,
Clock3,
Columns3,
+ Github,
Info,
KeyRound,
ListPlus,
@@ -122,6 +123,14 @@ export const SETTINGS_SECTIONS: SettingsSection[] = [
resource: 'webhooks',
group: 'automation',
},
+ {
+ slug: 'github',
+ label: 'GitHub',
+ description: 'Close issues automatically when their pull requests merge on GitHub.',
+ icon: Github,
+ resource: 'integrations',
+ group: 'automation',
+ },
];
// The AI configuration items are their own nav routes (not /settings/:section