runx-cli 0.6.19

Cargo-installed launcher for the runx governed agent workflow CLI.
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
// rust-style-allow: large-file - native CLI command dispatch remains one audited
// boundary so release shims and exit-code handling are visible in one place.
use std::env;
use std::ffi::OsString;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use runx_cli::router::{
    HarnessPlan, RouterAction, add_help_text, help_text, history_help_text, list_help_text,
    login_help_text, publish_help_text, registry_help_text, resume_help_text, skill_help_text,
    verify_help_text,
};

const INLINE_HARNESS_SIGNING_HINT: &str = "runx: hint: inline harnesses seal signed receipts; set RUNX_RECEIPT_SIGN_KID, RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64, and RUNX_RECEIPT_SIGN_ISSUER_TYPE together, or unset all three to use local-development receipts.";
const INLINE_HARNESS_STALE_RECEIPT_STORE_HINT: &str = "runx: hint: the receipt store contains entries that do not verify with the current issuer; retry with --receipt-dir \"$(mktemp -d)\" for an isolated harness run.";

fn main() -> ExitCode {
    let args: Vec<OsString> = env::args_os().skip(1).collect();

    match runx_cli::router::route_args(args) {
        RouterAction::Error(message) => {
            let _ignored = write_stderr_line(&format!("runx: {message}"));
            ExitCode::from(64)
        }
        RouterAction::JsonError(plan) => {
            write_json_failure(&plan.message, &plan.code, plan.exit_code)
        }
        RouterAction::PrintHelp => write_stdout(&help_text()),
        RouterAction::PrintAddHelp => write_stdout(&add_help_text()),
        RouterAction::PrintHistoryHelp => write_stdout(&history_help_text()),
        RouterAction::PrintListHelp => write_stdout(&list_help_text()),
        RouterAction::PrintLoginHelp => write_stdout(&login_help_text()),
        RouterAction::PrintPublishHelp => write_stdout(&publish_help_text()),
        RouterAction::PrintRegistryHelp => write_stdout(&registry_help_text()),
        RouterAction::PrintRegistryUsageError => {
            let _ignored = write_stderr_line(&registry_help_text());
            ExitCode::from(64)
        }
        RouterAction::PrintResumeHelp => write_stdout(&resume_help_text()),
        RouterAction::PrintSkillHelp => write_stdout(&skill_help_text()),
        RouterAction::PrintVerifyHelp => write_stdout(&verify_help_text()),
        RouterAction::PrintVersion => {
            write_stdout_line(&format!("runx-cli {}", env!("CARGO_PKG_VERSION")))
        }
        RouterAction::RunInit(plan) => runx_cli::scaffold::run_native_init(plan),
        RouterAction::RunNew(plan) => runx_cli::scaffold::run_native_new(plan),
        RouterAction::RunHistory(plan) => run_native_history(plan.args),
        RouterAction::RunVerify(plan) => run_native_verify(plan.args),
        RouterAction::RunList(plan) => run_native_list(plan),
        RouterAction::RunLogin(plan) => runx_cli::login::run_native_login(plan),
        RouterAction::RunMcp(plan) => runx_cli::mcp::run_native_mcp(plan),
        RouterAction::RunHarness(plan) => run_native_harness(plan),
        RouterAction::RunKernel(plan) => runx_cli::kernel::run_native_kernel(plan),
        RouterAction::RunPayment(plan) => runx_cli::payment::run_native_payment(plan),
        RouterAction::RunParser(plan) => runx_cli::parser::run_native_parser(plan),
        RouterAction::RunConfig(plan) => run_native_config(plan),
        RouterAction::RunPolicy(plan) => runx_cli::policy::run_native_policy(plan),
        RouterAction::RunPublish(plan) => runx_cli::publish::run_native_publish(plan),
        RouterAction::RunRegistry(plan) => runx_cli::registry::run_native_registry(plan),
        RouterAction::RunResume(plan) => runx_cli::resume::run_native_resume(plan),
        RouterAction::RunSkill(plan) => runx_cli::skill::run_native_skill(plan),
        RouterAction::RunDoctor(plan) => runx_cli::doctor::run_native_doctor(plan),
        RouterAction::RunDev(plan) => runx_cli::dev::run_native_dev(plan),
        RouterAction::RunExport(plan) => runx_cli::export::run_native_export(plan),
        RouterAction::RunTool(plan) => runx_cli::tool::run_native_tool(plan),
        RouterAction::RunAddUrl(plan) => runx_cli::add::run_native_add(plan),
    }
}

