greengate-runtime 4.3.0

The amont hook logic: registry, dispatchers, checks and the trust model
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
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
//! pre-push-run-tests-js — run each touched JS package's gate before pushing.
//!
//! git feeds pre-push one line per ref on stdin. That list is parsed ONCE by
//! the dispatcher (see `pushrefs`) and lent here, because stdin can only be
//! consumed once and more than one check needs it:
//!     <local ref> <local oid> <remote ref> <remote oid>
//! An all-zero local oid is a deletion; an all-zero remote oid means the branch
//! is new, so everything it carries is in range.

use super::common::program;
use super::json_scan::{string_end, top_level_value};
use crate::check::Outcome;
use crate::git;
use crate::manifest::ROOT_RUNS_KEY;
use std::io::IsTerminal;
use std::process::{Command, Stdio};

/// Whichever of these the package defines, cheapest first, stopping at the
/// first failure — a type error costs seconds, not a full suite.
///
/// `lint` is deliberately absent: pre-commit-lint-js already lints staged files
/// with the repo's pinned eslint, so repeating it here costs time and catches
/// nothing new.
///
/// That argument is not special to `lint`. Any entry here can be moved earlier
/// by a repository — see [`gated_at_commit`] — and once it runs on every commit,
/// running it again on push is the same pure repetition. `typecheck` is the one
/// people move: push is too late to hear about a type error you introduced an
/// hour ago.
const GATE: [&str; 3] = crate::manifest::NPM_GATE_SCRIPTS;

/// Whether `name` is one of the scripts the npm push gate runs ([`GATE`]).
pub(crate) fn is_gate_script(name: &str) -> bool {
    GATE.contains(&name)
}

/// GATE entries this repository already runs at COMMIT time, and so must not
/// run again here.
///
/// A repository moves one earlier by declaring it in `amont.conf` under the
/// name of the script:
///
/// ```text
/// pre-commit  typecheck  *.ts,*.tsx  block  npm run typecheck
/// ```
///
/// The name is the contract, deliberately — matching on the command would have
/// to guess at `npm` vs `pnpm` vs `yarn`, at `--silent`, at a wrapper script,
/// and would answer "no" to things that plainly are the same check.
///
/// **Only a declaration that would actually run, and actually block, counts**:
///
///   * `Kind::Runnable` excludes an unusable line and — through
///     [`crate::manifest::gate`] — an UNTRUSTED manifest. A repository could
///     otherwise declare `pre-commit typecheck`, never be trusted, and silently
///     have types checked at neither end.
///   * `hook.skip` is honoured for the same reason, one layer up: a declaration
///     the author has switched off is not a check.
///   * The EFFECTIVE severity must be `block`, overrides included. A `warn`
///     declaration lets the commit through on failure, so treating it as
///     commit-time coverage would replace a blocking push check with a
///     non-blocking commit one.
///
/// The declaration's scope rides along rather than being judged here: whether
/// it covered a given push depends on which files that push changed, which is
/// a per-ref question `run` answers with [`crate::check::Scope::covers_all`].
///
/// Get any of these wrong and the result is the failure this project is
/// arranged against — a push that reports a green gate having run nothing.
/// A declaration passing this filter is still only a PROMISE: whether the
/// check executed for the commits actually being pushed is what
/// [`crate::gate_stamp`]'s per-commit stamps answer, in `run`.
pub(crate) fn gated_at_commit(
    settings: &crate::config::Settings,
    declared: &[crate::manifest::External],
) -> Vec<GateDecl> {
    let mut decls = blocking_commit_decls(settings, declared);
    decls.retain(|d| GATE.contains(&d.script.as_str()));
    decls
}

/// EVERY blocking commit-time declaration, whatever its name — the general
/// form [`gated_at_commit`] narrows to the npm GATE vocabulary. This is what
/// earns stamps and what the bypass ledger counts: a `pre-commit test *.rs
/// block cargo test` line gates exactly the way `typecheck` always has, and
/// a same-named pre-push declaration defers to its stamps (see
/// [`pair_verdict`]). The npm push gate was the first consumer of this
/// machinery, not its definition.
pub(crate) fn blocking_commit_decls(
    settings: &crate::config::Settings,
    declared: &[crate::manifest::External],
) -> Vec<GateDecl> {
    // The fast path: pre-commit calls this on every commit to know what to
    // stamp, and most repositories declare nothing — no pre-commit
    // declaration means no git spawns for skips and severity overrides.
    if gate_names_declared(declared).is_empty() {
        return Vec::new();
    }
    let skips = crate::configured_skips(settings);
    let severities = crate::registry::Overrides::read(settings);
    declared
        .iter()
        .filter_map(|ext| {
            let crate::manifest::Kind::Runnable { files, .. } = &ext.kind else {
                return None;
            };
            ext.blocks_at_commit(&severities, &skips).then(|| GateDecl {
                script: ext.short_name.clone(),
                id: ext.id.clone(),
                lineno: ext.lineno,
                // What it fires on and is judged on: the resolved trigger
                // (its own scope united with its push twin's), else its own.
                scope: ext.effective_scope(),
                files: *files,
            })
        })
        .collect()
}

/// Names this manifest declares at pre-commit, before any config is read —
/// the zero-spawn question "could this repository have a commit-time gate at
/// all". [`blocking_commit_decls`] and the bypass ledger's fast path both
/// start here, from the same predicate, so they cannot drift.
pub(crate) fn gate_names_declared(declared: &[crate::manifest::External]) -> Vec<String> {
    declared
        .iter()
        .filter(|ext| ext.stage == crate::check::Stage::PreCommit)
        .map(|ext| ext.short_name.clone())
        .collect()
}

/// How a `Gated` push was covered, so its line can say what the skip rests on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Coverage {
    /// Every pushed commit in the pair's scope carries its stamp.
    EveryCommit,
    /// At least one ref had a commit with no stamp, and was covered by its
    /// TIP alone: these tips' own stamp keys hold the pair token (ADR-0019).
    /// Short shas, one per such ref.
    Tips(Vec<String>),
}

/// Why a same-named commit-time declaration did not vouch for a push. Each of
/// these used to be a silent `NotPaired`, and a silent rerun of the whole suite
/// is how a land held for two hours (2026-11-10).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum WhyNot {
    /// Its scope does not cover these pushed files.
    ScopeGap {
        /// What the declaration covers, as written (`*.rs`).
        scope: String,
        uncovered: Vec<String>,
        cause: GapCause,
        /// The manifest file the line is in (`greengate.conf`, or an
        /// unswept repository's `amont.conf`).
        file: &'static str,
        /// The 1-based manifest line to edit, when it is known.
        at: Option<usize>,
    },
    /// It is a warn check, which vouches for nothing.
    Warn,
    /// `hook.skip` switches it off here.
    Skipped,
    /// The repository lacks the marker that turns it on.
    NotOptedIn(Vec<String>),
    /// Its program was not found, so its stamps vouch for nothing.
    Unidentified,
}

/// What left a declaration narrower than the files its push twin acts on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum GapCause {
    /// A `files` declaration is handed the matched paths, so it is never
    /// widened.
    Files,
    /// The twin acts on every change, which widening would not follow.
    UnscopedTwin,
    /// Nothing explains it: the trigger was not resolved (a missed
    /// `resolve_triggers` call), which is a bug here and not in the repository.
    Unresolved,
}

/// The reason a declaration did not vouch because the repository lacks its
/// opt-in marker.
fn not_opted_in(scope: &crate::check::Scope) -> WhyNot {
    WhyNot::NotOptedIn(scope.opt_in.iter().map(|m| m.to_string()).collect())
}

/// The reason a declaration did not vouch because its scope misses some of the
/// files `relevant` to its push twin. One derivation for every gate that pairs
/// (`pair_verdict` and the npm push gate), so the same gap gets the same
/// words on both paths. `twin_line` is the `amont.conf` line of a DECLARED
/// push twin that acts on every change, the line to scope.
fn scope_gap(
    file: &'static str,
    pair: &GateDecl,
    push_scope: &crate::check::Scope,
    relevant: &[String],
    twin_line: Option<usize>,
) -> WhyNot {
    let (cause, at) = if pair.files {
        (GapCause::Files, pair.lineno)
    } else if push_scope.is_unscoped() {
        (GapCause::UnscopedTwin, twin_line)
    } else {
        (GapCause::Unresolved, pair.lineno)
    };
    WhyNot::ScopeGap {
        scope: scope_label(&pair.scope),
        uncovered: relevant
            .iter()
            .filter(|file| !pair.scope.covers(file))
            .cloned()
            .collect(),
        cause,
        file,
        at,
    }
}

