wavepeek 2.1.0

Command-line tool for RTL waveform inspection with deterministic machine-friendly output.
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
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
pub mod change;
pub mod docs;
pub mod extract;
pub mod info;
pub mod limits;
pub mod property;
pub mod sampling;
pub mod schema;
pub mod scope;
pub mod signal;
pub mod skill;
pub mod value;

use clap::error::ErrorKind;
use clap::parser::ValueSource;
use clap::{Arg, ArgAction, CommandFactory, FromArgMatches, Parser, Subcommand};

use crate::engine::{self, Command as EngineCommand};
use crate::error::WavepeekError;
use crate::output::{self, JsonlWriter};
use crate::output_mode::OutputMode;

#[derive(Debug, Parser)]
#[command(
    name = "wavepeek",
    disable_version_flag = true,
    about = "wavepeek is a machine-friendly command-line tool for RTL waveform inspection.\nSee more with '--help'",
    long_about = r#"wavepeek is a machine-friendly command-line tool for RTL waveform inspection.
See more with '--help'

General conventions:
- Waveform-inspection commands require `--waves <FILE>`.
- VCD/FST input is available in every build.
- FSDB support is currently Linux x86_64 only and requires a build compiled with Cargo feature `fsdb` and the Synopsys Verdi FSDB Reader SDK.
- Output is bounded by default (e.g. with `--max` or similar) and recursive traversals are depth-bounded.
- Default output is human-readable for waveform commands; `--json` enables machine-readable output and its contract is defined by `wavepeek schema`.
- Time values require explicit units (`zs`, `as`, `fs`, `ps`, `ns`, `us`, `ms`, `s`) and integer magnitudes.
- Parsed times are normalized to dump `time_unit`; time-window flags (`--from`, `--to`) use inclusive boundaries.
- Process-level failures follow `fatal: <category>: <message>`."#,
    after_help = "Next steps:\n  wavepeek --help\n  wavepeek help <command-path...>\n  wavepeek docs\n  wavepeek skill",
    help_template = "{about-with-newline}\nUsage: {usage}\n\nWaveform commands:\n  info      Show waveform metadata\n  scope     Explore hierarchy scopes\n  signal    Explore signals within scope\n  value     Get signal values at explicit time point(s)\n  change    List signal changes over a time range\n  property  Evaluate properties over a time range\n  extract   Extract event rows from waveform signals\n\nHelper commands:\n  schema    Print canonical JSON schema contract\n  docs      Browse embedded documentation\n  skill     Print packaged agent skill Markdown\n  help      Show help for the given subcommand(s)\n\nOptions:\n{options}{after-help}"
)]
pub struct Cli {
    /// Print semver version
    #[arg(short = 'V', action = ArgAction::SetTrue)]
    version_semver: bool,
    /// Print full version
    #[arg(long = "version", action = ArgAction::SetTrue)]
    version_full: bool,
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(Debug, Subcommand)]
enum Command {
    #[command(flatten, next_help_heading = "Waveform commands")]
    Waveform(WaveformCommand),
    #[command(flatten, next_help_heading = "Helper commands")]
    Helper(HelperCommand),
}

#[derive(Debug, Subcommand)]
enum WaveformCommand {
    #[command(
        about = "Reports metadata for the selected waveform dump.",
        long_about = r#"Reports metadata for the selected waveform dump.

Behavior:
- Prints available metadata (e.g. time unit, start/end times, etc.) in free form
- `--json` uses the machine contract defined by `wavepeek schema`."#,
        after_long_help = "See also:\n  wavepeek docs show commands/info"
    )]
    Info(info::InfoArgs),
    #[command(
        about = "Provides deterministic hierarchy traversal over scope paths.",
        long_about = r#"Provides deterministic hierarchy traversal over scope paths.

Behavior:
- Finds all scopes matching `--filter` and displays scope name, depth, and kind.
- Traversal order is stable: pre-order depth-first, with lexicographic child ordering.
- Includes stable scope kind aliases from hierarchy data (not only modules); excluded backend-specific spellings are normalized to the stable contract surface.
- `--tree` switches from flat list to visual hierarchy rendering.
- Truncation and disabled-limit conditions emit coded diagnostics.
- `--json` uses the machine contract defined by `wavepeek schema`.

