trusty-common 0.49.0

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Drift guards for the canonical launchd-label registry (#4919).
//!
//! Why: the registry only helps if nothing outside it writes a launchd label.
//! #2827 was fixed by correcting one literal, and the same class of defect came
//! straight back somewhere else because nothing stopped the next literal from
//! being typed. These tests are that stop.

use super::*;

/// Why: a `SERVICES` entry could restate a label the convention would never
/// produce — which is exactly how `com.trusty.trusty-search` survived. The
/// convention has to be checkable, not merely documented.
/// What: every main-daemon entry's `label` must equal `canonical_label(member)`.
/// #6290: retired rows are held to the same rule — a retirement moves a row
/// between tables, so its label must still be the one that is actually loaded
/// on a host, or the eviction boots out a unit that does not exist.
/// Test: this is the test.
#[test]
fn canonical_consts_match_the_convention() {
    for svc in SERVICES.iter().chain(RETIRED_SERVICES) {
        if svc.sub_unit.is_some() {
            continue;
        }
        assert_eq!(
            svc.label,
            canonical_label(svc.member),
            "{}'s label restates something the `com.trusty.<stem>` convention \
             does not produce — either the convention changed (update \
             `canonical_label`) or the literal drifted (#4919)",
            svc.member
        );
    }
}

/// Why: a sub-unit whose label does not extend its member's base label is a
/// unit an upgrade will orphan — `com.trusty.trusty-search.logrotate` outlived
/// the main unit it was named after and is still loaded on the owner's host.
/// What: every sub-unit entry's label must be `<base>.<sub_unit>`, where base
/// is that member's own main-daemon label.
/// Test: this is the test.
#[test]
fn sub_unit_labels_extend_their_base() {
    for svc in SERVICES {
        let Some(sub) = svc.sub_unit else { continue };
        let base = canonical_label(svc.member);
        assert_eq!(
            svc.label,
            sub_label(&base, sub),
            "{}'s `{sub}` sub-unit must be named off its member's base label",
            svc.member
        );
    }
}

/// Why: listing a still-canonical label as legacy makes an install evict the
/// unit it just bootstrapped — a self-inflicted outage, which is half of what
/// #4919 is about.
/// What: no legacy alias may equal any service's canonical label.
/// Test: this is the test.
#[test]
fn legacy_labels_are_never_canonical() {
    for svc in SERVICES {
        for legacy in svc.legacy {
            assert!(
                service_for_label(legacy).is_none(),
                "{legacy} is listed as a legacy alias of {} but is also some \
                 service's canonical label — evicting it would take down a \
                 live unit",
                svc.label
            );
        }
    }
}

/// Why: two services claiming the same legacy alias means an install of either
/// one boots out the other's unit.
/// What: every canonical label is unique, and no legacy alias appears twice.
/// Test: this is the test.
#[test]
fn every_legacy_label_resolves_to_one_service() {
    let mut seen: Vec<&str> = Vec::new();
    // #6290: across BOTH tables. A retired label colliding with a live one is
    // the worst version of this — an install would evict the unit it is about
    // to need.
    for svc in SERVICES.iter().chain(RETIRED_SERVICES) {
        for label in std::iter::once(&svc.label).chain(svc.legacy.iter()) {
            assert!(
                !seen.contains(label),
                "{label} is claimed by more than one service"
            );
            seen.push(label);
        }
    }
}

/// Why (#6290): the two tables answer opposite questions — what an install
/// WRITES versus what an upgrade CLEARS — and a row that appeared in both would
/// have an install bootstrap a unit and then boot it out, or the reverse,
/// depending on step order.
/// What: no retired member appears in `SERVICES`, and `RETIRED_SERVICES` names
/// exactly the members whose daemon has been retired.
/// Test: this is the test.
#[test]
fn retired_services_are_not_installed() {
    for retired in RETIRED_SERVICES {
        assert!(
            !SERVICES.iter().any(|s| s.member == retired.member),
            "{} is retired but still listed as a service an install writes",
            retired.member
        );
        assert!(
            retired_service_for_member(retired.member).is_some(),
            "{} must be reachable by member lookup, or nothing can evict it",
            retired.member
        );
    }
    let members: Vec<&str> = RETIRED_SERVICES.iter().map(|s| s.member).collect();
    assert_eq!(
        members,
        vec!["trusty-review", "trusty-analyze"],
        "adding a retirement is a deliberate act — update this pin with it"
    );
}

/// Why (#6290): trusty-review's unit exists under two names on real hosts —
/// `com.trusty.review` from the post-#4919 installer and
/// `com.trusty.trusty-review` from before it. An eviction that clears only one
/// leaves the other loaded, respawning a `serve` subcommand the binary no
/// longer has, which is a crash loop with nothing in the log but a usage
/// message.
/// What: both labels come back from `retired_labels_for_member`, canonical
/// first, and a live member yields nothing.
/// Test: this is the test.
#[test]
fn retired_review_carries_both_its_labels() {
    let labels = retired_labels_for_member("trusty-review");
    assert_eq!(labels, vec![REVIEW, "com.trusty.trusty-review"]);
    assert!(
        retired_labels_for_member("trusty-search").is_empty(),
        "a live member has nothing to evict"
    );
    assert!(
        legacy_labels_for(REVIEW).contains(&"com.trusty.trusty-review"),
        "the retired row's legacy alias must still resolve through the label lookup"
    );
}

/// Why: the pre-#4919 labels must stay recorded as legacy or an upgrade from a
/// host installed before this fix silently leaves the old unit running beside
/// the new one — #2938's exact footgun, two daemons on :7878.
/// What: pins the specific aliases the divergent sites used.
/// Test: this is the test.
#[test]
fn pre_fix_labels_are_recorded_as_legacy() {
    assert!(
        legacy_labels_for(SEARCH).contains(&"com.trusty.trusty-search"),
        "the label `trusty-search service install` wrote before #4919 must be \
         evicted on upgrade"
    );
    assert!(
        legacy_labels_for(SEARCH).contains(&"com.bobmatnyc.trusty-search"),
        "the trusty-search Makefile's `com.bobmatnyc.*` family must be evicted \
         on upgrade"
    );
    assert!(legacy_labels_for(CONSOLE).contains(&"com.trusty.trusty-console"));
    assert!(legacy_labels_for(REVIEW).contains(&"com.trusty.trusty-review"));
    assert!(legacy_labels_for(SEARCH_LOGROTATE).contains(&"com.trusty.trusty-search.logrotate"));
}

/// Directories whose launchd-label literals are legitimately outside the
/// registry.
///
/// `macos_signing` mints CODESIGN identifiers, a different namespace that uses
/// the full binary name on purpose — renaming one invalidates the binary's
/// designated requirement and re-triggers macOS TCC prompts (#2558). It must
/// not be normalised onto the launchd convention.
const SCAN_EXEMPT_PATHS: &[&str] = &["trusty-installer/src/commands/macos_signing"];

/// Why (#4919, and #2827 before it): every re-fix so far corrected one literal
/// and left the mechanism that mints them intact, so a new divergent literal
/// appeared somewhere else — the installer's mirror table, a Makefile, a shell
/// hint. This scans the production sources for launchd-label literals and
/// fails on any the registry does not own, so the third recurrence cannot
/// merge.
///
/// What: walks every workspace member's `src/**.rs` plus the build and deploy
/// files a label can hide in (`Makefile`, `*.sh`, `*.plist`, `*.yml`), strips
/// each Rust file's inline test module (test fixtures deliberately name drifted
/// labels that exist on other hosts) and every comment, extracts
/// `com.trusty.*` / `com.bobmatnyc.*` tokens, and reports each one. Legacy
/// aliases are rejected everywhere. In Rust a CANONICAL label typed as a
/// literal is rejected too — a correct-but-duplicated literal is the state
/// trusty-search's label was in before it drifted, and Rust has the registry.
/// A Makefile, shell script or plist cannot import a Rust constant, so it may
/// name the canonical label; a legacy or unknown one still fails.
/// Test: this is the test.
#[test]
fn no_stray_launchd_label_literals_in_workspace_sources() {
    let root = workspace_root();
    let mut files = Vec::new();
    collect_scannable_files(&root, &mut files);

    let rs = files.iter().filter(|p| kind_of(p) == Kind::Rust).count();
    let other = files.len() - rs;
    assert!(
        rs > 2000 && other > 20,
        "the scan found {rs} Rust and {other} build/deploy file(s) under {} — a \
         broken walk would pass this test vacuously",
        root.display()
    );

    let mut strays: Vec<String> = Vec::new();
    for path in &files {
        let rel = path
            .strip_prefix(&root)
            .unwrap_or(path)
            .display()
            .to_string();
        if SCAN_EXEMPT_PATHS.iter().any(|ex| rel.contains(ex)) {
            continue;
        }
        // The registry is where the literals are SUPPOSED to live.
        if rel.contains("trusty-common/src/launchd_labels") {
            continue;
        }
        let Ok(body) = std::fs::read_to_string(path) else {
            continue;
        };
        strays.extend(strays_in(&rel, kind_of(path), &body));
    }

    assert!(
        strays.is_empty(),
        "launchd label literals not owned by `trusty_common::launchd_labels` \
         (#4919 — derive them from the registry instead of restating them).\n\
         CHECK THE NAMESPACE FIRST (#5438): a CODESIGN identifier is not a launchd \
         label. Codesign identifiers keep the full binary name on purpose \
         (`com.trusty.trusty-memory`, not `com.trusty.memory`) and must NEVER be \
         renamed onto the registry's convention — that invalidates the binary's \
         designated requirement and re-triggers macOS TCC prompts (#2558). Bind one \
         to a `readonly <NAME>_IDENTIFIER=` constant instead, which is the naming \
         `codesign_stripped` exempts and \
         `codesign_scripts_name_identifiers_by_convention` enforces. In a plist the \
         same split runs off the KEY (#6540): launchd reads a job label from \
         `<key>Label</key>` and nowhere else, so a `CFBundleIdentifier` value is \
         already exempt — a hit under any other key is a real launchd label.\n  \
         {}",
        strays.join("\n  ")
    );
}

/// Every launchd-label literal in one file's body that the registry does not
/// own, formatted as the scan reports it.
///
/// Why: the scan's per-file decision is also what the namespace regressions need
/// to assert against, so both read the same code rather than an approximation of
/// it.
/// What: comment-stripped lines, minus the codesign identifier token and — for a
/// plist — the bundle-identifier values, then every remaining `com.trusty.*` /
/// `com.bobmatnyc.*` token that is neither an evicted legacy alias nor a
/// canonical label a non-Rust file is allowed to name.
/// Test: `no_stray_launchd_label_literals_in_workspace_sources`,
/// `plist_bundle_identifier_is_not_a_launchd_label`,
/// `plist_label_key_value_is_still_a_stray`.
fn strays_in(rel: &str, kind: Kind, body: &str) -> Vec<String> {
    let mut lines = production_lines(body, kind);
    if kind == Kind::Xml {
        // #6540: a plist's bundle identifier is the codesign namespace.
        lines = bundle_identifier_stripped(lines);
    }
    let mut out = Vec::new();
    for line in lines {
        // Naming a legacy label in order to EVICT it is the one correct use of
        // one. A `launchctl bootout`/`unload` line in a build file is doing
        // exactly the migration this issue is about; the bug is naming a legacy
        // label to install, load, or point a user at.
        let evicting = kind != Kind::Rust && (line.contains("bootout") || line.contains("unload"));
        for label in extract_labels(&codesign_stripped(&line)) {
            if evicting && legacy_labels_for_any().contains(&label.as_str()) {
                continue;
            }
            // A Makefile, shell script or plist cannot import a Rust constant,
            // so naming the CANONICAL label is the best it can do. What it must
            // never carry is a legacy or unknown label — that is what
            // `com.bobmatnyc.trusty-search` was. Rust has no such excuse: it
            // gets the registry, so any literal is a stray.
            if kind != Kind::Rust && is_canonical_label(&label) {
                continue;
            }
            out.push(format!("{rel}: {label}"));
        }
    }
    out
}

/// Plist keys whose `<string>` value is a BUNDLE identifier, never a launchd
/// job label.
///
/// launchd reads a job's label from `Label` and from no other key. A
/// `CFBundleIdentifier` names a bundle to codesign, `defaults`, and `os_log`;
/// `TrustyConsole.saver` carries one and is loaded by legacyScreenSaver, so it
/// is not a launchd job at all (#6540).
const PLIST_BUNDLE_IDENTIFIER_KEYS: &[&str] = &["CFBundleIdentifier"];

/// Blank out the `<string>` value belonging to a bundle-identifier `<key>`.
///
/// Why (#6540, and #5438 before it): the scan read `TrustyConsole.saver`'s
/// `CFBundleIdentifier` as a stray launchd label and told the reader to derive
/// it from the registry — the one edit that invalidates the bundle's designated
/// requirement and re-triggers macOS TCC prompts (#2558). `codesign_stripped`
/// classifies a shell line by an adjacent marker; a plist needs the same
/// distinction drawn from its key.
///
/// What: takes plist lines in order and empties the body of the `<string>`
/// element that follows a `PLIST_BUNDLE_IDENTIFIER_KEYS` key, whether the two
/// share a line or not. Any other `<key>` clears the pending state, so only the
/// bundle identifier's own value is exempt — a `<key>Label</key>` value is left
/// for the scan.
/// Test: `plist_bundle_identifier_is_not_a_launchd_label`,
/// `plist_label_key_value_is_still_a_stray`,
/// `bundle_identifier_stripped_spares_a_label_on_the_same_line`.
fn bundle_identifier_stripped(lines: Vec<String>) -> Vec<String> {
    let mut out: Vec<String> = Vec::with_capacity(lines.len());
    let mut awaiting_value = false;
    for line in lines {
        let key_end = PLIST_BUNDLE_IDENTIFIER_KEYS.iter().find_map(|k| {
            let marker = format!("<key>{k}</key>");
            line.find(&marker).map(|i| i + marker.len())
        });
        match key_end {
            Some(end) if line[end..].contains("<string>") => {
                awaiting_value = false;
                out.push(blank_plist_string(&line, end));
            }
            Some(_) => {
                awaiting_value = true;
                out.push(line);
            }
            None if awaiting_value && line.contains("<string>") => {
                awaiting_value = false;
                out.push(blank_plist_string(&line, 0));
            }
            None => {
                // Another key ends the pending value; a malformed plist must not
                // carry the exemption forward onto an unrelated string.
                if line.contains("<key>") {
                    awaiting_value = false;
                }
                out.push(line);
            }
        }
    }
    out
}

/// Empty the body of the first `<string>…</string>` element at or after `from`.
///
/// Returns the line unchanged when the element is absent or unterminated —
/// failing CLOSED, so an unrecognised shape stays scanned.
fn blank_plist_string(line: &str, from: usize) -> String {
    const OPEN: &str = "<string>";
    const CLOSE: &str = "</string>";
    let Some(open) = line[from..].find(OPEN).map(|i| from + i + OPEN.len()) else {
        return line.to_string();
    };
    let Some(close) = line[open..].find(CLOSE).map(|i| open + i) else {
        return line.to_string();
    };
    let mut out = line.to_string();
    out.replace_range(open..close, "");
    out
}

/// REGRESSION (#6540): a `.saver` bundle's `CFBundleIdentifier` is not a launchd
/// label.
///
/// Why: `TrustyConsole.saver`'s `Info.plist` turned `cargo test -p trusty-common`
/// red on `main` and blocked every release, and the advice the failure printed —
/// derive it from the registry — would have broken the bundle's signature
/// (#2558). This is the shape that failed.
/// Test: this is the test.
#[test]
fn plist_bundle_identifier_is_not_a_launchd_label() {
    let body = "<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleIdentifier</key>\n\
                \t<string>com.trusty.console.saver</string>\n\
                \t<key>CFBundleName</key>\n\t<string>TrustyConsole</string>\n\
                </dict>\n</plist>\n";
    let found = strays_in("crates/x/macos/saver/Info.plist", Kind::Xml, body);
    assert!(
        found.is_empty(),
        "a CFBundleIdentifier is the codesign namespace, not a launchd label: {found:?}"
    );

    // The same value under no key at all is still read as a stray, so the
    // exemption is the KEY and not the string.
    let bare = strays_in(
        "crates/x/macos/saver/Info.plist",
        Kind::Xml,
        "<string>com.trusty.console.saver</string>\n",
    );
    assert_eq!(
        bare,
        vec!["crates/x/macos/saver/Info.plist: com.trusty.console.saver".to_string()],
        "only a bundle-identifier key earns the exemption"
    );
}

/// Why: the exemption must not cost the scan its reason to exist — `Label` is
/// the key launchd actually reads, and an unregistered label under it is exactly
/// the drift #4919 was filed for.
/// Test: this is the test.
#[test]
fn plist_label_key_value_is_still_a_stray() {
    let body = "\t<key>Label</key>\n\t<string>com.trusty.fixture-unregistered</string>\n";
    assert_eq!(
        strays_in("deploy/x.plist", Kind::Xml, body),
        vec!["deploy/x.plist: com.trusty.fixture-unregistered".to_string()],
        "a Label value must stay scanned"
    );

    // A bundle-identifier key does not carry its exemption onto the next key's
    // value.
    let after = "\t<key>CFBundleIdentifier</key>\n\t<key>Label</key>\n\
                 \t<string>com.trusty.fixture-unregistered</string>\n";
    assert_eq!(
        strays_in("deploy/x.plist", Kind::Xml, after).len(),
        1,
        "the pending exemption must end at the next key"
    );
}

/// Why (mirrors `codesign_stripped_spares_only_the_identifier_token`): a
/// whole-line skip would hide a real label that shares the line.
/// Test: this is the test.
#[test]
fn bundle_identifier_stripped_spares_a_label_on_the_same_line() {
    let line = "<key>CFBundleIdentifier</key><string>com.trusty.console.saver</string>\
                <key>Label</key><string>com.trusty.fixture-unregistered</string>";
    let out = bundle_identifier_stripped(vec![line.to_string()]).remove(0);
    assert!(
        !out.contains("com.trusty.console.saver"),
        "the bundle identifier must be exempt, got: {out}"
    );
    assert!(
        out.contains("com.trusty.fixture-unregistered"),
        "a launchd label on the same line must still be scanned, got: {out}"
    );
}

/// What sort of file is being scanned, which decides its comment syntax and
/// whether it has an inline test module to strip.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    /// Rust source: `//` comments, and an inline `#[cfg(test)] mod tests { … }`
    /// to strip.
    Rust,
    /// Makefile / shell / YAML: `#` comments, no test module.
    Hash,
    /// XML property list: `<!-- -->` comments, no test module.
    Xml,
}

