1use anyhow::{Context, Result};
4use std::fs;
5use std::path::Path;
6use std::process::Command;
7
8use super::frontmatter::SpecStatus;
9use super::parse::Spec;
10
11fn apply_blocked_status(specs: &mut [Spec]) {
15 apply_blocked_status_with_repos(specs, std::path::Path::new(".chant/specs"), &[]);
16}
17
18pub fn apply_blocked_status_with_repos(
21 specs: &mut [Spec],
22 specs_dir: &std::path::Path,
23 repos: &[crate::config::RepoConfig],
24) {
25 let specs_snapshot = specs.to_vec();
27
28 for spec in specs.iter_mut() {
29 if spec.frontmatter.status != SpecStatus::Pending
31 && spec.frontmatter.status != SpecStatus::Blocked
32 {
33 continue;
34 }
35
36 let is_blocked_locally = spec.is_blocked(&specs_snapshot);
38
39 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 let _ = spec.set_status(SpecStatus::Blocked);
47 } else if spec.frontmatter.status == SpecStatus::Blocked {
48 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
59pub 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(&mut specs);
74
75 Ok(specs)
76}
77
78fn 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 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
115pub fn resolve_spec(specs_dir: &Path, partial_id: &str) -> Result<Spec> {
118 let specs = load_all_specs(specs_dir)?;
119
120 if let Some(spec) = specs.iter().find(|s| s.id == partial_id) {
122 return Ok(spec.clone());
123 }
124
125 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 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 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
168fn load_spec_from_worktree_or_main(spec_id: &str) -> Result<Spec> {
177 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 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 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
200pub fn is_completed(spec_id: &str) -> Result<bool> {
217 let spec = load_spec_from_worktree_or_main(spec_id)?;
219
220 if spec.frontmatter.status != SpecStatus::InProgress {
222 return Ok(false);
223 }
224
225 let unchecked_count = spec.count_unchecked_checkboxes();
227 if unchecked_count > 0 {
228 return Ok(false);
229 }
230
231 if !has_success_signals(spec_id)? {
234 return Ok(false);
235 }
236
237 is_worktree_clean(spec_id)
239}
240
241pub(crate) fn has_success_signals(spec_id: &str) -> Result<bool> {
250 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
267pub fn is_failed(spec_id: &str) -> Result<bool> {
286 let spec = load_spec_from_worktree_or_main(spec_id)?;
288
289 if spec.frontmatter.status != SpecStatus::InProgress {
291 return Ok(false);
292 }
293
294 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 let unchecked_count = spec.count_unchecked_checkboxes();
302 if unchecked_count == 0 {
303 return Ok(false);
305 }
306
307 if has_success_signals(spec_id)? {
310 return Ok(false);
311 }
312
313 Ok(true)
315}
316
317fn is_worktree_clean(spec_id: &str) -> Result<bool> {
326 let worktree_path = Path::new("/tmp").join(format!("chant-{}", spec_id));
327
328 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}