goblin-engine 0.1.0

A high-performance async workflow engine for executing scripts in planned sequences with dependency resolution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use clap::{Parser, Subcommand};
use goblin_engine::{Engine, EngineConfig, EnginePool, Result};
use std::path::PathBuf;
use tracing::{info, error};
use tracing_subscriber::{EnvFilter, fmt::format::FmtSpan};

#[derive(Parser)]
#[command(name = "goblin")]
#[command(about = "A workflow engine for executing scripts in a planned sequence")]
#[command(version)]
struct Cli {
    /// Configuration file path
    #[arg(short, long, value_name = "FILE")]
    config: Option<PathBuf>,

    /// Scripts directory (overrides config)
    #[arg(short, long, value_name = "DIR")]
    scripts_dir: Option<PathBuf>,

    /// Plans directory (overrides config)
    #[arg(short, long, value_name = "DIR")]
    plans_dir: Option<PathBuf>,

    /// Verbose logging
    #[arg(short, long)]
    verbose: bool,

    /// Use engine pool for concurrent execution (specify pool size, default: 8)
    #[arg(long, value_name = "SIZE")]
    pool_size: Option<usize>,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize a new goblin configuration
    Init {
        /// Directory to initialize (defaults to current directory)
        #[arg(value_name = "DIR")]
        directory: Option<PathBuf>,
    },
    /// List available scripts
    Scripts,
    /// List available plans  
    Plans,
    /// Execute a single script
    RunScript {
        /// Script name to execute
        script: String,
        /// Arguments to pass to the script
        args: Vec<String>,
    },
    /// Execute a plan
    RunPlan {
        /// Plan name to execute
        plan: String,
        /// Default input to provide to the plan
        #[arg(short, long)]
        input: Option<String>,
    },
    /// Validate configuration and loaded scripts/plans
    Validate,
    /// Show engine statistics
    Stats,
    /// Generate sample configuration
    Config,
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Initialize logging
    let log_level = if cli.verbose { "debug" } else { "info" };
    let env_filter = EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| EnvFilter::new(log_level));

    tracing_subscriber::fmt()
        .with_env_filter(env_filter)
        .with_span_events(FmtSpan::CLOSE)
        .init();

    // Load configuration
    let mut config = load_config(&cli).await?;
    
    // Override config with CLI arguments
    if let Some(scripts_dir) = cli.scripts_dir {
        config.scripts_dir = Some(scripts_dir);
    }
    if let Some(plans_dir) = cli.plans_dir {
        config.plans_dir = Some(plans_dir);
    }

    // Create and configure engine
    let mut engine = Engine::new();
    if let Some(scripts_dir) = &config.scripts_dir {
        engine = engine.with_scripts_dir(scripts_dir.clone());
    }

    // Auto-discover scripts
    if config.scripts_dir.is_some() {
        match engine.auto_discover_scripts() {
            Ok(count) => info!("Discovered {} scripts", count),
            Err(e) => error!("Failed to discover scripts: {}", e),
        }
    }

    // Load plans if plans directory is specified
    if let Some(plans_dir) = &config.plans_dir {
        load_plans(&engine, plans_dir).await?;
    }

    // Create engine pool if requested
    let pool = if let Some(pool_size) = cli.pool_size {
        let size = if pool_size == 0 { 8 } else { pool_size };
        info!("Creating engine pool with {} instances", size);
        
        let pool = EnginePool::with_config(size, config.scripts_dir.clone()).await?;
        
        // Load plans on all instances if plans directory is specified
        if let Some(plans_dir) = &config.plans_dir {
            load_plans_on_pool(&pool, plans_dir).await?;
        }
        
        Some(pool)
    } else {
        None
    };

    // Execute command
    match cli.command {
        Commands::Init { directory } => {
            let target_dir = directory.unwrap_or_else(|| PathBuf::from("."));
            init_project(target_dir).await?;
        }
        Commands::Scripts => {
            list_scripts(&engine).await?;
        }
        Commands::Plans => {
            list_plans(&engine).await?;
        }
        Commands::RunScript { script, args } => {
            if let Some(pool) = &pool {
                run_script_with_pool(pool, &script, args).await?;
            } else {
                run_script(&engine, &script, args).await?;
            }
        }
        Commands::RunPlan { plan, input } => {
            if let Some(pool) = &pool {
                run_plan_with_pool(pool, &plan, input).await?;
            } else {
                run_plan(&engine, &plan, input).await?;
            }
        }
        Commands::Validate => {
            validate_engine(&engine).await?;
        }
        Commands::Stats => {
            if let Some(pool) = &pool {
                show_pool_stats(pool).await?;
            } else {
                show_stats(&engine).await?;
            }
        }
        Commands::Config => {
            generate_sample_config().await?;
        }
    }

    Ok(())
}