/// Lines of a file that carry executable meaning — comments stripped, and for
/// Rust, the inline test module removed.
///
/// Why: comments legitimately discuss a legacy label (this module's own header
/// does), and test fixtures deliberately name drifted labels that exist on other
/// hosts, such as `launchd_probe`'s `com.trusty.mpm.dogfood`. Scanning either
/// would force them to lie.
///
/// #4919 review: the first version used `take_while`, so the scan STOPPED at the
/// first `#[cfg(test)]`-ish line. In a `mod.rs` that declaration sits near the
/// top among the module list, so the entire production body below it went
/// unscanned — a literal planted at line 301 of
/// `trusty-mpm/src/services/discoverer/mod.rs` passed. It now SKIPS the test
/// item and keeps going: a bare `mod tests;` declaration costs one line, and a
/// `mod tests { … }` block is skipped by brace balance.
///
/// What: yields owned lines with comment text removed. A line whose code part
/// is empty is dropped.
/// Test: `production_lines_skips_past_a_test_module_declaration`,
/// `production_lines_strips_an_inline_test_block`,
/// `production_lines_keeps_a_feature_cfg_that_merely_contains_test`.
fn production_lines(body: &str, kind: Kind) -> Vec<String> {
    let mut out = Vec::new();
    let mut lines = body.lines().peekable();
    let mut in_block_comment = false;
    while let Some(line) = lines.next() {
        if kind == Kind::Rust && !in_block_comment && is_test_cfg_attribute(line) {
            skip_test_item(line, &mut lines);
            continue;
        }
        let code = strip_comment(line, kind, &mut in_block_comment);
        if !code.trim().is_empty() {
            out.push(code);
        }
    }
    out
}

