linear-motion 0.2.0

A CLI tool for syncing between Linear and Motion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# Linear API Documentation

Complete documentation for the Linear GraphQL API and webhooks for the linear-motion sync project.

## Table of Contents

- [Authentication]#authentication
- [GraphQL API]#graphql-api
- [Webhooks]#webhooks
- [Key Data Structures]#key-data-structures
- [Sync Strategy]#sync-strategy
- [Rate Limits]#rate-limits
- [Error Handling]#error-handling

---

## Authentication

### API Key Authentication

Linear uses API key authentication for GraphQL API access:

```http
Authorization: Bearer YOUR_API_KEY
```

### OAuth 2.0

For applications requiring user authorization:

- **Authorization URL**: `https://linear.app/oauth/authorize`
- **Token URL**: `https://api.linear.app/oauth/token`
- **Scopes**: Various scopes available for different resource access

---

## GraphQL API

### Base URL

```
https://api.linear.app/graphql
```

### Key Endpoints

All API interactions use a single GraphQL endpoint with different queries and mutations.

#### Example Query

```graphql
query {
  issues(first: 50) {
    nodes {
      id
      identifier
      title
      description
      state {
        name
        type
      }
      assignee {
        id
        name
        email
      }
      team {
        id
        name
        key
      }
      project {
        id
        name
        state
      }
      labels {
        nodes {
          id
          name
          color
        }
      }
      priority
      estimate
      createdAt
      updatedAt
      dueDate
      completedAt
    }
  }
}
```

---

## Webhooks

### Webhook Configuration

Linear supports webhooks for real-time synchronization:

#### Creating a Webhook

```graphql
mutation {
  webhookCreate(input: {
    url: "https://your-app.com/webhooks/linear"
    resourceTypes: ["Issue", "Project", "Comment", "IssueLabel"]
    enabled: true
    secret: "your-webhook-secret"
    allPublicTeams: true
  }) {
    success
    webhook {
      id
      url
      resourceTypes
      enabled
    }
  }
}
```

#### Supported Resource Types

- `Issue` - Issue creation, updates, state changes
- `Project` - Project creation, updates, status changes
- `Comment` - Comments on issues and projects
- `IssueLabel` - Label creation, updates, assignments
- `User` - User updates (limited)
- `Team` - Team changes
- `Cycle` - Development cycle changes

#### Webhook Payload Structure

```json
{
  "action": "create|update|delete",
  "type": "Issue|Project|Comment|IssueLabel",
  "data": {
    "id": "issue-id",
    "identifier": "ENG-123",
    "title": "Issue Title",
    "description": "Issue description in markdown",
    "state": {
      "id": "state-id",
      "name": "In Progress",
      "type": "started"
    },
    "assignee": {
      "id": "user-id",
      "name": "John Doe",
      "email": "john@company.com"
    },
    "team": {
      "id": "team-id",
      "name": "Engineering",
      "key": "ENG"
    },
    "project": {
      "id": "project-id",
      "name": "Project Name",
      "state": "inProgress"
    },
    "labels": [
      {
        "id": "label-id",
        "name": "bug",
        "color": "#ff6b6b"
      }
    ],
    "priority": 2,
    "estimate": 3,
    "createdAt": "2024-01-01T00:00:00.000Z",
    "updatedAt": "2024-01-01T12:00:00.000Z",
    "dueDate": "2024-01-15T00:00:00.000Z",
    "completedAt": null
  },
  "updatedFrom": {
    // Previous values for update events
  },
  "createdAt": "2024-01-01T12:00:00.000Z"
}
```

#### Webhook Security

Webhooks are signed with HMAC-SHA256:

```rust
// Example verification in Rust
use hmac::{Hmac, Mac};
use sha2::Sha256;

type HmacSha256 = Hmac<Sha256>;

fn verify_webhook(payload: &str, signature: &str, secret: &str) -> bool {
    let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
    mac.update(payload.as_bytes());
    let expected = format!("sha256={}", hex::encode(mac.finalize().into_bytes()));
    signature == expected
}
```

---

## Key Data Structures

### Issue

The primary entity for tasks/tickets:

```graphql
type Issue {
  id: ID!
  identifier: String!  # Human-readable ID like "ENG-123"
  title: String!
  description: String  # Markdown format
  
  # Status and workflow
  state: WorkflowState!
  priority: Int        # 0=No priority, 1=Urgent, 2=High, 3=Medium, 4=Low
  estimate: Float      # Story points or time estimate
  
  # Relationships
  assignee: User
  team: Team!
  project: Project
  cycle: Cycle
  parent: Issue        # For sub-issues
  labels: [IssueLabel!]!
  
  # Attachments and comments
  attachments: [Attachment!]!
  comments: [Comment!]!
  
  # Dates
  createdAt: DateTime!
  updatedAt: DateTime!
  startedAt: DateTime
  completedAt: DateTime
  canceledAt: DateTime
  dueDate: DateTime
  
  # Metadata
  url: String!
  branchName: String
  customerTicketCount: Int
}
```

