Skip to main content

chant/spec/
lifecycle.rs

1//! Spec lifecycle operations.
2
3use anyhow::{Context, Result};
4use std::fs;
5use std::path::Path;
6use std::process::Command;
7
8use super::frontmatter::SpecStatus;
9use super::parse::Spec;
10
11/// Apply blocked status to specs with unmet dependencies.
12/// For pending specs that have incomplete dependencies, updates their status to blocked.
13/// This is a local-only version that only checks dependencies within the current repo.
14fn apply_blocked_status(specs: &mut [Spec]) {
15    apply_blocked_status_with_repos(specs, std::path::Path::new(".chant/specs"), &[]);
16}
17
18/// Apply blocked status considering both local and cross-repo dependencies.
19/// This version supports cross-repo dependency checking when repos config is available.
20pub fn apply_blocked_status_with_repos(
21    specs: &mut [Spec],
22    specs_dir: &std::path::Path,
23    repos: &[crate::config::RepoConfig],
24) {
25    // Build a reference list of specs for dependency checking
26    let specs_snapshot = specs.to_vec();
27
28    for spec in specs.iter_mut() {
29        // Handle both Pending and Blocked specs
30        if spec.frontmatter.status != SpecStatus::Pending
31            && spec.frontmatter.status != SpecStatus::Blocked
32        {
33            continue;
34        }
35
36        // Check if this spec has unmet dependencies (local only)
37        let is_blocked_locally = spec.is_blocked(&specs_snapshot);
38
39        // Check cross-repo dependencies if repos config is available
40        let is_blocked_cross_repo = !repos.is_empty()
41            && crate::deps::is_blocked_by_dependencies(spec, &specs_snapshot, specs_dir, repos);
42
43        if is_blocked_locally || is_blocked_cross_repo {
44            // Has unmet dependencies - mark as blocked
45            // This is a valid Pending→Blocked transition, so it should always succeed
46            let _ = spec.set_status(SpecStatus::Blocked);
47        } else if spec.frontmatter.status == SpecStatus::Blocked {
48            // No unmet dependencies and was previously blocked - revert to pending
49            // This is a valid Blocked→Pending transition, so it should always succeed
50            let _ = spec.set_status(SpecStatus::Pending);
51        }
52    }
53}
54
55pub fn load_all_specs(specs_dir: &Path) -> Result<Vec<Spec>> {
56    load_all_specs_with_options(specs_dir, true)
57}
58
59/// Load all specs with optional branch resolution.
60pub fn load_all_specs_with_options(
61    specs_dir: &Path,
62    use_branch_resolution: bool,
63) -> Result<Vec<Spec>> {
64    let mut specs = Vec::new();
65
66    if !specs_dir.exists() {
67        return Ok(specs);
68    }
69
70    load_specs_recursive(specs_dir, &mut specs, use_branch_resolution)?;
71
72    // Apply blocked status to specs with unmet dependencies
73    apply_blocked_status(&mut specs);
74
75    Ok(specs)
76}
77
78/// Recursively load specs from a directory and its subdirectories.
79fn load_specs_recursive(
80    dir: &Path,
81    specs: &mut Vec<Spec>,
82    use_branch_resolution: bool,
83) -> Result<()> {
84    if !dir.exists() {
85        return Ok(());
86    }
87
88    for entry in fs::read_dir(dir)? {
89        let entry = entry?;
90        let path = entry.path();
91        let metadata = entry.metadata()?;
92
93        if metadata.is_dir() {
94            // Recursively load from subdirectories
95            load_specs_recursive(&path, specs, use_branch_resolution)?;
96        } else if path.extension().map(|e| e == "md").unwrap_or(false) {
97            let load_result = if use_branch_resolution {
98                Spec::load_with_branch_resolution(&path)
99            } else {
100                Spec::load(&path)
101            };
102
103            match load_result {
104                Ok(spec) => specs.push(spec),
105                Err(e) => {
106                    eprintln!("Warning: Failed to load spec {:?}: {}", path, e);
107                }
108            }
109        }
110    }
111
112    Ok(())
113}
114
115/// Resolve a partial spec ID to a full spec.
116/// Only searches active specs (in .chant/specs/), not archived specs.
117pub fn resolve_spec(specs_dir: &Path, partial_id: &str) -> Result<Spec> {
118    let specs = load_all_specs(specs_dir)?;
119
120    // Exact match
121    if let Some(spec) = specs.iter().find(|s| s.id == partial_id) {
122        return Ok(spec.clone());
123    }
124
125    // Suffix match (random suffix)
126    let suffix_matches: Vec<_> = specs
127        .iter()
128        .filter(|s| s.id.ends_with(partial_id))
129        .collect();
130    if suffix_matches.len() == 1 {
131        return Ok(suffix_matches[0].clone());
132    }
133
134    // Sequence match for today (e.g., "001")
135    if partial_id.len() == 3 {
136        let today = chrono::Local::now().format("%Y-%m-%d").to_string();
137        let today_pattern = format!("{}-{}-", today, partial_id);
138        let today_matches: Vec<_> = specs
139            .iter()
140            .filter(|s| s.id.starts_with(&today_pattern))
141            .collect();
142        if today_matches.len() == 1 {
143            return Ok(today_matches[0].clone());
144        }
145    }
146
147    // Partial date match (e.g., "22-001" or "01-22-001")
148    let partial_matches: Vec<_> = specs.iter().filter(|s| s.id.contains(partial_id)).collect();
149    if partial_matches.len() == 1 {
150        return Ok(partial_matches[0].clone());
151    }
152
153    if partial_matches.len() > 1 {
154        anyhow::bail!(
155            "Ambiguous spec ID '{}'. Matches: {}",
156            partial_id,
157            partial_matches
158                .iter()
159                .map(|s| s.id.as_str())
160                .collect::<Vec<_>>()
161                .join(", ")
162        );
163    }
164
165    anyhow::bail!("Spec not found: {}", partial_id)
166}
167
168/// Load a spec from its worktree if it exists, otherwise from the main repo.
169///
170/// This ensures that watch sees the current state of the spec including
171/// any changes made by the agent in the worktree.
172///
173/// # Errors
174///
175/// Returns an error if the spec file is unreadable from both locations.
176fn load_spec_from_worktree_or_main(spec_id: &str) -> Result<Spec> {
177    // Check if a worktree exists for this spec
178    if let Some(worktree_path) = crate::worktree::get_active_worktree(spec_id, None) {
179        let worktree_spec_path = worktree_path
180            .join(".chant/specs")
181            .join(format!("{}.md", spec_id));
182
183        // Try to load from worktree first
184        if worktree_spec_path.exists() {
185            return Spec::load(&worktree_spec_path).with_context(|| {
186                format!(
187                    "Failed to read spec file from worktree: {}",
188                    worktree_spec_path.display()
189                )
190            });
191        }
192    }
193
194    // Fall back to main repo
195    let spec_path = Path::new(".chant/specs").join(format!("{}.md", spec_id));
196    Spec::load(&spec_path)
197        .with_context(|| format!("Failed to read spec file: {}", spec_path.display()))
198}
199
200/// Check if a spec is completed (ready for finalization).
201///
202/// A spec is considered completed if:
203/// - Status is `in_progress`
204/// - All acceptance criteria checkboxes are checked (`[x]`)
205/// - Worktree is clean (no uncommitted changes including untracked files)
206///
207/// Edge cases:
208/// - Spec with no acceptance criteria: Treated as completed if worktree clean
209/// - Spec already finalized: Returns false (status not `in_progress`)
210///
211/// # Errors
212///
213/// Returns an error if:
214/// - Spec file is unreadable
215/// - Worktree is inaccessible (git status fails)
216pub fn is_completed(spec_id: &str) -> Result<bool> {
217    // Load the spec from worktree if it exists, otherwise from main repo
218    let spec = load_spec_from_worktree_or_main(spec_id)?;
219
220    // Only in_progress specs can be completed
221    if spec.frontmatter.status != SpecStatus::InProgress {
222        return Ok(false);
223    }
224
225    // Check if all criteria are checked
226    let unchecked_count = spec.count_unchecked_checkboxes();
227    if unchecked_count > 0 {
228        return Ok(false);
229    }
230
231    // Fix G: verify commit exists before reporting completion
232    // This prevents watch from reporting false completions
233    if !has_success_signals(spec_id)? {
234        return Ok(false);
235    }
236
237    // Check if worktree is clean
238    is_worktree_clean(spec_id)
239}
240
241/// Check if a spec has success signals indicating work was completed.
242///
243/// Success signals include:
244/// - Commits matching the `chant(spec_id):` pattern
245///
246/// # Errors
247///
248/// Returns an error if git command fails
249pub(crate) fn has_success_signals(spec_id: &str) -> Result<bool> {
250    // Check for commits with the chant(spec_id): pattern
251    let pattern = format!("chant({}):", spec_id);
252    let output = Command::new("git")
253        .args(["log", "--all", "--grep", &pattern, "--format=%H"])
254        .output()
255        .context("Failed to check git log for spec commits")?;
256
257    if !output.status.success() {
258        return Ok(false);
259    }
260
261    let commits_output = String::from_utf8_lossy(&output.stdout);
262    let has_commits = !commits_output.trim().is_empty();
263
264    Ok(has_commits)
265}
266
267/// Check if a spec has failed.
268///
269/// A spec is considered failed if:
270/// - Status is `in_progress`
271/// - Agent has exited (no lock file present)
272/// - Some acceptance criteria are still incomplete
273/// - No success signals present (commits matching `chant(spec_id):` pattern)
274///
275/// Edge cases:
276/// - Agent still running: Returns false
277/// - Spec already finalized/failed: Returns false (status not `in_progress`)
278/// - Has commits matching chant(spec_id) pattern: Returns false (agent completed work)
279///
280/// # Errors
281///
282/// Returns an error if:
283/// - Spec file is unreadable
284/// - Git commands fail
285pub fn is_failed(spec_id: &str) -> Result<bool> {
286    // Load the spec from worktree if it exists, otherwise from main repo
287    let spec = load_spec_from_worktree_or_main(spec_id)?;
288
289    // Only in_progress specs can fail
290    if spec.frontmatter.status != SpecStatus::InProgress {
291        return Ok(false);
292    }
293
294    // Check if agent is still running (lock file exists)
295    let lock_file = Path::new(crate::paths::LOCKS_DIR).join(format!("{}.lock", spec_id));
296    if lock_file.exists() {
297        return Ok(false);
298    }
299
300    // Check if criteria are incomplete
301    let unchecked_count = spec.count_unchecked_checkboxes();
302    if unchecked_count == 0 {
303        // All criteria checked - not failed
304        return Ok(false);
305    }
306
307    // Check for success signals before flagging as failed
308    // If work was committed, don't mark as failed even if criteria unchecked
309    if has_success_signals(spec_id)? {
310        return Ok(false);
311    }
312
313    // No lock, incomplete criteria, no success signals - failed
314    Ok(true)
315}
316
317/// Check if worktree for a spec is clean (no uncommitted changes).
318///
319/// Uses `git status --porcelain` to check for uncommitted changes.
320/// Untracked files count as dirty for safety.
321///
322/// # Errors
323///
324/// Returns an error if git status command fails or worktree is inaccessible.
325fn is_worktree_clean(spec_id: &str) -> Result<bool> {
326    let worktree_path = Path::new("/tmp").join(format!("chant-{}", spec_id));
327
328    // If worktree doesn't exist, check in current directory
329    let check_path = if worktree_path.exists() {
330        &worktree_path
331    } else {
332        Path::new(".")
333    };
334
335    let output = Command::new("git")
336        .args(["status", "--porcelain"])
337        .current_dir(check_path)
338        .output()
339        .with_context(|| format!("Failed to check git status in {:?}", check_path))?;
340
341    if !output.status.success() {
342        let stderr = String::from_utf8_lossy(&output.stderr);
343        anyhow::bail!("git status failed: {}", stderr);
344    }
345
346    let status_output = String::from_utf8_lossy(&output.stdout);
347    Ok(status_output.trim().is_empty())
348}