/// Whether a line is a `#[cfg(…)]` attribute gating on the `test` cfg.
///
/// Whether a `#[cfg(…)]` attribute gates code that exists ONLY under `cfg(test)`.
///
/// Why: three separate ways to get this wrong, each of which silences the scan
/// over production code.
///
/// 1. A substring match for `test` fires on
///    `#[cfg(feature = "embedder-test-support")]`, which gates production code.
/// 2. #4919 review: POLARITY. `#[cfg(not(test))]` gates code that exists in
///    every NON-test build — the most production a thing can be — and
///    `#[cfg(any(…, test))]` gates code that exists in test builds AND others.
///    Treating either as "a test item" made `skip_test_item` swallow exactly
///    the code it was supposed to read. Literals planted inside
///    `#[cfg(not(test))] fn cache_base_dir()` and an `any(…, test)` function
///    both passed the guard; eight such sites exist in this workspace.
/// 3. `all(test, …)` IS test-only, because every conjunct must hold.
///
/// What: true only when a standalone `test` token appears outside any `not(…)`
/// and outside any `any(…)`. Everything else is production.
/// Test: `production_lines_keeps_a_feature_cfg_that_merely_contains_test`,
/// `is_test_cfg_attribute_respects_polarity`.
fn is_test_cfg_attribute(line: &str) -> bool {
    let t = line.trim_start();
    if !t.starts_with("#[cfg(") {
        return false;
    }
    let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
    let mut rest = t;
    while let Some(idx) = rest.find("test") {
        let before = &rest[..idx];
        let before_ok = before.chars().next_back().is_none_or(|c| !is_ident(c));
        let after_ok = rest[idx + 4..].chars().next().is_none_or(|c| !is_ident(c));
        // A standalone `test` still does not make the item test-only if it sits
        // under a `not(` or an `any(` that is still open at this point.
        if before_ok && after_ok && !under_negation_or_disjunction(before) {
            return true;
        }
        rest = &rest[idx + 4..];
    }
    false
}

