kdo 0.1.0-alpha.2

Context-native workspace manager for AI coding agents. Cuts token consumption on polyglot monorepos.
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
//! Task execution engine — `kdo run` and `kdo exec`.
//!
//! Runs tasks in topological order across workspace projects, expanding task
//! `depends_on` into a linear DAG-respecting plan. Supports env merging,
//! aliases, per-project overrides, persistent tasks, and pass-through args.

use kdo_core::{Project, TaskSpec, WorkspaceConfig};
use kdo_graph::WorkspaceGraph;
use owo_colors::OwoColorize;
use std::collections::{BTreeMap, HashSet};
use std::path::Path;
use std::process::Stdio;

/// Colors for project name prefixes (cycle through these).
const PROJECT_COLORS: &[&str] = &["cyan", "green", "yellow", "magenta", "blue", "red"];

/// A single execution step in the run plan.
#[derive(Debug, Clone)]
struct Step {
    project: Project,
    task_name: String,
    command: String,
    env: BTreeMap<String, String>,
    persistent: bool,
}

/// Run a named task. Resolves aliases, expands `depends_on`, and executes the
/// resulting plan. `extra_args` is appended to every resolved command (for
/// `kdo run build -- --release` pass-through).
pub fn run_task(
    graph: &WorkspaceGraph,
    config: &WorkspaceConfig,
    task_name: &str,
    filter: Option<&str>,
    parallel: bool,
    extra_args: &[String],
) -> miette::Result<()> {
    let resolved_name = config.resolve_alias(task_name);
    let projects = get_target_projects(graph, filter);

    if projects.is_empty() {
        eprintln!("{}", "No projects matched filter.".yellow());
        return Ok(());
    }

    let workspace_env = merge_workspace_env(config);
    let mut visited: HashSet<(String, String)> = HashSet::new();
    let mut plan: Vec<Step> = Vec::new();

    for project in &projects {
        plan_task(
            graph,
            config,
            &workspace_env,
            project,
            resolved_name,
            extra_args,
            &mut visited,
            &mut plan,
        )?;
    }

    if plan.is_empty() {
        miette::bail!("task '{task_name}' not found in any project or kdo.toml");
    }

    let failures = if parallel {
        run_parallel(&plan)?
    } else {
        run_sequential(&plan)?
    };

    if !failures.is_empty() {
        miette::bail!("{} task(s) failed: {}", failures.len(), failures.join(", "));
    }

    Ok(())
}

/// Recursively plan a task for a project, expanding `depends_on` first.
#[allow(clippy::too_many_arguments)]
fn plan_task(
    graph: &WorkspaceGraph,
    config: &WorkspaceConfig,
    workspace_env: &BTreeMap<String, String>,
    project: &Project,
    task_name: &str,
    extra_args: &[String],
    visited: &mut HashSet<(String, String)>,
    plan: &mut Vec<Step>,
) -> miette::Result<()> {
    let key = (project.name.clone(), task_name.to_string());
    if visited.contains(&key) {
        return Ok(());
    }
    visited.insert(key);

    let resolved = resolve_task(config, project, task_name);

    // Expand dependencies before emitting this step.
    if let Some((Some(spec), _)) = &resolved {
        for dep in spec.depends_on() {
            if let Some(upstream_task) = dep.strip_prefix('^') {
                let upstream = graph
                    .dependency_closure(&project.name)
                    .map_err(|e| miette::miette!("{e}"))?;
                for dep_project in upstream {
                    plan_task(
                        graph,
                        config,
                        workspace_env,
                        dep_project,
                        upstream_task,
                        extra_args,
                        visited,
                        plan,
                    )?;
                }
            } else if let Some(workspace_task) = dep.strip_prefix("//") {
                for project_ref in graph.projects() {
                    plan_task(
                        graph,
                        config,
                        workspace_env,
                        project_ref,
                        workspace_task,
                        extra_args,
                        visited,
                        plan,
                    )?;
                }
            } else {
                plan_task(
                    graph,
                    config,
                    workspace_env,
                    project,
                    dep,
                    extra_args,
                    visited,
                    plan,
                )?;
            }
        }
    }

    let Some((spec_opt, mut command)) = resolved else {
        return Ok(());
    };

    // Composite tasks (depends_on only, no command) emit no step.
    if command.is_empty() {
        return Ok(());
    }

    if !extra_args.is_empty() {
        command.push(' ');
        command.push_str(&shell_quote_args(extra_args));
    }

    let mut env = workspace_env.clone();
    if let Some(project_cfg) = config.projects.get(&project.name) {
        for (k, v) in &project_cfg.env {
            env.insert(k.clone(), v.clone());
        }
    }
    let persistent = if let Some(spec) = &spec_opt {
        for (k, v) in spec.env() {
            env.insert(k.clone(), v.clone());
        }
        spec.persistent()
    } else {
        false
    };

    plan.push(Step {
        project: project.clone(),
        task_name: task_name.to_string(),
        command,
        env,
        persistent,
    });
    Ok(())
}

