trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Tests for the spawn-time `gh` identity resolver
//! (`resolve_gh_account_env_with`/`resolve_gh_account_env`/
//! `resolve_gh_account_env_for_registry`/`find_pinned_gh_identity` in
//! `gh_account.rs`) — #3025's `GH_TOKEN` minting and #5851's `GH_CONFIG_DIR`
//! selection.
//!
//! #5851 coverage: `config_dir_is_selected_over_a_minted_token` proves the
//! token path is skipped (not merely overridden) when a config dir is pinned;
//! `config_dir_without_credential_still_pins_and_warns` pins the deliberate
//! fail-CLOSED decision for an empty config dir; and
//! `pinned_config_dir_reaches_the_spawn_env` is the end-to-end fail-open check
//! that fails against the pre-fix code. No test here shells out to `gh` or
//! reads `~/.config/gh` — the config dirs are temp dirs and the `hosts.yml`
//! files are written by the fixtures.
//!
//! Why: split into a companion `_tests.rs` file (rather than growing the
//! large inline `#[cfg(test)] mod tests` in `gh_account.rs` itself) purely to
//! keep `gh_account.rs` — a production file capped at 500 SLOC — clear of
//! further growth; this file is classified as a test file by its `_tests.rs`
//! suffix. Every `resolve_gh_account_env_with` case exercises a FAKE token
//! resolver closure so no live `gh` login is ever required in CI; every
//! `find_pinned_gh_identity`/`resolve_gh_account_env_for_registry` case
//! exercises a REAL, temp-dir-backed `ProjectRegistry` fixture — this is the
//! #3025 review-follow-up coverage proving the registry, not the static
//! config file, is consulted.
//! What: the `resolve_gh_account_env_with` outcomes (no account, blank
//! account, success, resolver failure — the fail-open spawn contract; plus
//! #5851's config-dir arms), and the registry-matching coverage: a registered
//! project's pinned `gh_account` and `github.config_dir` ARE picked up for its
//! `repo_url`, an unregistered/mismatched `repo_url` is NOT, and a project
//! pinning neither yields `None`.
//! Test: itself (each `#[test]`/`#[tokio::test]` below is its own coverage unit).

use std::path::{Path, PathBuf};

use super::{
    GH_TOKEN_ENV_VAR, GH_USER_ENV_VAR, find_pinned_gh_identity,
    resolve_gh_account_env_for_registry_with, resolve_gh_account_env_with,
};
use crate::core::gh_account_dir::gh_account_dir_tests::{TableCheck, TableProbe, migrated_dir};
use crate::core::gh_org_accounts::{OrgAccounts, OrgAccountsError};
use crate::core::trusty_tools_config::GithubConfig;
use crate::project::Project;
use crate::project::ProjectRegistry;

/// The `GH_CONFIG_DIR` name, spelled out here rather than imported so a rename
/// on the production side cannot silently make these assertions vacuous.
const GH_CONFIG_DIR: &str = "GH_CONFIG_DIR";

/// Assert `vars` carries `name` exactly once, and return its value.
fn value_of(vars: &[(String, String)], name: &str) -> String {
    let matches: Vec<&(String, String)> = vars.iter().filter(|(k, _)| k == name).collect();
    assert_eq!(matches.len(), 1, "expected exactly one {name} in {vars:?}");
    matches[0].1.clone()
}

/// The registry spawn env with an empty `[accounts]` table, so no test reads
/// the host's `~/.trusty-mpm/config.toml` (#9091).
async fn for_registry(registry: &ProjectRegistry, cwd: &Path) -> Vec<(String, String)> {
    resolve_gh_account_env_for_registry_with(registry, cwd, || Ok(OrgAccounts::default())).await
}

/// [`find_pinned_gh_identity`] for a registry whose pins agree.
async fn agreed_pin(registry: &ProjectRegistry, origin: &str) -> Option<super::PinnedGhIdentity> {
    find_pinned_gh_identity(registry, origin)
        .await
        .expect("the registry reads and its pins agree")
}

/// Write a `hosts.yml` naming `account` into `dir`, the shape `gh` writes for
/// a scoped config home that has been logged into.
fn write_hosts_yml(dir: &Path, account: &str) {
    let yaml = format!("github.com:\n    git_protocol: https\n    user: {account}\n");
    std::fs::write(dir.join("hosts.yml"), yaml).expect("write hosts.yml");
}

/// Why: `gh_account: None` (no pinning configured) must resolve to `None` —
/// nothing to inject, no regression for every project that never sets the
/// field.
/// Test: itself.
#[test]
fn resolve_gh_account_env_with_unset_is_none() {
    let result = resolve_gh_account_env_with(None, None, |_| Ok("unused".to_string()));
    assert!(result.is_none());
}

/// Why: a blank/whitespace-only `gh_account` must be treated the same as
/// unset — never invokes the resolver, never fabricates env vars from
/// nothing.
/// Test: itself.
#[test]
fn resolve_gh_account_env_with_blank_is_none() {
    let result = resolve_gh_account_env_with(Some("   "), None, |_| Ok("unused".to_string()));
    assert!(result.is_none());
}

/// Why: a successful resolution must inject BOTH `GH_TOKEN` (the minted
/// token) and `GH_USER` (the pinned account name) — in that order — so a
/// caller applying `vars` sequentially gets a deterministic env. #5851 leaves
/// this arm untouched: a project with no `github.config_dir` behaves exactly
/// as it did before.
/// Test: itself.
#[test]
fn resolve_gh_account_env_with_success_returns_token_and_user() {
    let result = resolve_gh_account_env_with(Some("bobmatnyc"), None, |account| {
        assert_eq!(account, "bobmatnyc");
        Ok("ghp_fake_token".to_string())
    });
    let env = result.expect("some").expect("ok");
    assert_eq!(
        env.vars,
        vec![
            (GH_TOKEN_ENV_VAR.to_string(), "ghp_fake_token".to_string()),
            (GH_USER_ENV_VAR.to_string(), "bobmatnyc".to_string()),
        ]
    );
    assert_eq!(env.warning, None);
}

