⚡ 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): resolve PRs through linked issue identities (#1739)
Yilmer Daniel Avila Villarrealed612a036ba7
diff --git a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts b/apps/api/src/gitea-integration/controllers/import-gitea-issues.tsindex 40440903d..68da790ef 100644--- a/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts+++ b/apps/api/src/gitea-integration/controllers/import-gitea-issues.ts@@ -10,7 +10,6 @@ import {} from "../../database/schema";import { publishEvent } from "../../events";import type { GiteaConfig } from "../../plugins/gitea/config";-import { extractTaskNumberGitea } from "../../plugins/gitea/utils/branch-matcher";import {createGiteaClient,type GiteaIssue,@@ -21,7 +20,7 @@ import {createExternalLink,findExternalLink,} from "../../plugins/github/services/link-manager";-import { findTaskByNumber } from "../../plugins/github/services/task-service";+import { resolvePullRequestTask } from "../../plugins/github/services/resolve-pull-request-task";import {extractIssuePriority,extractIssueStatus,@@ -446,33 +445,22 @@ async function linkPullRequestToTask(projectSlug: string,config: GiteaConfig,): Promise<void> {- const taskNumber = extractTaskNumberGitea(- pr.head.ref,- pr.title,- pr.body ?? undefined,- config,- projectSlug,- );-- if (!taskNumber) {- return;- }-- const task = await findTaskByNumber(projectId, taskNumber);-- if (!task) {- return;- }-const existingLink = await findExternalLink(integrationId,"pull_request",pr.number.toString(),);+ if (existingLink) return;- if (existingLink) {- return;- }+ const task = await resolvePullRequestTask({+ integrationId,+ projectId,+ projectSlug,+ config,+ repositoryUrl: `${config.baseUrl.replace(/\/$/, "")}/${config.repositoryOwner}/${config.repositoryName}`,+ pullRequest: pr,+ });+ if (!task) return;await createExternalLink({taskId: task.id,diff --git a/apps/api/src/github-integration/controllers/import-issues.ts b/apps/api/src/github-integration/controllers/import-issues.tsindex b12bd4f49..aefebadf6 100644--- a/apps/api/src/github-integration/controllers/import-issues.ts+++ b/apps/api/src/github-integration/controllers/import-issues.ts@@ -16,7 +16,7 @@ import {type GitHubConfig,hasVerifiedGitHubBinding,} from "../../plugins/github/config";-import { extractTaskNumber } from "../../plugins/github/utils/branch-matcher";+import { resolvePullRequestTask } from "../../plugins/github/services/resolve-pull-request-task";import {extractIssuePriority,extractIssueStatus,@@ -524,23 +524,20 @@ async function linkPull(project: typeof projectTable.$inferSelect,config: GitHubConfig,) {- const number = extractTaskNumber(- pull.headRefName,- pull.title,- pull.body ?? undefined,+ if (await findLink(tx, integrationId, "pull_request", pull.number)) return;+ const task = await resolvePullRequestTask({+ integrationId,+ projectId: project.id,+ projectSlug: project.slug,config,- project.slug,- );- if (- !number ||- (await findLink(tx, integrationId, "pull_request", pull.number))- )- return;- const task = await tx.query.taskTable.findFirst({- where: and(- eq(taskTable.projectId, project.id),- eq(taskTable.number, number),- ),+ repositoryUrl: `https://github.com/${config.repositoryOwner}/${config.repositoryName}`,+ pullRequest: {+ number: pull.number,+ title: pull.title,+ body: pull.body,+ head: { ref: pull.headRefName },+ },+ database: tx,});if (!task) return;await tx.insert(externalLinkTable).values({diff --git a/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts b/apps/api/src/plugins/gitea/webhooks/pull-request-opened.tsindex 94e6a4414..ff28c1a56 100644--- a/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts+++ b/apps/api/src/plugins/gitea/webhooks/pull-request-opened.ts@@ -3,8 +3,8 @@ import {createExternalLink,findExternalLink,} from "../../github/services/link-manager";+import { resolvePullRequestTask } from "../../github/services/resolve-pull-request-task";import {- findTaskByNumber,isTaskInFinalState,updateTaskStatus,} from "../../github/services/task-service";@@ -13,7 +13,6 @@ import {findAllIntegrationsByGiteaRepo,repoOwnerLogin,} from "../services/integration-lookup";-import { extractTaskNumberGitea } from "../utils/branch-matcher";import { resolveTargetStatus } from "../utils/resolve-column";import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";@@ -56,6 +55,7 @@ export async function handleGiteaPullRequestOpened(integrationId,);+ const candidates = [];for (const integration of integrations) {if (!integration.project) {continue;@@ -71,80 +71,70 @@ export async function handleGiteaPullRequestOpened(});continue;}- const projectSlug = integration.project.slug;- const branchName = pull_request.head.ref;-- const taskNumber = extractTaskNumberGitea(- branchName,- pull_request.title,- pull_request.body ?? undefined,- config,- projectSlug,- );-- if (!taskNumber) {- continue;- }-- const task = await findTaskByNumber(integration.projectId, taskNumber);-- if (!task) {- continue;- }-const existingLink = await findExternalLink(integration.id,"pull_request",pull_request.number.toString(),);+ if (existingLink) return;- if (existingLink) {- continue;- }-- await createExternalLink({- taskId: task.id,+ const task = await resolvePullRequestTask({integrationId: integration.id,- resourceType: "pull_request",- externalId: pull_request.number.toString(),- url: pull_request.html_url,- title: pull_request.title,- metadata: {- state: pull_request.state,- draft: pull_request.draft,- merged: pull_request.merged,- branch: branchName,- author: pull_request.user?.login ?? pull_request.user?.username,- },+ projectId: integration.projectId,+ projectSlug: integration.project.slug,+ config,+ repositoryUrl: repository.html_url,+ pullRequest: pull_request,});+ if (task) candidates.push({ integration, config, task });+ }- const targetStatus = await resolveTargetStatus(- integration.projectId,- "pr_opened",- config.statusTransitions?.onPROpen || "in-review",- );-- const isTaskFinal = await isTaskInFinalState(task);+ const candidate = candidates[0];+ if (candidates.length !== 1 || !candidate) return;+ const { integration, config, task } = candidate;+ if (integrationId && integration.id !== integrationId) return;+ const branchName = pull_request.head.ref;++ await createExternalLink({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "pull_request",+ externalId: pull_request.number.toString(),+ url: pull_request.html_url,+ title: pull_request.title,+ metadata: {+ state: pull_request.state,+ draft: pull_request.draft,+ merged: pull_request.merged,+ branch: branchName,+ author: pull_request.user?.login ?? pull_request.user?.username,+ },+ });++ const targetStatus = await resolveTargetStatus(+ integration.projectId,+ "pr_opened",+ config.statusTransitions?.onPROpen || "in-review",+ );- if (task.status !== targetStatus && !isTaskFinal) {- const statusResult = await updateTaskStatus(task.id, targetStatus);- if (- statusResult.applied &&- statusResult.before.status !== statusResult.after.status- ) {- await publishEvent("task.status_changed", {- taskId: statusResult.after.id,- projectId: statusResult.after.projectId,- userId: null,- oldStatus: statusResult.before.status,- newStatus: statusResult.after.status,- title: statusResult.after.title,- assigneeId: statusResult.after.userId,- type: "status_changed",- });- }+ const isTaskFinal = await isTaskInFinalState(task);++ if (task.status !== targetStatus && !isTaskFinal) {+ const statusResult = await updateTaskStatus(task.id, targetStatus);+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ await publishEvent("task.status_changed", {+ taskId: statusResult.after.id,+ projectId: statusResult.after.projectId,+ userId: null,+ oldStatus: statusResult.before.status,+ newStatus: statusResult.after.status,+ title: statusResult.after.title,+ assigneeId: statusResult.after.userId,+ type: "status_changed",+ });}-- return;}}diff --git a/apps/api/src/plugins/github/services/resolve-pull-request-task.ts b/apps/api/src/plugins/github/services/resolve-pull-request-task.tsnew file mode 100644index 000000000..bcf55e46e--- /dev/null+++ b/apps/api/src/plugins/github/services/resolve-pull-request-task.ts@@ -0,0 +1,68 @@+import { and, eq, inArray } from "drizzle-orm";+import db from "../../../database";+import { externalLinkTable, taskTable } from "../../../database/schema";+import type { GitHubConfig } from "../config";+import { extractTaskNumber } from "../utils/branch-matcher";+import { extractIssueReferences } from "../utils/issue-references";++export async function resolvePullRequestTask({+ integrationId,+ projectId,+ projectSlug,+ config,+ repositoryUrl,+ pullRequest,+ database = db,+}: {+ database?: Pick<typeof db, "selectDistinct" | "query">;+ integrationId: string;+ projectId: string;+ projectSlug: string;+ config: Pick<GitHubConfig, "branchPattern" | "customBranchRegex">;+ repositoryUrl: string;+ pullRequest: {+ number: number;+ title: string;+ body: string | null;+ head: { ref: string };+ };+}) {+ const taskNumber = extractTaskNumber(+ pullRequest.head.ref,+ pullRequest.title,+ pullRequest.body ?? undefined,+ config,+ projectSlug,+ );+ if (taskNumber !== null) {+ return database.query.taskTable.findFirst({+ where: and(+ eq(taskTable.projectId, projectId),+ eq(taskTable.number, taskNumber),+ ),+ });+ }++ const issueNumbers = extractIssueReferences(+ pullRequest.title,+ pullRequest.body,+ repositoryUrl,+ );+ if (issueNumbers.length === 0) return;++ const matches = await database+ .selectDistinct({ task: taskTable })+ .from(externalLinkTable)+ .innerJoin(taskTable, eq(taskTable.id, externalLinkTable.taskId))+ .where(+ and(+ eq(externalLinkTable.integrationId, integrationId),+ eq(externalLinkTable.resourceType, "issue"),+ inArray(externalLinkTable.externalId, issueNumbers),+ eq(taskTable.projectId, projectId),+ ),+ )+ .limit(2);++ return matches.length === 1 ? matches[0]?.task : undefined;+}diff --git a/apps/api/src/plugins/github/utils/branch-matcher.ts b/apps/api/src/plugins/github/utils/branch-matcher.tsindex 6a2d9f63a..71ff8ee30 100644--- a/apps/api/src/plugins/github/utils/branch-matcher.ts+++ b/apps/api/src/plugins/github/utils/branch-matcher.ts@@ -40,7 +40,7 @@ export function createBranchRegex(export function extractTaskNumberFromBranch(branchName: string,- config: GitHubConfig,+ config: Pick<GitHubConfig, "branchPattern" | "customBranchRegex">,projectSlug: string,): number | null {if (config.customBranchRegex) {@@ -69,50 +69,41 @@ export function extractTaskNumberFromBranch(return null;}-export function extractTaskNumberFromPRTitle(title: string): number | null {- const patterns = [- /\[(\d+)\]/,- /#(\d+)/,- /\((\d+)\)/,- /^(\d+)[:\-\s]/,- /task[:\-\s]*(\d+)/i,- ];-- for (const pattern of patterns) {- const match = title.match(pattern);- if (match?.[1]) {- const num = Number.parseInt(match[1], 10);- if (!Number.isNaN(num)) return num;- }+function extractExplicitTaskNumber(+ text: string,+ projectSlug?: string,+): number | null {+ if (projectSlug) {+ const slug = projectSlug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const key = text.match(+ new RegExp(`(?:^|[^\\w-])${slug}-(\\d+)(?=$|[^\\w])`, "i"),+ );+ if (key?.[1]) return Number.parseInt(key[1], 10);}- return null;+ const task = text.match(/\btask[:\-\s#]+(\d+)\b/i);+ return task?.[1] ? Number.parseInt(task[1], 10) : null;}-export function extractTaskNumberFromPRBody(body: string): number | null {- const patterns = [- /task[:\-\s#]*(\d+)/i,- /closes[:\-\s#]*(\d+)/i,- /fixes[:\-\s#]*(\d+)/i,- /resolves[:\-\s#]*(\d+)/i,- ];-- for (const pattern of patterns) {- const match = body.match(pattern);- if (match?.[1]) {- const num = Number.parseInt(match[1], 10);- if (!Number.isNaN(num)) return num;- }- }+export function extractTaskNumberFromPRTitle(+ title: string,+ projectSlug?: string,+): number | null {+ return extractExplicitTaskNumber(title, projectSlug);+}- return null;+export function extractTaskNumberFromPRBody(+ body: string,+ projectSlug?: string,+): number | null {+ return extractExplicitTaskNumber(body, projectSlug);}export function extractTaskNumber(branchName: string,prTitle: string | undefined,prBody: string | undefined,- config: GitHubConfig,+ config: Pick<GitHubConfig, "branchPattern" | "customBranchRegex">,projectSlug: string,): number | null {const fromBranch = extractTaskNumberFromBranch(@@ -123,12 +114,12 @@ export function extractTaskNumber(if (fromBranch !== null) return fromBranch;if (prTitle) {- const fromTitle = extractTaskNumberFromPRTitle(prTitle);+ const fromTitle = extractTaskNumberFromPRTitle(prTitle, projectSlug);if (fromTitle !== null) return fromTitle;}if (prBody) {- const fromBody = extractTaskNumberFromPRBody(prBody);+ const fromBody = extractTaskNumberFromPRBody(prBody, projectSlug);if (fromBody !== null) return fromBody;}diff --git a/apps/api/src/plugins/github/utils/issue-references.ts b/apps/api/src/plugins/github/utils/issue-references.tsnew file mode 100644index 000000000..59a83f2e9--- /dev/null+++ b/apps/api/src/plugins/github/utils/issue-references.ts@@ -0,0 +1,53 @@+function issueNumber(reference: string, repository: URL): string | null {+ const short = reference.match(/^(?:([\w.-]+\/[\w.-]+))?#(\d+)$/);+ if (short) {+ const repositoryName = repository.pathname+ .split("/")+ .filter(Boolean)+ .slice(-2)+ .join("/");+ if (short[1] && short[1].toLowerCase() !== repositoryName.toLowerCase())+ return null;+ return short[2] ?? null;+ }++ try {+ const url = new URL(reference.replace(/[.,;:)]+$/, ""));+ const repositoryPath = repository.pathname.replace(/\/$/, "");+ if (url.origin !== repository.origin) return null;+ const prefix = `${repositoryPath}/issues/`;+ if (!url.pathname.toLowerCase().startsWith(prefix.toLowerCase()))+ return null;+ const number = url.pathname.slice(prefix.length);+ return /^\d+$/.test(number) ? number : null;+ } catch {+ return null;+ }+}++export function extractIssueReferences(+ title: string,+ body: string | null,+ repositoryUrl: string,+): string[] {+ const repository = new URL(repositoryUrl);+ const reference = "(?:https?://[^\\s<>]+|(?:[\\w.-]+/[\\w.-]+)?#\\d+)";+ const titlePattern = new RegExp(+ `(?:^|[\\s(\\[])(${reference})(?=$|[\\s)\\].,;:])`,+ "gi",+ );+ const bodyPattern = new RegExp(+ `\\b(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)\\b\\s*:?\\s*(${reference})(?=$|[\\s)\\].,;:])`,+ "gi",+ );+ const numbers = new Set<string>();+ for (const match of [+ ...title.matchAll(titlePattern),+ ...(body ?? "").matchAll(bodyPattern),+ ]) {+ if (!match[1]) continue;+ const number = issueNumber(match[1], repository);+ if (number !== null) numbers.add(number);+ }+ return [...numbers];+}diff --git a/apps/api/src/plugins/github/webhooks/pull-request-opened.ts b/apps/api/src/plugins/github/webhooks/pull-request-opened.tsindex ebfcd2052..5534e164f 100644--- a/apps/api/src/plugins/github/webhooks/pull-request-opened.ts+++ b/apps/api/src/plugins/github/webhooks/pull-request-opened.ts@@ -1,13 +1,12 @@import { publishEvent } from "../../../events";import type { GitHubConfig } from "../config";import { createExternalLink, findExternalLink } from "../services/link-manager";+import { resolvePullRequestTask } from "../services/resolve-pull-request-task";import {findAllIntegrationsByRepo,- findTaskByNumber,isTaskInFinalState,updateTaskStatus,} from "../services/task-service";-import { extractTaskNumber } from "../utils/branch-matcher";import { resolveTargetStatus } from "../utils/resolve-column";type PROpenedPayload = {@@ -34,90 +33,80 @@ type PROpenedPayload = {};export async function handlePullRequestOpened(payload: PROpenedPayload) {- const { pull_request } = payload;+ const { pull_request, repository } = payload;const integrations = await findAllIntegrationsByRepo(payload);+ const candidates = [];for (const integration of integrations) {if (!integration.project) {continue;}const config = JSON.parse(integration.config) as GitHubConfig;- const projectSlug = integration.project.slug;- const branchName = pull_request.head.ref;-- const taskNumber = extractTaskNumber(- branchName,- pull_request.title,- pull_request.body ?? undefined,- config,- projectSlug,- );-- if (taskNumber === null) {- continue;- }-- const task = await findTaskByNumber(integration.projectId, taskNumber);-- if (!task) {- continue;- }-const existingLink = await findExternalLink(integration.id,"pull_request",pull_request.number.toString(),);+ if (existingLink) return;- if (existingLink) {- continue;- }-- await createExternalLink({- taskId: task.id,+ const task = await resolvePullRequestTask({integrationId: integration.id,- resourceType: "pull_request",- externalId: pull_request.number.toString(),- url: pull_request.html_url,- title: pull_request.title,- metadata: {- state: pull_request.state,- draft: pull_request.draft,- merged: pull_request.merged,- branch: branchName,- author: pull_request.user?.login,- },+ projectId: integration.projectId,+ projectSlug: integration.project.slug,+ config,+ repositoryUrl: `https://github.com/${repository.owner.login}/${repository.name}`,+ pullRequest: pull_request,});+ if (task) candidates.push({ integration, config, task });+ }- const targetStatus = await resolveTargetStatus(- integration.projectId,- "pr_opened",- config.statusTransitions?.onPROpen || "in-review",- );-- const isTaskFinal = await isTaskInFinalState(task);-- if (task.status !== targetStatus && !isTaskFinal) {- const statusResult = await updateTaskStatus(task.id, targetStatus);- if (- statusResult.applied &&- statusResult.before.status !== statusResult.after.status- ) {- await publishEvent("task.status_changed", {- taskId: statusResult.after.id,- projectId: statusResult.after.projectId,- userId: null,- oldStatus: statusResult.before.status,- newStatus: statusResult.after.status,- title: statusResult.after.title,- assigneeId: statusResult.after.userId,- type: "status_changed",- });- }+ const candidate = candidates[0];+ if (candidates.length !== 1 || !candidate) return;+ const { integration, config, task } = candidate;+ const branchName = pull_request.head.ref;++ await createExternalLink({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "pull_request",+ externalId: pull_request.number.toString(),+ url: pull_request.html_url,+ title: pull_request.title,+ metadata: {+ state: pull_request.state,+ draft: pull_request.draft,+ merged: pull_request.merged,+ branch: branchName,+ author: pull_request.user?.login,+ },+ });++ const targetStatus = await resolveTargetStatus(+ integration.projectId,+ "pr_opened",+ config.statusTransitions?.onPROpen || "in-review",+ );++ const isTaskFinal = await isTaskInFinalState(task);++ if (task.status !== targetStatus && !isTaskFinal) {+ const statusResult = await updateTaskStatus(task.id, targetStatus);+ if (+ statusResult.applied &&+ statusResult.before.status !== statusResult.after.status+ ) {+ await publishEvent("task.status_changed", {+ taskId: statusResult.after.id,+ projectId: statusResult.after.projectId,+ userId: null,+ oldStatus: statusResult.before.status,+ newStatus: statusResult.after.status,+ title: statusResult.after.title,+ assigneeId: statusResult.after.userId,+ type: "status_changed",+ });}-- return;}}diff --git a/apps/docs/core/integrations/github/configuration.mdx b/apps/docs/core/integrations/github/configuration.mdxindex 66fc0b6af..8ba8bb208 100644--- a/apps/docs/core/integrations/github/configuration.mdx+++ b/apps/docs/core/integrations/github/configuration.mdx@@ -257,6 +257,18 @@ You can also provide a custom regex pattern for more complex matching.The `{slug}` variable is your project's slug (case-insensitive), `{number}` is the task number, and `{title}` is an optional slug of the task title.</Tip>+### Pull Request Task References++Kaneo checks the configured branch pattern first, then explicit task references in the PR title and body. Use your project key, such as `PROJ-42` or `fix(PROJ-42): correct the link`, or an explicit `task: 42` marker. Task markers require a separator after `task`; words such as `task42` do not identify a task.++Issue references use the remote repository's numbering. A title containing `#61` or a body containing `Closes #61` resolves through the issue link recorded by this integration. If GitHub issue 61 is linked to Kaneo task `PROJ-42`, the PR belongs to `PROJ-42`, even if `PROJ-61` also exists. Same-repository `owner/repo#61` references and issue URLs are also supported. References to another repository are ignored.++Without an explicit task reference, unmapped issues do not create PR associations. References that map to multiple tasks within the integration are skipped. Repeated issue links to the same task are accepted. Bare numeric title shortcuts such as `[42]`, `(42)`, or `42: ...` are not task identifiers; use the project key instead.++GitHub webhooks also skip conflicting candidates or an existing PR association across projects connected to the repository. Signed Gitea webhooks resolve only within their authenticated integration; another project's mappings or PR links do not block that integration. Direct Gitea handler calls without an integration ID use the repository-wide checks. Imports for both providers remain scoped to the selected project.++These rules apply to new associations from webhooks and imports. Existing PR associations within the applicable scope are preserved; historical incorrect links require separate correction.+### Status Transition ConfigurationCustomize when tasks automatically change status:diff --git a/tests/api-integration/pull-request-task-links.test.ts b/tests/api-integration/pull-request-task-links.test.tsnew file mode 100644index 000000000..9332f4809--- /dev/null+++ b/tests/api-integration/pull-request-task-links.test.ts@@ -0,0 +1,516 @@+import { createHmac } from "node:crypto";+import { and, eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { importGiteaIssues } from "../../apps/api/src/gitea-integration/controllers/import-gitea-issues";+import { importIssues } from "../../apps/api/src/github-integration/controllers/import-issues";+import { handleGiteaWebhookRequest } from "../../apps/api/src/plugins/gitea/webhook-handler";+import { handleGiteaPullRequestClosed } from "../../apps/api/src/plugins/gitea/webhooks/pull-request-closed";+import { handleGiteaPullRequestOpened } from "../../apps/api/src/plugins/gitea/webhooks/pull-request-opened";+import { resolvePullRequestTask } from "../../apps/api/src/plugins/github/services/resolve-pull-request-task";+import { handlePullRequestClosed } from "../../apps/api/src/plugins/github/webhooks/pull-request-closed";+import { handlePullRequestOpened } from "../../apps/api/src/plugins/github/webhooks/pull-request-opened";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++const remote = vi.hoisted(() => ({ listIssues: vi.fn(), listPulls: vi.fn() }));+vi.mock("../../apps/api/src/plugins/github/utils/github-app", () => ({+ getVerifiedInstallationOctokit: async () => ({+ graphql: async (query: string) => ({+ repository: {+ databaseId: 2,+ ...(query.includes("query ImportIssues(")+ ? {+ issues: {+ totalCount: 0,+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: [],+ },+ }+ : {+ pullRequests: {+ totalCount: (await remote.listPulls()).length,+ pageInfo: { hasNextPage: false, endCursor: null },+ nodes: (await remote.listPulls()).map(+ (pull: {+ number: number;+ title: string;+ body: string | null;+ html_url: string;+ state: string;+ head: { ref: string };+ }) => ({+ number: pull.number,+ title: pull.title,+ body: pull.body,+ url: pull.html_url,+ state: pull.state.toUpperCase(),+ headRefName: pull.head.ref,+ createdAt: "2020-01-01T00:00:00Z",+ author: null,+ }),+ ),+ },+ }),+ },+ }),+ }),+}));+vi.mock("../../apps/api/src/plugins/gitea/utils/gitea-api", () => ({+ createGiteaClient: () => ({+ listIssues: remote.listIssues,+ listPulls: remote.listPulls,+ }),+}));++async function createFixture(+ provider: "github" | "gitea",+ slug = "KAN",+ repo = "repo",+) {+ const member = await createWorkspaceMember();+ const { project, columns } = await createProjectFixture({+ workspaceId: member.workspace.id,+ slug,+ });+ const [integration] = await db+ .insert(schema.integrationTable)+ .values({+ projectId: project.id,+ type: provider,+ isActive: true,+ config: JSON.stringify({+ repositoryOwner: "acme",+ repositoryName: repo,+ installationId: 1,+ repositoryId: repo === "repo" ? 2 : 3,+ verifiedGithubAccountId: "4",+ verifiedByUserId: member.user.id,+ accessToken: "test-only-token",+ webhookSecret: "test-only-webhook-secret",+ baseUrl: "https://git.example.com",+ branchPattern: "{slug}-{number}",+ }),+ })+ .returning();+ const tasks = await db+ .insert(schema.taskTable)+ .values(+ [42, 61].map((number) => ({+ projectId: project.id,+ number,+ title: `Task ${number}`,+ status: "to-do",+ columnId: columns.todo.id,+ priority: "medium",+ position: number,+ })),+ )+ .returning();+ return {+ project,+ columns,+ integration,+ intended: tasks[0],+ unrelated: tasks[1],+ };+}++describe.each(["github", "gitea"] as const)(+ "%s pull request task identity",+ (provider) => {+ let fixture: Awaited<ReturnType<typeof createFixture>>;+ const repositoryUrl =+ provider === "github"+ ? "https://github.com/acme/repo"+ : "https://git.example.com/acme/repo";+ const payload = (+ title = "Copy message text",+ body = "Closes #61",+ branch = "unmatched-branch",+ ) => ({+ action: "opened",+ installation: { id: 1 },+ repository: {+ id: 2,+ owner: { login: "acme" },+ name: "repo",+ html_url: repositoryUrl,+ },+ pull_request: {+ number: 109,+ title,+ body,+ head: { ref: branch },+ html_url: `${repositoryUrl}/pull/109`,+ state: "open",+ draft: false,+ merged: false,+ user: { login: "octocat" },+ },+ });+ const runImport = async () => {+ if (provider === "gitea") {+ const result = await importGiteaIssues(fixture.project.id);+ expect(result.errors).toBeUndefined();+ return;+ }+ let result = await importIssues(fixture.project.id);+ for (let attempt = 0; result.pending && attempt < 10; attempt++) {+ result = await importIssues(fixture.project.id, result.runId);+ }+ expect(result.pending).toBe(false);+ };+ const open = (event = payload()) =>+ provider === "github"+ ? handlePullRequestOpened(event)+ : handleGiteaPullRequestOpened(event, fixture.integration.id);+ const openUnscoped = (event = payload()) =>+ provider === "github"+ ? handlePullRequestOpened(event)+ : handleGiteaPullRequestOpened(event);+ const openSigned = async () => {+ const body = JSON.stringify(payload());+ const signature = createHmac("sha256", "test-only-webhook-secret")+ .update(body)+ .digest("hex");+ expect(+ await handleGiteaWebhookRequest(+ fixture.integration.id,+ body,+ signature,+ "pull_request",+ ),+ ).toEqual({ success: true });+ };+ const linkIssue = (+ taskId: string,+ externalId = "61",+ integrationId = fixture.integration.id,+ resourceType = "issue",+ ) =>+ db.insert(schema.externalLinkTable).values({+ taskId,+ integrationId,+ resourceType,+ externalId,+ url: `${repositoryUrl}/issues/${externalId}`,+ });+ const links = () =>+ db.query.externalLinkTable.findMany({+ where: and(+ eq(schema.externalLinkTable.resourceType, "pull_request"),+ eq(schema.externalLinkTable.externalId, "109"),+ ),+ });+ const task = (id: string) =>+ db.query.taskTable.findFirst({ where: eq(schema.taskTable.id, id) });+ const expectUnchanged = async () => {+ expect(await links()).toHaveLength(0);+ expect((await task(fixture.intended.id))?.status).toBe("to-do");+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ };++ beforeEach(async () => {+ await resetTestDatabase();+ fixture = await createFixture(provider);+ vi.clearAllMocks();+ remote.listIssues.mockResolvedValue([]);+ remote.listPulls.mockResolvedValue([payload().pull_request]);+ });++ it("links remote issue 61 to task 42 without advancing local task 61", async () => {+ await linkIssue(fixture.intended.id);+ await open();+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ expect(await task(fixture.intended.id)).toMatchObject({+ status: "in-review",+ columnId: fixture.columns.inReview.id,+ });+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ });++ it("checks for an existing PR link only once per integration", async () => {+ await linkIssue(fixture.intended.id);+ const lookup = vi.spyOn(db.query.externalLinkTable, "findFirst");+ await open();+ expect(lookup).toHaveBeenCalledTimes(1);+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ });++ it("does not let a separatorless task label override the linked issue", async () => {+ await linkIssue(fixture.intended.id);+ await open(payload("Refactor task61 renderer"));+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ });++ it("merges the mapped task without completing the same-numbered local task", async () => {+ await linkIssue(fixture.intended.id);+ await open();+ const event = payload();+ const closed = {+ ...event,+ action: "closed",+ pull_request: {+ ...event.pull_request,+ state: "closed",+ merged: true,+ merged_at: "2026-01-01T00:00:00Z",+ },+ };+ if (provider === "github") await handlePullRequestClosed(closed);+ else await handleGiteaPullRequestClosed(closed);+ expect((await task(fixture.intended.id))?.status).toBe("done");+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ });++ it("imports a PR using the remote issue mapping", async () => {+ await linkIssue(fixture.intended.id);+ await runImport();+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ });++ it("imports an explicit task key without an issue link", async () => {+ remote.listPulls.mockResolvedValue([+ payload("KAN-42: Fix copy", "").pull_request,+ ]);+ await runImport();+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ });++ it("resolves issue links written inside the import transaction", async () => {+ await db.transaction(async (tx) => {+ await tx.insert(schema.externalLinkTable).values({+ taskId: fixture.intended.id,+ integrationId: fixture.integration.id,+ resourceType: "issue",+ externalId: "61",+ url: `${repositoryUrl}/issues/61`,+ });+ const resolved = await resolvePullRequestTask({+ integrationId: fixture.integration.id,+ projectId: fixture.project.id,+ projectSlug: fixture.project.slug,+ config: { branchPattern: "{slug}-{number}" },+ repositoryUrl,+ pullRequest: payload().pull_request,+ database: tx,+ });+ expect(resolved?.id).toBe(fixture.intended.id);+ });+ });++ it("does not import a PR without a matching issue link", async () => {+ await runImport();+ await expectUnchanged();+ });++ it("preserves an existing PR association during import", async () => {+ await linkIssue(fixture.intended.id);+ await linkIssue(+ fixture.unrelated.id,+ "109",+ fixture.integration.id,+ "pull_request",+ );+ await runImport();+ expect(await links()).toMatchObject([{ taskId: fixture.unrelated.id }]);+ expect((await task(fixture.intended.id))?.status).toBe("to-do");+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ });++ it("accepts duplicate issue links pointing to the same task", async () => {+ await linkIssue(fixture.intended.id);+ await linkIssue(fixture.intended.id);+ await open();+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ });++ it("recognizes a project key in a conventional commit title", async () => {+ await open(+ payload(+ "feat(KAN-42): copy message text",+ "Closes #61",+ "codex/kan-42-copy-message-text",+ ),+ );+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ });++ it("does not infer a local task from an unmapped remote issue", async () => {+ await open();+ await expectUnchanged();+ });++ it("does not use an issue link from another integration", async () => {+ const other = await createFixture(provider, "OTHER", "other-repo");+ await linkIssue(fixture.intended.id, "61", other.integration.id);+ await open();+ await expectUnchanged();+ });++ it("does not use a branch link as an issue link", async () => {+ await linkIssue(+ fixture.intended.id,+ "61",+ fixture.integration.id,+ "branch",+ );+ await open();+ await expectUnchanged();+ });++ it("does not use an issue link whose task belongs to another project", async () => {+ const other = await createFixture(provider, "OTHER", "other-repo");+ await linkIssue(other.intended.id);+ await open();+ await expectUnchanged();+ expect((await task(other.intended.id))?.status).toBe("to-do");+ });++ it("skips conflicting duplicate issue links", async () => {+ await linkIssue(fixture.intended.id);+ await linkIssue(fixture.unrelated.id);+ await open();+ await expectUnchanged();+ });++ it("skips closing references mapped to different tasks", async () => {+ await linkIssue(fixture.intended.id);+ await linkIssue(fixture.unrelated.id, "88");+ await open(payload("Copy message text", "Closes #61, fixes #88"));+ await expectUnchanged();+ });++ it("accepts multiple issue links to the same task", async () => {+ await linkIssue(fixture.intended.id);+ await linkIssue(fixture.intended.id, "88");+ await open(payload("Copy message text", "Closes #61, fixes #88"));+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ });++ it("preserves explicit branch precedence over an issue reference", async () => {+ await linkIssue(fixture.unrelated.id);+ await open(payload("Copy message text", "Closes #61", "kan-42-copy"));+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ });++ it("preserves an existing PR association on a reopened delivery", async () => {+ await linkIssue(+ fixture.unrelated.id,+ "109",+ fixture.integration.id,+ "pull_request",+ );+ await open({+ ...payload("fix(KAN-42): copy message text"),+ action: "reopened",+ });+ expect(await links()).toMatchObject([{ taskId: fixture.unrelated.id }]);+ expect((await task(fixture.intended.id))?.status).toBe("to-do");+ expect((await task(fixture.unrelated.id))?.status).toBe("to-do");+ });++ it("links a final task without moving it back to review", async () => {+ await linkIssue(fixture.intended.id);+ await db+ .update(schema.taskTable)+ .set({ status: "done", columnId: fixture.columns.done.id })+ .where(eq(schema.taskTable.id, fixture.intended.id));+ await open();+ expect(await links()).toMatchObject([{ taskId: fixture.intended.id }]);+ expect((await task(fixture.intended.id))?.status).toBe("done");+ });++ it("skips ambiguous candidates across repository integrations for an unscoped delivery", async () => {+ const other = await createFixture(provider, "OTHER");+ await linkIssue(fixture.intended.id);+ await linkIssue(other.intended.id, "61", other.integration.id);+ await openUnscoped();+ await expectUnchanged();+ expect((await task(other.intended.id))?.status).toBe("to-do");+ });++ it("preserves an existing PR association in another integration for an unscoped delivery", async () => {+ const other = await createFixture(provider, "OTHER");+ await linkIssue(fixture.intended.id);+ await linkIssue(+ other.intended.id,+ "109",+ other.integration.id,+ "pull_request",+ );+ await openUnscoped();+ expect(await links()).toMatchObject([{ taskId: other.intended.id }]);+ expect((await task(fixture.intended.id))?.status).toBe("to-do");+ expect((await task(other.intended.id))?.status).toBe("to-do");+ });++ if (provider === "gitea") {+ it("resolves a signed delivery within its integration despite another project's candidate", async () => {+ const other = await createFixture(provider, "OTHER");+ await linkIssue(fixture.intended.id);+ await linkIssue(other.intended.id, "61", other.integration.id);+ await openSigned();+ expect(await links()).toMatchObject([+ {+ taskId: fixture.intended.id,+ integrationId: fixture.integration.id,+ },+ ]);+ expect((await task(fixture.intended.id))?.status).toBe("in-review");+ expect((await task(other.intended.id))?.status).toBe("to-do");+ });++ it("does not let another integration's PR link block a signed delivery", async () => {+ const other = await createFixture(provider, "OTHER");+ await linkIssue(fixture.intended.id);+ await linkIssue(+ other.intended.id,+ "109",+ other.integration.id,+ "pull_request",+ );+ await openSigned();+ expect((await links()).map((link) => link.taskId).sort()).toEqual(+ [fixture.intended.id, other.intended.id].sort(),+ );+ expect((await task(fixture.intended.id))?.status).toBe("in-review");+ expect((await task(other.intended.id))?.status).toBe("to-do");+ });++ it("does not mutate another integration with the signed integration's authority", async () => {+ const other = await createFixture(provider, "OTHER");+ await linkIssue(other.intended.id, "61", other.integration.id);+ await open();+ await expectUnchanged();+ expect((await task(other.intended.id))?.status).toBe("to-do");+ });++ it("rejects a signed integration that does not match the repository", async () => {+ const other = await createFixture(provider, "OTHER", "other-repo");+ await linkIssue(fixture.intended.id);+ await handleGiteaPullRequestOpened(payload(), other.integration.id);+ await expectUnchanged();+ expect((await task(other.intended.id))?.status).toBe("to-do");+ });++ it("rejects an inactive signed integration", async () => {+ await linkIssue(fixture.intended.id);+ await db+ .update(schema.integrationTable)+ .set({ isActive: false })+ .where(eq(schema.integrationTable.id, fixture.integration.id));+ await open();+ await expectUnchanged();+ });+ }+ },+);diff --git a/tests/api/plugins/github/utils/branch-matcher.test.ts b/tests/api/plugins/github/utils/branch-matcher.test.tsindex 997bfd5f3..43f079113 100644--- a/tests/api/plugins/github/utils/branch-matcher.test.ts+++ b/tests/api/plugins/github/utils/branch-matcher.test.ts@@ -110,18 +110,104 @@ describe("extractTaskNumberFromBranch", () => {});describe("extractTaskNumberFromPRTitle", () => {- it("recognizes supported title formats", () => {- expect(extractTaskNumberFromPRTitle("[12] Ship notifications")).toBe(12);- expect(extractTaskNumberFromPRTitle("Fix sidebar (#34)")).toBe(34);- expect(extractTaskNumberFromPRTitle("55: tidy auth flow")).toBe(55);+ it.each(["task 21", "task: 21", "task-21", "task#21"])(+ "recognizes the delimited marker %s in titles and bodies",+ (reference) => {+ const projectSlug = "KAN";++ const titleTaskNumber = extractTaskNumberFromPRTitle(+ reference,+ projectSlug,+ );+ const bodyTaskNumber = extractTaskNumberFromPRBody(+ reference,+ projectSlug,+ );++ expect(titleTaskNumber).toBe(21);+ expect(bodyTaskNumber).toBe(21);+ },+ );++ it("recognizes explicit task references", () => {+ const projectSlug = "KAN";+ const conventionalTitle = "feat(KAN-42): copy text";+ const bracketedTitle = "[kan-42] Copy text";+ const taskMarkerTitle = "Task: 55 tidy auth flow";++ const conventionalTaskNumber = extractTaskNumberFromPRTitle(+ conventionalTitle,+ projectSlug,+ );+ const bracketedTaskNumber = extractTaskNumberFromPRTitle(+ bracketedTitle,+ projectSlug,+ );+ const markerTaskNumber = extractTaskNumberFromPRTitle(+ taskMarkerTitle,+ projectSlug,+ );++ expect(conventionalTaskNumber).toBe(42);+ expect(bracketedTaskNumber).toBe(42);+ expect(markerTaskNumber).toBe(55);+ });++ it.each([+ "[12] Ship notifications",+ "Fix sidebar (#34)",+ "55: tidy auth flow",+ "Release (61)",+ "feat(OTHER-42): copy text",+ "feat(XKAN-42): copy text",+ "feat(KAN-42extra): copy text",+ "task42",+ "Refactor task61 renderer",+ ])("does not treat %s as a local task", (title) => {+ const projectSlug = "KAN";++ const taskNumber = extractTaskNumberFromPRTitle(title, projectSlug);++ expect(taskNumber).toBeNull();});});describe("extractTaskNumberFromPRBody", () => {it("recognizes task references in the body", () => {- expect(extractTaskNumberFromPRBody("Closes #21")).toBe(21);- expect(extractTaskNumberFromPRBody("task: 77")).toBe(77);- expect(extractTaskNumberFromPRBody("No linked task")).toBeNull();+ const projectSlug = "KAN";+ const issueReference = "Closes #21";+ const taskMarker = "task: 77";+ const projectReference = "Implements KAN-42";+ const unlinkedBody = "No linked task";++ const issueTaskNumber = extractTaskNumberFromPRBody(issueReference);+ const markerTaskNumber = extractTaskNumberFromPRBody(taskMarker);+ const projectTaskNumber = extractTaskNumberFromPRBody(+ projectReference,+ projectSlug,+ );+ const unlinkedTaskNumber = extractTaskNumberFromPRBody(unlinkedBody);++ expect(issueTaskNumber).toBeNull();+ expect(markerTaskNumber).toBe(77);+ expect(projectTaskNumber).toBe(42);+ expect(unlinkedTaskNumber).toBeNull();+ });++ it.each([+ "Closes #61",+ "Fixes #61",+ "Resolves #61",+ "Closes 61",+ "Fixes acme/repo#61",+ "task42",+ "Refactor task61 renderer",+ ])("does not interpret %s as a local task", (body) => {+ const projectSlug = "KAN";++ const taskNumber = extractTaskNumberFromPRBody(body, projectSlug);++ expect(taskNumber).toBeNull();});});@@ -130,7 +216,7 @@ describe("extractTaskNumber", () => {expect(extractTaskNumber("kan-88-polish-editor",- "[12] Ship notifications",+ "[KAN-12] Ship notifications","Closes #21",baseConfig,"KAN",@@ -142,7 +228,7 @@ describe("extractTaskNumber", () => {expect(extractTaskNumber("misc-branch",- "[12] Ship notifications",+ "[KAN-12] Ship notifications","Closes #21",baseConfig,"KAN",@@ -171,4 +257,28 @@ describe("extractTaskNumber", () => {),).toBe(0);});++ it("does not confuse the remote closing issue with a project key", () => {+ expect(+ extractTaskNumber(+ "codex/kan-42-copy-message-text",+ "feat(KAN-42): copy message text",+ "Closes #61",+ baseConfig,+ "KAN",+ ),+ ).toBe(42);+ });++ it("leaves issue-only references for remote issue resolution", () => {+ expect(+ extractTaskNumber(+ "misc-branch",+ "Fix #61",+ "Closes #61",+ baseConfig,+ "KAN",+ ),+ ).toBeNull();+ });});diff --git a/tests/api/plugins/github/utils/issue-references.test.ts b/tests/api/plugins/github/utils/issue-references.test.tsnew file mode 100644index 000000000..af40c45b2--- /dev/null+++ b/tests/api/plugins/github/utils/issue-references.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from "vitest";+import { extractIssueReferences } from "../../../../../apps/api/src/plugins/github/utils/issue-references";++const repository = "https://github.com/acme/repo";++describe("extractIssueReferences", () => {+ it.each([+ "close",+ "closes",+ "closed",+ "fix",+ "fixes",+ "fixed",+ "resolve",+ "resolves",+ "resolved",+ "CLOSES:",+ ])("recognizes %s as a remote issue reference", (keyword) => {+ expect(+ extractIssueReferences("Change", `${keyword} #61`, repository),+ ).toEqual(["61"]);+ });++ it.each([+ "Closes acme/repo#61",+ "Closes ACME/REPO#61",+ "Closes https://github.com/acme/repo/issues/61",+ "Closes https://github.com/acme/repo/issues/61.",+ ])("resolves same-repository reference %s", (body) => {+ expect(extractIssueReferences("Change", body, repository)).toEqual(["61"]);+ });++ it.each([+ "Closes other/repo#61",+ "Closes acme/other#61",+ "Closes https://example.com/acme/repo/issues/61",+ "Closes https://github.com/acme/other/issues/61",+ "Closes https://github.com/acme/repo/pull/61",+ "Closes #61extra",+ "Closes 61",+ "Mention #61",+ "Discloses #61",+ ])("ignores %s", (body) => {+ expect(extractIssueReferences("Change", body, repository)).toEqual([]);+ });++ it("deduplicates title and repeated body references", () => {+ expect(+ extractIssueReferences(+ "Fix sidebar (#61)",+ "Closes #61, resolves #88, fixes #61",+ repository,+ ),+ ).toEqual(["61", "88"]);+ });++ it("keeps qualified title references scoped to their repository", () => {+ expect(+ extractIssueReferences("Fix other/repo#61", null, repository),+ ).toEqual([]);+ });++ it("supports a Gitea instance hosted below a path", () => {+ expect(+ extractIssueReferences(+ "Change",+ "Closes https://git.example.com/gitea/acme/repo/issues/61",+ "https://git.example.com/gitea/acme/repo",+ ),+ ).toEqual(["61"]);+ expect(+ extractIssueReferences(+ "Change",+ "Closes https://git.example.com/acme/repo/issues/61",+ "https://git.example.com/gitea/acme/repo",+ ),+ ).toEqual([]);+ });+});