feat(linear): add MCP-style save issue (#9670)

* feat(linear): add MCP-style save issue

* fix(linear): harden save issue parity

* fix(linear): close save issue contract gaps

* docs(linear): bundle project discovery with save issue
This commit is contained in:
Brennan Benson
2026-07-21 13:25:22 -07:00
committed by GitHub
parent 87af1c8673
commit a10a2ba53c
33 changed files with 1094 additions and 61 deletions
+156
View File
@@ -0,0 +1,156 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { LINEAR_WRITE_BODY_CAP } from '../../shared/linear-agent-access'
import * as linearTeams from '../linear/teams'
import { OrcaRuntimeService } from './orca-runtime'
const issue = {
id: 'issue-1',
identifier: 'ENG-1',
title: 'Existing title',
description: 'Existing description',
url: 'https://linear.app/acme/issue/ENG-1',
team: { id: 'team-1', key: 'ENG', name: 'Engineering' },
state: { id: 'state-1', name: 'Todo' },
parent: null,
project: null,
assignee: null,
priority: 0,
estimate: null,
dueDate: null,
labelIds: [],
labels: []
}
type SaveIssueInternals = {
resolveLinearAssignee(input: string, teamId: string, workspaceId: string): Promise<string>
resolveLinearAgentState(input: string, states: unknown[]): unknown | null
buildLinearSaveUpdate(
params: { labels?: string[] },
current: typeof issue,
workspaceId: string
): Promise<{ labelIds?: string[] }>
}
afterEach(() => {
vi.restoreAllMocks()
})
describe('Linear save issue', () => {
it('delegates creates with the MCP-required team and title', async () => {
const runtime = new OrcaRuntimeService()
const create = vi.spyOn(runtime, 'linearIssueCreate').mockResolvedValue({
issue,
meta: { workspaceId: 'workspace-1', writeId: 'write-1', deduplicated: false }
})
await expect(
runtime.linearSaveIssue({ team: 'ENG', title: 'New issue', workspaceId: 'workspace-1' })
).resolves.toMatchObject({ meta: { created: true } })
expect(create).toHaveBeenCalledWith(
expect.objectContaining({
teamInput: 'ENG',
title: 'New issue',
workspaceId: 'workspace-1'
})
)
})
it('keeps team changes explicitly unsupported on updates', async () => {
const runtime = new OrcaRuntimeService()
await expect(
runtime.linearSaveIssue({ input: 'ENG-1', team: 'OPS', title: 'Moved issue' })
).rejects.toMatchObject({
code: 'linear_write_failed',
message: 'Team can only be set when creating an issue.'
})
})
it('rejects oversized descriptions before resolving an issue or calling Linear', async () => {
const runtime = new OrcaRuntimeService()
const resolveTarget = vi.fn()
Object.assign(runtime, { resolveLinearAgentWriteTarget: resolveTarget })
await expect(
runtime.linearSaveIssue({
input: 'ENG-1',
description: 'x'.repeat(LINEAR_WRITE_BODY_CAP + 1)
})
).rejects.toMatchObject({ code: 'linear_body_too_large' })
expect(resolveTarget).not.toHaveBeenCalled()
})
it('does not send a mutation or confirmation read when every field is already set', async () => {
const runtime = new OrcaRuntimeService()
const runWrite = vi.fn()
const notify = vi.fn().mockResolvedValue(undefined)
Object.assign(runtime, {
resolveLinearAgentWriteTarget: vi
.fn()
.mockResolvedValue({ issue, workspaceId: 'workspace-1' }),
readLinearAgentIssueWriteRecord: vi.fn().mockResolvedValue(issue),
buildLinearSaveUpdate: vi.fn().mockResolvedValue({ title: issue.title }),
runLinearAgentWrite: runWrite,
notifyLinearLinkedIssueUpdated: notify
})
await expect(
runtime.linearSaveIssue({ input: issue.identifier, title: issue.title })
).resolves.toMatchObject({ issue, meta: { created: false } })
expect(runWrite).not.toHaveBeenCalled()
expect(notify).toHaveBeenCalledWith('workspace-1', issue.identifier)
})
it('accepts user UUIDs without listing every team member', async () => {
const runtime = new OrcaRuntimeService() as unknown as SaveIssueInternals
const listMembers = vi.spyOn(linearTeams, 'getTeamMembersOrThrow')
const userId = '11111111-1111-4111-8111-111111111111'
await expect(runtime.resolveLinearAssignee(userId, 'team-1', 'workspace-1')).resolves.toBe(
userId
)
expect(listMembers).not.toHaveBeenCalled()
})
it('matches assignees by full name or email like Linear MCP', async () => {
const runtime = new OrcaRuntimeService() as unknown as SaveIssueInternals
vi.spyOn(linearTeams, 'getTeamMembersOrThrow').mockResolvedValue([
{
id: 'user-1',
displayName: 'Ada',
name: 'Ada Lovelace',
email: 'ada@example.com'
}
])
await expect(
runtime.resolveLinearAssignee('Ada Lovelace', 'team-1', 'workspace-1')
).resolves.toBe('user-1')
await expect(
runtime.resolveLinearAssignee('ADA@EXAMPLE.COM', 'team-1', 'workspace-1')
).resolves.toBe('user-1')
})
it('resolves workflow lifecycle types while preferring exact state names', () => {
const runtime = new OrcaRuntimeService() as unknown as SaveIssueInternals
const states = [
{ id: 'state-progress', name: 'In Progress', type: 'started' },
{ id: 'state-started', name: 'Started', type: 'unstarted' }
]
expect(runtime.resolveLinearAgentState('started', states)).toBe(states[1])
expect(runtime.resolveLinearAgentState('unstarted', states)).toBe(states[1])
})
it('clears labels without listing the team label catalog', async () => {
const runtime = new OrcaRuntimeService() as unknown as SaveIssueInternals
const listLabels = vi.spyOn(linearTeams, 'getTeamLabelsOrThrow')
await expect(
runtime.buildLinearSaveUpdate({ labels: [] }, issue, 'workspace-1')
).resolves.toEqual({ labelIds: [] })
expect(listLabels).not.toHaveBeenCalled()
})
})
+245 -10
View File
@@ -182,6 +182,8 @@ import type {
LinearMcpIssueListResult,
LinearIssueRelationWriteRequest,
LinearIssueRelationWriteResult,
LinearSaveIssueRequest,
LinearSaveIssueResult,
LinearTeamLabelsResult,
LinearTeamListResult,
LinearTeamMembersResult,
@@ -25114,6 +25116,85 @@ export class OrcaRuntimeService {
}
}
async linearSaveIssue(params: LinearSaveIssueRequest): Promise<LinearSaveIssueResult> {
if ((params.description?.length ?? 0) > LINEAR_WRITE_BODY_CAP) {
throw linearError('linear_body_too_large', 'Linear issue body is too large.')
}
if (!params.input && !params.current) {
if (!params.title || !params.team) {
throw linearError(
'linear_write_failed',
'Creating with save-issue requires both team and title.'
)
}
const created = await this.linearIssueCreate({
title: params.title,
body: params.description,
teamInput: params.team,
state: params.state,
assignee: params.assignee ?? undefined,
priority: params.priority,
estimate: params.estimate ?? undefined,
dueDate: params.dueDate ?? undefined,
labels: params.labels,
projectInput: params.project ?? undefined,
parentInput: params.parentId ?? undefined,
workspaceId: params.workspaceId,
writeId: params.writeId,
context: params.context
})
return { ...created, meta: { ...created.meta, created: true } }
}
if (params.team !== undefined) {
throw linearError('linear_write_failed', 'Team can only be set when creating an issue.')
}
const target = await this.resolveLinearAgentWriteTarget(params)
const current = await this.readLinearAgentIssueWriteRecord(target.issue.id, target.workspaceId)
const fields = await this.buildLinearSaveUpdate(params, current, target.workspaceId)
if (Object.keys(fields).length === 0) {
throw linearError('linear_write_failed', 'No issue fields were provided to save.')
}
const alreadySet = this.linearSavedIssueMatchesIntent(current, fields)
const updated = alreadySet
? current
: await this.runLinearAgentWrite(
async (signal) => {
const saved = await updateLinearIssueForAgent(
target.issue.id,
fields,
target.workspaceId,
{ signal }
)
if (!this.linearSavedIssueMatchesIntent(saved, fields)) {
throw new LinearWriteFailure(
'unconfirmed',
'Linear issue save could not be confirmed.'
)
}
return saved
},
(cause) =>
linearError(
'linear_write_unconfirmed',
'Linear may have applied the issue save, but Orca could not confirm it.',
{
nextSteps: [
`Run \`orca linear issue ${target.issue.identifier} --workspace ${target.workspaceId} --json\` before retrying.`
],
...(cause ? { cause } : {})
}
)
)
await this.notifyLinearLinkedIssueUpdated(target.workspaceId, target.issue.identifier)
return {
issue: updated,
meta: {
workspaceId: target.workspaceId,
created: false
}
}
}
async linearIssueUpdateTask(
params: LinearIssueTaskUpdateRequest
): Promise<LinearIssueTaskUpdateResult> {
@@ -25467,13 +25548,12 @@ export class OrcaRuntimeService {
states: Awaited<ReturnType<typeof getLinearTeamStatesOrThrow>>
): Awaited<ReturnType<typeof getLinearTeamStatesOrThrow>>[number] | null {
const normalized = input.toLocaleLowerCase()
return (
states.find(
(state) =>
state.id.toLocaleLowerCase() === normalized ||
state.name.toLocaleLowerCase() === normalized
) ?? null
const exact = states.find(
(state) =>
state.id.toLocaleLowerCase() === normalized || state.name.toLocaleLowerCase() === normalized
)
// Why: Linear MCP accepts lifecycle types; keep explicit IDs/names authoritative when they collide.
return exact ?? states.find((state) => state.type.toLocaleLowerCase() === normalized) ?? null
}
private async getLinearTeamLabelsForWrite(
@@ -25564,6 +25644,153 @@ export class OrcaRuntimeService {
return null
}
private async buildLinearSaveUpdate(
params: LinearSaveIssueRequest,
current: NonNullable<Awaited<ReturnType<typeof getLinearIssueByUuidForAgent>>>,
workspaceId: string
): Promise<LinearIssueUpdate> {
const fields: LinearIssueUpdate = {}
if (params.title !== undefined) {
fields.title = params.title
}
if (params.description !== undefined) {
fields.description = params.description
}
if (params.priority !== undefined) {
fields.priority = params.priority
}
if (params.estimate !== undefined) {
fields.estimate = params.estimate
}
if (params.dueDate !== undefined) {
fields.dueDate = params.dueDate
}
if (params.state !== undefined) {
const states = await this.getLinearTeamStatesForWrite(current.team.id, workspaceId)
const state = this.resolveLinearAgentState(params.state, states)
if (!state) {
throw linearError(
'linear_invalid_state',
`No workflow state exactly matched "${params.state}".`
)
}
fields.stateId = state.id
}
if (params.assignee !== undefined) {
fields.assigneeId =
params.assignee === null
? null
: await this.resolveLinearAssignee(params.assignee, current.team.id, workspaceId)
}
if (params.labels !== undefined) {
if (params.labels.length === 0) {
fields.labelIds = []
} else {
const labels = await this.resolveLinearLabelsForIssue(current, params.labels, workspaceId)
fields.labelIds = labels.map((label) => label.id)
}
}
if (params.project !== undefined) {
fields.projectId =
params.project === null
? null
: (
await this.resolveLinearCreateProject(params.project, {
id: current.team.id,
workspaceId
})
).id
}
if (params.parentId !== undefined) {
fields.parentId =
params.parentId === null
? null
: (
await this.resolveLinearAgentWriteTarget({
input: params.parentId,
workspaceId,
context: params.context
})
).issue.id
if (fields.parentId === current.id) {
throw linearError('linear_invalid_parent', 'An issue cannot be its own parent.')
}
}
return fields
}
private async resolveLinearAssignee(
input: string,
teamId: string,
workspaceId: string
): Promise<string> {
if (input.toLocaleLowerCase() === 'me') {
return (await this.getLinearViewerForWrite(workspaceId)).id
}
// Why: caller-supplied IDs were accepted directly before save-issue; avoid a paginated member scan on that existing fast path.
if (isLinearUuid(input)) {
return input
}
let members: Awaited<ReturnType<typeof getLinearTeamMembersOrThrow>>
try {
members = await getLinearTeamMembersOrThrow(teamId, workspaceId)
} catch (error) {
throw this.mapLinearReadFailure(error)
}
const normalized = input.toLocaleLowerCase()
const matches = members.filter(
(member) =>
member.id.toLocaleLowerCase() === normalized ||
member.displayName.toLocaleLowerCase() === normalized ||
member.name?.toLocaleLowerCase() === normalized ||
member.email?.toLocaleLowerCase() === normalized
)
if (matches.length === 1) {
return matches[0].id
}
throw linearError(
'linear_invalid_assignee',
matches.length === 0
? `No team member exactly matched "${input}".`
: `Multiple team members exactly matched "${input}".`
)
}
private linearSavedIssueMatchesIntent(
issue: NonNullable<Awaited<ReturnType<typeof getLinearIssueByUuidForAgent>>>,
fields: LinearIssueUpdate
): boolean {
if (fields.title !== undefined && issue.title !== fields.title) {
return false
}
if (fields.description !== undefined && (issue.description ?? '') !== fields.description) {
return false
}
if (fields.parentId !== undefined && (issue.parent?.id ?? null) !== fields.parentId) {
return false
}
if (fields.stateId !== undefined && issue.state?.id !== fields.stateId) {
return false
}
if (fields.assigneeId !== undefined && (issue.assignee?.id ?? null) !== fields.assigneeId) {
return false
}
if (fields.priority !== undefined && issue.priority !== fields.priority) {
return false
}
if (fields.estimate !== undefined && (issue.estimate ?? null) !== fields.estimate) {
return false
}
if (fields.dueDate !== undefined && (issue.dueDate ?? null) !== fields.dueDate) {
return false
}
if (fields.projectId !== undefined && (issue.project?.id ?? null) !== fields.projectId) {
return false
}
const issueLabelIds = issue.labelIds ?? issue.labels?.map((label) => label.id) ?? []
return fields.labelIds === undefined || sameStringSet(issueLabelIds, fields.labelIds)
}
private async resolveLinearCreateFields(
params: {
state?: string
@@ -25590,10 +25817,11 @@ export class OrcaRuntimeService {
fields.stateId = state.id
}
if (params.assignee) {
fields.assigneeId =
params.assignee.toLocaleLowerCase() === 'me'
? (await this.getLinearViewerForWrite(team.workspaceId)).id
: params.assignee
fields.assigneeId = await this.resolveLinearAssignee(
params.assignee,
team.id,
team.workspaceId
)
}
if (params.priority !== undefined) {
fields.priority = params.priority
@@ -25637,6 +25865,13 @@ export class OrcaRuntimeService {
await this.assertLinearProjectIncludesTeam(idMatch, team.id, team.workspaceId, trimmed)
return idMatch
}
const slugMatch = searchCandidates.find(
(project) => project.slugId?.toLowerCase() === normalized
)
if (slugMatch) {
await this.assertLinearProjectIncludesTeam(slugMatch, team.id, team.workspaceId, trimmed)
return slugMatch
}
const nameMatches = await this.readLinearProjectsByExactNameForCreate(trimmed, team.workspaceId)
const compatibleNameMatches = await this.filterLinearProjectsForTeam(
nameMatches,
@@ -54,6 +54,7 @@ describe('Linear agent access RPC methods', () => {
linearIssueUpdateTask: vi.fn().mockResolvedValue({ ok: true }),
linearIssueAddComment: vi.fn().mockResolvedValue({ ok: true }),
linearIssueAttachLink: vi.fn().mockResolvedValue({ ok: true }),
linearSaveIssue: vi.fn().mockResolvedValue({ ok: true }),
linearIssueCreate: vi.fn().mockResolvedValue({ ok: true })
} as unknown as OrcaRuntimeService
const dispatcher = new RpcDispatcher({ runtime, methods: LINEAR_AGENT_ACCESS_METHODS })
@@ -139,6 +140,16 @@ describe('Linear agent access RPC methods', () => {
workspaceId: 'workspace-1'
})
)
const saveResponse = await dispatcher.dispatch(
makeRequest('linear.saveIssue', {
input: 'ENG-1',
title: 'Updated title',
assignee: null,
labels: ['Bug'],
project: null,
workspaceId: 'workspace-1'
})
)
expect(setStateResponse.ok).toBe(true)
expect(teamListResponse.ok).toBe(true)
@@ -152,6 +163,7 @@ describe('Linear agent access RPC methods', () => {
expect(commentResponse.ok).toBe(true)
expect(attachResponse.ok).toBe(true)
expect(createResponse.ok).toBe(true)
expect(saveResponse.ok).toBe(true)
expect(runtime.linearIssueSetState).toHaveBeenCalledWith({
input: 'ENG-1',
to: 'In Review',
@@ -218,6 +230,15 @@ describe('Linear agent access RPC methods', () => {
writeId: '33333333-3333-4333-8333-333333333333',
workspaceId: 'workspace-1'
})
expect(runtime.linearSaveIssue).toHaveBeenCalledWith({
input: 'ENG-1',
title: 'Updated title',
assignee: null,
labels: ['Bug'],
project: null,
workspaceId: 'workspace-1',
writeId: undefined
})
})
it('rejects malformed write ids before the runtime is called', async () => {
@@ -336,6 +357,7 @@ type LinearUnconfirmedBuilder = {
): Error & { data?: { cause?: string; nextSteps?: string[] } }
resolveLinearAgentState(input: string, states: unknown[]): unknown | null
linearCreatedIssueMatchesIntent(issue: unknown, intent: unknown): boolean
linearSavedIssueMatchesIntent(issue: unknown, intent: unknown): boolean
notifyLinearLinkedIssueUpdated(
workspaceId: string,
identifier: string | readonly string[]
@@ -560,6 +582,43 @@ describe('Linear agent write recovery helpers', () => {
).toBe(false)
})
it('confirms save-issue updates including explicit relationship clears', () => {
const runtime = new OrcaRuntimeService()
const builder = runtime as unknown as LinearUnconfirmedBuilder
const issue = {
id: 'issue-2',
identifier: 'ENG-2',
title: 'Updated title',
description: 'Updated description',
url: 'https://example.invalid/ENG-2',
team: { id: 'team-1', key: 'ENG', name: 'Engineering' },
state: { id: 'state-review', name: 'In Review' },
parent: null,
project: null,
assignee: null,
priority: 2,
estimate: null,
dueDate: null,
labelIds: ['label-1']
}
expect(
builder.linearSavedIssueMatchesIntent(issue, {
title: 'Updated title',
description: 'Updated description',
stateId: 'state-review',
parentId: null,
projectId: null,
assigneeId: null,
priority: 2,
estimate: null,
dueDate: null,
labelIds: ['label-1']
})
).toBe(true)
expect(builder.linearSavedIssueMatchesIntent(issue, { projectId: 'project-2' })).toBe(false)
})
it('resolves workflow states by UUID or case-insensitive exact name', () => {
const runtime = new OrcaRuntimeService()
const states = [
@@ -130,6 +130,21 @@ const LinearIssueCreate = z.object({
context: LinearCurrentContext
})
const LinearSaveIssue = LinearWriteTarget.extend({
team: OptionalString,
title: OptionalString,
description: z.string().optional(),
state: OptionalString,
assignee: z.string().nullable().optional(),
priority: z.number().int().min(0).max(4).optional(),
estimate: z.number().min(0).nullable().optional(),
dueDate: OptionalLinearDueDateOrClear,
labels: z.array(z.string()).optional(),
project: z.string().nullable().optional(),
parentId: z.string().nullable().optional(),
writeId: OptionalString
})
function parseLinearWriteId(writeId: string | undefined): string | undefined {
if (writeId === undefined) {
return undefined
@@ -141,6 +156,12 @@ function parseLinearWriteId(writeId: string | undefined): string | undefined {
}
export const LINEAR_AGENT_ACCESS_METHODS: RpcMethod[] = [
defineMethod({
name: 'linear.saveIssue',
params: LinearSaveIssue,
handler: async (params, { runtime }) =>
runtime.linearSaveIssue({ ...params, writeId: parseLinearWriteId(params.writeId) })
}),
defineMethod({
name: 'linear.agentSearchIssues',
params: AgentSearchIssues,
@@ -74,6 +74,29 @@ describe('Linear agent project access helpers', () => {
expect(readExactName).toHaveBeenCalledWith('launch', 'workspace-1')
})
it('resolves Linear projects by URL slug without a paginated exact-name scan', async () => {
const runtime = new OrcaRuntimeService()
const tester = runtime as unknown as LinearProjectResolverTester
vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never)
vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([
{
id: 'project-1',
slugId: 'launch-d8f6c7e7',
name: 'Launch',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
}
] as never)
const readExactName = vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate')
await expect(
tester.resolveLinearCreateProject('LAUNCH-D8F6C7E7', {
id: 'team-1',
workspaceId: 'workspace-1'
})
).resolves.toMatchObject({ id: 'project-1' })
expect(readExactName).not.toHaveBeenCalled()
})
it('resolves same-named Linear projects by target team compatibility', async () => {
const runtime = new OrcaRuntimeService()
const tester = runtime as unknown as LinearProjectResolverTester