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
//! Tests for `tm register` positional resolution and alias derivation (#4912).
//!
//! Why: four things must be pinned or they regress silently.
//! - `owner/repo` is the primary form and must resolve to the GitHub URL with
//!   the canonical `owner-repo` alias. Before the review it registered the
//!   literal string as a URL whose host was `owner` — unclonable, alias
//!   `trusty-tools`, exit 0, and no collision with the later correct entry.
//! - The legacy `<alias> <url>` order must still resolve correctly.
//! - The derived alias must be HYPHEN-joined `owner-repo` for every URL shape.
//! - The shapes that should NOT resolve — relative paths, host-only URLs,
//!   browser pastes — must still be refused rather than swept into shorthand.
//!
//! What: unit tests over [`super::classify`], [`super::resolve_register_args`],
//! and the boundary path splitter, plus end-to-end tests through
//! `standalone::register_cmd` proving a refusal never touches `registry.json`.
//! Test: this file.

use super::{Positional, classify, looks_like_repo, path_segments, resolve_register_args};

// ---------------------------------------------------------------------------
// Classification
// ---------------------------------------------------------------------------

/// Every shape lands in exactly one case. The order of the arms is load-bearing:
/// a dot-prefixed path must be caught BEFORE the host-shape test, which it would
/// otherwise pass on its own leading dot — `./repo` on the `.` in `.`, and
/// `.hidden/repo` on the `.` in `.hidden`.
#[test]
fn classify_sorts_every_shape() {
    // Full URLs.
    for s in [
        "https://github.com/owner/repo",
        "git@github.com:owner/repo.git",
        "ssh://git@git.example.com:2222/team/thing.git",
        "github.com/owner/repo",
        "localhost:3000/owner/repo",
        "/srv/git/repo.git",
        "~/src/repo.git",
    ] {
        assert!(matches!(classify(s), Positional::Url(_)), "{s} not a URL");
    }

    // GitHub shorthand — the primary form.
    assert_eq!(
        classify("bobmatnyc/trusty-tools"),
        Positional::Shorthand {
            account: None,
            owner: "bobmatnyc",
            repo: "trusty-tools"
        }
    );
    assert_eq!(
        classify("123/repo"),
        Positional::Shorthand {
            account: None,
            owner: "123",
            repo: "repo"
        }
    );
    // A repo name may carry a dot; an owner may not, which is what keeps
    // `github.com/o/r` on the URL side without a host list.
    assert_eq!(
        classify("owner/repo.js"),
        Positional::Shorthand {
            account: None,
            owner: "owner",
            repo: "repo.js"
        }
    );

    // Relative paths — never shorthand, and never a host.
    for s in [
        "./repo",
        "../repo",
        ".",
        "..",
        ".hidden/repo",
        ".config/x/y",
    ] {
        assert_eq!(classify(s), Positional::RelativePath, "{s} misclassified");
    }

    // Neither.
    for s in ["my-alias", "owner/", "a/b/c", "owner/re po", "owner:repo"] {
        assert_eq!(classify(s), Positional::Other, "{s} misclassified");
    }
}

/// Aliases are `^[a-z0-9][a-z0-9._-]*$` — none can be read as a repo, so the
/// two-positional routing can never mistake one for the other.
#[test]
fn looks_like_repo_rejects_aliases() {
    for alias in ["my-alias", "proj", "a.b-c", "repo123", "owner-repo"] {
        assert!(!looks_like_repo(alias), "{alias} misread as a repo");
    }
}

// ---------------------------------------------------------------------------
// GitHub shorthand — the primary form
// ---------------------------------------------------------------------------

/// THE #4912 PRIMARY FORM. `owner/repo` resolves to the GitHub URL and derives
/// the canonical `owner-repo` alias. GitHub is assumed, matching the
/// `is_github_remote` gate `tm launch` already applies.
#[test]
fn shorthand_resolves_to_github() {
    let (alias, url) = resolve_register_args("bobmatnyc/trusty-tools", None).unwrap();
    assert_eq!(url, "https://github.com/bobmatnyc/trusty-tools");
    assert_eq!(alias, "bobmatnyc-trusty-tools");

    // The alias must match what the full URL derives — one derivation path.
    let (from_url, _) =
        resolve_register_args("https://github.com/bobmatnyc/trusty-tools", None).unwrap();
    assert_eq!(alias, from_url);
}

/// An all-numeric owner is valid shorthand, and the port-drop in the path
/// splitter must not eat it.
#[test]
fn shorthand_numeric_owner() {
    let (alias, url) = resolve_register_args("123/repo", None).unwrap();
    assert_eq!(url, "https://github.com/123/repo");
    assert_eq!(alias, "123-repo");
}

