supercov-engine 4.18.0

Rust instrumentation, evidence, attribution, and query engine for Supercov
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
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
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
//! A Rust Worker a browser suite drives through `wrangler dev`.
//!
//! The crate is instrumented in the suite's copy and `worker-build` compiles
//! it to wasm, where the region runtime keeps its region in linear memory
//! behind two exports per crate: its address and a clear. Supercov points the
//! copy's wrangler configuration at an entry module that remembers every wasm
//! instance the isolate creates, and at an inspector port of its own, so the
//! suite's own `wrangler dev` command is left as written. While the suite
//! runs, a poller takes each instance's region through the inspector and
//! clears it every few milliseconds. Each take is a window, credited by time
//! to the one browser test whose span it overlaps, as for a Go or JVM server;
//! what no single test's window holds is the run's background.

use std::{
    collections::BTreeMap,
    fs,
    io::Write,
    net::{SocketAddr, TcpListener, TcpStream},
    path::{Path, PathBuf},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    thread::JoinHandle,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use base64::Engine as _;
use serde_json::{Value, json};

use crate::{
    integrity::{FrontendIntegrityInputs, create_explicit_run_integrity},
    lifecycle::{note_kept_evidence, remove_stored_tree_deferred},
    run_store::{RunIntegrity, RunMetadata},
    rust_project::PreparedRustProject,
    served_tests::ServedTest,
};

/// The module wrangler bundles in place of the project's own entry: it
/// installs the registry, then is the project's entry.
const ENTRY_FILE: &str = "supercov-worker-entry.mjs";
const REGISTRY_FILE: &str = "supercov-worker-registry.mjs";

/// Remember every wasm instance the isolate creates, for the inspector:
/// workerd answers no heap queries, so instances cannot be found later.
const REGISTRY: &str = r#"// Generated by Supercov: remembers this isolate's wasm instances.
const instances = (globalThis.__supercovWasm ??= []);
const Instance = WebAssembly.Instance;
function Recorded(module, imports) {
  const instance = new Instance(module, imports);
  instances.push(instance);
  return instance;
}
Recorded.prototype = Instance.prototype;
WebAssembly.Instance = Recorded;
const instantiate = WebAssembly.instantiate;
WebAssembly.instantiate = async function (source, imports) {
  const result = await instantiate.call(WebAssembly, source, imports);
  instances.push(result instanceof Instance ? result : result.instance);
  return result;
};
"#;

/// Evaluated in the Worker's context on every poll: each instrumented
/// crate's region as its header and the pages a probe touched since the
/// last take, then cleared. A region with nothing new is left out, except
/// the first time, which carries what `cfg!` said of the crate's gates.
const TAKE: &str = r#"(() => {
  const seen = (globalThis.__supercovTaken ??= new WeakSet());
  const out = [];
  for (const instance of globalThis.__supercovWasm ?? []) {
    const exports = instance.exports;
    for (const name of Object.keys(exports)) {
      if (!name.startsWith('__supercov_region_')) continue;
      const crate = name.slice('__supercov_region_'.length);
      const packed = BigInt.asUintN(64, BigInt(exports[name]()));
      const at = Number(packed >> 32n), length = Number(packed & 0xffffffffn);
      if (!length || !exports.memory) continue;
      const view = new DataView(exports.memory.buffer, at, length);
      const first = !seen.has(exports);
      if (!first && view.getUint32(40, true) === 0 && view.getUint32(44, true) === 0) continue;
      seen.add(exports);
      const bytes = new Uint8Array(exports.memory.buffer, at, length);
      const encode = (from, to) => {
        let text = '';
        for (let index = from; index < to; index += 0x8000)
          text += String.fromCharCode.apply(null, bytes.subarray(index, Math.min(to, index + 0x8000)));
        return btoa(text);
      };
      const bodyAt = view.getUint32(32, true);
      const segments = [[0, encode(0, bodyAt)]];
      for (let page = 0; bodyAt + page * 4096 < length; page++) {
        if (bytes[128 + (page >> 3)] & (1 << (page & 7))) {
          const from = bodyAt + page * 4096;
          segments.push([from, encode(from, Math.min(length, from + 4096))]);
        }
      }
      out.push([crate, length, segments]);
      exports['__supercov_clear_' + crate]();
    }
  }
  return out;
})()"#;

/// How often the poller takes the regions. A window shorter than the gap
/// between two tests is what lets each be credited its own.
const POLL_INTERVAL: Duration = Duration::from_millis(5);

/// A wrangler configuration Supercov can point at its entry.
#[derive(Debug, Clone, PartialEq, Eq)]
struct WorkerConfig {
    path: PathBuf,
    main: String,
    inspector_port: Option<u16>,
}

/// The wrangler configurations under `root` that build a Rust Worker: a
/// `[build] command` running `worker-build`, beside the crate's Cargo.toml.
///
/// A plain walk: a `.gitignore` above the project (a monorepo's, or the
/// checkout a fixture sits in) must not hide the project itself.
fn worker_configs(root: &Path) -> Vec<PathBuf> {
    const SKIPPED: &[&str] = &[
        "node_modules",
        "target",
        "build",
        "dist",
        ".git",
        ".supercov",
        ".wrangler",
    ];
    let mut found = Vec::new();
    let mut directories = vec![(root.to_path_buf(), 0)];
    while let Some((directory, depth)) = directories.pop() {
        let Ok(entries) = fs::read_dir(&directory) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let name = entry.file_name();
            let Some(name) = name.to_str() else {
                continue;
            };
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            if kind.is_dir() {
                if depth < 6 && !SKIPPED.contains(&name) {
                    directories.push((path, depth + 1));
                }
                continue;
            }
            if !kind.is_file()
                || !matches!(name, "wrangler.toml" | "wrangler.json" | "wrangler.jsonc")
            {
                continue;
            }
            let builds_rust = read_config(&path).is_some_and(|(_, document)| {
                build_command(&document).is_some_and(|command| command.contains("worker-build"))
            });
            if builds_rust && path.with_file_name("Cargo.toml").is_file() {
                found.push(path);
            }
        }
    }
    found.sort();
    found
}

