Skip to main content

chant/operations/
reset.rs

1//! Spec reset operation.
2//!
3//! Canonical implementation for resetting specs to pending status.
4
5use anyhow::Result;
6use std::path::Path;
7
8use crate::spec::{Spec, SpecStatus};
9
10/// Options for spec reset
11#[derive(Debug, Clone, Default)]
12pub struct ResetOptions {
13    /// Whether to re-execute the spec after reset
14    pub re_execute: bool,
15    /// Optional prompt template for re-execution
16    pub prompt: Option<String>,
17    /// Optional branch to use for re-execution
18    pub branch: Option<String>,
19}
20
21/// Reset a spec to pending status.
22///
23/// This is the canonical reset logic used by both CLI and MCP.
24/// Only failed or in_progress specs can be reset.
25pub fn reset_spec(spec: &mut Spec, spec_path: &Path, _options: ResetOptions) -> Result<()> {
26    // Check if spec is in failed or in_progress state
27    if spec.frontmatter.status != SpecStatus::Failed
28        && spec.frontmatter.status != SpecStatus::InProgress
29    {
30        anyhow::bail!(
31            "Spec '{}' is not in failed or in_progress state (current: {:?}). \
32             Only failed or in_progress specs can be reset.",
33            spec.id,
34            spec.frontmatter.status
35        );
36    }
37
38    let spec_id = &spec.id;
39
40    // Clean up resources: lock file, PID file, worktree, branch
41    // Use best-effort cleanup - don't fail if resources don't exist
42
43    // Remove lock file
44    let _ = crate::lock::remove_lock(spec_id);
45
46    // Remove PID file
47    let _ = crate::pid::remove_pid_file(spec_id);
48
49    // Remove process files
50    let _ = crate::pid::remove_process_files(spec_id);
51
52    // Remove worktree if it exists
53    if let Ok(config) = crate::config::Config::load() {
54        let project_name = Some(config.project.name.as_str());
55        if let Some(worktree_path) = crate::worktree::get_active_worktree(spec_id, project_name) {
56            let _ = crate::worktree::remove_worktree(&worktree_path);
57        }
58    }
59
60    // Remove branch if it exists
61    if let Ok(config) = crate::config::Config::load() {
62        let branch_prefix = &config.defaults.branch_prefix;
63        let branch = format!("{}{}", branch_prefix, spec_id);
64        let _ = std::process::Command::new("git")
65            .args(["branch", "-D", &branch])
66            .output();
67    }
68
69    // Reset to pending using state machine
70    spec.set_status(SpecStatus::Pending)
71        .map_err(|e| anyhow::anyhow!("Failed to transition spec to Pending: {}", e))?;
72
73    // Save the spec
74    spec.save(spec_path)?;
75
76    Ok(())
77}