rsconstruct 0.9.183

Rust based fast build system
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
//! `rsconstruct.lock`: the exact versions of the external tools a project
//! builds with, the way `Cargo.lock` and `uv.lock` record its libraries.
//!
//! `rsconstruct.toml` names tools by bare name — a processor's tools, the
//! `[dependencies]` lists — and a bare name alone would let every CI runner
//! install whatever release was newest that day. This file records which
//! release the project builds with. It is written by `rsconstruct tool
//! lock`, read by `tool install` and `tool check`, and
//! checked by `build` in CI (for the processors that build; see
//! [`Coverage`]). rsconstruct itself is not locked: the fleet's
//! `scripts/ci-install-tools.sh` downloads the latest release (only the last
//! few releases stay published, so a pinned one would vanish from under CI,
//! and every release would have meant a fleet-wide lock bump). Locks written
//! before 2026-10-26 carry an `[rsconstruct]` table; it is accepted so they
//! keep parsing, ignored, and left out of the next rewrite.
//!
//! What is locked is what rsconstruct itself installs from a registry:
//! crates (`cargo`), npm packages, gems, and the release assets of the
//! `binary` install method (by URL and SHA-256). Packages a project
//! lockfile already pins (uv.lock, package-lock.json) belong to that file:
//! a project's Python packages, the Python tools its processors run
//! included, are all pinned by uv.lock, so this file never pins one.
//! System packages (apt and friends) come with the OS image and are not
//! locked.
//!
//! Outside CI a missing or incomplete lock is filled in (only the missing
//! entries are resolved; nothing already locked moves). In CI (`CI=true`)
//! it is an error: a lock written on a runner is never committed, so each
//! runner would resolve its own versions. Moving locked entries to newer
//! releases is `rsconstruct tool lock --upgrade` and nothing else.
//!
//! Crates, npm packages, gems and non-`.deb` binaries are installed into
//! the project itself (see `tool_store`), so each project runs exactly its
//! locked versions, in CI and on a developer machine alike. `.deb` binaries
//! go onto the machine.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::Path;

use crate::build_context::BuildContext;
use crate::processor::ProcessorMap;

pub const LOCK_FILE: &str = "rsconstruct.lock";
/// The file `rsconstruct tool lock` wrote before rsconstruct.lock existed.
/// It recorded machine-local tool paths, so it cannot be converted; finding
/// one is an error that says to delete it.
pub const LEGACY_LOCK_FILE: &str = ".tools.versions";
const LOCK_VERSION: u32 = 1;

const LOCK_HEADER: &str = "\
# rsconstruct.lock: the exact tool versions this project builds with.
# Written by `rsconstruct tool lock`; move to newer releases with
# `rsconstruct tool lock --upgrade`. Commit this file; do not edit it by hand.
";

/// The registry-backed install methods whose versions the lock records,
/// besides `binary`.
const VERSIONED_METHODS: [&str; 3] = ["cargo", "gem", "npm"];

/// The parsed contents of rsconstruct.lock.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ToolLock {
    pub version: u32,
    /// The `[rsconstruct]` table of a lock written before 2026-10-26, when
    /// `tool lock` recorded the release it ran as for CI to download. Read
    /// so a committed lock keeps parsing under `deny_unknown_fields`, never
    /// consulted, and never written: a rewrite drops it (see
    /// [`describe_changes`]).
    #[serde(default, skip_serializing)]
    pub rsconstruct: Option<LegacySelfPin>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub cargo: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub gem: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub npm: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub binary: BTreeMap<String, BinaryPin>,
}

/// The body of the legacy `[rsconstruct]` table: the release `tool lock` ran
/// as. Only ever parsed, see [`ToolLock::rsconstruct`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LegacySelfPin {
    pub version: String,
}

/// One `binary` recipe, pinned: the exact asset to download, the hash it
/// must have, and how to recognize the installed result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BinaryPin {
    pub url: String,
    /// SHA-256 of the downloaded file (the archive, for an archive).
    pub sha256: String,
    /// SHA-256 of the installed executable, for every recipe but a `.deb`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub executable_sha256: Option<String>,
    /// A `.deb`'s package name and version, as dpkg will report them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deb_package: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deb_version: Option<String>,
}

impl ToolLock {
    fn empty() -> Self {
        Self {
            version: LOCK_VERSION,
            ..Self::default()
        }
    }

    fn versions(&self, method: &str) -> &BTreeMap<String, String> {
        match method {
            "cargo" => &self.cargo,
            "gem" => &self.gem,
            "npm" => &self.npm,
            other => unreachable!("not a versioned lock method: {other}"),
        }
    }

    fn versions_mut(&mut self, method: &str) -> &mut BTreeMap<String, String> {
        match method {
            "cargo" => &mut self.cargo,
            "gem" => &mut self.gem,
            "npm" => &mut self.npm,
            other => unreachable!("not a versioned lock method: {other}"),
        }
    }

    /// The locked version of `name` under the versioned `method`.
    pub fn version(&self, method: &str, name: &str) -> Option<&String> {
        self.versions(method).get(name)
    }

    /// `package` as an install request for `method`, pinned to its locked
    /// version: `name@1.2.3` for cargo and npm, `name:1.2.3` for gem.
    /// Returned unchanged for a method the lock does not version, when the
    /// lock has no entry for it, or when the entry already carries its own
    /// version constraint, which then stands as written.
    pub fn pinned(&self, method: &str, package: &str) -> String {
        if !VERSIONED_METHODS.contains(&method) || !is_bare(method, package) {
            return package.to_string();
        }
        let Some(version) = self.versions(method).get(package) else {
            return package.to_string();
        };
        match method {
            "gem" => format!("{package}:{version}"),
            _ => format!("{package}@{version}"),
        }
    }
}

/// Whether `package` is a bare name the lock can pin, rather than a request
/// that already says which version it wants (`pkg@1.0`, `rake:13.0`).
fn is_bare(method: &str, package: &str) -> bool {
    match method {
        // A scoped package starts with '@'; only a later '@' is a version.
        "npm" => package.rfind('@').is_none_or(|i| i == 0),
        "gem" => !package.contains(':'),
        "cargo" => !package.contains('@'),
        _ => false,
    }
}

