jorm 0.1.1

A lightweight DAG execution engine with natural language processing
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
#![allow(clippy::uninlined_format_args)]

use clap::{Parser, Subcommand};
use jorm::scheduler::{Daemon, Schedule};
use jorm::server::http::HttpServer;
use jorm::{DagParser, JormEngine, Result, TaskType};
use std::path::PathBuf;
use std::process;
use std::sync::Arc;

#[derive(Parser)]
#[command(name = "jorm")]
#[command(about = "A simplified DAG execution engine")]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Execute a DAG from a file
    Execute {
        /// Path to the DAG file
        #[arg(short, long)]
        file: PathBuf,
    },
    /// Generate and execute a DAG from natural language
    Generate {
        /// Natural language description of the workflow
        #[arg(short, long)]
        description: String,
        /// Preview the generated DAG without executing
        #[arg(short, long)]
        preview: bool,
    },
    /// Validate a DAG file syntax
    Validate {
        /// Path to the DAG file to validate
        #[arg(short, long)]
        file: PathBuf,
    },
    /// Start the HTTP server
    Server {
        /// Port to listen on
        #[arg(short, long, default_value = "8080")]
        port: u16,
        /// Authentication token (can also be set via JORM_AUTH_TOKEN env var)
        #[arg(short, long)]
        auth_token: Option<String>,
    },
    /// Daemon operations
    Daemon {
        #[command(subcommand)]
        action: DaemonAction,
    },
}

#[derive(Subcommand)]
enum DaemonAction {
    /// Start the daemon
    Start {
        /// State file for daemon persistence
        #[arg(long, default_value = ".jorm/daemon.state")]
        state_file: PathBuf,
        /// Schedules configuration file
        #[arg(short, long)]
        schedules: Option<PathBuf>,
        /// Log file for daemon output
        #[arg(short, long)]
        log_file: Option<PathBuf>,
    },
    /// Stop the daemon
    Stop {
        /// State file for daemon persistence
        #[arg(long, default_value = ".jorm/daemon.state")]
        state_file: PathBuf,
    },
    /// Check daemon status
    Status {
        /// State file for daemon persistence
        #[arg(long, default_value = ".jorm/daemon.state")]
        state_file: PathBuf,
    },
    /// Add a schedule to the daemon
    AddSchedule {
        /// Schedule ID
        #[arg(short, long)]
        id: String,
        /// Cron expression
        #[arg(short, long)]
        cron: String,
        /// DAG file to execute
        #[arg(short, long)]
        dag_file: PathBuf,
        /// State file for daemon persistence
        #[arg(long, default_value = ".jorm/daemon.state")]
        state_file: PathBuf,
    },
    /// Remove a schedule from the daemon
    RemoveSchedule {
        /// Schedule ID to remove
        #[arg(short, long)]
        id: String,
        /// State file for daemon persistence
        #[arg(long, default_value = ".jorm/daemon.state")]
        state_file: PathBuf,
    },
    /// List all schedules
    ListSchedules {
        /// State file for daemon persistence
        #[arg(long, default_value = ".jorm/daemon.state")]
        state_file: PathBuf,
    },
}

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

    let exit_code = match run_command(cli).await {
        Ok(code) => code,
        Err(e) => {
            eprintln!("Error: {}", e);
            1
        }
    };

    process::exit(exit_code);
}

async fn run_command(cli: Cli) -> Result<i32> {
    match cli.command {
        Commands::Execute { file } => execute_dag_file(file).await,
        Commands::Generate {
            description,
            preview,
        } => generate_dag(description, preview).await,
        Commands::Validate { file } => validate_dag_file(file).await,
        Commands::Server { port, auth_token } => start_http_server(port, auth_token).await,
        Commands::Daemon { action } => handle_daemon_action(action).await,
    }
}

async fn execute_dag_file(file: PathBuf) -> Result<i32> {
    println!("🚀 Executing DAG file: {}", file.display());

    let engine = JormEngine::new().await?;
    let file_path = file
        .to_str()
        .ok_or_else(|| jorm::JormError::FileError("Invalid file path".to_string()))?;

    match engine.execute_from_file(file_path).await {
        Ok(result) => {
            if result.success {
                println!("✅ Execution completed successfully!");
                println!("📊 Results:");
                for task_result in &result.task_results {
                    if task_result.success {
                        println!("{}: {}", task_result.task_name, task_result.output);
                    } else {
                        println!(
                            "{}: {}",
                            task_result.task_name,
                            task_result
                                .error
                                .as_ref()
                                .unwrap_or(&"Unknown error".to_string())
                        );
                    }
                }
                Ok(0)
            } else {
                println!("❌ Execution failed: {}", result.message);
                println!("📊 Results:");
                for task_result in &result.task_results {
                    if task_result.success {
                        println!("{}: {}", task_result.task_name, task_result.output);
                    } else {
                        println!(
                            "{}: {}",
                            task_result.task_name,
                            task_result
                                .error
                                .as_ref()
                                .unwrap_or(&"Unknown error".to_string())
                        );
                    }
                }
                Ok(1)
            }
        }
        Err(e) => {
            println!("❌ Failed to execute DAG: {}", e);
            Ok(1)
        }
    }
}