/// Why: a resolver failure (account not logged in, `gh` missing, etc.) must
/// surface as `Some(Err(..))` — never panic, never silently fall through to
/// an empty/placeholder token — so the caller can log a clear warning and
/// proceed WITHOUT injecting `GH_TOKEN` (issue #3025's documented failure
/// mode).
/// Test: itself.
#[test]
fn resolve_gh_account_env_with_failure_returns_err() {
    let result = resolve_gh_account_env_with(Some("bob-duetto"), None, |_| {
        Err("account 'bob-duetto' is not logged in".to_string())
    });
    let err = result.expect("some").expect_err("err");
    assert!(err.contains("bob-duetto"), "err: {err}");
}

/// Why: the account name passed to the resolver must be TRIMMED (leading/
/// trailing whitespace stripped) so a config value with incidental
/// whitespace still resolves correctly.
/// Test: itself.
#[test]
fn resolve_gh_account_env_with_trims_account_name() {
    let result = resolve_gh_account_env_with(Some("  bobmatnyc  "), None, |account| {
        assert_eq!(account, "bobmatnyc");
        Ok("tok".to_string())
    });
    let env = result.expect("some").expect("ok");
    assert!(
        env.vars
            .contains(&(GH_USER_ENV_VAR.to_string(), "bobmatnyc".to_string()))
    );
}

// ── #5851: `config_dir` selects, `gh auth token -u` does not ───────────────

/// Why (#5851, the core of the fix): `gh auth token -u <account>` returns the
/// SAME value for every logged-in account on a keyring-backed host, so a
/// project pinned to `github.config_dir` must be selected by `GH_CONFIG_DIR`
/// and must NOT also carry a `GH_TOKEN` — an env token outranks the scoped
/// config in `gh`'s own resolution order, which would make the config dir
/// decorative. The token resolver panics if called, proving the token path is
/// skipped entirely rather than merely overridden.
/// Test: itself.
#[test]
fn config_dir_is_selected_over_a_minted_token() {
    let dir = tempfile::tempdir().expect("tempdir");
    write_hosts_yml(dir.path(), "bobmatnyc");

    let result = resolve_gh_account_env_with(Some("bobmatnyc"), Some(dir.path()), |_| {
        panic!("the token path must not run when a config_dir is pinned")
    });
    let env = result.expect("some").expect("ok");

    assert_eq!(
        value_of(&env.vars, GH_CONFIG_DIR),
        dir.path().to_string_lossy()
    );
    assert!(
        !env.vars.iter().any(|(k, _)| k == GH_TOKEN_ENV_VAR),
        "GH_TOKEN must never accompany GH_CONFIG_DIR: {:?}",
        env.vars
    );
    assert_eq!(value_of(&env.vars, GH_USER_ENV_VAR), "bobmatnyc");
}

/// Why: a config dir naming an account carries a credential as far as this
/// layer can tell, so it must produce no warning — the warning has to mean
/// something when it does fire.
/// Test: itself.
#[test]
fn config_dir_with_credential_has_no_warning() {
    let dir = tempfile::tempdir().expect("tempdir");
    write_hosts_yml(dir.path(), "bobmatnyc");
    let env = resolve_gh_account_env_with(Some("bobmatnyc"), Some(dir.path()), |_| {
        panic!("token path must not run")
    })
    .expect("some")
    .expect("ok");
    assert_eq!(env.warning, None);
}

/// Why (#5851, the decision on the no-credential case): a pinned config dir
/// that holds no credential makes every `gh` call exit 4. The deliberate
/// choice is to STILL pin it — dropping `GH_CONFIG_DIR` would hand the session
/// back to the machine-global account, which is the wrong-identity bug this
/// change exists to close — and to emit one warning that names the directory
/// and the scoped `gh auth login` that fixes it. This test fails if either
/// half regresses: a silent fall-back, or a mute failure.
/// Test: itself.
#[test]
fn config_dir_without_credential_still_pins_and_warns() {
    let dir = tempfile::tempdir().expect("tempdir");
    // Deliberately no hosts.yml — the empty-config-dir case.
    let env = resolve_gh_account_env_with(Some("bobmatnyc"), Some(dir.path()), |_| {
        panic!("the token path must not be used as a fallback for an empty config dir")
    })
    .expect("some")
    .expect("ok");

    assert_eq!(
        value_of(&env.vars, GH_CONFIG_DIR),
        dir.path().to_string_lossy(),
        "an empty config dir must still be pinned — falling back is the fail-open defect"
    );
    assert!(!env.vars.iter().any(|(k, _)| k == GH_TOKEN_ENV_VAR));

    let warning = env.warning.expect("an empty config dir must warn");
    let shown = dir.path().display().to_string();
    assert!(
        warning.contains(&shown),
        "warning must name the dir: {warning}"
    );
    assert!(
        warning.contains("gh auth login"),
        "warning must say what to run: {warning}"
    );
}

/// Why: a whitespace-only `config_dir` is not a directory; it must be treated
/// as unset and fall through to the pre-#5851 token path, matching how
/// `gh_identity::resolve_gh_env` trims the same field.
/// Test: itself.
#[test]
fn blank_config_dir_falls_through_to_the_token_path() {
    let env = resolve_gh_account_env_with(Some("bobmatnyc"), Some(Path::new("   ")), |_| {
        Ok("tok".to_string())
    })
    .expect("some")
    .expect("ok");
    assert_eq!(value_of(&env.vars, GH_TOKEN_ENV_VAR), "tok");
    assert!(!env.vars.iter().any(|(k, _)| k == GH_CONFIG_DIR));
}

/// Why: a project can pin a config dir without naming an account (isolation
/// with no stated preference). `GH_CONFIG_DIR` must still be injected — it is
/// the selector — and `GH_USER`, which is informational only, must be absent
/// rather than fabricated.
/// Test: itself.
#[test]
fn config_dir_without_an_account_still_pins() {
    let dir = tempfile::tempdir().expect("tempdir");
    write_hosts_yml(dir.path(), "bobmatnyc");
    let env = resolve_gh_account_env_with(None, Some(dir.path()), |_| panic!("no token path"))
        .expect("some")
        .expect("ok");
    assert_eq!(
        value_of(&env.vars, GH_CONFIG_DIR),
        dir.path().to_string_lossy()
    );
    assert!(!env.vars.iter().any(|(k, _)| k == GH_USER_ENV_VAR));
}