Use this command to explore hierarchy shape before narrowing to signal-level queries."#,
        after_long_help = "See also:\n  wavepeek docs show commands/scope"
    )]
    Scope(scope::ScopeArgs),
    #[command(
        about = "Provides scope-local signal listings.",
        long_about = r#"Provides scope-local signal listings.

Behavior:
- Finds all signals matching `--filter` within the selected scope and displays name, kind, and available metadata (for example width).
- Default mode lists only direct signals in the selected scope.
- Recursive mode walks child scopes depth-first in stable lexicographic order; `--max-depth` limits recursion when set.
- Includes stable signal kind aliases (not only wires); excluded backend-specific VHDL spellings are normalized to the stable contract surface.
- Truncation and disabled-limit conditions emit coded diagnostics.
- `--json` uses the machine contract defined by `wavepeek schema`.

Use this command after `scope` to inspect available signals in a target scope."#
    )]
    Signal(signal::SignalArgs),
    #[command(
        about = "Provides point sampling for selected signals.",
        long_about = r#"Provides point sampling for selected signals.

Behavior:
- Prints values for the requested signals at each selected time point.
- By default, signal names are top-related canonical paths (e.g. `top.cpu.state`).
- For deep hierarchies, set `--scope` once with a canonical scope path and use shorter scope-relative names in `--signals`.
- Do not mix top-related canonical names and scope-relative names in one request.
- `--at` accepts one explicit time token or a comma-separated list in one argument.
- Output preserves the input order from `--at` and `--signals`, including duplicates.
- Human output emits one `@<time>` row per requested time with `display=value` fields, matching `change`.
- When following up a `change` or `property` JSON row, prefer that row's `sample_time` field for `--at`; in `pre-edge` mode, `time` is the selected trigger timestamp and `sample_time` is where values were sampled.
- Time tokens must include explicit units and align to dump precision.
- Values are emitted as Verilog literals (`<width>'h<digits>` with `x`/`z` support).
- Fails fast if any requested signal cannot be resolved or if any selected time point is more precise than dump resolution.
- `--json` uses the machine contract defined by `wavepeek schema`.

Use this command for deterministic spot checks at specific timestamps."#
    )]
    Value(value::ValueArgs),
    #[command(
        about = "Provides range-based delta snapshots for selected signals.",
        long_about = r#"Provides range-based delta snapshots for selected signals.

Behavior:
- Prints requested signal values for each `--on` trigger firing when at least one value changed since the previous firing.
- Similar to a modified SystemVerilog `$monitor`, but with print trigger control instead of printing at every timestamp.
- Range boundaries are inclusive; baseline state is initialized at range start.
- `--on` is required. Use explicit clock edges such as `--on 'posedge clk'` for RTL-style sampling.
- Value sampling defaults to pre-edge sampling: displayed values are sampled just before edge-only triggers while row timestamps stay at the trigger edge.
- Use `--sample-mode native` for raw wildcard or plain-signal triggers such as `--on '*'`.
- JSON and JSONL rows include both `time` (selected event timestamp) and `sample_time` (where values were sampled); text output shows `sample@<time>` only when it differs from `time`.
- Rows are emitted only when sampled signal values changed from prior sampled state.
- Empty-result, truncation, and explicitly disabled-limit conditions emit coded diagnostics.
- `--json` uses the machine contract defined by `wavepeek schema`.

Use this command to inspect value transitions over bounded time windows."#
    )]
    Change(change::ChangeArgs),
    #[command(
        about = "Provides timestamps where the specified property holds over event triggers.",
        long_about = r#"Provides timestamps where the specified property holds over event triggers.

Behavior:
- Evaluates `--eval` at timestamps selected by `--on` and prints time plus metadata when the property holds.
- Level capture (`--capture match`) reports a match at every selected timestamp where the property holds.
- Edge capture (`--capture switch`, `assert`, or `deassert`) reports transitions: no match to match, or match to no match.
- `--on` is required. Use explicit clock edges such as `--on 'posedge clk'` for RTL-style sampling.
- Value sampling defaults to pre-edge sampling: `--eval` reads values just before edge-only triggers while row timestamps stay at the trigger edge.
- Use `--sample-mode native` for raw wildcard or plain-signal triggers such as `--on '*'`.
- JSON and JSONL rows include both `time` (selected event timestamp) and `sample_time` (where `--eval` was sampled); text output shows `sample@<time>` only when it differs from `time`.
- Empty-result, truncation, and explicitly disabled-limit conditions emit coded diagnostics.
- Remotely similar to a SystemVerilog assert, but without temporal expressions.
- `--json` uses the machine contract defined by `wavepeek schema`.

