keelrun-cli 0.1.0

The `keel` binary: run | init | doctor | status | explain. The product's face — every command has a byte-deterministic `--json` twin and stable exit codes (dx-spec §1–2, §5–6).
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
//! `keel run <script> [args…]` — dispatch a program into its language front end.
//!
//! The heavy lifting (bootstrap, import hook, adapters, discovery) lives in the
//! Python and Node packages; `run` is only the dispatcher (dx-spec §1, Level 0):
//!
//! - `*.py`                     → `python3 -m keel run <script> [args…]`
//! - `*.{mjs,js,ts,cjs,…}`      → `node --import keel/hook <script> [args…]`
//! - a dir / `package.json`     → resolve its `main`, then the Node path
//! - anything else              → a precise what/why/next error, exit 2
//!
//! The child inherits the environment (so every `KEEL_*` var passes through);
//! `--disable` layers `KEEL_DISABLE=1` on top. The child's exit code is the
//! process's exit code — wrapping is invisible on the success path.

use std::path::{Path, PathBuf};
use std::process::Command;

use serde::Serialize;

use crate::{EXIT_FAILURE, EXIT_USAGE, Rendered};

/// Node's resolver name for the preload hook (the `keel` package's `./hook`
/// export). Resolved from the project's `node_modules`, exactly as
/// `node --import keel/hook` would in a project that installed `keel`.
const NODE_HOOK: &str = "keel/hook";

/// The concrete plan: which interpreter to exec with which argv, and whether to
/// disable Keel in the child. Pure data, so dispatch is unit-testable without
/// spawning anything.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunPlan {
    /// The program to exec (`python3` or `node`).
    pub program: String,
    /// Its full argument vector (excluding `program` itself).
    pub argv: Vec<String>,
    /// Whether to set `KEEL_DISABLE=1` in the child.
    pub disable: bool,
}

/// Why a target could not be dispatched — each rendered as what/why/next.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunError {
    /// The target file/dir does not exist.
    NotFound { target: String },
    /// The extension is not one `keel run` knows how to dispatch.
    UnknownKind { target: String },
    /// A Node package dir/`package.json` had no resolvable entry file.
    NoEntry { target: String },
}

impl RunError {
    pub(crate) fn render(&self) -> Rendered {
        let (what, why, next, kind) = match self {
            Self::NotFound { target } => (
                format!("Cannot run `{target}`: no such file or directory."),
                "The path does not exist relative to the current directory.".to_owned(),
                "Check the path; `keel run` takes a script file, a package.json, or a project directory.".to_owned(),
                "not-found",
            ),
            Self::UnknownKind { target } => (
                format!("Cannot run `{target}`: unrecognized program type."),
                "`keel run` dispatches Python (.py) and Node (.mjs/.js/.ts/.cjs/.mts/.cts/.jsx/.tsx, or a package.json main); this target is neither.".to_owned(),
                "Rename to a supported extension, point at the project's package.json, or invoke the interpreter directly.".to_owned(),
                "unknown-kind",
            ),
            Self::NoEntry { target } => (
                format!("Cannot run `{target}`: no entry file found."),
                "The directory/package.json has no resolvable `main` (and no index.js).".to_owned(),
                "Add a `main` to package.json, or pass the entry script directly.".to_owned(),
                "no-entry",
            ),
        };
        let human = format!("keel \u{25b8} {what}\n  why:  {why}\n  next: {next}");
        let report = RunErrorReport {
            error: kind,
            next: &next,
            what: &what,
            why: &why,
        };
        Rendered {
            human,
            json: crate::render::to_json(&report),
            exit: EXIT_USAGE,
            to_stderr: true,
        }
    }
}

/// The machine twin of a dispatch failure.
#[derive(Debug, Serialize)]
struct RunErrorReport<'a> {
    error: &'static str,
    next: &'a str,
    what: &'a str,
    why: &'a str,
}