/// A cargo, npm or gem request that names its own version (`pkg@1.2.0`,
/// `@scope/pkg@2.0.0`, `rake:13.0`), split into name and version. None for a
/// bare name, which the lock pins instead, and for other methods.
pub fn split_versioned(method: &str, package: &str) -> Option<(String, String)> {
    let (name, version) = match method {
        "cargo" => package.split_once('@')?,
        "npm" => match package.rfind('@') {
            Some(i) if i > 0 => (&package[..i], &package[i + 1..]),
            _ => return None,
        },
        "gem" => package.split_once(':')?,
        _ => return None,
    };
    (!name.is_empty() && !version.is_empty()).then(|| (name.to_string(), version.to_string()))
}

/// Everything a project's lock must hold: the tools its configured
/// processors install from a registry and its `[dependencies]` packages,
/// by install method.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Wanted {
    pub cargo: BTreeSet<String>,
    pub gem: BTreeSet<String>,
    pub npm: BTreeSet<String>,
    pub binary: BTreeSet<String>,
}

impl Wanted {
    fn names(&self, method: &str) -> &BTreeSet<String> {
        match method {
            "cargo" => &self.cargo,
            "gem" => &self.gem,
            "npm" => &self.npm,
            "binary" => &self.binary,
            other => unreachable!("not a lock method: {other}"),
        }
    }

    /// Record `package` under `method` when the lock can pin it. Returns
    /// whether it was recorded.
    fn add(&mut self, method: &str, package: &str) -> bool {
        let set = match method {
            "cargo" => &mut self.cargo,
            "gem" => &mut self.gem,
            "npm" => &mut self.npm,
            "binary" => {
                if !crate::tools::binary_is_pinnable(package) {
                    return false;
                }
                self.binary.insert(package.to_string());
                return true;
            }
            _ => return false,
        };
        if !is_bare(method, package) {
            return false;
        }
        set.insert(package.to_string());
        true
    }
}

/// Collect what the project's lock must hold.
///
/// Processor tools are taken by the install method `tool install` uses for
/// them (the one in the slot of their preferred target). A processor tool
/// that a project lockfile already pins — a Python package in uv.lock, a
/// Node package in package-lock.json — is left to that file: `tool install
/// project` installs it from there, and a second pin here could only
/// disagree with it. A Python tool uv.lock does not pin is an error: the
/// repo's `.venv` is uv's, so pyproject.toml is the one place to declare
/// it. `[dependencies]` entries are always included; `tool install
/// project` installs them with these pins.
pub fn collect_wanted(
    processors: &ProcessorMap,
    enabled: &dyn Fn(&str) -> bool,
    deps: &crate::config::DependenciesConfig,
    root: &Path,
) -> Result<Wanted> {
    let LockfileOwned {
        pip: uv_owned,
        npm: npm_owned,
    } = lockfile_owned(deps, root)?;

    let mut unpinned_python: BTreeSet<String> = BTreeSet::new();
    let mut wanted = Wanted::default();
    let mut names: Vec<&String> = processors.keys().collect();
    names.sort();
    for name in names {
        if !enabled(name) {
            continue;
        }
        for tool in processors[name].required_tools() {
            // A repo-local script (`scripts/check.py`) is not installed.
            if tool.contains('/') {
                continue;
            }
            let Some(method) =
                crate::tools::tool_info(&tool).and_then(crate::tools::ToolInfo::preferred_method)
            else {
                continue;
            };
            match method.method {
                "pip" => {
                    let name = crate::config::normalized_distribution_name(method.package);
                    if !uv_owned.contains(&name) {
                        unpinned_python.insert(method.package.to_string());
                    }
                }
                "npm" if npm_owned.contains(method.package) => {}
                _ => {
                    wanted.add(method.method, method.package);
                }
            }
        }
    }
    // uv builds a Python project's .venv, so the project locks the uv that
    // `tool install project` installs ahead of `uv sync`.
    if crate::config::has_python_deps(root)?
        && let Some(method) =
            crate::tools::tool_info("uv").and_then(crate::tools::ToolInfo::preferred_method)
    {
        wanted.add(method.method, method.package);
    }
    if !unpinned_python.is_empty() {
        let names: Vec<&str> = unpinned_python.iter().map(String::as_str).collect();
        return Err(crate::exit_code::config_error(format!(
            "these Python tools are not pinned by uv.lock: {}. The repo's .venv is uv's, so \
             add them to pyproject.toml's dev dependency group (`uv add --dev {}`), which \
             also updates uv.lock",
            names.join(", "),
            names.join(" "),
        )));
    }
    for (method, list) in [
        ("cargo", &deps.cargo),
        ("gem", &deps.gem),
        ("npm", &deps.npm),
    ] {
        for package in list {
            wanted.add(method, package);
        }
    }
    // npm installs a Node project's packages and they run on node, so the
    // project locks the node `tool install project` installs ahead of them.
    if (!wanted.npm.is_empty() || !deps.node_deps(root)?.is_empty())
        && let Some(method) =
            crate::tools::tool_info("node").and_then(crate::tools::ToolInfo::preferred_method)
    {
        wanted.add(method.method, method.package);
    }
    Ok(wanted)
}

/// The packages a project lockfile pins, which rsconstruct.lock therefore
/// leaves alone.
#[derive(Debug, Default, PartialEq, Eq)]
struct LockfileOwned {
    /// PEP 503-normalized names pinned by uv.lock.
    pip: BTreeSet<String>,
    /// Names pinned by package-lock.json.
    npm: BTreeSet<String>,
}