/// Resolve a task for a project. Returns `(task_spec_if_rich, command_string)`.
/// Precedence: per-project override > workspace task > manifest script > language default.
fn resolve_task(
    config: &WorkspaceConfig,
    project: &Project,
    task_name: &str,
) -> Option<(Option<TaskSpec>, String)> {
    if let Some(project_cfg) = config.projects.get(&project.name) {
        if let Some(spec) = project_cfg.tasks.get(task_name) {
            return Some((Some(spec.clone()), spec.command().unwrap_or("").to_string()));
        }
    }
    if let Some(spec) = config.tasks.get(task_name) {
        return Some((Some(spec.clone()), spec.command().unwrap_or("").to_string()));
    }
    if let Some(cmd) = resolve_task_command(project, task_name) {
        return Some((None, cmd));
    }
    None
}

/// Merge workspace-level env: env_files first, then `[env]` keys on top.
fn merge_workspace_env(config: &WorkspaceConfig) -> BTreeMap<String, String> {
    let mut env = BTreeMap::new();
    for path in &config.env_files {
        if let Ok(content) = std::fs::read_to_string(path) {
            for line in content.lines() {
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                if let Some((k, v)) = line.split_once('=') {
                    let v = v.trim().trim_matches('"').trim_matches('\'');
                    env.insert(k.trim().to_string(), v.to_string());
                }
            }
        }
    }
    for (k, v) in &config.env {
        env.insert(k.clone(), v.clone());
    }
    env
}

