seer-cli 0.51.0

Interactive CLI for Seer domain name utilities
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
//! Interactive REPL, launched when `seer` runs without a subcommand.
//!
//! A rustyline loop with tab completion ([`SeerCompleter`]) and history in
//! `~/.seer_history` (a line typed with a leading space is not recorded).
//! [`CommandContext`] holds the session state: the output format (`set
//! output`) and the user config the clients are built from. `copy` puts the
//! last result on the clipboard.

mod catalog;
mod commands;
mod completer;

pub use commands::{CommandContext, CommandResult};
pub use completer::SeerCompleter;

use std::io::Write;

use colored::Colorize;
use rustyline::error::ReadlineError;
use rustyline::history::DefaultHistory;
use rustyline::{CompletionType, Editor};
use seer_core::colors::CatppuccinExt;

use crate::display::Spinner;
use crate::query::{Clients, Query};

const HISTORY_FILE: &str = ".seer_history";

pub struct Repl {
    editor: Editor<SeerCompleter, DefaultHistory>,
    context: CommandContext,
    /// Built once from the user config and kept for the session.
    clients: Clients,
    dns_follower: seer_core::DnsFollower,
    /// Last single-result command output, for the `copy` command.
    last_result: Option<crate::payload::Payload>,
}

/// The line editor configuration. `history_ignore_space` lets a user keep a
/// sensitive query out of `~/.seer_history` by typing a leading space.
fn editor_config() -> rustyline::Config {
    rustyline::Config::builder()
        .history_ignore_space(true)
        .completion_type(CompletionType::List)
        .edit_mode(rustyline::EditMode::Emacs)
        .build()
}

/// The text recorded in history for a raw input line: trailing whitespace is
/// dropped, but LEADING whitespace must survive — rustyline decides whether to
/// honor `history_ignore_space` by looking at it. Adding the fully trimmed
/// line (as the loop used to) saved ` whois secret.com` anyway.
fn history_entry(line: &str) -> &str {
    line.trim_end()
}

impl Repl {
    pub fn new() -> anyhow::Result<Self> {
        let completer = SeerCompleter::new();
        let mut editor = Editor::with_config(editor_config())?;
        editor.set_helper(Some(completer));

        // Load history
        let history_path = std::env::home_dir()
            .map(|p| p.join(HISTORY_FILE))
            .unwrap_or_else(|| HISTORY_FILE.into());

        let _ = editor.load_history(&history_path);

        // Build clients from the user config so the REPL honors per-protocol
        // timeouts / nameserver / bulk concurrency.
        let context = CommandContext::new();
        let cfg = &context.config;

        Ok(Self {
            editor,
            clients: Clients::from_config(cfg),
            // Honor the config file's DNS timeout like `dig` does.
            dns_follower: seer_core::DnsFollower::from_config(cfg),
            last_result: None,
            context,
        })
    }

    /// Sets the session's output format, as `set output <fmt>` does. Used to
    /// carry an explicit `seer --format <fmt>` into the REPL.
    pub fn set_output_format(&mut self, format: seer_core::output::OutputFormat) {
        self.context.output_format = format;
    }

    pub async fn run(&mut self) -> anyhow::Result<()> {
        self.print_banner();

        let mut last_ctrl_c: Option<std::time::Instant> = None;

        loop {
            let prompt = self.get_prompt();

            match self.editor.readline(&prompt) {
                Ok(line) => {
                    last_ctrl_c = None;
                    let command_line = line.trim();
                    if command_line.is_empty() {
                        continue;
                    }

                    self.editor.add_history_entry(history_entry(&line))?;

                    match self.execute_line(command_line).await {
                        CommandResult::Continue => {}
                        CommandResult::Exit => break,
                        CommandResult::Error(e) => {
                            // Honor `set output json|yaml|markdown` on the
                            // error path too, so a wrapper consuming REPL
                            // output gets the same structured `{"error": ...}`
                            // shape the CLI emits.
                            match crate::utils::machine_error(self.context.output_format, &e) {
                                Some(structured) => eprintln!("{}", structured),
                                None => eprintln!("{} {}", "Error:".ctp_red().bold(), e),
                            }
                        }
                    }

                    // Add blank line before next prompt for readability
                    println!();
                }
                Err(ReadlineError::Interrupted) => {
                    if last_ctrl_c.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(2))
                    {
                        println!("exit");
                        break;
                    }
                    last_ctrl_c = Some(std::time::Instant::now());
                    println!("{}", "Press Ctrl+C again to exit (or type 'exit')".dimmed());
                    continue;
                }
                Err(ReadlineError::Eof) => {
                    println!("exit");
                    break;
                }
                Err(err) => {
                    eprintln!("{} {:?}", "Error:".ctp_red().bold(), err);
                    break;
                }
            }
        }