/// The `amont.conf` line of the `pre-push` declaration named `name`, if there
/// is one: the line to edit when its twin acts on every change.
fn declared_twin_line(manifest: &crate::manifest::Manifest, name: &str) -> Option<usize> {
    manifest
        .externals
        .iter()
        .find(|e| e.stage == crate::check::Stage::PrePush && e.short_name == name)
        .and_then(|e| e.lineno)
}

/// Whether a reason's first line is cut to fit 80 columns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LineWidth {
    /// On a terminal: cut the variable part, keep the ending.
    Cut,
    /// Piped, in a CI log: every path in full.
    Whole,
}

/// The lines that say why a same-named commit-time declaration did not vouch:
/// the reason, then for a scope gap an indented line naming the `amont.conf`
/// line to edit. Pure, so the words and their width are tested.
///
/// On a terminal the first line is cut to 80 columns (the sign and its space
/// stand for two of them), and only its variable part is cut, so its ending,
/// `— running it here`, always survives. Piped, nothing is cut: a CI log keeps
/// every path. Every value from the manifest or the repository is sanitised.
pub(crate) fn reason_lines(name: &str, why: &WhyNot, width: LineWidth) -> Vec<String> {
    let name = crate::ui::sanitize(name);
    let first = |prefix: String, variable: String, suffix: &str| -> String {
        if width == LineWidth::Cut {
            let line = crate::tree_lint::fit_line(&format!("  {prefix}"), &variable, suffix);
            line.strip_prefix("  ").unwrap_or(&line).to_string()
        } else {
            format!("{prefix}{variable}{suffix}")
        }
    };
    match why {
        WhyNot::ScopeGap {
            scope,
            uncovered,
            cause,
            file,
            at,
        } => {
            let shown: Vec<String> = uncovered
                .iter()
                .take(3)
                .map(|path| crate::ui::sanitize(path))
                .collect();
            let paths = match uncovered.len().saturating_sub(3) {
                0 => shown.join(", "),
                more => format!("{} and {more} more", shown.join(", ")),
            };
            let head = first(
                format!(
                    "{name} at commit covers {}, not ",
                    crate::ui::sanitize(scope)
                ),
                paths,
                " — running it here",
            );
            let at_known = at.is_some();
            let at = match at {
                Some(line) => format!("{file} line {line}"),
                None => (*file).to_string(),
            };
            let first_path = shown.first().map(String::as_str).unwrap_or("it");
            let fix = match cause {
                GapCause::Files => {
                    format!("    a files declaration is not widened: add {first_path} to {at}")
                }
                GapCause::UnscopedTwin if at_known => {
                    format!("    its push twin runs on every change: scope that line in {at}")
                }
                GapCause::UnscopedTwin => format!(
                    "    its push twin runs on every change: declare a scoped pre-push {name} line in {at}"
                ),
                GapCause::Unresolved => format!(
                    "    its push twin's files were not applied: a {} bug, please report it",
                    crate::names::BIN
                ),
            };
            vec![head, fix]
        }
        WhyNot::Warn => vec![first(
            String::new(),
            name,
            " at commit is warn-only, so it vouches for nothing — running it here",
        )],
        WhyNot::Skipped => vec![first(
            String::new(),
            name,
            " at commit is skipped here (hook.skip) — running it here",
        )],
        WhyNot::NotOptedIn(markers) => {
            let markers: Vec<String> = markers.iter().map(|m| crate::ui::sanitize(m)).collect();
            vec![first(
                String::new(),
                name,
                &format!(
                    " at commit is not opted in (needs {}) — running it here",
                    markers.join(" | ")
                ),
            )]
        }
        WhyNot::Unidentified => vec![first(
            String::new(),
            name,
            " at commit: its program was not found — running it here",
        )],
    }
}

/// Say why a same-named commit-time declaration did not vouch, before the push
/// runs the gate. Exit codes are untouched: this is a line, not a verdict.
pub(crate) fn say_why_not(name: &str, why: &WhyNot) {
    let width = if std::io::stdout().is_terminal() {
        LineWidth::Cut
    } else {
        LineWidth::Whole
    };
    let mut lines = reason_lines(name, why, width).into_iter();
    if let Some(head) = lines.next() {
        crate::say!("{} {head}", crate::ui::warning_sign());
    }
    for rest in lines {
        crate::say!("{rest}");
    }
}

/// What a declared PRE-PUSH external should do about a same-named
/// commit-time declaration — the general form of the npm gate's stamp
/// suppression, for names the GATE list never heard of. Declaring `test`
/// (or `lint`, or anything) at BOTH stages is the contract: the pre-commit
/// side earns per-commit stamps, and the pre-push side runs only for pushes
/// carrying commits with no record of it, unless a ref's tip itself passed.
pub(crate) enum PairVerdict {
    /// No blocking commit-time pair covers this push — run normally. With the
    /// reason, when a same-named commit-time declaration exists and did not
    /// vouch: the push says so, then runs the gate. `None` when there is no
    /// such declaration, or nothing for it to vouch for.
    NotPaired(Option<WhyNot>),
    /// Every judged ref is covered — skip, saying so, and how.
    Gated(Coverage),
    /// A pair exists but this many pushed commits carry no record of it —
    /// run, saying why the declaration's word was not enough.
    Unstamped(usize),
    /// No pushed commit is unstamped except this many, whose gate the busy
    /// policy deferred at commit (ADR-0013): defer the twin to CI as well.
    /// Never `Gated`, which would attest a suite that ran nowhere.
    Deferred(usize),
}