/// Whether the text preceding a `test` token leaves a `not(` or `any(` open.
///
/// What: walks the prefix tracking parenthesis depth, recording the depth at
/// which each `not(` / `any(` opened, and reports whether any such combinator
/// is still unclosed at the end of the prefix.
fn under_negation_or_disjunction(prefix: &str) -> bool {
    let bytes = prefix.as_bytes();
    let mut depth: i32 = 0;
    let mut open_combinators: Vec<i32> = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'(' {
            let head = prefix[..i].trim_end();
            if head.ends_with("not") || head.ends_with("any") {
                open_combinators.push(depth);
            }
            depth += 1;
        } else if bytes[i] == b')' {
            depth -= 1;
            open_combinators.retain(|d| *d < depth);
        }
        i += 1;
    }
    !open_combinators.is_empty()
}

/// Consume the item a `#[cfg(test)]` attribute applies to.
///
/// Why (#4919 review): `#[cfg(test)] use std::fmt;` puts the attribute and the
/// item on ONE line. Unconditionally consuming from the NEXT line therefore ate
/// a line of production code — a literal planted there passed the guard.
///
/// What: returns immediately when the attribute line already carries its whole
/// item (a `;`-terminated statement, or braces that balance on that line).
/// Otherwise a declaration ending in `;` costs one line and a braced item is
/// consumed until its braces balance.
/// Test: `skip_test_item_consumes_nothing_when_the_item_is_on_the_attribute_line`.
fn skip_test_item<'a>(
    attr_line: &str,
    lines: &mut std::iter::Peekable<impl Iterator<Item = &'a str>>,
) {
    // Everything after the closing `]` of the attribute, if anything.
    let tail = attr_line
        .rsplit_once("])")
        .map_or_else(|| attr_line.rsplit_once(']').map(|(_, t)| t), |_| None)
        .unwrap_or("")
        .trim();
    if !tail.is_empty() {
        let opens = tail.matches('{').count();
        let closes = tail.matches('}').count();
        if tail.ends_with(';') || (opens > 0 && opens == closes) {
            return;
        }
        if opens > closes {
            consume_until_balanced(lines, i32::try_from(opens - closes).unwrap_or(1));
            return;
        }
    }

    let mut depth: i32 = 0;
    let mut opened = false;
    for line in lines.by_ref() {
        depth += i32::try_from(line.matches('{').count()).unwrap_or(0);
        depth -= i32::try_from(line.matches('}').count()).unwrap_or(0);
        if line.contains('{') {
            opened = true;
        }
        if opened {
            if depth <= 0 {
                return;
            }
        } else if line.trim_end().ends_with(';') {
            return;
        }
    }
}

/// Consume lines until an already-open brace nesting closes.
fn consume_until_balanced<'a>(
    lines: &mut std::iter::Peekable<impl Iterator<Item = &'a str>>,
    mut depth: i32,
) {
    for line in lines.by_ref() {
        depth += i32::try_from(line.matches('{').count()).unwrap_or(0);
        depth -= i32::try_from(line.matches('}').count()).unwrap_or(0);
        if depth <= 0 {
            return;
        }
    }
}

/// Remove the comment portion of a line for the given file kind.
///
/// Why (#4919 review): the Rust arm used to blank any line whose trimmed start
/// was `*`, as a proxy for "inside a block comment". That also blanked a deref
/// assignment — `*target = "com.trusty.trusty-search".to_string();` passed the
/// guard while the identical `let` form failed. Block-comment state is now
/// tracked across lines instead of guessed at from one.
///
/// What: `in_block_comment` carries `/* … */` state between calls. A line
/// inside a block comment, or a `//`-prefixed line, yields empty. Note that a
/// continuation line of a multi-line Rust STRING literal carries no quote of
/// its own, so quote-presence is not usable as a filter — that is how the
/// `com.trusty.mpm.plist` hints in `daemon_bridge` and `serve_stdio` (the #2827
/// defect class) initially escaped this scan.
/// Test: `strip_comment_keeps_a_deref_assignment`,
/// `strip_comment_tracks_block_comment_state`.
fn strip_comment(line: &str, kind: Kind, in_block_comment: &mut bool) -> String {
    let t = line.trim_start();
    match kind {
        Kind::Rust => {
            if *in_block_comment {
                // The comment ends here; anything after `*/` is code again.
                if let Some((_, after)) = line.split_once("*/") {
                    *in_block_comment = false;
                    return after.to_string();
                }
                return String::new();
            }
            if t.starts_with("//") {
                return String::new();
            }
            if let Some((before, rest)) = line.split_once("/*") {
                if let Some((_, after)) = rest.split_once("*/") {
                    return format!("{before}{after}");
                }
                *in_block_comment = true;
                return before.to_string();
            }
            line.to_string()
        }
        Kind::Hash => line.split('#').next().unwrap_or("").to_string(),
        Kind::Xml => {
            if t.starts_with("<!--") {
                String::new()
            } else {
                line.to_string()
            }
        }
    }
}