fn run_native_history(args: Vec<OsString>) -> ExitCode {
    let cwd = match env::current_dir() {
        Ok(cwd) => cwd,
        Err(error) => {
            let _ignored = write_stderr_line(&format!("runx: failed to resolve cwd: {error}"));
            return ExitCode::from(1);
        }
    };
    match runx_cli::history::run_history_command(&args, &runx_cli::history::env_map(), &cwd) {
        Ok(output) => write_stdout(&output.output),
        Err(runx_cli::history::HistoryCliError::InvalidArgs(message)) => {
            let _ignored = write_stderr_line(&format!("runx: {message}"));
            ExitCode::from(64)
        }
        Err(error) => {
            let _ignored = write_stderr_line(&format!("runx: {error}"));
            ExitCode::from(1)
        }
    }
}

fn run_native_verify(args: Vec<OsString>) -> ExitCode {
    let json = runx_cli::router::json_requested(&args);
    let cwd = match env::current_dir() {
        Ok(cwd) => cwd,
        Err(error) => {
            let _ignored = write_stderr_line(&format!("runx: failed to resolve cwd: {error}"));
            return ExitCode::from(1);
        }
    };
    match runx_cli::verify::run_verify_command_with_stdin(
        &args,
        &runx_cli::history::env_map(),
        &cwd,
        io::stdin(),
    ) {
        Ok(result) => {
            let exit = write_stdout(&result.output);
            if result.failed {
                ExitCode::from(1)
            } else {
                exit
            }
        }
        Err(runx_cli::verify::VerifyCliError::InvalidArgs(message)) => {
            if json {
                return write_json_failure(&message, "invalid_args", 64);
            }
            let _ignored = write_stderr_line(&format!("runx: {message}"));
            ExitCode::from(64)
        }
        Err(error) => {
            if json {
                return write_json_failure(&error.to_string(), "runtime_error", 1);
            }
            let _ignored = write_stderr_line(&format!("runx: {error}"));
            ExitCode::from(1)
        }
    }
}

fn run_native_list(plan: runx_cli::router::ListPlan) -> ExitCode {
    let cwd = match env::current_dir() {
        Ok(cwd) => cwd,
        Err(error) => {
            let _ignored = write_stderr_line(&format!("runx: failed to resolve cwd: {error}"));
            return ExitCode::from(1);
        }
    };
    match runx_cli::list::run_list_command(&plan, &cwd) {
        Ok(output) => write_stdout(&output),
        Err(error) => {
            let _ignored = write_stderr_line(&format!("runx: {error}"));
            ExitCode::from(1)
        }
    }
}

fn run_native_config(plan: runx_cli::config::ConfigPlan) -> ExitCode {
    let cwd = match env::current_dir() {
        Ok(cwd) => cwd,
        Err(error) => {
            let _ignored = write_stderr_line(&format!("runx: failed to resolve cwd: {error}"));
            return ExitCode::from(1);
        }
    };
    match runx_cli::config::run_config_command(&plan, &runx_cli::history::env_map(), &cwd) {
        Ok(output) => write_stdout(&output),
        Err(runx_cli::config::ConfigCliError::InvalidArgs(message)) => {
            let _ignored = write_stderr_line(&format!("runx: {message}"));
            ExitCode::from(64)
        }
        Err(error) => {
            let _ignored = write_stderr_line(&format!("runx: {error}"));
            ExitCode::from(1)
        }
    }
}