### Project

Container for organizing issues:

```graphql
type Project {
  id: ID!
  name: String!
  description: String
  slugId: String!
  
  # Visual
  color: String!
  icon: String
  
  # Status
  state: String!      # "planned", "started", "paused", "completed", "canceled"
  health: String      # "onTrack", "atRisk", "offTrack"
  
  # Relationships
  lead: User
  creator: User!
  teams: [Team!]!
  issues: [Issue!]!
  members: [User!]!
  
  # Progress
  progress: Float!    # 0.0 to 1.0
  scope: Int!         # Total story points
  
  # Dates
  createdAt: DateTime!
  updatedAt: DateTime!
  startDate: DateTime
  targetDate: DateTime
  completedAt: DateTime
  canceledAt: DateTime
  
  # Metadata
  url: String!
  sortOrder: Float!
  
  # Content
  updates: [ProjectUpdate!]!
  documents: [Document!]!
  links: [ProjectLink!]!
  milestones: [ProjectMilestone!]!
}
```

### Team

Organizational unit:

```graphql
type Team {
  id: ID!
  name: String!
  key: String!         # Short identifier like "ENG"
  description: String
  
  # Visual
  color: String
  icon: String
  
  # Configuration
  private: Boolean!
  
  # Relationships
  organization: Organization!
  members: [User!]!
  issues: [Issue!]!
  projects: [Project!]!
  cycles: [Cycle!]!
  labels: [IssueLabel!]!
  states: [WorkflowState!]!
  templates: [Template!]!
  
  # Dates
  createdAt: DateTime!
  updatedAt: DateTime!
  
  # Settings
  issueEstimationType: String  # "notUsed", "exponential", "fibonacci", "linear", "tShirt"
  issueOrderingNoPriorityFirst: Boolean!
  issueGenerationEnabled: Boolean!
  cyclesEnabled: Boolean!
  
  # Integrations
  integrationsSettings: IntegrationsSettings
  webhooks: [Webhook!]!
}
```

### User

Team member:

```graphql
type User {
  id: ID!
  name: String!
  displayName: String!
  email: String!
  
  # Profile
  avatarUrl: String
  timezone: String
  
  # Status
  active: Boolean!
  admin: Boolean!
  guest: Boolean!
  
  # Relationships
  organization: Organization!
  teams: [Team!]!
  assignedIssues: [Issue!]!
  createdIssues: [Issue!]!
  
  # Dates
  createdAt: DateTime!
  updatedAt: DateTime!
  lastSeenAt: DateTime
  
  # Settings
  isMe: Boolean!
  url: String!
}
```

### WorkflowState

Issue status:

```graphql
type WorkflowState {
  id: ID!
  name: String!
  description: String
  
  # Visual
  color: String!
  type: String!        # "backlog", "unstarted", "started", "completed", "canceled"
  
  # Configuration
  position: Float!     # Sort order
  
  # Relationships
  team: Team!
  issues: [Issue!]!
  
  # Dates
  createdAt: DateTime!
  updatedAt: DateTime!
}
```

---

## Sync Strategy

### Recommended Approach for linear-motion

1. **Initial Sync**
   - Fetch all projects and their issues
   - Create corresponding Motion workspaces/projects and tasks
   - Store mapping between Linear IDs and Motion IDs

2. **Webhook-Driven Updates**
   - Set up webhooks for real-time sync
   - Handle create, update, delete events
   - Implement conflict resolution

3. **Bidirectional Sync**
   - Linear → Motion: Primary direction via webhooks
   - Motion → Linear: Periodic sync or via Motion webhooks (if available)

### Key Queries for Sync

#### Get All Projects with Issues

