Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(vcs): self-hosted Git providers (Forgejo, Gitea, GitLab) alongside GitHub (MUL-3772) (#5006)
dixonl90581d9527ba13
diff --git a/.env.example b/.env.exampleindex 27500735d6..4241cce022 100644--- a/.env.example+++ b/.env.example@@ -269,6 +269,15 @@ GITHUB_WEBHOOK_SECRET=GITHUB_APP_ID=GITHUB_APP_PRIVATE_KEY=+# Self-hosted Git provider integration (Settings → Integrations): Forgejo, Gitea,+# and GitLab. Off until MULTICA_VCS_SECRET_KEY is set — a base64-encoded+# 32-byte key that encrypts each workspace's access token and webhook secret at+# rest. Leave empty to disable. Generate one with: openssl rand -base64 32+# Unlike GitHub there is no App: each workspace connects its own instance URL+# and access token in the UI, and registers the returned webhook URL/secret on+# its repo or org webhook settings.+MULTICA_VCS_SECRET_KEY=+# Lark / Feishu bot integration (Settings → Integrations "Bind to Lark")# Off until MULTICA_LARK_SECRET_KEY is set — a base64-encoded 32-byte key# that encrypts each Bot's app secret at rest. Leave empty to disable.diff --git a/Makefile b/Makefileindex d6cd268398..4ad610ce07 100644--- a/Makefile+++ b/Makefile@@ -83,16 +83,19 @@ selfhost: ## Create .env if needed, then pull and start the official self-hostedcp .env.example .env; \JWT=$$(openssl rand -hex 32); \PGPASS=$$(openssl rand -hex 24); \+ VCSKEY=$$(openssl rand -base64 32); \if [ "$$(uname)" = "Darwin" ]; then \sed -i '' "s/^JWT_SECRET=.*/JWT_SECRET=$$JWT/" .env; \sed -i '' "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$$PGPASS/" .env; \sed -i '' -E "s#^(DATABASE_URL=postgres://[^:]+:)[^@]*(@.*)#\1$$PGPASS\2#" .env; \+ sed -i '' "s#^MULTICA_VCS_SECRET_KEY=.*#MULTICA_VCS_SECRET_KEY=$$VCSKEY#" .env; \else \sed -i "s/^JWT_SECRET=.*/JWT_SECRET=$$JWT/" .env; \sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$$PGPASS/" .env; \sed -i -E "s#^(DATABASE_URL=postgres://[^:]+:)[^@]*(@.*)#\1$$PGPASS\2#" .env; \+ sed -i "s#^MULTICA_VCS_SECRET_KEY=.*#MULTICA_VCS_SECRET_KEY=$$VCSKEY#" .env; \fi; \- echo "==> Generated random JWT_SECRET and POSTGRES_PASSWORD"; \+ echo "==> Generated random JWT_SECRET, POSTGRES_PASSWORD, and MULTICA_VCS_SECRET_KEY"; \fi@echo "==> Pulling official Multica images..."@if ! $(COMPOSE) -f docker-compose.selfhost.yml pull; then \@@ -139,16 +142,19 @@ selfhost-build: ## Build backend/web from the current checkout and start the selcp .env.example .env; \JWT=$$(openssl rand -hex 32); \PGPASS=$$(openssl rand -hex 24); \+ VCSKEY=$$(openssl rand -base64 32); \if [ "$$(uname)" = "Darwin" ]; then \sed -i '' "s/^JWT_SECRET=.*/JWT_SECRET=$$JWT/" .env; \sed -i '' "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$$PGPASS/" .env; \sed -i '' -E "s#^(DATABASE_URL=postgres://[^:]+:)[^@]*(@.*)#\1$$PGPASS\2#" .env; \+ sed -i '' "s#^MULTICA_VCS_SECRET_KEY=.*#MULTICA_VCS_SECRET_KEY=$$VCSKEY#" .env; \else \sed -i "s/^JWT_SECRET=.*/JWT_SECRET=$$JWT/" .env; \sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=$$PGPASS/" .env; \sed -i -E "s#^(DATABASE_URL=postgres://[^:]+:)[^@]*(@.*)#\1$$PGPASS\2#" .env; \+ sed -i "s#^MULTICA_VCS_SECRET_KEY=.*#MULTICA_VCS_SECRET_KEY=$$VCSKEY#" .env; \fi; \- echo "==> Generated random JWT_SECRET and POSTGRES_PASSWORD"; \+ echo "==> Generated random JWT_SECRET, POSTGRES_PASSWORD, and MULTICA_VCS_SECRET_KEY"; \fi@echo "==> Building Multica from the current checkout..."$(COMPOSE) -f docker-compose.selfhost.yml -f docker-compose.selfhost.build.yml up -d --builddiff --git a/apps/docs/content/docs/meta.ja.json b/apps/docs/content/docs/meta.ja.jsonindex 8909ffd4bf..2a74493d28 100644--- a/apps/docs/content/docs/meta.ja.json+++ b/apps/docs/content/docs/meta.ja.json@@ -32,6 +32,7 @@"---連携---","channels","github-integration",+ "vcs-integration","lark-bot-integration","slack-bot-integration","---セルフホスト & 運用---",diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.jsonindex d571c70f90..756d2c79b6 100644--- a/apps/docs/content/docs/meta.json+++ b/apps/docs/content/docs/meta.json@@ -32,6 +32,7 @@"---Integrations---","channels","github-integration",+ "vcs-integration","lark-bot-integration","slack-bot-integration","---Self-hosting & ops---",diff --git a/apps/docs/content/docs/meta.ko.json b/apps/docs/content/docs/meta.ko.jsonindex 419e77824d..3c18dc47c9 100644--- a/apps/docs/content/docs/meta.ko.json+++ b/apps/docs/content/docs/meta.ko.json@@ -32,6 +32,7 @@"---연동---","channels","github-integration",+ "vcs-integration","lark-bot-integration","slack-bot-integration","---자체 호스팅 & 운영---",diff --git a/apps/docs/content/docs/meta.zh.json b/apps/docs/content/docs/meta.zh.jsonindex 3cc5fc336f..503726f7d6 100644--- a/apps/docs/content/docs/meta.zh.json+++ b/apps/docs/content/docs/meta.zh.json@@ -32,6 +32,7 @@"---集成---","channels","github-integration",+ "vcs-integration","lark-bot-integration","slack-bot-integration","---自部署运维---",diff --git a/apps/docs/content/docs/vcs-integration.mdx b/apps/docs/content/docs/vcs-integration.mdxnew file mode 100644index 0000000000..985eb4e594--- /dev/null+++ b/apps/docs/content/docs/vcs-integration.mdx@@ -0,0 +1,70 @@+---+title: Self-hosted Git providers+description: Connect a self-hosted Forgejo, Gitea, or GitLab instance per workspace so pull/merge requests that reference an issue identifier auto-attach to that issue, move it to Done on merge, and show CI status.+---++import { Callout } from "fumadocs-ui/components/callout";++Multica connects to a self-hosted Git provider per workspace: **Forgejo**, **Gitea**, or **GitLab**. Once connected, any pull request (GitLab: merge request) whose branch name, title, or body contains an issue identifier (for example `MUL-123`) is **auto-linked** to that [issue](/issues), appears under **Pull requests** in the issue sidebar, and — when merged with a closing keyword — moves the issue to **Done**. CI for the head commit shows as a checks bar on the card.++These providers run alongside GitHub: a workspace can use any combination.++<Callout type="info">+Unlike GitHub, these providers have no "App" model. Each workspace stores its own instance URL plus an access token, and registers a webhook on its repository or organisation. The token and webhook secret are encrypted at rest.+</Callout>++## Prerequisites (server)++Set a base64-encoded 32-byte key so the server can encrypt stored credentials. Without it, the connect form is disabled.++```sh+openssl rand -base64 32+```++```sh+MULTICA_VCS_SECRET_KEY=<base64 32-byte key>+```++Set `MULTICA_PUBLIC_URL` to the server's public base URL so Multica can show a ready-to-paste webhook URL. Without it, the UI shows only the webhook path and you prepend your own origin.++## Connect a workspace++1. Create an access token in your provider with read access to the repositories you want mirrored:+ - **Forgejo / Gitea**: Settings → Applications.+ - **GitLab**: a personal (or group/project) access token with the `read_api` scope.+2. In Multica, open **Settings → Integrations → Git providers**.+3. Choose the **provider**, enter the instance URL (for example `https://forgejo.example.com`) and the access token, then **Connect**. Multica validates the token against the instance before saving.+4. Copy the **webhook URL** and **webhook secret** shown after connecting.++<Callout type="warn">+The webhook secret is shown only once. Copy it before leaving the page. Reconnecting the same instance rotates the token and secret.+</Callout>++## Register the webhook++On the repository (or organisation/group, to cover every repo):++**Forgejo / Gitea** — Settings → Webhooks → Add Webhook → Forgejo/Gitea:++- **Target URL**: the webhook URL from the previous step.+- **HTTP method** `POST`, **content type** `application/json`.+- **Secret**: the webhook secret (used to verify the `X-Gitea-Signature` HMAC).+- **Trigger events**: select **Pull Request**, and **Commit Status** to mirror CI.++**GitLab** — Settings → Webhooks:++- **URL**: the webhook URL.+- **Secret token**: the webhook secret (sent as `X-Gitlab-Token` and compared verbatim).+- **Triggers**: enable **Merge request events**, and **Pipeline events** to mirror CI.++Multica authenticates every delivery against the stored secret, so a webhook without the matching secret is rejected.++## What gets mirrored++- **Pull / merge requests** — open, closed, merged, and draft state, author, branch, and (where the provider supplies them) diff stats.+- **Issue links** — identifiers in the title, body, or branch link the PR to the issue. A closing keyword (`Closes`/`Fixes`/`Resolves MUL-123`) on a merged PR moves the issue to **Done** once no linked PR is still open.+- **CI** — Forgejo/Gitea commit statuses and GitLab pipelines aggregate into a passed/failed/pending checks bar for the head commit.++## Agents opening pull requests++Creating PRs needs no provider configuration in Multica. Agents check out repositories in the runtime and push branches and open PRs using the runtime host's own Git credentials. To let agents work against a provider, ensure the daemon host can authenticate to it — for example an SSH deploy key, or a token in the host's Git credential helper — and add the repository URL as usual. Repository checkout works with any Git URL, so no provider-specific wiring is required.diff --git a/apps/docs/content/docs/vcs-integration.zh.mdx b/apps/docs/content/docs/vcs-integration.zh.mdxnew file mode 100644index 0000000000..6d4b6e742d--- /dev/null+++ b/apps/docs/content/docs/vcs-integration.zh.mdx@@ -0,0 +1,70 @@+---+title: 自托管 Git 代码托管+description: 为每个工作区连接自托管的 Forgejo、Gitea 或 GitLab 实例,使引用了 issue 编号的 Pull Request / Merge Request 自动关联到对应 issue,在合并时将其移动到「完成」,并展示 CI 状态。+---++import { Callout } from "fumadocs-ui/components/callout";++Multica 按工作区连接自托管的 Git 代码托管:**Forgejo**、**Gitea** 或 **GitLab**。连接后,任何在分支名、标题或正文中包含 issue 编号(例如 `MUL-123`)的 Pull Request(GitLab 为 Merge Request)都会**自动关联**到对应的 [issue](/issues),出现在 issue 侧栏的 **Pull requests** 中;当带有关闭关键字的 PR 合并后,issue 会被移动到「完成」。head commit 的 CI 会以检查条的形式显示在卡片上。++这些代码托管与 GitHub 并行工作:一个工作区可任意组合使用。++<Callout type="info">+与 GitHub 不同,这些代码托管没有「App」模型。每个工作区保存自己的实例地址和访问令牌,并在其仓库或组织上注册 Webhook。令牌和 Webhook 密钥均加密存储。+</Callout>++## 前置条件(服务端)++设置一个 base64 编码的 32 字节密钥,供服务端加密存储的凭据。未设置时,连接表单将不可用。++```sh+openssl rand -base64 32+```++```sh+MULTICA_VCS_SECRET_KEY=<base64 32 字节密钥>+```++设置 `MULTICA_PUBLIC_URL` 为服务端的公网基础地址,Multica 即可直接给出可粘贴的 Webhook 地址;否则界面只显示 Webhook 路径,需自行拼接来源地址。++## 连接工作区++1. 在代码托管中创建具备仓库读取权限的访问令牌:+ - **Forgejo / Gitea**:设置 → 应用。+ - **GitLab**:具备 `read_api` 权限的个人(或群组/项目)访问令牌。+2. 在 Multica 中打开 **设置 → 集成 → Git 代码托管**。+3. 选择**提供方**,填写实例地址(例如 `https://forgejo.example.com`)和访问令牌,点击 **连接**。Multica 会先用该令牌访问实例进行校验,再保存。+4. 复制连接后显示的 **Webhook 地址** 与 **Webhook 密钥**。++<Callout type="warn">+Webhook 密钥只显示一次,请在离开页面前复制。重新连接同一实例会轮换令牌与密钥。+</Callout>++## 注册 Webhook++在仓库(或组织/群组,以覆盖所有仓库):++**Forgejo / Gitea** —— 设置 → Webhook → 添加 Webhook → Forgejo/Gitea:++- **目标 URL**:上一步的 Webhook 地址。+- **HTTP 方法** `POST`,**内容类型** `application/json`。+- **密钥**:Webhook 密钥(用于校验 `X-Gitea-Signature` HMAC)。+- **触发事件**:勾选 **Pull Request**,并勾选 **Commit Status** 以镜像 CI。++**GitLab** —— 设置 → Webhooks:++- **URL**:Webhook 地址。+- **Secret token**:Webhook 密钥(作为 `X-Gitlab-Token` 发送并逐字比对)。+- **触发器**:启用 **Merge request events**,并启用 **Pipeline events** 以镜像 CI。++Multica 会用存储的密钥校验每次投递,因此没有匹配密钥的 Webhook 会被拒绝。++## 镜像的内容++- **Pull / Merge Request** —— open、closed、merged、draft 状态,以及作者、分支和(在代码托管提供时)diff 统计。+- **issue 关联** —— 标题、正文或分支中的编号会将 PR 关联到 issue。合并的 PR 带有关闭关键字(`Closes`/`Fixes`/`Resolves MUL-123`)且没有仍处于 open 的关联 PR 时,issue 会被移动到「完成」。+- **CI** —— Forgejo/Gitea 的提交状态与 GitLab 的流水线会汇总为 head commit 的通过/失败/进行中检查条。++## 智能体创建 Pull Request++创建 PR 无需在 Multica 中进行任何代码托管配置。智能体在运行时中检出仓库,并使用运行时主机自身的 Git 凭据推送分支和创建 PR。要让智能体在某个代码托管上工作,确保 daemon 主机能对其完成认证即可——例如 SSH 部署密钥,或主机 Git 凭据助手中的令牌——再像往常一样添加仓库地址。仓库检出支持任意 Git URL,因此无需提供方专属配置。diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 6983ca1270..dcd494a618 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -119,6 +119,8 @@ services:# in the database, so this single deployment-wide key is all the operator# needs to set here.MULTICA_SLACK_SECRET_KEY: ${MULTICA_SLACK_SECRET_KEY:-}+ # VCS integration at-rest encryption key for token-based providers+ MULTICA_VCS_SECRET_KEY: ${MULTICA_VCS_SECRET_KEY:-}restart: unless-stoppedfrontend:diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 9780f1ec83..923a9f47e3 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -135,6 +135,9 @@ import type {GitHubPullRequest,ListGitHubInstallationsResponse,GitHubConnectResponse,+ ListVCSConnectionsResponse,+ ConnectVCSRequest,+ ConnectVCSResponse,ListLarkInstallationsResponse,BeginLarkInstallResponse,LarkInstallStatusResponse,@@ -2802,6 +2805,37 @@ export class ApiClient {return this.fetch(`/api/issues/${issueId}/pull-requests`);}+ // VCS integration (Forgejo / Gitea / GitLab)+ async listVCSConnections(workspaceId: string): Promise<ListVCSConnectionsResponse> {+ return this.fetch(`/api/workspaces/${workspaceId}/vcs/connections`);+ }++ async connectVCS(+ workspaceId: string,+ body: ConnectVCSRequest,+ ): Promise<ConnectVCSResponse> {+ return this.fetch(`/api/workspaces/${workspaceId}/vcs/connections`, {+ method: "POST",+ body: JSON.stringify(body),+ });+ }++ async deleteVCSConnection(workspaceId: string, connectionId: string): Promise<void> {+ await this.fetch(`/api/workspaces/${workspaceId}/vcs/connections/${connectionId}`, {+ method: "DELETE",+ });+ }++ async rotateVCSWebhook(+ workspaceId: string,+ connectionId: string,+ ): Promise<ConnectVCSResponse> {+ return this.fetch(+ `/api/workspaces/${workspaceId}/vcs/connections/${connectionId}/rotate-webhook`,+ { method: "POST" },+ );+ }+// Lark integrationasync listLarkInstallations(workspaceId: string): Promise<ListLarkInstallationsResponse> {return this.fetch(`/api/workspaces/${workspaceId}/lark/installations`);diff --git a/packages/core/package.json b/packages/core/package.jsonindex 4b2646a13f..0d05477e6a 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -89,6 +89,8 @@"./billing/mutations": "./billing/mutations.ts","./github": "./github/index.ts","./github/queries": "./github/queries.ts",+ "./vcs": "./vcs/index.ts",+ "./vcs/queries": "./vcs/queries.ts","./lark": "./lark/index.ts","./lark/queries": "./lark/queries.ts","./composio": "./composio/index.ts",diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex e9988b02c8..788d4e3903 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -686,6 +686,10 @@ export function useRealtimeSync(const wsId = getCurrentWsId();if (wsId) qc.invalidateQueries({ queryKey: slackKeys.installations(wsId) });},+ vcs_connection: () => {+ const wsId = getCurrentWsId();+ if (wsId) qc.invalidateQueries({ queryKey: ["vcs", wsId] });+ },pull_request: () => {// PR list is keyed by issue id, not workspace, so we invalidate all// PR queries — the open issue detail page will refetch its own list.diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 21dd7edd4b..9cb492f103 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -134,6 +134,13 @@ export type {ListGitHubInstallationsResponse,GitHubConnectResponse,} from "./github";+export type {+ VCSProvider,+ VCSConnection,+ ListVCSConnectionsResponse,+ ConnectVCSRequest,+ ConnectVCSResponse,+} from "./vcs";export type {LarkInstallation,ListLarkInstallationsResponse,diff --git a/packages/core/types/vcs.ts b/packages/core/types/vcs.tsnew file mode 100644index 0000000000..04d7dfaba0--- /dev/null+++ b/packages/core/types/vcs.ts@@ -0,0 +1,46 @@+/**+ * Token-based Git provider integration types (Forgejo, Gitea, GitLab). Unlike+ * GitHub there is no App/installation model: each workspace stores a+ * token-based connection to a provider instance. Pull requests mirrored from any+ * of these providers surface through the shared GitHubPullRequest shape, tagged+ * with the matching `provider`.+ */++export type VCSProvider = "forgejo" | "gitea" | "gitlab";++export interface VCSConnection {+ id: string;+ workspace_id: string;+ provider: VCSProvider;+ /** Instance base URL, e.g. https://forgejo.example.com (no trailing slash). */+ instance_url: string;+ /** Login (user or org) the stored access token authenticates as. */+ account_login: string;+ /** Absolute webhook endpoint to register on the provider. Empty when the server+ * has no public URL configured; the UI then prefixes `webhook_path`. */+ webhook_url: string;+ webhook_path: string;+ created_at: string;+}++export interface ListVCSConnectionsResponse {+ connections: VCSConnection[];+ /** Whether the deployment has MULTICA_VCS_SECRET_KEY configured. When false+ * the connect form is disabled. Older backends omit it; treat as false. */+ configured?: boolean;+ /** Whether the caller can connect / disconnect. Non-admins get false. */+ can_manage?: boolean;+}++export interface ConnectVCSRequest {+ provider: VCSProvider;+ instance_url: string;+ access_token: string;+}++export interface ConnectVCSResponse extends VCSConnection {+ /** One-time plaintext webhook secret to paste into the provider (HMAC secret+ * for Forgejo/Gitea, X-Gitlab-Token value for GitLab). Not retrievable+ * afterwards (stored encrypted); reconnecting rotates it. */+ webhook_secret: string;+}diff --git a/packages/core/vcs/index.ts b/packages/core/vcs/index.tsnew file mode 100644index 0000000000..b69c251208--- /dev/null+++ b/packages/core/vcs/index.ts@@ -0,0 +1 @@+export * from "./queries";diff --git a/packages/core/vcs/queries.ts b/packages/core/vcs/queries.tsnew file mode 100644index 0000000000..daafbec01b--- /dev/null+++ b/packages/core/vcs/queries.ts@@ -0,0 +1,14 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";++export const vcsKeys = {+ all: (wsId: string) => ["vcs", wsId] as const,+ connections: (wsId: string) => [...vcsKeys.all(wsId), "connections"] as const,+};++export const vcsConnectionsOptions = (wsId: string) =>+ queryOptions({+ queryKey: vcsKeys.connections(wsId),+ queryFn: () => api.listVCSConnections(wsId),+ enabled: !!wsId,+ });diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 2447dce933..ac4c7c4e78 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -447,6 +447,47 @@"repositories_shortcut_link": "Manage repositories →","toast_failed": "Failed to update GitHub settings"},+ "vcs": {+ "section_title": "Git providers (self-hosted)",+ "page_description": "Connect a self-hosted Forgejo, Gitea, or GitLab instance to mirror pull requests onto issues. Each connection uses an access token; agents push branches and open PRs using the runtime's own Git credentials.",+ "connect_title": "Connect a provider instance",+ "connected_as": "Connected as {{login}}",+ "form_provider_label": "Provider",+ "form_instance_url_label": "Instance URL",+ "form_token_label": "Access token",+ "form_token_placeholder": "Access token",+ "form_token_hint": "Create an access token with read access to repositories. Forgejo/Gitea: Settings, Applications. GitLab: a personal access token with the read_api scope.",+ "connect": "Connect",+ "connecting": "Connecting...",+ "disconnect": "Disconnect",+ "disconnecting": "Disconnecting...",+ "not_configured": "Git provider integration is not configured on this server. Ask an administrator to set",+ "contact_admin": "Ask a workspace admin to connect a Git provider instance.",+ "webhook_setup_title": "Finish setup in your provider",+ "webhook_setup_description": "Add a webhook on your repository or organisation with the URL and secret below. Forgejo/Gitea: choose the Gitea format and the Pull Request (and Commit Status) events. GitLab: paste the secret as the token and enable Merge request and Pipeline events.",+ "webhook_url_label": "Webhook URL",+ "webhook_secret_label": "Webhook secret",+ "webhook_secret_warning": "Copy the secret now. It is shown only once and cannot be retrieved later.",+ "copy": "Copy",+ "copied": "Copied to clipboard",+ "copy_failed": "Could not copy",+ "disconnect_confirm_title": "Disconnect this provider?",+ "disconnect_confirm_description": "Mirrored pull requests and their issue links for this connection will be removed. This cannot be undone.",+ "disconnect_confirm_cancel": "Cancel",+ "disconnect_confirm_action": "Disconnect",+ "toast_connected": "Provider connected",+ "toast_connect_failed": "Could not connect to the provider",+ "toast_disconnected": "Provider disconnected",+ "toast_disconnect_failed": "Could not disconnect",+ "regenerate_webhook": "Regenerate webhook",+ "rotate_confirm_title": "Regenerate webhook secret?",+ "rotate_confirm_description": "The current webhook secret will stop working immediately. Deliveries from your Git provider will fail until you update the webhook secret in provider settings.",+ "rotate_confirm_cancel": "Cancel",+ "rotate_confirm_action": "Regenerate",+ "rotating": "Regenerating...",+ "toast_rotated": "Webhook secret regenerated",+ "toast_rotate_failed": "Could not regenerate webhook secret"+ },"lark": {"section_title": "Lark","page_description": "Connect each Multica Agent to a Lark (飞书) PersonalAgent Bot. Members can DM the Bot, @ it in groups, and type /issue to spin up a new Multica issue.",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 41c23dee77..c885f5a6ee 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -439,6 +439,47 @@"repositories_shortcut_link": "リポジトリを管理 →","toast_failed": "GitHub 設定を更新できませんでした"},+ "vcs": {+ "section_title": "Git providers (self-hosted)",+ "page_description": "Connect a self-hosted Forgejo, Gitea, or GitLab instance to mirror pull requests onto issues. Each connection uses an access token; agents push branches and open PRs using the runtime's own Git credentials.",+ "connect_title": "Connect a provider instance",+ "connected_as": "Connected as {{login}}",+ "form_provider_label": "Provider",+ "form_instance_url_label": "Instance URL",+ "form_token_label": "Access token",+ "form_token_placeholder": "Access token",+ "form_token_hint": "Create an access token with read access to repositories. Forgejo/Gitea: Settings, Applications. GitLab: a personal access token with the read_api scope.",+ "connect": "Connect",+ "connecting": "Connecting...",+ "disconnect": "Disconnect",+ "disconnecting": "Disconnecting...",+ "not_configured": "Git provider integration is not configured on this server. Ask an administrator to set",+ "contact_admin": "Ask a workspace admin to connect a Git provider instance.",+ "webhook_setup_title": "Finish setup in your provider",+ "webhook_setup_description": "Add a webhook on your repository or organisation with the URL and secret below. Forgejo/Gitea: choose the Gitea format and the Pull Request (and Commit Status) events. GitLab: paste the secret as the token and enable Merge request and Pipeline events.",+ "webhook_url_label": "Webhook URL",+ "webhook_secret_label": "Webhook secret",+ "webhook_secret_warning": "Copy the secret now. It is shown only once and cannot be retrieved later.",+ "copy": "Copy",+ "copied": "Copied to clipboard",+ "copy_failed": "Could not copy",+ "disconnect_confirm_title": "Disconnect this provider?",+ "disconnect_confirm_description": "Mirrored pull requests and their issue links for this connection will be removed. This cannot be undone.",+ "disconnect_confirm_cancel": "Cancel",+ "disconnect_confirm_action": "Disconnect",+ "toast_connected": "Provider connected",+ "toast_connect_failed": "Could not connect to the provider",+ "toast_disconnected": "Provider disconnected",+ "toast_disconnect_failed": "Could not disconnect",+ "regenerate_webhook": "Regenerate webhook",+ "rotate_confirm_title": "Regenerate webhook secret?",+ "rotate_confirm_description": "The current webhook secret will stop working immediately. Deliveries from your Git provider will fail until you update the webhook secret in provider settings.",+ "rotate_confirm_cancel": "Cancel",+ "rotate_confirm_action": "Regenerate",+ "rotating": "Regenerating...",+ "toast_rotated": "Webhook secret regenerated",+ "toast_rotate_failed": "Could not regenerate webhook secret"+ },"lark": {"section_title": "Lark","page_description": "各 Multica エージェントを Lark (飞书) PersonalAgent ボットに接続します。メンバーはボットに DM したり、グループで @ メンションしたり、/issue と入力して新しい Multica イシューを起こすことができます。",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 715f2877f0..aa76ffc374 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -439,6 +439,47 @@"repositories_shortcut_link": "저장소 관리 →","toast_failed": "GitHub 설정을 업데이트하지 못했습니다"},+ "vcs": {+ "section_title": "Git providers (self-hosted)",+ "page_description": "Connect a self-hosted Forgejo, Gitea, or GitLab instance to mirror pull requests onto issues. Each connection uses an access token; agents push branches and open PRs using the runtime's own Git credentials.",+ "connect_title": "Connect a provider instance",+ "connected_as": "Connected as {{login}}",+ "form_provider_label": "Provider",+ "form_instance_url_label": "Instance URL",+ "form_token_label": "Access token",+ "form_token_placeholder": "Access token",+ "form_token_hint": "Create an access token with read access to repositories. Forgejo/Gitea: Settings, Applications. GitLab: a personal access token with the read_api scope.",+ "connect": "Connect",+ "connecting": "Connecting...",+ "disconnect": "Disconnect",+ "disconnecting": "Disconnecting...",+ "not_configured": "Git provider integration is not configured on this server. Ask an administrator to set",+ "contact_admin": "Ask a workspace admin to connect a Git provider instance.",+ "webhook_setup_title": "Finish setup in your provider",+ "webhook_setup_description": "Add a webhook on your repository or organisation with the URL and secret below. Forgejo/Gitea: choose the Gitea format and the Pull Request (and Commit Status) events. GitLab: paste the secret as the token and enable Merge request and Pipeline events.",+ "webhook_url_label": "Webhook URL",+ "webhook_secret_label": "Webhook secret",+ "webhook_secret_warning": "Copy the secret now. It is shown only once and cannot be retrieved later.",+ "copy": "Copy",+ "copied": "Copied to clipboard",+ "copy_failed": "Could not copy",+ "disconnect_confirm_title": "Disconnect this provider?",+ "disconnect_confirm_description": "Mirrored pull requests and their issue links for this connection will be removed. This cannot be undone.",+ "disconnect_confirm_cancel": "Cancel",+ "disconnect_confirm_action": "Disconnect",+ "toast_connected": "Provider connected",+ "toast_connect_failed": "Could not connect to the provider",+ "toast_disconnected": "Provider disconnected",+ "toast_disconnect_failed": "Could not disconnect",+ "regenerate_webhook": "Regenerate webhook",+ "rotate_confirm_title": "Regenerate webhook secret?",+ "rotate_confirm_description": "The current webhook secret will stop working immediately. Deliveries from your Git provider will fail until you update the webhook secret in provider settings.",+ "rotate_confirm_cancel": "Cancel",+ "rotate_confirm_action": "Regenerate",+ "rotating": "Regenerating...",+ "toast_rotated": "Webhook secret regenerated",+ "toast_rotate_failed": "Could not regenerate webhook secret"+ },"repositories": {"section_title": "저장소","description": "이 워크스페이스와 연결된 Git 저장소입니다. 에이전트는 이 저장소를 클론해 코드 작업을 합니다.",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex e80a7cc1b8..605d50266c 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -446,6 +446,47 @@"repositories_shortcut_link": "前往管理 →","toast_failed": "更新 GitHub 设置失败"},+ "vcs": {+ "section_title": "Git 代码托管(自托管)",+ "page_description": "连接自托管的 Forgejo、Gitea 或 GitLab 实例,将 Pull Request 镜像到 issue 上。每个连接使用一个访问令牌;智能体使用运行时自身的 Git 凭据推送分支并创建 PR。",+ "connect_title": "连接代码托管实例",+ "connected_as": "已以 {{login}} 身份连接",+ "form_provider_label": "提供方",+ "form_instance_url_label": "实例地址",+ "form_token_label": "访问令牌",+ "form_token_placeholder": "访问令牌",+ "form_token_hint": "创建具备仓库读取权限的访问令牌。Forgejo/Gitea:设置 - 应用;GitLab:具备 read_api 权限的个人访问令牌。",+ "connect": "连接",+ "connecting": "连接中…",+ "disconnect": "断开",+ "disconnecting": "断开中…",+ "not_configured": "此服务器尚未配置 Git 代码托管集成。请管理员设置",+ "contact_admin": "请工作区管理员连接 Git 代码托管实例。",+ "webhook_setup_title": "在代码托管中完成设置",+ "webhook_setup_description": "在仓库或组织中添加 Webhook,使用下方的地址和密钥。Forgejo/Gitea:格式选择 Gitea,事件勾选 Pull Request(及 Commit Status)。GitLab:将密钥填入 token,并启用 Merge request 与 Pipeline 事件。",+ "webhook_url_label": "Webhook 地址",+ "webhook_secret_label": "Webhook 密钥",+ "webhook_secret_warning": "请立即复制密钥。它只显示一次,之后无法再次获取。",+ "copy": "复制",+ "copied": "已复制到剪贴板",+ "copy_failed": "复制失败",+ "disconnect_confirm_title": "断开此代码托管连接?",+ "disconnect_confirm_description": "该连接镜像的 Pull Request 及其 issue 关联将被移除。此操作无法撤销。",+ "disconnect_confirm_cancel": "取消",+ "disconnect_confirm_action": "断开",+ "toast_connected": "已连接代码托管",+ "toast_connect_failed": "无法连接代码托管",+ "toast_disconnected": "已断开代码托管连接",+ "toast_disconnect_failed": "断开连接失败",+ "regenerate_webhook": "重新生成 Webhook",+ "rotate_confirm_title": "重新生成 Webhook 密钥?",+ "rotate_confirm_description": "当前的 Webhook 密钥将立即失效。在代码托管设置中更新密钥前,来自该平台的推送将无法送达。",+ "rotate_confirm_cancel": "取消",+ "rotate_confirm_action": "重新生成",+ "rotating": "重新生成中…",+ "toast_rotated": "已重新生成 Webhook 密钥",+ "toast_rotate_failed": "重新生成 Webhook 密钥失败"+ },"lark": {"section_title": "飞书","page_description": "将每个 Multica 智能体绑定到飞书 PersonalAgent Bot。成员可在飞书私聊 Bot、群聊 @ Bot,或输入 /issue 直接创建 Multica issue。",diff --git a/packages/views/settings/components/integrations-tab.test.tsx b/packages/views/settings/components/integrations-tab.test.tsxindex beee6e059e..089201df21 100644--- a/packages/views/settings/components/integrations-tab.test.tsx+++ b/packages/views/settings/components/integrations-tab.test.tsx@@ -44,6 +44,10 @@ vi.mock("./slack-tab", () => ({SlackTab: () => <div data-testid="slack-tab" />,}));+vi.mock("./vcs-tab", () => ({+ VCSTab: () => <div data-testid="vcs-tab" />,+}));+import { IntegrationsTab } from "./integrations-tab";function renderTab() {diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsxindex ac338b5d62..5b8eaf39f6 100644--- a/packages/views/settings/components/integrations-tab.tsx+++ b/packages/views/settings/components/integrations-tab.tsx@@ -4,6 +4,7 @@ import { useQuery } from "@tanstack/react-query";import { LarkTab } from "./lark-tab";import { ComposioTab } from "./composio-tab";import { SlackTab } from "./slack-tab";+import { VCSTab } from "./vcs-tab";import { ApiError } from "@multica/core/api";import { composioToolkitsOptions } from "@multica/core/composio";import { useFeatureEnabled } from "@multica/core/config";@@ -13,10 +14,11 @@ import { SettingsSection, SettingsTab } from "./settings-layout";// Integrations is the umbrella tab for third-party platform connections.// GitHub has its own top-level tab (see github-tab.tsx); everything else-// — currently Lark, Composio, and Slack, with Linear etc. to follow — lives in-// here under its own section heading so additional integrations slot in without-// changing the IA. IntegrationsTab is just the host; each integration owns its-// own description and install flow.+// — currently Lark, Composio, Slack, and the self-hosted Git providers (Forgejo /+// Gitea / GitLab), with Linear etc. to follow — lives in here under its own+// section heading so additional integrations slot in without changing the IA.+// IntegrationsTab is just the host; each integration owns its own description+// and install flow.export function IntegrationsTab() {const { t } = useT("settings");@@ -44,6 +46,9 @@ export function IntegrationsTab() {<SettingsSection title={t(($) => $.slack.section_title)}><SlackTab /></SettingsSection>+ <SettingsSection title={t(($) => $.vcs.section_title)}>+ <VCSTab />+ </SettingsSection></SettingsTab>);}diff --git a/packages/views/settings/components/vcs-tab.tsx b/packages/views/settings/components/vcs-tab.tsxnew file mode 100644index 0000000000..11a554e29f--- /dev/null+++ b/packages/views/settings/components/vcs-tab.tsx@@ -0,0 +1,360 @@+"use client";++import { useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { Copy, GitBranch, RefreshCw, Trash2 } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Card, CardContent } from "@multica/ui/components/ui/card";+import { Input } from "@multica/ui/components/ui/input";+import { Label } from "@multica/ui/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { useWorkspaceId } from "@multica/core/hooks";+import { vcsConnectionsOptions } from "@multica/core/vcs";+import { api } from "@multica/core/api";+import type { ConnectVCSResponse, VCSProvider } from "@multica/core/types";+import { useT } from "../../i18n";++const PROVIDERS: VCSProvider[] = ["forgejo", "gitea", "gitlab"];+const PROVIDER_LABELS: Record<VCSProvider, string> = {+ forgejo: "Forgejo",+ gitea: "Gitea",+ gitlab: "GitLab",+};+const PROVIDER_OPTIONS = PROVIDERS.map((p) => ({+ value: p,+ label: PROVIDER_LABELS[p],+}));+++export function VCSTab() {+ const { t } = useT("settings");+ const wsId = useWorkspaceId();+ const qc = useQueryClient();++ const { data } = useQuery(vcsConnectionsOptions(wsId));+ const connections = data?.connections ?? [];+ const configured = data?.configured === true;+ const canManage = data?.can_manage === true;++ const [provider, setProvider] = useState<VCSProvider>("forgejo");+ const [instanceUrl, setInstanceUrl] = useState("");+ const [token, setToken] = useState("");+ const [connecting, setConnecting] = useState(false);+ const [justConnected, setJustConnected] = useState<ConnectVCSResponse | null>(null);+ const [rotateTarget, setRotateTarget] = useState<string | null>(null);+ const [rotating, setRotating] = useState(false);+ const [deleteTarget, setDeleteTarget] = useState<string | null>(null);+ const [deleting, setDeleting] = useState(false);++ async function handleConnect() {+ if (connecting || !instanceUrl.trim() || !token.trim()) return;+ setConnecting(true);+ try {+ const resp = await api.connectVCS(wsId, {+ provider,+ instance_url: instanceUrl.trim(),+ access_token: token.trim(),+ });+ await qc.invalidateQueries({ queryKey: ["vcs", wsId] });+ setJustConnected(resp);+ setInstanceUrl("");+ setToken("");+ toast.success(t(($) => $.vcs.toast_connected));+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.vcs.toast_connect_failed));+ } finally {+ setConnecting(false);+ }+ }++ async function handleRotateWebhook() {+ if (!rotateTarget || rotating) return;+ setRotating(true);+ try {+ const resp = await api.rotateVCSWebhook(wsId, rotateTarget);+ await qc.invalidateQueries({ queryKey: ["vcs", wsId] });+ setJustConnected(resp);+ setRotateTarget(null);+ toast.success(t(($) => $.vcs.toast_rotated));+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.vcs.toast_rotate_failed));+ } finally {+ setRotating(false);+ }+ }++ async function handleDelete() {+ if (!deleteTarget || deleting) return;+ setDeleting(true);+ try {+ await api.deleteVCSConnection(wsId, deleteTarget);+ await qc.invalidateQueries({ queryKey: ["vcs", wsId] });+ if (justConnected?.id === deleteTarget) setJustConnected(null);+ toast.success(t(($) => $.vcs.toast_disconnected));+ setDeleteTarget(null);+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.vcs.toast_disconnect_failed));+ } finally {+ setDeleting(false);+ }+ }++ async function copy(value: string) {+ try {+ await navigator.clipboard.writeText(value);+ toast.success(t(($) => $.vcs.copied));+ } catch {+ toast.error(t(($) => $.vcs.copy_failed));+ }+ }++ return (+ <div className="space-y-6">+ <p className="text-sm text-muted-foreground">{t(($) => $.vcs.page_description)}</p>++ {connections.length > 0 && (+ <div className="space-y-3">+ {connections.map((c) => (+ <Card key={c.id}>+ <CardContent className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">+ <div className="flex min-w-0 items-start gap-3">+ <div className="rounded-md border bg-muted/50 p-2 text-muted-foreground shrink-0">+ <GitBranch className="h-4 w-4" />+ </div>+ <div className="min-w-0 space-y-0.5">+ <p className="text-sm font-medium break-all">+ {(PROVIDER_LABELS[c.provider] ?? c.provider) + " · " + c.instance_url}+ </p>+ <p className="text-xs text-muted-foreground break-all">+ {t(($) => $.vcs.connected_as, { login: c.account_login })}+ </p>+ </div>+ </div>+ {canManage && (+ <div className="flex flex-wrap items-center gap-2 shrink-0">+ <Button+ variant="outline"+ size="sm"+ onClick={() => setRotateTarget(c.id)}+ >+ <RefreshCw className="h-3 w-3" />+ {t(($) => $.vcs.regenerate_webhook)}+ </Button>+ <Button variant="outline" size="sm" onClick={() => setDeleteTarget(c.id)}>+ <Trash2 className="h-3 w-3" />+ {t(($) => $.vcs.disconnect)}+ </Button>+ </div>+ )}+ </CardContent>+ </Card>+ ))}+ </div>+ )}++ {justConnected && (+ <Card className="border-primary/40">+ <CardContent className="space-y-3">+ <div className="space-y-1">+ <p className="text-sm font-medium">{t(($) => $.vcs.webhook_setup_title)}</p>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.vcs.webhook_setup_description)}+ </p>+ </div>+ <CopyField+ label={t(($) => $.vcs.webhook_url_label)}+ value={justConnected.webhook_url || justConnected.webhook_path}+ onCopy={copy}+ copyLabel={t(($) => $.vcs.copy)}+ />+ <CopyField+ label={t(($) => $.vcs.webhook_secret_label)}+ value={justConnected.webhook_secret}+ onCopy={copy}+ copyLabel={t(($) => $.vcs.copy)}+ mono+ />+ <p className="text-xs text-amber-600 dark:text-amber-500">+ {t(($) => $.vcs.webhook_secret_warning)}+ </p>+ </CardContent>+ </Card>+ )}++ {canManage && (+ <Card>+ <CardContent className="space-y-4">+ <p className="text-sm font-medium">{t(($) => $.vcs.connect_title)}</p>+ {!configured ? (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.vcs.not_configured)}{" "}+ <code className="rounded bg-muted px-1 py-0.5 text-[10px]">+ MULTICA_VCS_SECRET_KEY+ </code>+ .+ </p>+ ) : (+ <>+ <div className="space-y-1.5">+ <Label htmlFor="vcs-provider">{t(($) => $.vcs.form_provider_label)}</Label>+ <Select+ items={PROVIDER_OPTIONS}+ value={provider}+ onValueChange={(v) => setProvider(v as VCSProvider)}+ >+ <SelectTrigger id="vcs-provider" disabled={connecting}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {PROVIDERS.map((p) => (+ <SelectItem key={p} value={p}>+ {PROVIDER_LABELS[p]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="vcs-url">{t(($) => $.vcs.form_instance_url_label)}</Label>+ <Input+ id="vcs-url"+ placeholder="https://forgejo.example.com"+ value={instanceUrl}+ onChange={(e) => setInstanceUrl(e.target.value)}+ disabled={connecting}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="vcs-token">{t(($) => $.vcs.form_token_label)}</Label>+ <Input+ id="vcs-token"+ type="password"+ placeholder={t(($) => $.vcs.form_token_placeholder)}+ value={token}+ onChange={(e) => setToken(e.target.value)}+ disabled={connecting}+ />+ <p className="text-xs text-muted-foreground">{t(($) => $.vcs.form_token_hint)}</p>+ </div>+ <div className="flex justify-end">+ <Button+ size="sm"+ onClick={handleConnect}+ disabled={connecting || !instanceUrl.trim() || !token.trim()}+ >+ {connecting ? t(($) => $.vcs.connecting) : t(($) => $.vcs.connect)}+ </Button>+ </div>+ </>+ )}+ </CardContent>+ </Card>+ )}++ {!canManage && connections.length === 0 && (+ <p className="text-xs text-muted-foreground">{t(($) => $.vcs.contact_admin)}</p>+ )}++ <AlertDialog+ open={!!rotateTarget}+ onOpenChange={(v) => {+ if (!v && !rotating) setRotateTarget(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.vcs.rotate_confirm_title)}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.vcs.rotate_confirm_description)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={rotating}>+ {t(($) => $.vcs.rotate_confirm_cancel)}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleRotateWebhook} disabled={rotating}>+ {rotating ? t(($) => $.vcs.rotating) : t(($) => $.vcs.rotate_confirm_action)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ <AlertDialog+ open={!!deleteTarget}+ onOpenChange={(v) => {+ if (!v && !deleting) setDeleteTarget(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.vcs.disconnect_confirm_title)}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.vcs.disconnect_confirm_description)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={deleting}>+ {t(($) => $.vcs.disconnect_confirm_cancel)}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleDelete} disabled={deleting}>+ {deleting ? t(($) => $.vcs.disconnecting) : t(($) => $.vcs.disconnect_confirm_action)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++function CopyField({+ label,+ value,+ onCopy,+ copyLabel,+ mono,+}: {+ label: string;+ value: string;+ onCopy: (v: string) => void;+ copyLabel: string;+ mono?: boolean;+}) {+ return (+ <div className="space-y-1.5">+ <Label className="text-xs">{label}</Label>+ <div className="flex items-center gap-2">+ <Input+ readOnly+ value={value}+ className={mono ? "min-w-0 font-mono text-xs" : "min-w-0 text-xs"}+ />+ <Button+ variant="outline"+ size="sm"+ className="shrink-0"+ onClick={() => onCopy(value)}+ title={copyLabel}+ >+ <Copy className="h-3 w-3" />+ </Button>+ </div>+ </div>+ );+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 14e53e3595..f9ab30ce0a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -608,6 +608,22 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busslog.Info("composio integration disabled (COMPOSIO_API_KEY not set)")}+ // VCS at-rest encryption: the box encrypts per-workspace access tokens and+ // webhook secrets for token-based providers (Forgejo / Gitea / GitLab).+ // Without it, connect/webhook handlers return 503 (so a misconfigured+ // self-host never stores plaintext secrets).+ if vcsKey, err := secretbox.LoadKey("MULTICA_VCS_SECRET_KEY"); err == nil {+ box, err := secretbox.New(vcsKey)+ if err != nil {+ slog.Error("vcs: secretbox.New failed; vcs integration disabled", "error", err)+ } else {+ h.VCSSecretBox = box+ slog.Info("vcs integration enabled")+ }+ } else {+ slog.Info("vcs integration disabled (MULTICA_VCS_SECRET_KEY not set)")+ }+if opts.HeartbeatScheduler != nil {h.HeartbeatScheduler = opts.HeartbeatScheduler}@@ -744,6 +760,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// browser redirect; the workspace/agent/initiator are recovered from the// sealed state). It exchanges the code, upserts the install, then bounces// the browser back to Settings → Integrations.+ // VCS webhook for token-based providers (Forgejo / Gitea / GitLab). No Multica+ // auth — authenticated per-connection by the provider's signature scheme;+ // the connection id in the path selects the workspace, provider, and+ // decryption secret.+ r.Post("/api/webhooks/vcs/{connectionId}", h.HandleVCSWebhook)// Stripe webhook (no Multica auth — Stripe signs the raw body// with a shared secret, the multica-cloud upstream verifies. We// only forward the bytes + the Stripe-Signature header; see@@ -869,6 +890,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// the handler strips the management handle and adds a// can_manage hint so the UI can gate connect/disconnect.r.Get("/github/installations", h.ListGitHubInstallations)+ // VCS connections (Forgejo / Gitea / GitLab) — member-visible+ // for the same reason as GitHub installations; connect /+ // disconnect are admin-gated in the group below.+ r.Get("/vcs/connections", h.ListVCSConnections)// Custom runtime profiles — listing/reading is member-visible// (the Runtime page renders for everyone; create/edit/delete// are admin-gated below).@@ -902,6 +927,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Use(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner", "admin"))r.Get("/github/connect", h.GitHubConnect)r.Delete("/github/installations/{installationId}", h.DeleteGitHubInstallation)+ // VCS connect / disconnect / webhook regeneration (admin-only).+ r.Post("/vcs/connections", h.ConnectVCS)+ r.Post("/vcs/connections/{connectionId}/rotate-webhook", h.RotateVCSConnectionWebhook)+ r.Delete("/vcs/connections/{connectionId}", h.DeleteVCSConnection)})// Lark integration. Every endpoint here only requiresdiff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.goindex e97eecc1c0..a01f5b0ae6 100644--- a/server/internal/daemon/config_test.go+++ b/server/internal/daemon/config_test.go@@ -1,6 +1,7 @@package daemonimport (+ "context""os""os/exec""path/filepath"@@ -635,7 +636,11 @@ func TestResolveAgentsViaLoginShell_StripsAliasShadowing(t *testing.T) {// scenario the test couldn't actually set up.t.Setenv("SHELL", sh)t.Setenv("ENV", rc)- probe, err := exec.Command(sh, "-ilc", "alias fakeclaude 2>/dev/null").Output()+ probeCtx, probeCancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer probeCancel()+ probeCmd := exec.CommandContext(probeCtx, sh, "-ilc", "alias fakeclaude 2>/dev/null")+ probeCmd.Stdin = strings.NewReader("")+ probe, err := probeCmd.Output()if err != nil || !strings.Contains(string(probe), "fakeclaude") {t.Skipf("test host's /bin/sh did not load alias from $ENV; cannot simulate shadowing (probe=%q err=%v)", string(probe), err)}diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex 0144ade92b..d6dd3977a4 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -105,6 +105,7 @@ func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {}func TestGetConfigUsesAppURLForSameOriginDaemonSetup(t *testing.T) {+ t.Setenv("MULTICA_PUBLIC_URL", "")t.Setenv("MULTICA_APP_URL", "https://multica.internal.example/")req := httptest.NewRequest(http.MethodGet, "/api/config", nil)@@ -128,6 +129,7 @@ func TestGetConfigUsesAppURLForSameOriginDaemonSetup(t *testing.T) {}func TestGetConfigUsesFrontendOriginForSameOriginDaemonSetup(t *testing.T) {+ t.Setenv("MULTICA_PUBLIC_URL", "")t.Setenv("MULTICA_APP_URL", "")t.Setenv("FRONTEND_ORIGIN", "https://multica.internal.example/")diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex 1f45430af7..e67d50ea2f 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -15,6 +15,7 @@ import ("net/url""os""regexp"+ "sort""strconv""strings""time"@@ -55,7 +56,11 @@ type GitHubInstallationResponse struct {}type GitHubPullRequestResponse struct {- ID string `json:"id"`+ ID string `json:"id"`+ // Provider is the Git provider this PR was mirrored from: "github", "forgejo",+ // "gitea", or "gitlab". The frontend uses it to pick the host icon and+ // label (e.g. GitLab "merge request").+ Provider string `json:"provider"`WorkspaceID string `json:"workspace_id"`RepoOwner string `json:"repo_owner"`RepoName string `json:"repo_name"`@@ -127,6 +132,7 @@ func githubInstallationToBroadcast(i db.GithubInstallation) GitHubInstallationRefunc githubPullRequestToResponse(p db.GithubPullRequest) GitHubPullRequestResponse {return GitHubPullRequestResponse{ID: uuidToString(p.ID),+ Provider: "github",WorkspaceID: uuidToString(p.WorkspaceID),RepoOwner: p.RepoOwner,RepoName: p.RepoName,@@ -155,6 +161,7 @@ func githubPullRequestToResponse(p db.GithubPullRequest) GitHubPullRequestResponfunc issuePullRequestRowToResponse(p db.ListPullRequestsByIssueRow) GitHubPullRequestResponse {return GitHubPullRequestResponse{ID: uuidToString(p.ID),+ Provider: "github",WorkspaceID: uuidToString(p.WorkspaceID),RepoOwner: p.RepoOwner,RepoName: p.RepoName,@@ -571,6 +578,21 @@ func (h *Handler) ListPullRequestsForIssue(w http.ResponseWriter, r *http.Requesfor _, row := range rows {out = append(out, issuePullRequestRowToResponse(row))}+ // PRs from token-based providers (Forgejo / Gitea / GitLab) share the same+ // card list. They live in their own provider-tagged tables, so they merge+ // in here mapped to the same response shape; the combined list is re-sorted+ // newest-first.+ vcsRows, err := h.Queries.ListVCSPullRequestsByIssue(r.Context(), issue.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list pull requests")+ return+ }+ for _, row := range vcsRows {+ out = append(out, vcsPullRequestRowToResponse(row))+ }+ sort.SliceStable(out, func(i, j int) bool {+ return out[i].PRCreatedAt > out[j].PRCreatedAt+ })writeJSON(w, http.StatusOK, map[string]any{"pull_requests": out})}@@ -976,7 +998,10 @@ func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtypeif issue.Status == "done" || issue.Status == "cancelled" {continue}- counts, err := h.Queries.GetIssuePullRequestCloseAggregate(ctx, issue.ID)+ // Combined across providers: an issue may also carry a still-open+ // self-hosted VCS PR, which must block auto-advance here just as+ // an open GitHub PR blocks it on the VCS webhook path.+ counts, err := h.Queries.GetIssueCombinedPullRequestCloseAggregate(ctx, issue.ID)if err != nil {slog.Warn("github: count linked pr states failed", "err", err, "issue_id", uuidToString(issue.ID))continuediff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 33543a12ea..a3c9337b9b 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -31,6 +31,7 @@ import ("github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/internal/util/secretbox"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/featureflag""github.com/multica-ai/multica/server/pkg/llm"@@ -228,7 +229,14 @@ type Handler struct {// Config); when unconfigured its Enabled() reports false and callers fall// back silently.LLM *llm.Client- cfg Config+ // VCSSecretBox encrypts/decrypts per-workspace Git provider access tokens and+ // webhook secrets at rest (Forgejo / Gitea / GitLab). Nil when+ // MULTICA_VCS_SECRET_KEY is unset; the connect/webhook handlers return 503+ // in that case so a misconfigured self-host deployment surfaces a clear+ // error rather than silently storing plaintext. Wired in+ // cmd/server/router.go after New.+ VCSSecretBox *secretbox.Box+ cfg Config}func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner, analyticsClient analytics.Client, cfg Config, daemonHubs ...*daemonws.Hub) *Handler {diff --git a/server/internal/handler/vcs.go b/server/internal/handler/vcs.gonew file mode 100644index 0000000000..d17e9b3c25--- /dev/null+++ b/server/internal/handler/vcs.go@@ -0,0 +1,306 @@+package handler++import (+ "crypto/rand"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "errors"+ "net/http"+ "net/url"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/integrations/vcs"+ "github.com/multica-ai/multica/server/internal/middleware"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// ── Response shapes ─────────────────────────────────────────────────────────++// VCSConnectionResponse is the JSON shape for a stored Git provider connection.+// Secrets are never included; the webhook secret is returned exactly once at+// create time via VCSConnectResponse.+type VCSConnectionResponse struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ Provider string `json:"provider"`+ InstanceURL string `json:"instance_url"`+ AccountLogin string `json:"account_login"`+ WebhookURL string `json:"webhook_url"`+ WebhookPath string `json:"webhook_path"`+ CreatedAt string `json:"created_at"`+}++// VCSConnectResponse embeds the stored connection plus the one-time plaintext+// webhook secret the user must paste into the provider (the HMAC secret for+// Forgejo/Gitea, the X-Gitlab-Token value for GitLab). Not retrievable after.+type VCSConnectResponse struct {+ VCSConnectionResponse+ WebhookSecret string `json:"webhook_secret"`+}++const vcsWebhookPathPrefix = "/api/webhooks/vcs/"++func (h *Handler) isVCSConfigured() bool { return h.VCSSecretBox != nil }++func (h *Handler) vcsWebhookPath(connID string) string { return vcsWebhookPathPrefix + connID }++func (h *Handler) vcsWebhookURL(connID string) string {+ base := strings.TrimRight(h.cfg.PublicURL, "/")+ if base == "" {+ return ""+ }+ return base + h.vcsWebhookPath(connID)+}++func (h *Handler) vcsConnectionToResponse(c db.VcsConnection) VCSConnectionResponse {+ id := uuidToString(c.ID)+ return VCSConnectionResponse{+ ID: id,+ WorkspaceID: uuidToString(c.WorkspaceID),+ Provider: c.Provider,+ InstanceURL: c.InstanceUrl,+ AccountLogin: c.AccountLogin,+ WebhookURL: h.vcsWebhookURL(id),+ WebhookPath: h.vcsWebhookPath(id),+ CreatedAt: timestampToString(c.CreatedAt),+ }+}++func (h *Handler) sealVCSSecret(plaintext string) (string, error) {+ sealed, err := h.VCSSecretBox.Seal([]byte(plaintext))+ if err != nil {+ return "", err+ }+ return base64.StdEncoding.EncodeToString(sealed), nil+}++func (h *Handler) openVCSSecret(enc string) (string, error) {+ if enc == "" {+ return "", nil+ }+ ciphertext, err := base64.StdEncoding.DecodeString(enc)+ if err != nil {+ return "", err+ }+ plaintext, err := h.VCSSecretBox.Open(ciphertext)+ if err != nil {+ return "", err+ }+ return string(plaintext), nil+}++// ── Handlers ────────────────────────────────────────────────────────────────++// ListVCSConnections (GET /workspaces/{id}/vcs/connections) is member-visible;+// connect/disconnect are admin-gated by the router. No secrets returned.+func (h *Handler) ListVCSConnections(w http.ResponseWriter, r *http.Request) {+ workspaceID := chi.URLParam(r, "id")+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ member, _ := middleware.MemberFromContext(r.Context())+ canManage := roleAllowed(member.Role, "owner", "admin")++ rows, err := h.Queries.ListVCSConnectionsByWorkspace(r.Context(), wsUUID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list connections")+ return+ }+ out := make([]VCSConnectionResponse, 0, len(rows))+ for _, row := range rows {+ out = append(out, h.vcsConnectionToResponse(row))+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "connections": out,+ "configured": h.isVCSConfigured(),+ "can_manage": canManage,+ })+}++type connectVCSRequest struct {+ Provider string `json:"provider"`+ InstanceURL string `json:"instance_url"`+ AccessToken string `json:"access_token"`+}++// ConnectVCS (POST /workspaces/{id}/vcs/connections) validates the supplied+// instance URL + token against the live instance for the chosen provider, mints a+// webhook secret, stores both secrets encrypted, and returns the connection+// plus the one-time webhook secret. Reconnecting the same instance rotates it.+func (h *Handler) ConnectVCS(w http.ResponseWriter, r *http.Request) {+ workspaceID := chi.URLParam(r, "id")+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ if !h.isVCSConfigured() {+ writeError(w, http.StatusServiceUnavailable, "vcs integration not configured (MULTICA_VCS_SECRET_KEY unset)")+ return+ }++ var req connectVCSRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ provider, ok := vcs.For(req.Provider)+ if !ok {+ writeError(w, http.StatusBadRequest, "unsupported provider")+ return+ }+ instanceURL := vcs.NormalizeInstanceURL(req.InstanceURL)+ token := strings.TrimSpace(req.AccessToken)+ if instanceURL == "" || token == "" {+ writeError(w, http.StatusBadRequest, "instance_url and access_token are required")+ return+ }+ parsed, err := url.Parse(instanceURL)+ if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {+ writeError(w, http.StatusBadRequest, "instance_url must be an absolute http(s) URL")+ return+ }++ account, err := provider.ValidateToken(r.Context(), instanceURL, token)+ if err != nil {+ if errors.Is(err, vcs.ErrUnauthorized) {+ writeError(w, http.StatusBadRequest, "the provider rejected the access token")+ return+ }+ writeError(w, http.StatusBadGateway, "could not reach the provider instance")+ return+ }++ webhookSecret, err := newVCSWebhookSecret()+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to mint webhook secret")+ return+ }+ tokenEnc, err := h.sealVCSSecret(token)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to encrypt token")+ return+ }+ secretEnc, err := h.sealVCSSecret(webhookSecret)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to encrypt webhook secret")+ return+ }++ var connectedBy pgtype.UUID+ if member, ok := middleware.MemberFromContext(r.Context()); ok {+ connectedBy = member.UserID+ }++ conn, err := h.Queries.UpsertVCSConnection(r.Context(), db.UpsertVCSConnectionParams{+ WorkspaceID: wsUUID,+ Provider: string(provider.Kind()),+ InstanceUrl: instanceURL,+ AccountLogin: account.Login,+ AccessTokenEncrypted: tokenEnc,+ WebhookSecretEncrypted: secretEnc,+ ConnectedByID: connectedBy,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to save connection")+ return+ }++ resp := h.vcsConnectionToResponse(conn)+ h.publish(protocol.EventVCSConnectionCreated, workspaceID, "system", "", map[string]any{"id": resp.ID})+ writeJSON(w, http.StatusOK, VCSConnectResponse{+ VCSConnectionResponse: resp,+ WebhookSecret: webhookSecret,+ })+}++// DeleteVCSConnection (DELETE /workspaces/{id}/vcs/connections/{connectionId}).+func (h *Handler) DeleteVCSConnection(w http.ResponseWriter, r *http.Request) {+ workspaceID := chi.URLParam(r, "id")+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "connectionId"), "connection id")+ if !ok {+ return+ }+ if err := h.Queries.DeleteVCSConnection(r.Context(), db.DeleteVCSConnectionParams{+ ID: idUUID,+ WorkspaceID: wsUUID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to remove connection")+ return+ }+ h.publish(protocol.EventVCSConnectionDeleted, workspaceID, "system", "", map[string]any{+ "id": chi.URLParam(r, "connectionId"),+ })+ w.WriteHeader(http.StatusNoContent)+}++// RotateVCSConnectionWebhook (POST /workspaces/{id}/vcs/connections/{connectionId}/rotate-webhook)+// generates a fresh webhook secret for an existing VCS connection, stores it encrypted,+// and returns the connection plus the one-time plaintext secret.+func (h *Handler) RotateVCSConnectionWebhook(w http.ResponseWriter, r *http.Request) {+ workspaceID := chi.URLParam(r, "id")+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ connID := chi.URLParam(r, "connectionId")+ connUUID, ok := parseUUIDOrBadRequest(w, connID, "connection id")+ if !ok {+ return+ }+ if !h.isVCSConfigured() {+ writeError(w, http.StatusServiceUnavailable, "vcs integration not configured (MULTICA_VCS_SECRET_KEY unset)")+ return+ }++ conn, err := h.Queries.GetVCSConnectionByID(r.Context(), connUUID)+ if err != nil || uuidToString(conn.WorkspaceID) != uuidToString(wsUUID) {+ writeError(w, http.StatusNotFound, "vcs connection not found")+ return+ }++ webhookSecret, err := newVCSWebhookSecret()+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to mint webhook secret")+ return+ }+ secretEnc, err := h.sealVCSSecret(webhookSecret)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to encrypt webhook secret")+ return+ }++ updated, err := h.Queries.RotateVCSConnectionWebhookSecret(r.Context(), db.RotateVCSConnectionWebhookSecretParams{+ ID: connUUID,+ WorkspaceID: wsUUID,+ WebhookSecretEncrypted: secretEnc,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to rotate webhook secret")+ return+ }++ resp := h.vcsConnectionToResponse(updated)+ h.publish(protocol.EventVCSConnectionCreated, workspaceID, "system", "", map[string]any{"id": resp.ID})+ writeJSON(w, http.StatusOK, VCSConnectResponse{+ VCSConnectionResponse: resp,+ WebhookSecret: webhookSecret,+ })+}++// newVCSWebhookSecret returns a 32-byte random secret as hex (64 chars).+func newVCSWebhookSecret() (string, error) {+ b := make([]byte, 32)+ if _, err := rand.Read(b); err != nil {+ return "", err+ }+ return hex.EncodeToString(b), nil+}diff --git a/server/internal/handler/vcs_webhook.go b/server/internal/handler/vcs_webhook.gonew file mode 100644index 0000000000..45a6ebf3f7--- /dev/null+++ b/server/internal/handler/vcs_webhook.go@@ -0,0 +1,308 @@+package handler++import (+ "context"+ "errors"+ "io"+ "log/slog"+ "net/http"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/integrations/vcs"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// ── Response mappers ────────────────────────────────────────────────────────++// vcsPullRequestToResponse maps a stored VCS PR onto the shared PR response+// shape for single-PR webhook broadcasts (no aggregated check counts; the+// frontend re-queries the issue's PR list for fresh counts).+func vcsPullRequestToResponse(p db.VcsPullRequest) GitHubPullRequestResponse {+ return GitHubPullRequestResponse{+ ID: uuidToString(p.ID),+ Provider: p.Provider,+ WorkspaceID: uuidToString(p.WorkspaceID),+ RepoOwner: p.RepoOwner,+ RepoName: p.RepoName,+ Number: p.PrNumber,+ Title: p.Title,+ State: p.State,+ HtmlURL: p.HtmlUrl,+ Branch: textToPtr(p.Branch),+ AuthorLogin: textToPtr(p.AuthorLogin),+ AuthorAvatarURL: textToPtr(p.AuthorAvatarUrl),+ MergedAt: timestampToPtr(p.MergedAt),+ ClosedAt: timestampToPtr(p.ClosedAt),+ PRCreatedAt: timestampToString(p.PrCreatedAt),+ PRUpdatedAt: timestampToString(p.PrUpdatedAt),+ MergeableState: nil,+ ChecksConclusion: nil,+ Additions: p.Additions,+ Deletions: p.Deletions,+ ChangedFiles: p.ChangedFiles,+ }+}++// vcsPullRequestRowToResponse maps an issue's PR-list row, which carries the+// aggregated commit-status counts, onto the shared response shape.+func vcsPullRequestRowToResponse(p db.ListVCSPullRequestsByIssueRow) GitHubPullRequestResponse {+ return GitHubPullRequestResponse{+ ID: uuidToString(p.ID),+ Provider: p.Provider,+ WorkspaceID: uuidToString(p.WorkspaceID),+ RepoOwner: p.RepoOwner,+ RepoName: p.RepoName,+ Number: p.PrNumber,+ Title: p.Title,+ State: p.State,+ HtmlURL: p.HtmlUrl,+ Branch: textToPtr(p.Branch),+ AuthorLogin: textToPtr(p.AuthorLogin),+ AuthorAvatarURL: textToPtr(p.AuthorAvatarUrl),+ MergedAt: timestampToPtr(p.MergedAt),+ ClosedAt: timestampToPtr(p.ClosedAt),+ PRCreatedAt: timestampToString(p.PrCreatedAt),+ PRUpdatedAt: timestampToString(p.PrUpdatedAt),+ MergeableState: nil,+ ChecksConclusion: aggregateChecksConclusion(p.ChecksFailed, p.ChecksPassed, p.ChecksPending, p.ChecksTotal),+ ChecksPassed: p.ChecksPassed,+ ChecksFailed: p.ChecksFailed,+ ChecksPending: p.ChecksPending,+ Additions: p.Additions,+ Deletions: p.Deletions,+ ChangedFiles: p.ChangedFiles,+ }+}++// ── Webhook ─────────────────────────────────────────────────────────────────++// HandleVCSWebhook (POST /api/webhooks/vcs/{connectionId}) authenticates and+// mirrors webhooks from any token-based Git provider. The connection id in the path+// selects the workspace, the provider, and the decryption secret; the provider+// adapter handles the provider-specific signature scheme, event header, and+// payload shape, returning normalized events to the shared mirror logic below.+func (h *Handler) HandleVCSWebhook(w http.ResponseWriter, r *http.Request) {+ if !h.isVCSConfigured() {+ writeError(w, http.StatusServiceUnavailable, "vcs webhooks not configured")+ return+ }+ connUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "connectionId"), "connection id")+ if !ok {+ return+ }+ body, err := io.ReadAll(io.LimitReader(r.Body, 10<<20)) // 10 MiB cap+ if err != nil {+ writeError(w, http.StatusBadRequest, "read body failed")+ return+ }++ conn, err := h.Queries.GetVCSConnectionByID(r.Context(), connUUID)+ if err != nil {+ if !errors.Is(err, pgx.ErrNoRows) {+ slog.Warn("vcs: lookup connection failed", "err", err)+ }+ writeError(w, http.StatusNotFound, "unknown connection")+ return+ }+ provider, ok := vcs.For(conn.Provider)+ if !ok {+ slog.Error("vcs: connection has unknown provider", "provider", conn.Provider)+ writeError(w, http.StatusInternalServerError, "unknown provider")+ return+ }++ secret, err := h.openVCSSecret(conn.WebhookSecretEncrypted)+ if err != nil {+ slog.Error("vcs: decrypt webhook secret failed", "err", err)+ writeError(w, http.StatusInternalServerError, "secret error")+ return+ }+ if !provider.VerifySignature(secret, r.Header, body) {+ writeError(w, http.StatusUnauthorized, "invalid signature")+ return+ }++ switch provider.EventKind(r.Header) {+ case vcs.EventPullRequest:+ if pr, err := provider.ParsePullRequest(body); err != nil {+ slog.Warn("vcs: bad pull_request payload", "provider", conn.Provider, "err", err)+ } else {+ h.mirrorVCSPullRequest(r.Context(), conn, pr)+ }+ case vcs.EventCIStatus:+ if st, err := provider.ParseCIStatus(body); err != nil {+ slog.Warn("vcs: bad status payload", "provider", conn.Provider, "err", err)+ } else {+ h.mirrorVCSCIStatus(r.Context(), conn, st)+ }+ default:+ // Acknowledge unmodelled events so the provider doesn't flag the hook.+ }+ w.WriteHeader(http.StatusAccepted)+}++func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnection, ev vcs.PullRequestEvent) {+ if ev.RepoOwner == "" || ev.RepoName == "" || ev.Number == 0 {+ slog.Warn("vcs: pull_request missing repo identity", "provider", conn.Provider)+ return+ }++ pr, err := h.Queries.UpsertVCSPullRequest(ctx, db.UpsertVCSPullRequestParams{+ WorkspaceID: conn.WorkspaceID,+ ConnectionID: conn.ID,+ Provider: conn.Provider,+ RepoOwner: ev.RepoOwner,+ RepoName: ev.RepoName,+ PrNumber: ev.Number,+ Title: ev.Title,+ State: ev.State,+ HtmlUrl: ev.HTMLURL,+ Branch: ptrToText(strPtrOrNil(ev.Branch)),+ AuthorLogin: ptrToText(strPtrOrNil(ev.AuthorLogin)),+ AuthorAvatarUrl: ptrToText(strPtrOrNil(ev.AuthorAvatarURL)),+ MergedAt: parseGHTime(ev.MergedAt),+ ClosedAt: parseGHTime(ev.ClosedAt),+ PrCreatedAt: parseGHTimeRequired(ev.CreatedAt),+ PrUpdatedAt: parseGHTimeRequired(ev.UpdatedAt),+ Additions: ev.Additions,+ Deletions: ev.Deletions,+ ChangedFiles: ev.ChangedFiles,+ HeadSha: ev.HeadSHA,+ })+ if err != nil {+ slog.Warn("vcs: upsert pr failed", "err", err)+ return+ }++ // Out-of-order guard for the link metadata. UpsertVCSPullRequest keeps the+ // newer persisted row on a stale redelivery, so `pr` may reflect a newer+ // event than this `ev`. Everything the link write derives below —+ // close_intent, reference_only, preserveCloseIntent — comes from `ev`, so+ // rewriting the link from a stale event would corrupt what the newer event+ // already set (e.g. a redelivered older "opened" event flipping a merged+ // PR's link back to reference_only, blocking auto-advance). If the persisted+ // row is strictly newer than this event, the newer event already linked and+ // published — stop here. (An event with no usable timestamp falls back to+ // now(), which is never strictly after the stored value, so it proceeds.)+ evUpdatedAt := parseGHTimeRequired(ev.UpdatedAt)+ if pr.PrUpdatedAt.Valid && evUpdatedAt.Valid && pr.PrUpdatedAt.Time.After(evUpdatedAt.Time) {+ return+ }++ workspaceID := uuidToString(conn.WorkspaceID)+ resp := vcsPullRequestToResponse(pr)++ // Auto-link to issues by identifiers in title/body/branch. Connecting a+ // a provider is the opt-in, so there is no separate per-workspace flag. The+ // issue-side machinery is shared with GitHub.+ linkedIssueIDs := make([]string, 0)+ idents := extractIdentifiers(ev.Title, ev.Body, ev.Branch)+ closingIdents := map[string]struct{}{}+ for _, c := range extractClosingIdentifiers(ev.Title, ev.Body) {+ closingIdents[c] = struct{}{}+ }+ // qualifyingIdents genuinely tie this PR to an issue: a title prefix, a+ // branch-name reference, or a body closing keyword. An identifier matched+ // ONLY by a bare body mention is reference_only — it links (so the PR shows+ // in history) but is hidden from the issue PR list and excluded from the+ // close aggregate, so a drive-by "Related MUL-1" neither looks like a+ // working PR nor blocks a genuine Closes sibling from advancing the issue.+ // Mirrors the GitHub path (MUL-3739); branch is deliberately excluded from+ // the closing-keyword scan there and here.+ qualifyingIdents := map[string]struct{}{}+ for _, id := range extractIdentifiers(ev.Title, ev.Branch) {+ qualifyingIdents[id] = struct{}{}+ }+ for c := range closingIdents {+ qualifyingIdents[c] = struct{}{}+ }+ // Freeze close_intent once the terminal merge/close event has arrived.+ preserveCloseIntent := !ev.Terminal() && (ev.State == "merged" || ev.State == "closed")+ prefix := h.getIssuePrefix(ctx, conn.WorkspaceID)+ reevalIssues := make([]db.Issue, 0, len(idents))+ for _, id := range idents {+ issue, ok := h.lookupIssueByIdentifier(ctx, conn.WorkspaceID, prefix, id)+ if !ok {+ continue+ }+ _, declared := closingIdents[id]+ closeIntent := declared && !preserveCloseIntent+ _, qualifies := qualifyingIdents[id]+ referenceOnly := !qualifies+ if err := h.Queries.LinkIssueToVCSPullRequest(ctx, db.LinkIssueToVCSPullRequestParams{+ IssueID: issue.ID,+ PullRequestID: pr.ID,+ CloseIntent: closeIntent,+ ReferenceOnly: referenceOnly,+ PreserveCloseIntent: preserveCloseIntent,+ LinkedByType: strToText("system"),+ LinkedByID: pgtype.UUID{},+ }); err != nil {+ slog.Warn("vcs: link failed", "err", err)+ continue+ }+ linkedIssueIDs = append(linkedIssueIDs, uuidToString(issue.ID))+ reevalIssues = append(reevalIssues, issue)+ }++ if ev.State == "merged" || ev.State == "closed" {+ for _, issue := range reevalIssues {+ if issue.Status == "done" || issue.Status == "cancelled" {+ continue+ }+ counts, err := h.Queries.GetIssueCombinedPullRequestCloseAggregate(ctx, issue.ID)+ if err != nil {+ slog.Warn("vcs: count linked pr states failed", "err", err, "issue_id", uuidToString(issue.ID))+ continue+ }+ if counts.OpenCount == 0 && counts.MergedWithCloseIntentCount > 0 {+ h.advanceIssueToDone(ctx, issue, workspaceID)+ }+ }+ }++ h.publish(protocol.EventPullRequestUpdated, workspaceID, "system", "", map[string]any{+ "pull_request": resp,+ "linked_issue_ids": linkedIssueIDs,+ })+}++func (h *Handler) mirrorVCSCIStatus(ctx context.Context, conn db.VcsConnection, ev vcs.CIStatusEvent) {+ if ev.SHA == "" || ev.State == "" {+ return+ }+ // Use the provider's own event timestamp so UpsertVCSCommitStatus's+ // monotonic guard has something real to compare — writing time.Now() here+ // made the guard always true, so an out-of-order redelivery could regress a+ // status. Falls back to now() only when the payload carried no timestamp.+ if err := h.Queries.UpsertVCSCommitStatus(ctx, db.UpsertVCSCommitStatusParams{+ ConnectionID: conn.ID,+ Sha: ev.SHA,+ Context: ev.Context,+ State: ev.State,+ TargetUrl: ptrToText(strPtrOrNil(ev.TargetURL)),+ Description: ptrToText(strPtrOrNil(ev.Description)),+ UpdatedAt: parseGHTimeRequired(ev.UpdatedAt),+ }); err != nil {+ slog.Warn("vcs: upsert commit status failed", "err", err)+ return+ }++ issueIDs, err := h.Queries.ListIssueIDsForVCSPRHead(ctx, db.ListIssueIDsForVCSPRHeadParams{+ ConnectionID: conn.ID,+ HeadSha: ev.SHA,+ })+ if err != nil {+ slog.Warn("vcs: lookup issues for status failed", "err", err)+ return+ }+ workspaceID := uuidToString(conn.WorkspaceID)+ for _, issueID := range issueIDs {+ h.publish(protocol.EventPullRequestUpdated, workspaceID, "system", "", map[string]any{+ "issue_id": uuidToString(issueID),+ })+ }+}diff --git a/server/internal/handler/vcs_webhook_test.go b/server/internal/handler/vcs_webhook_test.gonew file mode 100644index 0000000000..67078e773a--- /dev/null+++ b/server/internal/handler/vcs_webhook_test.go@@ -0,0 +1,526 @@+package handler++import (+ "bytes"+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func withVCSBox(t *testing.T) *secretbox.Box {+ t.Helper()+ box, err := secretbox.New(bytes.Repeat([]byte("k"), 32))+ if err != nil {+ t.Fatalf("secretbox.New: %v", err)+ }+ prev := testHandler.VCSSecretBox+ testHandler.VCSSecretBox = box+ t.Cleanup(func() { testHandler.VCSSecretBox = prev })+ return box+}++const vcsTestSecret = "vcs-webhook-secret"++func seedVCSConnection(t *testing.T, ctx context.Context, box *secretbox.Box, provider, instanceURL string) string {+ t.Helper()+ sealed, err := box.Seal([]byte(vcsTestSecret))+ if err != nil {+ t.Fatalf("seal: %v", err)+ }+ tokenSealed, _ := box.Seal([]byte("tok"))+ conn, err := testHandler.Queries.UpsertVCSConnection(ctx, db.UpsertVCSConnectionParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ Provider: provider,+ InstanceUrl: instanceURL,+ AccountLogin: "acme",+ AccessTokenEncrypted: base64.StdEncoding.EncodeToString(tokenSealed),+ WebhookSecretEncrypted: base64.StdEncoding.EncodeToString(sealed),+ ConnectedByID: pgtype.UUID{},+ })+ if err != nil {+ t.Fatalf("UpsertVCSConnection: %v", err)+ }+ return uuidToString(conn.ID)+}++func cleanupVCS(ctx context.Context, issueID string) {+ testPool.Exec(ctx, `DELETE FROM issue_vcs_pull_request WHERE issue_id = $1`, issueID)+ testPool.Exec(ctx, `DELETE FROM vcs_commit_status cs USING vcs_connection c WHERE cs.connection_id = c.id AND c.workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM vcs_pull_request WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM vcs_connection WHERE workspace_id = $1`, testWorkspaceID)+ if issueID != "" {+ testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, issueID)+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)+ }+}++func newVCSIssue(t *testing.T, title string) IssueResponse {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": title, "status": "in_progress",+ })+ testHandler.CreateIssue(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())+ }+ var created IssueResponse+ json.NewDecoder(w.Body).Decode(&created)+ return created+}++func vcsWebhookReq(connID string, headers map[string]string, raw []byte) *http.Request {+ req := httptest.NewRequest("POST", "/api/webhooks/vcs/"+connID, bytes.NewReader(raw))+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("connectionId", connID)+ return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))+}++func giteaSig(raw []byte) string {+ mac := hmac.New(sha256.New, []byte(vcsTestSecret))+ mac.Write(raw)+ return hex.EncodeToString(mac.Sum(nil))+}++func TestVCSWebhook_ForgejoMirrorsAndCloses(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")+ issue := newVCSIssue(t, "Forgejo PR auto-merge")+ t.Cleanup(func() { cleanupVCS(ctx, issue.ID) })++ raw, _ := json.Marshal(map[string]any{+ "action": "closed",+ "pull_request": map[string]any{+ "number": 7, "html_url": "https://forgejo.test/acme/widget/pulls/7",+ "title": "Fix login " + issue.Identifier, "body": "Closes " + issue.Identifier,+ "state": "closed", "merged": true,+ "merged_at": "2026-04-29T00:00:00Z", "closed_at": "2026-04-29T00:00:00Z",+ "created_at": "2026-04-28T00:00:00Z", "updated_at": "2026-04-29T00:00:00Z",+ "head": map[string]any{"ref": "fix/login", "sha": "abc"},+ "user": map[string]any{"username": "octo"},+ },+ "repository": map[string]any{"name": "widget", "owner": map[string]any{"username": "acme"}},+ })+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": giteaSig(raw),+ }, raw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("expected 202, got %d (%s)", w.Code, w.Body.String())+ }++ rows, err := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issue.ID))+ if err != nil {+ t.Fatalf("ListVCSPullRequestsByIssue: %v", err)+ }+ if len(rows) != 1 || rows[0].State != "merged" || rows[0].Provider != "forgejo" {+ t.Fatalf("unexpected rows: %+v", rows)+ }+ updated, _ := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID))+ if updated.Status != "done" {+ t.Errorf("expected issue done, got %q", updated.Status)+ }+}++// A bare body mention ("Related MUL-X", no closing keyword, not in title or+// branch) must link reference_only: excluded from the issue PR list and from+// the close gate, so it neither shows as a working PR nor blocks a genuine+// Closes sibling from advancing the issue. Mirrors the GitHub qualifying rule.+func TestVCSWebhook_ReferenceOnlyExcludedAndNonBlocking(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")+ issue := newVCSIssue(t, "Reference-only mention")+ t.Cleanup(func() { cleanupVCS(ctx, issue.ID) })++ // PR #7: OPEN, mentions the issue only in the body with no closing keyword,+ // generic title/branch → reference_only.+ refRaw, _ := json.Marshal(map[string]any{+ "action": "opened",+ "pull_request": map[string]any{+ "number": 7, "html_url": "https://forgejo.test/acme/widget/pulls/7",+ "title": "Update docs", "body": "Related " + issue.Identifier,+ "state": "open", "merged": false,+ "created_at": "2026-04-28T00:00:00Z", "updated_at": "2026-04-28T00:00:00Z",+ "head": map[string]any{"ref": "docs", "sha": "ref7"},+ "user": map[string]any{"username": "octo"},+ },+ "repository": map[string]any{"name": "widget", "owner": map[string]any{"username": "acme"}},+ })+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": giteaSig(refRaw),+ }, refRaw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("ref PR: expected 202, got %d (%s)", w.Code, w.Body.String())+ }++ // The link exists but is reference_only, so it is hidden from the PR list.+ var referenceOnly bool+ if err := testPool.QueryRow(ctx,+ `SELECT reference_only FROM issue_vcs_pull_request WHERE issue_id = $1`,+ issue.ID).Scan(&referenceOnly); err != nil {+ t.Fatalf("select reference_only: %v", err)+ }+ if !referenceOnly {+ t.Fatalf("body-only mention should be reference_only")+ }+ if rows, err := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issue.ID)); err != nil {+ t.Fatalf("list: %v", err)+ } else if len(rows) != 0 {+ t.Fatalf("reference_only PR must be excluded from the list, got %d rows", len(rows))+ }++ // PR #8: MERGED with a title reference + Closes keyword → qualifying,+ // close_intent. The still-open reference_only PR #7 must NOT block advance.+ closeRaw, _ := json.Marshal(map[string]any{+ "action": "closed",+ "pull_request": map[string]any{+ "number": 8, "html_url": "https://forgejo.test/acme/widget/pulls/8",+ "title": "Fix " + issue.Identifier, "body": "Closes " + issue.Identifier,+ "state": "closed", "merged": true,+ "merged_at": "2026-04-29T00:00:00Z", "closed_at": "2026-04-29T00:00:00Z",+ "created_at": "2026-04-28T00:00:00Z", "updated_at": "2026-04-29T00:00:00Z",+ "head": map[string]any{"ref": "fix", "sha": "cls8"},+ "user": map[string]any{"username": "octo"},+ },+ "repository": map[string]any{"name": "widget", "owner": map[string]any{"username": "acme"}},+ })+ w = httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": giteaSig(closeRaw),+ }, closeRaw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("close PR: expected 202, got %d (%s)", w.Code, w.Body.String())+ }++ updated, _ := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID))+ if updated.Status != "done" {+ t.Errorf("issue should advance despite the open reference_only PR, got %q", updated.Status)+ }+}++// The close gate must span providers: an issue with an OPEN GitHub PR and a+// MERGED close-intent VCS PR must report open_count > 0, so neither webhook+// auto-advances it out from under the still-open GitHub work (and vice versa).+func TestCombinedCloseAggregateSpansProviders(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "gitlab", "https://gitlab.test")+ issue := newVCSIssue(t, "Cross-provider close gate")+ now := pgtype.Timestamptz{Time: time.Now().UTC(), Valid: true}+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, issue.ID)+ testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE workspace_id = $1`, testWorkspaceID)+ cleanupVCS(ctx, issue.ID)+ })++ // OPEN GitHub PR linked to the issue (installation_id carries no FK).+ ghPR, err := testHandler.Queries.UpsertGitHubPullRequest(ctx, db.UpsertGitHubPullRequestParams{+ WorkspaceID: parseUUID(testWorkspaceID), InstallationID: 987654,+ RepoOwner: "acme", RepoName: "gh", PrNumber: 3,+ Title: "WIP " + issue.Identifier, State: "open",+ HtmlUrl: "https://github.com/acme/gh/pull/3",+ PrCreatedAt: now, PrUpdatedAt: now, HeadSha: "ghsha",+ })+ if err != nil {+ t.Fatalf("UpsertGitHubPullRequest: %v", err)+ }+ if err := testHandler.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{+ IssueID: parseUUID(issue.ID), PullRequestID: ghPR.ID, CloseIntent: false,+ ReferenceOnly: false, LinkedByType: strToText("system"),+ }); err != nil {+ t.Fatalf("LinkIssueToPullRequest: %v", err)+ }++ // MERGED close-intent VCS PR linked to the same issue.+ vcsPR, err := testHandler.Queries.UpsertVCSPullRequest(ctx, db.UpsertVCSPullRequestParams{+ WorkspaceID: parseUUID(testWorkspaceID), ConnectionID: parseUUID(connID),+ Provider: "gitlab", RepoOwner: "acme", RepoName: "gl", PrNumber: 4,+ Title: "Fix " + issue.Identifier, State: "merged",+ HtmlUrl: "https://gitlab.test/acme/gl/-/merge_requests/4",+ PrCreatedAt: now, PrUpdatedAt: now, HeadSha: "glsha",+ })+ if err != nil {+ t.Fatalf("UpsertVCSPullRequest: %v", err)+ }+ if err := testHandler.Queries.LinkIssueToVCSPullRequest(ctx, db.LinkIssueToVCSPullRequestParams{+ IssueID: parseUUID(issue.ID), PullRequestID: vcsPR.ID, CloseIntent: true,+ ReferenceOnly: false, LinkedByType: strToText("system"),+ }); err != nil {+ t.Fatalf("LinkIssueToVCSPullRequest: %v", err)+ }++ counts, err := testHandler.Queries.GetIssueCombinedPullRequestCloseAggregate(ctx, parseUUID(issue.ID))+ if err != nil {+ t.Fatalf("GetIssueCombinedPullRequestCloseAggregate: %v", err)+ }+ if counts.OpenCount != 1 {+ t.Errorf("open_count = %d, want 1 (the open GitHub PR must be seen)", counts.OpenCount)+ }+ if counts.MergedWithCloseIntentCount != 1 {+ t.Errorf("merged_with_close_intent_count = %d, want 1 (the VCS MR)", counts.MergedWithCloseIntentCount)+ }+}++// DeleteIssue's VCS-link cleanup must honour the same workspace guard as the+// issue delete: passing a foreign issue_id with a mismatched workspace_id must+// be a complete no-op, not silently drop the victim tenant's link rows (#1661).+func TestDeleteIssue_VCSLinkCleanupIsWorkspaceScoped(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")+ issue := newVCSIssue(t, "Tenant-scoped delete")+ t.Cleanup(func() { cleanupVCS(ctx, issue.ID) })++ raw, _ := json.Marshal(map[string]any{+ "action": "opened",+ "pull_request": map[string]any{+ "number": 7, "html_url": "https://forgejo.test/acme/widget/pulls/7",+ "title": "Fix " + issue.Identifier, "state": "open", "merged": false,+ "created_at": "2026-05-01T00:00:00Z", "updated_at": "2026-05-01T00:00:00Z",+ "head": map[string]any{"ref": "fix", "sha": "abc"},+ "user": map[string]any{"username": "octo"},+ },+ "repository": map[string]any{"name": "widget", "owner": map[string]any{"username": "acme"}},+ })+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": giteaSig(raw),+ }, raw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("seed PR: %d %s", w.Code, w.Body.String())+ }++ linkCount := func() int {+ var n int+ testPool.QueryRow(ctx, `SELECT count(*) FROM issue_vcs_pull_request WHERE issue_id = $1`, issue.ID).Scan(&n)+ return n+ }+ if linkCount() != 1 {+ t.Fatalf("expected 1 link after seed, got %d", linkCount())+ }++ // Mismatched workspace_id → complete no-op: issue and link both survive.+ wrongWS := parseUUID("11111111-1111-1111-1111-111111111111")+ if err := testHandler.Queries.DeleteIssue(ctx, db.DeleteIssueParams{ID: parseUUID(issue.ID), WorkspaceID: wrongWS}); err != nil {+ t.Fatalf("DeleteIssue(wrong ws): %v", err)+ }+ if _, err := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID)); err != nil {+ t.Errorf("issue must survive a mismatched-workspace delete: %v", err)+ }+ if linkCount() != 1 {+ t.Errorf("link rows must survive a mismatched-workspace delete, got %d", linkCount())+ }++ // Correct workspace_id → issue and its links both removed.+ if err := testHandler.Queries.DeleteIssue(ctx, db.DeleteIssueParams{ID: parseUUID(issue.ID), WorkspaceID: parseUUID(testWorkspaceID)}); err != nil {+ t.Fatalf("DeleteIssue(correct ws): %v", err)+ }+ if linkCount() != 0 {+ t.Errorf("link rows should be gone after correct delete, got %d", linkCount())+ }+}++// A redelivered older event must not rewrite the link metadata that a newer+// event already set. The PR-upsert monotonic guard protects the PR row; this+// covers the link (close_intent / reference_only).+func TestVCSWebhook_StaleEventDoesNotRewriteLink(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")+ issue := newVCSIssue(t, "Out-of-order link guard")+ t.Cleanup(func() { cleanupVCS(ctx, issue.ID) })++ fire := func(action, state string, merged bool, title, body, updatedAt string) {+ raw, _ := json.Marshal(map[string]any{+ "action": action,+ "pull_request": map[string]any{+ "number": 7, "html_url": "https://forgejo.test/acme/widget/pulls/7",+ "title": title, "body": body, "state": state, "merged": merged,+ "created_at": "2026-05-01T00:00:00Z", "updated_at": updatedAt,+ "merged_at": "2026-05-02T00:00:00Z",+ "head": map[string]any{"ref": "wip", "sha": "abc"},+ "user": map[string]any{"username": "octo"},+ },+ "repository": map[string]any{"name": "widget", "owner": map[string]any{"username": "acme"}},+ })+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": giteaSig(raw),+ }, raw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("%s event: %d %s", action, w.Code, w.Body.String())+ }+ }++ // Newer terminal event: merged with a qualifying Closes → close_intent, not reference_only.+ fire("closed", "closed", true, "Fix "+issue.Identifier, "Closes "+issue.Identifier, "2026-05-02T00:00:00Z")+ // Older redelivered "opened" event: bare body mention, generic title/branch.+ // Without the guard this rewrites the link to close_intent=false, reference_only=true.+ fire("opened", "open", false, "WIP", "touches "+issue.Identifier, "2026-05-01T00:00:00Z")++ var closeIntent, referenceOnly bool+ if err := testPool.QueryRow(ctx,+ `SELECT close_intent, reference_only FROM issue_vcs_pull_request WHERE issue_id = $1`,+ issue.ID).Scan(&closeIntent, &referenceOnly); err != nil {+ t.Fatalf("select link: %v", err)+ }+ if !closeIntent || referenceOnly {+ t.Errorf("stale event rewrote link: close_intent=%v reference_only=%v, want true/false", closeIntent, referenceOnly)+ }+ // The PR row also stayed at the newer merged state.+ rows, _ := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issue.ID))+ if len(rows) != 1 || rows[0].State != "merged" {+ t.Errorf("PR row regressed: %+v", rows)+ }+}++func TestVCSWebhook_GitlabMergeRequest(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "gitlab", "https://gitlab.test")+ issue := newVCSIssue(t, "GitLab MR test")+ t.Cleanup(func() { cleanupVCS(ctx, issue.ID) })++ raw, _ := json.Marshal(map[string]any{+ "object_kind": "merge_request",+ "user": map[string]any{"username": "alice"},+ "project": map[string]any{"path_with_namespace": "acme/widget"},+ "object_attributes": map[string]any{+ "iid": 42, "title": "Add " + issue.Identifier, "description": "Closes " + issue.Identifier,+ "state": "merged", "action": "merge", "source_branch": "feat",+ "url": "https://gitlab.test/acme/widget/-/merge_requests/42",+ "last_commit": map[string]any{"id": "deadbeef"},+ },+ })+ // GitLab authenticates by plaintext X-Gitlab-Token, not HMAC.+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitlab-Event": "Merge Request Hook", "X-Gitlab-Token": vcsTestSecret,+ }, raw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("expected 202, got %d (%s)", w.Code, w.Body.String())+ }++ rows, err := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issue.ID))+ if err != nil {+ t.Fatalf("ListVCSPullRequestsByIssue: %v", err)+ }+ if len(rows) != 1 || rows[0].Provider != "gitlab" || rows[0].RepoOwner != "acme" || rows[0].PrNumber != 42 {+ t.Fatalf("unexpected rows: %+v", rows)+ }+ if rows[0].State != "merged" {+ t.Errorf("expected merged, got %q", rows[0].State)+ }+ updated, _ := testHandler.Queries.GetIssue(ctx, parseUUID(issue.ID))+ if updated.Status != "done" {+ t.Errorf("expected issue done, got %q", updated.Status)+ }+}++func TestVCSWebhook_CommitStatusMirrors(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")+ issue := newVCSIssue(t, "Forgejo CI status")+ t.Cleanup(func() { cleanupVCS(ctx, issue.ID) })++ prRaw, _ := json.Marshal(map[string]any{+ "action": "opened",+ "pull_request": map[string]any{+ "number": 11, "html_url": "https://forgejo.test/acme/widget/pulls/11",+ "title": issue.Identifier + " feature", "state": "open",+ "created_at": "2026-04-28T00:00:00Z", "updated_at": "2026-04-28T00:00:00Z",+ "head": map[string]any{"ref": "feat", "sha": "deadbeef"},+ "user": map[string]any{"username": "octo"},+ },+ "repository": map[string]any{"name": "widget", "owner": map[string]any{"username": "acme"}},+ })+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": giteaSig(prRaw),+ }, prRaw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("pr: expected 202, got %d", w.Code)+ }++ stRaw, _ := json.Marshal(map[string]any{"sha": "deadbeef", "context": "ci/woodpecker", "state": "success"})+ w = httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "status", "X-Gitea-Signature": giteaSig(stRaw),+ }, stRaw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("status: expected 202, got %d", w.Code)+ }++ rows, _ := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issue.ID))+ if len(rows) != 1 || rows[0].ChecksTotal != 1 || rows[0].ChecksPassed != 1 {+ t.Fatalf("expected 1 passed check, got %+v", rows)+ }+}++func TestVCSWebhook_BadSignature(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")+ t.Cleanup(func() { cleanupVCS(ctx, "") })++ raw := []byte(`{"action":"opened","pull_request":{"number":1}}`)+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": "00",+ }, raw))+ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401, got %d", w.Code)+ }+}++func TestVCSWebhook_UnknownConnection(t *testing.T) {+ withVCSBox(t)+ req := vcsWebhookReq("00000000-0000-0000-0000-000000000000", map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": "00",+ }, []byte(`{}`))+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d", w.Code)+ }+}++func TestVCSWebhook_MalformedTolerated(t *testing.T) {+ ctx := context.Background()+ box := withVCSBox(t)+ connID := seedVCSConnection(t, ctx, box, "forgejo", "https://forgejo.test")+ t.Cleanup(func() { cleanupVCS(ctx, "") })++ raw := []byte(`{"action":"opened","pull_request":"not-an-object"}`)+ w := httptest.NewRecorder()+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{+ "X-Gitea-Event": "pull_request", "X-Gitea-Signature": giteaSig(raw),+ }, raw))+ if w.Code != http.StatusAccepted {+ t.Fatalf("expected 202, got %d (%s)", w.Code, w.Body.String())+ }+ var count int+ testPool.QueryRow(ctx, `SELECT count(*) FROM vcs_pull_request WHERE workspace_id = $1`, testWorkspaceID).Scan(&count)+ if count != 0 {+ t.Errorf("expected no PR rows, got %d", count)+ }+}diff --git a/server/internal/integrations/vcs/forgejo.go b/server/internal/integrations/vcs/forgejo.gonew file mode 100644index 0000000000..6b6906ca78--- /dev/null+++ b/server/internal/integrations/vcs/forgejo.go@@ -0,0 +1,257 @@+package vcs++import (+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "strings"+ "time"+)++// forgejoProvider implements Provider for Forgejo and its upstream Gitea, which+// are wire-identical: same /api/v1 REST surface, same X-Gitea-Signature+// HMAC-SHA256 webhooks, same pull_request / status event shapes. One struct+// serves both; it is registered under KindForgejo and KindGitea so the only+// user-visible difference is the provider label.+type forgejoProvider struct{ kind Kind }++func init() {+ register(forgejoProvider{kind: KindForgejo})+ register(forgejoProvider{kind: KindGitea})+}++func (p forgejoProvider) Kind() Kind { return p.kind }++func (p forgejoProvider) EventKind(h http.Header) EventKind {+ event := h.Get("X-Gitea-Event")+ if event == "" {+ event = h.Get("X-GitHub-Event") // Gitea mirrors this header too+ }+ switch event {+ case "pull_request":+ return EventPullRequest+ case "status":+ return EventCIStatus+ default:+ return EventOther+ }+}++// VerifySignature checks X-Gitea-Signature, a bare hex HMAC-SHA256 of the body+// (no "sha256=" prefix — that is GitHub's convention; tolerate it anyway).+func (p forgejoProvider) VerifySignature(secret string, h http.Header, body []byte) bool {+ // HMAC with an empty key is forgeable, so reject an empty secret outright+ // (mirrors the GitLab verifier). Not reachable today — the secret is always+ // 32 random bytes — but keep the auth boundary safe regardless.+ if secret == "" {+ return false+ }+ sig := strings.TrimSpace(h.Get("X-Gitea-Signature"))+ sig = strings.TrimPrefix(sig, "sha256=")+ want, err := hex.DecodeString(sig)+ if err != nil {+ return false+ }+ mac := hmac.New(sha256.New, []byte(secret))+ mac.Write(body)+ return hmac.Equal(mac.Sum(nil), want)+}++type fjPullRequestPayload struct {+ Action string `json:"action"`+ PullRequest struct {+ Number int32 `json:"number"`+ Title string `json:"title"`+ Body string `json:"body"`+ State string `json:"state"`+ Merged bool `json:"merged"`+ Draft bool `json:"draft"`+ HTMLURL string `json:"html_url"`+ Additions int32 `json:"additions"`+ Deletions int32 `json:"deletions"`+ ChangedFiles int32 `json:"changed_files"`+ MergedAt string `json:"merged_at"`+ ClosedAt string `json:"closed_at"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+ User struct {+ Login string `json:"login"`+ UserName string `json:"username"`+ AvatarURL string `json:"avatar_url"`+ } `json:"user"`+ Head struct {+ Ref string `json:"ref"`+ Sha string `json:"sha"`+ } `json:"head"`+ } `json:"pull_request"`+ Repository struct {+ Name string `json:"name"`+ FullName string `json:"full_name"`+ Owner struct {+ Login string `json:"login"`+ UserName string `json:"username"`+ } `json:"owner"`+ } `json:"repository"`+}++func (p forgejoProvider) ParsePullRequest(body []byte) (PullRequestEvent, error) {+ var d fjPullRequestPayload+ if err := json.Unmarshal(body, &d); err != nil {+ return PullRequestEvent{}, err+ }+ owner := coalesce(d.Repository.Owner.UserName, d.Repository.Owner.Login)+ if owner == "" {+ if i := strings.Index(d.Repository.FullName, "/"); i > 0 {+ owner = d.Repository.FullName[:i]+ }+ }+ return PullRequestEvent{+ Action: d.Action,+ RepoOwner: owner,+ RepoName: d.Repository.Name,+ Number: d.PullRequest.Number,+ Title: d.PullRequest.Title,+ Body: d.PullRequest.Body,+ State: derivePRState(d.PullRequest.State, d.PullRequest.Draft, d.PullRequest.Merged),+ HTMLURL: d.PullRequest.HTMLURL,+ Branch: d.PullRequest.Head.Ref,+ HeadSHA: d.PullRequest.Head.Sha,+ AuthorLogin: coalesce(d.PullRequest.User.UserName, d.PullRequest.User.Login),+ AuthorAvatarURL: d.PullRequest.User.AvatarURL,+ Additions: d.PullRequest.Additions,+ Deletions: d.PullRequest.Deletions,+ ChangedFiles: d.PullRequest.ChangedFiles,+ MergedAt: d.PullRequest.MergedAt,+ ClosedAt: d.PullRequest.ClosedAt,+ CreatedAt: d.PullRequest.CreatedAt,+ UpdatedAt: d.PullRequest.UpdatedAt,+ }, nil+}++type fjStatusPayload struct {+ SHA string `json:"sha"`+ Context string `json:"context"`+ State string `json:"state"`+ TargetURL string `json:"target_url"`+ Description string `json:"description"`+ // Forgejo/Gitea send these as RFC3339 on the commit-status object.+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++func (p forgejoProvider) ParseCIStatus(body []byte) (CIStatusEvent, error) {+ var d fjStatusPayload+ if err := json.Unmarshal(body, &d); err != nil {+ return CIStatusEvent{}, err+ }+ // Prefer the status' own updated_at (RFC3339) so the monotonic guard is+ // real; fall back to created_at, then empty (handler uses ingestion time).+ updatedAt := d.UpdatedAt+ if updatedAt == "" {+ updatedAt = d.CreatedAt+ }+ return CIStatusEvent{+ SHA: d.SHA,+ Context: d.Context,+ State: normalizeForgejoState(d.State),+ TargetURL: d.TargetURL,+ Description: d.Description,+ UpdatedAt: updatedAt,+ }, nil+}++// normalizeForgejoState maps Forgejo/Gitea commit-status states onto the shared+// passed/failed/pending vocabulary. "warning" is treated as a pass (it does not+// block), mirroring how GitHub's neutral/skipped count as passed.+func normalizeForgejoState(s string) string {+ switch s {+ case "success", "warning":+ return "passed"+ case "failure", "error":+ return "failed"+ default: // pending, and anything unknown+ return "pending"+ }+}++func (p forgejoProvider) ValidateToken(ctx context.Context, instanceURL, token string) (Account, error) {+ endpoint := NormalizeInstanceURL(instanceURL) + "/api/v1/user"+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)+ if err != nil {+ return Account{}, fmt.Errorf("forgejo: build request: %w", err)+ }+ req.Header.Set("Authorization", "token "+token)+ req.Header.Set("Accept", "application/json")++ resp, err := httpClient.Do(req)+ if err != nil {+ return Account{}, fmt.Errorf("forgejo: request: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ // Log the upstream status + body snippet so a bad token (401) is+ // distinguishable from an insufficient-scope token (403) without+ // leaking the secret into the HTTP response.+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))+ slog.Warn("forgejo: token validation rejected",+ "endpoint", endpoint,+ "status", resp.StatusCode,+ "body", strings.TrimSpace(string(b)))+ return Account{}, ErrUnauthorized+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))+ return Account{}, fmt.Errorf("forgejo: GET /user: status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))+ }+ var u struct {+ Login string `json:"login"`+ UserName string `json:"username"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&u); err != nil {+ return Account{}, fmt.Errorf("forgejo: decode user: %w", err)+ }+ login := coalesce(u.Login, u.UserName)+ if login == "" {+ return Account{}, errors.New("forgejo: user response missing login")+ }+ return Account{Login: login}, nil+}++// ── shared helpers ──────────────────────────────────────────────────────────++var httpClient = &http.Client{Timeout: 15 * time.Second}++// NormalizeInstanceURL trims whitespace and any trailing slash so stored+// instance URLs and derived webhook URLs are stable regardless of input.+func NormalizeInstanceURL(raw string) string {+ return strings.TrimRight(strings.TrimSpace(raw), "/")+}++// derivePRState collapses (state, draft, merged) into the normalized PR state.+func derivePRState(state string, draft, merged bool) string {+ if merged {+ return "merged"+ }+ if state == "closed" {+ return "closed"+ }+ if draft {+ return "draft"+ }+ return "open"+}++func coalesce(a, b string) string {+ if a != "" {+ return a+ }+ return b+}diff --git a/server/internal/integrations/vcs/gitlab.go b/server/internal/integrations/vcs/gitlab.gonew file mode 100644index 0000000000..615a0be5ce--- /dev/null+++ b/server/internal/integrations/vcs/gitlab.go@@ -0,0 +1,248 @@+package vcs++import (+ "context"+ "crypto/subtle"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"+)++// gitlabProvider implements Provider for GitLab, which differs from+// Forgejo/Gitea on every axis: /api/v4 with a PRIVATE-TOKEN header, webhooks+// authenticated by a plaintext X-Gitlab-Token compare (no HMAC), an+// X-Gitlab-Event header, "merge request" terminology, and pipeline events for+// CI. The normalized PullRequestEvent/CIStatusEvent hide all of that from the+// handler.+type gitlabProvider struct{}++func init() { register(gitlabProvider{}) }++func (gitlabProvider) Kind() Kind { return KindGitLab }++func (gitlabProvider) EventKind(h http.Header) EventKind {+ switch h.Get("X-Gitlab-Event") {+ case "Merge Request Hook":+ return EventPullRequest+ case "Pipeline Hook":+ return EventCIStatus+ default:+ return EventOther+ }+}++// VerifySignature compares the X-Gitlab-Token header to the stored secret in+// constant time. GitLab does not HMAC-sign webhook bodies; the shared token is+// the whole authentication, so an empty stored secret never validates.+func (gitlabProvider) VerifySignature(secret string, h http.Header, _ []byte) bool {+ if secret == "" {+ return false+ }+ got := h.Get("X-Gitlab-Token")+ return subtle.ConstantTimeCompare([]byte(got), []byte(secret)) == 1+}++type glMergeRequestPayload struct {+ ObjectKind string `json:"object_kind"`+ User struct {+ Username string `json:"username"`+ AvatarURL string `json:"avatar_url"`+ } `json:"user"`+ Project struct {+ PathWithNamespace string `json:"path_with_namespace"`+ } `json:"project"`+ ObjectAttributes struct {+ IID int32 `json:"iid"`+ Title string `json:"title"`+ Description string `json:"description"`+ State string `json:"state"` // opened|closed|merged|locked+ Action string `json:"action"`+ SourceBranch string `json:"source_branch"`+ URL string `json:"url"`+ Draft bool `json:"draft"`+ WorkInProgress bool `json:"work_in_progress"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+ LastCommit struct {+ ID string `json:"id"`+ } `json:"last_commit"`+ } `json:"object_attributes"`+}++func (gitlabProvider) ParsePullRequest(body []byte) (PullRequestEvent, error) {+ var d glMergeRequestPayload+ if err := json.Unmarshal(body, &d); err != nil {+ return PullRequestEvent{}, err+ }+ owner, name := splitNamespace(d.Project.PathWithNamespace)+ draft := d.ObjectAttributes.Draft || d.ObjectAttributes.WorkInProgress ||+ strings.HasPrefix(strings.ToLower(d.ObjectAttributes.Title), "draft:")+ return PullRequestEvent{+ Action: d.ObjectAttributes.Action,+ RepoOwner: owner,+ RepoName: name,+ Number: d.ObjectAttributes.IID,+ Title: d.ObjectAttributes.Title,+ Body: d.ObjectAttributes.Description,+ State: normalizeGitLabMRState(d.ObjectAttributes.State, draft),+ HTMLURL: d.ObjectAttributes.URL,+ Branch: d.ObjectAttributes.SourceBranch,+ HeadSHA: d.ObjectAttributes.LastCommit.ID,+ AuthorLogin: d.User.Username,+ AuthorAvatarURL: d.User.AvatarURL,+ CreatedAt: normalizeGitLabTime(d.ObjectAttributes.CreatedAt),+ UpdatedAt: normalizeGitLabTime(d.ObjectAttributes.UpdatedAt),+ }, nil+}++// normalizeGitLabTime converts GitLab's webhook timestamp format+// ("2017-09-20 08:31:45 UTC") into the RFC3339 the rest of the pipeline expects+// (PullRequestEvent/CIStatusEvent document their time fields as "RFC3339 or+// empty", and the shared parser is RFC3339-only). Without this every GitLab+// event's timestamp failed to parse and was silently replaced with ingestion+// time, defeating the PR-upsert and commit-status monotonic guards for GitLab+// and skewing PR list ordering. Normalizing here keeps the fix inside the+// provider adapter, matching the package's "providers contribute only what+// differs" design rather than teaching the shared parser a GitLab dialect.+// Output uses RFC3339Nano to preserve any sub-second precision GitLab sends, so+// two events within the same wall-clock second still order correctly under the+// monotonic guards (the shared time.RFC3339 parser accepts the fractional part).+// Unrecognized input returns "" so the handler falls back to ingestion time.+func normalizeGitLabTime(s string) string {+ if s == "" {+ return ""+ }+ for _, layout := range []string{+ time.RFC3339,+ time.RFC3339Nano,+ "2006-01-02 15:04:05 MST",+ "2006-01-02 15:04:05 -0700",+ "2006-01-02 15:04:05.999999 MST",+ } {+ if t, err := time.Parse(layout, s); err == nil {+ return t.UTC().Format(time.RFC3339Nano)+ }+ }+ return ""+}++// normalizeGitLabMRState maps GitLab MR states onto open/closed/merged/draft.+// "locked" is a transient open sub-state, so it reads as open.+func normalizeGitLabMRState(state string, draft bool) string {+ switch state {+ case "merged":+ return "merged"+ case "closed":+ return "closed"+ default: // opened, locked+ if draft {+ return "draft"+ }+ return "open"+ }+}++type glPipelinePayload struct {+ ObjectKind string `json:"object_kind"`+ ObjectAttributes struct {+ SHA string `json:"sha"`+ Status string `json:"status"`+ URL string `json:"url"`+ CreatedAt string `json:"created_at"`+ FinishedAt string `json:"finished_at"`+ } `json:"object_attributes"`+}++func (gitlabProvider) ParseCIStatus(body []byte) (CIStatusEvent, error) {+ var d glPipelinePayload+ if err := json.Unmarshal(body, &d); err != nil {+ return CIStatusEvent{}, err+ }+ // Prefer the pipeline's finished_at (the state transition we're recording);+ // fall back to created_at. Normalized to RFC3339 so the commit-status+ // monotonic guard has a real, comparable timestamp instead of ingestion time.+ updatedAt := d.ObjectAttributes.FinishedAt+ if updatedAt == "" {+ updatedAt = d.ObjectAttributes.CreatedAt+ }+ return CIStatusEvent{+ SHA: d.ObjectAttributes.SHA,+ // GitLab pipelines are modelled as one status per commit, not per named+ // check, so a stable synthetic context keys the single status row.+ // Known limitations of this simplification (acceptable for the default+ // branch-pipeline config; revisit if needed):+ // - Merge-train / merged-results pipelines run on a synthetic merge+ // commit whose SHA differs from the MR head (last_commit.id), so the+ // head_sha join won't match and the card shows no checks.+ // - Multiple pipelines on one commit (e.g. a scheduled pipeline plus an+ // MR pipeline) collapse into this single context, so the last one to+ // fire wins per commit.+ Context: "gitlab/pipeline",+ State: normalizeGitLabPipelineState(d.ObjectAttributes.Status),+ TargetURL: d.ObjectAttributes.URL,+ UpdatedAt: normalizeGitLabTime(updatedAt),+ }, nil+}++// normalizeGitLabPipelineState maps pipeline statuses onto passed/failed/+// pending. skipped is a pass (nothing failed); canceled is a failure-class+// terminal, matching how GitHub treats cancelled.+func normalizeGitLabPipelineState(s string) string {+ switch s {+ case "success", "skipped":+ return "passed"+ case "failed", "canceled":+ return "failed"+ default: // created, waiting_for_resource, preparing, pending, running, manual, scheduled+ return "pending"+ }+}++func (gitlabProvider) ValidateToken(ctx context.Context, instanceURL, token string) (Account, error) {+ endpoint := NormalizeInstanceURL(instanceURL) + "/api/v4/user"+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)+ if err != nil {+ return Account{}, fmt.Errorf("gitlab: build request: %w", err)+ }+ req.Header.Set("PRIVATE-TOKEN", token)+ req.Header.Set("Accept", "application/json")++ resp, err := httpClient.Do(req)+ if err != nil {+ return Account{}, fmt.Errorf("gitlab: request: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ return Account{}, ErrUnauthorized+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))+ return Account{}, fmt.Errorf("gitlab: GET /user: status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))+ }+ var u struct {+ Username string `json:"username"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&u); err != nil {+ return Account{}, fmt.Errorf("gitlab: decode user: %w", err)+ }+ if u.Username == "" {+ return Account{}, errors.New("gitlab: user response missing username")+ }+ return Account{Login: u.Username}, nil+}++// splitNamespace splits a GitLab path_with_namespace ("group/subgroup/repo")+// into owner ("group/subgroup") and repo name ("repo"). Subgroups are kept in+// the owner so the identity stays unique.+func splitNamespace(path string) (owner, name string) {+ path = strings.Trim(path, "/")+ if i := strings.LastIndex(path, "/"); i >= 0 {+ return path[:i], path[i+1:]+ }+ return "", path+}diff --git a/server/internal/integrations/vcs/vcs.go b/server/internal/integrations/vcs/vcs.gonew file mode 100644index 0000000000..3c0a59f73e--- /dev/null+++ b/server/internal/integrations/vcs/vcs.go@@ -0,0 +1,144 @@+// Package vcs is the provider abstraction for token-based Git providers that+// Multica mirrors pull requests and CI status from: Forgejo, Gitea (Forgejo's+// upstream, wire-identical), and GitLab. GitHub is intentionally NOT a vcs+// provider — its App/installation model and check_suite CI differ enough that+// it keeps its own handler (server/internal/handler/github.go).+//+// Each provider only contributes the parts that actually differ between+// providers: how a webhook is authenticated, how its event/payload shapes map to+// the normalized PR/CI structs below, and how a token is validated. The shared+// storage, issue auto-link / auto-close, and broadcast logic live once in the+// handler layer and consume the normalized types.+package vcs++import (+ "context"+ "errors"+ "net/http"+)++// Kind identifies a provider. The string values are persisted on+// vcs_connection.provider and used as the registry key.+type Kind string++const (+ KindForgejo Kind = "forgejo"+ KindGitea Kind = "gitea"+ KindGitLab Kind = "gitlab"+)++// Valid reports whether k is a known provider kind.+func (k Kind) Valid() bool {+ switch k {+ case KindForgejo, KindGitea, KindGitLab:+ return true+ }+ return false+}++// ErrUnauthorized is returned by ValidateToken when the instance rejects the+// token (HTTP 401/403). Callers surface it as a connect-time validation+// failure distinct from transport/instance errors.+var ErrUnauthorized = errors.New("vcs: token unauthorized")++// EventKind is the normalized webhook event category. Anything a provider does+// not model maps to EventOther and is acknowledged but ignored.+type EventKind int++const (+ EventOther EventKind = iota+ EventPullRequest+ EventCIStatus+)++// PullRequestEvent is the provider-agnostic shape of a pull/merge request+// webhook. State is already normalized to one of open/closed/merged/draft, so+// the handler never re-derives it. GitLab "merge requests" map onto the same+// struct.+type PullRequestEvent struct {+ // Action is the raw provider action (e.g. "opened", "closed", "merge").+ // The handler only needs to know whether it is terminal; see Terminal.+ Action string+ RepoOwner string+ RepoName string+ Number int32+ Title string+ Body string+ State string // open | closed | merged | draft+ HTMLURL string+ Branch string+ HeadSHA string+ AuthorLogin string+ AuthorAvatarURL string+ Additions int32+ Deletions int32+ ChangedFiles int32+ MergedAt string // RFC3339 or empty+ ClosedAt string+ CreatedAt string+ UpdatedAt string+}++// Terminal reports whether this event is the PR's merge/close event, after+// which the close-intent decision must be frozen. Providers spell the terminal+// action differently (Forgejo "closed"/"merged", GitLab "merge"/"close"), so+// the set is matched here rather than in the handler.+func (e PullRequestEvent) Terminal() bool {+ switch e.Action {+ case "closed", "merged", "merge", "close":+ return true+ }+ return false+}++// CIStatusEvent is the provider-agnostic shape of a commit-status / pipeline+// webhook. State is normalized to passed/failed/pending so the aggregation+// query is provider-independent.+type CIStatusEvent struct {+ SHA string+ Context string // status check / pipeline name; "" is allowed+ State string // passed | failed | pending+ TargetURL string+ Description string+ // UpdatedAt is the provider's own event timestamp (RFC3339 or empty). It+ // feeds the commit-status monotonic guard so an out-of-order redelivery+ // can't regress a status; empty means "unknown", and the handler falls back+ // to ingestion time.+ UpdatedAt string+}++// Account is the minimal identity returned by ValidateToken.+type Account struct {+ Login string+}++// Provider is the per-provider adapter. Implementations are stateless and cheap+// to construct; the registry holds one instance per kind.+type Provider interface {+ Kind() Kind+ // EventKind classifies an inbound webhook from its headers.+ EventKind(h http.Header) EventKind+ // VerifySignature authenticates the raw body against the connection's+ // stored secret. Forgejo/Gitea use HMAC-SHA256 (X-Gitea-Signature);+ // GitLab uses a plaintext token compare (X-Gitlab-Token).+ VerifySignature(secret string, h http.Header, body []byte) bool+ // ParsePullRequest decodes a pull/merge request webhook body.+ ParsePullRequest(body []byte) (PullRequestEvent, error)+ // ParseCIStatus decodes a commit-status / pipeline webhook body.+ ParseCIStatus(body []byte) (CIStatusEvent, error)+ // ValidateToken confirms the token works against instanceURL and returns+ // the authenticated account. Maps a 401/403 to ErrUnauthorized.+ ValidateToken(ctx context.Context, instanceURL, token string) (Account, error)+}++// registry maps a Kind to its Provider. Populated by package init in the+// adapter files (forgejo.go, gitlab.go).+var registry = map[Kind]Provider{}++func register(p Provider) { registry[p.Kind()] = p }++// For returns the provider for kind, or (nil, false) if unknown.+func For(kind string) (Provider, bool) {+ p, ok := registry[Kind(kind)]+ return p, ok+}diff --git a/server/internal/integrations/vcs/vcs_test.go b/server/internal/integrations/vcs/vcs_test.gonew file mode 100644index 0000000000..9091f3ee48--- /dev/null+++ b/server/internal/integrations/vcs/vcs_test.go@@ -0,0 +1,298 @@+package vcs++import (+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestRegistry(t *testing.T) {+ for _, k := range []string{"forgejo", "gitea", "gitlab"} {+ if _, ok := For(k); !ok {+ t.Errorf("registry missing provider %q", k)+ }+ }+ if _, ok := For("bitbucket"); ok {+ t.Error("unknown provider should not resolve")+ }+}++func TestKindValid(t *testing.T) {+ if !KindForgejo.Valid() || !KindGitea.Valid() || !KindGitLab.Valid() {+ t.Error("known kinds must be valid")+ }+ if Kind("svn").Valid() {+ t.Error("unknown kind must be invalid")+ }+}++func TestNormalizeInstanceURL(t *testing.T) {+ cases := map[string]string{+ "https://forgejo.example.com/": "https://forgejo.example.com",+ " https://forge.test ": "https://forge.test",+ "https://forge.test/sub/": "https://forge.test/sub",+ }+ for in, want := range cases {+ if got := NormalizeInstanceURL(in); got != want {+ t.Errorf("NormalizeInstanceURL(%q) = %q, want %q", in, got, want)+ }+ }+}++func TestForgejoVerifySignature(t *testing.T) {+ p, _ := For("forgejo")+ secret, body := "s3cr3t", []byte(`{"action":"opened"}`)+ mac := hmac.New(sha256.New, []byte(secret))+ mac.Write(body)+ valid := hex.EncodeToString(mac.Sum(nil))++ h := http.Header{}+ h.Set("X-Gitea-Signature", valid)+ if !p.VerifySignature(secret, h, body) {+ t.Error("valid signature rejected")+ }+ h.Set("X-Gitea-Signature", "sha256="+valid)+ if !p.VerifySignature(secret, h, body) {+ t.Error("sha256-prefixed signature rejected")+ }+ if p.VerifySignature("wrong", h, body) {+ t.Error("wrong secret accepted")+ }+ if p.VerifySignature(secret, h, []byte("tampered")) {+ t.Error("tampered body accepted")+ }+ // An empty secret must be rejected outright — HMAC with an empty key is+ // forgeable. Sign the body with the empty key and confirm it's still refused.+ emptyMac := hmac.New(sha256.New, []byte(""))+ emptyMac.Write(body)+ h.Set("X-Gitea-Signature", hex.EncodeToString(emptyMac.Sum(nil)))+ if p.VerifySignature("", h, body) {+ t.Error("empty secret accepted")+ }+}++func TestGitlabVerifySignature(t *testing.T) {+ p, _ := For("gitlab")+ h := http.Header{}+ h.Set("X-Gitlab-Token", "tok123")+ if !p.VerifySignature("tok123", h, nil) {+ t.Error("matching token rejected")+ }+ if p.VerifySignature("other", h, nil) {+ t.Error("mismatched token accepted")+ }+ if p.VerifySignature("", h, nil) {+ t.Error("empty stored secret must never validate")+ }+}++func TestForgejoEventKindAndParse(t *testing.T) {+ p, _ := For("gitea")+ h := http.Header{}+ h.Set("X-Gitea-Event", "pull_request")+ if p.EventKind(h) != EventPullRequest {+ t.Error("pull_request not classified")+ }+ h.Set("X-Gitea-Event", "status")+ if p.EventKind(h) != EventCIStatus {+ t.Error("status not classified")+ }++ pr, err := p.ParsePullRequest([]byte(`{+ "action":"closed",+ "pull_request":{"number":7,"title":"Fix MUL-1","state":"closed","merged":true,+ "html_url":"https://g/acme/widget/pulls/7","head":{"ref":"fix","sha":"abc"},+ "user":{"username":"octo"},"additions":3},+ "repository":{"name":"widget","owner":{"username":"acme"}}}`))+ if err != nil {+ t.Fatalf("ParsePullRequest: %v", err)+ }+ if pr.RepoOwner != "acme" || pr.RepoName != "widget" || pr.Number != 7 {+ t.Errorf("bad identity: %+v", pr)+ }+ if pr.State != "merged" {+ t.Errorf("state = %q, want merged", pr.State)+ }+ if pr.AuthorLogin != "octo" || pr.HeadSHA != "abc" {+ t.Errorf("bad author/sha: %+v", pr)+ }+ if !pr.Terminal() {+ t.Error("closed action must be terminal")+ }++ st, err := p.ParseCIStatus([]byte(`{"sha":"abc","context":"ci","state":"success"}`))+ if err != nil {+ t.Fatalf("ParseCIStatus: %v", err)+ }+ if st.State != "passed" {+ t.Errorf("state = %q, want passed", st.State)+ }+}++func TestGitlabParse(t *testing.T) {+ p, _ := For("gitlab")+ h := http.Header{}+ h.Set("X-Gitlab-Event", "Merge Request Hook")+ if p.EventKind(h) != EventPullRequest {+ t.Error("MR hook not classified")+ }++ pr, err := p.ParsePullRequest([]byte(`{+ "object_kind":"merge_request",+ "user":{"username":"alice","avatar_url":"a"},+ "project":{"path_with_namespace":"group/sub/widget"},+ "object_attributes":{"iid":42,"title":"Add MUL-9","state":"merged","action":"merge",+ "source_branch":"feat","url":"https://gl/group/sub/widget/-/merge_requests/42",+ "last_commit":{"id":"deadbeef"}}}`))+ if err != nil {+ t.Fatalf("ParsePullRequest: %v", err)+ }+ if pr.RepoOwner != "group/sub" || pr.RepoName != "widget" {+ t.Errorf("namespace split wrong: owner=%q name=%q", pr.RepoOwner, pr.RepoName)+ }+ if pr.Number != 42 || pr.State != "merged" || pr.HeadSHA != "deadbeef" {+ t.Errorf("bad MR: %+v", pr)+ }+ if !pr.Terminal() {+ t.Error("merge action must be terminal")+ }++ h.Set("X-Gitlab-Event", "Pipeline Hook")+ if p.EventKind(h) != EventCIStatus {+ t.Error("pipeline hook not classified")+ }+ st, err := p.ParseCIStatus([]byte(`{"object_kind":"pipeline","object_attributes":{"sha":"deadbeef","status":"failed"}}`))+ if err != nil {+ t.Fatalf("ParseCIStatus: %v", err)+ }+ if st.SHA != "deadbeef" || st.State != "failed" || st.Context != "gitlab/pipeline" {+ t.Errorf("bad status: %+v", st)+ }+}++func TestGitlabDraftDetection(t *testing.T) {+ p, _ := For("gitlab")+ pr, _ := p.ParsePullRequest([]byte(`{"object_kind":"merge_request",+ "project":{"path_with_namespace":"g/r"},+ "object_attributes":{"iid":1,"title":"Draft: wip","state":"opened","work_in_progress":true}}`))+ if pr.State != "draft" {+ t.Errorf("state = %q, want draft", pr.State)+ }+}++func TestValidateToken(t *testing.T) {+ cases := []struct {+ kind, path, authHeader, authValue, bodyJSON, wantLogin string+ }{+ {"forgejo", "/api/v1/user", "Authorization", "token tok", `{"login":"octo"}`, "octo"},+ {"gitlab", "/api/v4/user", "PRIVATE-TOKEN", "tok", `{"username":"alice"}`, "alice"},+ }+ for _, c := range cases {+ t.Run(c.kind, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != c.path {+ t.Errorf("path = %q, want %q", r.URL.Path, c.path)+ }+ if r.Header.Get(c.authHeader) != c.authValue {+ t.Errorf("%s = %q, want %q", c.authHeader, r.Header.Get(c.authHeader), c.authValue)+ }+ _, _ = w.Write([]byte(c.bodyJSON))+ }))+ defer srv.Close()+ p, _ := For(c.kind)+ acct, err := p.ValidateToken(context.Background(), srv.URL, "tok")+ if err != nil {+ t.Fatalf("ValidateToken: %v", err)+ }+ if acct.Login != c.wantLogin {+ t.Errorf("login = %q, want %q", acct.Login, c.wantLogin)+ }+ })+ }+}++// GitLab sends timestamps as "2017-09-20 08:31:45 UTC" (not RFC3339). The+// shared handler parser is RFC3339-only, so without normalization every GitLab+// timestamp was dropped and replaced with ingestion time — defeating the+// monotonic guards on PR upsert and commit status for GitLab specifically, and+// skewing PR list ordering. These assert the adapter normalizes to RFC3339.+func TestNormalizeGitLabTime(t *testing.T) {+ cases := []struct{ in, want string }{+ {"", ""},+ {"2017-09-20 08:31:45 UTC", "2017-09-20T08:31:45Z"},+ {"2017-09-20T08:31:45Z", "2017-09-20T08:31:45Z"},+ // Sub-second precision is preserved (RFC3339Nano output) so two events in+ // the same wall-clock second still order correctly under the monotonic+ // guards; a zero fraction still formats without a decimal part.+ {"2017-09-20T08:31:45.123Z", "2017-09-20T08:31:45.123Z"},+ {"2017-09-20 08:31:45.123456 UTC", "2017-09-20T08:31:45.123456Z"},+ {"not a time", ""},+ }+ for _, c := range cases {+ if got := normalizeGitLabTime(c.in); got != c.want {+ t.Errorf("normalizeGitLabTime(%q) = %q, want %q", c.in, got, c.want)+ }+ }+}++func TestGitlabParseTimestamps(t *testing.T) {+ p, _ := For("gitlab")+ // A merge_request payload with GitLab-format created_at/updated_at.+ pr, err := p.ParsePullRequest([]byte(`{+ "object_kind":"merge_request",+ "project":{"path_with_namespace":"g/r"},+ "object_attributes":{"iid":1,"title":"MUL-1","state":"opened","action":"open",+ "created_at":"2017-09-20 08:31:45 UTC","updated_at":"2017-09-21 09:00:00 UTC",+ "last_commit":{"id":"abc"}}}`))+ if err != nil {+ t.Fatalf("ParsePullRequest: %v", err)+ }+ if pr.CreatedAt != "2017-09-20T08:31:45Z" || pr.UpdatedAt != "2017-09-21T09:00:00Z" {+ t.Errorf("timestamps not normalized: created=%q updated=%q", pr.CreatedAt, pr.UpdatedAt)+ }+ if _, err := time.Parse(time.RFC3339, pr.UpdatedAt); err != nil {+ t.Errorf("UpdatedAt not RFC3339: %v", err)+ }++ // A pipeline payload's finished_at feeds the commit-status guard.+ st, err := p.ParseCIStatus([]byte(`{"object_kind":"pipeline",+ "object_attributes":{"sha":"abc","status":"success",+ "created_at":"2017-09-20 08:00:00 UTC","finished_at":"2017-09-20 08:05:00 UTC"}}`))+ if err != nil {+ t.Fatalf("ParseCIStatus: %v", err)+ }+ if st.UpdatedAt != "2017-09-20T08:05:00Z" {+ t.Errorf("CI UpdatedAt = %q, want finished_at normalized", st.UpdatedAt)+ }+}++func TestForgejoStatusTimestamp(t *testing.T) {+ p, _ := For("forgejo")+ // Forgejo/Gitea status payloads carry RFC3339 created_at/updated_at.+ st, err := p.ParseCIStatus([]byte(`{"sha":"abc","context":"ci","state":"success",+ "created_at":"2017-09-20T08:00:00Z","updated_at":"2017-09-20T08:05:00Z"}`))+ if err != nil {+ t.Fatalf("ParseCIStatus: %v", err)+ }+ if st.UpdatedAt != "2017-09-20T08:05:00Z" {+ t.Errorf("CI UpdatedAt = %q, want updated_at", st.UpdatedAt)+ }+}++func TestValidateTokenUnauthorized(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer srv.Close()+ p, _ := For("forgejo")+ _, err := p.ValidateToken(context.Background(), srv.URL, "bad")+ if !errors.Is(err, ErrUnauthorized) {+ t.Fatalf("err = %v, want ErrUnauthorized", err)+ }+}diff --git a/server/migrations/213_vcs_integration.down.sql b/server/migrations/213_vcs_integration.down.sqlnew file mode 100644index 0000000000..e8a98e9335--- /dev/null+++ b/server/migrations/213_vcs_integration.down.sql@@ -0,0 +1,4 @@+DROP TABLE IF EXISTS vcs_commit_status;+DROP TABLE IF EXISTS issue_vcs_pull_request;+DROP TABLE IF EXISTS vcs_pull_request;+DROP TABLE IF EXISTS vcs_connection;diff --git a/server/migrations/213_vcs_integration.up.sql b/server/migrations/213_vcs_integration.up.sqlnew file mode 100644index 0000000000..f15f2be6e3--- /dev/null+++ b/server/migrations/213_vcs_integration.up.sql@@ -0,0 +1,92 @@+-- VCS (self-hosted Git provider: Forgejo, Gitea, GitLab) integration:+-- per-workspace token-based connections. Unlike the GitHub App model+-- (server/migrations/079), these providers have no app/installation concept —+-- each workspace stores its own instance URL plus an access token used for+-- API enrichment and a webhook secret used to verify inbound webhook signatures.+--+-- Both secrets are stored as base64-encoded secretbox ciphertext (never+-- plaintext). Decryption uses the MULTICA_VCS_SECRET_KEY box wired in+-- cmd/server/router.go.+--+-- Mirrored pull requests and commit statuses are stored in vcs_pull_request+-- and vcs_commit_status tables, separate from GitHub tables.+--+-- Per the project migration rules these tables carry NO foreign keys or+-- cascades: relationships and dependent cleanup are resolved in application+-- code (DeleteVCSConnection, DeleteWorkspace, and DeleteIssue each sweep the+-- rows below in a single atomic statement). The inline UNIQUE / PRIMARY KEY+-- constraints stay — they back the ON CONFLICT upsert targets in vcs.sql.+-- Secondary indexes live in follow-up single-statement CREATE INDEX+-- CONCURRENTLY migrations (214-218), which cannot share a file with these+-- CREATE TABLEs.++CREATE TABLE IF NOT EXISTS vcs_connection (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ provider TEXT NOT NULL DEFAULT 'forgejo'+ CHECK (provider IN ('forgejo', 'gitea', 'gitlab')),+ instance_url TEXT NOT NULL,+ account_login TEXT NOT NULL,+ access_token_encrypted TEXT NOT NULL,+ webhook_secret_encrypted TEXT NOT NULL,+ connected_by_id UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (workspace_id, instance_url)+);++CREATE TABLE IF NOT EXISTS vcs_pull_request (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ connection_id UUID NOT NULL,+ provider TEXT NOT NULL DEFAULT 'forgejo'+ CHECK (provider IN ('forgejo', 'gitea', 'gitlab')),+ repo_owner TEXT NOT NULL,+ repo_name TEXT NOT NULL,+ pr_number INTEGER NOT NULL,+ title TEXT NOT NULL,+ state TEXT NOT NULL+ CHECK (state IN ('open', 'closed', 'merged', 'draft')),+ html_url TEXT NOT NULL,+ branch TEXT,+ head_sha TEXT NOT NULL DEFAULT '',+ author_login TEXT,+ author_avatar_url TEXT,+ merged_at TIMESTAMPTZ,+ closed_at TIMESTAMPTZ,+ pr_created_at TIMESTAMPTZ NOT NULL,+ pr_updated_at TIMESTAMPTZ NOT NULL,+ additions INTEGER NOT NULL DEFAULT 0,+ deletions INTEGER NOT NULL DEFAULT 0,+ changed_files INTEGER NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (connection_id, repo_owner, repo_name, pr_number)+);++CREATE TABLE IF NOT EXISTS issue_vcs_pull_request (+ issue_id UUID NOT NULL,+ pull_request_id UUID NOT NULL,+ close_intent BOOLEAN NOT NULL DEFAULT FALSE,+ -- reference_only marks a link justified ONLY by a bare body mention (no+ -- closing keyword and no title/branch reference). Mirrors the GitHub+ -- issue_pull_request column (migration 127): such links are hidden from the+ -- issue PR list and excluded from the close aggregate so a drive-by mention+ -- neither shows as a working PR nor blocks a genuine Closes sibling.+ reference_only BOOLEAN NOT NULL DEFAULT FALSE,+ linked_by_type TEXT,+ linked_by_id UUID,+ linked_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (issue_id, pull_request_id)+);++CREATE TABLE IF NOT EXISTS vcs_commit_status (+ connection_id UUID NOT NULL,+ sha TEXT NOT NULL,+ context TEXT NOT NULL,+ state TEXT NOT NULL,+ target_url TEXT,+ description TEXT,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (connection_id, sha, context)+);diff --git a/server/migrations/214_vcs_connection_workspace_index.down.sql b/server/migrations/214_vcs_connection_workspace_index.down.sqlnew file mode 100644index 0000000000..8e7a1e1283--- /dev/null+++ b/server/migrations/214_vcs_connection_workspace_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_vcs_connection_workspace;diff --git a/server/migrations/214_vcs_connection_workspace_index.up.sql b/server/migrations/214_vcs_connection_workspace_index.up.sqlnew file mode 100644index 0000000000..1935943b8b--- /dev/null+++ b/server/migrations/214_vcs_connection_workspace_index.up.sql@@ -0,0 +1,4 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_vcs_connection_workspace+ ON vcs_connection (workspace_id);diff --git a/server/migrations/215_vcs_pull_request_workspace_index.down.sql b/server/migrations/215_vcs_pull_request_workspace_index.down.sqlnew file mode 100644index 0000000000..7416156ef2--- /dev/null+++ b/server/migrations/215_vcs_pull_request_workspace_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_vcs_pull_request_workspace;diff --git a/server/migrations/215_vcs_pull_request_workspace_index.up.sql b/server/migrations/215_vcs_pull_request_workspace_index.up.sqlnew file mode 100644index 0000000000..56d3219b8d--- /dev/null+++ b/server/migrations/215_vcs_pull_request_workspace_index.up.sql@@ -0,0 +1,4 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_vcs_pull_request_workspace+ ON vcs_pull_request (workspace_id);diff --git a/server/migrations/216_vcs_pull_request_connection_index.down.sql b/server/migrations/216_vcs_pull_request_connection_index.down.sqlnew file mode 100644index 0000000000..b1825e4414--- /dev/null+++ b/server/migrations/216_vcs_pull_request_connection_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_vcs_pull_request_connection;diff --git a/server/migrations/216_vcs_pull_request_connection_index.up.sql b/server/migrations/216_vcs_pull_request_connection_index.up.sqlnew file mode 100644index 0000000000..48fc59cbb1--- /dev/null+++ b/server/migrations/216_vcs_pull_request_connection_index.up.sql@@ -0,0 +1,4 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_vcs_pull_request_connection+ ON vcs_pull_request (connection_id);diff --git a/server/migrations/217_issue_vcs_pull_request_pr_index.down.sql b/server/migrations/217_issue_vcs_pull_request_pr_index.down.sqlnew file mode 100644index 0000000000..b8d051dbc3--- /dev/null+++ b/server/migrations/217_issue_vcs_pull_request_pr_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_vcs_pull_request_pr;diff --git a/server/migrations/217_issue_vcs_pull_request_pr_index.up.sql b/server/migrations/217_issue_vcs_pull_request_pr_index.up.sqlnew file mode 100644index 0000000000..9830ae3952--- /dev/null+++ b/server/migrations/217_issue_vcs_pull_request_pr_index.up.sql@@ -0,0 +1,4 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_vcs_pull_request_pr+ ON issue_vcs_pull_request (pull_request_id);diff --git a/server/migrations/218_vcs_commit_status_lookup_index.down.sql b/server/migrations/218_vcs_commit_status_lookup_index.down.sqlnew file mode 100644index 0000000000..232d3d32c0--- /dev/null+++ b/server/migrations/218_vcs_commit_status_lookup_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_vcs_commit_status_lookup;diff --git a/server/migrations/218_vcs_commit_status_lookup_index.up.sql b/server/migrations/218_vcs_commit_status_lookup_index.up.sqlnew file mode 100644index 0000000000..dd458323c4--- /dev/null+++ b/server/migrations/218_vcs_commit_status_lookup_index.up.sql@@ -0,0 +1,4 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_vcs_commit_status_lookup+ ON vcs_commit_status (connection_id, sha);diff --git a/server/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.goindex e68786b4d8..9f5e7793b6 100644--- a/server/pkg/db/generated/github.sql.go+++ b/server/pkg/db/generated/github.sql.go@@ -283,11 +283,18 @@ func (q *Queries) GetIssuePullRequestCloseAggregate(ctx context.Context, issueID}const getIssueReviewHeadSha = `-- name: GetIssueReviewHeadSha :one-SELECT pr.head_sha-FROM github_pull_request pr-JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id-WHERE ipr.issue_id = $1 AND pr.head_sha <> ''-ORDER BY (pr.state IN ('open', 'draft')) DESC, pr.pr_updated_at DESC+SELECT head_sha FROM (+ SELECT pr.head_sha AS head_sha, pr.state AS state, pr.pr_updated_at AS pr_updated_at+ FROM github_pull_request pr+ JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id+ WHERE ipr.issue_id = $1 AND pr.head_sha <> '' AND NOT ipr.reference_only+ UNION ALL+ SELECT pr.head_sha AS head_sha, pr.state AS state, pr.pr_updated_at AS pr_updated_at+ FROM vcs_pull_request pr+ JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+ WHERE ipr.issue_id = $1 AND pr.head_sha <> '' AND NOT ipr.reference_only+) combined+ORDER BY (state IN ('open', 'draft')) DESC, pr_updated_at DESCLIMIT 1`@@ -300,6 +307,14 @@ LIMIT 1// newest linked PR with a head_sha when none are open. Returns no rows (empty// string) when the issue has no linked PR — callers treat that as "no SHA key"// and dedup on (issue_id, agent_id) alone, preserving pre-TEN-356 behavior.+//+// Spans both GitHub and self-hosted VCS PRs: a self-hosted PR pushing a new+// commit must move the dedup head SHA the same way a GitHub PR does, otherwise+// a fresh review round could be merged away against a stale key.+// reference_only links are excluded on both arms, matching the PR-list and+// close-aggregate queries: a body-only mention is hidden from the list and the+// close gate, so it must not win this ORDER BY and become the review dedup head+// SHA either, masking the real working PR's SHA.func (q *Queries) GetIssueReviewHeadSha(ctx context.Context, issueID pgtype.UUID) (string, error) {row := q.db.QueryRow(ctx, getIssueReviewHeadSha, issueID)var head_sha stringdiff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 64c626c60a..49dc5d7d91 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -339,7 +339,13 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith}const deleteIssue = `-- name: DeleteIssue :exec-DELETE FROM issue WHERE id = $1 AND workspace_id = $2+WITH target AS (+ SELECT issue.id FROM issue WHERE issue.id = $1 AND issue.workspace_id = $2+),+cleared_vcs_pr_links AS (+ DELETE FROM issue_vcs_pull_request WHERE issue_id IN (SELECT target.id FROM target)+)+DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target)`type DeleteIssueParams struct {@@ -352,6 +358,17 @@ type DeleteIssueParams struct {// (loadIssueForUser / GetIssueInWorkspace) already enforce membership today,// but a future loader bypass or a new caller skipping the loader would be// silently catastrophic without this guard. See incident #1661.+//+// issue_vcs_pull_request (migration 213) has no FK to issue, so the link rows+// are not cascaded away. Sweep them here so they go atomically with the issue.+// The mirrored PR rows themselves belong to the connection, not the issue, so+// they persist (matching the GitHub link behaviour).+//+// The sweep MUST route through the same workspace-checked target as the issue+// delete: deleting links by bare issue_id would drop another tenant's link rows+// when a caller passes a foreign issue_id with its own workspace_id (the issue+// itself is correctly untouched, but the links are already gone) — the exact+// cross-tenant leak the #1661 guard above exists to prevent.func (q *Queries) DeleteIssue(ctx context.Context, arg DeleteIssueParams) error {_, err := q.db.Exec(ctx, deleteIssue, arg.ID, arg.WorkspaceID)return errdiff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex ce4fd0f4cd..17caa06ebc 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -668,6 +668,16 @@ type IssueToLabel struct {LabelID pgtype.UUID `json:"label_id"`}+type IssueVcsPullRequest struct {+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`+ CloseIntent bool `json:"close_intent"`+ ReferenceOnly bool `json:"reference_only"`+ LinkedByType pgtype.Text `json:"linked_by_type"`+ LinkedByID pgtype.UUID `json:"linked_by_id"`+ LinkedAt pgtype.Timestamptz `json:"linked_at"`+}+type LarkBindingToken struct {TokenHash string `json:"token_hash"`WorkspaceID pgtype.UUID `json:"workspace_id"`@@ -1019,6 +1029,55 @@ type UserComposioConnection struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type VcsCommitStatus struct {+ ConnectionID pgtype.UUID `json:"connection_id"`+ Sha string `json:"sha"`+ Context string `json:"context"`+ State string `json:"state"`+ TargetUrl pgtype.Text `json:"target_url"`+ Description pgtype.Text `json:"description"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type VcsConnection struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Provider string `json:"provider"`+ InstanceUrl string `json:"instance_url"`+ AccountLogin string `json:"account_login"`+ AccessTokenEncrypted string `json:"access_token_encrypted"`+ WebhookSecretEncrypted string `json:"webhook_secret_encrypted"`+ ConnectedByID pgtype.UUID `json:"connected_by_id"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type VcsPullRequest struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ConnectionID pgtype.UUID `json:"connection_id"`+ Provider string `json:"provider"`+ RepoOwner string `json:"repo_owner"`+ RepoName string `json:"repo_name"`+ PrNumber int32 `json:"pr_number"`+ Title string `json:"title"`+ State string `json:"state"`+ HtmlUrl string `json:"html_url"`+ Branch pgtype.Text `json:"branch"`+ HeadSha string `json:"head_sha"`+ AuthorLogin pgtype.Text `json:"author_login"`+ AuthorAvatarUrl pgtype.Text `json:"author_avatar_url"`+ MergedAt pgtype.Timestamptz `json:"merged_at"`+ ClosedAt pgtype.Timestamptz `json:"closed_at"`+ PrCreatedAt pgtype.Timestamptz `json:"pr_created_at"`+ PrUpdatedAt pgtype.Timestamptz `json:"pr_updated_at"`+ Additions int32 `json:"additions"`+ Deletions int32 `json:"deletions"`+ ChangedFiles int32 `json:"changed_files"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type VerificationCode struct {ID pgtype.UUID `json:"id"`Email string `json:"email"`diff --git a/server/pkg/db/generated/vcs.sql.go b/server/pkg/db/generated/vcs.sql.gonew file mode 100644index 0000000000..3065baeccd--- /dev/null+++ b/server/pkg/db/generated/vcs.sql.go@@ -0,0 +1,594 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: vcs.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const deleteVCSConnection = `-- name: DeleteVCSConnection :exec+WITH target AS (+ SELECT vcs_connection.id FROM vcs_connection WHERE vcs_connection.id = $1 AND vcs_connection.workspace_id = $2+),+cleared_links AS (+ DELETE FROM issue_vcs_pull_request+ WHERE pull_request_id IN (+ SELECT vcs_pull_request.id FROM vcs_pull_request+ WHERE vcs_pull_request.connection_id IN (SELECT target.id FROM target)+ )+),+cleared_statuses AS (+ DELETE FROM vcs_commit_status WHERE connection_id IN (SELECT target.id FROM target)+),+cleared_prs AS (+ DELETE FROM vcs_pull_request WHERE connection_id IN (SELECT target.id FROM target)+)+DELETE FROM vcs_connection WHERE vcs_connection.id = $1 AND vcs_connection.workspace_id = $2+`++type DeleteVCSConnectionParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// These tables carry no FKs, so the cascade that once removed the connection's+// mirrored PRs, their issue links, and CI statuses is gone (migration 213). Do+// that cleanup explicitly here, in one statement so it commits or rolls back+// atomically with the connection row. The target CTE also scopes every child+// delete to a connection that actually belongs to the workspace, so a wrong+// workspace_id is a no-op rather than deleting another tenant's child rows.+func (q *Queries) DeleteVCSConnection(ctx context.Context, arg DeleteVCSConnectionParams) error {+ _, err := q.db.Exec(ctx, deleteVCSConnection, arg.ID, arg.WorkspaceID)+ return err+}++const getIssueCombinedPullRequestCloseAggregate = `-- name: GetIssueCombinedPullRequestCloseAggregate :one+WITH combined AS (+ SELECT pr.state AS state, ipr.close_intent AS close_intent+ FROM github_pull_request pr+ JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id+ WHERE ipr.issue_id = $1 AND NOT ipr.reference_only+ UNION ALL+ SELECT pr.state AS state, ipr.close_intent AS close_intent+ FROM vcs_pull_request pr+ JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+ WHERE ipr.issue_id = $1 AND NOT ipr.reference_only+)+SELECT+ COALESCE(SUM(CASE WHEN state IN ('open', 'draft') THEN 1 ELSE 0 END), 0)::bigint AS open_count,+ COALESCE(SUM(CASE WHEN state = 'merged' AND close_intent THEN 1 ELSE 0 END), 0)::bigint AS merged_with_close_intent_count+FROM combined+`++type GetIssueCombinedPullRequestCloseAggregateRow struct {+ OpenCount int64 `json:"open_count"`+ MergedWithCloseIntentCount int64 `json:"merged_with_close_intent_count"`+}++// Cross-provider close gate. An issue can carry PRs from GitHub AND a+// self-hosted VCS provider at the same time, so auto-advance has to see BOTH+// table pairs. Reading only one (as the per-provider aggregates do) lets a+// merged close-intent PR/MR on one provider advance an issue that still has an+// open PR on the other — either webhook is blind to the other's in-flight work.+// Sum the in-flight (open/draft) and merged-with-close-intent counts across+// github_pull_request+issue_pull_request and vcs_pull_request++// issue_vcs_pull_request. reference_only links are excluded on both sides, so a+// bare body mention neither counts as in-flight nor gates advance.+func (q *Queries) GetIssueCombinedPullRequestCloseAggregate(ctx context.Context, issueID pgtype.UUID) (GetIssueCombinedPullRequestCloseAggregateRow, error) {+ row := q.db.QueryRow(ctx, getIssueCombinedPullRequestCloseAggregate, issueID)+ var i GetIssueCombinedPullRequestCloseAggregateRow+ err := row.Scan(&i.OpenCount, &i.MergedWithCloseIntentCount)+ return i, err+}++const getVCSConnectionByID = `-- name: GetVCSConnectionByID :one+SELECT id, workspace_id, provider, instance_url, account_login, access_token_encrypted, webhook_secret_encrypted, connected_by_id, created_at, updated_at FROM vcs_connection+WHERE id = $1+`++func (q *Queries) GetVCSConnectionByID(ctx context.Context, id pgtype.UUID) (VcsConnection, error) {+ row := q.db.QueryRow(ctx, getVCSConnectionByID, id)+ var i VcsConnection+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Provider,+ &i.InstanceUrl,+ &i.AccountLogin,+ &i.AccessTokenEncrypted,+ &i.WebhookSecretEncrypted,+ &i.ConnectedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const linkIssueToVCSPullRequest = `-- name: LinkIssueToVCSPullRequest :exec++INSERT INTO issue_vcs_pull_request (+ issue_id, pull_request_id, linked_by_type, linked_by_id, close_intent, reference_only+) VALUES (+ $1, $2, $4, $5, $3, $6+)+ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET+ close_intent = CASE+ WHEN $7 THEN issue_vcs_pull_request.close_intent+ ELSE EXCLUDED.close_intent+ END,+ reference_only = CASE+ WHEN $7 THEN issue_vcs_pull_request.reference_only+ ELSE EXCLUDED.reference_only+ END+`++type LinkIssueToVCSPullRequestParams struct {+ IssueID pgtype.UUID `json:"issue_id"`+ PullRequestID pgtype.UUID `json:"pull_request_id"`+ CloseIntent bool `json:"close_intent"`+ LinkedByType pgtype.Text `json:"linked_by_type"`+ LinkedByID pgtype.UUID `json:"linked_by_id"`+ ReferenceOnly bool `json:"reference_only"`+ PreserveCloseIntent bool `json:"preserve_close_intent"`+}++// =====================+// Issue ↔ VCS PR link+// =====================+// reference_only marks a link justified ONLY by a bare body mention (no closing+// keyword and no title/branch reference), mirroring the GitHub link upsert.+// preserve_close_intent freezes both close_intent and reference_only once a+// terminal merge/close event has been recorded.+func (q *Queries) LinkIssueToVCSPullRequest(ctx context.Context, arg LinkIssueToVCSPullRequestParams) error {+ _, err := q.db.Exec(ctx, linkIssueToVCSPullRequest,+ arg.IssueID,+ arg.PullRequestID,+ arg.CloseIntent,+ arg.LinkedByType,+ arg.LinkedByID,+ arg.ReferenceOnly,+ arg.PreserveCloseIntent,+ )+ return err+}++const listIssueIDsForVCSPRHead = `-- name: ListIssueIDsForVCSPRHead :many+SELECT DISTINCT ipr.issue_id+FROM vcs_pull_request pr+JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+WHERE pr.connection_id = $1 AND pr.head_sha = $2 AND pr.head_sha <> ''+`++type ListIssueIDsForVCSPRHeadParams struct {+ ConnectionID pgtype.UUID `json:"connection_id"`+ HeadSha string `json:"head_sha"`+}++// Issues linked to any PR whose head sha matches the given status, so a+// commit-status event can fan out a PR-card refresh to the right issues.+func (q *Queries) ListIssueIDsForVCSPRHead(ctx context.Context, arg ListIssueIDsForVCSPRHeadParams) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listIssueIDsForVCSPRHead, arg.ConnectionID, arg.HeadSha)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var issue_id pgtype.UUID+ if err := rows.Scan(&issue_id); err != nil {+ return nil, err+ }+ items = append(items, issue_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listVCSConnectionsByWorkspace = `-- name: ListVCSConnectionsByWorkspace :many++SELECT id, workspace_id, provider, instance_url, account_login, access_token_encrypted, webhook_secret_encrypted, connected_by_id, created_at, updated_at FROM vcs_connection+WHERE workspace_id = $1+ORDER BY created_at ASC+`++// =====================+// VCS Connection (Forgejo / Gitea / GitLab)+// =====================+func (q *Queries) ListVCSConnectionsByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]VcsConnection, error) {+ rows, err := q.db.Query(ctx, listVCSConnectionsByWorkspace, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []VcsConnection{}+ for rows.Next() {+ var i VcsConnection+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Provider,+ &i.InstanceUrl,+ &i.AccountLogin,+ &i.AccessTokenEncrypted,+ &i.WebhookSecretEncrypted,+ &i.ConnectedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listVCSPullRequestsByIssue = `-- name: ListVCSPullRequestsByIssue :many+WITH checks AS (+ SELECT+ pr.id AS pr_id,+ COUNT(*)::bigint AS total,+ SUM(CASE WHEN cs.state = 'failed' THEN 1 ELSE 0 END)::bigint AS failed,+ SUM(CASE WHEN cs.state = 'passed' THEN 1 ELSE 0 END)::bigint AS passed,+ SUM(CASE WHEN cs.state = 'pending' THEN 1 ELSE 0 END)::bigint AS pending+ FROM vcs_pull_request pr+ JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+ JOIN vcs_commit_status cs+ ON cs.connection_id = pr.connection_id+ AND cs.sha = pr.head_sha+ AND pr.head_sha <> ''+ WHERE ipr.issue_id = $1 AND NOT ipr.reference_only+ GROUP BY pr.id+)+SELECT+ pr.id, pr.workspace_id, pr.connection_id, pr.provider, pr.repo_owner, pr.repo_name, pr.pr_number, pr.title, pr.state, pr.html_url, pr.branch, pr.head_sha, pr.author_login, pr.author_avatar_url, pr.merged_at, pr.closed_at, pr.pr_created_at, pr.pr_updated_at, pr.additions, pr.deletions, pr.changed_files, pr.created_at, pr.updated_at,+ COALESCE(c.total, 0)::bigint AS checks_total,+ COALESCE(c.passed, 0)::bigint AS checks_passed,+ COALESCE(c.failed, 0)::bigint AS checks_failed,+ COALESCE(c.pending, 0)::bigint AS checks_pending+FROM vcs_pull_request pr+JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+LEFT JOIN checks c ON c.pr_id = pr.id+WHERE ipr.issue_id = $1 AND NOT ipr.reference_only+ORDER BY pr.pr_created_at DESC+`++type ListVCSPullRequestsByIssueRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ConnectionID pgtype.UUID `json:"connection_id"`+ Provider string `json:"provider"`+ RepoOwner string `json:"repo_owner"`+ RepoName string `json:"repo_name"`+ PrNumber int32 `json:"pr_number"`+ Title string `json:"title"`+ State string `json:"state"`+ HtmlUrl string `json:"html_url"`+ Branch pgtype.Text `json:"branch"`+ HeadSha string `json:"head_sha"`+ AuthorLogin pgtype.Text `json:"author_login"`+ AuthorAvatarUrl pgtype.Text `json:"author_avatar_url"`+ MergedAt pgtype.Timestamptz `json:"merged_at"`+ ClosedAt pgtype.Timestamptz `json:"closed_at"`+ PrCreatedAt pgtype.Timestamptz `json:"pr_created_at"`+ PrUpdatedAt pgtype.Timestamptz `json:"pr_updated_at"`+ Additions int32 `json:"additions"`+ Deletions int32 `json:"deletions"`+ ChangedFiles int32 `json:"changed_files"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ ChecksTotal int64 `json:"checks_total"`+ ChecksPassed int64 `json:"checks_passed"`+ ChecksFailed int64 `json:"checks_failed"`+ ChecksPending int64 `json:"checks_pending"`+}++// Aggregates each PR's commit statuses for its CURRENT head sha into+// passed/failed/pending counts. vcs_commit_status holds one row per+// (connection, sha, context) with a normalized state, so a count by state is+// correct. Statuses for an old head sha stay stored but are excluded by the+// head_sha join, so a stale run can't pollute the bar.+func (q *Queries) ListVCSPullRequestsByIssue(ctx context.Context, issueID pgtype.UUID) ([]ListVCSPullRequestsByIssueRow, error) {+ rows, err := q.db.Query(ctx, listVCSPullRequestsByIssue, issueID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListVCSPullRequestsByIssueRow{}+ for rows.Next() {+ var i ListVCSPullRequestsByIssueRow+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ConnectionID,+ &i.Provider,+ &i.RepoOwner,+ &i.RepoName,+ &i.PrNumber,+ &i.Title,+ &i.State,+ &i.HtmlUrl,+ &i.Branch,+ &i.HeadSha,+ &i.AuthorLogin,+ &i.AuthorAvatarUrl,+ &i.MergedAt,+ &i.ClosedAt,+ &i.PrCreatedAt,+ &i.PrUpdatedAt,+ &i.Additions,+ &i.Deletions,+ &i.ChangedFiles,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ChecksTotal,+ &i.ChecksPassed,+ &i.ChecksFailed,+ &i.ChecksPending,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const rotateVCSConnectionWebhookSecret = `-- name: RotateVCSConnectionWebhookSecret :one+UPDATE vcs_connection+SET webhook_secret_encrypted = $3,+ updated_at = now()+WHERE id = $1 AND workspace_id = $2+RETURNING id, workspace_id, provider, instance_url, account_login, access_token_encrypted, webhook_secret_encrypted, connected_by_id, created_at, updated_at+`++type RotateVCSConnectionWebhookSecretParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ WebhookSecretEncrypted string `json:"webhook_secret_encrypted"`+}++func (q *Queries) RotateVCSConnectionWebhookSecret(ctx context.Context, arg RotateVCSConnectionWebhookSecretParams) (VcsConnection, error) {+ row := q.db.QueryRow(ctx, rotateVCSConnectionWebhookSecret, arg.ID, arg.WorkspaceID, arg.WebhookSecretEncrypted)+ var i VcsConnection+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Provider,+ &i.InstanceUrl,+ &i.AccountLogin,+ &i.AccessTokenEncrypted,+ &i.WebhookSecretEncrypted,+ &i.ConnectedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const upsertVCSCommitStatus = `-- name: UpsertVCSCommitStatus :exec++INSERT INTO vcs_commit_status (+ connection_id, sha, context, state, target_url, description, updated_at+) VALUES (+ $1, $2, $3, $4, $6, $7, $5+)+ON CONFLICT (connection_id, sha, context) DO UPDATE SET+ state = EXCLUDED.state,+ target_url = EXCLUDED.target_url,+ description = EXCLUDED.description,+ updated_at = EXCLUDED.updated_at+WHERE EXCLUDED.updated_at >= vcs_commit_status.updated_at+`++type UpsertVCSCommitStatusParams struct {+ ConnectionID pgtype.UUID `json:"connection_id"`+ Sha string `json:"sha"`+ Context string `json:"context"`+ State string `json:"state"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ TargetUrl pgtype.Text `json:"target_url"`+ Description pgtype.Text `json:"description"`+}++// =====================+// VCS commit status (CI)+// =====================+// One row per (connection, sha, context); a redelivery or state transition+// overwrites in place. updated_at guards against an older event overwriting a+// newer one for the same context. state is normalized (passed/failed/pending).+func (q *Queries) UpsertVCSCommitStatus(ctx context.Context, arg UpsertVCSCommitStatusParams) error {+ _, err := q.db.Exec(ctx, upsertVCSCommitStatus,+ arg.ConnectionID,+ arg.Sha,+ arg.Context,+ arg.State,+ arg.UpdatedAt,+ arg.TargetUrl,+ arg.Description,+ )+ return err+}++const upsertVCSConnection = `-- name: UpsertVCSConnection :one+INSERT INTO vcs_connection (+ workspace_id, provider, instance_url, account_login,+ access_token_encrypted, webhook_secret_encrypted, connected_by_id+) VALUES (+ $1, $2, $3, $4, $5, $6, $7+)+ON CONFLICT (workspace_id, instance_url) DO UPDATE SET+ provider = EXCLUDED.provider,+ account_login = EXCLUDED.account_login,+ access_token_encrypted = EXCLUDED.access_token_encrypted,+ webhook_secret_encrypted = EXCLUDED.webhook_secret_encrypted,+ connected_by_id = EXCLUDED.connected_by_id,+ updated_at = now()+RETURNING id, workspace_id, provider, instance_url, account_login, access_token_encrypted, webhook_secret_encrypted, connected_by_id, created_at, updated_at+`++type UpsertVCSConnectionParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Provider string `json:"provider"`+ InstanceUrl string `json:"instance_url"`+ AccountLogin string `json:"account_login"`+ AccessTokenEncrypted string `json:"access_token_encrypted"`+ WebhookSecretEncrypted string `json:"webhook_secret_encrypted"`+ ConnectedByID pgtype.UUID `json:"connected_by_id"`+}++// Reconnecting the same instance rotates the stored token/secret, provider,+// and identity in place rather than creating a duplicate row.+func (q *Queries) UpsertVCSConnection(ctx context.Context, arg UpsertVCSConnectionParams) (VcsConnection, error) {+ row := q.db.QueryRow(ctx, upsertVCSConnection,+ arg.WorkspaceID,+ arg.Provider,+ arg.InstanceUrl,+ arg.AccountLogin,+ arg.AccessTokenEncrypted,+ arg.WebhookSecretEncrypted,+ arg.ConnectedByID,+ )+ var i VcsConnection+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Provider,+ &i.InstanceUrl,+ &i.AccountLogin,+ &i.AccessTokenEncrypted,+ &i.WebhookSecretEncrypted,+ &i.ConnectedByID,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const upsertVCSPullRequest = `-- name: UpsertVCSPullRequest :one++INSERT INTO vcs_pull_request (+ workspace_id, connection_id, provider, repo_owner, repo_name, pr_number,+ title, state, html_url, branch, author_login, author_avatar_url,+ merged_at, closed_at, pr_created_at, pr_updated_at,+ additions, deletions, changed_files, head_sha+) VALUES (+ $1, $2, $3, $4, $5, $6,+ $7, $8, $9, $16, $17, $18,+ $19, $20, $10, $11,+ $12, $13, $14, $15+)+ON CONFLICT (connection_id, repo_owner, repo_name, pr_number) DO UPDATE SET+ workspace_id = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.workspace_id ELSE vcs_pull_request.workspace_id END,+ provider = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.provider ELSE vcs_pull_request.provider END,+ title = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.title ELSE vcs_pull_request.title END,+ state = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.state ELSE vcs_pull_request.state END,+ html_url = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.html_url ELSE vcs_pull_request.html_url END,+ branch = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.branch ELSE vcs_pull_request.branch END,+ author_login = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.author_login ELSE vcs_pull_request.author_login END,+ author_avatar_url = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.author_avatar_url ELSE vcs_pull_request.author_avatar_url END,+ merged_at = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.merged_at ELSE vcs_pull_request.merged_at END,+ closed_at = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.closed_at ELSE vcs_pull_request.closed_at END,+ pr_updated_at = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.pr_updated_at ELSE vcs_pull_request.pr_updated_at END,+ additions = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.additions ELSE vcs_pull_request.additions END,+ deletions = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.deletions ELSE vcs_pull_request.deletions END,+ changed_files = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.changed_files ELSE vcs_pull_request.changed_files END,+ head_sha = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.head_sha ELSE vcs_pull_request.head_sha END,+ updated_at = now()+RETURNING id, workspace_id, connection_id, provider, repo_owner, repo_name, pr_number, title, state, html_url, branch, head_sha, author_login, author_avatar_url, merged_at, closed_at, pr_created_at, pr_updated_at, additions, deletions, changed_files, created_at, updated_at+`++type UpsertVCSPullRequestParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ConnectionID pgtype.UUID `json:"connection_id"`+ Provider string `json:"provider"`+ RepoOwner string `json:"repo_owner"`+ RepoName string `json:"repo_name"`+ PrNumber int32 `json:"pr_number"`+ Title string `json:"title"`+ State string `json:"state"`+ HtmlUrl string `json:"html_url"`+ PrCreatedAt pgtype.Timestamptz `json:"pr_created_at"`+ PrUpdatedAt pgtype.Timestamptz `json:"pr_updated_at"`+ Additions int32 `json:"additions"`+ Deletions int32 `json:"deletions"`+ ChangedFiles int32 `json:"changed_files"`+ HeadSha string `json:"head_sha"`+ Branch pgtype.Text `json:"branch"`+ AuthorLogin pgtype.Text `json:"author_login"`+ AuthorAvatarUrl pgtype.Text `json:"author_avatar_url"`+ MergedAt pgtype.Timestamptz `json:"merged_at"`+ ClosedAt pgtype.Timestamptz `json:"closed_at"`+}++// =====================+// VCS Pull Request+// =====================+// pr_updated_at guards against an out-of-order webhook redelivery regressing+// the PR state, mirroring the updated_at guard on UpsertVCSCommitStatus. Each+// mutable column is applied only when the incoming event is at least as new as+// the stored row; a stale event keeps the existing values. The row is still+// touched (and thus RETURNED) either way, so callers always get the current PR+// — the webhook needs pr.id to link the issue even on a stale redelivery.+func (q *Queries) UpsertVCSPullRequest(ctx context.Context, arg UpsertVCSPullRequestParams) (VcsPullRequest, error) {+ row := q.db.QueryRow(ctx, upsertVCSPullRequest,+ arg.WorkspaceID,+ arg.ConnectionID,+ arg.Provider,+ arg.RepoOwner,+ arg.RepoName,+ arg.PrNumber,+ arg.Title,+ arg.State,+ arg.HtmlUrl,+ arg.PrCreatedAt,+ arg.PrUpdatedAt,+ arg.Additions,+ arg.Deletions,+ arg.ChangedFiles,+ arg.HeadSha,+ arg.Branch,+ arg.AuthorLogin,+ arg.AuthorAvatarUrl,+ arg.MergedAt,+ arg.ClosedAt,+ )+ var i VcsPullRequest+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ConnectionID,+ &i.Provider,+ &i.RepoOwner,+ &i.RepoName,+ &i.PrNumber,+ &i.Title,+ &i.State,+ &i.HtmlUrl,+ &i.Branch,+ &i.HeadSha,+ &i.AuthorLogin,+ &i.AuthorAvatarUrl,+ &i.MergedAt,+ &i.ClosedAt,+ &i.PrCreatedAt,+ &i.PrUpdatedAt,+ &i.Additions,+ &i.Deletions,+ &i.ChangedFiles,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex bd352cd074..feeb2f79bc 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -116,6 +116,26 @@ cleared_issue_properties AS (deleted_pending_check_suites AS (DELETE FROM github_pending_check_suite WHERE workspace_id = $1),+ws_vcs_prs AS (+ SELECT id FROM vcs_pull_request WHERE workspace_id = $1+),+ws_vcs_connections AS (+ SELECT id FROM vcs_connection WHERE workspace_id = $1+),+cleared_vcs_pr_links AS (+ DELETE FROM issue_vcs_pull_request+ WHERE pull_request_id IN (SELECT id FROM ws_vcs_prs)+),+cleared_vcs_commit_statuses AS (+ DELETE FROM vcs_commit_status+ WHERE connection_id IN (SELECT id FROM ws_vcs_connections)+),+cleared_vcs_prs AS (+ DELETE FROM vcs_pull_request WHERE workspace_id = $1+),+cleared_vcs_connections AS (+ DELETE FROM vcs_connection WHERE workspace_id = $1+),cleared_client_usage_workspace AS (UPDATE client_usage_daily SET workspace_id = NULL WHERE workspace_id = $1)@@ -127,6 +147,11 @@ DELETE FROM workspace WHERE workspace.id = $1// tables the DELETE below sweeps — they are not cleaned up implicitly. Remove// their workspace-owned rows here so they commit or roll back atomically with// the workspace row.+// VCS tables (migration 213) carry no FK to workspace, so they are not cascaded+// away by the DELETE below. Sweep the workspace's connections, mirrored PRs,+// their issue links, and CI statuses here. issue_vcs_pull_request has no+// workspace_id, so reach it through the workspace's PRs; vcs_commit_status has+// none either, so reach it through the workspace's connections.func (q *Queries) DeleteWorkspace(ctx context.Context, id pgtype.UUID) error {_, err := q.db.Exec(ctx, deleteWorkspace, id)return errdiff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sqlindex 0b3fda2a41..91c0fa1a12 100644--- a/server/pkg/db/queries/github.sql+++ b/server/pkg/db/queries/github.sql@@ -197,11 +197,26 @@ ORDER BY pr.pr_created_at DESC;-- newest linked PR with a head_sha when none are open. Returns no rows (empty-- string) when the issue has no linked PR — callers treat that as "no SHA key"-- and dedup on (issue_id, agent_id) alone, preserving pre-TEN-356 behavior.-SELECT pr.head_sha-FROM github_pull_request pr-JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id-WHERE ipr.issue_id = $1 AND pr.head_sha <> ''-ORDER BY (pr.state IN ('open', 'draft')) DESC, pr.pr_updated_at DESC+--+-- Spans both GitHub and self-hosted VCS PRs: a self-hosted PR pushing a new+-- commit must move the dedup head SHA the same way a GitHub PR does, otherwise+-- a fresh review round could be merged away against a stale key.+-- reference_only links are excluded on both arms, matching the PR-list and+-- close-aggregate queries: a body-only mention is hidden from the list and the+-- close gate, so it must not win this ORDER BY and become the review dedup head+-- SHA either, masking the real working PR's SHA.+SELECT head_sha FROM (+ SELECT pr.head_sha AS head_sha, pr.state AS state, pr.pr_updated_at AS pr_updated_at+ FROM github_pull_request pr+ JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id+ WHERE ipr.issue_id = $1 AND pr.head_sha <> '' AND NOT ipr.reference_only+ UNION ALL+ SELECT pr.head_sha AS head_sha, pr.state AS state, pr.pr_updated_at AS pr_updated_at+ FROM vcs_pull_request pr+ JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+ WHERE ipr.issue_id = $1 AND pr.head_sha <> '' AND NOT ipr.reference_only+) combined+ORDER BY (state IN ('open', 'draft')) DESC, pr_updated_at DESCLIMIT 1;-- name: ListIssueIDsForPullRequest :manydiff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 1e977ac3ae..91d7d6f089 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -170,7 +170,24 @@ LIMIT 1;-- (loadIssueForUser / GetIssueInWorkspace) already enforce membership today,-- but a future loader bypass or a new caller skipping the loader would be-- silently catastrophic without this guard. See incident #1661.-DELETE FROM issue WHERE id = $1 AND workspace_id = $2;+--+-- issue_vcs_pull_request (migration 213) has no FK to issue, so the link rows+-- are not cascaded away. Sweep them here so they go atomically with the issue.+-- The mirrored PR rows themselves belong to the connection, not the issue, so+-- they persist (matching the GitHub link behaviour).+--+-- The sweep MUST route through the same workspace-checked target as the issue+-- delete: deleting links by bare issue_id would drop another tenant's link rows+-- when a caller passes a foreign issue_id with its own workspace_id (the issue+-- itself is correctly untouched, but the links are already gone) — the exact+-- cross-tenant leak the #1661 guard above exists to prevent.+WITH target AS (+ SELECT issue.id FROM issue WHERE issue.id = $1 AND issue.workspace_id = $2+),+cleared_vcs_pr_links AS (+ DELETE FROM issue_vcs_pull_request WHERE issue_id IN (SELECT target.id FROM target)+)+DELETE FROM issue WHERE issue.id IN (SELECT target.id FROM target);-- name: ListOpenIssues :many-- See ListIssues for the semantics of involves_user_id (mirrors the 4-branchdiff --git a/server/pkg/db/queries/vcs.sql b/server/pkg/db/queries/vcs.sqlnew file mode 100644index 0000000000..0d38360dea--- /dev/null+++ b/server/pkg/db/queries/vcs.sql@@ -0,0 +1,215 @@+-- =====================+-- VCS Connection (Forgejo / Gitea / GitLab)+-- =====================++-- name: ListVCSConnectionsByWorkspace :many+SELECT * FROM vcs_connection+WHERE workspace_id = $1+ORDER BY created_at ASC;++-- name: GetVCSConnectionByID :one+SELECT * FROM vcs_connection+WHERE id = $1;++-- name: UpsertVCSConnection :one+-- Reconnecting the same instance rotates the stored token/secret, provider,+-- and identity in place rather than creating a duplicate row.+INSERT INTO vcs_connection (+ workspace_id, provider, instance_url, account_login,+ access_token_encrypted, webhook_secret_encrypted, connected_by_id+) VALUES (+ $1, $2, $3, $4, $5, $6, sqlc.narg('connected_by_id')+)+ON CONFLICT (workspace_id, instance_url) DO UPDATE SET+ provider = EXCLUDED.provider,+ account_login = EXCLUDED.account_login,+ access_token_encrypted = EXCLUDED.access_token_encrypted,+ webhook_secret_encrypted = EXCLUDED.webhook_secret_encrypted,+ connected_by_id = EXCLUDED.connected_by_id,+ updated_at = now()+RETURNING *;++-- name: DeleteVCSConnection :exec+-- These tables carry no FKs, so the cascade that once removed the connection's+-- mirrored PRs, their issue links, and CI statuses is gone (migration 213). Do+-- that cleanup explicitly here, in one statement so it commits or rolls back+-- atomically with the connection row. The target CTE also scopes every child+-- delete to a connection that actually belongs to the workspace, so a wrong+-- workspace_id is a no-op rather than deleting another tenant's child rows.+WITH target AS (+ SELECT vcs_connection.id FROM vcs_connection WHERE vcs_connection.id = $1 AND vcs_connection.workspace_id = $2+),+cleared_links AS (+ DELETE FROM issue_vcs_pull_request+ WHERE pull_request_id IN (+ SELECT vcs_pull_request.id FROM vcs_pull_request+ WHERE vcs_pull_request.connection_id IN (SELECT target.id FROM target)+ )+),+cleared_statuses AS (+ DELETE FROM vcs_commit_status WHERE connection_id IN (SELECT target.id FROM target)+),+cleared_prs AS (+ DELETE FROM vcs_pull_request WHERE connection_id IN (SELECT target.id FROM target)+)+DELETE FROM vcs_connection WHERE vcs_connection.id = $1 AND vcs_connection.workspace_id = $2;++-- name: RotateVCSConnectionWebhookSecret :one+UPDATE vcs_connection+SET webhook_secret_encrypted = $3,+ updated_at = now()+WHERE id = $1 AND workspace_id = $2+RETURNING *;++-- =====================+-- VCS Pull Request+-- =====================++-- name: UpsertVCSPullRequest :one+-- pr_updated_at guards against an out-of-order webhook redelivery regressing+-- the PR state, mirroring the updated_at guard on UpsertVCSCommitStatus. Each+-- mutable column is applied only when the incoming event is at least as new as+-- the stored row; a stale event keeps the existing values. The row is still+-- touched (and thus RETURNED) either way, so callers always get the current PR+-- — the webhook needs pr.id to link the issue even on a stale redelivery.+INSERT INTO vcs_pull_request (+ workspace_id, connection_id, provider, repo_owner, repo_name, pr_number,+ title, state, html_url, branch, author_login, author_avatar_url,+ merged_at, closed_at, pr_created_at, pr_updated_at,+ additions, deletions, changed_files, head_sha+) VALUES (+ $1, $2, $3, $4, $5, $6,+ $7, $8, $9, sqlc.narg('branch'), sqlc.narg('author_login'), sqlc.narg('author_avatar_url'),+ sqlc.narg('merged_at'), sqlc.narg('closed_at'), $10, $11,+ $12, $13, $14, $15+)+ON CONFLICT (connection_id, repo_owner, repo_name, pr_number) DO UPDATE SET+ workspace_id = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.workspace_id ELSE vcs_pull_request.workspace_id END,+ provider = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.provider ELSE vcs_pull_request.provider END,+ title = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.title ELSE vcs_pull_request.title END,+ state = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.state ELSE vcs_pull_request.state END,+ html_url = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.html_url ELSE vcs_pull_request.html_url END,+ branch = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.branch ELSE vcs_pull_request.branch END,+ author_login = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.author_login ELSE vcs_pull_request.author_login END,+ author_avatar_url = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.author_avatar_url ELSE vcs_pull_request.author_avatar_url END,+ merged_at = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.merged_at ELSE vcs_pull_request.merged_at END,+ closed_at = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.closed_at ELSE vcs_pull_request.closed_at END,+ pr_updated_at = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.pr_updated_at ELSE vcs_pull_request.pr_updated_at END,+ additions = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.additions ELSE vcs_pull_request.additions END,+ deletions = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.deletions ELSE vcs_pull_request.deletions END,+ changed_files = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.changed_files ELSE vcs_pull_request.changed_files END,+ head_sha = CASE WHEN EXCLUDED.pr_updated_at >= vcs_pull_request.pr_updated_at THEN EXCLUDED.head_sha ELSE vcs_pull_request.head_sha END,+ updated_at = now()+RETURNING *;++-- name: ListVCSPullRequestsByIssue :many+-- Aggregates each PR's commit statuses for its CURRENT head sha into+-- passed/failed/pending counts. vcs_commit_status holds one row per+-- (connection, sha, context) with a normalized state, so a count by state is+-- correct. Statuses for an old head sha stay stored but are excluded by the+-- head_sha join, so a stale run can't pollute the bar.+WITH checks AS (+ SELECT+ pr.id AS pr_id,+ COUNT(*)::bigint AS total,+ SUM(CASE WHEN cs.state = 'failed' THEN 1 ELSE 0 END)::bigint AS failed,+ SUM(CASE WHEN cs.state = 'passed' THEN 1 ELSE 0 END)::bigint AS passed,+ SUM(CASE WHEN cs.state = 'pending' THEN 1 ELSE 0 END)::bigint AS pending+ FROM vcs_pull_request pr+ JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+ JOIN vcs_commit_status cs+ ON cs.connection_id = pr.connection_id+ AND cs.sha = pr.head_sha+ AND pr.head_sha <> ''+ WHERE ipr.issue_id = sqlc.arg('issue_id') AND NOT ipr.reference_only+ GROUP BY pr.id+)+SELECT+ pr.*,+ COALESCE(c.total, 0)::bigint AS checks_total,+ COALESCE(c.passed, 0)::bigint AS checks_passed,+ COALESCE(c.failed, 0)::bigint AS checks_failed,+ COALESCE(c.pending, 0)::bigint AS checks_pending+FROM vcs_pull_request pr+JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+LEFT JOIN checks c ON c.pr_id = pr.id+WHERE ipr.issue_id = sqlc.arg('issue_id') AND NOT ipr.reference_only+ORDER BY pr.pr_created_at DESC;++-- name: GetIssueCombinedPullRequestCloseAggregate :one+-- Cross-provider close gate. An issue can carry PRs from GitHub AND a+-- self-hosted VCS provider at the same time, so auto-advance has to see BOTH+-- table pairs. Reading only one (as the per-provider aggregates do) lets a+-- merged close-intent PR/MR on one provider advance an issue that still has an+-- open PR on the other — either webhook is blind to the other's in-flight work.+-- Sum the in-flight (open/draft) and merged-with-close-intent counts across+-- github_pull_request+issue_pull_request and vcs_pull_request++-- issue_vcs_pull_request. reference_only links are excluded on both sides, so a+-- bare body mention neither counts as in-flight nor gates advance.+WITH combined AS (+ SELECT pr.state AS state, ipr.close_intent AS close_intent+ FROM github_pull_request pr+ JOIN issue_pull_request ipr ON ipr.pull_request_id = pr.id+ WHERE ipr.issue_id = $1 AND NOT ipr.reference_only+ UNION ALL+ SELECT pr.state AS state, ipr.close_intent AS close_intent+ FROM vcs_pull_request pr+ JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+ WHERE ipr.issue_id = $1 AND NOT ipr.reference_only+)+SELECT+ COALESCE(SUM(CASE WHEN state IN ('open', 'draft') THEN 1 ELSE 0 END), 0)::bigint AS open_count,+ COALESCE(SUM(CASE WHEN state = 'merged' AND close_intent THEN 1 ELSE 0 END), 0)::bigint AS merged_with_close_intent_count+FROM combined;++-- =====================+-- VCS commit status (CI)+-- =====================++-- name: UpsertVCSCommitStatus :exec+-- One row per (connection, sha, context); a redelivery or state transition+-- overwrites in place. updated_at guards against an older event overwriting a+-- newer one for the same context. state is normalized (passed/failed/pending).+INSERT INTO vcs_commit_status (+ connection_id, sha, context, state, target_url, description, updated_at+) VALUES (+ $1, $2, $3, $4, sqlc.narg('target_url'), sqlc.narg('description'), $5+)+ON CONFLICT (connection_id, sha, context) DO UPDATE SET+ state = EXCLUDED.state,+ target_url = EXCLUDED.target_url,+ description = EXCLUDED.description,+ updated_at = EXCLUDED.updated_at+WHERE EXCLUDED.updated_at >= vcs_commit_status.updated_at;++-- name: ListIssueIDsForVCSPRHead :many+-- Issues linked to any PR whose head sha matches the given status, so a+-- commit-status event can fan out a PR-card refresh to the right issues.+SELECT DISTINCT ipr.issue_id+FROM vcs_pull_request pr+JOIN issue_vcs_pull_request ipr ON ipr.pull_request_id = pr.id+WHERE pr.connection_id = $1 AND pr.head_sha = $2 AND pr.head_sha <> '';++-- =====================+-- Issue ↔ VCS PR link+-- =====================++-- name: LinkIssueToVCSPullRequest :exec+-- reference_only marks a link justified ONLY by a bare body mention (no closing+-- keyword and no title/branch reference), mirroring the GitHub link upsert.+-- preserve_close_intent freezes both close_intent and reference_only once a+-- terminal merge/close event has been recorded.+INSERT INTO issue_vcs_pull_request (+ issue_id, pull_request_id, linked_by_type, linked_by_id, close_intent, reference_only+) VALUES (+ $1, $2, sqlc.narg('linked_by_type'), sqlc.narg('linked_by_id'), $3, sqlc.arg('reference_only')+)+ON CONFLICT (issue_id, pull_request_id) DO UPDATE SET+ close_intent = CASE+ WHEN sqlc.arg('preserve_close_intent') THEN issue_vcs_pull_request.close_intent+ ELSE EXCLUDED.close_intent+ END,+ reference_only = CASE+ WHEN sqlc.arg('preserve_close_intent') THEN issue_vcs_pull_request.reference_only+ ELSE EXCLUDED.reference_only+ END;diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sqlindex b892b372aa..55893850d1 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -159,6 +159,31 @@ cleared_issue_properties AS (deleted_pending_check_suites AS (DELETE FROM github_pending_check_suite WHERE workspace_id = $1),+-- VCS tables (migration 213) carry no FK to workspace, so they are not cascaded+-- away by the DELETE below. Sweep the workspace's connections, mirrored PRs,+-- their issue links, and CI statuses here. issue_vcs_pull_request has no+-- workspace_id, so reach it through the workspace's PRs; vcs_commit_status has+-- none either, so reach it through the workspace's connections.+ws_vcs_prs AS (+ SELECT id FROM vcs_pull_request WHERE workspace_id = $1+),+ws_vcs_connections AS (+ SELECT id FROM vcs_connection WHERE workspace_id = $1+),+cleared_vcs_pr_links AS (+ DELETE FROM issue_vcs_pull_request+ WHERE pull_request_id IN (SELECT id FROM ws_vcs_prs)+),+cleared_vcs_commit_statuses AS (+ DELETE FROM vcs_commit_status+ WHERE connection_id IN (SELECT id FROM ws_vcs_connections)+),+cleared_vcs_prs AS (+ DELETE FROM vcs_pull_request WHERE workspace_id = $1+),+cleared_vcs_connections AS (+ DELETE FROM vcs_connection WHERE workspace_id = $1+),cleared_client_usage_workspace AS (UPDATE client_usage_daily SET workspace_id = NULL WHERE workspace_id = $1)diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 831a1109bf..e6f063f607 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -147,6 +147,10 @@ const (EventPullRequestUpdated = "pull_request:updated"EventPullRequestUnlinked = "pull_request:unlinked"+ // VCS integration events (Forgejo / Gitea / GitLab)+ EventVCSConnectionCreated = "vcs_connection:created"+ EventVCSConnectionDeleted = "vcs_connection:deleted"+// Lark integration events. `created` covers both first-install// (UNIQUE on (workspace_id, agent_id) means at most one row per// agent) and re-install via UpsertLarkInstallation — front-ends