/// A configuration as JSON whatever it was written in.
fn read_config(path: &Path) -> Option<(String, Value)> {
    let text = fs::read_to_string(path).ok()?;
    let document = if path
        .extension()
        .is_some_and(|extension| extension == "toml")
    {
        let table = text.parse::<toml::Table>().ok()?;
        serde_json::to_value(table).ok()?
    } else {
        serde_json::from_str(&strip_jsonc(&text)).ok()?
    };
    Some((text, document))
}

fn build_command(document: &Value) -> Option<String> {
    match document.get("build")?.get("command")? {
        Value::String(command) => Some(command.clone()),
        Value::Array(parts) => Some(
            parts
                .iter()
                .filter_map(Value::as_str)
                .collect::<Vec<_>>()
                .join(" "),
        ),
        _ => None,
    }
}

fn parse_config(path: &Path) -> Option<WorkerConfig> {
    let (_, document) = read_config(path)?;
    Some(WorkerConfig {
        path: path.to_owned(),
        main: document.get("main")?.as_str()?.to_owned(),
        inspector_port: document
            .get("dev")
            .and_then(|dev| dev.get("inspector_port"))
            .and_then(Value::as_u64)
            .and_then(|port| u16::try_from(port).ok()),
    })
}

/// JSON with comments and trailing commas, as wrangler.jsonc allows, made
/// plain JSON. Strings are copied as they are.
fn strip_jsonc(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut characters = text.chars().peekable();
    while let Some(character) = characters.next() {
        match character {
            '"' => {
                out.push('"');
                while let Some(inner) = characters.next() {
                    out.push(inner);
                    match inner {
                        '\\' => {
                            if let Some(escaped) = characters.next() {
                                out.push(escaped);
                            }
                        }
                        '"' => break,
                        _ => {}
                    }
                }
            }
            '/' if characters.peek() == Some(&'/') => {
                for inner in characters.by_ref() {
                    if inner == '\n' {
                        out.push('\n');
                        break;
                    }
                }
            }
            '/' if characters.peek() == Some(&'*') => {
                characters.next();
                let mut previous = '\0';
                for inner in characters.by_ref() {
                    if previous == '*' && inner == '/' {
                        break;
                    }
                    previous = inner;
                }
            }
            _ => out.push(character),
        }
    }
    // A comma before a closing bracket, past any whitespace.
    let mut cleaned = String::with_capacity(out.len());
    let mut in_string = false;
    let mut escaped = false;
    let bytes = out.as_bytes();
    for (index, character) in out.char_indices() {
        if in_string {
            cleaned.push(character);
            if escaped {
                escaped = false;
            } else if character == '\\' {
                escaped = true;
            } else if character == '"' {
                in_string = false;
            }
            continue;
        }
        if character == '"' {
            in_string = true;
        } else if character == ',' {
            let next = bytes[index + 1..]
                .iter()
                .find(|byte| !byte.is_ascii_whitespace());
            if matches!(next, Some(b'}' | b']')) {
                continue;
            }
        }
        cleaned.push(character);
    }
    cleaned
}

/// Point the copy's configuration at the entry module and, given one, the
/// inspector port. The rest of the configuration is the project's.
fn rewrite_config(config: &WorkerConfig, entry: &str, port: Option<u16>) -> Result<(), String> {
    let path = &config.path;
    let text = fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))?;
    let rewritten = if path
        .extension()
        .is_some_and(|extension| extension == "toml")
    {
        let mut document = text
            .parse::<toml_edit::DocumentMut>()
            .map_err(|error| format!("{}: {error}", path.display()))?;
        document["main"] = toml_edit::value(entry);
        if let (None, Some(port)) = (config.inspector_port, port) {
            if !document.contains_key("dev") {
                document["dev"] = toml_edit::table();
            }
            document["dev"]["inspector_port"] = toml_edit::value(i64::from(port));
        }
        document.to_string()
    } else {
        let mut document: Value = serde_json::from_str(&strip_jsonc(&text))
            .map_err(|error| format!("{}: {error}", path.display()))?;
        document["main"] = json!(entry);
        if let (None, Some(port)) = (config.inspector_port, port) {
            if !document.get("dev").is_some_and(Value::is_object) {
                document["dev"] = json!({});
            }
            document["dev"]["inspector_port"] = json!(port);
        }
        serde_json::to_string_pretty(&document).map_err(|error| error.to_string())?
    };
    fs::write(path, rewritten).map_err(|error| format!("{}: {error}", path.display()))
}

/// Write the registry and Supercov's entry beside a configuration and point
/// the configuration at it. A configuration that already names the entry --
/// a copy kept from an earlier run -- is left as it is: the entry would
/// otherwise import itself.
fn point_at_entry(config: &WorkerConfig, port: Option<u16>) -> Result<(), String> {
    if config.main.trim_start_matches("./") == ENTRY_FILE {
        return Ok(());
    }
    let directory = config.path.parent().unwrap_or(Path::new("."));
    fs::write(directory.join(REGISTRY_FILE), REGISTRY).map_err(|error| error.to_string())?;
    let main = config.main.trim_start_matches("./");
    let entry = format!(
        "// Generated by Supercov: the project's entry, with its wasm instances remembered.\nimport './{REGISTRY_FILE}';\nexport * from './{main}';\nexport {{ default }} from './{main}';\n"
    );
    fs::write(directory.join(ENTRY_FILE), entry).map_err(|error| error.to_string())?;
    rewrite_config(config, ENTRY_FILE, port)
}

/// A port nothing listens on now.
fn free_port() -> Result<u16, String> {
    let listener = TcpListener::bind("127.0.0.1:0").map_err(|error| error.to_string())?;
    listener
        .local_addr()
        .map(|address| address.port())
        .map_err(|error| error.to_string())
}

/// The cfg values of wasm32-unknown-unknown, as the crate's own toolchain
/// reports them: what decides which items the target leaves out.
pub(crate) fn wasm_target_cfg(
    crate_directory: &Path,
) -> Option<crate::rust_instrumenter::TargetCfg> {
    let output = std::process::Command::new("rustc")
        .args(["--print", "cfg", "--target", "wasm32-unknown-unknown"])
        .current_dir(crate_directory)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let values = String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| line.parse::<cargo_platform::Cfg>().ok())
        .collect::<Vec<_>>();
    Some(crate::rust_instrumenter::TargetCfg::new(&values))
}