/// POSIX shell-quote arguments so they survive `sh -c`.
fn shell_quote_args(args: &[String]) -> String {
    args.iter()
        .map(|a| {
            if a.chars()
                .all(|c| c.is_alphanumeric() || "-_./:=".contains(c))
            {
                a.clone()
            } else {
                let escaped = a.replace('\'', "'\\''");
                format!("'{escaped}'")
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Run an arbitrary command in each project directory.
pub fn exec_command(
    graph: &WorkspaceGraph,
    command: &str,
    filter: Option<&str>,
    parallel: bool,
) -> miette::Result<()> {
    let projects = get_target_projects(graph, filter);

    if projects.is_empty() {
        eprintln!("{}", "No projects matched filter.".yellow());
        return Ok(());
    }

    let plan: Vec<Step> = projects
        .into_iter()
        .map(|p| Step {
            project: p.clone(),
            task_name: "exec".to_string(),
            command: command.to_string(),
            env: BTreeMap::new(),
            persistent: false,
        })
        .collect();

    let failures = if parallel {
        run_parallel(&plan)?
    } else {
        run_sequential(&plan)?
    };

    if !failures.is_empty() {
        miette::bail!(
            "{} command(s) failed: {}",
            failures.len(),
            failures.join(", ")
        );
    }

    Ok(())
}

/// Get target projects in topological order, optionally filtered by name.
fn get_target_projects<'a>(graph: &'a WorkspaceGraph, filter: Option<&str>) -> Vec<&'a Project> {
    let ordered = graph.topological_order();
    if let Some(filter_name) = filter {
        ordered
            .into_iter()
            .filter(|p| p.name == filter_name || p.name.contains(filter_name))
            .collect()
    } else {
        ordered
    }
}

/// Run steps sequentially, printing prefixed output.
fn run_sequential(plan: &[Step]) -> miette::Result<Vec<String>> {
    let mut failures = Vec::new();
    for (i, step) in plan.iter().enumerate() {
        let prefix = format_prefix(
            &step.project.name,
            &step.task_name,
            i % PROJECT_COLORS.len(),
        );
        eprintln!("{prefix} {}", step.command.dimmed());
        let success = execute_step(step)?;
        if success {
            eprintln!("{prefix} {}", "done".green());
        } else if step.persistent {
            eprintln!("{prefix} {}", "persistent task exited".yellow());
        } else {
            eprintln!("{prefix} {}", "FAILED".red().bold());
            failures.push(step.project.name.clone());
        }
    }
    Ok(failures)
}

/// Run steps in parallel using rayon, collecting failures.
fn run_parallel(plan: &[Step]) -> miette::Result<Vec<String>> {
    use rayon::prelude::*;
    use std::sync::Mutex;

    let failures = Mutex::new(Vec::new());

    plan.par_iter().enumerate().for_each(|(i, step)| {
        let prefix = format_prefix(
            &step.project.name,
            &step.task_name,
            i % PROJECT_COLORS.len(),
        );
        eprintln!("{prefix} {}", step.command.dimmed());
        match execute_step(step) {
            Ok(true) => eprintln!("{prefix} {}", "done".green()),
            Ok(false) if step.persistent => {
                eprintln!("{prefix} {}", "persistent task exited".yellow());
            }
            Ok(false) => {
                eprintln!("{prefix} {}", "FAILED".red().bold());
                failures.lock().unwrap().push(step.project.name.clone());
            }
            Err(e) => {
                eprintln!("{prefix} {} {e}", "ERROR".red().bold());
                failures.lock().unwrap().push(step.project.name.clone());
            }
        }
    });

    Ok(failures.into_inner().unwrap())
}

/// Try to resolve a task command from a project's manifest or language defaults.
pub fn resolve_task_command(project: &Project, task_name: &str) -> Option<String> {
    match project.language {
        kdo_core::Language::Rust | kdo_core::Language::Anchor => match task_name {
            "build" => Some("cargo build".into()),
            "test" => Some("cargo test".into()),
            "check" => Some("cargo check".into()),
            "lint" => Some("cargo clippy".into()),
            "fmt" => Some("cargo fmt".into()),
            "clean" => Some("cargo clean".into()),
            _ => None,
        },
        kdo_core::Language::TypeScript | kdo_core::Language::JavaScript => {
            let pkg_path = project.manifest_path.clone();
            if let Ok(content) = std::fs::read_to_string(&pkg_path) {
                if let Ok(pkg) = serde_json::from_str::<serde_json::Value>(&content) {
                    if pkg
                        .get("scripts")
                        .and_then(|s| s.get(task_name))
                        .and_then(|v| v.as_str())
                        .is_some()
                    {
                        let pm = detect_node_pm(&project.path);
                        return Some(format!("{pm} run {task_name}"));
                    }
                }
            }
            match task_name {
                "build" => Some("npm run build".into()),
                "test" => Some("npm test".into()),
                "lint" => Some("npm run lint".into()),
                "dev" => Some("npm run dev".into()),
                _ => None,
            }
        }
        kdo_core::Language::Python => {
            let py = detect_python();
            match task_name {
                "test" => Some(format!("{py} -m pytest")),
                "lint" => Some("ruff check .".into()),
                "fmt" => Some("ruff format .".into()),
                "build" => Some(format!("{py} -c \"print('no build step for Python')\"")),
                _ => None,
            }
        }
        kdo_core::Language::Go => match task_name {
            "build" => Some("go build ./...".into()),
            "test" => Some("go test ./...".into()),
            "lint" => Some("golangci-lint run".into()),
            "fmt" => Some("gofmt -w .".into()),
            "check" => Some("go vet ./...".into()),
            _ => None,
        },
    }
}

/// Detect python binary (python3 preferred over python).
pub fn detect_python() -> &'static str {
    if std::process::Command::new("python3")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
    {
        "python3"
    } else {
        "python"
    }
}

/// Detect which Node package manager to use based on lockfile presence.
pub fn detect_node_pm(project_dir: &Path) -> &'static str {
    if project_dir.join("bun.lockb").exists() || project_dir.join("bun.lock").exists() {
        "bun"
    } else if project_dir.join("pnpm-lock.yaml").exists() {
        "pnpm"
    } else if project_dir.join("yarn.lock").exists() {
        "yarn"
    } else {
        "npm"
    }
}

/// Execute a single plan step in its project directory with merged env.
fn execute_step(step: &Step) -> miette::Result<bool> {
    use miette::IntoDiagnostic;

    let mut cmd = std::process::Command::new("sh");
    cmd.args(["-c", &step.command])
        .current_dir(&step.project.path)
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit());
    for (k, v) in &step.env {
        cmd.env(k, v);
    }
    let status = cmd.status().into_diagnostic()?;
    Ok(status.success())
}

/// Format a colored `[project:task]` prefix.
fn format_prefix(project: &str, task: &str, color_idx: usize) -> String {
    let label = format!("{project}:{task}");
    let colored = match PROJECT_COLORS[color_idx] {
        "cyan" => label.cyan().bold().to_string(),
        "green" => label.green().bold().to_string(),
        "yellow" => label.yellow().bold().to_string(),
        "magenta" => label.magenta().bold().to_string(),
        "blue" => label.blue().bold().to_string(),
        "red" => label.red().bold().to_string(),
        _ => label.bold().to_string(),
    };
    format!("[{colored}]")
}