watoots-cli 0.7.1

Command-line interface for watoots: inspect, run, record, and replay WebAssembly component plugins.
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
//! The `watoots` command line, driven as a user would.

use std::path::PathBuf;
use std::process::{Command, Output};
use std::sync::OnceLock;

fn repo_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")
}

fn sample_plugin() -> &'static PathBuf {
    static ARTIFACT: OnceLock<PathBuf> = OnceLock::new();
    ARTIFACT.get_or_init(|| {
        let root = repo_root();
        let status = Command::new(env!("CARGO"))
            .args(["build", "--manifest-path"])
            .arg(root.join("examples/plugins/rust-lint/Cargo.toml"))
            .args(["--target", "wasm32-wasip2", "--release"])
            .status()
            .expect("running cargo to build the sample plugin");
        assert!(status.success(), "failed to build the sample plugin");
        root.join("examples/plugins/rust-lint/target/wasm32-wasip2/release/rust_lint.wasm")
    })
}

fn watoots(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_watoots"))
        .args(args)
        .current_dir(repo_root())
        .output()
        .expect("running watoots")
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn policy() -> String {
    repo_root()
        .join("examples/policies/rust-lint.toml")
        .display()
        .to_string()
}

#[test]
fn inspect_without_a_manifest_shows_the_whole_bill() {
    let plugin = sample_plugin().display().to_string();
    let output = watoots(&["inspect", &plugin]);

    // The default view answers "what can it do", not "what does it import":
    // a capability row rather than an interface name.
    let text = stdout(&output);
    assert!(text.contains("capabilities"), "{text}");
    assert!(text.contains("clock"), "{text}");
    assert!(text.contains("DENY"), "{text}");
    // An interface the application is expected to serve is not a denial, and
    // must not be filed as one.
    assert!(text.contains("your application must serve"), "{text}");
    // Denials mean a non-zero exit, so `watoots inspect` works in a gate.
    assert!(!output.status.success());
}

#[test]
fn inspect_imports_lists_the_interfaces_individually() {
    let plugin = sample_plugin().display().to_string();
    let output = watoots(&["inspect", &plugin, "--imports"]);

    let text = stdout(&output);
    assert!(text.contains("wasi:clocks/monotonic-clock"), "{text}");
    assert!(text.contains("DENY"), "{text}");
    assert!(!output.status.success());
}

#[test]
fn inspect_with_a_policy_and_the_served_interface_is_clean() {
    let plugin = sample_plugin().display().to_string();
    let output = watoots(&[
        "inspect",
        &plugin,
        "-m",
        &policy(),
        "--provide",
        "watoots:example/log",
    ]);

    let text = stdout(&output);
    assert!(text.contains("every import is granted"), "{text}");
    assert!(output.status.success());
}

#[test]
fn record_then_replay_round_trips() {
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("lint.wave");
    let plugin = sample_plugin().display().to_string();

    let recorded = watoots(&[
        "record",
        &plugin,
        "-m",
        &policy(),
        "--answer",
        "watoots:example/log@0.1.0#emit=",
        "-c",
        "lint",
        "-o",
        &trace.display().to_string(),
        "--",
        r#""notes.md""#,
        r#""TODO: fix\n""#,
    ]);
    assert!(recorded.status.success(), "{:?}", recorded);

    // The trace is text, and readable. That is the whole differentiator.
    let text = std::fs::read_to_string(&trace).unwrap();
    assert!(text.starts_with("watoots-trace 1\n"), "{text}");
    assert!(text.contains("export-call lint"), "{text}");
    assert!(text.contains("unresolved TODO"), "{text}");

    let replayed = watoots(&[
        "replay",
        &trace.display().to_string(),
        "-c",
        &plugin,
        "--assert",
    ]);
    assert!(replayed.status.success(), "{}", stdout(&replayed));
    assert!(stdout(&replayed).contains("matched the trace"));
}

#[test]
fn an_edited_trace_fails_the_assert() {
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("lint.wave");
    let plugin = sample_plugin().display().to_string();

    watoots(&[
        "record",
        &plugin,
        "-m",
        &policy(),
        "--answer",
        "watoots:example/log@0.1.0#emit=",
        "-c",
        "lint",
        "-o",
        &trace.display().to_string(),
        "--",
        r#""notes.md""#,
        r#""TODO\n""#,
    ]);

    // Hand-edit the recording, which is a thing you can do precisely because
    // it is text.
    let text = std::fs::read_to_string(&trace).unwrap();
    std::fs::write(&trace, text.replace("1 diagnostic(s)", "7 diagnostic(s)")).unwrap();

    let replayed = watoots(&[
        "replay",
        &trace.display().to_string(),
        "-c",
        &plugin,
        "--assert",
    ]);
    assert!(!replayed.status.success(), "the edit should have failed CI");

    let report = stdout(&replayed);
    assert!(report.contains("diverged"), "{report}");
    assert!(report.contains("7 diagnostic(s)"), "{report}");
    assert!(report.contains("1 diagnostic(s)"), "{report}");
}

#[test]
fn trace_fmt_converts_between_encodings() {
    let dir = tempfile::tempdir().unwrap();
    let text_trace = dir.path().join("lint.wave");
    let binary_trace = dir.path().join("lint.wtr");
    let plugin = sample_plugin().display().to_string();

    watoots(&[
        "record",
        &plugin,
        "-m",
        &policy(),
        "--answer",
        "watoots:example/log@0.1.0#emit=",
        "-c",
        "name",
        "-o",
        &text_trace.display().to_string(),
    ]);

    let converted = watoots(&[
        "trace",
        "fmt",
        &text_trace.display().to_string(),
        "--binary",
        "-o",
        &binary_trace.display().to_string(),
    ]);
    assert!(converted.status.success());
    assert!(std::fs::read(&binary_trace).unwrap().starts_with(b"WTTR"));

    // And back again, unchanged.
    let back = watoots(&["trace", "fmt", &binary_trace.display().to_string()]);
    assert_eq!(stdout(&back), std::fs::read_to_string(&text_trace).unwrap());
}

#[test]
fn replaying_against_the_wrong_component_is_refused() {
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("lint.wave");
    let plugin = sample_plugin().display().to_string();
    let other = dir.path().join("other.wasm");
    std::fs::write(&other, b"(component)").unwrap();

    watoots(&[
        "record",
        &plugin,
        "-m",
        &policy(),
        "--answer",
        "watoots:example/log@0.1.0#emit=",
        "-c",
        "name",
        "-o",
        &trace.display().to_string(),
    ]);

    let output = watoots(&[
        "replay",
        &trace.display().to_string(),
        "-c",
        &other.display().to_string(),
    ]);
    assert!(!output.status.success());
    assert!(
        String::from_utf8_lossy(&output.stderr).contains("different component"),
        "{:?}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn emit_test_writes_a_runnable_fixture() {
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("lint.wave");
    let fixture = dir.path().join("replay_test.rs");
    let plugin = sample_plugin().display().to_string();

    watoots(&[
        "record",
        &plugin,
        "-m",
        &policy(),
        "--answer",
        "watoots:example/log@0.1.0#emit=",
        "-c",
        "name",
        "-o",
        &trace.display().to_string(),
    ]);
    watoots(&[
        "replay",
        &trace.display().to_string(),
        "-c",
        &plugin,
        "--emit-test",
        &fixture.display().to_string(),
    ]);

    let source = std::fs::read_to_string(&fixture).unwrap();
    assert!(source.contains("#[test]"), "{source}");
    assert!(source.contains("watoots_trace::replay"), "{source}");
    assert!(source.contains("is_faithful"), "{source}");
}

#[test]
fn inspect_targets_reports_a_world_the_component_does_not_implement() {
    let plugin = sample_plugin().display().to_string();
    let wit = tempfile::Builder::new()
        .suffix(".wit")
        .tempfile()
        .expect("creating a WIT file");
    std::fs::write(
        wit.path(),
        "package test:other@0.1.0;\nworld formatter {\n  export format: func() -> string;\n}\n",
    )
    .expect("writing WIT");

    let output = watoots(&[
        "inspect",
        &plugin,
        "--targets",
        &wit.path().display().to_string(),
    ]);
    let text = stdout(&output);
    assert!(text.contains("does not implement world"), "{text}");
    assert!(!output.status.success());
}

#[test]
fn wit_semver_check_accepts_a_world_that_demands_less() {
    let dir = tempfile::tempdir().expect("temp dir");
    let previous = dir.path().join("previous.wit");
    let current = dir.path().join("current.wit");
    // The compatible direction: the new world asks plugins for fewer exports,
    // so everything built against the old one still satisfies it.
    std::fs::write(
        &previous,
        "package test:api@0.1.0;\nworld api {\n  export greet: func() -> string;\n  \
         export farewell: func() -> string;\n}\n",
    )
    .unwrap();
    std::fs::write(
        &current,
        "package test:api@0.2.0;\nworld api {\n  export greet: func() -> string;\n}\n",
    )
    .unwrap();

    let output = watoots(&[
        "wit",
        "semver-check",
        "--previous",
        &previous.display().to_string(),
        "--current",
        &current.display().to_string(),
    ]);
    assert!(output.status.success(), "{}", stdout(&output));
}

#[test]
fn wit_semver_check_rejects_a_changed_signature() {
    let dir = tempfile::tempdir().expect("temp dir");
    let previous = dir.path().join("previous.wit");
    let current = dir.path().join("current.wit");
    std::fs::write(
        &previous,
        "package test:api@0.1.0;\nworld api {\n  export greet: func() -> string;\n}\n",
    )
    .unwrap();
    std::fs::write(
        &current,
        "package test:api@0.2.0;\nworld api {\n  export greet: func(formal: bool) -> string;\n}\n",
    )
    .unwrap();

    let output = watoots(&[
        "wit",
        "semver-check",
        "--previous",
        &previous.display().to_string(),
        "--current",
        &current.display().to_string(),
    ]);
    assert!(!output.status.success(), "{}", stdout(&output));
    assert!(
        stdout(&output).contains("incompatible"),
        "{}",
        stdout(&output)
    );
}

// ---------------------------------------------------------------------------
// `watoots fuzz` — ADR-0008
// ---------------------------------------------------------------------------

/// Rolls a random number. The argument is ignored: it is there so the generator
/// has something to generate, and so the trace has an argument to encode.
///
/// WAT rather than a compiled guest, so this stays hermetic — `Component::new`
/// assembles the text itself, which is the same trick the host's own tests use.
/// `wasi:random` is the point: under the manifest's default determinism it is a
/// seeded generator and a session reproduces, and with determinism switched off
/// it is the real thing and a session does not. That makes it the smallest
/// honest demonstration of what the fuzzer is looking for.
const ROLLS: &str = r#"
(component
  (type (;0;)
    (instance
      (type (;0;) (func (result u64)))
      (export (;0;) "get-random-u64" (func (type 0)))
    )
  )
  (import "wasi:random/random@0.2.9" (instance $r (type 0)))
  (alias export $r "get-random-u64" (func $rand_fn))
  (core func $rand_lowered (canon lower (func $rand_fn)))
  (core module $m
    (import "r" "get-random-u64" (func $rand (result i64)))
    (func (export "roll") (param $n i32) (result i64) (call $rand))
  )
  (core instance $r_i (export "get-random-u64" (func $rand_lowered)))
  (core instance $i (instantiate $m (with "r" (instance $r_i))))
  (func $roll (param "n" u32) (result u64) (canon lift (core func $i "roll")))
  (export "roll" (func $roll))
)
"#;

/// Writes the component and a manifest into a temp dir, and returns both paths
/// plus somewhere to put crash files.
fn rolling_plugin(determinism: bool) -> (tempfile::TempDir, String, String, String) {
    let dir = tempfile::tempdir().expect("temp dir");
    let component = dir.path().join("rolls.wasm");
    let manifest = dir.path().join("policy.toml");
    let out = dir.path().join("findings");
    std::fs::write(&component, ROLLS).unwrap();
    std::fs::write(
        &manifest,
        // A policy *file* has to state a signature posture, which is the point
        // of the rule: this one is a fixture, not a deployment, and says so.
        if determinism {
            "[permissions]\nrandom = true\n\n[signature]\nrequired = false\n"
        } else {
            "[permissions]\nrandom = true\n\n[determinism]\nenabled = false\n\n\
             [signature]\nrequired = false\n"
        },
    )
    .unwrap();
    (
        dir,
        component.display().to_string(),
        manifest.display().to_string(),
        out.display().to_string(),
    )
}

#[test]
fn fuzz_reports_nothing_when_a_session_reproduces() {
    let (_dir, component, manifest, out) = rolling_plugin(true);
    let output = watoots(&[
        "fuzz", &component, "-m", &manifest, "--cases", "8", "--out", &out,
    ]);
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
    assert!(output.status.success(), "{stderr}{}", stdout(&output));
    assert!(stderr.contains("no findings"), "{stderr}");
}

#[test]
fn fuzz_catches_a_session_that_does_not_reproduce() {
    // Determinism off, so the plugin answers differently on the replay than it
    // did on the recording. That is exactly the class of bug record/replay is
    // for, and the fuzzer has to notice it without being told what `roll`
    // should return.
    let (_dir, component, manifest, out) = rolling_plugin(false);
    let output = watoots(&[
        "fuzz", &component, "-m", &manifest, "--cases", "8", "--out", &out,
    ]);
    let text = stdout(&output);

    assert!(!output.status.success(), "{text}");
    assert!(text.contains("crash 0"), "{text}");
    assert!(text.contains("diverged"), "{text}");

    // The crash is an artifact, not just a message: a trace file, and the line
    // that turns it into a Rust regression test.
    let crash = std::path::Path::new(&out).join("crash-000.wave");
    assert!(crash.is_file(), "{text}");
    let recorded = std::fs::read_to_string(&crash).unwrap();
    assert!(recorded.starts_with("watoots-trace 1\n"), "{recorded}");
    assert!(recorded.contains("export-call roll"), "{recorded}");
    assert!(
        text.contains("watoots replay") && text.contains("--emit-test"),
        "a crash has to say how to become a test: {text}"
    );

    // And that file really is replayable input, not just something written out.
    let replayed = watoots(&[
        "replay",
        &crash.display().to_string(),
        "--component",
        &component,
        "--assert",
    ]);
    assert!(!replayed.status.success(), "{}", stdout(&replayed));
}

#[test]
fn fuzz_reproduces_a_case_from_its_seed() {
    // A crash report carries `--seed <n> --cases 1`. If that did not reproduce
    // the report would be useless, so the campaign has to be a function of the
    // seed and nothing else.
    let (_dir, component, manifest, out) = rolling_plugin(true);
    let run = || {
        let output = watoots(&[
            "fuzz", &component, "-m", &manifest, "--cases", "1", "--seed", "9137", "--out", &out,
        ]);
        assert!(output.status.success());
        // The trace itself is the thing that has to match, so record one.
        let trace = std::path::Path::new(&out).join("seed.wave");
        let recorded = watoots(&[
            "record",
            &component,
            "-m",
            &manifest,
            "-c",
            "roll",
            "-o",
            &trace.display().to_string(),
            "7",
        ]);
        assert!(recorded.status.success());
        std::fs::read_to_string(&trace).unwrap()
    };
    assert_eq!(run(), run());
}

#[test]
fn fuzz_refuses_an_export_the_component_does_not_have() {
    let (_dir, component, manifest, out) = rolling_plugin(true);
    let output = watoots(&[
        "fuzz", &component, "-m", &manifest, "--call", "nope", "--out", &out,
    ]);
    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("no function \"nope\""), "{stderr}");
    assert!(
        stderr.contains("roll"),
        "a refusal should say what there is: {stderr}"
    );
}

#[test]
fn profile_reports_the_three_buckets_and_names_the_functions() {
    let plugin = sample_plugin().display().to_string();
    let output = watoots(&[
        "profile",
        &plugin,
        "-m",
        &policy(),
        "--answer",
        "watoots:example/log@0.1.0#emit=",
        "-c",
        "lint",
        "--repeat",
        "5",
        "--",
        r#""notes.md""#,
        r#""TODO: fix\n""#,
    ]);
    assert!(output.status.success(), "{output:?}");

    let text = stdout(&output);
    assert!(text.contains("5 call(s)"), "{text}");
    assert!(text.contains("guest"), "{text}");
    assert!(text.contains("host call"), "{text}");
    assert!(text.contains("marshalling"), "{text}");
    // The number most likely to be over-read says what it is, every time.
    assert!(text.contains("marshalling is the remainder"), "{text}");
    // Per-function attribution: the export by name, and the host function the
    // guest called by interface and name.
    assert!(text.contains("export  lint"), "{text}");
    assert!(
        text.contains("import  watoots:example/log@0.1.0#emit"),
        "{text}"
    );
}

#[test]
fn profile_writes_a_firefox_profile_when_asked() {
    let dir = tempfile::tempdir().unwrap();
    let json = dir.path().join("guest.json");
    let plugin = sample_plugin().display().to_string();

    let output = watoots(&[
        "profile",
        &plugin,
        "-m",
        &policy(),
        "--answer",
        "watoots:example/log@0.1.0#emit=",
        "-c",
        "lint",
        "--firefox",
        &json.display().to_string(),
        "--",
        r#""notes.md""#,
        r#""TODO: fix\n""#,
    ]);
    assert!(output.status.success(), "{output:?}");

    let written = std::fs::read_to_string(&json).unwrap();
    assert!(written.starts_with('{'), "the processed profile is JSON");
    assert!(written.contains("\"threads\""), "and it has threads");
}

#[test]
fn profiling_and_recording_are_separate_subcommands() {
    // ADR-0009 refuses the combination rather than permitting it silently, and
    // the CLI expresses that by not offering a --record flag on `profile`.
    let plugin = sample_plugin().display().to_string();
    let output = watoots(&["profile", &plugin, "-c", "lint", "--output", "t.wave"]);
    assert!(!output.status.success());
    let text = String::from_utf8_lossy(&output.stderr).into_owned();
    assert!(text.contains("unexpected argument"), "{text}");
}

// ---------------------------------------------------------------------------
// The asset plugin: the sample that needs a capability.
// ---------------------------------------------------------------------------

/// Build `examples/plugins/rust-asset` and install it beside its `luts/`.
///
/// Returned relative to the repository root, which is the directory `watoots()`
/// runs in — and it has to be, because `${plugin_dir}` in the shipped policy
/// expands to the component path *as spelled on the command line*, and watoots
/// preopens a granted directory under exactly the name it was granted as. A
/// component named through `target/` would preopen a `luts/` that is not there.
fn asset_plugin() -> &'static str {
    static ARTIFACT: OnceLock<()> = OnceLock::new();
    ARTIFACT.get_or_init(|| {
        let root = repo_root();
        let crate_dir = root.join("examples/plugins/rust-asset");
        let status = Command::new(env!("CARGO"))
            .args(["build", "--manifest-path"])
            .arg(crate_dir.join("Cargo.toml"))
            .args(["--target", "wasm32-wasip2", "--release"])
            .status()
            .expect("running cargo to build the asset plugin");
        assert!(status.success(), "failed to build the asset plugin");
        std::fs::copy(
            crate_dir.join("target/wasm32-wasip2/release/rust_asset.wasm"),
            crate_dir.join("rust_asset.wasm"),
        )
        .expect("installing the artifact beside its luts/");
    });
    "examples/plugins/rust-asset/rust_asset.wasm"
}

