Commit 7584c792
7584c792b876Merged
Scott Nixon <[email protected]> ยท 7 months ago ยท 2 files ยท +2 added
Description
chore: track backup files for generate.rs and phase-1-spec.dot
Details
- Commit
- 7584c792b876
- Parent
- f27389b7ed40
crates/attractor-cli/src/commands/generate.rs.bakaddedView file
1+
use anyhow;2+
use std::io::Write;3+
use std::sync::atomic::{AtomicBool, Ordering};4+
use std::sync::Arc;5+
6+
/// Spawn a braille spinner on stderr. Returns a guard that stops it on drop.7+
fn start_spinner(message: &str) -> SpinnerGuard {8+
const FRAMES: &[&str] = &["โ ", "โ ", "โ น", "โ ธ", "โ ผ", "โ ด", "โ ฆ", "โ ง", "โ ", "โ "];9+
10+
let done = Arc::new(AtomicBool::new(false));11+
let done_clone = done.clone();12+
let msg = message.to_string();13+
14+
let handle = std::thread::spawn(move || {15+
let mut i = 0usize;16+
let start = std::time::Instant::now();17+
while !done_clone.load(Ordering::Relaxed) {18+
let elapsed = start.elapsed().as_secs();19+
let mins = elapsed / 60;20+
let secs = elapsed % 60;21+
eprint!(22+
"\r\x1b[2K\x1b[36m{}\x1b[0m {} \x1b[2m{}:{:02}\x1b[0m",23+
FRAMES[i % FRAMES.len()],24+
msg,25+
mins,26+
secs27+
);28+
let _ = std::io::stderr().flush();29+
std::thread::sleep(std::time::Duration::from_millis(80));30+
i += 1;31+
}32+
// Clear the spinner line33+
eprint!("\r\x1b[2K");34+
let _ = std::io::stderr().flush();35+
});36+
37+
SpinnerGuard {38+
done,39+
handle: Some(handle),40+
}41+
}42+
43+
struct SpinnerGuard {44+
done: Arc<AtomicBool>,45+
handle: Option<std::thread::JoinHandle<()>>,46+
}47+
48+
impl Drop for SpinnerGuard {49+
fn drop(&mut self) {50+
self.done.store(true, Ordering::Relaxed);51+
if let Some(h) = self.handle.take() {52+
let _ = h.join();53+
}54+
}55+
}56+
57+
pub async fn cmd_generate(58+
prd_path: Option<&std::path::Path>,59+
spec_path: &std::path::Path,60+
output: Option<&std::path::Path>,61+
verbose: bool,62+
) -> anyhow::Result<()> {63+
// Read spec (required)64+
let spec_content = std::fs::read_to_string(spec_path).map_err(|e| {65+
anyhow::anyhow!("Failed to read spec file '{}': {}", spec_path.display(), e)66+
})?;67+
68+
// Read PRD (optional)69+
let prd_content =70+
match prd_path {71+
Some(path) => Some(std::fs::read_to_string(path).map_err(|e| {72+
anyhow::anyhow!("Failed to read PRD file '{}': {}", path.display(), e)73+
})?),74+
None => None,75+
};76+
77+
if verbose {78+
eprintln!(79+
"[debug] spec: {} ({} bytes)",80+
spec_path.display(),81+
spec_content.len()82+
);83+
if let Some(p) = prd_path {84+
eprintln!(85+
"[debug] prd: {} ({} bytes)",86+
p.display(),87+
prd_content.as_ref().map_or(0, |c| c.len())88+
);89+
}90+
}91+
92+
// Build the prompt93+
let prompt = build_prompt(&spec_content, prd_content.as_deref());94+
95+
if verbose {96+
eprintln!("[debug] prompt: {} bytes", prompt.len());97+
eprintln!("[debug] cmd: claude -p - --model sonnet --settings '{{\"enabledPlugins\":{{}}}}' --strict-mcp-config '{{}}' --tools '' --output-format json --no-session-persistence");98+
}99+
100+
// Call Claude CLI with spinner โ disable plugins/MCP/skills for speed101+
let mut cmd = tokio::process::Command::new("claude");102+
cmd.arg("-p")103+
.arg("-")104+
.arg("--model")105+
.arg("sonnet")106+
.arg("--system-prompt")107+
.arg("You are a Graphviz DOT generator. Output ONLY a raw digraph. No commentary, no markdown fences, no skill invocations, no function calls.")108+
.arg("--settings")109+
.arg(r#"{"enabledPlugins":{}}"#)110+
.arg("--strict-mcp-config")111+
.arg("{}")112+
.arg("--tools")113+
.arg("")114+
.arg("--output-format")115+
.arg("json")116+
.arg("--no-session-persistence");117+
118+
cmd.stdin(std::process::Stdio::piped());119+
cmd.stdout(std::process::Stdio::piped());120+
cmd.stderr(std::process::Stdio::piped());121+
122+
let gen_start = std::time::Instant::now();123+
let spinner = start_spinner("Generating pipeline from spec...");124+
let mut child = cmd.spawn()?;125+
126+
// Write prompt to stdin, then close it127+
if let Some(mut stdin) = child.stdin.take() {128+
use tokio::io::AsyncWriteExt;129+
stdin.write_all(prompt.as_bytes()).await?;130+
// stdin is dropped here, closing the pipe131+
}132+
133+
let output_result = child.wait_with_output().await?;134+
drop(spinner);135+
let gen_elapsed = gen_start.elapsed();136+
eprintln!("Claude responded in {:.1}s", gen_elapsed.as_secs_f64());137+
138+
if !output_result.status.success() {139+
let stderr = String::from_utf8_lossy(&output_result.stderr);140+
if verbose {141+
let stdout = String::from_utf8_lossy(&output_result.stdout);142+
eprintln!("[debug] exit code: {:?}", output_result.status.code());143+
eprintln!("[debug] stdout: {}", &stdout[..stdout.len().min(1000)]);144+
eprintln!("[debug] stderr: {}", &stderr[..stderr.len().min(1000)]);145+
}146+
anyhow::bail!("Claude CLI failed: {}", stderr);147+
}148+
149+
let output_json = String::from_utf8(output_result.stdout)?;150+
151+
if verbose {152+
eprintln!("[debug] response json: {} bytes", output_json.len());153+
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&output_json) {154+
if let Some(cost) = parsed.get("total_cost_usd") {155+
eprintln!("[debug] cost: ${}", cost);156+
}157+
if let Some(usage) = parsed.get("usage") {158+
eprintln!("[debug] usage: {}", usage);159+
}160+
}161+
}162+
163+
let parsed: serde_json::Value = serde_json::from_str(&output_json)?;164+
165+
let result_str = parsed["result"]166+
.as_str()167+
.ok_or_else(|| anyhow::anyhow!("Claude output missing 'result' field"))?;168+
169+
// Extract the digraph from Claude's response (handles preamble, fences, etc.)170+
let dot_content = match extract_digraph(result_str) {171+
Some(d) => d,172+
None => {173+
eprintln!("No digraph found in Claude's response. First 500 chars:");174+
eprintln!("{}", &result_str[..result_str.len().min(500)]);175+
anyhow::bail!("Claude did not produce a valid digraph");176+
}177+
};178+
179+
if verbose {180+
eprintln!("[debug] extracted DOT: {} bytes", dot_content.len());181+
eprintln!(182+
"[debug] first 200 chars:\n{}",183+
&dot_content[..dot_content.len().min(200)]184+
);185+
}186+
187+
// Determine output path188+
let output_path = match output {189+
Some(path) => path.to_path_buf(),190+
None => {191+
let stem = spec_path192+
.file_stem()193+
.and_then(|s| s.to_str())194+
.unwrap_or("pipeline");195+
std::path::PathBuf::from(format!("pipelines/{}.dot", stem))196+
}197+
};198+
199+
// Create parent directory if needed200+
if let Some(parent) = output_path.parent() {201+
std::fs::create_dir_all(parent)?;202+
}203+
204+
// Write the pipeline file205+
std::fs::write(&output_path, &dot_content)?;206+
207+
// Validate the generated pipeline208+
let graph = match crate::load_pipeline(&output_path) {209+
Ok(g) => g,210+
Err(e) => {211+
eprintln!("Generated file written to: {}", output_path.display());212+
eprintln!("DOT parse failed โ first 500 chars of output:");213+
eprintln!("{}", &dot_content[..dot_content.len().min(500)]);214+
anyhow::bail!("Generated pipeline is not valid DOT: {}", e);215+
}216+
};217+
let diagnostics = attractor_pipeline::validate(&graph);218+
219+
let has_error = diagnostics220+
.iter()221+
.any(|d| matches!(d.severity, attractor_pipeline::Severity::Error));222+
223+
if has_error {224+
println!("Warning: pipeline has validation errors:");225+
for diag in &diagnostics {226+
if matches!(diag.severity, attractor_pipeline::Severity::Error) {227+
println!(" [ERROR] {}: {}", diag.rule, diag.message);228+
}229+
}230+
}231+
232+
let node_count = graph.all_nodes().count();233+
234+
println!("Pipeline generated");235+
println!(" Output: {}", output_path.display());236+
println!(" Spec: {}", spec_path.display());237+
if let Some(prd) = prd_path {238+
println!(" PRD: {}", prd.display());239+
}240+
println!(" Nodes: {}", node_count);241+
println!(242+
" Validation: {}",243+
if has_error { "FAILED" } else { "PASSED" }244+
);245+
246+
if !has_error {247+
println!("\nNext steps:");248+
println!("1. Review pipeline: cat {}", output_path.display());249+
println!("2. Run pipeline: pas run {} -w .", output_path.display());250+
}251+
252+
Ok(())253+
}254+
255+
fn build_prompt(spec: &str, prd: Option<&str>) -> String {256+
let prd_section = match prd {257+
Some(content) => format!("## PRD (Product Requirements Document)\n\n{}\n\n", content),258+
None => String::new(),259+
};260+
261+
format!(262+
r#"Generate a Graphviz DOT pipeline for an AI workflow engine. Each node is a Claude Code session that receives the `prompt` attribute as its task.263+
264+
{prd_section}## Technical Specification265+
266+
{spec}267+
268+
## Pipeline conventions269+
270+
IMPORTANT: ALL attribute values MUST be double-quoted. Use `shape="Mdiamond"` not `shape=Mdiamond`. Use multi-line node declarations with one attribute per line.271+
272+
Shapes: `"Mdiamond"` = start, `"Msquare"` = done, `"box"` = work, `"diamond"` (node_type="conditional") = decision, `"hexagon"` (node_type="wait.human") = human gate.273+
Graph attrs: `label`, `goal`, `model="sonnet"`.274+
Node attrs: `label`, `shape`, `prompt` (self-contained instructions with ALL context from the spec โ no references to external tickets).275+
Optional: `allowed_tools` (e.g. "Read,Grep,Glob"), `goal_gate="true"`, `llm_model`.276+
Edge attrs: `label` (e.g. "PASS","FAIL"), `condition` (e.g. preferred_label=PASS), `loop_restart="true"` on back-edges.277+
278+
## Timeouts279+
280+
Every node MUST have a `timeout` attribute. Claude Code sessions have startup overhead and often iterate multiple times, so timeouts must be generous. Set based on complexity:281+
- Trivial (conditionals, haiku routing, reading a single file): `timeout="120s"`282+
- Light (linting, formatting checks, simple single-step verification): `timeout="300s"`283+
- Standard (investigation, verification with iteration, fixups, most work nodes): `timeout="600s"`284+
- Heavy (implementing features, writing substantial new code, multi-file changes): `timeout="900s"`285+
- Intensive (full test suites, large refactors, multi-step builds): `timeout="1200s"`286+
287+
When in doubt, use 600s. Underestimating causes pipeline failures; overestimating just means unused budget. Most work+verify nodes should be 600s or higher.288+
289+
Example node format:290+
my_node [291+
label="Short Label"292+
shape="box"293+
timeout="600s"294+
prompt="Detailed instructions here."295+
]296+
297+
## Structure298+
299+
start -> [task1] -> [verify1] -PASS-> [task2] -> ... -> commit_changes -> done300+
\-FAIL-> [fixup1] -> [verify1] (loop_restart=true)301+
302+
Each spec task becomes a work node + verify diamond. FAIL edges loop through a fixup node. PASS edges advance. Node prompts must be fully self-contained.303+
304+
## Commit step (REQUIRED)305+
306+
The LAST work node before `done` MUST be a commit node that stages and commits all changes:307+
commit_changes [308+
label="Commit Changes"309+
shape="box"310+
timeout="120s"311+
allowed_tools="Bash(git:*)"312+
prompt="Stage and commit all changes made by this pipeline.313+
1. Run git diff --stat to review what changed314+
2. Stage the changed files: git add -A315+
3. Commit with a descriptive message summarizing the work done"316+
]317+
318+
Output ONLY the raw digraph. No markdown fences, no commentary."#,319+
prd_section = prd_section,320+
spec = spec,321+
)322+
}323+
324+
/// Extract a DOT digraph from Claude's response.325+
/// Handles: raw digraph, markdown-fenced digraph, digraph buried in preamble text.326+
fn extract_digraph(s: &str) -> Option<String> {327+
// First strip markdown code fences if present328+
let stripped = strip_code_fences(s);329+
330+
// Find "digraph" keyword331+
let start = stripped.find("digraph")?;332+
333+
// Find the opening brace334+
let brace_start = stripped[start..].find('{')? + start;335+
336+
// Walk forward matching braces to find the closing one337+
let mut depth = 0;338+
let mut end = None;339+
for (i, ch) in stripped[brace_start..].char_indices() {340+
match ch {341+
'{' => depth += 1,342+
'}' => {343+
depth -= 1;344+
if depth == 0 {345+
end = Some(brace_start + i + 1);346+
break;347+
}348+
}349+
_ => {}350+
}351+
}352+
353+
end.map(|e| stripped[start..e].to_string())354+
}355+
356+
/// Strip markdown code fences from a string (e.g., ```dot ... ```).357+
fn strip_code_fences(s: &str) -> String {358+
let lines: Vec<&str> = s.lines().collect();359+
if lines.len() > 2360+
&& lines[0].starts_with("```")361+
&& lines.last().map_or(false, |l| l.trim() == "```")362+
{363+
lines[1..lines.len() - 1].join("\n")364+
} else {365+
s.to_string()366+
}367+
}368+
369+
/// Generate pipelines from a directory of PRD+spec pairs.370+
///371+
/// Scans `dir` for files matching `*-spec.md`, pairs each with a372+
/// corresponding `*-prd.md` (if present), and generates one .dot file per373+
/// pair. Output names are zero-padded to sort correctly.374+
pub async fn cmd_generate_dir(375+
dir: &std::path::Path,376+
output_dir: Option<&std::path::Path>,377+
verbose: bool,378+
) -> anyhow::Result<Vec<std::path::PathBuf>> {379+
// Discover *-spec.md files, sorted380+
let mut specs: Vec<std::path::PathBuf> = std::fs::read_dir(dir)?381+
.filter_map(|e| e.ok())382+
.map(|e| e.path())383+
.filter(|p| {384+
p.extension().map_or(false, |ext| ext == "md")385+
&& p.file_stem()386+
.and_then(|s| s.to_str())387+
.map_or(false, |s| s.ends_with("-spec"))388+
})389+
.collect();390+
specs.sort();391+
392+
if specs.is_empty() {393+
anyhow::bail!(394+
"No *-spec.md files found in {}\n\n\395+
Spec files must have names ending in -spec.md (e.g. auth-spec.md,\n\396+
phase-01-spec.md). Each spec is paired with a matching -prd.md if\n\397+
one exists (auth-spec.md pairs with auth-prd.md). PRDs are optional.\n\n\398+
Use zero-padded prefixes to control generation order:\n\399+
\x20 phase-01-spec.md, phase-02-spec.md, ..., phase-11-spec.md",400+
dir.display()401+
);402+
}403+
404+
let out_dir = output_dir405+
.map(|p| p.to_path_buf())406+
.unwrap_or_else(|| std::path::PathBuf::from("pipelines"));407+
std::fs::create_dir_all(&out_dir)?;408+
409+
println!(410+
"Found {} spec(s) in {} (lexical order):",411+
specs.len(),412+
dir.display()413+
);414+
for spec in &specs {415+
let stem = spec.file_stem().and_then(|s| s.to_str()).unwrap_or("?");416+
let prd_stem = stem.replace("-spec", "-prd");417+
let prd_path = dir.join(format!("{}.md", prd_stem));418+
let prd_status = if prd_path.exists() { "+ PRD" } else { "no PRD" };419+
println!(420+
" {} ({})",421+
spec.file_name().unwrap_or_default().to_string_lossy(),422+
prd_status423+
);424+
}425+
println!();426+
427+
let mut generated: Vec<std::path::PathBuf> = Vec::new();428+
429+
for (i, spec_path) in specs.iter().enumerate() {430+
let stem = spec_path431+
.file_stem()432+
.and_then(|s| s.to_str())433+
.unwrap_or("pipeline");434+
435+
// Pair with PRD: replace "-spec" suffix with "-prd"436+
let prd_stem = stem.replace("-spec", "-prd");437+
let prd_path = dir.join(format!("{}.md", prd_stem));438+
let prd = if prd_path.exists() {439+
Some(prd_path.as_path())440+
} else {441+
None442+
};443+
444+
let output_path = out_dir.join(format!("{}.dot", stem));445+
446+
println!(447+
"[{}/{}] {} {}โ {}",448+
i + 1,449+
specs.len(),450+
spec_path.file_name().unwrap_or_default().to_string_lossy(),451+
if prd.is_some() { "(with PRD) " } else { "" },452+
output_path.display()453+
);454+
455+
cmd_generate(prd, spec_path, Some(&output_path), verbose).await?;456+
generated.push(output_path);457+
}458+
459+
println!("\nGenerated {} pipeline(s)", generated.len());460+
Ok(generated)461+
}462+
463+
#[cfg(test)]464+
mod tests {465+
use super::*;466+
467+
// โโ strip_code_fences โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ468+
469+
#[test]470+
fn strip_fences_dot() {471+
let input = "```dot\ndigraph { a -> b }\n```";472+
assert_eq!(strip_code_fences(input), "digraph { a -> b }");473+
}474+
475+
#[test]476+
fn strip_fences_plain() {477+
let input = "```\ndigraph { a -> b }\n```";478+
assert_eq!(strip_code_fences(input), "digraph { a -> b }");479+
}480+
481+
#[test]482+
fn strip_fences_graphviz() {483+
let input = "```graphviz\ndigraph G {\n start -> done\n}\n```";484+
assert_eq!(strip_code_fences(input), "digraph G {\n start -> done\n}");485+
}486+
487+
#[test]488+
fn strip_fences_trailing_whitespace() {489+
let input = "```dot\ndigraph { a -> b }\n``` ";490+
assert_eq!(strip_code_fences(input), "digraph { a -> b }");491+
}492+
493+
#[test]494+
fn strip_fences_noop_when_no_fences() {495+
let input = "digraph { a -> b }";496+
assert_eq!(strip_code_fences(input), input);497+
}498+
499+
#[test]500+
fn strip_fences_noop_single_line() {501+
let input = "```dot```";502+
assert_eq!(strip_code_fences(input), input);503+
}504+
505+
#[test]506+
fn strip_fences_preserves_inner_content() {507+
let input = "```dot\nline1\nline2\nline3\n```";508+
assert_eq!(strip_code_fences(input), "line1\nline2\nline3");509+
}510+
511+
// โโ build_prompt โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ512+
513+
#[test]514+
fn build_prompt_spec_only() {515+
let result = build_prompt("my spec content", None);516+
assert!(result.contains("## Technical Specification"));517+
assert!(result.contains("my spec content"));518+
assert!(!result.contains("## PRD"));519+
}520+
521+
#[test]522+
fn build_prompt_with_prd() {523+
let result = build_prompt("my spec", Some("my prd"));524+
assert!(result.contains("## PRD (Product Requirements Document)"));525+
assert!(result.contains("my prd"));526+
assert!(result.contains("my spec"));527+
}528+
529+
#[test]530+
fn build_prompt_contains_pipeline_conventions() {531+
let result = build_prompt("spec", None);532+
assert!(result.contains("Mdiamond"));533+
assert!(result.contains("Msquare"));534+
assert!(result.contains("node_type=\"conditional\""));535+
assert!(result.contains("loop_restart"));536+
}537+
538+
#[test]539+
fn build_prompt_contains_timeout_guidance() {540+
let result = build_prompt("spec", None);541+
assert!(result.contains("timeout"));542+
assert!(result.contains("timeout=\"120s\""));543+
assert!(result.contains("timeout=\"300s\""));544+
assert!(result.contains("timeout=\"600s\""));545+
assert!(result.contains("timeout=\"900s\""));546+
assert!(result.contains("timeout=\"1200s\""));547+
assert!(result.contains("Trivial"));548+
assert!(result.contains("Intensive"));549+
assert!(result.contains("When in doubt, use 600s"));550+
}551+
552+
#[test]553+
fn build_prompt_requires_commit_step() {554+
let result = build_prompt("spec", None);555+
assert!(result.contains("commit_changes"));556+
assert!(result.contains("Commit Changes"));557+
assert!(result.contains("git add -A"));558+
assert!(result.contains("Bash(git:*)"));559+
}560+
561+
#[test]562+
fn build_prompt_asks_for_raw_digraph() {563+
let result = build_prompt("spec", None);564+
assert!(result.contains("Output ONLY the raw digraph"));565+
assert!(result.contains("No markdown fences"));566+
}567+
568+
#[test]569+
fn build_prompt_prd_before_spec() {570+
let result = build_prompt("SPEC_CONTENT", Some("PRD_CONTENT"));571+
let prd_pos = result.find("PRD_CONTENT").unwrap();572+
let spec_pos = result.find("SPEC_CONTENT").unwrap();573+
assert!(574+
prd_pos < spec_pos,575+
"PRD should appear before spec in prompt"576+
);577+
}578+
579+
// โโ extract_digraph โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ580+
581+
#[test]582+
fn extract_raw_digraph() {583+
let input = "digraph G { a -> b }";584+
assert_eq!(extract_digraph(input).unwrap(), "digraph G { a -> b }");585+
}586+
587+
#[test]588+
fn extract_from_fenced() {589+
let input = "```dot\ndigraph G { a -> b }\n```";590+
assert_eq!(extract_digraph(input).unwrap(), "digraph G { a -> b }");591+
}592+
593+
#[test]594+
fn extract_from_preamble() {595+
let input = "Looking for skills...\n<function_calls>\n</function_calls>\n\ndigraph G {\n start -> done\n}";596+
let result = extract_digraph(input).unwrap();597+
assert!(result.starts_with("digraph G {"));598+
assert!(result.ends_with('}'));599+
assert!(result.contains("start -> done"));600+
}601+
602+
#[test]603+
fn extract_nested_braces() {604+
let input = r#"digraph G {605+
subgraph cluster_0 {606+
a -> b607+
}608+
b -> c609+
}"#;610+
let result = extract_digraph(input).unwrap();611+
assert_eq!(result, input);612+
}613+
614+
#[test]615+
fn extract_from_fenced_with_preamble() {616+
let input = "Here's the pipeline:\n\n```dot\ndigraph Pipeline {\n start -> work\n work -> done\n}\n```\n\nHope that helps!";617+
let result = extract_digraph(input).unwrap();618+
assert!(result.starts_with("digraph Pipeline {"));619+
assert!(result.contains("start -> work"));620+
}621+
622+
#[test]623+
fn extract_none_when_no_digraph() {624+
assert!(extract_digraph("no graph here").is_none());625+
assert!(extract_digraph("").is_none());626+
assert!(extract_digraph("graph { a -> b }").is_none());627+
}628+
629+
#[test]630+
fn extract_with_braces_in_prompts() {631+
let input = r#"digraph G {632+
node1 [prompt="if (x) { return true; }"]633+
node1 -> done634+
}"#;635+
let result = extract_digraph(input).unwrap();636+
assert!(result.contains("node1 -> done"));637+
}638+
}pipelines/phase-1-spec.dot.bakaddedView file
Loading diffโฆ