/// Judge a pre-push gate against its commit-time pair, with exactly the npm
/// gate's rules: the pair must be BLOCKING (a warn check vouches for
/// nothing), its scope must have seen every file this push changes that the
/// push-side check would fire on, and every relevant commit must carry its
/// stamp. Any git refusal reads as "no stamp", which runs the check — the
/// only safe direction.
///
/// Takes the push side as `(name, scope)` rather than an `&External`,
/// because those two are all it ever used and a BUILT-IN has both. That is
/// the whole reason built-ins can be paired now: the logic never needed a
/// declaration, only a name to match and a scope to judge against.
///
/// `name` is the SHORT name — `cargo-test`, not `pre-push-cargo-test`. It is
/// compared against [`GateDecl::script`], which is what the author wrote in
/// `amont.conf`. Passing an id here matches nothing and silently pairs
/// nothing; see `Check::pairing_name`.
pub(crate) fn pair_verdict(
    settings: &crate::config::Settings,
    name: &str,
    push_scope: &crate::check::Scope,
    manifest: &crate::manifest::Manifest,
    push: &crate::pushrefs::PushRefs,
) -> PairVerdict {
    // Cheap name test before any config read or git spawn: most pre-push
    // gates have no commit-time namesake.
    let Some(commit_side) = manifest
        .externals
        .iter()
        .find(|e| e.stage == crate::check::Stage::PreCommit && e.short_name == name)
    else {
        return PairVerdict::NotPaired(None);
    };
    let Some(pair) = blocking_commit_decls(settings, &manifest.externals)
        .into_iter()
        .find(|d| d.script == name)
    else {
        return PairVerdict::NotPaired(why_not_blocking(settings, commit_side));
    };
    // A declaration this repository has not opted into never ran at commit
    // time, so it has nothing to vouch with — the push side runs on its own
    // word. Judged against the REPOSITORY, once, and never against a commit's
    // changed files: see `repo_opted_in`.
    if !repo_opted_in(&pair.scope) {
        return PairVerdict::NotPaired(Some(not_opted_in(&pair.scope)));
    }
    // The complete token of the commit-time declaration. Unknown identity (its
    // program cannot be found) means its stamps vouch for nothing: the push
    // says so, then runs on its own word.
    let Some(pair_token) = manifest
        .externals
        .iter()
        .find(|e| e.id == pair.id)
        .and_then(|e| crate::gate_identity::external_token(e, &pair.script))
    else {
        return PairVerdict::NotPaired(Some(WhyNot::Unidentified));
    };
    let zero = git::stdout(&["hash-object", "--stdin"])
        .map(|h| "0".repeat(h.len()))
        .unwrap_or_else(|| "0".repeat(40));
    let mut unstamped = 0usize;
    let mut deferred = 0usize;
    let mut judged_any = false;
    // The refs covered by their tip alone, as short shas for the line.
    let mut tips: Vec<String> = Vec::new();
    // Under `onBusy defer`, a commit whose gate the busy policy deferred is
    // not "unstamped": its twin defers too (ADR-0013). `GREENGATE_ON_BUSY=wait`
    // turns this off and the twin runs.
    let defer = matches!(
        crate::host_slots::busy_policy(settings),
        crate::host_slots::BusyPolicy::Defer { .. }
    );
    for r in push.get() {
        let changed = crate::pushrefs::changed_files_for(r, &zero);
        // `covers`, NOT `matches`, and the difference is the whole reason
        // built-ins can be paired at all.
        //
        // `matches` also asks the OPT-IN question — "is there a Cargo.toml
        // here" — and asking it of a single path can only ever answer no.
        // `pre-push-cargo-test` opts in on `Cargo.toml`, so every changed
        // `.rs` file would be judged irrelevant, `judged_any` would stay
        // false, and the verdict would be `NotPaired` for every push in
        // every Rust repository. Silently: a gate that never pairs looks
        // exactly like a gate with no pair declared.
        //
        // Opt-in is a fact about the REPOSITORY, settled once by the
        // dispatcher when it decided this check runs here at all. What this
        // loop needs is the per-file question, which is `covers`.
        let relevant: Vec<String> = changed
            .iter()
            .filter(|f| push_scope.is_unscoped() || push_scope.covers(f))
            .cloned()
            .collect();
        if relevant.is_empty() {
            continue; // this ref never fires the push-side check
        }
        judged_any = true;
        if !pair.scope.covers_all(&relevant) {
            // The pair has not judged everything this push changes, so its
            // word covers nothing here. Said out loud, as "running it here"
            // and never as partial coverage, which would read as
            // reassurance: it names what the declaration misses.
            return PairVerdict::NotPaired(Some(scope_gap(
                manifest.file_name(),
                &pair,
                push_scope,
                &relevant,
                declared_twin_line(manifest, name),
            )));
        }
        let per_commit = crate::pushrefs::commits_and_files_for(r, &zero);
        let ids: Vec<String> = per_commit.iter().map(|(c, _)| c.clone()).collect();
        let stamps = crate::gate_stamp::stamps_for(&ids);
        // `touches`, NOT `matches`, for the same reason as above and with a
        // worse consequence. `matches` asks the opt-in question of ONE
        // COMMIT's changed files: a `*.txt+marker` pair judged a commit that
        // changed `a.txt` and left `marker` alone as "would never fire", so
        // the commit was not counted, `unstamped` stayed 0, and the verdict
        // was `Gated` — the push-side twin skipped on the strength of a
        // stamp that did not exist. Opt-in was settled for the repository
        // above; per commit the only question is whether it touched the
        // scope.
        let missing: Vec<String> = per_commit
            .iter()
            .filter(|(_, files)| pair.scope.touches(files))
            .filter(|(commit, _)| !stamps.get(commit).is_some_and(|s| s.contains(&pair_token)))
            .map(|(commit, _)| commit.clone())
            .collect();
        // The tip is what ships. When its OWN stamp key — the tree's note, its
        // declared-input fingerprints, its canonical tree (ADR-0011, ADR-0012),
        // exactly what `stamps_for` read above — holds the pair token, the
        // code being pushed passed the commit-time gate, and an older commit
        // that never earned a stamp (relais's hookless `commit-tree`, a
        // deferral) changes nothing about it (ADR-0019). A changed declared
        // input or gate script gives the tip a different key, so it vouches
        // for nothing and the per-commit count stands.
        //
        // Asked only when some commit is missing its stamp: a fully stamped
        // ref is covered the old way, and its line keeps meaning so.
        //
        // Never for a `files` pair: its command saw only that commit's
        // matched paths, so its stamp says nothing about the rest of the tree.
        // holds-until: every pair without `files` judges the whole tree. A
        // command that picks the staged paths itself (`lint-staged`,
        // `--cached`, `--staged`) and has a pre-push twin breaks that; none
        // existed in the fleet on 2026-11-06 (docs/custom-checks.md).
        //
        // AFTER the coverage guards above, never before: a ref whose changes
        // the pair's scope does not cover is `NotPaired`, whatever its tip
        // says.
        if !missing.is_empty()
            && !pair.files
            && stamps
                .get(&r.local_oid)
                .is_some_and(|s| s.contains(&pair_token))
        {
            tips.push(crate::gate_evidence::short(&r.local_oid).to_string());
            continue;
        }
        let excused = if defer {
            crate::gate_stamp::deferred_for(&missing, &pair.script)
        } else {
            Default::default()
        };
        deferred += excused.len();
        unstamped += missing.len() - excused.len();
    }
    if !judged_any {
        return PairVerdict::NotPaired(None);
    }
    // Never `Gated` when a deferral covers a commit: `Gated` puts the twin
    // in `passed`, which the signed attestation names, and CI would then skip
    // a suite that ran nowhere.
    if unstamped > 0 {
        PairVerdict::Unstamped(unstamped)
    } else if deferred > 0 {
        PairVerdict::Deferred(deferred)
    } else {
        PairVerdict::Gated(if tips.is_empty() {
            Coverage::EveryCommit
        } else {
            Coverage::Tips(tips)
        })
    }
}

/// A scope as a person writes it: `*.rs`, `Cargo.toml`, `dir/**/*.md`.
fn scope_label(scope: &crate::check::Scope) -> String {
    scope
        .files
        .iter()
        .chain(scope.names.iter())
        .chain(scope.dirs.iter())
        .map(|t| {
            if t.starts_with('.') {
                format!("*{t}")
            } else {
                (*t).to_string()
            }
        })
        .collect::<Vec<_>>()
        .join(",")
}

/// Why a runnable commit-time declaration that is not among the blocking ones
/// did not vouch: `hook.skip` switches it off, or it is a warn check. `None`
/// for one that is not runnable at all (an untrusted manifest, a broken line),
/// which the dispatchers already say once per stage.
fn why_not_blocking(
    settings: &crate::config::Settings,
    ext: &crate::manifest::External,
) -> Option<WhyNot> {
    if !matches!(ext.kind, crate::manifest::Kind::Runnable { .. }) {
        return None;
    }
    let skipped = crate::configured_skips(settings)
        .iter()
        .any(|s| crate::skip_suppresses(&ext.id, s));
    Some(if skipped {
        WhyNot::Skipped
    } else {
        WhyNot::Warn
    })
}

/// Has this repository opted into `scope`? The index is the only honest
/// source — the same question `manifest.rs` asks before running the
/// declaration at commit time, so the stamp check and the run agree on
/// whether it could have run at all.
///
/// `true` when git will not list the files: an unverified answer must not
/// silently promote a declaration to "never ran" — that direction re-runs
/// the push-side gate, which is the safe one. `tracked_files` is cached
/// per process, so the git spawn is paid once however many pairs ask.
fn repo_opted_in(scope: &crate::check::Scope) -> bool {
    scope.opt_in.is_empty()
        || crate::hooks::common::tracked_files().map_or(true, |tracked| scope.opted_in(&tracked))
}

/// One gate entry a commit-time declaration stands in for.
pub(crate) struct GateDecl {
    /// The declared name — a GATE script for the npm push gate, any name
    /// for a declared pre-commit/pre-push pair.
    pub script: String,
    /// `<stage>-<name>` — what dispatch outcomes and `hook.skip` key on.
    /// Carried so pre-commit can match "this declaration" to "that outcome"
    /// without re-deriving the id and drifting.
    pub id: String,
    /// The declaration's scope, judged per ref by
    /// [`crate::check::Scope::covers_all`].
    pub scope: crate::check::Scope,
    /// The `files` marker: the command is handed only the commit's matched
    /// paths, so its stamp vouches for that commit's files and never for the
    /// tree. Such a pair cannot cover a ref by its tip ([`pair_verdict`]).
    pub files: bool,
    /// The 1-based `amont.conf` line that declares it, for a message that
    /// sends a person to the line to edit.
    pub lineno: Option<usize>,
}

/// The extensions this check treats as "JS worth testing". Exported so
/// `registry.rs` declares the scope from the same constant — see
/// `lint_json_yaml::EXTS` for the drift this prevents.
pub const JS_EXTS: &[&str] = &[".js", ".jsx", ".ts", ".tsx", ".vue"];

fn is_js(file: &str) -> bool {
    JS_EXTS.iter().any(|e| file.ends_with(e))
}

fn parent_of(path: &str) -> &str {
    match path.rfind('/') {
        Some(i) => &path[..i],
        None => "",
    }
}