/// What uv.lock and package-lock.json own. package-lock.json counts only
/// when `tool install project` installs from it: one that is on disk but
/// not the configured source (`npm_source = "package-json"`) pins nothing,
/// so its packages must be locked here or they float.
fn lockfile_owned(deps: &crate::config::DependenciesConfig, root: &Path) -> Result<LockfileOwned> {
    let mut owned = LockfileOwned::default();
    let uv_lock = root.join("uv.lock");
    if uv_lock.exists() {
        owned.pip = crate::config::uv_lock_pinned_deps(&uv_lock)?
            .iter()
            .map(|req| crate::config::normalized_distribution_name(req))
            .collect();
    }
    let package_lock = root.join("package-lock.json");
    if deps.npm_source == crate::config::NpmSource::PackageLock && package_lock.exists() {
        owned.npm = crate::config::package_lock_pins(&package_lock)?
            .into_keys()
            .collect();
    }
    Ok(owned)
}

/// Fail when the pre-rsconstruct.lock file is still around.
fn reject_legacy_lock() -> Result<()> {
    if Path::new(LEGACY_LOCK_FILE).exists() {
        return Err(crate::exit_code::config_error(format!(
            "{LEGACY_LOCK_FILE} is no longer read: rsconstruct.lock replaced it, and its \
             machine-local tool paths cannot be converted. Delete {LEGACY_LOCK_FILE} and run \
             `rsconstruct tool lock`."
        )));
    }
    Ok(())
}

/// Read rsconstruct.lock. Returns None if it doesn't exist.
pub fn read_lock_file() -> Result<Option<ToolLock>> {
    let path = Path::new(LOCK_FILE);
    if !path.exists() {
        return Ok(None);
    }
    let content =
        fs::read_to_string(path).with_context(|| format!("Failed to read {}", path.display()))?;
    parse_lock(&content).map(Some)
}

fn parse_lock(content: &str) -> Result<ToolLock> {
    let lock: ToolLock = toml::from_str(content)
        .map_err(|e| crate::exit_code::config_error(format!("Failed to parse {LOCK_FILE}: {e}")))?;
    if lock.version != LOCK_VERSION {
        return Err(crate::exit_code::config_error(format!(
            "{LOCK_FILE} has format version {}, but this rsconstruct reads version \
             {LOCK_VERSION}",
            lock.version
        )));
    }
    Ok(lock)
}

fn render_lock(lock: &ToolLock) -> Result<String> {
    let body = toml::to_string(lock).context("Failed to serialize rsconstruct.lock")?;
    Ok(format!("{LOCK_HEADER}\n{body}"))
}

/// Write rsconstruct.lock atomically (temp file + rename), so a crash or
/// concurrent reader never observes a truncated lock.
fn write_lock_file(lock: &ToolLock) -> Result<()> {
    let path = Path::new(LOCK_FILE);
    let text = render_lock(lock)?;
    let tmp = format!("{LOCK_FILE}.tmp-{}", std::process::id());
    fs::write(&tmp, text).with_context(|| format!("Failed to write {tmp}"))?;
    fs::rename(&tmp, path)
        .with_context(|| format!("Failed to move {tmp} into place as {}", path.display()))?;
    Ok(())
}

/// Lock entries as `(method, name)` pairs.
type Entries = Vec<(String, String)>;

/// The entries `wanted` needs that `lock` lacks, and the ones `lock` holds
/// that nothing needs any more.
fn diff(lock: &ToolLock, wanted: &Wanted) -> (Entries, Entries) {
    let mut missing = Vec::new();
    let mut stale = Vec::new();
    for method in VERSIONED_METHODS {
        let locked = lock.versions(method);
        let names = wanted.names(method);
        missing.extend(
            names
                .iter()
                .filter(|n| !locked.contains_key(*n))
                .map(|n| (method.to_string(), n.clone())),
        );
        stale.extend(
            locked
                .keys()
                .filter(|n| !names.contains(*n))
                .map(|n| (method.to_string(), n.clone())),
        );
    }
    missing.extend(
        wanted
            .binary
            .iter()
            .filter(|n| !lock.binary.contains_key(*n))
            .map(|n| ("binary".to_string(), n.clone())),
    );
    stale.extend(
        lock.binary
            .keys()
            .filter(|n| !wanted.binary.contains(*n))
            .map(|n| ("binary".to_string(), n.clone())),
    );
    (missing, stale)
}

/// The latest release of `name` in `method`'s registry.
fn resolve_version(method: &str, name: &str) -> Result<String> {
    let (url, pointer) = match method {
        "cargo" => (
            format!("https://crates.io/api/v1/crates/{name}"),
            "/crate/max_stable_version",
        ),
        "gem" => (
            format!("https://rubygems.org/api/v1/versions/{name}/latest.json"),
            "/version",
        ),
        // A scoped name's '/' is part of the package, not a path step.
        "npm" => (
            format!(
                "https://registry.npmjs.org/{}/latest",
                name.replace('/', "%2F")
            ),
            "/version",
        ),
        other => unreachable!("not a versioned lock method: {other}"),
    };
    let json = crate::download::get_json(&url)?;
    json.pointer(pointer)
        .and_then(serde_json::Value::as_str)
        .filter(|v| !v.is_empty() && *v != "unknown")
        .map(str::to_string)
        .with_context(|| format!("{url} names no released version of {method} package {name}"))
}

/// Fill `lock`'s entry for `(method, name)` from the registry.
fn resolve_into(
    ctx: &BuildContext,
    lock: &mut ToolLock,
    method: &str,
    name: &str,
    verbose: bool,
) -> Result<()> {
    if verbose {
        println!("Resolving {method} {name}");
    }
    if method == "binary" {
        let pin = crate::tools::lock_binary(ctx, name, verbose)
            .with_context(|| format!("Failed to lock binary {name}"))?;
        lock.binary.insert(name.to_string(), pin);
    } else {
        let version = resolve_version(method, name)
            .with_context(|| format!("Failed to lock {method} package {name}"))?;
        lock.versions_mut(method).insert(name.to_string(), version);
    }
    Ok(())
}