fn now_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| elapsed.as_millis() as i64)
        .unwrap_or(0)
}

/// Takes the regions of one `wrangler dev` through its inspector until told
/// to stop, appending a window per take with anything in it.
struct Poller {
    stop: Arc<AtomicBool>,
    thread: Option<JoinHandle<()>>,
}

impl Poller {
    fn start(port: u16, windows: PathBuf) -> Self {
        let stop = Arc::new(AtomicBool::new(false));
        let flag = Arc::clone(&stop);
        let thread = std::thread::Builder::new()
            .name("supercov-worker-poller".into())
            .spawn(move || poll(port, &windows, &flag))
            .ok();
        Self { stop, thread }
    }

    /// Take once more if wrangler is still there, then stop.
    fn finish(mut self) {
        self.stop.store(true, Ordering::Release);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

impl Drop for Poller {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Release);
    }
}

fn poll(port: u16, windows: &Path, stop: &AtomicBool) {
    let Ok(mut file) = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(windows)
    else {
        return;
    };
    let address = SocketAddr::from(([127, 0, 0, 1], port));
    // wrangler starts when the suite asks for it, and restarts the Worker on
    // a rebuild: connect, and connect again, until the run is over.
    while !stop.load(Ordering::Acquire) {
        let Ok(stream) = TcpStream::connect_timeout(&address, Duration::from_millis(200)) else {
            std::thread::sleep(Duration::from_millis(100));
            continue;
        };
        let _ = stream.set_nodelay(true);
        let _ = stream.set_read_timeout(Some(Duration::from_millis(20)));
        let Ok((mut socket, _)) =
            tungstenite::client::client(format!("ws://127.0.0.1:{port}/ws"), stream)
        else {
            std::thread::sleep(Duration::from_millis(100));
            continue;
        };
        session(&mut socket, &mut file, stop);
        let _ = socket.close(None);
    }
}

/// One inspector connection: enable the runtime, learn the Worker's
/// execution context, and take its regions on the clock. Returns when the
/// connection ends, or after the last take once the run is over.
fn session(socket: &mut tungstenite::WebSocket<TcpStream>, file: &mut fs::File, stop: &AtomicBool) {
    use tungstenite::{Error, Message};
    let send = |socket: &mut tungstenite::WebSocket<TcpStream>, message: Value| {
        socket
            .send(Message::text(message.to_string()))
            .map_err(|_| ())
    };
    if send(socket, json!({"id": 1, "method": "Runtime.enable"})).is_err() {
        return;
    }
    let mut contexts = Vec::<i64>::new();
    let mut next_id = 2_u64;
    // The take in flight: its id, when it was sent, and where its window
    // starts.
    let mut awaiting: Option<(u64, Instant)> = None;
    let mut window_start = now_ms();
    let mut last_take = Instant::now() - POLL_INTERVAL;
    let mut final_sent = false;
    loop {
        let stopping = stop.load(Ordering::Acquire);
        if stopping && awaiting.is_none() && (final_sent || contexts.is_empty()) {
            return;
        }
        if awaiting.is_none()
            && let Some(context) = contexts.last()
            && (stopping || last_take.elapsed() >= POLL_INTERVAL)
        {
            let id = next_id;
            next_id += 1;
            let request = json!({
                "id": id,
                "method": "Runtime.evaluate",
                "params": {"expression": TAKE, "contextId": context, "returnByValue": true},
            });
            if send(socket, request).is_err() {
                return;
            }
            awaiting = Some((id, Instant::now()));
            last_take = Instant::now();
            final_sent = stopping;
        }
        match socket.read() {
            Ok(Message::Text(text)) => {
                let Ok(message) = serde_json::from_str::<Value>(text.as_str()) else {
                    continue;
                };
                match message.get("method").and_then(Value::as_str) {
                    Some("Runtime.executionContextCreated") => {
                        if let Some(id) = message["params"]["context"]["id"].as_i64() {
                            contexts.push(id);
                        }
                    }
                    Some("Runtime.executionContextDestroyed") => {
                        if let Some(id) = message["params"]["executionContextId"].as_i64() {
                            contexts.retain(|context| *context != id);
                        }
                    }
                    Some("Runtime.executionContextsCleared") => contexts.clear(),
                    _ => {}
                }
                if let Some((id, _)) = awaiting
                    && message.get("id").and_then(Value::as_u64) == Some(id)
                {
                    awaiting = None;
                    let end = now_ms();
                    let regions = &message["result"]["result"]["value"];
                    if regions
                        .as_array()
                        .is_some_and(|regions| !regions.is_empty())
                    {
                        let line = json!({"start": window_start, "end": end, "regions": regions});
                        let _ = writeln!(file, "{line}");
                    }
                    window_start = end;
                }
            }
            Ok(Message::Close(_)) => return,
            Ok(_) => {}
            Err(Error::Io(error))
                if matches!(
                    error.kind(),
                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                ) => {}
            Err(_) => return,
        }
        // A take the Worker never answered (it was replaced mid-evaluation)
        // is given up; the next one covers the same span.
        if awaiting.is_some_and(|(_, sent)| sent.elapsed() > Duration::from_secs(5)) {
            awaiting = None;
        }
    }
}

/// One take as the poller appended it.
struct Window {
    start: i64,
    end: i64,
    /// Each region, rebuilt: crate key and bytes.
    regions: Vec<(String, Vec<u8>)>,
}