Use this command to check event-driven property matches and transitions over bounded time windows."#
    )]
    Property(property::PropertyArgs),
    #[command(
        subcommand,
        about = "Extract row-oriented waveform data.",
        long_about = r#"Extract row-oriented waveform data.

Use nested extractors for protocol-neutral or protocol-specific event rows. The generic extractor selects edge events, evaluates a predicate at the pre-edge sample point, and emits ordered payload values."#
    )]
    Extract(extract::ExtractCommand),
}

#[derive(Debug, Subcommand)]
enum HelperCommand {
    #[command(
        about = "Print canonical JSON schema contract.",
        long_about = r#"Print canonical JSON schema contract.

Behavior:
- Prints exactly one deterministic schema document to stdout.
- Default output is the JSON envelope schema for `--json` command outputs.
- `--stream` prints the JSONL record schema for `--jsonl` output.
- `--input` prints the JSON input document schema for commands that accept structured input.

Use this command to fetch machine-readable contracts consumed by JSON-mode clients."#
    )]
    Schema(schema::SchemaArgs),
    Docs(docs::DocsArgs),
    #[command(
        about = "Print the packaged agent skill Markdown for wavepeek.",
        long_about = "Print the packaged agent skill Markdown for wavepeek."
    )]
    Skill(skill::SkillArgs),
}

struct OptionalFeatureHelp {
    name: &'static str,
    enabled: bool,
    disabled_hint: &'static str,
}

const OPTIONAL_FEATURES: &[OptionalFeatureHelp] = &[OptionalFeatureHelp {
    name: "FSDB",
    enabled: cfg!(feature = "fsdb"),
    disabled_hint: "FSDB support is currently Linux x86_64 only; reinstall with Cargo flag `--features fsdb` and provide the Synopsys Verdi FSDB Reader SDK",
}];

const ROOT_NEXT_STEPS: &str = "Next steps:\n  wavepeek --help\n  wavepeek help <command-path...>\n  wavepeek docs\n  wavepeek skill";

fn root_after_long_help() -> String {
    let mut help = String::from("Optional features:\n");
    for feature in OPTIONAL_FEATURES {
        if feature.enabled {
            help.push_str("- ");
            help.push_str(feature.name);
            help.push_str(" - enabled\n");
        } else {
            help.push_str("- ");
            help.push_str(feature.name);
            help.push_str(" - disabled (");
            help.push_str(feature.disabled_hint);
            help.push_str(")\n");
        }
    }
    help.push('\n');
    help.push_str(ROOT_NEXT_STEPS);
    help
}

pub fn run() -> Result<(), WavepeekError> {
    let argv: Vec<_> = std::env::args_os().collect();
    let parse_argv = if argv.len() == 1 {
        vec![argv[0].clone(), "-h".into()]
    } else if argv.len() == 2 && matches!(argv[1].to_str(), Some("docs" | "extract")) {
        vec![argv[0].clone(), argv[1].clone(), "-h".into()]
    } else {
        argv
    };

    let matches = match build_cli_command().try_get_matches_from(parse_argv) {
        Ok(matches) => matches,
        Err(error) => return handle_parse_error(error),
    };

    if change_tune_overrides_requested(&matches) && !is_debug_mode_enabled() {
        return Err(WavepeekError::Args(
            "internal tuning overrides (--tune-*) require DEBUG=1. Set DEBUG=1 only for local diagnostics or CI debugging."
                .to_string(),
        ));
    }

    let cli = match Cli::from_arg_matches(&matches) {
        Ok(cli) => cli,
        Err(error) => return handle_parse_error(error),
    };

    if cli.version_semver {
        println!(env!("CARGO_PKG_VERSION"));
        return Ok(());
    }

    if cli.version_full {
        println!("wavepeek v{}", env!("CARGO_PKG_VERSION"));
        return Ok(());
    }

    let Some(command) = cli.command else {
        return Ok(());
    };

    dispatch(command)
}

