⚡ 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): enforce current task ownership
Tin85e07cf4bfbb
diff --git a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts b/apps/api/src/gitea-integration/controllers/import-gitea-issues.tsindex e055011a9..0e89e3ad1 100644--- a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts@@ -29,6 +29,12 @@ import {import { formatTaskDescriptionFromIssue } from "../../plugins/github/utils/format";import { claimTaskNumber } from "../../task/controllers/claim-task-numbers";+import {+ type IntegrationDatabase,+ linkedTaskScope,+ withIntegrationTask,+} from "../../plugins/github/services/integration-task-scope";+type ImportResult = {imported: number;updated: number;@@ -210,70 +216,94 @@ async function importSingleIssue(const status = extractIssueStatus(adaptedLabels);if (existingLink) {- const updateData: Record<string, unknown> = {- title: issue.title,- description: formatTaskDescriptionFromIssue(issue.body),- };-- if (priority) updateData.priority = priority;- if (status) updateData.status = status;-- await db- .update(taskTable)- .set(updateData)- .where(eq(taskTable.id, existingLink.taskId));-- await importLabelsForTask(labels, existingLink.taskId, workspaceId);-- await importCommentsForTask(- issue.number,+ const result = await withIntegrationTask(existingLink.taskId,- config,- client,+ { id: integrationId, projectId, project: { workspaceId } },+ async (database) => {+ const updateData: Record<string, unknown> = {+ title: issue.title,+ description: formatTaskDescriptionFromIssue(issue.body),+ };++ if (priority) updateData.priority = priority;+ if (status) updateData.status = status;++ await database+ .update(taskTable)+ .set(updateData)+ .where(linkedTaskScope(existingLink.taskId, projectId));++ await importLabelsForTask(+ labels,+ existingLink.taskId,+ workspaceId,+ database,+ );++ await importCommentsForTask(+ issue.number,+ existingLink.taskId,+ config,+ client,+ database,+ );++ return "updated" as const;+ },);-- return "updated";+ return result ?? "skipped";}- const createdTask = await db.transaction(async (tx) => {- const nextNumber = await claimTaskNumber(projectId, tx);+ const createdTask = await withIntegrationTask(+ null,+ { id: integrationId, projectId, project: { workspaceId } },+ async (tx) => {+ const nextNumber = await claimTaskNumber(projectId, tx);- const taskValues: typeof taskTable.$inferInsert = {- projectId,- userId: null,- title: issue.title,- description: formatTaskDescriptionFromIssue(issue.body),- status: status || "to-do",- priority: priority ?? "low",- number: nextNumber,- };+ const taskValues: typeof taskTable.$inferInsert = {+ projectId,+ userId: null,+ title: issue.title,+ description: formatTaskDescriptionFromIssue(issue.body),+ status: status || "to-do",+ priority: priority ?? "low",+ number: nextNumber,+ };- const [created] = await tx.insert(taskTable).values(taskValues).returning();+ const [created] = await tx+ .insert(taskTable)+ .values(taskValues)+ .returning();- if (!created) {- throw new Error("Failed to create task");- }+ if (!created) {+ throw new Error("Failed to create task");+ }- return created;- });+ await createExternalLink(+ {+ taskId: created.id,+ integrationId,+ resourceType: "issue",+ externalId: issue.number.toString(),+ url: issue.html_url,+ title: issue.title,+ metadata: {+ state: issue.state,+ createdFrom: "gitea-import",+ author: issue.user?.login ?? issue.user?.username,+ },+ },+ tx,+ );- await createExternalLink({- taskId: createdTask.id,- integrationId,- resourceType: "issue",- externalId: issue.number.toString(),- url: issue.html_url,- title: issue.title,- metadata: {- state: issue.state,- createdFrom: "gitea-import",- author: issue.user?.login ?? issue.user?.username,- },- });+ await importLabelsForTask(labels, created.id, workspaceId, tx);- await importLabelsForTask(labels, createdTask.id, workspaceId);+ await importCommentsForTask(issue.number, created.id, config, client, tx);- await importCommentsForTask(issue.number, createdTask.id, config, client);+ return created;+ },+ );+ if (!createdTask) return "skipped";await publishEvent("task.created", {...createdTask,@@ -293,6 +323,7 @@ async function importLabelsForTask(issueLabels: GiteaIssue["labels"],taskId: string,workspaceId: string,+ database: IntegrationDatabase = db,): Promise<void> {const nonSystemLabels = (issueLabels ?? []).map((label) => {@@ -316,7 +347,7 @@ async function importLabelsForTask(const expectedNames = nonSystemLabels.map((label) => label.name);if (expectedNames.length > 0) {- await db+ await database.delete(labelTable).where(and(@@ -325,10 +356,10 @@ async function importLabelsForTask(),);} else {- await db.delete(labelTable).where(eq(labelTable.taskId, taskId));+ await database.delete(labelTable).where(eq(labelTable.taskId, taskId));}- const existingLabelsOnTask = await db.query.labelTable.findMany({+ const existingLabelsOnTask = await database.query.labelTable.findMany({where:expectedNames.length > 0? and(@@ -347,7 +378,7 @@ async function importLabelsForTask(continue;}- const existingWorkspaceLabel = await db.query.labelTable.findFirst({+ const existingWorkspaceLabel = await database.query.labelTable.findFirst({where: and(eq(labelTable.workspaceId, workspaceId),eq(labelTable.name, labelData.name),@@ -356,7 +387,7 @@ async function importLabelsForTask(const colorToUse = existingWorkspaceLabel?.color || labelData.color;- await db+ await database.insert(labelTable).values({name: labelData.name,@@ -375,6 +406,7 @@ async function importCommentsForTask(taskId: string,config: GiteaConfig,client: ReturnType<typeof createGiteaClient>,+ database: IntegrationDatabase = db,): Promise<void> {const allComments: Array<{id: number;@@ -407,7 +439,7 @@ async function importCommentsForTask(continue;}- await db+ await database.insert(activityTable).values({taskId,diff --git a/apps/api/src/github-integration/controllers/import-issues.ts b/apps/api/src/github-integration/controllers/import-issues.tsindex aefebadf6..70328deb1 100644--- a/apps/api/src/github-integration/controllers/import-issues.ts+++ b/apps/api/src/github-integration/controllers/import-issues.ts@@ -173,6 +173,17 @@ export async function importIssues(projectId: string, runId?: string) {}const currentRun: typeof githubImportTable.$inferSelect = run;run = await db.transaction(async (tx) => {+ const [currentProject] = await tx+ .select()+ .from(projectTable)+ .where(+ and(+ eq(projectTable.id, project.id),+ eq(projectTable.workspaceId, project.workspaceId),+ ),+ )+ .for("key share");+ if (!currentProject) throw conflict();// Serialize against integration changes and webhook issue creation. No// provider request is made while this transaction holds row locks.const [currentIntegration] = await tx@@ -305,12 +316,16 @@ async function applyPage(}const current = state.currentIssue;if (!current) throw new Error("Import continuation missing");- const task = await tx.query.taskTable.findFirst({- where: and(- eq(taskTable.id, current.taskId),- eq(taskTable.projectId, project.id),- ),- });+ const [task] = await tx+ .select()+ .from(taskTable)+ .where(+ and(+ eq(taskTable.id, current.taskId),+ eq(taskTable.projectId, project.id),+ ),+ )+ .for("no key update");if (!task) {state.skipped++;finishIssue(state);@@ -540,6 +555,12 @@ async function linkPull(database: tx,});if (!task) return;+ const [scopedTask] = await tx+ .select({ id: taskTable.id })+ .from(taskTable)+ .where(and(eq(taskTable.id, task.id), eq(taskTable.projectId, project.id)))+ .for("share");+ if (!scopedTask) return;await tx.insert(externalLinkTable).values({taskId: task.id,integrationId,diff --git a/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts b/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.tsindex afcef8dfb..bc90b9e33 100644--- a/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts+++ b/apps/api/src/gitlab-integration/controllers/import-gitlab-issues.ts@@ -39,6 +39,12 @@ type ImportResult = {type GitlabClient = ReturnType<typeof createGitlabClient>;const PER_PAGE = 100;+import {+ type IntegrationDatabase,+ linkedTaskScope,+ withIntegrationTask,+} from "../../plugins/github/services/integration-task-scope";+const MAX_PAGES = 50;export async function importGitlabIssues(@@ -187,63 +193,92 @@ async function importSingleIssue(const status = extractIssueStatus(labels);if (existingLink) {- const updateData: Record<string, unknown> = {- title: issue.title,- description: taskDescriptionFromIssue(issue.description),- };-- if (priority) updateData.priority = priority;- if (status) updateData.status = status;-- await db- .update(taskTable)- .set(updateData)- .where(eq(taskTable.id, existingLink.taskId));-- await importLabelsForTask(labels, existingLink.taskId, workspaceId);- await importNotesForTask(issue, existingLink.taskId, config, client);-- return "updated";+ const result = await withIntegrationTask(+ existingLink.taskId,+ { id: integrationId, projectId, project: { workspaceId } },+ async (database) => {+ const updateData: Record<string, unknown> = {+ title: issue.title,+ description: taskDescriptionFromIssue(issue.description),+ };++ if (priority) updateData.priority = priority;+ if (status) updateData.status = status;++ await database+ .update(taskTable)+ .set(updateData)+ .where(linkedTaskScope(existingLink.taskId, projectId));++ await importLabelsForTask(+ labels,+ existingLink.taskId,+ workspaceId,+ database,+ );+ await importNotesForTask(+ issue,+ existingLink.taskId,+ config,+ client,+ database,+ );++ return "updated" as const;+ },+ );+ return result ?? "skipped";}- const createdTask = await db.transaction(async (tx) => {- const number = await claimTaskNumber(projectId, tx);-- const taskValues: typeof taskTable.$inferInsert = {- projectId,- userId: null,- title: issue.title,- description: taskDescriptionFromIssue(issue.description),- status: status || "to-do",- priority: priority ?? "low",- number,- };+ const createdTask = await withIntegrationTask(+ null,+ { id: integrationId, projectId, project: { workspaceId } },+ async (tx) => {+ const number = await claimTaskNumber(projectId, tx);- const [created] = await tx.insert(taskTable).values(taskValues).returning();+ const taskValues: typeof taskTable.$inferInsert = {+ projectId,+ userId: null,+ title: issue.title,+ description: taskDescriptionFromIssue(issue.description),+ status: status || "to-do",+ priority: priority ?? "low",+ number,+ };++ const [created] = await tx+ .insert(taskTable)+ .values(taskValues)+ .returning();++ if (!created) {+ throw new Error("Failed to create task");+ }- if (!created) {- throw new Error("Failed to create task");- }+ await createExternalLink(+ {+ taskId: created.id,+ integrationId,+ resourceType: "issue",+ externalId: issue.iid.toString(),+ url: issue.web_url,+ title: issue.title,+ metadata: {+ state: issue.state,+ createdFrom: "gitlab-import",+ author: issue.author?.username ?? issue.author?.name,+ },+ },+ tx,+ );- return created;- });+ await importLabelsForTask(labels, created.id, workspaceId, tx);+ await importNotesForTask(issue, created.id, config, client, tx);- await createExternalLink({- taskId: createdTask.id,- integrationId,- resourceType: "issue",- externalId: issue.iid.toString(),- url: issue.web_url,- title: issue.title,- metadata: {- state: issue.state,- createdFrom: "gitlab-import",- author: issue.author?.username ?? issue.author?.name,+ return created;},- });-- await importLabelsForTask(labels, createdTask.id, workspaceId);- await importNotesForTask(issue, createdTask.id, config, client);+ );+ if (!createdTask) return "skipped";await publishEvent("task.created", {...createdTask,@@ -263,6 +298,7 @@ async function importLabelsForTask(issueLabels: string[],taskId: string,workspaceId: string,+ database: IntegrationDatabase = db,): Promise<void> {const names = issueLabels.filter((name) => name && !isSystemLabelName(name));@@ -271,7 +307,7 @@ async function importLabelsForTask(return;}- const existingLabelsOnTask = await db.query.labelTable.findMany({+ const existingLabelsOnTask = await database.query.labelTable.findMany({where: and(eq(labelTable.taskId, taskId), inArray(labelTable.name, names)),});@@ -280,14 +316,14 @@ async function importLabelsForTask(continue;}- const existingWorkspaceLabel = await db.query.labelTable.findFirst({+ const existingWorkspaceLabel = await database.query.labelTable.findFirst({where: and(eq(labelTable.workspaceId, workspaceId),eq(labelTable.name, name),),});- await db+ await database.insert(labelTable).values({name,@@ -306,6 +342,7 @@ async function importNotesForTask(taskId: string,config: GitlabConfig,client: GitlabClient,+ database: IntegrationDatabase = db,): Promise<void> {for (let page = 1; page <= MAX_PAGES; page++) {const notes = await client.listIssueNotes(@@ -325,7 +362,7 @@ async function importNotesForTask(const username = note.author?.username ?? note.author?.name ?? "";- await db+ await database.insert(activityTable).values({taskId,diff --git a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts b/apps/api/src/plugins/gitea/webhooks/issue-closed.tsindex 1aa0e8a1b..e64a41a8c 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-closed.ts@@ -1,6 +1,10 @@+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../../github/services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";-import { externalLinkTable, taskTable } from "../../../database/schema";+import { externalLinkTable } from "../../../database/schema";import { publishEvent } from "../../../events";import { updateExternalLink } from "../../github/services/link-manager";import { updateTaskStatus } from "../../github/services/task-service";@@ -65,69 +69,87 @@ export async function handleGiteaIssueClosed(continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- });+ await withIntegrationTask(+ externalLink.taskId,+ integration,+ async (db, afterCommit) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- if (!task) {- continue;- }+ if (!task) {+ return;+ }- 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 Gitea issue metadata for close sync", {- externalLinkId: externalLink.id,- metadata: externalLink.metadata,- error,- });- }- }+ 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 Gitea issue metadata for close sync",+ {+ externalLinkId: externalLink.id,+ metadata: externalLink.metadata,+ error,+ },+ );+ }+ }- const lastOutbound = existingMetadata.lastOutboundStateSyncAt;- if (typeof lastOutbound === "number" && Number.isFinite(lastOutbound)) {- const eventMs = parseIssueUpdatedAtMs(issue);- if (- eventMs !== null &&- Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS- ) {- continue;- }- }+ const lastOutbound = existingMetadata.lastOutboundStateSyncAt;+ if (+ typeof lastOutbound === "number" &&+ Number.isFinite(lastOutbound)+ ) {+ const eventMs = parseIssueUpdatedAtMs(issue);+ if (+ eventMs !== null &&+ Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS+ ) {+ return;+ }+ }- const targetStatus = await resolveTargetStatus(- task.projectId,- "issue_closed",- "done",- );+ 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",- });- }+ const statusResult = await updateTaskStatus(task.id, targetStatus, db);+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ 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",+ await updateExternalLink(+ externalLink.id,+ {+ metadata: {+ ...existingMetadata,+ state: "closed",+ },+ },+ db,+ );},- });+ );}}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.tsindex b6fd060e5..634110e74 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-comment-created.ts@@ -1,4 +1,4 @@-import db from "../../../database";+import { withIntegrationTask } from "../../github/services/integration-task-scope";import { activityTable } from "../../../database/schema";import { findExternalLink } from "../../github/services/link-manager";import {@@ -68,26 +68,28 @@ export async function handleGiteaIssueCommentCreated(continue;}- await db- .insert(activityTable)- .values({- taskId: existingLink.taskId,- type: "comment",- content: comment.body,- externalUserName: username || "Unknown",- externalUserAvatar: comment.user?.avatar_url ?? null,- externalSource: "gitea",- externalUrl: comment.html_url,- eventData: {- externalCommentId: comment.id,- },- })- .onConflictDoNothing({- target: [- activityTable.taskId,- activityTable.externalSource,- activityTable.externalUrl,- ],- });+ await withIntegrationTask(existingLink.taskId, integration, async (db) => {+ await db+ .insert(activityTable)+ .values({+ taskId: existingLink.taskId,+ type: "comment",+ content: comment.body,+ externalUserName: username || "Unknown",+ externalUserAvatar: comment.user?.avatar_url ?? null,+ externalSource: "gitea",+ externalUrl: comment.html_url,+ eventData: {+ externalCommentId: comment.id,+ },+ })+ .onConflictDoNothing({+ target: [+ activityTable.taskId,+ activityTable.externalSource,+ activityTable.externalUrl,+ ],+ });+ });}}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts b/apps/api/src/plugins/gitea/webhooks/issue-edited.tsindex b609982eb..7709dade2 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-edited.ts@@ -1,5 +1,7 @@-import { eq } from "drizzle-orm";-import db from "../../../database";+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../../github/services/integration-task-scope";import { taskTable } from "../../../database/schema";import {findExternalLink,@@ -63,98 +65,102 @@ export async function handleGiteaIssueEdited(continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- });-- if (!task) {- continue;- }-- const metadata = externalLink.metadata- ? JSON.parse(externalLink.metadata)- : {};+ await withIntegrationTask(externalLink.taskId, integration, async (db) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- const updateData: Record<string, unknown> = {};- const updatedMetadata = { ...metadata };+ if (!task) {+ return;+ }- if (!updatedMetadata.lastSync) {- updatedMetadata.lastSync = {};- }+ const metadata = externalLink.metadata+ ? JSON.parse(externalLink.metadata)+ : {};- if (changes.title) {- const lastTitleSync = metadata.lastSync?.title;+ const updateData: Record<string, unknown> = {};+ const updatedMetadata = { ...metadata };- let shouldUpdateTitle = true;+ if (!updatedMetadata.lastSync) {+ updatedMetadata.lastSync = {};+ }- if (lastTitleSync) {- if (- lastTitleSync.value === issue.title &&- lastTitleSync.source === "kaneo"- ) {- shouldUpdateTitle = false;+ if (changes.title) {+ const lastTitleSync = metadata.lastSync?.title;++ let shouldUpdateTitle = true;++ if (lastTitleSync) {+ if (+ lastTitleSync.value === issue.title &&+ lastTitleSync.source === "kaneo"+ ) {+ shouldUpdateTitle = false;+ }+ const timeSinceLastSync =+ Date.now() - new Date(lastTitleSync.timestamp).getTime();+ if (timeSinceLastSync < 2000 && shouldUpdateTitle) {+ shouldUpdateTitle = false;+ }}- const timeSinceLastSync =- Date.now() - new Date(lastTitleSync.timestamp).getTime();- if (timeSinceLastSync < 2000 && shouldUpdateTitle) {- shouldUpdateTitle = false;+ if (shouldUpdateTitle) {+ updateData.title = issue.title;+ updatedMetadata.lastSync.title = {+ timestamp: new Date().toISOString(),+ source: "gitea",+ value: issue.title,+ };}}- if (shouldUpdateTitle) {- updateData.title = issue.title;- updatedMetadata.lastSync.title = {- timestamp: new Date().toISOString(),- source: "gitea",- value: issue.title,- };- }- }-- if (changes.body) {- const lastDescSync = metadata.lastSync?.description;- const formattedDescription = formatTaskDescriptionFromIssue(issue.body);-- let shouldUpdateDescription = true;-- if (lastDescSync) {- if (- lastDescSync.value === formattedDescription &&- lastDescSync.source === "kaneo"- ) {- shouldUpdateDescription = false;+ if (changes.body) {+ const lastDescSync = metadata.lastSync?.description;+ const formattedDescription = formatTaskDescriptionFromIssue(issue.body);++ let shouldUpdateDescription = true;++ if (lastDescSync) {+ if (+ lastDescSync.value === formattedDescription &&+ lastDescSync.source === "kaneo"+ ) {+ shouldUpdateDescription = false;+ }+ const timeSinceLastSync =+ Date.now() - new Date(lastDescSync.timestamp).getTime();+ if (timeSinceLastSync < 2000 && shouldUpdateDescription) {+ shouldUpdateDescription = false;+ }}- const timeSinceLastSync =- Date.now() - new Date(lastDescSync.timestamp).getTime();- if (timeSinceLastSync < 2000 && shouldUpdateDescription) {- shouldUpdateDescription = false;+ if (shouldUpdateDescription) {+ updateData.description = formattedDescription;+ updatedMetadata.lastSync.description = {+ timestamp: new Date().toISOString(),+ source: "gitea",+ value: formattedDescription,+ };}}- if (shouldUpdateDescription) {- updateData.description = formattedDescription;- updatedMetadata.lastSync.description = {- timestamp: new Date().toISOString(),- source: "gitea",- value: formattedDescription,- };+ if (Object.keys(updateData).length > 0) {+ await db+ .update(taskTable)+ .set(updateData)+ .where(linkedTaskScope(task.id, integration.projectId));++ await updateExternalLink(+ externalLink.id,+ {+ title: issue.title,+ metadata: updatedMetadata,+ },+ db,+ );}- }-- if (Object.keys(updateData).length > 0) {- await db- .update(taskTable)- .set(updateData)- .where(eq(taskTable.id, task.id));- await updateExternalLink(externalLink.id, {- title: issue.title,- metadata: updatedMetadata,- });- }-- return;+ return;+ });}}diff --git a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts b/apps/api/src/plugins/gitea/webhooks/issue-labeled.tsindex f0057cba4..8c7f7afa1 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-labeled.ts@@ -1,5 +1,9 @@+import {+ type IntegrationDatabase,+ linkedTaskScope,+ withIntegrationTask,+} from "../../github/services/integration-task-scope";import { eq, inArray } from "drizzle-orm";-import db from "../../../database";import { labelTable, taskTable } from "../../../database/schema";import { publishEvent } from "../../../events";import { findExternalLink } from "../../github/services/link-manager";@@ -56,6 +60,7 @@ async function syncGiteaLabelsToTask(taskId: string,workspaceId: string,giteaLabels: Array<{ name: string; color?: string }>,+ db: IntegrationDatabase,) {const desiredNames = new Set(giteaLabels.map((l) => l.name));const existingRows = await db.query.labelTable.findMany({@@ -141,117 +146,135 @@ export async function handleGiteaIssueLabeled(continue;}- const priority = extractIssuePriority(issue.labels);- const status = extractIssueStatus(issue.labels);-- if (priority) {- await db- .update(taskTable)- .set({ priority })- .where(eq(taskTable.id, existingLink.taskId));- }+ await withIntegrationTask(+ existingLink.taskId,+ integration,+ async (db, afterCommit) => {+ const priority = extractIssuePriority(issue.labels);+ const status = extractIssueStatus(issue.labels);- if (status) {- const statusResult = await updateTaskStatus(- existingLink.taskId,- 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 (priority) {+ await db+ .update(taskTable)+ .set({ priority })+ .where(+ linkedTaskScope(existingLink.taskId, integration.projectId),+ );+ }- if (payload.action === "label_updated") {- if (issue.labels === undefined) {- continue;- }+ if (status) {+ const statusResult = await updateTaskStatus(+ existingLink.taskId,+ status,+ db,+ );+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ 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",+ }),+ );+ }+ }- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, existingLink.taskId),- with: {- project: true,- },- });- if (task?.project?.workspaceId) {- await syncGiteaLabelsToTask(- existingLink.taskId,- task.project.workspaceId,- giteaLabelsForSync(issue.labels),- );- }- continue;- }+ if (payload.action === "label_updated") {+ if (issue.labels === undefined) {+ return;+ }- if (!addedLabel) {- continue;- }+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(+ existingLink.taskId,+ integration.projectId,+ ),+ with: {+ project: true,+ },+ });+ if (task?.project?.workspaceId) {+ await syncGiteaLabelsToTask(+ existingLink.taskId,+ task.project.workspaceId,+ giteaLabelsForSync(issue.labels),+ db,+ );+ }+ return;+ }- if (isSystemLabelName(addedLabel.name)) {- continue;- }+ if (!addedLabel) {+ return;+ }- if (payload.action === "labeled") {- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, existingLink.taskId),- with: {- project: true,- },- });+ if (isSystemLabelName(addedLabel.name)) {+ return;+ }- if (task?.project?.workspaceId) {- const existingLabel = await db.query.labelTable.findFirst({- where: (table, { and, eq: e }) =>- and(- e(table.workspaceId, task.project.workspaceId),- e(table.name, addedLabel.name),- e(table.taskId, task.id),+ if (payload.action === "labeled") {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(+ existingLink.taskId,+ integration.projectId,),- });+ with: {+ project: true,+ },+ });- if (!existingLabel) {- const color = addedLabel.color- ? `#${addedLabel.color.replace(/^#/, "")}`- : "#6B7280";- await db- .insert(labelTable)- .values({- name: addedLabel.name,- color,- taskId: task.id,- workspaceId: task.project.workspaceId,- })- .onConflictDoNothing({- target: [labelTable.taskId, labelTable.name],+ if (task?.project?.workspaceId) {+ const existingLabel = await db.query.labelTable.findFirst({+ where: (table, { and, eq: e }) =>+ and(+ e(table.workspaceId, task.project.workspaceId),+ e(table.name, addedLabel.name),+ e(table.taskId, task.id),+ ),});++ if (!existingLabel) {+ const color = addedLabel.color+ ? `#${addedLabel.color.replace(/^#/, "")}`+ : "#6B7280";+ await db+ .insert(labelTable)+ .values({+ name: addedLabel.name,+ color,+ taskId: task.id,+ workspaceId: task.project.workspaceId,+ })+ .onConflictDoNothing({+ target: [labelTable.taskId, labelTable.name],+ });+ }+ }}- }- }- if (payload.action === "unlabeled") {- const labelsToDelete = await db.query.labelTable.findMany({- where: (table, { and, eq: e }) =>- and(- e(table.taskId, existingLink.taskId),- e(table.name, addedLabel.name),- ),- });+ if (payload.action === "unlabeled") {+ const labelsToDelete = await db.query.labelTable.findMany({+ where: (table, { and, eq: e }) =>+ and(+ e(table.taskId, existingLink.taskId),+ e(table.name, addedLabel.name),+ ),+ });- for (const label of labelsToDelete) {- await db.delete(labelTable).where(eq(labelTable.id, label.id));- }- }+ for (const label of labelsToDelete) {+ await db.delete(labelTable).where(eq(labelTable.id, label.id));+ }+ }+ },+ );} catch (error) {console.error("Gitea issue_labeled handler failed for integration", {integrationId: integration.id,diff --git a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitea/webhooks/issue-reopened.tsindex 0e853b867..9ee96f25b 100644--- a/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/gitea/webhooks/issue-reopened.ts@@ -1,6 +1,10 @@+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../../github/services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";-import { externalLinkTable, taskTable } from "../../../database/schema";+import { externalLinkTable } from "../../../database/schema";import { publishEvent } from "../../../events";import { updateExternalLink } from "../../github/services/link-manager";import { updateTaskStatus } from "../../github/services/task-service";@@ -66,70 +70,92 @@ export async function handleGiteaIssueReopened(continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- });+ await withIntegrationTask(+ externalLink.taskId,+ integration,+ async (db, afterCommit) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- if (!task) {- continue;- }+ if (!task) {+ return;+ }- 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 Gitea issue metadata for reopen sync", {- externalLinkId: externalLink.id,- metadata: externalLink.metadata,- error,- });- }- }+ 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 Gitea issue metadata for reopen sync",+ {+ externalLinkId: externalLink.id,+ metadata: externalLink.metadata,+ error,+ },+ );+ }+ }- const lastOutbound = existingMetadata.lastOutboundStateSyncAt;- if (typeof lastOutbound === "number" && Number.isFinite(lastOutbound)) {- const eventMs = parseIssueUpdatedAtMs(issue);- if (- eventMs !== null &&- Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS- ) {- continue;- }- }+ const lastOutbound = existingMetadata.lastOutboundStateSyncAt;+ if (+ typeof lastOutbound === "number" &&+ Number.isFinite(lastOutbound)+ ) {+ const eventMs = parseIssueUpdatedAtMs(issue);+ if (+ eventMs !== null &&+ Math.abs(eventMs - lastOutbound) <= OUTBOUND_STATE_ECHO_WINDOW_MS+ ) {+ return;+ }+ }- const targetStatus = await resolveTargetStatus(- task.projectId,- "issue_reopened",- "to-do",- );+ 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",- });- }+ const statusResult = await updateTaskStatus(+ task.id,+ targetStatus,+ db,+ );+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ 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: "open",+ await updateExternalLink(+ externalLink.id,+ {+ metadata: {+ ...existingMetadata,+ state: "open",+ },+ },+ db,+ );},- });+ );} catch (error) {console.error("Gitea issue_reopened handler failed for integration", {integrationId: integration.id,diff --git a/apps/api/src/plugins/github/services/integration-task-scope.ts b/apps/api/src/plugins/github/services/integration-task-scope.tsnew file mode 100644index 000000000..c1f4f9e75--- /dev/null+++ b/apps/api/src/plugins/github/services/integration-task-scope.ts@@ -0,0 +1,74 @@+import { and, eq, sql } from "drizzle-orm";+import db from "../../../database";+import {+ externalLinkTable,+ integrationTable,+ projectTable,+ taskTable,+} from "../../../database/schema";++export type IntegrationDatabase =+ | typeof db+ | Parameters<Parameters<typeof db.transaction>[0]>[0];+type IntegrationScope = {+ id: string;+ projectId: string;+ project?: { workspaceId: string };+};++// Key-share protects the project/workspace key while allowing task-number+// allocation. Task locks protect their project until related writes commit.+export async function withIntegrationTask<T>(+ taskId: string | null,+ integration: IntegrationScope,+ apply: (+ database: IntegrationDatabase,+ afterCommit: (effect: () => Promise<void>) => void,+ ) => Promise<T>,+): Promise<T | undefined> {+ const effects: Array<() => Promise<void>> = [];+ const result = await db.transaction(async (tx) => {+ const [project] = await tx+ .select({ id: projectTable.id })+ .from(projectTable)+ .innerJoin(+ integrationTable,+ eq(integrationTable.projectId, projectTable.id),+ )+ .where(+ and(+ eq(integrationTable.id, integration.id),+ eq(projectTable.id, integration.projectId),+ integration.project+ ? eq(projectTable.workspaceId, integration.project.workspaceId)+ : undefined,+ ),+ )+ .for("key share", { of: projectTable });+ if (!project) return undefined;+ if (taskId !== null) {+ const [task] = await tx+ .select({ id: taskTable.id })+ .from(taskTable)+ .where(+ and(+ eq(taskTable.id, taskId),+ eq(taskTable.projectId, integration.projectId),+ ),+ )+ .for("no key update");+ if (!task) return undefined;+ }+ return apply(tx, (effect) => effects.push(effect));+ });+ for (const effect of effects) await effect();+ return result;+}++export function linkedTaskScope(taskId: string, projectId: string) {+ return and(eq(taskTable.id, taskId), eq(taskTable.projectId, projectId));+}++export function externalLinkScope() {+ return sql`exists (select 1 from ${taskTable} scoped_task join ${integrationTable} scoped_integration on scoped_integration.project_id = scoped_task.project_id where scoped_task.id = ${externalLinkTable.taskId} and scoped_integration.id = ${externalLinkTable.integrationId})`;+}diff --git a/apps/api/src/plugins/github/services/link-manager.ts b/apps/api/src/plugins/github/services/link-manager.tsindex abf8ba1b7..c62f3b860 100644--- a/apps/api/src/plugins/github/services/link-manager.ts+++ b/apps/api/src/plugins/github/services/link-manager.ts@@ -1,6 +1,12 @@import { and, eq } from "drizzle-orm";import db from "../../../database";-import { externalLinkTable } from "../../../database/schema";+import {+ externalLinkTable,+ integrationTable,+ taskTable,+} from "../../../database/schema";++import { externalLinkScope } from "./integration-task-scope";type DbOrTx = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];@@ -24,6 +30,26 @@ export async function createExternalLink(params: CreateExternalLinkParams,database: DbOrTx = db,): Promise<{ id: string }> {+ if (database === db) {+ return db.transaction((tx) => createExternalLink(params, tx));+ }+ const [task] = await database+ .select({ id: taskTable.id })+ .from(taskTable)+ .innerJoin(+ integrationTable,+ eq(integrationTable.projectId, taskTable.projectId),+ )+ .where(+ and(+ eq(taskTable.id, params.taskId),+ eq(integrationTable.id, params.integrationId),+ ),+ )+ .for("share", { of: taskTable });+ if (!task)+ throw new Error("Task no longer belongs to the integration project");+const result = await database.insert(externalLinkTable).values({@@ -56,6 +82,7 @@ export async function findExternalLink(eq(externalLinkTable.integrationId, integrationId),eq(externalLinkTable.resourceType, resourceType),eq(externalLinkTable.externalId, externalId),+ externalLinkScope(),),});}@@ -70,13 +97,14 @@ export async function findExternalLinkByTaskAndType(eq(externalLinkTable.taskId, taskId),eq(externalLinkTable.integrationId, integrationId),eq(externalLinkTable.resourceType, resourceType),+ externalLinkScope(),),});}export async function findExternalLinksByTask(taskId: string) {return db.query.externalLinkTable.findMany({- where: eq(externalLinkTable.taskId, taskId),+ where: and(eq(externalLinkTable.taskId, taskId), externalLinkScope()),with: {integration: true,},@@ -86,6 +114,7 @@ export async function findExternalLinksByTask(taskId: string) {export async function updateExternalLink(id: string,params: UpdateExternalLinkParams,+ database: DbOrTx = db,) {const updateData: Record<string, unknown> = {};@@ -103,7 +132,7 @@ export async function updateExternalLink(return;}- await db+ await database.update(externalLinkTable).set(updateData).where(eq(externalLinkTable.id, id));diff --git a/apps/api/src/plugins/github/services/task-service.ts b/apps/api/src/plugins/github/services/task-service.tsindex ac0a2d591..2029003b1 100644--- a/apps/api/src/plugins/github/services/task-service.ts+++ b/apps/api/src/plugins/github/services/task-service.ts@@ -8,6 +8,8 @@ import {} from "../../../database/schema";import { type GitHubConfig, hasVerifiedGitHubBinding } from "../config";+import type { IntegrationDatabase } from "./integration-task-scope";+export type TaskRow = InferSelectModel<typeof taskTable>;export type UpdateTaskStatusResult =@@ -34,8 +36,9 @@ export async function findTaskById(taskId: string) {export async function updateTaskStatus(taskId: string,newStatus: string,+ database: IntegrationDatabase = db,): Promise<UpdateTaskStatusResult> {- const task = await db.query.taskTable.findFirst({+ const task = await database.query.taskTable.findFirst({where: eq(taskTable.id, taskId),});@@ -45,7 +48,7 @@ export async function updateTaskStatus(let columnId: string | null = null;- const column = await db.query.columnTable.findFirst({+ const column = await database.query.columnTable.findFirst({where: and(eq(columnTable.projectId, task.projectId),eq(columnTable.slug, newStatus),@@ -61,14 +64,13 @@ export async function updateTaskStatus(return { applied: false };}- await db+ const [after] = await database.update(taskTable).set({ status: newStatus, columnId })- .where(eq(taskTable.id, taskId));-- const after = await db.query.taskTable.findFirst({- where: eq(taskTable.id, taskId),- });+ .where(+ and(eq(taskTable.id, taskId), eq(taskTable.projectId, task.projectId)),+ )+ .returning();if (!after) {return { applied: false };diff --git a/apps/api/src/plugins/github/webhooks/issue-closed.ts b/apps/api/src/plugins/github/webhooks/issue-closed.tsindex 9a8933b9a..d5d2db083 100644--- a/apps/api/src/plugins/github/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/github/webhooks/issue-closed.ts@@ -1,6 +1,10 @@+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";-import { externalLinkTable, taskTable } from "../../../database/schema";+import { externalLinkTable } from "../../../database/schema";import { publishEvent } from "../../../events";import { updateExternalLink } from "../services/link-manager";import {@@ -45,51 +49,63 @@ export async function handleIssueClosed(payload: IssueClosedPayload) {continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- });+ await withIntegrationTask(+ externalLink.taskId,+ integration,+ async (db, afterCommit) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- if (!task) {- continue;- }+ if (!task) {+ return;+ }- const existingMetadata = parseLinkMetadata(externalLink.metadata, {- externalLinkId: externalLink.id,- source: "issue_closed",- });+ const existingMetadata = parseLinkMetadata(externalLink.metadata, {+ externalLinkId: externalLink.id,+ source: "issue_closed",+ });- if (existingMetadata.createdFrom === "kaneo") {- continue;- }+ if (existingMetadata.createdFrom === "kaneo") {+ return;+ }- const targetStatus = await resolveTargetStatus(- task.projectId,- "issue_closed",- "done",- );+ 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",- });- }+ const statusResult = await updateTaskStatus(task.id, targetStatus, db);+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ 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",+ await updateExternalLink(+ externalLink.id,+ {+ metadata: {+ ...existingMetadata,+ state: "closed",+ },+ },+ db,+ );},- });+ );}}diff --git a/apps/api/src/plugins/github/webhooks/issue-comment-created.ts b/apps/api/src/plugins/github/webhooks/issue-comment-created.tsindex ff88fa658..8e4b738b7 100644--- a/apps/api/src/plugins/github/webhooks/issue-comment-created.ts+++ b/apps/api/src/plugins/github/webhooks/issue-comment-created.ts@@ -1,4 +1,4 @@-import db from "../../../database";+import { withIntegrationTask } from "../services/integration-task-scope";import { activityTable } from "../../../database/schema";import { findExternalLink } from "../services/link-manager";import { findAllIntegrationsByRepo } from "../services/task-service";@@ -53,25 +53,27 @@ export async function handleIssueCommentCreated(continue;}- await db- .insert(activityTable)- .values({- taskId: existingLink.taskId,- type: "comment",- content: comment.body,- externalUserName: comment.user?.login ?? "Unknown",- externalUserAvatar: comment.user?.avatar_url ?? null,- externalSource: "github",- externalUrl: comment.html_url,- })- .onConflictDoNothing({- target: [- activityTable.taskId,- activityTable.externalSource,- activityTable.externalUrl,- ],- });+ await withIntegrationTask(existingLink.taskId, integration, async (db) => {+ await db+ .insert(activityTable)+ .values({+ taskId: existingLink.taskId,+ type: "comment",+ content: comment.body,+ externalUserName: comment.user?.login ?? "Unknown",+ externalUserAvatar: comment.user?.avatar_url ?? null,+ externalSource: "github",+ externalUrl: comment.html_url,+ })+ .onConflictDoNothing({+ target: [+ activityTable.taskId,+ activityTable.externalSource,+ activityTable.externalUrl,+ ],+ });- return;+ return;+ });}}diff --git a/apps/api/src/plugins/github/webhooks/issue-edited.ts b/apps/api/src/plugins/github/webhooks/issue-edited.tsindex 8847206bc..7a91fd900 100644--- a/apps/api/src/plugins/github/webhooks/issue-edited.ts+++ b/apps/api/src/plugins/github/webhooks/issue-edited.ts@@ -1,5 +1,7 @@-import { eq } from "drizzle-orm";-import db from "../../../database";+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../services/integration-task-scope";import { taskTable } from "../../../database/schema";import { findExternalLink, updateExternalLink } from "../services/link-manager";import { findAllIntegrationsByRepo } from "../services/task-service";@@ -69,128 +71,132 @@ export async function handleIssueEdited(payload: IssueEditedPayload) {continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- });-- if (!task) {- console.error(`Task ${externalLink.taskId} not found`);- continue;- }-- const metadata = parseLinkMetadata<IssueEditedMetadata>(- externalLink.metadata,- {- externalLinkId: externalLink.id,- source: "issue_edited",- },- );+ await withIntegrationTask(externalLink.taskId, integration, async (db) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- const updateData: Record<string, unknown> = {};- const updatedMetadata: IssueEditedMetadata = { ...metadata };+ if (!task) {+ console.error(`Task ${externalLink.taskId} not found`);+ return;+ }- if (!updatedMetadata.lastSync) {- updatedMetadata.lastSync = {};- }+ const metadata = parseLinkMetadata<IssueEditedMetadata>(+ externalLink.metadata,+ {+ externalLinkId: externalLink.id,+ source: "issue_edited",+ },+ );- if (changes.title) {- const lastTitleSync = metadata.lastSync?.title;+ const updateData: Record<string, unknown> = {};+ const updatedMetadata: IssueEditedMetadata = { ...metadata };- let shouldUpdateTitle = true;+ if (!updatedMetadata.lastSync) {+ updatedMetadata.lastSync = {};+ }- if (lastTitleSync) {- if (- lastTitleSync.value === issue.title &&- lastTitleSync.source === "kaneo"- ) {- console.log("Skipping title update - already synced from Kaneo");- shouldUpdateTitle = false;+ if (changes.title) {+ const lastTitleSync = metadata.lastSync?.title;++ let shouldUpdateTitle = true;++ if (lastTitleSync) {+ if (+ lastTitleSync.value === issue.title &&+ lastTitleSync.source === "kaneo"+ ) {+ console.log("Skipping title update - already synced from Kaneo");+ shouldUpdateTitle = false;+ }+ const timeSinceLastSync =+ Date.now() - new Date(lastTitleSync.timestamp ?? 0).getTime();+ if (timeSinceLastSync < 2000 && shouldUpdateTitle) {+ console.log(+ `Skipping title update - recent sync detected (${timeSinceLastSync}ms ago)`,+ );+ shouldUpdateTitle = false;+ }}- const timeSinceLastSync =- Date.now() - new Date(lastTitleSync.timestamp ?? 0).getTime();- if (timeSinceLastSync < 2000 && shouldUpdateTitle) {+ if (shouldUpdateTitle) {+ updateData.title = issue.title;+ updatedMetadata.lastSync.title = {+ timestamp: new Date().toISOString(),+ source: "github",+ value: issue.title,+ };console.log(- `Skipping title update - recent sync detected (${timeSinceLastSync}ms ago)`,+ `Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,);- shouldUpdateTitle = false;}}- if (shouldUpdateTitle) {- updateData.title = issue.title;- updatedMetadata.lastSync.title = {- timestamp: new Date().toISOString(),- source: "github",- value: issue.title,- };- console.log(- `Updating task title from GitHub: "${changes.title.from}" → "${issue.title}"`,+ if (changes.body) {+ const lastDescSync = metadata.lastSync?.description;+ const formattedDescription = formatTaskDescriptionFromIssue(+ issue.body,+ task.id,);- }- }- if (changes.body) {- const lastDescSync = metadata.lastSync?.description;- const formattedDescription = formatTaskDescriptionFromIssue(- issue.body,- task.id,- );-- let shouldUpdateDescription = true;-- if (lastDescSync) {- if (- lastDescSync.value === formattedDescription &&- lastDescSync.source === "kaneo"- ) {- console.log(- "Skipping description update - already synced from Kaneo",- );- shouldUpdateDescription = false;+ let shouldUpdateDescription = true;++ if (lastDescSync) {+ if (+ lastDescSync.value === formattedDescription &&+ lastDescSync.source === "kaneo"+ ) {+ console.log(+ "Skipping description update - already synced from Kaneo",+ );+ shouldUpdateDescription = false;+ }+ const timeSinceLastSync =+ Date.now() - new Date(lastDescSync.timestamp ?? 0).getTime();+ if (timeSinceLastSync < 2000 && shouldUpdateDescription) {+ console.log(+ `Skipping description update - recent sync detected (${timeSinceLastSync}ms ago)`,+ );+ shouldUpdateDescription = false;+ }}- const timeSinceLastSync =- Date.now() - new Date(lastDescSync.timestamp ?? 0).getTime();- if (timeSinceLastSync < 2000 && shouldUpdateDescription) {- console.log(- `Skipping description update - recent sync detected (${timeSinceLastSync}ms ago)`,- );- shouldUpdateDescription = false;+ if (shouldUpdateDescription) {+ updateData.description = formattedDescription;+ updatedMetadata.lastSync.description = {+ timestamp: new Date().toISOString(),+ source: "github",+ value: formattedDescription,+ };+ console.log("Updating task description from GitHub");}}- if (shouldUpdateDescription) {- updateData.description = formattedDescription;- updatedMetadata.lastSync.description = {- timestamp: new Date().toISOString(),- source: "github",- value: formattedDescription,- };- console.log("Updating task description from GitHub");- }- }-- if (Object.keys(updateData).length > 0) {- await db- .update(taskTable)- .set(updateData)- .where(eq(taskTable.id, task.id));-- await updateExternalLink(externalLink.id, {- title: issue.title,- metadata: updatedMetadata,- });+ if (Object.keys(updateData).length > 0) {+ await db+ .update(taskTable)+ .set(updateData)+ .where(linkedTaskScope(task.id, integration.projectId));++ await updateExternalLink(+ externalLink.id,+ {+ title: issue.title,+ metadata: updatedMetadata,+ },+ db,+ );- console.log(- `Synced ${Object.keys(updateData).join(", ")} from GitHub issue #${issue.number} to task ${task.id}`,- );- } else {- console.log(- `No updates needed for task ${task.id} from issue #${issue.number}`,- );- }+ console.log(+ `Synced ${Object.keys(updateData).join(", ")} from GitHub issue #${issue.number} to task ${task.id}`,+ );+ } else {+ console.log(+ `No updates needed for task ${task.id} from issue #${issue.number}`,+ );+ }- return;+ return;+ });}}diff --git a/apps/api/src/plugins/github/webhooks/issue-labeled.ts b/apps/api/src/plugins/github/webhooks/issue-labeled.tsindex 63252bec6..46c295a80 100644--- a/apps/api/src/plugins/github/webhooks/issue-labeled.ts+++ b/apps/api/src/plugins/github/webhooks/issue-labeled.ts@@ -1,5 +1,8 @@+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../services/integration-task-scope";import { eq } from "drizzle-orm";-import db from "../../../database";import { labelTable, taskTable } from "../../../database/schema";import { publishEvent } from "../../../events";import { findExternalLink } from "../services/link-manager";@@ -46,96 +49,110 @@ export async function handleIssueLabeled(payload: IssueLabeledPayload) {continue;}- const priority = extractIssuePriority(issue.labels);- const status = extractIssueStatus(issue.labels);+ await withIntegrationTask(+ existingLink.taskId,+ integration,+ async (db, afterCommit) => {+ const priority = extractIssuePriority(issue.labels);+ const status = extractIssueStatus(issue.labels);- if (priority) {- await db- .update(taskTable)- .set({ priority })- .where(eq(taskTable.id, existingLink.taskId));- }+ if (priority) {+ await db+ .update(taskTable)+ .set({ priority })+ .where(linkedTaskScope(existingLink.taskId, integration.projectId));+ }- if (status) {- const statusResult = await updateTaskStatus(existingLink.taskId, 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 (status) {+ const statusResult = await updateTaskStatus(+ existingLink.taskId,+ status,+ db,+ );+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ 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 (!addedLabel) {- return;- }+ if (!addedLabel) {+ return;+ }- const isSystemLabel =- addedLabel.name.startsWith("priority:") ||- addedLabel.name.startsWith("status:");+ const isSystemLabel =+ addedLabel.name.startsWith("priority:") ||+ addedLabel.name.startsWith("status:");- if (isSystemLabel) {- return;- }+ if (isSystemLabel) {+ return;+ }- if (payload.action === "labeled") {- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, existingLink.taskId),- with: {- project: true,- },- });-- if (task?.project?.workspaceId) {- const existingLabel = await db.query.labelTable.findFirst({- where: (table, { and, eq }) =>- and(- eq(table.workspaceId, task.project.workspaceId),- eq(table.name, addedLabel.name),- eq(table.taskId, task.id),- ),- });-- if (!existingLabel) {- const color = addedLabel.color ? `#${addedLabel.color}` : "#6B7280";- await db- .insert(labelTable)- .values({- name: addedLabel.name,- color,- taskId: task.id,- workspaceId: task.project.workspaceId,- })- .onConflictDoNothing({- target: [labelTable.taskId, labelTable.name],+ if (payload.action === "labeled") {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(existingLink.taskId, integration.projectId),+ with: {+ project: true,+ },+ });++ if (task?.project?.workspaceId) {+ const existingLabel = await db.query.labelTable.findFirst({+ where: (table, { and, eq }) =>+ and(+ eq(table.workspaceId, task.project.workspaceId),+ eq(table.name, addedLabel.name),+ eq(table.taskId, task.id),+ ),});++ if (!existingLabel) {+ const color = addedLabel.color+ ? `#${addedLabel.color}`+ : "#6B7280";+ await db+ .insert(labelTable)+ .values({+ name: addedLabel.name,+ color,+ taskId: task.id,+ workspaceId: task.project.workspaceId,+ })+ .onConflictDoNothing({+ target: [labelTable.taskId, labelTable.name],+ });+ }+ }}- }- }- if (payload.action === "unlabeled") {- const labelsToDelete = await db.query.labelTable.findMany({- where: (table, { and, eq }) =>- and(- eq(table.taskId, existingLink.taskId),- eq(table.name, addedLabel.name),- ),- });-- for (const label of labelsToDelete) {- await db.delete(labelTable).where(eq(labelTable.id, label.id));- }- }+ if (payload.action === "unlabeled") {+ const labelsToDelete = await db.query.labelTable.findMany({+ where: (table, { and, eq }) =>+ and(+ eq(table.taskId, existingLink.taskId),+ eq(table.name, addedLabel.name),+ ),+ });++ for (const label of labelsToDelete) {+ await db.delete(labelTable).where(eq(labelTable.id, label.id));+ }+ }- return;+ return;+ },+ );}}diff --git a/apps/api/src/plugins/github/webhooks/issue-reopened.ts b/apps/api/src/plugins/github/webhooks/issue-reopened.tsindex e2fb54779..fbcf4595f 100644--- a/apps/api/src/plugins/github/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/github/webhooks/issue-reopened.ts@@ -1,6 +1,10 @@+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";-import { externalLinkTable, taskTable } from "../../../database/schema";+import { externalLinkTable } from "../../../database/schema";import { publishEvent } from "../../../events";import { updateExternalLink } from "../services/link-manager";import {@@ -45,51 +49,63 @@ export async function handleIssueReopened(payload: IssueReopenedPayload) {continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- });+ await withIntegrationTask(+ externalLink.taskId,+ integration,+ async (db, afterCommit) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- if (!task) {- continue;- }+ if (!task) {+ return;+ }- const existingMetadata = parseLinkMetadata(externalLink.metadata, {- externalLinkId: externalLink.id,- source: "issue_reopened",- });+ const existingMetadata = parseLinkMetadata(externalLink.metadata, {+ externalLinkId: externalLink.id,+ source: "issue_reopened",+ });- if (existingMetadata.createdFrom === "kaneo") {- continue;- }+ if (existingMetadata.createdFrom === "kaneo") {+ return;+ }- const targetStatus = await resolveTargetStatus(- task.projectId,- "issue_reopened",- "to-do",- );+ 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",- });- }+ const statusResult = await updateTaskStatus(task.id, targetStatus, db);+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ 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: "open",+ await updateExternalLink(+ externalLink.id,+ {+ metadata: {+ ...existingMetadata,+ state: "open",+ },+ },+ db,+ );},- });+ );}}diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts b/apps/api/src/plugins/gitlab/webhooks/issue-closed.tsindex 328d8c150..6bd9bc7ab 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-closed.ts@@ -1,6 +1,10 @@+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../../github/services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";-import { externalLinkTable, taskTable } from "../../../database/schema";+import { externalLinkTable } from "../../../database/schema";import { publishEvent } from "../../../events";import { updateExternalLink } from "../../github/services/link-manager";import { updateTaskStatus } from "../../github/services/task-service";@@ -61,75 +65,90 @@ export async function handleGitlabIssueClosed(continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- });+ await withIntegrationTask(+ externalLink.taskId,+ integration,+ async (db, afterCommit) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- if (!task) {- continue;- }+ if (!task) {+ return;+ }- 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,- });- }- }+ 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,+ },+ );+ }+ }- // Only an echo if it reports the state Kaneo last wrote.- 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;- }- }+ // Only an echo if it reports the state Kaneo last wrote.+ 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+ ) {+ return;+ }+ }- const targetStatus = await resolveTargetStatus(- task.projectId,- "issue_closed",- "done",- );+ 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", {- sourceIntegrationId: integration.id,- 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",- });- }+ const statusResult = await updateTaskStatus(task.id, targetStatus, db);+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ publishEvent("task.status_changed", {+ sourceIntegrationId: integration.id,+ 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",+ await updateExternalLink(+ externalLink.id,+ {+ metadata: {+ ...existingMetadata,+ state: "closed",+ },+ },+ db,+ );},- });+ );}}diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts b/apps/api/src/plugins/gitlab/webhooks/issue-reopened.tsindex 28b9b5c32..d2c1835b1 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-reopened.ts@@ -1,6 +1,10 @@+import {+ linkedTaskScope,+ withIntegrationTask,+} from "../../github/services/integration-task-scope";import { and, eq } from "drizzle-orm";import db from "../../../database";-import { externalLinkTable, taskTable } from "../../../database/schema";+import { externalLinkTable } from "../../../database/schema";import { publishEvent } from "../../../events";import { updateExternalLink } from "../../github/services/link-manager";import { updateTaskStatus } from "../../github/services/task-service";@@ -61,74 +65,89 @@ export async function handleGitlabIssueReopened(continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- });+ await withIntegrationTask(+ externalLink.taskId,+ integration,+ async (db, afterCommit) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ });- if (!task) {- continue;- }+ if (!task) {+ return;+ }- 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,- });- }- }+ 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 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+ ) {+ return;+ }+ }- const targetStatus = await resolveTargetStatus(- task.projectId,- "issue_reopened",- "to-do",- );+ 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", {- sourceIntegrationId: integration.id,- 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",- });- }+ const statusResult = await updateTaskStatus(task.id, targetStatus, db);+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ publishEvent("task.status_changed", {+ sourceIntegrationId: integration.id,+ 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",+ await updateExternalLink(+ externalLink.id,+ {+ metadata: {+ ...existingMetadata,+ state: "opened",+ },+ },+ db,+ );},- });+ );}}diff --git a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts b/apps/api/src/plugins/gitlab/webhooks/issue-updated.tsindex ba3375d71..3954c3a4b 100644--- a/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts+++ b/apps/api/src/plugins/gitlab/webhooks/issue-updated.ts@@ -1,5 +1,9 @@+import {+ type IntegrationDatabase,+ linkedTaskScope,+ withIntegrationTask,+} from "../../github/services/integration-task-scope";import { eq, inArray } from "drizzle-orm";-import db from "../../../database";import { labelTable, taskTable } from "../../../database/schema";import { publishEvent } from "../../../events";import {@@ -63,6 +67,7 @@ async function syncGitlabLabelsToTask(workspaceId: string,gitlabLabels: Array<{ name: string; color: string }>,previousLabels: GitlabWebhookLabel[] | undefined,+ db: IntegrationDatabase,) {const desiredNames = new Set(gitlabLabels.map((l) => l.name));const existingRows = await db.query.labelTable.findMany({@@ -159,114 +164,129 @@ export async function handleGitlabIssueUpdated(continue;}- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, externalLink.taskId),- with: { project: true },- });+ await withIntegrationTask(+ externalLink.taskId,+ integration,+ async (db, afterCommit) => {+ const task = await db.query.taskTable.findFirst({+ where: linkedTaskScope(externalLink.taskId, integration.projectId),+ with: { project: true },+ });- if (!task) {- continue;- }+ if (!task) {+ return;+ }- let metadata: LinkMetadata = parseLinkSyncMetadata(- externalLink.metadata,- { externalLinkId: externalLink.id, field: "issue" },- );+ 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 (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?.title &&+ !isEchoOf(metadata.lastSync?.title, "kaneo", issue.title)+ ) {+ updateData.title = issue.title;+ lastSync.title = {+ timestamp: now,+ source: "gitlab",+ value: issue.title,+ };+ }- if (changes?.description) {- // Kaneo recorded the body with its footer, so compare the raw body.- const issueBody = issue.description ?? "";- if (!isEchoOf(metadata.lastSync?.description, "kaneo", issueBody)) {- const description = taskDescriptionFromIssue(issue.description);- updateData.description = description;- lastSync.description = {- timestamp: now,- source: "gitlab",- value: description,- };- }- }+ if (changes?.description) {+ // Kaneo recorded the body with its footer, so compare the raw body.+ const issueBody = issue.description ?? "";+ if (+ !isEchoOf(metadata.lastSync?.description, "kaneo", issueBody)+ ) {+ const description = taskDescriptionFromIssue(issue.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));+ if (Object.keys(updateData).length > 0) {+ await db+ .update(taskTable)+ .set(updateData)+ .where(linkedTaskScope(task.id, integration.projectId));- metadata = { ...metadata, lastSync };+ metadata = { ...metadata, lastSync };- await updateExternalLink(externalLink.id, {- title: issue.title,- metadata,- });- }- }+ await updateExternalLink(+ externalLink.id,+ {+ title: issue.title,+ metadata,+ },+ db,+ );+ }+ }- if (!touchedLabels || !currentLabels) {- continue;- }+ if (!touchedLabels || !currentLabels) {+ return;+ }- const titles = labelTitles(currentLabels);- const priority = extractIssuePriority(titles);- const status = extractIssueStatus(titles);+ 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 (priority) {+ await db+ .update(taskTable)+ .set({ priority })+ .where(linkedTaskScope(task.id, integration.projectId));+ }- // Unrelated label edits also include the full label snapshot. Its status- // can predate a close/reopen, so only apply an actual status-label change.- const previousStatus = extractIssueStatus(- labelTitles(changes?.labels?.previous),- );- if (status && status !== previousStatus) {- const statusResult = await updateTaskStatus(task.id, status);- if (- statusResult.applied &&- statusResult.before.status !== statusResult.after.status- ) {- await publishEvent("task.status_changed", {- sourceIntegrationId: integration.id,- 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",- });- }- }+ // Unrelated label edits also include the full label snapshot. Its status+ // can predate a close/reopen, so only apply an actual status-label change.+ const previousStatus = extractIssueStatus(+ labelTitles(changes?.labels?.previous),+ );+ if (status && status !== previousStatus) {+ const statusResult = await updateTaskStatus(task.id, status, db);+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ afterCommit(() =>+ publishEvent("task.status_changed", {+ sourceIntegrationId: integration.id,+ 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),- changes?.labels?.previous,- );- }+ if (task.project?.workspaceId) {+ await syncGitlabLabelsToTask(+ task.id,+ task.project.workspaceId,+ nonSystemLabels(currentLabels),+ changes?.labels?.previous,+ db,+ );+ }+ },+ );} catch (error) {console.error("GitLab issue update handler failed for integration", {integrationId: integration.id,diff --git a/apps/api/src/plugins/gitlab/webhooks/note-created.ts b/apps/api/src/plugins/gitlab/webhooks/note-created.tsindex 67308e5ea..8faf4a1c6 100644--- a/apps/api/src/plugins/gitlab/webhooks/note-created.ts+++ b/apps/api/src/plugins/gitlab/webhooks/note-created.ts@@ -1,4 +1,4 @@-import db from "../../../database";+import { withIntegrationTask } from "../../github/services/integration-task-scope";import { activityTable } from "../../../database/schema";import { findExternalLink } from "../../github/services/link-manager";import { findAllIntegrationsByGitlabProject } from "../services/integration-lookup";@@ -67,30 +67,32 @@ export async function handleGitlabNoteCreated(continue;}- if (syncedNoteIds(externalLink.metadata).includes(note.id)) {- continue;- }+ await withIntegrationTask(externalLink.taskId, integration, async (db) => {+ if (syncedNoteIds(externalLink.metadata).includes(note.id)) {+ return;+ }- 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,- ],- });+ 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/project/controllers/move-project.ts b/apps/api/src/project/controllers/move-project.tsindex 04fa46f94..f89774c11 100644--- a/apps/api/src/project/controllers/move-project.ts+++ b/apps/api/src/project/controllers/move-project.ts@@ -13,6 +13,8 @@ import createActivities from "../../activity/controllers/create-activities";import db from "../../database";import {assetTable,+ externalLinkTable,+ integrationTable,labelTable,projectTable,taskRelationTable,@@ -200,6 +202,28 @@ async function moveProject(});}+ // Older task moves could leave links owned by a different project.+ await tx+ .delete(externalLinkTable)+ .where(+ and(+ inArray(+ externalLinkTable.taskId,+ tx+ .select({ id: taskTable.id })+ .from(taskTable)+ .where(eq(taskTable.projectId, id)),+ ),+ notInArray(+ externalLinkTable.integrationId,+ tx+ .select({ id: integrationTable.id })+ .from(integrationTable)+ .where(eq(integrationTable.projectId, id)),+ ),+ ),+ );+// Assets and task labels denormalize the project's workspace.await tx.update(assetTable)diff --git a/apps/api/src/task/controllers/move-task.ts b/apps/api/src/task/controllers/move-task.tsindex f45ff1f27..d2c2918e8 100644--- a/apps/api/src/task/controllers/move-task.ts+++ b/apps/api/src/task/controllers/move-task.ts@@ -4,6 +4,7 @@ import db from "../../database";import {assetTable,columnTable,+ externalLinkTable,projectTable,taskTable,} from "../../database/schema";@@ -113,6 +114,22 @@ async function moveTask({);const movedTask = await db.transaction(async (tx) => {+ for (const projectId of [sourceProject.id, destinationProjectId].sort()) {+ const [project] = await tx+ .select({ id: projectTable.id })+ .from(projectTable)+ .where(+ and(+ eq(projectTable.id, projectId),+ eq(projectTable.workspaceId, sourceProject.workspaceId),+ ),+ )+ .for("key share");+ if (!project)+ throw new HTTPException(409, {+ message: "Project was moved to another workspace, please try again",+ });+ }const nextTaskNumber = await claimTaskNumber(destinationProjectId, tx);const nextPosition = await nextTaskPosition(tx,@@ -130,7 +147,12 @@ async function moveTask({number: nextTaskNumber,position: nextPosition,})- .where(eq(taskTable.id, taskId))+ .where(+ and(+ eq(taskTable.id, taskId),+ eq(taskTable.projectId, sourceProject.id),+ ),+ ).returning();if (!updatedTask) {@@ -139,6 +161,10 @@ async function moveTask({});}+ await tx+ .delete(externalLinkTable)+ .where(eq(externalLinkTable.taskId, taskId));+await tx.update(assetTable).set({ projectId: destinationProjectId })diff --git a/tests/api-integration/github-description-sync.test.ts b/tests/api-integration/github-description-sync.test.tsindex b77b319bb..fe64b25f4 100644--- a/tests/api-integration/github-description-sync.test.ts+++ b/tests/api-integration/github-description-sync.test.ts@@ -13,9 +13,6 @@ const m = vi.hoisted(() => ({find: vi.fn(),update: vi.fn(async () => undefined),}));-vi.mock("../../apps/api/src/plugins/github/services/task-service", () => ({- findAllIntegrationsByRepo: async () => [{ id: "verified-integration" }],-}));vi.mock("../../apps/api/src/plugins/github/services/link-manager", () => ({findExternalLink: m.find,updateExternalLink: m.update,@@ -29,6 +26,18 @@ beforeEach(async () => {async function setup() {const { workspace } = await createWorkspaceMember();const { project } = await createProjectFixture({ workspaceId: workspace.id });+ await db.insert(schema.integrationTable).values({+ projectId: project.id,+ type: "github",+ config: JSON.stringify({+ repositoryOwner: "example",+ repositoryName: "repo",+ installationId: 10,+ repositoryId: 20,+ verifiedGithubAccountId: "123",+ verifiedByUserId: "user",+ }),+ });const [task] = await db.insert(schema.taskTable).values({@@ -103,6 +112,7 @@ describe("GitHub description round trip", () => {}),}),}),+ expect.anything(),);});diff --git a/tests/api-integration/integration-task-ownership.test.ts b/tests/api-integration/integration-task-ownership.test.tsnew file mode 100644index 000000000..de144beff--- /dev/null+++ b/tests/api-integration/integration-task-ownership.test.ts@@ -0,0 +1,288 @@+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { importGiteaIssues } from "../../apps/api/src/gitea-integration/controllers/import-gitea-issues";+import { importGitlabIssues } from "../../apps/api/src/gitlab-integration/controllers/import-gitlab-issues";+import { handleGiteaIssueEdited } from "../../apps/api/src/plugins/gitea/webhooks/issue-edited";+import { handleGiteaIssueLabeled } from "../../apps/api/src/plugins/gitea/webhooks/issue-labeled";+import { handleGiteaIssueCommentCreated } from "../../apps/api/src/plugins/gitea/webhooks/issue-comment-created";+import { withIntegrationTask } from "../../apps/api/src/plugins/github/services/integration-task-scope";+import moveTask from "../../apps/api/src/task/controllers/move-task";+import moveProject from "../../apps/api/src/project/controllers/move-project";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const m = vi.hoisted(() => ({+ listIssues: vi.fn(),+ listIssueComments: vi.fn(async () => []),+ listIssueNotes: vi.fn(async () => []),+ listPulls: vi.fn(async () => []),+ listMergeRequests: vi.fn(async () => []),+}));+vi.mock(+ "../../apps/api/src/plugins/gitea/utils/gitea-api",+ async (original) => ({+ ...(await original<+ typeof import("../../apps/api/src/plugins/gitea/utils/gitea-api")+ >()),+ createGiteaClient: () => m,+ }),+);+vi.mock(+ "../../apps/api/src/plugins/gitlab/utils/gitlab-api",+ async (original) => ({+ ...(await original<+ typeof import("../../apps/api/src/plugins/gitlab/utils/gitlab-api")+ >()),+ createGitlabClient: () => m,+ }),+);+const remoteIssue = {+ number: 1,+ iid: 1,+ title: "Remote title",+ body: "Remote description",+ description: "Remote description",+ html_url: "https://gitea.example/owner/repo/issues/1",+ web_url: "https://gitlab.example/group/repo/-/issues/1",+ state: "open",+ labels: [],+};+const repository = {+ owner: { login: "owner" },+ name: "repo",+ html_url: "https://gitea.example/owner/repo",+};+beforeEach(async () => {+ await resetTestDatabase();+ vi.clearAllMocks();+ m.listIssues.mockResolvedValue([remoteIssue]);+});+async function setup(type = "gitea") {+ const source = await createWorkspaceMember({ role: "owner" });+ const privateWorkspace = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: source.workspace.id,+ });+ const { project: destination } = await createProjectFixture({+ workspaceId: source.workspace.id,+ });+ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Private title",+ description: "Private description",+ number: 1,+ })+ .returning();+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type,+ config: JSON.stringify({+ baseUrl: `https://${type}.example`,+ accessToken: "fake-test-token",+ repositoryOwner: "owner",+ repositoryName: "repo",+ projectPath: "group/repo",+ }),+ })+ .returning();+ const [link] = await db+ .insert(schema.externalLinkTable)+ .values({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: "1",+ url: remoteIssue.html_url,+ })+ .returning();+ return {+ source,+ privateWorkspace,+ project,+ destination,+ task,+ integration,+ link,+ };+}+async function moveWithoutCleanup(fixture: Awaited<ReturnType<typeof setup>>) {+ // Reproduce links left by earlier releases, even after their new project+ // has moved into a private workspace.+ await db+ .update(schema.taskTable)+ .set({ projectId: fixture.destination.id })+ .where(eq(schema.taskTable.id, fixture.task.id));+ await db+ .update(schema.projectTable)+ .set({ workspaceId: fixture.privateWorkspace.workspace.id })+ .where(eq(schema.projectTable.id, fixture.destination.id));+}+async function expectPrivateTask(taskId: string) {+ expect(+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, taskId),+ }),+ ).toMatchObject({+ title: "Private title",+ description: "Private description",+ });+ expect(+ await db.query.labelTable.findMany({+ where: eq(schema.labelTable.taskId, taskId),+ }),+ ).toEqual([]);+ expect(+ await db.query.activityTable.findMany({+ where: eq(schema.activityTable.taskId, taskId),+ }),+ ).toEqual([]);+}+describe("integration task ownership", () => {+ it.each(["gitea", "gitlab"])(+ "%s import cannot modify a moved task through an old link",+ async (type) => {+ const fixture = await setup(type);+ await moveWithoutCleanup(fixture);+ const result = await (+ type === "gitea" ? importGiteaIssues : importGitlabIssues+ )(fixture.project.id);+ expect(result.updated).toBe(0);+ await expectPrivateTask(fixture.task.id);+ },+ );+ it("gitea edits, labels and comments cannot follow stale links", async () => {+ const f = await setup();+ await moveWithoutCleanup(f);+ await handleGiteaIssueEdited(+ {+ action: "edited",+ issue: remoteIssue,+ repository,+ changes: {+ title: { from: "Private title" },+ body: { from: "Private description" },+ },+ },+ f.integration.id,+ );+ await handleGiteaIssueLabeled(+ {+ action: "labeled",+ issue: {+ number: 1,+ labels: [{ name: "priority:high" }, { name: "bug" }],+ },+ label: { name: "bug", color: "ff0000" },+ repository,+ },+ f.integration.id,+ );+ await handleGiteaIssueCommentCreated(+ {+ action: "created",+ issue: { number: 1 },+ repository,+ comment: {+ id: 4,+ body: "Wrong workspace",+ html_url: `${remoteIssue.html_url}#comment-4`,+ user: { login: "author", avatar_url: "" },+ created_at: new Date().toISOString(),+ },+ },+ f.integration.id,+ );+ await expectPrivateTask(f.task.id);+ });+ it("moving a task removes links to its previous project's integration atomically", async () => {+ const f = await setup();+ await moveTask({+ taskId: f.task.id,+ destinationProjectId: f.destination.id,+ currentUserId: f.source.user.id,+ });+ expect(+ await db.query.externalLinkTable.findMany({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ }),+ ).toEqual([]);+ });+ it("moving a project removes legacy links owned by another project", async () => {+ const f = await setup();+ await db+ .update(schema.taskTable)+ .set({ projectId: f.destination.id })+ .where(eq(schema.taskTable.id, f.task.id));+ await moveProject(+ f.destination.id,+ f.source.workspace.id,+ f.privateWorkspace.workspace.id,+ f.source.user.id,+ );+ expect(+ await db.query.externalLinkTable.findMany({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ }),+ ).toEqual([]);+ });+ it("a concurrent task move waits for scoped integration writes to commit", async () => {+ const f = await setup();+ let release!: () => void;+ let started!: () => void;+ const barrier = new Promise<void>((resolve) => {+ release = resolve;+ });+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ const sync = withIntegrationTask(+ f.task.id,+ { ...f.integration, project: f.project },+ async (tx) => {+ started();+ await barrier;+ await tx+ .update(schema.taskTable)+ .set({ title: "Synced before moving" })+ .where(eq(schema.taskTable.id, f.task.id));+ },+ );+ await ready;+ let moved = false;+ const move = moveTask({+ taskId: f.task.id,+ destinationProjectId: f.destination.id,+ currentUserId: f.source.user.id,+ }).then(() => {+ moved = true;+ });+ try {+ await new Promise((resolve) => setTimeout(resolve, 30));+ expect(moved).toBe(false);+ } finally {+ release();+ }+ await Promise.all([sync, move]);+ expect(+ await db.query.taskTable.findFirst({+ where: eq(schema.taskTable.id, f.task.id),+ }),+ ).toMatchObject({+ projectId: f.destination.id,+ title: "Synced before moving",+ });+ expect(+ await db.query.externalLinkTable.findMany({+ where: eq(schema.externalLinkTable.taskId, f.task.id),+ }),+ ).toEqual([]);+ });+});diff --git a/tests/api/gitlab-integration/import-gitlab-issues.test.ts b/tests/api/gitlab-integration/import-gitlab-issues.test.tsindex c75cc9ec3..a5fd23135 100644--- a/tests/api/gitlab-integration/import-gitlab-issues.test.ts+++ b/tests/api/gitlab-integration/import-gitlab-issues.test.ts@@ -103,3 +103,33 @@ describe("importGitlabIssues labels on an already linked task", () => {);});});++// Ownership locking is covered by integration-task-scope.test.ts. These cases+// exercise provider behavior with the transaction's existing database mock.+vi.mock(+ "../../../apps/api/src/plugins/github/services/integration-task-scope",+ async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../../../apps/api/src/plugins/github/services/integration-task-scope")+ >();+ return {+ ...actual,+ withIntegrationTask: async (+ _taskId: string,+ _integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ ) => Promise<unknown>,+ ) => {+ const database = (await import("../../../apps/api/src/database"))+ .default;+ const effects: Array<() => Promise<void>> = [];+ const result = await apply(database, (effect) => effects.push(effect));+ for (const effect of effects) await effect();+ return result;+ },+ };+ },+);diff --git a/tests/api/plugins/gitea/comment-sync.test.ts b/tests/api/plugins/gitea/comment-sync.test.tsindex be86d4211..55925b728 100644--- a/tests/api/plugins/gitea/comment-sync.test.ts+++ b/tests/api/plugins/gitea/comment-sync.test.ts@@ -165,3 +165,33 @@ describe("Gitea comment sync", () => {);});});++// Ownership locking is covered by integration-task-scope.test.ts. These cases+// exercise provider behavior with the transaction's existing database mock.+vi.mock(+ "../../../../apps/api/src/plugins/github/services/integration-task-scope",+ async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../../../../apps/api/src/plugins/github/services/integration-task-scope")+ >();+ return {+ ...actual,+ withIntegrationTask: async (+ _taskId: string,+ _integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ ) => Promise<unknown>,+ ) => {+ const database = (await import("../../../../apps/api/src/database"))+ .default;+ const effects: Array<() => Promise<void>> = [];+ const result = await apply(database, (effect) => effects.push(effect));+ for (const effect of effects) await effect();+ return result;+ },+ };+ },+);diff --git a/tests/api/plugins/github/integration-task-scope.test.ts b/tests/api/plugins/github/integration-task-scope.test.tsnew file mode 100644index 000000000..701540fef--- /dev/null+++ b/tests/api/plugins/github/integration-task-scope.test.ts@@ -0,0 +1,113 @@+import { PgDialect } from "drizzle-orm/pg-core";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++const m = vi.hoisted(() => ({+ locks: vi.fn(),+ predicates: vi.fn(),+ commit: vi.fn(),+}));+vi.mock("../../../../apps/api/src/database", () => ({+ default: {+ transaction: async (apply: (database: unknown) => Promise<unknown>) => {+ const builder = {+ innerJoin: () => builder,+ where: (predicate: unknown) => {+ m.predicates(predicate);+ return builder;+ },+ for: m.locks,+ };+ const result = await apply({ select: () => ({ from: () => builder }) });+ m.commit();+ return result;+ },+ },+}));+const { withIntegrationTask } =+ await import("../../../../apps/api/src/plugins/github/services/integration-task-scope");+const integration = {+ id: "integration",+ projectId: "project",+ project: { workspaceId: "workspace" },+};+beforeEach(() => vi.clearAllMocks());+describe("integration task ownership", () => {+ it("locks and checks the integration project, workspace and task before writing", async () => {+ m.locks+ .mockResolvedValueOnce([{ id: "project" }])+ .mockResolvedValueOnce([{ id: "task" }]);+ const apply = vi.fn().mockResolvedValue("updated");+ expect(await withIntegrationTask("task", integration, apply)).toBe(+ "updated",+ );+ expect(m.locks.mock.calls.map(([mode]) => mode)).toEqual([+ "key share",+ "no key update",+ ]);+ const predicates = m.predicates.mock.calls.map(([predicate]) =>+ new PgDialect().sqlToQuery(predicate),+ );+ expect(predicates[0].params).toEqual([+ "integration",+ "project",+ "workspace",+ ]);+ expect(predicates[1].params).toEqual(["task", "project"]);+ expect(predicates[1].sql).toContain('"task"."project_id"');+ expect(apply).toHaveBeenCalledTimes(1);+ });+ it("ignores a project moved out of the authorized workspace", async () => {+ m.locks.mockResolvedValueOnce([]);+ const apply = vi.fn();+ expect(+ await withIntegrationTask("task", integration, apply),+ ).toBeUndefined();+ expect(apply).not.toHaveBeenCalled();+ expect(m.locks).toHaveBeenCalledTimes(1);+ });+ it("ignores a stale link to a task moved into a different project", async () => {+ m.locks+ .mockResolvedValueOnce([{ id: "project" }])+ .mockResolvedValueOnce([]);+ const apply = vi.fn();+ expect(+ await withIntegrationTask("task", integration, apply),+ ).toBeUndefined();+ expect(apply).not.toHaveBeenCalled();+ });+ it("publishes effects only after committing the scoped writes", async () => {+ m.locks+ .mockResolvedValueOnce([{ id: "project" }])+ .mockResolvedValueOnce([{ id: "task" }]);+ const effect = vi.fn(async () => {+ expect(m.commit).toHaveBeenCalledTimes(1);+ });+ await withIntegrationTask(+ "task",+ integration,+ async (_database, afterCommit) => {+ afterCommit(effect);+ expect(effect).not.toHaveBeenCalled();+ },+ );+ expect(effect).toHaveBeenCalledTimes(1);+ });+ it("does not publish an event when related writes fail", async () => {+ m.locks+ .mockResolvedValueOnce([{ id: "project" }])+ .mockResolvedValueOnce([{ id: "task" }]);+ const effect = vi.fn();+ await expect(+ withIntegrationTask(+ "task",+ integration,+ async (_database, afterCommit) => {+ afterCommit(effect);+ throw new Error("write failed");+ },+ ),+ ).rejects.toThrow("write failed");+ expect(m.commit).not.toHaveBeenCalled();+ expect(effect).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/plugins/github/issue-reopened.test.ts b/tests/api/plugins/github/issue-reopened.test.tsindex 8f360ce5c..5f0373c47 100644--- a/tests/api/plugins/github/issue-reopened.test.ts+++ b/tests/api/plugins/github/issue-reopened.test.ts@@ -68,12 +68,20 @@ it.each(["null", "[]", "42", '"text"', "invalid JSON"])(});await handleIssueReopened(payload);expect(m.find).toHaveBeenCalledWith(payload);- expect(m.update).toHaveBeenCalledWith("first", {- metadata: { state: "open" },- });- expect(m.update).toHaveBeenCalledWith("second", {- metadata: { custom: "keep", state: "open" },- });+ expect(m.update).toHaveBeenCalledWith(+ "first",+ {+ metadata: { state: "open" },+ },+ expect.anything(),+ );+ expect(m.update).toHaveBeenCalledWith(+ "second",+ {+ metadata: { custom: "keep", state: "open" },+ },+ expect.anything(),+ );expect(m.status).toHaveBeenCalledTimes(2);},);@@ -88,3 +96,33 @@ it("retains the Kaneo-origin skip rule for valid metadata", async () => {expect(m.update).not.toHaveBeenCalled();expect(m.status).not.toHaveBeenCalled();});++// Ownership locking is covered by integration-task-scope.test.ts. These cases+// exercise provider behavior with the transaction's existing database mock.+vi.mock(+ "../../../../apps/api/src/plugins/github/services/integration-task-scope",+ async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../../../../apps/api/src/plugins/github/services/integration-task-scope")+ >();+ return {+ ...actual,+ withIntegrationTask: async (+ _taskId: string,+ _integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ ) => Promise<unknown>,+ ) => {+ const database = (await import("../../../../apps/api/src/database"))+ .default;+ const effects: Array<() => Promise<void>> = [];+ const result = await apply(database, (effect) => effects.push(effect));+ for (const effect of effects) await effect();+ return result;+ },+ };+ },+);diff --git a/tests/api/plugins/gitlab/webhooks/issue-reopened.test.ts b/tests/api/plugins/gitlab/webhooks/issue-reopened.test.tsindex 9cc336e5d..0ddaa8a87 100644--- a/tests/api/plugins/gitlab/webhooks/issue-reopened.test.ts+++ b/tests/api/plugins/gitlab/webhooks/issue-reopened.test.ts@@ -103,9 +103,13 @@ describe("handleGitlabIssueReopened failures", () => {await handleGitlabIssueReopened(payload, "integration-1");- expect(mocks.updateExternalLink).toHaveBeenCalledWith("link-1", {- metadata: { state: "opened" },- });+ expect(mocks.updateExternalLink).toHaveBeenCalledWith(+ "link-1",+ {+ metadata: { state: "opened" },+ },+ expect.anything(),+ );expect(mocks.publishEvent).toHaveBeenCalledWith("task.status_changed",expect.objectContaining({@@ -115,3 +119,33 @@ describe("handleGitlabIssueReopened failures", () => {);});});++// Ownership locking is covered by integration-task-scope.test.ts. These cases+// exercise provider behavior with the transaction's existing database mock.+vi.mock(+ "../../../../../apps/api/src/plugins/github/services/integration-task-scope",+ async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../../../../../apps/api/src/plugins/github/services/integration-task-scope")+ >();+ return {+ ...actual,+ withIntegrationTask: async (+ _taskId: string,+ _integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ ) => Promise<unknown>,+ ) => {+ const database = (await import("../../../../../apps/api/src/database"))+ .default;+ const effects: Array<() => Promise<void>> = [];+ const result = await apply(database, (effect) => effects.push(effect));+ for (const effect of effects) await effect();+ return result;+ },+ };+ },+);diff --git a/tests/api/plugins/gitlab/webhooks/issue-updated.test.ts b/tests/api/plugins/gitlab/webhooks/issue-updated.test.tsindex 78a80643a..48f24e179 100644--- a/tests/api/plugins/gitlab/webhooks/issue-updated.test.ts+++ b/tests/api/plugins/gitlab/webhooks/issue-updated.test.ts@@ -170,3 +170,33 @@ describe("handleGitlabIssueUpdated", () => {expect(mocks.taskUpdates).toHaveLength(0);});});++// Ownership locking is covered by integration-task-scope.test.ts. These cases+// exercise provider behavior with the transaction's existing database mock.+vi.mock(+ "../../../../../apps/api/src/plugins/github/services/integration-task-scope",+ async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../../../../../apps/api/src/plugins/github/services/integration-task-scope")+ >();+ return {+ ...actual,+ withIntegrationTask: async (+ _taskId: string,+ _integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ ) => Promise<unknown>,+ ) => {+ const database = (await import("../../../../../apps/api/src/database"))+ .default;+ const effects: Array<() => Promise<void>> = [];+ const result = await apply(database, (effect) => effects.push(effect));+ for (const effect of effects) await effect();+ return result;+ },+ };+ },+);diff --git a/tests/api/plugins/gitlab/webhooks/note-created.test.ts b/tests/api/plugins/gitlab/webhooks/note-created.test.tsindex ec4184a75..9acd51557 100644--- a/tests/api/plugins/gitlab/webhooks/note-created.test.ts+++ b/tests/api/plugins/gitlab/webhooks/note-created.test.ts@@ -121,3 +121,33 @@ describe("handleGitlabNoteCreated", () => {expect(mocks.insertedActivities).toHaveLength(0);});});++// Ownership locking is covered by integration-task-scope.test.ts. These cases+// exercise provider behavior with the transaction's existing database mock.+vi.mock(+ "../../../../../apps/api/src/plugins/github/services/integration-task-scope",+ async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("../../../../../apps/api/src/plugins/github/services/integration-task-scope")+ >();+ return {+ ...actual,+ withIntegrationTask: async (+ _taskId: string,+ _integration: unknown,+ apply: (+ database: unknown,+ afterCommit: (effect: () => Promise<void>) => void,+ ) => Promise<unknown>,+ ) => {+ const database = (await import("../../../../../apps/api/src/database"))+ .default;+ const effects: Array<() => Promise<void>> = [];+ const result = await apply(database, (effect) => effects.push(effect));+ for (const effect of effects) await effect();+ return result;+ },+ };+ },+);