/// Node source extensions `keel run` dispatches.
const NODE_EXTS: &[&str] = &["mjs", "js", "ts", "cjs", "mts", "cts", "jsx", "tsx"];

/// Build the [`RunPlan`] for `target` and `args`. Reads the filesystem to
/// classify the target and (for a package) to resolve its entry file.
pub fn plan(target: &str, args: &[String], disable: bool) -> Result<RunPlan, RunError> {
    let path = Path::new(target);

    // package.json passed explicitly, or a directory containing one.
    if path.file_name().is_some_and(|n| n == "package.json") {
        return node_package(path, args, disable);
    }
    if path.is_dir() {
        let manifest = path.join("package.json");
        if manifest.exists() {
            return node_package(&manifest, args, disable);
        }
        return Err(RunError::UnknownKind {
            target: target.to_owned(),
        });
    }
    if !path.exists() {
        return Err(RunError::NotFound {
            target: target.to_owned(),
        });
    }

    match path.extension().and_then(|e| e.to_str()) {
        Some("py") => Ok(python_plan(target, args, disable)),
        Some(ext) if NODE_EXTS.contains(&ext) => Ok(node_plan(target, args, disable)),
        _ => Err(RunError::UnknownKind {
            target: target.to_owned(),
        }),
    }
}

fn python_plan(target: &str, extra: &[String], disable: bool) -> RunPlan {
    let mut argv = vec![
        "-m".to_owned(),
        "keel".to_owned(),
        "run".to_owned(),
        target.to_owned(),
    ];
    argv.extend_from_slice(extra);
    RunPlan {
        program: "python3".to_owned(),
        argv,
        disable,
    }
}

/// Pin a Node target as a path operand, never a Node option. Node parses any
/// argv entry beginning with `-` (before the entry point) as a flag, so a file
/// literally named `--inspect-brk=0.0.0.0:9229.js` — a valid filename that
/// passes the exists/extension checks — would open an unauthenticated debug port
/// instead of running as a script. Prefixing a relative target with `./`
/// (absolute paths and already-dot-prefixed paths are left as-is) makes it
/// unambiguously a path. The Python path is immune (its target lands after
/// `-m keel run`).
fn as_script_operand(target: &str) -> String {
    if target.starts_with('/') || target.starts_with("./") || target.starts_with("../") {
        target.to_owned()
    } else {
        format!("./{target}")
    }
}

fn node_plan(target: &str, extra: &[String], disable: bool) -> RunPlan {
    let mut argv = vec![
        "--import".to_owned(),
        NODE_HOOK.to_owned(),
        as_script_operand(target),
    ];
    argv.extend_from_slice(extra);
    RunPlan {
        program: "node".to_owned(),
        argv,
        disable,
    }
}

/// Resolve a package's entry file from its `package.json` `main` (default
/// `index.js`), then dispatch it via the Node path.
fn node_package(manifest: &Path, args: &[String], disable: bool) -> Result<RunPlan, RunError> {
    let dir = manifest.parent().unwrap_or_else(|| Path::new("."));
    let text = std::fs::read_to_string(manifest).map_err(|_| RunError::NoEntry {
        target: manifest.display().to_string(),
    })?;
    let main = serde_json::from_str::<serde_json::Value>(&text)
        .ok()
        .and_then(|v| v.get("main").and_then(|m| m.as_str()).map(str::to_owned))
        .unwrap_or_else(|| "index.js".to_owned());
    let entry: PathBuf = dir.join(main);
    if !entry.exists() {
        return Err(RunError::NoEntry {
            target: manifest.display().to_string(),
        });
    }
    Ok(node_plan(&entry.to_string_lossy(), args, disable))
}

/// Execute a [`RunPlan`], inheriting the environment (so `KEEL_*` passes
/// through). Returns the child's exit code, or a rendered spawn error.
pub fn exec(plan: &RunPlan) -> Result<i32, Rendered> {
    exec_with(plan, |_cmd| {})
}