fn read_windows(directory: &Path) -> Result<Vec<Window>, String> {
    let mut files = fs::read_dir(directory)
        .map(|entries| {
            entries
                .filter_map(Result::ok)
                .map(|entry| entry.path())
                .filter(|path| {
                    path.extension()
                        .is_some_and(|extension| extension == "windows")
                })
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    files.sort();
    let mut windows = Vec::new();
    for file in &files {
        let text =
            fs::read_to_string(file).map_err(|error| format!("{}: {error}", file.display()))?;
        // A line cut short by Supercov being stopped mid-write is skipped.
        for line in text.lines() {
            let Ok(value) = serde_json::from_str::<Value>(line) else {
                continue;
            };
            if let Some(window) = window_from(&value) {
                windows.push(window);
            }
        }
    }
    Ok(windows)
}

fn window_from(value: &Value) -> Option<Window> {
    let mut regions = Vec::new();
    for region in value.get("regions")?.as_array()? {
        let crate_key = region.get(0)?.as_str()?.to_owned();
        let length = usize::try_from(region.get(1)?.as_u64()?).ok()?;
        let mut bytes = vec![0_u8; length];
        for segment in region.get(2)?.as_array()? {
            let offset = usize::try_from(segment.get(0)?.as_u64()?).ok()?;
            let data = base64::engine::general_purpose::STANDARD
                .decode(segment.get(1)?.as_str()?)
                .ok()?;
            bytes
                .get_mut(offset..offset + data.len())?
                .copy_from_slice(&data);
        }
        regions.push((crate_key, bytes));
    }
    Some(Window {
        start: value.get("start")?.as_i64()?,
        end: value.get("end")?.as_i64()?,
        regions,
    })
}

/// The Rust Workers of one Cargo workspace a browser suite may start.
pub struct RustWorkerServer {
    project: PreparedRustProject,
    pollers: Vec<Poller>,
    integrity: RunIntegrity,
    source_inputs: crate::source_manifest::Inputs,
    source_roots: Option<Vec<String>>,
    /// `.supercov/work/<run>/rust-worker`, holding `evidence/`.
    directory: PathBuf,
}

impl RustWorkerServer {
    /// Whether `root` holds a Rust Worker a suite could start.
    pub fn present(root: &Path) -> bool {
        !worker_configs(root).is_empty()
    }

    /// Instrument the copy's Worker crates and point their configurations at
    /// Supercov's entry, one server per Cargo workspace. Empty when the
    /// project has no Rust Worker.
    pub fn prepare(
        root: &Path,
        workspace: &Path,
        run_id: &str,
        command: &[String],
        diagnostics: &mut dyn Write,
    ) -> Result<Vec<Self>, String> {
        let configs = worker_configs(workspace);
        // Configurations by the Cargo workspace their crate belongs to: a
        // workspace is instrumented once, whatever number of Workers it holds.
        let mut by_workspace = BTreeMap::<PathBuf, Vec<WorkerConfig>>::new();
        for path in configs {
            let Some(config) = parse_config(&path) else {
                writeln!(
                    diagnostics,
                    "[supercov] {} names no `main`; its Worker is not measured",
                    path.display()
                )
                .map_err(|error| error.to_string())?;
                continue;
            };
            let crate_directory = path.parent().unwrap_or(workspace).to_owned();
            let cargo_root = cargo_workspace_root(&crate_directory).unwrap_or(crate_directory);
            by_workspace.entry(cargo_root).or_default().push(config);
        }
        let mut servers = Vec::new();
        for (index, (cargo_root, configs)) in by_workspace.into_iter().enumerate() {
            let Ok(relative) = cargo_root.strip_prefix(workspace) else {
                continue;
            };
            let source_roots = crate::source_discovery::configured_source_roots(
                &std::env::vars().collect::<BTreeMap<_, _>>(),
            );
            // The project's inputs, as a later query recomputes them to judge
            // whether the run is current.
            let mut integrity_inputs = crate::rust_run::collect_integrity_inputs(root, command)?;
            crate::source_discovery::fold_roots_into_configuration(
                &mut integrity_inputs.execution_configuration,
                source_roots.as_deref(),
            );
            let source_inputs =
                crate::source_capture::capture(root, "rust", integrity_inputs.assertion_paths())?;
            let integrity = create_explicit_run_integrity(
                root,
                &integrity_inputs,
                &FrontendIntegrityInputs::embedded_rust(),
            )
            .map_err(|error| error.to_string())?;
            let cfg = wasm_target_cfg(&cargo_root);
            let mut project =
                crate::rust_project::prepare_rust_project_for(&cargo_root, None, cfg.as_ref())
                    .map_err(|error| error.to_string())?;
            crate::rust_wasm_evidence::root_paths(&mut project, relative);
            let directory = root
                .join(".supercov/work")
                .join(run_id)
                .join(format!("rust-worker-{index}"));
            let evidence = directory.join("evidence");
            fs::create_dir_all(&evidence).map_err(|error| error.to_string())?;
            let mut pollers = Vec::new();
            for (number, config) in configs.iter().enumerate() {
                let port = match config.inspector_port {
                    Some(port) => port,
                    None => free_port()?,
                };
                point_at_entry(config, Some(port))?;
                pollers.push(Poller::start(
                    port,
                    evidence.join(format!("{number:04}.windows")),
                ));
            }
            servers.push(Self {
                project,
                pollers,
                integrity,
                source_inputs,
                source_roots,
                directory,
            });
        }
        Ok(servers)
    }

    pub fn source_files(&self) -> usize {
        self.project.source_files.len()
    }

    /// The source this Worker was instrumented from: an image built from an
    /// earlier copy holds probes placed in other source.
    pub fn source_fingerprint(&self) -> String {
        self.integrity.fingerprint.source.clone()
    }

    /// What the suite's environment needs: a lint on the rewritten source
    /// must not fail the Worker's build under the crate's own lint policy.
    ///
    /// Capped at `warn`, not `allow` as for `cargo test`: Cargo learns which
    /// crate types a target supports from rustc's "dropping unsupported crate
    /// type" warnings, and wasm32 drops `dylib` and `proc-macro`, so with
    /// every lint allowed it cannot read the answer and stops the build. The
    /// probes' parentheses, the one lint they raise, are allowed by name.
    pub fn environment(&self) -> BTreeMap<String, String> {
        let mut rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
        if !rustflags.is_empty() {
            rustflags.push(' ');
        }
        rustflags.push_str("--cap-lints=warn -A unused_parens");
        BTreeMap::from([("RUSTFLAGS".into(), rustflags)])
    }

    /// Publish what the Workers ran as a Rust run of its own: each window
    /// credited, by time, to the one browser test whose span it overlaps;
    /// what no single test's does is the run's background. None when no
    /// Worker ran or no browser test reported.
    pub fn publish(
        mut self,
        root: &Path,
        _evidence_run_id: &str,
        metadata: RunMetadata,
        served: &[ServedTest],
        diagnostics: &mut dyn Write,
    ) -> Result<Option<(PathBuf, RunMetadata)>, String> {
        for poller in std::mem::take(&mut self.pollers) {
            poller.finish();
        }
        let evidence_directory = self.directory.join("evidence");
        let result = read_windows(&evidence_directory).and_then(|windows| {
            crate::rust_wasm_evidence::publish(
                root,
                crate::rust_wasm_evidence::WasmRun {
                    language: "Rust Worker",
                    archive: "rust-worker-evidence.raw.gz",
                    project: &self.project,
                    integrity: &self.integrity,
                    source_inputs: &self.source_inputs,
                    source_roots: self.source_roots.clone(),
                },
                windows
                    .into_iter()
                    .map(|window| crate::rust_wasm_evidence::WasmRecord {
                        owner: crate::rust_wasm_evidence::Owner::Window(window.start, window.end),
                        regions: window.regions,
                    })
                    .collect(),
                metadata,
                served,
                diagnostics,
            )
        });
        let result = result.map_err(|error| {
            let run = self
                .directory
                .parent()
                .and_then(Path::file_name)
                .map(|name| name.to_string_lossy().into_owned())
                .unwrap_or_default();
            note_kept_evidence(
                root,
                &evidence_directory,
                &format!("{run}-rust-worker"),
                error,
            )
        });
        let _ = remove_stored_tree_deferred(root, &self.directory);
        result
    }
}

/// The program Supercov's `wrangler` stands in for, named in the test
/// processes' environment.
pub const REAL_WRANGLER: &str = "SUPERCOV_WRANGLER";
/// The hidden commands the stand-in and its poller run as.
pub const WRANGLER_COMMAND: &str = "__wrangler";
pub const WRANGLER_POLL_COMMAND: &str = "__wrangler-poll";

/// The Rust Workers a `cargo test` suite starts itself, with `wrangler dev`.
///
/// The crate is instrumented with the rest of the workspace, and `wrangler
/// dev` builds it in the copy as it builds it anywhere. What it ran is read
/// by a `wrangler` of Supercov's, first on the test processes' `PATH`: it
/// starts a poller on an inspector port of its own and then becomes the real
/// `wrangler`, so the test keeps the process and the signals it expects. The
/// poller writes what it takes into the evidence directory of the test that
/// started the Worker, and the run reads it there as that test's own: exact,
/// not credited by time.
pub struct CargoTestWorkers {
    environment: Vec<(String, std::ffi::OsString)>,
}

impl CargoTestWorkers {
    /// Point the copy's Worker configurations at Supercov's entry and put the
    /// stand-in in `tools`. None where the workspace has no Rust Worker, or
    /// where no `wrangler` is installed: a test that looks for one must find
    /// none, as it would without Supercov.
    pub fn prepare(workspace: &Path, tools: &Path) -> Result<Option<Self>, String> {
        let configs = worker_configs(workspace)
            .iter()
            .filter_map(|path| parse_config(path))
            .collect::<Vec<_>>();
        if configs.is_empty() {
            return Ok(None);
        }
        let path = std::env::var_os("PATH").unwrap_or_default();
        let Some(real) = on_path(&path, "wrangler") else {
            return Ok(None);
        };
        for config in &configs {
            point_at_entry(config, None)?;
        }
        let supercov = std::env::current_exe().map_err(|error| error.to_string())?;
        fs::create_dir_all(tools).map_err(|error| format!("{}: {error}", tools.display()))?;
        write_stand_in(tools, &supercov)?;
        let mut directories = vec![tools.to_owned()];
        directories.extend(std::env::split_paths(&path));
        let joined = std::env::join_paths(directories).map_err(|error| error.to_string())?;
        Ok(Some(Self {
            environment: vec![
                ("PATH".into(), joined),
                (REAL_WRANGLER.into(), real.into_os_string()),
            ],
        }))
    }

    /// What each test process is started with.
    pub fn environment(&self) -> impl Iterator<Item = (&str, &std::ffi::OsStr)> {
        self.environment
            .iter()
            .map(|(name, value)| (name.as_str(), value.as_os_str()))
    }
}

/// A program on `path`: a file of that name, or on Windows one with a
/// PATHEXT extension.
fn on_path(path: &std::ffi::OsStr, name: &str) -> Option<PathBuf> {
    let names = if cfg!(windows) {
        vec![
            format!("{name}.cmd"),
            format!("{name}.exe"),
            name.to_owned(),
        ]
    } else {
        vec![name.to_owned()]
    };
    std::env::split_paths(path).find_map(|directory| {
        names
            .iter()
            .map(|name| directory.join(name))
            .find(|candidate| fs::metadata(candidate).is_ok_and(|metadata| metadata.is_file()))
    })
}

fn write_stand_in(tools: &Path, supercov: &Path) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let quoted = supercov.to_string_lossy().replace('\'', r"'\''");
        let script = tools.join("wrangler");
        fs::write(
            &script,
            format!("#!/bin/sh\nexec '{quoted}' {WRANGLER_COMMAND} \"$@\"\n"),
        )
        .map_err(|error| format!("{}: {error}", script.display()))?;
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755))
            .map_err(|error| format!("{}: {error}", script.display()))?;
    }
    #[cfg(windows)]
    {
        let script = tools.join("wrangler.cmd");
        fs::write(
            &script,
            format!("@\"{}\" {WRANGLER_COMMAND} %*\r\n", supercov.display()),
        )
        .map_err(|error| format!("{}: {error}", script.display()))?;
    }
    Ok(())
}