/// How much of the lock a check against it judges.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Coverage {
    /// The lock holds exactly what is wanted: nothing missing, nothing
    /// unused. `tool check` and the installs in CI, which see the whole
    /// project.
    Exact,
    /// The lock holds at least what is wanted; what else it holds is not
    /// judged. The `build` check, which sees only the processors with
    /// products in the graph (after `-p`/`-x`): an entry that selection does
    /// not need may still be needed by a processor outside it.
    AtLeast,
}

/// The committed lock, as CI reads it: it must exist and cover `wanted` to
/// the degree `coverage` asks.
fn read_locked(wanted: &Wanted, coverage: Coverage) -> Result<ToolLock> {
    reject_legacy_lock()?;
    let Some(lock) = read_lock_file()? else {
        return Err(lock_error(format!(
            "No {LOCK_FILE} found. Run `rsconstruct tool lock` outside CI and commit it."
        )));
    };
    let (missing, stale) = diff(&lock, wanted);
    let mut problems: Vec<String> = Vec::new();
    problems.extend(
        missing
            .iter()
            .map(|(m, n)| format!("{m} {n} — needed but not locked")),
    );
    if coverage == Coverage::Exact {
        problems.extend(
            stale
                .iter()
                .map(|(m, n)| format!("{m} {n} — locked but no longer needed")),
        );
    }
    if !problems.is_empty() {
        return Err(lock_error(format!(
            "{LOCK_FILE} does not match this project (run `rsconstruct tool lock` \
             outside CI and commit the result):\n{}",
            problems.join("\n")
        )));
    }
    Ok(lock)
}

/// How a command treats a lock that is missing or does not cover the
/// project.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockMode {
    /// The lock must exist and cover the project exactly; anything else is
    /// an error. CI.
    Locked,
    /// Resolve and add what is missing, drop what nothing needs; never move
    /// an entry that is already locked. Outside CI.
    Fill,
    /// Resolve every entry afresh. `tool lock --upgrade`; the named form
    /// is [`upgrade_named`].
    Upgrade,
}

impl LockMode {
    /// The mode for installs and builds: Locked in CI, Fill elsewhere.
    pub fn for_environment() -> Self {
        if crate::config::running_in_ci() {
            Self::Locked
        } else {
            Self::Fill
        }
    }
}

/// The lock after `sync`, and what syncing changed in it.
pub struct Synced {
    pub lock: ToolLock,
    /// No lock existed before; this one was just written.
    pub created: bool,
    /// One `+ method name version`, `- method name` or
    /// `~ method name old -> new` line per change.
    pub changes: Vec<String>,
}

impl Synced {
    /// Print what changed, unless nothing did. A lock that was just created
    /// is always announced, even one with no entries (a project whose tools
    /// are all apt packages): the file is new and must be committed.
    pub fn report(&self) {
        if self.changes.is_empty() && !self.created {
            return;
        }
        for line in &self.changes {
            println!("  {line}");
        }
        if self.created {
            println!("Created {LOCK_FILE}; commit it.");
        } else {
            println!("Updated {LOCK_FILE}; commit it.");
        }
    }
}

fn entry_label(lock: &ToolLock, method: &str, name: &str) -> String {
    if method == "binary" {
        lock.binary
            .get(name)
            .map_or_else(String::new, |p| p.url.clone())
    } else {
        lock.versions(method).get(name).cloned().unwrap_or_default()
    }
}

/// Bring rsconstruct.lock in line with `wanted` according to `mode`, and
/// return it.
pub fn sync(ctx: &BuildContext, wanted: &Wanted, mode: LockMode, verbose: bool) -> Result<Synced> {
    if mode == LockMode::Locked {
        let lock = read_locked(wanted, Coverage::Exact)?;
        return Ok(Synced {
            lock,
            created: false,
            changes: Vec::new(),
        });
    }

    reject_legacy_lock()?;
    let existing = read_lock_file()?;
    let upgrade_all = mode == LockMode::Upgrade;
    rewrite(ctx, wanted, existing, upgrade_all, &[], verbose)
}

/// `tool lock --upgrade <name>...`: everything `tool lock` does, plus
/// re-resolve the entries `names` select to their latest release. A name
/// selects that tool under every install method the project locks it for.
/// A name the project does not lock is an error, not a no-op: a typo must
/// not look like "already the latest" (and `rsconstruct` is such a name —
/// rsconstruct itself is not locked).
pub fn upgrade_named(
    ctx: &BuildContext,
    wanted: &Wanted,
    names: &[String],
    verbose: bool,
) -> Result<Synced> {
    reject_legacy_lock()?;
    let targets = select_entries(wanted, names)?;
    let existing = read_lock_file()?;
    rewrite(ctx, wanted, existing, false, &targets, verbose)
}

/// The `(method, name)` entries `names` select from `wanted`.
fn select_entries(wanted: &Wanted, names: &[String]) -> Result<Entries> {
    let mut targets = Vec::new();
    let mut unknown = Vec::new();
    for name in names {
        let before = targets.len();
        for method in VERSIONED_METHODS.iter().copied().chain(["binary"]) {
            if wanted.names(method).contains(name) {
                targets.push((method.to_string(), name.clone()));
            }
        }
        if targets.len() == before {
            unknown.push(name.as_str());
        }
    }
    if !unknown.is_empty() {
        return Err(crate::exit_code::config_error(format!(
            "not a tool this project locks: {} (see the entries in {LOCK_FILE})",
            unknown.join(", ")
        )));
    }
    Ok(targets)
}

