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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Workflow management subcommand handler
use clap::Subcommand;
use std::path::PathBuf;
use colored::Colorize;
use nika::ast::parse_workflow;
use nika::error::NikaError;
/// Workflow management actions
#[derive(Subcommand)]
pub enum WorkflowAction {
/// Open workflow in interactive editor
Edit {
/// Path to .nika.yaml file
file: PathBuf,
},
/// Add a new task interactively
AddTask {
/// Path to .nika.yaml file
file: PathBuf,
/// Task ID (generated if not provided)
#[arg(long)]
id: Option<String>,
/// Task verb (infer, exec, fetch, invoke, agent)
#[arg(long, value_name = "VERB")]
verb: Option<String>,
/// Insert after this task ID
#[arg(long)]
after: Option<String>,
},
/// Visualize workflow as DAG graph
Graph {
/// Path to .nika.yaml file
file: PathBuf,
/// Output format: ascii, dot, mermaid
#[arg(short, long, default_value = "ascii")]
format: String,
/// Output file (stdout if not specified)
#[arg(short, long)]
output: Option<PathBuf>,
},
/// Validate workflow with suggestions for improvements
Check {
/// Path to .nika.yaml file
file: PathBuf,
/// Show improvement suggestions
#[arg(long)]
suggest: bool,
/// Output format: text, json
#[arg(long, default_value = "text")]
format: String,
},
}
pub async fn handle_workflow_command(action: WorkflowAction, quiet: bool) -> Result<(), NikaError> {
match action {
WorkflowAction::Edit { file } => {
// Open workflow in Studio editor
#[cfg(feature = "tui")]
{
if !quiet {
println!(
"{} Opening {} in Studio editor...",
"→".cyan(),
file.display()
);
}
nika::tui::run_tui_studio(Some(file)).await
}
#[cfg(not(feature = "tui"))]
{
let _ = (file, quiet); // Suppress unused warnings
Err(NikaError::ConfigError {
reason: "TUI feature not enabled. Rebuild with `--features tui`".to_string(),
})
}
}
WorkflowAction::AddTask {
file,
id,
verb,
after,
} => {
// Validate file exists
if !file.exists() {
return Err(NikaError::WorkflowNotFound {
path: file.to_string_lossy().to_string(),
});
}
// Read existing workflow
let content = std::fs::read_to_string(&file)?;
// Generate task ID if not provided
let task_id = id.unwrap_or_else(|| {
format!("task_{}", chrono::Utc::now().timestamp_millis() % 10000)
});
// Default verb is infer
let task_verb = verb.unwrap_or_else(|| "infer".to_string());
// Build the new task YAML
let new_task = match task_verb.as_str() {
"infer" => format!(
r#" - id: {}
infer: "TODO: Add your prompt here"
"#,
task_id
),
"exec" => format!(
r#" - id: {}
exec: "echo 'TODO: Add your command here'"
"#,
task_id
),
"fetch" => format!(
r#" - id: {}
fetch:
url: "https://example.com/api"
method: GET
"#,
task_id
),
"invoke" => format!(
r#" - id: {}
invoke:
mcp: novanet
tool: novanet_context
params: {{}}
"#,
task_id
),
"agent" => format!(
r#" - id: {}
agent:
prompt: "TODO: Add your agent prompt here"
max_turns: 5
"#,
task_id
),
_ => {
return Err(NikaError::ValidationError {
reason: format!(
"Unknown verb '{}'. Valid: infer, exec, fetch, invoke, agent",
task_verb
),
});
}
};
// Find insertion point
let mut lines: Vec<&str> = content.lines().collect();
let mut insert_index = None;
// Find tasks: section and optionally the task to insert after
let mut in_tasks = false;
let mut after_task_end = None;
for (i, line) in lines.iter().enumerate() {
if line.trim() == "tasks:" {
in_tasks = true;
continue;
}
if in_tasks {
// Check if this is a task start (- id:)
if line.trim().starts_with("- id:") {
// Check if this is the task we want to insert after
if let Some(ref after_id) = after {
if line.contains(after_id) {
// Mark that we found the after task
after_task_end = Some(i);
} else if after_task_end.is_some() {
// We've found the next task after our target
insert_index = Some(i);
break;
}
}
}
// Check for top-level sections (context:, mcp:, etc.)
if !line.starts_with(' ') && !line.starts_with('-') && line.contains(':') {
insert_index = Some(i);
break;
}
}
}
// If no insert point found, append at end of tasks
let insert_at = insert_index.unwrap_or(lines.len());
// Insert the new task
let new_task_lines: Vec<&str> = new_task.lines().collect();
for (j, task_line) in new_task_lines.iter().enumerate() {
lines.insert(insert_at + j, task_line);
}
// Write back
let new_content = lines.join("\n");
std::fs::write(&file, new_content)?;
if !quiet {
println!(
"{} Added task '{}' ({}) to {}",
"✓".green(),
task_id.cyan(),
task_verb.yellow(),
file.display()
);
if let Some(after_id) = after {
println!(" {} Inserted after task '{}'", "→".cyan(), after_id);
}
}
Ok(())
}
WorkflowAction::Graph {
file,
format,
output,
} => {
// Validate file exists
if !file.exists() {
return Err(NikaError::WorkflowNotFound {
path: file.to_string_lossy().to_string(),
});
}
// Parse workflow
let content = std::fs::read_to_string(&file)?;
let workflow = parse_workflow(&content)?;
// Generate graph based on format
let graph_output = match format.as_str() {
"ascii" => generate_ascii_dag(&workflow),
"dot" => generate_dot_dag(&workflow),
"mermaid" => generate_mermaid_dag(&workflow),
_ => {
return Err(NikaError::ValidationError {
reason: format!("Unknown format '{}'. Valid: ascii, dot, mermaid", format),
});
}
};
// Output
match output {
Some(path) => {
std::fs::write(&path, &graph_output)?;
if !quiet {
println!(
"{} DAG written to {} (format: {})",
"✓".green(),
path.display(),
format.cyan()
);
}
}
None => {
println!("{}", graph_output);
}
}
Ok(())
}
WorkflowAction::Check {
file,
suggest,
format,
} => {
// Validate file exists
if !file.exists() {
return Err(NikaError::WorkflowNotFound {
path: file.to_string_lossy().to_string(),
});
}
// Parse and validate
let content = std::fs::read_to_string(&file)?;
let workflow = parse_workflow(&content)?;
// Collect validation results
let mut issues: Vec<(String, String, String)> = Vec::new(); // (level, code, message)
let mut suggestions: Vec<String> = Vec::new();
// Check schema version
let schema = workflow.schema.clone();
if !schema.starts_with("nika/workflow@") {
issues.push((
"error".to_string(),
"NIKA-001".to_string(),
"Missing or invalid schema version".to_string(),
));
} else if let Some(version) = schema.strip_prefix("nika/workflow@") {
if version != "0.12" && suggest {
suggestions.push(format!(
"Consider upgrading from @{} to @0.12 for latest features",
version
));
}
}
// Check for common issues
if workflow.tasks.is_empty() {
issues.push((
"error".to_string(),
"NIKA-010".to_string(),
"Workflow has no tasks".to_string(),
));
}
// Check for duplicate task IDs
let mut seen_ids = std::collections::HashSet::new();
for task in &workflow.tasks {
if !seen_ids.insert(&task.id) {
issues.push((
"error".to_string(),
"NIKA-141".to_string(),
format!("Duplicate task ID: '{}'", task.id),
));
}
}
// Check for unused tasks (not referenced in deps or with blocks)
if suggest {
let mut referenced: std::collections::HashSet<&str> =
std::collections::HashSet::new();
for (source, target) in workflow.edges() {
referenced.insert(source);
referenced.insert(target);
}
for task in &workflow.tasks {
if let Some(ref with_spec) = task.with_spec {
for entry in with_spec.values() {
if let Some(task_ref) = entry.task_id() {
referenced.insert(task_ref);
}
}
}
}
for task in &workflow.tasks {
if !referenced.contains(task.id.as_str()) && workflow.tasks.len() > 1 {
// First task or leaf tasks are often not referenced
if workflow.tasks.first().map(|t| &t.id) != Some(&task.id) {
suggestions.push(format!(
"Task '{}' is not referenced by any other task",
task.id
));
}
}
}
}
// Output results
match format.as_str() {
"json" => {
let result = serde_json::json!({
"file": file.to_string_lossy(),
"valid": issues.iter().all(|(level, _, _)| level != "error"),
"issues": issues.iter().map(|(level, code, msg)| {
serde_json::json!({
"level": level,
"code": code,
"message": msg
})
}).collect::<Vec<_>>(),
"suggestions": suggestions
});
println!("{}", serde_json::to_string_pretty(&result)?);
}
_ => {
// Text format
let has_errors = issues.iter().any(|(level, _, _)| level == "error");
if issues.is_empty() {
if !quiet {
println!("{} {} is valid", "✓".green(), file.display());
}
} else {
for (level, code, msg) in &issues {
let prefix = if level == "error" {
"✗".red()
} else {
"⚠".yellow()
};
println!("{} [{}] {}", prefix, code.cyan(), msg);
}
}
if suggest && !suggestions.is_empty() {
println!();
println!("{}", "Suggestions:".cyan().bold());
for suggestion in &suggestions {
println!(" {} {}", "→".cyan(), suggestion);
}
}
if has_errors {
return Err(NikaError::ValidationError {
reason: format!("{} validation error(s) found", issues.len()),
});
}
}
}
Ok(())
}
}
}
fn generate_ascii_dag(workflow: &nika::ast::Workflow) -> String {
let mut output = String::new();
let name = "(unnamed)";
output.push_str("┌─────────────────────────────────────────┐\n");
output.push_str(&format!("│ DAG: {}", name));
let padding = 40usize.saturating_sub(name.len() + 6);
output.push_str(&" ".repeat(padding));
output.push_str("│\n");
output.push_str("├─────────────────────────────────────────┤\n");
// Build task list with verb icons
for task in &workflow.tasks {
let verb_icon = match &task.action {
nika::ast::TaskAction::Infer { .. } => "⚡",
nika::ast::TaskAction::Exec { .. } => "📟",
nika::ast::TaskAction::Fetch { .. } => "🛰️",
nika::ast::TaskAction::Invoke { .. } => "🔌",
nika::ast::TaskAction::Agent { .. } => "🐔",
};
let line = format!("│ {} {}", verb_icon, task.id);
let line_padding = 40usize.saturating_sub(task.id.len() + 4);
output.push_str(&format!("{}{}│\n", line, " ".repeat(line_padding)));
}
// Show flows (derived from task dependencies)
let edges = workflow.edges();
if !edges.is_empty() {
output.push_str("├─────────────────────────────────────────┤\n");
output.push_str("│ Edges: │\n");
for (source, target) in &edges {
let flow_str = format!(" {} → {}", source, target);
let flow_padding = 39usize.saturating_sub(flow_str.len());
output.push_str(&format!("│{}{}│\n", flow_str, " ".repeat(flow_padding)));
}
}
output.push_str("└─────────────────────────────────────────┘\n");
output
}
/// Generate DOT (Graphviz) DAG representation
fn generate_dot_dag(workflow: &nika::ast::Workflow) -> String {
let mut output = String::new();
let name = "workflow";
output.push_str(&format!("digraph {} {{\n", name));
output.push_str(" rankdir=LR;\n");
output.push_str(" node [shape=box, style=rounded];\n\n");
// Add nodes with styling based on verb
for task in &workflow.tasks {
let color = match &task.action {
nika::ast::TaskAction::Infer { .. } => "lightblue",
nika::ast::TaskAction::Exec { .. } => "lightgreen",
nika::ast::TaskAction::Fetch { .. } => "lightyellow",
nika::ast::TaskAction::Invoke { .. } => "lightpink",
nika::ast::TaskAction::Agent { .. } => "plum",
};
output.push_str(&format!(
" {} [label=\"{}\", fillcolor={}, style=\"rounded,filled\"];\n",
task.id.replace('-', "_"),
task.id,
color
));
}
// Add edges (derived from task dependencies)
output.push('\n');
for (source, target) in workflow.edges() {
output.push_str(&format!(
" {} -> {};\n",
source.replace('-', "_"),
target.replace('-', "_")
));
}
output.push_str("}\n");
output
}
/// Generate Mermaid DAG representation
fn generate_mermaid_dag(workflow: &nika::ast::Workflow) -> String {
let mut output = String::new();
output.push_str("```mermaid\ngraph LR\n");
// Add nodes with styling
for task in &workflow.tasks {
let shape = match &task.action {
nika::ast::TaskAction::Infer { .. } => ("([", "])"), // Stadium
nika::ast::TaskAction::Exec { .. } => ("[", "]"), // Rectangle
nika::ast::TaskAction::Fetch { .. } => ("{{", "}}"), // Hexagon
nika::ast::TaskAction::Invoke { .. } => ("[[", "]]"), // Subroutine
nika::ast::TaskAction::Agent { .. } => ("((", "))"), // Circle
};
let verb = match &task.action {
nika::ast::TaskAction::Infer { .. } => "infer",
nika::ast::TaskAction::Exec { .. } => "exec",
nika::ast::TaskAction::Fetch { .. } => "fetch",
nika::ast::TaskAction::Invoke { .. } => "invoke",
nika::ast::TaskAction::Agent { .. } => "agent",
};
output.push_str(&format!(
" {}{}{} : {}{}\n",
task.id.replace('-', "_"),
shape.0,
task.id,
verb,
shape.1
));
}
// Add edges (derived from task dependencies)
output.push('\n');
for (source, target) in workflow.edges() {
output.push_str(&format!(
" {} --> {}\n",
source.replace('-', "_"),
target.replace('-', "_")
));
}
output.push_str("```\n");
output
}