/// Shorthand with an explicit alias, in both positional orders.
#[test]
fn shorthand_with_explicit_alias() {
    let (alias, url) = resolve_register_args("owner/repo", Some("shiny")).unwrap();
    assert_eq!(alias, "shiny");
    assert_eq!(url, "https://github.com/owner/repo");

    let (alias, url) = resolve_register_args("shiny", Some("owner/repo")).unwrap();
    assert_eq!(alias, "shiny");
    assert_eq!(url, "https://github.com/owner/repo");
}

/// Relative paths are paths, not shorthand — they resolve against the process
/// cwd but would be cloned from elsewhere. Each shape refused explicitly.
///
/// The dot-prefixed directory forms matter beyond the obvious `./`: a leading
/// dot lands inside the first segment, so `.hidden/repo` passed the "first
/// segment contains a dot" host test and reached the registry as a host named
/// `.hidden`. No hostname may begin with a dot, so the guard covers any leading
/// `.` rather than just `./` and `../`.
#[test]
fn relative_paths_are_never_shorthand() {
    for s in [
        "./repo",
        "../repo",
        "./owner/repo",
        "../a/b",
        ".hidden/repo",
        ".github/workflows",
    ] {
        let err = resolve_register_args(s, None).unwrap_err().to_string();
        assert!(
            err.contains("relative path"),
            "{s} must be refused as a path, got: {err}"
        );
    }
}

/// Absolute paths stay accepted as local clone sources — they worked before
/// #4912 and are unambiguous, unlike the relative forms. Home-relative paths are
/// accepted too, but only because they are expanded first; see
/// `home_relative_path_is_expanded` for what makes them clonable.
#[test]
fn absolute_and_home_paths_are_accepted() {
    let (alias, url) = resolve_register_args("/srv/git/repo.git", Some("local")).unwrap();
    assert_eq!(alias, "local");
    assert_eq!(url, "/srv/git/repo.git", "an absolute path is stored as-is");
    assert!(resolve_register_args("~/src/repo.git", Some("home")).is_ok());
}

/// `~/src/repo.git` was accepted and stored verbatim, but `clone_repo`
/// (`core::standalone::load`) runs `git` with no shell, so `git clone
/// '~/src/repo.git'` fails with "repository does not exist". Expand the tilde so
/// the stored path is the absolute one the user meant.
#[test]
fn home_relative_path_is_expanded() {
    let home = dirs::home_dir().expect("home directory");
    let (_, url) = resolve_register_args("~/src/repo.git", Some("home")).unwrap();
    assert_eq!(url, home.join("src/repo.git").to_string_lossy());
    assert!(!url.contains('~'), "tilde must not survive: {url}");
}

// ---------------------------------------------------------------------------
// Positional order
// ---------------------------------------------------------------------------

/// New order: `tm register <url> <alias>`.
#[test]
fn two_args_url_first() {
    let (alias, url) =
        resolve_register_args("https://github.com/owner/repo", Some("my-alias")).unwrap();
    assert_eq!(alias, "my-alias");
    assert_eq!(url, "https://github.com/owner/repo");
}

/// Legacy order: `tm register <alias> <url>` must keep working (#4912).
#[test]
fn two_args_legacy_alias_first() {
    let (alias, url) =
        resolve_register_args("my-alias", Some("https://github.com/owner/repo")).unwrap();
    assert_eq!(alias, "my-alias");
    assert_eq!(url, "https://github.com/owner/repo");
}

/// Legacy order with the SSH form — the `git@` prefix is the URL signal.
#[test]
fn two_args_legacy_ssh_url_second() {
    let (alias, url) =
        resolve_register_args("proj", Some("git@github.com:owner/repo.git")).unwrap();
    assert_eq!(alias, "proj");
    assert_eq!(url, "git@github.com:owner/repo.git");
}

/// One positional: the alias is derived, not required.
#[test]
fn one_arg_derives() {
    let (alias, url) = resolve_register_args("https://github.com/owner/repo", None).unwrap();
    assert_eq!(alias, "owner-repo");
    assert_eq!(url, "https://github.com/owner/repo");
}

/// A lone argument naming nothing is a usage error, not a half-registration.
/// The message must show both accepted forms.
#[test]
fn one_arg_non_repo_errors() {
    for s in ["my-alias", "owner/", "a/b/c"] {
        let err = resolve_register_args(s, None).unwrap_err().to_string();
        assert!(
            err.contains("does not name a repository"),
            "{s}: unexpected {err}"
        );
        assert!(err.contains("<owner>/<repo>"), "no remedy in: {err}");
    }
}