```graphql
query GetProjectsWithIssues($first: Int!, $after: String) {
  projects(first: $first, after: $after) {
    nodes {
      id
      name
      description
      state
      color
      targetDate
      startDate
      lead { id name email }
      issues(first: 100) {
        nodes {
          id
          identifier
          title
          description
          state { name type }
          assignee { id name email }
          priority
          estimate
          dueDate
          createdAt
          updatedAt
          completedAt
        }
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

#### Get Team Information

```graphql
query GetTeams {
  teams {
    nodes {
      id
      name
      key
      members {
        id
        name
        email
      }
      states {
        id
        name
        type
        color
      }
    }
  }
}
```

#### Create Issue

```graphql
mutation CreateIssue($input: IssueCreateInput!) {
  issueCreate(input: $input) {
    success
    issue {
      id
      identifier
      title
    }
  }
}
```

#### Update Issue

```graphql
mutation UpdateIssue($id: String!, $input: IssueUpdateInput!) {
  issueUpdate(id: $id, input: $input) {
    success
    issue {
      id
      identifier
      title
      updatedAt
    }
  }
}
```

---

## Rate Limits

Linear implements rate limiting:

- **Default**: 1000 requests per hour per API key
- **Burst**: Up to 100 requests per minute
- **Headers**: Rate limit information in response headers
  - `x-ratelimit-limit`
  - `x-ratelimit-remaining`
  - `x-ratelimit-reset`

### Best Practices

- Use GraphQL field selection to minimize data transfer
- Implement exponential backoff for rate limit errors
- Cache frequently accessed data
- Use webhooks instead of polling

---

## Error Handling

### Common Errors

#### Authentication Errors

```json
{
  "errors": [
    {
      "message": "Authentication required",
      "extensions": {
        "code": "FORBIDDEN"
      }
    }
  ]
}
```

#### Rate Limiting

```json
{
  "errors": [
    {
      "message": "Rate limited",
      "extensions": {
        "code": "RATE_LIMITED"
      }
    }
  ]
}
```

#### Validation Errors

```json
{
  "errors": [
    {
      "message": "Variable '$input' of required type 'IssueCreateInput!' was not provided.",
      "extensions": {
        "code": "BAD_USER_INPUT"
      }
    }
  ]
}
```

### Error Recovery

1. **Retry Logic**: Implement exponential backoff
2. **Partial Failures**: Handle GraphQL partial success scenarios  
3. **Webhook Failures**: Linear retries failed webhooks with exponential backoff
4. **Data Integrity**: Implement checksums or version tracking

---

## Implementation Notes for Rust

### Recommended Crates

```toml
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.0", features = ["full"] }
graphql_client = "0.13"
hmac = "0.12"
sha2 = "0.10"
hex = "0.4"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1.0", features = ["v4", "serde"] }
```

### GraphQL Client Setup

```rust
use graphql_client::GraphQLQuery;

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "src/linear_schema.graphql",
    query_path = "src/queries/get_issues.graphql",
)]
pub struct GetIssues;

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "src/linear_schema.graphql", 
    query_path = "src/mutations/create_issue.graphql",
)]
pub struct CreateIssue;
```

### Webhook Handler Example

```rust
use axum::{extract::State, http::StatusCode, Json};
use serde_json::Value;

async fn linear_webhook_handler(
    State(app_state): State<AppState>,
    headers: HeaderMap,
    Json(payload): Json<Value>,
) -> Result<StatusCode, StatusCode> {
    // Verify webhook signature
    let signature = headers
        .get("linear-signature")
        .and_then(|v| v.to_str().ok())
        .ok_or(StatusCode::BAD_REQUEST)?;
    
    if !verify_webhook_signature(&payload.to_string(), signature, &app_state.webhook_secret) {
        return Err(StatusCode::UNAUTHORIZED);
    }
    
    // Process webhook
    match payload.get("type").and_then(|t| t.as_str()) {
        Some("Issue") => handle_issue_webhook(payload, &app_state).await?,
        Some("Project") => handle_project_webhook(payload, &app_state).await?,
        _ => return Err(StatusCode::BAD_REQUEST),
    }
    
    Ok(StatusCode::OK)
}
```

### Data Mapping

```rust
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

#[derive(Debug, Serialize, Deserialize)]
pub struct LinearIssue {
    pub id: String,
    pub identifier: String,
    pub title: String,
    pub description: Option<String>,
    pub state: WorkflowState,
    pub assignee: Option<User>,
    pub team: Team,
    pub project: Option<Project>,
    pub priority: i32,
    pub estimate: Option<f64>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub due_date: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
}

impl From<LinearIssue> for motion_api::Task {
    fn from(issue: LinearIssue) -> Self {
        motion_api::Task {
            name: issue.title,
            description: issue.description,
            assignee_id: issue.assignee.map(|a| a.id),
            workspace_id: map_team_to_workspace(&issue.team.id),
            project_id: issue.project.map(|p| map_linear_project_to_motion(&p.id)),
            priority: map_linear_priority_to_motion(issue.priority),
            due_date: issue.due_date,
            // ... other mappings
        }
    }
}
```

---

*This documentation covers the essential Linear API features needed for building the linear-motion synchronization tool.*