/// Write the lock for `wanted`, starting from `existing`: drop unused
/// entries, resolve missing ones, and re-resolve `reresolve` (or, with
/// `fresh`, every entry). A legacy `[rsconstruct]` table is dropped.
fn rewrite(
    ctx: &BuildContext,
    wanted: &Wanted,
    existing: Option<ToolLock>,
    fresh: bool,
    reresolve: &[(String, String)],
    verbose: bool,
) -> Result<Synced> {
    let created = existing.is_none();
    let before = existing.unwrap_or_else(ToolLock::empty);
    let mut lock = if fresh {
        ToolLock::empty()
    } else {
        before.clone()
    };
    for (method, name) in reresolve {
        if method == "binary" {
            lock.binary.remove(name);
        } else {
            lock.versions_mut(method).remove(name);
        }
    }
    let (missing, stale) = diff(&lock, wanted);
    for (method, name) in &stale {
        if method == "binary" {
            lock.binary.remove(name);
        } else {
            lock.versions_mut(method).remove(name);
        }
    }
    for (method, name) in &missing {
        resolve_into(ctx, &mut lock, method, name, verbose)?;
    }
    lock.rsconstruct = None;

    let changes = describe_changes(&before, &lock);
    if created || lock != before {
        write_lock_file(&lock)?;
    }
    Ok(Synced {
        lock,
        created,
        changes,
    })
}

/// One line per entry that differs between `before` and `after`.
fn describe_changes(before: &ToolLock, after: &ToolLock) -> Vec<String> {
    let mut changes = Vec::new();
    // Dropping the legacy table is a change the user must see: without this
    // line a rewrite that did nothing else would be reported as "up to
    // date" while the file on disk changed.
    if let (Some(old), None) = (&before.rsconstruct, &after.rsconstruct) {
        changes.push(format!(
            "- rsconstruct {} (rsconstruct itself is no longer locked; CI downloads the latest release)",
            old.version
        ));
    }
    let methods = VERSIONED_METHODS.iter().copied().chain(["binary"]);
    for method in methods {
        let keys = |l: &ToolLock| -> BTreeSet<String> {
            if method == "binary" {
                l.binary.keys().cloned().collect()
            } else {
                l.versions(method).keys().cloned().collect()
            }
        };
        let all: BTreeSet<String> = keys(before).union(&keys(after)).cloned().collect();
        for name in all {
            let old = entry_label(before, method, &name);
            let new = entry_label(after, method, &name);
            match (old.is_empty(), new.is_empty()) {
                (true, false) => changes.push(format!("+ {method} {name} {new}")),
                (false, true) => changes.push(format!("- {method} {name}")),
                (false, false) if old != new => {
                    changes.push(format!("~ {method} {name} {old} -> {new}"));
                }
                _ => {}
            }
        }
    }
    changes
}

fn lock_error(msg: String) -> anyhow::Error {
    crate::exit_code::RsconstructError::new(crate::exit_code::RsconstructExitCode::ToolError, msg)
        .into()
}

/// A locked tool whose installed copy is not the locked one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mismatch {
    pub method: String,
    pub name: String,
    pub locked: String,
    /// What is installed instead, or None when nothing is.
    pub installed: Option<String>,
}

impl std::fmt::Display for Mismatch {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.installed {
            Some(found) => write!(
                f,
                "{} {} — locked {}, installed {found}",
                self.method, self.name, self.locked
            ),
            None => write!(
                f,
                "{} {} — locked {}, not installed",
                self.method, self.name, self.locked
            ),
        }
    }
}

/// The Python packages installed in the environment the `[build] python`
/// interpreter on PATH
/// belongs to (the repo's `.venv`, which rsconstruct puts first on PATH),
/// with their versions, among `names`. Asks the interpreter itself, not
/// `pip show`: a uv-managed venv has no pip. Used by `doctor`.
pub fn installed_pip_versions(ctx: &BuildContext, names: &[&str]) -> BTreeMap<String, String> {
    const SCRIPT: &str = "\
import sys, importlib.metadata as m
for n in sys.argv[1:]:
    try:
        print(n, m.version(n))
    except m.PackageNotFoundError:
        pass
";
    let mut cmd = std::process::Command::new(crate::python_env::interpreter());
    cmd.arg("-c").arg(SCRIPT).args(names);
    let Ok(out) = crate::processor::run_command_capture(ctx, &cmd) else {
        return BTreeMap::new();
    };
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter_map(|l| l.split_once(' '))
        .map(|(n, v)| (n.to_string(), v.trim().to_string()))
        .collect()
}

/// The installed version of a pinned `.deb` binary, as dpkg reports it.
fn installed_deb_version(ctx: &BuildContext, package: &str) -> Option<String> {
    let mut cmd = std::process::Command::new("dpkg-query");
    cmd.args(["-W", "-f", "${Version}", package]);
    let out = crate::processor::run_command_capture(ctx, &cmd).ok()?;
    let version = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (out.status.success() && !version.is_empty()).then_some(version)
}

/// How the project's tool directory records a pinned binary: by the
/// SHA-256 of its executable. None for a `.deb`, which is not installed
/// there.
pub fn binary_version(pin: &BinaryPin) -> Option<String> {
    if pin.deb_package.is_some() {
        return None;
    }
    pin.executable_sha256
        .as_ref()
        .map(|sha| format!("sha256-{sha}"))
}

/// The locked tools among `wanted` whose installed copy is not the locked
/// one. Crates, npm packages, gems and non-`.deb` binaries are judged by
/// the project's tool directory, and `.deb` binaries by dpkg.
pub fn mismatches(ctx: &BuildContext, lock: &ToolLock, wanted: &Wanted) -> Vec<Mismatch> {
    let mut found = Vec::new();
    let mut push = |method: &str, name: &str, locked: &str, installed: Option<String>| {
        found.push(Mismatch {
            method: method.to_string(),
            name: name.to_string(),
            locked: locked.to_string(),
            installed,
        });
    };

    let in_project = crate::tool_store::installed_versions(Path::new("."));
    let project_version = |method: &str, name: &str| -> Option<String> {
        in_project
            .get(&(method.to_string(), name.to_string()))
            .map(|versions| versions.join(", "))
    };
    for method in ["cargo", "gem", "npm"] {
        for name in wanted.names(method) {
            if let Some(locked) = lock.versions(method).get(name) {
                let have = project_version(method, name);
                if have.as_ref() != Some(locked) {
                    push(method, name, locked, have);
                }
            }
        }
    }
    for name in &wanted.binary {
        let Some(pin) = lock.binary.get(name) else {
            continue;
        };
        let (locked, have) = match (&pin.deb_package, &pin.deb_version) {
            (Some(package), Some(version)) => {
                (version.clone(), installed_deb_version(ctx, package))
            }
            _ => match binary_version(pin) {
                Some(version) => (version, project_version("binary", name)),
                None => continue,
            },
        };
        if have.as_ref() != Some(&locked) {
            push("binary", name, &locked, have);
        }
    }
    found
}