/// Two repo-shaped arguments are ambiguous — refuse rather than guess.
#[test]
fn two_urls_error() {
    for (a, b) in [
        ("https://github.com/a/b", "https://github.com/c/d"),
        ("owner/repo", "other/repo"),
    ] {
        let err = resolve_register_args(a, Some(b)).unwrap_err().to_string();
        assert!(
            err.contains("both arguments name a repository"),
            "({a}, {b}): unexpected {err}"
        );
    }
}

/// Two alias-shaped arguments mean no repo was supplied at all.
#[test]
fn two_non_urls_error() {
    let err = resolve_register_args("alpha", Some("beta"))
        .unwrap_err()
        .to_string();
    assert!(
        err.contains("neither argument names a repository"),
        "unexpected: {err}"
    );
}

// ---------------------------------------------------------------------------
// Alias derivation from full URLs
// ---------------------------------------------------------------------------

/// Every real URL shape derives the same HYPHEN-joined `owner-repo`. Full
/// non-GitHub URLs keep working — only non-GitHub *shorthand* is deferred.
/// A URL that already carries a scheme is stored verbatim; the scheme-less form
/// is the one exception and has its own test.
#[test]
fn derives_from_every_url_shape() {
    let cases = [
        ("https://github.com/owner/repo", "owner-repo"),
        ("https://github.com/owner/repo.git", "owner-repo"),
        ("https://github.com/owner/repo/", "owner-repo"),
        ("https://github.com/owner/repo.git/", "owner-repo"),
        ("git@github.com:owner/repo.git", "owner-repo"),
        ("git@github.com:owner/repo", "owner-repo"),
        // Non-GitHub hosts derive identically — nothing here is GitHub-specific.
        ("https://gitlab.com/acme/widget.git", "acme-widget"),
        ("https://git.example.com/team/thing", "team-thing"),
        (
            "ssh://git@git.example.com:2222/team/thing.git",
            "team-thing",
        ),
        ("git@bitbucket.org:team/thing.git", "team-thing"),
    ];
    for (url, want) in cases {
        let (alias, got_url) = resolve_register_args(url, None).unwrap();
        assert_eq!(alias, want, "wrong alias for {url}");
        assert_eq!(got_url, url, "URL must be stored verbatim");
    }
}

/// A scheme-less host classified as a URL and was stored verbatim — but
/// `git clone github.com/bobmatnyc/trusty-tools` fails with `repository … does
/// not exist`, long after `tm register` exited 0. Prepend the scheme so the
/// stored string is one git can actually fetch.
#[test]
fn scheme_less_host_gains_https() {
    let cases = [
        (
            "github.com/owner/repo",
            "https://github.com/owner/repo",
            "owner-repo",
        ),
        ("a.b/c", "https://a.b/c", "c"),
        ("localhost/repo", "https://localhost/repo", "repo"),
    ];
    for (input, want_url, want_alias) in cases {
        let (alias, url) = resolve_register_args(input, None).unwrap();
        assert_eq!(url, want_url, "for {input}");
        assert_eq!(alias, want_alias, "for {input}");
    }
}

/// No discernible owner → fall back to the repo segment alone (erroring would
/// reject valid self-hosted single-segment paths).
#[test]
fn no_owner_falls_back_to_repo() {
    let (alias, _) = resolve_register_args("https://example.com/repo", None).unwrap();
    assert_eq!(alias, "repo");
}

/// A host-only URL names nothing. BOTH forms must error — the no-trailing-slash
/// one silently derived `examplecom` before the review.
#[test]
fn host_only_url_errors() {
    for url in [
        "https://example.com/",
        "https://example.com",
        "https://example.com:8080",
        "git@github.com:",
    ] {
        let err = resolve_register_args(url, None).unwrap_err().to_string();
        assert!(
            err.contains("no owner/repo path"),
            "{url} must be refused, got: {err}"
        );
    }
}

/// Browser pastes point INTO a repo and derive nonsense from the last two path
/// segments (`tree-main`, `pull-4914`). Refuse with the repo-root form named.
#[test]
fn browser_paste_shapes_are_rejected() {
    let cases = [
        "https://github.com/owner/repo/tree/main",
        "https://github.com/owner/repo/pull/4914",
        "https://github.com/owner/repo/blob/main/README.md",
        "https://github.com/owner/repo/issues/12",
        "https://github.com/owner/repo/commit/abc123",
        "https://gitlab.com/group/sub/repo/-/blob/main/x",
    ];
    for url in cases {
        let err = resolve_register_args(url, None).unwrap_err().to_string();
        assert!(
            err.contains("points inside a repository"),
            "{url} must be refused, got: {err}"
        );
        assert!(err.contains("repository root"), "no remedy in: {err}");
    }
}

