cobre-cli 0.5.1

Command-line interface for Cobre power system studies
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! CLI error type with exit code mapping and terminal formatting.
//!
//! [`CliError`] is the single error type returned by all subcommand functions.
//! It maps library errors to structured CLI exit codes and produces
//! human-readable diagnostic output with actionable hints.
//!
//! # Exit codes
//!
//! | Code | Variant | Cause |
//! |------|---------|-------|
//! | 1 | [`CliError::Validation`] | Case directory failed validation |
//! | 2 | [`CliError::Io`] | File missing, permission denied, disk full |
//! | 3 | [`CliError::Solver`] | LP infeasible or solver error during training/simulation |
//! | 4 | [`CliError::Internal`] | Communication failure, unexpected state, channel crash |

use console::Term;

/// Errors that can occur during CLI command execution.
///
/// Each variant maps to a specific exit code and carries enough context
/// for [`CliError::format_error`] to print an actionable diagnostic to stderr.
///
/// # Examples
///
/// ```
/// use cobre_cli::error::CliError;
///
/// let err = CliError::Validation {
///     report: "constraint violation: hydro cascade contains a cycle".to_string(),
/// };
/// assert_eq!(err.exit_code(), 1);
/// assert!(!err.to_string().is_empty());
/// ```
#[derive(Debug, thiserror::Error)]
pub enum CliError {
    /// Case directory failed the validation pipeline (exit code 1).
    ///
    /// Covers schema errors, cross-reference errors, semantic constraint
    /// violations, and policy compatibility mismatches detected during
    /// `cobre_io::load_case`.
    #[error("validation error: {report}")]
    Validation {
        /// Human-readable summary of the validation failure.
        report: String,
    },

    /// Filesystem I/O error (exit code 2).
    ///
    /// Covers file-not-found, permission denied, disk full, and write
    /// failures in both the loading pipeline and the output writers.
    #[error("I/O error in {context}: {source}")]
    Io {
        /// Underlying I/O error.
        source: std::io::Error,
        /// Path or operation description that provides context for the failure.
        context: String,
    },

    /// LP solver error during training or simulation (exit code 3).
    ///
    /// Covers infeasible subproblems and numerical solver failures. The
    /// training loop performs a hard stop when this error is returned.
    #[error("solver error: {message}")]
    Solver {
        /// Human-readable description of the solver failure.
        message: String,
    },

    /// Internal or communication error (exit code 4).
    ///
    /// Covers distributed communication failures, stochastic model errors,
    /// unexpected channel closures, and other conditions that indicate a
    /// software or environment problem rather than a user error.
    #[error("internal error: {message}")]
    Internal {
        /// Human-readable description of the internal failure.
        message: String,
    },
}

impl CliError {
    /// Return the process exit code for this error.
    ///
    /// # Examples
    ///
    /// ```
    /// use cobre_cli::error::CliError;
    ///
    /// assert_eq!(CliError::Validation { report: "bad".to_string() }.exit_code(), 1);
    /// assert_eq!(CliError::Solver { message: "infeasible".to_string() }.exit_code(), 3);
    /// ```
    pub fn exit_code(&self) -> i32 {
        match self {
            Self::Validation { .. } => 1,
            Self::Io { .. } => 2,
            Self::Solver { .. } => 3,
            Self::Internal { .. } => 4,
        }
    }

    /// Print a structured, colored diagnostic to `stderr`.
    ///
    /// Uses `console::style` for colored labels: `error:` in bold red,
    /// hint lines prefixed with `->` in yellow. Colors are suppressed
    /// automatically when the terminal is not interactive or when
    /// `NO_COLOR` is set (handled by the `console` crate).
    ///
    /// # Examples
    ///
    /// ```
    /// use cobre_cli::error::CliError;
    /// use console::Term;
    ///
    /// let err = CliError::Solver { message: "LP infeasible at stage 12".to_string() };
    /// let stderr = Term::stderr();
    /// err.format_error(&stderr);
    /// ```
    pub fn format_error(&self, stderr: &Term) {
        let label = console::style("error:").red().bold();
        let hint_arrow = console::style("->").yellow();

        match self {
            Self::Validation { report } => {
                let _ = stderr.write_line(&format!("{label} {report}"));
                let _ = stderr.write_line(&format!(
                    "  {hint_arrow} run `cobre validate <CASE_DIR>` for a full diagnostic report"
                ));
            }
            Self::Io { source, context } => {
                let _ = stderr.write_line(&format!("{label} I/O error in {context}: {source}"));
                let _ = stderr.write_line(&format!(
                    "  {hint_arrow} check that the path exists and you have read/write permissions"
                ));
            }
            Self::Solver { message } => {
                let _ = stderr.write_line(&format!("{label} {message}"));
                let _ = stderr.write_line(&format!(
                    "  {hint_arrow} check constraint bounds (hydros may have conflicting min/max storage)"
                ));
                let _ = stderr.write_line(&format!(
                    "  {hint_arrow} run `cobre validate <CASE_DIR>` for a full diagnostic report"
                ));
            }
            Self::Internal { message } => {
                let _ = stderr.write_line(&format!("{label} {message}"));
                let _ = stderr.write_line(&format!(
                    "  {hint_arrow} this may indicate a software or environment problem"
                ));
                let _ = stderr.write_line(&format!(
                    "  {hint_arrow} report this at https://github.com/cobre-rs/cobre/issues"
                ));
            }
        }
    }
}

