submilli-engine 0.3.0

Compiles Submilli programs, a TypeScript subset, to WebAssembly and runs them under capability policy
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
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
use super::{GitConfig, Job, storage, worker};
use crate::runtime::{StoreData, Vfs};
use cap_std::fs::Dir;
use serde_json::json;
use std::path::Path;
use std::sync::{Arc, Mutex, atomic::AtomicBool, atomic::AtomicU64};

fn native(repo: &Path, args: &[&str]) -> Vec<u8> {
    let output = std::process::Command::new("git")
        .arg("-C")
        .arg(repo)
        // Fixtures must stay unchanged after Git exits: background maintenance
        // can remove loose objects or leave temporary files during a scan.
        .args(["-c", "maintenance.auto=false", "-c", "gc.auto=0"])
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .args(args)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    output.stdout
}

fn repository() -> tempfile::TempDir {
    let root = tempfile::tempdir().unwrap();
    native(root.path(), &["init", "-b", "main"]);
    native(root.path(), &["config", "user.name", "Native"]);
    native(root.path(), &["config", "user.email", "native@example.com"]);
    std::fs::write(root.path().join("base"), "base").unwrap();
    native(root.path(), &["add", "."]);
    native(root.path(), &["commit", "-m", "base"]);
    root
}

/// The repository at `root`, opened to write.
fn snapshot(root: &Path) -> storage::Snapshot {
    storage::Snapshot::open_unmetered(
        &super::location::Location::at(root),
        Arc::new(AtomicBool::new(false)),
        storage::MAX_WORKING_BYTES,
        true,
    )
    .unwrap()
}

#[cfg(unix)]
#[test]
fn metadata_publication_preserves_native_hook_execution() {
    use std::os::unix::fs::PermissionsExt;
    let root = repository();
    let hook = root.path().join(".git/hooks/pre-commit");
    std::fs::write(&hook, "#!/bin/sh\nprintf ran > hook-ran\n").unwrap();
    std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
    let mut state = snapshot(root.path());
    super::operations::set_remote(&mut state, "origin", "https://example.com/repo.git", true)
        .unwrap();
    state.publish().unwrap();
    assert_ne!(
        std::fs::metadata(&hook).unwrap().permissions().mode() & 0o111,
        0
    );
    native(
        root.path(),
        &["commit", "--allow-empty", "-m", "native hook"],
    );
    assert_eq!(std::fs::read(root.path().join("hook-ran")).unwrap(), b"ran");
}

#[cfg(unix)]
#[test]
fn failed_metadata_staging_does_not_leave_a_recovery_blocker() {
    let root = repository();
    let head = native(root.path(), &["rev-parse", "HEAD"]);
    let state = snapshot(root.path());
    // A reference staged where the repository has a directory: publication
    // refuses it before moving anything.
    std::fs::write(state.repo.refs.git_dir().join("refs/heads/blocked"), "x").unwrap();
    std::fs::create_dir(root.path().join(".git/refs/heads/blocked")).unwrap();
    assert!(state.publish().is_err());
    assert_eq!(native(root.path(), &["rev-parse", "HEAD"]), head);
    assert!(std::fs::read_dir(root.path()).unwrap().all(|entry| {
        !entry
            .unwrap()
            .file_name()
            .to_string_lossy()
            .starts_with(".git-submilli-")
    }));
    snapshot(root.path()).publish().unwrap();
}

fn job(vfs: &Vfs, op: &str) -> Job {
    let data = StoreData::with_vfs(vfs.clone());
    Job {
        op: op.into(),
        path: "/".into(),
        caller: "main".into(),
        config: GitConfig {
            name: "Agent".into(),
            email: "agent@example.com".into(),
            username: None,
        },
        security: data.security_check.clone(),
        secrets: data.secret_provider.clone(),
        http: data.http_client.clone(),
        runtime: tokio::runtime::Handle::current(),
        deadline: tokio::time::Instant::now() + std::time::Duration::from_secs(60),
        cancelled: Arc::new(AtomicBool::new(false)),
        max_bytes: storage::MAX_WORKING_BYTES,
        transferred: Arc::new(AtomicU64::new(0)),
        meter: Default::default(),
        algorithm_fuel: Arc::new(super::work::AlgorithmWork::new(u64::MAX)),
        denial: Arc::new(Mutex::new(None)),
        history_cache: (op == "log")
            .then(|| Arc::new(super::log_cache::Cache::new(&data.tenant_limits).unwrap())),
        line: None,
    }
}

#[tokio::test]
async fn native_merge_in_progress_refuses_mutations_without_changing_history() {
    let root = repository();
    native(root.path(), &["checkout", "-b", "topic"]);
    std::fs::write(root.path().join("topic"), "topic").unwrap();
    native(root.path(), &["add", "."]);
    native(root.path(), &["commit", "-m", "topic"]);
    native(root.path(), &["checkout", "main"]);
    native(root.path(), &["merge", "--no-commit", "--no-ff", "topic"]);
    let before = storage::read_files(
        &Dir::open_ambient_dir(root.path(), cap_std::ambient_authority()).unwrap(),
        false,
        &AtomicBool::new(false),
        storage::MAX_WORKING_BYTES,
    )
    .unwrap();
    let vfs = Vfs::external(root.path().to_owned()).unwrap();
    for (op, args) in [
        ("commit", vec![json!("incorrect merge")]),
        ("add", vec![json!(["."])]),
    ] {
        let result = worker::run(&vfs, &job(&vfs, op), op, &args);
        assert!(
            result
                .err()
                .unwrap()
                .to_string()
                .contains("in-progress native Git")
        );
    }
    let after = storage::read_files(
        &Dir::open_ambient_dir(root.path(), cap_std::ambient_authority()).unwrap(),
        false,
        &AtomicBool::new(false),
        storage::MAX_WORKING_BYTES,
    )
    .unwrap();
    assert_eq!(before, after);
}

#[tokio::test]
async fn empty_native_state_directories_also_prevent_mutations() {
    let root = repository();
    let vfs = Vfs::external(root.path().to_owned()).unwrap();
    for marker in ["rebase-apply", "rebase-merge", "sequencer"] {
        let path = root.path().join(".git").join(marker);
        std::fs::create_dir(&path).unwrap();
        let result = worker::run(
            &vfs,
            &job(&vfs, "createBranch"),
            "createBranch",
            &[json!("topic"), json!("HEAD")],
        );
        assert!(
            result
                .err()
                .unwrap()
                .to_string()
                .contains("in-progress native Git")
        );
        std::fs::remove_dir(path).unwrap();
    }
}