/// `wrangler dev`, with options before or after the command: wrangler's
/// global options that take a value (`--cwd worker dev`) are read past.
fn starts_dev(arguments: &[std::ffi::OsString]) -> bool {
    const VALUED: &[&str] = &["--cwd", "-c", "--config", "-e", "--env", "--env-file"];
    let mut arguments = arguments.iter().map(|argument| argument.to_string_lossy());
    while let Some(argument) = arguments.next() {
        if VALUED.contains(&argument.as_ref()) {
            arguments.next();
        } else if !argument.starts_with('-') {
            return argument == "dev";
        }
    }
    false
}

/// The inspector port the arguments name, as `--inspector-port N` or
/// `--inspector-port=N`.
fn named_inspector_port(arguments: &[std::ffi::OsString]) -> Option<u16> {
    let mut arguments = arguments.iter().map(|argument| argument.to_string_lossy());
    while let Some(argument) = arguments.next() {
        if argument == "--inspector-port" {
            return arguments.next()?.parse().ok();
        }
        if let Some(port) = argument.strip_prefix("--inspector-port=") {
            return port.parse().ok();
        }
    }
    None
}

/// Supercov's `wrangler`: under a test, `wrangler dev` gets an inspector
/// port and a poller writing into the test's evidence; then this process
/// becomes the real `wrangler`. The build it runs caps lints at `warn`, as
/// for a Worker under a browser suite.
pub fn launch_wrangler(arguments: Vec<std::ffi::OsString>) -> i32 {
    let Some(real) = std::env::var_os(REAL_WRANGLER) else {
        eprintln!("[supercov] {WRANGLER_COMMAND} runs only as the wrangler of a measured test");
        return 127;
    };
    let mut arguments = arguments;
    let evidence = std::env::var_os("SUPERCOV_RUST_EVIDENCE_DIR").map(PathBuf::from);
    if starts_dev(&arguments)
        && let Some(evidence) = evidence
    {
        let port = match named_inspector_port(&arguments) {
            Some(port) => Some(port),
            None => free_port().ok().inspect(|port| {
                arguments.push("--inspector-port".into());
                arguments.push(port.to_string().into());
            }),
        };
        if let (Some(port), Ok(supercov)) = (port, std::env::current_exe()) {
            let windows = evidence.join(format!("worker-{}.windows", std::process::id()));
            let _ = std::process::Command::new(supercov)
                .arg(WRANGLER_POLL_COMMAND)
                .arg(std::process::id().to_string())
                .arg(port.to_string())
                .arg(&windows)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn();
        }
    }
    let mut rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
    if !rustflags.is_empty() {
        rustflags.push(' ');
    }
    rustflags.push_str("--cap-lints=warn -A unused_parens");
    let mut command = std::process::Command::new(&real);
    command.args(&arguments).env("RUSTFLAGS", rustflags);
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        let error = command.exec();
        eprintln!(
            "[supercov] could not start {}: {error}",
            Path::new(&real).display()
        );
        126
    }
    #[cfg(not(unix))]
    {
        match command.status() {
            Ok(status) => status.code().unwrap_or(1),
            Err(error) => {
                eprintln!(
                    "[supercov] could not start {}: {error}",
                    Path::new(&real).display()
                );
                126
            }
        }
    }
}