/// Check that rsconstruct.lock covers `wanted` (exactly, or at least — see
/// [`Coverage`]) and that every wanted tool is installed at its locked
/// version. `tool check` asks for the whole project exactly; the `build`
/// check in CI and with `--verify-tool-versions` asks for the processors
/// that build.
pub fn verify(ctx: &BuildContext, wanted: &Wanted, coverage: Coverage) -> Result<ToolLock> {
    let lock = read_locked(wanted, coverage)?;
    let found = mismatches(ctx, &lock, wanted);
    if !found.is_empty() {
        let lines: Vec<String> = found.iter().map(ToString::to_string).collect();
        return Err(lock_error(format!(
            "Installed tools do not match {LOCK_FILE} (run `rsconstruct tool install machine` \
             and `rsconstruct tool install project`):\n{}",
            lines.join("\n")
        )));
    }
    Ok(lock)
}

/// Identify a single tool for cache-keying purposes, by the resolved
/// binary's `(path, size, mtime)` — no `--version` subprocess and,
/// critically, no read of the file's bytes.
///
/// Content-hashing the binary was the obvious choice and measured terribly:
/// tool binaries are big (pandoc is ~200 MB here) and there are dozens of
/// them, which made this 45% of a cold build. `(path, size, mtime)` is the
/// same identity assumption the mtime cache already makes for every input
/// file in the project, so keying tools this way is not a weaker standard
/// than the rest of the build — and it is strictly stronger than a
/// `--version` string, which misses a rebuilt binary reporting an unchanged
/// version. Reinstalling a tool changes its mtime, which is the case that
/// has to invalidate.
///
/// Returns None for a tool that is not on PATH: a missing tool is the tool
/// preflight's problem, not the cache key's, and failing here would break
/// builds whose products don't need that processor at all.
fn tool_identity(tool: &str) -> Option<String> {
    let path = which::which(tool).ok()?;
    let meta = match fs::metadata(&path) {
        Ok(m) => m,
        Err(e) => {
            // A tool that IS on PATH but can't be stat'd (dangling symlink,
            // unreadable parent) must not silently drop out of the cache key
            // — that reopens the "tool upgrade leaves stale PASSes valid"
            // hole this mechanism exists to close. Surface it.
            crate::output::warn(&format!(
                "Cannot stat tool '{tool}' at {}: {e} — excluding it from cache keys",
                path.display()
            ));
            return None;
        }
    };
    let mtime = meta
        .modified()
        .ok()
        .and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())
        .map_or(0, |d| d.as_nanos());
    Some(format!("{tool}@{}:{}:{mtime}", path.display(), meta.len()))
}