fn asset_policy() -> &'static str {
    "examples/policies/rust-asset.toml"
}

/// A 2x2 image as WAVE: a mid-tone, a saturated pixel, white and black.
const ASSET_IMAGE: &str =
    "{width: 2, height: 2, pixels: [10, 20, 30, 200, 100, 50, 255, 255, 255, 0, 0, 0]}";

#[test]
fn inspect_reports_the_asset_plugin_as_wanting_exactly_one_directory() {
    let output = watoots(&[
        "inspect",
        asset_plugin(),
        "-m",
        asset_policy(),
        "--provide",
        "watoots:asset/log",
    ]);

    let text = stdout(&output);
    // The install-time answer to "what does this thing want": one directory,
    // named, and nothing else beyond what `std` drags in.
    assert!(text.contains("reads ${plugin_dir}/luts"), "{text}");
    assert!(text.contains("network      -"), "{text}");
    assert!(text.contains("every import is granted"), "{text}");
    assert!(output.status.success(), "{output:?}");
}

#[test]
fn describe_lists_bare_operation_kinds() {
    // `supports` is `list<operation-kind>`, so this renders as five enum cases
    // and nothing else. When it was `list<operation>` the same call printed
    // `gain({channel: red, factor: 1})` — a record of invented values a reader
    // had to know to ignore, and a shape four guests would have invented four
    // different ways.
    let output = watoots(&[
        "run",
        asset_plugin(),
        "-m",
        asset_policy(),
        "--answer",
        "watoots:asset/log@0.1.0#emit=",
        "-c",
        "describe",
    ]);

    assert!(output.status.success(), "{output:?}");
    assert_eq!(
        stdout(&output).trim(),
        r#"{name: "rust-asset", supports: [grayscale, invert, gain, resize, lut]}"#
    );
}

