git-parsec 0.3.0

Git worktree lifecycle manager — ticket to PR in one command. Parallel AI agent workflows with Jira & GitHub Issues integration.
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
use super::Ticket;
use anyhow::{bail, Context, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SprintInfo {
    pub id: u64,
    pub name: String,
    pub start_date: Option<String>,
    pub end_date: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoardTicket {
    pub key: String,
    pub summary: String,
    pub status: String,
    pub assignee: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InboxTicket {
    pub key: String,
    pub summary: String,
    pub status: String,
    pub priority: String,
    pub url: String,
}

pub struct JiraTracker {
    base_url: String,
    email: Option<String>,
    client: Client,
}

impl JiraTracker {
    pub fn new(base_url: &str, email: Option<&str>) -> Self {
        Self {
            base_url: base_url.trim_end_matches('/').to_string(),
            email: email.map(String::from),
            client: Client::new(),
        }
    }

    /// Resolve the Jira API token from environment.
    /// Priority: PARSEC_JIRA_TOKEN > JIRA_PAT
    fn resolve_token() -> Result<String> {
        crate::env::jira_token().ok_or_else(|| {
            anyhow::anyhow!(
                "No Jira token found. Set {} or {} environment variable.",
                crate::env::PARSEC_JIRA_TOKEN,
                crate::env::JIRA_PAT,
            )
        })
    }

    /// Fetch a single issue via Jira REST API v2.
    /// Requires: Jira (Cloud or Server/DC 7.x+)
    /// Endpoint: GET /rest/api/2/issue/{id}
    pub async fn fetch_ticket(&self, id: &str) -> Result<Ticket> {
        let token = Self::resolve_token()?;

        let url = format!("{}/rest/api/2/issue/{}", self.base_url, id);

        let mut request = self
            .client
            .get(&url)
            .header("Content-Type", "application/json");

        // If email is configured: Basic auth (Jira Cloud with API token)
        // Otherwise: Bearer token (Jira Server/DC with PAT)
        if let Some(ref email) = self.email {
            request = request.basic_auth(email, Some(&token));
        } else {
            request = request.bearer_auth(&token);
        }

        let response = request
            .send()
            .await
            .context("Failed to send request to Jira")?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            bail!("Jira API returned {} for {}: {}", status, id, body);
        }

        let body: serde_json::Value = response
            .json()
            .await
            .context("Failed to parse Jira response")?;

        let title = body["fields"]["summary"]
            .as_str()
            .unwrap_or("Untitled")
            .to_string();

        let status = body["fields"]["status"]["name"].as_str().map(String::from);

        let assignee = body["fields"]["assignee"]["displayName"]
            .as_str()
            .map(String::from);

        Ok(Ticket {
            id: id.to_string(),
            title,
            status,
            assignee,
            url: Some(format!("{}/browse/{}", self.base_url, id)),
        })
    }

    /// Fetch the first board ID for a project via Jira Agile REST API v1.0.
    /// Requires: Jira Software (Cloud or Server/DC 7.x+)
    /// Endpoint: GET /rest/agile/1.0/board?projectKeyOrId={project}
    pub async fn fetch_board_id(&self, project: &str) -> Result<u64> {
        let token = Self::resolve_token()?;
        let url = format!(
            "{}/rest/agile/1.0/board?projectKeyOrId={}",
            self.base_url, project
        );

        let mut request = self
            .client
            .get(&url)
            .header("Content-Type", "application/json");

        if let Some(ref email) = self.email {
            request = request.basic_auth(email, Some(&token));
        } else {
            request = request.bearer_auth(&token);
        }

        let response = request
            .send()
            .await
            .context("Failed to fetch boards from Jira")?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            bail!("Jira Agile API returned {} for boards: {}", status, body);
        }

        let body: serde_json::Value = response
            .json()
            .await
            .context("Failed to parse board response")?;

        body["values"]
            .as_array()
            .and_then(|boards| boards.first())
            .and_then(|b| b["id"].as_u64())
            .ok_or_else(|| anyhow::anyhow!("No board found for project {project}"))
    }

    /// Fetch the active sprint for a board via Jira Agile REST API v1.0.
    /// Requires: Jira Software (Cloud or Server/DC 7.x+)
    /// Endpoint: GET /rest/agile/1.0/board/{id}/sprint?state=active
    pub async fn fetch_active_sprint(&self, board_id: u64) -> Result<SprintInfo> {
        let token = Self::resolve_token()?;
        let url = format!(
            "{}/rest/agile/1.0/board/{}/sprint?state=active",
            self.base_url, board_id
        );

        let mut request = self
            .client
            .get(&url)
            .header("Content-Type", "application/json");

        if let Some(ref email) = self.email {
            request = request.basic_auth(email, Some(&token));
        } else {
            request = request.bearer_auth(&token);
        }

        let response = request
            .send()
            .await
            .context("Failed to fetch sprints from Jira")?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            bail!("Jira Agile API returned {} for sprints: {}", status, body);
        }

        let body: serde_json::Value = response
            .json()
            .await
            .context("Failed to parse sprint response")?;

        let sprint = body["values"]
            .as_array()
            .and_then(|sprints| sprints.first())
            .ok_or_else(|| anyhow::anyhow!("No active sprint found for board {board_id}"))?;

        Ok(SprintInfo {
            id: sprint["id"].as_u64().unwrap_or(0),
            name: sprint["name"].as_str().unwrap_or("").to_string(),
            start_date: sprint["startDate"].as_str().map(String::from),
            end_date: sprint["endDate"].as_str().map(String::from),
        })
    }

    /// Fetch available transitions for an issue.
    /// Endpoint: GET /rest/api/2/issue/{key}/transitions
    pub async fn fetch_transitions(&self, key: &str) -> Result<Vec<(String, String)>> {
        let token = Self::resolve_token()?;
        let url = format!("{}/rest/api/2/issue/{}/transitions", self.base_url, key);

        let mut request = self
            .client
            .get(&url)
            .header("Content-Type", "application/json");

        if let Some(ref email) = self.email {
            request = request.basic_auth(email, Some(&token));
        } else {
            request = request.bearer_auth(&token);
        }

        let response = request
            .send()
            .await
            .context("Failed to fetch transitions")?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            bail!(
                "Jira transitions API returned {} for {}: {}",
                status,
                key,
                body
            );
        }

        let body: serde_json::Value = response
            .json()
            .await
            .context("Failed to parse transitions response")?;

        let transitions = body["transitions"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|t| {
                        let id = t["id"].as_str()?.to_string();
                        let name = t["to"]["name"]
                            .as_str()
                            .or_else(|| t["name"].as_str())?
                            .to_string();
                        Some((id, name))
                    })
                    .collect()
            })
            .unwrap_or_default();

        Ok(transitions)
    }

    /// Transition an issue to a new status by name.
    /// Finds the matching transition ID, then POST /rest/api/2/issue/{key}/transitions
    pub async fn transition_issue(&self, key: &str, target_status: &str) -> Result<()> {
        let transitions = self.fetch_transitions(key).await?;

        let transition_id = transitions
            .iter()
            .find(|(_, name)| name.eq_ignore_ascii_case(target_status))
            .map(|(id, _)| id.clone())
            .ok_or_else(|| {
                let available: Vec<&str> = transitions.iter().map(|(_, n)| n.as_str()).collect();
                anyhow::anyhow!(
                    "No transition to '{}' found for {}. Available: {:?}",
                    target_status,
                    key,
                    available
                )
            })?;

        let token = Self::resolve_token()?;
        let url = format!("{}/rest/api/2/issue/{}/transitions", self.base_url, key);

        let payload = serde_json::json!({
            "transition": { "id": transition_id }
        });

        let mut request = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .json(&payload);

        if let Some(ref email) = self.email {
            request = request.basic_auth(email, Some(&token));
        } else {
            request = request.bearer_auth(&token);
        }

        let response = request
            .send()
            .await
            .context("Failed to send transition request")?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            bail!(
                "Jira transition API returned {} for {}: {}",
                status,
                key,
                body
            );
        }

        Ok(())
    }

    /// Post a comment on a Jira issue.
    /// Endpoint: POST /rest/api/2/issue/{key}/comment
    pub async fn add_comment(&self, key: &str, body: &str) -> Result<()> {
        let token = Self::resolve_token()?;
        let url = format!("{}/rest/api/2/issue/{}/comment", self.base_url, key);

        let payload = serde_json::json!({
            "body": body
        });

        let mut request = self
            .client
            .post(&url)
            .header("Content-Type", "application/json")
            .json(&payload);

        if let Some(ref email) = self.email {
            request = request.basic_auth(email, Some(&token));
        } else {
            request = request.bearer_auth(&token);
        }

        let response = request
            .send()
            .await
            .context("Failed to send comment request to Jira")?;

        if !response.status().is_success() {
            let status = response.status();
            let resp_body = response.text().await.unwrap_or_default();
            bail!(
                "Jira comment API returned {} for {}: {}",
                status,
                key,
                resp_body
            );
        }

        Ok(())
    }

    /// Fetch all issues in a sprint via Jira Agile REST API v1.0.
    /// Requires: Jira Software (Cloud or Server/DC 7.x+)
    /// Endpoint: GET /rest/agile/1.0/sprint/{id}/issue?fields=summary,status,assignee
    pub async fn fetch_sprint_issues(&self, sprint_id: u64) -> Result<Vec<BoardTicket>> {
        let token = Self::resolve_token()?;
        let url = format!(
            "{}/rest/agile/1.0/sprint/{}/issue?fields=summary,status,assignee&maxResults=200",
            self.base_url, sprint_id
        );

        let mut request = self
            .client
            .get(&url)
            .header("Content-Type", "application/json");

        if let Some(ref email) = self.email {
            request = request.basic_auth(email, Some(&token));
        } else {
            request = request.bearer_auth(&token);
        }

        let response = request
            .send()
            .await
            .context("Failed to fetch sprint issues from Jira")?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            bail!(
                "Jira Agile API returned {} for sprint issues: {}",
                status,
                body
            );
        }

        let body: serde_json::Value = response
            .json()
            .await
            .context("Failed to parse sprint issues response")?;

        let issues = body["issues"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .map(|issue| BoardTicket {
                        key: issue["key"].as_str().unwrap_or("").to_string(),
                        summary: issue["fields"]["summary"]
                            .as_str()
                            .unwrap_or("")
                            .to_string(),
                        status: issue["fields"]["status"]["name"]
                            .as_str()
                            .unwrap_or("Unknown")
                            .to_string(),
                        assignee: issue["fields"]["assignee"]["displayName"]
                            .as_str()
                            .map(String::from),
                    })
                    .collect()
            })
            .unwrap_or_default();

        Ok(issues)
    }

    /// Search for issues assigned to the current user via JQL.
    /// Endpoint: GET /rest/api/2/search?jql=...&fields=summary,status,priority,assignee
    pub async fn search_assigned_issues(&self, jql: &str) -> Result<Vec<InboxTicket>> {
        let token = Self::resolve_token()?;
        let url = format!("{}/rest/api/2/search", self.base_url);

        let mut request = self
            .client
            .get(&url)
            .header("Content-Type", "application/json")
            .query(&[
                ("jql", jql),
                ("fields", "summary,status,priority,assignee"),
                ("maxResults", "50"),
            ]);

        if let Some(ref email) = self.email {
            request = request.basic_auth(email, Some(&token));
        } else {
            request = request.bearer_auth(&token);
        }

        let response = request
            .send()
            .await
            .context("Failed to search Jira issues")?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            bail!("Jira search API returned {} : {}", status, body);
        }

        let body: serde_json::Value = response
            .json()
            .await
            .context("Failed to parse Jira search response")?;

        let issues = body["issues"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .map(|issue| {
                        let key = issue["key"].as_str().unwrap_or("").to_string();
                        InboxTicket {
                            url: format!("{}/browse/{}", self.base_url, key),
                            key,
                            summary: issue["fields"]["summary"]
                                .as_str()
                                .unwrap_or("")
                                .to_string(),
                            status: issue["fields"]["status"]["name"]
                                .as_str()
                                .unwrap_or("Unknown")
                                .to_string(),
                            priority: issue["fields"]["priority"]["name"]
                                .as_str()
                                .unwrap_or("None")
                                .to_string(),
                        }
                    })
                    .collect()
            })
            .unwrap_or_default();

        Ok(issues)
    }
}