async fn generate_dag(description: String, preview: bool) -> Result<i32> {
    println!("🤖 Generating DAG from natural language...");
    println!("📝 Description: {}", description);

    let engine = JormEngine::new().await?;

    if preview {
        match engine.generate_dag_from_nl(&description).await {
            Ok(dag_content) => {
                println!("✅ Generated DAG preview:");
                println!("─────────────────────────────────────");
                println!("{}", dag_content);
                println!("─────────────────────────────────────");
                println!("💡 Use without --preview flag to execute directly");
                Ok(0)
            }
            Err(e) => {
                println!("❌ Failed to generate DAG: {}", e);
                Ok(1)
            }
        }
    } else {
        match engine.execute_from_natural_language(&description).await {
            Ok(result) => {
                if result.success {
                    println!("✅ Generation and execution completed successfully!");
                    println!("📊 Results:");
                    for task_result in &result.task_results {
                        if task_result.success {
                            println!("{}: {}", task_result.task_name, task_result.output);
                        } else {
                            println!(
                                "{}: {}",
                                task_result.task_name,
                                task_result
                                    .error
                                    .as_ref()
                                    .unwrap_or(&"Unknown error".to_string())
                            );
                        }
                    }
                    Ok(0)
                } else {
                    println!("❌ Execution failed: {}", result.message);
                    println!("📊 Results:");
                    for task_result in &result.task_results {
                        if task_result.success {
                            println!("{}: {}", task_result.task_name, task_result.output);
                        } else {
                            println!(
                                "{}: {}",
                                task_result.task_name,
                                task_result
                                    .error
                                    .as_ref()
                                    .unwrap_or(&"Unknown error".to_string())
                            );
                        }
                    }
                    Ok(1)
                }
            }
            Err(e) => {
                println!("❌ Failed to generate and execute DAG: {}", e);
                Ok(1)
            }
        }
    }
}

async fn validate_dag_file(file: PathBuf) -> Result<i32> {
    println!("🔍 Validating DAG file: {}", file.display());

    let parser = DagParser::new();
    let file_path = file
        .to_str()
        .ok_or_else(|| jorm::JormError::FileError("Invalid file path".to_string()))?;

    match parser.parse_file(file_path).await {
        Ok(dag) => {
            match dag.validate() {
                Ok(_) => {
                    println!("✅ DAG file is valid!");
                    println!("📊 Summary:");
                    println!("  📝 DAG name: {}", dag.name);
                    println!("  🔢 Total tasks: {}", dag.tasks.len());
                    println!("  🔗 Dependencies: {}", dag.dependencies.len());

                    // Show task types summary
                    let mut task_types = std::collections::HashMap::new();
                    for task in dag.tasks.values() {
                        let task_type = match &task.task_type {
                            TaskType::Shell { .. } => "Shell",
                            TaskType::Http { .. } => "HTTP",
                            TaskType::Python { .. } => "Python",
                            TaskType::Rust { .. } => "Rust",
                            TaskType::FileCopy { .. } => "File Copy",
                            TaskType::FileMove { .. } => "File Move",
                            TaskType::FileDelete { .. } => "File Delete",
                            TaskType::Jorm { .. } => "Jorm",
                        };
                        *task_types.entry(task_type).or_insert(0) += 1;
                    }

                    println!("  📋 Task types:");
                    for (task_type, count) in task_types {
                        println!("    - {}: {}", task_type, count);
                    }

                    Ok(0)
                }
                Err(e) => {
                    println!("❌ DAG validation failed: {}", e);
                    Ok(1)
                }
            }
        }
        Err(e) => {
            println!("❌ Failed to parse DAG file: {}", e);
            Ok(1)
        }
    }
}

async fn start_http_server(port: u16, auth_token: Option<String>) -> Result<i32> {
    println!("🌐 Starting HTTP server on port {}", port);

    let engine = Arc::new(JormEngine::new().await?);
    let server = if let Some(token) = auth_token {
        HttpServer::with_auth_token(engine, port, token)
    } else {
        HttpServer::new(engine, port)
    };

    match server.start().await {
        Ok(_) => {
            println!("✅ HTTP server started successfully");
            Ok(0)
        }
        Err(e) => {
            println!("❌ Failed to start HTTP server: {}", e);
            Ok(1)
        }
    }
}