fn is_debug_mode_enabled() -> bool {
    std::env::var("DEBUG")
        .map(|value| value == "1")
        .unwrap_or(false)
}

fn change_tune_overrides_requested(matches: &clap::ArgMatches) -> bool {
    let Some(("change", change_matches)) = matches.subcommand() else {
        return false;
    };

    is_command_line_override(change_matches, "tune_engine")
        || is_command_line_override(change_matches, "tune_candidates")
        || is_command_line_override(change_matches, "tune_edge_fast_force")
}

fn is_command_line_override(matches: &clap::ArgMatches, arg: &str) -> bool {
    matches!(matches.value_source(arg), Some(ValueSource::CommandLine))
}

fn build_cli_command() -> clap::Command {
    let mut command = Cli::command().after_long_help(root_after_long_help());
    if let Some(help) = command.find_subcommand_mut("help") {
        *help = help.clone().about("Show help for the given subcommand(s)");
    }
    for command_name in ["info", "scope", "signal", "value", "change", "property"] {
        if let Some(subcommand) = command.find_subcommand_mut(command_name) {
            *subcommand = with_other_help_options(subcommand.clone());
        }
    }
    if let Some(extract) = command.find_subcommand_mut("extract")
        && let Some(generic) = extract.find_subcommand_mut("generic")
    {
        *generic = with_other_help_options(generic.clone());
    }
    command
}

fn with_other_help_options(command: clap::Command) -> clap::Command {
    command
        .disable_help_flag(true)
        .arg(
            Arg::new("help_short")
                .short('h')
                .action(ArgAction::HelpShort)
                .help("Print help (see more with '--help')")
                .help_heading("Other options"),
        )
        .arg(
            Arg::new("help_long")
                .long("help")
                .action(ArgAction::HelpLong)
                .help("Print help (see a summary with '-h')")
                .help_heading("Other options"),
        )
}

fn handle_parse_error(error: clap::Error) -> Result<(), WavepeekError> {
    match error.kind() {
        ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => error.print().map_err(|io_error| {
            WavepeekError::Internal(format!("failed to print help: {io_error}"))
        }),
        _ => Err(WavepeekError::Args(normalize_clap_error(&error))),
    }
}

fn normalize_clap_error(error: &clap::Error) -> String {
    let rendered = error.render().to_string();
    let detail = clap_error_detail(rendered.as_str());
    let hint = help_hint_for_rendered_clap_error(rendered.as_str());

    format!("{detail} {hint}")
}

fn clap_error_detail(rendered: &str) -> String {
    let lines: Vec<&str> = rendered.lines().collect();
    if let Some(start_index) = lines
        .iter()
        .position(|line| line.trim_start().starts_with("error:"))
    {
        let mut chunks = Vec::new();

        for (index, line) in lines.iter().enumerate().skip(start_index) {
            let trimmed = line.trim();
            if index > start_index
                && (trimmed.starts_with("Usage:") || trimmed.starts_with("For more information"))
            {
                break;
            }

            if index == start_index {
                if let Some(rest) = trimmed.strip_prefix("error:") {
                    let rest = rest.trim();
                    if !rest.is_empty() {
                        chunks.push(rest.to_string());
                    }
                }
                continue;
            }

            if !trimmed.is_empty() {
                chunks.push(trimmed.to_string());
            }
        }

        if !chunks.is_empty() {
            return chunks.join(" ");
        }
    }

    for line in lines {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("error:") {
            return rest.trim().to_string();
        }
    }

    rendered
        .lines()
        .find_map(|line| {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        })
        .unwrap_or_else(|| "invalid arguments".to_string())
}

fn help_hint_for_rendered_clap_error(rendered: &str) -> String {
    let usage_line = rendered
        .lines()
        .map(str::trim)
        .find(|line| line.starts_with("Usage:"));

    let Some(usage_line) = usage_line else {
        return "See 'wavepeek --help'.".to_string();
    };

    let usage = usage_line.trim_start_matches("Usage:").trim();
    let mut parts = usage.split_whitespace();
    let Some(command_name) = parts.next() else {
        return "See 'wavepeek --help'.".to_string();
    };
    if command_name != "wavepeek" {
        return "See 'wavepeek --help'.".to_string();
    }

    let mut path_tokens = Vec::new();
    for token in parts {
        if token.starts_with('[') || token.starts_with('<') || token.starts_with('-') {
            break;
        }
        path_tokens.push(token);
    }

    if path_tokens.is_empty() {
        return "See 'wavepeek --help'.".to_string();
    }

    format!("See 'wavepeek {} --help'.", path_tokens.join(" "))
}