        // Save history
        let history_path = std::env::home_dir()
            .map(|p| p.join(HISTORY_FILE))
            .unwrap_or_else(|| HISTORY_FILE.into());

        let _ = self.editor.save_history(&history_path);

        // The history file records every queried domain/IP/ASN. Restrict it to
        // the owner (0600), mirroring the posture of the ~/.seer/* state files
        // (history.rs / watchlist.rs); it lives at ~/.seer_history, outside the
        // 0700 ~/.seer dir, so the directory mode does not protect it.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(&history_path, std::fs::Permissions::from_mode(0o600));
        }

        Ok(())
    }

    fn print_banner(&self) {
        println!();
        println!("{}", "  ✦ ·:*¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨*:· ✦".bright_cyan());
        println!("{}", "   ╔═╗    ╔═╗    ╔═╗    ╦═╗".bright_purple());
        println!("{}", "   ╚═╗    ╠═     ╠═     ╠╦╝".bright_purple());
        println!("{}", "   ╚═╝    ╚═╝    ╚═╝    ╩╚═".bright_purple());
        println!("{}", "  ✦ '·:*¨¨¨¨¨¨¨¨¨¨¨¨¨¨*:·' ✦".bright_cyan());
        println!();
        println!(
            "  {} - Domain Name Helper",
            format!("Seer v{}", env!("CARGO_PKG_VERSION"))
                .bright_purple()
                .bold()
        );
        println!("  Type {} for available commands\n", "help".bright_green());
    }

    fn get_prompt(&self) -> String {
        let format_indicator = match self.context.output_format {
            seer_core::output::OutputFormat::Human => "",
            seer_core::output::OutputFormat::Json => " [json]",
            seer_core::output::OutputFormat::Yaml => " [yaml]",
            seer_core::output::OutputFormat::Markdown => " [md]",
        };
        format!(
            "{}{} ",
            "seer".bright_cyan().bold(),
            format!("{}›", format_indicator).white()
        )
    }

    async fn execute_line(&mut self, line: &str) -> CommandResult {
        // Shell-style tokenization so quoted arguments (e.g. a bulk file path
        // containing spaces) survive — plain whitespace splitting mangled them.
        let tokens = match commands::tokenize_line(line) {
            Ok(t) => t,
            Err(e) => return CommandResult::Error(e),
        };
        let parts: Vec<&str> = tokens.iter().map(|s| s.as_str()).collect();
        if parts.is_empty() {
            return CommandResult::Continue;
        }

        let command = parts[0].to_lowercase();
        let result = self.dispatch(&command, &parts).await;

        // A failed command must not leave the PREVIOUS result behind for
        // `copy` to hand out as if it were this command's output. `copy` and
        // `set` only act on session state, so their errors (bad format name)
        // keep the buffer.
        if matches!(result, CommandResult::Error(_)) && !matches!(command.as_str(), "copy" | "set")
        {
            self.last_result = None;
        }
        result
    }

    /// Routes a tokenized line (`parts[0]` is the command as typed, `command`
    /// its lowercased form) to its handler. Everything that is not a session
    /// or multi-step command is a single-shot query (see `crate::query`).
    async fn dispatch(&mut self, command: &str, parts: &[&str]) -> CommandResult {
        let args = &parts[1..];

        match catalog::canonical(command) {
            "help" => {
                self.print_help();
                CommandResult::Continue
            }
            "exit" => CommandResult::Exit,
            "bulk" => self.execute_bulk(args).await,
            "follow" => self.execute_follow(args).await,
            "watch" => self.execute_watch(args).await,
            "history" => self.execute_history(args).await,
            "set" => self.execute_set(args),
            "copy" => self.execute_copy(args),
            "clear" => {
                print!("\x1B[2J\x1B[1;1H");
                let _ = std::io::stdout().flush();
                CommandResult::Continue
            }
            _ => match commands::parse_query(command, parts) {
                Ok(query) => self.execute_query(query).await,
                Err(e) => CommandResult::Error(e),
            },
        }
    }

    fn print_help(&self) {
        println!();
        for section in catalog::SECTIONS {
            println!("{}", section.title.bright_purple().bold());
            for command in section.commands {
                let invocation = format!("{} {}", command.name, command.usage);
                println!(
                    "  {:<34} {}",
                    invocation.trim_end().bright_cyan(),
                    command.about
                );
            }
            if let Some(note) = section.note {
                println!("  {}", note().dimmed());
            }
            println!();
        }
    }
    fn print_bulk_help(&self) {
        println!();
        println!("{}", "BULK OPERATIONS".bright_purple().bold());
        println!();
        println!("{}", "Usage:".bright_cyan());
        println!("  bulk <operation> <file> [type] [-o output.csv]");
        println!();
        println!("{}", "Operations:".bright_cyan());
        for (op, about) in crate::ops::BULK_OPS {
            println!("  {:<12} {}", op.bright_green(), about);
        }
        println!();
        println!("{}", "Input File Formats:".bright_cyan());
        println!("{}", crate::ops::BULK_INPUT_FORMATS);
        println!("{}", "Output:".bright_cyan());
        println!("  Results are written to CSV file (default: <input>_results.csv)");
        println!("  Use -o to specify custom output path");
        println!("  Each operation's CSV columns: see `seer bulk --help`");
        println!();
        println!("{}", "Examples:".bright_cyan());
        println!("  bulk status domains.txt");
        println!("  bulk lookup domains.csv -o results.csv");
        println!("  bulk dig domains.txt MX");
        println!();
    }

    /// Runs a single-shot query, prints it in the session's output format
    /// (advisory notes on stderr, as in the CLI), and keeps it for `copy`.
    async fn execute_query(&mut self, query: Query) -> CommandResult {
        match crate::query::run(query, &self.clients, &self.context.config, true).await {
            Ok(outcome) => {
                let format = self.context.output_format;
                outcome.present(format, |payload| {
                    println!("{}", crate::payload::serialize(payload, format));
                });
                self.last_result = Some(outcome.payload);
                CommandResult::Continue
            }
            Err(e) => CommandResult::Error(e.to_string()),
        }
    }
    async fn execute_bulk(&mut self, args: &[&str]) -> CommandResult {
        // Handle help flags
        if args.is_empty()
            || args
                .iter()
                .any(|a| *a == "-h" || *a == "--help" || *a == "help")
        {
            self.print_bulk_help();
            return CommandResult::Continue;
        }

        let parsed = match commands::parse_bulk_args(args) {
            Ok(p) => p,
            Err(e) => return CommandResult::Error(e),
        };

        // Expand `~` / `~/...` once at the boundary so both the bulk-input
        // read and the auto-derived output path see a home-resolved path.
        let file_path = crate::utils::expand_tilde(&parsed.file);
        let output_path = parsed
            .output
            .as_deref()
            .map(crate::utils::expand_tilde)
            .unwrap_or_else(|| crate::ops::default_bulk_output_path(&file_path));

        // Read domains from file.
        // `read_bulk_input` rejects FIFOs, sockets, devices, directories, and
        // oversized files via a pre-read metadata check, preventing hangs on
        // `mkfifo`'d paths.
        let content = match crate::utils::read_bulk_input(&file_path) {
            Ok(c) => c,
            Err(e) => return CommandResult::Error(e),
        };

        let domains = match crate::ops::parse_bulk_domains(&content) {
            Ok(d) => d,
            Err(e) => return CommandResult::Error(e),
        };

        // Validate the operation before any progress UI is set up so an
        // unknown op can't leave a stale progress bar registered.
        let operations = match crate::ops::build_bulk_operations(
            &parsed.operation,
            &domains,
            parsed.record_type,
        ) {
            Ok(operations) => operations,
            Err(e) => return CommandResult::Error(e),
        };

        println!(
            "{}",
            crate::ops::bulk_banner(domains.len(), &parsed.operation)
        );

        let bar = crate::ops::bulk_bar(operations.len());
        let executor = seer_core::BulkExecutor::from_config(&self.context.config);
        let callback = crate::ops::bar_progress_callback(&bar);
        let results = executor.execute(operations, Some(callback)).await;
        crate::ops::finish_bulk_bar(&bar);

        if let Err(e) = crate::ops::write_bulk_csv(&results, &parsed.operation, &output_path) {
            return CommandResult::Error(e);
        }

        println!("\n");
        println!("Results written to: {}", output_path.ctp_green());
        println!("{}", crate::ops::bulk_summary(&results));

        if results.iter().any(|r| !r.success) {
            println!("\n{}", "Failures:".bright_red().bold());
            for result in results.iter().filter(|r| !r.success) {
                let domain = result.operation.domain();
                println!(
                    "  {} - {}",
                    domain,
                    result.error.as_deref().unwrap_or("Unknown error")
                );
            }
        }

        CommandResult::Continue
    }

    async fn execute_follow(&self, args: &[&str]) -> CommandResult {
        let commands::FollowArgs {
            domain,
            iterations,
            interval_minutes,
            record_type,
            nameserver,
            changes_only,
        } = match commands::parse_follow_args(args) {
            Ok(p) => p,
            Err(e) => return CommandResult::Error(e),
        };

        // Fall back to the configured nameserver when none is given inline,
        // matching `execute_dig` and the CLI's `seer follow`.
        let nameserver = nameserver.or_else(|| self.context.config.nameserver.clone());

        let config = match seer_core::FollowConfig::new(iterations, interval_minutes) {
            Ok(cfg) => cfg.with_changes_only(changes_only),
            Err(e) => return CommandResult::Error(e.to_string()),
        };

        println!(
            "Following {} {} records ({} iterations, {} interval)",
            domain.ctp_green(),
            record_type.to_string().ctp_yellow(),
            iterations.to_string().ctp_yellow(),
            crate::utils::format_interval(interval_minutes)
        );
        println!(
            "Press {} or {} to stop early\n",
            "Esc".ctp_yellow(),
            "Ctrl+C".ctp_yellow()
        );

        // In raw mode Ctrl+C arrives as a key, so no SIGINT handler here.
        let result = crate::ops::run_live_follow(
            &self.dns_follower,
            &domain,
            record_type,
            nameserver.as_deref(),
            config,
            self.context.output_format,
            false,
        )
        .await;

        match result {
            Ok(result) => {
                let formatter = seer_core::output::get_formatter(self.context.output_format);
                if result.interrupted {
                    println!("\n{}", "Follow interrupted by user".ctp_yellow());
                }
                println!("\n{}", formatter.format_follow(&result));
                CommandResult::Continue
            }
            Err(e) => CommandResult::Error(e.to_string()),
        }
    }

    async fn execute_watch(&mut self, args: &[&str]) -> CommandResult {
        if let Some(action) = args.first() {
            return match crate::ops::watch_edit(action, args.get(1).copied(), "watch").await {
                Ok(message) => {
                    println!("{}", message);
                    CommandResult::Continue
                }
                Err(e) => CommandResult::Error(e),
            };
        }
        let watchlist = match crate::ops::load_watchlist().await {
            Ok(w) => w,
            Err(e) => return CommandResult::Error(e),
        };
        if watchlist.domains.is_empty() {
            println!("{}", crate::ops::watchlist_listing(&watchlist, "watch"));
            return CommandResult::Continue;
        }
        let spinner = Spinner::new(&format!("Checking {} domains", watchlist.domains.len()));
        let report =
            seer_core::check_watchlist_with_config(&watchlist.domains, &self.context.config).await;
        spinner.finish();
        let formatter = seer_core::output::get_formatter(self.context.output_format);
        println!("{}", formatter.format_watch(&report));
        self.last_result = Some(crate::payload::Payload::Watch(Box::new(report)));
        CommandResult::Continue
    }

    async fn execute_history(&self, args: &[&str]) -> CommandResult {
        let result = if args.contains(&"--clear") {
            crate::ops::clear_history()
                .await
                .map(|()| "Lookup history cleared".to_string())
        } else {
            crate::ops::load_history().await.map(|history| {
                crate::ops::history_listing(&history, args.first().copied(), "lookup")
            })
        };
        match result {
            Ok(text) => {
                println!("{}", text);
                CommandResult::Continue
            }
            Err(e) => CommandResult::Error(e),
        }
    }
    /// Pure part of `copy`: pick the format, serialize the last result.
    /// Returns (text to place on the clipboard, confirmation message).
    fn render_copy(&self, args: &[&str]) -> Result<(String, String), String> {
        let arg = args.first().map(|s| s.to_lowercase());
        let format = match arg.as_deref() {
            None => seer_core::output::OutputFormat::Markdown,
            Some("markdown") | Some("md") => seer_core::output::OutputFormat::Markdown,
            Some("json") => seer_core::output::OutputFormat::Json,
            Some("yaml") | Some("yml") => seer_core::output::OutputFormat::Yaml,
            Some(other) => {
                return Err(format!(
                    "Unknown format '{other}'. Usage: copy [markdown|json|yaml]"
                ))
            }
        };
        let Some(payload) = &self.last_result else {
            return Err("Nothing to copy yet — run a lookup first".to_string());
        };
        let text = crate::payload::serialize(payload, format);
        let msg = format!(
            "Copied {} result as {}",
            payload.kind(),
            format!("{format:?}").to_lowercase()
        );
        Ok((text, msg))
    }

    fn execute_copy(&self, args: &[&str]) -> CommandResult {
        match self.render_copy(args) {
            Ok((text, msg)) => {
                if let Err(e) = crate::clipboard::copy(&text) {
                    return CommandResult::Error(format!("Clipboard write failed: {e}"));
                }
                println!("{}", msg.green());
                CommandResult::Continue
            }
            Err(msg) => {
                // "Nothing to copy" is guidance, not an error; usage/format
                // problems go through the error path like other commands.
                if msg.starts_with("Nothing to copy") {
                    println!("{}", msg.yellow());
                    CommandResult::Continue
                } else {
                    CommandResult::Error(msg)
                }
            }
        }
    }

    fn execute_set(&mut self, args: &[&str]) -> CommandResult {
        if args.len() < 2 {
            return CommandResult::Error(catalog::usage("set"));
        }

        match args[0] {
            "output" => match args[1].parse() {
                Ok(format) => {
                    self.context.output_format = format;
                    println!("Output format set to: {}", args[1]);
                    CommandResult::Continue
                }
                Err(_) => CommandResult::Error(
                    "Invalid format. Use: human, json, yaml, markdown".to_string(),
                ),
            },
            _ => CommandResult::Error(format!("Unknown setting: {}", args[0])),
        }
    }
}