/// Like [`exec`], but lets the caller layer extra environment onto the child
/// before it spawns (`keel record run` sets `KEEL_RECORD` this way — see
/// `crate::record`). `exec` is exactly `exec_with(plan, |_| {})`.
pub(crate) fn exec_with(
    plan: &RunPlan,
    configure: impl FnOnce(&mut Command),
) -> Result<i32, Rendered> {
    let mut cmd = Command::new(&plan.program);
    cmd.args(&plan.argv);
    if plan.disable {
        cmd.env("KEEL_DISABLE", "1");
    }
    configure(&mut cmd);
    match cmd.status() {
        Ok(status) => Ok(status.code().unwrap_or(EXIT_FAILURE)),
        Err(err) => {
            let what = format!("Cannot run `{}`: {err}.", plan.program);
            let why = format!(
                "`{}` was not found on PATH or could not be started.",
                plan.program
            );
            let next = if plan.program == "python3" {
                "Install Python 3 and the `keel` package (`pip install keel`)."
            } else {
                "Install Node.js and the `keel` package (`npm i -D keel`)."
            };
            let human = format!("keel \u{25b8} {what}\n  why:  {why}\n  next: {next}");
            let report = RunErrorReport {
                error: "spawn-failed",
                next,
                what: &what,
                why: &why,
            };
            Err(Rendered {
                human,
                json: crate::render::to_json(&report),
                exit: EXIT_FAILURE,
                to_stderr: true,
            })
        }
    }
}

