feat(linear): add project support to agent CLI (#5433)

* feat(linear): add project support to agent CLI

* fix(linear): resolve project names across search pages

* fix(linear): harden agent project support

* fix(linear): address project review feedback

---------

Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
This commit is contained in:
Trevin Chow
2026-06-15 18:24:53 -07:00
committed by GitHub
co-authored by Jinjing
parent 7f3aac9f5e
commit 2b8d9a43de
27 changed files with 1249 additions and 24 deletions
+32
View File
@@ -165,6 +165,35 @@ describe('orca linear CLI handlers', () => {
})
})
it('maps project list to agent project RPC with capped limit', async () => {
queueFixtures(
callMock,
okFixture('req_projects', {
projects: [],
meta: {
query: 'launch',
workspaceId: 'all',
limit: 50,
returned: 0,
hasMore: false,
partial: false,
workspaceErrors: []
}
})
)
await main(
['linear', 'project', 'list', '--query', 'launch', '--workspace', 'all', '--limit', '500'],
'/tmp/repo'
)
expect(callMock).toHaveBeenCalledWith('linear.agentProjectList', {
query: 'launch',
limit: 50,
workspaceId: 'all'
})
})
it('keeps boolean flags between Linear and search from consuming the subcommand', async () => {
queueFixtures(
callMock,
@@ -396,6 +425,8 @@ describe('orca linear CLI handlers', () => {
'Triage bug',
'--team',
'ENG',
'--project',
'project-1',
'--state',
'Todo',
'--assignee',
@@ -420,6 +451,7 @@ describe('orca linear CLI handlers', () => {
expect.objectContaining({
title: 'Triage bug',
teamInput: 'ENG',
projectInput: 'project-1',
state: 'Todo',
assignee: 'me',
priority: 2,
+18
View File
@@ -8,6 +8,8 @@ import type {
LinearIssueListRequest,
LinearIssueListResult,
LinearIssueContextResult,
LinearProjectListRequest,
LinearProjectListResult,
LinearIssueTaskUpdateRequest,
LinearIssueTaskUpdateResult,
LinearSearchResult,
@@ -49,6 +51,7 @@ import {
formatLinearCreate,
formatLinearIssue,
formatLinearIssueList,
formatLinearProjectList,
formatLinearTaskUpdate,
formatLinearSearch,
formatLinearStatusSet,
@@ -58,6 +61,7 @@ import {
formatLinearTeamStates,
printLinearIssueWarnings,
printLinearListWarnings,
printLinearProjectListWarnings,
printLinearSearchWarnings
} from '../linear-format'
@@ -117,6 +121,19 @@ export const LINEAR_HANDLERS: Record<string, CommandHandler> = {
})
printResult(response, json, formatLinearTeamLabels)
},
'linear project list': async ({ flags, client, json }) => {
const limit = clampLinearSearchLimit(getOptionalPositiveIntegerFlag(flags, 'limit'))
const request: LinearProjectListRequest = {
query: getOptionalStringFlag(flags, 'query'),
limit,
workspaceId: getOptionalStringFlag(flags, 'workspace')
}
const response = await client.call<LinearProjectListResult>('linear.agentProjectList', request)
if (!json) {
printLinearProjectListWarnings(response.result)
}
printResult(response, json, formatLinearProjectList)
},
'linear list': async ({ flags, client, json }) => {
const limit = getOptionalPositiveIntegerFlag(flags, 'limit')
const filter = getLinearListFilter(flags)
@@ -229,6 +246,7 @@ export const LINEAR_HANDLERS: Record<string, CommandHandler> = {
title: getRequiredStringFlag(flags, 'title'),
...(body !== undefined ? { body } : {}),
teamInput: getOptionalStringFlag(flags, 'team'),
projectInput: getOptionalStringFlag(flags, 'project'),
state: getOptionalStringFlag(flags, 'state'),
assignee: getOptionalStringFlag(flags, 'assignee'),
priority: flags.has('priority') ? getPriorityFlag(flags, 'priority') : undefined,
+59 -2
View File
@@ -1,6 +1,16 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { LinearIssueContextResult, LinearSearchResult } from '../shared/linear-agent-access'
import { formatLinearIssue, printLinearSearchWarnings } from './linear-format'
import type {
LinearCreateResult,
LinearIssueContextResult,
LinearProjectListResult,
LinearSearchResult
} from '../shared/linear-agent-access'
import {
formatLinearCreate,
formatLinearIssue,
formatLinearProjectList,
printLinearSearchWarnings
} from './linear-format'
describe('linear-format', () => {
beforeEach(() => {
@@ -50,4 +60,51 @@ describe('linear-format', () => {
expect(formatLinearIssue(result)).toContain('Estimate: 5')
expect(formatLinearIssue(result)).toContain('Due: 2026-06-30')
})
it('formats project rows with names, ids, teams, and workspace', () => {
const result = {
projects: [
{
id: 'project-1',
name: 'Launch',
workspaceName: 'Acme',
teams: [
{ id: 'team-1', name: 'Engineering', key: 'ENG' },
{ id: 'team-2', name: 'Product', key: '' }
]
}
],
meta: { limit: 20, returned: 1, hasMore: false, partial: false, workspaceErrors: [] }
} as unknown as LinearProjectListResult
const output = formatLinearProjectList(result)
expect(output).toContain('Launch')
expect(output).toContain('project-1')
expect(output).toContain('ENG')
expect(output).toContain('Product')
expect(output).toContain('Acme')
})
it('includes the project in create output when present', () => {
const result = {
issue: {
id: 'issue-1',
identifier: 'ENG-123',
title: 'Follow up',
url: 'https://linear.app/acme/issue/ENG-123',
team: { id: 'team-1', key: 'ENG', name: 'Engineering' },
state: null,
parent: null,
project: { id: 'project-1', name: 'Launch' }
},
meta: {
workspaceId: 'workspace-1',
writeId: '11111111-1111-4111-8111-111111111111',
deduplicated: false
}
} as LinearCreateResult
expect(formatLinearCreate(result)).toBe('Created ENG-123 in Launch: Follow up.')
})
})
+17 -1
View File
@@ -5,6 +5,7 @@ import type {
LinearIssueListResult,
LinearIssueContextResult,
LinearIssueTaskUpdateResult,
LinearProjectListResult,
LinearSearchIssueSummary,
LinearSearchResult,
LinearTeamLabelsResult,
@@ -13,6 +14,10 @@ import type {
LinearTeamStatesResult,
LinearStatusSetResult
} from '../shared/linear-agent-access'
import {
formatLinearProjectListRows,
linearProjectListWarningLines
} from '../shared/linear-project-list-format'
export function formatLinearIssue(result: LinearIssueContextResult): string {
const issue = result.issue
@@ -103,6 +108,10 @@ export function formatLinearIssueList(result: LinearIssueListResult): string {
return result.issues.map(formatSearchRow).join('\n')
}
export function formatLinearProjectList(result: LinearProjectListResult): string {
return formatLinearProjectListRows(result)
}
export function formatLinearStatusSet(result: LinearStatusSetResult): string {
const suffix = result.meta.alreadyInState ? ' (already set)' : ''
return `Set ${result.issue.identifier} to ${result.state.name}${suffix}.`
@@ -120,8 +129,9 @@ export function formatLinearAttach(result: LinearAttachResult): string {
export function formatLinearCreate(result: LinearCreateResult): string {
const parent = result.issue.parent ? ` under ${result.issue.parent.identifier}` : ''
const project = result.issue.project?.name ? ` in ${result.issue.project.name}` : ''
const suffix = result.meta.deduplicated ? ' (already created)' : ''
return `Created ${result.issue.identifier}${parent}: ${result.issue.title}${suffix}.`
return `Created ${result.issue.identifier}${parent}${project}: ${result.issue.title}${suffix}.`
}
export function formatLinearTaskUpdate(result: LinearIssueTaskUpdateResult): string {
@@ -166,6 +176,12 @@ export function printLinearListWarnings(
}
}
export function printLinearProjectListWarnings(result: LinearProjectListResult): void {
for (const warning of linearProjectListWarningLines(result)) {
console.error(warning)
}
}
function formatSearchRow(issue: LinearSearchIssueSummary): string {
const state = issue.state?.name ?? 'unknown'
const assignee = issue.assignee?.displayName ?? 'unassigned'
+2 -2
View File
@@ -12,6 +12,7 @@ import {
LINEAR_WRITE_BODY_CAP,
clampLinearIssueDepth
} from '../shared/linear-agent-access'
import { isLinearUuid } from '../shared/linear-uuid'
import {
getOptionalNonNegativeIntegerFlag,
getOptionalStringFlag,
@@ -21,7 +22,6 @@ import {
} from './flags'
import { RuntimeClientError } from './runtime-client'
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const LINEAR_PRIORITY_VALUES = new Map([
['none', 0],
['urgent', 1],
@@ -202,7 +202,7 @@ export function getOptionalWriteId(flags: Map<string, string | boolean>): string
return undefined
}
const writeId = getRequiredStringFlag(flags, 'write-id')
if (!UUID_PATTERN.test(writeId)) {
if (!isLinearUuid(writeId)) {
throw new RuntimeClientError('linear_invalid_write_id', '--write-id must be a UUID')
}
return writeId
+14 -2
View File
@@ -62,6 +62,17 @@ export const LINEAR_COMMAND_SPECS: CommandSpec[] = [
allowedFlags: [...GLOBAL_FLAGS, 'team', 'workspace'],
examples: ['orca linear team labels --team ENG --json']
},
{
path: ['linear', 'project', 'list'],
summary: 'List connected Linear projects',
usage:
'orca linear project list [--query <text>] [--limit <n>] [--workspace <id>|all] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'query', 'limit', 'workspace'],
examples: [
'orca linear project list --query launch --json',
'orca linear project list --workspace all --json'
]
},
{
path: ['linear', 'list'],
summary: 'List Linear issues for task triage',
@@ -213,13 +224,14 @@ export const LINEAR_COMMAND_SPECS: CommandSpec[] = [
path: ['linear', 'create'],
summary: 'Create a Linear issue',
usage:
'orca linear create --title <title> [--body <text> | --body-file <path|->] [--team <key|id>] [--state <stateId|exact-name>] [--assignee me|<userId>] [--priority none|low|medium|high|urgent] [--estimate <number>] [--due-date <yyyy-mm-dd>] [--label <labelId-or-exact-name>]... [--parent <id> | --parent-current] [--write-id <uuid>] [--workspace <id>] [--json]',
'orca linear create --title <title> [--body <text> | --body-file <path|->] [--team <key|id>] [--project <projectId-or-exact-name>] [--state <stateId|exact-name>] [--assignee me|<userId>] [--priority none|low|medium|high|urgent] [--estimate <number>] [--due-date <yyyy-mm-dd>] [--label <labelId-or-exact-name>]... [--parent <id> | --parent-current] [--write-id <uuid>] [--workspace <id>] [--json]',
allowedFlags: [
...GLOBAL_FLAGS,
'title',
'body',
'body-file',
'team',
'project',
'state',
'assignee',
'priority',
@@ -232,7 +244,7 @@ export const LINEAR_COMMAND_SPECS: CommandSpec[] = [
'workspace'
],
examples: [
'orca linear create --title "Investigate flaky login" --team ENG',
'orca linear create --title "Investigate flaky login" --team ENG --project "Launch"',
'orca linear create --title "Follow-up bug" --parent-current --body-file - --json'
],
notes: ['Use --body-file - to read multiline issue bodies from stdin.']
+5 -3
View File
@@ -628,7 +628,7 @@ describe('Linear issue queries', () => {
).rejects.toMatchObject({ kind: 'unconfirmed' })
})
it('creates parented agent issues with a client supplied id', async () => {
it('creates parented agent issues with a client supplied id and project id', async () => {
const createIssue = vi.fn().mockResolvedValue({
success: true,
issue: Promise.resolve({ id: 'issue-created' })
@@ -657,7 +657,8 @@ describe('Linear issue queries', () => {
await expect(
createIssueForAgent('team-1', 'Follow up', 'Details', 'workspace-1', {
id: '33333333-3333-4333-8333-333333333333',
parentId: 'issue-parent'
parentId: 'issue-parent',
projectId: 'project-1'
})
).resolves.toMatchObject({
id: 'issue-created',
@@ -670,7 +671,8 @@ describe('Linear issue queries', () => {
teamId: 'team-1',
title: 'Follow up',
description: 'Details',
parentId: 'issue-parent'
parentId: 'issue-parent',
projectId: 'project-1'
})
expect(rawRequest.mock.calls.at(-1)?.[0]).toContain('description')
})
+4
View File
@@ -104,6 +104,7 @@ export type LinearIssueWriteRecord = {
team: { id: string; key: string; name: string }
state: { id: string; name: string } | null
parent: { id: string; identifier: string } | null
project?: { id: string; name: string } | null
assignee?: { id: string; displayName: string } | null
priority?: number | null
estimate?: number | null
@@ -242,6 +243,7 @@ const AGENT_ISSUE_WRITE_FIELDS = `
team { id key name }
state { id name }
parent { id identifier }
project { id name }
assignee { id displayName }
priority
estimate
@@ -1113,6 +1115,7 @@ export async function createIssueForAgent(
options: {
id: string
parentId?: string | null
projectId?: string | null
stateId?: string
assigneeId?: string | null
priority?: number
@@ -1134,6 +1137,7 @@ export async function createIssueForAgent(
title,
...(description ? { description } : {}),
...(options.parentId ? { parentId: options.parentId } : {}),
...(options.projectId ? { projectId: options.projectId } : {}),
...(options.stateId ? { stateId: options.stateId } : {}),
...(options.assigneeId !== undefined ? { assigneeId: options.assigneeId } : {}),
...(options.priority !== undefined ? { priority: options.priority } : {}),
+98
View File
@@ -52,6 +52,27 @@ function rawProject(id: string) {
}
}
function rawProjectWithName(id: string, name: string) {
return {
...rawProject(id),
name
}
}
function projectSearchConnectionResponse(
projects: ReturnType<typeof rawProject>[],
pageInfo: { hasNextPage: boolean; endCursor?: string | null } = { hasNextPage: false }
) {
return {
data: {
searchProjects: {
nodes: projects,
pageInfo
}
}
}
}
function rawCustomView(id: string) {
return {
id,
@@ -80,6 +101,22 @@ function projectIssuesConnectionResponse(
}
}
function projectTeamsConnectionResponse(
teamIds: string[],
pageInfo: { hasNextPage: boolean; endCursor?: string | null } = { hasNextPage: false }
) {
return {
data: {
project: {
teams: {
nodes: teamIds.map((teamId) => ({ id: teamId, name: teamId, key: teamId })),
pageInfo
}
}
}
}
}
function customViewsResponse(viewId: string) {
return {
data: {
@@ -223,6 +260,67 @@ describe('Linear project queries', () => {
})
})
it('loads project teams above Linear connection page size', async () => {
rawRequest
.mockResolvedValueOnce(
projectTeamsConnectionResponse(
Array.from({ length: 50 }, (_, index) => `TEAM-${index + 1}`),
{ hasNextPage: true, endCursor: 'team-cursor-50' }
)
)
.mockResolvedValueOnce(projectTeamsConnectionResponse(['TEAM-51'], { hasNextPage: false }))
const { listProjectTeams } = await import('./projects')
const result = await listProjectTeams('project-1', 'workspace-1', true)
expect(result).toHaveLength(51)
expect(result.at(-1)).toMatchObject({ id: 'TEAM-51', key: 'TEAM-51' })
expect(rawRequest.mock.calls[0]?.[1]).toMatchObject({ id: 'project-1', first: 50 })
expect(rawRequest.mock.calls[0]?.[1]).not.toHaveProperty('after')
expect(rawRequest.mock.calls[1]?.[1]).toMatchObject({
id: 'project-1',
first: 50,
after: 'team-cursor-50'
})
})
it('loads exact project name matches beyond the first search page', async () => {
rawRequest
.mockResolvedValueOnce(
projectSearchConnectionResponse(
Array.from({ length: 50 }, (_, index) =>
rawProjectWithName(`project-${index + 1}`, `Other ${index + 1}`)
),
{ hasNextPage: true, endCursor: 'project-cursor-50' }
)
)
.mockResolvedValueOnce(
projectSearchConnectionResponse([
rawProjectWithName('project-launch', 'Launch'),
rawProjectWithName('project-launch-lower', 'launch')
])
)
const { listProjectsByExactName } = await import('./projects')
const result = await listProjectsByExactName('Launch', 'workspace-1', true)
expect(result).toMatchObject([
{ id: 'project-launch', name: 'Launch' },
{ id: 'project-launch-lower', name: 'launch' }
])
expect(rawRequest).toHaveBeenCalledTimes(2)
expect(rawRequest.mock.calls[0]?.[1]).toMatchObject({
term: 'Launch',
first: 50
})
expect(rawRequest.mock.calls[0]?.[1]).not.toHaveProperty('after')
expect(rawRequest.mock.calls[1]?.[1]).toMatchObject({
term: 'Launch',
first: 50,
after: 'project-cursor-50'
})
})
it('creates a project with team metadata and maps the created project', async () => {
rawRequest.mockResolvedValueOnce({
data: {
+162 -3
View File
@@ -150,6 +150,12 @@ type ProjectIssueConnectionResponse = {
} | null
}
type ProjectTeamsResponse = {
project?: {
teams?: LinearConnection<{ id: string; name?: string | null; key?: string | null }> | null
} | null
}
type CustomViewConnectionResponse = {
customViews?: LinearConnection<LinearCustomViewNode> | null
customView?:
@@ -316,13 +322,14 @@ const PROJECTS_QUERY = `
`
const SEARCH_PROJECTS_QUERY = `
query OrcaLinearProjectSearch($term: String!, $first: Int) {
searchProjects(term: $term, first: $first) {
query OrcaLinearProjectSearch($term: String!, $first: Int, $after: String) {
searchProjects(term: $term, first: $first, after: $after) {
nodes {
${ORCA_PROJECT_FIELDS}
}
pageInfo {
hasNextPage
endCursor
}
}
}
@@ -368,6 +375,24 @@ const PROJECT_ISSUES_QUERY = `
}
`
const PROJECT_TEAMS_QUERY = `
query OrcaLinearProjectTeams($id: String!, $first: Int, $after: String) {
project(id: $id) {
teams(first: $first, after: $after) {
nodes {
id
name
key
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
`
const CUSTOM_VIEWS_QUERY = `
query OrcaLinearCustomViews(
$first: Int,
@@ -482,9 +507,10 @@ const CUSTOM_VIEW_PROJECTS_QUERY = `
`
const inFlight = new Map<string, Promise<unknown>>()
const LINEAR_PROJECT_API_PAGE_SIZE_MAX = 50
function clampLimit(limit = 20): number {
return Math.min(Math.max(1, Math.floor(limit)), 50)
return Math.min(Math.max(1, Math.floor(limit)), LINEAR_PROJECT_API_PAGE_SIZE_MAX)
}
function coalesce<T>(key: string, load: () => Promise<T>, force = false): Promise<T> {
@@ -855,6 +881,70 @@ export async function listProjects(
)
}
export async function listProjectsByExactName(
name: string,
workspaceId: LinearConcreteWorkspaceId,
force = false
): Promise<LinearProjectSummary[]> {
const projectName = name.trim()
if (!projectName) {
throw new Error('Project name is required')
}
const normalized = projectName.toLowerCase()
const concreteWorkspaceId = normalizeConcreteWorkspaceId(workspaceId)
const key = `listProjectsByExactName:${concreteWorkspaceId}:${normalized}`
return coalesce(
key,
async () => {
const entries = getClients(concreteWorkspaceId)
const entry = entries[0]
if (!entry) {
return []
}
await acquire()
try {
const matches: LinearProjectSummary[] = []
let after: string | undefined
while (true) {
const result = await entry.client.client.rawRequest<
ProjectConnectionResponse,
LinearRawVariables
>(SEARCH_PROJECTS_QUERY, {
term: projectName,
first: LINEAR_PROJECT_API_PAGE_SIZE_MAX,
...(after ? { after } : {})
})
const connection = result.data?.searchProjects
for (const project of connection?.nodes ?? []) {
if (project.name.trim().toLowerCase() === normalized) {
matches.push(mapProjectForWorkspace(entry, project))
}
}
const nextCursor = connection?.pageInfo?.endCursor ?? undefined
if (
connection?.pageInfo?.hasNextPage !== true ||
!nextCursor ||
nextCursor === after ||
(connection.nodes ?? []).length === 0
) {
break
}
after = nextCursor
}
return matches
} catch (error) {
if (isAuthError(error)) {
clearToken(entry.workspace.id)
}
throw error
} finally {
release()
}
},
force
)
}
export async function getProject(
id: string,
workspaceId: LinearConcreteWorkspaceId,
@@ -961,6 +1051,75 @@ export async function listProjectIssues(
)
}
export async function listProjectTeams(
projectId: string,
workspaceId: LinearConcreteWorkspaceId,
force = false
): Promise<NonNullable<LinearProjectSummary['teams']>> {
const id = projectId.trim()
if (!id) {
throw new Error('Project ID is required')
}
const concreteWorkspaceId = normalizeConcreteWorkspaceId(workspaceId)
const key = `listProjectTeams:${concreteWorkspaceId}:${id}`
return coalesce(
key,
async () => {
const entry = getClients(concreteWorkspaceId)[0]
if (!entry) {
return []
}
const teams: NonNullable<LinearProjectSummary['teams']> = []
let after: string | undefined
await acquire()
try {
while (true) {
const result = await entry.client.client.rawRequest<
ProjectTeamsResponse,
LinearRawVariables
>(PROJECT_TEAMS_QUERY, {
id,
first: 50,
...(after ? { after } : {})
})
const project = result.data?.project
if (!project) {
throw new Error('Project was not found')
}
const connection = project.teams
const nodes = connection?.nodes ?? []
teams.push(
...nodes.map((team) => ({
id: team.id,
name: team.name ?? '',
key: team.key ?? undefined
}))
)
const nextCursor = connection?.pageInfo?.endCursor ?? undefined
if (
!connection?.pageInfo?.hasNextPage ||
!nextCursor ||
nextCursor === after ||
nodes.length === 0
) {
break
}
after = nextCursor
}
return teams
} catch (error) {
if (isAuthError(error)) {
clearToken(entry.workspace.id)
}
throw error
} finally {
release()
}
},
force
)
}
export async function listCustomViews(
model: LinearCustomViewModel,
limit = 20,
+209 -1
View File
@@ -82,6 +82,7 @@ import type {
JiraIssueUpdate,
JiraSiteSelection,
LinearIssueUpdate,
LinearProjectSummary,
LinearWorkspaceSelection,
NestedRepoScanResult,
ProjectGroup,
@@ -106,6 +107,7 @@ import type {
LinearErrorCode,
LinearIssueListFilter,
LinearIssueListResult,
LinearProjectListResult,
LinearIssueSummary,
LinearIssueRequest,
LinearIssueTaskUpdateRequest,
@@ -116,7 +118,12 @@ import type {
LinearTeamStatesResult,
LinearStatusSetResult
} from '../../shared/linear-agent-access'
import { LINEAR_WRITE_BODY_CAP } from '../../shared/linear-agent-access'
import {
LINEAR_SEARCH_MAX_LIMIT,
LINEAR_WRITE_BODY_CAP,
clampLinearSearchLimit
} from '../../shared/linear-agent-access'
import { isLinearUuid } from '../../shared/linear-uuid'
import type { FeatureInteractionId } from '../../shared/feature-interactions'
import type { TerminalPaneSplitSource } from '../../shared/feature-education-telemetry'
import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, splitWorktreeId } from '../../shared/worktree-id'
@@ -392,7 +399,9 @@ import {
listCustomViewIssues as listLinearCustomViewIssues,
listCustomViewProjects as listLinearCustomViewProjects,
listCustomViews as listLinearCustomViews,
listProjectsByExactName as listLinearProjectsByExactName,
listProjectIssues as listLinearProjectIssues,
listProjectTeams as listLinearProjectTeams,
listProjects as listLinearProjects,
type LinearProjectCreateInput
} from '../linear/projects'
@@ -1406,6 +1415,7 @@ type LinearCreateFieldIntent = {
estimate?: number | null
dueDate?: string | null
labelIds?: string[]
projectId?: string
}
function sameStringSet(left: string[], right: string[]): boolean {
@@ -15538,6 +15548,44 @@ export class OrcaRuntimeService {
}
}
async linearProjectListForAgents(params: {
query?: string
limit?: number
workspaceId?: string | 'all'
}): Promise<LinearProjectListResult> {
const limit = clampLinearSearchLimit(params.limit)
try {
const result = await this.linearListProjects(params.query, limit, params.workspaceId, true)
const projects = result.items.slice(0, limit).map((project) => ({
id: project.id,
name: project.name,
...(project.url ? { url: project.url } : {}),
...(project.workspaceId ? { workspaceId: project.workspaceId } : {}),
...(project.workspaceName ? { workspaceName: project.workspaceName } : {}),
...(project.teams ? { teams: project.teams } : {})
}))
const workspaceErrors = (result.errors ?? []).map((error) => ({
workspace: { id: error.workspaceId, name: error.workspaceName ?? error.workspaceId },
code: this.linearWorkspaceErrorCode(error.type),
message: sanitizeLinearErrorMessage(error.message)
}))
return {
projects,
meta: {
query: params.query,
workspaceId: params.workspaceId,
limit,
returned: projects.length,
hasMore: result.hasMore === true || result.items.length > limit,
partial: workspaceErrors.length > 0,
workspaceErrors
}
}
} catch (error) {
throw this.mapLinearReadFailure(error)
}
}
async linearIssueListForAgents(params: {
filter?: LinearIssueListFilter
teamInput?: string
@@ -15995,6 +16043,7 @@ export class OrcaRuntimeService {
estimate?: number
dueDate?: string
labels?: string[]
projectInput?: string
parentInput?: string
parentCurrent?: boolean
workspaceId?: string
@@ -16249,6 +16298,7 @@ export class OrcaRuntimeService {
estimate?: number
dueDate?: string
labels?: string[]
projectInput?: string
},
team: { id: string; workspaceId: string }
): Promise<LinearCreateFieldIntent> {
@@ -16284,9 +16334,161 @@ export class OrcaRuntimeService {
const labels = await this.resolveLinearLabelsForTeam(team.id, params.labels, team.workspaceId)
fields.labelIds = labels.map((label) => label.id)
}
if (params.projectInput) {
const project = await this.resolveLinearCreateProject(params.projectInput, team)
fields.projectId = project.id
}
return fields
}
private async resolveLinearCreateProject(
input: string,
team: { id: string; workspaceId: string }
): Promise<LinearProjectSummary> {
const trimmed = input.trim()
if (!trimmed) {
throw linearError('linear_invalid_project', 'Pass a non-empty Linear project id or name.')
}
const byId = isLinearUuid(trimmed)
? await this.readLinearProjectByIdForCreate(trimmed, team.workspaceId)
: null
if (byId) {
await this.assertLinearProjectIncludesTeam(byId, team.id, team.workspaceId, trimmed)
return byId
}
const searchCandidates = await this.readLinearProjectsForCreate(trimmed, team.workspaceId)
const normalized = trimmed.toLowerCase()
const idMatch = searchCandidates.find((project) => project.id.toLowerCase() === normalized)
if (idMatch) {
await this.assertLinearProjectIncludesTeam(idMatch, team.id, team.workspaceId, trimmed)
return idMatch
}
const nameMatches = await this.readLinearProjectsByExactNameForCreate(trimmed, team.workspaceId)
const compatibleNameMatches = await this.filterLinearProjectsForTeam(
nameMatches,
team.id,
team.workspaceId
)
if (compatibleNameMatches.length === 1) {
return compatibleNameMatches[0]
}
if (compatibleNameMatches.length > 1) {
throw linearError(
'linear_invalid_project',
`Multiple Linear projects exactly matched "${trimmed}".`,
{
projects: compatibleNameMatches.map((project) => ({
id: project.id,
name: project.name,
teams: project.teams
})),
nextSteps: ['Run `orca linear project list --query <name> --json` and retry by id.']
}
)
}
if (nameMatches.length > 0) {
await this.assertLinearProjectIncludesTeam(nameMatches[0], team.id, team.workspaceId, trimmed)
}
throw linearError('linear_invalid_project', `No Linear project exactly matched "${trimmed}".`, {
projects: searchCandidates.map((project) => ({
id: project.id,
name: project.name,
teams: project.teams
})),
nextSteps: ['Run `orca linear project list --query <name> --json` and retry by id.']
})
}
private async readLinearProjectByIdForCreate(
id: string,
workspaceId: string
): Promise<LinearProjectSummary | null> {
try {
return await getLinearProject(id, workspaceId, true)
} catch (error) {
throw this.mapLinearReadFailure(error)
}
}
private async readLinearProjectsForCreate(
query: string,
workspaceId: string
): Promise<LinearProjectSummary[]> {
try {
return (await listLinearProjects(query, LINEAR_SEARCH_MAX_LIMIT, workspaceId, true)).items
} catch (error) {
throw this.mapLinearReadFailure(error)
}
}
private async readLinearProjectsByExactNameForCreate(
name: string,
workspaceId: string
): Promise<LinearProjectSummary[]> {
try {
return await listLinearProjectsByExactName(name, workspaceId, true)
} catch (error) {
throw this.mapLinearReadFailure(error)
}
}
private async assertLinearProjectIncludesTeam(
project: LinearProjectSummary,
teamId: string,
workspaceId: string,
input: string
): Promise<void> {
if (this.linearProjectIncludesTeam(project, teamId)) {
return
}
let teams: NonNullable<LinearProjectSummary['teams']> = []
try {
// Why: summary reads cap project teams, so large cross-team projects need
// a paged membership check before we reject an otherwise valid create.
teams = await listLinearProjectTeams(project.id, workspaceId, true)
} catch (error) {
throw this.mapLinearReadFailure(error)
}
if (teams.some((team) => team.id === teamId)) {
return
}
throw linearError(
'linear_invalid_project',
`Linear project "${input}" is not available to the target team.`,
{
project: { id: project.id, name: project.name, teams },
nextSteps: ['Choose a project that includes the create target team, then retry by id.']
}
)
}
private async filterLinearProjectsForTeam(
projects: LinearProjectSummary[],
teamId: string,
workspaceId: string
): Promise<LinearProjectSummary[]> {
const compatible: LinearProjectSummary[] = []
for (const project of projects) {
if (this.linearProjectIncludesTeam(project, teamId)) {
compatible.push(project)
continue
}
try {
const teams = await listLinearProjectTeams(project.id, workspaceId, true)
if (teams.some((team) => team.id === teamId)) {
compatible.push({ ...project, teams })
}
} catch (error) {
throw this.mapLinearReadFailure(error)
}
}
return compatible
}
private linearProjectIncludesTeam(project: LinearProjectSummary, teamId: string): boolean {
return project.teams?.some((team) => team.id === teamId) === true
}
private async getLinearViewerForWrite(
workspaceId: string
): Promise<{ id: string; displayName?: string | null; avatarUrl?: string | null }> {
@@ -16373,6 +16575,9 @@ export class OrcaRuntimeService {
if (intent.dueDate !== undefined && (issue.dueDate ?? null) !== intent.dueDate) {
return false
}
if (intent.projectId !== undefined && (issue.project?.id ?? null) !== intent.projectId) {
return false
}
const issueLabelIds = issue.labelIds ?? issue.labels?.map((label) => label.id) ?? []
if (intent.labelIds !== undefined && !sameStringSet(issueLabelIds, intent.labelIds)) {
return false
@@ -16978,6 +17183,9 @@ export class OrcaRuntimeService {
? [`--estimate=${fields.estimate}`]
: []),
...(fields.dueDate ? [`--due-date=${fields.dueDate}`] : []),
...(fields.projectId
? [`--project=${this.commandToken(fields.projectId, 'PROJECT_ID')}`]
: []),
...(fields.labelIds ?? []).map(
(labelId) => `--label=${this.commandToken(labelId, 'LABEL_ID')}`
)
@@ -20,6 +20,7 @@ describe('Linear agent access RPC methods', () => {
linearTeamStatesForAgents: vi.fn().mockResolvedValue({ ok: true }),
linearTeamLabelsForAgents: vi.fn().mockResolvedValue({ ok: true }),
linearIssueListForAgents: vi.fn().mockResolvedValue({ ok: true }),
linearProjectListForAgents: vi.fn().mockResolvedValue({ ok: true }),
linearIssueUpdateTask: vi.fn().mockResolvedValue({ ok: true }),
linearIssueAddComment: vi.fn().mockResolvedValue({ ok: true }),
linearIssueAttachLink: vi.fn().mockResolvedValue({ ok: true }),
@@ -54,6 +55,13 @@ describe('Linear agent access RPC methods', () => {
workspaceId: 'workspace-1'
})
)
const projectListResponse = await dispatcher.dispatch(
makeRequest('linear.agentProjectList', {
query: 'launch',
limit: 10,
workspaceId: 'all'
})
)
const taskUpdateResponse = await dispatcher.dispatch(
makeRequest('linear.issueUpdateTask', {
input: 'ENG-1',
@@ -85,6 +93,7 @@ describe('Linear agent access RPC methods', () => {
title: 'Follow up',
body: 'Details',
teamInput: 'ENG',
projectInput: 'project-1',
priority: 2,
parentInput: 'ENG-1',
writeId: '33333333-3333-4333-8333-333333333333',
@@ -98,6 +107,7 @@ describe('Linear agent access RPC methods', () => {
expect(teamStatesResponse.ok).toBe(true)
expect(teamLabelsResponse.ok).toBe(true)
expect(issueListResponse.ok).toBe(true)
expect(projectListResponse.ok).toBe(true)
expect(taskUpdateResponse.ok).toBe(true)
expect(commentResponse.ok).toBe(true)
expect(attachResponse.ok).toBe(true)
@@ -126,6 +136,11 @@ describe('Linear agent access RPC methods', () => {
limit: 10,
workspaceId: 'workspace-1'
})
expect(runtime.linearProjectListForAgents).toHaveBeenCalledWith({
query: 'launch',
limit: 10,
workspaceId: 'all'
})
expect(runtime.linearIssueUpdateTask).toHaveBeenCalledWith({
input: 'ENG-1',
operation: 'dueDate',
@@ -150,6 +165,7 @@ describe('Linear agent access RPC methods', () => {
title: 'Follow up',
body: 'Details',
teamInput: 'ENG',
projectInput: 'project-1',
priority: 2,
parentInput: 'ENG-1',
writeId: '33333333-3333-4333-8333-333333333333',
@@ -429,7 +445,13 @@ describe('Linear agent write recovery helpers', () => {
team: { id: 'team-2', key: 'OTHER', name: 'Other', workspaceId: 'workspace-1' },
title: 'Follow up',
bodyRequired: true,
createFields: { priority: 2, estimate: 3, dueDate: '2026-06-30', labelIds: ['label-1'] }
createFields: {
priority: 2,
estimate: 3,
dueDate: '2026-06-30',
projectId: 'project-1',
labelIds: ['label-1']
}
})
expect(comment.data?.nextSteps?.[0]).toContain('--body-file -')
@@ -444,6 +466,7 @@ describe('Linear agent write recovery helpers', () => {
expect(create.data?.nextSteps?.[0]).toContain('--priority=high')
expect(create.data?.nextSteps?.[0]).toContain('--estimate=3')
expect(create.data?.nextSteps?.[0]).toContain('--due-date=2026-06-30')
expect(create.data?.nextSteps?.[0]).toContain('--project=project-1')
expect(create.data?.nextSteps?.[0]).toContain('--label=label-1')
expect(create.data?.nextSteps?.[0]).toContain('Replace TITLE_HERE')
})
@@ -459,6 +482,7 @@ describe('Linear agent write recovery helpers', () => {
team: { id: 'team-1', key: 'ENG', name: 'Engineering' },
state: { id: 'state-review', name: 'In Review' },
parent: null,
project: { id: 'project-1', name: 'Launch' },
assignee: { id: 'user-1', displayName: 'Ada' },
priority: 2,
estimate: 3,
@@ -474,13 +498,14 @@ describe('Linear agent write recovery helpers', () => {
priority: 2,
estimate: 3,
dueDate: '2026-06-30',
projectId: 'project-1',
labelIds: ['label-1']
})
).toBe(true)
expect(
builder.linearCreatedIssueMatchesIntent(issue, {
stateId: 'state-review',
priority: 3
projectId: 'project-2'
})
).toBe(false)
})
@@ -544,7 +569,8 @@ describe('Linear agent write recovery helpers', () => {
url: 'https://example.invalid/ENG-2',
team: { id: 'team-1', key: 'ENG', name: 'Engineering' },
state: null,
parent: { id: 'issue-1', identifier: 'ENG-1' }
parent: { id: 'issue-1', identifier: 'ENG-1' },
project: { id: 'project-1', name: 'Launch' }
}))
await expect(
tester.getMatchingLinearCreatedIssue(
@@ -555,6 +581,17 @@ describe('Linear agent write recovery helpers', () => {
true
)
).resolves.toMatchObject({ id: 'issue-2' })
await expect(
tester.getMatchingLinearCreatedIssue(
'33333333-3333-4333-8333-333333333333',
'team-1',
'issue-1',
'workspace-1',
true,
{ projectId: 'project-2' }
)
).rejects.toMatchObject({ code: 'linear_invalid_write_id' })
})
it('keeps the unconfirmed retry envelope when duplicate recovery lookup fails', async () => {
@@ -2,8 +2,8 @@ import { z } from 'zod'
import { defineMethod, type RpcMethod } from '../core'
import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas'
import { linearError } from '../../../linear/issue-context-errors'
import { isLinearUuid } from '../../../../shared/linear-uuid'
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const LINEAR_DUE_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/
const LinearDueDate = z.string().refine((value) => LINEAR_DUE_DATE_PATTERN.test(value), {
message: 'Linear due dates must use YYYY-MM-DD'
@@ -35,6 +35,12 @@ const LinearIssueList = z.object({
workspaceId: z.union([z.string(), z.literal('all')]).optional()
})
const LinearProjectList = z.object({
query: OptionalString,
limit: OptionalFiniteNumber,
workspaceId: z.union([z.string(), z.literal('all')]).optional()
})
const LinearIncludeFlags = z.object({
comments: z.boolean(),
children: z.boolean(),
@@ -107,6 +113,7 @@ const LinearIssueCreate = z.object({
estimate: z.number().int().min(0).optional(),
dueDate: OptionalLinearDueDate,
labels: z.array(z.string()).optional(),
projectInput: OptionalString,
parentInput: OptionalString,
parentCurrent: z.boolean().optional(),
workspaceId: OptionalString.refine((value) => value !== 'all', {
@@ -120,7 +127,7 @@ function parseLinearWriteId(writeId: string | undefined): string | undefined {
if (writeId === undefined) {
return undefined
}
if (!UUID_PATTERN.test(writeId)) {
if (!isLinearUuid(writeId)) {
throw linearError('linear_invalid_write_id', '--write-id must be a UUID')
}
return writeId
@@ -167,6 +174,11 @@ export const LINEAR_AGENT_ACCESS_METHODS: RpcMethod[] = [
params: LinearIssueList,
handler: async (params, { runtime }) => runtime.linearIssueListForAgents(params)
}),
defineMethod({
name: 'linear.agentProjectList',
params: LinearProjectList,
handler: async (params, { runtime }) => runtime.linearProjectListForAgents(params)
}),
defineMethod({
name: 'linear.resolveCurrentIssue',
params: LinearCurrentContext,
@@ -0,0 +1,246 @@
import { describe, expect, it, vi } from 'vitest'
import { OrcaRuntimeService } from '../../orca-runtime'
import type * as LinearIssuesModule from '../../../linear/issues'
type LinearProjectResolverTester = {
resolveLinearCreateProject(
input: string,
team: { id: string; workspaceId: string }
): Promise<{
id: string
name: string
}>
readLinearProjectByIdForCreate(id: string, workspaceId: string): Promise<unknown | null>
readLinearProjectsForCreate(query: string, workspaceId: string): Promise<unknown[]>
readLinearProjectsByExactNameForCreate(name: string, workspaceId: string): Promise<unknown[]>
}
type LinearCreateTester = LinearProjectResolverTester & {
resolveLinearCreateTeam(
teamInput: string | undefined,
workspaceId: string | undefined,
parent: unknown
): Promise<{ id: string; key: string; name: string; workspaceId: string }>
}
describe('Linear agent project access helpers', () => {
it('resolves Linear projects by UUID before searching names', async () => {
const runtime = new OrcaRuntimeService()
const tester = runtime as unknown as LinearProjectResolverTester
const readById = vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue({
id: '11111111-1111-4111-8111-111111111111',
name: 'Launch',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
} as never)
const readByName = vi
.spyOn(tester, 'readLinearProjectsForCreate')
.mockResolvedValue([] as never)
await expect(
tester.resolveLinearCreateProject('11111111-1111-4111-8111-111111111111', {
id: 'team-1',
workspaceId: 'workspace-1'
})
).resolves.toMatchObject({ id: '11111111-1111-4111-8111-111111111111' })
expect(readById).toHaveBeenCalledWith('11111111-1111-4111-8111-111111111111', 'workspace-1')
expect(readByName).not.toHaveBeenCalled()
})
it('resolves Linear projects by trimmed case-insensitive exact name', async () => {
const runtime = new OrcaRuntimeService()
const tester = runtime as unknown as LinearProjectResolverTester
vi.spyOn(tester, 'readLinearProjectByIdForCreate').mockResolvedValue(null as never)
const readByName = vi.spyOn(tester, 'readLinearProjectsForCreate').mockResolvedValue([
{
id: 'project-1',
name: 'Launch',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
}
] as never)
const readExactName = vi
.spyOn(tester, 'readLinearProjectsByExactNameForCreate')
.mockResolvedValue([
{
id: 'project-1',
name: 'Launch',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
}
] as never)
await expect(
tester.resolveLinearCreateProject(' launch ', { id: 'team-1', workspaceId: 'workspace-1' })
).resolves.toMatchObject({ id: 'project-1' })
expect(readByName).toHaveBeenCalledWith('launch', 'workspace-1')
expect(readExactName).toHaveBeenCalledWith('launch', 'workspace-1')
})
it('resolves same-named Linear projects by target team compatibility', 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([] as never)
vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([
{
id: 'project-1',
name: 'Launch',
teams: [{ id: 'team-other', name: 'Other', key: 'OTH' }]
},
{
id: 'project-2',
name: 'launch',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
}
] as never)
await expect(
tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' })
).resolves.toMatchObject({ id: 'project-2' })
})
it('rejects ambiguous Linear project names with candidate ids', 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([] as never)
vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([
{
id: 'project-1',
name: 'Launch',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
},
{
id: 'project-2',
name: 'launch',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
}
] as never)
await expect(
tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' })
).rejects.toMatchObject({
code: 'linear_invalid_project',
data: {
projects: [
{ id: 'project-1', name: 'Launch' },
{ id: 'project-2', name: 'launch' }
]
}
})
})
it('fails closed when Linear project team membership cannot be verified', 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([] as never)
vi.spyOn(tester, 'readLinearProjectsByExactNameForCreate').mockResolvedValue([
{
id: 'project-1',
name: 'Launch'
}
] as never)
await expect(
tester.resolveLinearCreateProject('Launch', { id: 'team-1', workspaceId: 'workspace-1' })
).rejects.toMatchObject({
code: 'linear_invalid_project',
data: { project: { id: 'project-1', name: 'Launch', teams: [] } }
})
})
it('caps agent project lists globally and returns a narrow project DTO', async () => {
const runtime = new OrcaRuntimeService()
vi.spyOn(runtime, 'linearListProjects').mockResolvedValue({
items: [
{
id: 'project-1',
name: 'Launch',
url: 'https://linear.app/acme/project/launch',
workspaceId: 'workspace-1',
workspaceName: 'Acme',
content: 'internal notes',
description: 'roadmap',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
},
{
id: 'project-2',
name: 'Follow-up',
workspaceId: 'workspace-2',
workspaceName: 'Beta'
}
],
hasMore: false
} as never)
const result = await runtime.linearProjectListForAgents({ limit: 1, workspaceId: 'all' })
expect(result.projects).toHaveLength(1)
expect(result.projects[0]).toMatchObject({
id: 'project-1',
name: 'Launch',
url: 'https://linear.app/acme/project/launch',
workspaceId: 'workspace-1',
workspaceName: 'Acme',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
})
expect(result.projects[0]).not.toHaveProperty('content')
expect(result.projects[0]).not.toHaveProperty('description')
expect(result.meta).toMatchObject({ limit: 1, returned: 1, hasMore: true })
})
it('passes the resolved project id into agent issue create', async () => {
vi.resetModules()
const createIssueForAgent = vi.fn().mockResolvedValue({
id: 'issue-created',
identifier: 'ENG-123',
title: 'Follow up',
url: 'https://linear.app/acme/issue/ENG-123',
team: { id: 'team-1', key: 'ENG', name: 'Engineering' },
state: null,
parent: null,
project: { id: 'project-1', name: 'Launch' }
})
vi.doMock('../../../linear/issues', async (importOriginal) => {
const actual = await importOriginal<typeof LinearIssuesModule>()
return { ...actual, createIssueForAgent }
})
try {
const { OrcaRuntimeService: RuntimeService } = await import('../../orca-runtime')
const runtime = new RuntimeService()
const tester = runtime as unknown as LinearCreateTester
vi.spyOn(tester, 'resolveLinearCreateTeam').mockResolvedValue({
id: 'team-1',
key: 'ENG',
name: 'Engineering',
workspaceId: 'workspace-1'
})
vi.spyOn(tester, 'resolveLinearCreateProject').mockResolvedValue({
id: 'project-1',
name: 'Launch'
} as never)
const result = await runtime.linearIssueCreate({
title: 'Follow up',
teamInput: 'ENG',
projectInput: 'Launch',
writeId: '33333333-3333-4333-8333-333333333333'
})
expect(result.issue.project).toMatchObject({ id: 'project-1', name: 'Launch' })
expect(createIssueForAgent).toHaveBeenCalledWith(
'team-1',
'Follow up',
undefined,
'workspace-1',
expect.objectContaining({
id: '33333333-3333-4333-8333-333333333333',
parentId: null,
projectId: 'project-1'
})
)
} finally {
vi.doUnmock('../../../linear/issues')
vi.resetModules()
}
})
})
+145 -1
View File
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import { isLinearProjectListResult } from './ssh-remote-linear-result-guards'
import { runRemoteOrcaCli } from './ssh-remote-orca-cli'
function createRuntime() {
@@ -72,6 +73,27 @@ function createRuntime() {
labels: [{ id: 'label-1', name: 'Bug', color: '#ff0000' }],
meta: { workspaceId: 'workspace-1', returned: 1 }
})),
linearProjectListForAgents: vi.fn(async (request: unknown) => ({
request,
projects: [
{
id: 'project-1',
name: 'Launch',
workspaceId: 'workspace-1',
workspaceName: 'Acme',
teams: [{ id: 'team-1', name: 'Engineering', key: 'ENG' }]
}
],
meta: {
query: 'launch',
workspaceId: 'workspace-1',
limit: 5,
returned: 1,
hasMore: false,
partial: false,
workspaceErrors: []
}
})),
linearIssueListForAgents: vi.fn(async (request: unknown) => ({
request,
issues: [],
@@ -158,7 +180,8 @@ function createRuntime() {
url: 'https://linear.app/acme/issue/ENG-456',
team: { id: 'team-1', key: 'ENG', name: 'Engineering' },
state: { id: 'state-triage', name: 'Triage' },
parent: { id: 'issue-1', identifier: 'ENG-123' }
parent: { id: 'issue-1', identifier: 'ENG-123' },
project: { id: 'project-1', name: 'Launch' }
},
meta: {
workspaceId: 'workspace-1',
@@ -274,10 +297,27 @@ describe('runRemoteOrcaCli Linear commands', () => {
cwd: '/home/alice/remote-repo',
env: { ORCA_TERMINAL_HANDLE: 'term_ssh' }
})
const projects = await runRemoteOrcaCli(runtime, {
argv: [
'linear',
'project',
'list',
'--query',
'launch',
'--limit',
'5',
'--workspace',
'workspace-1',
'--json'
],
cwd: '/home/alice/remote-repo',
env: { ORCA_TERMINAL_HANDLE: 'term_ssh' }
})
expect(teamList.exitCode).toBe(0)
expect(labels.exitCode).toBe(0)
expect(list.exitCode).toBe(0)
expect(projects.exitCode).toBe(0)
expect(
(runtime as unknown as { linearTeamListForAgents: ReturnType<typeof vi.fn> })
.linearTeamListForAgents
@@ -295,6 +335,58 @@ describe('runRemoteOrcaCli Linear commands', () => {
limit: 5,
workspaceId: 'workspace-1'
})
expect(
(runtime as unknown as { linearProjectListForAgents: ReturnType<typeof vi.fn> })
.linearProjectListForAgents
).toHaveBeenCalledWith({
query: 'launch',
limit: 5,
workspaceId: 'workspace-1'
})
})
it('formats SSH Linear project list in non-json mode', async () => {
const runtime = createRuntime()
const result = await runRemoteOrcaCli(runtime, {
argv: ['linear', 'project', 'list', '--query', 'launch', '--workspace', 'workspace-1'],
cwd: '/home/alice/remote-repo',
env: { ORCA_TERMINAL_HANDLE: 'term_ssh' }
})
expect(result.exitCode).toBe(0)
expect(result.stdout).toContain('Launch')
expect(result.stdout).toContain('project-1')
expect(result.stdout).toContain('ENG')
expect(result.stdout).toContain('Acme')
expect(result.stderr).toBe('')
})
it('rejects malformed SSH Linear project list results before formatting', () => {
expect(
isLinearProjectListResult({
projects: [{ id: 'project-1' }],
meta: {
limit: 5,
returned: 1,
hasMore: false,
partial: false,
workspaceErrors: []
}
})
).toBe(false)
expect(
isLinearProjectListResult({
projects: [{ id: 'project-1', name: 'Launch', teams: [{ id: 'team-1' }] }],
meta: {
limit: 5,
returned: 1,
hasMore: false,
partial: false,
workspaceErrors: []
}
})
).toBe(false)
})
it('dispatches Linear status writes through the remote runtime with SSH context hints', async () => {
@@ -351,6 +443,58 @@ describe('runRemoteOrcaCli Linear commands', () => {
})
})
it('dispatches Linear creates with project input through the SSH remote runtime', async () => {
const runtime = createRuntime()
const result = await runRemoteOrcaCli(runtime, {
argv: [
'linear',
'create',
'--title',
'Follow-up',
'--team',
'ENG',
'--project',
'project-1',
'--json'
],
cwd: '/home/alice/remote-repo',
env: {
ORCA_TERMINAL_HANDLE: 'term_ssh',
ORCA_WORKTREE_ID: 'repo::remote'
}
})
expect(result.exitCode).toBe(0)
const payload = JSON.parse(result.stdout) as {
ok: boolean
result: { request: { title: string; teamInput: string; projectInput: string } }
}
expect(payload.ok).toBe(true)
expect(payload.result.request).toMatchObject({
title: 'Follow-up',
teamInput: 'ENG',
projectInput: 'project-1'
})
})
it('formats SSH Linear creates with project input in non-json mode', async () => {
const runtime = createRuntime()
const result = await runRemoteOrcaCli(runtime, {
argv: ['linear', 'create', '--title', 'Follow-up', '--team', 'ENG', '--project', 'project-1'],
cwd: '/home/alice/remote-repo',
env: {
ORCA_TERMINAL_HANDLE: 'term_ssh',
ORCA_WORKTREE_ID: 'repo::remote'
}
})
expect(result.exitCode).toBe(0)
expect(result.stdout).toBe('Created ENG-456 under ENG-123 in Launch: Follow-up.\n')
expect(result.stderr).toBe('')
})
it('parses --me as a boolean for SSH Linear assignee writes', async () => {
const runtime = createRuntime()
+19 -1
View File
@@ -2,6 +2,7 @@ import type {
LinearIssueContextResult,
LinearIssueListResult,
LinearIssueTaskUpdateResult,
LinearProjectListResult,
LinearSearchIssueSummary,
LinearSearchResult,
LinearTeamListResult,
@@ -13,12 +14,17 @@ import type {
LinearAttachResult,
LinearCreateResult
} from '../../shared/linear-agent-access'
import {
formatLinearProjectListRows,
linearProjectListWarningLines
} from '../../shared/linear-project-list-format'
import {
isLinearAttachResult,
isLinearCommentAddResult,
isLinearCreateResult,
isLinearIssueContextResult,
isLinearIssueListResult,
isLinearProjectListResult,
isLinearSearchResult,
isLinearStatusSetResult,
isLinearTaskUpdateResult,
@@ -44,6 +50,12 @@ export function formatRemoteLinearCli(result: unknown): { stdout: string; stderr
stderr: linearListWarnings(result)
}
}
if (isLinearProjectListResult(result)) {
return {
stdout: `${formatLinearProjectListRows(result)}\n`,
stderr: linearProjectListWarnings(result)
}
}
if (isLinearTeamListResult(result)) {
return { stdout: `${formatLinearTeamList(result)}\n`, stderr: linearListWarnings(result) }
}
@@ -195,8 +207,9 @@ function formatLinearAttach(result: LinearAttachResult): string {
function formatLinearCreate(result: LinearCreateResult): string {
const parent = result.issue.parent ? ` under ${result.issue.parent.identifier}` : ''
const project = result.issue.project?.name ? ` in ${result.issue.project.name}` : ''
const suffix = result.meta.deduplicated ? ' (already created)' : ''
return `Created ${result.issue.identifier}${parent}: ${result.issue.title}${suffix}.`
return `Created ${result.issue.identifier}${parent}${project}: ${result.issue.title}${suffix}.`
}
function taskOperationLabel(operation: LinearIssueTaskUpdateResult['operation']): string {
@@ -232,3 +245,8 @@ function linearListWarnings(
}
return warnings.length > 0 ? `${warnings.join('\n')}\n` : ''
}
function linearProjectListWarnings(result: LinearProjectListResult): string {
const warnings = linearProjectListWarningLines(result)
return warnings.length > 0 ? `${warnings.join('\n')}\n` : ''
}
@@ -11,6 +11,7 @@ import { RemoteCliArgumentError, type ParsedRemoteCli } from './ssh-remote-linea
import {
LINEAR_ISSUE_FLAGS,
LINEAR_LIST_FLAGS,
LINEAR_PROJECT_LIST_FLAGS,
LINEAR_SEARCH_FLAGS,
LINEAR_TEAM_LIST_FLAGS,
LINEAR_TEAM_LOOKUP_FLAGS
@@ -78,6 +79,19 @@ export async function tryDispatchRemoteLinearReadCli(
'linear.agentTeamLabels'
)
}
if (isRemoteCommand(parsed, 'linear', 'project', 'list')) {
validateLinearRemoteArgs(parsed, {
command: ['linear', 'project', 'list'],
allowedFlags: LINEAR_PROJECT_LIST_FLAGS,
positionalFlag: 'id',
maxPositionals: 0
})
return await call(dispatcher, 'linear.agentProjectList', {
query: optionalString(parsed.flags, 'query'),
limit: clampLinearSearchLimit(optionalPositiveInteger(parsed.flags, 'limit')),
workspaceId: optionalString(parsed.flags, 'workspace')
})
}
if (isRemoteCommand(parsed, 'linear', 'list')) {
validateLinearRemoteArgs(parsed, {
command: ['linear', 'list'],
@@ -37,6 +37,15 @@ export const LINEAR_TEAM_LOOKUP_FLAGS = new Set([
'team',
'workspace'
])
export const LINEAR_PROJECT_LIST_FLAGS = new Set([
'help',
'json',
'pairing-code',
'environment',
'query',
'limit',
'workspace'
])
export const LINEAR_LIST_FLAGS = new Set([
'help',
'json',
@@ -20,6 +20,9 @@ export function getRemoteLinearReadHelp(commandPath: string[]): string | null {
if (matchesRemoteCommand(commandPath, 'linear', 'team', 'labels')) {
return LINEAR_TEAM_LABELS_HELP
}
if (matchesRemoteCommand(commandPath, 'linear', 'project', 'list')) {
return LINEAR_PROJECT_LIST_HELP
}
if (matchesRemoteCommand(commandPath, 'linear', 'list')) {
return LINEAR_LIST_HELP
}
@@ -44,6 +47,7 @@ Commands:
team members List Linear team members
team states List Linear team workflow states
team labels List Linear team labels
project list List connected Linear projects
list List Linear issues
assignee set Set a Linear issue assignee
assignee clear Clear a Linear issue assignee
@@ -132,6 +136,12 @@ Usage: orca linear team labels --team <key|id> [--workspace <id>] [--json]
List Linear team labels`
const LINEAR_PROJECT_LIST_HELP = `orca linear project list
Usage: orca linear project list [--query <text>] [--limit <n>] [--workspace <id>|all] [--json]
List connected Linear projects`
const LINEAR_LIST_HELP = `orca linear list
Usage: orca linear list [--filter assigned|created|all|completed|open] [--team <key|id>] [--limit <n>] [--workspace <id>|all] [--json]
@@ -5,6 +5,7 @@ import type {
LinearIssueContextResult,
LinearIssueListResult,
LinearIssueTaskUpdateResult,
LinearProjectListResult,
LinearSearchResult,
LinearStatusSetResult,
LinearTeamLabelsResult,
@@ -45,6 +46,21 @@ export function isLinearIssueListResult(result: unknown): result is LinearIssueL
)
}
export function isLinearProjectListResult(result: unknown): result is LinearProjectListResult {
return (
isRecord(result) &&
Array.isArray(result.projects) &&
result.projects.every(isLinearProjectListProject) &&
isRecord(result.meta) &&
typeof result.meta.limit === 'number' &&
typeof result.meta.returned === 'number' &&
typeof result.meta.hasMore === 'boolean' &&
typeof result.meta.partial === 'boolean' &&
Array.isArray(result.meta.workspaceErrors) &&
result.meta.workspaceErrors.every(isLinearWorkspaceError)
)
}
export function isLinearTeamListResult(result: unknown): result is LinearTeamListResult {
return (
isRecord(result) &&
@@ -123,3 +139,34 @@ export function isLinearCreateResult(result: unknown): result is LinearCreateRes
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object'
}
function isLinearProjectListProject(project: unknown): boolean {
return (
isRecord(project) &&
typeof project.id === 'string' &&
typeof project.name === 'string' &&
(project.workspaceId === undefined || typeof project.workspaceId === 'string') &&
(project.workspaceName === undefined || typeof project.workspaceName === 'string') &&
(project.teams === undefined ||
(Array.isArray(project.teams) && project.teams.every(isLinearProjectTeam)))
)
}
function isLinearProjectTeam(team: unknown): boolean {
return (
isRecord(team) &&
typeof team.id === 'string' &&
typeof team.name === 'string' &&
(team.key === undefined || typeof team.key === 'string')
)
}
function isLinearWorkspaceError(error: unknown): boolean {
return (
isRecord(error) &&
isRecord(error.workspace) &&
typeof error.workspace.name === 'string' &&
typeof error.code === 'string' &&
typeof error.message === 'string'
)
}
@@ -48,6 +48,7 @@ const LINEAR_CREATE_FLAGS = new Set([
'body',
'body-file',
'team',
'project',
'state',
'assignee',
'priority',
@@ -223,6 +224,7 @@ export async function tryDispatchRemoteLinearWriteCli(
title: requiredString(parsed.flags, 'title'),
...(body !== undefined ? { body } : {}),
teamInput: optionalString(parsed.flags, 'team'),
projectInput: optionalString(parsed.flags, 'project'),
state: optionalString(parsed.flags, 'state'),
assignee: optionalString(parsed.flags, 'assignee'),
priority: parsed.flags.has('priority') ? priorityFlag(parsed.flags, 'priority') : undefined,
+1 -1
View File
@@ -74,4 +74,4 @@ const LINEAR_LABEL_REMOVE_HELP = `orca linear label remove\n\nUsage: orca linear
const LINEAR_LABEL_SET_HELP = `orca linear label set\n\nUsage: orca linear label set [<id>] [--current] --label <labelId-or-exact-name>... [--workspace <id>] [--json]\n\nReplace labels on a Linear issue`
const LINEAR_COMMENT_HELP = `orca linear comment add\n\nUsage: orca linear comment add [<id>] [--current] (--body <text> | --body-file -) [--reply-to <commentId>] [--write-id <uuid>] [--workspace <id>] [--json]\n\nAdd a comment to a Linear issue`
const LINEAR_ATTACH_HELP = `orca linear attach\n\nUsage: orca linear attach [<id>] [--current] --url <url> [--title <title>] [--write-id <uuid>] [--workspace <id>] [--json]\n\nAttach a link to a Linear issue`
const LINEAR_CREATE_HELP = `orca linear create\n\nUsage: orca linear create --title <title> [--body <text> | --body-file -] [--team <key|id>] [--state <stateId|exact-name>] [--assignee me|<userId>] [--priority none|low|medium|high|urgent] [--estimate <number>] [--due-date <yyyy-mm-dd>] [--label <labelId-or-exact-name>]... [--parent <id> | --parent-current] [--write-id <uuid>] [--workspace <id>] [--json]\n\nCreate a Linear issue`
const LINEAR_CREATE_HELP = `orca linear create\n\nUsage: orca linear create --title <title> [--body <text> | --body-file -] [--team <key|id>] [--project <projectId-or-exact-name>] [--state <stateId|exact-name>] [--assignee me|<userId>] [--priority none|low|medium|high|urgent] [--estimate <number>] [--due-date <yyyy-mm-dd>] [--label <labelId-or-exact-name>]... [--parent <id> | --parent-current] [--write-id <uuid>] [--workspace <id>] [--json]\n\nCreate a Linear issue`
@@ -1,5 +1,6 @@
import type { RpcResponse } from '../runtime/rpc/core'
import type { RpcDispatcher } from '../runtime/rpc/dispatcher'
import { isLinearUuid } from '../../shared/linear-uuid'
type ParsedRemoteCli = {
commandPath: string[]
@@ -16,7 +17,6 @@ export class RemoteLinearWriteArgumentError extends Error {
}
}
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const REPEATED_FLAG_SEPARATOR = '\u0000'
const LINEAR_PRIORITY_VALUES = new Map([
['none', 0],
@@ -114,7 +114,7 @@ export function optionalWriteId(flags: Map<string, string | boolean>): string |
return undefined
}
const writeId = requiredString(flags, 'write-id')
if (!UUID_PATTERN.test(writeId)) {
if (!isLinearUuid(writeId)) {
throw new RemoteLinearWriteArgumentError('linear_invalid_write_id', '--write-id must be a UUID')
}
return writeId
+9
View File
@@ -21,6 +21,7 @@ export const LINEAR_ERROR_CODES = [
'linear_invalid_assignee',
'linear_invalid_label',
'linear_invalid_parent',
'linear_invalid_project',
'linear_team_required',
'linear_invalid_url',
'linear_body_too_large',
@@ -73,6 +74,7 @@ export type {
LinearIssueCommentNode,
LinearIssueContextResult,
LinearIssueListResult,
LinearProjectListResult,
LinearIssueRelation,
LinearIssueSummary,
LinearNamedEntity,
@@ -111,6 +113,12 @@ export type LinearIssueListRequest = {
workspaceId?: string | 'all'
}
export type LinearProjectListRequest = {
query?: string
limit?: number
workspaceId?: string | 'all'
}
export type LinearStatusSetRequest = LinearWriteTargetRequest & {
to: string
}
@@ -149,6 +157,7 @@ export type LinearCreateRequest = {
estimate?: number
dueDate?: string
labels?: string[]
projectInput?: string
parentInput?: string
parentCurrent?: boolean
workspaceId?: string
+31
View File
@@ -216,6 +216,36 @@ export type LinearIssueListResult = {
}
}
export type LinearAgentProjectSummary = {
id: string
name: string
url?: string
workspaceId?: string
workspaceName?: string
teams?: {
id: string
name: string
key?: string
}[]
}
export type LinearProjectListResult = {
projects: LinearAgentProjectSummary[]
meta: {
query?: string
workspaceId?: string | 'all'
limit: number
returned: number
hasMore: boolean
partial: boolean
workspaceErrors: {
workspace: LinearWorkspaceCandidate
code: LinearErrorCode
message: string
}[]
}
}
export type LinearStatusSetResult = {
issue: LinearWriteIssueRef
state: { id: string; name: string; type: string }
@@ -264,6 +294,7 @@ export type LinearCreateResult = {
team: { id: string; key: string; name: string }
state: { id: string; name: string } | null
parent: { id: string; identifier: string } | null
project?: LinearNamedEntity | null
assignee?: LinearUserSummary | null
priority?: number | null
estimate?: number | null
+35
View File
@@ -0,0 +1,35 @@
import type { LinearProjectListResult } from './linear-agent-result-types'
// Why: non-JSON project output aligns ids with the existing compact Linear tables.
const LINEAR_PROJECT_NAME_COLUMN_WIDTH = 28
export function formatLinearProjectListRows(result: LinearProjectListResult): string {
if (result.projects.length === 0) {
return 'No Linear projects found.'
}
return result.projects
.map((project) => {
const teams =
project.teams
?.map((team) => {
const key = team.key?.trim()
return key ? key : team.name
})
.filter(Boolean)
.join(',') || 'no-teams'
const workspace = project.workspaceName ? ` ${project.workspaceName}` : ''
return `${project.name.padEnd(LINEAR_PROJECT_NAME_COLUMN_WIDTH)} ${project.id} ${teams}${workspace}`
})
.join('\n')
}
export function linearProjectListWarningLines(result: LinearProjectListResult): string[] {
const warnings: string[] = []
if (result.meta.hasMore) {
warnings.push(`warning: showing first ${result.meta.returned} Linear projects`)
}
for (const error of result.meta.workspaceErrors ?? []) {
warnings.push(`warning: ${error.workspace.name} unavailable for Linear: ${error.message}`)
}
return warnings
}
+5
View File
@@ -0,0 +1,5 @@
export const LINEAR_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
export function isLinearUuid(value: string): boolean {
return LINEAR_UUID_PATTERN.test(value)
}