/// Classify a path by the comment syntax it uses.
fn kind_of(path: &std::path::Path) -> Kind {
    let name = path.file_name().unwrap_or_default().to_string_lossy();
    if name.ends_with(".rs") {
        Kind::Rust
    } else if name.ends_with(".plist") {
        Kind::Xml
    } else {
        Kind::Hash
    }
}

/// Resolve the workspace root from this crate's manifest directory.
fn workspace_root() -> std::path::PathBuf {
    std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .ancestors()
        .nth(2)
        .expect("crates/trusty-common has a workspace root two levels up")
        .to_path_buf()
}

/// Recursively collect the files the label scan covers.
///
/// Why (#4919 review): scanning `crates/**/src/**.rs` alone left the two file
/// types the last recurrence actually lived in unguarded — the per-crate
/// `Makefile`s carried the `com.bobmatnyc.*` family and
/// `scripts/install-trusty-search-signed.sh` carried the inverted hint. A guard
/// that cannot see where the bug was is not a guard.
///
/// What: every `.rs` under a crate `src/` tree, plus every `Makefile`, `*.sh`,
/// `*.plist` and `*.yml` in the repository. Dedicated test/bench trees and
/// `docs/` are skipped — their fixtures and research notes name drifted labels
/// deliberately.
fn collect_scannable_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if path.is_dir() {
            if matches!(
                name.as_ref(),
                "target"
                    | "tests"
                    | "benches"
                    | "node_modules"
                    | "docs"
                    | ".git"
                    | ".claude"
                    | "test-data"
                    | "testdata"
                    | "vmtest-harness"
            ) {
                continue;
            }
            collect_scannable_files(&path, out);
            continue;
        }
        let is_rust = name.ends_with(".rs")
            && !name.ends_with("_tests.rs")
            && !name.ends_with("_test.rs")
            && name != "tests.rs";
        let is_build_or_deploy = name == "Makefile"
            || name.ends_with(".sh")
            || name.ends_with(".plist")
            || name.ends_with(".yml");
        if is_rust || is_build_or_deploy {
            out.push(path);
        }
    }
}

/// Why (#4919 review): the first `production_lines` used `take_while`, so a
/// `mod tests;` declaration near the top of a `mod.rs` terminated the scan and
/// everything below it went unread — 342 of 2847 files lost more than half
/// their body, many after ~15 lines. A planted literal at line 301 of
/// `trusty-mpm/src/services/discoverer/mod.rs` passed.
/// What: a declaration costs one line and scanning continues past it.
/// Test: this is the test.
#[test]
fn production_lines_skips_past_a_test_module_declaration() {
    let body = "pub mod a;\n#[cfg(test)]\nmod tests;\npub mod b;\nlet x = \"deep\";\n";
    let kept = production_lines(body, Kind::Rust);
    assert!(
        kept.iter().any(|l| l.contains("deep")),
        "code below a `mod tests;` declaration must still be scanned, kept: {kept:?}"
    );
    assert!(!kept.iter().any(|l| l.contains("mod tests;")));
}

/// Why: an inline test module names drifted labels on purpose, so it must be
/// skipped — but only as far as its closing brace.
/// What: the block body is dropped and code after it is kept.
/// Test: this is the test.
#[test]
fn production_lines_strips_an_inline_test_block() {
    let body = "fn real() {}\n#[cfg(all(test, target_os = \"macos\"))]\nmod tests {\n    let f = \"com.trusty.trusty-fixture\";\n}\nfn after() {}\n";
    let kept = production_lines(body, Kind::Rust);
    assert!(!kept.iter().any(|l| l.contains("trusty-fixture")));
    assert!(
        kept.iter().any(|l| l.contains("fn after")),
        "code after the test block must survive, kept: {kept:?}"
    );
}

/// Why: a substring check for `test` also fires on
/// `#[cfg(feature = "embedder-test-support")]`, which gates PRODUCTION code.
/// Skipping the item it guards would reopen the hole the fix closes.
/// What: only a standalone `test` cfg token counts.
/// Test: this is the test.
#[test]
fn production_lines_keeps_a_feature_cfg_that_merely_contains_test() {
    assert!(!is_test_cfg_attribute(
        "#[cfg(feature = \"embedder-test-support\")]"
    ));
    assert!(is_test_cfg_attribute("#[cfg(test)]"));
    assert!(is_test_cfg_attribute(
        "#[cfg(all(test, target_os = \"macos\"))]"
    ));

    let body = "#[cfg(feature = \"embedder-test-support\")]\npub fn kept() {}\n";
    let kept = production_lines(body, Kind::Rust);
    assert!(
        kept.iter().any(|l| l.contains("pub fn kept")),
        "a feature cfg must not swallow the item it guards, kept: {kept:?}"
    );
}

/// Why: Makefiles and shell scripts are where two of the divergent sites lived,
/// and their comments legitimately narrate the old labels.
/// What: `#` comments are stripped, code is kept.
/// Test: this is the test.
#[test]
fn production_lines_strips_hash_comments() {
    let body = "# was com.trusty.trusty-search\nPLIST := com.trusty.search.plist\n";
    let kept = production_lines(body, Kind::Hash);
    assert_eq!(kept.len(), 1);
    assert!(kept[0].contains("com.trusty.search"));
}

/// Why (#4919 review, round 2): POLARITY. `#[cfg(not(test))]` gates code that
/// exists in every non-test build, and `#[cfg(any(…, test))]` gates code that
/// exists in test builds AND others — both are PRODUCTION. Treating them as
/// test items made the scan skip exactly what it should read; literals planted
/// inside a `not(test)` function and an `any(…, test)` function both passed.
/// Eight such sites exist in this workspace.
/// What: `test` under `not(…)` or `any(…)` is production; bare `test` and
/// `all(test, …)` are test-only.
/// Test: this is the test.
#[test]
fn is_test_cfg_attribute_respects_polarity() {
    assert!(is_test_cfg_attribute("#[cfg(test)]"));
    assert!(is_test_cfg_attribute(
        "#[cfg(all(test, target_os = \"macos\"))]"
    ));

    assert!(
        !is_test_cfg_attribute("#[cfg(not(test))]"),
        "`not(test)` gates code present in every non-test build"
    );
    assert!(
        !is_test_cfg_attribute(
            "#[cfg(any(all(target_os = \"macos\", target_arch = \"aarch64\"), test))]"
        ),
        "`any(…, test)` gates code present outside test builds too"
    );
    assert!(!is_test_cfg_attribute("#[cfg(all(not(test), unix))]"));
}