/// Build a minimal `Project` fixture, mirroring the register-route shape.
fn project(name: &str, repo_url: &str, gh_account: Option<&str>) -> Project {
    Project {
        name: name.to_string(),
        repo_url: repo_url.to_string(),
        default_branch: "main".to_string(),
        stack_hint: None,
        tags: vec![],
        description: None,
        gh_user: None,
        gh_account: gh_account.map(str::to_string),
        github: None,
        commit_name: None,
        commit_email: None,
        worktree: None,
    }
}

/// The same fixture with a `github.config_dir` binding attached (#5851).
fn project_with_config_dir(name: &str, repo_url: &str, config_dir: &Path) -> Project {
    Project {
        github: Some(GithubConfig {
            config_dir: Some(config_dir.to_path_buf()),
            ..GithubConfig::default()
        }),
        ..project(name, repo_url, None)
    }
}

/// Why (#3025 review follow-up, CRITICAL fix): this is the exact coverage
/// the review demanded — register a project (via the registry, the REAL
/// write target `tm projects register --gh-account`/the PATCH route/the MCP
/// tool all use) with a pinned `gh_account`, then assert the resolver picks
/// it up for that project's `repo_url`. Proves the registry — not the
/// static `TrustyToolsConfig` file the original implementation mistakenly
/// consulted — is the source of truth.
/// Test: itself.
#[tokio::test]
async fn resolve_gh_account_env_for_registry_picks_up_registered_gh_account() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    registry
        .register(project(
            "widget",
            "https://github.com/acme/widget",
            Some("bobmatnyc"),
        ))
        .await
        .expect("register");

    let found = agreed_pin(&registry, "https://github.com/acme/widget")
        .await
        .expect("matched");
    assert_eq!(found.account.as_deref(), Some("bobmatnyc"));
    assert_eq!(found.config_dir, None);

    // Tolerates the `.git`-suffix/scheme variance `repo_url_matches` handles.
    let found_git_suffix = agreed_pin(&registry, "https://github.com/acme/widget.git")
        .await
        .expect("matched");
    assert_eq!(found_git_suffix.account.as_deref(), Some("bobmatnyc"));
}

/// Why (#5851): `github.config_dir` was already persisted on the record and
/// already mirrored from config, but the spawn-env lookup never read it — that
/// omission is what forced every session down the non-discriminating
/// `gh auth token -u` path. This asserts the lookup now returns it.
/// Test: itself.
#[tokio::test]
async fn find_pinned_gh_identity_reads_config_dir() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let config_dir = PathBuf::from("/home/bob/.config/gh-bobmatnyc");
    registry
        .register(project_with_config_dir(
            "widget",
            "https://github.com/acme/widget",
            &config_dir,
        ))
        .await
        .expect("register");

    let found = agreed_pin(&registry, "https://github.com/acme/widget")
        .await
        .expect("matched");
    assert_eq!(found.config_dir.as_deref(), Some(config_dir.as_path()));
}

/// Why: a `repo_url` that matches NO registered project must yield `None` —
/// not a panic, not a false-positive match against an unrelated project.
/// Test: itself.
#[tokio::test]
async fn resolve_gh_account_env_for_registry_no_match_is_none() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    registry
        .register(project(
            "widget",
            "https://github.com/acme/widget",
            Some("bobmatnyc"),
        ))
        .await
        .expect("register");

    let found = agreed_pin(&registry, "https://github.com/acme/other-repo").await;
    assert_eq!(found, None);
}

/// Why: a registered project with NO `gh_account` set must yield `None` —
/// the no-regression case for every project that never pins one.
/// Test: itself.
#[tokio::test]
async fn resolve_gh_account_env_for_registry_registered_without_gh_account_is_none() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    registry
        .register(project("widget", "https://github.com/acme/widget", None))
        .await
        .expect("register");

    let found = agreed_pin(&registry, "https://github.com/acme/widget").await;
    assert_eq!(found, None);
}

/// 🔴 #5850 REGRESSION: an unpinned duplicate record for the same repository
/// must not hide the pinned one from a session spawn.
///
/// Why this shape: `ProjectRegistry::list` returns records in `HashMap` order,
/// so the old first-match lookup picked an arbitrary record. Sixteen unpinned
/// duplicates make that pick land on an unpinned record almost every run
/// (16 in 17), which is enough to fail against the first-match code.
/// Test: itself.
#[tokio::test]
async fn find_pinned_gh_identity_skips_an_unpinned_duplicate() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    for i in 0..16 {
        registry
            .register(project(
                &format!("widget-{i:02}"),
                "https://github.com/acme/widget.git",
                None,
            ))
            .await
            .expect("register");
    }
    registry
        .register(project(
            "widget",
            "https://github.com/acme/widget",
            Some("bobmatnyc"),
        ))
        .await
        .expect("register");

    let found = agreed_pin(&registry, "https://github.com/acme/widget")
        .await
        .expect("the pinned record must be found past its unpinned duplicates");
    assert_eq!(found.account.as_deref(), Some("bobmatnyc"));
}

/// 🔴 #5850 REGRESSION: two records pinning the SAME login give the session the
/// one carrying a `config_dir`, not the global account.
///
/// Why: the `seed_from_config` record (login only) and the `tm --user` record
/// (login plus scoped dir) are one identity. Treating them as a conflict spawned
/// the session unpinned.
/// Test: itself.
#[tokio::test]
async fn find_pinned_gh_identity_prefers_the_config_dir_pin_for_one_login() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let config_dir = PathBuf::from("/home/bob/.config/gh-bob-duetto");
    registry
        .register(project(
            "jev",
            "https://github.com/acme/widget",
            Some("bob-duetto"),
        ))
        .await
        .expect("register");
    registry
        .register(Project {
            gh_account: Some("bob-duetto".to_string()),
            ..project_with_config_dir(
                "jev-matching",
                "https://github.com/acme/widget",
                &config_dir,
            )
        })
        .await
        .expect("register");

    let found = agreed_pin(&registry, "https://github.com/acme/widget")
        .await
        .expect("one login must resolve to a pin");
    assert_eq!(found.account.as_deref(), Some("bob-duetto"));
    assert_eq!(found.config_dir.as_deref(), Some(config_dir.as_path()));
}