#[cfg(test)]
mod copy_tests {
    use super::*;
    use crate::payload::fixtures;
    use seer_core::dns::RecordType;

    fn repl_with_result() -> Repl {
        let mut repl = Repl::new().expect("repl construction is offline");
        let dig = fixtures::dig(RecordType::A, vec![fixtures::a("example.com", "1.2.3.4")]);
        repl.last_result = Some(crate::payload::Payload::Dig(Box::new(dig)));
        repl
    }

    #[test]
    fn copy_with_no_result_is_friendly() {
        let repl = Repl::new().expect("repl construction is offline");
        let err = repl.render_copy(&[]).unwrap_err();
        assert!(err.contains("Nothing to copy"));
    }

    #[test]
    fn copy_defaults_to_markdown() {
        let repl = repl_with_result();
        let (text, msg) = repl.render_copy(&[]).expect("copyable");
        assert!(text.contains("1.2.3.4"));
        assert!(msg.contains("dig") && msg.contains("markdown"));
    }

    #[test]
    fn copy_accepts_explicit_formats() {
        let repl = repl_with_result();
        let (json, _) = repl.render_copy(&["json"]).expect("json");
        assert!(json.trim_start().starts_with('{'));
        let (yaml, _) = repl.render_copy(&["yaml"]).expect("yaml");
        assert!(!yaml.is_empty());
        let (md, _) = repl.render_copy(&["markdown"]).expect("markdown");
        assert!(md.contains("1.2.3.4"));
        let (json_upper, _) = repl.render_copy(&["JSON"]).expect("JSON");
        assert!(json_upper.trim_start().starts_with('{'));
        let (yml, _) = repl.render_copy(&["yml"]).expect("yml");
        assert!(!yml.is_empty());
    }