struct RemotePrefix;

impl crate::runtime::SecurityCheck for RemotePrefix {
    fn check(
        &self,
        _: &str,
        capability: &str,
        context: &serde_json::Value,
    ) -> crate::runtime::security::CheckOutcome {
        use crate::runtime::security::CheckOutcome;
        if matches!(capability, "git.clone" | "git.fetch")
            && !context["remote"]
                .as_str()
                .is_some_and(|url| url.starts_with("https://example.com/allowed/"))
        {
            return CheckOutcome::Deny {
                rule: None,
                reason: "remote outside allowed prefix".into(),
            };
        }
        CheckOutcome::Allow { rule: None }
    }
}

#[tokio::test]
async fn remote_grants_check_canonical_paths_before_creation_or_network() {
    let root = repository();
    let vfs = Vfs::external(root.path().to_owned()).unwrap();
    for (index, url) in [
        "https://example.com/allowed/../private",
        "https://example.com/allowed/%2e%2e/private",
    ]
    .into_iter()
    .enumerate()
    {
        let configure = if index == 0 {
            "addRemote"
        } else {
            "setRemoteUrl"
        };
        let mut request = job(&vfs, configure);
        request.security = Arc::new(RemotePrefix);
        // Configuring a URL does not authorize contacting it.
        worker::run(&vfs, &request, configure, &[json!("origin"), json!(url)]).unwrap();
        for op in ["fetch", "clone"] {
            let mut request = job(&vfs, op);
            request.security = Arc::new(RemotePrefix);
            let args = if op == "clone" {
                request.path = "/new".into();
                vec![json!(url), json!("/new"), serde_json::Value::Null]
            } else {
                vec![json!("origin"), json!("main")]
            };
            let error = worker::run(&vfs, &request, op, &args).err().unwrap();
            assert!(
                error.to_string().contains("remote outside allowed prefix"),
                "{error}"
            );
        }
    }
    assert!(!root.path().join("new").exists());
    let mut request = job(&vfs, "setRemoteUrl");
    request.security = Arc::new(RemotePrefix);
    worker::run(
        &vfs,
        &request,
        "setRemoteUrl",
        &[
            json!("origin"),
            json!("https://EXAMPLE.com:443/allowed/repo"),
        ],
    )
    .unwrap();
    assert_eq!(
        snapshot(root.path()).remotes().unwrap()["origin"],
        "https://example.com/allowed/repo"
    );
}

#[tokio::test]
async fn commit_rejects_symbolic_branch_alias_and_nonbranch_head() {
    for target in ["refs/heads/allowed", "refs/tags/allowed"] {
        let root = repository();
        let original = native(root.path(), &["rev-parse", "refs/heads/main"]);
        if target.starts_with("refs/heads/") {
            native(root.path(), &["symbolic-ref", target, "refs/heads/main"]);
        } else {
            native(root.path(), &["tag", "allowed"]);
        }
        native(root.path(), &["symbolic-ref", "HEAD", target]);
        std::fs::write(root.path().join("base"), "staged change").unwrap();
        native(root.path(), &["add", "base"]);
        let vfs = Vfs::external(root.path().to_owned()).unwrap();
        let error = worker::run(&vfs, &job(&vfs, "commit"), "commit", &[json!("forbidden")])
            .err()
            .unwrap();
        assert!(
            error
                .to_string()
                .contains(if target.starts_with("refs/heads/") {
                    "symbolic local branch"
                } else {
                    "HEAD must target a local branch"
                })
        );
        assert_eq!(
            native(root.path(), &["rev-parse", "refs/heads/main"]),
            original
        );
        assert_eq!(native(root.path(), &["rev-parse", target]), original);
    }
}

struct OnlyAliasBranch;

impl crate::runtime::SecurityCheck for OnlyAliasBranch {
    fn check(
        &self,
        _: &str,
        capability: &str,
        context: &serde_json::Value,
    ) -> crate::runtime::security::CheckOutcome {
        use crate::runtime::security::CheckOutcome;
        if capability == "git.commit" && context["branch"] != "MAIN" {
            return CheckOutcome::Deny {
                rule: None,
                reason: "only MAIN is authorized".into(),
            };
        }
        CheckOutcome::Allow { rule: None }
    }
}

#[tokio::test]
async fn filesystem_ref_aliases_cannot_bypass_branch_grants() {
    let root = repository();
    let vfs = Vfs::external(root.path().to_owned()).unwrap();
    let state = snapshot(root.path());
    if !state.repo.git_dir().join("refs/heads/MAIN").exists() {
        // Distinct names remain valid on case-sensitive scratch filesystems.
        super::operations::create_branch(&state, "MAIN", "main").unwrap();
        return;
    }
    drop(state);
    let metadata = vfs.dir().unwrap().open_dir(".git").unwrap();
    for operation in ["switchBranch", "commit"] {
        if operation == "commit" {
            std::fs::write(root.path().join(".git/HEAD"), "ref: refs/heads/MAIN\n").unwrap();
            std::fs::write(root.path().join("base"), "staged change").unwrap();
            native(root.path(), &["add", "base"]);
        }
        let before = storage::read_files(
            &metadata,
            false,
            &AtomicBool::new(false),
            storage::MAX_WORKING_BYTES,
        )
        .unwrap();
        let mut request = job(&vfs, operation);
        request.security = Arc::new(OnlyAliasBranch);
        let argument = if operation == "switchBranch" {
            "MAIN"
        } else {
            "forbidden update"
        };
        let error = worker::run(&vfs, &request, operation, &[json!(argument)])
            .err()
            .expect("filesystem alias must not use MAIN's branch grant");
        assert!(error.to_string().contains("reference spelling"), "{error}");
        let after = storage::read_files(
            &metadata,
            false,
            &AtomicBool::new(false),
            storage::MAX_WORKING_BYTES,
        )
        .unwrap();
        assert_eq!(before, after);
    }
}

#[test]
fn branch_listing_follows_native_symbolic_aliases_without_panicking() {
    let root = repository();
    native(
        root.path(),
        &["symbolic-ref", "refs/heads/alias", "refs/heads/main"],
    );
    let state = snapshot(root.path());
    let branches = super::operations::read(&state, "branches", &[]).unwrap();
    assert_eq!(branches.as_array().unwrap().len(), 2);
    assert_eq!(branches[0]["id"], branches[1]["id"]);
    assert!(
        super::operations::checkout(&state, "alias")
            .unwrap_err()
            .to_string()
            .contains("symbolic local branch")
    );
    // One operation holds a repository at a time.
    drop(state);
    native(
        root.path(),
        &["symbolic-ref", "refs/heads/alias", "refs/heads/alias"],
    );
    let state = snapshot(root.path());
    assert!(
        super::operations::read(&state, "branches", &[])
            .unwrap_err()
            .to_string()
            .contains("reference nesting")
    );
}