async fn handle_daemon_action(action: DaemonAction) -> Result<i32> {
    match action {
        DaemonAction::Start {
            state_file,
            schedules,
            log_file,
        } => {
            println!("🚀 Starting Jorm daemon...");

            let engine = Arc::new(JormEngine::new().await?);
            let mut daemon = Daemon::new(engine, state_file, schedules, log_file);

            match daemon.start().await {
                Ok(_) => {
                    println!("✅ Daemon stopped gracefully");
                    Ok(0)
                }
                Err(e) => {
                    println!("❌ Daemon error: {}", e);
                    Ok(1)
                }
            }
        }
        DaemonAction::Stop { state_file } => {
            println!("🛑 Stopping Jorm daemon...");

            let engine = Arc::new(JormEngine::new().await?);
            let mut daemon = Daemon::new(engine, state_file, None, None);

            match daemon.stop().await {
                Ok(_) => {
                    println!("✅ Daemon stopped successfully");
                    Ok(0)
                }
                Err(e) => {
                    println!("❌ Failed to stop daemon: {}", e);
                    Ok(1)
                }
            }
        }
        DaemonAction::Status { state_file } => {
            let engine = Arc::new(JormEngine::new().await?);
            let daemon = Daemon::new(engine, state_file, None, None);

            match daemon.status().await {
                Ok(state) => {
                    if let Some(pid) = state.pid {
                        println!("✅ Daemon is running (PID: {})", pid);
                        if let Some(started_at) = state.started_at {
                            println!(
                                "   Started at: {}",
                                started_at.format("%Y-%m-%d %H:%M:%S UTC")
                            );
                        }
                        if let Some(schedules_file) = state.schedules_file {
                            println!("   Schedules file: {}", schedules_file);
                        }
                        if let Some(log_file) = state.log_file {
                            println!("   Log file: {}", log_file);
                        }
                    } else {
                        println!("❌ Daemon is not running");
                    }
                    Ok(0)
                }
                Err(e) => {
                    println!("❌ Failed to get daemon status: {}", e);
                    Ok(1)
                }
            }
        }
        DaemonAction::AddSchedule {
            id,
            cron,
            dag_file,
            state_file,
        } => {
            println!("📅 Adding schedule: {} -> {}", id, dag_file.display());

            let dag_file_str = dag_file
                .to_str()
                .ok_or_else(|| jorm::JormError::FileError("Invalid DAG file path".to_string()))?;

            match Schedule::new(id.clone(), cron, dag_file_str.to_string()) {
                Ok(schedule) => {
                    let engine = Arc::new(JormEngine::new().await?);
                    let mut daemon = Daemon::new(engine, state_file, None, None);

                    match daemon.add_schedule(schedule).await {
                        Ok(_) => {
                            println!("✅ Schedule '{}' added successfully", id);
                            Ok(0)
                        }
                        Err(e) => {
                            println!("❌ Failed to add schedule: {}", e);
                            Ok(1)
                        }
                    }
                }
                Err(e) => {
                    println!("❌ Invalid schedule: {}", e);
                    Ok(1)
                }
            }
        }
        DaemonAction::RemoveSchedule { id, state_file } => {
            println!("🗑️ Removing schedule: {}", id);

            let engine = Arc::new(JormEngine::new().await?);
            let mut daemon = Daemon::new(engine, state_file, None, None);

            match daemon.remove_schedule(&id).await {
                Ok(_) => {
                    println!("✅ Schedule '{}' removed successfully", id);
                    Ok(0)
                }
                Err(e) => {
                    println!("❌ Failed to remove schedule: {}", e);
                    Ok(1)
                }
            }
        }
        DaemonAction::ListSchedules { state_file } => {
            let engine = Arc::new(JormEngine::new().await?);
            let daemon = Daemon::new(engine, state_file, None, None);

            let schedules = daemon.list_schedules();

            if schedules.is_empty() {
                println!("📅 No schedules configured");
            } else {
                println!("📅 Configured schedules:");
                for schedule in schedules {
                    let status = if schedule.enabled {
                        "✅ Enabled"
                    } else {
                        "❌ Disabled"
                    };
                    println!("  {} [{}]", schedule.id, status);
                    println!("    Cron: {}", schedule.cron_expression);
                    println!("    DAG: {}", schedule.dag_file);
                    if let Some(last) = schedule.last_execution {
                        println!(
                            "    Last execution: {}",
                            last.format("%Y-%m-%d %H:%M:%S UTC")
                        );
                    }
                    if let Some(next) = schedule.next_execution {
                        println!(
                            "    Next execution: {}",
                            next.format("%Y-%m-%d %H:%M:%S UTC")
                        );
                    }
                    println!();
                }
            }

            Ok(0)
        }
    }
}