/// 🔴 #5850 REGRESSION: a no-login `config_dir` record next to a login record on
/// the same dir gives the session that dir AND the login.
///
/// Why: the login keeps `configured_account_pair` enforcement armed; losing it,
/// or refusing the pair, spawned the session as the global account.
/// Test: itself.
#[tokio::test]
async fn find_pinned_gh_identity_inherits_the_login_for_a_no_login_config_dir_pin() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let config_dir = PathBuf::from("/home/bob/.config/gh-bob-duetto");
    registry
        .register(Project {
            gh_account: None,
            ..project_with_config_dir("jev", "https://github.com/acme/widget", &config_dir)
        })
        .await
        .expect("register");
    registry
        .register(Project {
            gh_account: Some("bob-duetto".to_string()),
            github: Some(GithubConfig {
                config_dir: Some(config_dir.clone()),
                account: Some("bob-duetto".to_string()),
                ..GithubConfig::default()
            }),
            ..project("widget", "https://github.com/acme/widget", None)
        })
        .await
        .expect("register");

    let found = agreed_pin(&registry, "https://github.com/acme/widget")
        .await
        .expect("a missing login is not a disagreement");
    assert_eq!(found.account.as_deref(), Some("bob-duetto"));
    assert_eq!(found.config_dir.as_deref(), Some(config_dir.as_path()));
}

/// 🔴 #5850, #8914 HIGH 2: two records pinning DIFFERENT accounts are an
/// error the spawn fails closed on — neither side guesses.
/// Test: itself.
#[tokio::test]
async fn find_pinned_gh_identity_refuses_disagreeing_pins() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    for (name, account) in [("widget-a", "bobmatnyc"), ("widget-b", "bob-duetto")] {
        registry
            .register(project(
                name,
                "https://github.com/acme/widget",
                Some(account),
            ))
            .await
            .expect("register");
    }
    let found = find_pinned_gh_identity(&registry, "https://github.com/acme/widget").await;
    let reason = found.expect_err("disagreeing pins must not be resolved by position");
    assert!(reason.contains("different gh accounts"), "{reason}");
}

/// Why: a workspace with no git origin (a bare, non-git temp dir) must
/// resolve to an EMPTY vec end-to-end via `resolve_gh_account_env_for_registry`
/// itself — no regression for every workspace that predates #3025, and no
/// panic/hang even with an empty registry.
/// Test: itself.
#[tokio::test]
async fn resolve_gh_account_env_for_registry_no_origin_is_empty() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    let vars = for_registry(&registry, workspace.path()).await;
    assert!(vars.is_empty(), "vars: {vars:?}");
}

/// 🔴 FAIL-OPEN CHECK (#8934, #8914 invariant): a git repository with NO
/// `origin` has no GitHub identity to prove. Before #8934 it resolved to an
/// EMPTY env — the session inherited `GH_TOKEN` and ran gh as the machine's
/// active account. It must get the explicit "no remote, no gh" pin instead,
/// under which gh cannot start, and the launch must strip inherited tokens.
/// Test: itself.
#[tokio::test]
async fn a_local_only_repo_spawns_with_gh_disabled() {
    use crate::core::remote_mode::{LOCAL_ONLY_GH_CONFIG_DIR, LOCAL_ONLY_GH_TOKEN};
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    let init = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(workspace.path())
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");

    let vars = for_registry(&registry, workspace.path()).await;
    assert_eq!(value_of(&vars, GH_CONFIG_DIR), LOCAL_ONLY_GH_CONFIG_DIR);
    assert_eq!(value_of(&vars, "GH_TOKEN"), LOCAL_ONLY_GH_TOKEN);
    assert_eq!(value_of(&vars, "GH_ENTERPRISE_TOKEN"), LOCAL_ONLY_GH_TOKEN);
    assert_eq!(value_of(&vars, "GIT_TERMINAL_PROMPT"), "0");
    let unset = crate::core::gh_identity::inherited_identity_to_clear(&vars);
    assert!(unset.iter().any(|k| k == "GITHUB_TOKEN"), "{unset:?}");
}

/// 🔴 #8934 MEDIUM 7 FAIL-OPEN CHECK: an origin git cannot read proves no
/// identity. It used to spawn with an empty env — the machine's active
/// account; the session now gets the nobody-token.
/// Test: itself.
#[cfg(unix)]
#[tokio::test]
async fn an_unreadable_origin_spawns_with_the_nobody_token() {
    use std::os::unix::fs::PermissionsExt;
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme-8934/widget.git");
    let git_dir = workspace.path().join(".git");
    std::fs::set_permissions(&git_dir, std::fs::Permissions::from_mode(0o000)).expect("chmod");
    let vars = for_registry(&registry, workspace.path()).await;
    std::fs::set_permissions(&git_dir, std::fs::Permissions::from_mode(0o755)).expect("restore");
    for var in [GH_TOKEN_ENV_VAR, "GH_ENTERPRISE_TOKEN"] {
        assert_eq!(value_of(&vars, var), super::REFUSED_GH_TOKEN, "{var}");
    }
}

/// `git init` a workspace and point its `origin` at `origin_url`.
fn workspace_with_origin(dir: &Path, origin_url: &str) {
    let init = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(dir)
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");
    let remote = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["remote", "add", "origin", origin_url])
        .output()
        .expect("git remote add");
    assert!(remote.status.success(), "git remote add failed");
}