fn run_native_harness(plan: HarnessPlan) -> ExitCode {
    if contains_skill_package(&plan.fixture_paths) {
        let [target] = plan.fixture_paths.as_slice() else {
            let _ignored = write_stderr_line(
                "runx harness accepts one skill package, or one or more fixture files, not a mix",
            );
            return ExitCode::from(64);
        };
        return run_inline_harness(Path::new(target), plan.receipt_dir.as_ref());
    }
    run_standalone_harness(plan.fixture_paths)
}

fn run_standalone_harness(fixture_paths: Vec<OsString>) -> ExitCode {
    let mut outputs = Vec::new();
    let orchestrator = runx_cli::runtime::local_orchestrator();
    for fixture_path in fixture_paths {
        let request = runx_runtime::HarnessRunRequest {
            fixture_path: PathBuf::from(fixture_path),
        };
        match orchestrator.run_harness_fixture(&request) {
            Ok(output) => {
                if let Err(error) = runx_cli::runtime::persist_payment_ledger_projection(&output) {
                    let _ignored = write_stderr_line(&format!(
                        "runx: payment ledger projection failed: {error}"
                    ));
                    return ExitCode::from(1);
                }
                outputs.push(
                    match serde_json::to_value(&output.receipt)
                        .and_then(serde_json::from_value::<runx_contracts::JsonValue>)
                    {
                        Ok(value) => value,
                        Err(error) => {
                            let _ignored = write_stderr_line(&format!(
                                "runx: failed to serialize receipt: {error}"
                            ));
                            return ExitCode::from(1);
                        }
                    },
                );
            }
            Err(error) => {
                let _ignored = write_stderr_line(&format!(
                    "runx: native harness replay failed for {}: {error}",
                    request.fixture_path.display()
                ));
                return ExitCode::from(1);
            }
        }
    }
    write_harness_receipts(outputs)
}

fn write_harness_receipts(mut outputs: Vec<runx_contracts::JsonValue>) -> ExitCode {
    let output = if outputs.len() == 1 {
        outputs.pop().unwrap_or(runx_contracts::JsonValue::Null)
    } else {
        runx_contracts::JsonValue::Array(outputs)
    };
    match serde_json::to_string_pretty(&output) {
        Ok(json) => write_stdout_line(&json),
        Err(error) => {
            let _ignored =
                write_stderr_line(&format!("runx: failed to serialize receipt: {error}"));
            ExitCode::from(1)
        }
    }
}

// A skill package (directory or SKILL.md) runs its declared inline
// `harness.cases`; standalone fixture `.yaml` files replay as receipts.
fn contains_skill_package(paths: &[OsString]) -> bool {
    paths.iter().any(|path| is_skill_package(Path::new(path)))
}

// A harness target is a skill package (run its declared inline harness) when it
// is a SKILL.md file, or a directory that actually holds a skill package
// (a SKILL.md or X.yaml). A plain directory of fixture `.yaml` files is NOT a
// skill package and falls through to standalone fixture replay.
fn is_skill_package(path: &Path) -> bool {
    if path.is_dir() {
        return path.join("SKILL.md").exists() || path.join("X.yaml").exists();
    }
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.eq_ignore_ascii_case("SKILL.md"))
}