/// The single-word GitHub tab URL is the most-pasted shape of all, and the
/// interior rule alone never caught it: on a 3-segment path the keyword IS the
/// last segment, which is exempt so a repo named `tree` survives. So
/// `…/o/r/issues` registered `r-issues → https://github.com/o/r/issues` at exit
/// 0 — unclonable, and `r-issues` never collides with the canonical `o-r`, so
/// nothing later signals it. On GitHub any path past `owner/repo` is a web-UI
/// path, which catches these regardless of the keyword list.
#[test]
fn github_tab_urls_are_rejected() {
    let cases = [
        "https://github.com/owner/repo/issues",
        "https://github.com/owner/repo/pulls",
        "https://github.com/owner/repo/releases",
        "https://github.com/owner/repo/wiki",
        "https://github.com/owner/repo/actions",
        // Not in NON_REPO_SEGMENTS at all — the host rule still refuses it.
        "https://github.com/owner/repo/settings",
        // Scheme-less and SSH forms resolve to the same host.
        "github.com/owner/repo/issues",
        "git@github.com:owner/repo/issues",
    ];
    for url in cases {
        let err = resolve_register_args(url, None).unwrap_err().to_string();
        assert!(
            err.contains("points inside a repository"),
            "{url} must be refused, got: {err}"
        );
        assert!(err.contains("repository root"), "no remedy in: {err}");
    }
}

/// The web-path words are only refused in an interior position — a repo actually
/// NAMED `tree` (or a GitLab subgroup path ending in one) still works. The
/// GitHub host rule must not cost this precision.
#[test]
fn repo_named_like_a_web_path_is_ok() {
    let (alias, _) = resolve_register_args("https://github.com/owner/tree", None).unwrap();
    assert_eq!(alias, "owner-tree");
    let (alias, _) = resolve_register_args("https://gitlab.com/group/sub/blob", None).unwrap();
    assert_eq!(alias, "sub-blob");
}

/// A local path has no host, so it has no web UI and the keyword rule must not
/// run on it. These all registered before #4912 and were then refused with
/// "points inside a repository" — nonsense for a filesystem path, and with no
/// workaround, since the suggested remedy does not apply. The `file://` form is
/// the same shape wearing a scheme, which is why the guard keys off an empty
/// host rather than a leading `/`.
#[test]
fn local_paths_skip_the_web_path_rule() {
    for input in [
        "/Users/me/actions/repo.git",
        "/home/bob/raw/myrepo",
        "/srv/git/tree/repo.git",
        "file:///Users/me/actions/repo.git",
    ] {
        resolve_register_args(input, Some("local"))
            .unwrap_or_else(|e| panic!("{input} must register, got: {e}"));
    }

    // `~/…` is expanded to an absolute path BEFORE the guard runs, so it is
    // covered by the same empty-host rule. If that ordering ever changes, this
    // is what catches it.
    let (_, url) = resolve_register_args("~/tree/repo.git", Some("home")).unwrap();
    assert!(url.ends_with("/tree/repo.git"), "unexpected: {url}");
    assert!(!url.contains('~'), "tilde must not survive: {url}");
}

/// A query string or fragment is never part of a clone URL, and both corrupt the
/// derived alias. Strip them rather than storing an unclonable string.
#[test]
fn query_and_fragment_are_stripped() {
    for input in [
        "https://github.com/owner/repo?tab=readme-ov-file",
        "https://github.com/owner/repo#readme",
    ] {
        let (alias, url) = resolve_register_args(input, None).unwrap();
        assert_eq!(alias, "owner-repo", "for {input}");
        assert_eq!(url, "https://github.com/owner/repo", "for {input}");
    }
}

/// The `a/b-c` vs `a-b/c` flattening ambiguity: both derive the SAME alias.
/// Accepted, not special-cased — the second registration is caught by the
/// ordinary different-URL collision refusal.
#[test]
fn hyphen_flattening_ambiguity_is_accepted_and_collides() {
    let (a, _) = resolve_register_args("a/b-c", None).unwrap();
    let (b, _) = resolve_register_args("a-b/c", None).unwrap();
    assert_eq!(a, "a-b-c");
    assert_eq!(b, "a-b-c");
}