/// Why: the polarity fix only matters if the scan actually reads the body it
/// stops skipping.
/// What: a literal inside a `#[cfg(not(test))]` function is retained.
/// Test: this is the test.
#[test]
fn production_lines_reads_bodies_gated_on_not_test() {
    let body =
        "#[cfg(not(test))]\nfn cache_base_dir() {\n    let x = \"com.trusty.trusty-search\";\n}\n";
    let kept = production_lines(body, Kind::Rust);
    assert!(
        kept.iter().any(|l| l.contains("com.trusty.trusty-search")),
        "a `not(test)` body is production and must be scanned, kept: {kept:?}"
    );
}

/// Why (#4919 review, round 2): `strip_comment` blanked any line whose trimmed
/// start was `*`, as a proxy for "inside a block comment". A deref assignment
/// starts with `*` too, so `*target = "com.trusty.trusty-search".to_string();`
/// passed the guard while the identical `let` form failed.
/// What: a deref assignment is code; block-comment state is tracked across
/// lines instead of guessed from one.
/// Test: this is the test.
#[test]
fn strip_comment_keeps_a_deref_assignment() {
    let body = "*target = \"com.trusty.trusty-search\".to_string();\n";
    let kept = production_lines(body, Kind::Rust);
    assert!(
        kept.iter().any(|l| l.contains("com.trusty.trusty-search")),
        "a deref assignment is code, not a comment continuation, kept: {kept:?}"
    );
}

/// Why: block comments legitimately narrate legacy labels, so their bodies must
/// still be dropped — the fix must not simply stop stripping.
/// What: a `/* … */` body is dropped and code after it is kept.
/// Test: this is the test.
#[test]
fn strip_comment_tracks_block_comment_state() {
    let body = "/*\n * com.trusty.trusty-search was the old label\n */\nlet a = 1;\n";
    let kept = production_lines(body, Kind::Rust);
    assert!(
        !kept.iter().any(|l| l.contains("com.trusty.trusty-search")),
        "a block-comment body must stay unscanned, kept: {kept:?}"
    );
    assert!(kept.iter().any(|l| l.contains("let a = 1")));
}

/// Why (#4919 review, round 2): `#[cfg(test)] use std::fmt;` puts the attribute
/// AND the item on one line, so consuming from the next line ate a line of
/// production code — a literal planted there passed.
/// What: an attribute line carrying its whole item consumes nothing further.
/// Test: this is the test.
#[test]
fn skip_test_item_consumes_nothing_when_the_item_is_on_the_attribute_line() {
    let body = "#[cfg(test)] use std::fmt;\nlet x = \"com.trusty.trusty-search\";\n";
    let kept = production_lines(body, Kind::Rust);
    assert!(
        kept.iter().any(|l| l.contains("com.trusty.trusty-search")),
        "the line after a self-contained test item is production, kept: {kept:?}"
    );
}

/// Why (#4919 review, round 2): the codesign skip was whole-line, so a shell
/// line carrying both an identifier and a plist path had its real launchd label
/// skipped along with the identifier.
/// What: only the token adjacent to the marker is removed.
/// Test: this is the test.
#[test]
fn codesign_stripped_spares_only_the_identifier_token() {
    let line = "local X_IDENTIFIER=\"com.trusty.trusty-mpm\"; local f2=\"/x/com.bobmatnyc.trusty-search.plist\"";
    let out = codesign_stripped(line);
    assert!(
        !out.contains("com.trusty.trusty-mpm"),
        "the codesign identifier must be exempt, got: {out}"
    );
    assert!(
        out.contains("com.bobmatnyc.trusty-search"),
        "a launchd label on the same line must still be scanned, got: {out}"
    );

    let flag = codesign_stripped("codesign --identifier com.trusty.trusty-search /bin/x");
    assert!(!flag.contains("com.trusty.trusty-search"), "got: {flag}");
}

/// Every legacy alias in the registry, flattened.
///
/// Used to recognise a build-file line that names an old label in order to boot
/// it out — the migration this issue exists to perform.
fn legacy_labels_for_any() -> Vec<&'static str> {
    SERVICES
        .iter()
        .flat_map(|s| s.legacy.iter().copied())
        .collect()
}

/// Why: a Makefile that boots out a legacy label is performing the migration,
/// not perpetuating the drift. Rejecting it would have forced the deploy
/// recipes to drop the eviction they need.
/// What: a legacy label on a `bootout` line is allowed in a build file; the
/// same label on an install line is not.
/// Test: this is the test.
#[test]
fn eviction_lines_may_name_a_legacy_label() {
    let evict = "\t-launchctl bootout gui/$$(id -u)/com.trusty.trusty-search 2>/dev/null\n";
    let install = "PLIST := $(HOME)/Library/LaunchAgents/com.trusty.trusty-search.plist\n";

    let kept = production_lines(evict, Kind::Hash);
    assert!(
        !kept.is_empty(),
        "the bootout line must survive comment stripping"
    );
    assert!(
        legacy_labels_for_any().contains(&"com.trusty.trusty-search"),
        "the alias must be registered for the eviction allowance to apply"
    );
    // The install-shaped line carries no bootout/unload, so it stays a stray.
    let install_kept = production_lines(install, Kind::Hash);
    assert!(!install_kept[0].contains("bootout"));
}

/// Blank out only the identifier TOKEN adjacent to a codesign marker.
///
/// Why: codesign and bundle identifiers are a different namespace that uses the
/// full binary name deliberately — renaming one invalidates a binary's
/// designated requirement and re-triggers macOS TCC prompts (#2558).
///
/// #4919 review: skipping the whole LINE was too coarse. A shell line carrying
/// both an identifier and a plist path —
/// `local X_IDENTIFIER="a"; local f2=".../com.bobmatnyc.trusty-search.plist"` —
/// had its real launchd label skipped along with the identifier.
///
/// What: replaces the quoted or bare token immediately following
/// `--identifier` or an `*_IDENTIFIER=` assignment, leaving the rest of the
/// line to be scanned.
/// Test: `codesign_stripped_spares_only_the_identifier_token`.
fn codesign_stripped(line: &str) -> String {
    const MARKERS: &[&str] = &["--identifier", "IDENTIFIER="];
    let mut out = line.to_string();
    for marker in MARKERS {
        while let Some(idx) = out.find(marker) {
            let after = idx + marker.len();
            let rest = &out[after..];
            // Skip separators between the marker and its value.
            let val_start = rest
                .find(|c: char| !matches!(c, ' ' | '=' | '"' | '\'' | '\t'))
                .unwrap_or(rest.len());
            let tail = &rest[val_start..];
            let val_end = tail
                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_'))
                .unwrap_or(tail.len());
            let abs_start = after + val_start;
            let abs_end = abs_start + val_end;
            // Neutralise the marker so the loop terminates, and drop the token.
            out.replace_range(abs_start..abs_end, "");
            out.replace_range(idx..after, &"_".repeat(marker.len()));
        }
    }
    out
}