    #[test]
    fn copy_rejects_unknown_format() {
        let repl = repl_with_result();
        let err = repl.render_copy(&["bogus"]).unwrap_err();
        assert!(err.contains("Usage: copy"));
    }

    // `tld` looks offline (static WHOIS-server/registry-URL tables), but
    // `seer_core::lookup_tld` also calls `RdapClient::get_rdap_base_url_for_tld`,
    // which fetches/refreshes the IANA RDAP bootstrap data over the network
    // when the process-global cache is cold — so this is a live-network test
    // by the project's convention (see e.g. seer-core/src/rdap/client.rs).
    /// The `doctor` command previously rendered its report without touching
    /// `last_result`, so a following `copy` silently copied whatever ran
    /// BEFORE it — wrong output, no error. Seed a DNS result (the stale value
    /// the bug would have surfaced), then confirm a doctor payload wins.
    #[test]
    fn copy_after_doctor_copies_the_doctor_report_not_the_previous_result() {
        use seer_core::doctor::{CheckStatus, DoctorCheck, DoctorReport};

        let mut repl = repl_with_result();
        // Pre-condition: the stale payload the bug would have copied.
        assert_eq!(repl.last_result.as_ref().expect("seeded").kind(), "dig");

        repl.last_result = Some(crate::payload::Payload::Doctor(Box::new(
            DoctorReport::from_checks(vec![DoctorCheck {
                name: "dns".into(),
                status: CheckStatus::Pass,
                detail: "resolved example.com".into(),
                latency_ms: Some(12),
            }]),
        )));

        let (text, msg) = repl.render_copy(&[]).expect("doctor payload is copyable");
        assert!(
            msg.contains("doctor"),
            "confirmation should name doctor: {msg}"
        );
        assert!(
            text.contains("resolved example.com"),
            "copied text should be the doctor report: {text}"
        );
        assert!(
            !text.contains("1.2.3.4"),
            "must not copy the stale DNS result: {text}"
        );
    }

