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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use anyhow::{Context, Result};
use chrono::Utc;
use std::path::{Path, PathBuf};

use super::lifecycle::{ParsecState, ShipResult, Workspace, WorkspaceStatus};
use crate::config::ParsecConfig;
use crate::git;

// ---------------------------------------------------------------------------
// WorktreeManager
// ---------------------------------------------------------------------------

pub struct WorktreeManager {
    repo_root: PathBuf,
    config: ParsecConfig,
}

impl WorktreeManager {
    pub fn new(repo: &Path, config: &ParsecConfig) -> Result<Self> {
        // Always resolve to the main repo root so that state is shared
        // across all worktrees (sibling or internal).
        let repo_root = git::get_main_repo_root(repo)
            .or_else(|_| git::get_repo_root(repo))
            .with_context(|| format!("failed to locate git repository root from {:?}", repo))?;

        Ok(Self {
            repo_root,
            config: config.clone(),
        })
    }

    pub fn repo_root(&self) -> &Path {
        &self.repo_root
    }

    // -----------------------------------------------------------------------
    // create
    // -----------------------------------------------------------------------

    pub fn create(
        &self,
        ticket: &str,
        base: Option<&str>,
        ticket_title: Option<String>,
        parent_ticket: Option<&str>,
        existing_branch: Option<&str>,
    ) -> Result<Workspace> {
        let base_branch = match base {
            Some(b) => b.to_owned(),
            None => {
                if let Some(parent) = parent_ticket {
                    // When stacking, use the parent's branch as base
                    let parent_ws = self.get(parent)?;
                    parent_ws.branch.clone()
                } else if let Some(ref default_base) = self.config.workspace.default_base {
                    default_base.clone()
                } else {
                    git::get_default_branch(&self.repo_root)
                        .context("failed to detect default branch")?
                }
            }
        };

        let worktree_path = match self.config.workspace.layout {
            crate::config::WorktreeLayout::Sibling => {
                // ../reponame.ticket/
                let repo_name = self
                    .repo_root
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| "repo".to_string());
                self.repo_root
                    .parent()
                    .unwrap_or(&self.repo_root)
                    .join(format!("{}.{}", repo_name, ticket))
            }
            crate::config::WorktreeLayout::Internal => self
                .repo_root
                .join(&self.config.workspace.base_dir)
                .join(ticket),
        };

        // Graceful fetch — won't fail if no remote exists
        git::fetch_if_remote(&self.repo_root)?;

        let branch = if let Some(eb) = existing_branch {
            // Use an existing branch — resolve the local name
            let local_name = eb.strip_prefix("origin/").unwrap_or(eb).to_owned();
            git::worktree_add_existing(&self.repo_root, &worktree_path, eb).with_context(|| {
                format!(
                    "failed to create worktree from existing branch '{}' for ticket '{}' at {:?}",
                    eb, ticket, worktree_path
                )
            })?;
            local_name
        } else {
            let branch = format!("{}{}", self.config.workspace.branch_prefix, ticket);
            git::worktree_add(&self.repo_root, &worktree_path, &branch, &base_branch)
                .with_context(|| {
                    format!(
                        "failed to create worktree for ticket '{}' at {:?}",
                        ticket, worktree_path
                    )
                })?;
            branch
        };

        let workspace = Workspace {
            ticket: ticket.to_owned(),
            path: worktree_path.clone(),
            branch,
            base_branch,
            created_at: Utc::now(),
            ticket_title,
            status: WorkspaceStatus::Active,
            parent_ticket: parent_ticket.map(|s| s.to_owned()),
        };

        let mut state =
            ParsecState::load(&self.repo_root).context("failed to load parsec state")?;
        state.add_workspace(workspace.clone());
        state
            .save(&self.repo_root)
            .context("failed to save parsec state")?;

        // Run post-create hooks
        if !self.config.hooks.post_create.is_empty() {
            let skip_prompt = std::env::var("PARSEC_YES")
                .map(|v| v == "1")
                .unwrap_or(false);

            let confirmed = if skip_prompt {
                true
            } else {
                eprintln!("The following post-create hooks will be executed:");
                for hook_cmd in &self.config.hooks.post_create {
                    eprintln!("  - {}", hook_cmd);
                }
                eprint!("Run these hooks? [y/N] ");

                let mut input = String::new();
                match std::io::stdin().read_line(&mut input) {
                    Ok(_) => input.trim().eq_ignore_ascii_case("y"),
                    Err(_) => false,
                }
            };

            if confirmed {
                for hook_cmd in &self.config.hooks.post_create {
                    eprintln!("Running post-create hook: {}", hook_cmd);
                    let status = std::process::Command::new("sh")
                        .args(["-c", hook_cmd])
                        .current_dir(&worktree_path)
                        .status();
                    match status {
                        Ok(s) if s.success() => {}
                        Ok(s) => eprintln!("warning: hook '{}' exited with {}", hook_cmd, s),
                        Err(e) => eprintln!("warning: failed to run hook '{}': {}", hook_cmd, e),
                    }
                }
            } else {
                eprintln!("Skipping post-create hooks.");
            }
        }