impl From<cobre_io::LoadError> for CliError {
    fn from(err: cobre_io::LoadError) -> Self {
        match err {
            cobre_io::LoadError::IoError { path, source } => Self::Io {
                source,
                context: path.display().to_string(),
            },
            other => Self::Validation {
                report: other.to_string(),
            },
        }
    }
}

impl From<cobre_io::OutputError> for CliError {
    fn from(err: cobre_io::OutputError) -> Self {
        match err {
            cobre_io::OutputError::IoError { path, source } => Self::Io {
                source,
                context: path.display().to_string(),
            },
            other => Self::Internal {
                message: other.to_string(),
            },
        }
    }
}

impl From<cobre_comm::BackendError> for CliError {
    fn from(err: cobre_comm::BackendError) -> Self {
        Self::Internal {
            message: format!("communication backend error: {err}"),
        }
    }
}

impl From<cobre_sddp::SddpError> for CliError {
    fn from(err: cobre_sddp::SddpError) -> Self {
        match err {
            cobre_sddp::SddpError::Infeasible {
                stage,
                iteration,
                scenario,
            } => Self::Solver {
                message: format!(
                    "LP infeasible at stage {stage}, iteration {iteration}, scenario {scenario}"
                ),
            },
            cobre_sddp::SddpError::Solver(solver_err) => Self::Solver {
                message: solver_err.to_string(),
            },
            cobre_sddp::SddpError::Io(load_err) => Self::from(load_err),
            cobre_sddp::SddpError::Validation(msg) => Self::Validation { report: msg },
            cobre_sddp::SddpError::Communication(comm_err) => Self::Internal {
                message: comm_err.to_string(),
            },
            cobre_sddp::SddpError::Simulation(msg) => Self::Internal { message: msg },
            cobre_sddp::SddpError::Stochastic(stoch_err) => Self::Internal {
                message: stoch_err.to_string(),
            },
        }
    }
}