/// Compute a tool version hash per processor.
///
/// Returns a map from processor name to a hash of its tools' identities, for
/// mixing into every product that processor builds — so upgrading a tool
/// invalidates what that tool produced. Set `[build] hash_tool_versions =
/// false` to opt out.
pub fn processor_tool_hashes(
    processors: &ProcessorMap,
    enabled: &dyn Fn(&str) -> bool,
) -> std::collections::HashMap<String, String> {
    let mut result = std::collections::HashMap::new();

    let mut names: Vec<&String> = processors.keys().collect();
    names.sort();

    // Collect the distinct tool set first. One tool is typically required by
    // several processors; resolving and hashing it once per processor would
    // multiply the work for nothing.
    let mut wanted: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for name in &names {
        if !enabled(name) {
            continue;
        }
        let tools = processors[*name].required_tools();
        if tools.is_empty() {
            continue;
        }
        wanted.insert((*name).clone(), tools);
    }
    let distinct: BTreeSet<String> = wanted.values().flatten().cloned().collect();

    // Resolve each distinct tool once. This is a `which` plus a stat per
    // tool, so it stays serial deliberately: an earlier attempt to thread
    // this measured *slower* on a cold page cache (~2.4s vs ~1.5s), because
    // the threads contended on one large sequential read. Making the identity
    // cheap beat making it concurrent — see `tool_identity`.
    let identity_cache: BTreeMap<String, Option<String>> = distinct
        .iter()
        .map(|t| (t.clone(), tool_identity(t)))
        .collect();

    for name in names {
        let Some(tools) = wanted.get(name) else {
            continue;
        };

        let mut version_parts: Vec<String> = Vec::new();
        for tool in tools {
            if let Some(Some(identity)) = identity_cache.get(tool) {
                version_parts.push(identity.clone());
            }
        }

        if !version_parts.is_empty() {
            version_parts.sort();
            // Length-prefixed parts, not a newline join: identities embed
            // filesystem paths, which can contain newlines.
            let parts: Vec<&str> = version_parts.iter().map(String::as_str).collect();
            result.insert(name.clone(), crate::checksum::hash_parts(&parts));
        }
    }

    result
}

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

    fn sample_lock() -> ToolLock {
        let mut lock = ToolLock::empty();
        lock.cargo
            .insert("cargo-deny".to_string(), "0.18.3".to_string());
        lock.npm
            .insert("@scope/tool".to_string(), "2.0.0".to_string());
        lock.gem.insert("mdl".to_string(), "0.13.0".to_string());
        lock.binary.insert(
            "rumdl".to_string(),
            BinaryPin {
                url: "https://example.com/rumdl.tar.gz".to_string(),
                sha256: "aa".to_string(),
                executable_sha256: Some("bb".to_string()),
                deb_package: None,
                deb_version: None,
            },
        );
        lock
    }

    #[test]
    fn lock_round_trips_through_toml_with_header() {
        let lock = sample_lock();
        let text = render_lock(&lock).unwrap();
        assert!(text.starts_with("# rsconstruct.lock"), "{text}");
        assert_eq!(parse_lock(&text).unwrap(), lock);
    }

    /// A lock written before 2026-10-26 carries an `[rsconstruct]` table.
    /// It must still parse (the fleet's committed locks have it), and a
    /// rewrite leaves it out and says so.
    #[test]
    fn legacy_rsconstruct_table_parses_and_is_dropped_on_rewrite() {
        let old = "version = 1\n\n[rsconstruct]\nversion = \"0.9.140\"\n\n[cargo]\ncargo-deny = \"0.20.2\"\n";
        let before = parse_lock(old).unwrap();
        assert_eq!(
            before.rsconstruct.as_ref().map(|p| p.version.as_str()),
            Some("0.9.140")
        );

        let mut after = before.clone();
        after.rsconstruct = None;
        let text = render_lock(&after).unwrap();
        assert!(!text.contains("[rsconstruct]"), "{text}");
        assert!(text.contains("[cargo]\ncargo-deny = \"0.20.2\""), "{text}");
        // Rendering never writes the table, whatever the struct holds.
        assert!(!render_lock(&before).unwrap().contains("[rsconstruct]"));

        let changes = describe_changes(&before, &after);
        assert_eq!(changes.len(), 1, "{changes:?}");
        assert!(
            changes[0].starts_with("- rsconstruct 0.9.140"),
            "{changes:?}"
        );
    }

    #[test]
    fn empty_sections_are_left_out() {
        let text = render_lock(&ToolLock::empty()).unwrap();
        assert!(!text.contains("[cargo]"), "{text}");
        assert!(!text.contains("[binary"), "{text}");
    }

    #[test]
    fn other_format_versions_and_unknown_keys_are_errors() {
        assert!(parse_lock("version = 2\n").is_err());
        assert!(parse_lock("version = 1\n[surprise]\n").is_err());
        assert!(parse_lock("version = 1\n").is_ok());
    }

    #[test]
    fn pinned_formats_each_package_manager() {
        let lock = sample_lock();
        assert_eq!(lock.pinned("cargo", "cargo-deny"), "cargo-deny@0.18.3");
        assert_eq!(lock.pinned("npm", "@scope/tool"), "@scope/tool@2.0.0");
        assert_eq!(lock.pinned("gem", "mdl"), "mdl:0.13.0");
    }

    /// Unlocked names, explicit constraints and unversioned methods pass
    /// through untouched. pip is one of those: uv.lock pins Python
    /// packages, not this file.
    #[test]
    fn pinned_leaves_other_requests_alone() {
        let lock = sample_lock();
        assert_eq!(lock.pinned("cargo", "cargo-nextest"), "cargo-nextest");
        assert_eq!(lock.pinned("cargo", "cargo-deny@0.1.0"), "cargo-deny@0.1.0");
        assert_eq!(lock.pinned("pip", "ruff"), "ruff");
        assert_eq!(lock.pinned("apt", "ruff"), "ruff");
    }

    #[test]
    fn wanted_skips_constrained_and_unlocked_entries() {
        let mut wanted = Wanted::default();
        assert!(!wanted.add("pip", "ruff"));
        assert!(wanted.add("npm", "@scope/tool"));
        assert!(!wanted.add("npm", "@scope/tool@1.0.0"));
        assert!(!wanted.add("apt", "aspell"));
        assert!(!wanted.add("binary", "google-chrome-stable"));
        assert!(wanted.add("binary", "rumdl"));
        assert_eq!(wanted.npm.len(), 1);
        assert_eq!(wanted.binary.len(), 1);
    }

    #[test]
    fn diff_reports_missing_and_stale_entries() {
        let lock = sample_lock();
        let mut wanted = Wanted::default();
        wanted.add("cargo", "cargo-deny");
        wanted.add("cargo", "cargo-nextest");
        wanted.add("binary", "rumdl");
        let (missing, stale) = diff(&lock, &wanted);
        assert_eq!(
            missing,
            vec![("cargo".to_string(), "cargo-nextest".to_string())]
        );
        let stale: Vec<String> = stale.iter().map(|(m, n)| format!("{m} {n}")).collect();
        assert_eq!(stale, vec!["gem mdl", "npm @scope/tool"]);
    }

    /// A name selects its tool under every method the project locks it
    /// for; an unknown name is an error, and `rsconstruct` is one
    /// (rsconstruct itself is not locked).
    #[test]
    fn select_entries_matches_names_across_methods() {
        let mut wanted = Wanted::default();
        wanted.add("cargo", "oxlint");
        wanted.add("binary", "oxlint");
        let names = |list: &[&str]| list.iter().map(ToString::to_string).collect::<Vec<_>>();

        let targets = select_entries(&wanted, &names(&["oxlint"])).unwrap();
        let targets: Vec<String> = targets.iter().map(|(m, n)| format!("{m} {n}")).collect();
        assert_eq!(targets, vec!["cargo oxlint", "binary oxlint"]);

        let err = select_entries(&wanted, &names(&["rsconstruct"])).unwrap_err();
        assert!(err.to_string().contains("rsconstruct"), "{err}");

        let err = select_entries(&wanted, &names(&["oxlint", "nosuch"])).unwrap_err();
        assert!(err.to_string().contains("nosuch"), "{err}");
    }

    #[test]
    fn describe_changes_lists_additions_removals_and_moves() {
        let before = sample_lock();
        let mut after = before.clone();
        after
            .cargo
            .insert("cargo-deny".to_string(), "0.19.0".to_string());
        after.gem.remove("mdl");
        after
            .cargo
            .insert("mdbook".to_string(), "0.4.40".to_string());
        assert_eq!(
            describe_changes(&before, &after),
            vec![
                "~ cargo cargo-deny 0.18.3 -> 0.19.0",
                "+ cargo mdbook 0.4.40",
                "- gem mdl",
            ]
        );
    }

    #[test]
    fn split_versioned_takes_explicit_versions_only() {
        let split = |m: &str, p: &str| split_versioned(m, p);
        let pair = |n: &str, v: &str| Some((n.to_string(), v.to_string()));
        assert_eq!(
            split("cargo", "cargo-deny@0.18.3"),
            pair("cargo-deny", "0.18.3")
        );
        assert_eq!(
            split("npm", "@scope/tool@2.0.0"),
            pair("@scope/tool", "2.0.0")
        );
        assert_eq!(split("gem", "rake:13.0"), pair("rake", "13.0"));
        assert_eq!(split("npm", "@scope/tool"), None);
        assert_eq!(split("cargo", "cargo-deny"), None);
        assert_eq!(split("pip", "ruff==0.1"), None);
    }

    /// A non-`.deb` binary is recorded by its executable's hash; a `.deb`
    /// is not installed into the project at all.
    #[test]
    fn binary_version_is_the_executable_hash() {
        let lock = sample_lock();
        assert_eq!(
            binary_version(&lock.binary["rumdl"]).as_deref(),
            Some("sha256-bb")
        );
        let deb = BinaryPin {
            url: "https://example.com/x.deb".to_string(),
            sha256: "aa".to_string(),
            executable_sha256: None,
            deb_package: Some("x".to_string()),
            deb_version: Some("1.0".to_string()),
        };
        assert_eq!(binary_version(&deb), None);
    }

    /// package-lock.json owns its packages only when `tool install project`
    /// installs from it. With `npm_source = "package-json"`, one on disk
    /// pins nothing, so the packages it names must still be locked here —
    /// before this, `tool lock` dropped them and they floated. uv.lock is
    /// always the source of the repo's .venv, so it always owns its pins.
    #[test]
    fn lockfiles_own_packages_only_when_they_are_the_source() {
        let tmp = tempfile::TempDir::new().unwrap();
        fs::write(
            tmp.path().join("package-lock.json"),
            r#"{"lockfileVersion": 3, "packages": {"node_modules/markdownlint-cli": {"version": "0.45.0"}}}"#,
        )
        .unwrap();
        fs::write(
            tmp.path().join("uv.lock"),
            "version = 1\n\n[[package]]\nname = \"ruff\"\nversion = \"0.14.0\"\nsource = { registry = \"https://pypi.org/simple\" }\n",
        )
        .unwrap();

        let defaults = crate::config::DependenciesConfig::default();
        let owned = lockfile_owned(&defaults, tmp.path()).unwrap();
        assert_eq!(
            owned.npm.iter().collect::<Vec<_>>(),
            vec!["markdownlint-cli"]
        );
        assert_eq!(owned.pip.iter().collect::<Vec<_>>(), vec!["ruff"]);

        let floating = crate::config::DependenciesConfig {
            npm_source: crate::config::NpmSource::PackageJson,
            ..Default::default()
        };
        let owned = lockfile_owned(&floating, tmp.path()).unwrap();
        assert!(owned.npm.is_empty(), "{owned:?}");
        assert_eq!(owned.pip.iter().collect::<Vec<_>>(), vec!["ruff"]);
    }

    /// A Python tool a processor runs must be pinned by uv.lock: the repo's
    /// .venv is uv's, so pyproject.toml is the one place to declare it.
    /// Pinned, it is left to uv.lock and not locked here; what is locked
    /// here is the uv binary that builds the .venv.
    #[test]
    fn python_tools_must_be_pinned_by_uv_lock() {
        let tmp = tempfile::TempDir::new().unwrap();
        let processors = crate::builder::create_all_default_processors().unwrap();
        let ruff = "processor.checker.ruff";
        let deps = crate::config::DependenciesConfig::default();

        let err = collect_wanted(&processors, &|p| p == ruff, &deps, tmp.path()).unwrap_err();
        assert!(err.to_string().contains("uv add --dev ruff"), "{err}");

        fs::write(
            tmp.path().join("uv.lock"),
            "version = 1\n\n[[package]]\nname = \"ruff\"\nversion = \"0.14.0\"\nsource = { registry = \"https://pypi.org/simple\" }\n",
        )
        .unwrap();
        let wanted = collect_wanted(&processors, &|p| p == ruff, &deps, tmp.path()).unwrap();
        let mut expected = Wanted::default();
        expected.add("binary", "uv");
        assert_eq!(wanted, expected);
    }

    /// A project without a Python environment does not lock uv.
    #[test]
    fn uv_is_locked_only_for_a_python_project() {
        let tmp = tempfile::TempDir::new().unwrap();
        let processors = crate::builder::create_all_default_processors().unwrap();
        let deps = crate::config::DependenciesConfig::default();
        let wanted = collect_wanted(&processors, &|_| false, &deps, tmp.path()).unwrap();
        assert_eq!(wanted, Wanted::default());
    }

    /// A Node project locks the node its npm steps run on, whether its
    /// packages come from package-lock.json or from `[dependencies] npm`.
    #[test]
    fn node_is_locked_for_a_node_project() {
        let processors = crate::builder::create_all_default_processors().unwrap();
        let with_node = || {
            let mut want = Wanted::default();
            want.add("binary", "node");
            want
        };

        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("package.json"),
            r#"{"devDependencies": {"eslint": "^9"}}"#,
        )
        .unwrap();
        std::fs::write(
            tmp.path().join("package-lock.json"),
            r#"{"lockfileVersion": 3, "packages": {"node_modules/eslint": {"version": "9.0.0"}}}"#,
        )
        .unwrap();
        let deps = crate::config::DependenciesConfig::default();
        let wanted = collect_wanted(&processors, &|_| false, &deps, tmp.path()).unwrap();
        assert_eq!(wanted, with_node());

        let tmp = tempfile::TempDir::new().unwrap();
        let deps = crate::config::DependenciesConfig {
            npm: vec!["eslint".to_string()],
            ..Default::default()
        };
        let wanted = collect_wanted(&processors, &|_| false, &deps, tmp.path()).unwrap();
        let mut expected = with_node();
        expected.add("npm", "eslint");
        assert_eq!(wanted, expected);
    }
}