    /// Every copy format must render a doctor payload — `copy` offers
    /// markdown/json/yaml, and doctor is the one payload with no
    /// `OutputFormatter` method behind it.
    #[test]
    fn doctor_payload_serializes_in_every_copy_format() {
        use seer_core::doctor::{CheckStatus, DoctorCheck, DoctorReport};
        use seer_core::output::OutputFormat;

        let payload = crate::payload::Payload::Doctor(Box::new(DoctorReport::from_checks(vec![
            DoctorCheck {
                name: "whois".into(),
                status: CheckStatus::Warn,
                detail: "port 43 slow".into(),
                latency_ms: Some(4200),
            },
        ])));
        for format in [
            OutputFormat::Markdown,
            OutputFormat::Json,
            OutputFormat::Yaml,
        ] {
            let out = crate::payload::serialize(&payload, format);
            assert!(
                out.contains("whois"),
                "{format:?} output missing check name: {out}"
            );
        }
    }

    /// `delegation` previously never stored a payload, so `copy` after it
    /// silently copied whatever ran before.
    #[test]
    fn delegation_payload_is_copyable() {
        let mut repl = repl_with_result();
        repl.last_result = Some(crate::payload::Payload::Delegation(Box::new(
            seer_core::dns::DelegationReport {
                domain: "example.com".into(),
                parent_zone: "com".into(),
                parent_server_queried: vec!["a.gtld-servers.net".into()],
                delegated_ns: vec!["a.iana-servers.net".into()],
                zone_ns: vec!["a.iana-servers.net".into()],
                in_sync: true,
                missing_from_zone: vec![],
                missing_from_parent: vec![],
                lame: vec![],
                warnings: vec![],
            },
        )));
        let (text, msg) = repl.render_copy(&["json"]).expect("copyable");
        assert!(msg.contains("delegation"), "got: {msg}");
        assert!(text.contains("a.iana-servers.net"), "got: {text}");
        assert!(!text.contains("1.2.3.4"), "must not copy the stale result");
    }