/// FAIL-OPEN CHECK (#5851) — the blocking regression test.
///
/// Why: before this fix, `find_pinned_gh_account` read only `gh_account` and
/// never looked at `github.config_dir`, so a project pinned by a scoped `gh`
/// config home got NOTHING injected and its session ran under whatever account
/// was globally active. This drives the whole production path end to end — real
/// git origin, real temp-dir-backed registry, no `gh` subprocess anywhere —
/// and asserts `GH_CONFIG_DIR` reaches the spawn env. Against the pre-fix code
/// it returns an empty vec and this test fails on the first assertion; that is
/// the point of it.
/// What: registers a project whose `github.config_dir` is set and whose
/// `gh_account` is NOT, so neither the pre-fix nor the post-fix run can reach
/// `gh auth token`; asserts `GH_CONFIG_DIR` is present and `GH_TOKEN` is not.
/// Test: itself.
#[tokio::test]
async fn pinned_config_dir_reaches_the_spawn_env() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let gh_home = tempfile::tempdir().expect("gh home tempdir");
    write_hosts_yml(gh_home.path(), "bobmatnyc");
    registry
        .register(project_with_config_dir(
            "widget",
            "https://github.com/acme/widget",
            gh_home.path(),
        ))
        .await
        .expect("register");

    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme/widget.git");

    let vars = for_registry(&registry, workspace.path()).await;
    assert_eq!(
        value_of(&vars, GH_CONFIG_DIR),
        gh_home.path().to_string_lossy(),
        "a project pinned by github.config_dir must have it injected at spawn"
    );
    // #8914 HIGH 3: a config dir alone let gh read the keyring's active
    // account; a test build proves no token, so the nobody-token is injected.
    assert_eq!(value_of(&vars, GH_TOKEN_ENV_VAR), super::REFUSED_GH_TOKEN);
}

/// 🔴 #8914 HIGH 2 FAIL-OPEN CHECK: two records pinning different accounts for
/// one origin used to spawn with no identity, as the active account. Through
/// the whole production path the session now gets the nobody-token.
/// Test: itself.
#[tokio::test]
async fn disagreeing_pins_spawn_with_the_nobody_token() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    for (name, account) in [("widget-a", "octo-a"), ("widget-b", "octo-b")] {
        let origin = "https://github.com/acme-8914/widget";
        registry
            .register(project(name, origin, Some(account)))
            .await
            .expect("register");
    }
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme-8914/widget.git");

    let vars = for_registry(&registry, workspace.path()).await;
    for var in [GH_TOKEN_ENV_VAR, "GH_ENTERPRISE_TOKEN"] {
        assert_eq!(value_of(&vars, var), super::REFUSED_GH_TOKEN, "{var}");
    }
}

/// 🔴 #8914 HIGH 2 FAIL-OPEN CHECK: a registry that cannot be read cannot say
/// the origin is unpinned, so the session gets the nobody-token.
/// Test: itself.
#[tokio::test]
async fn an_unreadable_registry_spawns_with_the_nobody_token() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let origin = "https://github.com/acme-8914/widget";
    registry
        .register(project("widget", origin, Some("octo-a")))
        .await
        .expect("register");
    std::fs::write(dir.path().join("projects.json"), "{ not json").expect("corrupt");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme-8914/widget.git");

    let vars = for_registry(&registry, workspace.path()).await;
    assert_eq!(value_of(&vars, GH_TOKEN_ENV_VAR), super::REFUSED_GH_TOKEN);
}

/// 🔴 #8914 HIGH 3 FAIL-OPEN CHECK: an operator's own `--gh-config-dir` holds
/// no token, so a spawn that set only `GH_CONFIG_DIR` ran as the keyring's
/// active account. Through the whole production path the session now gets a
/// token variable — the nobody-token, since a test build proves none.
/// Test: itself.
#[tokio::test]
async fn an_operator_config_dir_pin_never_leaves_the_session_on_the_active_account() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let gh_home = tempfile::tempdir().expect("gh home tempdir");
    write_hosts_yml(gh_home.path(), "octo-8914-op");
    let origin = "https://github.com/acme-8914/widget";
    registry
        .register(Project {
            gh_account: Some("octo-8914-op".into()),
            ..project_with_config_dir("widget", origin, gh_home.path())
        })
        .await
        .expect("register");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme-8914/widget.git");

    let vars = for_registry(&registry, workspace.path()).await;
    assert_eq!(
        value_of(&vars, GH_TOKEN_ENV_VAR),
        super::REFUSED_GH_TOKEN,
        "a tokenless config dir resolves to the keyring's active account: {vars:?}"
    );
    assert_eq!(
        value_of(&vars, GH_CONFIG_DIR),
        gh_home.path().to_string_lossy()
    );
}

/// 🔴 #8914 FAIL-OPEN CHECK: a project pinned to tm's own
/// `<state_root>/gh-accounts/<login>` dir used to spawn with only
/// `GH_CONFIG_DIR` set. That dir holds no token, so the session's gh read the
/// keyring's active account. Through the whole production path (real git
/// origin, real registry, no gh or network in a test build) the session must
/// now get a token variable — here the nobody-token, since a test build never
/// proves one — and still point `GH_CONFIG_DIR` at the account dir.
/// Test: itself.
#[tokio::test]
async fn a_tm_account_dir_pin_never_leaves_the_session_on_the_active_account() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let account_dir = crate::core::paths::FrameworkPaths::default()
        .root
        .join("gh-accounts")
        .join("octo-8914-test");
    registry
        .register(Project {
            gh_account: Some("octo-8914-test".into()),
            ..project_with_config_dir(
                "widget",
                "https://github.com/acme-8914/widget",
                &account_dir,
            )
        })
        .await
        .expect("register");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme-8914/widget.git");

    let vars = for_registry(&registry, workspace.path()).await;
    assert_eq!(
        value_of(&vars, GH_TOKEN_ENV_VAR),
        super::REFUSED_GH_TOKEN,
        "a bare tm account dir resolves to the keyring's active account: {vars:?}"
    );
    assert_eq!(
        value_of(&vars, GH_CONFIG_DIR),
        account_dir.to_string_lossy()
    );
}

/// Why: a project that pins NEITHER key must still resolve to an empty vec via
/// the full registry path — the no-regression case for every project that
/// predates #3025/#5851, now proved with a real matching origin rather than
/// only the no-origin fall-through.
/// Test: itself.
#[tokio::test]
async fn registered_project_pinning_nothing_injects_nothing() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    registry
        .register(project("widget", "https://github.com/acme/widget", None))
        .await
        .expect("register");

    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme/widget.git");

    let vars = for_registry(&registry, workspace.path()).await;
    assert!(vars.is_empty(), "vars: {vars:?}");
}