// ---------------------------------------------------------------------------
// Boundary path splitter
// ---------------------------------------------------------------------------

/// The local validator must agree with the shared deriver on where the host
/// ends, for every shape both see — otherwise a refusal fires on a URL the
/// deriver would have handled, or vice versa.
#[test]
fn path_segments_matches_every_url_shape() {
    let cases: [(&str, Vec<&str>); 8] = [
        ("https://github.com/owner/repo", vec!["owner", "repo"]),
        ("https://github.com/owner/repo/", vec!["owner", "repo"]),
        ("github.com/owner/repo", vec!["owner", "repo"]),
        ("git@github.com:owner/repo.git", vec!["owner", "repo.git"]),
        (
            "ssh://git@git.example.com:2222/team/thing.git",
            vec!["team", "thing.git"],
        ),
        ("https://example.com:8080/o/r", vec!["o", "r"]),
        ("https://example.com/repo", vec!["repo"]),
        (
            "https://github.com/o/r/tree/main",
            vec!["o", "r", "tree", "main"],
        ),
    ];
    for (url, want) in cases {
        assert_eq!(path_segments(url), want, "wrong segments for {url}");
    }
}

/// The port-drop must key off the `:` host terminator, not "the first segment is
/// digits" — otherwise an all-numeric owner is swallowed. That matters more now
/// that `123/repo` is valid shorthand.
#[test]
fn path_segments_keeps_numeric_owner() {
    assert_eq!(
        path_segments("https://github.com/123/repo"),
        ["123", "repo"]
    );
    let (alias, _) = resolve_register_args("https://github.com/123/repo", None).unwrap();
    assert_eq!(alias, "123-repo");
}

/// A host with no path yields no segments — with or without a trailing slash.
#[test]
fn path_segments_host_only() {
    for url in ["https://example.com", "https://example.com/", "example.com"] {
        assert!(
            path_segments(url).is_empty(),
            "{url} must yield no path segments"
        );
    }
}

// ---------------------------------------------------------------------------
// Collision behaviour, end to end through the command handler
// ---------------------------------------------------------------------------

/// A derived alias already bound to a DIFFERENT URL must refuse and leave the
/// registry file byte-identical. Silent rebinding is the failure shape #4912
/// explicitly forbids.
#[test]
fn collision_refuses_and_leaves_registry_untouched() {
    let dir = tempfile::TempDir::new().unwrap();
    let paths = crate::commands::managed_root::ManagedPaths::from_root(dir.path().to_path_buf());

    // First registration derives `a-b-c` from `a/b-c`.
    crate::commands::standalone::register_cmd(&paths, "a/b-c", None, false).unwrap();
    let registry_path = dir.path().join("registry.json");
    let before = std::fs::read(&registry_path).unwrap();

    // `a-b/c` flattens to the same alias but is a different URL.
    let err = crate::commands::standalone::register_cmd(&paths, "a-b/c", None, false).unwrap_err();
    let msg = format!("{err:#}");
    assert!(
        msg.contains("already registered"),
        "collision must be loud: {msg}"
    );

    let after = std::fs::read(&registry_path).unwrap();
    assert_eq!(
        before, after,
        "a refused registration must not mutate the registry"
    );
}

/// A refused argument must not create a registry file at all — the refusal
/// happens before any load or save.
#[test]
fn rejected_url_writes_nothing() {
    let dir = tempfile::TempDir::new().unwrap();
    let paths = crate::commands::managed_root::ManagedPaths::from_root(dir.path().to_path_buf());
    for bad in ["./repo", "https://example.com", "a/b/c"] {
        assert!(
            crate::commands::standalone::register_cmd(&paths, bad, None, false).is_err(),
            "{bad} must be refused"
        );
    }
    assert!(
        !dir.path().join("registry.json").exists(),
        "a refused argument must not write a registry"
    );
}

/// Shorthand registers end to end and stores the resolved GitHub URL.
#[test]
fn shorthand_registers_end_to_end() {
    let dir = tempfile::TempDir::new().unwrap();
    let paths = crate::commands::managed_root::ManagedPaths::from_root(dir.path().to_path_buf());
    crate::commands::standalone::register_cmd(&paths, "bobmatnyc/trusty-tools", None, false)
        .unwrap();

    let registry =
        trusty_mpm::core::standalone::registry::ManagedRegistry::load(dir.path()).unwrap();
    let entries = registry.list();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].alias, "bobmatnyc-trusty-tools");
    assert_eq!(entries[0].url, "https://github.com/bobmatnyc/trusty-tools");
}