    /// `copy` after `dig`: one type copies the result object, several the
    /// array, and a trace its hops — in every copy format.
    #[test]
    fn dig_and_trace_payloads_are_copyable() {
        use crate::payload::Payload;
        let mut repl = repl_with_result();
        let chained = fixtures::dig(
            RecordType::A,
            vec![
                fixtures::cname("www.seer.test", "edge.cdn.test."),
                fixtures::a("edge.cdn.test", "192.0.2.7"),
            ],
        );
        let mx = fixtures::dig(
            RecordType::MX,
            vec![fixtures::mx("www.seer.test", "mail.seer.test.")],
        );

        repl.last_result = Some(Payload::Dig(Box::new(chained.clone())));
        let (json, msg) = repl.render_copy(&["json"]).expect("copyable");
        assert!(msg.contains("dig"), "got: {msg}");
        assert!(json.trim_start().starts_with('{'), "an object: {json}");
        assert!(json.contains("edge.cdn.test") && !json.contains("1.2.3.4"));
        let (md, _) = repl.render_copy(&[]).expect("markdown");
        assert!(md.contains("## DNS A Records: www.seer.test"), "{md}");

        repl.last_result = Some(Payload::DigMany(vec![chained, mx]));
        let (json, _) = repl.render_copy(&["json"]).expect("copyable");
        assert!(json.trim_start().starts_with('['), "an array: {json}");
        let (md, _) = repl.render_copy(&["markdown"]).expect("markdown");
        assert!(md.contains("## DNS MX Records"), "{md}");
        let (yaml, _) = repl.render_copy(&["yaml"]).expect("yaml");
        assert!(yaml.contains("mail.seer.test."), "{yaml}");

        repl.last_result = Some(Payload::Trace(Box::new(fixtures::trace(
            vec![fixtures::a("www.seer.test", "192.0.2.7")],
            None,
        ))));
        let (md, msg) = repl.render_copy(&[]).expect("copyable");
        assert!(msg.contains("trace"), "got: {msg}");
        assert!(md.contains("a.root-servers.net."), "{md}");
    }