async fn load_config(cli: &Cli) -> Result<EngineConfig> {
    if let Some(config_path) = &cli.config {
        info!("Loading configuration from: {}", config_path.display());
        EngineConfig::from_file(config_path)
    } else {
        // Try to find goblin.toml in current directory
        let default_config = PathBuf::from("goblin.toml");
        if default_config.exists() {
            info!("Loading configuration from: {}", default_config.display());
            EngineConfig::from_file(default_config)
        } else {
            info!("Using default configuration");
            Ok(EngineConfig::default())
        }
    }
}

async fn load_plans(engine: &Engine, plans_dir: &PathBuf) -> Result<()> {
    if !plans_dir.exists() {
        error!("Plans directory does not exist: {}", plans_dir.display());
        return Ok(());
    }

    let mut loaded = 0;
    for entry in std::fs::read_dir(plans_dir)? {
        let entry = entry?;
        let path = entry.path();
        
        if path.is_file() && path.extension().map_or(false, |ext| ext == "toml") {
            match engine.load_plan(path.clone()) {
                Ok(_) => {
                    info!("Loaded plan: {}", path.file_stem().unwrap().to_string_lossy());
                    loaded += 1;
                }
                Err(e) => {
                    error!("Failed to load plan from {}: {}", path.display(), e);
                }
            }
        }
    }
    
    info!("Loaded {} plans", loaded);
    Ok(())
}

async fn init_project(target_dir: PathBuf) -> Result<()> {
    info!("Initializing goblin project in: {}", target_dir.display());
    
    // Create directories
    std::fs::create_dir_all(&target_dir)?;
    let scripts_dir = target_dir.join("scripts");
    let plans_dir = target_dir.join("plans");
    std::fs::create_dir_all(&scripts_dir)?;
    std::fs::create_dir_all(&plans_dir)?;

    // Create sample configuration
    let config_path = target_dir.join("goblin.toml");
    if !config_path.exists() {
        let sample_config = EngineConfig::sample_config();
        std::fs::write(&config_path, sample_config)?;
        info!("Created configuration file: {}", config_path.display());
    }

    // Create example script
    let example_script_dir = scripts_dir.join("example");
    std::fs::create_dir_all(&example_script_dir)?;
    
    let goblin_toml_content = r#"name = "example"
command = "echo 'Hello from Goblin!'"
timeout = 30
test_command = "echo true"
require_test = false
"#;
    
    let goblin_toml_path = example_script_dir.join("goblin.toml");
    if !goblin_toml_path.exists() {
        std::fs::write(&goblin_toml_path, goblin_toml_content)?;
        info!("Created example script: {}", goblin_toml_path.display());
    }

    // Create example plan
    let example_plan_content = r#"name = "example_plan"

[[steps]]
name = "greeting"
function = "example"
inputs = ["default_input"]
"#;
    
    let example_plan_path = plans_dir.join("example.toml");
    if !example_plan_path.exists() {
        std::fs::write(&example_plan_path, example_plan_content)?;
        info!("Created example plan: {}", example_plan_path.display());
    }

    println!("✅ Goblin project initialized successfully!");
    println!("📁 Scripts directory: {}", scripts_dir.display());
    println!("📋 Plans directory: {}", plans_dir.display());
    println!("⚙️  Configuration: {}", config_path.display());
    println!();
    println!("Try running:");
    println!("  goblin scripts");
    println!("  goblin run-plan example_plan --input 'World'");

    Ok(())
}