/// Re-registering the SAME repo is idempotent, and the shorthand and full-URL
/// forms are the same registration — not two.
#[test]
fn same_url_reregistration_is_idempotent() {
    let dir = tempfile::TempDir::new().unwrap();
    let paths = crate::commands::managed_root::ManagedPaths::from_root(dir.path().to_path_buf());
    crate::commands::standalone::register_cmd(&paths, "owner/repo", None, false).unwrap();
    crate::commands::standalone::register_cmd(&paths, "https://github.com/owner/repo", None, false)
        .unwrap();

    let registry =
        trusty_mpm::core::standalone::registry::ManagedRegistry::load(dir.path()).unwrap();
    let entries = registry.list();
    assert_eq!(entries.len(), 1, "shorthand and full URL are one repo");
    assert_eq!(entries[0].alias, "owner-repo");
}

// ---------------------------------------------------------------------------
// #7166: `<login>@<owner>/<repo>` account-selector shorthand.
// ---------------------------------------------------------------------------

/// `<login>@<owner>/<repo>` classifies as shorthand carrying the account, and
/// `looks_like_repo` still accepts it — the same predicate `tm register`,
/// `tm run`, and the `tm <token>` bare form all share.
#[test]
fn account_shorthand_classifies_and_looks_like_repo() {
    assert_eq!(
        classify("bob-duetto@duettoresearch/poc-hotel-supply"),
        Positional::Shorthand {
            account: Some("bob-duetto"),
            owner: "duettoresearch",
            repo: "poc-hotel-supply",
        }
    );
    assert!(looks_like_repo(
        "bob-duetto@duettoresearch/poc-hotel-supply"
    ));
    assert_eq!(
        super::embedded_account("bob-duetto@duettoresearch/poc-hotel-supply"),
        Some("bob-duetto")
    );
}

/// `git@github.com:owner/repo.git` (the SSH clone-URL form) is untouched by
/// the new `@`-splitting: `git@` is matched as a literal URL prefix before
/// the account-shorthand branch ever runs, so a login literally named `git`
/// pointed at an actual SSH remote never gets misread as a selector.
#[test]
fn ssh_url_is_not_mistaken_for_account_shorthand() {
    assert_eq!(
        classify("git@github.com:owner/repo.git"),
        Positional::Url("git@github.com:owner/repo.git")
    );
    assert_eq!(
        super::embedded_account("git@github.com:owner/repo.git"),
        None
    );
}

/// A `name@<url>` shape — not `name@owner/repo` — is left alone: the
/// selector only applies to the two-segment shorthand form. A `://` anywhere
/// in the string is matched as a `Url` by the FIRST check `classify` makes
/// (pre-#7166, unchanged), before the account-prefix branch ever runs, so
/// the whole string — `login@` included — is treated as (a probably
/// malformed) URL rather than misread as carrying an embedded account.
#[test]
fn account_prefix_before_a_full_url_is_not_shorthand() {
    assert_eq!(
        classify("bob@https://github.com/owner/repo"),
        Positional::Url("bob@https://github.com/owner/repo")
    );
    assert_eq!(
        super::embedded_account("bob@https://github.com/owner/repo"),
        None
    );
}

/// The resolved clone URL never carries the account — it is GitHub-assumed
/// `owner/repo` shorthand, identically to the unprefixed form.
#[test]
fn account_shorthand_resolves_to_the_same_url_as_plain_shorthand() {
    assert_eq!(
        super::resolved_url("bob-duetto@duettoresearch/poc-hotel-supply").unwrap(),
        "https://github.com/duettoresearch/poc-hotel-supply"
    );
}

/// Plain shorthand and a full URL both carry no embedded account.
#[test]
fn embedded_account_none_for_plain_shorthand_and_urls() {
    assert_eq!(super::embedded_account("owner/repo"), None);
    assert_eq!(
        super::embedded_account("https://github.com/owner/repo"),
        None
    );
}

/// [`super::resolve_account`] — the `--account` flag / embedded-selector
/// reconciliation.
#[test]
fn resolve_account_flag_only() {
    assert_eq!(
        super::resolve_account(Some("bobmatnyc"), None).unwrap(),
        Some("bobmatnyc".to_string())
    );
}

#[test]
fn resolve_account_embedded_only() {
    assert_eq!(
        super::resolve_account(None, Some("bobmatnyc")).unwrap(),
        Some("bobmatnyc".to_string())
    );
}

