diff --git a/src/agents/agentPair.ts b/src/agents/agentPair.ts index 7824e8eb..56a01a86 100644 --- a/src/agents/agentPair.ts +++ b/src/agents/agentPair.ts @@ -133,6 +133,8 @@ export type PairSessionStatus = export interface PairSession { id: string; taskId: string; + /** Linear issue UUID when the session is backed by a real issue (AGT-4055). */ + linearIssueId?: string; taskTitle: string; taskDescription: string; projectPath: string; @@ -168,6 +170,8 @@ export interface PairModelConfig { */ export interface CreatePairSessionOptions { taskId: string; + /** Linear issue UUID; omit for a session typed in by hand with no issue behind it. */ + linearIssueId?: string; taskTitle: string; taskDescription: string; projectPath: string; @@ -193,6 +197,7 @@ export function createPairSession(options: CreatePairSessionOptions): PairSessio const session: PairSession = { id: randomUUID().slice(0, 8), taskId: options.taskId, + linearIssueId: options.linearIssueId, taskTitle: options.taskTitle, taskDescription: options.taskDescription, projectPath: options.projectPath, diff --git a/src/agents/pipelineCoordination.ts b/src/agents/pipelineCoordination.ts index ec4e9f8c..91acfafd 100644 --- a/src/agents/pipelineCoordination.ts +++ b/src/agents/pipelineCoordination.ts @@ -6,6 +6,7 @@ // so the pipeline keeps to its own job and stays under the module size cap. import type { PipelineContext } from './pairPipelineTypes.js'; +import type { TaskItem } from '../orchestration/decisionEngine.js'; import { assignCallSign, type AgentRole } from '../coordination/agentNames.js'; import { taskEventKey } from '../orchestration/decisionEngine.js'; import { t } from '../locale/index.js'; @@ -37,10 +38,21 @@ export function stageCorrelationId( // stage keeps one identity across its iterations. Bounded so a long-lived // daemon does not grow it forever. interface AgentIdentity { name: string; address: string } + +/** + * The part of a run the board identity is derived from. The daemon pipeline + * passes its full PipelineContext; the interactive Discord /pair flow, which + * never builds one, passes just these fields (AGT-4055). + */ +export interface CoordinationSubject { + task: Pick; + projectPath: string; + config?: Pick; +} const agentIdentities = new Map(); const IDENTITY_CAP = 500; -function identityKey(context: PipelineContext, role: AgentRole): string { +function identityKey(context: CoordinationSubject, role: AgentRole): string { // Deliberately NOT scoped by session id. A retry opens a fresh session, and // if that changed the handle then an answer addressed to the first attempt // would sit in an inbox nobody reads. One (repo, task, role) is one @@ -62,7 +74,7 @@ function identityKey(context: PipelineContext, role: AgentRole): string { * both the self-naming and the suffix: a collision now resolves to a different * handle, never a decorated one. */ -function agentIdentity(context: PipelineContext, role: AgentRole): AgentIdentity { +function agentIdentity(context: CoordinationSubject, role: AgentRole): AgentIdentity { const key = identityKey(context, role); const existing = agentIdentities.get(key); if (existing) return existing; @@ -92,7 +104,7 @@ export function assignedAgentName(context: PipelineContext, role: AgentRole): st } /** The board identity an agent publishes under, shared with its MCP tools. */ -export function coordinationContextFor(context: PipelineContext, role: AgentRole) { +export function coordinationContextFor(context: CoordinationSubject, role: AgentRole) { const taskId = taskEventKey(context.task); const callSign = agentIdentity(context, role); const cell = repositoryCell(context.projectPath); diff --git a/src/discord/discordPair.coordination.test.ts b/src/discord/discordPair.coordination.test.ts new file mode 100644 index 00000000..85e151b9 --- /dev/null +++ b/src/discord/discordPair.coordination.test.ts @@ -0,0 +1,121 @@ +// AGT-4055: the Discord /pair flow calls runWorker/runReviewer directly, so the +// coordination inbox (AGT-4054) was inert there. These tests pin the wiring: +// issue-backed sessions get a board identity keyed like the daemon pipeline, +// hand-typed sessions get none. +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const runWorker = vi.fn(); +const runReviewer = vi.fn(); +const getIssue = vi.fn(); + +vi.mock('../agents/worker.js', async (importOriginal) => ({ + ...(await importOriginal()), + runWorker: (...args: unknown[]) => runWorker(...args), + formatWorkReport: () => 'work report', +})); + +vi.mock('../agents/reviewer.js', async (importOriginal) => ({ + ...(await importOriginal()), + runReviewer: (...args: unknown[]) => runReviewer(...args), + formatReviewFeedback: () => 'review feedback', +})); + +vi.mock('../linear/index.js', () => ({ + getIssue: (...args: unknown[]) => getIssue(...args), + getMyIssues: vi.fn(async () => []), + logPairStart: vi.fn(async () => undefined), + logPairReview: vi.fn(async () => undefined), + logPairComplete: vi.fn(async () => undefined), + logPairFailed: vi.fn(async () => undefined), + logPairRevision: vi.fn(async () => undefined), +})); + +vi.mock('../agents/pairMetrics.js', () => ({ + recordSession: vi.fn(async () => undefined), + getSummary: vi.fn(), + getDailyMetrics: vi.fn(), +})); + +vi.mock('../agents/pairWebhook.js', () => ({ + isValidWebhookUrl: () => false, + notifyPairApproved: vi.fn(), + notifyPairRejected: vi.fn(), + notifyPairFailed: vi.fn(), + notifyPairCancelled: vi.fn(), +})); + +vi.mock('../support/dev.js', () => ({ + resolveRepoPath: (name: string) => `/tmp/agt4055-${name}`, +})); + +const { handlePair, pairCoordinationContext } = await import('./discordPair.js'); + +function fakeMessage() { + const thread = { id: 'thread-1', send: vi.fn(async () => undefined), toString: () => '<#thread-1>' }; + const msg = { + channel: { threads: { create: vi.fn(async () => thread) } }, + reply: vi.fn(async () => undefined), + }; + return { msg, thread }; +} + +beforeEach(() => { + runWorker.mockReset().mockResolvedValue({ + success: true, summary: 'done', filesChanged: ['a.ts'], commands: [], output: '', + }); + runReviewer.mockReset().mockResolvedValue({ decision: 'approve', feedback: 'ok', issues: [], suggestions: [] }); + getIssue.mockReset(); +}); + +describe('pairCoordinationContext (AGT-4055)', () => { + it('gives no board identity to a session with no Linear issue behind it', () => { + expect(pairCoordinationContext({ taskId: 'fix the login bug', projectPath: '/tmp/x' }, 'worker')).toBeUndefined(); + }); + + it('keys an issue-backed session by the issue UUID and labels it with the identifier', () => { + const ctx = pairCoordinationContext( + { taskId: 'AGT-1', linearIssueId: 'uuid-agt-1', projectPath: '/tmp/agt4055-proj' }, + 'worker', + ); + expect(ctx).toBeDefined(); + expect(ctx?.taskId).toBe('uuid-agt-1'); + expect(ctx?.taskLabel).toBe('AGT-1'); + expect(ctx?.actorRole).toBe('worker'); + expect(ctx?.actor).toBeTruthy(); + }); + + it('keeps one handle per role across calls and separates worker from reviewer', () => { + const session = { taskId: 'AGT-2', linearIssueId: 'uuid-agt-2', projectPath: '/tmp/agt4055-proj' }; + const w1 = pairCoordinationContext(session, 'worker'); + const w2 = pairCoordinationContext(session, 'worker'); + const r = pairCoordinationContext(session, 'reviewer'); + expect(w2?.actor).toBe(w1?.actor); + expect(r?.actor).not.toBe(w1?.actor); + }); +}); + +describe('!pair run wiring (AGT-4055)', () => { + it('passes coordinationContext to both worker and reviewer when the issue resolves', async () => { + getIssue.mockResolvedValue({ id: 'uuid-agt-3', identifier: 'AGT-3', title: 'T', description: 'D' }); + const { msg } = fakeMessage(); + await handlePair(msg as never, ['run', 'AGT-3', 'proj']); + await vi.waitFor(() => expect(runReviewer).toHaveBeenCalled()); + + const workerCtx = runWorker.mock.calls[0][0].coordinationContext; + const reviewerCtx = runReviewer.mock.calls[0][0].coordinationContext; + expect(workerCtx?.taskId).toBe('uuid-agt-3'); + expect(workerCtx?.actorRole).toBe('worker'); + expect(reviewerCtx?.taskId).toBe('uuid-agt-3'); + expect(reviewerCtx?.actorRole).toBe('reviewer'); + }); + + it('runs without coordination tools when the Linear lookup finds nothing', async () => { + getIssue.mockResolvedValue(null); + const { msg } = fakeMessage(); + await handlePair(msg as never, ['run', 'free-text-task', 'proj']); + await vi.waitFor(() => expect(runReviewer).toHaveBeenCalled()); + + expect(runWorker.mock.calls[0][0].coordinationContext).toBeUndefined(); + expect(runReviewer.mock.calls[0][0].coordinationContext).toBeUndefined(); + }); +}); diff --git a/src/discord/discordPair.ts b/src/discord/discordPair.ts index 1a27fbf7..858e189c 100644 --- a/src/discord/discordPair.ts +++ b/src/discord/discordPair.ts @@ -17,6 +17,8 @@ import * as worker from '../agents/worker.js'; import * as reviewer from '../agents/reviewer.js'; import * as pairMetrics from '../agents/pairMetrics.js'; import * as pairWebhook from '../agents/pairWebhook.js'; +import { coordinationContextFor } from '../agents/pipelineCoordination.js'; +import type { CoordinationToolContext } from '../coordination/coordinationTools.js'; import { pairModeConfig, @@ -35,6 +37,29 @@ import { sanitizeAndBoundTerminalText, sanitizeTerminalText } from '../tui/sanit const DISCORD_CONTENT_LIMIT = 1900; +/** + * Coordination-board identity for a Discord /pair agent (AGT-4055). + * + * Only sessions backed by a Linear issue get one. The board is keyed by the + * issue UUID, the same key the daemon pipeline uses, so a Discord run and a + * daemon run on one issue are the same participants and their messages meet. + * A session typed in by hand has no issue behind it; it gets no coordination + * tools rather than a synthetic id nobody else would ever address. + * + * v1 visibility: what these agents publish lands on the coordination board + * (dashboard / CLI) only. It is not echoed into the Discord thread. + */ +export function pairCoordinationContext( + session: Pick, + role: 'worker' | 'reviewer', +): CoordinationToolContext | undefined { + if (!session.linearIssueId) return undefined; + return coordinationContextFor({ + task: { id: session.linearIssueId, issueId: session.linearIssueId, issueIdentifier: session.taskId }, + projectPath: session.projectPath, + }, role); +} + /** Bound and neutralize untrusted text before Discord thread posting. */ function neutralizeForDiscord(text: string, max = DISCORD_CONTENT_LIMIT): string { return truncateField(sanitizeAndBoundTerminalText(text), max, true); @@ -235,6 +260,7 @@ async function handlePairStart(msg: Message, taskId?: string): Promise { await startPairSession(msg, { taskId: task.identifier || task.id, + linearIssueId: typeof task.id === 'string' ? task.id : undefined, taskTitle: task.title, taskDescription: task.description || '', projectPath, @@ -256,12 +282,14 @@ async function handlePairRun(msg: Message, taskId: string, project: string): Pro // Fetch issue info from Linear let taskTitle = taskId; let taskDescription = ''; + let linearIssueId: string | undefined; try { const issue = await linear.getIssue(taskId); if (issue) { taskTitle = issue.title; taskDescription = issue.description || ''; + linearIssueId = issue.id; } } catch { // Continue even if Linear lookup fails (use taskId as title) @@ -269,6 +297,7 @@ async function handlePairRun(msg: Message, taskId: string, project: string): Pro await startPairSession(msg, { taskId, + linearIssueId, taskTitle, taskDescription, projectPath, @@ -385,6 +414,7 @@ async function runPairLoop(sessionId: string, thread: ThreadChannel): Promise