miyabi-github 1.1.0

GitHub API integration for Miyabi
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
//! GitHub Projects V2 API integration
//!
//! Provides GraphQL-based access to GitHub Projects V2 (Project Boards)
//! for use as Miyabi's data persistence layer.
//!
//! # Features
//!
//! - Query project items (issues/PRs) with custom fields
//! - Update custom field values (Status, Agent, Priority, etc.)
//! - Calculate KPIs from project data
//! - Support for 8 custom fields defined in Phase A

use miyabi_types::error::{MiyabiError, Result};
use serde::{Deserialize, Serialize};

use crate::GitHubClient;

/// GitHub Projects V2 client
impl GitHubClient {
    /// Get all items from a GitHub Project V2
    ///
    /// # Arguments
    /// * `project_number` - Project number (e.g., 1 for /projects/1)
    ///
    /// # Example
    /// ```no_run
    /// use miyabi_github::GitHubClient;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = GitHubClient::new("ghp_xxx", "owner", "repo")?;
    /// let items = client.get_project_items(1).await?;
    /// println!("Found {} items", items.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_project_items(&self, project_number: u32) -> Result<Vec<ProjectItem>> {
        let query = r#"
            query($owner: String!, $number: Int!) {
                user(login: $owner) {
                    projectV2(number: $number) {
                        id
                        items(first: 100) {
                            nodes {
                                id
                                content {
                                    ... on Issue {
                                        number
                                        title
                                        state
                                        labels(first: 10) {
                                            nodes {
                                                name
                                            }
                                        }
                                    }
                                    ... on PullRequest {
                                        number
                                        title
                                        state
                                    }
                                }
                                fieldValues(first: 20) {
                                    nodes {
                                        ... on ProjectV2ItemFieldSingleSelectValue {
                                            name
                                            field {
                                                ... on ProjectV2SingleSelectField {
                                                    name
                                                }
                                            }
                                        }
                                        ... on ProjectV2ItemFieldNumberValue {
                                            number
                                            field {
                                                ... on ProjectV2Field {
                                                    name
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        "#;

        let variables = serde_json::json!({
            "owner": self.owner(),
            "number": project_number as i64,
        });

        let response: ProjectResponse = self
            .client
            .graphql(&serde_json::json!({
                "query": query,
                "variables": variables
            }))
            .await
            .map_err(|e| MiyabiError::GitHub(format!("Failed to query project items: {}", e)))?;

        Ok(response
            .data
            .user
            .project_v2
            .items
            .nodes
            .into_iter()
            .map(ProjectItem::from_node)
            .collect())
    }

    /// Update a custom field value for a project item
    ///
    /// # Arguments
    /// * `project_id` - Project node ID (e.g., "PVT_kwDOAB...")
    /// * `item_id` - Project item node ID
    /// * `field_name` - Custom field name (e.g., "Status", "Agent")
    /// * `value` - New value
    ///
    /// # Example
    /// ```no_run
    /// use miyabi_github::GitHubClient;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = GitHubClient::new("ghp_xxx", "owner", "repo")?;
    /// client.update_project_field(
    ///     "PVT_kwDOAB...",
    ///     "PVTI_lADO...",
    ///     "Status",
    ///     "Done"
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn update_project_field(
        &self,
        project_id: &str,
        item_id: &str,
        field_name: &str,
        value: &str,
    ) -> Result<()> {
        // First, get field ID and option ID
        let field_query = r#"
            query($projectId: ID!, $fieldName: String!) {
                node(id: $projectId) {
                    ... on ProjectV2 {
                        field(name: $fieldName) {
                            ... on ProjectV2SingleSelectField {
                                id
                                options {
                                    id
                                    name
                                }
                            }
                        }
                    }
                }
            }
        "#;

        let field_vars = serde_json::json!({
            "projectId": project_id,
            "fieldName": field_name,
        });

        let field_response: FieldQueryResponse = self
            .client
            .graphql(&serde_json::json!({
                "query": field_query,
                "variables": field_vars
            }))
            .await
            .map_err(|e| {
                MiyabiError::GitHub(format!("Failed to query field {}: {}", field_name, e))
            })?;

        let field = field_response
            .data
            .node
            .field
            .ok_or_else(|| MiyabiError::GitHub(format!("Field '{}' not found", field_name)))?;

        let option = field
            .options
            .iter()
            .find(|opt| opt.name == value)
            .ok_or_else(|| {
                MiyabiError::GitHub(format!(
                    "Option '{}' not found in field '{}'",
                    value, field_name
                ))
            })?;

        // Update the field value
        let update_mutation = r#"
            mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
                updateProjectV2ItemFieldValue(input: {
                    projectId: $projectId
                    itemId: $itemId
                    fieldId: $fieldId
                    value: { singleSelectOptionId: $optionId }
                }) {
                    projectV2Item {
                        id
                    }
                }
            }
        "#;

        let update_vars = serde_json::json!({
            "projectId": project_id,
            "itemId": item_id,
            "fieldId": field.id,
            "optionId": option.id,
        });

        self.client
            .graphql::<serde_json::Value>(&serde_json::json!({
                "query": update_mutation,
                "variables": update_vars
            }))
            .await
            .map_err(|e| {
                MiyabiError::GitHub(format!("Failed to update field {}: {}", field_name, e))
            })?;

        Ok(())
    }

    /// Calculate KPIs from project data
    ///
    /// # Arguments
    /// * `project_number` - Project number
    ///
    /// # Returns
    /// KPIReport with aggregated metrics
    pub async fn calculate_project_kpis(&self, project_number: u32) -> Result<KPIReport> {
        let items = self.get_project_items(project_number).await?;

        let total_tasks = items.len();
        let completed_tasks = items.iter().filter(|i| i.status == "Done").count();
        let completion_rate = if total_tasks > 0 {
            (completed_tasks as f64 / total_tasks as f64) * 100.0
        } else {
            0.0
        };

        let total_hours: f64 = items.iter().filter_map(|i| i.actual_hours).sum();
        let total_cost: f64 = items.iter().filter_map(|i| i.cost_usd).sum();

        let quality_scores: Vec<f64> = items.iter().filter_map(|i| i.quality_score).collect();
        let avg_quality_score = if !quality_scores.is_empty() {
            quality_scores.iter().sum::<f64>() / quality_scores.len() as f64
        } else {
            0.0
        };

        // Group by agent
        let mut by_agent = std::collections::HashMap::new();
        for item in &items {
            if let Some(ref agent) = item.agent {
                *by_agent.entry(agent.clone()).or_insert(0) += 1;
            }
        }

        // Group by phase
        let mut by_phase = std::collections::HashMap::new();
        for item in &items {
            if let Some(ref phase) = item.phase {
                *by_phase.entry(phase.clone()).or_insert(0) += 1;
            }
        }

        Ok(KPIReport {
            total_tasks,
            completed_tasks,
            completion_rate,
            total_hours,
            total_cost,
            avg_quality_score,
            by_agent,
            by_phase,
        })
    }
}

/// Project item (Issue or PR) with custom fields
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectItem {
    pub id: String,
    pub content_type: ContentType,
    pub number: u64,
    pub title: String,
    pub state: String,
    // Custom fields (Phase A)
    pub agent: Option<String>,
    pub status: String,
    pub priority: Option<String>,
    pub phase: Option<String>,
    pub estimated_hours: Option<f64>,
    pub actual_hours: Option<f64>,
    pub quality_score: Option<f64>,
    pub cost_usd: Option<f64>,
}

impl ProjectItem {
    fn from_node(node: ProjectItemNode) -> Self {
        let (content_type, number, title, state) = match node.content {
            Content::Issue(issue) => (ContentType::Issue, issue.number, issue.title, issue.state),
            Content::PullRequest(pr) => (ContentType::PullRequest, pr.number, pr.title, pr.state),
        };

        // Extract custom fields
        let mut agent = None;
        let mut status = String::from("Pending");
        let mut priority = None;
        let mut phase = None;
        let mut estimated_hours = None;
        let mut actual_hours = None;
        let mut quality_score = None;
        let mut cost_usd = None;

        for field_value in node.field_values.nodes {
            match field_value {
                FieldValue::SingleSelect { name, field } => match field.name.as_str() {
                    "Agent" => agent = Some(name),
                    "Status" => status = name,
                    "Priority" => priority = Some(name),
                    "Phase" => phase = Some(name),
                    _ => {}
                },
                FieldValue::Number { number, field } => match field.name.as_str() {
                    "Estimated Hours" => estimated_hours = Some(number),
                    "Actual Hours" => actual_hours = Some(number),
                    "Quality Score" => quality_score = Some(number),
                    "Cost (USD)" => cost_usd = Some(number),
                    _ => {}
                },
            }
        }

        Self {
            id: node.id,
            content_type,
            number,
            title,
            state,
            agent,
            status,
            priority,
            phase,
            estimated_hours,
            actual_hours,
            quality_score,
            cost_usd,
        }
    }
}

/// Content type (Issue or PR)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContentType {
    Issue,
    PullRequest,
}

/// KPI report from project data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KPIReport {
    pub total_tasks: usize,
    pub completed_tasks: usize,
    pub completion_rate: f64,
    pub total_hours: f64,
    pub total_cost: f64,
    pub avg_quality_score: f64,
    pub by_agent: std::collections::HashMap<String, usize>,
    pub by_phase: std::collections::HashMap<String, usize>,
}

// GraphQL response types (internal)

#[derive(Debug, Deserialize)]
struct ProjectResponse {
    data: ProjectData,
}

#[derive(Debug, Deserialize)]
struct ProjectData {
    user: User,
}

#[derive(Debug, Deserialize)]
struct User {
    #[serde(rename = "projectV2")]
    project_v2: ProjectV2,
}

#[derive(Debug, Deserialize)]
struct ProjectV2 {
    #[allow(dead_code)]
    id: String,
    items: Items,
}

#[derive(Debug, Deserialize)]
struct Items {
    nodes: Vec<ProjectItemNode>,
}

#[derive(Debug, Deserialize)]
struct ProjectItemNode {
    id: String,
    content: Content,
    #[serde(rename = "fieldValues")]
    field_values: FieldValues,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Content {
    Issue(IssueContent),
    PullRequest(PRContent),
}

#[derive(Debug, Deserialize)]
struct IssueContent {
    number: u64,
    title: String,
    state: String,
    #[allow(dead_code)]
    labels: Labels,
}

#[derive(Debug, Deserialize)]
struct PRContent {
    number: u64,
    title: String,
    state: String,
}

#[derive(Debug, Deserialize)]
struct Labels {
    #[allow(dead_code)]
    nodes: Vec<LabelNode>,
}

#[derive(Debug, Deserialize)]
struct LabelNode {
    #[allow(dead_code)]
    name: String,
}

#[derive(Debug, Deserialize)]
struct FieldValues {
    nodes: Vec<FieldValue>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum FieldValue {
    SingleSelect { name: String, field: FieldName },
    Number { number: f64, field: FieldName },
}

#[derive(Debug, Deserialize)]
struct FieldName {
    name: String,
}

// Field query response types

#[derive(Debug, Deserialize)]
struct FieldQueryResponse {
    data: FieldQueryData,
}

#[derive(Debug, Deserialize)]
struct FieldQueryData {
    node: FieldQueryNode,
}

#[derive(Debug, Deserialize)]
struct FieldQueryNode {
    field: Option<FieldInfo>,
}

#[derive(Debug, Deserialize)]
struct FieldInfo {
    id: String,
    options: Vec<FieldOption>,
}

#[derive(Debug, Deserialize)]
struct FieldOption {
    id: String,
    name: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_project_item_creation() {
        // Test ProjectItem structure
        let item = ProjectItem {
            id: "PVTI_lADO...".to_string(),
            content_type: ContentType::Issue,
            number: 270,
            title: "Test Issue".to_string(),
            state: "OPEN".to_string(),
            agent: Some("CoordinatorAgent".to_string()),
            status: "In Progress".to_string(),
            priority: Some("P1-High".to_string()),
            phase: Some("Phase 5".to_string()),
            estimated_hours: Some(8.0),
            actual_hours: Some(6.5),
            quality_score: Some(85.0),
            cost_usd: Some(1.25),
        };

        assert_eq!(item.content_type, ContentType::Issue);
        assert_eq!(item.number, 270);
        assert_eq!(item.status, "In Progress");
    }

    #[test]
    fn test_kpi_report_creation() {
        let report = KPIReport {
            total_tasks: 100,
            completed_tasks: 45,
            completion_rate: 45.0,
            total_hours: 450.0,
            total_cost: 12.50,
            avg_quality_score: 87.5,
            by_agent: std::collections::HashMap::new(),
            by_phase: std::collections::HashMap::new(),
        };

        assert_eq!(report.completion_rate, 45.0);
        assert_eq!(report.total_tasks, 100);
    }
}