/// 🔴 #9091: an origin no record pins spawns as its org's `[accounts]` login,
/// through the whole production path. A test build proves no token, so the
/// mapped login reaches `GH_USER` beside the nobody-token.
/// Test: itself.
#[tokio::test]
async fn an_org_mapped_origin_spawns_as_the_mapped_account() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/Acme-9091/widget.git");
    let raw = "[accounts]\nacme-9091 = \"octo-9091-mapped\"\n";
    let load = || OrgAccounts::from_toml(raw, Path::new("/home/u/.trusty-mpm/config.toml"));

    let vars = resolve_gh_account_env_for_registry_with(&registry, workspace.path(), load).await;
    assert_eq!(value_of(&vars, GH_USER_ENV_VAR), "octo-9091-mapped");
    assert_eq!(value_of(&vars, GH_TOKEN_ENV_VAR), super::REFUSED_GH_TOKEN);
}

/// 🔴 #9091 Fail-Open Check: a broken `[accounts]` table gives the spawn the
/// nobody-token through the whole production path, never an empty env.
/// Test: itself.
#[tokio::test]
async fn a_broken_accounts_table_spawns_with_the_nobody_token() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme-9091/widget.git");
    let load = || -> Result<OrgAccounts, OrgAccountsError> {
        OrgAccounts::from_toml(
            "[accounts]\nacme-9091 = octo\n",
            Path::new("/home/u/.trusty-mpm/config.toml"),
        )
    };

    let vars = resolve_gh_account_env_for_registry_with(&registry, workspace.path(), load).await;
    for var in [GH_TOKEN_ENV_VAR, "GH_ENTERPRISE_TOKEN"] {
        assert_eq!(value_of(&vars, var), super::REFUSED_GH_TOKEN, "{var}");
    }
}

/// 🔴 #9091 r2: a record pinned only by `github.account` is a pin. The spawn
/// must not read the `[accounts]` table, and must run as that login — the one
/// the clone and the launch preflight choose.
/// Test: itself.
#[tokio::test]
async fn a_github_account_only_pin_spawns_as_that_login_without_the_map() {
    let dir = tempfile::tempdir().expect("tempdir");
    let registry = ProjectRegistry::load(dir.path()).await.expect("load");
    let origin = "https://github.com/acme-9091/widget";
    registry
        .register(Project {
            github: Some(GithubConfig {
                account: Some("octo-9091-gh".into()),
                ..Default::default()
            }),
            ..project("widget", origin, None)
        })
        .await
        .expect("register");
    let workspace = tempfile::tempdir().expect("workspace tempdir");
    workspace_with_origin(workspace.path(), "https://github.com/acme-9091/widget.git");

    let vars = resolve_gh_account_env_for_registry_with(&registry, workspace.path(), || {
        panic!("a pinned origin must not read the [accounts] table")
    })
    .await;
    assert_eq!(value_of(&vars, GH_USER_ENV_VAR), "octo-9091-gh");
    assert_eq!(value_of(&vars, GH_TOKEN_ENV_VAR), super::REFUSED_GH_TOKEN);
}

/// 🔴 #9091 r2: a record pinned only by `github.token_env` is a pin too. The
/// spawn must not read the `[accounts]` table, and injects nothing, as before
/// #9091. #9091 r3: a blank `config_dir` beside it is absent, not a dir pin.
/// Test: itself.
#[tokio::test]
async fn a_token_env_only_pin_spawns_as_before_without_the_map() {
    for config_dir in [None, Some(PathBuf::from("  "))] {
        let dir = tempfile::tempdir().expect("tempdir");
        let registry = ProjectRegistry::load(dir.path()).await.expect("load");
        let origin = "https://github.com/acme-9091/widget";
        registry
            .register(Project {
                github: Some(GithubConfig {
                    token_env: Some("TM_9091_TOKEN".into()),
                    config_dir: config_dir.clone(),
                    ..Default::default()
                }),
                ..project("widget", origin, None)
            })
            .await
            .expect("register");
        let workspace = tempfile::tempdir().expect("workspace tempdir");
        workspace_with_origin(workspace.path(), "https://github.com/acme-9091/widget.git");

        let vars = resolve_gh_account_env_for_registry_with(&registry, workspace.path(), || {
            panic!("a pinned origin must not read the [accounts] table")
        })
        .await;
        assert!(vars.is_empty(), "{config_dir:?}: {vars:?}");
    }
}

// ── #8510: an account-only spawn pin never falls back to "no identity" ─────

/// A repository whose registry record pins only an account.
const SPAWN_ORIGIN: &str = "https://github.com/duettoresearch/jev-matching";

/// An Enterprise Server repository whose registry record pins only an account.
const GHES_ORIGIN: &str = "https://ghe.corp/duettoresearch/jev-matching";

/// The account-only `octo-pinned` pin.
fn account_only_pin() -> super::PinnedGhIdentity {
    super::PinnedGhIdentity {
        account: Some("octo-pinned".into()),
        ..Default::default()
    }
}

/// Spawn the account-only pin for `origin`, proving through one candidate
/// dir with `probe` and `check` — the production prover over table fakes.
fn spawn_with(
    origin: &str,
    dir: &Path,
    probe: &TableProbe,
    check: &TableCheck,
) -> super::GhSpawnEnv {
    let sources = crate::core::gh_account_dir::AccountDirSources {
        own_config_dir: Some(dir.to_path_buf()),
        ..Default::default()
    };
    let prover = crate::core::gh_account_proof::AccountProver {
        sources: &sources,
        probe,
        check,
        cache: None,
    };
    let aliases = crate::session_manager::ssh_host_alias::SshHostAliases::empty();
    super::pinned_spawn_env(&account_only_pin(), origin, |login| {
        super::spawn_proof(&prover, login, origin, &aliases)
    })
    .expect("a pin must produce an env")
    .expect("the spawn env never errs")
}

/// A github.com candidate dir whose `-u octo-pinned` token authenticates as
/// `who`; `who: Err` is a failed `GET /user`.
fn github_spawn(who: Result<&str, &str>) -> super::GhSpawnEnv {
    let root = tempfile::tempdir().expect("tempdir");
    let dir = migrated_dir(root.path());
    let probe = TableProbe::default().answer(&dir, "github.com", "octo-pinned", Ok("tok-bob"));
    let check = TableCheck::default().answer("https://api.github.com", "tok-bob", who);
    spawn_with(SPAWN_ORIGIN, &dir, &probe, &check)
}

