subx-cli 2.0.0

AI subtitle processing CLI tool, which automatically matches, renames, and converts subtitle files.
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
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Binary-owned presentation extensions for [`SubXError`].
//!
//! The `SubXError` taxonomy itself lives in [`subx_core::error`] and ships with
//! the library half of the split (`subx-core`): `category()`, `machine_code()`
//! and `hint()` are inherent methods there because machine-readable front
//! ends (e.g. the Tauri GUI) consume them directly.
//!
//! Process exit codes and multi-line terminal prose with `Hint:` lines,
//! however, are properties of running the `subx-cli` binary — a library
//! consumer embeds `SubXError` in its own presentation layer and has neither
//! a process exit code nor a terminal. Those two operations therefore live
//! here, as an extension trait owned by the binary:
//!
//! - [`SubXErrorExt::exit_code`] — the stable 1–6 process exit mapping.
//! - [`SubXErrorExt::user_friendly_message`] — the multi-line, hinted,
//!   terminal-facing message.
//!
//! Code under `src/core/` and `src/services/` SHALL NOT import this trait or
//! call either method; core code that needs a rendered message uses
//! `Display` (`to_string()`), optionally combined with `hint()`.

use subx_core::error::SubXError;

/// Presentation-layer extensions to [`SubXError`] owned by the binary.
pub trait SubXErrorExt {
    /// Return the corresponding exit code for this error variant.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// # use subx_cli::cli::SubXErrorExt;
    /// assert_eq!(SubXError::config("x").exit_code(), 2);
    /// ```
    fn exit_code(&self) -> i32;

    /// Return a user-friendly error message with suggested remedies.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use subx_cli::error::SubXError;
    /// # use subx_cli::cli::SubXErrorExt;
    /// let msg = SubXError::config("missing key").user_friendly_message();
    /// assert!(msg.contains("Configuration error:"));
    /// ```
    fn user_friendly_message(&self) -> String;
}

impl SubXErrorExt for SubXError {
    fn exit_code(&self) -> i32 {
        match self {
            SubXError::Io(_) => 1,
            SubXError::Config { .. } => 2,
            SubXError::Api { .. } => 3,
            SubXError::AiService(_) => 3,
            SubXError::SubtitleFormat { .. } => 4,
            SubXError::AudioProcessing { .. } => 5,
            SubXError::FileMatching { .. } => 6,
            _ => 1,
        }
    }