impl From<cobre_sddp::SimulationError> for CliError {
    fn from(err: cobre_sddp::SimulationError) -> Self {
        match err {
            cobre_sddp::SimulationError::LpInfeasible {
                scenario_id,
                stage_id,
                solver_message,
            } => Self::Solver {
                message: format!(
                    "LP infeasible at scenario {scenario_id}, stage {stage_id}: {solver_message}"
                ),
            },
            cobre_sddp::SimulationError::SolverError {
                scenario_id,
                stage_id,
                solver_message,
            } => Self::Solver {
                message: format!(
                    "solver error at scenario {scenario_id}, stage {stage_id}: {solver_message}"
                ),
            },
            other => Self::Internal {
                message: other.to_string(),
            },
        }
    }
}

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

    #[test]
    fn validation_exit_code_is_1() {
        let err = CliError::Validation {
            report: "constraint violation".to_string(),
        };
        assert_eq!(err.exit_code(), 1);
    }

    #[test]
    fn io_exit_code_is_2() {
        let err = CliError::Io {
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
            context: "system/hydros.json".to_string(),
        };
        assert_eq!(err.exit_code(), 2);
    }

    #[test]
    fn solver_exit_code_is_3() {
        let err = CliError::Solver {
            message: "LP infeasible at stage 5".to_string(),
        };
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn internal_exit_code_is_4() {
        let err = CliError::Internal {
            message: "channel closed unexpectedly".to_string(),
        };
        assert_eq!(err.exit_code(), 4);
    }

    #[test]
    fn display_validation_non_empty() {
        let err = CliError::Validation {
            report: "hydro cascade contains a cycle".to_string(),
        };
        let s = err.to_string();
        assert!(!s.is_empty());
        assert!(s.contains("hydro cascade contains a cycle"), "{s}");
    }

    #[test]
    fn display_io_non_empty() {
        let err = CliError::Io {
            source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied"),
            context: "output/results".to_string(),
        };
        let s = err.to_string();
        assert!(!s.is_empty());
        assert!(s.contains("output/results"), "{s}");
        assert!(s.contains("permission denied"), "{s}");
    }

    #[test]
    fn display_solver_non_empty() {
        let err = CliError::Solver {
            message: "LP infeasible at stage 12, iteration 3, scenario 47".to_string(),
        };
        let s = err.to_string();
        assert!(!s.is_empty());
        assert!(s.contains("stage 12"), "{s}");
    }

    #[test]
    fn display_internal_non_empty() {
        let err = CliError::Internal {
            message: "allgatherv timed out".to_string(),
        };
        let s = err.to_string();
        assert!(!s.is_empty());
        assert!(s.contains("allgatherv timed out"), "{s}");
    }

    #[test]
    fn from_load_error_io_maps_to_cli_io() {
        use std::path::PathBuf;

        let load_err = cobre_io::LoadError::IoError {
            path: PathBuf::from("system/hydros.json"),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "no such file"),
        };
        let cli_err = CliError::from(load_err);
        assert!(
            matches!(cli_err, CliError::Io { .. }),
            "LoadError::IoError must map to CliError::Io, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 2);
    }

    #[test]
    fn from_load_error_constraint_maps_to_validation() {
        let load_err = cobre_io::LoadError::ConstraintError {
            description: "hydro cascade contains a cycle".to_string(),
        };
        let cli_err = CliError::from(load_err);
        assert!(
            matches!(cli_err, CliError::Validation { .. }),
            "LoadError::ConstraintError must map to CliError::Validation, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 1);
    }

    #[test]
    fn from_load_error_schema_maps_to_validation() {
        use std::path::PathBuf;

        let load_err = cobre_io::LoadError::SchemaError {
            path: PathBuf::from("system/buses.json"),
            field: "voltage".to_string(),
            message: "must be positive".to_string(),
        };
        let cli_err = CliError::from(load_err);
        assert!(
            matches!(cli_err, CliError::Validation { .. }),
            "LoadError::SchemaError must map to CliError::Validation, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 1);
    }

    #[test]
    fn from_load_error_cross_reference_maps_to_validation() {
        use std::path::PathBuf;

        let load_err = cobre_io::LoadError::CrossReferenceError {
            source_file: PathBuf::from("system/hydros.json"),
            source_entity: "Hydro 'H1'".to_string(),
            target_collection: "bus registry".to_string(),
            target_entity: "BUS_99".to_string(),
        };
        let cli_err = CliError::from(load_err);
        assert!(
            matches!(cli_err, CliError::Validation { .. }),
            "LoadError::CrossReferenceError must map to CliError::Validation, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 1);
    }

    #[test]
    fn from_sddp_error_infeasible_maps_to_solver() {
        let sddp_err = cobre_sddp::SddpError::Infeasible {
            stage: 5,
            iteration: 42,
            scenario: 3,
        };
        let cli_err = CliError::from(sddp_err);
        assert!(
            matches!(cli_err, CliError::Solver { .. }),
            "SddpError::Infeasible must map to CliError::Solver, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 3);
    }

    #[test]
    fn from_sddp_error_solver_maps_to_solver() {
        let sddp_err = cobre_sddp::SddpError::Solver(cobre_solver::SolverError::Infeasible);
        let cli_err = CliError::from(sddp_err);
        assert!(
            matches!(cli_err, CliError::Solver { .. }),
            "SddpError::Solver must map to CliError::Solver, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 3);
    }

    #[test]
    fn from_sddp_error_io_maps_to_cli_io_or_validation() {
        use std::path::PathBuf;

        // LoadError::IoError inside SddpError::Io -> CliError::Io
        let load_io = cobre_io::LoadError::IoError {
            path: PathBuf::from("system/hydros.json"),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
        };
        let sddp_err = cobre_sddp::SddpError::Io(load_io);
        let cli_err = CliError::from(sddp_err);
        assert!(
            matches!(cli_err, CliError::Io { .. }),
            "SddpError::Io(LoadError::IoError) must map to CliError::Io, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 2);
    }

    #[test]
    fn from_sddp_error_validation_maps_to_validation() {
        let sddp_err = cobre_sddp::SddpError::Validation("forward_passes must be > 0".to_string());
        let cli_err = CliError::from(sddp_err);
        assert!(
            matches!(cli_err, CliError::Validation { .. }),
            "SddpError::Validation must map to CliError::Validation, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 1);
    }

    #[test]
    fn from_sddp_error_communication_maps_to_internal() {
        let sddp_err =
            cobre_sddp::SddpError::Communication(cobre_comm::CommError::CollectiveFailed {
                operation: "allgatherv",
                mpi_error_code: 1,
                message: "timed out".to_string(),
            });
        let cli_err = CliError::from(sddp_err);
        assert!(
            matches!(cli_err, CliError::Internal { .. }),
            "SddpError::Communication must map to CliError::Internal, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 4);
    }

    #[test]
    fn from_sddp_error_stochastic_maps_to_internal() {
        let stoch_err = cobre_stochastic::StochasticError::InsufficientData {
            context: "hydro 7 has only 2 observations".to_string(),
        };
        let sddp_err = cobre_sddp::SddpError::Stochastic(stoch_err);
        let cli_err = CliError::from(sddp_err);
        assert!(
            matches!(cli_err, CliError::Internal { .. }),
            "SddpError::Stochastic must map to CliError::Internal, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 4);
    }

    #[test]
    fn from_sddp_error_simulation_maps_to_internal() {
        let sddp_err = cobre_sddp::SddpError::Simulation("output channel closed".to_string());
        let cli_err = CliError::from(sddp_err);
        assert!(
            matches!(cli_err, CliError::Internal { .. }),
            "SddpError::Simulation must map to CliError::Internal, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 4);
    }

    #[test]
    fn from_simulation_error_lp_infeasible_maps_to_solver() {
        let sim_err = cobre_sddp::SimulationError::LpInfeasible {
            scenario_id: 5,
            stage_id: 3,
            solver_message: "primal infeasible".to_string(),
        };
        let cli_err = CliError::from(sim_err);
        assert!(
            matches!(cli_err, CliError::Solver { .. }),
            "SimulationError::LpInfeasible must map to CliError::Solver, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 3);
    }

    #[test]
    fn from_simulation_error_solver_error_maps_to_solver() {
        let sim_err = cobre_sddp::SimulationError::SolverError {
            scenario_id: 10,
            stage_id: 7,
            solver_message: "numerical difficulties".to_string(),
        };
        let cli_err = CliError::from(sim_err);
        assert!(
            matches!(cli_err, CliError::Solver { .. }),
            "SimulationError::SolverError must map to CliError::Solver, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 3);
    }

    #[test]
    fn from_simulation_error_io_maps_to_internal() {
        let sim_err = cobre_sddp::SimulationError::IoError {
            message: "disk full".to_string(),
        };
        let cli_err = CliError::from(sim_err);
        assert!(
            matches!(cli_err, CliError::Internal { .. }),
            "SimulationError::IoError must map to CliError::Internal, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 4);
    }

    #[test]
    fn from_simulation_error_policy_incompatible_maps_to_internal() {
        let sim_err = cobre_sddp::SimulationError::PolicyIncompatible {
            message: "hydro count mismatch".to_string(),
        };
        let cli_err = CliError::from(sim_err);
        assert!(
            matches!(cli_err, CliError::Internal { .. }),
            "SimulationError::PolicyIncompatible must map to CliError::Internal, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 4);
    }

    #[test]
    fn from_simulation_error_channel_closed_maps_to_internal() {
        let sim_err = cobre_sddp::SimulationError::ChannelClosed;
        let cli_err = CliError::from(sim_err);
        assert!(
            matches!(cli_err, CliError::Internal { .. }),
            "SimulationError::ChannelClosed must map to CliError::Internal, got: {cli_err:?}"
        );
        assert_eq!(cli_err.exit_code(), 4);
    }

    #[test]
    fn from_backend_error_maps_to_internal() {
        let err = cobre_comm::BackendError::InvalidBackend {
            requested: "foobar".to_string(),
            available: vec!["local".to_string()],
        };
        let cli_err = CliError::from(err);
        assert!(matches!(cli_err, CliError::Internal { .. }));
        assert_eq!(cli_err.exit_code(), 4);
    }
}