/// The whole `keel run` command: plan, then exec. On a dispatch error render it;
/// on success return the child's exit code.
pub fn run(target: &str, args: &[String], disable: bool) -> (Option<Rendered>, i32) {
    match plan(target, args, disable) {
        Err(e) => {
            let r = e.render();
            let code = r.exit;
            (Some(r), code)
        }
        Ok(plan) => match exec(&plan) {
            Ok(code) => (None, code),
            Err(r) => {
                let code = r.exit;
                (Some(r), code)
            }
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn python_target_dispatches_to_python_module() {
        let dir = TempDir::new().unwrap();
        let script = dir.path().join("app.py");
        fs::write(&script, "print('hi')\n").unwrap();
        let plan = plan(&script.to_string_lossy(), &["--flag".into()], false).unwrap();
        assert_eq!(plan.program, "python3");
        assert_eq!(
            plan.argv,
            vec![
                "-m",
                "keel",
                "run",
                script.to_string_lossy().as_ref(),
                "--flag"
            ]
        );
    }

    #[test]
    fn node_target_dispatches_with_hook_import() {
        let dir = TempDir::new().unwrap();
        let script = dir.path().join("app.mjs");
        fs::write(&script, "console.log('hi')\n").unwrap();
        let plan = plan(&script.to_string_lossy(), &[], true).unwrap();
        assert_eq!(plan.program, "node");
        assert_eq!(plan.argv[0], "--import");
        assert_eq!(plan.argv[1], "keel/hook");
        assert!(plan.disable);
    }

    #[test]
    fn node_dash_named_target_is_pinned_as_a_path_operand() {
        // A relative target that would parse as a Node option is prefixed with
        // `./`; absolute and dot-prefixed paths are already unambiguous.
        assert_eq!(
            as_script_operand("--inspect-brk=0.0.0.0:9229.js"),
            "./--inspect-brk=0.0.0.0:9229.js"
        );
        assert_eq!(as_script_operand("app.mjs"), "./app.mjs");
        assert_eq!(as_script_operand("sub/app.mjs"), "./sub/app.mjs");
        assert_eq!(as_script_operand("/abs/app.mjs"), "/abs/app.mjs");
        assert_eq!(as_script_operand("./app.mjs"), "./app.mjs");
        assert_eq!(as_script_operand("../app.mjs"), "../app.mjs");
    }

    #[test]
    fn package_json_main_is_resolved() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("package.json"),
            "{ \"main\": \"start.mjs\" }",
        )
        .unwrap();
        fs::write(dir.path().join("start.mjs"), "// entry\n").unwrap();
        let plan = plan(&dir.path().to_string_lossy(), &[], false).unwrap();
        assert_eq!(plan.program, "node");
        assert!(plan.argv[2].ends_with("start.mjs"));
    }

    #[test]
    fn package_json_defaults_to_index_js() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("package.json"), "{}").unwrap();
        fs::write(dir.path().join("index.js"), "// entry\n").unwrap();
        let plan = plan(&dir.path().to_string_lossy(), &[], false).unwrap();
        assert!(plan.argv[2].ends_with("index.js"));
    }

    #[test]
    fn missing_file_is_not_found() {
        assert_eq!(
            plan("does-not-exist.py", &[], false),
            Err(RunError::NotFound {
                target: "does-not-exist.py".into()
            })
        );
    }

    #[test]
    fn unknown_extension_is_a_precise_error() {
        let dir = TempDir::new().unwrap();
        let f = dir.path().join("script.rb");
        fs::write(&f, "puts 1\n").unwrap();
        let err = plan(&f.to_string_lossy(), &[], false).unwrap_err();
        assert!(matches!(err, RunError::UnknownKind { .. }));
        let rendered = err.render();
        assert_eq!(rendered.exit, EXIT_USAGE);
        assert!(rendered.human.contains("next:"));
        assert_eq!(rendered.json["error"], "unknown-kind");
    }

    #[test]
    fn package_dir_without_entry_errors() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("package.json"), "{ \"main\": \"nope.js\" }").unwrap();
        let err = plan(&dir.path().to_string_lossy(), &[], false).unwrap_err();
        assert!(matches!(err, RunError::NoEntry { .. }));
    }

    #[test]
    fn child_exit_code_propagates() {
        // `keel run` is invisible on the success path — the child's exit code is
        // the process's exit code (dx-spec §1). Drive the exec path directly with
        // a shell that exits 7.
        let plan = RunPlan {
            program: "sh".to_owned(),
            argv: vec!["-c".to_owned(), "exit 7".to_owned()],
            disable: false,
        };
        assert_eq!(exec(&plan).expect("sh should spawn"), 7);
    }

    #[test]
    fn exec_with_layers_extra_env_onto_the_child() {
        // `keel record run` (crate::record) relies on this to thread
        // `KEEL_RECORD` into the child without duplicating `exec`'s spawn
        // logic — prove the closure actually reaches the child's environment.
        let plan = RunPlan {
            program: "sh".to_owned(),
            argv: vec![
                "-c".to_owned(),
                "[ \"$KEEL_RECORD_TEST\" = \"marker\" ] && exit 0 || exit 9".to_owned(),
            ],
            disable: false,
        };
        let code = exec_with(&plan, |cmd| {
            cmd.env("KEEL_RECORD_TEST", "marker");
        })
        .expect("sh should spawn");
        assert_eq!(code, 0);
    }

    #[test]
    fn spawn_failure_is_a_framed_error_with_exit_1() {
        // A program that cannot be spawned surfaces a what/why/next error on
        // stderr and exit 1 (an underlying failure, not a usage error).
        let plan = RunPlan {
            program: "keel-nonexistent-program-9f3a".to_owned(),
            argv: vec![],
            disable: false,
        };
        let rendered = exec(&plan).expect_err("nonexistent program cannot spawn");

        assert_eq!(rendered.exit, EXIT_FAILURE);
        assert!(rendered.to_stderr);
        assert_eq!(rendered.json["error"], "spawn-failed");
        // The human message is framed: what (keel ▸ …), why, and next.
        assert!(rendered.human.starts_with("keel \u{25b8} "));
        assert!(rendered.human.contains("keel-nonexistent-program-9f3a"));
        assert!(rendered.human.contains("why:"));
        assert!(rendered.human.contains("next:"));
    }
}