    fn user_friendly_message(&self) -> String {
        match self {
            SubXError::Io(e) => format!("File operation error: {}", e),
            SubXError::Config { message } => format!(
                "Configuration error: {}\nHint: run 'subx-cli config --help' for details",
                message
            ),
            SubXError::Api { message, source } => format!(
                "API error ({:?}): {}\nHint: check network connection and API key settings",
                source, message
            ),
            SubXError::AiService(msg) => format!(
                "AI service error: {}\nHint: check network connection and API key settings",
                msg
            ),
            SubXError::SubtitleFormat { message, .. } => format!(
                "Subtitle processing error: {}\nHint: check file format and encoding",
                message
            ),
            SubXError::AudioProcessing { message } => format!(
                "Audio processing error: {}\nHint: ensure media file integrity and support",
                message
            ),
            SubXError::FileMatching { message } => format!(
                "File matching error: {}\nHint: verify file paths and patterns",
                message
            ),
            SubXError::FileAlreadyExists(path) => format!("File already exists: {}", path),
            SubXError::FileNotFound(path) => format!("File not found: {}", path),
            SubXError::InvalidFileName(name) => format!("Invalid file name: {}", name),
            SubXError::FileOperationFailed(msg) => format!("File operation failed: {}", msg),
            SubXError::CommandExecution(msg) => msg.clone(),
            SubXError::OutputModeUnsupported { command } => format!(
                "The '{}' command does not support --output json; its stdout is a shell-completion script.\nHint: rerun without --output json (and ensure SUBX_OUTPUT is unset)",
                command
            ),
            SubXError::Other(err) => {
                format!("Unknown error: {}\nHint: please report this issue", err)
            }
            _ => format!("Error: {}", self),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io;
    use std::path::PathBuf;
    use subx_core::error::ApiErrorSource;

    // ── exit_code mapping ─────────────────────────────────────────────────────
    //
    // These tests moved here with the two presentation methods (change
    // relocate-misplaced-core-modules, Decision 4): `exit_code()` and
    // `user_friendly_message()` are trait methods now, so their coverage
    // lives with the trait.

    #[test]
    fn test_exit_codes() {
        assert_eq!(SubXError::config("test").exit_code(), 2);
        assert_eq!(SubXError::subtitle_format("SRT", "test").exit_code(), 4);
        assert_eq!(SubXError::audio_processing("test").exit_code(), 5);
        assert_eq!(SubXError::file_matching("test").exit_code(), 6);
    }

    #[test]
    fn test_user_friendly_messages() {
        let config_error = SubXError::config("missing key");
        let message = config_error.user_friendly_message();
        assert!(message.contains("Configuration error:"));
        assert!(message.contains("subx-cli config --help"));

        let ai_error = SubXError::ai_service("network failure".to_string());
        let message = ai_error.user_friendly_message();
        assert!(message.contains("AI service error:"));
        assert!(message.contains("check network connection"));
    }

    /// Audit: enumerates every `SubXError` variant and asserts that a
    /// representative instance — built from non-sensitive dummy data —
    /// never surfaces an OpenAI-style API key prefix (`sk-`) through
    /// `Display`, `Debug`, or `user_friendly_message()`. If you add a
    /// new variant, extend this list so the audit remains exhaustive.
    ///
    /// Separately, this test also exercises the sanitizing construction
    /// paths (`From<reqwest::Error>`-style flows via the AI client's
    /// `error_sanitizer` helpers) to confirm that when input *does*
    /// contain an `sk-*` secret, it is stripped before wrapping it in
    /// `SubXError::AiService`.
    ///
    /// The `Display`/`Debug` half of this audit — the same exhaustive
    /// variant list — lives in the `subx-core` repository's `src/error.rs`
    /// (`test_no_api_key_leaks_in_any_variant`), beside the code that
    /// defines the variants. Keep the two variant lists in step; updating
    /// one without the other half-defeats the `secrets-protection` audit.
    #[test]
    fn test_no_api_key_leaks_in_any_variant() {
        use std::path::PathBuf;
        use subx_core::services::ai::error_sanitizer::{
            DEFAULT_ERROR_BODY_MAX_LEN, sanitize_url_in_error, truncate_error_body,
        };

        // 1. Canonical variant audit: benign dummy data must never yield
        //    an `sk-` substring.
        let variants: Vec<SubXError> = vec![
            SubXError::Io(io::Error::other("disk error")),
            SubXError::Config {
                message: "missing key".to_string(),
            },
            SubXError::SubtitleFormat {
                format: "SRT".to_string(),
                message: "bad timestamp".to_string(),
            },
            SubXError::AiService("upstream service failed".to_string()),
            SubXError::Api {
                message: "auth failed".to_string(),
                source: ApiErrorSource::OpenAI,
            },
            SubXError::AudioProcessing {
                message: "codec failure".to_string(),
            },
            SubXError::FileMatching {
                message: "pattern mismatch".to_string(),
            },
            SubXError::FileAlreadyExists("/tmp/example".to_string()),
            SubXError::FileNotFound("/tmp/example".to_string()),
            SubXError::InvalidFileName("bad?name".to_string()),
            SubXError::FileOperationFailed("rename failed".to_string()),
            SubXError::CommandExecution("exit 1".to_string()),
            SubXError::NoInputSpecified,
            SubXError::InvalidPath(PathBuf::from("/tmp/example")),
            SubXError::PathNotFound(PathBuf::from("/tmp/example")),
            SubXError::DirectoryReadError {
                path: PathBuf::from("/tmp/example"),
                source: io::Error::other("denied"),
            },
            SubXError::InvalidSyncConfiguration,
            SubXError::UnsupportedFileType("xyz".to_string()),
            SubXError::OutputModeUnsupported {
                command: "generate-completion".to_string(),
            },
            SubXError::Other(anyhow::anyhow!("wrapped")),
        ];

        for err in &variants {
            let display = format!("{}", err);
            let debug = format!("{:?}", err);
            let friendly = err.user_friendly_message();
            for (label, text) in [
                ("Display", &display),
                ("Debug", &debug),
                ("friendly", &friendly),
            ] {
                assert!(
                    !text.contains("sk-"),
                    "{} surface for variant {:?} contains `sk-` prefix: {}",
                    label,
                    err,
                    text
                );
            }
        }

        // 2. Sanitizing construction paths: API keys injected via the
        //    upstream response body or URL query string must be stripped
        //    before being embedded into `SubXError::AiService`.
        const SECRET: &str = "sk-test-key-12345";
        let upstream_body = format!(
            "{{\"error\": \"invalid\", \"echoed\": \"Bearer {}\"}}",
            SECRET
        );
        let truncated = truncate_error_body(&upstream_body, DEFAULT_ERROR_BODY_MAX_LEN);
        // Helper does not itself mask secrets shorter than the limit; this
        // documents that short bodies pass through unchanged so upstream
        // callers must continue to keep secrets out of request bodies.
        assert!(truncated.contains(SECRET));

        let url_leak = format!(
            "request error: https://api.example.com/v1/chat?api-key={}",
            SECRET
        );
        let cleaned = sanitize_url_in_error(&url_leak);
        assert!(!cleaned.contains("sk-test-key"));
        let wrapped = SubXError::AiService(cleaned);
        assert!(!format!("{}", wrapped).contains("sk-test-key"));
        assert!(!format!("{:?}", wrapped).contains("sk-test-key"));
    }

    // ── exit_code – remaining variants ───────────────────────────────────────

    #[test]
    fn test_exit_code_io() {
        let err = SubXError::Io(io::Error::new(io::ErrorKind::NotFound, "x"));
        assert_eq!(err.exit_code(), 1);
    }

    #[test]
    fn test_exit_code_api() {
        let err = SubXError::Api {
            message: "x".to_string(),
            source: ApiErrorSource::OpenAI,
        };
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn test_exit_code_ai_service() {
        let err = SubXError::AiService("x".to_string());
        assert_eq!(err.exit_code(), 3);
    }

    #[test]
    fn test_exit_code_catchall_variants() {
        assert_eq!(SubXError::FileAlreadyExists("f".to_string()).exit_code(), 1);
        assert_eq!(SubXError::FileNotFound("f".to_string()).exit_code(), 1);
        assert_eq!(SubXError::InvalidFileName("f".to_string()).exit_code(), 1);
        assert_eq!(
            SubXError::FileOperationFailed("f".to_string()).exit_code(),
            1
        );
        assert_eq!(SubXError::CommandExecution("f".to_string()).exit_code(), 1);
        assert_eq!(SubXError::NoInputSpecified.exit_code(), 1);
        assert_eq!(SubXError::InvalidPath(PathBuf::from("/x")).exit_code(), 1);
        assert_eq!(SubXError::PathNotFound(PathBuf::from("/x")).exit_code(), 1);
        assert_eq!(SubXError::InvalidSyncConfiguration.exit_code(), 1);
        assert_eq!(
            SubXError::UnsupportedFileType("xyz".to_string()).exit_code(),
            1
        );
        assert_eq!(SubXError::Other(anyhow::anyhow!("other")).exit_code(), 1);
    }

    // ── category / machine_code / exit_code contract ────────────────────────

    /// Exhaustive contract test for the closed `SubXError` mapping locked
    /// by `specs/error-handling/spec.md`. If a new variant is added, this
    /// test (and the exhaustive matches in `category()`/`machine_code()`)
    /// SHALL be updated; the compiler-enforced exhaustive match guards
    /// the source of truth. It lives here (not in `src/error.rs`) because
    /// the `exit_code` column is a `SubXErrorExt` method.
    #[test]
    fn test_category_and_machine_code_contract() {
        let cases: Vec<(SubXError, &'static str, &'static str, i32)> = vec![
            (SubXError::Io(io::Error::other("x")), "io", "E_IO", 1),
            (
                SubXError::Config {
                    message: "x".into(),
                },
                "config",
                "E_CONFIG",
                2,
            ),
            (
                SubXError::SubtitleFormat {
                    format: "SRT".into(),
                    message: "x".into(),
                },
                "subtitle_format",
                "E_SUBTITLE_FORMAT",
                4,
            ),
            (
                SubXError::AiService("x".into()),
                "ai_service",
                "E_AI_SERVICE",
                3,
            ),
            (
                SubXError::Api {
                    message: "x".into(),
                    source: ApiErrorSource::OpenAI,
                },
                "api",
                "E_API",
                3,
            ),
            (
                SubXError::AudioProcessing {
                    message: "x".into(),
                },
                "audio_processing",
                "E_AUDIO_PROCESSING",
                5,
            ),
            (
                SubXError::FileMatching {
                    message: "x".into(),
                },
                "file_matching",
                "E_FILE_MATCHING",
                6,
            ),
            (
                SubXError::FileAlreadyExists("x".into()),
                "file_already_exists",
                "E_FILE_ALREADY_EXISTS",
                1,
            ),
            (
                SubXError::FileNotFound("x".into()),
                "file_not_found",
                "E_FILE_NOT_FOUND",
                1,
            ),
            (
                SubXError::InvalidFileName("x".into()),
                "invalid_file_name",
                "E_INVALID_FILE_NAME",
                1,
            ),
            (
                SubXError::FileOperationFailed("x".into()),
                "file_operation_failed",
                "E_FILE_OPERATION_FAILED",
                1,
            ),
            (
                SubXError::CommandExecution("x".into()),
                "command_execution",
                "E_COMMAND_EXECUTION",
                1,
            ),
            (
                SubXError::OutputModeUnsupported {
                    command: "generate-completion".into(),
                },
                "command_execution",
                "E_OUTPUT_MODE_UNSUPPORTED",
                1,
            ),
            (
                SubXError::NoInputSpecified,
                "no_input_specified",
                "E_NO_INPUT_SPECIFIED",
                1,
            ),
            (
                SubXError::InvalidPath(PathBuf::from("/x")),
                "invalid_path",
                "E_INVALID_PATH",
                1,
            ),
            (
                SubXError::PathNotFound(PathBuf::from("/x")),
                "path_not_found",
                "E_PATH_NOT_FOUND",
                1,
            ),
            (
                SubXError::DirectoryReadError {
                    path: PathBuf::from("/x"),
                    source: io::Error::other("denied"),
                },
                "directory_read_error",
                "E_DIRECTORY_READ_ERROR",
                1,
            ),
            (
                SubXError::InvalidSyncConfiguration,
                "invalid_sync_configuration",
                "E_INVALID_SYNC_CONFIGURATION",
                1,
            ),
            (
                SubXError::UnsupportedFileType("xyz".into()),
                "unsupported_file_type",
                "E_UNSUPPORTED_FILE_TYPE",
                1,
            ),
            (
                SubXError::Other(anyhow::anyhow!("x")),
                "other",
                "E_OTHER",
                1,
            ),
        ];

        for (err, cat, code, exit) in &cases {
            assert_eq!(err.category(), *cat, "category mismatch for {:?}", err);
            assert_eq!(
                err.machine_code(),
                *code,
                "machine_code mismatch for {:?}",
                err
            );
            assert_eq!(err.exit_code(), *exit, "exit_code mismatch for {:?}", err);
            assert!(!err.category().is_empty());
            assert!(err.machine_code().starts_with("E_"));
        }
    }

    // ── user_friendly_message – all variants ─────────────────────────────────

    #[test]
    fn test_user_friendly_message_io() {
        let err = SubXError::Io(io::Error::new(io::ErrorKind::PermissionDenied, "denied"));
        let msg = err.user_friendly_message();
        assert!(msg.contains("File operation error:"));
        assert!(msg.contains("denied"));
    }

    #[test]
    fn test_user_friendly_message_api() {
        let err = SubXError::Api {
            message: "forbidden".to_string(),
            source: ApiErrorSource::OpenAI,
        };
        let msg = err.user_friendly_message();
        assert!(msg.contains("API error"));
        assert!(msg.contains("forbidden"));
        assert!(msg.contains("check network connection"));
    }

    #[test]
    fn test_user_friendly_message_subtitle_format() {
        let err = SubXError::subtitle_format("ASS", "bad encoding");
        let msg = err.user_friendly_message();
        assert!(msg.contains("Subtitle processing error:"));
        assert!(msg.contains("bad encoding"));
        assert!(msg.contains("check file format"));
    }

    #[test]
    fn test_user_friendly_message_audio_processing() {
        let err = SubXError::audio_processing("corrupt frame");
        let msg = err.user_friendly_message();
        assert!(msg.contains("Audio processing error:"));
        assert!(msg.contains("corrupt frame"));
        assert!(msg.contains("media file integrity"));
    }

    #[test]
    fn test_user_friendly_message_file_matching() {
        let err = SubXError::file_matching("pattern mismatch");
        let msg = err.user_friendly_message();
        assert!(msg.contains("File matching error:"));
        assert!(msg.contains("pattern mismatch"));
        assert!(msg.contains("verify file paths"));
    }

    #[test]
    fn test_user_friendly_message_file_already_exists() {
        let err = SubXError::FileAlreadyExists("output.srt".to_string());
        assert_eq!(
            err.user_friendly_message(),
            "File already exists: output.srt"
        );
    }

    #[test]
    fn test_user_friendly_message_file_not_found() {
        let err = SubXError::FileNotFound("input.srt".to_string());
        assert_eq!(err.user_friendly_message(), "File not found: input.srt");
    }

    #[test]
    fn test_user_friendly_message_invalid_file_name() {
        let err = SubXError::InvalidFileName("bad?name".to_string());
        assert_eq!(err.user_friendly_message(), "Invalid file name: bad?name");
    }

    #[test]
    fn test_user_friendly_message_file_operation_failed() {
        let err = SubXError::FileOperationFailed("rename failed".to_string());
        assert_eq!(
            err.user_friendly_message(),
            "File operation failed: rename failed"
        );
    }

    #[test]
    fn test_user_friendly_message_command_execution() {
        let err = SubXError::CommandExecution("process died".to_string());
        assert_eq!(err.user_friendly_message(), "process died");
    }

    #[test]
    fn test_user_friendly_message_other() {
        let err = SubXError::Other(anyhow::anyhow!("mystery"));
        let msg = err.user_friendly_message();
        assert!(msg.contains("Unknown error:"));
        assert!(msg.contains("mystery"));
        assert!(msg.contains("please report this issue"));
    }

    #[test]
    fn test_user_friendly_message_catchall_variants() {
        // Variants that fall through to the `_ => format!("Error: {}", self)` arm.
        let cases: Vec<SubXError> = vec![
            SubXError::NoInputSpecified,
            SubXError::InvalidPath(PathBuf::from("/bad")),
            SubXError::PathNotFound(PathBuf::from("/missing")),
            SubXError::DirectoryReadError {
                path: PathBuf::from("/locked"),
                source: io::Error::new(io::ErrorKind::PermissionDenied, "denied"),
            },
            SubXError::InvalidSyncConfiguration,
            SubXError::UnsupportedFileType("xyz".to_string()),
        ];
        for err in &cases {
            let msg = err.user_friendly_message();
            assert!(
                msg.starts_with("Error:"),
                "Expected 'Error:' prefix for {:?}, got: {}",
                err,
                msg
            );
        }
    }

    // ── Display == user_friendly_message lock (task 5.4) ────────────────────

    /// Locks the invariant that `core::matcher::engine::operation_error_from`
    /// relies on when it renders `OperationError::message` through `Display`
    /// instead of calling the (binary-side) `user_friendly_message()`: the
    /// only variant that reaches that function — `FileOperationFailed` —
    /// renders identically through both paths, and carries no `Hint:` line
    /// that `Display` could lose. Widening the set of variants reaching
    /// `operation_error_from` without re-checking this equality silently
    /// changes the JSON per-item `error.message` contract.
    #[test]
    fn file_operation_failed_display_equals_user_friendly_message() {
        let err = SubXError::FileOperationFailed("could not rename".into());
        assert_eq!(err.to_string(), err.user_friendly_message());
        assert!(err.hint().is_none());
    }
}