Skip to main content

orch/github/
projects.rs

1//! GitHub Projects V2 integration — keeps project board columns in sync with task status.
2//!
3//! Uses GitHub's Projects V2 GraphQL API via the native `GhHttp` reqwest client.
4//! All operations are best-effort: failures are logged but never block task execution.
5
6pub(crate) mod label_status;
7
8use crate::backends::Status;
9use crate::config;
10use crate::github::http::GhHttp;
11use crate::home;
12use std::collections::HashMap;
13use std::collections::HashSet;
14
15use tokio::fs;
16
17/// Project board info returned by list queries.
18#[derive(Debug, Clone)]
19pub struct ProjectInfo {
20    pub id: String,
21    pub number: u64,
22    pub title: String,
23}
24
25/// Keeps a GitHub Projects V2 board in sync with orch task statuses.
26///
27/// Config keys (in `~/.orch/config.yml`):
28/// ```yaml
29/// gh:
30///   project_id: "PVT_kwHO..."
31///   project_status_field_id: "PVTSSF_..."
32///   project_status_map:
33///     backlog: "option-id-1"
34///     in_progress: "option-id-2"
35///     review: "option-id-3"
36///     done: "option-id-4"
37/// ```
38#[derive(Debug)]
39pub struct ProjectSync {
40    project_id: String,
41    status_field_id: String,
42    status_map: HashMap<String, String>,
43    /// GitHub Projects V2 "Estimate" number field ID (optional — not all projects have one).
44    estimate_field_id: Option<String>,
45    gh: GhHttp,
46}
47
48impl ProjectSync {
49    /// One `  column: option id` line per status column, for display
50    pub fn column_lines(&self) -> Vec<String> {
51        self.status_map
52            .iter()
53            .map(|(col, opt_id)| format!("  {col}: {opt_id}"))
54            .collect()
55    }
56
57    /// Load from config. Returns `None` if project integration is not configured.
58    pub fn from_config() -> Option<Self> {
59        let project_id = config::get("gh.project_id").ok()?;
60        if project_id.is_empty() {
61            return None;
62        }
63        let status_field_id = config::get("gh.project_status_field_id").ok()?;
64
65        let mut status_map = HashMap::new();
66        for key in &["backlog", "in_progress", "review", "done"] {
67            if let Ok(val) = config::get(&format!("gh.project_status_map.{key}")) {
68                status_map.insert(key.to_string(), val);
69            }
70        }
71
72        // Estimate field ID is optional — not all projects have an Estimate field.
73        let estimate_field_id = config::get("gh.project_estimate_field_id")
74            .ok()
75            .filter(|v| !v.is_empty());
76
77        let gh = match GhHttp::owner() {
78            Ok(gh) => gh,
79            Err(e) => {
80                tracing::warn!(error = %e, "project sync disabled: failed to build HTTP client");
81                return None;
82            }
83        };
84
85        Some(Self {
86            project_id,
87            status_field_id,
88            status_map,
89            estimate_field_id,
90            gh,
91        })
92    }
93
94    /// Discover the Status field ID and option IDs from a project.
95    ///
96    /// Queries the project's fields via GraphQL and finds the single-select
97    /// "Status" field, returning a `ProjectSync` populated with field/option IDs.
98    /// Also discovers the "Estimate" number field if present.
99    pub async fn discover_fields(project_id: &str) -> anyhow::Result<Self> {
100        let gh = GhHttp::owner()?;
101        // Fetch all field types so we can find both Status (single-select) and Estimate (number).
102        let query = r"query($projectId: ID!) { node(id: $projectId) { ... on ProjectV2 { fields(first: 100) { nodes { ... on ProjectV2SingleSelectField { id name options { id name } } ... on ProjectV2Field { id name } ... on ProjectV2FieldNumber { id name } } } } } }";
103
104        let result = gh
105            .graphql_with_vars(query, serde_json::json!({ "projectId": project_id }))
106            .await?;
107
108        let fields = result
109            .pointer("/data/node/fields/nodes")
110            .and_then(|n| n.as_array())
111            .ok_or_else(|| anyhow::anyhow!("failed to parse project fields response"))?;
112
113        // Find the "Status" field (case-insensitive single-select).
114        let status_field = fields
115            .iter()
116            .find(|f| {
117                f.get("name")
118                    .and_then(|n| n.as_str())
119                    .is_some_and(|n| n.eq_ignore_ascii_case("status"))
120            })
121            .ok_or_else(|| anyhow::anyhow!("no 'Status' field found in project"))?;
122
123        let field_id = status_field
124            .get("id")
125            .and_then(|v| v.as_str())
126            .ok_or_else(|| anyhow::anyhow!("Status field missing id"))?
127            .to_string();
128
129        let options = status_field
130            .get("options")
131            .and_then(|o| o.as_array())
132            .ok_or_else(|| anyhow::anyhow!("Status field missing options"))?;
133
134        // Map option names to their IDs, normalizing to our column keys.
135        let mut status_map = HashMap::new();
136        for opt in options {
137            let opt_id = opt.get("id").and_then(|v| v.as_str()).unwrap_or("");
138            let opt_name = opt.get("name").and_then(|v| v.as_str()).unwrap_or("");
139            let lower = opt_name.to_lowercase();
140
141            let key = if lower.contains("backlog") || lower.contains("todo") || lower == "new" {
142                "backlog"
143            } else if lower.contains("progress") || lower.contains("doing") {
144                "in_progress"
145            } else if lower.contains("review") {
146                "review"
147            } else if lower.contains("done") || lower.contains("complete") {
148                "done"
149            } else {
150                continue;
151            };
152
153            status_map.insert(key.to_string(), opt_id.to_string());
154        }
155
156        // Find the "Estimate" number field (case-insensitive).
157        let estimate_field_id = fields
158            .iter()
159            .find(|f| {
160                f.get("name")
161                    .and_then(|n| n.as_str())
162                    .is_some_and(|n| n.eq_ignore_ascii_case("estimate"))
163            })
164            .and_then(|f| f.get("id").and_then(|v| v.as_str()))
165            .filter(|id| !id.is_empty())
166            .map(String::from);
167
168        Ok(Self {
169            project_id: project_id.to_string(),
170            status_field_id: field_id,
171            status_map,
172            estimate_field_id,
173            gh,
174        })
175    }
176
177    /// List all accessible projects for the authenticated user and their orgs.
178    pub async fn list_projects() -> anyhow::Result<Vec<ProjectInfo>> {
179        let gh = GhHttp::owner()?;
180        let mut projects = Vec::new();
181
182        // Get current user login
183        let user = gh.get_whoami().await?;
184
185        // User projects
186        let query = r"query($login: String!) { user(login: $login) { projectsV2(first: 100) { nodes { id number title } } } }";
187        if let Ok(result) = gh
188            .graphql_with_vars(query, serde_json::json!({ "login": user }))
189            .await
190            && let Some(nodes) = result
191                .pointer("/data/user/projectsV2/nodes")
192                .and_then(|n| n.as_array())
193        {
194            for node in nodes {
195                if let Some(info) = parse_project_node(node) {
196                    projects.push(info);
197                }
198            }
199        }
200
201        // Try org projects for the repo owner (if different from user)
202        if let Ok(repo) = config::get_current_repo()
203            && let Some(owner) = repo.split('/').next()
204            && owner != user
205        {
206            let query = r"query($login: String!) { organization(login: $login) { projectsV2(first: 100) { nodes { id number title } } } }";
207            if let Ok(result) = gh
208                .graphql_with_vars(query, serde_json::json!({ "login": owner }))
209                .await
210                && let Some(nodes) = result
211                    .pointer("/data/organization/projectsV2/nodes")
212                    .and_then(|n| n.as_array())
213            {
214                for node in nodes {
215                    if let Some(info) = parse_project_node(node) {
216                        projects.push(info);
217                    }
218                }
219            }
220        }
221
222        Ok(projects)
223    }
224
225    /// Add an issue to the project board. Returns the project item ID.
226    pub async fn add_item(&self, issue_node_id: &str) -> anyhow::Result<String> {
227        let query = r"mutation($projectId: ID!, $contentId: ID!) { addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) { item { id } } }";
228
229        let result = self
230            .gh
231            .graphql_with_vars(
232                query,
233                serde_json::json!({
234                    "projectId": self.project_id,
235                    "contentId": issue_node_id,
236                }),
237            )
238            .await?;
239        result
240            .pointer("/data/addProjectV2ItemById/item/id")
241            .and_then(|v| v.as_str())
242            .map(String::from)
243            .ok_or_else(|| anyhow::anyhow!("failed to add item to project"))
244    }
245
246    /// Update an item's status column on the project board.
247    pub async fn update_item_status(&self, item_id: &str, status: &Status) -> anyhow::Result<()> {
248        let column = Self::status_to_column(status);
249        let option_id = self
250            .status_map
251            .get(column)
252            .ok_or_else(|| anyhow::anyhow!("no option ID for column: {column}"))?;
253
254        let query = r"mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { updateProjectV2ItemFieldValue(input: { projectId: $projectId, itemId: $itemId, fieldId: $fieldId, value: { singleSelectOptionId: $optionId } }) { projectV2Item { id } } }";
255
256        self.gh
257            .graphql_with_vars(
258                query,
259                serde_json::json!({
260                    "projectId": self.project_id,
261                    "itemId": item_id,
262                    "fieldId": self.status_field_id,
263                    "optionId": option_id,
264                }),
265            )
266            .await?;
267        Ok(())
268    }
269
270    /// Sync an issue's project board status: add to project if needed, then update column.
271    ///
272    /// This is the main entry point called from `update_status()`.
273    pub async fn sync_item_status(
274        &self,
275        issue_node_id: &str,
276        status: &Status,
277    ) -> anyhow::Result<()> {
278        // Add item to project (idempotent — returns existing item if already added)
279        let item_id = self.add_item(issue_node_id).await?;
280
281        // Update the status column
282        self.update_item_status(&item_id, status).await
283    }
284
285    /// Map orch `Status` to a project board column key.
286    pub fn status_to_column(status: &Status) -> &'static str {
287        match status {
288            Status::New | Status::Routed | Status::Waiting => "backlog",
289            Status::InProgress | Status::Blocked => "in_progress",
290            Status::InReview | Status::NeedsReview | Status::Approved => "review",
291            Status::Done => "done",
292        }
293    }
294
295    /// Get the status field ID.
296    pub fn status_field_id(&self) -> &str {
297        &self.status_field_id
298    }
299
300    /// Get the status map (column key → option ID).
301    pub fn status_map(&self) -> &HashMap<String, String> {
302        &self.status_map
303    }
304
305    /// Get the estimate field ID, if configured.
306    pub fn estimate_field_id(&self) -> Option<&str> {
307        self.estimate_field_id.as_deref()
308    }
309
310    /// Get the project ID.
311    pub fn project_id(&self) -> &str {
312        &self.project_id
313    }
314
315    /// Update an item's Estimate number field on the project board.
316    ///
317    /// Returns the project item ID (either found or newly added).
318    pub async fn sync_item_estimate(
319        &self,
320        issue_node_id: &str,
321        estimate: u8,
322    ) -> anyhow::Result<String> {
323        let Some(field_id) = &self.estimate_field_id else {
324            return Err(anyhow::anyhow!("estimate field not configured"));
325        };
326
327        // Add item to project (idempotent — returns existing item if already added).
328        let item_id = self.add_item(issue_node_id).await?;
329
330        // Update the estimate number field.
331        let query = r"mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $value: Float!) { updateProjectV2ItemFieldValue(input: { projectId: $projectId, itemId: $itemId, fieldId: $fieldId, value: { number: $value } }) { projectV2Item { id } } }";
332
333        self.gh
334            .graphql_with_vars(
335                query,
336                serde_json::json!({
337                    "projectId": self.project_id,
338                    "itemId": item_id,
339                    "fieldId": field_id,
340                    "value": f64::from(estimate),
341                }),
342            )
343            .await?;
344
345        Ok(item_id)
346    }
347
348    /// Batch-fetch estimate values for multiple project items by their content (issue) node IDs.
349    ///
350    /// Returns a map from content node ID → estimate value (0 if not set or field absent).
351    /// Only queries the estimate field — the result is used to populate orch's estimate
352    /// during task ingestion when `tasks.estimate` is still 0.
353    ///
354    /// GitHub's GraphQL API doesn't support querying items by arbitrary node IDs directly,
355    /// so we fetch all project items and their field values, then match by content ID.
356    /// This is acceptable for projects with reasonable item counts (< 1000).
357    pub async fn get_estimates_for_issues(
358        &self,
359        issue_node_ids: &[String],
360    ) -> anyhow::Result<HashMap<String, u8>> {
361        const FIBONACCI: &[u8] = &[0, 1, 2, 3, 5, 8, 13, 21];
362
363        let Some(field_id) = &self.estimate_field_id else {
364            return Ok(HashMap::new());
365        };
366
367        let issue_set: HashSet<&str> = issue_node_ids.iter().map(String::as_str).collect();
368
369        // Fetch all items in the project with their fieldValues filtered to the estimate field.
370        let query = r"query($projectId: ID!) { node(id: $projectId) { ... on ProjectV2 { items(first: 100) { nodes { id content { ... on Issue { id } ... on PullRequest { id } } fieldValues(first: 10) { nodes { ... on ProjectV2ItemFieldNumberValue { field { id } number } } } } } } } }";
371
372        let result = self
373            .gh
374            .graphql_with_vars(query, serde_json::json!({ "projectId": self.project_id }))
375            .await?;
376
377        let items = result
378            .pointer("/data/node/items/nodes")
379            .and_then(|n| n.as_array())
380            .ok_or_else(|| anyhow::anyhow!("failed to parse project items"))?;
381
382        let mut estimates = HashMap::new();
383
384        for item in items {
385            // Extract the content node ID (issue or PR).
386            let Some(content) = item.get("content") else {
387                continue;
388            };
389            let Some(content_id) = content.get("id").and_then(|v| v.as_str()) else {
390                continue;
391            };
392
393            // Skip if this content ID is not in our target set.
394            if !issue_set.contains(content_id) {
395                continue;
396            }
397
398            // Find the estimate field value.
399            let Some(field_values) = item
400                .get("fieldValues")
401                .and_then(|fv| fv.get("nodes"))
402                .and_then(|n| n.as_array())
403            else {
404                continue;
405            };
406            #[expect(
407                clippy::cast_possible_truncation,
408                clippy::cast_sign_loss,
409                reason = "the saturating cast is fine, only fibonacci values up to 21 are kept"
410            )]
411            let estimate = field_values
412                .iter()
413                .find(|fv| {
414                    fv.get("field")
415                        .and_then(|f| f.get("id"))
416                        .and_then(|id| id.as_str())
417                        .is_some_and(|id| id == field_id)
418                })
419                .and_then(|fv| fv.get("number"))
420                .and_then(serde_json::Value::as_f64)
421                .unwrap_or(0.0) as u8;
422
423            // Only accept Fibonacci values (0 = not set, or 1/2/3/5/8/13/21).
424            if FIBONACCI.contains(&estimate) {
425                estimates.insert(content_id.to_string(), estimate);
426            }
427        }
428
429        Ok(estimates)
430    }
431}
432
433/// Parse a project node from GraphQL response.
434fn parse_project_node(node: &serde_json::Value) -> Option<ProjectInfo> {
435    Some(ProjectInfo {
436        id: node.get("id")?.as_str()?.to_string(),
437        number: node.get("number")?.as_u64()?,
438        title: node.get("title")?.as_str()?.to_string(),
439    })
440}
441
442impl ProjectSync {
443    /// Write project config fields to `~/.orch/config.yml`.
444    pub async fn write_config(&self) -> anyhow::Result<()> {
445        let config_path = home::config_path()?;
446        let content = if config_path.exists() {
447            fs::read_to_string(&config_path).await?
448        } else {
449            String::new()
450        };
451
452        // Parse existing YAML or start fresh
453        let mut doc: serde_norway::Value = if content.is_empty() {
454            serde_norway::Value::Mapping(serde_norway::Mapping::new())
455        } else {
456            serde_norway::from_str(&content)?
457        };
458
459        let root = doc
460            .as_mapping_mut()
461            .ok_or_else(|| anyhow::anyhow!("config is not a YAML mapping"))?;
462
463        // Ensure gh section exists
464        let gh_key = serde_norway::Value::String("gh".to_string());
465        if !root.contains_key(&gh_key) {
466            root.insert(
467                gh_key.clone(),
468                serde_norway::Value::Mapping(serde_norway::Mapping::new()),
469            );
470        }
471        let gh = root
472            .get_mut(&gh_key)
473            .and_then(|v| v.as_mapping_mut())
474            .ok_or_else(|| anyhow::anyhow!("gh config is not a mapping"))?;
475
476        // Set project fields
477        gh.insert(
478            serde_norway::Value::String("project_id".to_string()),
479            serde_norway::Value::String(self.project_id.clone()),
480        );
481        gh.insert(
482            serde_norway::Value::String("project_status_field_id".to_string()),
483            serde_norway::Value::String(self.status_field_id.clone()),
484        );
485
486        // Build status map
487        let mut map = serde_norway::Mapping::new();
488        for (key, val) in &self.status_map {
489            map.insert(
490                serde_norway::Value::String(key.clone()),
491                serde_norway::Value::String(val.clone()),
492            );
493        }
494        gh.insert(
495            serde_norway::Value::String("project_status_map".to_string()),
496            serde_norway::Value::Mapping(map),
497        );
498
499        // Persist the estimate field ID (optional — not all projects have one).
500        if let Some(ref field_id) = self.estimate_field_id {
501            gh.insert(
502                serde_norway::Value::String("project_estimate_field_id".to_string()),
503                serde_norway::Value::String(field_id.clone()),
504            );
505        }
506
507        fs::write(&config_path, serde_norway::to_string(&doc)?).await?;
508        Ok(())
509    }
510}
511
512#[cfg(test)]
513mod tests {
514    use std::env;
515    use std::fs as std_fs;
516    use std::panic;
517    use std::panic::AssertUnwindSafe;
518
519    use super::*;
520    use crate::backends::Status;
521
522    #[test]
523    fn status_to_column_mapping() {
524        assert_eq!(ProjectSync::status_to_column(&Status::New), "backlog");
525        assert_eq!(ProjectSync::status_to_column(&Status::Routed), "backlog");
526        assert_eq!(
527            ProjectSync::status_to_column(&Status::InProgress),
528            "in_progress"
529        );
530        assert_eq!(
531            ProjectSync::status_to_column(&Status::Blocked),
532            "in_progress"
533        );
534        assert_eq!(ProjectSync::status_to_column(&Status::InReview), "review");
535        assert_eq!(ProjectSync::status_to_column(&Status::Approved), "review");
536        assert_eq!(
537            ProjectSync::status_to_column(&Status::NeedsReview),
538            "review"
539        );
540        assert_eq!(ProjectSync::status_to_column(&Status::Done), "done");
541    }
542
543    #[test]
544    fn parse_project_node_valid() {
545        let node = serde_json::json!({
546            "id": "PVT_kwHOA123",
547            "number": 42,
548            "title": "My Project"
549        });
550        let info = parse_project_node(&node).unwrap();
551        assert_eq!(info.id, "PVT_kwHOA123");
552        assert_eq!(info.number, 42);
553        assert_eq!(info.title, "My Project");
554    }
555
556    #[test]
557    fn parse_project_node_missing_field() {
558        let node = serde_json::json!({ "id": "PVT_kwHOA123" });
559        assert!(parse_project_node(&node).is_none());
560    }
561
562    #[test]
563    fn from_config_returns_none_when_not_configured() {
564        // Isolate from both the repo's .orch.yml and the global ~/.orch/config.yml:
565        // 1. Change to a temp dir so project config lookup finds no .orch.yml
566        // 2. Point ORCH_HOME at a separate temp dir so the global config is not found
567        // 3. Clear the config cache so no previously-cached values are reused
568        let original_cwd = env::current_dir().unwrap();
569        let prev_orch_home = env::var("ORCH_HOME").ok();
570
571        let temp_cwd = tempfile::tempdir().unwrap();
572        let temp_orch_home = tempfile::tempdir().unwrap();
573        let orch_dir = temp_orch_home.path().join(".orch");
574        std_fs::create_dir_all(&orch_dir).unwrap();
575
576        env::set_current_dir(temp_cwd.path()).unwrap();
577        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
578        unsafe { env::set_var("ORCH_HOME", &orch_dir) };
579        config::clear_test_cache();
580
581        let result = panic::catch_unwind(AssertUnwindSafe(|| {
582            assert!(ProjectSync::from_config().is_none());
583        }));
584
585        env::set_current_dir(&original_cwd).unwrap();
586        if let Some(prev) = prev_orch_home {
587            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
588            unsafe { env::set_var("ORCH_HOME", prev) };
589        } else {
590            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
591            unsafe { env::remove_var("ORCH_HOME") };
592        }
593        result.unwrap();
594    }
595
596    #[test]
597    fn get_estimates_filters_non_fibonacci_values() {
598        // The get_estimates_for_issues function should only accept Fibonacci values.
599        // Non-Fibonacci values should be silently dropped.
600        // We test this by verifying the parsing logic directly.
601        const FIBONACCI: &[u8] = &[0, 1, 2, 3, 5, 8, 13, 21];
602
603        // Fibonacci values should be accepted
604        for &v in FIBONACCI {
605            assert!(
606                FIBONACCI.contains(&v),
607                "Fibonacci value {v} should be accepted"
608            );
609        }
610
611        // Non-Fibonacci values should NOT be in the list
612        let non_fib = [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22];
613        for &v in &non_fib {
614            assert!(
615                !FIBONACCI.contains(&v),
616                "Non-Fibonacci value {v} should NOT be accepted"
617            );
618        }
619    }
620
621    #[test]
622    fn estimate_field_id_is_optional() {
623        // ProjectSync should be constructable with no estimate field.
624        // estimate_field_id() should return None when not configured.
625        let original_cwd = env::current_dir().unwrap();
626        let prev_orch_home = env::var("ORCH_HOME").ok();
627
628        let temp_cwd = tempfile::tempdir().unwrap();
629        let temp_orch_home = tempfile::tempdir().unwrap();
630        let orch_dir = temp_orch_home.path().join(".orch");
631        std_fs::create_dir_all(&orch_dir).unwrap();
632
633        env::set_current_dir(temp_cwd.path()).unwrap();
634        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
635        unsafe { env::set_var("ORCH_HOME", &orch_dir) };
636        config::clear_test_cache();
637
638        // Write a config with project ID and status field but NO estimate field.
639        let config_path = orch_dir.join("config.yml");
640        std_fs::write(
641            &config_path,
642            r#"
643gh:
644  project_id: "PVT_kwHOAB123"
645  project_status_field_id: "PVTSSF_123"
646  project_status_map:
647    backlog: "opt1"
648"#,
649        )
650        .unwrap();
651
652        let result = panic::catch_unwind(AssertUnwindSafe(|| {
653            let sync = ProjectSync::from_config();
654            assert!(
655                sync.is_some(),
656                "should be Some when project_id is configured"
657            );
658            assert_eq!(
659                sync.unwrap().estimate_field_id(),
660                None,
661                "estimate_field_id should be None when not configured"
662            );
663        }));
664
665        env::set_current_dir(&original_cwd).unwrap();
666        if let Some(prev) = prev_orch_home {
667            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
668            unsafe { env::set_var("ORCH_HOME", prev) };
669        } else {
670            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
671            unsafe { env::remove_var("ORCH_HOME") };
672        }
673        result.unwrap();
674    }
675}