async fn list_scripts(engine: &Engine) -> Result<()> {
    let scripts = engine.list_scripts();
    
    if scripts.is_empty() {
        println!("No scripts found. Make sure your scripts directory is configured and contains script subdirectories with goblin.toml files.");
        return Ok(());
    }

    println!("Available scripts:");
    for script_name in scripts {
        if let Some(script) = engine.get_script(&script_name) {
            println!("  📜 {} - {}", script_name, script.command);
            if script.has_test() {
                println!("      🧪 Test: {}", script.get_test_command().unwrap_or(""));
            }
        }
    }
    
    Ok(())
}

async fn list_plans(engine: &Engine) -> Result<()> {
    let plans = engine.list_plans();
    
    if plans.is_empty() {
        println!("No plans found. Make sure your plans directory is configured and contains TOML plan files.");
        return Ok(());
    }

    println!("Available plans:");
    for plan_name in plans {
        if let Some(plan) = engine.get_plan(&plan_name) {
            println!("  📋 {} ({} steps)", plan_name, plan.steps.len());
            for step in &plan.steps {
                println!("      🔹 {} -> {}", step.name, step.function);
            }
        }
    }
    
    Ok(())
}

async fn run_script(engine: &Engine, script_name: &str, args: Vec<String>) -> Result<()> {
    info!("Executing script: {} with args: {:?}", script_name, args);
    
    let result = engine.execute_script(script_name, args).await?;
    
    println!("✅ Script '{}' completed successfully", script_name);
    println!("⏱️  Duration: {:?}", result.duration);
    
    if !result.stdout.is_empty() {
        println!("📤 Output:");
        println!("{}", result.stdout);
    }
    
    if !result.stderr.is_empty() {
        println!("⚠️  Stderr:");
        println!("{}", result.stderr);
    }
    
    Ok(())
}

async fn run_plan(engine: &Engine, plan_name: &str, input: Option<String>) -> Result<()> {
    info!("Executing plan: {} with input: {:?}", plan_name, input);
    
    let context = engine.execute_plan(plan_name, input).await?;
    
    println!("✅ Plan '{}' completed successfully", plan_name);
    println!("🆔 Execution ID: {}", context.id);
    println!("⏱️  Duration: {:?}", context.elapsed());
    
    println!("📊 Step Results:");
    for (step_name, result) in &context.results {
        if step_name != "default_input" {
            println!("  🔹 {}: {}", step_name, result);
        }
    }
    
    Ok(())
}

async fn validate_engine(engine: &Engine) -> Result<()> {
    info!("Validating engine configuration...");
    
    // Validate all plans
    match engine.validate_all_plans() {
        Ok(_) => {
            println!("✅ All plans are valid");
        }
        Err(e) => {
            println!("❌ Validation failed: {}", e);
            return Err(e);
        }
    }
    
    let (scripts_count, plans_count) = engine.get_stats();
    println!("📊 Validation complete:");
    println!("  📜 Scripts: {}", scripts_count);
    println!("  📋 Plans: {}", plans_count);
    
    Ok(())
}

async fn show_stats(engine: &Engine) -> Result<()> {
    let (scripts_count, plans_count) = engine.get_stats();
    
    println!("📊 Engine Statistics:");
    println!("  📜 Loaded Scripts: {}", scripts_count);
    println!("  📋 Loaded Plans: {}", plans_count);
    
    if scripts_count > 0 {
        println!("\n📜 Scripts:");
        for script_name in engine.list_scripts() {
            if let Some(script) = engine.get_script(&script_name) {
                println!("{} (timeout: {:?})", script_name, script.timeout);
            }
        }
    }
    
    if plans_count > 0 {
        println!("\n📋 Plans:");
        for plan_name in engine.list_plans() {
            if let Some(plan) = engine.get_plan(&plan_name) {
                println!("{} ({} steps)", plan_name, plan.steps.len());
            }
        }
    }
    
    Ok(())
}

