Fully Automated - 100% Backpressure - Pipeline runner 🏃 for AI workflows. 🚀

Commit e08157b3

e08157b321cdMerged

Scott Nixon <[email protected]> · 8 months ago · 8 files · +7 added · ~1 modified

Description

refactor(cli): split main.rs into commands/ modules [attractor-z2a]

Move each CLI command into its own file under src/commands/: validate.rs, info.rs, run.rs, plan.rs, scaffold.rs, decompose.rs. main.rs is now ~155 lines: clap structs, dispatch, load_pipeline.

Details

Commit
e08157b321cd
Parent
cc9619ef3e89

crates/attractor-cli/src/commands/decompose.rsaddedView file

1+use anyhow;
2+
3+/// JSON schema for Claude's decompose output.
4+#[derive(serde::Deserialize, Debug)]
5+struct DecomposeOutput {
6+ epic: EpicDef,
7+ tasks: Vec<TaskDef>,
8+ #[serde(default)]
9+ dependencies: Vec<DepDef>,
10+}
11+
12+#[derive(serde::Deserialize, Debug)]
13+struct EpicDef {
14+ title: String,
15+ description: String,
16+}
17+
18+#[derive(serde::Deserialize, Debug)]
19+struct TaskDef {
20+ title: String,
21+ #[serde(default = "default_task_type")]
22+ r#type: String,
23+ #[serde(default = "default_priority")]
24+ priority: String,
25+ description: String,
26+ #[serde(default)]
27+ acceptance: Option<String>,
28+ #[serde(default)]
29+ design: Option<String>,
30+ #[serde(default)]
31+ notes: Option<String>,
32+}
33+
34+#[derive(serde::Deserialize, Debug)]
35+struct DepDef {
36+ blocked: usize,
37+ blocker: usize,
38+}
39+
40+fn default_task_type() -> String {
41+ "task".to_string()
42+}
43+
44+fn default_priority() -> String {
45+ "P2".to_string()
46+}
47+
48+pub async fn cmd_decompose(spec_path: &std::path::Path, dry_run: bool) -> anyhow::Result<()> {
49+ // Read the spec file
50+ let spec_content = std::fs::read_to_string(spec_path)?;
51+
52+ // Build prompt for Claude to generate structured JSON
53+ let prompt = format!(
54+ "Read this technical specification and output a JSON object describing an epic and its tasks.\n\n\
55+ SPEC:\n{}\n\n\
56+ INSTRUCTIONS:\n\
57+ \n\
58+ ## Output Format\n\
59+ Output ONLY a valid JSON object (no markdown fences, no commentary) with this structure:\n\
60+ {{\n\
61+ \"epic\": {{ \"title\": \"...\", \"description\": \"...\" }},\n\
62+ \"tasks\": [\n\
63+ {{\n\
64+ \"title\": \"...\",\n\
65+ \"type\": \"task\",\n\
66+ \"priority\": \"P2\",\n\
67+ \"description\": \"...\",\n\
68+ \"acceptance\": \"...\",\n\
69+ \"design\": \"...\",\n\
70+ \"notes\": \"...\"\n\
71+ }}\n\
72+ ],\n\
73+ \"dependencies\": [\n\
74+ {{ \"blocked\": 0, \"blocker\": 1 }}\n\
75+ ]\n\
76+ }}\n\
77+ \n\
78+ ## Structure\n\
79+ 1. Extract the title from the spec (usually in the first heading) for the epic\n\
80+ 2. Extract implementation phases/tasks from the spec sections\n\
81+ 3. Priority should be P2 for most tasks unless critical (P1) or backlog (P3/P4)\n\
82+ 4. Dependencies use task array indices (0-based). blocked depends on blocker.\n\
83+ \n\
84+ ## Task Content — PRESERVE ALL CONTEXT\n\
85+ Each task must contain ALL technical details needed to implement it without referring back to the spec.\n\
86+ An agent or developer picking up a ticket should have everything they need right there.\n\
87+ \n\
88+ Use these fields to carry the full context:\n\
89+ - description: High-level summary of what the task is and why (2-4 sentences)\n\
90+ - acceptance: Specific acceptance criteria — list the exact test names, assertions, expected behaviors, and edge cases.\n\
91+ Include function signatures, error types to check, and any numeric thresholds.\n\
92+ - design: Implementation details — code examples, file paths where code should go, architectural decisions,\n\
93+ design rationale, data structures, and any code snippets from the spec. This is where full code examples go.\n\
94+ - notes: Cross-references, warnings, gotchas, related tasks, CI considerations, and any \"IMPORTANT\" callouts from the spec.\n\
95+ \n\
96+ CRITICAL: Do NOT summarize or compress the spec content. If the spec has 60 lines of detail for a task, all 60 lines\n\
97+ of substance should be distributed across description, acceptance, design, and notes. The ticket IS the spec\n\
98+ for that unit of work. Lost context means wrong implementations.\n\
99+ \n\
100+ Output ONLY the JSON object. No other text.",
101+ spec_content
102+ );
103+
104+ // Call Claude CLI with JSON output format
105+ let mut cmd = tokio::process::Command::new("claude");
106+ cmd.arg("-p")
107+ .arg(&prompt)
108+ .arg("--output-format")
109+ .arg("json")
110+ .arg("--no-session-persistence");
111+
112+ // Capture output
113+ cmd.stdout(std::process::Stdio::piped());
114+ cmd.stderr(std::process::Stdio::piped());
115+
116+ let output_result = cmd.output().await?;
117+
118+ if !output_result.status.success() {
119+ let stderr = String::from_utf8_lossy(&output_result.stderr);
120+ anyhow::bail!("Claude CLI failed: {}", stderr);
121+ }
122+
123+ let output_json = String::from_utf8(output_result.stdout)?;
124+ let parsed: serde_json::Value = serde_json::from_str(&output_json)?;
125+
126+ let result_str = parsed["result"]
127+ .as_str()
128+ .ok_or_else(|| anyhow::anyhow!("Claude output missing 'result' field"))?;
129+
130+ // Strip markdown code fences if present (handles ```json, ```, etc.)
131+ let cleaned = strip_code_fences(result_str);
132+
133+ let decompose: DecomposeOutput = serde_json::from_str(&cleaned)
134+ .map_err(|e| anyhow::anyhow!("Failed to parse Claude's JSON output: {}\n\nRaw output:\n{}", e, cleaned))?;
135+
136+ if dry_run {
137+ println!("Decomposition (dry run):\n");
138+ println!("Epic: {}", decompose.epic.title);
139+ println!(" Description: {}", decompose.epic.description);
140+ println!("\nTasks ({}):", decompose.tasks.len());
141+ for (i, task) in decompose.tasks.iter().enumerate() {
142+ println!(" [{}] {} (type={}, priority={})", i, task.title, task.r#type, task.priority);
143+ println!(" Description: {}", truncate_for_display(&task.description, 120));
144+ if let Some(ref a) = task.acceptance {
145+ println!(" Acceptance: {}", truncate_for_display(a, 120));
146+ }
147+ if let Some(ref d) = task.design {
148+ println!(" Design: {}", truncate_for_display(d, 120));
149+ }
150+ if let Some(ref n) = task.notes {
151+ println!(" Notes: {}", truncate_for_display(n, 120));
152+ }
153+ }
154+ println!("\nDependencies ({}):", decompose.dependencies.len());
155+ for dep in &decompose.dependencies {
156+ println!(" Task [{}] blocked by Task [{}]", dep.blocked, dep.blocker);
157+ }
158+ validate_decomposition(&spec_content, None).await?;
159+ return Ok(());
160+ }
161+
162+ // Create the epic
163+ let epic_output = tokio::process::Command::new("bd")
164+ .args(["create", "--title", &decompose.epic.title, "--type", "epic",
165+ "--description", &decompose.epic.description, "--silent"])
166+ .output()
167+ .await?;
168+
169+ if !epic_output.status.success() {
170+ let stderr = String::from_utf8_lossy(&epic_output.stderr);
171+ anyhow::bail!("Failed to create epic: {}", stderr);
172+ }
173+
174+ let epic_id = String::from_utf8(epic_output.stdout)?.trim().to_string();
175+
176+ // Create tasks and collect their IDs
177+ let mut task_ids: Vec<String> = Vec::with_capacity(decompose.tasks.len());
178+
179+ for task in &decompose.tasks {
180+ let mut args = vec![
181+ "create".to_string(),
182+ "--title".to_string(), task.title.clone(),
183+ "--type".to_string(), task.r#type.clone(),
184+ "--priority".to_string(), task.priority.clone(),
185+ "--description".to_string(), task.description.clone(),
186+ ];
187+
188+ if let Some(ref acceptance) = task.acceptance {
189+ args.push("--acceptance".to_string());
190+ args.push(acceptance.clone());
191+ }
192+ if let Some(ref design) = task.design {
193+ args.push("--design".to_string());
194+ args.push(design.clone());
195+ }
196+ if let Some(ref notes) = task.notes {
197+ args.push("--notes".to_string());
198+ args.push(notes.clone());
199+ }
200+ args.push("--silent".to_string());
201+
202+ let task_output = tokio::process::Command::new("bd")
203+ .args(&args)
204+ .output()
205+ .await?;
206+
207+ if !task_output.status.success() {
208+ let stderr = String::from_utf8_lossy(&task_output.stderr);
209+ anyhow::bail!("Failed to create task '{}': {}", task.title, stderr);
210+ }
211+
212+ let task_id = String::from_utf8(task_output.stdout)?.trim().to_string();
213+ task_ids.push(task_id);
214+ }
215+
216+ // Add all tasks as children of the epic
217+ for task_id in &task_ids {
218+ let dep_output = tokio::process::Command::new("bd")
219+ .args(["dep", "add", &epic_id, task_id])
220+ .output()
221+ .await?;
222+
223+ if !dep_output.status.success() {
224+ let stderr = String::from_utf8_lossy(&dep_output.stderr);
225+ eprintln!("Warning: failed to add epic dependency for {}: {}", task_id, stderr);
226+ }
227+ }
228+
229+ // Add task-to-task dependencies
230+ let mut dep_count = 0;
231+ for dep in &decompose.dependencies {
232+ if dep.blocked < task_ids.len() && dep.blocker < task_ids.len() {
233+ let dep_output = tokio::process::Command::new("bd")
234+ .args(["dep", "add", &task_ids[dep.blocked], &task_ids[dep.blocker]])
235+ .output()
236+ .await?;
237+
238+ if !dep_output.status.success() {
239+ let stderr = String::from_utf8_lossy(&dep_output.stderr);
240+ eprintln!("Warning: failed to add dependency [{} -> {}]: {}",
241+ task_ids[dep.blocked], task_ids[dep.blocker], stderr);
242+ } else {
243+ dep_count += 1;
244+ }
245+ } else {
246+ eprintln!("Warning: dependency index out of range (blocked={}, blocker={}, tasks={})",
247+ dep.blocked, dep.blocker, task_ids.len());
248+ }
249+ }
250+
251+ println!("✓ Decomposition complete");
252+ println!(" Epic ID: {}", epic_id);
253+ println!(" Tasks created: {}", task_ids.len());
254+ println!(" Dependencies: {}", dep_count);
255+
256+ // Run post-decompose validation
257+ validate_decomposition(&spec_content, Some(&epic_id)).await?;
258+
259+ println!("\nNext steps:");
260+ println!("1. Review tasks: bd list");
261+ println!("2. Generate pipeline: attractor scaffold {}", epic_id);
262+
263+ Ok(())
264+}
265+
266+/// Strip markdown code fences from a string (e.g., ```json ... ```).
267+fn strip_code_fences(s: &str) -> String {
268+ let lines: Vec<&str> = s.lines().collect();
269+ if lines.len() > 2
270+ && lines[0].starts_with("```")
271+ && lines.last().map_or(false, |l| l.trim() == "```")
272+ {
273+ lines[1..lines.len() - 1].join("\n")
274+ } else {
275+ s.to_string()
276+ }
277+}
278+
279+/// Truncate a string for display, replacing newlines with spaces.
280+fn truncate_for_display(s: &str, max_len: usize) -> String {
281+ let flat: String = s.chars().map(|c| if c == '\n' { ' ' } else { c }).collect();
282+ if flat.len() > max_len {
283+ format!("{}...", &flat[..max_len])
284+ } else {
285+ flat
286+ }
287+}
288+
289+/// Validate decomposition results. When `epic_id` is Some, fetches tickets and
290+/// checks field completeness + spec coverage. When None (dry-run), just reports
291+/// the identifiers extracted from the spec that will be tracked.
292+pub async fn validate_decomposition(
293+ spec_content: &str,
294+ epic_id: Option<&str>,
295+) -> anyhow::Result<()> {
296+ use std::collections::HashSet;
297+
298+ // Extract key identifiers from spec
299+ // Only test names (not general fn names — those are too noisy from code examples)
300+ let re_test = regex::Regex::new(r"(test_\w+)").unwrap();
301+ let re_path = regex::Regex::new(r"(?:src|tests)/[\w/]+\.(?:rs|ndjson)").unwrap();
302+ let re_qualified = regex::Regex::new(r"([A-Z]\w+::\w+)").unwrap();
303+ let re_header = regex::Regex::new(r"####\s+`([^`]+)`").unwrap();
304+
305+ // Common stdlib/language types whose ::method calls are noise, not spec identifiers
306+ let stdlib_prefixes: HashSet<&str> = [
307+ "Arc", "Box", "Cell", "Cow", "HashMap", "HashSet", "Mutex", "Option",
308+ "PathBuf", "Rc", "RefCell", "Result", "RwLock", "String", "Vec",
309+ "AtomicBool", "AtomicU32", "AtomicU64", "AtomicUsize", "Ordering",
310+ "BufReader", "BufWriter", "Duration", "Instant", "SystemTime",
311+ "Command", "Path", "File", "Sender", "Receiver",
312+ "JoinHandle", "TcpStream", "TcpListener",
313+ "Bytes", "BytesMut", "Pin", "Waker",
314+ "Some", "None", "Ok", "Err", "Default", "Display", "Debug",
315+ "From", "Into", "TryFrom", "TryInto", "Iterator", "IntoIterator",
316+ "Read", "Write", "Seek", "BufRead", "AsRef", "Deref",
317+ "Serialize", "Deserialize", "Clone", "Copy", "Send", "Sync",
318+ "PhantomData", "ManuallyDrop", "MaybeUninit",
319+ // std::io and error types
320+ "Error", "ErrorKind", "IoError",
321+ // tokio types
322+ "Mutex", "RwLock", "Notify", "Semaphore", "Barrier",
323+ "OwnedSemaphorePermit", "JoinSet", "JoinError",
324+ // serde/common crate types
325+ "Value", "Map", "Number", "Formatter",
326+ // test assertion types
327+ "Assert", "Assertion",
328+ ].into_iter().collect();
329+
330+ // Generic trait method suffixes that aren't meaningful on any type
331+ let noise_suffixes = ["::clone", "::into",
332+ "::unwrap", "::expect", "::is_ok", "::is_err", "::is_some", "::is_none",
333+ "::as_ref", "::as_str", "::as_bytes", "::as_slice",
334+ "::to_string", "::to_owned", "::to_vec",
335+ ];
336+
337+ let mut identifiers = HashSet::new();
338+
339+ for cap in re_test.captures_iter(spec_content) {
340+ identifiers.insert(cap[1].to_string());
341+ }
342+ for mat in re_path.find_iter(spec_content) {
343+ identifiers.insert(mat.as_str().to_string());
344+ }
345+ for cap in re_qualified.captures_iter(spec_content) {
346+ let full = &cap[1];
347+ // Extract the type prefix (before ::)
348+ let prefix = full.split("::").next().unwrap_or("");
349+ if stdlib_prefixes.contains(prefix) {
350+ continue;
351+ }
352+ if noise_suffixes.iter().any(|s| full.ends_with(s)) {
353+ continue;
354+ }
355+ identifiers.insert(full.to_string());
356+ }
357+ for cap in re_header.captures_iter(spec_content) {
358+ identifiers.insert(cap[1].to_string());
359+ }
360+
361+ let total = identifiers.len();
362+
363+ // Dry-run mode: just report what we extracted from the spec
364+ let epic_id = match epic_id {
365+ Some(id) => id,
366+ None => {
367+ println!("\nSpec validation (dry run):");
368+ if total > 0 {
369+ println!(" Extracted {} identifiers to track coverage against tickets", total);
370+ let mut sorted: Vec<&str> = identifiers.iter().map(|s| s.as_str()).collect();
371+ sorted.sort();
372+ let display: Vec<&str> = sorted.iter().take(20).copied().collect();
373+ let suffix = if sorted.len() > 20 {
374+ format!(", ... ({} more)", sorted.len() - 20)
375+ } else {
376+ String::new()
377+ };
378+ println!(" Identifiers: {}{}", display.join(", "), suffix);
379+ } else {
380+ println!(" No identifiers extracted from spec (no function names, file paths, or types found)");
381+ }
382+ return Ok(());
383+ }
384+ };
385+
386+ // Fetch all child tickets
387+ let list_output = tokio::process::Command::new("bd")
388+ .args(["list", "--parent", epic_id, "--json", "--limit", "0"])
389+ .stdout(std::process::Stdio::piped())
390+ .stderr(std::process::Stdio::piped())
391+ .output()
392+ .await?;
393+
394+ if !list_output.status.success() {
395+ let stderr = String::from_utf8_lossy(&list_output.stderr);
396+ println!("\nValidation: skipped (bd list failed: {})", stderr.trim());
397+ return Ok(());
398+ }
399+
400+ let json_str = String::from_utf8(list_output.stdout)?;
401+ let tickets: Vec<serde_json::Value> = match serde_json::from_str(&json_str) {
402+ Ok(v) => v,
403+ Err(_) => {
404+ println!("\nValidation: skipped (could not parse ticket JSON)");
405+ return Ok(());
406+ }
407+ };
408+
409+ if tickets.is_empty() {
410+ println!("\nValidation: no child tickets found for {}", epic_id);
411+ return Ok(());
412+ }
413+
414+ // Field completeness check
415+ let check_fields = ["description", "acceptance_criteria", "design"];
416+ let mut incomplete: Vec<(String, String, Vec<&str>)> = Vec::new();
417+ let mut complete_count = 0;
418+
419+ for ticket in &tickets {
420+ let id = ticket["id"].as_str().unwrap_or("?");
421+ let title = ticket["title"].as_str().unwrap_or("?");
422+ let missing: Vec<&str> = check_fields
423+ .iter()
424+ .filter(|&&field| {
425+ ticket[field]
426+ .as_str()
427+ .map_or(true, |v| v.trim().is_empty())
428+ })
429+ .copied()
430+ .collect();
431+
432+ if missing.is_empty() {
433+ complete_count += 1;
434+ } else {
435+ incomplete.push((id.to_string(), title.to_string(), missing));
436+ }
437+ }
438+
439+ // Check coverage against tickets
440+ let ticket_texts: Vec<String> = tickets
441+ .iter()
442+ .map(|t| {
443+ let mut combined = String::new();
444+ for field in &["description", "acceptance_criteria", "design", "notes"] {
445+ if let Some(v) = t[*field].as_str() {
446+ combined.push_str(v);
447+ combined.push('\n');
448+ }
449+ }
450+ combined
451+ })
452+ .collect();
453+
454+ let mut missing_ids: Vec<&str> = Vec::new();
455+ let mut covered = 0usize;
456+
457+ for ident in &identifiers {
458+ if ticket_texts.iter().any(|text| text.contains(ident.as_str())) {
459+ covered += 1;
460+ } else {
461+ missing_ids.push(ident);
462+ }
463+ }
464+
465+ missing_ids.sort();
466+ let pct = if total > 0 {
467+ (covered as f64 / total as f64 * 100.0) as u32
468+ } else {
469+ 100
470+ };
471+
472+ // Print report
473+ println!("\nValidation:");
474+ println!(
475+ " Tickets: {} ({} tasks + 1 epic)",
476+ tickets.len() + 1,
477+ tickets.len()
478+ );
479+ println!(
480+ " Field completeness: {}/{} tickets fully populated",
481+ complete_count,
482+ tickets.len()
483+ );
484+ for (id, title, missing) in &incomplete {
485+ println!(
486+ " WARN: {} \"{}\" — missing: {}",
487+ id,
488+ title,
489+ missing.join(", ")
490+ );
491+ }
492+
493+ if total > 0 {
494+ println!(
495+ " Spec coverage: {}/{} identifiers ({}%)",
496+ covered, total, pct
497+ );
498+ if !missing_ids.is_empty() {
499+ let display: Vec<&str> = missing_ids.iter().take(10).copied().collect();
500+ let suffix = if missing_ids.len() > 10 {
501+ format!(", ... ({} more)", missing_ids.len() - 10)
502+ } else {
503+ String::new()
504+ };
505+ println!(" Missing: {}{}", display.join(", "), suffix);
506+ }
507+ } else {
508+ println!(" Spec coverage: no identifiers extracted from spec");
509+ }
510+
511+ Ok(())
512+}