/// Pull `com.trusty.*` / `com.bobmatnyc.*` label tokens out of one line.
///
/// Trailing `.plist` and punctuation are stripped so a path or a hint string
/// resolves to the label it names rather than reading as a stray.
fn extract_labels(line: &str) -> Vec<String> {
    const PREFIXES: &[&str] = &["com.trusty.", "com.bobmatnyc."];
    let mut found = Vec::new();
    for prefix in PREFIXES {
        let mut rest = line;
        while let Some(idx) = rest.find(prefix) {
            let tail = &rest[idx..];
            let end = tail
                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_'))
                .unwrap_or(tail.len());
            let token = tail[..end]
                .trim_end_matches('.')
                .trim_end_matches(".plist")
                .trim_end_matches('.');
            // A bare prefix is a `starts_with` guard, not a label.
            if token.len() > prefix.len() {
                found.push(token.to_string());
            }
            rest = &rest[idx + prefix.len()..];
        }
    }
    found
}

/// REGRESSION (#6290): only a FAILED eviction is a failure.
///
/// Why: `evict_legacy` used to return a bare `Vec<String>` of evicted labels,
/// which collapsed "nothing was there" and "the removal failed" into the same
/// absence. An installer reading that absence as success leaves a retired unit
/// loaded and respawning while exiting 0.
#[test]
fn eviction_outcome_only_failed_is_a_failure() {
    assert!(!EvictionOutcome::Evicted.is_failure());
    assert!(!EvictionOutcome::Absent.is_failure());
    assert!(EvictionOutcome::Failed("still loaded after bootout".into()).is_failure());

    // The label travels with its outcome, so a caller reporting per label never
    // has to recover it by position.
    let e = LabelEviction::new("com.trusty.review", EvictionOutcome::Absent);
    assert_eq!(e.label, "com.trusty.review");
    assert_eq!(e.outcome, EvictionOutcome::Absent);
}

/// Why (#6350): trusty-analyze's unit exists under two names on real hosts —
/// `com.trusty.analyze` from the post-#4919 installer and
/// `com.trusty.trusty-analyze` from before it. An eviction that clears only one
/// leaves the other loaded under `KeepAlive::Always`, restarting the on-demand
/// server the moment its idle window reclaims it.
/// What: both labels come back from `retired_labels_for_member`, canonical
/// first, and the member resolves through the retired lookup.
/// Test: this is the test.
#[test]
fn retired_analyze_carries_both_its_labels() {
    assert!(
        retired_service_for_member("trusty-analyze").is_some(),
        "trusty-analyze runs on demand since #6350 and installs no unit"
    );
    assert_eq!(
        retired_labels_for_member("trusty-analyze"),
        vec![ANALYZE, "com.trusty.trusty-analyze"]
    );
    assert!(
        retired_labels_for_member("trusty-memory").is_empty(),
        "a live member has nothing to evict"
    );
    // The retired row still resolves by label, which is what keeps
    // `legacy_labels_for` from returning empty for it.
    assert_eq!(
        legacy_labels_for(ANALYZE),
        &["com.trusty.trusty-analyze"],
        "an eviction needs the retired row's legacy list just as an install needs a live one's"
    );
}

/// The scripts whose codesign identifiers the label scan exempts.
///
/// Why: `codesign_stripped` exempts an identifier by NAMING — the token has to
/// sit beside `--identifier` or an `*_IDENTIFIER=` assignment. Nothing made a
/// script follow that naming, so #5436 had to hoist three inline identifiers in
/// `install-trusty-memory-signed.sh` after the scan reported them as stray
/// launchd labels and its panic text advised deriving them from the registry —
/// the one edit that invalidates a designated requirement (#2558).
///
/// #6540: the selector was `scripts/install-*-signed.sh`, so
/// `build-console-saver.sh` minted `BUNDLE_ID="com.trusty.console.saver"` with
/// nothing to catch it and reproduced that false red on `main`. A script that
/// runs `codesign` is a script that mints identifiers, whatever it is named.
///
/// What: every `scripts/*.sh` whose body invokes `codesign`.
/// Test: `codesign_scripts_name_identifiers_by_convention`.
fn codesign_scripts(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    let Ok(entries) = std::fs::read_dir(root.join("scripts")) else {
        return out;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().is_none_or(|e| e != "sh") {
            continue;
        }
        if std::fs::read_to_string(&path).is_ok_and(|b| b.contains("codesign")) {
            out.push(path);
        }
    }
    out.sort();
    out
}

/// The variable name in `$NAME`, `${NAME}` or a quoted form of either.
///
/// Returns `None` for a literal argument, which needs no name: an identifier
/// written inline already sits beside the `--identifier` marker.
fn shell_var_name(arg: &str) -> Option<String> {
    let arg = arg.strip_prefix('$')?;
    let arg = arg.strip_prefix('{').unwrap_or(arg);
    let end = arg
        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
        .unwrap_or(arg.len());
    (end > 0).then(|| arg[..end].to_string())
}

/// Split a shell line into `(variable, assigned value)` pairs.
///
/// What: for each `=`, the name is the identifier run immediately before it and
/// the value runs to the next `;`. `readonly`/`local`/`export` prefixes fall
/// away because the name is read backwards from the `=`. A `--flag=value`, a
/// `==` comparison, and a bare `=` with no name to its left all yield nothing.
/// Test: `identifier_convention_violations_flag_an_unmarked_binding`.
fn shell_assignments(line: &str) -> Vec<(String, String)> {
    let bytes = line.as_bytes();
    let mut out = Vec::new();
    for (idx, _) in line.match_indices('=') {
        let head = &line[..idx];
        let name_start = head
            .rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
            .map_or(0, |i| i + 1);
        let name = &head[name_start..];
        if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
            continue;
        }
        // `--identifier=…` is a flag, not a binding — rule A owns it.
        if name_start > 0 && bytes[name_start - 1] == b'-' {
            continue;
        }
        let tail = &line[idx + 1..];
        let value = tail.split(';').next().unwrap_or(tail);
        out.push((name.to_string(), value.to_string()));
    }
    out
}