#[test]
fn the_asset_plugin_does_not_load_without_the_filesystem_grant() {
    // The same policy minus one line. `lut` never runs; the component declares
    // `wasi:filesystem` in its binary, so this is a load error and the CLI
    // exits non-zero with the interface named.
    let dir = tempfile::tempdir().unwrap();
    let policy = dir.path().join("no-fs.toml");
    let text = std::fs::read_to_string(repo_root().join(asset_policy())).unwrap();
    let stripped: String = text
        .lines()
        .filter(|line| !line.starts_with("fs.read"))
        .collect::<Vec<_>>()
        .join("\n");
    std::fs::write(&policy, stripped).unwrap();

    let output = watoots(&[
        "run",
        asset_plugin(),
        "-m",
        &policy.display().to_string(),
        "--answer",
        "watoots:asset/log@0.1.0#emit=",
        "-c",
        "apply",
        "--",
        ASSET_IMAGE,
        "[invert]",
    ]);

    assert!(!output.status.success(), "{output:?}");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("wasi:filesystem"), "{stderr}");
}

#[test]
fn the_asset_plugin_reads_its_lookup_table_through_the_grant() {
    // With the grant, the same plugin opens the table itself and the pipeline
    // completes. The pixels are the hand-computed ones from
    // `crates/host/tests/asset_e2e.rs`; this is the command-line spelling of
    // the same claim, with WAVE on both sides.
    let output = watoots(&[
        "run",
        asset_plugin(),
        "-m",
        asset_policy(),
        "--answer",
        "watoots:asset/log@0.1.0#emit=",
        "-c",
        "apply",
        "--",
        ASSET_IMAGE,
        r#"[grayscale, lut("examples/plugins/rust-asset/luts/sepia.lut")]"#,
    ]);

    assert!(output.status.success(), "{output:?}");
    assert_eq!(
        stdout(&output).trim(),
        "ok({width: 2, height: 2, pixels: [24, 22, 17, 168, 149, 116, 255, 255, 239, 0, 0, 0]})"
    );
}