/// An account-only pin spawns with the proven token itself, never a config
/// dir, and with the nobody-token for the other host class.
/// Test: itself.
#[test]
fn an_account_only_spawn_pin_gets_the_proven_token() {
    let env = github_spawn(Ok("octo-pinned"));
    assert_eq!(value_of(&env.vars, "GH_TOKEN"), "tok-bob");
    assert_eq!(
        value_of(&env.vars, "GH_ENTERPRISE_TOKEN"),
        super::REFUSED_GH_TOKEN
    );
    assert_eq!(value_of(&env.vars, "GH_USER"), "octo-pinned");
    assert!(
        !env.vars.iter().any(|(k, _)| k == GH_CONFIG_DIR),
        "{:?}",
        env.vars
    );
    assert!(env.warning.is_none(), "{:?}", env.warning);
}

/// 🔴 #8510: an account-only pin with no proven token must NOT spawn with no
/// identity (the global account). Both token variables get the nobody-token,
/// and a warning names the reason and the fix.
/// Test: itself.
#[test]
fn an_account_only_spawn_pin_with_no_proven_token_fails_closed() {
    let env = super::pinned_spawn_env(&account_only_pin(), SPAWN_ORIGIN, |_| {
        Err("/x: the token gh returned for 'octo-pinned' authenticates as 'octo-other'".into())
    })
    .expect("a pinned account must never resolve to no identity")
    .expect("the refusal rides the env, not an error");
    for var in ["GH_TOKEN", "GH_ENTERPRISE_TOKEN"] {
        assert_eq!(value_of(&env.vars, var), super::REFUSED_GH_TOKEN, "{var}");
    }
    let warning = env.warning.expect("the refusal must be logged");
    assert!(
        warning.contains("authenticates as 'octo-other'")
            && warning.contains(&format!(
                "tm projects register <name> --repo-url {SPAWN_ORIGIN} --gh-account octo-pinned \
                 --gh-config-dir <dir>"
            )),
        "got: {warning}"
    );
}

/// #8914 HIGH 3: a pinned `config_dir` is never used bare; its account is
/// proven, and an unproven one gets the nobody-token. `session_spawn_env`
/// adds the dir itself.
/// Test: itself.
#[test]
fn a_config_dir_spawn_pin_is_proven_not_used_bare() {
    let dir = tempfile::tempdir().expect("tempdir");
    write_hosts_yml(dir.path(), "octo-pinned");
    let pinned = super::PinnedGhIdentity {
        account: Some("octo-pinned".into()),
        config_dir: Some(dir.path().to_path_buf()),
        ..Default::default()
    };
    let env = super::pinned_spawn_env(&pinned, SPAWN_ORIGIN, |login| {
        assert_eq!(login, "octo-pinned");
        Err("not proven".into())
    })
    .expect("a pin must produce an env")
    .expect("the spawn env never errs");
    assert_eq!(
        value_of(&env.vars, GH_TOKEN_ENV_VAR),
        super::REFUSED_GH_TOKEN
    );
}

/// 🔴 #8510 CRITICAL: `GET /user` says the token is another account's: the
/// nobody-token, and the warning names no token.
/// Test: itself.
#[test]
fn a_spawn_pin_refuses_a_token_for_another_account() {
    let env = github_spawn(Ok("octo-other"));
    assert_eq!(value_of(&env.vars, "GH_TOKEN"), super::REFUSED_GH_TOKEN);
    let warning = env.warning.expect("the refusal must be logged");
    assert!(
        warning.contains("authenticates as 'octo-other'") && !warning.contains("tok-"),
        "got: {warning}"
    );
}

/// 🔴 #8510 MEDIUM: the token lookup succeeds but `GET /user` times out: not
/// proven, so the nobody-token — never the unchecked token.
/// Test: itself.
#[test]
fn a_spawn_pin_refuses_when_the_user_check_fails() {
    let env = github_spawn(Err(
        "GET https://api.github.com/user did not answer in time",
    ));
    assert_eq!(value_of(&env.vars, "GH_TOKEN"), super::REFUSED_GH_TOKEN);
    let warning = env.warning.expect("the refusal must be logged");
    assert!(warning.contains("did not answer in time"), "got: {warning}");
}

/// 🔴 #8510 HIGH: gh on an Enterprise Server host reads `GH_ENTERPRISE_TOKEN`
/// and ignores `GH_TOKEN`, so the proven token goes there, and `GH_TOKEN` gets
/// the nobody-token so it never reaches api.github.com.
/// Test: itself.
#[test]
fn a_ghes_spawn_pin_puts_the_token_in_gh_enterprise_token() {
    let root = tempfile::tempdir().expect("tempdir");
    let dir = migrated_dir(root.path());
    let probe = TableProbe::default().answer(&dir, "ghe.corp", "octo-pinned", Ok("tok-ghe"));
    let check =
        TableCheck::default().answer("https://ghe.corp/api/v3", "tok-ghe", Ok("octo-pinned"));
    let env = spawn_with(GHES_ORIGIN, &dir, &probe, &check);
    assert_eq!(value_of(&env.vars, "GH_ENTERPRISE_TOKEN"), "tok-ghe");
    assert_eq!(value_of(&env.vars, "GH_TOKEN"), super::REFUSED_GH_TOKEN);
    assert!(env.warning.is_none(), "{:?}", env.warning);
}

/// 🔴 #8510 HIGH: an Enterprise Server pin with no proven token fails closed
/// on that host too — `GH_ENTERPRISE_TOKEN` is the nobody-token.
/// Test: itself.
#[test]
fn a_ghes_spawn_pin_refusal_blanks_both_token_vars() {
    let root = tempfile::tempdir().expect("tempdir");
    let dir = migrated_dir(root.path());
    let probe = TableProbe::default().answer(&dir, "ghe.corp", "octo-pinned", Ok("tok-ghe"));
    let check = TableCheck::default().answer("https://ghe.corp/api/v3", "tok-ghe", Ok("other"));
    let env = spawn_with(GHES_ORIGIN, &dir, &probe, &check);
    for var in ["GH_TOKEN", "GH_ENTERPRISE_TOKEN"] {
        assert_eq!(value_of(&env.vars, var), super::REFUSED_GH_TOKEN, "{var}");
    }
}