async fn load_plans_on_pool(pool: &EnginePool, plans_dir: &PathBuf) -> Result<()> {
    if !plans_dir.exists() {
        error!("Plans directory does not exist: {}", plans_dir.display());
        return Ok(());
    }

    let mut loaded = 0;
    for entry in std::fs::read_dir(plans_dir)? {
        let entry = entry?;
        let path = entry.path();
        
        if path.is_file() && path.extension().map_or(false, |ext| ext == "toml") {
            match pool.load_plan_on_all(path.clone()).await {
                Ok(_) => {
                    info!("Loaded plan on all instances: {}", path.file_stem().unwrap().to_string_lossy());
                    loaded += 1;
                }
                Err(e) => {
                    error!("Failed to load plan from {}: {}", path.display(), e);
                }
            }
        }
    }
    
    info!("Loaded {} plans on all pool instances", loaded);
    Ok(())
}

async fn run_script_with_pool(pool: &EnginePool, script_name: &str, args: Vec<String>) -> Result<()> {
    info!("Executing script with pool: {} with args: {:?}", script_name, args);
    
    let engine_guard = pool.acquire().await?;
    let result = engine_guard.execute_script(script_name, args).await?;
    
    println!("✅ Script '{}' completed successfully (using pool)", script_name);
    println!("⏱️  Duration: {:?}", result.duration);
    
    if !result.stdout.is_empty() {
        println!("📤 Output:");
        println!("{}", result.stdout);
    }
    
    if !result.stderr.is_empty() {
        println!("⚠️  Stderr:");
        println!("{}", result.stderr);
    }
    
    Ok(())
}

async fn run_plan_with_pool(pool: &EnginePool, plan_name: &str, input: Option<String>) -> Result<()> {
    info!("Executing plan with pool: {} with input: {:?}", plan_name, input);
    
    let mut engine_guard = pool.acquire().await?;
    let context = engine_guard.execute_plan_with_reset(plan_name, input).await?;
    
    println!("✅ Plan '{}' completed successfully (using pool)", plan_name);
    println!("🆔 Execution ID: {}", context.id);
    println!("⏱️  Duration: {:?}", context.elapsed());
    
    println!("📊 Step Results:");
    for (step_name, result) in &context.results {
        if step_name != "default_input" {
            println!("  🔹 {}: {}", step_name, result);
        }
    }
    
    Ok(())
}

async fn show_pool_stats(pool: &EnginePool) -> Result<()> {
    let pool_stats = pool.get_pool_stats();
    
    println!("📊 Engine Pool Statistics:");
    println!("  🏊 Total Instances: {}", pool_stats.total_instances);
    println!("  ✅ Available Instances: {}", pool_stats.available_instances);
    println!("  ⚡ Busy Instances: {}", pool_stats.busy_instances);
    
    // Try to get stats from one instance
    if let Some(engine_guard) = pool.try_acquire()? {
        let (scripts_count, plans_count) = engine_guard.get_stats();
        
        println!("\n📊 Per-Instance Statistics:");
        println!("  📜 Scripts per instance: {}", scripts_count);
        println!("  📋 Plans per instance: {}", plans_count);
        
        if scripts_count > 0 {
            println!("\n📜 Scripts:");
            for script_name in engine_guard.list_scripts() {
                if let Some(script) = engine_guard.get_script(&script_name) {
                    println!("{} (timeout: {:?})", script_name, script.timeout);
                }
            }
        }
        
        if plans_count > 0 {
            println!("\n📋 Plans:");
            for plan_name in engine_guard.list_plans() {
                if let Some(plan) = engine_guard.get_plan(&plan_name) {
                    println!("{} ({} steps)", plan_name, plan.steps.len());
                }
            }
        }
    } else {
        println!("⚠️  All instances are busy, couldn't get detailed stats");
    }
    
    Ok(())
}

async fn generate_sample_config() -> Result<()> {
    println!("{}", EngineConfig::sample_config());
    Ok(())
}