    /// A failed command must not leave the previous result for `copy` to
    /// hand out as if it were this command's output. The usage error fires
    /// before any network I/O, so this stays hermetic.
    #[tokio::test]
    async fn failed_command_clears_the_copy_buffer() {
        let mut repl = repl_with_result();
        let result = repl.execute_line("delegation").await;
        assert!(matches!(result, CommandResult::Error(_)), "got {result:?}");
        assert!(repl.last_result.is_none(), "stale payload must be dropped");
        let err = repl.render_copy(&[]).unwrap_err();
        assert!(err.contains("Nothing to copy"), "got: {err}");
    }

    /// `copy`/`set` errors are about the request itself (bad format name),
    /// not a failed lookup, so they keep the buffer.
    #[tokio::test]
    async fn copy_and_set_errors_keep_the_copy_buffer() {
        let mut repl = repl_with_result();
        let result = repl.execute_line("copy bogus").await;
        assert!(matches!(result, CommandResult::Error(_)), "got {result:?}");
        assert!(repl.last_result.is_some());
        let result = repl.execute_line("set output bogus").await;
        assert!(matches!(result, CommandResult::Error(_)), "got {result:?}");
        assert!(repl.last_result.is_some());
    }

    #[tokio::test]
    #[ignore = "live network; run with --ignored or SEER_LIVE_TESTS=1"]
    async fn doctor_command_populates_last_result() {
        let mut repl = Repl::new().expect("repl construction is offline");
        let _ = repl.execute_line("doctor").await;
        assert!(
            matches!(repl.last_result, Some(crate::payload::Payload::Doctor(_))),
            "doctor should store a copyable payload"
        );
    }

    #[tokio::test]
    #[ignore = "live network; run with --ignored or SEER_LIVE_TESTS=1"]
    async fn tld_command_populates_last_result() {
        let mut repl = Repl::new().expect("repl construction is offline");
        let _ = repl.execute_line("tld com").await;
        assert!(
            matches!(repl.last_result, Some(crate::payload::Payload::Tld(_))),
            "tld should store a copyable payload"
        );
    }
}

// Hermetic arg-validation tests for the delegation command: both the usage
// error and the invalid-domain error surface before any network I/O.
#[cfg(test)]
mod delegation_repl_tests {
    use super::*;

    #[tokio::test]
    async fn delegation_requires_a_domain() {
        let mut repl = Repl::new().expect("repl construction is offline");
        let result = repl.execute_line("delegation").await;
        let CommandResult::Error(msg) = result else {
            panic!("expected usage error, got {result:?}");
        };
        assert!(msg.contains("Usage: delegation"), "got: {msg}");
    }

    #[tokio::test]
    async fn delegation_rejects_invalid_domain_before_network() {
        let mut repl = Repl::new().expect("repl construction is offline");
        // Consecutive dots fail normalize_domain inside check() before any
        // network I/O, so this stays hermetic.
        let result = repl.execute_line("delegation bad..domain").await;
        let CommandResult::Error(msg) = result else {
            panic!("expected invalid-domain error, got {result:?}");
        };
        assert!(
            msg.to_lowercase().contains("invalid") && msg.contains("bad..domain"),
            "error should name the invalid input: {msg}"
        );
    }
}