/// The poller of one `wrangler dev` a test started: takes through `port`
/// while process `pid` -- that wrangler -- lives, appending to a `.part`
/// file it renames to `windows` when done, so the run knows it is whole.
pub fn poll_wrangler(arguments: Vec<std::ffi::OsString>) -> i32 {
    let [pid, port, windows] = arguments.as_slice() else {
        return 2;
    };
    let (Ok(pid), Ok(port)) = (
        pid.to_string_lossy().parse::<u32>(),
        port.to_string_lossy().parse::<u16>(),
    ) else {
        return 2;
    };
    let windows = PathBuf::from(windows);
    let part = partial(&windows);
    let poller = Poller::start(port, part.clone());
    while process_alive(pid) {
        std::thread::sleep(Duration::from_millis(20));
    }
    poller.finish();
    if fs::symlink_metadata(&part).is_ok() {
        let _ = fs::rename(&part, &windows);
    }
    0
}

fn partial(windows: &Path) -> PathBuf {
    let mut name = windows.as_os_str().to_owned();
    name.push(".part");
    PathBuf::from(name)
}

#[cfg(unix)]
fn process_alive(pid: u32) -> bool {
    let Ok(pid) = libc::pid_t::try_from(pid) else {
        return false;
    };
    // SAFETY: signal 0 only asks whether the process exists.
    let answered = unsafe { libc::kill(pid, 0) };
    answered == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

#[cfg(not(unix))]
fn process_alive(_pid: u32) -> bool {
    false
}

/// How long the run waits for a poller to finish after its test: the poller
/// notices wrangler is gone within a few polls.
const POLLER_SETTLE: Duration = Duration::from_secs(3);

/// The Worker takes in a test's evidence directory, written out as region
/// files the run reads as it reads a native process's; and the crates they
/// came from, which `wrangler dev` built though the run's own build did not.
/// A take whose region names another instrumentation is not this run's.
pub fn materialize_worker_windows(
    directory: &Path,
    token: &str,
) -> Result<std::collections::BTreeSet<String>, String> {
    let listed = |extension: &str| -> Vec<PathBuf> {
        let mut files = fs::read_dir(directory)
            .map(|entries| {
                entries
                    .filter_map(Result::ok)
                    .map(|entry| entry.path())
                    .filter(|path| {
                        path.file_name()
                            .and_then(|name| name.to_str())
                            .is_some_and(|name| {
                                name.starts_with("worker-") && name.ends_with(extension)
                            })
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        files.sort();
        files
    };
    let started = Instant::now();
    while !listed(".windows.part").is_empty() && started.elapsed() < POLLER_SETTLE {
        std::thread::sleep(Duration::from_millis(20));
    }
    // A poller still writing (its wrangler outlived the test) has given what
    // it has so far: every line it wrote is whole.
    let files = listed(".windows")
        .into_iter()
        .chain(listed(".windows.part"))
        .collect::<Vec<_>>();
    let mut crates = std::collections::BTreeSet::new();
    for (number, file) in files.iter().enumerate() {
        let text =
            fs::read_to_string(file).map_err(|error| format!("{}: {error}", file.display()))?;
        for (line, value) in text
            .lines()
            .filter_map(|line| serde_json::from_str::<Value>(line).ok())
            .enumerate()
        {
            let Some(window) = window_from(&value) else {
                continue;
            };
            for (index, (crate_key, bytes)) in window.regions.into_iter().enumerate() {
                if region_token(&bytes) != Some(token) {
                    continue;
                }
                let region = directory.join(format!(
                    "{token}-worker-{number:04}-{line:06}-{index}.region"
                ));
                fs::write(&region, &bytes)
                    .map_err(|error| format!("{}: {error}", region.display()))?;
                crates.insert(crate_key);
            }
        }
        fs::remove_file(file).map_err(|error| format!("{}: {error}", file.display()))?;
    }
    Ok(crates)
}

/// The instrumentation token a region's header carries.
fn region_token(bytes: &[u8]) -> Option<&str> {
    let field = bytes.get(56..72)?;
    let end = field
        .iter()
        .position(|byte| *byte == 0)
        .unwrap_or(field.len());
    std::str::from_utf8(&field[..end]).ok()
}

/// The root of the Cargo workspace `directory`'s crate belongs to.
pub(crate) fn cargo_workspace_root(directory: &Path) -> Option<PathBuf> {
    let output = std::process::Command::new("cargo")
        .args(["locate-project", "--workspace", "--message-format", "plain"])
        .current_dir(directory)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let manifest = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
    manifest.parent().map(Path::to_path_buf)
}

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

    #[test]
    fn jsonc_comments_and_trailing_commas_are_dropped_and_strings_kept() {
        let text = r#"{
  // the Worker
  "name": "a // not a comment",
  /* block */ "main": "build/worker/shim.mjs",
  "build": { "command": "worker-build --release", },
  "list": [1, 2, ],
  "quote": "say \"hi\", ]"
}"#;
        let value: Value = serde_json::from_str(&strip_jsonc(text)).unwrap();
        assert_eq!(value["name"], "a // not a comment");
        assert_eq!(value["main"], "build/worker/shim.mjs");
        assert_eq!(value["build"]["command"], "worker-build --release");
        assert_eq!(value["list"], json!([1, 2]));
        assert_eq!(value["quote"], "say \"hi\", ]");
    }

    #[test]
    fn the_stand_in_reads_dev_and_an_inspector_port_wherever_they_stand() {
        let os = |arguments: &[&str]| {
            arguments
                .iter()
                .map(std::ffi::OsString::from)
                .collect::<Vec<_>>()
        };
        assert!(starts_dev(&os(&["dev", "--local"])));
        assert!(starts_dev(&os(&["--cwd", "worker", "dev"])));
        assert!(starts_dev(&os(&[
            "-c",
            "wrangler.toml",
            "--env=staging",
            "dev"
        ])));
        assert!(starts_dev(&os(&["--local", "dev"])));
        assert!(!starts_dev(&os(&["deploy"])));
        assert!(!starts_dev(&os(&[])));
        assert_eq!(
            named_inspector_port(&os(&["dev", "--inspector-port", "9230"])),
            Some(9230)
        );
        assert_eq!(
            named_inspector_port(&os(&["dev", "--inspector-port=9231"])),
            Some(9231)
        );
        assert_eq!(named_inspector_port(&os(&["dev", "--port", "8787"])), None);
        assert_eq!(
            named_inspector_port(&os(&["dev", "--inspector-port"])),
            None
        );
    }

    /// A take becomes a region file of the test's own evidence, named by the
    /// run's token, and says which crate it came from; a take of another
    /// instrumentation, or a line cut short, is left out.
    #[test]
    fn a_take_becomes_a_region_file_of_the_test_that_started_the_worker() {
        let directory = temporary("materialize");
        let region = |token: &str| {
            let mut bytes = vec![0_u8; 4096 + 256];
            bytes[56..56 + token.len()].copy_from_slice(token.as_bytes());
            bytes[200] = 7;
            bytes
        };
        let segment =
            |bytes: &[u8]| json!([0, base64::engine::general_purpose::STANDARD.encode(bytes)]);
        let ours = region("abc123");
        let theirs = region("fff999");
        let line = json!({
            "start": 1,
            "end": 2,
            "regions": [
                ["abc123k1", ours.len(), [segment(&ours)]],
                ["fff999k2", theirs.len(), [segment(&theirs)]],
            ],
        });
        fs::write(
            directory.join("worker-41.windows"),
            format!("{line}\n{{\"start\": 3, \"end\""),
        )
        .unwrap();
        let crates = materialize_worker_windows(&directory, "abc123").unwrap();
        assert_eq!(
            crates,
            std::collections::BTreeSet::from(["abc123k1".to_owned()])
        );
        let mut names = fs::read_dir(&directory)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .collect::<Vec<_>>();
        names.sort();
        assert_eq!(names, ["abc123-worker-0000-000000-0.region"]);
        assert_eq!(fs::read(directory.join(&names[0])).unwrap(), ours);
        // Read once: a second pass finds nothing new.
        assert!(
            materialize_worker_windows(&directory, "abc123")
                .unwrap()
                .is_empty()
        );
        assert_eq!(region_token(&ours), Some("abc123"));
        assert_eq!(region_token(&[0_u8; 10]), None);
        fs::remove_dir_all(&directory).unwrap();
    }

    /// A workspace with a Worker and a `wrangler` on PATH gets the stand-in,
    /// and its configuration points at Supercov's entry once: a copy kept
    /// from an earlier run is not pointed at itself. Without a `wrangler`,
    /// nothing is put first on PATH.
    #[cfg(unix)]
    #[test]
    fn the_stand_in_is_put_first_only_where_a_wrangler_is_installed() {
        let workspace = temporary("stand-in");
        fs::create_dir_all(workspace.join("worker/src")).unwrap();
        fs::write(
            workspace.join("worker/Cargo.toml"),
            "[package]\nname = \"w\"\n",
        )
        .unwrap();
        fs::write(workspace.join("worker/src/lib.rs"), "").unwrap();
        fs::write(
            workspace.join("worker/wrangler.toml"),
            "name = \"w\"\nmain = \"build/worker/shim.mjs\"\n\n[build]\ncommand = \"worker-build --release\"\n",
        )
        .unwrap();
        let bin = workspace.join("bin");
        fs::create_dir_all(&bin).unwrap();
        let real = bin.join("wrangler");
        fs::write(&real, "#!/bin/sh\n").unwrap();
        let found = on_path(bin.as_os_str(), "wrangler");
        assert_eq!(found.as_deref(), Some(real.as_path()));
        assert_eq!(on_path(std::ffi::OsStr::new(""), "wrangler"), None);
        let tools = workspace.join("tools");
        let config = parse_config(&workspace.join("worker/wrangler.toml")).unwrap();
        point_at_entry(&config, None).unwrap();
        let pointed = fs::read_to_string(workspace.join("worker/wrangler.toml")).unwrap();
        assert!(
            pointed.contains(&format!("main = \"{ENTRY_FILE}\"")),
            "{pointed}"
        );
        assert!(!pointed.contains("inspector_port"), "{pointed}");
        let entry = fs::read_to_string(workspace.join("worker").join(ENTRY_FILE)).unwrap();
        // Again, as on a kept copy: the entry still names the project's.
        point_at_entry(
            &parse_config(&workspace.join("worker/wrangler.toml")).unwrap(),
            None,
        )
        .unwrap();
        assert_eq!(
            fs::read_to_string(workspace.join("worker").join(ENTRY_FILE)).unwrap(),
            entry
        );
        assert!(entry.contains("./build/worker/shim.mjs"), "{entry}");
        fs::create_dir_all(&tools).unwrap();
        write_stand_in(&tools, Path::new("/opt/it's/supercov")).unwrap();
        let script = fs::read_to_string(tools.join("wrangler")).unwrap();
        assert_eq!(
            script,
            format!("#!/bin/sh\nexec '/opt/it'\\''s/supercov' {WRANGLER_COMMAND} \"$@\"\n")
        );
        fs::remove_dir_all(&workspace).unwrap();
    }

    fn temporary(name: &str) -> PathBuf {
        let path = std::env::temp_dir().join(format!(
            "supercov-rust-worker-{}-{}-{name}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        fs::create_dir_all(&path).unwrap();
        path
    }

    #[test]
    fn only_a_configuration_that_builds_with_worker_build_beside_a_crate_is_a_rust_worker() {
        let root = temporary("configs");
        let write = |relative: &str, text: &str| {
            let path = root.join(relative);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(path, text).unwrap();
        };
        write(
            "worker/wrangler.toml",
            "main = \"build/worker/shim.mjs\"\n[build]\ncommand = \"cargo install -q worker-build && worker-build --release\"\n",
        );
        write("worker/Cargo.toml", "[package]\nname = \"w\"\n");
        // JavaScript Workers and a Rust one without its crate are not.
        write("js/wrangler.toml", "main = \"src/index.js\"\n");
        write(
            "orphan/wrangler.jsonc",
            "{ \"main\": \"x.mjs\", // c\n \"build\": { \"command\": \"worker-build\" } }",
        );
        write(
            "json/wrangler.jsonc",
            "{ \"main\": \"build/worker/shim.mjs\", /* c */ \"build\": { \"command\": \"worker-build --dev\", }, }",
        );
        write("json/Cargo.toml", "[package]\nname = \"j\"\n");
        write(
            "node_modules/dep/wrangler.toml",
            "main = \"m\"\n[build]\ncommand = \"worker-build\"\n",
        );
        write("node_modules/dep/Cargo.toml", "");
        let found = worker_configs(&root)
            .into_iter()
            .map(|path| path.strip_prefix(&root).unwrap().to_owned())
            .collect::<Vec<_>>();
        assert_eq!(
            found,
            [
                PathBuf::from("json/wrangler.jsonc"),
                PathBuf::from("worker/wrangler.toml")
            ]
        );
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn the_copy_points_at_the_entry_and_an_inspector_port_and_keeps_the_rest() {
        let root = temporary("rewrite");
        let toml_path = root.join("wrangler.toml");
        fs::write(
            &toml_path,
            "# the Worker\nname = \"grades\"\nmain = \"build/worker/shim.mjs\"\n\n[build]\ncommand = \"worker-build --release\"\n",
        )
        .unwrap();
        let config = parse_config(&toml_path).unwrap();
        rewrite_config(&config, ENTRY_FILE, Some(9444)).unwrap();
        let rewritten = fs::read_to_string(&toml_path).unwrap();
        assert!(rewritten.contains("# the Worker"), "{rewritten}");
        let (_, document) = read_config(&toml_path).unwrap();
        assert_eq!(document["main"], ENTRY_FILE);
        assert_eq!(document["dev"]["inspector_port"], 9444);
        assert_eq!(document["build"]["command"], "worker-build --release");

        // A port the author chose is theirs, and the poller uses it.
        let json_path = root.join("wrangler.jsonc");
        fs::write(
            &json_path,
            "{\n  // mine\n  \"main\": \"./build/worker/shim.mjs\",\n  \"dev\": { \"inspector_port\": 9555 },\n}\n",
        )
        .unwrap();
        let config = parse_config(&json_path).unwrap();
        assert_eq!(config.inspector_port, Some(9555));
        assert_eq!(config.main, "./build/worker/shim.mjs");
        rewrite_config(&config, ENTRY_FILE, Some(1)).unwrap();
        let (_, document) = read_config(&json_path).unwrap();
        assert_eq!(document["main"], ENTRY_FILE);
        assert_eq!(document["dev"]["inspector_port"], 9555);
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn a_window_is_rebuilt_from_its_header_and_touched_pages() {
        let encode = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
        let value = json!({
            "start": 10,
            "end": 15,
            "regions": [["abc", 8192, [[0, encode(&[1, 2, 3])], [4096, encode(&[9; 4])]]]],
        });
        let window = window_from(&value).unwrap();
        assert_eq!((window.start, window.end), (10, 15));
        let (crate_key, bytes) = &window.regions[0];
        assert_eq!(crate_key, "abc");
        assert_eq!(bytes.len(), 8192);
        assert_eq!(&bytes[..4], &[1, 2, 3, 0]);
        assert_eq!(&bytes[4096..4101], &[9, 9, 9, 9, 0]);
        // A segment past the region is a malformed window, not a panic.
        let bad = json!({"start": 0, "end": 1, "regions": [["a", 4, [[2, encode(&[1, 2, 3])]]]]});
        assert!(window_from(&bad).is_none());
    }
}