/// `init` writes the `.git` skeleton before it publishes, so the size limit's count
/// must be taken before either; and a branch name can't make that skeleton large.
#[tokio::test]
async fn init_is_counted_against_the_size_limit_and_bounds_branch_names() {
    let vfs = Vfs::tempdir().unwrap().with_size_limit(1 << 20);
    let quota = vfs.quota().unwrap().clone();
    worker::run(
        &vfs,
        &job(&vfs, "init"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .unwrap();
    assert!(quota.used() > 0, "the new repository counts");
    assert_eq!(quota.used(), vfs.measure_usage().unwrap());

    let long = "a".repeat(300);
    let Err(error) = worker::run(
        &vfs,
        &job(&vfs, "init"),
        "init",
        &[json!({ "branch": long })],
    ) else {
        panic!("a 300-byte branch name was accepted");
    };
    let error = error.to_string();
    assert!(error.contains("at most 250 bytes"), "{error}");
}

/// A 250-byte branch name leaves room for git's `.lock` file within a 255-byte
/// path component, through a commit and a new branch; one byte more is refused.
#[tokio::test]
async fn a_branch_name_of_250_bytes_works_end_to_end() {
    let vfs = Vfs::tempdir().unwrap().with_size_limit(1 << 20);
    let longest = "a".repeat(250);
    worker::run(
        &vfs,
        &job(&vfs, "init"),
        "init",
        &[json!({ "branch": longest })],
    )
    .unwrap();
    std::fs::write(vfs.root().join("notes.txt"), b"notes").unwrap();
    vfs.quota().unwrap().record(5);
    worker::run(&vfs, &job(&vfs, "add"), "add", &[json!(["notes.txt"])]).unwrap();
    worker::run(&vfs, &job(&vfs, "commit"), "commit", &[json!("add notes")]).unwrap();
    worker::run(
        &vfs,
        &job(&vfs, "createBranch"),
        "createBranch",
        &[json!("b".repeat(250)), json!(longest)],
    )
    .unwrap();
    let Err(error) = worker::run(
        &vfs,
        &job(&vfs, "createBranch"),
        "createBranch",
        &[json!("c".repeat(251)), json!(longest)],
    ) else {
        panic!("a 251-byte branch name was accepted");
    };
    let error = error.to_string();
    assert!(error.contains("at most 250 bytes"), "{error}");
}

/// After a commit, the size limit's count matches what the directory holds.
#[tokio::test]
async fn a_commit_is_counted_against_the_size_limit() {
    let vfs = Vfs::tempdir().unwrap().with_size_limit(1 << 20);
    let quota = vfs.quota().unwrap().clone();
    worker::run(
        &vfs,
        &job(&vfs, "init"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .unwrap();
    std::fs::write(vfs.root().join("notes.txt"), vec![b'x'; 5000]).unwrap();
    quota.record(5000);
    worker::run(&vfs, &job(&vfs, "add"), "add", &[json!(["notes.txt"])]).unwrap();
    worker::run(&vfs, &job(&vfs, "commit"), "commit", &[json!("add notes")]).unwrap();
    assert_eq!(quota.used(), vfs.measure_usage().unwrap());
}

/// A VFS that couldn't be measured is treated as full, for git as for every other
/// writer.
#[tokio::test]
async fn git_refuses_to_write_in_an_unmeasured_vfs() {
    let vfs = Vfs::tempdir().unwrap().with_measured_limit(1 << 20, None);
    let Err(error) = worker::run(
        &vfs,
        &job(&vfs, "init"),
        "init",
        &[json!({ "branch": "main" })],
    ) else {
        panic!("init wrote in an unmeasured VFS");
    };
    assert!(
        error
            .downcast_ref::<crate::runtime::host::QuotaExceededError>()
            .is_some(),
        "{error}"
    );
    assert!(
        error.to_string().contains("couldn't be measured"),
        "{error}"
    );
    assert!(!vfs.root().join(".git").exists(), "nothing is left behind");
}

/// A branch switch that replaces a file a handle holds leaves the old copy on
/// disk; the count keeps it until the handle lets go.
#[tokio::test]
async fn a_switch_that_replaces_a_held_file_counts_it_until_released() {
    let vfs = Vfs::tempdir().unwrap().with_size_limit(1 << 20);
    let quota = vfs.quota().unwrap().clone();
    let run = |op: &str, args: &[serde_json::Value]| {
        worker::run(&vfs, &job(&vfs, op), op, args).unwrap();
    };
    let write = |bytes: &[u8]| {
        std::fs::write(vfs.root().join("big.bin"), bytes).unwrap();
        quota.record(bytes.len() as u64);
    };
    run("init", &[json!({ "branch": "main" })]);
    write(&[b'm'; 5000]);
    run("add", &[json!(["big.bin"])]);
    run("commit", &[json!("main")]);
    run("createBranch", &[json!("other"), json!("HEAD")]);
    run("switchBranch", &[json!("other")]);
    quota.release(5000);
    write(&[b'o'; 5000]);
    run("add", &[json!(["big.bin"])]);
    run("commit", &[json!("other")]);
    assert_eq!(quota.used(), vfs.measure_usage().unwrap());

    let held = vfs.dir().unwrap().symlink_metadata("big.bin").unwrap();
    let guard = quota.hold(
        crate::runtime::fs::FileIdentity::of(&held).unwrap(),
        crate::runtime::Holder::Reader,
    );
    run("switchBranch", &[json!("main")]);
    assert_eq!(
        quota.used(),
        vfs.measure_usage().unwrap() + 5000,
        "the replaced copy is still on disk"
    );
    drop(guard);
    assert_eq!(quota.used(), vfs.measure_usage().unwrap());
}

/// Replacing a held file frees nothing until the handle lets go, so a switch
/// over one needs room for both copies.
#[tokio::test]
async fn a_switch_over_a_held_file_needs_room_for_both_copies() {
    let dir = tempfile::tempdir().unwrap();
    let roomy = Vfs::external(dir.path().to_path_buf())
        .unwrap()
        .with_size_limit(1 << 20);
    let quota = roomy.quota().unwrap().clone();
    let run =
        |vfs: &Vfs, op: &str, args: &[serde_json::Value]| worker::run(vfs, &job(vfs, op), op, args);
    let write = |bytes: &[u8]| {
        std::fs::write(dir.path().join("big.bin"), bytes).unwrap();
        quota.record(bytes.len() as u64);
    };
    run(&roomy, "init", &[json!({ "branch": "main" })]).unwrap();
    write(&[b'm'; 5000]);
    run(&roomy, "add", &[json!(["big.bin"])]).unwrap();
    run(&roomy, "commit", &[json!("main")]).unwrap();
    run(&roomy, "createBranch", &[json!("other"), json!("HEAD")]).unwrap();
    run(&roomy, "switchBranch", &[json!("other")]).unwrap();
    quota.release(5000);
    write(&[b'o'; 5000]);
    run(&roomy, "add", &[json!(["big.bin"])]).unwrap();
    run(&roomy, "commit", &[json!("other")]).unwrap();

    let used = roomy.measure_usage().unwrap();
    let tight = Vfs::external(dir.path().to_path_buf())
        .unwrap()
        .with_size_limit(used + 1000);
    let tight_quota = tight.quota().unwrap().clone();
    let held = tight.dir().unwrap().symlink_metadata("big.bin").unwrap();
    let guard = tight_quota.hold(
        crate::runtime::fs::FileIdentity::of(&held).unwrap(),
        crate::runtime::Holder::Reader,
    );
    let Err(error) = run(&tight, "switchBranch", &[json!("main")]) else {
        panic!("a switch over a held file fit without room for its old copy");
    };
    assert!(
        error
            .downcast_ref::<crate::runtime::host::QuotaExceededError>()
            .is_some(),
        "{error}"
    );
    drop(guard);
    run(&tight, "switchBranch", &[json!("main")]).unwrap();
    assert_eq!(tight_quota.used(), tight.measure_usage().unwrap());
}

/// A git change that doesn't grow the files is still refused in a VFS that
/// couldn't be measured: publication can't be counted there.
#[tokio::test]
async fn git_refuses_a_change_that_does_not_grow_an_unmeasured_vfs() {
    let dir = tempfile::tempdir().unwrap();
    let measured = Vfs::external(dir.path().to_path_buf())
        .unwrap()
        .with_size_limit(1 << 20);
    worker::run(
        &measured,
        &job(&measured, "init"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .unwrap();
    let long_url = format!("https://example.com/{}.git", "r".repeat(200));
    worker::run(
        &measured,
        &job(&measured, "addRemote"),
        "addRemote",
        &[json!("origin"), json!(long_url)],
    )
    .unwrap();
    let unmeasured = Vfs::external(dir.path().to_path_buf())
        .unwrap()
        .with_measured_limit(1 << 20, None);
    let Err(error) = worker::run(
        &unmeasured,
        &job(&unmeasured, "setRemoteUrl"),
        "setRemoteUrl",
        &[json!("origin"), json!("https://example.com/r.git")],
    ) else {
        panic!("a git change went through in an unmeasured VFS");
    };
    assert!(
        error
            .downcast_ref::<crate::runtime::host::QuotaExceededError>()
            .is_some(),
        "{error}"
    );
}

fn mounted(vfs: Vfs, volume: &Path, access: crate::runtime::vfs::Access) -> Vfs {
    vfs.with_mount(crate::runtime::vfs::MountSpec {
        guest_path: "/memory".into(),
        host: volume.to_path_buf(),
        volume: "memory".into(),
        access,
        quota: Some(Arc::new(crate::runtime::DiskQuota::new(1 << 20, 0))),
    })
    .unwrap()
}

fn job_at(vfs: &Vfs, op: &str, path: &str) -> Job {
    let mut job = job(vfs, op);
    job.path = path.into();
    job
}

#[tokio::test]
async fn mount_repository_lives_in_the_volume_and_charges_it() {
    let volume = tempfile::tempdir().unwrap();
    let vfs = mounted(
        Vfs::tempdir().unwrap().with_size_limit(1 << 20),
        volume.path(),
        crate::runtime::vfs::Access::ReadWrite,
    );
    let mount_quota = vfs.mounts()[0].quota().unwrap().clone();
    let root_quota = vfs.quota().unwrap().clone();
    worker::run(
        &vfs,
        &job_at(&vfs, "init", "/memory/repo"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .unwrap();
    assert!(volume.path().join("repo/.git/HEAD").is_file());
    assert!(mount_quota.used() > 0, "the volume is charged");
    assert_eq!(root_quota.used(), 0, "the root is not");
}

#[tokio::test]
async fn mount_point_inside_a_repository_is_refused() {
    let volume = tempfile::tempdir().unwrap();
    let vfs = mounted(
        Vfs::tempdir().unwrap(),
        volume.path(),
        crate::runtime::vfs::Access::ReadWrite,
    );
    let error = worker::run(
        &vfs,
        &job_at(&vfs, "init", "/"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .err()
    .unwrap()
    .to_string();
    assert!(
        error.contains("overlaps the mount point /memory"),
        "{error}"
    );
    assert!(!vfs.root().join(".git").exists());
}

#[tokio::test]
async fn root_volume_alias_preserves_guest_mount_placeholders() {
    use crate::runtime::vfs::{Access, MountSpec};
    let root = tempfile::tempdir().unwrap();
    let child = tempfile::tempdir().unwrap();
    let vfs = Vfs::external(root.path().to_path_buf())
        .unwrap()
        .with_volume_name("root")
        .with_mount(MountSpec {
            guest_path: "/alias".into(),
            host: root.path().to_path_buf(),
            volume: "root".into(),
            access: Access::ReadWrite,
            quota: None,
        })
        .unwrap()
        .with_mount(MountSpec {
            guest_path: "/child".into(),
            host: child.path().to_path_buf(),
            volume: "child".into(),
            access: Access::ReadWrite,
            quota: None,
        })
        .unwrap();
    for path in ["/", "/alias", "/alias/child", "/alias/alias"] {
        let error = worker::run(
            &vfs,
            &job_at(&vfs, "init", path),
            "init",
            &[json!({ "branch": "main" })],
        )
        .err()
        .unwrap()
        .to_string();
        assert!(error.contains("mount point"), "{path}: {error}");
    }
    assert!(!root.path().join(".git").exists());
    assert!(root.path().join("child").is_dir());
    worker::run(
        &vfs,
        &job_at(&vfs, "init", "/child"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .unwrap();
}

#[tokio::test]
async fn mount_read_only_refuses_repository_changes_but_not_reads() {
    let volume = tempfile::tempdir().unwrap();
    let writable = mounted(
        Vfs::tempdir().unwrap(),
        volume.path(),
        crate::runtime::vfs::Access::ReadWrite,
    );
    worker::run(
        &writable,
        &job_at(&writable, "init", "/memory"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .unwrap();
    std::fs::write(volume.path().join("note.txt"), "note").unwrap();
    worker::run(
        &writable,
        &job_at(&writable, "add", "/memory"),
        "add",
        &[json!(["note.txt"])],
    )
    .unwrap();
    std::fs::write(volume.path().join("other.txt"), "other").unwrap();
    let before = storage::read_files(
        &Dir::open_ambient_dir(volume.path(), cap_std::ambient_authority()).unwrap(),
        true,
        &AtomicBool::new(false),
        storage::MAX_WORKING_BYTES,
    )
    .unwrap();
    let vfs = mounted(
        Vfs::tempdir().unwrap(),
        volume.path(),
        crate::runtime::vfs::Access::ReadOnly,
    );
    for (op, args) in [
        ("add", vec![json!(["other.txt"])]),
        ("commit", vec![json!("message")]),
    ] {
        let error = worker::run(&vfs, &job_at(&vfs, op, "/memory"), op, &args)
            .err()
            .unwrap();
        let denied = error
            .downcast_ref::<crate::runtime::host::PermissionDenied>()
            .unwrap_or_else(|| panic!("{op}: {error}"));
        assert_eq!(denied.capability, format!("git.{op}"));
    }
    let error = worker::run(
        &vfs,
        &job_at(&vfs, "init", "/memory/nested"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .err()
    .unwrap();
    assert!(
        error
            .downcast_ref::<crate::runtime::host::PermissionDenied>()
            .is_some()
    );
    assert!(!volume.path().join("nested").exists());
    worker::run(&vfs, &job_at(&vfs, "status", "/memory"), "status", &[]).unwrap();
    let after = storage::read_files(
        &Dir::open_ambient_dir(volume.path(), cap_std::ambient_authority()).unwrap(),
        true,
        &AtomicBool::new(false),
        storage::MAX_WORKING_BYTES,
    )
    .unwrap();
    assert_eq!(before, after, "nothing in the volume changed");
}

#[cfg(target_os = "macos")]
#[tokio::test]
async fn mount_non_ascii_alias_cannot_host_a_repository() {
    let volume = tempfile::tempdir().unwrap();
    let vfs = Vfs::tempdir()
        .unwrap()
        .with_mount(crate::runtime::vfs::MountSpec {
            guest_path: "/skills".into(),
            host: volume.path().to_path_buf(),
            volume: "skills".into(),
            access: crate::runtime::vfs::Access::ReadWrite,
            quota: None,
        })
        .unwrap();
    // U+017F (long s) folds to `s` on a case-insensitive APFS volume.
    let error = worker::run(
        &vfs,
        &job_at(&vfs, "init", "/\u{17F}kills"),
        "init",
        &[json!({ "branch": "main" })],
    )
    .err()
    .unwrap()
    .to_string();
    assert!(error.contains("mount point /skills"), "{error}");
    assert_eq!(
        std::fs::read_dir(vfs.root().join("skills"))
            .unwrap()
            .count(),
        0
    );
}

/// A repository whose single file is `bytes` long, packed by native Git.
fn packed_repository(bytes: usize) -> tempfile::TempDir {
    let root = tempfile::tempdir().unwrap();
    native(root.path(), &["init", "-b", "main"]);
    native(root.path(), &["config", "user.name", "Native"]);
    native(root.path(), &["config", "user.email", "native@example.com"]);
    // Varied bytes, so the pack is as large as the file.
    let contents: Vec<u8> = (0..bytes).map(|i| (i * 7919 % 251) as u8).collect();
    std::fs::write(root.path().join("data"), contents).unwrap();
    native(root.path(), &["add", "."]);
    native(root.path(), &["commit", "-m", "data"]);
    native(root.path(), &["gc", "--quiet"]);
    root
}

/// The fuel `op` costs on the repository at `root`, its packs already checked.
fn fuel_of(root: &Path, op: &str, args: &[serde_json::Value]) -> u64 {
    let vfs = Vfs::external(root.to_path_buf()).unwrap();
    worker::run(&vfs, &job(&vfs, "branches"), "branches", &[]).unwrap();
    let job = job(&vfs, op);
    worker::run(&vfs, &job, op, args).unwrap();
    job.meter.fuel()
}

/// Reading and changing a repository costs what the operation touches, not
/// the size of its packs: nothing is copied or re-indexed per call.
#[tokio::test]
async fn fuel_does_not_grow_with_pack_size() {
    let small = packed_repository(1_000);
    let large = packed_repository(4_000_000);
    for (op, args) in [
        ("branches", vec![]),
        ("remotes", vec![]),
        (
            "addRemote",
            vec![json!("origin"), json!("https://example.com/repo.git")],
        ),
    ] {
        let small_fuel = fuel_of(small.path(), op, &args);
        let large_fuel = fuel_of(large.path(), op, &args);
        assert!(
            large_fuel < small_fuel + small_fuel / 2,
            "{op}: {small_fuel} fuel on a small pack, {large_fuel} on a 4 MB one"
        );
    }
}

/// Every file under `root`, `.git` included, with its mode and contents.
fn digest(root: &Path) -> storage::Files {
    let dir = Dir::open_ambient_dir(root, cap_std::ambient_authority()).unwrap();
    storage::read_files(&dir, false, &AtomicBool::new(false), 64 << 20).unwrap()
}

/// A publication that fails after any number of its steps is undone, leaving
/// the repository, worktree and `.git` alike, exactly as it was.
#[test]
fn a_publication_failing_at_any_step_leaves_the_repository_as_it_was() {
    let root = repository();
    for (path, contents) in [("kept", "kept"), ("changed", "before"), ("removed", "gone")] {
        std::fs::write(root.path().join(path), contents).unwrap();
    }
    std::fs::write(root.path().join("swap"), "a file").unwrap();
    native(root.path(), &["add", "."]);
    native(root.path(), &["commit", "-m", "main"]);
    native(root.path(), &["switch", "-c", "topic"]);
    std::fs::write(root.path().join("changed"), "after").unwrap();
    std::fs::remove_file(root.path().join("removed")).unwrap();
    std::fs::remove_file(root.path().join("swap")).unwrap();
    std::fs::create_dir_all(root.path().join("swap/deeper")).unwrap();
    std::fs::write(root.path().join("swap/deeper/inner"), "now a directory").unwrap();
    std::fs::write(root.path().join("added"), "new").unwrap();
    native(root.path(), &["add", "-A"]);
    native(root.path(), &["commit", "-m", "topic"]);
    native(root.path(), &["switch", "main"]);
    let before = digest(root.path());
    let mut published = false;
    for steps in 1..200 {
        let state = snapshot(root.path());
        super::operations::checkout(&state, "topic").unwrap();
        super::stage::FAIL_AFTER.with(|after| after.set(Some(steps)));
        let result = state.publish();
        super::stage::FAIL_AFTER.with(|after| after.set(None));
        if result.is_ok() {
            published = true;
            break;
        }
        assert_eq!(digest(root.path()), before, "after failing at step {steps}");
    }
    assert!(published, "publication finished within 200 steps");
    assert!(native(root.path(), &["status", "--porcelain"]).is_empty());
    assert_eq!(
        native(root.path(), &["symbolic-ref", "HEAD"]),
        b"refs/heads/topic\n"
    );
    assert_eq!(
        std::fs::read(root.path().join("swap/deeper/inner")).unwrap(),
        b"now a directory"
    );
    native(root.path(), &["fsck", "--full"]);

    // And back: the directory gives way to the file again.
    let state = snapshot(root.path());
    super::operations::checkout(&state, "main").unwrap();
    state.publish().unwrap();
    assert_eq!(digest(root.path()).get("swap"), before.get("swap"));
    assert!(native(root.path(), &["status", "--porcelain"]).is_empty());
}

/// Branches whose files differ only in case switch either way, on a
/// filesystem that folds case as on one that doesn't.
#[test]
fn a_switch_renames_a_file_that_differs_only_in_case() {
    let root = repository();
    std::fs::create_dir(root.path().join("Docs")).unwrap();
    std::fs::write(root.path().join("Docs/README"), "upper").unwrap();
    native(root.path(), &["add", "."]);
    native(root.path(), &["commit", "-m", "upper"]);
    native(root.path(), &["switch", "-c", "lower"]);
    native(root.path(), &["mv", "Docs/README", "Docs/readme.tmp"]);
    native(root.path(), &["mv", "Docs/readme.tmp", "Docs/readme"]);
    native(root.path(), &["mv", "Docs", "docs.tmp"]);
    native(root.path(), &["mv", "docs.tmp", "docs"]);
    native(root.path(), &["commit", "-m", "lower"]);
    native(root.path(), &["switch", "main"]);
    for (branch, path) in [("lower", "docs/readme"), ("main", "Docs/README")] {
        let state = snapshot(root.path());
        super::operations::checkout(&state, branch).unwrap();
        state.publish().unwrap();
        assert!(native(root.path(), &["status", "--porcelain"]).is_empty());
        let directory = path.split('/').next().unwrap();
        let names: Vec<_> = std::fs::read_dir(root.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
            .collect();
        assert!(
            names.iter().any(|name| name == directory),
            "{branch}: {names:?}"
        );
    }
}

/// gix rewrites `shallow` during a fetch; with a stage it writes the stage's
/// copy, which publication puts in place, or nothing reaches `.git`.
#[test]
fn shallow_is_staged_and_published() {
    let root = repository();
    let state = snapshot(root.path());
    let shallow = state.repo.shallow_file();
    assert!(
        !shallow.starts_with(root.path().join(".git")),
        "{shallow:?} is in .git"
    );
    let head = native(root.path(), &["rev-parse", "HEAD"]);
    std::fs::write(&shallow, &head).unwrap();
    drop(state);
    assert!(!root.path().join(".git/shallow").exists());
    let state = snapshot(root.path());
    std::fs::write(state.repo.shallow_file(), &head).unwrap();
    state.publish().unwrap();
    assert_eq!(
        std::fs::read(root.path().join(".git/shallow")).unwrap(),
        head
    );
    let state = snapshot(root.path());
    std::fs::remove_file(state.repo.shallow_file()).unwrap();
    state.publish().unwrap();
    assert!(!root.path().join(".git/shallow").exists());
}

/// A stage left before publication began is cleared by the next change, and
/// left alone by a read; one left part way through publication blocks the
/// repository. A file that only looks like a stage is neither.
#[test]
fn a_leftover_stage_is_cleared_unless_publication_began() {
    let root = repository();
    let left = root.path().join(format!(
        "{}{}",
        super::stage::STAGE_PREFIX,
        uuid::Uuid::new_v4()
    ));
    std::fs::create_dir_all(left.join("objects")).unwrap();
    let lookalike = root
        .path()
        .join(format!("{}notes", super::stage::STAGE_PREFIX));
    std::fs::write(&lookalike, "not a stage").unwrap();
    let open = |writes: bool| {
        storage::Snapshot::open_unmetered(
            &super::location::Location::at(root.path()),
            Arc::new(AtomicBool::new(false)),
            storage::MAX_WORKING_BYTES,
            writes,
        )
    };
    drop(open(false).unwrap());
    assert!(left.exists(), "a read leaves a stage alone");
    drop(open(true).unwrap());
    assert!(!left.exists(), "a change clears it");
    assert!(lookalike.exists());

    std::fs::create_dir(&left).unwrap();
    std::fs::write(left.join("publishing"), "").unwrap();
    for writes in [false, true] {
        let error = open(writes).err().unwrap();
        assert!(error.to_string().contains("host recovery"), "{error}");
    }
}

/// A publication that fails and can't be undone keeps what it replaced in its
/// stage, keeps a `.git` it created, and leaves the repository refused until
/// the host recovers it.
#[test]
fn a_publication_that_cannot_be_undone_needs_host_recovery() {
    let root = tempfile::tempdir().unwrap();
    let location = super::location::Location::at(root.path());
    let open = |writes| {
        storage::Snapshot::open_unmetered(
            &location,
            Arc::new(AtomicBool::new(false)),
            storage::MAX_WORKING_BYTES,
            writes,
        )
    };
    let created = storage::Snapshot::init_unmetered(
        &location,
        "main",
        Arc::new(AtomicBool::new(false)),
        storage::MAX_WORKING_BYTES,
    )
    .unwrap();
    created
        .stage_worktree_file("notes.txt", 0o100644, b"notes")
        .unwrap();
    *created.pending_worktree.borrow_mut() = Some(super::stage::WorktreeChange {
        remove: Vec::new(),
        place: vec!["notes.txt".into()],
    });
    super::stage::FAIL_AFTER.with(|after| after.set(Some(1)));
    super::stage::FAIL_UNDO.with(|undo| undo.set(true));
    let result = created.publish();
    super::stage::FAIL_AFTER.with(|after| after.set(None));
    super::stage::FAIL_UNDO.with(|undo| undo.set(false));
    let error = result.unwrap_err();
    assert!(format!("{error:#}").contains("host recovery"), "{error:#}");
    assert!(root.path().join(".git").exists(), "the created .git stays");
    for writes in [false, true] {
        let error = open(writes).err().unwrap();
        assert!(error.to_string().contains("host recovery"), "{error}");
    }
}

/// A repository of `files` small files under `d*/`, committed.
fn wide_repository(files: usize) -> tempfile::TempDir {
    let root = repository();
    for number in 0..files {
        let path = root
            .path()
            .join(format!("d{:02}/f{number:05}", number % 50));
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, format!("file {number}\n")).unwrap();
    }
    native(root.path(), &["add", "."]);
    native(root.path(), &["commit", "-m", "wide"]);
    root
}

/// `job` for `op` at the VFS root, its meter stopping the work past `ceiling` fuel.
fn job_with_ceiling(vfs: &Vfs, op: &str, ceiling: u64) -> Job {
    let mut job = job(vfs, op);
    job.meter = Arc::new(super::meter::Meter::new(
        ceiling,
        Some(Arc::clone(&job.cancelled)),
    ));
    job
}

/// With less fuel than an operation needs, the worker stops itself near the
/// ceiling instead of finishing and being charged after.
#[tokio::test]
async fn the_worker_stops_at_its_fuel_ceiling() {
    let root = wide_repository(2_000);
    let vfs = Vfs::external(root.path().to_path_buf()).unwrap();
    let full = job(&vfs, "status");
    worker::run(&vfs, &full, "status", &[]).unwrap();
    let needed = full.meter.fuel();
    let short = job_with_ceiling(&vfs, "status", needed / 10);
    assert!(worker::run(&vfs, &short, "status", &[]).is_err());
    assert!(short.meter.is_exhausted());
    assert!(
        short.meter.fuel() < needed / 2,
        "stopped at {} of {needed}",
        short.meter.fuel()
    );
}

/// A change stopped for fuel is stopped before it publishes: the repository
/// is as it was.
#[tokio::test]
async fn a_change_stopped_for_fuel_leaves_the_repository_as_it_was() {
    let root = wide_repository(500);
    for number in 0..500 {
        let path = root
            .path()
            .join(format!("d{:02}/f{number:05}", number % 50));
        std::fs::write(path, format!("changed {number}\n")).unwrap();
    }
    let before = digest(root.path());
    // What `add` needs, measured on a copy so the repository stays untouched.
    let probe = tempfile::tempdir().unwrap();
    native(
        probe.path(),
        &[
            "clone",
            "-q",
            "--no-hardlinks",
            root.path().to_str().unwrap(),
            ".",
        ],
    );
    // A local path is no HTTPS remote Git accepts.
    native(probe.path(), &["remote", "remove", "origin"]);
    for number in 0..500 {
        let path = probe
            .path()
            .join(format!("d{:02}/f{number:05}", number % 50));
        std::fs::write(path, format!("changed {number}\n")).unwrap();
    }
    let probe_vfs = Vfs::external(probe.path().to_path_buf()).unwrap();
    let measured = job(&probe_vfs, "add");
    worker::run(&probe_vfs, &measured, "add", &[json!(["."])]).unwrap();
    let vfs = Vfs::external(root.path().to_path_buf()).unwrap();
    let short = job_with_ceiling(&vfs, "add", measured.meter.fuel() / 4);
    assert!(worker::run(&vfs, &short, "add", &[json!(["."])]).is_err());
    assert!(short.meter.is_exhausted());
    assert_eq!(digest(root.path()), before);
}

#[tokio::test]
async fn missing_add_worker_arguments_fail_without_stranding_repository_lock() {
    let vfs = Vfs::tempdir().unwrap();
    super::worker::run(&vfs, &job(&vfs, "init"), "init", &[]).unwrap();
    let error = super::worker::run(&vfs, &job(&vfs, "add"), "add", &[])
        .err()
        .unwrap();
    assert!(error.is::<crate::runtime::host::FatalHostError>());
    assert!(error.to_string().contains("missing decoded paths"));
    assert!(super::worker::run(&vfs, &job(&vfs, "status"), "status", &[]).is_ok());
}

#[test]
fn reference_spelling_lists_each_directory_once() {
    let mut measurements = Vec::new();
    for count in [128, 256] {
        let root = repository();
        let head = String::from_utf8(native(root.path(), &["rev-parse", "HEAD"])).unwrap();
        for index in 0..count {
            std::fs::write(
                root.path()
                    .join(format!(".git/refs/heads/branch{index:04}")),
                &head,
            )
            .unwrap();
        }
        let state = snapshot(root.path());
        for index in 0..count {
            state
                .validate_reference_spelling(&format!("refs/heads/branch{index:04}"))
                .unwrap();
        }
        let actual = state.algorithm_fuel.spent();
        eprintln!("reference spelling {count}: {actual}");
        // The old heads-directory scan alone visited every prefix once.
        let old = crate::runtime::fuel::SYSCALL.cost((count * (count + 1) / 2) as u64);
        measurements.push((actual, old));
    }
    for (actual, old) in measurements {
        assert!(actual < old / 2, "{actual} versus old lower bound {old}");
    }
}

#[test]
fn tree_file_validation_runs_once_per_loaded_set() {
    let mut measurements = Vec::new();
    for count in [128, 256] {
        let root = repository();
        for index in 0..count {
            let directory = root.path().join(format!("dir{index:04}"));
            std::fs::create_dir(&directory).unwrap();
            std::fs::write(directory.join("file"), "x").unwrap();
        }
        native(root.path(), &["add", "."]);
        native(root.path(), &["commit", "-m", "files"]);
        let state = snapshot(root.path());
        let tree = state
            .repo
            .head_commit()
            .unwrap()
            .tree_id()
            .unwrap()
            .detach();
        let files = super::operations::tree_entries(&state, tree).unwrap();
        assert_eq!(files.len(), count + 1);
        measurements.push(state.algorithm_fuel.spent());
    }
    eprintln!("tree validation128/256: {measurements:?}");
    assert!(measurements[1] < measurements[0] * 5 / 2);
}

#[test]
fn show_inflates_only_the_requested_blob() {
    let mut measurements = Vec::new();
    for count in [128, 256] {
        let root = repository();
        for index in 0..count {
            std::fs::write(
                root.path().join(format!("other{index:04}")),
                "x".repeat(count * 128),
            )
            .unwrap();
        }
        native(root.path(), &["add", "."]);
        native(root.path(), &["commit", "-m", "large siblings"]);
        let state = snapshot(root.path());
        assert_eq!(
            super::operations::show(&state, "HEAD", "base").unwrap(),
            b"base"
        );
        measurements.push(state.algorithm_fuel.spent());
    }
    eprintln!("show unrelated128/256: {measurements:?}");
    assert!(measurements[1] < measurements[0] * 5 / 2);
}

#[test]
fn add_selects_requested_ranges_without_scanning_every_path() {
    let mut measurements = Vec::new();
    for count in [128, 256] {
        let root = repository();
        let mut paths = Vec::new();
        for index in 0..count {
            let name = format!("file{index:04}");
            std::fs::write(root.path().join(&name), "x").unwrap();
            paths.push(name);
        }
        native(root.path(), &["add", "."]);
        native(root.path(), &["commit", "-m", "files"]);
        let state = snapshot(root.path());
        super::operations::add(&state, &paths).unwrap();
        measurements.push(state.algorithm_fuel.spent());
        assert_eq!(
            super::operations::index_entries(&state).unwrap().len(),
            count + 1
        );
    }
    eprintln!("add individual128/256: {measurements:?}");
    assert!(measurements[1] < measurements[0] * 5 / 2);
}

#[test]
fn add_ranges_preserve_overlap_missing_children_and_deletions() {
    let root = repository();
    std::fs::create_dir(root.path().join("a")).unwrap();
    std::fs::create_dir(root.path().join("a-")).unwrap();
    std::fs::write(root.path().join("a/removed"), "old").unwrap();
    native(root.path(), &["add", "."]);
    native(root.path(), &["commit", "-m", "tracked child"]);
    std::fs::remove_file(root.path().join("a/removed")).unwrap();
    std::fs::write(root.path().join("a/new"), "new").unwrap();
    std::fs::write(root.path().join("a-/sibling"), "sibling").unwrap();
    let state = snapshot(root.path());
    let before = super::operations::index_entries(&state).unwrap();
    assert!(super::operations::add(&state, &["a".into(), "a/missing".into()]).is_err());
    assert_eq!(super::operations::index_entries(&state).unwrap(), before);
    super::operations::add(
        &state,
        &[
            "a".into(),
            "a-/sibling".into(),
            "a/new".into(),
            "a/removed".into(),
        ],
    )
    .unwrap();
    let files = super::operations::index_entries(&state).unwrap();
    assert_eq!(files.len(), 3);
    assert!(files.contains_key("a/new") && files.contains_key("a-/sibling"));
    assert!(!files.contains_key("a/removed"));
}

#[test]
fn diff_inflates_only_changed_blobs() {
    let mut measurements = Vec::new();
    for count in [128, 256] {
        let root = repository();
        for index in 0..count {
            std::fs::write(
                root.path().join(format!("other{index:04}")),
                "x".repeat(count * 128),
            )
            .unwrap();
        }
        native(root.path(), &["add", "."]);
        native(root.path(), &["commit", "-m", "large siblings"]);
        let from = String::from_utf8(native(root.path(), &["rev-parse", "HEAD"])).unwrap();
        std::fs::write(root.path().join("base"), "changed\n").unwrap();
        native(root.path(), &["add", "."]);
        native(root.path(), &["commit", "-m", "small change"]);
        let state = snapshot(root.path());
        let result = super::operations::read(
            &state,
            "diff",
            &[json!({"mode":"refs","from":from.trim(),"to":"HEAD"})],
        )
        .unwrap();
        assert!(result["patch"].as_str().unwrap().contains("+changed"));
        measurements.push(state.algorithm_fuel.spent());
    }
    eprintln!("diff unrelated128/256: {measurements:?}");
    assert!(measurements[1] < measurements[0] * 5 / 2);
    for (actual, old) in measurements.iter().zip([25_790_448, 102_963_724]) {
        assert!(*actual < old / 2);
    }
}

#[test]
fn selective_diff_preserves_staged_working_and_binary_changes() {
    let root = repository();
    std::fs::write(root.path().join("base"), "staged\n").unwrap();
    std::fs::write(root.path().join("binary"), [0, 1, 2]).unwrap();
    native(root.path(), &["add", "."]);
    let state = snapshot(root.path());
    let staged = super::operations::read(&state, "diff", &[json!({"mode":"staged"})]).unwrap();
    assert!(staged["patch"].as_str().unwrap().contains("+staged"));
    assert_eq!(staged["binaryPaths"], json!(["binary"]));
    drop(state);
    std::fs::write(root.path().join("base"), "working\n").unwrap();
    std::fs::write(root.path().join("untracked"), "not in diff\n").unwrap();
    let state = snapshot(root.path());
    let working = super::operations::read(&state, "diff", &[json!({"mode":"working"})]).unwrap();
    let patch = working["patch"].as_str().unwrap();
    assert!(patch.contains("-staged") && patch.contains("+working"));
    assert!(!patch.contains("untracked"));
}

#[test]
fn diff_uses_bounded_sanitized_native_index_and_recovers() {
    let root = repository();
    let mut state = snapshot(root.path());
    let path = root.path().join(".git/index");
    let healthy = std::fs::read(&path).unwrap();
    let payload = [b"a\0-1 1\n".repeat(1000), b"a\0-1 0\n".to_vec()].concat();
    let mut bytes = [b"DIRC".as_slice(), &2u32.to_be_bytes(), &0u32.to_be_bytes()].concat();
    bytes.extend_from_slice(b"TREE");
    bytes.extend_from_slice(&u32::try_from(payload.len()).unwrap().to_be_bytes());
    bytes.extend_from_slice(&payload);
    let mut hasher = gix::hash::hasher(gix::hash::Kind::Sha1);
    hasher.update(&bytes);
    bytes.extend_from_slice(hasher.try_finalize().unwrap().as_slice());
    std::fs::write(&path, &bytes).unwrap();
    for mode in ["working", "staged"] {
        super::operations::read(&state, "diff", &[json!({"mode":mode})]).unwrap();
    }
    let original_limit = state.max_bytes;
    state.max_bytes = 128;
    for mode in ["working", "staged"] {
        assert!(super::operations::read(&state, "diff", &[json!({"mode":mode})]).is_err());
    }
    state.max_bytes = original_limit;
    std::fs::write(&path, healthy).unwrap();
    for mode in ["working", "staged"] {
        let result = super::operations::read(&state, "diff", &[json!({"mode":mode})]).unwrap();
        assert_eq!(result["patch"], "");
    }
}