/// Does `package.json` define `script` under "scripts"?
///
/// A brace-matched scan rather than a JSON parser: the only question is whether
/// one key exists in one object, and a dependency-free binary is the point of
/// this migration. Restricted to the TOP-LEVEL "scripts" object so a
/// same-named key elsewhere (a dependency called `test`, say) cannot answer
/// for it.
pub fn defines_script(pkg_json: &str, script: &str) -> bool {
    let Some(body) = scripts_object(pkg_json) else {
        return false;
    };
    let needle = format!("\"{script}\"");
    let mut from = 0;
    while let Some(i) = body[from..].find(&needle) {
        let at = from + i;
        let after = &body[at + needle.len()..];
        if after.trim_start().starts_with(':') {
            return true;
        }
        from = at + needle.len();
    }
    false
}

/// The text of the top-level `"scripts"` object, braces included.
///
/// A depth-tracking scan, not `find("\"scripts\"")`: anchoring on the FIRST
/// occurrence of the substring anywhere meant `{"files":["scripts"],…}`
/// handed the brace-matcher whichever object came next — so a dependency
/// named `test` answered as a script while the real scripts object was never
/// read, which is exactly the false positive `defines_script`'s doc promises
/// away. A string only counts as a key when it sits at depth 1 (inside the
/// document object, outside any array) AND its next non-space byte is `:` —
/// `{"name": "scripts"}` is a value, not the key.
fn scripts_object(pkg_json: &str) -> Option<&str> {
    top_level_value(pkg_json, "scripts").filter(|value| value.starts_with('{'))
}

/// Tracked `package.json` paths, as directories relative to the repo root.
///
/// `git ls-files` instead of the shell version's `fd package.json`: it drops
/// the `fd` dependency (undeclared, and one of two binaries the hooks silently
/// required), and it is the more correct set anyway — only TRACKED packages can
/// be part of a push, and node_modules is excluded by construction rather than
/// by fd happening to honour .gitignore.
pub fn package_dirs(ls_files: &[String]) -> Vec<String> {
    let mut dirs: Vec<String> = ls_files
        .iter()
        .map(String::as_str)
        .filter(|f| *f == "package.json" || f.ends_with("/package.json"))
        .map(|f| parent_of(f).to_string())
        .collect();
    dirs.sort();
    dirs.dedup();
    dirs
}

/// Packages that actually contain one of the changed files.
///
/// `.iter().any()`, not the shell version's original `.filter()` — an empty
/// array is truthy in JS, so that selected EVERY package regardless of what
/// changed. Invisible in a single-package repo, quadratic noise in a monorepo.
pub fn packages_to_test(pkg_dirs: &[String], changed_dirs: &[String]) -> Vec<String> {
    pkg_dirs
        .iter()
        .filter(|pkg| {
            changed_dirs.iter().any(|dir| {
                if pkg.is_empty() {
                    true
                } else {
                    dir == *pkg || dir.starts_with(&format!("{pkg}/"))
                }
            })
        })
        .cloned()
        .collect()
}

/// What a repository says about which of its ROOT package's scripts already run
/// every workspace member (`set rootRunsMembers`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RootDeclaration {
    /// Nothing declared: a root and a member that both ran a script may be a
    /// repeat, and the push says how to declare it.
    Unset,
    /// These of the gate's scripts run every member from the root; none at all
    /// for `none`. Names are the gate's own: anything else is dropped.
    Declared(Vec<&'static str>),
}

/// The gate's scripts named in a `rootRunsMembers` value: `none` is none, and a
/// name the gate does not run is dropped (the parser already refused one in the
/// committed line, so only a local value can carry one).
fn gate_scripts_named(raw: &str) -> Vec<&'static str> {
    if raw.trim().eq_ignore_ascii_case("none") {
        return Vec::new();
    }
    raw.split(',')
        .map(str::trim)
        .filter_map(|name| GATE.iter().copied().find(|script| *script == name))
        .collect()
}

/// The declaration, held to what a local `git config` may do to the committed
/// line: remove names, or set `none`, and never add one. A machine that could
/// add a name would skip members' tests that no committed, trusted line vouches
/// for. A local `none` with nothing committed only silences the hint. Pure: the
/// raw values are read by [`root_declaration`].
fn declared_from(committed: Option<&str>, effective: Option<&str>) -> RootDeclaration {
    match (
        committed.map(gate_scripts_named),
        effective.map(gate_scripts_named),
    ) {
        (Some(committed), Some(effective)) => RootDeclaration::Declared(
            committed
                .into_iter()
                .filter(|script| effective.contains(script))
                .collect(),
        ),
        (Some(committed), None) => RootDeclaration::Declared(committed),
        (None, Some(effective)) if effective.is_empty() => RootDeclaration::Declared(Vec::new()),
        (None, _) => RootDeclaration::Unset,
    }
}

/// What this repository declares: the committed line, from a trusted
/// `amont.conf`, and the effective value after any local `git config`.
pub(crate) fn root_declaration(settings: &crate::config::Settings) -> RootDeclaration {
    let effective = crate::config::string_value(settings, ROOT_RUNS_KEY);
    declared_from(
        settings
            .policy()
            .settings
            .get(ROOT_RUNS_KEY)
            .map(String::as_str),
        effective.as_deref(),
    )
}

/// The scripts of `root_runs` the declaration says run every member.
fn covering_scripts(
    root_runs: &[&'static str],
    declaration: &RootDeclaration,
) -> Vec<&'static str> {
    match declaration {
        RootDeclaration::Declared(names) => root_runs
            .iter()
            .copied()
            .filter(|script| names.contains(script))
            .collect(),
        RootDeclaration::Unset => Vec::new(),
    }
}

/// Does an `amont.conf` this machine does not trust carry a
/// `set rootRunsMembers` line? Its policy is withheld, but the file can still be
/// read: only then does "trust it" tell the person something true.
fn untrusted_line_declares(root: &str) -> bool {
    crate::manifest::read_lines(std::path::Path::new(root))
        .iter()
        .any(|line| {
            matches!(line, crate::manifest::Line::Policy {
                what: crate::manifest::PolicyLine::Set { key, .. }, ..
            } if key == ROOT_RUNS_KEY)
        })
}

/// What the root covers in one push: the scripts it runs that are declared to
/// run every member, and where the members are.
struct RootCoverage {
    covering: Vec<&'static str>,
    members: Option<super::js_workspace::Members>,
}

impl RootCoverage {
    /// The scripts a package does not run again because the root's run covers
    /// it: the covering scripts for a member of the workspace, none for the
    /// root itself or a package outside the globs.
    fn skip_for(&self, folder: &str) -> &[&'static str] {
        let covered = !folder.is_empty()
            && self
                .members
                .as_ref()
                .is_some_and(|members| members.covers(folder));
        if covered {
            &self.covering
        } else {
            &[]
        }
    }
}

/// The command `script` runs, as `package.json` writes it, when it is a plain
/// string: what a stale declaration would be read against. `None` for a script
/// that is absent or written with an escape.
pub(crate) fn script_command(pkg_json: &str, script: &str) -> Option<String> {
    let body = scripts_object(pkg_json)?;
    let needle = format!("\"{script}\"");
    let mut from = 0;
    while let Some(i) = body[from..].find(&needle) {
        let at = from + i;
        let after = body[at + needle.len()..].trim_start();
        if let Some(after_colon) = after.strip_prefix(':') {
            let quoted_command = after_colon.trim_start().strip_prefix('"')?;
            let close = string_end(quoted_command.as_bytes(), 0)?;
            let command = &quoted_command[..close];
            return (!command.contains('\\')).then(|| command.to_string());
        }
        from = at + needle.len();
    }
    None
}

/// Whether the `amont.conf` that could declare the root's scripts counts here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Trust {
    /// A declaration in it would count: the hint says how to add one.
    Counted,
    /// It carries a `set rootRunsMembers` line this machine does not trust, so
    /// the line does not count until it is trusted.
    Withheld,
}

/// The lines that say a script ran at the root and in members with nothing
/// declaring that the root already runs them: a repeat, if it does, and what to
/// do. Pure, so the words and their width are tested: the first line carries the
/// sign, so it fits 78 columns, and so does every other line.
pub(crate) fn repeat_hint_lines(
    script: &str,
    members: usize,
    trust: Trust,
    manifest: &str,
) -> Vec<String> {
    let plural = if members == 1 { "" } else { "s" };
    let mut lines = vec![format!(
        "{} ran at the root and in {members} package{plural} — a repeat if the root runs them",
        crate::ui::sanitize(script)
    )];
    match trust {
        Trust::Counted => lines.push(format!(
            "    declare it in {manifest}: set rootRunsMembers {script}   (or: none)"
        )),
        Trust::Withheld => {
            lines.push(format!(
                "    {manifest} is not trusted: its rootRunsMembers line does not count"
            ));
            lines.push(format!("    run: {} trust", crate::names::BIN));
        }
    }
    lines
}