#[test]
fn resolve_account_agreeing_flag_and_embedded() {
    assert_eq!(
        super::resolve_account(Some("bobmatnyc"), Some("bobmatnyc")).unwrap(),
        Some("bobmatnyc".to_string())
    );
}

#[test]
fn resolve_account_conflicting_flag_and_embedded_errors() {
    let err = super::resolve_account(Some("bobmatnyc"), Some("bob-duetto")).unwrap_err();
    assert!(
        err.to_string().contains("conflicting account selection"),
        "{err}"
    );
}

#[test]
fn resolve_account_neither_is_none() {
    assert_eq!(super::resolve_account(None, None).unwrap(), None);
}

/// Pins the function-level contract only. Since #5850 no CLI path reaches this
/// arm: `Cli::account` refuses a blank value at parse time
/// (`cli_rejects_a_blank_account_flag_before_the_repository`), and the bare-form
/// lift does too (`bare_form_rejects_an_empty_account_value`).
#[test]
fn resolve_account_blank_flag_is_treated_as_absent() {
    assert_eq!(
        super::resolve_account(Some("   "), Some("bobmatnyc")).unwrap(),
        Some("bobmatnyc".to_string())
    );
}

/// #7166 review follow-up (parity with the `<login>@owner/repo` shorthand's
/// `login` segment, which already runs through `is_name_segment`): a
/// `--account` value with a space or shell metacharacter is refused HERE,
/// with an actionable message, rather than reaching `gh auth token -u
/// <value>` unvalidated and failing with a confusing `gh` error.
#[test]
fn resolve_account_rejects_a_malformed_flag_value() {
    let err = super::resolve_account(Some("not a login"), None).unwrap_err();
    assert!(err.to_string().contains("not a login"), "{err}");

    let err = super::resolve_account(Some("bob;rm -rf"), None).unwrap_err();
    assert!(
        err.to_string().contains("not a plausible gh login"),
        "{err}"
    );
}

/// The synthetic credential the #9124 tests feed in, and the lowercase
/// fragments that must never appear in what comes back (sink 3 lowercases).
const TOKEN_URL_PARTS: [&str; 2] = ["secretqatoken2", "qauser"];

/// Fail when `text` holds any part of the #9124 synthetic credential.
fn assert_no_token(what: &str, text: &str) {
    let lowered = text.to_ascii_lowercase();
    for part in TOKEN_URL_PARTS {
        assert!(!lowered.contains(part), "{what} leaks {part:?}: {text}");
    }
}

/// #9124 sink 1: `tm register` with a credentialed URL prints and stores the
/// URL without its userinfo; the alias and the stored URL hold no token.
#[test]
fn register_never_prints_or_stores_an_embedded_token_9124() {
    let dir = tempfile::TempDir::new().unwrap();
    let paths = crate::commands::managed_root::ManagedPaths::from_root(dir.path().to_path_buf());
    let line = crate::commands::standalone::register_alias(
        &paths,
        "https://qauser:SECRETQATOKEN2@example.invalid/org/x.git",
        None,
        false,
    )
    .unwrap();
    assert_no_token("the printed line", &line);
    let stored = std::fs::read_to_string(dir.path().join("registry.json")).unwrap();
    assert_no_token("registry.json", &stored);
    let registry =
        trusty_mpm::core::standalone::registry::ManagedRegistry::load(dir.path()).unwrap();
    assert_eq!(registry.list()[0].url, "https://example.invalid/org/x.git");
    assert_eq!(registry.list()[0].alias, "org-x");
}

/// #9124 sink 2: every refusal `tm register` makes for a credentialed URL —
/// host-only, a web-UI path, a collision with an entry stored before the fix
/// — names the URL without its token.
#[test]
fn register_errors_never_echo_an_embedded_token_9124() {
    for bad in [
        "https://qauser:SECRETQATOKEN2@example.invalid/",
        "https://qauser:SECRETQATOKEN2@github.com/o/r/issues",
        // #9259: a quote or space in the password does not end the userinfo.
        "https://qauser:pa'ssSECRETQATOKEN2@example.invalid/",
        "https://qauser:\"pSECRETQATOKEN2\"@example.invalid/",
        "https://qauser:pa ssSECRETQATOKEN2@github.com/o/r/issues",
    ] {
        let err = resolve_register_args(bad, None).unwrap_err();
        assert_no_token(bad, &format!("{err:#}"));
    }
    let err = resolve_register_args(
        "https://qauser:SECRETQATOKEN2@example.invalid/a/b",
        Some("https://qauser:SECRETQATOKEN2@example.invalid/c/d"),
    )
    .unwrap_err();
    assert_no_token("two repos", &format!("{err:#}"));

    let dir = tempfile::TempDir::new().unwrap();
    let paths = crate::commands::managed_root::ManagedPaths::from_root(dir.path().to_path_buf());
    let mut old =
        trusty_mpm::core::standalone::registry::ManagedRegistry::load(dir.path()).unwrap();
    old.add(
        "org-x",
        "https://qauser:SECRETQATOKEN2@example.invalid/org/x.git",
        false,
    )
    .unwrap();
    old.save().unwrap();
    let err = crate::commands::standalone::register_alias(
        &paths,
        "https://example.invalid/other/y.git",
        Some("org-x"),
        false,
    )
    .unwrap_err();
    assert_no_token("the collision", &format!("{err:#}"));
}