        Ok(workspace)
    }

    // -----------------------------------------------------------------------
    // adopt — import an existing branch into parsec state
    // -----------------------------------------------------------------------

    pub fn adopt(
        &self,
        ticket: &str,
        branch: Option<&str>,
        ticket_title: Option<String>,
    ) -> Result<Workspace> {
        let mut state =
            ParsecState::load(&self.repo_root).context("failed to load parsec state")?;

        // Check if ticket is already managed
        if state.get_workspace(ticket).is_some() {
            anyhow::bail!(
                "ticket '{}' is already managed by parsec. Use `parsec status {}` to see it.",
                ticket,
                ticket
            );
        }

        // Resolve the branch name
        let branch_name = match branch {
            Some(b) => b.to_owned(),
            None => {
                // Default: branch_prefix + ticket
                let candidate = format!("{}{}", self.config.workspace.branch_prefix, ticket);
                // Verify the branch exists
                match git::run_output(
                    &self.repo_root,
                    &[
                        "rev-parse",
                        "--verify",
                        &format!("refs/heads/{}", candidate),
                    ],
                ) {
                    Ok(_) => candidate,
                    Err(_) => {
                        // Try current branch
                        let current = git::run_output(
                            &self.repo_root,
                            &["rev-parse", "--abbrev-ref", "HEAD"],
                        )
                        .context("could not detect branch. Specify one with --branch <name>")?;
                        if current == "HEAD" || current == "main" || current == "master" {
                            anyhow::bail!(
                                "no branch found for ticket '{}'. Specify one with: parsec adopt {} --branch <branch-name>",
                                ticket, ticket
                            );
                        }
                        current
                    }
                }
            }
        };

        // Verify branch exists
        git::run_output(
            &self.repo_root,
            &[
                "rev-parse",
                "--verify",
                &format!("refs/heads/{}", branch_name),
            ],
        )
        .with_context(|| {
            format!(
                "branch '{}' does not exist. Create it first or check the name.",
                branch_name
            )
        })?;

        // Detect base branch
        let base_branch =
            git::get_default_branch(&self.repo_root).unwrap_or_else(|_| "main".to_owned());

        // Check if this branch already has a worktree
        let worktree_path = self.find_worktree_for_branch(&branch_name);

        let path = match worktree_path {
            Some(p) => p,
            None => {
                // No worktree exists — create one
                let wt_path = match self.config.workspace.layout {
                    crate::config::WorktreeLayout::Sibling => {
                        let repo_name = self
                            .repo_root
                            .file_name()
                            .map(|n| n.to_string_lossy().to_string())
                            .unwrap_or_else(|| "repo".to_string());
                        self.repo_root
                            .parent()
                            .unwrap_or(&self.repo_root)
                            .join(format!("{}.{}", repo_name, ticket))
                    }
                    crate::config::WorktreeLayout::Internal => self
                        .repo_root
                        .join(&self.config.workspace.base_dir)
                        .join(ticket),
                };
                git::run(
                    &self.repo_root,
                    &[
                        "worktree",
                        "add",
                        wt_path.to_str().unwrap_or(""),
                        &branch_name,
                    ],
                )
                .with_context(|| {
                    format!(
                        "failed to create worktree for branch '{}' at {:?}",
                        branch_name, wt_path
                    )
                })?;
                wt_path
            }
        };

        let workspace = Workspace {
            ticket: ticket.to_owned(),
            path,
            branch: branch_name,
            base_branch,
            created_at: Utc::now(),
            ticket_title,
            status: WorkspaceStatus::Active,
            parent_ticket: None,
        };

        state.add_workspace(workspace.clone());
        state
            .save(&self.repo_root)
            .context("failed to save parsec state after adopt")?;

        Ok(workspace)
    }

    /// Find existing worktree path for a given branch name.
    fn find_worktree_for_branch(&self, branch: &str) -> Option<PathBuf> {
        let output = git::run_output(&self.repo_root, &["worktree", "list", "--porcelain"]).ok()?;

        let mut current_path: Option<String> = None;
        for line in output.lines() {
            if let Some(val) = line.strip_prefix("worktree ") {
                current_path = Some(val.to_owned());
            } else if let Some(val) = line.strip_prefix("branch ") {
                let wt_branch = val.strip_prefix("refs/heads/").unwrap_or(val);
                if wt_branch == branch {
                    return current_path.map(PathBuf::from);
                }
            } else if line.is_empty() {
                current_path = None;
            }
        }
        None
    }

    // -----------------------------------------------------------------------
    // list
    // -----------------------------------------------------------------------

    pub fn list(&self) -> Result<Vec<Workspace>> {
        let state = ParsecState::load(&self.repo_root).context("failed to load parsec state")?;

        let mut workspaces: Vec<Workspace> = state.workspaces.into_values().collect();
        workspaces.sort_by_key(|w| w.created_at);
        Ok(workspaces)
    }

    // -----------------------------------------------------------------------
    // get
    // -----------------------------------------------------------------------

    pub fn get(&self, ticket: &str) -> Result<Workspace> {
        let state = ParsecState::load(&self.repo_root).context("failed to load parsec state")?;

        state
            .get_workspace(ticket)
            .cloned()
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "no workspace found for ticket '{}'. Run `parsec list` to see active workspaces, or `parsec adopt {}` to import an existing branch.",
                    ticket, ticket
                )
            })
    }

    // -----------------------------------------------------------------------
    // ship (push + cleanup only, PR creation is in commands.rs)
    // -----------------------------------------------------------------------

    /// Phase 1: Push the branch only, don't clean up yet.
    pub fn ship_push(&self, ticket: &str) -> Result<ShipResult> {
        let state = ParsecState::load(&self.repo_root).context("failed to load parsec state")?;

        let workspace = state
            .get_workspace(ticket)
            .cloned()
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "no workspace found for ticket '{}'. Run `parsec list` to see active workspaces, or `parsec adopt {}` to import an existing branch.",
                    ticket, ticket
                )
            })?;

        // Push the branch from the worktree itself so HEAD is correct.
        git::push_branch(&workspace.path, &workspace.branch)
            .with_context(|| format!("failed to push branch '{}'", workspace.branch))?;

        Ok(ShipResult {
            ticket: ticket.to_owned(),
            branch: workspace.branch,
            base_branch: workspace.base_branch,
            ticket_title: workspace.ticket_title,
            pr_url: None,
            cleaned_up: false,
        })
    }

    /// Phase 2: Clean up worktree and branch after successful PR creation.
    pub fn ship_cleanup(&self, ticket: &str) -> Result<bool> {
        if !self.config.ship.auto_cleanup {
            return Ok(false);
        }

        let state = ParsecState::load(&self.repo_root).context("failed to load parsec state")?;

        let workspace = match state.get_workspace(ticket) {
            Some(ws) => ws.clone(),
            None => return Ok(false), // Already cleaned up
        };

        let cleaned_up = match git::worktree_remove(&self.repo_root, &workspace.path) {
            Ok(()) => {
                if let Err(e) = git::delete_branch(&self.repo_root, &workspace.branch) {
                    eprintln!(
                        "warning: failed to delete branch '{}': {e}",
                        workspace.branch
                    );
                }
                true
            }
            Err(e) => {
                eprintln!("warning: failed to remove worktree: {e}");
                false
            }
        };

        // Update persisted state
        let mut state =
            ParsecState::load(&self.repo_root).context("failed to load parsec state")?;
        if cleaned_up {
            state.remove_workspace(ticket);
        } else if let Some(ws) = state.workspaces.get_mut(ticket) {
            ws.status = WorkspaceStatus::Shipped;
        }
        state
            .save(&self.repo_root)
            .context("failed to save parsec state after ship cleanup")?;

        Ok(cleaned_up)
    }

    /// Combined push + cleanup (backwards compat).
    #[allow(dead_code)]
    pub fn ship(&self, ticket: &str) -> Result<ShipResult> {
        let mut result = self.ship_push(ticket)?;
        let cleaned_up = self.ship_cleanup(ticket)?;
        result.cleaned_up = cleaned_up;
        Ok(result)
    }

    // -----------------------------------------------------------------------
    // clean
    // -----------------------------------------------------------------------

    pub fn clean(&self, all: bool, dry_run: bool) -> Result<Vec<Workspace>> {
        let mut state =
            ParsecState::load(&self.repo_root).context("failed to load parsec state")?;

        let candidates: Vec<Workspace> = state
            .workspaces
            .values()
            .filter(|ws| {
                if all {
                    return true;
                }
                git::is_branch_merged(&self.repo_root, &ws.branch, &ws.base_branch).unwrap_or(false)
            })
            .cloned()
            .collect();

        if !dry_run {
            for ws in &candidates {
                match git::worktree_remove(&self.repo_root, &ws.path) {
                    Ok(()) => {
                        if let Err(e) = git::delete_branch(&self.repo_root, &ws.branch) {
                            eprintln!("warning: failed to delete branch '{}': {e}", ws.branch);
                        }
                    }
                    Err(e) => {
                        eprintln!(
                            "warning: failed to remove worktree for '{}': {e}",
                            ws.ticket
                        );
                    }
                }
                state.remove_workspace(&ws.ticket);
            }

            state
                .save(&self.repo_root)
                .context("failed to save parsec state after clean")?;
        }

        Ok(candidates)
    }

    // -----------------------------------------------------------------------
    // clean_orphans
    // -----------------------------------------------------------------------

    /// Remove state entries whose worktree directory no longer exists on disk.
    pub fn clean_orphans(&self, dry_run: bool) -> Result<Vec<Workspace>> {
        let mut state =
            ParsecState::load(&self.repo_root).context("failed to load parsec state")?;

        let orphans: Vec<Workspace> = state
            .workspaces
            .values()
            .filter(|ws| !ws.path.exists())
            .cloned()
            .collect();

        if !dry_run {
            for ws in &orphans {
                state.remove_workspace(&ws.ticket);
            }
            state
                .save(&self.repo_root)
                .context("failed to save parsec state after orphan cleanup")?;
        }

        Ok(orphans)
    }
}