/// A terminal line is cut to this many columns.
const LINE_COLUMNS: usize = 80;
/// The `: ` and the two backticks around the root's command on the summary line.
const COMMAND_FRAME: usize = 4;
/// Fewer columns than this are not worth showing of a command.
const MIN_COMMAND_COLUMNS: usize = 12;

/// The one line that says how many members a declared root script skipped, so
/// tests that did not run are never silent: the count, what covers them, and
/// the root's command so a declaration gone stale reads against what it claims.
/// On a terminal only the command is cut, so the count and the cause survive.
pub(crate) fn skip_summary_line(
    manifest: &str,
    skipped: usize,
    script: &str,
    command: Option<&str>,
    width: LineWidth,
) -> String {
    let plural = if skipped == 1 { "" } else { "s" };
    let head = format!(
        "{skipped} package{plural} skipped, covered by the root's {} (per {manifest})",
        crate::ui::sanitize(script)
    );
    let Some(command) = command else {
        return head;
    };
    let command = crate::ui::sanitize(command);
    match width {
        // No room for even a few characters of the command: the count and the
        // cause are what must survive, so the command goes, and a `…` says
        // there was one.
        LineWidth::Cut
            if head.chars().count() + COMMAND_FRAME + MIN_COMMAND_COLUMNS > LINE_COLUMNS =>
        {
            crate::tree_lint::fit_line("", &head, ": …")
        }
        LineWidth::Cut => crate::tree_lint::fit_line(&format!("{head}: `"), &command, "`"),
        LineWidth::Whole => format!("{head}: `{command}`"),
    }
}

/// What the push says when a script is declared to cover the members but the
/// workspace cannot be confirmed: the members run, and the globs are what to
/// look at. Pure, so the width is tested: the first line carries the sign.
pub(crate) fn unreadable_workspace_lines(file: &str) -> Vec<String> {
    vec![
        "rootRunsMembers is declared, but its workspace globs are not understood".to_string(),
        format!(
            "    running every member; check the workspace globs in {}",
            crate::ui::sanitize(file)
        ),
    ]
}

/// The line said before a script runs in a package, so a second run of the same
/// script reads as a second run and not as the first one stalling. The folder
/// comes from a git path, so it is sanitised like every other value here.
pub(crate) fn announcement_line(script: &str, nth: usize, of: usize, folder: &str) -> String {
    let place = if folder.is_empty() {
        "the root".to_string()
    } else {
        crate::ui::sanitize(folder)
    };
    format!("npm run {script}: {nth} of {of}, in {place}")
}

/// The GATE, minus what a `pre-commit` declaration already covers.
///
/// Split from `run_gate` so the rule can be tested without a package on disk
/// and without spawning npm — `run_gate` reaches for both.
pub fn gate_for(pkg_json: &str, already: &[&str]) -> Vec<&'static str> {
    GATE.iter()
        .copied()
        .filter(|s| defines_script(pkg_json, s) && !already.contains(s))
        .collect()
}