/// The URL `register_alias` stored for `url` in a fresh managed root.
fn stored_after_register(url: &str) -> String {
    let dir = tempfile::TempDir::new().unwrap();
    let paths = crate::commands::managed_root::ManagedPaths::from_root(dir.path().to_path_buf());
    let line = crate::commands::standalone::register_alias(&paths, url, None, false).unwrap();
    // #9155: registering the same URL again is a no-op, not a DuplicateAlias.
    crate::commands::standalone::register_alias(&paths, url, None, false).unwrap();
    let registry =
        trusty_mpm::core::standalone::registry::ManagedRegistry::load(dir.path()).unwrap();
    let stored = registry.list()[0].url.clone();
    assert!(line.ends_with(&stored), "{line:?} names {stored:?}");
    stored
}

/// #9155: `tm register` keeps the ssh login and removes only a secret — the
/// `:password` on any scheme, the whole userinfo on http(s). The notice
/// prints only when a secret went, and an scp-style URL holding a password is
/// refused without echoing it (#9124 item 7).
#[test]
fn register_keeps_the_ssh_login_and_drops_only_the_secret_9155() {
    for (url, want, removed) in [
        ("git@github.com:o/r.git", "git@github.com:o/r.git", false),
        ("ssh://git@h:2222/t/r", "ssh://git@h:2222/t/r", false),
        (
            "ssh://u:SECRETQATOKEN2@h:2222/t/r",
            "ssh://u@h:2222/t/r",
            true,
        ),
        (
            "https://SECRETQATOKEN2@github.com/o/r",
            "https://github.com/o/r",
            true,
        ),
        (
            "https://qauser:SECRETQATOKEN2@github.com/o/r",
            "https://github.com/o/r",
            true,
        ),
    ] {
        assert_eq!(stored_after_register(url), want, "{url:?}");
        let (form, notice) = crate::commands::standalone::storage_form(url);
        assert_eq!(form, want, "{url:?}");
        assert_eq!(notice.is_some(), removed, "{url:?}");
        assert_no_token(url, notice.unwrap_or_default());
    }
    let scp = "qauser:SECRETQATOKEN2@host:o/r";
    assert_eq!(
        crate::commands::standalone::storage_form(scp),
        (
            "qauser@host:o/r".to_string(),
            Some(crate::commands::standalone::SECRET_REMOVED_NOTICE)
        )
    );
    let err = resolve_register_args(scp, None).unwrap_err();
    assert_no_token(scp, &format!("{err:#}"));
}

/// #9124 item 7: an scp-style `user:token@host:path` names no `://`, so the
/// error text masks its password through the scp branch.
#[test]
fn shown_masks_an_scp_style_password_9124() {
    assert_eq!(
        super::shown("qauser:SECRETQATOKEN2@host:o/r"),
        "***@host:o/r"
    );
    assert_eq!(
        super::shown("git@github.com:o/r.git"),
        "git@github.com:o/r.git"
    );
    assert_eq!(
        super::shown("https://qauser:SECRETQATOKEN2@h/o/r"),
        "https://***@h/o/r"
    );
    // #9259: a quoted or spaced password, in the URL and the scp form.
    for (s, want) in [
        (
            "https://qauser:pa'ssSECRETQATOKEN2@h/o/r",
            "https://***@h/o/r",
        ),
        (
            "https://qauser:\"p@ssSECRETQATOKEN2\"@h/o/r",
            "https://***@h/o/r",
        ),
        ("qauser:pa ssSECRETQATOKEN2@host:o/r", "***@host:o/r"),
        ("qauser:pa'ssSECRETQATOKEN2@h:o/r://x", "***@h:o/r://x"),
    ] {
        assert_eq!(super::shown(s), want);
    }
}