Fully Automated - 100% Backpressure - Pipeline runner ๐Ÿƒ for AI workflows. ๐Ÿš€

Commit 9feea5a3

9feea5a36520Merged

Scott Nixon <[email protected]> ยท 9 months ago ยท 3 files ยท +1 added ยท ~2 modified

Description

[attractor-86n] Add SQLite database layer for multi-project workspace

Implements the persistence foundation for the multi-project workspace epic.

Changes:

  • Created src/server/db.rs with SQLite pool initialization
  • Implemented CRUD functions: init_db, upsert_project, list_open_projects, close_project, upsert_document, get_documents
  • Database location: ~/.attractor/web.db
  • Schema: projects table (folder_path, name, is_open) and documents table (cached content per project)
  • Added comprehensive test suite (11 tests, all passing)
  • Module gated behind #[cfg(feature = "ssr")]

Technical decisions:

  • Uses runtime-checked sqlx::query_as (not compile-time macros)
  • Idempotent schema with CREATE TABLE IF NOT EXISTS
  • Soft-close projects (is_open=0) rather than deletion

All acceptance criteria met and verified.

Details

Commit
9feea5a36520
Parent
f8003dd54305

crates/attractor-cli/src/main.rsmodifiedView file

@@ -1,625 +1,0 @@
1-//! CLI binary for running and validating Attractor pipelines.
2-
3-use std::path::PathBuf;
4-
5-use clap::{Parser, Subcommand};
6-
7-#[derive(Parser)]
8-#[command(name = "attractor", version, about = "DOT-based pipeline runner for AI workflows")]
9-struct Cli {
10- #[command(subcommand)]
11- command: Commands,
12-
13- /// Enable verbose logging
14- #[arg(short, long, global = true)]
15- verbose: bool,
16-}
17-
18-#[derive(Subcommand)]
19-enum Commands {
20- /// Run a pipeline from a .dot file
21- Run {
22- /// Path to the pipeline .dot file
23- pipeline: PathBuf,
24-
25- /// Working directory for tool execution
26- #[arg(short, long)]
27- workdir: Option<PathBuf>,
28-
29- /// Logs output directory
30- #[arg(short, long, default_value = ".attractor/logs")]
31- logs: PathBuf,
32-
33- /// Don't actually call LLMs (dry run)
34- #[arg(long)]
35- dry_run: bool,
36-
37- /// Maximum total spend across all nodes (USD). Pipeline aborts if exceeded.
38- #[arg(long)]
39- max_budget_usd: Option<f64>,
40-
41- /// Maximum number of node executions before aborting. Prevents runaway loops. Default: 200.
42- #[arg(long, default_value = "200")]
43- max_steps: u64,
44- },
45-
46- /// Validate a pipeline .dot file
47- Validate {
48- /// Path to the pipeline .dot file
49- pipeline: PathBuf,
50- },
51-
52- /// Show information about a pipeline
53- Info {
54- /// Path to the pipeline .dot file
55- pipeline: PathBuf,
56- },
57-
58- /// Generate PRD or spec documents from templates
59- Plan {
60- /// Generate a PRD document
61- #[arg(long, conflicts_with = "spec")]
62- prd: bool,
63-
64- /// Generate a spec document
65- #[arg(long, conflicts_with = "prd")]
66- spec: bool,
67-
68- /// Generate from a prompt description (uses Claude CLI)
69- #[arg(long)]
70- from_prompt: Option<String>,
71-
72- /// Output file path (defaults: .attractor/prd.md or .attractor/spec.md)
73- #[arg(short, long)]
74- output: Option<PathBuf>,
75- },
76-
77- /// Decompose a spec into beads epic and tasks
78- Decompose {
79- /// Path to the spec markdown file
80- spec_path: PathBuf,
81-
82- /// Print the generated shell commands without executing them
83- #[arg(long)]
84- dry_run: bool,
85- },
86-
87- /// Scaffold a pipeline from a beads epic
88- Scaffold {
89- /// Beads epic ID (e.g., beads-xxx)
90- epic_id: String,
91-
92- /// Output file path (default: pipelines/<epic-id>.dot)
93- #[arg(short, long)]
94- output: Option<PathBuf>,
95- },
96-}
97-
98-#[tokio::main]
99-async fn main() -> anyhow::Result<()> {
100- let cli = Cli::parse();
101-
102- // Setup tracing
103- let filter = if cli.verbose { "debug" } else { "info" };
104- tracing_subscriber::fmt()
105- .with_env_filter(filter)
106- .init();
107-
108- match cli.command {
109- Commands::Run {
110- pipeline,
111- workdir,
112- logs,
113- dry_run,
114- max_budget_usd,
115- max_steps,
116- } => {
117- cmd_run(&pipeline, workdir.as_deref(), &logs, dry_run, max_budget_usd, max_steps).await?;
118- }
119- Commands::Validate { pipeline } => {
120- cmd_validate(&pipeline)?;
121- }
122- Commands::Info { pipeline } => {
123- cmd_info(&pipeline)?;
124- }
125- Commands::Plan { prd, spec, from_prompt, output } => {
126- cmd_plan(prd, spec, from_prompt.as_deref(), output.as_deref()).await?;
127- }
128- Commands::Decompose { spec_path, dry_run } => {
129- cmd_decompose(&spec_path, dry_run).await?;
130- }
131- Commands::Scaffold { epic_id, output } => {
132- cmd_scaffold(&epic_id, output.as_deref()).await?;
133- }
134- }
135-
136- Ok(())
137-}
138-
139-fn load_pipeline(path: &std::path::Path) -> anyhow::Result<attractor_pipeline::PipelineGraph> {
140- let source = std::fs::read_to_string(path)?;
141- let dot = attractor_dot::parse(&source)?;
142- let graph = attractor_pipeline::PipelineGraph::from_dot(dot)?;
143- Ok(graph)
144-}
145-
146-fn cmd_validate(path: &std::path::Path) -> anyhow::Result<()> {
147- let graph = load_pipeline(path)?;
148- let diagnostics = attractor_pipeline::validate(&graph);
149-
150- if diagnostics.is_empty() {
151- println!("Pipeline is valid");
152- return Ok(());
153- }
154-
155- let mut has_error = false;
156- for diag in &diagnostics {
157- let severity = match diag.severity {
158- attractor_pipeline::Severity::Error => {
159- has_error = true;
160- "ERROR"
161- }
162- attractor_pipeline::Severity::Warning => "WARN",
163- attractor_pipeline::Severity::Info => "INFO",
164- };
165- println!("[{}] {}: {}", severity, diag.rule, diag.message);
166- }
167-
168- if has_error {
169- std::process::exit(1);
170- }
171- Ok(())
172-}
173-
174-fn cmd_info(path: &std::path::Path) -> anyhow::Result<()> {
175- let graph = load_pipeline(path)?;
176-
177- println!("Pipeline: {}", graph.name);
178- if !graph.goal.is_empty() {
179- println!("Goal: {}", graph.goal);
180- }
181-
182- let node_count = graph.all_nodes().count();
183- let edge_count = graph.all_edges().len();
184- println!("Nodes: {}", node_count);
185- println!("Edges: {}", edge_count);
186-
187- if let Some(start) = graph.start_node() {
188- println!("Start: {} ({})", start.id, start.label);
189- }
190- if let Some(exit) = graph.exit_node() {
191- println!("Exit: {} ({})", exit.id, exit.label);
192- }
193-
194- // List nodes with their types
195- println!("\nNodes:");
196- for node in graph.all_nodes() {
197- let node_type = node.node_type.as_deref().unwrap_or("(default)");
198- println!(
199- " {} [{}] shape={} type={}",
200- node.id, node.label, node.shape, node_type
201- );
202- }
203-
204- Ok(())
205-}
206-
207-async fn cmd_run(
208- path: &std::path::Path,
209- workdir: Option<&std::path::Path>,
210- _logs: &std::path::Path,
211- dry_run: bool,
212- max_budget_usd: Option<f64>,
213- max_steps: u64,
214-) -> anyhow::Result<()> {
215- let graph = load_pipeline(path)?;
216-
217- println!("Running pipeline: {}", graph.name);
218- if !graph.goal.is_empty() {
219- println!("Goal: {}", graph.goal);
220- }
221- if dry_run {
222- println!("(dry run mode -- no LLM calls)");
223- }
224-
225- // Set up the pipeline context with workdir
226- let context = attractor_types::Context::new();
227- if let Some(dir) = workdir {
228- let abs = std::fs::canonicalize(dir)?;
229- context
230- .set(
231- "workdir",
232- serde_json::Value::String(abs.to_string_lossy().into_owned()),
233- )
234- .await;
235- println!("Working directory: {}", abs.display());
236- }
237- if dry_run {
238- context
239- .set("dry_run", serde_json::Value::Bool(true))
240- .await;
241- }
242-
243- // Safety limits
244- if let Some(budget) = max_budget_usd {
245- context
246- .set("max_budget_usd", serde_json::json!(budget))
247- .await;
248- println!("Budget limit: ${:.2}", budget);
249- }
250- context
251- .set("max_steps", serde_json::json!(max_steps))
252- .await;
253- println!("Step limit: {}", max_steps);
254-
255- let interviewer = std::sync::Arc::new(attractor_pipeline::ConsoleInterviewer);
256- let registry =
257- attractor_pipeline::default_registry_with_interviewer(interviewer);
258- let executor = attractor_pipeline::PipelineExecutor::new(registry);
259- let result = executor.run_with_context(&graph, context).await?;
260-
261- println!("\nPipeline completed");
262- println!("Completed nodes: {:?}", result.completed_nodes);
263-
264- // Print cost summary
265- let total_cost: f64 = result
266- .final_context
267- .iter()
268- .filter(|(k, _)| k.ends_with(".cost_usd"))
269- .filter_map(|(_, v)| v.as_f64())
270- .sum();
271- if total_cost > 0.0 {
272- println!("Total cost: ${:.4}", total_cost);
273- }
274-
275- Ok(())
276-}
277-
278-async fn cmd_plan(
279- prd: bool,
280- spec: bool,
281- from_prompt: Option<&str>,
282- output: Option<&std::path::Path>,
283-) -> anyhow::Result<()> {
284- // Validate: exactly one of --prd or --spec must be true
285- if !prd && !spec {
286- anyhow::bail!("Must specify either --prd or --spec");
287- }
288-
289- // Determine template and default output path
290- let (template_content, default_output) = if prd {
291- (
292- include_str!("../../../templates/prd-template.md"),
293- std::path::Path::new(".attractor/prd.md"),
294- )
295- } else {
296- (
297- include_str!("../../../templates/spec-template.md"),
298- std::path::Path::new(".attractor/spec.md"),
299- )
300- };
301-
302- let output_path = output.unwrap_or(default_output);
303-
304- if let Some(prompt_desc) = from_prompt {
305- // AI mode: Use Claude CLI to generate document
306- generate_with_claude(prompt_desc, template_content, output_path, prd).await?;
307- } else {
308- // Simple mode: Copy template to output
309- copy_template(template_content, output_path)?;
310- }
311-
312- // Print success message
313- println!("Created {} at {}", if prd { "PRD" } else { "spec" }, output_path.display());
314-
315- if from_prompt.is_none() {
316- println!("\nNext steps:");
317- println!("1. Edit {} to fill in your details", output_path.display());
318- println!("2. Replace all [bracketed placeholders] with actual content");
319- if prd {
320- println!("3. Create a beads epic: bd create --type=epic");
321- println!("4. Link the epic ID in the metadata section");
322- } else {
323- println!("3. Create beads tasks: bd decompose {}", output_path.display());
324- }
325- }
326-
327- Ok(())
328-}
329-
330-fn copy_template(content: &str, output: &std::path::Path) -> anyhow::Result<()> {
331- // Create parent directory if it doesn't exist
332- if let Some(parent) = output.parent() {
333- std::fs::create_dir_all(parent)?;
334- }
335- std::fs::write(output, content)?;
336- Ok(())
337-}
338-
339-async fn generate_with_claude(
340- description: &str,
341- template: &str,
342- output: &std::path::Path,
343- is_prd: bool,
344-) -> anyhow::Result<()> {
345- let doc_type = if is_prd { "PRD" } else { "Technical Specification" };
346-
347- // Build prompt for Claude
348- let prompt = format!(
349- "Generate a {} document following this exact template format:\n\n{}\n\n\
350- User request: {}\n\n\
351- Instructions:\n\
352- 1. Replace all [bracketed placeholders] with content based on the user request\n\
353- 2. Keep the exact section structure from the template\n\
354- 3. Fill in Status: Draft, Author: Claude, Created: {} (today's date)\n\
355- 4. Write concrete, specific content - no placeholder text or [brackets]\n\
356- 5. Output ONLY the markdown document, no explanations or commentary\n\
357- 6. If the user request is vague, make reasonable assumptions and document them",
358- doc_type,
359- template,
360- description,
361- chrono::Utc::now().format("%Y-%m-%d")
362- );
363-
364- // Shell out to claude CLI
365- let mut cmd = tokio::process::Command::new("claude");
366- cmd.arg("-p")
367- .arg(&prompt)
368- .arg("--dangerously-skip-permissions")
369- .arg("--no-session-persistence");
370-
371- // Capture output
372- cmd.stdout(std::process::Stdio::piped());
373- cmd.stderr(std::process::Stdio::piped());
374-
375- let output_result = cmd.output().await?;
376-
377- if !output_result.status.success() {
378- let stderr = String::from_utf8_lossy(&output_result.stderr);
379- anyhow::bail!("Claude CLI failed: {}", stderr);
380- }
381-
382- let generated_content = String::from_utf8(output_result.stdout)?;
383-
384- // Create parent directory if needed
385- if let Some(parent) = output.parent() {
386- std::fs::create_dir_all(parent)?;
387- }
388-
389- // Write generated content
390- std::fs::write(output, generated_content)?;
391-
392- Ok(())
393-}
394-
395-async fn cmd_decompose(spec_path: &std::path::Path, dry_run: bool) -> anyhow::Result<()> {
396- // Read the spec file
397- let spec_content = std::fs::read_to_string(spec_path)?;
398-
399- // Build prompt for Claude to generate bd commands
400- let prompt = format!(
401- "Read this technical specification and generate a shell script of beads (bd) CLI commands to create an epic and tasks.\n\n\
402- SPEC:\n{}\n\n\
403- INSTRUCTIONS:\n\
404- 1. Extract the title from the spec (usually in the first heading)\n\
405- 2. Extract implementation phases/tasks from the '## Implementation Phases' or similar section\n\
406- 3. Create an epic first: EPIC_ID=$(bd create --title='TITLE' --type=epic --priority=P1 --description='OVERVIEW' --silent)\n\
407- 4. For each task/phase: TASK_N=$(bd create --title='TITLE' --type=task --priority=PN --description='DESC' --silent)\n\
408- 5. Add dependencies using: bd dep add $BLOCKED_TASK $BLOCKER_TASK (the blocked task depends on the blocker)\n\
409- 6. Output ONLY executable shell commands - no markdown code fences (```), no explanations, no commentary\n\
410- 7. Use set -e at the start so it fails fast on errors\n\
411- 8. Echo the epic ID at the end: echo $EPIC_ID\n\
412- 9. Priority should be P2 for most tasks unless critical (P1) or backlog (P3/P4)\n\
413- 10. Task descriptions should be 1-2 sentences summarizing what needs to be done\n\
414- 11. CRITICAL: Do NOT wrap output in markdown code fences. Start directly with 'set -e'",
415- spec_content
416- );
417-
418- // Call Claude CLI with JSON output format
419- let mut cmd = tokio::process::Command::new("claude");
420- cmd.arg("-p")
421- .arg(&prompt)
422- .arg("--output-format")
423- .arg("json")
424- .arg("--dangerously-skip-permissions")
425- .arg("--no-session-persistence");
426-
427- // Capture output
428- cmd.stdout(std::process::Stdio::piped());
429- cmd.stderr(std::process::Stdio::piped());
430-
431- let output_result = cmd.output().await?;
432-
433- if !output_result.status.success() {
434- let stderr = String::from_utf8_lossy(&output_result.stderr);
435- anyhow::bail!("Claude CLI failed: {}", stderr);
436- }
437-
438- let output_json = String::from_utf8(output_result.stdout)?;
439- let parsed: serde_json::Value = serde_json::from_str(&output_json)?;
440-
441- let mut shell_commands = parsed["result"]
442- .as_str()
443- .ok_or_else(|| anyhow::anyhow!("Claude output missing 'result' field"))?
444- .to_string();
445-
446- // Strip markdown code fences if present
447- if shell_commands.starts_with("```") {
448- let lines: Vec<&str> = shell_commands.lines().collect();
449- if lines.len() > 2 && lines[0].starts_with("```") && lines[lines.len() - 1] == "```" {
450- shell_commands = lines[1..lines.len() - 1].join("\n");
451- }
452- }
453-
454- // Prepend shebang (and set -e if not already present)
455- let full_script = if shell_commands.starts_with("set -e") {
456- format!("#!/bin/sh\n{}", shell_commands)
457- } else {
458- format!("#!/bin/sh\nset -e\n\n{}", shell_commands)
459- };
460-
461- if dry_run {
462- println!("Generated shell commands (dry run):\n");
463- println!("{}", full_script);
464- return Ok(());
465- }
466-
467- // Execute the shell script
468- let temp_script = std::env::temp_dir().join("attractor-decompose.sh");
469- std::fs::write(&temp_script, &full_script)?;
470-
471- // Make executable
472- #[cfg(unix)]
473- {
474- use std::os::unix::fs::PermissionsExt;
475- let mut perms = std::fs::metadata(&temp_script)?.permissions();
476- perms.set_mode(0o755);
477- std::fs::set_permissions(&temp_script, perms)?;
478- }
479-
480- // Execute with sh -e
481- let exec_result = tokio::process::Command::new("sh")
482- .arg("-e")
483- .arg(&temp_script)
484- .output()
485- .await?;
486-
487- // Clean up temp file
488- std::fs::remove_file(&temp_script).ok();
489-
490- if !exec_result.status.success() {
491- let stderr = String::from_utf8_lossy(&exec_result.stderr);
492- anyhow::bail!("Shell script execution failed: {}", stderr);
493- }
494-
495- let output_text = String::from_utf8(exec_result.stdout)?;
496-
497- // Extract epic ID from last line of output
498- let epic_id = output_text
499- .lines()
500- .last()
501- .unwrap_or("")
502- .trim();
503-
504- // Count tasks created (number of lines with TASK_N=)
505- let task_count = shell_commands.matches("TASK_").count();
506-
507- // Count dependencies (number of bd dep add lines)
508- let dep_count = shell_commands.matches("bd dep add").count();
509-
510- println!("โœ“ Decomposition complete");
511- println!(" Epic ID: {}", epic_id);
512- println!(" Tasks created: {}", task_count);
513- println!(" Dependencies: {}", dep_count);
514- println!("\nNext steps:");
515- println!("1. Review tasks: bd list");
516- println!("2. Generate pipeline: attractor scaffold {}", epic_id);
517-
518- Ok(())
519-}
520-
521-async fn cmd_scaffold(epic_id: &str, output: Option<&std::path::Path>) -> anyhow::Result<()> {
522- // Load epic-runner template
523- let template = include_str!("../../../templates/epic-runner.dot");
524-
525- // Get epic details via bd show --json
526- let mut cmd = tokio::process::Command::new("bd");
527- cmd.arg("show")
528- .arg(epic_id)
529- .arg("--json");
530-
531- cmd.stdout(std::process::Stdio::piped());
532- cmd.stderr(std::process::Stdio::piped());
533-
534- let output_result = cmd.output().await?;
535-
536- if !output_result.status.success() {
537- let stderr = String::from_utf8_lossy(&output_result.stderr);
538- anyhow::bail!("bd show failed: {}", stderr);
539- }
540-
541- let json_output = String::from_utf8(output_result.stdout)?;
542- let epic_array: serde_json::Value = serde_json::from_str(&json_output)?;
543-
544- // bd show --json returns an array with one element
545- let epic_data = epic_array
546- .as_array()
547- .and_then(|arr| arr.first())
548- .ok_or_else(|| anyhow::anyhow!("bd show returned empty array"))?;
549-
550- let title = epic_data["title"]
551- .as_str()
552- .unwrap_or("Unknown Epic");
553- let description = epic_data["description"]
554- .as_str()
555- .unwrap_or("");
556-
557- // First, update the goal attribute BEFORE replacing EPIC_ID
558- let goal_text = format!(
559- "Implement all child tasks of epic {}: {}.{}",
560- epic_id,
561- title,
562- if description.is_empty() {
563- String::new()
564- } else {
565- format!(" {}", description)
566- }
567- );
568-
569- let mut pipeline_content = template.replace(
570- "goal=\"Implement all child tasks of epic EPIC_ID, closing each as completed.\"",
571- &format!("goal=\"{}\"", goal_text.replace('"', "\\\""))
572- );
573-
574- // Then replace all remaining EPIC_ID placeholders
575- pipeline_content = pipeline_content.replace("EPIC_ID", epic_id);
576-
577- // Determine output path
578- let output_path = if let Some(path) = output {
579- path.to_path_buf()
580- } else {
581- std::path::PathBuf::from(format!("pipelines/{}.dot", epic_id))
582- };
583-
584- // Create parent directory if needed
585- if let Some(parent) = output_path.parent() {
586- std::fs::create_dir_all(parent)?;
587- }
588-
589- // Write pipeline file
590- std::fs::write(&output_path, &pipeline_content)?;
591-
592- // Validate the generated pipeline
593- let graph = load_pipeline(&output_path)?;
594- let diagnostics = attractor_pipeline::validate(&graph);
595-
596- let has_error = diagnostics.iter().any(|d| {
597- matches!(d.severity, attractor_pipeline::Severity::Error)
598- });
599-
600- if has_error {
601- println!("โš  Pipeline generated but has validation errors:");
602- for diag in &diagnostics {
603- if matches!(diag.severity, attractor_pipeline::Severity::Error) {
604- println!(" [ERROR] {}: {}", diag.rule, diag.message);
605- }
606- }
607- }
608-
609- // Count nodes
610- let node_count = graph.all_nodes().count();
611-
612- println!("โœ“ Pipeline scaffolded");
613- println!(" Output: {}", output_path.display());
614- println!(" Epic: {} ({})", epic_id, title);
615- println!(" Nodes: {}", node_count);
616- println!(" Validation: {}", if has_error { "FAILED" } else { "PASSED" });
617-
618- if !has_error {
619- println!("\nNext steps:");
620- println!("1. Review pipeline: cat {}", output_path.display());
621- println!("2. Run pipeline: attractor run {} -w .", output_path.display());
622- }
623-
624- Ok(())
625-}