/// 🔴 #8510 LOW: a pinned project whose identity task panicked fails closed
/// instead of spawning with no vars (the global account).
/// Test: itself.
#[tokio::test]
async fn a_panicked_spawn_env_task_fails_closed() {
    let joined = tokio::task::spawn_blocking(|| -> Vec<(String, String)> {
        panic!("identity task panicked")
    })
    .await;
    let vars = super::joined_spawn_vars(
        joined,
        &account_only_pin(),
        SPAWN_ORIGIN,
        Path::new("/work/jev-matching"),
    );
    for var in ["GH_TOKEN", "GH_ENTERPRISE_TOKEN"] {
        assert_eq!(value_of(&vars, var), super::REFUSED_GH_TOKEN, "{var}");
    }
    assert_eq!(value_of(&vars, "GH_USER"), "octo-pinned");
}

/// A `tracing` writer that appends every formatted line to a shared buffer.
#[derive(Clone, Default)]
struct LogBuffer(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);

impl std::io::Write for LogBuffer {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// Run a github.com spawn whose token authenticates as `who` — resolution,
/// proof and the production logger alike — under a capturing subscriber;
/// return the injected vars and every log line.
fn logged_spawn(who: Result<&str, &str>) -> (Vec<(String, String)>, String) {
    let buffer = LogBuffer::default();
    let writer = buffer.clone();
    let subscriber = tracing_subscriber::fmt()
        .with_writer(move || writer.clone())
        .with_ansi(false)
        .with_max_level(tracing::Level::TRACE)
        .finish();
    // #8510 r6: the spawn itself runs under the subscriber, so a token logged
    // while proving it is captured, not only what `log_spawn_env` writes.
    let vars = tracing::subscriber::with_default(subscriber, || {
        super::log_spawn_env(Some(Ok(github_spawn(who))), Path::new("/work/jev-matching"))
    });
    let bytes = buffer
        .0
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone();
    (vars, String::from_utf8(bytes).expect("utf-8 log"))
}

/// 🔴 #8510 r4: a spawn env carrying the proven token prints no token in
/// `{:?}`.
/// Test: itself.
#[test]
fn spawn_env_debug_redacts_every_token() {
    let env = github_spawn(Ok("octo-pinned"));
    assert_eq!(value_of(&env.vars, "GH_TOKEN"), "tok-bob");
    let shown = format!("{env:?}");
    assert!(!shown.contains("tok-bob"), "shown: {shown}");
    assert!(
        shown.contains("GH_USER") && shown.contains("octo-pinned"),
        "shown: {shown}"
    );
}

/// 🔴 #8510 r4: an origin behind a `~/.ssh/config` alias proves on the host
/// the alias names — the host the daemon's `repo_slug_for` derives — never on
/// the alias itself; an alias nothing renames refuses.
/// Test: itself.
#[test]
fn a_spawn_proves_an_ssh_aliased_origin_on_the_daemons_host() {
    let aliased = "git@github-duetto:duettoresearch/jev-matching.git";
    let aliases = crate::session_manager::ssh_host_alias::SshHostAliases::parse(
        "Host github-duetto\n  HostName github.com\n",
    );
    let daemon_slug =
        crate::session_manager::worktree_repo_slug::parse_repo_slug(aliased, &aliases)
            .expect("the daemon resolves the alias");
    assert_eq!(daemon_slug, "duettoresearch/jev-matching");

    let root = tempfile::tempdir().expect("tempdir");
    let dir = migrated_dir(root.path());
    let probe = TableProbe::default().answer(&dir, "github.com", "octo-pinned", Ok("tok-bob"));
    let check =
        TableCheck::default().answer("https://api.github.com", "tok-bob", Ok("octo-pinned"));
    let sources = crate::core::gh_account_dir::AccountDirSources {
        own_config_dir: Some(dir.clone()),
        ..Default::default()
    };
    let prover = crate::core::gh_account_proof::AccountProver {
        sources: &sources,
        probe: &probe,
        check: &check,
        cache: None,
    };
    let proven = super::spawn_proof(&prover, "octo-pinned", aliased, &aliases)
        .expect("the aliased origin proves on github.com");
    assert_eq!(proven.host, "github.com");

    let unresolved = crate::session_manager::ssh_host_alias::SshHostAliases::empty();
    let err = super::spawn_proof(&prover, "octo-pinned", aliased, &unresolved)
        .expect_err("an alias nothing renames names no host");
    assert!(err.contains("'github-duetto'"), "got: {err}");
    assert_eq!(probe.calls().len(), 1, "the refusal never runs gh");
}

/// 🔴 #8510: no arm writes a token to the log — neither the injected proven
/// token nor the unproven one a refusal rejected. The refusals still log their
/// reason, so the capture is not vacuous.
/// Test: itself.
#[test]
fn a_spawn_pin_logs_no_token_in_any_arm() {
    let (vars, log) = logged_spawn(Ok("octo-pinned"));
    assert_eq!(value_of(&vars, "GH_TOKEN"), "tok-bob");
    assert!(!log.contains("tok-"), "a token reached the log: {log}");

    for who in [
        Ok("octo-other"),
        Err("GET https://api.github.com/user answered HTTP 401"),
    ] {
        let (vars, log) = logged_spawn(who);
        assert_eq!(value_of(&vars, "GH_TOKEN"), super::REFUSED_GH_TOKEN);
        assert!(
            log.contains("pinned to gh account 'octo-pinned'"),
            "the refusal must be logged: {log}"
        );
        assert!(!log.contains("tok-"), "a token reached the log: {log}");
    }
}

/// #9124: both `proof_origin` refusals quote the origin, and both reach the
/// log; neither carries the origin's token.
/// Test: itself.
#[test]
fn proof_origin_refusals_never_quote_the_origin_token() {
    const TOKEN: &str = "ghp_9124ProofOriginSyntheticToken0";
    let aliases = crate::session_manager::ssh_host_alias::SshHostAliases::empty();
    for origin in [
        format!("https://octo:{TOKEN}@github.com/"),
        format!("ssh://octo:{TOKEN}@github-alias/acme/widget.git"),
    ] {
        let err = crate::session_manager::worktree_reclaim_gh::proof_origin(&origin, &aliases)
            .expect_err("the origin names no provable host");
        assert!(!err.contains(TOKEN), "the token reached the refusal");
        assert!(err.contains("://***@"), "{err}");
    }
}