#[test]
fn a_lut_the_grant_does_not_cover_is_an_answer_and_not_a_crash() {
    // A path outside the preopened directory. WASI refuses it, the plugin turns
    // that into `unreadable`, and `run` exits zero because the call succeeded —
    // the *plugin* said no, which is a different thing from the host saying no.
    let output = watoots(&[
        "run",
        asset_plugin(),
        "-m",
        asset_policy(),
        "--answer",
        "watoots:asset/log@0.1.0#emit=",
        "-c",
        "apply",
        "--",
        ASSET_IMAGE,
        r#"[lut("examples/policies/rust-asset.toml")]"#,
    ]);

    assert!(output.status.success(), "{output:?}");
    // `unreadable` carries `file-failure { path, reason }`, so the reason is in
    // the value the caller already has. Nobody has to go and find a log sink to
    // learn that the manifest is the thing to look at.
    let text = stdout(&output);
    assert!(
        text.starts_with(r#"err(unreadable({path: "examples/policies/rust-asset.toml", reason: "#),
        "{text}"
    );
    assert!(text.contains("check the manifest"), "{text}");
}

#[test]
fn a_malformed_image_comes_back_as_a_failure_rather_than_a_trap() {
    // 2x2 needs 12 bytes of RGB8; this is 11.
    let output = watoots(&[
        "run",
        asset_plugin(),
        "-m",
        asset_policy(),
        "--answer",
        "watoots:asset/log@0.1.0#emit=",
        "-c",
        "apply",
        "--",
        "{width: 2, height: 2, pixels: [10, 20, 30, 200, 100, 50, 255, 255, 255, 0, 0]}",
        "[invert]",
    ]);

    assert!(output.status.success(), "{output:?}");
    let text = stdout(&output);
    assert!(text.starts_with("err(malformed("), "{text}");
    assert!(text.contains("12 bytes"), "{text}");
    assert!(text.contains("got 11"), "{text}");
}

// ---------------------------------------------------------------------------
// `watoots reload` (ADR-0010)
// ---------------------------------------------------------------------------

/// A counter with both state hooks, and a second build whose `get` adds a
/// thousand — so one number says which build is running and what it started
/// from. WAT rather than a built guest: this command's subject is the swap,
/// not the toolchain.
const COUNTER_V1: &str = r#"
(component
  (core module $m
    (global $n (mut i32) (i32.const 0))
    (func (export "get") (result i32) (global.get $n))
    (func (export "bump") (param i32)
      (global.set $n (i32.add (global.get $n) (local.get 0))))
    (func (export "save") (result i32) (global.get $n))
    (func (export "restore") (param i32) (global.set $n (local.get 0))))
  (core instance $i (instantiate $m))
  (func $get (result u32) (canon lift (core func $i "get")))
  (func $bump (param "n" u32) (canon lift (core func $i "bump")))
  (func $save (result u32) (canon lift (core func $i "save")))
  (func $restore (param "state" u32) (canon lift (core func $i "restore")))
  (export "get" (func $get))
  (export "bump" (func $bump))
  (export "save-state" (func $save))
  (export "restore-state" (func $restore))
)
"#;

const COUNTER_V2: &str = r#"
(component
  (core module $m
    (global $n (mut i32) (i32.const 0))
    (func (export "bump") (param i32) (result i32)
      (global.set $n (i32.add (global.get $n) (local.get 0)))
      (i32.add (global.get $n) (i32.const 1000)))
    (func (export "save") (result i32) (global.get $n))
    (func (export "restore") (param i32) (global.set $n (local.get 0))))
  (core instance $i (instantiate $m))
  (func $bump (param "n" u32) (result u32) (canon lift (core func $i "bump")))
  (func $save (result u32) (canon lift (core func $i "save")))
  (func $restore (param "state" u32) (canon lift (core func $i "restore")))
  (export "bump" (func $bump))
  (export "save-state" (func $save))
  (export "restore-state" (func $restore))
)
"#;

const COUNTER_WANTS_NETWORK: &str = r#"
(component
  (import "wasi:sockets/tcp@0.2.6" (instance (export "connect" (func))))
  (core module $m
    (global $n (mut i32) (i32.const 0))
    (func (export "bump") (param i32) (result i32)
      (global.set $n (i32.add (global.get $n) (local.get 0)))
      (global.get $n)))
  (core instance $i (instantiate $m))
  (func $bump (param "n" u32) (result u32) (canon lift (core func $i "bump")))
  (export "bump" (func $bump))
)
"#;

/// Two components on disk, ready to be swapped between.
fn counter_dir(replacement: &str) -> (tempfile::TempDir, String, String) {
    let dir = tempfile::tempdir().expect("temp dir");
    let first = dir.path().join("counter.wat");
    let second = dir.path().join("counter-next.wat");
    std::fs::write(&first, COUNTER_V1).expect("writing the first build");
    std::fs::write(&second, replacement).expect("writing the replacement");
    let (a, b) = (first.display().to_string(), second.display().to_string());
    (dir, a, b)
}

#[test]
fn reload_calls_swaps_and_calls_again() {
    let (_dir, first, second) = counter_dir(COUNTER_V2);
    let output = watoots(&["reload", &first, "--to", &second, "-c", "bump", "--", "7"]);
    assert!(output.status.success(), "{output:?}");

    // `bump` returns nothing in the first build and `n + 1000` in the second,
    // so stdout is one line and 1014 says both that the new code is running and
    // that it started from the state the old one handed over.
    let text = stdout(&output);
    assert_eq!(text.trim(), "1014", "{text}");

    let log = String::from_utf8_lossy(&output.stderr).into_owned();
    assert!(log.contains("reload 1"), "{log}");
    assert!(log.contains("state: carried"), "{log}");
}

#[test]
fn reload_re_runs_the_grant_check_against_the_new_bytes() {
    // The command exists for this: `inspect` can say the replacement asks for
    // sockets, but only a reload says so at the moment it would take over.
    let (_dir, first, second) = counter_dir(COUNTER_WANTS_NETWORK);
    let output = watoots(&["reload", &first, "--to", &second, "-c", "bump", "--", "1"]);

    assert!(!output.status.success(), "{output:?}");
    let log = String::from_utf8_lossy(&output.stderr).into_owned();
    assert!(log.contains("wasi:sockets"), "{log}");
    assert!(log.contains("not granted"), "{log}");
}

// ---------------------------------------------------------------------------
// `watoots diff`: what changed between two builds, and would it still load.

#[test]
fn diff_of_a_build_against_itself_is_quiet_and_succeeds() {
    let plugin = sample_plugin().display().to_string();
    let output = watoots(&["diff", &plugin, &plugin, "-m", &policy()]);

    let text = stdout(&output);
    assert!(text.contains("imports\n  (unchanged)"), "{text}");
    assert!(text.contains("exports\n  (unchanged)"), "{text}");
    assert!(text.contains("needs no new grants"), "{text}");
    assert!(output.status.success(), "{text}");
}

#[test]
fn diff_names_the_manifest_key_a_new_import_would_need() {
    // The lint policy against the asset build: a different world, so the
    // "update" wants the filesystem the lint policy never granted. Contrived as
    // a pair, exact as a check -- this is the reload refusal, previewed.
    let previous = sample_plugin().display().to_string();
    let current = asset_plugin().to_string();
    let output = watoots(&["diff", &previous, &current, "-m", &policy()]);

    let text = stdout(&output);
    assert!(text.contains("+ wasi:filesystem/types"), "{text}");
    // Not merely "denied": the line an operator would edit.
    assert!(text.contains("permissions.fs.read"), "{text}");
    assert!(text.contains("reload would refuse this build"), "{text}");
    // Non-zero, so it works in a gate.
    assert!(!output.status.success(), "{text}");
}

#[test]
fn diff_reports_a_removed_export_as_breaking_callers() {
    let previous = sample_plugin().display().to_string();
    let current = asset_plugin().to_string();
    let output = watoots(&["diff", &previous, &current, "-m", &policy()]);

    let text = stdout(&output);
    assert!(text.contains("- lint"), "{text}");
    assert!(text.contains("callers of this break"), "{text}");
    assert!(text.contains("export(s) removed"), "{text}");
}

#[test]
fn diff_does_not_file_an_application_interface_as_a_permission_problem() {
    // `watoots:asset/log` is the application's to serve. Reporting it as a
    // denied permission would send someone to edit the wrong file -- the same
    // rule `inspect` follows.
    let previous = sample_plugin().display().to_string();
    let current = asset_plugin().to_string();
    let output = watoots(&["diff", &previous, &current, "-m", &policy()]);

    let text = stdout(&output);
    assert!(text.contains("watoots:asset/log"), "{text}");
    assert!(
        text.contains("your application must serve"),
        "an application interface must not be reported as a denial: {text}"
    );
    let log_line = text
        .lines()
        .find(|line| line.contains("watoots:asset/log"))
        .unwrap_or_default();
    assert!(
        !log_line.contains("NOT GRANTED"),
        "not a permission problem: {log_line}"
    );
}

#[test]
fn diff_without_a_manifest_reports_changes_without_judging_them() {
    let previous = sample_plugin().display().to_string();
    let current = asset_plugin().to_string();
    let output = watoots(&["diff", &previous, &current]);

    let text = stdout(&output);
    // It still says what changed...
    assert!(text.contains("+ wasi:filesystem/types"), "{text}");
    // ...and says how to find out whether that matters, rather than guessing.
    assert!(text.contains("pass -m"), "{text}");
}

#[test]
fn a_lost_import_is_news_and_the_two_failure_kinds_stay_separate() {
    // Fewer capabilities is the safe direction, so dropping imports must not
    // read as a permission problem. Run the pair backwards to see losses on
    // their own.
    let output = watoots(&[
        "diff",
        asset_plugin(),
        &sample_plugin().display().to_string(),
        "-m",
        asset_policy(),
        "--provide",
        "watoots:example/log",
    ]);

    let text = stdout(&output);
    assert!(text.contains("- wasi:filesystem/types"), "{text}");
    assert!(text.contains("no longer needed"), "{text}");
    // The import side is clean: giving up capabilities needs no new grant.
    assert!(text.contains("this update needs no new grants"), "{text}");

    // It still fails, and for the other reason entirely -- the exports changed.
    // The two are reported and counted separately because they are fixed in
    // different places, and this is what pins that apart.
    assert!(text.contains("export(s) removed"), "{text}");
    assert!(!output.status.success(), "{text}");
}

#[test]
fn running_an_unverified_plugin_says_so_loudly_and_says_why() {
    // Not behind --audit. A warning nobody sees by default is theatre, which is
    // the argument ADR-0011 makes for the audit trail and applies here too.
    let output = watoots(&[
        "run",
        &sample_plugin().display().to_string(),
        "-m",
        &policy(),
        "--answer",
        "watoots:example/log#emit=",
        "-c",
        "name",
    ]);

    let text = String::from_utf8_lossy(&output.stderr);
    assert!(text.contains("running unverified"), "{text}");
    // The risk, not the setting: "verification is off" is not actionable.
    assert!(text.contains("replace that file"), "{text}");
    // And the way out.
    assert!(text.contains("cosign sign-blob"), "{text}");

    // stderr, not stdout: `watoots run ... > out` has to keep working.
    let out = stdout(&output);
    assert!(!out.contains("running unverified"), "{out}");
}

#[test]
fn inspect_reports_the_signature_posture_alongside_the_capabilities() {
    // `inspect` is the read-this-before-you-install tool. A report that lists
    // every permission and silently omits who may have signed the plugin is
    // incomplete in the one section a reviewer most needs.
    let plugin = sample_plugin().display().to_string();
    let output = watoots(&["inspect", &plugin, "-m", &policy()]);

    let text = stdout(&output);
    assert!(text.contains("publisher"), "{text}");
    assert!(text.contains("signature"), "{text}");
    // The consequence, not just the setting.
    assert!(text.contains("any bytes at this path load"), "{text}");
    // WARN rather than DENY: nothing asked for a signature, so nothing was
    // refused. `DENY` has to keep meaning "requested and refused".
    assert!(text.contains("signature    WARN"), "{text}");
}

#[test]
fn record_keeps_the_trace_when_the_call_fails_because_that_is_the_bug() {
    // The one session anyone actually wants a file for is the one where the
    // plugin failed. The first version of `record` threw it away with a `?`.
    // Found by the preview demo trying to record a decoder hitting its memory
    // ceiling, which is exactly the shape of a real bug report.
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("bug.wave");
    let policy = dir.path().join("tight.toml");
    // A transfer ceiling the result cannot fit under: the call fails with a
    // limit, which is a failure the trace format can carry. Transfer rather
    // than fuel because instantiation lifts nothing and so is unaffected --
    // a fuel budget small enough to fail the call also fails the load, which
    // is the *other* test's case.
    std::fs::write(
        &policy,
        "[permissions]\nclocks = \"monotonic\"\nenv = {}\n\n\
         [limits]\ntransfer = 64\n\n[signature]\nrequired = false\n",
    )
    .unwrap();
    let plugin = sample_plugin().display().to_string();
    // Enough diagnostics that lifting the result costs more than 64.
    let source = format!("\"{}\"", "TODO x\\n".repeat(400));

    let recorded = watoots(&[
        "record",
        &plugin,
        "-m",
        &policy.display().to_string(),
        "--answer",
        "watoots:example/log@0.1.0#emit=",
        "-c",
        "lint",
        "-o",
        &trace.display().to_string(),
        "--",
        r#""notes.md""#,
        &source,
    ]);
    // The command fails, because the call did...
    assert!(!recorded.status.success());
    let err = String::from_utf8_lossy(&recorded.stderr);
    assert!(
        err.contains("copied between the host and the guest"),
        "{err}"
    );
    // ...and the trace exists anyway, carrying the failure as its outcome.
    let text = std::fs::read_to_string(&trace).expect("the trace was written");
    assert!(text.contains("export-call lint"), "{text}");
    assert!(text.contains("WT_ERR_LIMIT_EXCEEDED"), "{text}");

    // Replaying it reproduces the failure: that is what makes it a bug report.
    let replayed = watoots(&[
        "replay",
        &trace.display().to_string(),
        "-c",
        &plugin,
        "--assert",
    ]);
    assert!(
        replayed.status.success(),
        "{}",
        String::from_utf8_lossy(&replayed.stderr)
    );
    assert!(
        stdout(&replayed).contains("matched"),
        "{}",
        stdout(&replayed)
    );
}

#[test]
fn record_writes_nothing_when_the_failure_was_before_the_call() {
    // A component that will not load has no crossings to record. An empty
    // trace would misdescribe what happened, so there is no file.
    let dir = tempfile::tempdir().unwrap();
    let trace = dir.path().join("nothing.wave");
    let not_a_component = dir.path().join("garbage.wasm");
    std::fs::write(&not_a_component, b"this is not a component").unwrap();

    let recorded = watoots(&[
        "record",
        &not_a_component.display().to_string(),
        "-c",
        "lint",
        "-o",
        &trace.display().to_string(),
    ]);
    assert!(!recorded.status.success());
    assert!(!trace.exists(), "no call happened, so no trace");
}