fn dispatch(command: Command) -> Result<(), WavepeekError> {
    let engine_command = into_engine_command(command);
    if engine_command.output_mode() == OutputMode::Jsonl {
        let stdout = std::io::stdout();
        let mut writer = JsonlWriter::new(stdout.lock(), engine_command.name());
        return engine::run_jsonl(engine_command, &mut writer);
    }

    let result = engine::run(engine_command)?;
    output::write(result)
}

fn into_engine_command(command: Command) -> EngineCommand {
    match command {
        Command::Waveform(command) => match command {
            WaveformCommand::Info(args) => EngineCommand::Info(args),
            WaveformCommand::Scope(args) => EngineCommand::Scope(args),
            WaveformCommand::Signal(args) => EngineCommand::Signal(args),
            WaveformCommand::Value(args) => EngineCommand::Value(args),
            WaveformCommand::Change(args) => EngineCommand::Change(args),
            WaveformCommand::Property(args) => EngineCommand::Property(args),
            WaveformCommand::Extract(command) => match command {
                extract::ExtractCommand::Generic(args) => EngineCommand::ExtractGeneric(args),
            },
        },
        Command::Helper(command) => match command {
            HelperCommand::Schema(args) => EngineCommand::Schema(args),
            HelperCommand::Docs(args) => EngineCommand::Docs(args),
            HelperCommand::Skill(args) => EngineCommand::Skill(args),
        },
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use clap::{CommandFactory, Parser};

    use crate::cli::limits::LimitArg;

    use super::{
        Cli, EngineCommand, build_cli_command, change_tune_overrides_requested, clap_error_detail,
        handle_parse_error, help_hint_for_rendered_clap_error, into_engine_command,
        normalize_clap_error,
    };

    #[test]
    fn info_dispatch_keeps_json_and_waves_args() {
        let cli = Cli::parse_from([
            "wavepeek",
            "info",
            "--waves",
            "fixtures/sample.vcd",
            "--json",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::Info(args) => {
                assert_eq!(args.waves, PathBuf::from("fixtures/sample.vcd"));
                assert!(args.json);
            }
            other => panic!("expected info command, got {other:?}"),
        }
    }

    #[test]
    fn scope_dispatch_keeps_bounded_query_args() {
        let cli = Cli::parse_from([
            "wavepeek",
            "scope",
            "--waves",
            "fixtures/sample.vcd",
            "--max",
            "12",
            "--max-depth",
            "3",
            "--filter",
            "^top\\..*",
            "--tree",
            "--json",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::Scope(args) => {
                assert_eq!(args.waves, PathBuf::from("fixtures/sample.vcd"));
                assert_eq!(args.max, LimitArg::Numeric(12));
                assert_eq!(args.max_depth, LimitArg::Numeric(3));
                assert_eq!(args.filter, "^top\\..*");
                assert!(args.tree);
                assert!(args.json);
            }
            other => panic!("expected scope command, got {other:?}"),
        }
    }

    #[test]
    fn scope_dispatch_accepts_unlimited_limit_literals() {
        let cli = Cli::parse_from([
            "wavepeek",
            "scope",
            "--waves",
            "fixtures/sample.vcd",
            "--max",
            "unlimited",
            "--max-depth",
            "unlimited",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::Scope(args) => {
                assert_eq!(args.waves, PathBuf::from("fixtures/sample.vcd"));
                assert_eq!(args.max, LimitArg::Unlimited);
                assert_eq!(args.max_depth, LimitArg::Unlimited);
            }
            other => panic!("expected scope command, got {other:?}"),
        }
    }

    #[test]
    fn signal_dispatch_keeps_recursive_and_max_depth_args() {
        let cli = Cli::parse_from([
            "wavepeek",
            "signal",
            "--waves",
            "fixtures/sample.vcd",
            "--scope",
            "top.cpu",
            "--recursive",
            "--max-depth",
            "3",
            "--max",
            "7",
            "--filter",
            ".*clk.*",
            "--abs",
            "--json",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::Signal(args) => {
                assert_eq!(args.waves, PathBuf::from("fixtures/sample.vcd"));
                assert_eq!(args.scope, "top.cpu");
                assert!(args.recursive);
                assert_eq!(args.max_depth, LimitArg::Numeric(3));
                assert_eq!(args.max, LimitArg::Numeric(7));
                assert_eq!(args.filter, ".*clk.*");
                assert!(args.abs);
                assert!(args.json);
            }
            other => panic!("expected signal command, got {other:?}"),
        }
    }

    #[test]
    fn value_dispatch_keeps_scope_signals_abs_and_json_args() {
        let cli = Cli::parse_from([
            "wavepeek",
            "value",
            "--waves",
            "fixtures/sample.vcd",
            "--at",
            "10ns",
            "--scope",
            "top",
            "--signals",
            "clk,data",
            "--abs",
            "--json",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::Value(args) => {
                assert_eq!(args.waves, PathBuf::from("fixtures/sample.vcd"));
                assert_eq!(args.at, "10ns");
                assert_eq!(args.scope.as_deref(), Some("top"));
                assert_eq!(args.signals, vec!["clk", "data"]);
                assert!(args.abs);
                assert!(args.json);
            }
            other => panic!("expected value command, got {other:?}"),
        }
    }

    #[test]
    fn change_dispatch_keeps_on_abs_and_limits() {
        let cli = Cli::parse_from([
            "wavepeek",
            "change",
            "--waves",
            "fixtures/sample.vcd",
            "--from",
            "1ns",
            "--to",
            "10ns",
            "--scope",
            "top",
            "--signals",
            "clk,data",
            "--on",
            "posedge clk",
            "--max",
            "12",
            "--abs",
            "--json",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::Change(args) => {
                assert_eq!(args.waves, PathBuf::from("fixtures/sample.vcd"));
                assert_eq!(args.from.as_deref(), Some("1ns"));
                assert_eq!(args.to.as_deref(), Some("10ns"));
                assert_eq!(args.scope.as_deref(), Some("top"));
                assert_eq!(args.signals, vec!["clk", "data"]);
                assert_eq!(args.on, "posedge clk");
                assert_eq!(args.sample_mode, crate::cli::sampling::SampleMode::PreEdge);
                assert_eq!(args.max, LimitArg::Numeric(12));
                assert!(args.abs);
                assert!(args.json);
            }
            other => panic!("expected change command, got {other:?}"),
        }
    }

    #[test]
    fn property_dispatch_parses_capture_default() {
        let cli = Cli::parse_from([
            "wavepeek",
            "property",
            "--waves",
            "fixtures/sample.vcd",
            "--on",
            "posedge top.clk",
            "--eval",
            "1",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::Property(args) => {
                assert_eq!(args.on, "posedge top.clk");
                assert_eq!(args.sample_mode, crate::cli::sampling::SampleMode::PreEdge);
                assert_eq!(args.eval, "1");
                assert_eq!(args.capture, crate::cli::property::CaptureMode::Switch);
                assert_eq!(args.max, LimitArg::Numeric(50));
            }
            other => panic!("expected property command, got {other:?}"),
        }
    }

    #[test]
    fn property_dispatch_accepts_unlimited_max() {
        let cli = Cli::parse_from([
            "wavepeek",
            "property",
            "--waves",
            "fixtures/sample.vcd",
            "--on",
            "posedge top.clk",
            "--eval",
            "1",
            "--max",
            "unlimited",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::Property(args) => {
                assert_eq!(args.max, LimitArg::Unlimited);
            }
            other => panic!("expected property command, got {other:?}"),
        }
    }

    #[test]
    fn extract_generic_dispatch_keeps_single_source_args() {
        let cli = Cli::parse_from([
            "wavepeek",
            "extract",
            "generic",
            "--waves",
            "fixtures/sample.vcd",
            "--scope",
            "top",
            "--name",
            "rx.beat",
            "--on",
            "posedge clk",
            "--when",
            "valid && ready",
            "--payload",
            "data,last",
            "--max",
            "unlimited",
            "--abs",
            "--jsonl",
        ]);

        let command = into_engine_command(cli.command.expect("parsed command"));
        match command {
            EngineCommand::ExtractGeneric(args) => {
                assert_eq!(args.waves, PathBuf::from("fixtures/sample.vcd"));
                assert_eq!(args.scope.as_deref(), Some("top"));
                assert_eq!(args.name.as_deref(), Some("rx.beat"));
                assert_eq!(args.on.as_deref(), Some("posedge clk"));
                assert_eq!(args.when.as_deref(), Some("valid && ready"));
                assert_eq!(
                    args.payload,
                    Some(vec!["data".to_string(), "last".to_string()])
                );
                assert_eq!(args.max, LimitArg::Unlimited);
                assert!(args.abs);
                assert!(args.jsonl);
            }
            other => panic!("expected extract generic command, got {other:?}"),
        }
    }

    #[test]
    fn clap_errors_are_normalized_to_single_line_message() {
        let error = Cli::try_parse_from(["wavepeek", "schema", "--waves", "dump.vcd"])
            .expect_err("schema --waves should fail");

        let normalized = normalize_clap_error(&error);
        assert!(normalized.contains("unexpected argument '--waves'"));
        assert!(normalized.contains("See 'wavepeek schema --help'."));
        assert!(!normalized.contains("Usage:"));
    }

    #[test]
    fn clap_error_detail_preserves_missing_argument_names() {
        let rendered = "error: the following required arguments were not provided:\n  --waves <FILE>\n\nUsage: wavepeek info --waves <FILE>\n\nFor more information, try '--help'.\n";

        let normalized = clap_error_detail(rendered);
        assert!(normalized.contains("the following required arguments were not provided"));
        assert!(normalized.contains("--waves <FILE>"));
        assert!(!normalized.contains("Usage:"));
    }

    #[test]
    fn help_hint_uses_global_help_for_top_level_parse_failures() {
        let rendered = "error: unexpected argument '--wat' found\n\nUsage: wavepeek [OPTIONS] <COMMAND>\n\nFor more information, try '--help'.\n";
        let hint = help_hint_for_rendered_clap_error(rendered);
        assert_eq!(hint, "See 'wavepeek --help'.");
    }

    #[test]
    fn help_hint_uses_subcommand_help_for_subcommand_parse_failures() {
        let rendered = "error: unexpected argument '--wat' found\n\nUsage: wavepeek info --waves <FILE>\n\nFor more information, try '--help'.\n";
        let hint = help_hint_for_rendered_clap_error(rendered);
        assert_eq!(hint, "See 'wavepeek info --help'.");
    }

    #[test]
    fn cli_helper_functions_exercise_override_detection_and_fallback_paths() {
        let command = build_cli_command();
        let info = command
            .find_subcommand("info")
            .expect("info subcommand should exist")
            .clone();
        assert!(info.get_arguments().any(|arg| arg.get_id() == "help_short"));
        assert!(info.get_arguments().any(|arg| arg.get_id() == "help_long"));

        let matches = Cli::command()
            .try_get_matches_from([
                "wavepeek",
                "change",
                "--waves",
                "fixtures/sample.vcd",
                "--signals",
                "clk",
                "--on",
                "*",
                "--sample-mode",
                "native",
                "--tune-engine",
                "fused",
            ])
            .expect("change command should parse");
        assert!(change_tune_overrides_requested(&matches));

        let matches = Cli::command()
            .try_get_matches_from([
                "wavepeek",
                "change",
                "--waves",
                "fixtures/sample.vcd",
                "--signals",
                "clk",
                "--on",
                "*",
                "--sample-mode",
                "native",
            ])
            .expect("change command should parse");
        assert!(!change_tune_overrides_requested(&matches));

        let help_error = Cli::command()
            .try_get_matches_from(["wavepeek", "info", "--help"])
            .expect_err("--help should short-circuit through clap");
        handle_parse_error(help_error).expect("display-help errors should print cleanly");

        assert_eq!(
            clap_error_detail("plain fallback detail"),
            "plain fallback detail"
        );
        assert_eq!(clap_error_detail("\n\n   \n"), "invalid arguments");
        assert_eq!(
            help_hint_for_rendered_clap_error("Usage: nope info --waves <FILE>\n"),
            "See 'wavepeek --help'."
        );
    }
}