mycelium-manager 0.2.5

A robust, production-grade task/plan manager CLI (binary: myc)
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
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::error::{MyceliumError, Result};

pub struct LinearClient {
    api_key: String,
    http: reqwest::blocking::Client,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinearTeam {
    pub id: String,
    pub name: String,
    pub key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LinearUser {
    pub id: String,
    pub name: String,
    pub email: String,
    #[serde(default)]
    pub display_name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LinearWorkflowState {
    pub id: String,
    pub name: String,
    #[serde(rename = "type")]
    pub state_type: String, // "triage", "backlog", "unstarted", "started", "completed", "cancelled"
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LinearIssue {
    pub id: String,
    pub identifier: String, // e.g. "TEAM-123"
    pub title: String,
    pub description: Option<String>,
    pub priority: u8,
    pub state: LinearWorkflowState,
    pub assignee: Option<LinearUser>,
    pub due_date: Option<String>, // ISO date string
    pub labels: LinearLabelConnection,
    pub updated_at: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinearLabelConnection {
    pub nodes: Vec<LinearLabel>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinearLabel {
    pub id: String,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinearProject {
    pub id: String,
    pub name: String,
}

impl LinearClient {
    pub fn new(api_key: &str) -> Self {
        Self {
            api_key: api_key.to_string(),
            http: reqwest::blocking::Client::new(),
        }
    }

    fn graphql(&self, query: &str, variables: Option<Value>) -> Result<Value> {
        let mut body = json!({ "query": query });
        if let Some(vars) = variables {
            body["variables"] = vars;
        }

        let resp = self
            .http
            .post("https://api.linear.app/graphql")
            .header("Authorization", &self.api_key)
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .map_err(|e| MyceliumError::Http(e.to_string()))?;

        let status = resp.status();
        let text = resp
            .text()
            .map_err(|e| MyceliumError::Http(e.to_string()))?;

        if !status.is_success() {
            return Err(MyceliumError::LinearApi(format!(
                "HTTP {}: {}",
                status, text
            )));
        }

        let json: Value =
            serde_json::from_str(&text).map_err(|e| MyceliumError::LinearApi(e.to_string()))?;

        if let Some(errors) = json.get("errors") {
            return Err(MyceliumError::LinearApi(format!("{}", errors)));
        }

        json.get("data")
            .cloned()
            .ok_or_else(|| MyceliumError::LinearApi("No data in response".to_string()))
    }

    pub fn fetch_teams(&self) -> Result<Vec<LinearTeam>> {
        let query = r#"
            query {
                teams {
                    nodes {
                        id
                        name
                        key
                    }
                }
            }
        "#;
        let data = self.graphql(query, None)?;
        let nodes = &data["teams"]["nodes"];
        serde_json::from_value(nodes.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }

    pub fn fetch_team_members(&self, team_id: &str) -> Result<Vec<LinearUser>> {
        let query = r#"
            query($teamId: String!) {
                team(id: $teamId) {
                    members {
                        nodes {
                            id
                            name
                            email
                            displayName
                        }
                    }
                }
            }
        "#;
        let data = self.graphql(query, Some(json!({ "teamId": team_id })))?;
        let nodes = &data["team"]["members"]["nodes"];
        serde_json::from_value(nodes.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }

    pub fn fetch_workflow_states(&self, team_id: &str) -> Result<Vec<LinearWorkflowState>> {
        let query = r#"
            query($teamId: String!) {
                team(id: $teamId) {
                    states {
                        nodes {
                            id
                            name
                            type
                        }
                    }
                }
            }
        "#;
        let data = self.graphql(query, Some(json!({ "teamId": team_id })))?;
        let nodes = &data["team"]["states"]["nodes"];
        serde_json::from_value(nodes.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }

    /// Fetch issues with optional label filtering and active-only state filtering.
    /// `filter_labels`: if non-empty, only issues with ALL these labels are returned.
    /// `active_only`: if true, skip issues in completed/cancelled states.
    pub fn fetch_issues_filtered(
        &self,
        team_id: &str,
        filter_labels: &[String],
        active_only: bool,
        cursor: Option<&str>,
    ) -> Result<(Vec<LinearIssue>, Option<String>)> {
        let query = r#"
            query($teamId: String!, $after: String, $filter: IssueFilter) {
                team(id: $teamId) {
                    issues(first: 50, after: $after, filter: $filter) {
                        nodes {
                            id
                            identifier
                            title
                            description
                            priority
                            state {
                                id
                                name
                                type
                            }
                            assignee {
                                id
                                name
                                email
                                displayName
                            }
                            dueDate
                            labels {
                                nodes {
                                    id
                                    name
                                }
                            }
                            updatedAt
                            createdAt
                        }
                        pageInfo {
                            hasNextPage
                            endCursor
                        }
                    }
                }
            }
        "#;

        let mut vars = json!({ "teamId": team_id });
        if let Some(c) = cursor {
            vars["after"] = json!(c);
        }

        // Build filter
        let mut filter = json!({});
        let mut and_conditions: Vec<Value> = Vec::new();

        // Label filter: each label must be present (AND logic)
        if !filter_labels.is_empty() {
            for label_name in filter_labels {
                and_conditions.push(json!({
                    "labels": { "some": { "name": { "eq": label_name } } }
                }));
            }
        }

        // Active-only: exclude completed and cancelled states
        if active_only {
            and_conditions.push(json!({
                "state": {
                    "type": { "nin": ["completed", "cancelled"] }
                }
            }));
        }

        if !and_conditions.is_empty() {
            filter["and"] = json!(and_conditions);
            vars["filter"] = filter;
        }

        let data = self.graphql(query, Some(vars))?;
        let issues_data = &data["team"]["issues"];
        let nodes: Vec<LinearIssue> = serde_json::from_value(issues_data["nodes"].clone())
            .map_err(|e| MyceliumError::LinearApi(e.to_string()))?;

        let next_cursor = if issues_data["pageInfo"]["hasNextPage"]
            .as_bool()
            .unwrap_or(false)
        {
            issues_data["pageInfo"]["endCursor"]
                .as_str()
                .map(|s| s.to_string())
        } else {
            None
        };

        Ok((nodes, next_cursor))
    }

    pub fn fetch_all_issues_filtered(
        &self,
        team_id: &str,
        filter_labels: &[String],
        active_only: bool,
    ) -> Result<Vec<LinearIssue>> {
        let mut all = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let (issues, next) =
                self.fetch_issues_filtered(team_id, filter_labels, active_only, cursor.as_deref())?;
            all.extend(issues);
            if next.is_none() {
                break;
            }
            cursor = next;
        }
        Ok(all)
    }

    pub fn create_issue(
        &self,
        team_id: &str,
        title: &str,
        description: Option<&str>,
        priority: u8,
        state_id: &str,
        assignee_id: Option<&str>,
        due_date: Option<&str>,
        label_ids: &[String],
    ) -> Result<LinearIssue> {
        let query = r#"
            mutation($input: IssueCreateInput!) {
                issueCreate(input: $input) {
                    success
                    issue {
                        id
                        identifier
                        title
                        description
                        priority
                        state {
                            id
                            name
                            type
                        }
                        assignee {
                            id
                            name
                            email
                            displayName
                        }
                        dueDate
                        labels {
                            nodes {
                                id
                                name
                            }
                        }
                        updatedAt
                        createdAt
                    }
                }
            }
        "#;
        let mut input = json!({
            "teamId": team_id,
            "title": title,
            "priority": priority,
            "stateId": state_id,
        });
        if let Some(desc) = description {
            input["description"] = json!(desc);
        }
        if let Some(aid) = assignee_id {
            input["assigneeId"] = json!(aid);
        }
        if let Some(due) = due_date {
            input["dueDate"] = json!(due);
        }
        if !label_ids.is_empty() {
            input["labelIds"] = json!(label_ids);
        }

        let data = self.graphql(query, Some(json!({ "input": input })))?;
        let issue = &data["issueCreate"]["issue"];
        serde_json::from_value(issue.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }

    pub fn update_issue(
        &self,
        issue_id: &str,
        title: Option<&str>,
        description: Option<&str>,
        priority: Option<u8>,
        state_id: Option<&str>,
        assignee_id: Option<&str>,
        due_date: Option<&str>,
        label_ids: Option<&[String]>,
    ) -> Result<LinearIssue> {
        let query = r#"
            mutation($issueId: String!, $input: IssueUpdateInput!) {
                issueUpdate(id: $issueId, input: $input) {
                    success
                    issue {
                        id
                        identifier
                        title
                        description
                        priority
                        state {
                            id
                            name
                            type
                        }
                        assignee {
                            id
                            name
                            email
                            displayName
                        }
                        dueDate
                        labels {
                            nodes {
                                id
                                name
                            }
                        }
                        updatedAt
                        createdAt
                    }
                }
            }
        "#;
        let mut input = json!({});
        if let Some(t) = title {
            input["title"] = json!(t);
        }
        if let Some(d) = description {
            input["description"] = json!(d);
        }
        if let Some(p) = priority {
            input["priority"] = json!(p);
        }
        if let Some(s) = state_id {
            input["stateId"] = json!(s);
        }
        if let Some(a) = assignee_id {
            input["assigneeId"] = json!(a);
        }
        if let Some(d) = due_date {
            input["dueDate"] = json!(d);
        }
        if let Some(l) = label_ids {
            input["labelIds"] = json!(l);
        }

        let data = self.graphql(query, Some(json!({ "issueId": issue_id, "input": input })))?;
        let issue = &data["issueUpdate"]["issue"];
        serde_json::from_value(issue.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }

    pub fn fetch_labels(&self, team_id: &str) -> Result<Vec<LinearLabel>> {
        let query = r#"
            query($teamId: String!) {
                team(id: $teamId) {
                    labels {
                        nodes {
                            id
                            name
                        }
                    }
                }
            }
        "#;
        let data = self.graphql(query, Some(json!({ "teamId": team_id })))?;
        let nodes = &data["team"]["labels"]["nodes"];
        serde_json::from_value(nodes.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }

    pub fn create_label(&self, team_id: &str, name: &str) -> Result<LinearLabel> {
        let query = r#"
            mutation($input: IssueLabelCreateInput!) {
                issueLabelCreate(input: $input) {
                    success
                    issueLabel {
                        id
                        name
                    }
                }
            }
        "#;
        let data = self.graphql(
            query,
            Some(json!({ "input": { "teamId": team_id, "name": name } })),
        )?;
        let label = &data["issueLabelCreate"]["issueLabel"];
        serde_json::from_value(label.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }

    pub fn fetch_projects(&self) -> Result<Vec<LinearProject>> {
        let query = r#"
            query {
                projects(first: 100) {
                    nodes {
                        id
                        name
                    }
                }
            }
        "#;
        let data = self.graphql(query, None)?;
        let nodes = &data["projects"]["nodes"];
        serde_json::from_value(nodes.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }

    pub fn create_project(&self, team_id: &str, name: &str) -> Result<LinearProject> {
        let query = r#"
            mutation($input: ProjectCreateInput!) {
                projectCreate(input: $input) {
                    success
                    project {
                        id
                        name
                    }
                }
            }
        "#;
        let data = self.graphql(
            query,
            Some(json!({
                "input": {
                    "name": name,
                    "teamIds": [team_id]
                }
            })),
        )?;
        let project = &data["projectCreate"]["project"];
        serde_json::from_value(project.clone()).map_err(|e| MyceliumError::LinearApi(e.to_string()))
    }
}