/// How one package's gate went.
enum GateRun {
    /// Every script passed; these are the ones that ran.
    Passed(Vec<&'static str>),
    /// A script failed or timed out.
    Failed,
}

/// Where in this push's list of runs a package is: for its announcement.
#[derive(Clone, Copy)]
struct Place {
    nth: usize,
    of: usize,
}

/// A package's directory in the checkout the gate runs in.
fn package_dir(root: &str, folder: &str) -> String {
    if folder.is_empty() {
        root.to_string()
    } else {
        format!("{root}/{folder}")
    }
}

/// Run `scripts` in one package, announcing each before it runs.
fn run_gate(
    settings: &crate::config::Settings,
    root: &str,
    folder: &str,
    scripts: &[&'static str],
    place: Place,
) -> GateRun {
    let dir = package_dir(root, folder);
    let mut ran = Vec::new();
    for &script in scripts {
        crate::say!("{}", announcement_line(script, place.nth, place.of, folder));
        // Same hazard as cargo test: git exports GIT_DIR to hooks, and a JS
        // test that shells out to git would then operate on this repo rather
        // than its own fixture.
        let mut cmd = Command::new(program("npm"));
        cmd.args(["run", script])
            .current_dir(&dir)
            .stdin(Stdio::null());
        super::common::strip_git_env(&mut cmd);
        match super::common::status_streamed(settings, &mut cmd, super::common::Retry::Once) {
            Ok(super::common::Ran::Status(status)) if status.success() => ran.push(script),
            Ok(super::common::Ran::TimedOut(budget)) => {
                super::common::say_timed_out(script, budget);
                return GateRun::Failed;
            }
            // The gate's own exit code is not propagated: git only
            // distinguishes zero from non-zero, and npm's codes said nothing
            // the message above has not already said.
            Ok(_) | Err(_) => return GateRun::Failed,
        }
    }
    GateRun::Passed(ran)
}

pub fn run(
    settings: &crate::config::Settings,
    refs: &[crate::pushrefs::PushRef],
    manifest: &crate::manifest::Manifest,
    gate: &str,
) -> Outcome {
    let declared = manifest.externals.as_slice();
    // An all-zero oid, of whatever length this repo's hash is (sha1 or sha256).
    let zero = git::stdout(&["hash-object", "--stdin"])
        .map(|h| "0".repeat(h.len()))
        .unwrap_or_else(|| "0".repeat(40));

    // `Unavailable`, never `Passed`, when git itself will not answer: a push
    // gate that reports green having asked nothing is the exact conflation
    // `Outcome::Unavailable` exists to prevent (see its doc in check.rs), and
    // the same split `install::repo_hooks` was rewritten for. The dispatcher
    // says "could not run" and does not block — loud, and honest.
    let Some(root) = git::stdout(&["rev-parse", "--show-toplevel"]) else {
        super::common::warn("run-tests-js: git would not answer — the gate did NOT run");
        return Outcome::Unavailable;
    };
    let Some(tracked) = git::stdout_paths(&["ls-files"]) else {
        super::common::warn("run-tests-js: git would not answer — the gate did NOT run");
        return Outcome::Unavailable;
    };
    let pkg_dirs = package_dirs(&tracked);

    // The DECLARATIONS are a property of the repository, resolved once; whether
    // one covers a given push is a property of that ref's changed files and of
    // its commits' stamps, judged inside the loop.
    let declared_gate = gated_at_commit(settings, declared);
    let mut announced: Vec<String> = Vec::new();
    let mut warned: Vec<String> = Vec::new();
    let mut said_why: Vec<String> = Vec::new();
    // What the repository declares about its root scripts, read once; whether
    // its `amont.conf` counts; and what has been said once per push: the repeat
    // hint per script, and that a declared workspace could not be read.
    let root_declaration = root_declaration(settings);
    let trust = if manifest.policy_withheld.is_some() && untrusted_line_declares(&root) {
        Trust::Withheld
    } else {
        Trust::Counted
    };
    let mut hinted: Vec<&'static str> = Vec::new();
    let mut said_unreadable = false;

    for r in refs {
        let local_oid = r.local_oid.as_str();
        if local_oid == zero {
            continue; // deleting a ref pushes no code
        }
        // `pushrefs::changed_files_for` exists for exactly this question, and
        // this check used to recompute it inline with all three bugs that
        // function's doc comment records fixing:
        //
        //   - a brand-new branch (`remote_oid == zero`) diffed only its TIP,
        //     so on a multi-commit push an earlier commit's `.ts` change was
        //     invisible and the suite never ran;
        //   - a two-dot range handed to `diff-tree` is a two-TREE compare, not
        //     a commit walk, so a file changed and reverted later in the same
        //     push netted to nothing;
        //   - merge commits show NOTHING without `-m`, so a file touched only
        //     to resolve a conflict selected no package.
        //
        // Every one of those let a push proceed GREEN with the suite never
        // having run. `rust_tools::test` was already the model.
        let changed = crate::pushrefs::changed_files_for(r, &zero);
        let js_changed: Vec<String> = changed.iter().filter(|f| is_js(f)).cloned().collect();
        let changed_dirs: Vec<String> = js_changed
            .iter()
            .map(|f| parent_of(f).to_string())
            .collect();
        if changed_dirs.is_empty() {
            continue;
        }

        // A declaration only stands in for this push if its scope saw every JS
        // file the push changes — and only for the ROOT package, because that
        // is where the declared command runs. A sub-package's gate is a
        // different command in a different directory, and no root declaration
        // has judged it.
        //
        // And the declaration must have EXECUTED, which is the stamps'
        // question: every commit in this push the declaration would have
        // fired on must carry a `gate_stamp` note naming the script. A commit
        // made with `--no-verify`, from a client that runs no hooks, on a
        // machine without amont, or with a rewritten hash has no stamp — and
        // an unstamped commit is one the check never judged, so the gate runs
        // rather than trusting the declaration's word for it.
        //
        // And the REPOSITORY must have opted into it — judged against the
        // index, not per commit: see `pair_verdict` for the skipped-gate bug
        // that asking it of a commit's changed files produced.
        let candidates: Vec<&GateDecl> = declared_gate
            .iter()
            .filter(|d| d.scope.covers_all(&js_changed) && repo_opted_in(&d.scope))
            .collect();
        // A declaration that stood in for a script and did not cover this push
        // used to be dropped without a word, and the script ran again. Said
        // once per script, in the pair gates' words.
        for d in &declared_gate {
            if said_why.contains(&d.script) {
                continue;
            }
            let why = if !repo_opted_in(&d.scope) {
                Some(not_opted_in(&d.scope))
            } else if !d.scope.covers_all(&js_changed) {
                let js_scope = crate::check::Scope::files(JS_EXTS);
                Some(scope_gap(
                    manifest.file_name(),
                    d,
                    &js_scope,
                    &js_changed,
                    None,
                ))
            } else {
                None
            };
            if let Some(why) = why {
                say_why_not(&d.script, &why);
                said_why.push(d.script.clone());
            }
        }
        let mut already: Vec<String> = Vec::new();
        if !candidates.is_empty() {
            let per_commit = crate::pushrefs::commits_and_files_for(r, &zero);
            let ids: Vec<String> = per_commit.iter().map(|(c, _)| c.clone()).collect();
            let stamps = crate::gate_stamp::stamps_for(&ids);
            for d in candidates {
                // Complete token or no vouching: a declaration whose program
                // cannot be identified vouches for nothing, so it says so and
                // the script runs.
                let token = declared
                    .iter()
                    .find(|e| e.id == d.id)
                    .and_then(|e| crate::gate_identity::external_token(e, &d.script));
                let Some(token) = token else {
                    // Nothing to vouch with: say so once, and the script runs.
                    if !said_why.contains(&d.script) {
                        say_why_not(&d.script, &WhyNot::Unidentified);
                        said_why.push(d.script.clone());
                    }
                    continue;
                };
                let unstamped = per_commit
                    .iter()
                    .filter(|(_, files)| d.scope.touches(files))
                    .filter(|(commit, _)| {
                        !stamps
                            .get(commit)
                            .is_some_and(|stamped| stamped.contains(&token))
                    })
                    .count();
                if unstamped == 0 {
                    already.push(d.script.clone());
                } else if !warned.contains(&d.script) {
                    crate::say!(
                        "{} {} is declared at commit time, but {unstamped} pushed \
                         commit{} carr{} no record of it — running it here",
                        crate::ui::warning_sign(),
                        d.script,
                        if unstamped == 1 { "" } else { "s" },
                        if unstamped == 1 { "ies" } else { "y" },
                    );
                    warned.push(d.script.clone());
                }
            }
        }

        // Same question as cargo-test: the suite should be answering about
        // the commits being pushed, not about whatever is open in the
        // editor — and about THIS ref's commits, not some other ref in the
        // same push. A single worktree shared across every ref would run a
        // second ref's tests against a first ref's tree.
        let (run_in, _guard) = crate::pushed_tree::where_to_run(settings, local_oid, &root, gate);
        let where_ = run_in.to_string_lossy().into_owned();
        let folders = packages_to_test(&pkg_dirs, &changed_dirs);

        // Said out loud, and not folded into the pass line. A check that stops
        // running is exactly what this project refuses to let happen quietly —
        // the reader has to be able to see that `typecheck` moved rather than
        // discover later that nothing ran it. Announced only when the skip is
        // actually applied to this ref: claiming suppression that severity,
        // scope or a missing root package disqualified would be the same lie
        // in the other direction.
        if folders.iter().any(|f| f.is_empty()) {
            let newly: Vec<String> = already
                .iter()
                .filter(|s| !announced.contains(s))
                .cloned()
                .collect();
            if !newly.is_empty() {
                crate::hooks::common::ok(
                    settings,
                    &format!(
                        "{} gated at commit instead — not repeating {} here",
                        newly.join(", "),
                        if newly.len() == 1 { "it" } else { "them" },
                    ),
                );
                announced.extend(newly);
            }
        }

        let already_strs: Vec<&str> = already.iter().map(String::as_str).collect();

        // The root's scripts that run in THIS push, and of those the ones the
        // repository declares run every member: a changed member the workspace
        // covers is not run again for them. Read from the pushed tree, like
        // the packages themselves.
        let manifest_file = crate::manifest::manifest_name(std::path::Path::new(&where_));
        let root_pkg = if folders.iter().any(|f| f.is_empty()) {
            std::fs::read_to_string(format!("{where_}/package.json")).ok()
        } else {
            None
        };
        let root_runs: Vec<&'static str> = root_pkg
            .as_deref()
            .map(|pkg| gate_for(pkg, &already_strs))
            .unwrap_or_default();
        let covering = covering_scripts(&root_runs, &root_declaration);
        let members = if covering.is_empty() {
            None
        } else {
            super::js_workspace::members_of(std::path::Path::new(&where_))
        };
        // Declared, trusted, and unreadable: the members run (the safe side),
        // and the person is told why a declared line seems to do nothing.
        if !covering.is_empty() && members.is_none() && !said_unreadable {
            said_unreadable = true;
            let file = if std::path::Path::new(&where_)
                .join("pnpm-workspace.yaml")
                .is_file()
            {
                "pnpm-workspace.yaml"
            } else {
                "package.json"
            };
            let mut lines = unreadable_workspace_lines(file).into_iter();
            if let Some(head) = lines.next() {
                crate::say!("{} {head}", crate::ui::warning_sign());
            }
            for rest in lines {
                crate::say!("{rest}");
            }
        }
        let coverage = RootCoverage { covering, members };

        // What each package runs here, and what the root's run lets it skip.
        let mut plan: Vec<(String, Vec<&'static str>)> = Vec::new();
        let mut skipped: Vec<(&'static str, usize)> = Vec::new();
        for folder in folders {
            let defined =
                std::fs::read_to_string(format!("{}/package.json", package_dir(&where_, &folder)))
                    .map(|pkg| gate_for(&pkg, &[]))
                    .unwrap_or_default();
            // The root's own skips are what a declared commit-time command
            // covers; a member's are what the root runs.
            let skip: &[&str] = if folder.is_empty() {
                &already_strs
            } else {
                coverage.skip_for(&folder)
            };
            let (skipped_here, to_run): (Vec<&'static str>, Vec<&'static str>) = defined
                .into_iter()
                .partition(|script| skip.contains(script));
            if !folder.is_empty() {
                for script in skipped_here {
                    match skipped.iter_mut().find(|(name, _)| *name == script) {
                        Some((_, count)) => *count += 1,
                        None => skipped.push((script, 1)),
                    }
                }
            }
            if !to_run.is_empty() {
                plan.push((folder, to_run));
            }
        }
        // One line per script for all the members it skips: said always, quiet
        // or not, because a line that says tests were NOT run is exactly the
        // kind this project does not let get hidden.
        let width = if std::io::stdout().is_terminal() {
            LineWidth::Cut
        } else {
            LineWidth::Whole
        };
        for &script in GATE.iter() {
            let Some(&(_, count)) = skipped.iter().find(|(name, _)| *name == script) else {
                continue;
            };
            let command = root_pkg
                .as_deref()
                .and_then(|pkg| script_command(pkg, script));
            crate::say!(
                "{}",
                skip_summary_line(manifest_file, count, script, command.as_deref(), width)
            );
        }

        let total = plan.len();
        let mut ran_in_members: Vec<(&'static str, usize)> = Vec::new();
        let mut ran_at_root: Vec<&'static str> = Vec::new();
        for (index, (folder, scripts)) in plan.into_iter().enumerate() {
            let place = Place {
                nth: index + 1,
                of: total,
            };
            let GateRun::Passed(ran) = run_gate(settings, &where_, &folder, &scripts, place) else {
                return Outcome::Failed;
            };
            for script in ran {
                if folder.is_empty() {
                    ran_at_root.push(script);
                } else if let Some((_, count)) =
                    ran_in_members.iter_mut().find(|(name, _)| *name == script)
                {
                    *count += 1;
                } else {
                    ran_in_members.push((script, 1));
                }
            }
        }
        // A script that ran at the root AND in members, with nothing declared,
        // may be a repeat: said once per script, with what to do about it.
        if root_declaration == RootDeclaration::Unset {
            for (script, members) in ran_in_members {
                if ran_at_root.contains(&script) && !hinted.contains(&script) {
                    hinted.push(script);
                    let mut lines =
                        repeat_hint_lines(script, members, trust, manifest_file).into_iter();
                    if let Some(head) = lines.next() {
                        crate::say!("{} {head}", crate::ui::warning_sign());
                    }
                    for rest in lines {
                        crate::say!("{rest}");
                    }
                }
            }
        }
    }
    Outcome::Passed
}

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

    /// The filter itself, without a package on disk or an npm to spawn.
    ///
    /// Order is part of the contract and is asserted: GATE is cheapest-first so
    /// a type error costs seconds rather than a full suite, and removing an
    /// entry must not disturb what is left.
    #[test]
    fn the_gate_drops_only_what_commit_already_covers() {
        let pkg = r#"{"scripts":{"typecheck":"tsc","test":"vitest run"}}"#;
        assert_eq!(gate_for(pkg, &[]), vec!["typecheck", "test"]);
        assert_eq!(gate_for(pkg, &["typecheck"]), vec!["test"]);
        assert_eq!(gate_for(pkg, &["test"]), vec!["typecheck"]);
        assert!(gate_for(pkg, &["typecheck", "test"]).is_empty());
        // A name the package does not define is not a script to skip, and
        // naming one must not disturb the rest.
        assert_eq!(gate_for(pkg, &["test:unit"]), vec!["typecheck", "test"]);
    }

    /// Coverage is all-match: one changed file outside the declaration's scope
    /// means commits this push carries were never judged by it.
    #[test]
    fn a_scope_covers_only_when_every_changed_file_matches() {
        use crate::check::Scope;
        const TS_ONLY: Scope = Scope::files(&[".ts", ".tsx"]);
        let all_ts: Vec<String> = vec!["src/a.ts".into(), "src/b.tsx".into()];
        let mixed: Vec<String> = vec!["src/a.ts".into(), "src/legacy.js".into()];
        let js_only: Vec<String> = vec!["src/legacy.js".into()];
        assert!(TS_ONLY.covers_all(&all_ts));
        assert!(!TS_ONLY.covers_all(&mixed));
        assert!(!TS_ONLY.covers_all(&js_only));
        // An empty scope is `*` — it saw everything.
        assert!(Scope::ALWAYS.covers_all(&mixed));
        // Nothing relevant changed: nothing was missed.
        assert!(TS_ONLY.covers_all(&[]));

        // A bare-filename scope covers by BASENAME, never by suffix.
        const BY_NAME: Scope = Scope {
            files: &[],
            names: &["package.json"],
            dirs: &[],
            opt_in: &[],
            not_during: &[],
        };
        assert!(BY_NAME.covers_all(&["apps/web/package.json".into()]));
        assert!(!BY_NAME.covers_all(&["not-package.json".into()]));
    }

    #[test]
    fn finds_scripts_only_inside_the_scripts_object() {
        let pkg = r#"{"name":"x","scripts":{"test":"vitest","typecheck":"tsc"},"devDependencies":{"lint":"1"}}"#;
        assert!(defines_script(pkg, "test"));
        assert!(defines_script(pkg, "typecheck"));
        assert!(!defines_script(pkg, "test:unit"));
        // present, but as a DEPENDENCY — must not answer for the scripts object
        assert!(!defines_script(pkg, "lint"));
    }

    #[test]
    fn survives_nested_objects_and_escaped_quotes() {
        let pkg = r#"{"scripts":{"test":"echo \"hi\"","build":"x"},"other":{"test":"no"}}"#;
        assert!(defines_script(pkg, "test"));
        assert!(defines_script(pkg, "build"));
        assert!(!defines_script(pkg, "other"));
    }

    #[test]
    fn no_scripts_object_means_no_scripts() {
        assert!(!defines_script(r#"{"name":"x"}"#, "test"));
    }

    /// The misanchor this scan replaced: `find("\"scripts\"")` hit the string
    /// inside the `files` ARRAY, brace-matched the dependencies object that
    /// followed, and a dependency named `test` answered as a script — while
    /// the real scripts object was never read.
    #[test]
    fn a_scripts_string_elsewhere_cannot_anchor_the_scan() {
        let pkg = r#"{"files":["scripts"],"dependencies":{"test":"1.0"},"scripts":{"build":"x"}}"#;
        assert!(
            !defines_script(pkg, "test"),
            "a dependency answered as a script"
        );
        assert!(
            defines_script(pkg, "build"),
            "the real scripts object was skipped"
        );

        // The same shape via a string VALUE rather than an array element.
        let pkg =
            r#"{"description":"scripts","dependencies":{"test":"1.0"},"scripts":{"build":"x"}}"#;
        assert!(!defines_script(pkg, "test"));
        assert!(defines_script(pkg, "build"));

        // A NESTED "scripts" key (inside another object) is not the top-level
        // one.
        let pkg = r#"{"config":{"scripts":{"test":"inner"}},"scripts":{"build":"x"}}"#;
        assert!(!defines_script(pkg, "test"));
        assert!(defines_script(pkg, "build"));
    }

    /// `"scripts"` as a top-level key whose value is not an object defines
    /// nothing — and no later impostor may answer instead.
    #[test]
    fn a_non_object_scripts_value_defines_nothing() {
        assert!(!defines_script(r#"{"scripts":"echo hi"}"#, "test"));
        assert!(!defines_script(
            r#"{"scripts":"x","other":{"test":"y"}}"#,
            "test"
        ));
    }

    #[test]
    fn collects_package_directories() {
        let ls: Vec<String> = [
            "package.json",
            "apps/web/package.json",
            "apps/web/src/a.ts",
            "README.md",
        ]
        .into_iter()
        .map(String::from)
        .collect();
        assert_eq!(
            package_dirs(&ls),
            vec!["".to_string(), "apps/web".to_string()]
        );
    }

    /// The JS bug: `.filter()` returns an array, `[]` is truthy, so every
    /// package was selected whatever changed.
    #[test]
    fn selects_only_packages_containing_a_change() {
        let pkgs = vec!["apps/web".to_string(), "apps/api".to_string()];
        let changed = vec!["apps/web/src".to_string()];
        assert_eq!(
            packages_to_test(&pkgs, &changed),
            vec!["apps/web".to_string()]
        );
    }

    #[test]
    fn the_repo_root_package_matches_any_change() {
        let pkgs = vec!["".to_string()];
        assert_eq!(
            packages_to_test(&pkgs, &["src".to_string()]),
            vec!["".to_string()]
        );
    }

    fn every_reason(path: &str) -> Vec<WhyNot> {
        vec![
            WhyNot::ScopeGap {
                scope: "*.rs".into(),
                uncovered: vec![path.into()],
                cause: GapCause::Files,
                file: crate::manifest::MANIFEST,
                at: Some(3),
            },
            WhyNot::Warn,
            WhyNot::Skipped,
            WhyNot::NotOptedIn(vec!["marker".into()]),
            WhyNot::Unidentified,
        ]
    }

    /// The first line of every reason fits 80 columns with the sign and its
    /// space in front, for an ordinary name, and ends in `running it here`:
    /// the part a reader needs must never be the part that gets cut.
    #[test]
    fn every_reason_fits_its_line_and_keeps_its_ending() {
        for why in every_reason("rustfmt.toml") {
            let head = &reason_lines("cargo-test", &why, LineWidth::Whole)[0];
            assert!(head.chars().count() + 2 <= 80, "{head}");
            assert!(head.ends_with("— running it here"), "{head}");
        }
    }

    /// On a terminal a long path, or a long name, is cut, never the ending.
    #[test]
    fn on_a_terminal_only_the_variable_part_is_cut() {
        let long = "crates/a/very/deep/package/directory/src/components/widgets/Button.stories.tsx";
        for why in every_reason(long) {
            let head = &reason_lines("cargo-test", &why, LineWidth::Cut)[0];
            assert!(head.chars().count() + 2 <= 80, "{head}");
            assert!(head.ends_with("— running it here"), "{head}");
        }
        let name = "a-rather-long-check-name-indeed-for-a-gate";
        for why in [
            WhyNot::Warn,
            WhyNot::Skipped,
            WhyNot::NotOptedIn(vec!["marker".into()]),
            WhyNot::Unidentified,
        ] {
            let head = &reason_lines(name, &why, LineWidth::Cut)[0];
            assert!(head.chars().count() + 2 <= 80, "{head}");
            assert!(head.ends_with("— running it here"), "{head}");
        }
    }

    /// Piped, nothing is cut: a CI log keeps every path.
    #[test]
    fn piped_nothing_is_cut() {
        let long = "crates/a/very/deep/package/directory/src/components/widgets/Button.stories.tsx";
        let why = WhyNot::ScopeGap {
            scope: "*.rs".into(),
            uncovered: vec![long.into()],
            cause: GapCause::Files,
            file: crate::manifest::MANIFEST,
            at: None,
        };
        assert!(reason_lines("cargo-test", &why, LineWidth::Whole)[0].contains(long));
    }

    /// Everything the manifest or the repository supplies is sanitised, the
    /// scope and the markers included.
    #[test]
    fn values_from_the_manifest_are_sanitised() {
        let why = WhyNot::NotOptedIn(vec!["mark\u{1b}[31mer".into()]);
        let head = &reason_lines("cargo-test", &why, LineWidth::Whole)[0];
        assert!(!head.contains('\u{1b}'), "{head:?}");
    }

    /// What a declaration is read against: the root script's command, when it
    /// is a plain string.
    #[test]
    fn a_scripts_command_is_read_when_it_is_a_plain_string() {
        let pkg = r#"{"name":"r","scripts":{"build":"tsc","test":"pnpm -r --workspace-concurrency=2 test"}}"#;
        assert_eq!(
            script_command(pkg, "test").as_deref(),
            Some("pnpm -r --workspace-concurrency=2 test")
        );
        assert_eq!(script_command(pkg, "typecheck"), None, "absent");
        let escaped = r#"{"scripts":{"test":"echo \"x\""}}"#;
        assert_eq!(
            script_command(escaped, "test"),
            None,
            "an escape is not guessed at"
        );
        let elsewhere = r#"{"dependencies":{"test":"1.0.0"},"scripts":{}}"#;
        assert_eq!(
            script_command(elsewhere, "test"),
            None,
            "only the scripts object"
        );
    }

    /// The repeat hint's lines fit 80 columns (the first with the sign), for
    /// every script the gate runs, and name the line to add; withheld, they say
    /// why a line there would not count and how to trust it.
    #[test]
    fn the_repeat_hint_fits_its_line_and_names_the_fix() {
        for script in crate::manifest::NPM_GATE_SCRIPTS {
            let lines = repeat_hint_lines(script, 30, Trust::Counted, crate::manifest::MANIFEST);
            assert!(lines[0].chars().count() + 2 <= 80, "{}", lines[0]);
            assert!(lines[0].contains("a repeat if the root runs them"));
            assert!(
                lines[1].contains(&format!("set rootRunsMembers {script}")),
                "{}",
                lines[1]
            );
            for line in &lines[1..] {
                assert!(line.chars().count() <= 80, "{line}");
            }
        }
        let one = repeat_hint_lines("test", 1, Trust::Counted, crate::manifest::MANIFEST);
        assert!(one[0].contains("in 1 package —"), "{}", one[0]);
        let withheld = repeat_hint_lines("test", 2, Trust::Withheld, crate::manifest::MANIFEST);
        assert!(withheld[1].contains("is not trusted"), "{}", withheld[1]);
        assert!(withheld[2].contains("trust"), "{}", withheld[2]);
        for line in &withheld[1..] {
            assert!(line.chars().count() <= 80, "{line}");
            assert!(!line.contains("declare it in"), "{line}");
        }
    }

    /// The summary line keeps its count and its cause on a terminal, for every
    /// script the gate runs, and cuts only the command.
    #[test]
    fn the_skip_summary_fits_its_line() {
        for script in crate::manifest::NPM_GATE_SCRIPTS {
            // A count of any width still fits: three digits cost a column.
            for count in [1, 30, 100, 1000] {
                let line = skip_summary_line(
                    crate::manifest::MANIFEST,
                    count,
                    script,
                    Some("pnpm -r test"),
                    LineWidth::Cut,
                );
                assert!(line.chars().count() <= LINE_COLUMNS, "{line}");
            }
            let head =
                skip_summary_line(crate::manifest::MANIFEST, 30, script, None, LineWidth::Cut);
            assert!(head.chars().count() <= 80, "{head}");
            assert!(head.contains("30 packages skipped"), "{head}");
            let cut = skip_summary_line(
                crate::manifest::MANIFEST,
                30,
                script,
                Some(&"x".repeat(200)),
                LineWidth::Cut,
            );
            assert!(cut.chars().count() <= 80, "{cut}");
            assert!(cut.contains("covered by the root's"), "{cut}");
            // Every gate script's head leaves no room for the command, so the
            // marker branch is the one taken.
            assert!(cut.ends_with(": …"), "{cut}");
        }
        assert!(
            skip_summary_line(crate::manifest::MANIFEST, 1, "test", None, LineWidth::Whole)
                .starts_with("1 package skipped")
        );
    }

    /// The warning sign and the space after it.
    const SIGN_COLUMNS: usize = 2;

    /// A non-object top-level `scripts` answers "no scripts"; a nested
    /// `scripts` key later in the file never stands in for it.
    #[test]
    fn a_non_object_scripts_key_is_not_replaced_by_a_nested_one() {
        let pkg = r#"{"scripts":"none","other":{"scripts":{"test":"x"}}}"#;
        assert_eq!(scripts_object(pkg), None);
        assert!(!defines_script(pkg, "test"));
    }

    /// The unreadable-workspace lines fit 80 columns, the first with its sign,
    /// and name the file read.
    #[test]
    fn the_unreadable_workspace_lines_fit_and_name_the_file() {
        for file in ["package.json", "pnpm-workspace.yaml"] {
            let lines = unreadable_workspace_lines(file);
            assert!(
                lines[0].chars().count() + SIGN_COLUMNS <= LINE_COLUMNS,
                "{}",
                lines[0]
            );
            assert!(lines[1].chars().count() <= LINE_COLUMNS, "{}", lines[1]);
            assert!(lines[1].contains(file), "{}", lines[1]);
        }
    }

    /// The announcement counts a run, names its place, and sanitises the folder.
    #[test]
    fn the_announcement_names_its_place() {
        assert_eq!(
            announcement_line("test", 1, 3, ""),
            "npm run test: 1 of 3, in the root"
        );
        assert_eq!(
            announcement_line("test", 2, 3, "packages/a"),
            "npm run test: 2 of 3, in packages/a"
        );
        assert!(!announcement_line("test", 2, 3, "a\u{1b}[31mb").contains('\u{1b}'));
    }

    /// A local `git config` is held to the committed line: it removes names or
    /// sets `none`, and never adds one.
    #[test]
    fn a_local_value_only_removes_what_is_committed() {
        use RootDeclaration::{Declared, Unset};
        assert_eq!(
            declared_from(Some("test,typecheck"), Some("test")),
            Declared(vec!["test"])
        );
        assert_eq!(declared_from(Some("test"), Some("none")), Declared(vec![]));
        assert_eq!(declared_from(Some("none"), Some("test")), Declared(vec![]));
        assert_eq!(declared_from(None, Some("none")), Declared(vec![]));
        assert_eq!(declared_from(None, Some("test")), Unset);
        assert_eq!(declared_from(None, None), Unset);
        assert_eq!(declared_from(Some("test"), None), Declared(vec!["test"]));
        assert_eq!(
            declared_from(Some("test,bogus"), None),
            Declared(vec!["test"])
        );
    }

    /// Only the root's scripts that are declared cover members.
    #[test]
    fn only_declared_root_scripts_cover() {
        let declared = RootDeclaration::Declared(vec!["test"]);
        assert_eq!(
            covering_scripts(&["test", "typecheck"], &declared),
            vec!["test"]
        );
        assert!(covering_scripts(&["test"], &RootDeclaration::Unset).is_empty());
    }

    /// Nothing declared reads as unset.
    #[test]
    fn nothing_declared_is_unset() {
        let settings = crate::config::Settings::default();
        assert_eq!(root_declaration(&settings), RootDeclaration::Unset);
    }
}