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