⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(integrations): address label sync review findings
Tin6a1f24d31dcf
diff --git a/apps/api/src/integration-sync/controllers/get-integration.ts b/apps/api/src/integration-sync/controllers/get-integration.tsindex f800fef71..7201cc391 100644--- a/apps/api/src/integration-sync/controllers/get-integration.ts+++ b/apps/api/src/integration-sync/controllers/get-integration.ts@@ -3,9 +3,14 @@ import { HTTPException } from "hono/http-exception";import db from "../../database";import { integrationTable } from "../../database/schema";import { readSyncRules } from "../../plugins/sync/rules";+import type { IntegrationDatabase } from "../../plugins/github/services/integration-task-scope";-export async function getSyncIntegration(projectId: string, provider: string) {- const integration = await db.query.integrationTable.findFirst({+export async function getSyncIntegration(+ projectId: string,+ provider: string,+ database: IntegrationDatabase = db,+) {+ const integration = await database.query.integrationTable.findFirst({where: and(eq(integrationTable.projectId, projectId),eq(integrationTable.type, provider),diff --git a/apps/api/src/integration-sync/controllers/lock-resume-scope.ts b/apps/api/src/integration-sync/controllers/lock-resume-scope.tsnew file mode 100644index 000000000..b588cb430--- /dev/null+++ b/apps/api/src/integration-sync/controllers/lock-resume-scope.ts@@ -0,0 +1,68 @@+import { and, eq, inArray, isNull, or } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import {+ externalLinkTable,+ integrationTable,+ labelTable,+ taskTable,+} from "../../database/schema";+import type { IntegrationDatabase } from "../../plugins/github/services/integration-task-scope";+import { readSyncRules } from "../../plugins/sync/rules";+import { getSyncIntegration } from "./get-integration";++export async function lockResumeScope(+ projectId: string,+ provider: string,+ linkId: string,+ tx: IntegrationDatabase,+) {+ const integration = await getSyncIntegration(projectId, provider, tx);+ const [binding] = await tx+ .select()+ .from(integrationTable)+ .where(eq(integrationTable.id, integration.id))+ .for("share");+ const link = await tx.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.id, linkId),+ eq(externalLinkTable.integrationId, integration.id),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ });+ if (!link) throw new HTTPException(404, { message: "Linked task not found" });+ await tx+ .select({ id: taskTable.id })+ .from(taskTable)+ .where(+ and(eq(taskTable.id, link.taskId), eq(taskTable.projectId, projectId)),+ )+ .for("no key update");+ const rule = readSyncRules(binding!.config)?.outgoing;+ if (!rule)+ throw new HTTPException(409, {+ message: "Integration rules changed; review again",+ });+ if (rule.mode === "labels") {+ // Protect both selected roots and assigned copies against rename/deletion+ // until the provider write and local resume have committed.+ await tx+ .select({ id: labelTable.id })+ .from(labelTable)+ .where(+ and(+ eq(labelTable.workspaceId, integration.project.workspaceId),+ or(+ and(isNull(labelTable.taskId), inArray(labelTable.id, rule.labels)),+ eq(labelTable.taskId, link.taskId),+ ),+ ),+ )+ .orderBy(labelTable.id)+ .for("share");+ }+ await tx+ .select({ id: externalLinkTable.id })+ .from(externalLinkTable)+ .where(eq(externalLinkTable.id, linkId))+ .for("update");+}diff --git a/apps/api/src/integration-sync/controllers/preview-rules.ts b/apps/api/src/integration-sync/controllers/preview-rules.tsindex 48aaa0ada..c33de9399 100644--- a/apps/api/src/integration-sync/controllers/preview-rules.ts+++ b/apps/api/src/integration-sync/controllers/preview-rules.ts@@ -1,5 +1,5 @@import { createHash } from "node:crypto";-import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";+import { and, asc, desc, eq, gt, or, sql } from "drizzle-orm";import db from "../../database";import { externalLinkTable, taskTable } from "../../database/schema";import type { IntegrationDatabase } from "../../plugins/github/services/integration-task-scope";@@ -23,103 +23,102 @@ export async function previewSyncRules(readSyncRules(integration.config)!.outgoing,database,);- const rows = await database- .selectDistinctOn([taskTable.id], {+ const paused = sql<boolean>`coalesce(${externalLinkTable.metadata} ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)`;+ const scope = database.$with("sync_scope").as(+ database+ .selectDistinctOn([taskTable.id], {+ id: taskTable.id,+ eligible: proposed.predicate.as("eligible"),+ current: current.predicate.as("current"),+ linkId: sql<string | null>`${externalLinkTable.id}`.as("link_id"),+ url: externalLinkTable.url,+ paused: paused.as("paused"),+ })+ .from(taskTable)+ .leftJoin(+ externalLinkTable,+ and(+ eq(externalLinkTable.taskId, taskTable.id),+ eq(externalLinkTable.integrationId, integration.id),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ )+ .where(eq(taskTable.projectId, integration.projectId))+ .orderBy(asc(taskTable.id), desc(paused), asc(externalLinkTable.id)),+ );+ const [impact] = await database+ .with(scope)+ .select({+ total: sql<number>`count(*)::int`,+ matching: sql<number>`count(*) filter (where ${scope.eligible})::int`,+ willCreate: sql<number>`count(*) filter (where ${scope.eligible} and ${scope.linkId} is null)::int`,+ willPause: sql<number>`count(*) filter (where ${scope.linkId} is not null and not ${scope.eligible} and not ${scope.paused})::int`,+ needsReview: sql<number>`count(*) filter (where ${scope.linkId} is not null and ${scope.eligible} and (${scope.paused} or not ${scope.current}))::int`,+ paused: sql<number>`count(*) filter (where ${scope.linkId} is not null and (not ${scope.eligible} or ${scope.paused}))::int`,+ // Build the ordered scope revision in PostgreSQL instead of transferring+ // every task/link to the API just to hash it. Page cursors do not affect it.+ revision: sql<string>`md5(coalesce(string_agg(jsonb_build_array(${scope.id}, ${scope.eligible}, ${scope.current}, ${scope.linkId}, ${scope.url}, ${scope.paused})::text, ',' order by ${scope.id}), ''))`,+ })+ .from(scope);+ const matchingTasks = await database+ .with(scope)+ .select({+ id: taskTable.id,+ number: taskTable.number,+ title: taskTable.title,+ })+ .from(scope)+ .innerJoin(taskTable, eq(taskTable.id, scope.id))+ .where(sql`${scope.eligible}`)+ .orderBy(asc(scope.id))+ .limit(10);+ const pausedPage = await database+ .with(scope)+ .select({id: taskTable.id,- eligible: proposed.predicate,- current: current.predicate,- linkId: externalLinkTable.id,- url: externalLinkTable.url,- paused: sql<boolean>`coalesce(${externalLinkTable.metadata} ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)`,+ number: taskTable.number,+ title: taskTable.title,+ linkId: scope.linkId,+ url: scope.url,+ eligible: scope.eligible,})- .from(taskTable)- .leftJoin(- externalLinkTable,+ .from(scope)+ .innerJoin(taskTable, eq(taskTable.id, scope.id))+ .where(and(- eq(externalLinkTable.taskId, taskTable.id),- eq(externalLinkTable.integrationId, integration.id),- eq(externalLinkTable.resourceType, "issue"),+ sql`${scope.linkId} is not null`,+ or(sql`not ${scope.eligible}`, scope.paused),+ after ? gt(scope.id, after) : undefined,),)- .where(eq(taskTable.projectId, integration.projectId))- .orderBy(- asc(taskTable.id),- desc(- sql`coalesce(${externalLinkTable.metadata} ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)`,- ),- asc(externalLinkTable.id),- );- const matching = rows.filter((row) => row.eligible);- const paused = rows.filter(- (row) => row.linkId && (!row.eligible || row.paused),- );- const pausedPage = paused- .filter((row) => !after || row.id > after)- .slice(0, 26);- const sampled = [- ...new Set(- [...matching.slice(0, 10), ...pausedPage.slice(0, 25)].map(- (row) => row.id,- ),- ),- ];- const tasks = sampled.length- ? await database- .select({- id: taskTable.id,- number: taskTable.number,- title: taskTable.title,- })- .from(taskTable)- .where(- and(- eq(taskTable.projectId, integration.projectId),- inArray(taskTable.id, sampled),- ),- )- : [];- const samples = new Map(tasks.map((task) => [task.id, task]));+ .orderBy(asc(scope.id))+ .limit(26);const previewToken = createHash("sha256").update(JSON.stringify({integration: [integration.id, integration.config, integration.isActive],rules,labels: proposed.labels,- rows,+ revision: impact!.revision,}),).digest("hex");+ const { revision: _, ...counts } = impact!;return {isActive: integration.isActive === true,rules,labels: proposed.labels,missingLabels: proposed.missing,- total: new Set(rows.map((row) => row.id)).size,- matching: matching.length,- willCreate: matching.filter((row) => !row.linkId).length,- willPause: rows.filter((row) => row.linkId && !row.eligible && !row.paused)- .length,- needsReview: rows.filter(- (row) => row.linkId && row.eligible && (row.paused || !row.current),- ).length,- paused: paused.length,- matchingTasks: matching- .slice(0, 10)- .flatMap((row) => samples.get(row.id) ?? []),+ ...counts,+ matchingTasks,pausedNextCursor: pausedPage.length > 25 ? pausedPage[24]!.id : null,- pausedTasks: pausedPage.slice(0, 25).flatMap((row) => {- const task = samples.get(row.id);- return task && row.linkId && row.url- ? [- {- ...task,- linkId: row.linkId,- url: row.url,- eligible: row.eligible,- },- ]- : [];- }),+ pausedTasks: pausedPage+ .slice(0, 25)+ .flatMap((task) =>+ task.linkId && task.url+ ? [{ ...task, linkId: task.linkId, url: task.url }]+ : [],+ ),previewToken,};}diff --git a/apps/api/src/integration-sync/controllers/resume-sync.ts b/apps/api/src/integration-sync/controllers/resume-sync.tsindex e546960ba..5ed89eff2 100644--- a/apps/api/src/integration-sync/controllers/resume-sync.ts+++ b/apps/api/src/integration-sync/controllers/resume-sync.ts@@ -1,13 +1,8 @@import { randomUUID } from "node:crypto";-import { and, asc, eq, sql } from "drizzle-orm";+import { asc, eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import {- columnTable,- externalLinkTable,- integrationTable,- taskTable,-} from "../../database/schema";+import { columnTable, taskTable } from "../../database/schema";import { publishEvent } from "../../events";import { updateExternalLink } from "../../plugins/github/services/link-manager";import { parseDeferredIssueEdit } from "../../plugins/github/utils/deferred-issue-edit";@@ -16,13 +11,11 @@ import {type SyncStamp,} from "../../plugins/github/utils/sync-echo";import { formatIssueBody } from "../../plugins/github/utils/format";-import { taskMatchesRule } from "../../plugins/sync/eligibility";-import { readSyncRules } from "../../plugins/sync/rules";import { reviewSyncResume } from "./review-resume";+import { lockResumeScope } from "./lock-resume-scope";+import { withSyncLease } from "../../plugins/sync/lease";+import type { TaskStatusChangedEvent } from "../../plugins/types";-// A resume lease performs fresh reads and a nested commit using the pool.-// Queue concurrent requests locally to leave connections available for them.-let resumeQueue: Promise<void> = Promise.resolve();export async function resumeSync(projectId: string,provider: string,@@ -30,14 +23,9 @@ export async function resumeSync(token: string,source: "kaneo" | "provider",) {- const next = resumeQueue.then(() =>+ return withSyncLease(`sync-resume:${linkId}`, () =>resumeWithLease(projectId, provider, linkId, token, source),);- resumeQueue = next.then(- () => {},- () => {},- );- return next;}async function resumeWithLease(@@ -47,78 +35,33 @@ async function resumeWithLease(token: string,source: "kaneo" | "provider",) {- await db.transaction(async (lease) => {- const result = await lease.execute<{ locked: boolean }>(- sql`select pg_try_advisory_xact_lock(hashtextextended(${`sync-resume:${linkId}`}, 0)) as locked`,- );- if (!result.rows[0]?.locked)- throw new HTTPException(409, {- message: "This task is already being resumed",- });- const review = await reviewSyncResume(projectId, provider, linkId);- if (review.token !== token)- throw new HTTPException(409, {- message: "Task or issue changed; review the comparison again",- });- let updatedAt: string | null = null;- if (source === "kaneo") {- try {- updatedAt = (await review.access.write(review.local)).updatedAt;- } catch {- throw new HTTPException(502, {- message: "External issue could not be updated; sync remains paused",- });- }- }+ let providerWritten = false;+ let statusChange:+ | (TaskStatusChangedEvent & { assigneeId: string | null })+ | undefined;+ let taskId: string | undefined;+ try {await db.transaction(async (tx) => {- const [binding] = await tx- .select()- .from(integrationTable)- .where(- and(- eq(integrationTable.id, review.integration.id),- eq(integrationTable.config, review.integration.config),- eq(integrationTable.isActive, true),- ),- )- .for("share");- const [task] = await tx- .select()- .from(taskTable)- .where(- and(- eq(taskTable.id, review.task.id),- eq(taskTable.projectId, projectId),- ),- )- .for("no key update");- const [link] = await tx- .select()- .from(externalLinkTable)- .where(- and(- eq(externalLinkTable.id, linkId),- eq(externalLinkTable.integrationId, review.integration.id),- eq(externalLinkTable.taskId, review.task.id),- ),- )- .for("update");- if (- !binding ||- !task ||- !link ||- task.updatedAt.getTime() !== review.task.updatedAt.getTime() ||- link.metadata !== review.link.metadata ||- !(await taskMatchesRule(- task.id,- projectId,- readSyncRules(binding.config)!.outgoing,- tx,- ))- )+ await lockResumeScope(projectId, provider, linkId, tx);+ const review = await reviewSyncResume(projectId, provider, linkId, tx);+ taskId = review.task.id;+ const task = review.task;+ const link = review.link;+ if (review.token !== token)throw new HTTPException(409, {- message: "Sync scope or task changed; review again before resuming",+ message: "Task or issue changed; review the comparison again",});+ let updatedAt: string | null = null;+ if (source === "kaneo") {+ try {+ updatedAt = (await review.access.write(review.local)).updatedAt;+ providerWritten = true;+ } catch {+ throw new HTTPException(502, {+ message: "External issue could not be updated; sync remains paused",+ });+ }+ }if (source === "provider") {const final = review.remote.state === "closed";const columns = await tx@@ -144,6 +87,17 @@ async function resumeWithLease(columnId: target.id,}).where(eq(taskTable.id, task.id));+ if (task.status !== target.slug)+ statusChange = {+ sourceIntegrationId: review.integration.id,+ taskId: task.id,+ projectId,+ userId: null,+ assigneeId: task.userId,+ oldStatus: task.status,+ newStatus: target.slug,+ title: review.remote.title,+ };}const job = parseDeferredIssueEdit(JSON.parse(link.metadata ?? "{}").deferredIssueEdit,@@ -166,6 +120,7 @@ async function resumeWithLease(...(job ? { completeDeferredEdit: job.id } : {}),metadata: {syncFilterPaused: false,+ syncResumeUncertain: false,...(provider === "gitlab"? {lastOutboundStateSyncAt: Date.now(),@@ -211,8 +166,24 @@ async function resumeWithLease();}});- await publishEvent("task.updated", { projectId, taskId: review.task.id });- await publishEvent("project.updated", { projectId });- });+ } catch (error) {+ if (providerWritten) {+ // A database failure after a successful provider write must remain visible+ // to the next review. The link stays paused and clients refresh both sides.+ await updateExternalLink(linkId, {+ metadata: { syncFilterPaused: true, syncResumeUncertain: true },+ });+ await publishEvent("project.updated", { projectId });+ if (taskId) await publishEvent("task.updated", { projectId, taskId });+ }+ throw error;+ }+ if (statusChange)+ await publishEvent("task.status_changed", {+ ...statusChange,+ type: "status_changed",+ });+ await publishEvent("task.updated", { projectId, taskId });+ await publishEvent("project.updated", { projectId });return { success: true };}diff --git a/apps/api/src/integration-sync/controllers/review-resume.ts b/apps/api/src/integration-sync/controllers/review-resume.tsindex 9fed4128f..3b4b0b8ba 100644--- a/apps/api/src/integration-sync/controllers/review-resume.ts+++ b/apps/api/src/integration-sync/controllers/review-resume.ts@@ -8,14 +8,16 @@ import { taskMatchesRule } from "../../plugins/sync/eligibility";import { providerIssue } from "../../plugins/sync/provider-issue";import { isSyncPaused, readSyncRules } from "../../plugins/sync/rules";import { getSyncIntegration } from "./get-integration";+import type { IntegrationDatabase } from "../../plugins/github/services/integration-task-scope";export async function reviewSyncResume(projectId: string,provider: string,linkId: string,+ database: IntegrationDatabase = db,) {- const integration = await getSyncIntegration(projectId, provider);- const link = await db.query.externalLinkTable.findFirst({+ const integration = await getSyncIntegration(projectId, provider, database);+ const link = await database.query.externalLinkTable.findFirst({where: and(eq(externalLinkTable.id, linkId),eq(externalLinkTable.integrationId, integration.id),@@ -24,7 +26,7 @@ export async function reviewSyncResume(});const task =link &&- (await db.query.taskTable.findFirst({+ (await database.query.taskTable.findFirst({where: and(eq(taskTable.id, link.taskId),eq(taskTable.projectId, projectId),@@ -39,6 +41,7 @@ export async function reviewSyncResume(task.id,projectId,readSyncRules(integration.config)!.outgoing,+ database,)))throw new HTTPException(409, {@@ -51,7 +54,7 @@ export async function reviewSyncResume(const local = {title: task.title,description: task.description ?? "",- state: (await isTaskInFinalState(task))+ state: (await isTaskInFinalState(task, database))? ("closed" as const): ("open" as const),};@@ -66,6 +69,7 @@ export async function reviewSyncResume(binding: [integration.id, integration.config],task,link,+ local,remoteIssue,}),)diff --git a/apps/api/src/integration-sync/controllers/save-rules.ts b/apps/api/src/integration-sync/controllers/save-rules.tsindex ed4cd542e..d3677f0cb 100644--- a/apps/api/src/integration-sync/controllers/save-rules.ts+++ b/apps/api/src/integration-sync/controllers/save-rules.ts@@ -1,13 +1,9 @@import { and, eq, not, or } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import {- externalLinkTable,- integrationTable,- taskTable,-} from "../../database/schema";+import { integrationTable } from "../../database/schema";import { publishEvent } from "../../events";-import { updateExternalLink } from "../../plugins/github/services/link-manager";+import { pauseIssueLinks } from "../../plugins/sync/pause-issue-links";import { outgoingPredicate } from "../../plugins/sync/task-predicate";import { readSyncRules, type SyncRules } from "../../plugins/sync/rules";import { getSyncIntegration } from "./get-integration";@@ -58,24 +54,12 @@ export async function saveSyncRules(rules.outgoing,tx,);- const links = await tx- .select({ id: externalLinkTable.id })- .from(externalLinkTable)- .innerJoin(taskTable, eq(taskTable.id, externalLinkTable.taskId))- .where(- and(- eq(externalLinkTable.integrationId, integration.id),- eq(externalLinkTable.resourceType, "issue"),- eq(taskTable.projectId, projectId),- or(not(oldScope.predicate), not(nextScope.predicate)),- ),- );- for (const link of links)- await updateExternalLink(- link.id,- { metadata: { syncFilterPaused: true } },- tx,- );+ await pauseIssueLinks(+ projectId,+ integration.id,+ or(not(oldScope.predicate), not(nextScope.predicate))!,+ tx,+ );const config = JSON.parse(current.config) as Record<string, unknown>;await tx.update(integrationTable)diff --git a/apps/api/src/label/controllers/delete-label.ts b/apps/api/src/label/controllers/delete-label.tsindex d037b46bb..8256e89fc 100644--- a/apps/api/src/label/controllers/delete-label.ts+++ b/apps/api/src/label/controllers/delete-label.ts@@ -6,6 +6,7 @@ import { publishEvent } from "../../events";import { removeLabelFromGitea } from "../../plugins/gitea/utils/sync-label-to-gitea";import { removeLabelFromGitHub } from "../../plugins/github/utils/sync-label-to-github";import { removeLabelFromGitlab } from "../../plugins/gitlab/utils/sync-label-to-gitlab";+import { notifySyncWorkspaceLabelChanged } from "../../plugins/sync/workspace-label-changed";import { withLabelDeletionLock } from "../deletion-lock";export const LABEL_DELETE_BATCH_SIZE = 25;@@ -97,14 +98,7 @@ async function deleteLabel(.returning();if (!root) throw new HTTPException(404, { message: "Label not found" });if (root.workspaceId) {- const projects = await db- .select({ id: projectTable.id })- .from(projectTable)- .where(eq(projectTable.workspaceId, root.workspaceId));- for (const project of projects)- await publishEvent("integration.sync_labels_changed", {- projectId: project.id,- });+ await notifySyncWorkspaceLabelChanged(root.workspaceId, root.id);const predicate = and(eq(labelTable.workspaceId, root.workspaceId),eq(labelTable.name, root.name),diff --git a/apps/api/src/label/controllers/update-label.ts b/apps/api/src/label/controllers/update-label.tsindex fa6a4d4b6..d66159a56 100644--- a/apps/api/src/label/controllers/update-label.ts+++ b/apps/api/src/label/controllers/update-label.ts@@ -4,6 +4,7 @@ import db from "../../database";import { labelTable, projectTable, taskTable } from "../../database/schema";import { publishEvent } from "../../events";+import { notifySyncWorkspaceLabelChanged } from "../../plugins/sync/workspace-label-changed";async function updateLabel(id: string, name: string, color: string) {const result = await db.transaction(async (tx) => {@@ -70,11 +71,20 @@ async function updateLabel(id: string, name: string, color: string) {eq(projectTable.workspaceId, label.workspaceId ?? ""),),);- return { updatedLabel, projects };+ return { updatedLabel, projects, original: label };});for (const { projectId } of result.projects) {await publishEvent("project.updated", { projectId });- await publishEvent("integration.sync_labels_changed", { projectId });+ }+ if (result.original.name !== name) {+ if (!result.original.taskId && result.original.workspaceId)+ await notifySyncWorkspaceLabelChanged(result.original.workspaceId, id);+ else if (result.original.taskId)+ for (const { projectId } of result.projects)+ await publishEvent("task.labels_updated", {+ projectId,+ taskId: result.original.taskId,+ });}return result.updatedLabel;}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts b/apps/api/src/plugins/gitea/webhooks/issue-opened.tsindex 352bf5cca..132b13e93 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-opened.ts@@ -35,6 +35,7 @@ type IssueOpenedPayload = {issue: {number: number;title: string;+ state?: string;body: string | null;html_url: string;labels?: Array<string | { name?: string }>;@@ -83,6 +84,7 @@ export async function handleGiteaIssueOpened(continue;}const projectId = integration.projectId;+ const closed = issue.state === "closed";const priority = extractIssuePriority(issue.labels);const status = extractIssueStatus(issue.labels);@@ -110,16 +112,24 @@ export async function handleGiteaIssueOpened(return null;const resolvedStatus = await resolveTargetStatus(projectId,- "issue_opened",- status || "to-do",+ closed ? "issue_closed" : "issue_opened",+ closed ? "done" : status || "to-do",tx,);- const targetColumn = await tx.query.columnTable.findFirst({+ let targetColumn = await tx.query.columnTable.findFirst({where: and(eq(columnTable.projectId, projectId),eq(columnTable.slug, resolvedStatus),),});+ if (closed && !targetColumn?.isFinal)+ targetColumn = await tx.query.columnTable.findFirst({+ where: and(+ eq(columnTable.projectId, projectId),+ eq(columnTable.isFinal, true),+ ),+ orderBy: (column, { asc }) => [asc(column.position)],+ });const nextTaskNumber = await claimTaskNumber(projectId, tx);const [task] = await tx.insert(taskTable)@@ -128,7 +138,7 @@ export async function handleGiteaIssueOpened(userId: null,title: issue.title,description: formatTaskDescriptionFromIssue(issue.body),- status: resolvedStatus,+ status: closed ? (targetColumn?.slug ?? "done") : resolvedStatus,columnId: targetColumn?.id ?? null,priority: priority ?? "low",number: nextTaskNumber,@@ -136,7 +146,7 @@ export async function handleGiteaIssueOpened(.returning();if (!task) throw new Error("Failed to create task from gitea issue");const linkMetadata = {- state: "open",+ state: closed ? "closed" : "open",createdFrom: "gitea",author: issue.user?.login ?? issue.user?.username,};diff --git a/apps/api/src/plugins/github/webhooks/issue-opened.ts b/apps/api/src/plugins/github/webhooks/issue-opened.tsindex 40bdbbec2..81fd1bc92 100644--- a/apps/api/src/plugins/github/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-opened.ts@@ -27,6 +27,7 @@ type IssueOpenedPayload = {issue: {number: number;title: string;+ state?: string;body: string | null;html_url: string;labels?: Array<string | { name?: string }>;@@ -72,6 +73,7 @@ export async function handleIssueOpened(if (!acceptsIssue(integration.config, issue.labels)) continue;const config = JSON.parse(integration.config) as GitHubConfig;const projectId = integration.projectId;+ const closed = issue.state === "closed";const priority = extractIssuePriority(issue.labels);const status = extractIssueStatus(issue.labels);@@ -95,16 +97,24 @@ export async function handleIssueOpened(if (existingLink) return null;const targetStatus = await resolveTargetStatus(projectId,- "issue_opened",- status || "to-do",+ closed ? "issue_closed" : "issue_opened",+ closed ? "done" : status || "to-do",tx,);- const targetColumn = await tx.query.columnTable.findFirst({+ let targetColumn = await tx.query.columnTable.findFirst({where: and(eq(columnTable.projectId, projectId),eq(columnTable.slug, targetStatus),),});+ if (closed && !targetColumn?.isFinal)+ targetColumn = await tx.query.columnTable.findFirst({+ where: and(+ eq(columnTable.projectId, projectId),+ eq(columnTable.isFinal, true),+ ),+ orderBy: (column, { asc }) => [asc(column.position)],+ });const number = await claimTaskNumber(projectId, tx);const [task] = await tx.insert(taskTable)@@ -113,7 +123,7 @@ export async function handleIssueOpened(userId: null,title: issue.title,description: formatTaskDescriptionFromIssue(issue.body),- status: targetStatus,+ status: closed ? (targetColumn?.slug ?? "done") : targetStatus,columnId: targetColumn?.id ?? null,priority: priority ?? "low",number,@@ -129,7 +139,7 @@ export async function handleIssueOpened(url: issue.html_url,title: issue.title,metadata: {- state: "open",+ state: closed ? "closed" : "open",createdFrom: "github",author: issue.user?.login,},diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts b/apps/api/src/plugins/gitlab/webhooks/issue-opened.tsindex 6a67d1253..a07ae36d3 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-opened.ts@@ -39,6 +39,7 @@ type IssueOpenedPayload = {object_attributes: {iid: number;title: string;+ state?: string;description: string | null;url: string;action?: string;@@ -94,6 +95,7 @@ export async function handleGitlabIssueOpened(continue;}const projectId = integration.projectId;+ const closed = issue.state === "closed";const priority = extractIssuePriority(existingLabels);const status = extractIssueStatus(existingLabels);@@ -116,16 +118,24 @@ export async function handleGitlabIssueOpened(return null;const resolvedStatus = await resolveTargetStatus(projectId,- "issue_opened",- status || "to-do",+ closed ? "issue_closed" : "issue_opened",+ closed ? "done" : status || "to-do",tx,);- const targetColumn = await tx.query.columnTable.findFirst({+ let targetColumn = await tx.query.columnTable.findFirst({where: and(eq(columnTable.projectId, projectId),eq(columnTable.slug, resolvedStatus),),});+ if (closed && !targetColumn?.isFinal)+ targetColumn = await tx.query.columnTable.findFirst({+ where: and(+ eq(columnTable.projectId, projectId),+ eq(columnTable.isFinal, true),+ ),+ orderBy: (column, { asc }) => [asc(column.position)],+ });const nextTaskNumber = await claimTaskNumber(projectId, tx);const [task] = await tx.insert(taskTable)@@ -134,7 +144,7 @@ export async function handleGitlabIssueOpened(userId: null,title: issue.title,description: taskDescriptionFromIssue(issue.description),- status: resolvedStatus,+ status: closed ? (targetColumn?.slug ?? "done") : resolvedStatus,columnId: targetColumn?.id ?? null,priority: priority ?? "low",number: nextTaskNumber,@@ -142,7 +152,7 @@ export async function handleGitlabIssueOpened(.returning();if (!task) throw new Error("Failed to create task from gitlab issue");const linkMetadata = {- state: "opened",+ state: closed ? "closed" : "opened",createdFrom: "gitlab",author: author,};diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.tsindex d2feb6252..88c0bf9f7 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts@@ -37,6 +37,7 @@ type IssueUpdatedPayload = {object_attributes: {iid: number;title: string;+ state?: string;description: string | null;url: string;action?: string;@@ -166,9 +167,12 @@ export async function handleGitlabIssueUpdated(if (touchedLabels &&readSyncRules(integration.config)?.incoming.mode === "labels" &&- acceptsIssue(integration.config, payload.labels)+ acceptsIssue(integration.config, currentLabels)) {- await handleGitlabIssueOpened(payload, integration.id);+ await handleGitlabIssueOpened(+ { ...payload, labels: currentLabels },+ integration.id,+ );}continue;}diff --git a/apps/api/src/plugins/registry.ts b/apps/api/src/plugins/registry.tsindex b725fb5c1..1a139f529 100644--- a/apps/api/src/plugins/registry.ts+++ b/apps/api/src/plugins/registry.ts@@ -251,10 +251,10 @@ export function initializeEventSubscriptions(): void {},);- subscribeToEvent<{ projectId: string }>(+ subscribeToEvent<{ projectId: string; integrationId?: string }>("integration.sync_labels_changed",async (data) => {- await reconcileProjectSync(data.projectId);+ await reconcileProjectSync(data.projectId, data.integrationId);},);diff --git a/apps/api/src/plugins/sync/create-task-issue.ts b/apps/api/src/plugins/sync/create-task-issue.tsindex e4b561034..129f24276 100644--- a/apps/api/src/plugins/sync/create-task-issue.ts+++ b/apps/api/src/plugins/sync/create-task-issue.ts@@ -1,71 +1,61 @@-import { and, eq, sql } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import db from "../../database";import { externalLinkTable, taskTable } from "../../database/schema";import type { PluginContext, TaskCreatedEvent } from "../types";import { canSyncTask } from "./eligibility";--// Keep one lease per API process so provider callbacks can use the pool without-// exhausting it. PostgreSQL also serializes the same task across API instances.-let creationQueue: Promise<void> = Promise.resolve();+import { withSyncLease } from "./lease";export async function withTaskSyncCreation(event: TaskCreatedEvent,context: PluginContext,create: (current: TaskCreatedEvent) => Promise<void>,) {- const next = creationQueue.then(() =>- createWithLease(event, context, create),+ await withSyncLease(+ `sync-create:${context.integrationId}:${event.taskId}`,+ () => createWithLease(event, context, create),);- creationQueue = next.catch(() => {});- await next;}async function createWithLease(event: TaskCreatedEvent,context: PluginContext,create: (current: TaskCreatedEvent) => Promise<void>,) {- await db.transaction(async (tx) => {- const result = await tx.execute<{ locked: boolean }>(- sql`select pg_try_advisory_xact_lock(hashtextextended(${`sync-create:${context.integrationId}:${event.taskId}`}, 0)) as locked`,- );- if (!result.rows[0]?.locked) return;- if (- !(await canSyncTask(- event.taskId,- context.integrationId,- undefined,- JSON.stringify(context.config),- ))- )- return;- if (- await db.query.externalLinkTable.findFirst({- where: and(- eq(externalLinkTable.taskId, event.taskId),- eq(externalLinkTable.integrationId, context.integrationId),- eq(externalLinkTable.resourceType, "issue"),- ),- columns: { id: true },- })- )- return;- const task = await db.query.taskTable.findFirst({+ if (+ !(await canSyncTask(+ event.taskId,+ context.integrationId,+ undefined,+ JSON.stringify(context.config),+ ))+ )+ return;+ if (+ await db.query.externalLinkTable.findFirst({where: and(- eq(taskTable.id, event.taskId),- eq(taskTable.projectId, context.projectId),+ eq(externalLinkTable.taskId, event.taskId),+ eq(externalLinkTable.integrationId, context.integrationId),+ eq(externalLinkTable.resourceType, "issue"),),- });- if (!task || task.number === null) return;- await create({- taskId: task.id,- projectId: task.projectId,- userId: task.userId ?? "",- title: task.title,- description: task.description,- priority: task.priority,- status: task.status,- number: task.number,- });- await canSyncTask(task.id, context.integrationId);+ columns: { id: true },+ })+ )+ return;+ const task = await db.query.taskTable.findFirst({+ where: and(+ eq(taskTable.id, event.taskId),+ eq(taskTable.projectId, context.projectId),+ ),+ });+ if (!task || task.number === null) return;+ await create({+ taskId: task.id,+ projectId: task.projectId,+ userId: task.userId ?? "",+ title: task.title,+ description: task.description,+ priority: task.priority,+ status: task.status,+ number: task.number,});+ await canSyncTask(task.id, context.integrationId);}diff --git a/apps/api/src/plugins/sync/integrations.ts b/apps/api/src/plugins/sync/integrations.tsnew file mode 100644index 000000000..62e94c0af--- /dev/null+++ b/apps/api/src/plugins/sync/integrations.ts@@ -0,0 +1,29 @@+import { and, eq, inArray } from "drizzle-orm";+import db from "../../database";+import { integrationTable } from "../../database/schema";+import { readSyncRules, syncProviders } from "./rules";++export async function getSyncIntegrations(+ projectId: string,+ integrationId?: string,+) {+ const rows = await db.query.integrationTable.findMany({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.isActive, true),+ inArray(integrationTable.type, [...syncProviders]),+ integrationId ? eq(integrationTable.id, integrationId) : undefined,+ ),+ });+ return rows.flatMap((integration) => {+ try {+ const config = JSON.parse(integration.config) as Record<string, unknown>;+ // Legacy integrations retain their existing task-created behavior.+ return config.syncRules && readSyncRules(config)+ ? [{ ...integration, parsedConfig: config }]+ : [];+ } catch {+ return [];+ }+ });+}diff --git a/apps/api/src/plugins/sync/lease.ts b/apps/api/src/plugins/sync/lease.tsnew file mode 100644index 000000000..4b0ab90ec--- /dev/null+++ b/apps/api/src/plugins/sync/lease.ts@@ -0,0 +1,62 @@+import type { PoolClient } from "pg";+import { getDatabasePool } from "../../database";++const queues = new Map<string, Promise<unknown>>();+const waiting: Array<() => void> = [];+let active = 0;+const MAX_CONCURRENT_SYNC = 2;++// Reserve only two pool connections for session locks. Provider callbacks and+// ordinary requests can still use the rest of the pool during network calls.+export function withSyncLease<T>(+ key: string,+ run: () => Promise<T>,+): Promise<T> {+ const previous = queues.get(key) ?? Promise.resolve();+ const next = previous+ .catch(() => {})+ .then(async () => {+ if (active >= MAX_CONCURRENT_SYNC)+ await new Promise<void>((resolve) => waiting.push(resolve));+ else active++;+ let client: PoolClient | undefined;+ let locked = false;+ let releaseError: Error | undefined;+ try {+ client = await getDatabasePool().connect();+ // Wait for competing instances, then recheck the link in run(). A failed+ // first attempt must not consume a competing task's creation attempt.+ await client.query("select pg_advisory_lock(hashtextextended($1, 0))", [+ key,+ ]);+ locked = true;+ return await run();+ } finally {+ if (client) {+ try {+ if (locked)+ await client.query(+ "select pg_advisory_unlock(hashtextextended($1, 0))",+ [key],+ );+ } catch (error) {+ releaseError =+ error instanceof Error+ ? error+ : new Error("Sync lock release failed");+ }+ client.release(releaseError);+ }+ const resume = waiting.shift();+ if (resume) resume();+ else active--;+ }+ });+ queues.set(key, next);+ void next+ .finally(() => {+ if (queues.get(key) === next) queues.delete(key);+ })+ .catch(() => {});+ return next;+}diff --git a/apps/api/src/plugins/sync/pause-issue-links.ts b/apps/api/src/plugins/sync/pause-issue-links.tsnew file mode 100644index 000000000..cb85c4f5c--- /dev/null+++ b/apps/api/src/plugins/sync/pause-issue-links.ts@@ -0,0 +1,55 @@+import { and, asc, eq, gt, sql, type SQL } from "drizzle-orm";+import { externalLinkTable, taskTable } from "../../database/schema";+import type { IntegrationDatabase } from "../github/services/integration-task-scope";+import { parseLinkMetadata } from "../github/utils/parse-link-metadata";++export async function pauseIssueLinks(+ projectId: string,+ integrationId: string,+ excluded: SQL,+ tx: IntegrationDatabase,+) {+ let cursor: string | undefined;+ for (;;) {+ const links = await tx+ .select({+ id: externalLinkTable.id,+ metadata: externalLinkTable.metadata,+ })+ .from(externalLinkTable)+ .innerJoin(taskTable, eq(taskTable.id, externalLinkTable.taskId))+ .where(+ and(+ eq(externalLinkTable.integrationId, integrationId),+ eq(externalLinkTable.resourceType, "issue"),+ eq(taskTable.projectId, projectId),+ excluded,+ cursor ? gt(externalLinkTable.id, cursor) : undefined,+ sql`not coalesce(${externalLinkTable.metadata} ~ '"syncFilterPaused"[[:space:]]*:[[:space:]]*true', false)`,+ ),+ )+ .orderBy(asc(externalLinkTable.id))+ .limit(100)+ .for("update", { of: externalLinkTable });+ if (!links.length) return;+ const values = sql.join(+ links.map(+ (link) =>+ sql`(${link.id}::text, ${JSON.stringify({+ ...parseLinkMetadata(link.metadata, {+ externalLinkId: link.id,+ source: "sync_pause",+ }),+ syncFilterPaused: true,+ })}::text)`,+ ),+ sql`, `,+ );+ // Locked rows retain concurrent sync metadata. One update per bounded page+ // replaces a metadata transaction and round trip for every issue link.+ await tx.execute(+ sql`update ${externalLinkTable} set metadata = paused.metadata, updated_at = ${new Date()} from (values ${values}) as paused(id, metadata) where ${externalLinkTable.id} = paused.id`,+ );+ cursor = links.at(-1)!.id;+ }+}diff --git a/apps/api/src/plugins/sync/reconcile.ts b/apps/api/src/plugins/sync/reconcile.tsindex 9a2977387..09d0099b7 100644--- a/apps/api/src/plugins/sync/reconcile.ts+++ b/apps/api/src/plugins/sync/reconcile.ts@@ -1,30 +1,38 @@-import { and, asc, eq, gt, inArray } from "drizzle-orm";+import { and, asc, eq, gt } from "drizzle-orm";import db from "../../database";-import { integrationTable, taskTable } from "../../database/schema";+import { externalLinkTable, taskTable } from "../../database/schema";import { publishEvent } from "../../events";import { getPlugin } from "../registry";import { canSyncTask } from "./eligibility";-import { readSyncRules, syncProviders } from "./rules";+import { getSyncIntegrations } from "./integrations";export async function reconcileTaskSync(projectId: string,taskId: string,onlyIntegrationId?: string,) {- const integrations = await db.query.integrationTable.findMany({- where: and(- eq(integrationTable.projectId, projectId),- eq(integrationTable.isActive, true),- inArray(integrationTable.type, [...syncProviders]),- onlyIntegrationId- ? eq(integrationTable.id, onlyIntegrationId)- : undefined,- ),- });+ const integrations = await getSyncIntegrations(projectId, onlyIntegrationId);+ await reconcileTaskWithIntegrations(projectId, taskId, integrations);+}++async function reconcileTaskWithIntegrations(+ projectId: string,+ taskId: string,+ integrations: Awaited<ReturnType<typeof getSyncIntegrations>>,+) {+ if (!integrations.length) return;+ const links = () =>+ db.query.externalLinkTable.findMany({+ where: and(+ eq(externalLinkTable.taskId, taskId),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ columns: { id: true, metadata: true },+ orderBy: (link, { asc }) => [asc(link.id)],+ });+ const before = await links();for (const integration of integrations) {- // Legacy integrations retain their existing task-created behavior.- const config = JSON.parse(integration.config) as Record<string, unknown>;- if (!config.syncRules || !readSyncRules(config)) continue;+ const config = integration.parsedConfig;if (!(await canSyncTask(taskId,@@ -54,13 +62,16 @@ export async function reconcileTaskSync({ integrationId: integration.id, projectId, config },);}- await publishEvent("task.updated", { projectId, taskId });+ if (JSON.stringify(before) !== JSON.stringify(await links()))+ await publishEvent("task.updated", { projectId, taskId });}export async function reconcileProjectSync(projectId: string,integrationId?: string,) {+ const integrations = await getSyncIntegrations(projectId, integrationId);+ if (!integrations.length) return;let cursor: string | undefined;for (;;) {const tasks = await db@@ -76,7 +87,7 @@ export async function reconcileProjectSync(.limit(50);if (!tasks.length) return;for (const task of tasks)- await reconcileTaskSync(projectId, task.id, integrationId);+ await reconcileTaskWithIntegrations(projectId, task.id, integrations);cursor = tasks.at(-1)?.id;}}diff --git a/apps/api/src/plugins/sync/task-predicate.ts b/apps/api/src/plugins/sync/task-predicate.tsindex 4db79de8e..72b9dcee9 100644--- a/apps/api/src/plugins/sync/task-predicate.ts+++ b/apps/api/src/plugins/sync/task-predicate.ts@@ -1,4 +1,4 @@-import { and, eq, isNull, sql } from "drizzle-orm";+import { and, asc, eq, isNull, sql } from "drizzle-orm";import db from "../../database";import { labelTable, taskTable } from "../../database/schema";import type { IntegrationDatabase } from "../github/services/integration-task-scope";@@ -22,7 +22,8 @@ export async function outgoingPredicate(isNull(labelTable.taskId),isNull(labelTable.deletionStartedAt),),- );+ )+ .orderBy(asc(labelTable.id));if (rule.mode === "all")return { predicate: sql<boolean>`true`, labels, missing: [] as string[] };const selected = labels.filter((label) => rule.labels.includes(label.id));diff --git a/apps/api/src/plugins/sync/workspace-label-changed.ts b/apps/api/src/plugins/sync/workspace-label-changed.tsnew file mode 100644index 000000000..6efa4aa89--- /dev/null+++ b/apps/api/src/plugins/sync/workspace-label-changed.ts@@ -0,0 +1,34 @@+import { and, eq, inArray } from "drizzle-orm";+import db from "../../database";+import { integrationTable, projectTable } from "../../database/schema";+import { publishEvent } from "../../events";+import { readSyncRules, syncProviders } from "./rules";++export async function notifySyncWorkspaceLabelChanged(+ workspaceId: string,+ labelId: string,+) {+ const integrations = await db+ .select({+ id: integrationTable.id,+ projectId: integrationTable.projectId,+ config: integrationTable.config,+ })+ .from(integrationTable)+ .innerJoin(projectTable, eq(projectTable.id, integrationTable.projectId))+ .where(+ and(+ eq(projectTable.workspaceId, workspaceId),+ eq(integrationTable.isActive, true),+ inArray(integrationTable.type, [...syncProviders]),+ ),+ );+ for (const integration of integrations) {+ const rule = readSyncRules(integration.config)?.outgoing;+ if (rule?.mode === "labels" && rule.labels.includes(labelId))+ await publishEvent("integration.sync_labels_changed", {+ projectId: integration.projectId,+ integrationId: integration.id,+ });+ }+}diff --git a/apps/web/src/components/project/integrations/integration-row.tsx b/apps/web/src/components/project/integrations/integration-row.tsxindex f36a49fbf..5bf233e78 100644--- a/apps/web/src/components/project/integrations/integration-row.tsx+++ b/apps/web/src/components/project/integrations/integration-row.tsx@@ -96,6 +96,7 @@ export function IntegrationRow({integration.id === "gitlab") && (<div className="mt-4"><SyncRulesSection+ key={`${projectId}:${integration.id}`}projectId={projectId}provider={integration.id}/>diff --git a/tests/api-integration/integration-sync-providers.test.ts b/tests/api-integration/integration-sync-providers.test.tsindex 4d3fbd8c5..56a0c8c68 100644--- a/tests/api-integration/integration-sync-providers.test.ts+++ b/tests/api-integration/integration-sync-providers.test.ts@@ -1,4 +1,4 @@-import { eq } from "drizzle-orm";+import { eq, sql } from "drizzle-orm";import {beforeAll,beforeEach,@@ -7,8 +7,12 @@ import {it,vi,} from "vite-plus/test";-import db, { schema } from "../../apps/api/src/database";+import * as events from "../../apps/api/src/events";+import db, { getDatabasePool, schema } from "../../apps/api/src/database";import { giteaPlugin } from "../../apps/api/src/plugins/gitea";+import { handleGiteaIssueLabeled } from "../../apps/api/src/plugins/gitea/webhooks/issue-labeled";+import { handleIssueLabeled } from "../../apps/api/src/plugins/github/webhooks/issue-labeled";+import { handleGitlabIssueUpdated } from "../../apps/api/src/plugins/gitlab/webhooks/issue-updated";import { handleGiteaIssueOpened } from "../../apps/api/src/plugins/gitea/webhooks/issue-opened";import { githubPlugin } from "../../apps/api/src/plugins/github";import { handleIssueOpened } from "../../apps/api/src/plugins/github/webhooks/issue-opened";@@ -244,6 +248,83 @@ describe.each(["github", "gitea", "gitlab"] as const)(expect(JSON.parse(link!.metadata!)).toMatchObject({ state: "closed" });});+ it("imports a closed issue gaining a label into a completed column", async () => {+ const f = await setup(type);+ if (type === "github") {+ const payload = {+ action: "labeled",+ installation: { id: 2 },+ issue: {+ number: 99,+ title: "Closed issue",+ body: "Body",+ state: "closed",+ html_url: "https://github.com/team/repo/issues/99",+ labels: ["export"],+ user: { login: "author" },+ },+ repository: {+ id: 1,+ owner: { login: "team" },+ name: "repo",+ full_name: "team/repo",+ },+ };+ await handleIssueLabeled(payload);+ } else if (type === "gitea") {+ const payload = {+ action: "label_updated",+ issue: {+ number: 99,+ title: "Closed issue",+ body: "Body",+ state: "closed",+ html_url: "https://git.example/team/repo/issues/99",+ labels: ["export"],+ user: { login: "author" },+ },+ repository: {+ owner: { login: "team" },+ name: "repo",+ html_url: "https://git.example/team/repo",+ },+ };+ await handleGiteaIssueLabeled(payload, f.integration.id);+ } else {+ // GitLab can send the authoritative labels only inside the change.+ await handleGitlabIssueUpdated(+ {+ object_attributes: {+ iid: 99,+ title: "Closed issue",+ description: "Body",+ state: "closed",+ url: "https://gitlab.example/team/repo/-/issues/99",+ },+ changes: {+ labels: { previous: [], current: [{ title: "export" }] },+ },+ project: {+ name: "repo",+ path_with_namespace: "team/repo",+ web_url: "https://gitlab.example/team/repo",+ },+ },+ f.integration.id,+ );+ }+ const link = (await db.query.externalLinkTable.findMany())[0]!;+ expect(JSON.parse(link.metadata!)).toMatchObject({ state: "closed" });+ expect(+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, link.taskId),+ }),+ ).toMatchObject({+ columnId: f.columns.done.id,+ status: f.columns.done.slug,+ });+ });+it("admits only matching repository issues and deduplicates concurrent webhooks", async () => {const f = await setup(type);async function receive(labels: string[]) {@@ -356,3 +437,146 @@ it("exports a burst larger than the database pool without exhausting lease conneexpect(mocks.giteaCreate).toHaveBeenCalledTimes(20);expect(await db.query.externalLinkTable.findMany()).toHaveLength(20);});++it("lets an unrelated export proceed while another provider call is slow", async () => {+ const f = await setup("gitea");+ await f.assign();+ const [other] = await db+ .insert(schema.taskTable)+ .values({ projectId: f.project.id, number: 2, title: "Fast task" })+ .returning();+ await db.insert(schema.labelTable).values({+ taskId: other!.id,+ workspaceId: f.workspace.id,+ name: "export",+ color: "#123456",+ });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ mocks.giteaCreate.mockImplementationOnce(async () => {+ await gate;+ return {+ number: 12,+ html_url: "https://git.example/issues/12",+ title: "Slow issue",+ state: "open",+ };+ });+ mocks.giteaCreate.mockResolvedValueOnce({+ number: 13,+ html_url: "https://git.example/issues/13",+ title: "Fast issue",+ state: "open",+ });+ const slow = reconcileTaskSync(f.project.id, f.task.id);+ try {+ await vi.waitFor(() => expect(mocks.giteaCreate).toHaveBeenCalledTimes(1));+ await reconcileTaskSync(f.project.id, other!.id);+ expect(+ await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.taskId, other!.id),+ }),+ ).toBeTruthy();+ } finally {+ release();+ await slow;+ }+});++it("retries a competing creation after the first attempt fails", async () => {+ const f = await setup("gitea");+ await f.assign();+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ mocks.giteaCreate.mockImplementationOnce(async () => {+ await gate;+ throw new Error("Temporary provider failure");+ });+ const first = reconcileTaskSync(f.project.id, f.task.id);+ await vi.waitFor(() => expect(mocks.giteaCreate).toHaveBeenCalledTimes(1));+ const competing = reconcileTaskSync(f.project.id, f.task.id);+ release();+ await Promise.all([first, competing]);+ expect(mocks.giteaCreate).toHaveBeenCalledTimes(2);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(1);+});++it("runs task creation HTTP calls without an idle database transaction", async () => {+ const f = await setup("gitea");+ await f.assign();+ mocks.giteaCreate.mockImplementationOnce(async () => {+ const result = await db.execute<{ transactions: string }>(sql`+ select count(*)::text as transactions from pg_stat_activity+ where datname = current_database() and pid <> pg_backend_pid() and state = 'idle in transaction'+ `);+ expect(result.rows[0]!.transactions).toBe("0");+ return {+ number: 12,+ html_url: "https://git.example/issues/12",+ title: "Export task",+ state: "open",+ };+ });+ await reconcileTaskSync(f.project.id, f.task.id);+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(1);+});++it("waits for another instance's creation lease instead of dropping the export", async () => {+ const f = await setup("gitea");+ await f.assign();+ const key = `sync-create:${f.integration.id}:${f.task.id}`;+ const holder = await getDatabasePool().connect();+ await holder.query("select pg_advisory_lock(hashtextextended($1, 0))", [key]);+ const competing = reconcileTaskSync(f.project.id, f.task.id);+ try {+ await vi.waitFor(async () => {+ const result = await db.execute<{ waiting: number }>(sql`+ select count(*)::int as waiting from pg_stat_activity+ where datname = current_database() and wait_event = 'advisory'+ `);+ expect(result.rows[0]!.waiting).toBeGreaterThan(0);+ });+ expect(mocks.giteaCreate).not.toHaveBeenCalled();+ } finally {+ await holder.query("select pg_advisory_unlock(hashtextextended($1, 0))", [+ key,+ ]);+ holder.release();+ await competing;+ }+ expect(mocks.giteaCreate).toHaveBeenCalledOnce();+ expect(await db.query.externalLinkTable.findMany()).toHaveLength(1);+});++it("broadcasts only changed links and avoids task scans for unconfigured integrations", async () => {+ const f = await setup("gitea");+ const publish = vi.spyOn(events, "publishEvent");+ await reconcileProjectSync(f.project.id);+ expect(publish).not.toHaveBeenCalled();+ await f.assign();+ await reconcileTaskSync(f.project.id, f.task.id);+ expect(publish).toHaveBeenCalledOnce();+ publish.mockClear();+ await reconcileProjectSync(f.project.id);+ expect(publish).not.toHaveBeenCalled();+ const { syncRules: _, ...legacy } = f.config;+ await db+ .update(schema.integrationTable)+ .set({ config: JSON.stringify(legacy) })+ .where(eq(schema.integrationTable.id, f.integration.id));+ const query = vi.spyOn(getDatabasePool(), "query");+ await reconcileProjectSync(f.project.id);+ expect(+ query.mock.calls.every((call) => {+ const first = call[0] as unknown as string | { text: string };+ return !(typeof first === "string" ? first : first.text).includes(+ 'from "task"',+ );+ }),+ ).toBe(true);+ expect(publish).not.toHaveBeenCalled();+});diff --git a/tests/api-integration/integration-sync-rules.test.ts b/tests/api-integration/integration-sync-rules.test.tsindex 0b3b86913..87a13dfd7 100644--- a/tests/api-integration/integration-sync-rules.test.ts+++ b/tests/api-integration/integration-sync-rules.test.ts@@ -1,5 +1,6 @@-import { and, eq } from "drizzle-orm";+import { and, eq, sql } from "drizzle-orm";import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import * as events from "../../apps/api/src/events";import db, { schema } from "../../apps/api/src/database";import { createApp } from "../../apps/api/src/index";import { getSyncIntegration } from "../../apps/api/src/integration-sync/controllers/get-integration";@@ -7,6 +8,7 @@ import { previewSyncRules } from "../../apps/api/src/integration-sync/controllerimport { resumeSync } from "../../apps/api/src/integration-sync/controllers/resume-sync";import { reviewSyncResume } from "../../apps/api/src/integration-sync/controllers/review-resume";import { saveSyncRules } from "../../apps/api/src/integration-sync/controllers/save-rules";+import * as linkManager from "../../apps/api/src/plugins/github/services/link-manager";import { createExternalLink } from "../../apps/api/src/plugins/github/services/link-manager";import { withIntegrationTask } from "../../apps/api/src/plugins/github/services/integration-task-scope";import { withTaskSyncCreation } from "../../apps/api/src/plugins/sync/create-task-issue";@@ -408,6 +410,59 @@ describe("integration label policies", () => {});});+it("pages a large paused scope and preserves metadata across batched rule saves", async () => {+ const f = await setup();+ await f.link();+ const tasks = await db+ .insert(schema.taskTable)+ .values(+ Array.from({ length: 205 }, (_, index) => ({+ projectId: f.project.id,+ number: index + 2,+ title: `Task ${index}`,+ })),+ )+ .returning();+ await db.insert(schema.externalLinkTable).values(+ tasks.map((task) => ({+ taskId: task.id,+ integrationId: f.integration.id,+ resourceType: "issue",+ externalId: String(task.number),+ url: `https://git.example/issues/${task.number}`,+ metadata: JSON.stringify({+ retained: task.id,+ deferredIssueEdit: { id: "old-job" },+ }),+ })),+ );+ const preview = await f.preview();+ expect(preview).toMatchObject({ total: 206, willPause: 206, paused: 206 });+ expect(preview.pausedTasks).toHaveLength(25);+ expect(preview.pausedNextCursor).toBeTruthy();+ await saveSyncRules(f.project.id, "gitea", f.rules, preview.previewToken);+ const links = await db.query.externalLinkTable.findMany();+ expect(links.every((link) => isSyncPaused(link.metadata))).toBe(true);+ expect(+ links.filter(+ (link) => JSON.parse(link.metadata!).deferredIssueEdit?.id === "old-job",+ ),+ ).toHaveLength(205);+ const binding = await getSyncIntegration(f.project.id, "gitea");+ const first = await previewSyncRules(binding, f.rules);+ const second = await previewSyncRules(+ binding,+ f.rules,+ undefined,+ first.pausedNextCursor!,+ );+ expect(second.previewToken).toBe(first.previewToken);+ expect(second.pausedTasks).toHaveLength(25);+ expect(+ second.pausedTasks.every((task) => task.id > first.pausedNextCursor!),+ ).toBe(true);+});+describe("reviewed sync resume", () => {async function paused() {const f = await setup();@@ -416,8 +471,83 @@ describe("reviewed sync resume", () => {const link = await f.link(true);return { ...f, link };}+ it("rejects a stale local comparison before writing to the provider", async () => {+ const f = await paused();+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);+ await db+ .update(schema.taskTable)+ .set({ title: "Changed locally" })+ .where(eq(schema.taskTable.id, f.task.id));+ await expect(+ resumeSync(f.project.id, "gitea", f.link.id, review.token, "kaneo"),+ ).rejects.toMatchObject({ status: 409 });+ expect(provider.write).not.toHaveBeenCalled();+ });++ it("locks local values, integration, labels and link while writing to the provider", async () => {+ const f = await paused();+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ provider.write.mockImplementation(async () => {+ await gate;+ return { updatedAt: "2026-01-02T00:00:00Z" };+ });+ const resume = resumeSync(+ f.project.id,+ "gitea",+ f.link.id,+ review.token,+ "kaneo",+ );+ try {+ await vi.waitFor(() => expect(provider.write).toHaveBeenCalledOnce());+ const attempts = [+ (tx: typeof db) =>+ tx+ .update(schema.taskTable)+ .set({ title: "Concurrent edit" })+ .where(eq(schema.taskTable.id, f.task.id)),+ (tx: typeof db) =>+ tx+ .update(schema.integrationTable)+ .set({ isActive: false })+ .where(eq(schema.integrationTable.id, f.integration.id)),+ (tx: typeof db) =>+ tx+ .delete(schema.labelTable)+ .where(eq(schema.labelTable.taskId, f.task.id)),+ (tx: typeof db) =>+ tx+ .update(schema.externalLinkTable)+ .set({ metadata: "{}" })+ .where(eq(schema.externalLinkTable.id, f.link.id)),+ ];+ for (const apply of attempts)+ await expect(+ db.transaction(async (tx) => {+ await tx.execute(sql`set local lock_timeout = '100ms'`);+ await apply(tx as typeof db);+ }),+ ).rejects.toMatchObject({ cause: { code: "55P03" } });+ } finally {+ release();+ await resume;+ }+ expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);+ });+it("adopts repository values and completion state using the existing link", async () => {+ const publish = vi+ .spyOn(events, "publishEvent")+ .mockResolvedValue(undefined);const f = await paused();+ await db+ .update(schema.taskTable)+ .set({ userId: f.user.id })+ .where(eq(schema.taskTable.id, f.task.id));const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);expect(review.local.title).toBe("Kaneo title");await resumeSync(@@ -436,6 +566,17 @@ describe("reviewed sync resume", () => {columnId: f.columns.done.id,});expect(provider.write).not.toHaveBeenCalled();+ expect(publish).toHaveBeenCalledWith(+ "task.status_changed",+ expect.objectContaining({+ sourceIntegrationId: f.integration.id,+ assigneeId: f.user.id,+ taskId: f.task.id,+ oldStatus: f.columns.todo.slug,+ newStatus: f.columns.done.slug,+ title: "Repository title",+ }),+ );expect(await canSyncTask(f.task.id, f.integration.id)).toBe(true);expect(await db.query.externalLinkTable.findMany({@@ -468,6 +609,33 @@ describe("reviewed sync resume", () => {expect(provider.write).not.toHaveBeenCalled();expect(await canSyncTask(f.task.id, f.integration.id)).toBe(false);});+ it("records an uncertain resume and refreshes clients if local commit fails after the provider write", async () => {+ const f = await paused();+ const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);+ vi.spyOn(linkManager, "updateExternalLink").mockRejectedValueOnce(+ new Error("Local metadata commit failed"),+ );+ const publish = vi.spyOn(events, "publishEvent");+ await expect(+ resumeSync(f.project.id, "gitea", f.link.id, review.token, "kaneo"),+ ).rejects.toThrow("Local metadata commit failed");+ expect(provider.write).toHaveBeenCalledOnce();+ const link = await db.query.externalLinkTable.findFirst({+ where: eq(schema.externalLinkTable.id, f.link.id),+ });+ expect(JSON.parse(link!.metadata!)).toMatchObject({+ syncFilterPaused: true,+ syncResumeUncertain: true,+ });+ expect(publish).toHaveBeenCalledWith("project.updated", {+ projectId: f.project.id,+ });+ expect(publish).toHaveBeenCalledWith("task.updated", {+ projectId: f.project.id,+ taskId: f.task.id,+ });+ });+it("keeps the link paused when a provider request fails", async () => {const f = await paused();const review = await reviewSyncResume(f.project.id, "gitea", f.link.id);diff --git a/tests/api-integration/outbound-intent-correlation.test.ts b/tests/api-integration/outbound-intent-correlation.test.tsindex 8f531118d..eca2a0c0f 100644--- a/tests/api-integration/outbound-intent-correlation.test.ts+++ b/tests/api-integration/outbound-intent-correlation.test.ts@@ -164,16 +164,21 @@ it("stops correction when a disconnect races the post-response task read", asyncurl: "https://provider.example/1",}).returning();+ let responseReceived = false;const findTask = db.query.taskTable.findFirst.bind(db.query.taskTable);const read = vi.spyOn(db.query.taskTable, "findFirst").mockImplementation(async (options) => {- await db- .delete(schema.externalLinkTable)- .where(eq(schema.externalLinkTable.id, link.id));+ if (responseReceived)+ await db+ .delete(schema.externalLinkTable)+ .where(eq(schema.externalLinkTable.id, link.id));return findTask(options);});- const write = vi.fn(async () => "2026-09-30T00:00:01Z");+ const write = vi.fn(async () => {+ responseReceived = true;+ return "2026-09-30T00:00:01Z";+ });try {await syncLatestTaskValue(task.id, project.id, link, "title", "A", write);expect(write).toHaveBeenCalledTimes(1);