π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(scm): route a pull request to the agent that opened it, wherever it lives (#19888)
Arvin Xu8de8d87c434f
diff --git a/apps/server/src/services/scm/ScmControlService.ts b/apps/server/src/services/scm/ScmControlService.tsindex 6f583570cdb..30f31ce7e9a 100644--- a/apps/server/src/services/scm/ScmControlService.ts+++ b/apps/server/src/services/scm/ScmControlService.ts@@ -21,6 +21,7 @@ import {postGitHubPullRequestComment,updateGitHubPullRequestComment,} from './github/app';+import { canWriteScmScope } from './scope';import { buildTrackingComment } from './trackingComment';import type { ScmInboundEvent } from './types';import { buildCiFailurePrompt, buildReviewPrompt, type ScmWakeReason } from './wakePrompt';@@ -74,6 +75,19 @@ export class ScmControlService {constructor(private db: LobeChatDatabase) {}handle = async (params: ScmControlEvent): Promise<ScmControlOutcome> => {+ // An author-routed row points into whatever scope the author's records+ // live in, and that was decided when the pull request opened. Checks and+ // reviews reuse the stored row, so without asking again a member who+ // has since left β or been made a viewer β would still get merges+ // accepting and failures waking runs in that workspace.+ if (!(await this.ownerCanStillWrite(params.row))) {+ // The gate is for what we do on the author's behalf. The Work row only+ // records what GitHub reported, and a merge left unmirrored would sit+ // in the workspace as an open Work forever.+ if (params.kind === 'merged') await this.mirrorMerge(params.row);+ return { detail: 'owner can no longer write to this workspace', outcome: 'skipped' };+ }+const outcome = await this.route(params);// A failure the debounce window swallowed rides along with the next// event, whatever that event was.@@ -93,9 +107,7 @@ export class ScmControlService {// The Work row mirrors what GitHub says about the pull request, so// it follows the merge whatever the automation switches say; only// the acceptance verdict is opt-out.- if (row.workId) {- await this.db.update(works).set({ status: 'merged' }).where(eq(works.id, row.workId));- }+ await this.mirrorMerge(row);if (!(await this.isEnabled(row, 'acceptOnMerge'))) {return { detail: 'acceptOnMerge is off', outcome: 'skipped' };}@@ -161,10 +173,43 @@ export class ScmControlService {key: keyof GithubIntegrationPreference,): Promise<boolean> => (await this.preference(row))?.[key] !== false;+ private ownerCanStillWrite = async (row: ScmChangeRequestItem): Promise<boolean> =>+ row.metadata?.routedBy !== 'author' ||+ !row.workspaceId ||+ canWriteScmScope(this.db, row.userId, row.workspaceId);++ private conversationIsInstallers = async (row: ScmChangeRequestItem): Promise<boolean> => {+ if (row.metadata?.routedBy !== 'author' || !row.installationId) return true;+ const installation = await ScmInstallationModel.findById(this.db, row.installationId);+ if (!installation) return false;+ // Inside the installation's own workspace the conversation is the+ // tenant's; anywhere else it is only the installer's if it is theirs.+ return installation.workspaceId+ ? row.workspaceId === installation.workspaceId+ : !row.workspaceId && row.userId === installation.userId;+ };++ /** The Work row mirrors GitHub; it follows a merge whatever else is decided. */+ private mirrorMerge = async (row: ScmChangeRequestItem): Promise<void> => {+ if (!row.workId) return;+ await this.db.update(works).set({ status: 'merged' }).where(eq(works.id, row.workId));+ };++ /**+ * The switches belong to whoever connected the installation, not to the+ * row's owner. With author routing those are different people, and an+ * installer's explicit opt-out β no accepting on merge, no comments on+ * private repositories β must not be undone by an author's defaults.+ */private preference = async (row: ScmChangeRequestItem,- ): Promise<GithubIntegrationPreference | undefined> =>- (await new UserModel(this.db, row.userId).getUserPreference())?.integration?.github;+ ): Promise<GithubIntegrationPreference | undefined> => {+ const installation = row.installationId+ ? await ScmInstallationModel.findById(this.db, row.installationId)+ : null;+ const userId = installation?.userId ?? row.userId;+ return (await new UserModel(this.db, userId).getUserPreference())?.integration?.github;+ };// --------------- tracking comment ---------------@@ -278,7 +323,13 @@ export class ScmControlService {}let conversation: { title?: string | null; url: string } | null = null;- if (row.topicId) {+ // An author-routed pull request can link someone's personal+ // conversation, while the comment is posted under the installer's+ // switches onto a repository that person does not control. Its title+ // and address are theirs to publish, not the installer's, so the+ // comment names a conversation only when it belongs to the tenant that+ // connected the installation.+ if (row.topicId && (await this.conversationIsInstallers(row))) {const topic = await new TopicModel(this.db,row.userId,diff --git a/apps/server/src/services/scm/ScmIngestService.ts b/apps/server/src/services/scm/ScmIngestService.tsindex 51a6d555a3a..457f22ed465 100644--- a/apps/server/src/services/scm/ScmIngestService.ts+++ b/apps/server/src/services/scm/ScmIngestService.ts@@ -4,7 +4,7 @@ import { isFailingCheck, ScmChangeRequestModel, ScmInstallationModel } from '@/dimport type { ScmChangeRequestItem, ScmInstallationItem } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';-import { resolveChangeRequestLinks } from './links';+import { resolveChangeRequestLinks, resolveChangeRequestOwner } from './links';import type { ScmInboundEvent, ScmIngestOutcome } from './types';const log = debug('lobe-server:scm:ingest');@@ -158,8 +158,16 @@ export class ScmIngestService {return { detail: `installation ${event.installationId} is not bound`, status: 'skipped' };}- const scope = { userId: installation.userId, workspaceId: installation.workspaceId };- const links = await resolveChangeRequestLinks(this.db, {+ // The installation says which repositories we listen to; it does not say+ // whose work a pull request is. An agent that opened one is not required+ // to live in the workspace the installation is bound to, so the owner+ // comes from the author the provider named.+ const scope = await resolveChangeRequestOwner(this.db, {+ authorExternalId: event.changeRequest.authorExternalId,+ installation,+ provider: 'github',+ });+ const { links, workspaceId } = await resolveChangeRequestLinks(this.db, {body: event.body,number: event.changeRequest.number,repoFullName: event.changeRequest.repoFullName,@@ -167,21 +175,40 @@ export class ScmIngestService {url: event.changeRequest.url,});+ // The row follows the records it matched, so the conversation is looked+ // up where it actually lives.+ const matched = Boolean(links.topicId || links.acceptanceId || links.workId);++ // A delivery that resolves nothing β the acceptance link was edited out+ // of the body, say β carries less context, not a new owner. The owner+ // below then only seeds a new row; `keepOwner` leaves an existing one+ // where it was, decided under the row lock so a concurrent delivery+ // that did match cannot be undone by one that did not.+ const owner =+ scope.kind === 'author'+ ? { userId: scope.userId, workspaceId: matched ? workspaceId : installation.workspaceId }+ : { userId: scope.userId, workspaceId: scope.workspaceId ?? null };+const row = await ScmChangeRequestModel.upsert(this.db, {...event.changeRequest,eventAt: event.occurredAt,eventKind: event.kind,links: { ...links, installationId: installation.id },- userId: scope.userId,- workspaceId: scope.workspaceId,+ keepOwner: !matched,+ metadata: { ...event.changeRequest.metadata, routedBy: scope.kind },+ userId: owner.userId,+ workspaceId: owner.workspaceId,});log(- '%s %s#%d -> %s (acceptance=%s topic=%s)',+ '%s %s#%d -> %s (owner=%s/%s via %s, acceptance=%s topic=%s)',event.kind,row.repoFullName,row.number,row.id,+ owner.userId,+ owner.workspaceId ?? 'personal',+ scope.kind,row.acceptanceId ?? '-',row.topicId ?? '-',);diff --git a/apps/server/src/services/scm/__tests__/ScmControlService.test.ts b/apps/server/src/services/scm/__tests__/ScmControlService.test.tsindex dd2507b801c..96fe601ae9b 100644--- a/apps/server/src/services/scm/__tests__/ScmControlService.test.ts+++ b/apps/server/src/services/scm/__tests__/ScmControlService.test.ts@@ -13,6 +13,8 @@ import {users,verifyRuns,works,+ workspaceMembers,+ workspaces,} from '@/database/schemas';import { SCM_MAX_WAKES, ScmControlService } from '../ScmControlService';@@ -600,6 +602,106 @@ describe('ScmControlService β wake', () => {expect(flipped.status).toBe('merged');});+ it('stops acting on an author-routed row once the author cannot write there', async () => {+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'scm-control-left-ws' })+ .returning();+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'member', userId, workspaceId: workspace.id });+ const topic = await createTopic();+ // Routed to the author when the pull request opened, into a workspace+ // they could write to then.+ const row = await ScmChangeRequestModel.upsert(serverDB, {+ ...baseRow,+ links: { topicId: topic.id },+ metadata: { routedBy: 'author' },+ workspaceId: workspace.id,+ });++ // A later check or review reuses the stored row. Leaving the workspace,+ // or being made a viewer, has to stop it there.+ for (const change of [{ role: 'viewer' }, { deletedAt: new Date() }]) {+ await serverDB+ .update(workspaceMembers)+ .set(change)+ .where(eq(workspaceMembers.workspaceId, workspace.id));+ expect(await control().handle({ event: checksEvent, kind: 'ci_failed', row })).toEqual({+ detail: 'owner can no longer write to this workspace',+ outcome: 'skipped',+ });+ }+ expect(mocks.execAgent).not.toHaveBeenCalled();++ // The merge itself is still mirrored: the gate covers what we do on the+ // author's behalf, not the record of what GitHub reported.+ const [work] = await serverDB+ .insert(works)+ .values({+ resourceId: 'arvinxx/sandbox#5',+ resourceType: 'github_pull_request',+ status: 'open',+ toolIdentifier: 'lobe-local-system',+ toolName: 'runCommand',+ type: 'external',+ userId,+ visibility: 'private',+ })+ .returning();+ expect(+ await control().handle({+ event: changeRequestEvent('merged'),+ kind: 'merged',+ row: { ...row, state: 'merged', workId: work.id },+ }),+ ).toMatchObject({ outcome: 'skipped' });+ const [mirrored] = await serverDB.select().from(works).where(eq(works.id, work.id));+ expect(mirrored.status).toBe('merged');++ await serverDB.delete(workspaces).where(eq(workspaces.id, workspace.id));+ });++ it("reads the switches of whoever connected the installation, not the author's", async () => {+ // The org owner connected the installation and turned accepting on+ // merge off; the author routed to never touched their switches.+ const installer = 'scm-control-installer';+ await serverDB.insert(users).values({+ id: installer,+ preference: { integration: { github: { acceptOnMerge: false } } } as any,+ });+ const installation = await ScmInstallationModel.bind(serverDB, {+ accountExternalId: '1',+ accountLogin: 'lobehub',+ accountType: 'organization',+ installationId: '90001',+ provider: 'github',+ repositorySelection: 'all',+ userId: installer,+ });+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ status: 'delivered', subjectId: 's', subjectType: 'standalone', userId })+ .returning();+ const row = await ScmChangeRequestModel.upsert(serverDB, {+ ...baseRow,+ links: { acceptanceId: acceptance.id, installationId: installation.id },+ metadata: { routedBy: 'author' },+ state: 'merged',+ });++ expect(+ await control().handle({ event: changeRequestEvent('merged'), kind: 'merged', row }),+ ).toMatchObject({ detail: 'acceptOnMerge is off', outcome: 'skipped' });+ const [after] = await serverDB+ .select()+ .from(acceptances)+ .where(eq(acceptances.id, acceptance.id));+ expect(after.status).toBe('delivered');++ await serverDB.delete(users).where(eq(users.id, installer));+ });+it('reports a failed wake without counting it', async () => {const topic = await createTopic();const row = await ScmChangeRequestModel.upsert(serverDB, {@@ -639,6 +741,41 @@ describe('ScmControlService β the tracking comment in GitHub', () => {});};+ it("leaves someone else's personal conversation out of the public comment", async () => {+ // An org installation connected by someone else; the pull request was+ // routed to the author's personal conversation.+ const installer = 'scm-control-installer-2';+ await serverDB.insert(users).values({ id: installer });+ const topic = await createTopic();+ const installation = await ScmInstallationModel.bind(serverDB, {+ accountExternalId: '1',+ accountLogin: 'lobehub',+ accountType: 'organization',+ installationId: '90001',+ provider: 'github',+ repositorySelection: 'all',+ userId: installer,+ });+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ status: 'delivered', subjectId: 's', subjectType: 'standalone', userId })+ .returning();+ const row = await ScmChangeRequestModel.upsert(serverDB, {+ ...baseRow,+ links: { acceptanceId: acceptance.id, installationId: installation.id, topicId: topic.id },+ metadata: { repoPrivate: true, routedBy: 'author' },+ });++ await control().handle({ event: changeRequestEvent('opened'), kind: 'opened', row });++ const body = mocks.postComment.mock.calls[0][0].body as string;+ expect(body).not.toContain('PR topic');+ expect(body).not.toContain(`/agent/agt_control/${topic.id}`);+ expect(body).toContain(`https://app.test/acceptance/${acceptance.id}`);++ await serverDB.delete(users).where(eq(users.id, installer));+ });+it('posts one comment with a hidden marker and a status table, then rewrites it in place', async () => {const row = await bindAndOpen({ metadata: { repoPrivate: true } });diff --git a/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts b/apps/server/src/services/scm/__tests__/ScmIngestService.test.tsindex 9a3e16c7129..c82a50bb843 100644--- a/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts+++ b/apps/server/src/services/scm/__tests__/ScmIngestService.test.ts@@ -1,9 +1,18 @@// @vitest-environment nodeimport { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ScmChangeRequestModel, ScmInstallationModel } from '@/database/models/scm';-import { acceptances, scmWebhookDeliveries, users } from '@/database/schemas';+import {+ acceptances,+ scmIdentities,+ scmWebhookDeliveries,+ topics,+ users,+ works,+ workspaces,+} from '@/database/schemas';import * as fx from '../github/__tests__/fixtures';import { normalizeGitHubEvent } from '../github/normalize';@@ -243,6 +252,115 @@ describe('ScmIngestService', () => {expect(row).toMatchObject({ ciStatus: 'success', lastEventKind: 'ci_passed' });});+ it("routes a pull request to the author's own conversation, not the installation's tenant", async () => {+ // The org installed the App on its workspace; the pull request was+ // opened by a member whose agent lives in their personal scope.+ const orgOwner = 'scm-ingest-org-owner';+ await serverDB.insert(users).values({ id: orgOwner });+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: orgOwner, slug: 'scm-ingest-ws' })+ .returning();+ await ScmInstallationModel.bind(serverDB, {+ accountExternalId: '1',+ accountLogin: 'lobehub',+ accountType: 'organization',+ installationId: String(fx.installation.id),+ provider: 'github',+ repositorySelection: 'all',+ userId: orgOwner,+ workspaceId: workspace.id,+ });++ // `pullRequest.user.id` is 42 in the fixture; that account is linked to+ // our member, who is not in the workspace at all.+ await serverDB.insert(scmIdentities).values({+ externalLogin: 'arvinxx',+ externalUserId: '42',+ provider: 'github',+ userId,+ });+ const [topic] = await serverDB.insert(topics).values({ title: 'PR topic', userId }).returning();+ await serverDB.insert(works).values({+ originTopicId: topic.id,+ resourceId: 'lobehub/lobehub#19719',+ resourceType: 'github_pull_request',+ toolIdentifier: 'lobe-local-system',+ toolName: 'runCommand',+ type: 'external',+ userId,+ visibility: 'private',+ });++ expect(await ingest('pull_request', fx.pullRequestEvent('opened'))).toMatchObject({+ status: 'processed',+ });++ const row = await ScmChangeRequestModel.findByIdentity(+ serverDB,+ 'github',+ 'lobehub/lobehub',+ 19_719,+ );+ // The conversation is found, and the row says where to look for it.+ expect(row).toMatchObject({ topicId: topic.id, userId, workspaceId: null });++ // The workspace still sees the pull request: it owns the installation.+ const seen = await ScmChangeRequestModel.listByScope(serverDB, {+ userId: orgOwner,+ workspaceId: workspace.id,+ });+ expect(seen.map((item) => item.id)).toContain(row!.id);++ await serverDB.delete(users).where(eq(users.id, orgOwner));+ });++ it('keeps the routed owner when a later event resolves nothing', async () => {+ const orgOwner = 'scm-ingest-org-owner-2';+ await serverDB.insert(users).values({ id: orgOwner });+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: orgOwner, slug: 'scm-ingest-ws-2' })+ .returning();+ await ScmInstallationModel.bind(serverDB, {+ accountExternalId: '1',+ accountLogin: 'lobehub',+ accountType: 'organization',+ installationId: String(fx.installation.id),+ provider: 'github',+ repositorySelection: 'all',+ userId: orgOwner,+ workspaceId: workspace.id,+ });+ await serverDB.insert(scmIdentities).values({+ externalLogin: 'arvinxx',+ externalUserId: '42',+ provider: 'github',+ userId,+ });+ // Personal acceptance, named in the fixture body.+ await serverDB+ .insert(acceptances)+ .values({ id: acceptanceId, subjectId: 's', subjectType: 'standalone', userId });++ await ingest('pull_request', fx.pullRequestEvent('opened'));+ let row = await ScmChangeRequestModel.findByIdentity(+ serverDB,+ 'github',+ 'lobehub/lobehub',+ 19_719,+ );+ expect(row).toMatchObject({ acceptanceId, userId, workspaceId: null });++ // The link is edited out of the body and nothing else points at the+ // pull request. That is less context, not a new owner.+ await ingest('pull_request', fx.pullRequestEvent('edited', { body: 'No links here.' }));+ row = await ScmChangeRequestModel.findById(serverDB, row!.id);+ expect(row).toMatchObject({ acceptanceId, userId, workspaceId: null });++ await serverDB.delete(users).where(eq(users.id, orgOwner));+ });+it('maintains the installation from lifecycle events', async () => {const installation = await bindInstallation();diff --git a/apps/server/src/services/scm/__tests__/links.test.ts b/apps/server/src/services/scm/__tests__/links.test.tsindex cba282915df..f62dec7ae7c 100644--- a/apps/server/src/services/scm/__tests__/links.test.ts+++ b/apps/server/src/services/scm/__tests__/links.test.ts@@ -1,10 +1,20 @@// @vitest-environment nodeimport { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { acceptances, topics, users, verifyRuns, works, workspaces } from '@/database/schemas';+import {+ acceptances,+ scmIdentities,+ topics,+ users,+ verifyRuns,+ works,+ workspaceMembers,+ workspaces,+} from '@/database/schemas';-import { parseAcceptanceIds, resolveChangeRequestLinks } from '../links';+import { parseAcceptanceIds, resolveChangeRequestLinks, resolveChangeRequestOwner } from '../links';const serverDB = await getTestDB();const userId = 'scm-links-user';@@ -41,17 +51,33 @@ describe('resolveChangeRequestLinks', () => {const base = {number: 19_719,repoFullName: 'lobehub/lobehub',- scope: { userId },+ scope: { kind: 'installation', userId, workspaceId: null } as const,url: 'https://github.com/lobehub/lobehub/pull/19719',};+ /** A workspace plus an active membership for `member`. */+ const workspaceWith = async (slug: string, member: string) => {+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: member, slug })+ .returning();+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'owner', userId: member, workspaceId: workspace.id });+ return workspace;+ };++ /** The links half of the result; the workspace half is asserted on its own. */+ const resolve = async (params: Parameters<typeof resolveChangeRequestLinks>[1]) =>+ (await resolveChangeRequestLinks(serverDB, params)).links;+it('links the acceptance named in the body and its topic subject', async () => {const [topic] = await serverDB.insert(topics).values({ title: 't', userId }).returning();await serverDB.insert(acceptances).values({ id: acceptanceId, subjectId: topic.id, subjectType: 'topic', userId });- const links = await resolveChangeRequestLinks(serverDB, {+ const links = await resolve({...base,body: `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`,});@@ -75,7 +101,7 @@ describe('resolveChangeRequestLinks', () => {}).returning();- const links = await resolveChangeRequestLinks(serverDB, {+ const links = await resolve({...base,body: 'Acceptance: https://app.lobehub.com/acceptance/11111111-2222-4333-8444-555555555555',});@@ -112,7 +138,7 @@ describe('resolveChangeRequestLinks', () => {// A body naming their acceptance, a Work they registered, a round they// ingested: none of it links from my installation.expect(- await resolveChangeRequestLinks(serverDB, {+ await resolve({...base,body: `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`,}),@@ -121,7 +147,7 @@ describe('resolveChangeRequestLinks', () => {// Once I register my own Work it wins, and theirs still does not leak in.const [mine] = await insertWork(userId);expect(mine.id).not.toBe(theirs.id);- expect((await resolveChangeRequestLinks(serverDB, base)).workId).toBe(mine.id);+ expect((await resolve(base)).workId).toBe(mine.id);});it('separates a workspace installation from personal records of the same user', async () => {@@ -135,15 +161,13 @@ describe('resolveChangeRequestLinks', () => {const body = `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`;expect(- await resolveChangeRequestLinks(serverDB, {+ await resolve({...base,body,- scope: { userId, workspaceId: workspace.id },+ scope: { kind: 'installation', userId, workspaceId: workspace.id },}),).toEqual({});- expect(await resolveChangeRequestLinks(serverDB, { ...base, body })).toEqual({- acceptanceId,- });+ expect(await resolve({ ...base, body })).toEqual({ acceptanceId });});it('falls back to the acceptance round that ingested the PR url', async () => {@@ -158,11 +182,207 @@ describe('resolveChangeRequestLinks', () => {userId,});- const links = await resolveChangeRequestLinks(serverDB, base);+ const links = await resolve(base);expect(links).toEqual({ acceptanceId });});+ it("reaches the author's personal records from a workspace installation", async () => {+ // The org installed the App on its workspace; a member opened the pull+ // request from a personal agent that is not in that workspace at all.+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: otherUserId, slug: 'scm-links-author-ws' })+ .returning();+ const [topic] = await serverDB.insert(topics).values({ title: 't', userId }).returning();+ const [work] = await serverDB+ .insert(works)+ .values({+ originTopicId: topic.id,+ resourceId: 'lobehub/lobehub#19719',+ resourceType: 'github_pull_request',+ toolIdentifier: 'lobe-local-system',+ toolName: 'runCommand',+ type: 'external',+ userId,+ visibility: 'private',+ })+ .returning();++ // The installation's own tenant sees nothing β that is today's dead end.+ expect(+ await resolve({+ ...base,+ scope: { kind: 'installation', userId: otherUserId, workspaceId: workspace.id },+ }),+ ).toEqual({});++ // Routed by the author, the personal conversation is found, and the+ // result says the records are personal so the wake looks there.+ const resolved = await resolveChangeRequestLinks(serverDB, {+ ...base,+ scope: { kind: 'author', userId },+ });+ expect(resolved.links).toEqual({ topicId: topic.id, workId: work.id });+ expect(resolved.workspaceId).toBeNull();+ });++ it('reports the workspace of the records it matched, not the installation', async () => {+ const workspace = await workspaceWith('scm-links-ws-match', userId);+ await serverDB.insert(acceptances).values({+ id: acceptanceId,+ subjectId: 's',+ subjectType: 'standalone',+ userId,+ workspaceId: workspace.id,+ });++ const resolved = await resolveChangeRequestLinks(serverDB, {+ ...base,+ body: `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`,+ scope: { kind: 'author', userId },+ });+ expect(resolved.links).toEqual({ acceptanceId });+ expect(resolved.workspaceId).toBe(workspace.id);+ });++ it("still refuses another person's records when routing by author", async () => {+ await serverDB+ .insert(acceptances)+ .values({ id: acceptanceId, subjectId: 's', subjectType: 'standalone', userId: otherUserId });++ // The body names it, but the author is someone else.+ expect(+ await resolve({+ ...base,+ body: `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`,+ scope: { kind: 'author', userId },+ }),+ ).toEqual({});+ });++ it('drops a workspace record once the author has left that workspace', async () => {+ const workspace = await workspaceWith('scm-links-left-ws', userId);+ await serverDB.insert(acceptances).values({+ id: acceptanceId,+ subjectId: 's',+ subjectType: 'standalone',+ userId,+ workspaceId: workspace.id,+ });+ const body = `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`;+ const scope = { kind: 'author', userId } as const;++ expect(await resolve({ ...base, body, scope })).toEqual({ acceptanceId });++ // Membership is soft-deleted, but the creator id stays on the record β+ // owning it once must not keep it reachable, or a former member could+ // still have it accepted by merging a pull request.+ await serverDB+ .update(workspaceMembers)+ .set({ deletedAt: new Date() })+ .where(eq(workspaceMembers.userId, userId));++ expect(await resolve({ ...base, body, scope })).toEqual({});+ });++ it('does not let a read-only viewer reach workspace records', async () => {+ const workspace = await workspaceWith('scm-links-viewer-ws', userId);+ await serverDB.insert(acceptances).values({+ id: acceptanceId,+ subjectId: 's',+ subjectType: 'standalone',+ userId,+ workspaceId: workspace.id,+ });+ const body = `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`;+ const scope = { kind: 'author', userId } as const;++ // Downgraded after creating it: a viewer cannot accept it in the app,+ // so a merge must not do it for them.+ await serverDB+ .update(workspaceMembers)+ .set({ role: 'viewer' })+ .where(eq(workspaceMembers.userId, userId));++ expect(await resolve({ ...base, body, scope })).toEqual({});+ });++ it('keeps every link inside the first scope that matched', async () => {+ // The body names an acceptance in workspace A; a Work for the same pull+ // request sits in workspace B. Taking both would report one workspace+ // and hand the control half a topic that does not live there.+ const a = await workspaceWith('scm-links-ws-a', userId);+ const b = await workspaceWith('scm-links-ws-b', userId);+ await serverDB.insert(acceptances).values({+ id: acceptanceId,+ subjectId: 's',+ subjectType: 'standalone',+ userId,+ workspaceId: a.id,+ });+ const [topic] = await serverDB.insert(topics).values({ title: 't', userId }).returning();+ await serverDB.insert(works).values({+ originTopicId: topic.id,+ resourceId: 'lobehub/lobehub#19719',+ resourceType: 'github_pull_request',+ toolIdentifier: 'lobe-local-system',+ toolName: 'runCommand',+ type: 'external',+ userId,+ visibility: 'private',+ workspaceId: b.id,+ });++ const resolved = await resolveChangeRequestLinks(serverDB, {+ ...base,+ body: `Acceptance: https://app.lobehub.com/acceptance/${acceptanceId}`,+ scope: { kind: 'author', userId },+ });++ expect(resolved.workspaceId).toBe(a.id);+ expect(resolved.links).toEqual({ acceptanceId });+ expect(resolved.links.workId).toBeUndefined();+ expect(resolved.links.topicId).toBeUndefined();+ });+it('returns nothing when no source matches', async () => {- expect(await resolveChangeRequestLinks(serverDB, base)).toEqual({});+ expect(await resolve(base)).toEqual({});+ });++ describe('resolveChangeRequestOwner', () => {+ const installation = { userId: otherUserId, workspaceId: 'ws-1' };++ it('routes to the LobeHub user who linked the authoring GitHub account', async () => {+ // Inserted directly: only the identity's owner matters here, and the+ // credential column needs a key vault the test does not have.+ await serverDB.insert(scmIdentities).values({+ externalLogin: 'arvinxx',+ externalUserId: '28616219',+ provider: 'github',+ userId,+ });++ expect(+ await resolveChangeRequestOwner(serverDB, {+ authorExternalId: '28616219',+ installation,+ provider: 'github',+ }),+ ).toEqual({ kind: 'author', userId });+ });++ it("falls back to the installation's tenant for an author we cannot name", async () => {+ // A bot opened it, or the author never linked their account: guessing+ // would be worse than the narrow answer.+ for (const authorExternalId of ['99999999', null, undefined]) {+ expect(+ await resolveChangeRequestOwner(serverDB, {+ authorExternalId,+ installation,+ provider: 'github',+ }),+ ).toEqual({ kind: 'installation', userId: otherUserId, workspaceId: 'ws-1' });+ }+ });});});diff --git a/apps/server/src/services/scm/links.ts b/apps/server/src/services/scm/links.tsindex 5eedfa6d630..cbb5ae894c1 100644--- a/apps/server/src/services/scm/links.ts+++ b/apps/server/src/services/scm/links.ts@@ -1,9 +1,12 @@import type { ScmChangeRequestLinks } from '@lobechat/types';-import { and, desc, eq, inArray, isNotNull, isNull, type SQL, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm';-import { acceptances, verifyRuns, works } from '@/database/schemas';+import { ScmIdentityModel } from '@/database/models/scm';+import { acceptances, verifyRuns, works, workspaceMembers } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { SCM_WRITE_ROLES } from './scope';+/*** Resolve which LobeHub records a provider change request belongs to. Three* sources, in order of trust:@@ -15,11 +18,10 @@ import type { LobeChatDatabase } from '@/database/type';* 3. The acceptance round that recorded this PR url in its coding context* (`verify_runs.context.pullRequest.url`), written by `lh acceptance run ingest`.*- * Every source is confined to the tenant the installation is bound to: a- * personal installation only sees that user's personal records, a workspace- * installation only that workspace's. A PR body can name any acceptance id,- * and without this fence a merge on an attacker's repository would accept- * someone else's delivery.+ * Every source is fenced, because a PR body can name any acceptance id and+ * without a fence a merge on an attacker's repository would accept someone+ * else's delivery. What the fence is depends on how much the provider tells+ * us β see {@link resolveChangeRequestOwner}.** Every source is optional; the result only ever fills links, and the model* never clears one, so a later event with less context cannot undo a match.@@ -42,29 +44,135 @@ export const parseAcceptanceIds = (text: string | null | undefined): string[] =>return ids;};+/**+ * Who a change request's links may be resolved against.+ *+ * - `author` β the provider named the pull request's author, and that+ * account is linked to a LobeHub user. The strongest signal we get: it+ * comes from a signature-verified webhook, not from text anyone can+ * write, and it identifies the person whose agent opened the pull+ * request. Their records are in scope wherever they live, so an agent+ * does not have to belong to the workspace the installation is bound to.+ * Nothing new is exposed either β the wake prompt carries job logs and+ * review text the author can already read on the provider.+ * - `installation` β no author identity to go on (never linked, or a bot+ * opened the pull request). Fall back to the tenant that owns the+ * installation, which is all we can honestly claim.+ */+export type ScmLinkScope =+ | { kind: 'author'; userId: string }+ | { kind: 'installation'; userId: string; workspaceId?: string | null };++/** Resolve the pull request's author to a LobeHub user, when we know them. */+export const resolveChangeRequestOwner = async (+ db: LobeChatDatabase,+ params: {+ authorExternalId?: string | null;+ installation: { userId: string; workspaceId?: string | null };+ provider: 'github';+ },+): Promise<ScmLinkScope> => {+ if (params.authorExternalId) {+ const identity = await ScmIdentityModel.findByExternalUser(+ db,+ params.provider,+ params.authorExternalId,+ );+ if (identity) return { kind: 'author', userId: identity.userId };+ }+ return {+ kind: 'installation',+ userId: params.installation.userId,+ workspaceId: params.installation.workspaceId ?? null,+ };+};+export interface ResolveLinksParams {body?: string | null;number: number;repoFullName: string;- /** Scope of the installation the event came through; every source must match it exactly. */- scope: { userId: string; workspaceId?: string | null };+ /** Who the sources must belong to; see {@link ScmLinkScope}. */+ scope: ScmLinkScope;url: string;}-/** Exact tenant match: the workspace, or the user's personal (workspace-less) records. */+export interface ResolvedChangeRequestLinks {+ links: ScmChangeRequestLinks;+ /**+ * Workspace the matched records live in, `null` when they are personal.+ * The change request follows them, so the conversation it links to is+ * looked up in the scope that actually holds it.+ */+ workspaceId: string | null;+}++/**+ * Not yet decided (`undefined`), personal (`null`), or one workspace.+ *+ * The first source that matches fixes this for the ones after it. Left+ * free, a body-named acceptance in workspace A and a Work in workspace B+ * could both match and the result would report only one of them β after+ * which the control half looks the other's topic up in the wrong scope and+ * silently finds nothing.+ */+type ScopePin = string | null | undefined;+const inScope = (+ db: LobeChatDatabase,table: { userId: SQL.Aliased | any; workspaceId: any },- scope: ResolveLinksParams['scope'],-): SQL =>- scope.workspaceId- ? eq(table.workspaceId, scope.workspaceId)- : and(eq(table.userId, scope.userId), isNull(table.workspaceId))!;+ scope: ScmLinkScope,+ pin: ScopePin,+): SQL => {+ const pinned =+ pin === undefined+ ? undefined+ : pin === null+ ? isNull(table.workspaceId)+ : eq(table.workspaceId, pin);++ if (scope.kind === 'author') {+ // Everything this person owns, wherever they can still reach it. The+ // creator's id stays on a workspace record after they leave, so owning+ // it once is not enough β an active membership has to back it, or a+ // former member could still have an old workspace acceptance accepted+ // by merging a pull request.+ const memberOf = db+ .select({ workspaceId: workspaceMembers.workspaceId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.userId, scope.userId),+ isNull(workspaceMembers.deletedAt),+ // Linking a record is the first step to mutating it β a merge+ // accepts it, a failure wakes its agent β and a viewer can do+ // neither through the app, so they cannot do it through a merge.+ inArray(workspaceMembers.role, [...SCM_WRITE_ROLES]),+ ),+ );++ return and(+ eq(table.userId, scope.userId),+ or(isNull(table.workspaceId), inArray(table.workspaceId, memberOf)),+ pinned,+ )!;+ }++ return and(+ scope.workspaceId+ ? eq(table.workspaceId, scope.workspaceId)+ : and(eq(table.userId, scope.userId), isNull(table.workspaceId)),+ pinned,+ )!;+};export const resolveChangeRequestLinks = async (db: LobeChatDatabase,params: ResolveLinksParams,-): Promise<ScmChangeRequestLinks> => {+): Promise<ResolvedChangeRequestLinks> => {const links: ScmChangeRequestLinks = {};+ // Undecided until a source matches; from then on every later source has+ // to agree with it.+ let pin: ScopePin;// 1. Acceptance link in the body β first id that exists in this scope// wins. The body is user-controlled and may name a hundred ids, so they@@ -76,15 +184,17 @@ export const resolveChangeRequestLinks = async (id: acceptances.id,subjectId: acceptances.subjectId,subjectType: acceptances.subjectType,+ workspaceId: acceptances.workspaceId,}).from(acceptances)- .where(and(inArray(acceptances.id, candidates), inScope(acceptances, params.scope)));+ .where(and(inArray(acceptances.id, candidates), inScope(db, acceptances, params.scope, pin)));const byId = new Map(rows.map((row) => [row.id, row]));for (const id of candidates) {const row = byId.get(id);if (!row) continue;links.acceptanceId = row.id;+ pin = row.workspaceId ?? null;if (row.subjectType === 'topic') links.topicId = row.subjectId;if (row.subjectType === 'task') links.taskId = row.subjectId;break;@@ -94,38 +204,46 @@ export const resolveChangeRequestLinks = async (// 2. The registered Work in this scope, newest first.const resourceId = `${params.repoFullName}#${params.number}`;const [work] = await db- .select({ id: works.id, originTopicId: works.originTopicId })+ .select({+ id: works.id,+ originTopicId: works.originTopicId,+ workspaceId: works.workspaceId,+ }).from(works).where(and(eq(works.resourceType, 'github_pull_request'),eq(works.resourceId, resourceId),- inScope(works, params.scope),+ inScope(db, works, params.scope, pin),),).orderBy(desc(works.updatedAt)).limit(1);if (work) {links.workId = work.id;+ pin ??= work.workspaceId ?? null;if (!links.topicId && work.originTopicId) links.topicId = work.originTopicId;}// 3. The acceptance round in this scope that ingested this PR url.if (!links.acceptanceId) {const [run] = await db- .select({ acceptanceId: verifyRuns.acceptanceId })+ .select({ acceptanceId: verifyRuns.acceptanceId, workspaceId: verifyRuns.workspaceId }).from(verifyRuns).where(and(isNotNull(verifyRuns.acceptanceId),- inScope(verifyRuns, params.scope),+ inScope(db, verifyRuns, params.scope, pin),sql`${verifyRuns.context} -> 'pullRequest' ->> 'url' = ${params.url}`,),).orderBy(desc(verifyRuns.createdAt)).limit(1);- if (run?.acceptanceId) links.acceptanceId = run.acceptanceId;+ if (run?.acceptanceId) {+ links.acceptanceId = run.acceptanceId;+ pin ??= run.workspaceId ?? null;+ }}- return links;+ return { links, workspaceId: pin ?? null };};diff --git a/apps/server/src/services/scm/scope.ts b/apps/server/src/services/scm/scope.tsindex 7b5286d7696..e22dd29c887 100644--- a/apps/server/src/services/scm/scope.ts+++ b/apps/server/src/services/scm/scope.ts@@ -2,11 +2,14 @@ import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import type { LobeChatDatabase } from '@/database/type';/**- * Who may bind a provider installation to a workspace: every active member- * except read-only viewers. Binding pulls the installation's repositories- * and pull-request traffic into the whole workspace, which is a write.+ * Who may write into a workspace through the SCM loop: every active member+ * except read-only viewers. Binding an installation pulls its repositories+ * into the whole workspace, and a merge that accepts an acceptance or a+ * wake that starts a run mutates it β all writes.*/-const INSTALLER_ROLES: ReadonlySet<string> = new Set(['owner', 'admin', 'member']);+export const SCM_WRITE_ROLES = ['owner', 'admin', 'member'] as const;++const INSTALLER_ROLES: ReadonlySet<string> = new Set(SCM_WRITE_ROLES);export const canManageWorkspaceScm = (role: string | null | undefined): boolean =>!!role && INSTALLER_ROLES.has(role);diff --git a/packages/database/src/models/scm/__tests__/changeRequest.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.test.tsindex a1c0b3083b1..1b953164570 100644--- a/packages/database/src/models/scm/__tests__/changeRequest.test.ts+++ b/packages/database/src/models/scm/__tests__/changeRequest.test.ts@@ -547,6 +547,152 @@ describe('ScmChangeRequestModel', () => {expect((after?.repositories ?? []).map((r) => r.externalId).sort()).toEqual(['2', '3', '4']);});+ it('keeps an existing owner when told to, whatever owner the delivery carries', async () => {+ const otherUser = 'scm-model-user-keep';+ await serverDB.insert(users).values({ id: otherUser });+ // One delivery routed the pull request to its author, with a link.+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ subjectId: 's', subjectType: 'standalone', userId })+ .returning();+ const routed = await ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ links: { acceptanceId: acceptance.id },+ metadata: { routedBy: 'author' },+ });++ // A concurrent one resolved nothing and falls back to someone else.+ // It must not move the row β which would read as a tenant change and+ // clear the link the first one stored.+ const after = await ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ keepOwner: true,+ metadata: { routedBy: 'installation' },+ userId: otherUser,+ });++ expect(after.id).toBe(routed.id);+ expect(after).toMatchObject({ acceptanceId: acceptance.id, userId });+ expect(after.metadata.routedBy).toBe('author');++ await serverDB.delete(users).where(eq(users.id, otherUser));+ });++ it('never lets a stale delivery reroute the row or replace its links', async () => {+ const otherUser = 'scm-model-user-stale';+ await serverDB.insert(users).values({ id: otherUser });+ const [older, newer] = await serverDB+ .insert(acceptances)+ .values([+ { subjectId: 'a', subjectType: 'standalone', userId: otherUser },+ { subjectId: 'b', subjectType: 'standalone', userId },+ ])+ .returning();++ // The newer event routed the pull request to `userId`.+ const routed = await ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ eventAt: new Date('2026-09-23T12:00:00Z'),+ links: { acceptanceId: newer.id },+ metadata: { routedBy: 'author' },+ });++ // An older delivery, naming other records under another owner, lands+ // afterwards. It resolved links, so it is not a keep-owner event.+ const after = await ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ eventAt: new Date('2026-09-23T11:00:00Z'),+ links: { acceptanceId: older.id },+ metadata: { routedBy: 'installation' },+ userId: otherUser,+ });++ expect(after.id).toBe(routed.id);+ expect(after).toMatchObject({ acceptanceId: newer.id, userId });+ expect(after.metadata.routedBy).toBe('author');++ await serverDB.delete(users).where(eq(users.id, otherUser));+ });++ it('replays the loser of a first-insert race under the lock instead of overwriting', async () => {+ const otherUser = 'scm-model-user-race';+ await serverDB.insert(users).values({ id: otherUser });+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ subjectId: 's', subjectType: 'standalone', userId })+ .returning();++ // Both deliveries see no row. One matched and routes to `userId`; the+ // other matched nothing and only carries a fallback owner.+ await Promise.all([+ ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ links: { acceptanceId: acceptance.id },+ metadata: { routedBy: 'author' },+ }),+ ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ keepOwner: true,+ metadata: { routedBy: 'installation' },+ userId: otherUser,+ }),+ ]);++ const row = await ScmChangeRequestModel.findByIdentity(+ serverDB,+ 'github',+ snapshot.repoFullName,+ snapshot.number,+ );+ // Whichever inserted first, the link survives. When the matched one won,+ // the other replays with `keepOwner` and leaves it alone; when the+ // unmatched one won, the matched one replays as a normal routed event.+ expect(row?.acceptanceId).toBe(acceptance.id);+ expect(row?.userId).toBe(userId);++ await serverDB.delete(users).where(eq(users.id, otherUser));+ });++ it('replays a lost first insert against the winner, deterministically', async () => {+ // The race above only races on a pooled Postgres; PGlite serializes+ // the two transactions. Stage the loss directly: the unmatched delivery+ // looked and saw no row, and by the time it inserts the matched one has+ // committed.+ const otherUser = 'scm-model-user-staged';+ await serverDB.insert(users).values({ id: otherUser });+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ subjectId: 's', subjectType: 'standalone', userId })+ .returning();++ const model = ScmChangeRequestModel as unknown as {+ upsertOnce: (...args: unknown[]) => Promise<unknown>;+ };+ const original = model.upsertOnce;+ const spy = vi.spyOn(model, 'upsertOnce').mockImplementationOnce(async () => {+ await original(serverDB, {+ ...snapshot,+ links: { acceptanceId: acceptance.id },+ metadata: { routedBy: 'author' },+ });+ return null; // the insert hit the unique index and did nothing+ });++ const row = await ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ keepOwner: true,+ metadata: { routedBy: 'installation' },+ userId: otherUser,+ });++ expect(spy).toHaveBeenCalledTimes(2);+ expect(row).toMatchObject({ acceptanceId: acceptance.id, userId });+ expect(row.metadata.routedBy).toBe('author');++ spy.mockRestore();+ await serverDB.delete(users).where(eq(users.id, otherUser));+ });+it('changes pendingWake in place, without reading the metadata bag first', async () => {const row = await ScmChangeRequestModel.upsert(serverDB, {...snapshot,diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.tsindex 2406135a07c..dc6c7f1beb6 100644--- a/packages/database/src/models/scm/changeRequest.ts+++ b/packages/database/src/models/scm/changeRequest.ts@@ -9,10 +9,10 @@ import type {ScmReviewDecision,ScmUpsertChangeRequestParams,} from '@lobechat/types';-import { and, desc, eq, isNull, lt, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNull, lt, or, sql } from 'drizzle-orm';import type { ScmChangeRequestItem } from '../../schemas';-import { scmChangeRequests } from '../../schemas';+import { scmChangeRequests, scmInstallations } from '../../schemas';import type { LobeChatDatabase } from '../../type';/**@@ -185,19 +185,40 @@ export class ScmChangeRequestModel {.orderBy(desc(scmChangeRequests.updatedAt));/** Change requests visible to a scope, newest activity first. */+ /**+ * What this scope should see: its own change requests, plus everything on+ * the installations it connected.+ *+ * The two are no longer the same set. A row belongs to whoever opened the+ * pull request, which may be a member using their personal agent, while+ * the installation belongs to the workspace β without the second half a+ * workspace would stop seeing pull requests on its own repositories.+ */static listByScope = async (db: LobeChatDatabase,scope: { userId: string; workspaceId?: string | null },options: { limit?: number } = {},): Promise<ScmChangeRequestItem[]> => {- const scopeCondition = scope.workspaceId+ const owned = scope.workspaceId? eq(scmChangeRequests.workspaceId, scope.workspaceId): and(eq(scmChangeRequests.userId, scope.userId), isNull(scmChangeRequests.workspaceId));+ const connected = db+ .select({ id: scmInstallations.id })+ .from(scmInstallations)+ .where(+ and(+ isNull(scmInstallations.revokedAt),+ scope.workspaceId+ ? eq(scmInstallations.workspaceId, scope.workspaceId)+ : and(eq(scmInstallations.userId, scope.userId), isNull(scmInstallations.workspaceId)),+ ),+ );+return db.select().from(scmChangeRequests)- .where(scopeCondition)+ .where(or(owned, inArray(scmChangeRequests.installationId, connected))).orderBy(desc(scmChangeRequests.updatedAt)).limit(options.limit ?? 50);};@@ -224,7 +245,21 @@ export class ScmChangeRequestModel {static upsert = async (db: LobeChatDatabase,params: ScmUpsertChangeRequestParams,- ): Promise<ScmChangeRequestItem> =>+ ): Promise<ScmChangeRequestItem> => {+ const row = await ScmChangeRequestModel.upsertOnce(db, params);+ if (row) return row;+ // Lost the race to create the row. The winner has committed by now, so+ // go round again: this time there is a row to lock, and ownership,+ // staleness and links are all judged against it like any other event.+ const retried = await ScmChangeRequestModel.upsertOnce(db, params);+ if (!retried) throw new Error('scm change request vanished between insert and retry');+ return retried;+ };++ private static upsertOnce = async (+ db: LobeChatDatabase,+ params: ScmUpsertChangeRequestParams,+ ): Promise<ScmChangeRequestItem | null> =>// The whole read-modify-write runs under a row lock. Reading the row// outside one lets a `merged` and an older `synchronize` delivery both// see the pre-merge state, and whichever writes last wins β the stale@@ -242,13 +277,26 @@ export class ScmChangeRequestModel {and(eq(scmChangeRequests.provider, params.provider),params.externalId- ? eq(scmChangeRequests.externalId, params.externalId)+ ? or(+ eq(scmChangeRequests.externalId, params.externalId),+ and(+ eq(scmChangeRequests.repoFullName, params.repoFullName),+ eq(scmChangeRequests.number, params.number),+ ),+ )!: and(eq(scmChangeRequests.repoFullName, params.repoFullName),eq(scmChangeRequests.number, params.number),)!,),)+ // The provider id first: after a rename it is the row that matters.+ .orderBy(+ params.externalId+ ? sql`(${scmChangeRequests.externalId} = ${params.externalId}) desc`+ : desc(scmChangeRequests.updatedAt),+ )+ .limit(1).for('update');// Deliveries are not ordered: GitHub retries, and a redelivery of an old@@ -302,6 +350,9 @@ export class ScmChangeRequestModel {metadata: {...existing?.metadata,...params.metadata,+ ...((params.keepOwner || stale) && existing+ ? { routedBy: existing.metadata?.routedBy }+ : {}),...(params.eventAt ? { lastProviderEventAt: params.eventAt.toISOString() } : {}),// Once adopted (or superseded by a newer head) the bucket is spent....(headChanged ? { pendingChecks: undefined } : {}),@@ -314,17 +365,24 @@ export class ScmChangeRequestModel {url: params.url,};+ // An out-of-order delivery describes an older state of the pull+ // request, including where it was routed then. It can fill a link the+ // row lacks; it cannot move the row or replace a link a newer event set.const scopeMoved =!!existing &&+ !params.keepOwner &&+ !stale &&(existing.userId !== params.userId ||(existing.workspaceId ?? null) !== (params.workspaceId ?? null));const inherited = scopeMoved ? undefined : existing;+ const pick = <T>(incoming: T | null | undefined, stored: T | null | undefined): T | null =>+ (stale ? (stored ?? incoming) : (incoming ?? stored)) ?? null;const linkValues = {- acceptanceId: links.acceptanceId ?? inherited?.acceptanceId ?? null,+ acceptanceId: pick(links.acceptanceId, inherited?.acceptanceId),installationId: links.installationId ?? existing?.installationId ?? null,- taskId: links.taskId ?? inherited?.taskId ?? null,- topicId: links.topicId ?? inherited?.topicId ?? null,- workId: links.workId ?? inherited?.workId ?? null,+ taskId: pick(links.taskId, inherited?.taskId),+ topicId: pick(links.topicId, inherited?.topicId),+ workId: pick(links.workId, inherited?.workId),};const ownerValues = scopeMoved? { userId: params.userId, workspaceId: params.workspaceId ?? null }@@ -354,7 +412,14 @@ export class ScmChangeRequestModel {// acceptance id parsed from the body), so fills apply; the lifecycle// columns do not.const stateValues = stale- ? { metadata: { ...snapshot.metadata, ...existing.metadata, ...params.metadata } }+ ? {+ metadata: {+ ...snapshot.metadata,+ ...existing.metadata,+ ...params.metadata,+ routedBy: existing.metadata?.routedBy,+ },+ }: snapshot;const [row] = await tx.update(scmChangeRequests)@@ -371,8 +436,10 @@ export class ScmChangeRequestModel {return row;}- // No row to lock yet, so two first deliveries can race here; the- // unique index settles it and both end up applied.+ // No row to lock yet, so two first deliveries can race here. The+ // unique index picks the winner; the loser must not overwrite it+ // blind β its links and owner were computed without the winner's β+ // so it reports the loss and `upsert` replays it under the lock.const [row] = await tx.insert(scmChangeRequests).values({@@ -386,8 +453,7 @@ export class ScmChangeRequestModel {userId: params.userId,workspaceId: params.workspaceId ?? null,})- .onConflictDoUpdate({- set: { ...snapshot, ...linkValues, ...eventValues, updatedAt: now },+ .onConflictDoNothing({target: [scmChangeRequests.provider,scmChangeRequests.repoFullName,@@ -396,7 +462,7 @@ export class ScmChangeRequestModel {}).returning();- return row;+ return row ?? null;});/** Fill in links that are still null. Never overwrites a link already set. */diff --git a/packages/types/src/scm.ts b/packages/types/src/scm.tsindex bdaac205a52..b2f52e36d16 100644--- a/packages/types/src/scm.ts+++ b/packages/types/src/scm.ts@@ -167,6 +167,14 @@ export interface ScmChangeRequestMetadata {* whatever order the deliveries arrive in.*/reviewers?: Record<string, { at?: string; decision: 'approved' | 'changes_requested' }>;+ /**+ * How the owner was decided. `author` rows point at a person's records+ * wherever they live, so every action on them rechecks that the person+ * can still write there; `installation` rows (and rows written before+ * author routing, which carry nothing) belong to the installation's+ * tenant and need no such check.+ */+ routedBy?: 'author' | 'installation';}/** Processing state of one inbound webhook delivery. */@@ -213,6 +221,13 @@ export interface ScmChangeRequestLinks {export interface ScmUpsertChangeRequestParams extends ScmChangeRequestSnapshot {eventAt?: Date;eventKind?: ScmChangeRequestEventKind;+ /**+ * The owner below is only a fallback for a row that does not exist yet:+ * an existing row keeps its owner, workspace and `routedBy`. Decided+ * under the row lock, so a delivery that resolved nothing cannot move a+ * row another delivery just routed.+ */+ keepOwner?: boolean;links?: ScmChangeRequestLinks;userId: string;workspaceId?: string | null;