Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(api): add GitLab plugin with webhooks and sync helpers

zaralX7aab29a61e27
diff --git a/apps/api/src/plugins/gitlab/config.ts b/apps/api/src/plugins/gitlab/config.ts
new file mode 100644
index 000000000..bf46bfb3f
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/config.ts
@@ -0,0 +1,121 @@
+import * as v from "valibot";
+import { branchPatterns } from "../github/config";
+
+export { branchPatterns };
+
+export const gitlabConfigSchema = v.object({
+ baseUrl: v.pipe(v.string(), v.url()),
+ accessToken: v.pipe(v.string(), v.trim(), v.nonEmpty()),
+ // GitLab accepts personal, project and group tokens in PRIVATE-TOKEN, and
+ // OAuth2 tokens in Authorization: Bearer. The user picks which they pasted.
+ tokenType: v.optional(v.picklist(["private", "bearer"])),
+ // Nested groups make a single path the only workable identifier, so unlike
+ // the Gitea config there is no owner/name split.
+ projectPath: v.pipe(v.string(), v.trim(), v.nonEmpty()),
+ webhookSecret: v.optional(v.string()),
+ branchPattern: v.optional(v.string()),
+ customBranchRegex: v.optional(v.string()),
+ commentTaskLinkOnGitlabIssue: v.optional(v.boolean()),
+ statusTransitions: v.optional(
+ v.object({
+ onBranchPush: v.optional(v.string()),
+ onPROpen: v.optional(v.string()),
+ onPRMerge: v.optional(v.string()),
+ }),
+ ),
+});
+
+export type GitlabConfig = v.InferOutput<typeof gitlabConfigSchema>;
+
+export type GitlabTokenType = "private" | "bearer";
+
+export async function validateGitlabConfig(
+ config: unknown,
+): Promise<{ valid: boolean; errors?: string[] }> {
+ try {
+ v.parse(gitlabConfigSchema, config);
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof v.ValiError) {
+ return {
+ valid: false,
+ errors: error.issues.map((issue) => issue.message),
+ };
+ }
+ return {
+ valid: false,
+ errors: [error instanceof Error ? error.message : "Invalid config"],
+ };
+ }
+}
+
+export const GITLAB_CLOUD_URL = "https://gitlab.com";
+
+export const defaultGitlabConfig: Partial<GitlabConfig> = {
+ branchPattern: "{slug}-{number}",
+ commentTaskLinkOnGitlabIssue: true,
+ statusTransitions: {
+ onBranchPush: "in-progress",
+ onPROpen: "in-review",
+ onPRMerge: "done",
+ },
+};
+
+export function normalizeGitlabBaseUrl(url: string): string {
+ const trimmed = url.trim().replace(/\/+$/, "");
+ const parsed = new URL(trimmed);
+
+ if (!["http:", "https:"].includes(parsed.protocol)) {
+ throw new Error("GitLab base URL must use http or https");
+ }
+
+ // A query or fragment would swallow the appended /api/v4/... path and let a
+ // caller aim the request at an arbitrary path on the target host.
+ if (parsed.search || parsed.hash || parsed.username || parsed.password) {
+ throw new Error(
+ "GitLab base URL must not contain a query, fragment, or credentials",
+ );
+ }
+
+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;
+}
+
+// Paths arrive from a form and from webhook payloads, and both reach the API
+// as a single encoded path segment, so a leading slash or a stray ".." must not
+// survive into the request.
+export function normalizeProjectPath(path: string): string {
+ const segments = path
+ .trim()
+ .replace(/^\/+|\/+$/g, "")
+ .split("/")
+ .filter(Boolean);
+
+ if (segments.length < 2) {
+ throw new Error(
+ "GitLab project path must include a namespace, for example group/project",
+ );
+ }
+
+ if (segments.some((segment) => segment === "." || segment === "..")) {
+ throw new Error("GitLab project path must not contain relative segments");
+ }
+
+ return segments.join("/");
+}
+
+export function getDefaultGitlabConfig(
+ baseUrl: string,
+ accessToken: string,
+ tokenType: GitlabTokenType,
+ projectPath: string,
+ webhookSecret: string,
+): GitlabConfig {
+ return {
+ baseUrl: normalizeGitlabBaseUrl(baseUrl),
+ accessToken,
+ tokenType,
+ projectPath: normalizeProjectPath(projectPath),
+ webhookSecret,
+ ...defaultGitlabConfig,
+ };
+}
diff --git a/apps/api/src/plugins/gitlab/events/task-comment-created.ts b/apps/api/src/plugins/gitlab/events/task-comment-created.ts
new file mode 100644
index 000000000..3d52cdab7
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/events/task-comment-created.ts
@@ -0,0 +1,77 @@
+import {
+ findExternalLinkByTaskAndType,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import type { PluginContext, TaskCommentCreatedEvent } from "../../types";
+import type { GitlabConfig } from "../config";
+import { createGitlabClient } from "../utils/gitlab-api";
+import { parseLinkSyncMetadata } from "../utils/link-sync";
+import { syncedNoteIds, withSyncedNoteId } from "../utils/synced-notes";
+
+export async function handleTaskCommentCreated(
+ event: TaskCommentCreatedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GitlabConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ const existingLink = await findExternalLinkByTaskAndType(
+ event.taskId,
+ context.integrationId,
+ "issue",
+ );
+
+ if (!existingLink) {
+ return;
+ }
+
+ if (!/^\d+$/.test(existingLink.externalId)) {
+ console.error(
+ "Skipping GitLab comment sync for invalid external issue id",
+ {
+ taskId: event.taskId,
+ externalId: existingLink.externalId,
+ },
+ );
+ return;
+ }
+
+ const issueIid = Number(existingLink.externalId);
+
+ if (!Number.isFinite(issueIid) || issueIid < 1) {
+ console.error("Skipping GitLab comment sync for invalid issue iid", {
+ taskId: event.taskId,
+ externalId: existingLink.externalId,
+ });
+ return;
+ }
+
+ try {
+ const note = await createGitlabClient(config).createIssueNote(
+ config.projectPath,
+ issueIid,
+ event.comment,
+ );
+
+ // The note webhook reports this note as authored by the token's own user, so
+ // recording its id is what stops it coming back as a duplicate comment.
+ const metadata = parseLinkSyncMetadata(existingLink.metadata, {
+ externalLinkId: existingLink.id,
+ field: "syncedNoteIds",
+ });
+
+ await updateExternalLink(existingLink.id, {
+ metadata: {
+ ...metadata,
+ syncedNoteIds: withSyncedNoteId(
+ syncedNoteIds(existingLink.metadata),
+ note.id,
+ ),
+ },
+ });
+ } catch (error) {
+ console.error("Failed to create GitLab comment:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/events/task-created.ts b/apps/api/src/plugins/gitlab/events/task-created.ts
new file mode 100644
index 000000000..01550df25
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/events/task-created.ts
@@ -0,0 +1,63 @@
+import {
+ createExternalLink,
+ findExternalLinkByTaskAndType,
+} from "../../github/services/link-manager";
+import {
+ formatIssueBody,
+ formatIssueTitle,
+ getLabelsForIssue,
+} from "../../github/utils/format";
+import type { PluginContext, TaskCreatedEvent } from "../../types";
+import type { GitlabConfig } from "../config";
+import { createGitlabClient } from "../utils/gitlab-api";
+import { addLabelsToIssueGitlab } from "../utils/labels";
+
+export async function handleTaskCreated(
+ event: TaskCreatedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GitlabConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ const existingLink = await findExternalLinkByTaskAndType(
+ event.taskId,
+ context.integrationId,
+ "issue",
+ );
+
+ if (existingLink) {
+ return;
+ }
+
+ try {
+ const client = createGitlabClient(config);
+ const createdIssue = await client.createIssue(config.projectPath, {
+ title: formatIssueTitle(event.title),
+ description: formatIssueBody(event.description, event.taskId),
+ });
+
+ await createExternalLink({
+ taskId: event.taskId,
+ integrationId: context.integrationId,
+ resourceType: "issue",
+ externalId: createdIssue.iid.toString(),
+ url: createdIssue.web_url,
+ title: createdIssue.title,
+ metadata: {
+ state: createdIssue.state,
+ createdFrom: "kaneo",
+ lastOutboundStateSyncAt: Date.now(),
+ },
+ });
+
+ await addLabelsToIssueGitlab(
+ config,
+ createdIssue.iid,
+ getLabelsForIssue(event.priority, event.status),
+ );
+ } catch (error) {
+ console.error("Failed to create GitLab issue:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/events/task-description-changed.ts b/apps/api/src/plugins/gitlab/events/task-description-changed.ts
new file mode 100644
index 000000000..b7b49b267
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/events/task-description-changed.ts
@@ -0,0 +1,75 @@
+import {
+ findExternalLinksByTask,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import { formatIssueBody } from "../../github/utils/format";
+import type { PluginContext, TaskDescriptionChangedEvent } from "../../types";
+import type { GitlabConfig } from "../config";
+import { createGitlabClient } from "../utils/gitlab-api";
+import {
+ isEchoOf,
+ parseLinkSyncMetadata,
+ withLastSync,
+} from "../utils/link-sync";
+
+export async function handleTaskDescriptionChanged(
+ event: TaskDescriptionChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GitlabConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ try {
+ const links = await findExternalLinksByTask(event.taskId);
+ const issueLink = links.find(
+ (link) =>
+ link.integrationId === context.integrationId &&
+ link.resourceType === "issue",
+ );
+
+ if (!issueLink) {
+ return;
+ }
+
+ const metadata = parseLinkSyncMetadata(issueLink.metadata, {
+ externalLinkId: issueLink.id,
+ field: "description",
+ });
+
+ const newDescription = event.newDescription ?? "";
+
+ if (isEchoOf(metadata.lastSync?.description, "gitlab", newDescription)) {
+ return;
+ }
+
+ const issueIid = Number.parseInt(issueLink.externalId, 10);
+ if (Number.isNaN(issueIid)) {
+ console.warn("Skipping GitLab description sync for invalid issue iid", {
+ issueLinkId: issueLink.id,
+ externalId: issueLink.externalId,
+ });
+ return;
+ }
+
+ // The issue body carries a task footer, and that whole string is what comes
+ // back through the webhook, so it is the value the echo check compares.
+ const issueDescription = formatIssueBody(newDescription, event.taskId);
+
+ await createGitlabClient(config).updateIssue(config.projectPath, issueIid, {
+ description: issueDescription,
+ });
+
+ await updateExternalLink(issueLink.id, {
+ metadata: withLastSync(
+ metadata,
+ "description",
+ "kaneo",
+ issueDescription,
+ ),
+ });
+ } catch (error) {
+ console.error("Failed to update GitLab issue description:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/events/task-priority-changed.ts b/apps/api/src/plugins/gitlab/events/task-priority-changed.ts
new file mode 100644
index 000000000..756a8b055
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/events/task-priority-changed.ts
@@ -0,0 +1,45 @@
+import { findExternalLinksByTask } from "../../github/services/link-manager";
+import type { PluginContext, TaskPriorityChangedEvent } from "../../types";
+import type { GitlabConfig } from "../config";
+import { updateIssueLabelsGitlab } from "../utils/labels";
+
+export async function handleTaskPriorityChanged(
+ event: TaskPriorityChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GitlabConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ try {
+ const links = await findExternalLinksByTask(event.taskId);
+ const issueLink = links.find(
+ (link) =>
+ link.integrationId === context.integrationId &&
+ link.resourceType === "issue",
+ );
+
+ if (!issueLink) {
+ return;
+ }
+
+ const issueIid = Number.parseInt(issueLink.externalId, 10);
+ if (Number.isNaN(issueIid)) {
+ return;
+ }
+
+ const remove =
+ event.oldPriority && event.oldPriority !== "no-priority"
+ ? [`priority:${event.oldPriority}`]
+ : [];
+ const add =
+ event.newPriority && event.newPriority !== "no-priority"
+ ? [`priority:${event.newPriority}`]
+ : [];
+
+ await updateIssueLabelsGitlab(config, issueIid, { add, remove });
+ } catch (error) {
+ console.error("Failed to update GitLab issue priority:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/events/task-status-changed.ts b/apps/api/src/plugins/gitlab/events/task-status-changed.ts
new file mode 100644
index 000000000..c42b3c534
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/events/task-status-changed.ts
@@ -0,0 +1,66 @@
+import {
+ findExternalLinksByTask,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import type { PluginContext, TaskStatusChangedEvent } from "../../types";
+import type { GitlabConfig } from "../config";
+import { createGitlabClient } from "../utils/gitlab-api";
+import { updateIssueLabelsGitlab } from "../utils/labels";
+
+export async function handleTaskStatusChanged(
+ event: TaskStatusChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GitlabConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ try {
+ const links = await findExternalLinksByTask(event.taskId);
+ const issueLink = links.find(
+ (link) =>
+ link.integrationId === context.integrationId &&
+ link.resourceType === "issue",
+ );
+
+ if (!issueLink) {
+ return;
+ }
+
+ const issueIid = Number.parseInt(issueLink.externalId, 10);
+ if (Number.isNaN(issueIid)) {
+ console.warn("Skipping GitLab status sync for invalid issue iid", {
+ issueLinkId: issueLink.id,
+ externalId: issueLink.externalId,
+ });
+ return;
+ }
+
+ await updateIssueLabelsGitlab(config, issueIid, {
+ remove: [`status:${event.oldStatus}`],
+ add: [`status:${event.newStatus}`],
+ });
+
+ const closing = event.newStatus === "done";
+ const reopening = event.oldStatus === "done" && event.newStatus !== "done";
+
+ if (!closing && !reopening) {
+ return;
+ }
+
+ await createGitlabClient(config).updateIssue(config.projectPath, issueIid, {
+ state_event: closing ? "close" : "reopen",
+ });
+
+ await updateExternalLink(issueLink.id, {
+ metadata: {
+ ...(issueLink.metadata ? JSON.parse(issueLink.metadata) : {}),
+ state: closing ? "closed" : "opened",
+ lastOutboundStateSyncAt: Date.now(),
+ },
+ });
+ } catch (error) {
+ console.error("Failed to update GitLab issue status:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/events/task-title-changed.ts b/apps/api/src/plugins/gitlab/events/task-title-changed.ts
new file mode 100644
index 000000000..b9888a8ad
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/events/task-title-changed.ts
@@ -0,0 +1,64 @@
+import {
+ findExternalLinksByTask,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import type { PluginContext, TaskTitleChangedEvent } from "../../types";
+import type { GitlabConfig } from "../config";
+import { createGitlabClient } from "../utils/gitlab-api";
+import {
+ isEchoOf,
+ parseLinkSyncMetadata,
+ withLastSync,
+} from "../utils/link-sync";
+
+export async function handleTaskTitleChanged(
+ event: TaskTitleChangedEvent,
+ context: PluginContext,
+): Promise<void> {
+ const config = context.config as GitlabConfig;
+ if (!config.baseUrl || !config.accessToken) {
+ return;
+ }
+
+ try {
+ const links = await findExternalLinksByTask(event.taskId);
+ const issueLink = links.find(
+ (link) =>
+ link.integrationId === context.integrationId &&
+ link.resourceType === "issue",
+ );
+
+ if (!issueLink) {
+ return;
+ }
+
+ const metadata = parseLinkSyncMetadata(issueLink.metadata, {
+ externalLinkId: issueLink.id,
+ field: "title",
+ });
+
+ if (isEchoOf(metadata.lastSync?.title, "gitlab", event.newTitle)) {
+ return;
+ }
+
+ const issueIid = Number.parseInt(issueLink.externalId, 10);
+ if (Number.isNaN(issueIid)) {
+ console.warn("Skipping GitLab title sync for invalid issue iid", {
+ issueLinkId: issueLink.id,
+ externalId: issueLink.externalId,
+ });
+ return;
+ }
+
+ await createGitlabClient(config).updateIssue(config.projectPath, issueIid, {
+ title: event.newTitle,
+ });
+
+ await updateExternalLink(issueLink.id, {
+ title: event.newTitle,
+ metadata: withLastSync(metadata, "title", "kaneo", event.newTitle),
+ });
+ } catch (error) {
+ console.error("Failed to update GitLab issue title:", error);
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/index.ts b/apps/api/src/plugins/gitlab/index.ts
new file mode 100644
index 000000000..0baf70304
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/index.ts
@@ -0,0 +1,20 @@
+import type { IntegrationPlugin } from "../types";
+import { validateGitlabConfig } from "./config";
+import { handleTaskCommentCreated } from "./events/task-comment-created";
+import { handleTaskCreated } from "./events/task-created";
+import { handleTaskDescriptionChanged } from "./events/task-description-changed";
+import { handleTaskPriorityChanged } from "./events/task-priority-changed";
+import { handleTaskStatusChanged } from "./events/task-status-changed";
+import { handleTaskTitleChanged } from "./events/task-title-changed";
+
+export const gitlabPlugin: IntegrationPlugin = {
+ type: "gitlab",
+ name: "GitLab",
+ onTaskCreated: handleTaskCreated,
+ onTaskStatusChanged: handleTaskStatusChanged,
+ onTaskPriorityChanged: handleTaskPriorityChanged,
+ onTaskTitleChanged: handleTaskTitleChanged,
+ onTaskDescriptionChanged: handleTaskDescriptionChanged,
+ onTaskCommentCreated: handleTaskCommentCreated,
+ validateConfig: validateGitlabConfig,
+};
diff --git a/apps/api/src/plugins/gitlab/services/integration-lookup.ts b/apps/api/src/plugins/gitlab/services/integration-lookup.ts
new file mode 100644
index 000000000..7fc75a6a4
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/services/integration-lookup.ts
@@ -0,0 +1,45 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { integrationTable } from "../../../database/schema";
+import type { GitlabConfig } from "../config";
+import { normalizeGitlabBaseUrl, normalizeProjectPath } from "../config";
+
+export async function findAllIntegrationsByGitlabProject(
+ baseUrl: string,
+ projectPath: string,
+ integrationId?: string,
+) {
+ const normalizedBase = normalizeGitlabBaseUrl(baseUrl);
+ const normalizedPath = normalizeProjectPath(projectPath);
+ const conditions = [
+ eq(integrationTable.type, "gitlab"),
+ eq(integrationTable.isActive, true),
+ ];
+ if (integrationId) {
+ conditions.push(eq(integrationTable.id, integrationId));
+ }
+
+ const integrations = await db.query.integrationTable.findMany({
+ where: and(...conditions),
+ with: {
+ project: true,
+ },
+ });
+
+ return integrations.filter((integration) => {
+ try {
+ const config = JSON.parse(integration.config) as GitlabConfig;
+ const matches =
+ normalizeGitlabBaseUrl(config.baseUrl) === normalizedBase &&
+ normalizeProjectPath(config.projectPath) === normalizedPath;
+ if (integrationId && !matches) {
+ console.warn("[GitLab Webhook] Signed integration project mismatch", {
+ integrationId,
+ });
+ }
+ return matches;
+ } catch {
+ return false;
+ }
+ });
+}
diff --git a/apps/api/src/plugins/gitlab/utils/branch-matcher.ts b/apps/api/src/plugins/gitlab/utils/branch-matcher.ts
new file mode 100644
index 000000000..fe91433c9
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/branch-matcher.ts
@@ -0,0 +1,47 @@
+import type { GitHubConfig } from "../../github/config";
+import {
+ extractTaskNumber,
+ extractTaskNumberFromBranch,
+ extractTaskNumberFromPRBody,
+ extractTaskNumberFromPRTitle,
+ generateBranchName,
+} from "../../github/utils/branch-matcher";
+import type { GitlabConfig } from "../config";
+
+function asBranchConfig(config: GitlabConfig): GitHubConfig {
+ return config as unknown as GitHubConfig;
+}
+
+export {
+ extractTaskNumberFromPRBody,
+ extractTaskNumberFromPRTitle,
+ generateBranchName,
+};
+
+export function extractTaskNumberFromBranchGitlab(
+ branchName: string,
+ config: GitlabConfig,
+ projectSlug: string,
+): number | null {
+ return extractTaskNumberFromBranch(
+ branchName,
+ asBranchConfig(config),
+ projectSlug,
+ );
+}
+
+export function extractTaskNumberGitlab(
+ branchName: string,
+ mrTitle: string | undefined,
+ mrDescription: string | undefined,
+ config: GitlabConfig,
+ projectSlug: string,
+): number | null {
+ return extractTaskNumber(
+ branchName,
+ mrTitle,
+ mrDescription,
+ asBranchConfig(config),
+ projectSlug,
+ );
+}
diff --git a/apps/api/src/plugins/gitlab/utils/gitlab-api.ts b/apps/api/src/plugins/gitlab/utils/gitlab-api.ts
new file mode 100644
index 000000000..9cb703069
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/gitlab-api.ts
@@ -0,0 +1,377 @@
+import * as Sentry from "@sentry/node";
+import { assertPublicDestination } from "../../../utils/assert-public-destination";
+import type { GitlabConfig, GitlabTokenType } from "../config";
+import { normalizeGitlabBaseUrl, normalizeProjectPath } from "../config";
+
+export type GitlabLabel = {
+ id: number;
+ name: string;
+ color?: string;
+};
+
+export type GitlabUser = {
+ id: number;
+ username?: string;
+ name?: string;
+ avatar_url?: string | null;
+};
+
+export type GitlabIssue = {
+ id: number;
+ iid: number;
+ title: string;
+ description: string | null;
+ web_url: string;
+ state: string;
+ labels?: string[];
+ author?: GitlabUser | null;
+ updated_at?: string;
+};
+
+export type GitlabNote = {
+ id: number;
+ body: string;
+ system: boolean;
+ author?: GitlabUser | null;
+ created_at: string;
+};
+
+export type GitlabMergeRequest = {
+ iid: number;
+ title: string;
+ description: string | null;
+ web_url: string;
+ state: string;
+ draft?: boolean;
+ source_branch?: string;
+ author?: GitlabUser | null;
+ merged_at?: string | null;
+};
+
+export type GitlabProject = {
+ id: number;
+ name: string;
+ path_with_namespace: string;
+ name_with_namespace: string;
+ visibility: string;
+ web_url: string;
+ permissions?: {
+ project_access?: { access_level?: number } | null;
+ group_access?: { access_level?: number } | null;
+ } | null;
+};
+
+export type GitlabApiErrorKind =
+ | "REDIRECT"
+ | "INVALID_JSON"
+ | "HTTP_ERROR"
+ | "TIMEOUT"
+ | "EMPTY_RESPONSE";
+
+export class GitlabApiError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ public kind: GitlabApiErrorKind,
+ public body?: string,
+ ) {
+ super(message);
+ this.name = "GitlabApiError";
+ }
+}
+
+function authHeaders(token: string, tokenType: GitlabTokenType): HeadersInit {
+ return {
+ ...(tokenType === "bearer"
+ ? { Authorization: `Bearer ${token}` }
+ : { "PRIVATE-TOKEN": token }),
+ "Content-Type": "application/json",
+ };
+}
+
+const GITLAB_FETCH_TIMEOUT_MS = 10_000;
+
+export async function gitlabFetch<T>(
+ baseUrl: string,
+ token: string,
+ tokenType: GitlabTokenType,
+ path: string,
+ init?: RequestInit,
+): Promise<T | undefined> {
+ const root = normalizeGitlabBaseUrl(baseUrl);
+ const url = `${root}/api/v4${path.startsWith("/") ? path : `/${path}`}`;
+
+ await assertPublicDestination(root, "GitLab");
+
+ const controller = new AbortController();
+ let timedOut = false;
+ const timeoutId = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, GITLAB_FETCH_TIMEOUT_MS);
+ if (init?.signal) {
+ if (init.signal.aborted) {
+ controller.abort();
+ } else {
+ init.signal.addEventListener("abort", () => controller.abort(), {
+ once: true,
+ });
+ }
+ }
+
+ try {
+ Sentry.addBreadcrumb({
+ category: "integration",
+ level: "info",
+ data: { integration: "gitlab" },
+ });
+ const res = await fetch(url, {
+ ...init,
+ signal: controller.signal,
+ // Following redirects would let a public host bounce the request to an
+ // internal address after the destination check has already passed.
+ redirect: "manual",
+ headers: {
+ ...authHeaders(token, tokenType),
+ ...init?.headers,
+ },
+ });
+
+ if (res.status >= 300 && res.status < 400) {
+ throw new GitlabApiError(
+ `GitLab request was redirected (HTTP ${res.status})`,
+ res.status,
+ "REDIRECT",
+ );
+ }
+
+ const text = await res.text();
+ clearTimeout(timeoutId);
+
+ if (!res.ok) {
+ throw new GitlabApiError(
+ `GitLab API error ${res.status}`,
+ res.status,
+ "HTTP_ERROR",
+ text,
+ );
+ }
+
+ if (res.status === 204 || text === "") {
+ return undefined;
+ }
+
+ try {
+ return JSON.parse(text) as T;
+ } catch {
+ throw new GitlabApiError(
+ "GitLab API returned invalid JSON",
+ res.status,
+ "INVALID_JSON",
+ text,
+ );
+ }
+ } catch (error) {
+ clearTimeout(timeoutId);
+ if (error instanceof GitlabApiError) {
+ throw error;
+ }
+ if (error instanceof Error && error.name === "AbortError") {
+ if (timedOut) {
+ throw new GitlabApiError(
+ `GitLab request timed out after ${GITLAB_FETCH_TIMEOUT_MS}ms`,
+ 408,
+ "TIMEOUT",
+ );
+ }
+ throw error;
+ }
+ throw error;
+ }
+}
+
+export function tokenTypeOf(config: {
+ tokenType?: GitlabTokenType;
+}): GitlabTokenType {
+ return config.tokenType === "bearer" ? "bearer" : "private";
+}
+
+function required<T>(value: T | undefined, what: string): T {
+ if (value === undefined) {
+ throw new GitlabApiError(
+ `GitLab ${what} response was empty`,
+ 500,
+ "EMPTY_RESPONSE",
+ );
+ }
+ return value;
+}
+
+export function createGitlabClient(
+ config: Pick<GitlabConfig, "baseUrl" | "accessToken" | "tokenType">,
+) {
+ const { baseUrl, accessToken } = config;
+ const tokenType = tokenTypeOf(config);
+ const project = (path: string) =>
+ `/projects/${encodeURIComponent(normalizeProjectPath(path))}`;
+
+ const call = <T>(path: string, init?: RequestInit) =>
+ gitlabFetch<T>(baseUrl, accessToken, tokenType, path, init);
+
+ return {
+ async getProject(projectPath: string): Promise<GitlabProject> {
+ return required(
+ await call<GitlabProject>(project(projectPath)),
+ "project",
+ );
+ },
+
+ async listMemberProjects(page = 1, perPage = 50): Promise<GitlabProject[]> {
+ return required(
+ await call<GitlabProject[]>(
+ `/projects?membership=true&simple=true&order_by=last_activity_at&per_page=${perPage}&page=${page}`,
+ ),
+ "projects",
+ );
+ },
+
+ async createIssue(
+ projectPath: string,
+ body: { title: string; description?: string | null },
+ ): Promise<GitlabIssue> {
+ return required(
+ await call<GitlabIssue>(`${project(projectPath)}/issues`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ "create issue",
+ );
+ },
+
+ async updateIssue(
+ projectPath: string,
+ iid: number,
+ body: Record<string, unknown>,
+ ): Promise<GitlabIssue> {
+ return required(
+ await call<GitlabIssue>(`${project(projectPath)}/issues/${iid}`, {
+ method: "PUT",
+ body: JSON.stringify(body),
+ }),
+ "update issue",
+ );
+ },
+
+ async getIssue(projectPath: string, iid: number): Promise<GitlabIssue> {
+ return required(
+ await call<GitlabIssue>(`${project(projectPath)}/issues/${iid}`),
+ "issue",
+ );
+ },
+
+ async listIssues(
+ projectPath: string,
+ page: number,
+ state: "opened" | "closed" | "all",
+ ): Promise<GitlabIssue[]> {
+ return required(
+ await call<GitlabIssue[]>(
+ `${project(projectPath)}/issues?state=${state}&order_by=created_at&sort=asc&per_page=100&page=${page}`,
+ ),
+ "issues",
+ );
+ },
+
+ async listIssueNotes(
+ projectPath: string,
+ iid: number,
+ page: number,
+ perPage: number,
+ ): Promise<GitlabNote[]> {
+ return required(
+ await call<GitlabNote[]>(
+ `${project(projectPath)}/issues/${iid}/notes?sort=asc&order_by=created_at&per_page=${perPage}&page=${page}`,
+ ),
+ "notes",
+ );
+ },
+
+ async createIssueNote(
+ projectPath: string,
+ iid: number,
+ body: string,
+ ): Promise<GitlabNote> {
+ return required(
+ await call<GitlabNote>(`${project(projectPath)}/issues/${iid}/notes`, {
+ method: "POST",
+ body: JSON.stringify({ body }),
+ }),
+ "create note",
+ );
+ },
+
+ async listLabels(projectPath: string): Promise<GitlabLabel[]> {
+ const all: GitlabLabel[] = [];
+ let page = 1;
+
+ while (page <= 20) {
+ const batch = required(
+ await call<GitlabLabel[]>(
+ `${project(projectPath)}/labels?per_page=100&page=${page}`,
+ ),
+ "labels",
+ );
+ all.push(...batch);
+ if (batch.length < 100) break;
+ page += 1;
+ }
+
+ return all;
+ },
+
+ async createLabel(
+ projectPath: string,
+ name: string,
+ color: string,
+ ): Promise<GitlabLabel> {
+ return required(
+ await call<GitlabLabel>(`${project(projectPath)}/labels`, {
+ method: "POST",
+ body: JSON.stringify({
+ name,
+ color: `#${color.replace(/^#/, "")}`,
+ }),
+ }),
+ "create label",
+ );
+ },
+
+ async listMergeRequests(
+ projectPath: string,
+ page: number,
+ ): Promise<GitlabMergeRequest[]> {
+ return required(
+ await call<GitlabMergeRequest[]>(
+ `${project(projectPath)}/merge_requests?state=opened&per_page=100&page=${page}`,
+ ),
+ "merge requests",
+ );
+ },
+ };
+}
+
+export async function verifyGitlabToken(
+ baseUrl: string,
+ token: string,
+ tokenType: GitlabTokenType,
+) {
+ return required(
+ await gitlabFetch<{ id: number; username: string }>(
+ normalizeGitlabBaseUrl(baseUrl),
+ token,
+ tokenType,
+ "/user",
+ ),
+ "user",
+ );
+}
diff --git a/apps/api/src/plugins/gitlab/utils/labels.ts b/apps/api/src/plugins/gitlab/utils/labels.ts
new file mode 100644
index 000000000..7f232bdf9
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/labels.ts
@@ -0,0 +1,108 @@
+import type { GitlabConfig } from "../config";
+import { createGitlabClient } from "./gitlab-api";
+
+const labelColors: Record<string, string> = {
+ "priority:low": "0EA5E9",
+ "priority:medium": "EAB308",
+ "priority:high": "F97316",
+ "priority:urgent": "EF4444",
+ "status:to-do": "6B7280",
+ "status:in-progress": "3B82F6",
+ "status:in-review": "8B5CF6",
+ "status:done": "10B981",
+ "status:planned": "8B5CF6",
+ "status:archived": "6B7280",
+};
+
+function getLabelColor(labelName: string): string {
+ return labelColors[labelName] || "6B7280";
+}
+
+// GitLab creates a missing project label on its own when an issue is labelled,
+// but picks the colour itself. Creating them up front is what keeps the
+// priority and status labels recognisable.
+export async function ensureLabelsExistGitlab(
+ config: GitlabConfig,
+ labels: string[],
+): Promise<void> {
+ if (labels.length === 0) return;
+
+ const client = createGitlabClient(config);
+ const { projectPath } = config;
+
+ let existing: string[];
+ try {
+ existing = (await client.listLabels(projectPath)).map((l) => l.name);
+ } catch (error) {
+ console.error("Failed to list GitLab labels for ensureLabelsExistGitlab", {
+ projectPath,
+ error,
+ });
+ return;
+ }
+
+ for (const name of labels) {
+ if (existing.includes(name)) continue;
+
+ try {
+ await client.createLabel(projectPath, name, getLabelColor(name));
+ } catch (error) {
+ console.error(`Failed to ensure GitLab label "${name}":`, error);
+ }
+ }
+}
+
+/**
+ * Adds and removes issue labels in one request, so an issue never briefly
+ * carries two `status:` labels for a racing read to pick up.
+ */
+export async function updateIssueLabelsGitlab(
+ config: GitlabConfig,
+ issueIid: number,
+ changes: { add?: string[]; remove?: string[] },
+) {
+ const add = changes.add ?? [];
+ const remove = changes.remove ?? [];
+
+ if (add.length === 0 && remove.length === 0) return;
+
+ await ensureLabelsExistGitlab(config, add);
+
+ const body: Record<string, string> = {};
+ if (add.length > 0) {
+ body.add_labels = add.join(",");
+ }
+ if (remove.length > 0) {
+ body.remove_labels = remove.join(",");
+ }
+
+ try {
+ await createGitlabClient(config).updateIssue(
+ config.projectPath,
+ issueIid,
+ body,
+ );
+ } catch (error) {
+ console.error("Failed to update GitLab issue labels:", {
+ projectPath: config.projectPath,
+ issueIid,
+ error,
+ });
+ }
+}
+
+export async function addLabelsToIssueGitlab(
+ config: GitlabConfig,
+ issueIid: number,
+ labelNames: string[],
+) {
+ await updateIssueLabelsGitlab(config, issueIid, { add: labelNames });
+}
+
+export async function removeLabelGitlab(
+ config: GitlabConfig,
+ issueIid: number,
+ labelName: string,
+) {
+ await updateIssueLabelsGitlab(config, issueIid, { remove: [labelName] });
+}
diff --git a/apps/api/src/plugins/gitlab/utils/link-sync.ts b/apps/api/src/plugins/gitlab/utils/link-sync.ts
new file mode 100644
index 000000000..743336b09
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/link-sync.ts
@@ -0,0 +1,89 @@
+export type LinkSyncState = {
+ timestamp: string;
+ source: string;
+ value: string;
+};
+
+export type LinkMetadata = {
+ lastSync?: {
+ title?: LinkSyncState;
+ description?: LinkSyncState;
+ };
+ [key: string]: unknown;
+};
+
+/**
+ * How long an identical value still counts as the other side's echo. Generous
+ * enough for a slow webhook delivery, short enough that setting a title back to
+ * an older value tomorrow is treated as the real edit it is.
+ */
+export const TEXT_ECHO_WINDOW_MS = 60_000;
+
+/**
+ * A value one side writes comes straight back from the other as a webhook or an
+ * event. The value itself is what identifies the echo -- suppressing anything
+ * that merely arrives soon after a write would drop a real edit made right on
+ * top of it -- and the window bounds how long that identity holds.
+ */
+export function isEchoOf(
+ state: LinkSyncState | undefined,
+ source: string,
+ incoming: string,
+): boolean {
+ if (state?.source !== source || state.value !== incoming) {
+ return false;
+ }
+
+ const writtenAt = Date.parse(state.timestamp);
+ if (Number.isNaN(writtenAt)) {
+ return false;
+ }
+
+ return Date.now() - writtenAt <= TEXT_ECHO_WINDOW_MS;
+}
+
+export function parseLinkSyncMetadata(
+ raw: string | null | undefined,
+ context: { externalLinkId: string; field: string },
+): LinkMetadata {
+ if (!raw) {
+ return {};
+ }
+
+ try {
+ const parsed = JSON.parse(raw) as unknown;
+ if (
+ typeof parsed !== "object" ||
+ parsed === null ||
+ Array.isArray(parsed)
+ ) {
+ return {};
+ }
+ return parsed as LinkMetadata;
+ } catch (error) {
+ console.warn("Failed to parse GitLab external link metadata", {
+ ...context,
+ error,
+ });
+ return {};
+ }
+}
+
+export function withLastSync(
+ metadata: LinkMetadata,
+ field: "title" | "description",
+ source: string,
+ value: string,
+): LinkMetadata {
+ return {
+ ...metadata,
+ lastSync: {
+ ...(metadata.lastSync ?? {}),
+ [field]: {
+ timestamp: new Date().toISOString(),
+ source,
+ value,
+ },
+ },
+ };
+}
diff --git a/apps/api/src/plugins/gitlab/utils/outbound-echo.ts b/apps/api/src/plugins/gitlab/utils/outbound-echo.ts
new file mode 100644
index 000000000..c52d9136b
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/outbound-echo.ts
@@ -0,0 +1,11 @@
+/** Skip webhook sync when it likely echoes our own outbound API update. */
+export const OUTBOUND_STATE_ECHO_WINDOW_MS = 5000;
+
+export function parseIssueUpdatedAtMs(issue: {
+ updated_at?: string;
+}): number | null {
+ const raw = issue.updated_at;
+ if (!raw || typeof raw !== "string") return null;
+ const t = Date.parse(raw);
+ return Number.isNaN(t) ? null : t;
+}
diff --git a/apps/api/src/plugins/gitlab/utils/payload.ts b/apps/api/src/plugins/gitlab/utils/payload.ts
new file mode 100644
index 000000000..02fbb9872
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/payload.ts
@@ -0,0 +1,34 @@
+/**
+ * Shapes shared by every GitLab webhook payload. Unlike the REST API, which
+ * returns issue labels as plain names, webhooks send label objects keyed by
+ * `title`.
+ */
+export type GitlabWebhookProject = {
+ name: string;
+ web_url: string;
+ path_with_namespace: string;
+};
+
+export type GitlabWebhookLabel = {
+ title?: string;
+ color?: string;
+};
+
+export type GitlabWebhookUser = {
+ name?: string;
+ username?: string;
+ avatar_url?: string | null;
+};
+
+export function labelTitles(
+ labels: GitlabWebhookLabel[] | undefined,
+): string[] {
+ if (!labels) return [];
+ return labels
+ .map((label) => label.title)
+ .filter((title): title is string => Boolean(title));
+}
+
+export function labelColor(label: GitlabWebhookLabel): string {
+ return label.color ? `#${label.color.replace(/^#/, "")}` : "#6B7280";
+}
diff --git a/apps/api/src/plugins/gitlab/utils/resolve-column.ts b/apps/api/src/plugins/gitlab/utils/resolve-column.ts
new file mode 100644
index 000000000..27e6c74cf
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/resolve-column.ts
@@ -0,0 +1,48 @@
+import { and, asc, eq } from "drizzle-orm";
+import db from "../../../database";
+import { columnTable, workflowRuleTable } from "../../../database/schema";
+
+export async function resolveTargetStatus(
+ projectId: string,
+ eventType: string,
+ fallbackStatus: string,
+): Promise<string> {
+ const projectColumns = await db
+ .select({
+ id: columnTable.id,
+ slug: columnTable.slug,
+ })
+ .from(columnTable)
+ .where(eq(columnTable.projectId, projectId))
+ .orderBy(asc(columnTable.position));
+
+ if (projectColumns.length === 0) {
+ return fallbackStatus;
+ }
+
+ const rule = await db.query.workflowRuleTable.findFirst({
+ where: and(
+ eq(workflowRuleTable.projectId, projectId),
+ eq(workflowRuleTable.integrationType, "gitlab"),
+ eq(workflowRuleTable.eventType, eventType),
+ ),
+ });
+
+ if (rule) {
+ const mappedColumn = projectColumns.find(
+ (column) => column.id === rule.columnId,
+ );
+ if (mappedColumn) {
+ return mappedColumn.slug;
+ }
+ }
+
+ const fallbackColumn = projectColumns.find(
+ (column) => column.slug === fallbackStatus,
+ );
+ if (fallbackColumn) {
+ return fallbackColumn.slug;
+ }
+
+ return projectColumns[0]?.slug ?? fallbackStatus;
+}
diff --git a/apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab.ts b/apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab.ts
new file mode 100644
index 000000000..5a3ca29a5
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/sync-label-to-gitlab.ts
@@ -0,0 +1,146 @@
+import { eq } from "drizzle-orm";
+import db from "../../../database";
+import { externalLinkTable } from "../../../database/schema";
+import type { GitlabConfig } from "../config";
+import { createGitlabClient } from "./gitlab-api";
+
+const namedColorToHex: Record<string, string> = {
+ red: "EF4444",
+ orange: "F97316",
+ amber: "F59E0B",
+ yellow: "EAB308",
+ lime: "84CC16",
+ green: "22C55E",
+ emerald: "10B981",
+ teal: "14B8A6",
+ cyan: "06B6D4",
+ sky: "0EA5E9",
+ blue: "3B82F6",
+ indigo: "6366F1",
+ violet: "8B5CF6",
+ purple: "A855F7",
+ fuchsia: "D946EF",
+ pink: "EC4899",
+ rose: "F43F5E",
+ gray: "6B7280",
+ slate: "64748B",
+ zinc: "71717A",
+ neutral: "737373",
+ stone: "78716C",
+};
+
+function toHexColor(color: string): string {
+ const lower = color.toLowerCase().replace(/^#/, "");
+ if (namedColorToHex[lower]) {
+ return namedColorToHex[lower];
+ }
+ if (/^[0-9a-f]{6}$/i.test(lower)) {
+ return lower;
+ }
+ if (/^[0-9a-f]{3}$/i.test(lower)) {
+ const [r, g, b] = lower.split("");
+ return `${r}${r}${g}${g}${b}${b}`;
+ }
+ return "6B7280";
+}
+
+async function getGitlabIssueContext(taskId: string) {
+ const externalLinks = await db.query.externalLinkTable.findMany({
+ where: eq(externalLinkTable.taskId, taskId),
+ with: {
+ integration: true,
+ },
+ });
+
+ const externalLink = externalLinks.find(
+ (link) =>
+ link.resourceType === "issue" && link.integration?.type === "gitlab",
+ );
+
+ if (!externalLink?.integration) {
+ return null;
+ }
+
+ let config: GitlabConfig;
+ try {
+ config = JSON.parse(externalLink.integration.config) as GitlabConfig;
+ } catch {
+ return null;
+ }
+
+ if (!config.accessToken || !config.baseUrl) {
+ return null;
+ }
+
+ const issueIid = Number.parseInt(externalLink.externalId, 10);
+ if (Number.isNaN(issueIid)) {
+ console.warn("Invalid GitLab issue externalId for label sync", {
+ externalLinkId: externalLink.id,
+ externalId: externalLink.externalId,
+ taskId,
+ });
+ return null;
+ }
+
+ return {
+ client: createGitlabClient(config),
+ config,
+ issueIid,
+ };
+}
+
+export async function syncLabelToGitlab(
+ taskId: string,
+ labelName: string,
+ labelColor: string,
+) {
+ const ctx = await getGitlabIssueContext(taskId);
+ if (!ctx) return;
+
+ const { client, config, issueIid } = ctx;
+
+ const labels = await client.listLabels(config.projectPath);
+
+ if (!labels.some((l) => l.name === labelName)) {
+ try {
+ await client.createLabel(
+ config.projectPath,
+ labelName,
+ toHexColor(labelColor),
+ );
+ } catch (error) {
+ console.error(`Failed to create label "${labelName}" in GitLab:`, error);
+ return;
+ }
+ }
+
+ try {
+ const issue = await client.getIssue(config.projectPath, issueIid);
+ if (issue.labels?.includes(labelName)) {
+ return;
+ }
+ await client.updateIssue(config.projectPath, issueIid, {
+ add_labels: labelName,
+ });
+ } catch (error) {
+ console.error(`Failed to add label "${labelName}" to GitLab issue:`, error);
+ }
+}
+
+export async function removeLabelFromGitlab(taskId: string, labelName: string) {
+ const ctx = await getGitlabIssueContext(taskId);
+ if (!ctx) return;
+
+ const { client, config, issueIid } = ctx;
+
+ try {
+ await client.updateIssue(config.projectPath, issueIid, {
+ remove_labels: labelName,
+ });
+ } catch (error) {
+ console.error(
+ `Failed to remove label "${labelName}" from GitLab issue:`,
+ error,
+ );
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/utils/synced-notes.ts b/apps/api/src/plugins/gitlab/utils/synced-notes.ts
new file mode 100644
index 000000000..ba472ef79
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/synced-notes.ts
@@ -0,0 +1,24 @@
+// Ids of the notes Kaneo posted to GitLab itself. The note webhook reports them
+// as authored by the token's user, so there is nothing in the payload that marks
+// them as ours -- the recorded id is what keeps them from coming back as a
+// duplicate comment. Only the most recent ids matter, since an older note will
+// have been delivered long ago.
+const MAX_TRACKED_NOTE_IDS = 50;
+
+export function syncedNoteIds(metadata: string | null | undefined): number[] {
+ if (!metadata) return [];
+
+ try {
+ const parsed = JSON.parse(metadata) as { syncedNoteIds?: unknown };
+ if (!Array.isArray(parsed.syncedNoteIds)) return [];
+ return parsed.syncedNoteIds.filter(
+ (id): id is number => typeof id === "number",
+ );
+ } catch {
+ return [];
+ }
+}
+
+export function withSyncedNoteId(existing: number[], noteId: number): number[] {
+ return [...existing, noteId].slice(-MAX_TRACKED_NOTE_IDS);
+}
diff --git a/apps/api/src/plugins/gitlab/utils/system-labels.ts b/apps/api/src/plugins/gitlab/utils/system-labels.ts
new file mode 100644
index 000000000..3415e312e
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/system-labels.ts
@@ -0,0 +1,3 @@
+export function isSystemLabelName(name: string) {
+ return name.startsWith("priority:") || name.startsWith("status:");
+}
diff --git a/apps/api/src/plugins/gitlab/utils/verify-token.ts b/apps/api/src/plugins/gitlab/utils/verify-token.ts
new file mode 100644
index 000000000..9e258c41e
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/verify-token.ts
@@ -0,0 +1,24 @@
+import { timingSafeEqual } from "node:crypto";
+
+// GitLab echoes the hook's secret token back in a plain header rather than
+// signing the body the way Gitea does, so delivery is authenticated by
+// comparing that token. GitLab 19.0 added a Standard Webhooks signing token in
+// `webhook-signature`, but that secret is generated by GitLab and pasted into
+// Kaneo, which is the opposite direction from the secret set up here.
+export function verifyGitlabToken(
+ secret: string,
+ tokenHeader: string | undefined,
+): boolean {
+ if (!tokenHeader || !secret) {
+ return false;
+ }
+
+ const provided = Buffer.from(tokenHeader, "utf8");
+ const expected = Buffer.from(secret, "utf8");
+
+ if (provided.length !== expected.length) {
+ return false;
+ }
+
+ return timingSafeEqual(provided, expected);
+}
diff --git a/apps/api/src/plugins/gitlab/utils/webhook-project.ts b/apps/api/src/plugins/gitlab/utils/webhook-project.ts
new file mode 100644
index 000000000..32deed778
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/utils/webhook-project.ts
@@ -0,0 +1,25 @@
+import { normalizeGitlabBaseUrl } from "../config";
+
+// A webhook payload carries the project's web URL and its full path, so the
+// instance root is the URL with that path removed. This also covers instances
+// served under a path prefix, where the root is not just the origin.
+export function baseUrlFromProjectWebUrl(
+ webUrl: string,
+ pathWithNamespace: string,
+): string {
+ try {
+ const url = new URL(webUrl);
+ const path = url.pathname.replace(/^\/+|\/+$/g, "");
+ const suffix = pathWithNamespace.replace(/^\/+|\/+$/g, "");
+
+ if (!suffix || !path.endsWith(suffix)) {
+ return "";
+ }
+
+ const basePath = path.slice(0, path.length - suffix.length);
+
+ return normalizeGitlabBaseUrl(`${url.origin}/${basePath}`);
+ } catch {
+ return "";
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhook-handler.ts b/apps/api/src/plugins/gitlab/webhook-handler.ts
new file mode 100644
index 000000000..12f318b3e
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhook-handler.ts
@@ -0,0 +1,211 @@
+import { eq } from "drizzle-orm";
+import db from "../../database";
+import { integrationTable } from "../../database/schema";
+import type { GitlabConfig } from "./config";
+import { verifyGitlabToken } from "./utils/verify-token";
+import { handleGitlabIssueClosed } from "./webhooks/issue-closed";
+import { handleGitlabIssueOpened } from "./webhooks/issue-opened";
+import { handleGitlabIssueReopened } from "./webhooks/issue-reopened";
+import { handleGitlabIssueUpdated } from "./webhooks/issue-updated";
+import { handleGitlabMergeRequestClosed } from "./webhooks/merge-request-closed";
+import { handleGitlabMergeRequestOpened } from "./webhooks/merge-request-opened";
+import { handleGitlabNoteCreated } from "./webhooks/note-created";
+import { handleGitlabPush } from "./webhooks/push";
+
+type GitlabPushPayload = Parameters<typeof handleGitlabPush>[0];
+type GitlabIssuePayload = Parameters<typeof handleGitlabIssueOpened>[0];
+type GitlabIssueClosedPayload = Parameters<typeof handleGitlabIssueClosed>[0];
+type GitlabIssueReopenedPayload = Parameters<
+ typeof handleGitlabIssueReopened
+>[0];
+type GitlabIssueUpdatedPayload = Parameters<typeof handleGitlabIssueUpdated>[0];
+type GitlabMergeRequestPayload = Parameters<
+ typeof handleGitlabMergeRequestOpened
+>[0];
+type GitlabMergeRequestClosedPayload = Parameters<
+ typeof handleGitlabMergeRequestClosed
+>[0];
+type GitlabNotePayload = Parameters<typeof handleGitlabNoteCreated>[0];
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+function hasProject(value: Record<string, unknown>) {
+ return isRecord(value.project);
+}
+
+function hasObjectAttributes(value: Record<string, unknown>) {
+ return isRecord(value.object_attributes);
+}
+
+function isPushPayload(
+ payload: Record<string, unknown>,
+): payload is GitlabPushPayload {
+ return typeof payload.ref === "string" && hasProject(payload);
+}
+
+function isIssuePayload(
+ payload: Record<string, unknown>,
+): payload is GitlabIssuePayload {
+ return hasProject(payload) && hasObjectAttributes(payload);
+}
+
+function isMergeRequestPayload(
+ payload: Record<string, unknown>,
+): payload is GitlabMergeRequestPayload {
+ return hasProject(payload) && hasObjectAttributes(payload);
+}
+
+function isNotePayload(
+ payload: Record<string, unknown>,
+): payload is GitlabNotePayload {
+ return hasProject(payload) && hasObjectAttributes(payload);
+}
+
+function objectAction(payload: Record<string, unknown>): string | undefined {
+ const attributes = payload.object_attributes;
+ if (!isRecord(attributes)) return undefined;
+ return typeof attributes.action === "string" ? attributes.action : undefined;
+}
+
+/** True when an "update" took the merge request out of draft. */
+function leftDraft(payload: Record<string, unknown>): boolean {
+ const changes = payload.changes;
+ if (!isRecord(changes)) return false;
+ const draft = changes.draft;
+ if (!isRecord(draft)) return false;
+ return draft.previous === true && draft.current === false;
+}
+
+export async function handleGitlabWebhookRequest(
+ integrationId: string,
+ rawBody: string,
+ tokenHeader: string | undefined,
+): Promise<{ success: boolean; error?: string }> {
+ const integration = await db.query.integrationTable.findFirst({
+ where: eq(integrationTable.id, integrationId),
+ });
+
+ if (integration?.type !== "gitlab") {
+ return { success: false, error: "GitLab integration not found" };
+ }
+
+ let config: GitlabConfig;
+ try {
+ config = JSON.parse(integration.config) as GitlabConfig;
+ } catch {
+ return { success: false, error: "Invalid integration config" };
+ }
+
+ const secret = config.webhookSecret;
+ if (!secret) {
+ return { success: false, error: "Webhook secret not configured" };
+ }
+
+ if (!verifyGitlabToken(secret, tokenHeader)) {
+ return { success: false, error: "Invalid webhook token" };
+ }
+
+ let payload: Record<string, unknown>;
+ try {
+ payload = JSON.parse(rawBody) as Record<string, unknown>;
+ } catch {
+ return { success: false, error: "Invalid JSON payload" };
+ }
+
+ // GitLab names the event in the body as well as in X-Gitlab-Event, and the
+ // body is what the token above authenticates.
+ const objectKind =
+ typeof payload.object_kind === "string" ? payload.object_kind : undefined;
+
+ if (!objectKind) {
+ return { success: false, error: "Missing object_kind" };
+ }
+
+ try {
+ await dispatchGitlabEvent(objectKind, payload, integration.id);
+ return { success: true };
+ } catch (error) {
+ console.error("[GitLab Webhook] Handler error:", error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "Webhook handler failed",
+ };
+ }
+}
+
+async function dispatchGitlabEvent(
+ objectKind: string,
+ payload: Record<string, unknown>,
+ integrationId: string,
+) {
+ console.log(`[GitLab Webhook] Event: ${objectKind}`);
+
+ switch (objectKind) {
+ case "push":
+ if (isPushPayload(payload)) {
+ await handleGitlabPush(payload, integrationId);
+ }
+ return;
+ case "issue": {
+ if (!isIssuePayload(payload)) {
+ return;
+ }
+ switch (objectAction(payload)) {
+ case "open":
+ await handleGitlabIssueOpened(payload, integrationId);
+ return;
+ case "close":
+ await handleGitlabIssueClosed(
+ payload as unknown as GitlabIssueClosedPayload,
+ integrationId,
+ );
+ return;
+ case "reopen":
+ await handleGitlabIssueReopened(
+ payload as unknown as GitlabIssueReopenedPayload,
+ integrationId,
+ );
+ return;
+ case "update":
+ await handleGitlabIssueUpdated(
+ payload as unknown as GitlabIssueUpdatedPayload,
+ integrationId,
+ );
+ return;
+ default:
+ return;
+ }
+ }
+ case "merge_request": {
+ if (!isMergeRequestPayload(payload)) {
+ return;
+ }
+ const action = objectAction(payload);
+ if (action === "open" || action === "reopen") {
+ await handleGitlabMergeRequestOpened(payload, integrationId);
+ return;
+ }
+ if (action === "update" && leftDraft(payload)) {
+ await handleGitlabMergeRequestOpened(payload, integrationId);
+ return;
+ }
+ if (action === "merge" || action === "close") {
+ await handleGitlabMergeRequestClosed(
+ payload as unknown as GitlabMergeRequestClosedPayload,
+ integrationId,
+ );
+ }
+ return;
+ }
+ case "note": {
+ if (isNotePayload(payload)) {
+ await handleGitlabNoteCreated(payload, integrationId);
+ }
+ return;
+ }
+ default:
+ console.log(`[GitLab Webhook] Ignored event: ${objectKind}`);
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts b/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts
new file mode 100644
index 000000000..a7cd510cd
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts
@@ -0,0 +1,135 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { externalLinkTable, taskTable } from "../../../database/schema";
+import { publishEvent } from "../../../events";
+import { updateExternalLink } from "../../github/services/link-manager";
+import { updateTaskStatus } from "../../github/services/task-service";
+import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
+import {
+ OUTBOUND_STATE_ECHO_WINDOW_MS,
+ parseIssueUpdatedAtMs,
+} from "../utils/outbound-echo";
+import type { GitlabWebhookProject } from "../utils/payload";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromProjectWebUrl } from "../utils/webhook-project";
+
+type IssueClosedPayload = {
+ object_attributes: {
+ iid: number;
+ title: string;
+ url: string;
+ state: string;
+ action?: string;
+ updated_at?: string;
+ };
+ project: GitlabWebhookProject;
+};
+
+export async function handleGitlabIssueClosed(
+ payload: IssueClosedPayload,
+ integrationId?: string,
+) {
+ const issue = payload.object_attributes;
+ const { project } = payload;
+
+ if (issue.action !== "close") {
+ return;
+ }
+
+ const baseUrl = baseUrlFromProjectWebUrl(
+ project.web_url,
+ project.path_with_namespace,
+ );
+ if (!baseUrl) return;
+
+ const integrations = await findAllIntegrationsByGitlabProject(
+ baseUrl,
+ project.path_with_namespace,
+ integrationId,
+ );
+
+ for (const integration of integrations) {
+ const externalLink = await db.query.externalLinkTable.findFirst({
+ where: and(
+ eq(externalLinkTable.integrationId, integration.id),
+ eq(externalLinkTable.resourceType, "issue"),
+ eq(externalLinkTable.externalId, issue.iid.toString()),
+ ),
+ });
+
+ if (!externalLink) {
+ continue;
+ }
+
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, externalLink.taskId),
+ });
+
+ if (!task) {
+ continue;
+ }
+
+ let existingMetadata: Record<string, unknown> = {};
+ if (externalLink.metadata) {
+ try {
+ existingMetadata = JSON.parse(externalLink.metadata) as Record<
+ string,
+ unknown
+ >;
+ } catch (error) {
+ console.warn("Failed to parse GitLab issue metadata for close sync", {
+ externalLinkId: externalLink.id,
+ metadata: externalLink.metadata,
+ error,
+ });
+ }
+ }
+
+ // A close arriving right after Kaneo closed the issue is our own echo, but
+ // only when the state Kaneo last wrote is the state being reported.
+ const lastOutbound = existingMetadata.lastOutboundStateSyncAt;
+ if (
+ typeof lastOutbound === "number" &&
+ Number.isFinite(lastOutbound) &&
+ existingMetadata.state === "closed"
+ ) {
+ const eventMs = parseIssueUpdatedAtMs(issue);
+ if (
+ eventMs !== null &&
+ Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS
+ ) {
+ continue;
+ }
+ }
+
+ const targetStatus = await resolveTargetStatus(
+ task.projectId,
+ "issue_closed",
+ "done",
+ );
+
+ const statusResult = await updateTaskStatus(task.id, targetStatus);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ });
+ }
+
+ await updateExternalLink(externalLink.id, {
+ metadata: {
+ ...existingMetadata,
+ state: "closed",
+ },
+ });
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts b/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts
new file mode 100644
index 000000000..5db7d6fa1
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts
@@ -0,0 +1,210 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { columnTable, projectTable, taskTable } from "../../../database/schema";
+import { publishEvent } from "../../../events";
+import { claimTaskNumber } from "../../../task/controllers/claim-task-numbers";
+import {
+ createExternalLink,
+ findExternalLink,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import {
+ extractIssuePriority,
+ extractIssueStatus,
+} from "../../github/utils/extract-priority";
+import { formatTaskDescriptionFromIssue } from "../../github/utils/format";
+import type { GitlabConfig } from "../config";
+import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
+import { createGitlabClient } from "../utils/gitlab-api";
+import { addLabelsToIssueGitlab } from "../utils/labels";
+import type {
+ GitlabWebhookLabel,
+ GitlabWebhookProject,
+ GitlabWebhookUser,
+} from "../utils/payload";
+import { labelTitles } from "../utils/payload";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { withSyncedNoteId } from "../utils/synced-notes";
+import { baseUrlFromProjectWebUrl } from "../utils/webhook-project";
+
+type IssueOpenedPayload = {
+ user?: GitlabWebhookUser | null;
+ object_attributes: {
+ iid: number;
+ title: string;
+ description: string | null;
+ url: string;
+ action?: string;
+ };
+ labels?: GitlabWebhookLabel[];
+ project: GitlabWebhookProject;
+};
+
+export async function handleGitlabIssueOpened(
+ payload: IssueOpenedPayload,
+ integrationId?: string,
+) {
+ const issue = payload.object_attributes;
+ const { project } = payload;
+
+ const baseUrl = baseUrlFromProjectWebUrl(
+ project.web_url,
+ project.path_with_namespace,
+ );
+ if (!baseUrl) {
+ return;
+ }
+
+ const integrations = await findAllIntegrationsByGitlabProject(
+ baseUrl,
+ project.path_with_namespace,
+ integrationId,
+ );
+
+ if (integrations.length === 0) {
+ return;
+ }
+
+ const existingLabels = labelTitles(payload.labels);
+ const author = payload.user?.username ?? payload.user?.name;
+
+ for (const integration of integrations) {
+ let config: GitlabConfig;
+ try {
+ config = JSON.parse(integration.config) as GitlabConfig;
+ } catch (error) {
+ console.error("Invalid GitLab config for integration", {
+ integrationId: integration.id,
+ error,
+ });
+ continue;
+ }
+ const projectId = integration.projectId;
+
+ const priority = extractIssuePriority(existingLabels);
+ const status = extractIssueStatus(existingLabels);
+
+ const existingLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issue.iid.toString(),
+ );
+
+ if (existingLink) {
+ continue;
+ }
+
+ const nextTaskNumber = await claimTaskNumber(projectId);
+
+ const resolvedStatus = await resolveTargetStatus(
+ projectId,
+ "issue_opened",
+ status || "to-do",
+ );
+
+ const targetColumn = await db.query.columnTable.findFirst({
+ where: and(
+ eq(columnTable.projectId, projectId),
+ eq(columnTable.slug, resolvedStatus),
+ ),
+ });
+
+ const taskValues: typeof taskTable.$inferInsert = {
+ projectId,
+ userId: null,
+ title: issue.title,
+ description: formatTaskDescriptionFromIssue(issue.description),
+ status: resolvedStatus,
+ columnId: targetColumn?.id ?? null,
+ priority: priority ?? "low",
+ number: nextTaskNumber,
+ };
+
+ const [createdTask] = await db
+ .insert(taskTable)
+ .values(taskValues)
+ .returning();
+
+ if (!createdTask) {
+ console.error("Failed to create task from GitLab issue");
+ continue;
+ }
+
+ const linkMetadata: Record<string, unknown> = {
+ state: "opened",
+ createdFrom: "gitlab",
+ author,
+ };
+
+ // Must run before task.created: the plugin's onTaskCreated uses link
+ // existence to skip self-originated tasks, else it duplicates the issue.
+ const issueLink = await createExternalLink({
+ taskId: createdTask.id,
+ integrationId: integration.id,
+ resourceType: "issue",
+ externalId: issue.iid.toString(),
+ url: issue.url,
+ title: issue.title,
+ metadata: linkMetadata,
+ });
+
+ await publishEvent("task.created", {
+ ...createdTask,
+ taskId: createdTask.id,
+ userId: createdTask.userId ?? "",
+ type: "task",
+ content: null,
+ source: "gitlab",
+ externalId: issue.iid.toString(),
+ actor: author ?? "gitlab-webhook",
+ });
+
+ const kaneoProject = await db.query.projectTable.findFirst({
+ where: eq(projectTable.id, projectId),
+ });
+
+ if (!kaneoProject) {
+ continue;
+ }
+
+ const clientUrl = process.env.KANEO_CLIENT_URL || "http://localhost:5173";
+ const taskUrl = `${clientUrl}/dashboard/workspace/${kaneoProject.workspaceId}/project/${projectId}/task/${createdTask.id}`;
+ const taskIdentifier = `${kaneoProject.slug.toUpperCase()}-${createdTask.number}`;
+
+ try {
+ const labelsToAdd: string[] = [];
+
+ if (priority && !existingLabels.includes(`priority:${priority}`)) {
+ labelsToAdd.push(`priority:${priority}`);
+ }
+
+ if (status && !existingLabels.includes(`status:${status}`)) {
+ labelsToAdd.push(`status:${status}`);
+ }
+
+ if (labelsToAdd.length > 0) {
+ await addLabelsToIssueGitlab(config, issue.iid, labelsToAdd);
+ }
+
+ if (config.commentTaskLinkOnGitlabIssue !== false) {
+ const note = await createGitlabClient(config).createIssueNote(
+ config.projectPath,
+ issue.iid,
+ `[${taskIdentifier}](${taskUrl})`,
+ );
+
+ // This note returns through the note webhook authored by the token's
+ // own user, so without its id recorded it lands in the task activity as
+ // a comment Kaneo wrote to itself.
+ await updateExternalLink(issueLink.id, {
+ metadata: {
+ ...linkMetadata,
+ syncedNoteIds: withSyncedNoteId([], note.id),
+ },
+ });
+ }
+ } catch (error) {
+ console.error("Failed to process GitLab issue:", error);
+ }
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts
new file mode 100644
index 000000000..d2ecf0e60
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts
@@ -0,0 +1,145 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { externalLinkTable, taskTable } from "../../../database/schema";
+import { publishEvent } from "../../../events";
+import { updateExternalLink } from "../../github/services/link-manager";
+import { updateTaskStatus } from "../../github/services/task-service";
+import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
+import {
+ OUTBOUND_STATE_ECHO_WINDOW_MS,
+ parseIssueUpdatedAtMs,
+} from "../utils/outbound-echo";
+import type { GitlabWebhookProject } from "../utils/payload";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromProjectWebUrl } from "../utils/webhook-project";
+
+type IssueReopenedPayload = {
+ object_attributes: {
+ iid: number;
+ title: string;
+ url: string;
+ state: string;
+ action?: string;
+ updated_at?: string;
+ };
+ project: GitlabWebhookProject;
+};
+
+export async function handleGitlabIssueReopened(
+ payload: IssueReopenedPayload,
+ integrationId?: string,
+) {
+ const issue = payload.object_attributes;
+ const { project } = payload;
+
+ if (issue.action !== "reopen") {
+ return;
+ }
+
+ const baseUrl = baseUrlFromProjectWebUrl(
+ project.web_url,
+ project.path_with_namespace,
+ );
+ if (!baseUrl) return;
+
+ const integrations = await findAllIntegrationsByGitlabProject(
+ baseUrl,
+ project.path_with_namespace,
+ integrationId,
+ );
+
+ for (const integration of integrations) {
+ try {
+ const externalLink = await db.query.externalLinkTable.findFirst({
+ where: and(
+ eq(externalLinkTable.integrationId, integration.id),
+ eq(externalLinkTable.resourceType, "issue"),
+ eq(externalLinkTable.externalId, issue.iid.toString()),
+ ),
+ });
+
+ if (!externalLink) {
+ continue;
+ }
+
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, externalLink.taskId),
+ });
+
+ if (!task) {
+ continue;
+ }
+
+ let existingMetadata: Record<string, unknown> = {};
+ if (externalLink.metadata) {
+ try {
+ existingMetadata = JSON.parse(externalLink.metadata) as Record<
+ string,
+ unknown
+ >;
+ } catch (error) {
+ console.warn(
+ "Failed to parse GitLab issue metadata for reopen sync",
+ {
+ externalLinkId: externalLink.id,
+ metadata: externalLink.metadata,
+ error,
+ },
+ );
+ }
+ }
+
+ const lastOutbound = existingMetadata.lastOutboundStateSyncAt;
+ if (
+ typeof lastOutbound === "number" &&
+ Number.isFinite(lastOutbound) &&
+ existingMetadata.state === "opened"
+ ) {
+ const eventMs = parseIssueUpdatedAtMs(issue);
+ if (
+ eventMs !== null &&
+ Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS
+ ) {
+ continue;
+ }
+ }
+
+ const targetStatus = await resolveTargetStatus(
+ task.projectId,
+ "issue_reopened",
+ "to-do",
+ );
+
+ const statusResult = await updateTaskStatus(task.id, targetStatus);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ });
+ }
+
+ await updateExternalLink(externalLink.id, {
+ metadata: {
+ ...existingMetadata,
+ state: "opened",
+ },
+ });
+ } catch (error) {
+ console.error("GitLab issue reopen handler failed for integration", {
+ integrationId: integration.id,
+ issueIid: issue.iid,
+ project: project.path_with_namespace,
+ error,
+ });
+ }
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
new file mode 100644
index 000000000..8e24334a7
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts
@@ -0,0 +1,268 @@
+import { eq, inArray } from "drizzle-orm";
+import db from "../../../database";
+import { labelTable, taskTable } from "../../../database/schema";
+import { publishEvent } from "../../../events";
+import {
+ findExternalLink,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import { updateTaskStatus } from "../../github/services/task-service";
+import {
+ extractIssuePriority,
+ extractIssueStatus,
+} from "../../github/utils/extract-priority";
+import { formatTaskDescriptionFromIssue } from "../../github/utils/format";
+import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
+import {
+ isEchoOf,
+ type LinkMetadata,
+ parseLinkSyncMetadata,
+} from "../utils/link-sync";
+import type {
+ GitlabWebhookLabel,
+ GitlabWebhookProject,
+} from "../utils/payload";
+import { labelColor, labelTitles } from "../utils/payload";
+import { isSystemLabelName } from "../utils/system-labels";
+import { baseUrlFromProjectWebUrl } from "../utils/webhook-project";
+
+// GitLab reports an edit, a label change and a status label change as one
+// "update" action with a `changes` object, so what Gitea splits across
+// issue_edited and issue_labeled arrives here together.
+type IssueUpdatedPayload = {
+ object_attributes: {
+ iid: number;
+ title: string;
+ description: string | null;
+ url: string;
+ action?: string;
+ };
+ labels?: GitlabWebhookLabel[];
+ changes?: {
+ title?: { previous?: string | null; current?: string | null };
+ description?: { previous?: string | null; current?: string | null };
+ labels?: {
+ previous?: GitlabWebhookLabel[];
+ current?: GitlabWebhookLabel[];
+ };
+ };
+ project: GitlabWebhookProject;
+};
+
+function nonSystemLabels(
+ labels: GitlabWebhookLabel[] | undefined,
+): Array<{ name: string; color: string }> {
+ const out: Array<{ name: string; color: string }> = [];
+ for (const label of labels ?? []) {
+ if (!label.title || isSystemLabelName(label.title)) continue;
+ out.push({ name: label.title, color: labelColor(label) });
+ }
+ return out;
+}
+
+async function syncGitlabLabelsToTask(
+ taskId: string,
+ workspaceId: string,
+ gitlabLabels: Array<{ name: string; color: string }>,
+) {
+ const desiredNames = new Set(gitlabLabels.map((l) => l.name));
+ const existingRows = await db.query.labelTable.findMany({
+ where: eq(labelTable.taskId, taskId),
+ });
+
+ const labelsToInsert = gitlabLabels
+ .filter((g) => !existingRows.some((row) => row.name === g.name))
+ .map((g) => ({
+ name: g.name,
+ color: g.color,
+ taskId,
+ workspaceId,
+ }));
+
+ const colorToIds = new Map<string, string[]>();
+ for (const g of gitlabLabels) {
+ const row = existingRows.find((r) => r.name === g.name);
+ if (!row) continue;
+ const have = row.color ? `#${row.color.replace(/^#/, "")}` : "#6B7280";
+ if (have === g.color) continue;
+ const list = colorToIds.get(g.color) ?? [];
+ list.push(row.id);
+ colorToIds.set(g.color, list);
+ }
+
+ for (const [color, ids] of colorToIds) {
+ await db
+ .update(labelTable)
+ .set({ color })
+ .where(inArray(labelTable.id, ids));
+ }
+
+ if (labelsToInsert.length > 0) {
+ await db
+ .insert(labelTable)
+ .values(labelsToInsert)
+ .onConflictDoNothing({
+ target: [labelTable.taskId, labelTable.name],
+ });
+ }
+
+ const labelsToDelete = existingRows
+ .filter(
+ (row) => !desiredNames.has(row.name) && !isSystemLabelName(row.name),
+ )
+ .map((row) => row.id);
+
+ if (labelsToDelete.length > 0) {
+ await db.delete(labelTable).where(inArray(labelTable.id, labelsToDelete));
+ }
+}
+
+export async function handleGitlabIssueUpdated(
+ payload: IssueUpdatedPayload,
+ integrationId?: string,
+) {
+ const issue = payload.object_attributes;
+ const { project, changes } = payload;
+
+ const touchedText = Boolean(changes?.title || changes?.description);
+ const touchedLabels = Boolean(changes?.labels);
+
+ if (!touchedText && !touchedLabels) {
+ return;
+ }
+
+ const baseUrl = baseUrlFromProjectWebUrl(
+ project.web_url,
+ project.path_with_namespace,
+ );
+ if (!baseUrl) return;
+
+ const integrations = await findAllIntegrationsByGitlabProject(
+ baseUrl,
+ project.path_with_namespace,
+ integrationId,
+ );
+
+ const currentLabels = changes?.labels?.current ?? payload.labels;
+
+ for (const integration of integrations) {
+ try {
+ const externalLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issue.iid.toString(),
+ );
+
+ if (!externalLink) {
+ continue;
+ }
+
+ const task = await db.query.taskTable.findFirst({
+ where: eq(taskTable.id, externalLink.taskId),
+ with: { project: true },
+ });
+
+ if (!task) {
+ continue;
+ }
+
+ let metadata: LinkMetadata = parseLinkSyncMetadata(
+ externalLink.metadata,
+ { externalLinkId: externalLink.id, field: "issue" },
+ );
+
+ if (touchedText) {
+ const updateData: Record<string, unknown> = {};
+ const lastSync = { ...(metadata.lastSync ?? {}) };
+ const now = new Date().toISOString();
+
+ if (
+ changes?.title &&
+ !isEchoOf(metadata.lastSync?.title, "kaneo", issue.title)
+ ) {
+ updateData.title = issue.title;
+ lastSync.title = {
+ timestamp: now,
+ source: "gitlab",
+ value: issue.title,
+ };
+ }
+
+ if (changes?.description) {
+ const description = formatTaskDescriptionFromIssue(issue.description);
+ if (!isEchoOf(metadata.lastSync?.description, "kaneo", description)) {
+ updateData.description = description;
+ lastSync.description = {
+ timestamp: now,
+ source: "gitlab",
+ value: description,
+ };
+ }
+ }
+
+ if (Object.keys(updateData).length > 0) {
+ await db
+ .update(taskTable)
+ .set(updateData)
+ .where(eq(taskTable.id, task.id));
+
+ metadata = { ...metadata, lastSync };
+
+ await updateExternalLink(externalLink.id, {
+ title: issue.title,
+ metadata,
+ });
+ }
+ }
+
+ if (!touchedLabels) {
+ continue;
+ }
+
+ const titles = labelTitles(currentLabels);
+ const priority = extractIssuePriority(titles);
+ const status = extractIssueStatus(titles);
+
+ if (priority) {
+ await db
+ .update(taskTable)
+ .set({ priority })
+ .where(eq(taskTable.id, task.id));
+ }
+
+ if (status) {
+ const statusResult = await updateTaskStatus(task.id, status);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ });
+ }
+ }
+
+ if (task.project?.workspaceId) {
+ await syncGitlabLabelsToTask(
+ task.id,
+ task.project.workspaceId,
+ nonSystemLabels(currentLabels),
+ );
+ }
+ } catch (error) {
+ console.error("GitLab issue update handler failed for integration", {
+ integrationId: integration.id,
+ issueIid: issue.iid,
+ project: project.path_with_namespace,
+ error,
+ });
+ }
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/merge-request-closed.ts b/apps/api/src/plugins/gitlab/webhooks/merge-request-closed.ts
new file mode 100644
index 000000000..cd7499616
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhooks/merge-request-closed.ts
@@ -0,0 +1,155 @@
+import { and, eq } from "drizzle-orm";
+import db from "../../../database";
+import { externalLinkTable } from "../../../database/schema";
+import { publishEvent } from "../../../events";
+import { updateExternalLink } from "../../github/services/link-manager";
+import {
+ findTaskById,
+ updateTaskStatus,
+} from "../../github/services/task-service";
+import type { GitlabConfig } from "../config";
+import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
+import type { GitlabWebhookProject } from "../utils/payload";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromProjectWebUrl } from "../utils/webhook-project";
+
+type MergeRequestClosedPayload = {
+ object_attributes: {
+ iid: number;
+ title: string;
+ url: string;
+ state: string;
+ action?: string;
+ source_branch?: string;
+ };
+ project: GitlabWebhookProject;
+};
+
+export async function handleGitlabMergeRequestClosed(
+ payload: MergeRequestClosedPayload,
+ integrationId?: string,
+) {
+ const mergeRequest = payload.object_attributes;
+ const { project } = payload;
+ const merged = mergeRequest.action === "merge";
+
+ const baseUrl = baseUrlFromProjectWebUrl(
+ project.web_url,
+ project.path_with_namespace,
+ );
+ if (!baseUrl) return;
+
+ const integrations = await findAllIntegrationsByGitlabProject(
+ baseUrl,
+ project.path_with_namespace,
+ integrationId,
+ );
+
+ for (const integration of integrations) {
+ let config: GitlabConfig;
+ try {
+ config = JSON.parse(integration.config) as GitlabConfig;
+ } catch (error) {
+ console.error("Invalid GitLab config for integration", {
+ integrationId: integration.id,
+ error,
+ });
+ continue;
+ }
+
+ const externalLink = await db.query.externalLinkTable.findFirst({
+ where: and(
+ eq(externalLinkTable.integrationId, integration.id),
+ eq(externalLinkTable.resourceType, "pull_request"),
+ eq(externalLinkTable.externalId, mergeRequest.iid.toString()),
+ ),
+ });
+
+ if (!externalLink) {
+ continue;
+ }
+
+ const task = await findTaskById(externalLink.taskId);
+
+ if (!task) {
+ continue;
+ }
+
+ let existingMetadata: Record<string, unknown> = {};
+ if (externalLink.metadata) {
+ try {
+ existingMetadata = JSON.parse(externalLink.metadata) as Record<
+ string,
+ unknown
+ >;
+ } catch (error) {
+ console.warn("Failed to parse GitLab merge request metadata", {
+ externalLinkId: externalLink.id,
+ metadata: externalLink.metadata,
+ error,
+ });
+ }
+ }
+
+ await updateExternalLink(externalLink.id, {
+ metadata: {
+ ...existingMetadata,
+ state: merged ? "merged" : "closed",
+ draft: false,
+ merged,
+ },
+ });
+
+ if (!merged) {
+ return;
+ }
+
+ const allTaskMergeRequests = await db.query.externalLinkTable.findMany({
+ where: and(
+ eq(externalLinkTable.taskId, task.id),
+ eq(externalLinkTable.resourceType, "pull_request"),
+ ),
+ });
+
+ const hasOpenMergeRequests = allTaskMergeRequests.some((link) => {
+ if (link.id === externalLink.id) return false;
+ try {
+ const metadata = link.metadata
+ ? (JSON.parse(link.metadata) as { state?: string })
+ : {};
+ return metadata.state === "opened";
+ } catch {
+ return false;
+ }
+ });
+
+ if (hasOpenMergeRequests) {
+ return;
+ }
+
+ const targetStatus = await resolveTargetStatus(
+ integration.projectId,
+ "pr_merged",
+ config.statusTransitions?.onPRMerge || "done",
+ );
+
+ const statusResult = await updateTaskStatus(task.id, targetStatus);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ });
+ }
+
+ return;
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/merge-request-opened.ts b/apps/api/src/plugins/gitlab/webhooks/merge-request-opened.ts
new file mode 100644
index 000000000..b76a43245
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhooks/merge-request-opened.ts
@@ -0,0 +1,157 @@
+import { publishEvent } from "../../../events";
+import {
+ createExternalLink,
+ findExternalLink,
+ updateExternalLink,
+} from "../../github/services/link-manager";
+import {
+ findTaskByNumber,
+ isTaskInFinalState,
+ updateTaskStatus,
+} from "../../github/services/task-service";
+import type { GitlabConfig } from "../config";
+import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
+import { extractTaskNumberGitlab } from "../utils/branch-matcher";
+import type { GitlabWebhookProject, GitlabWebhookUser } from "../utils/payload";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromProjectWebUrl } from "../utils/webhook-project";
+
+// A merge request is stored as a `pull_request` external link: the resource
+// type is the shared vocabulary the task UI already renders, not a forge term.
+type MergeRequestOpenedPayload = {
+ user?: GitlabWebhookUser | null;
+ object_attributes: {
+ iid: number;
+ title: string;
+ description: string | null;
+ url: string;
+ state: string;
+ action?: string;
+ draft?: boolean;
+ source_branch?: string;
+ };
+ project: GitlabWebhookProject;
+};
+
+export async function handleGitlabMergeRequestOpened(
+ payload: MergeRequestOpenedPayload,
+ integrationId?: string,
+) {
+ const mergeRequest = payload.object_attributes;
+ const { project } = payload;
+ const branchName = mergeRequest.source_branch;
+
+ if (!branchName) {
+ return;
+ }
+
+ const baseUrl = baseUrlFromProjectWebUrl(
+ project.web_url,
+ project.path_with_namespace,
+ );
+ if (!baseUrl) return;
+
+ const integrations = await findAllIntegrationsByGitlabProject(
+ baseUrl,
+ project.path_with_namespace,
+ integrationId,
+ );
+
+ for (const integration of integrations) {
+ if (!integration.project) {
+ continue;
+ }
+
+ let config: GitlabConfig;
+ try {
+ config = JSON.parse(integration.config) as GitlabConfig;
+ } catch (error) {
+ console.error("Invalid GitLab config for integration", {
+ integrationId: integration.id,
+ error,
+ });
+ continue;
+ }
+
+ const taskNumber = extractTaskNumberGitlab(
+ branchName,
+ mergeRequest.title,
+ mergeRequest.description ?? undefined,
+ config,
+ integration.project.slug,
+ );
+
+ if (!taskNumber) {
+ continue;
+ }
+
+ const task = await findTaskByNumber(integration.projectId, taskNumber);
+
+ if (!task) {
+ continue;
+ }
+
+ const existingLink = await findExternalLink(
+ integration.id,
+ "pull_request",
+ mergeRequest.iid.toString(),
+ );
+
+ const metadata = {
+ state: mergeRequest.state,
+ draft: mergeRequest.draft === true,
+ merged: false,
+ branch: branchName,
+ author: payload.user?.username ?? payload.user?.name,
+ };
+
+ if (existingLink) {
+ await updateExternalLink(existingLink.id, {
+ title: mergeRequest.title,
+ url: mergeRequest.url,
+ metadata,
+ });
+ } else {
+ await createExternalLink({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "pull_request",
+ externalId: mergeRequest.iid.toString(),
+ url: mergeRequest.url,
+ title: mergeRequest.title,
+ metadata,
+ });
+ }
+
+ // A reopen arrives with the link already recorded, and the task still needs
+ // to move back out of whatever state closing it left behind.
+ const targetStatus = await resolveTargetStatus(
+ integration.projectId,
+ "pr_opened",
+ config.statusTransitions?.onPROpen || "in-review",
+ );
+
+ const isTaskFinal = await isTaskInFinalState(task);
+
+ if (task.status !== targetStatus && !isTaskFinal) {
+ const statusResult = await updateTaskStatus(task.id, targetStatus);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ });
+ }
+ }
+
+ return;
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/note-created.ts b/apps/api/src/plugins/gitlab/webhooks/note-created.ts
new file mode 100644
index 000000000..3e3778327
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhooks/note-created.ts
@@ -0,0 +1,92 @@
+import db from "../../../database";
+import { activityTable } from "../../../database/schema";
+import { findExternalLink } from "../../github/services/link-manager";
+import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
+import type { GitlabWebhookProject, GitlabWebhookUser } from "../utils/payload";
+import { syncedNoteIds } from "../utils/synced-notes";
+import { baseUrlFromProjectWebUrl } from "../utils/webhook-project";
+
+type NoteCreatedPayload = {
+ user?: GitlabWebhookUser | null;
+ object_attributes: {
+ id: number;
+ note: string;
+ noteable_type: string;
+ url: string;
+ system?: boolean;
+ };
+ issue?: { iid: number };
+ project: GitlabWebhookProject;
+};
+
+export async function handleGitlabNoteCreated(
+ payload: NoteCreatedPayload,
+ integrationId?: string,
+) {
+ const note = payload.object_attributes;
+
+ if (note.noteable_type !== "Issue" || !payload.issue) {
+ return;
+ }
+
+ // GitLab posts a system note for label, milestone and status changes. Those
+ // are not comments and would read as one in the task activity.
+ if (note.system) {
+ return;
+ }
+
+ const baseUrl = baseUrlFromProjectWebUrl(
+ payload.project.web_url,
+ payload.project.path_with_namespace,
+ );
+ if (!baseUrl) return;
+
+ const integrations = await findAllIntegrationsByGitlabProject(
+ baseUrl,
+ payload.project.path_with_namespace,
+ integrationId,
+ );
+
+ const username = payload.user?.username ?? payload.user?.name ?? "";
+ const issueIid = payload.issue.iid;
+
+ for (const integration of integrations) {
+ const externalLink = await findExternalLink(
+ integration.id,
+ "issue",
+ issueIid.toString(),
+ );
+
+ if (!externalLink) {
+ continue;
+ }
+
+ // A note Kaneo posted itself comes back authored by the token's own user,
+ // so the author is no help; the id Kaneo recorded when posting is.
+ if (syncedNoteIds(externalLink.metadata).includes(note.id)) {
+ continue;
+ }
+
+ await db
+ .insert(activityTable)
+ .values({
+ taskId: externalLink.taskId,
+ type: "comment",
+ content: note.note,
+ externalUserName: username || "Unknown",
+ externalUserAvatar: payload.user?.avatar_url ?? null,
+ externalSource: "gitlab",
+ externalUrl: note.url,
+ eventData: {
+ externalCommentId: note.id,
+ },
+ })
+ .onConflictDoNothing({
+ target: [
+ activityTable.taskId,
+ activityTable.externalSource,
+ activityTable.externalUrl,
+ ],
+ });
+ }
+}
diff --git a/apps/api/src/plugins/gitlab/webhooks/push.ts b/apps/api/src/plugins/gitlab/webhooks/push.ts
new file mode 100644
index 000000000..58c54f1b0
--- /dev/null
+++ b/apps/api/src/plugins/gitlab/webhooks/push.ts
@@ -0,0 +1,157 @@
+import { publishEvent } from "../../../events";
+import { createOrUpdateExternalLink } from "../../github/services/link-manager";
+import {
+ findTaskByNumber,
+ isTaskInFinalState,
+ updateTaskStatus,
+} from "../../github/services/task-service";
+import type { GitlabConfig } from "../config";
+import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";
+import { extractTaskNumberFromBranchGitlab } from "../utils/branch-matcher";
+import type { GitlabWebhookProject } from "../utils/payload";
+import { resolveTargetStatus } from "../utils/resolve-column";
+import { baseUrlFromProjectWebUrl } from "../utils/webhook-project";
+
+type PushPayload = {
+ ref: string;
+ commits?: Array<{
+ id: string;
+ message: string;
+ timestamp?: string;
+ author?: { name?: string };
+ }>;
+ project: GitlabWebhookProject;
+};
+
+const PROTECTED_BRANCHES = [
+ "main",
+ "master",
+ "develop",
+ "staging",
+ "production",
+];
+
+// A branch name may contain slashes, and those are path separators in GitLab's
+// tree URL rather than characters to escape.
+function treePath(branchName: string): string {
+ return branchName.split("/").map(encodeURIComponent).join("/");
+}
+
+export async function handleGitlabPush(
+ payload: PushPayload,
+ integrationId?: string,
+) {
+ const { ref, project } = payload;
+
+ if (!ref.startsWith("refs/heads/")) {
+ console.log(`[GitLab Push] Skipping non-branch ref: ${ref}`);
+ return;
+ }
+
+ const branchName = ref.slice("refs/heads/".length);
+ console.log(`[GitLab Push] Processing branch: ${branchName}`);
+
+ if (PROTECTED_BRANCHES.includes(branchName)) {
+ console.log(`[GitLab Push] Skipping protected branch: ${branchName}`);
+ return;
+ }
+
+ const baseUrl = baseUrlFromProjectWebUrl(
+ project.web_url,
+ project.path_with_namespace,
+ );
+ if (!baseUrl) {
+ return;
+ }
+
+ const integrations = await findAllIntegrationsByGitlabProject(
+ baseUrl,
+ project.path_with_namespace,
+ integrationId,
+ );
+
+ if (integrations.length === 0) {
+ return;
+ }
+
+ const headCommit = payload.commits?.[payload.commits.length - 1];
+
+ for (const integration of integrations) {
+ if (!integration.project) {
+ continue;
+ }
+
+ let config: GitlabConfig;
+ try {
+ config = JSON.parse(integration.config) as GitlabConfig;
+ } catch (error) {
+ console.error("Invalid GitLab integration config for push webhook", {
+ integrationId: integration.id,
+ error,
+ });
+ continue;
+ }
+
+ const taskNumber = extractTaskNumberFromBranchGitlab(
+ branchName,
+ config,
+ integration.project.slug,
+ );
+
+ if (!taskNumber) {
+ continue;
+ }
+
+ const task = await findTaskByNumber(integration.projectId, taskNumber);
+
+ if (!task) {
+ continue;
+ }
+
+ await createOrUpdateExternalLink({
+ taskId: task.id,
+ integrationId: integration.id,
+ resourceType: "branch",
+ externalId: branchName,
+ url: `${project.web_url}/-/tree/${treePath(branchName)}`,
+ title: branchName,
+ metadata: {
+ lastCommit: headCommit
+ ? {
+ sha: headCommit.id,
+ message: headCommit.message,
+ author: headCommit.author?.name,
+ timestamp: headCommit.timestamp,
+ }
+ : null,
+ },
+ });
+
+ const targetStatus = await resolveTargetStatus(
+ integration.projectId,
+ "branch_push",
+ config.statusTransitions?.onBranchPush || "in-progress",
+ );
+
+ const isTaskFinal = await isTaskInFinalState(task);
+
+ if (task.status !== targetStatus && !isTaskFinal) {
+ const statusResult = await updateTaskStatus(task.id, targetStatus);
+ if (
+ statusResult.applied &&
+ statusResult.before.status !== statusResult.after.status
+ ) {
+ await publishEvent("task.status_changed", {
+ taskId: statusResult.after.id,
+ projectId: statusResult.after.projectId,
+ userId: null,
+ oldStatus: statusResult.before.status,
+ newStatus: statusResult.after.status,
+ title: statusResult.after.title,
+ assigneeId: statusResult.after.userId,
+ type: "status_changed",
+ });
+ }
+ }
+ }
+}