fn run_inline_harness(skill_path: &Path, receipt_dir: Option<&OsString>) -> ExitCode {
    let request = runx_runtime::InlineHarnessRequest {
        skill_path: skill_path.to_path_buf(),
        receipt_dir: receipt_dir.map(PathBuf::from),
        env: None,
    };
    let report = match runx_cli::runtime::local_orchestrator().run_inline_harness(&request) {
        Ok(report) => report,
        Err(error) => {
            let error_message = error.to_string();
            let _ignored = write_stderr_line(&format!(
                "runx: inline harness failed for {}: {error_message}",
                skill_path.display()
            ));
            if let Some(hint) = inline_harness_failure_hint(&error_message) {
                let _ignored = write_stderr_line(hint);
            }
            return ExitCode::from(1);
        }
    };
    if report.status == "failed" {
        if let Some(hint) = inline_harness_report_hint(&report) {
            let _ignored = write_stderr_line(hint);
        }
    }
    let json = match serde_json::to_string_pretty(&report) {
        Ok(json) => json,
        Err(error) => {
            let _ignored = write_stderr_line(&format!(
                "runx: failed to serialize harness summary: {error}"
            ));
            return ExitCode::from(1);
        }
    };
    // The summary (including a `failed` one) is the artifact a caller parses, so
    // always emit it; a `failed` suite still exits non-zero for shell use.
    let _ignored = write_stdout_line(&json);
    if report.status == "failed" {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

fn inline_harness_failure_hint(message: &str) -> Option<&'static str> {
    if is_receipt_signing_error(message) {
        return Some(INLINE_HARNESS_SIGNING_HINT);
    }
    None
}

fn inline_harness_report_hint(report: &runx_runtime::InlineHarnessReport) -> Option<&'static str> {
    if report
        .assertion_errors
        .iter()
        .any(|error| is_receipt_signing_error(error))
    {
        return Some(INLINE_HARNESS_SIGNING_HINT);
    }
    if report
        .assertion_errors
        .iter()
        .any(|error| error.contains("receipt store index is stale"))
    {
        return Some(INLINE_HARNESS_STALE_RECEIPT_STORE_HINT);
    }
    None
}

fn is_receipt_signing_error(message: &str) -> bool {
    message.contains("governed runtime receipt signing requires")
        || message.contains("production receipt signing requires")
        || message.contains("production receipt signer")
}

fn write_stdout(message: &str) -> ExitCode {
    let mut stdout = io::stdout().lock();
    if stdout.write_all(message.as_bytes()).is_ok() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

fn write_json_failure(message: &str, code: &str, exit_code: u8) -> ExitCode {
    let output = runx_cli::router::json_failure_output(message, code);
    let mut stdout = io::stdout().lock();
    if stdout.write_all(output.as_bytes()).is_ok() {
        ExitCode::from(exit_code)
    } else {
        ExitCode::from(1)
    }
}

fn write_stdout_line(message: &str) -> ExitCode {
    let mut stdout = io::stdout().lock();
    if writeln!(stdout, "{message}").is_ok() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

fn write_stderr_line(message: &str) -> ExitCode {
    let mut stderr = io::stderr().lock();
    if writeln!(stderr, "{message}").is_ok() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn inline_harness_report_hint_recognizes_missing_signer() {
        let report = failed_inline_harness_report(
            "smoke: skill run failed: governed runtime receipt signing requires RUNX_RECEIPT_SIGN_KID, RUNX_RECEIPT_SIGN_ED25519_SEED_BASE64, and RUNX_RECEIPT_SIGN_ISSUER_TYPE",
        );

        assert_eq!(
            inline_harness_report_hint(&report),
            Some(INLINE_HARNESS_SIGNING_HINT)
        );
    }

    #[test]
    fn inline_harness_report_hint_recognizes_stale_receipt_store() {
        let report = failed_inline_harness_report(
            "smoke: receipt store index is stale: receipt proof is invalid for sha256:abc",
        );

        assert_eq!(
            inline_harness_report_hint(&report),
            Some(INLINE_HARNESS_STALE_RECEIPT_STORE_HINT)
        );
    }

    fn failed_inline_harness_report(error: &str) -> runx_runtime::InlineHarnessReport {
        runx_runtime::InlineHarnessReport {
            status: "failed",
            case_count: 1,
            assertion_error_count: 1,
            assertion_errors: vec![error.to_owned()],
            case_names: vec!["smoke".to_owned()],
            receipt_ids: Vec::new(),
            graph_case_count: 0,
        }
    }
}