#[cfg(test)]
mod session_tests {
    use super::*;
    use rustyline::history::History;

    /// The loop trimmed the line before `add_history_entry`, so rustyline
    /// never saw the leading space that `history_ignore_space` keys on and
    /// ` whois secret.com` was persisted to ~/.seer_history anyway.
    #[test]
    fn leading_space_line_is_kept_out_of_history() {
        let mut history = DefaultHistory::with_config(&editor_config());
        history
            .add(history_entry(" whois secret.com"))
            .expect("history add");
        assert!(history.is_empty(), "leading-space line must not be saved");
        history
            .add(history_entry("whois public.com  "))
            .expect("history add");
        assert_eq!(history.len(), 1);
    }

    /// `seer --format json` with no subcommand used to start the REPL in the
    /// config default, discarding the flag.
    #[test]
    fn explicit_format_carries_into_the_repl() {
        let mut repl = Repl::new().expect("repl construction is offline");
        repl.set_output_format(seer_core::output::OutputFormat::Json);
        assert_eq!(
            repl.context.output_format,
            seer_core::output::OutputFormat::Json
        );
        assert!(repl.get_prompt().contains("[json]"));
    }

    /// Mistyped flags used to be silently ignored (`drift x --recrod` ran a
    /// non-recording check). They now fail before any network I/O.
    #[tokio::test]
    async fn repl_rejects_unknown_flags_before_network() {
        let mut repl = Repl::new().expect("repl construction is offline");
        for line in [
            "drift example.com --recrod",
            "subdomains example.com --reslove",
            "takeover example.com --hots a.example.com",
            "follow example.com 5 MXX",
        ] {
            let result = repl.execute_line(line).await;
            let CommandResult::Error(msg) = result else {
                panic!("{line:?} should be rejected, got {result:?}");
            };
            assert!(
                msg.contains("--recrod")
                    || msg.contains("--reslove")
                    || msg.contains("--hots")
                    || msg.contains("MXX"),
                "{line:?}: error should name the bad token: {msg}"
            );
        }
    }
}

// A typo'd record type previously fell back to A silently, so `dig example.com
// MXX` returned A answers while the user believed they queried MX. Validation
// now rejects the input before any network I/O, keeping these tests hermetic.
#[cfg(test)]
mod record_type_tests {
    use super::*;

    fn assert_rejects(result: &CommandResult) {
        let CommandResult::Error(msg) = result else {
            panic!("expected error for invalid record type, got {result:?}");
        };
        assert!(msg.contains("BOGUS"), "error should name the input: {msg}");
        assert!(
            msg.contains("MX") && msg.contains("SSHFP"),
            "error should list valid types: {msg}"
        );
    }

    #[tokio::test]
    async fn dig_rejects_invalid_record_type() {
        let mut repl = Repl::new().expect("repl construction is offline");
        let result = repl.execute_line("dig example.com BOGUS").await;
        assert_rejects(&result);
        // In any position: dig-style arguments come in any order.
        let result = repl.execute_line("dig BOGUS @8.8.8.8 example.com").await;
        assert_rejects(&result);
    }

    /// dig's other usage errors surface before any network I/O too.
    #[tokio::test]
    async fn dig_rejects_bad_arguments_before_network() {
        let mut repl = Repl::new().expect("repl construction is offline");
        for (line, problem) in [
            ("dig", "Usage: dig [@server] <name>"),
            ("dns +short", "no name to query"),
            ("dig example.com +bogus", "+bogus"),
            ("dig example.com @8.8.8.8 +trace", "root servers"),
            ("dig -x example.com", "-x needs an IP address"),
        ] {
            let result = repl.execute_line(line).await;
            let CommandResult::Error(msg) = result else {
                panic!("{line:?} should be rejected, got {result:?}");
            };
            assert!(msg.contains(problem), "{line:?}: {msg}");
        }
    }

    #[tokio::test]
    async fn propagation_rejects_invalid_record_type() {
        let mut repl = Repl::new().expect("repl construction is offline");
        let result = repl.execute_line("propagation example.com BOGUS").await;
        assert_rejects(&result);
    }

    #[tokio::test]
    async fn compare_rejects_invalid_record_type() {
        let mut repl = Repl::new().expect("repl construction is offline");
        let result = repl
            .execute_line("compare example.com BOGUS @8.8.8.8 @1.1.1.1")
            .await;
        assert_rejects(&result);
    }
}