/// Every way `rel`'s body binds a codesign identifier without the naming the
/// launchd-label scan's exemption depends on.
///
/// Why (#5438): the exemption was convention. A script that narrates an
/// identifier under any other name reproduces #5436's false red, where the scan
/// reports a codesign identifier as a stray launchd label and prescribes the
/// rename that breaks signing (#2558).
/// What: two rules over comment-stripped lines. `--identifier` must receive a
/// literal or a variable whose name ends in `IDENTIFIER`; and a variable bound
/// to a label-shaped literal the scan would reject must be named
/// `*_IDENTIFIER`. A canonical registry label is a launchd label, not an
/// identifier, so it is left alone — as is a legacy alias named on an eviction
/// line, which the scan already permits.
/// Test: `identifier_convention_violations_flag_an_unmarked_binding`,
/// `identifier_convention_violations_accept_the_repaired_shape`.
fn identifier_convention_violations(rel: &str, body: &str) -> Vec<String> {
    const FLAG: &str = "--identifier";
    let mut out = Vec::new();
    for line in production_lines(body, Kind::Hash) {
        for (idx, _) in line.match_indices(FLAG) {
            let arg = line[idx + FLAG.len()..].trim_start_matches([' ', '=', '"', '\'', '\t']);
            let Some(name) = shell_var_name(arg) else {
                continue;
            };
            if !name.to_ascii_uppercase().ends_with("IDENTIFIER") {
                out.push(format!(
                    "{rel}: `--identifier \"${name}\"` — a codesign identifier must reach the \
                     flag through a variable whose name ends in `_IDENTIFIER`, so its binding \
                     site is exempt from the launchd-label scan (#5438)"
                ));
            }
        }
        let evicting = line.contains("bootout") || line.contains("unload");
        for (name, value) in shell_assignments(&line) {
            if name.to_ascii_uppercase().ends_with("_IDENTIFIER") {
                continue;
            }
            for label in extract_labels(&value) {
                if is_canonical_label(&label) {
                    continue;
                }
                if evicting && legacy_labels_for_any().contains(&label.as_str()) {
                    continue;
                }
                out.push(format!(
                    "{rel}: `{name}=\"{label}\"` — a codesign identifier must be bound to a \
                     `readonly <NAME>_IDENTIFIER=` constant, never renamed onto the launchd \
                     convention (#2558); if `{label}` really is a launchd label, take it from \
                     `trusty_common::launchd_labels` instead (#5438)"
                ));
            }
        }
    }
    out
}

/// Why (#5438): closure condition 2 — the exemption is checked mechanically
/// across every script that signs something, instead of being observed by habit.
/// #6540 widened it past the signed installers after the console-saver build
/// script minted an identifier outside that glob.
/// What: no script binds a codesign identifier under a name the scan cannot
/// see. The counts guard against a vacuous pass — a walk that matched nothing,
/// or scripts that carry no identifier at all, would otherwise report success.
/// Test: this is the test.
#[test]
fn codesign_scripts_name_identifiers_by_convention() {
    let root = workspace_root();
    let scripts = codesign_scripts(&root);
    assert!(
        scripts.len() >= 3,
        "expected the codesigning scripts under {}/scripts, found {}",
        root.display(),
        scripts.len()
    );
    assert!(
        scripts.iter().any(|p| p
            .file_name()
            .is_some_and(|n| n.to_string_lossy().ends_with("-signed.sh"))),
        "the signed installers #5438 was filed over must stay in scope, found: {scripts:?}"
    );

    let mut bindings = 0usize;
    let mut violations: Vec<String> = Vec::new();
    for path in &scripts {
        let rel = path
            .strip_prefix(&root)
            .unwrap_or(path)
            .display()
            .to_string();
        let Ok(body) = std::fs::read_to_string(path) else {
            continue;
        };
        for line in production_lines(&body, Kind::Hash) {
            bindings += shell_assignments(&line)
                .iter()
                .filter(|(n, _)| n.to_ascii_uppercase().ends_with("_IDENTIFIER"))
                .count();
        }
        violations.extend(identifier_convention_violations(&rel, &body));
    }

    assert!(
        bindings > 0,
        "no `*_IDENTIFIER=` binding found in any of {} script(s) — the scan would \
         have nothing to exempt, so the walk is reading the wrong files",
        scripts.len()
    );
    assert!(
        violations.is_empty(),
        "codesign identifiers bound outside the `*_IDENTIFIER` naming the \
         launchd-label scan exempts:\n  {}",
        violations.join("\n  ")
    );
}

/// REGRESSION (#5438): the shape #5436 had to repair by hand is caught by name.
///
/// Why: before this check the binding below produced a stray-label red whose
/// advice — derive it from the registry — breaks the binary's designated
/// requirement (#2558). Nothing failed until a developer typed it.
/// What: both the unmarked binding and the flag reading it are reported, and the
/// second assertion shows the scan really would have taken that binding for a
/// launchd label.
/// Test: this is the test.
#[test]
fn identifier_convention_violations_flag_an_unmarked_binding() {
    let body = "local mem_id=\"com.trusty.trusty-memory\"\n\
                codesign --force --identifier \"$mem_id\" \"$bin\"\n";
    let found = identifier_convention_violations("scripts/install-fixture-signed.sh", body);
    assert_eq!(
        found.len(),
        2,
        "the binding and the flag are both violations, got: {found:?}"
    );
    assert!(
        found.iter().any(|v| v.contains("com.trusty.trusty-memory")),
        "the failure must name the label, got: {found:?}"
    );
    assert!(
        found.iter().all(|v| v.contains("IDENTIFIER")),
        "the failure must state the expected naming, got: {found:?}"
    );

    let binding = production_lines(body, Kind::Hash).remove(0);
    assert!(
        !extract_labels(&codesign_stripped(&binding)).is_empty(),
        "this is the binding the label scan reads as a stray: {binding}"
    );
}

/// Why: the check must accept what #5436 shipped, and must not mistake a
/// launchd label for an identifier — a plist path names a canonical label and
/// belongs to the registry, not the codesign namespace.
/// Test: this is the test.
#[test]
fn identifier_convention_violations_accept_the_repaired_shape() {
    let body = "readonly MEMORY_IDENTIFIER=\"com.trusty.trusty-memory\"\n\
                codesign --identifier \"$MEMORY_IDENTIFIER\" \"$bin\"\n\
                codesign --identifier com.trusty.trusty-memory \"$bin\"\n\
                local plist=\"$HOME/Library/LaunchAgents/com.trusty.memory.plist\"\n\
                # local narrated=\"com.trusty.trusty-memory\"\n";
    let found = identifier_convention_violations("scripts/install-fixture-signed.sh", body);
    assert!(found.is_empty(), "expected no violations, got: {found:?}");
}