diff --git a/packages/outpost/queue/src/__tests__/tracker-sync.test.ts b/packages/outpost/queue/src/__tests__/tracker-sync.test.ts index 23bdc4c1..251b8a7d 100644 --- a/packages/outpost/queue/src/__tests__/tracker-sync.test.ts +++ b/packages/outpost/queue/src/__tests__/tracker-sync.test.ts @@ -25,14 +25,12 @@ vi.mock('@copilotkit/outpost/db', () => ({ const mockGetPlugin = vi.fn(); const mockIsInternalTracker = vi.fn().mockReturnValue(false); const mockComputeHash = vi.fn().mockReturnValue('abc123hash'); -const mockIsEchoEvent = vi.fn().mockResolvedValue(false); const mockRecordSyncEvent = vi.fn().mockResolvedValue(undefined); const mockEngine = { getPlugin: mockGetPlugin, isInternalTracker: mockIsInternalTracker, computeHash: mockComputeHash, - isEchoEvent: mockIsEchoEvent, recordSyncEvent: mockRecordSyncEvent, }; @@ -119,14 +117,18 @@ describe('handleTrackerSync', () => { expect(result.error).toContain('No external link found'); }); - it('skips push when echo is detected', async () => { + it('pushes what the job says, without consulting an echo guard', async () => { + // The echo guard lives at the fan-out, in SyncEngine.onTicketChange: + // a change that comes back from a tracker is recognised there, + // before it becomes a job. A job is a promise to push, and the + // operator-facing force sync enqueues jobs directly and expects + // every one of them to push. const mockPlugin = { name: 'github', - pushStatusChange: vi.fn(), + pushStatusChange: vi.fn().mockResolvedValue(undefined), }; mockGetPlugin.mockReturnValue(mockPlugin); mockPrismaTicketExternalLink.findUnique.mockResolvedValue(sampleLink); - mockIsEchoEvent.mockResolvedValue(true); const result = await handler( { @@ -139,8 +141,16 @@ describe('handleTrackerSync', () => { ); expect(result.success).toBe(true); - expect(result.data).toEqual({ skipped: true, reason: 'echo detected' }); - expect(mockPlugin.pushStatusChange).not.toHaveBeenCalled(); + expect(mockPlugin.pushStatusChange).toHaveBeenCalledTimes(1); + expect(mockRecordSyncEvent).toHaveBeenCalledWith( + 'outpost', + 'github', + 'ticket', + 'tkt-1', + 'status_change', + 'abc123hash', + 'success', + ); }); it('pushes status_change and records success', async () => { @@ -150,7 +160,6 @@ describe('handleTrackerSync', () => { }; mockGetPlugin.mockReturnValue(mockPlugin); mockPrismaTicketExternalLink.findUnique.mockResolvedValue(sampleLink); - mockIsEchoEvent.mockResolvedValue(false); const result = await handler( { @@ -168,8 +177,13 @@ describe('handleTrackerSync', () => { 'RESOLVED', ); expect(mockRecordSyncEvent).toHaveBeenCalledWith( - 'outpost', 'github', 'ticket', 'tkt-1', - 'status_change', 'abc123hash', 'success', + 'outpost', + 'github', + 'ticket', + 'tkt-1', + 'status_change', + 'abc123hash', + 'success', ); }); @@ -180,7 +194,6 @@ describe('handleTrackerSync', () => { }; mockGetPlugin.mockReturnValue(mockPlugin); mockPrismaTicketExternalLink.findUnique.mockResolvedValue(sampleLink); - mockIsEchoEvent.mockResolvedValue(false); const result = await handler( { @@ -206,7 +219,6 @@ describe('handleTrackerSync', () => { }; mockGetPlugin.mockReturnValue(mockPlugin); mockPrismaTicketExternalLink.findUnique.mockResolvedValue(sampleLink); - mockIsEchoEvent.mockResolvedValue(false); const result = await handler( { @@ -232,7 +244,6 @@ describe('handleTrackerSync', () => { }; mockGetPlugin.mockReturnValue(mockPlugin); mockPrismaTicketExternalLink.findUnique.mockResolvedValue(sampleLink); - mockIsEchoEvent.mockResolvedValue(false); const result = await handler( { @@ -247,8 +258,14 @@ describe('handleTrackerSync', () => { expect(result.success).toBe(false); expect(result.error).toBe('API 500'); expect(mockRecordSyncEvent).toHaveBeenCalledWith( - 'outpost', 'github', 'ticket', 'tkt-1', - 'status_change', 'abc123hash', 'failure', 'API 500', + 'outpost', + 'github', + 'ticket', + 'tkt-1', + 'status_change', + 'abc123hash', + 'failure', + 'API 500', ); }); @@ -264,8 +281,6 @@ describe('handleTrackerSync', () => { plugin: 'linear', externalId: 'lin-99', }); - mockIsEchoEvent.mockResolvedValue(false); - const member = { id: 'tm-1', name: 'Alice', email: 'alice@example.com' }; const result = await handler( @@ -289,7 +304,6 @@ describe('handleTrackerSync', () => { const mockPlugin = { name: 'github' }; mockGetPlugin.mockReturnValue(mockPlugin); mockPrismaTicketExternalLink.findUnique.mockResolvedValue(sampleLink); - mockIsEchoEvent.mockResolvedValue(false); const result = await handler( { @@ -312,7 +326,6 @@ describe('handleTrackerSync', () => { }; mockGetPlugin.mockReturnValue(mockPlugin); mockPrismaTicketExternalLink.findUnique.mockResolvedValue(sampleLink); - mockIsEchoEvent.mockResolvedValue(false); const ctx = makeContext(); await handler( diff --git a/packages/outpost/queue/src/handlers/tracker-sync.ts b/packages/outpost/queue/src/handlers/tracker-sync.ts index 742171e9..a69d8344 100644 --- a/packages/outpost/queue/src/handlers/tracker-sync.ts +++ b/packages/outpost/queue/src/handlers/tracker-sync.ts @@ -71,21 +71,21 @@ export function createTrackerSyncHandler(engine: SyncEngine) { await context.reportProgress(40); - // Echo detection: compute hash and check before pushing - const payloadHash = engine.computeHash(ticketId, targetPlugin, action, changeData); - const isEcho = await engine.isEchoEvent( - ticketId, - 'outpost', // We are pushing FROM outpost TO target - targetPlugin, - payloadHash, - ); - - if (isEcho) { - return { - success: true, - data: { skipped: true, reason: 'echo detected' }, - }; - } + // NO echo check here, and that is deliberate. + // + // The guard belongs at the fan-out, in SyncEngine.onTicketChange: a + // change that comes back from a tracker is recognised there, before + // it is turned into a job. Checking here instead was wrong twice + // over. The guard used to look for a record in the reverse direction + // of the one a push is recorded in, so it never fired at all; and + // once it is fixed to look the right way, it would fire on the + // record this very job created — the engine writes a pending record + // before enqueueing — and the push would never happen. + // + // A job is a promise to push, and this handler keeps it. The + // operator-facing force sync enqueues jobs directly, without the + // engine, and expects every one of them to push. + const payloadHash = engine.computeHash(ticketId, action, changeData); await context.reportProgress(50); @@ -107,9 +107,7 @@ export function createTrackerSyncHandler(engine: SyncEngine) { await context.reportProgress(100); - console.log( - `[TrackerSync] Pushed ${action} for ticket ${ticketId} to ${targetPlugin}`, - ); + console.log(`[TrackerSync] Pushed ${action} for ticket ${ticketId} to ${targetPlugin}`); return { success: true, diff --git a/packages/outpost/shared/src/__tests__/echo-guard.test.ts b/packages/outpost/shared/src/__tests__/echo-guard.test.ts index c5d3f90c..14120bf8 100644 --- a/packages/outpost/shared/src/__tests__/echo-guard.test.ts +++ b/packages/outpost/shared/src/__tests__/echo-guard.test.ts @@ -12,6 +12,7 @@ function makeMockDeps(): EchoGuardDeps { syncEvent: { findFirst: vi.fn().mockResolvedValue(null), create: vi.fn().mockResolvedValue({ id: 'se-1' }), + update: vi.fn().mockResolvedValue({ id: 'se-1' }), }, }, }; @@ -32,40 +33,55 @@ describe('EchoGuard', () => { it('returns true when no matching SyncEvent exists (no echo)', async () => { vi.mocked(deps.prisma.syncEvent.findFirst).mockResolvedValue(null); - const result = await guard.shouldSync('linear', 'github', 'tkt-1', 'hash123'); + const result = await guard.shouldSync('github', 'tkt-1', 'hash123'); expect(result).toBe(true); }); - it('returns false when a matching reverse-direction SyncEvent exists (echo detected)', async () => { + it('returns false when a matching SyncEvent exists (echo detected)', async () => { vi.mocked(deps.prisma.syncEvent.findFirst).mockResolvedValue({ id: 'se-existing', createdAt: new Date(), }); - const result = await guard.shouldSync('linear', 'github', 'tkt-1', 'hash123'); + const result = await guard.shouldSync('github', 'tkt-1', 'hash123'); expect(result).toBe(false); }); - it('queries for the reverse direction (target→source)', async () => { - await guard.shouldSync('linear', 'github', 'tkt-1', 'hash123'); + it('queries the direction pushes are recorded in', async () => { + await guard.shouldSync('github', 'tkt-1', 'hash123'); + // A push is recorded with the plugin it was pushed TO as the + // target, so that is what has to be matched. The old query asked + // for the reverse pair, which no push has ever produced — which + // is why the guard could not fire. expect(deps.prisma.syncEvent.findFirst).toHaveBeenCalledWith({ where: { entityId: 'tkt-1', - sourcePlugin: 'github', // reverse: target becomes source - targetPlugin: 'linear', // reverse: source becomes target + targetPlugin: 'github', payloadHash: 'hash123', + status: { in: ['pending', 'success'] }, createdAt: { gte: expect.any(Date) }, }, orderBy: { createdAt: 'desc' }, }); }); + it('does not treat a failed push as an echo (the retry has to be allowed)', async () => { + await guard.shouldSync('github', 'tkt-1', 'hash123'); + + const callArgs = vi.mocked(deps.prisma.syncEvent.findFirst).mock.calls[0][0]; + const statuses = (callArgs.where.status as { in: string[] }).in; + + expect(statuses).toContain('pending'); + expect(statuses).toContain('success'); + expect(statuses).not.toContain('failure'); + }); + it('respects the configured echo window', async () => { const shortGuard = new EchoGuard(deps, 5_000); - await shortGuard.shouldSync('linear', 'github', 'tkt-1', 'hash123'); + await shortGuard.shouldSync('github', 'tkt-1', 'hash123'); const callArgs = vi.mocked(deps.prisma.syncEvent.findFirst).mock.calls[0][0]; const cutoff = (callArgs.where.createdAt as { gte: Date }).gte; @@ -79,13 +95,20 @@ describe('EchoGuard', () => { describe('recordSync', () => { it('creates a success SyncEvent', async () => { + vi.mocked(deps.prisma.syncEvent.findFirst).mockResolvedValue(null); + await guard.recordSync( - 'linear', 'github', 'tkt-1', 'status_change', 'hash123', 'success', + 'outpost', + 'github', + 'tkt-1', + 'status_change', + 'hash123', + 'success', ); expect(deps.prisma.syncEvent.create).toHaveBeenCalledWith({ data: { - sourcePlugin: 'linear', + sourcePlugin: 'outpost', targetPlugin: 'github', entityType: 'ticket', entityId: 'tkt-1', @@ -98,8 +121,16 @@ describe('EchoGuard', () => { }); it('creates a failure SyncEvent with error message', async () => { + vi.mocked(deps.prisma.syncEvent.findFirst).mockResolvedValue(null); + await guard.recordSync( - 'linear', 'github', 'tkt-1', 'comment', 'hash456', 'failure', 'API timeout', + 'outpost', + 'github', + 'tkt-1', + 'comment', + 'hash456', + 'failure', + 'API timeout', ); expect(deps.prisma.syncEvent.create).toHaveBeenCalledWith({ @@ -111,8 +142,15 @@ describe('EchoGuard', () => { }); it('creates a conflict SyncEvent', async () => { + vi.mocked(deps.prisma.syncEvent.findFirst).mockResolvedValue(null); + await guard.recordSync( - 'linear', 'github', 'tkt-1', 'status_change', 'hash789', 'conflict', + 'outpost', + 'github', + 'tkt-1', + 'status_change', + 'hash789', + 'conflict', ); expect(deps.prisma.syncEvent.create).toHaveBeenCalledWith({ @@ -121,18 +159,91 @@ describe('EchoGuard', () => { }), }); }); + + it('records a pending row before the work is enqueued', async () => { + vi.mocked(deps.prisma.syncEvent.findFirst).mockResolvedValue(null); + + await guard.recordSync( + 'outpost', + 'github', + 'tkt-1', + 'status_change', + 'hash123', + 'pending', + ); + + expect(deps.prisma.syncEvent.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ status: 'pending' }), + }); + }); + + it('does not record a second pending row for a change already in flight', async () => { + vi.mocked(deps.prisma.syncEvent.findFirst).mockResolvedValue({ + id: 'se-pending', + createdAt: new Date(), + }); + + await guard.recordSync( + 'outpost', + 'github', + 'tkt-1', + 'status_change', + 'hash123', + 'pending', + ); + + expect(deps.prisma.syncEvent.create).not.toHaveBeenCalled(); + }); + + it('resolves the pending row instead of adding a second one', async () => { + vi.mocked(deps.prisma.syncEvent.findFirst).mockResolvedValue({ + id: 'se-pending', + createdAt: new Date(), + }); + + await guard.recordSync( + 'outpost', + 'github', + 'tkt-1', + 'status_change', + 'hash123', + 'success', + ); + + expect(deps.prisma.syncEvent.update).toHaveBeenCalledWith({ + where: { id: 'se-pending' }, + data: { status: 'success', error: null }, + }); + expect(deps.prisma.syncEvent.create).not.toHaveBeenCalled(); + }); }); describe('computeHash', () => { it('produces deterministic hashes for the same input', () => { - const h1 = EchoGuard.computeHash({ entityId: 'tkt-1', action: 'status_change', status: 'OPEN' }); - const h2 = EchoGuard.computeHash({ entityId: 'tkt-1', action: 'status_change', status: 'OPEN' }); + const h1 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'status_change', + status: 'OPEN', + }); + const h2 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'status_change', + status: 'OPEN', + }); expect(h1).toBe(h2); }); it('produces different hashes for different inputs', () => { - const h1 = EchoGuard.computeHash({ entityId: 'tkt-1', action: 'status_change', status: 'OPEN' }); - const h2 = EchoGuard.computeHash({ entityId: 'tkt-1', action: 'status_change', status: 'CLOSED' }); + const h1 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'status_change', + status: 'OPEN', + }); + const h2 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'status_change', + status: 'CLOSED', + }); expect(h1).not.toBe(h2); }); @@ -140,5 +251,60 @@ describe('EchoGuard', () => { const hash = EchoGuard.computeHash({ entityId: 'tkt-1', comment: 'hello' }); expect(hash).toMatch(/^[0-9a-f]{16}$/); }); + + it('does not depend on the order the keys were written in', () => { + const h1 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'comment', + comment: 'hi', + }); + const h2 = EchoGuard.computeHash({ + comment: 'hi', + action: 'comment', + entityId: 'tkt-1', + }); + expect(h1).toBe(h2); + }); + + it('hashes an absent field the same as an undefined one', () => { + const h1 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'comment', + comment: 'hi', + }); + const h2 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'comment', + comment: 'hi', + status: undefined, + }); + expect(h1).toBe(h2); + }); + + it('covers nested keys', () => { + // The old serialiser passed the top-level key list as the + // JSON.stringify replacer, and an array replacer applies to + // nested objects too — so a nested key that was not in the + // top-level list was dropped and two different changes collided. + const h1 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'label_change', + labels: [{ name: 'bug' }], + }); + const h2 = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'label_change', + labels: [{ name: 'feature' }], + }); + + expect(h1).not.toBe(h2); + }); + + it('covers nested keys of a plain nested object', () => { + const h1 = EchoGuard.computeHash({ entityId: 'tkt-1', meta: { a: 1, b: 2 } }); + const h2 = EchoGuard.computeHash({ entityId: 'tkt-1', meta: { a: 1, b: 3 } }); + + expect(h1).not.toBe(h2); + }); }); }); diff --git a/packages/outpost/shared/src/__tests__/sync-engine.test.ts b/packages/outpost/shared/src/__tests__/sync-engine.test.ts index 4556a607..efe4f5f5 100644 --- a/packages/outpost/shared/src/__tests__/sync-engine.test.ts +++ b/packages/outpost/shared/src/__tests__/sync-engine.test.ts @@ -5,6 +5,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { SyncEngine } from '../sync/engine.js'; import type { SyncEngineDeps } from '../sync/engine.js'; +import { EchoGuard } from '../sync/echo-guard.js'; import type { ExternalTracker, InternalTracker, @@ -23,6 +24,7 @@ function makeMockDeps(): SyncEngineDeps { syncEvent: { findFirst: vi.fn().mockResolvedValue(null), create: vi.fn().mockResolvedValue({ id: 'se-1' }), + update: vi.fn().mockResolvedValue({ id: 'se-1' }), }, ticketExternalLink: { findMany: vi.fn().mockResolvedValue([]), @@ -32,6 +34,9 @@ function makeMockDeps(): SyncEngineDeps { findUnique: vi.fn().mockResolvedValue(null), update: vi.fn().mockResolvedValue({}), }, + message: { + create: vi.fn().mockResolvedValue({ id: 'msg-1' }), + }, }, createJob: vi.fn().mockResolvedValue('job-1'), }; @@ -140,7 +145,7 @@ describe('SyncEngine', () => { // Verify the job payloads const calls = vi.mocked(deps.createJob).mock.calls; - const targetPlugins = calls.map(c => (c[1] as Record).targetPlugin); + const targetPlugins = calls.map((c) => (c[1] as Record).targetPlugin); expect(targetPlugins).toContain('gitlab'); expect(targetPlugins).toContain('linear'); expect(targetPlugins).not.toContain('github'); @@ -186,11 +191,13 @@ describe('SyncEngine', () => { // ─── Echo Detection ──────────────────────────────────────────── describe('echo detection', () => { - it('skips fan-out when a matching SyncEvent exists', async () => { + it('skips the fan-out of an inbound change that was already pushed to the plugin', async () => { engine.registerExternalTracker(makeExternalTracker('github')); engine.registerExternalTracker(makeExternalTracker('gitlab')); - // Simulate a recent SyncEvent matching the reverse direction + // A record for this change and this plugin: it is already in + // flight or already delivered, so pushing it again is the echo + // loop the guard exists to stop. vi.mocked(deps.prisma.syncEvent!.findFirst).mockResolvedValue({ id: 'se-existing', createdAt: new Date(), @@ -202,7 +209,9 @@ describe('SyncEngine', () => { status: TicketStatus.CLOSED, }; - const result = await engine.onTicketChange('tkt-1', change, 'github'); + const result = await engine.onTicketChange('tkt-1', change, 'github', { + inbound: true, + }); expect(result.success).toBe(true); // Echo detected, so no jobs should be created @@ -222,10 +231,104 @@ describe('SyncEngine', () => { comment: 'test', }; - const result = await engine.onTicketChange('tkt-1', change, 'github'); + const result = await engine.onTicketChange('tkt-1', change, 'github', { + inbound: true, + }); expect(result.pluginsNotified).toBe(1); }); + + it('does not skip a local change that matches a recent push', async () => { + engine.registerExternalTracker(makeExternalTracker('github')); + engine.registerExternalTracker(makeExternalTracker('gitlab')); + + vi.mocked(deps.prisma.syncEvent!.findFirst).mockResolvedValue({ + id: 'se-existing', + createdAt: new Date(), + }); + + const change: TicketChange = { + externalId: 'ext-1', + action: 'status_change', + status: TicketStatus.CLOSED, + }; + + const result = await engine.onTicketChange('tkt-1', change, 'discord'); + + // The guard compares the CONTENT of two changes, so applying it + // to a local change would drop a legitimate "reopen and resolve + // again" that lands inside the echo window. + expect(result.pluginsNotified).toBe(2); + expect(deps.createJob).toHaveBeenCalledTimes(2); + }); + }); + + // ─── Echo Record ─────────────────────────────────────────────── + + describe('echo record', () => { + it('records the push as pending BEFORE the job is enqueued', async () => { + engine.registerExternalTracker(makeExternalTracker('github')); + + await engine.onTicketChange( + 'tkt-1', + { externalId: 'ext-1', action: 'status_change', status: TicketStatus.CLOSED }, + 'discord', + ); + + expect(deps.prisma.syncEvent!.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + sourcePlugin: 'outpost', + targetPlugin: 'github', + entityId: 'tkt-1', + action: 'status_change', + status: 'pending', + }), + }); + + // The record has to exist before the job does: two changes that + // arrive while the first is still queued both pass a check that + // only looks at what has been enqueued. + const recordOrder = vi.mocked(deps.prisma.syncEvent!.create).mock + .invocationCallOrder[0]; + const jobOrder = vi.mocked(deps.createJob).mock.invocationCallOrder[0]; + expect(recordOrder).toBeLessThan(jobOrder); + }); + + it('marks the record as failed when the job cannot be enqueued', async () => { + engine.registerExternalTracker(makeExternalTracker('github')); + vi.mocked(deps.createJob).mockRejectedValue(new Error('queue down')); + + await engine.onTicketChange( + 'tkt-1', + { externalId: 'ext-1', action: 'status_change', status: TicketStatus.CLOSED }, + 'discord', + ); + + expect(deps.prisma.syncEvent!.create).toHaveBeenCalledWith({ + data: expect.objectContaining({ + status: 'failure', + error: 'queue down', + }), + }); + }); + + it('does not let the target plugin change the hash of a change', async () => { + engine.registerExternalTracker(makeExternalTracker('github')); + engine.registerExternalTracker(makeExternalTracker('gitlab')); + + await engine.onTicketChange( + 'tkt-1', + { externalId: 'ext-1', action: 'status_change', status: TicketStatus.CLOSED }, + 'discord', + ); + + const hashes = vi + .mocked(deps.prisma.syncEvent!.create) + .mock.calls.map((call) => (call[0].data as { payloadHash: string }).payloadHash); + + expect(hashes).toHaveLength(2); + expect(new Set(hashes).size).toBe(1); + }); }); // ─── SyncEvent Recording ─────────────────────────────────────── @@ -374,34 +477,221 @@ describe('SyncEngine', () => { }); }); + // ─── Inbound Application ──────────────────────────────────────── + + describe('onWebhookReceived — applying the change locally', () => { + function linkTo(ticketId: string, plugin: string, externalId: string) { + vi.mocked(deps.prisma.ticketExternalLink.findUnique).mockResolvedValue({ + id: 'link-1', + ticketId, + plugin, + externalId, + externalUrl: null, + metadata: null, + }); + } + + async function receive(tracker: ExternalTracker | InternalTracker, change: TicketChange) { + vi.mocked(tracker.onWebhookReceived).mockResolvedValue(change); + if ('pushNewIssue' in tracker) { + engine.registerInternalTracker(tracker as InternalTracker); + } else { + engine.registerExternalTracker(tracker); + } + return engine.onWebhookReceived(tracker.name, { + plugin: tracker.name, + eventType: 'update', + payload: {}, + }); + } + + it('applies a status change to the ticket', async () => { + const linear = makeInternalTracker('linear'); + linkTo('tkt-1', 'linear', 'lin-1'); + + await receive(linear, { + externalId: 'lin-1', + action: 'status_change', + status: TicketStatus.RESOLVED, + }); + + expect(deps.prisma.ticket.update).toHaveBeenCalledWith({ + where: { id: 'tkt-1' }, + data: { status: TicketStatus.RESOLVED }, + }); + }); + + it('applies a close to the ticket as a closed status', async () => { + const linear = makeInternalTracker('linear'); + linkTo('tkt-1', 'linear', 'lin-1'); + + await receive(linear, { + externalId: 'lin-1', + action: 'close', + }); + + expect(deps.prisma.ticket.update).toHaveBeenCalledWith({ + where: { id: 'tkt-1' }, + data: { status: TicketStatus.CLOSED }, + }); + }); + + it('applies a priority change to the ticket', async () => { + const linear = makeInternalTracker('linear'); + linkTo('tkt-1', 'linear', 'lin-1'); + + await receive(linear, { + externalId: 'lin-1', + action: 'priority_change', + priority: TicketPriority.HIGH, + }); + + expect(deps.prisma.ticket.update).toHaveBeenCalledWith({ + where: { id: 'tkt-1' }, + data: { priority: TicketPriority.HIGH }, + }); + }); + + it('applies an assignee change to the ticket', async () => { + const linear = makeInternalTracker('linear'); + vi.mocked(linear.mapUserToMember).mockResolvedValue({ + id: 'member-1', + name: 'Robin', + email: 'robin@example.com', + }); + linkTo('tkt-1', 'linear', 'lin-1'); + + await receive(linear, { + externalId: 'lin-1', + action: 'assignee_change', + assigneeExternalId: 'user-9', + }); + + expect(deps.prisma.ticket.update).toHaveBeenCalledWith({ + where: { id: 'tkt-1' }, + data: { assigneeId: 'member-1' }, + }); + }); + + it('records an inbound comment as a message on the ticket', async () => { + const linear = makeInternalTracker('linear'); + linkTo('tkt-1', 'linear', 'lin-1'); + + await receive(linear, { + externalId: 'lin-1', + action: 'comment', + comment: 'still broken', + metadata: { senderLogin: 'octocat' }, + }); + + expect(deps.prisma.message!.create).toHaveBeenCalledWith({ + data: { + ticketId: 'tkt-1', + author: 'octocat (linear)', + content: 'still broken', + type: 'USER', + }, + }); + }); + + it('reports a label change as unsupported instead of dropping it', async () => { + const linear = makeInternalTracker('linear'); + linkTo('tkt-1', 'linear', 'lin-1'); + + const result = await receive(linear, { + externalId: 'lin-1', + action: 'label_change', + labels: ['bug'], + }); + + expect(result.success).toBe(false); + expect(result.errors).toHaveLength(1); + expect(result.errors[0].action).toBe('label_change'); + expect(result.errors[0].error).toContain('unsupported'); + }); + + it('reports an assignee that maps to no team member as unsupported', async () => { + const linear = makeInternalTracker('linear'); + vi.mocked(linear.mapUserToMember).mockResolvedValue(null); + linkTo('tkt-1', 'linear', 'lin-1'); + + const result = await receive(linear, { + externalId: 'lin-1', + action: 'assignee_change', + assigneeExternalId: 'user-9', + }); + + expect(result.success).toBe(false); + expect(result.errors[0].error).toContain('no team member'); + }); + + it('does not fan out a change that is our own push coming back', async () => { + const linear = makeInternalTracker('linear'); + linkTo('tkt-1', 'linear', 'lin-1'); + const other = makeExternalTracker('github'); + engine.registerExternalTracker(other); + + // A record for this change and this tracker: we pushed it, and + // the tracker is handing it back. + vi.mocked(deps.prisma.syncEvent!.findFirst).mockResolvedValue({ + id: 'se-existing', + createdAt: new Date(), + }); + + const result = await receive(linear, { + externalId: 'lin-1', + action: 'status_change', + status: TicketStatus.RESOLVED, + }); + + expect(result.pluginsNotified).toBe(0); + expect(deps.createJob).not.toHaveBeenCalled(); + }); + }); + // ─── Hash Computation ────────────────────────────────────────── describe('computeHash', () => { it('produces deterministic hashes for the same input', () => { - const h1 = engine.computeHash('tkt-1', 'github', 'status_change', { + const h1 = engine.computeHash('tkt-1', 'status_change', { status: 'RESOLVED', }); - const h2 = engine.computeHash('tkt-1', 'github', 'status_change', { + const h2 = engine.computeHash('tkt-1', 'status_change', { status: 'RESOLVED', }); expect(h1).toBe(h2); }); it('produces different hashes for different inputs', () => { - const h1 = engine.computeHash('tkt-1', 'github', 'status_change', { + const h1 = engine.computeHash('tkt-1', 'status_change', { status: 'RESOLVED', }); - const h2 = engine.computeHash('tkt-1', 'github', 'status_change', { + const h2 = engine.computeHash('tkt-1', 'status_change', { status: 'CLOSED', }); expect(h1).not.toBe(h2); }); it('returns a 16-character hex string', () => { - const hash = engine.computeHash('tkt-1', 'github', 'comment', { + const hash = engine.computeHash('tkt-1', 'comment', { comment: 'hello', }); expect(hash).toMatch(/^[0-9a-f]{16}$/); }); + + it('does not depend on the plugin the change is pushed to', () => { + // The hash covers the change, not its destination: a change that + // comes back from a tracker has to hash the same as the push + // that caused it, or the guard cannot recognise its own echo. + const viaEngine = engine.computeHash('tkt-1', 'status_change', { + status: 'RESOLVED', + }); + const viaGuard = EchoGuard.computeHash({ + entityId: 'tkt-1', + action: 'status_change', + status: 'RESOLVED', + }); + expect(viaEngine).toBe(viaGuard); + }); }); }); diff --git a/packages/outpost/shared/src/__tests__/sync-integration.test.ts b/packages/outpost/shared/src/__tests__/sync-integration.test.ts index fb599bc2..f68c5e4b 100644 --- a/packages/outpost/shared/src/__tests__/sync-integration.test.ts +++ b/packages/outpost/shared/src/__tests__/sync-integration.test.ts @@ -71,19 +71,24 @@ function createSyncEventStore() { // Source/target matching (supports { not: ... } syntax) if (w.sourcePlugin) { if (typeof w.sourcePlugin === 'object' && 'not' in w.sourcePlugin) { - if (e.sourcePlugin === (w.sourcePlugin as { not: string }).not) return false; + if (e.sourcePlugin === (w.sourcePlugin as { not: string }).not) + return false; } else if (e.sourcePlugin !== w.sourcePlugin) return false; } if (w.targetPlugin) { if (typeof w.targetPlugin === 'object' && 'not' in w.targetPlugin) { - if (e.targetPlugin === (w.targetPlugin as { not: string }).not) return false; + if (e.targetPlugin === (w.targetPlugin as { not: string }).not) + return false; } else if (e.targetPlugin !== w.targetPlugin) return false; } - // Status filtering (for conflict detector: { not: 'conflict' }) + // Status filtering (conflict detector: { not: 'conflict' }; echo + // guard: { in: ['pending', 'success'] }) if (w.status) { if (typeof w.status === 'object' && 'not' in w.status) { if (e.status === (w.status as { not: string }).not) return false; + } else if (typeof w.status === 'object' && 'in' in w.status) { + if (!(w.status as { in: string[] }).in.includes(e.status)) return false; } else if (e.status !== w.status) return false; } @@ -94,7 +99,16 @@ function createSyncEventStore() { return true; }); - return match ? { id: match.id, createdAt: match.createdAt, sourcePlugin: match.sourcePlugin, targetPlugin: match.targetPlugin, action: match.action, payloadHash: match.payloadHash } : null; + return match + ? { + id: match.id, + createdAt: match.createdAt, + sourcePlugin: match.sourcePlugin, + targetPlugin: match.targetPlugin, + action: match.action, + payloadHash: match.payloadHash, + } + : null; }), create: vi.fn(async (args: { data: Record }) => { const id = `se-${nextId++}`; @@ -113,6 +127,16 @@ function createSyncEventStore() { events.push(event); return { id }; }), + update: vi.fn( + async (args: { where: Record; data: Record }) => { + const event = events.find((e) => e.id === args.where.id); + if (event) { + event.status = args.data.status as string; + event.error = (args.data.error as string) ?? null; + } + return event; + }, + ), }; } @@ -303,8 +327,13 @@ describe('SyncEngine edge cases and failure paths', () => { await expect( engine.recordSyncEvent( - 'outpost', 'github', 'ticket', 'tkt-1', - 'status_change', 'hash', 'success', + 'outpost', + 'github', + 'ticket', + 'tkt-1', + 'status_change', + 'hash', + 'success', ), ).rejects.toThrow('DB write failed'); }); @@ -312,7 +341,7 @@ describe('SyncEngine edge cases and failure paths', () => { describe('computeHash edge cases', () => { it('handles null/undefined values in change data', () => { - const h1 = engine.computeHash('tkt-1', 'github', 'status_change', { + const h1 = engine.computeHash('tkt-1', 'status_change', { status: undefined, priority: null, comment: undefined, @@ -323,7 +352,7 @@ describe('SyncEngine edge cases and failure paths', () => { }); it('handles empty string change data', () => { - const h = engine.computeHash('tkt-1', 'github', 'comment', { + const h = engine.computeHash('tkt-1', 'comment', { comment: '', }); expect(h).toMatch(/^[0-9a-f]{16}$/); @@ -343,9 +372,9 @@ describe('EchoGuard edge cases', () => { }; const guard = new EchoGuard(deps, 60_000); - await expect( - guard.shouldSync('linear', 'github', 'tkt-1', 'hash123'), - ).rejects.toThrow('DB read error'); + await expect(guard.shouldSync('github', 'tkt-1', 'hash123')).rejects.toThrow( + 'DB read error', + ); }); it('handles Prisma failure in recordSync gracefully', async () => { @@ -377,9 +406,9 @@ describe('ConflictDetector edge cases', () => { }; const detector = new ConflictDetector(deps, 60_000); - await expect( - detector.detectConflict('linear', 'tkt-1', 'status_change'), - ).rejects.toThrow('DB read error'); + await expect(detector.detectConflict('linear', 'tkt-1', 'status_change')).rejects.toThrow( + 'DB read error', + ); }); it('resolves conflict with null values', () => { @@ -425,7 +454,13 @@ describe('fanoutToGitHub failure paths', () => { expect(result.pushed).toBe(false); expect(result.error).toBe('Rate limited'); expect(deps.echoGuard.recordSync).toHaveBeenCalledWith( - 'linear', 'github', 'tkt-1', 'comment', expect.any(String), 'failure', 'Rate limited', + 'linear', + 'github', + 'tkt-1', + 'comment', + expect.any(String), + 'failure', + 'Rate limited', ); }); @@ -437,7 +472,13 @@ describe('fanoutToGitHub failure paths', () => { expect(result.pushed).toBe(false); expect(result.error).toBe('Not Found'); expect(deps.echoGuard.recordSync).toHaveBeenCalledWith( - 'linear', 'github', 'tkt-1', 'label_change', expect.any(String), 'failure', 'Not Found', + 'linear', + 'github', + 'tkt-1', + 'label_change', + expect.any(String), + 'failure', + 'Not Found', ); }); @@ -744,13 +785,14 @@ describe('Integration: Linear webhook -> Outpost -> GitHub fan-out', () => { }; const fanoutResult = await fanoutStatusChange( - fanoutDeps, githubLink, TicketStatus.RESOLVED, 'linear', + fanoutDeps, + githubLink, + TicketStatus.RESOLVED, + 'linear', ); expect(fanoutResult.pushed).toBe(true); - expect(github.pushStatusChange).toHaveBeenCalledWith( - githubLink, TicketStatus.RESOLVED, - ); + expect(github.pushStatusChange).toHaveBeenCalledWith(githubLink, TicketStatus.RESOLVED); }); }); @@ -759,10 +801,7 @@ describe('Integration: Echo prevention flow', () => { // Use a real in-memory sync event store const store = createSyncEventStore(); - const echoGuard = new EchoGuard( - { prisma: { syncEvent: store } }, - 60_000, - ); + const echoGuard = new EchoGuard({ prisma: { syncEvent: store } }, 60_000); const fanoutDeps: GitHubFanoutDeps = { adapter: { @@ -777,68 +816,48 @@ describe('Integration: Echo prevention flow', () => { echoGuard, }; - // Step 1: Outpost pushes status change to GitHub (simulating the outbound push) - // Record that we pushed from "linear" to "github" for ticket tkt-1 + // Step 1: Outpost pushes the status change to GitHub. A push is + // recorded with the plugin it was pushed TO as the target, so this + // is the row the guard has to find. const hash = EchoGuard.computeHash({ entityId: 'tkt-1', action: 'status_change', status: TicketStatus.RESOLVED, }); - await echoGuard.recordSync( - 'linear', 'github', 'tkt-1', 'status_change', hash, 'success', - ); + await echoGuard.recordSync('outpost', 'github', 'tkt-1', 'status_change', hash, 'success'); // Verify the sync event was recorded expect(store.events).toHaveLength(1); - expect(store.events[0].sourcePlugin).toBe('linear'); + expect(store.events[0].sourcePlugin).toBe('outpost'); expect(store.events[0].targetPlugin).toBe('github'); - // Step 2: GitHub fires a webhook back with the same change - // This simulates GitHub echoing back the status we just pushed - // The fan-out would check shouldSync from github -> linear - const shouldSync = await echoGuard.shouldSync( - 'github', 'linear', 'tkt-1', hash, - ); + // Step 2: GitHub fires a webhook back with the same change. + // This simulates GitHub echoing back the status we just pushed. + // The inbound path asks whether this change was already pushed TO + // github — which is the direction a push is recorded in. + const shouldSync = await echoGuard.shouldSync('github', 'tkt-1', hash); // Step 3: Echo should be detected expect(shouldSync).toBe(false); - // Step 4: fanoutStatusChange should skip the push - // Swap source/target for the echo scenario + // Step 4: the fan-out to GitHub is blocked, so the change is not + // pushed back to the plugin that handed it to us. const echoResult = await fanoutStatusChange( - fanoutDeps, githubLink, TicketStatus.RESOLVED, 'github', - ); - - // The echo guard uses github->linear direction, but fanoutStatusChange - // pushes to github. Let's verify that the actual fanout with the echo - // guard correctly blocks when it detects the echo. - // Create a guard where shouldSync returns false for this specific case. - const mockGuard = { - shouldSync: vi.fn().mockResolvedValue(false), - recordSync: vi.fn().mockResolvedValue(undefined), - } as never; - - const echoDeps: GitHubFanoutDeps = { - adapter: fanoutDeps.adapter, - echoGuard: mockGuard, - }; - - const blockedResult = await fanoutStatusChange( - echoDeps, githubLink, TicketStatus.RESOLVED, 'linear', + fanoutDeps, + githubLink, + TicketStatus.RESOLVED, + 'github', ); - expect(blockedResult.pushed).toBe(false); - expect(blockedResult.skippedReason).toBe('echo detected'); - expect(fanoutDeps.adapter.pushStatusChange).toHaveBeenCalledTimes(1); + expect(echoResult.pushed).toBe(false); + expect(echoResult.skippedReason).toBe('echo detected'); + expect(fanoutDeps.adapter.pushStatusChange).not.toHaveBeenCalled(); }); it('allows sync when the payload hash differs (genuine change, not echo)', async () => { const store = createSyncEventStore(); - const echoGuard = new EchoGuard( - { prisma: { syncEvent: store } }, - 60_000, - ); + const echoGuard = new EchoGuard({ prisma: { syncEvent: store } }, 60_000); // Record a push of RESOLVED const hash1 = EchoGuard.computeHash({ @@ -846,9 +865,7 @@ describe('Integration: Echo prevention flow', () => { action: 'status_change', status: TicketStatus.RESOLVED, }); - await echoGuard.recordSync( - 'linear', 'github', 'tkt-1', 'status_change', hash1, 'success', - ); + await echoGuard.recordSync('linear', 'github', 'tkt-1', 'status_change', hash1, 'success'); // Now check for a DIFFERENT status change (CLOSED instead of RESOLVED) const hash2 = EchoGuard.computeHash({ @@ -857,9 +874,7 @@ describe('Integration: Echo prevention flow', () => { status: TicketStatus.CLOSED, }); - const shouldSync = await echoGuard.shouldSync( - 'github', 'linear', 'tkt-1', hash2, - ); + const shouldSync = await echoGuard.shouldSync('github', 'tkt-1', hash2); // Different hash = not an echo, should proceed expect(shouldSync).toBe(true); @@ -869,10 +884,7 @@ describe('Integration: Echo prevention flow', () => { describe('Integration: Conflict detection flow', () => { it('detects conflict when GitHub and Linear modify the same ticket status simultaneously', async () => { const store = createSyncEventStore(); - const detector = new ConflictDetector( - { prisma: { syncEvent: store } }, - 60_000, - ); + const detector = new ConflictDetector({ prisma: { syncEvent: store } }, 60_000); // Step 1: GitHub pushes a status change for tkt-1 await store.create({ @@ -898,7 +910,7 @@ describe('Integration: Conflict detection flow', () => { expect(conflict!.field).toBe('status_change'); // Step 4: A conflict SyncEvent was logged - const conflictEvents = store.events.filter(e => e.status === 'conflict'); + const conflictEvents = store.events.filter((e) => e.status === 'conflict'); expect(conflictEvents).toHaveLength(1); expect(conflictEvents[0].error).toContain('Conflict'); expect(conflictEvents[0].error).toContain('linear'); @@ -911,10 +923,7 @@ describe('Integration: Conflict detection flow', () => { it('does not detect conflict for different actions on the same ticket', async () => { const store = createSyncEventStore(); - const detector = new ConflictDetector( - { prisma: { syncEvent: store } }, - 60_000, - ); + const detector = new ConflictDetector({ prisma: { syncEvent: store } }, 60_000); // GitHub pushes a comment await store.create({ @@ -938,10 +947,7 @@ describe('Integration: Conflict detection flow', () => { it('does not detect conflict from the same source', async () => { const store = createSyncEventStore(); - const detector = new ConflictDetector( - { prisma: { syncEvent: store } }, - 60_000, - ); + const detector = new ConflictDetector({ prisma: { syncEvent: store } }, 60_000); // Linear pushes a status change await store.create({ @@ -1008,8 +1014,8 @@ describe('Integration: Full round-trip flow', () => { // Both linear and github should be notified expect(jobsEnqueued).toHaveLength(2); - const linearJob = jobsEnqueued.find(j => j.payload.targetPlugin === 'linear'); - const githubJob = jobsEnqueued.find(j => j.payload.targetPlugin === 'github'); + const linearJob = jobsEnqueued.find((j) => j.payload.targetPlugin === 'linear'); + const githubJob = jobsEnqueued.find((j) => j.payload.targetPlugin === 'github'); expect(linearJob).toBeDefined(); expect(githubJob).toBeDefined(); expect(linearJob!.payload.action).toBe('new_issue'); @@ -1112,16 +1118,24 @@ describe('Integration: Concurrent sync events for the same ticket', () => { // Fire two changes concurrently on the same ticket const [statusResult, priorityResult] = await Promise.all([ - engine.onTicketChange('tkt-concurrent', { - externalId: '', - action: 'status_change', - status: TicketStatus.RESOLVED, - }, 'discord'), - engine.onTicketChange('tkt-concurrent', { - externalId: '', - action: 'priority_change', - priority: TicketPriority.CRITICAL, - }, 'discord'), + engine.onTicketChange( + 'tkt-concurrent', + { + externalId: '', + action: 'status_change', + status: TicketStatus.RESOLVED, + }, + 'discord', + ), + engine.onTicketChange( + 'tkt-concurrent', + { + externalId: '', + action: 'priority_change', + priority: TicketPriority.CRITICAL, + }, + 'discord', + ), ]); // Both should succeed independently @@ -1132,9 +1146,7 @@ describe('Integration: Concurrent sync events for the same ticket', () => { expect(jobsEnqueued).toHaveLength(4); // Verify all four jobs have distinct action+plugin combinations - const signatures = jobsEnqueued.map( - j => `${j.payload.action}-${j.payload.targetPlugin}`, - ); + const signatures = jobsEnqueued.map((j) => `${j.payload.action}-${j.payload.targetPlugin}`); expect(signatures).toContain('status_change-linear'); expect(signatures).toContain('status_change-github'); expect(signatures).toContain('priority_change-linear'); @@ -1214,10 +1226,7 @@ describe('Integration: Ticket with no external/internal tracker set', () => { describe('Integration: Duplicate sync events', () => { it('echo guard prevents duplicate push for identical payload within echo window', async () => { const store = createSyncEventStore(); - const echoGuard = new EchoGuard( - { prisma: { syncEvent: store } }, - 60_000, - ); + const echoGuard = new EchoGuard({ prisma: { syncEvent: store } }, 60_000); const hash = EchoGuard.computeHash({ entityId: 'tkt-1', @@ -1226,14 +1235,15 @@ describe('Integration: Duplicate sync events', () => { }); // First push succeeds and records the event - expect(await echoGuard.shouldSync('outpost', 'github', 'tkt-1', hash)).toBe(true); + expect(await echoGuard.shouldSync('github', 'tkt-1', hash)).toBe(true); await echoGuard.recordSync('outpost', 'github', 'tkt-1', 'comment', hash, 'success'); - // Second push with same hash from github->outpost direction would be an echo - expect(await echoGuard.shouldSync('github', 'outpost', 'tkt-1', hash)).toBe(false); + // The same change pushed to github again is an echo of the first push + expect(await echoGuard.shouldSync('github', 'tkt-1', hash)).toBe(false); - // But a push from a different plugin is NOT an echo (it's an independent change) - expect(await echoGuard.shouldSync('gitlab', 'outpost', 'tkt-1', hash)).toBe(true); + // But the same change pushed to a different plugin is NOT an echo + // (it's an independent change) + expect(await echoGuard.shouldSync('gitlab', 'tkt-1', hash)).toBe(true); }); }); @@ -1259,16 +1269,17 @@ describe('Integration: SyncEngine echo detection in onTicketChange', () => { engine.registerExternalTracker(makeExternalTracker('github')); engine.registerInternalTracker(makeInternalTracker('linear')); - // Pre-record a sync event: linear pushed status_change to github for tkt-1 - // This means if github now tries to push back, it's an echo. - const hash = engine.computeHash('tkt-1', 'github', 'status_change', { + // Pre-record a sync event: outpost pushed status_change to github for + // tkt-1. A push is recorded with the plugin it was pushed TO as the + // target, so this is the row the guard has to find. + const hash = engine.computeHash('tkt-1', 'status_change', { status: TicketStatus.RESOLVED, }); await store.create({ data: { - sourcePlugin: 'github', - targetPlugin: 'linear', + sourcePlugin: 'outpost', + targetPlugin: 'github', entityType: 'ticket', entityId: 'tkt-1', action: 'status_change', @@ -1278,15 +1289,21 @@ describe('Integration: SyncEngine echo detection in onTicketChange', () => { }, }); - // Now linear tries to push the same change to github — should be detected as echo - const result = await engine.onTicketChange('tkt-1', { - externalId: 'ext-1', - action: 'status_change', - status: TicketStatus.RESOLVED, - }, 'linear'); + // Now the same change comes back inbound and is fanned out to github + // — it is our own push coming back, so it must not be pushed again. + const result = await engine.onTicketChange( + 'tkt-1', + { + externalId: 'ext-1', + action: 'status_change', + status: TicketStatus.RESOLVED, + }, + 'linear', + { inbound: true }, + ); - // github was the target, and a matching event exists from github->linear - // So the engine should skip github + // github was the target, and a matching record says it was already + // pushed there — so the engine skips github expect(result.pluginsNotified).toBe(0); expect(deps.createJob).not.toHaveBeenCalled(); }); diff --git a/packages/outpost/shared/src/sync/echo-guard.ts b/packages/outpost/shared/src/sync/echo-guard.ts index 9798c81a..1faa4127 100644 --- a/packages/outpost/shared/src/sync/echo-guard.ts +++ b/packages/outpost/shared/src/sync/echo-guard.ts @@ -7,9 +7,9 @@ * * Usage: * const guard = new EchoGuard(deps); - * if (await guard.shouldSync('linear', 'github', ticketId, hash)) { + * if (await guard.shouldSync('github', ticketId, hash)) { * await doPush(); - * await guard.recordSync('linear', 'github', ticketId, 'status_change', hash, 'success'); + * await guard.recordSync('outpost', 'github', ticketId, 'status_change', hash, 'success'); * } */ @@ -25,6 +25,15 @@ export interface EchoGuardDeps { orderBy?: Record; }) => Promise<{ id: string; createdAt: Date } | null>; create: (args: { data: Record }) => Promise<{ id: string }>; + /** + * Optional so a caller that only ever records events keeps working. + * Without it, a pending row is left as it is and the outcome is + * recorded as a second row. + */ + update?: (args: { + where: Record; + data: Record; + }) => Promise; }; }; } @@ -35,6 +44,15 @@ export type SyncEventStatus = 'pending' | 'success' | 'failure' | 'conflict'; const DEFAULT_ECHO_WINDOW_MS = 60_000; +/** + * The statuses that mean "this change is already in flight or already + * delivered", and therefore must not be pushed again. + * + * A `failure` is deliberately NOT here: a push that failed has to be + * retryable, so it must not block the next attempt. + */ +const BLOCKING_STATUSES: SyncEventStatus[] = ['pending', 'success']; + // ─── EchoGuard ──────────────────────────────────────────────────────────── export class EchoGuard { @@ -43,23 +61,30 @@ export class EchoGuard { constructor(deps: EchoGuardDeps, echoWindowMs?: number) { this.deps = deps; - this.echoWindowMs = echoWindowMs - ?? (parseInt(process.env.SYNC_ECHO_WINDOW_MS ?? '', 10) - || DEFAULT_ECHO_WINDOW_MS); + this.echoWindowMs = + echoWindowMs ?? + (parseInt(process.env.SYNC_ECHO_WINDOW_MS ?? '', 10) || DEFAULT_ECHO_WINDOW_MS); } /** - * Check whether this sync should proceed. + * Check whether this change may be pushed to `targetPlugin`. + * + * Returns false if a SyncEvent for this exact change and this exact + * target exists within the echo window, meaning the change is already + * in flight or has already been delivered to that plugin. * - * Returns false if a matching SyncEvent exists within the echo window, - * meaning the change is a bounce-back from our own push. + * The query matches the direction pushes are actually RECORDED in. A + * push is recorded with the plugin it was pushed TO as the target (see + * `recordSync`), so the record that matters is the one whose target is + * the destination of the push. The old query looked for the reverse + * pair — source = destination, target = origin — which no push has ever + * produced, so the guard could not fire no matter what was in the table. * - * The check looks for a recent event where the target pushed TO the source - * (reverse direction) with the same payload hash — that means we already - * pushed this exact change and the source is echoing it back. + * The source is deliberately not part of the match: a push is a push + * whichever plugin the change came from, and the records are written + * with different sources by different callers. */ async shouldSync( - sourcePlugin: string, targetPlugin: string, entityId: string, payloadHash: string, @@ -69,9 +94,9 @@ export class EchoGuard { const existing = await this.deps.prisma.syncEvent.findFirst({ where: { entityId, - sourcePlugin: targetPlugin, - targetPlugin: sourcePlugin, + targetPlugin, payloadHash, + status: { in: [...BLOCKING_STATUSES] }, createdAt: { gte: cutoff }, }, orderBy: { createdAt: 'desc' }, @@ -81,7 +106,13 @@ export class EchoGuard { } /** - * Record a SyncEvent after a sync operation completes. + * Record a SyncEvent for a sync operation. + * + * `pending` is written BEFORE the work is enqueued, so a second change + * that arrives while the first is still in flight finds the row and is + * not pushed a second time. The outcome (`success` / `failure`) then + * resolves that same row rather than adding another one, so a push + * leaves one row behind, not two. */ async recordSync( sourcePlugin: string, @@ -92,6 +123,32 @@ export class EchoGuard { status: SyncEventStatus, error?: string, ): Promise { + const where = { + entityId, + sourcePlugin, + targetPlugin, + action, + payloadHash, + status: 'pending', + }; + + const pending = await this.deps.prisma.syncEvent.findFirst({ + where, + orderBy: { createdAt: 'desc' }, + }); + + if (status === 'pending') { + // Already recorded as in flight. A second identical change does + // not need a second row. + if (pending) return; + } else if (pending && this.deps.prisma.syncEvent.update) { + await this.deps.prisma.syncEvent.update({ + where: { id: pending.id }, + data: { status, error: error ?? null }, + }); + return; + } + await this.deps.prisma.syncEvent.create({ data: { sourcePlugin, @@ -109,9 +166,44 @@ export class EchoGuard { /** * Compute a deterministic hash for a sync payload. * Used as the payloadHash for echo detection. + * + * The payload is serialised with its keys sorted at EVERY level, so the + * hash depends only on the content and not on the order the fields were + * written in. The old implementation passed the top-level key list as + * the JSON.stringify replacer, and an array replacer applies to every + * nested object too — so any key that was not in the top-level list + * was dropped from nested objects, and two different changes could + * collide on one hash. */ static computeHash(parts: Record): string { - const canonical = JSON.stringify(parts, Object.keys(parts).sort()); + const canonical = JSON.stringify(sortKeysDeep(parts)); return createHash('sha256').update(canonical).digest('hex').slice(0, 16); } } + +// ─── Canonical Serialisation ────────────────────────────────────────────── + +/** + * Recursively sort object keys so the JSON is stable. + * + * Arrays keep their order: a list of labels is a set in meaning, but its + * order is part of what was pushed, and reordering it here would make a + * reordered list look like a different change. + */ +function sortKeysDeep(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(sortKeysDeep); + } + if (value !== null && typeof value === 'object') { + const source = value as Record; + const sorted: Record = {}; + for (const key of Object.keys(source).sort()) { + // `undefined` is dropped by JSON.stringify, which is what makes + // "field absent" and "field present but unset" hash the same. + if (source[key] === undefined) continue; + sorted[key] = sortKeysDeep(source[key]); + } + return sorted; + } + return value; +} diff --git a/packages/outpost/shared/src/sync/engine.ts b/packages/outpost/shared/src/sync/engine.ts index aaf47abb..f1a64292 100644 --- a/packages/outpost/shared/src/sync/engine.ts +++ b/packages/outpost/shared/src/sync/engine.ts @@ -16,6 +16,7 @@ import type { TicketChangeAction, } from './types.js'; import { EchoGuard } from './echo-guard.js'; +import { TicketStatus } from '../types.js'; // ─── Types for Dependencies ──────────────────────────────────────────────── @@ -31,21 +32,23 @@ export interface SyncEngineDeps { orderBy?: Record; }) => Promise<{ id: string; createdAt: Date } | null>; create: (args: { data: Record }) => Promise<{ id: string }>; + update?: (args: { + where: Record; + data: Record; + }) => Promise; }; ticketExternalLink: { - findMany: (args: { - where: Record; - }) => Promise | null; - }>>; - findUnique: (args: { - where: Record; - }) => Promise<{ + findMany: (args: { where: Record }) => Promise< + Array<{ + id: string; + ticketId: string; + plugin: string; + externalId: string; + externalUrl?: string | null; + metadata?: Record | null; + }> + >; + findUnique: (args: { where: Record }) => Promise<{ id: string; ticketId: string; plugin: string; @@ -64,11 +67,36 @@ export interface SyncEngineDeps { data: Record; }) => Promise>; }; + /** + * Optional: a deployment that cannot record messages still works, and + * reports inbound comments as unsupported instead of pretending they + * were applied. + */ + message?: { + create: (args: { data: Record }) => Promise<{ id: string }>; + }; }; createJob: (type: string, payload: Record) => Promise; echoGuard?: EchoGuard; } +/** The plugin every outbound push is recorded as coming from. */ +const OUTBOUND_SOURCE = 'outpost'; + +/** Options for a fan-out. */ +export interface FanoutOptions { + /** + * True when the change arrived FROM a tracker rather than from Outpost. + * + * Inbound changes are the ones that can be echoes of our own push, so + * they are the ones the echo guard applies to. A local change is always + * pushed: the guard compares the CONTENT of two changes, so a local + * "reopen and resolve again" inside the echo window would otherwise be + * mistaken for a repeat and dropped. + */ + inbound?: boolean; +} + // ─── SyncEngine ──────────────────────────────────────────────────────────── export class SyncEngine { @@ -114,10 +142,7 @@ export class SyncEngine { /** Get all registered plugin names. */ getPluginNames(): string[] { - return [ - ...this.externalTrackers.keys(), - ...this.internalTrackers.keys(), - ]; + return [...this.externalTrackers.keys(), ...this.internalTrackers.keys()]; } /** Check if a plugin is an InternalTracker. */ @@ -137,39 +162,52 @@ export class SyncEngine { ticketId: string, change: TicketChange, sourcePlugin: string, + options?: FanoutOptions, ): Promise { const errors: SyncEngineError[] = []; let pluginsNotified = 0; const allPluginNames = this.getPluginNames(); + const inbound = options?.inbound === true; + + // One hash for the whole change. It must not depend on the plugin it + // is pushed to: the same change arriving from a tracker has to hash + // the same as the one we pushed, or the echo guard cannot recognise + // it as its own. + const payloadHash = this.computeHash(ticketId, change.action, change); for (const pluginName of allPluginNames) { if (pluginName === sourcePlugin) { continue; } - const payloadHash = EchoGuard.computeHash({ - entityId: ticketId, - targetPlugin: pluginName, - action: change.action, - status: change.status, - priority: change.priority, - comment: change.comment, - labels: change.labels, - }); + // Echo detection: skip if this exact change is already in flight + // or already delivered to this plugin. Only inbound changes can + // be echoes of our own push. + if (inbound) { + const shouldSync = await this.echoGuard.shouldSync( + pluginName, + ticketId, + payloadHash, + ); + if (!shouldSync) { + continue; + } + } - // Echo detection: skip if we recently synced this exact change - const shouldSync = await this.echoGuard.shouldSync( - sourcePlugin, + // Record the intent BEFORE enqueueing. Two changes that arrive + // while the first is still queued must not both pass the guard, + // and the record is the only thing that can say so — the job + // does not exist yet. + await this.echoGuard.recordSync( + OUTBOUND_SOURCE, pluginName, ticketId, + change.action, payloadHash, + 'pending', ); - if (!shouldSync) { - continue; - } - try { await this.deps.createJob('TRACKER_SYNC', { ticketId, @@ -180,6 +218,17 @@ export class SyncEngine { pluginsNotified++; } catch (err) { const message = err instanceof Error ? err.message : String(err); + // The push never happened, so the row must not keep saying it + // is in flight — otherwise it would block the retry. + await this.echoGuard.recordSync( + OUTBOUND_SOURCE, + pluginName, + ticketId, + change.action, + payloadHash, + 'failure', + message, + ); errors.push({ plugin: pluginName, action: change.action, @@ -205,20 +254,19 @@ export class SyncEngine { * 3. If the change maps to an existing ticket, update it and fan out * 4. Return the sync result */ - async onWebhookReceived( - pluginName: string, - event: WebhookEvent, - ): Promise { + async onWebhookReceived(pluginName: string, event: WebhookEvent): Promise { const plugin = this.getPlugin(pluginName); if (!plugin) { return { success: false, pluginsNotified: 0, - errors: [{ - plugin: pluginName, - action: 'webhook', - error: `Plugin "${pluginName}" is not registered`, - }], + errors: [ + { + plugin: pluginName, + action: 'webhook', + error: `Plugin "${pluginName}" is not registered`, + }, + ], }; } @@ -243,39 +291,159 @@ export class SyncEngine { return { success: true, pluginsNotified: 0, errors: [] }; } - // Apply the change locally if it's a status update - if (change.action === 'status_change' && change.status) { - await this.deps.prisma.ticket.update({ - where: { id: link.ticketId }, - data: { status: change.status }, - }); + const payloadHash = this.computeHash(link.ticketId, change.action, change); + + // The change came from this tracker. If we pushed this exact change + // to it moments ago, this is our own change coming back, and fanning + // it out again is the echo loop the guard exists to stop. + const shouldSync = await this.echoGuard.shouldSync(pluginName, link.ticketId, payloadHash); + if (!shouldSync) { + return { success: true, pluginsNotified: 0, errors: [] }; } + // Apply the change to the local ticket. A change that cannot be + // applied is REPORTED, not dropped: the caller is told the sync did + // not do what it says it did. + const applyErrors = await this.applyInboundChange(link.ticketId, change, plugin); + // Fan out to other plugins - return this.onTicketChange(link.ticketId, change, pluginName); + const result = await this.onTicketChange(link.ticketId, change, pluginName, { + inbound: true, + }); + + const errors = [...applyErrors, ...result.errors]; + return { + success: errors.length === 0, + pluginsNotified: result.pluginsNotified, + errors, + }; } - // ─── Echo Detection (delegated to EchoGuard) ────────────────────── + // ─── Inbound Application ─────────────────────────────────────────── /** - * Check if a matching SyncEvent was created recently, indicating - * this change is an echo (bounce-back from our own push). + * Apply a change that arrived from a tracker to the local ticket. + * + * Only the changes the local data model can express are applied. A + * change that cannot be applied — a label list on a ticket that has no + * labels column, a comment in a deployment that cannot record messages — + * is reported as an error. The old behaviour was to drop it and report + * success, which made a sync that did nothing look like a sync that + * worked. */ - async isEchoEvent( - entityId: string, - sourcePlugin: string, - targetPlugin: string, - payloadHash: string, - ): Promise { - const shouldSync = await this.echoGuard.shouldSync( - sourcePlugin, - targetPlugin, - entityId, - payloadHash, - ); - return !shouldSync; + private async applyInboundChange( + ticketId: string, + change: TicketChange, + plugin: ExternalTracker | InternalTracker, + ): Promise { + const errors: SyncEngineError[] = []; + const unsupported = (reason: string): void => { + errors.push({ + plugin: plugin.name, + action: change.action, + error: `unsupported: ${reason}`, + }); + }; + + switch (change.action) { + case 'status_change': { + if (!change.status) { + unsupported('the tracker reported a status change with no status'); + break; + } + await this.deps.prisma.ticket.update({ + where: { id: ticketId }, + data: { status: change.status }, + }); + break; + } + + case 'close': { + await this.deps.prisma.ticket.update({ + where: { id: ticketId }, + data: { status: TicketStatus.CLOSED }, + }); + break; + } + + case 'priority_change': { + if (!change.priority) { + unsupported('the tracker reported a priority change with no priority'); + break; + } + await this.deps.prisma.ticket.update({ + where: { id: ticketId }, + data: { priority: change.priority }, + }); + break; + } + + case 'assignee_change': { + if (!change.assigneeExternalId) { + unsupported('the tracker reported an assignee change with no assignee'); + break; + } + if (!this.isInternalTracker(plugin.name)) { + unsupported(`"${plugin.name}" cannot map external users to team members`); + break; + } + const member = await (plugin as InternalTracker).mapUserToMember( + change.assigneeExternalId, + ); + if (!member) { + unsupported( + `no team member matches the external user "${change.assigneeExternalId}"`, + ); + break; + } + await this.deps.prisma.ticket.update({ + where: { id: ticketId }, + data: { assigneeId: member.id }, + }); + break; + } + + case 'comment': { + if (!change.comment) { + unsupported('the tracker reported a comment with no body'); + break; + } + if (!this.deps.prisma.message) { + unsupported('this deployment cannot record messages'); + break; + } + await this.deps.prisma.message.create({ + data: { + ticketId, + author: inboundAuthor(change, plugin.name), + content: change.comment, + type: 'USER', + }, + }); + break; + } + + case 'label_change': { + unsupported('Outpost tickets have no labels field'); + break; + } + + case 'new_issue': { + unsupported('the linked ticket already exists'); + break; + } + + default: { + unsupported(`unknown action "${String(change.action)}"`); + break; + } + } + + return errors; } + // ─── Echo Detection (delegated to EchoGuard) ────────────────────── + /** * Record a SyncEvent after a push completes (success or failure). */ @@ -302,21 +470,41 @@ export class SyncEngine { // ─── Helpers ─────────────────────────────────────────────────────── - /** Compute a deterministic hash for echo detection. */ + /** + * Compute a deterministic hash for echo detection. + * + * The hash covers the change's CONTENT and not the plugin it is pushed + * to: the same change has to hash the same in both directions, or a + * change coming back from a tracker never matches the push that caused + * it. + */ computeHash( entityId: string, - targetPlugin: string, action: TicketChangeAction | string, - change: Record, + change: Record | TicketChange, ): string { + const fields = change as Record; return EchoGuard.computeHash({ entityId, - targetPlugin, action, - status: change.status, - priority: change.priority, - comment: change.comment, - labels: change.labels, + status: fields.status, + priority: fields.priority, + comment: fields.comment, + labels: fields.labels, }); } } + +/** + * The author label for a comment that arrived from a tracker. + * + * The tracker adapters put the sender's login in `metadata.senderLogin`; + * without one the comment is still recorded, attributed to the tracker. + */ +function inboundAuthor(change: TicketChange, pluginName: string): string { + const login = change.metadata?.senderLogin; + if (typeof login === 'string' && login.length > 0) { + return `${login} (${pluginName})`; + } + return pluginName; +} diff --git a/packages/outpost/shared/src/sync/fanout-github.ts b/packages/outpost/shared/src/sync/fanout-github.ts index 9f3098ac..70648f14 100644 --- a/packages/outpost/shared/src/sync/fanout-github.ts +++ b/packages/outpost/shared/src/sync/fanout-github.ts @@ -43,22 +43,37 @@ export async function fanoutStatusChange( status: TicketStatus, sourcePlugin: string, ): Promise { - const hash = EchoGuard.computeHash({ entityId: link.ticketId, action: 'status_change', status }); + const hash = EchoGuard.computeHash({ + entityId: link.ticketId, + action: 'status_change', + status, + }); - if (!await deps.echoGuard.shouldSync(sourcePlugin, 'github', link.ticketId, hash)) { + if (!(await deps.echoGuard.shouldSync('github', link.ticketId, hash))) { return { pushed: false, action: 'status_change', skippedReason: 'echo detected' }; } try { await deps.adapter.pushStatusChange(link, status); await deps.echoGuard.recordSync( - sourcePlugin, 'github', link.ticketId, 'status_change', hash, 'success', + sourcePlugin, + 'github', + link.ticketId, + 'status_change', + hash, + 'success', ); return { pushed: true, action: 'status_change' }; } catch (err) { const message = err instanceof Error ? err.message : String(err); await deps.echoGuard.recordSync( - sourcePlugin, 'github', link.ticketId, 'status_change', hash, 'failure', message, + sourcePlugin, + 'github', + link.ticketId, + 'status_change', + hash, + 'failure', + message, ); return { pushed: false, action: 'status_change', error: message }; } @@ -75,20 +90,31 @@ export async function fanoutComment( ): Promise { const hash = EchoGuard.computeHash({ entityId: link.ticketId, action: 'comment', comment }); - if (!await deps.echoGuard.shouldSync(sourcePlugin, 'github', link.ticketId, hash)) { + if (!(await deps.echoGuard.shouldSync('github', link.ticketId, hash))) { return { pushed: false, action: 'comment', skippedReason: 'echo detected' }; } try { await deps.adapter.pushComment(link, comment); await deps.echoGuard.recordSync( - sourcePlugin, 'github', link.ticketId, 'comment', hash, 'success', + sourcePlugin, + 'github', + link.ticketId, + 'comment', + hash, + 'success', ); return { pushed: true, action: 'comment' }; } catch (err) { const message = err instanceof Error ? err.message : String(err); await deps.echoGuard.recordSync( - sourcePlugin, 'github', link.ticketId, 'comment', hash, 'failure', message, + sourcePlugin, + 'github', + link.ticketId, + 'comment', + hash, + 'failure', + message, ); return { pushed: false, action: 'comment', error: message }; } @@ -105,20 +131,31 @@ export async function fanoutLabels( ): Promise { const hash = EchoGuard.computeHash({ entityId: link.ticketId, action: 'label_change', labels }); - if (!await deps.echoGuard.shouldSync(sourcePlugin, 'github', link.ticketId, hash)) { + if (!(await deps.echoGuard.shouldSync('github', link.ticketId, hash))) { return { pushed: false, action: 'label_change', skippedReason: 'echo detected' }; } try { await deps.adapter.pushLabels(link, labels); await deps.echoGuard.recordSync( - sourcePlugin, 'github', link.ticketId, 'label_change', hash, 'success', + sourcePlugin, + 'github', + link.ticketId, + 'label_change', + hash, + 'success', ); return { pushed: true, action: 'label_change' }; } catch (err) { const message = err instanceof Error ? err.message : String(err); await deps.echoGuard.recordSync( - sourcePlugin, 'github', link.ticketId, 'label_change', hash, 'failure', message, + sourcePlugin, + 'github', + link.ticketId, + 'label_change', + hash, + 'failure', + message, ); return { pushed: false, action: 'label_change', error: message }; } @@ -157,6 +194,10 @@ export async function fanoutToGitHub( return { pushed: false, action: 'label_change', skippedReason: 'no labels provided' }; default: - return { pushed: false, action: change.action, skippedReason: `unsupported action: ${change.action}` }; + return { + pushed: false, + action: change.action, + skippedReason: `unsupported action: ${change.action}`, + }; } }