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
//! Unit tests for `tm run` target classification (#4990).
//!
//! Why: classification decides which subsystem a `tm run` invocation reaches,
//! and it must happen before any network call — a bad `owner/repo` string has
//! to be rejected with a usable message, not become a `git clone` that fails
//! minutes later. It must also agree with `tm register`, or the same string
//! would name two different things depending on which command saw it.
//! What: the alias/repo split, shorthand and full-URL resolution, the
//! rejections inherited from `tm register`, and the agreement between the two
//! identity primitives.
//! Test: this file IS the test module.

use super::*;

/// The routing decision itself: an alias goes to the standalone driver, a
/// repo shape goes to the daemon-managed cold start.
///
/// Why: the two arms are disjoint by construction — a DOC-24 alias matches
/// `^[a-z0-9][a-z0-9._-]*$`, so it can never contain the `/` a repo form
/// requires. This pins that disjointness rather than trusting it.
/// Test: itself.
#[test]
fn classify_sorts_alias_from_repo() {
    for alias in ["my-project", "trusty-tools", "a", "x.y_z-1"] {
        assert_eq!(
            classify_run_target(alias).expect("alias classifies"),
            RunTarget::Alias(alias.to_string()),
            "{alias} must route to the standalone driver"
        );
    }

    let target = classify_run_target("bobmatnyc/trusty-tools").expect("shorthand classifies");
    assert!(
        matches!(target, RunTarget::Repo { .. }),
        "owner/repo must route to the managed cold start, got {target:?}"
    );
}

/// `owner/repo` resolves to the GitHub URL `tm register` would store.
///
/// Why: the brief's headline case, and the exact string this later hands to
/// `git clone`.
/// Test: itself.
#[test]
fn classify_resolves_shorthand() {
    let target = classify_run_target("bobmatnyc/trusty-tools").expect("classifies");
    assert_eq!(
        target,
        RunTarget::Repo {
            owner: "bobmatnyc".into(),
            repo: "trusty-tools".into(),
            clone_url: "https://github.com/bobmatnyc/trusty-tools".into(),
            account: None,
        }
    );
}

/// A full URL — SSH or HTTPS, any host — resolves to the same identity shape.
///
/// Why: `parse_owner_repo` refuses URL-shaped input by design, so this is the
/// `parse_github_path` fallback arm. Without it a full URL would be rejected.
/// Test: itself.
#[test]
fn classify_resolves_full_urls() {
    let ssh = classify_run_target("git@github.com:bobmatnyc/trusty-tools.git").expect("ssh");
    assert_eq!(
        ssh,
        RunTarget::Repo {
            owner: "bobmatnyc".into(),
            repo: "trusty-tools".into(),
            clone_url: "git@github.com:bobmatnyc/trusty-tools.git".into(),
            account: None,
        }
    );

    let https = classify_run_target("https://gitlab.com/acme/widget.git").expect("https");
    assert_eq!(
        https,
        RunTarget::Repo {
            owner: "acme".into(),
            repo: "widget".into(),
            clone_url: "https://gitlab.com/acme/widget.git".into(),
            account: None,
        }
    );
}

/// An absolute local path is a clone source, and its identity comes from the
/// last TWO path segments.
///
/// Why: `classify` sorts a leading `/` as a `Url`, so `tm run
/// /Users/me/code/app` is accepted and clones from that local repo. The
/// identity is then `code/app` — `owner` is the PARENT DIRECTORY name, not a
/// GitHub owner — so the managed checkout lands at
/// `<repos_root>/code/app`. That is deterministic and harmless, but it is
/// surprising enough to pin: a future change to the fallback order would
/// silently relocate an existing operator's checkout.
/// Test: itself.
#[test]
fn absolute_path_derives_identity_from_the_last_two_segments() {
    let target = classify_run_target("/Users/me/code/app").expect("absolute path classifies");
    assert_eq!(
        target,
        RunTarget::Repo {
            owner: "code".into(),
            repo: "app".into(),
            clone_url: "/Users/me/code/app".into(),
            account: None,
        }
    );
}

/// AGREEMENT: for shorthand, the identity primitive this module uses matches
/// the one derived from the resolved URL.
///
/// Why: `classify_run_target` prefers `parse_owner_repo` and falls back to
/// `parse_github_path`. Two derivations is one more than the number that can
/// silently drift, so the property that they agree is pinned here rather than
/// assumed. If it ever fails, `tm run owner/repo` and `tm register owner/repo`
/// would resolve to different directories.
/// Test: itself.
#[test]
fn shorthand_identity_agrees_with_url_identity() {
    for spec in [
        "bobmatnyc/trusty-tools",
        "Acme/Cool_App",
        "123/repo",
        "a-b/c.d",
    ] {
        let url = crate::commands::register_args::resolved_url(spec).expect("resolves");
        let from_shorthand = parse_owner_repo(spec).expect("shorthand parses");
        let from_url = parse_github_path(&url).expect("url parses");
        assert_eq!(
            from_shorthand, from_url,
            "identity for '{spec}' must not depend on which parser saw it"
        );
    }
}

/// INVALID INPUT IS REJECTED BEFORE ANY NETWORK CALL.
///
/// Why: `classify_run_target` is pure — it runs no git, opens no socket. These
/// strings therefore fail with a message while a user is still watching, which
/// is the whole reason the rejection lives at the CLI boundary and not at
/// clone time. The specific shapes are inherited from `tm register`: a browser
/// paste into a repo's web UI, a relative path, and a host with no repo.
/// Test: itself.
#[test]
fn classify_rejects_browser_pastes_and_paths() {
    for (bad, expected) in [
        (
            "https://github.com/bobmatnyc/trusty-tools/pull/4990",
            "points inside a repository",
        ),
        (
            "https://github.com/bobmatnyc/trusty-tools/tree/main",
            "points inside a repository",
        ),
        // A relative path is neither a repo nor an alias. Routing it to the
        // registry would report "alias './some/dir' not found", which names
        // the wrong problem — the regression this case pins.
        ("./some/dir", "is a relative path"),
        ("../sibling", "is a relative path"),
        ("https://github.com", "names a host"),
    ] {
        let err = match classify_run_target(bad) {
            Err(e) => e.to_string(),
            Ok(t) => panic!("'{bad}' must be refused before any network call, got {t:?}"),
        };
        assert!(
            err.contains(expected),
            "rejection of '{bad}' must say '{expected}', got: {err}"
        );
    }
}

/// #6441: every repo shape `tm run` accepts is also a bare-`tm` target.
///
/// Why: `tm <url>` and `tm run <url>` must not disagree about what a string
/// means, so `classify_bare` delegates to `classify_run_target` rather than
/// re-deriving. This pins the delegation on the shapes both see.
/// Test: itself.
#[test]
fn classify_bare_accepts_repo_shapes() {
    for spec in [
        "bobmatnyc/mcp-a-protocol",
        "https://github.com/bobmatnyc/mcp-a-protocol",
        "https://github.com/bobmatnyc/mcp-a-protocol.git",
        "git@github.com:bobmatnyc/mcp-a-protocol.git",
    ] {
        let bare = classify_bare(spec)
            .unwrap_or_else(|| panic!("'{spec}' is a repo shape, not a typo"))
            .unwrap_or_else(|e| panic!("'{spec}' must resolve: {e}"));
        assert_eq!(
            bare,
            classify_run_target(spec).expect("tm run accepts it too"),
            "'{spec}' must mean the same thing bare as it does after `tm run`"
        );
        assert!(matches!(bare, RunTarget::Repo { .. }));
    }
}

/// THE GATE: anything that is not repo-shaped declines, and declines QUIETLY.
///
/// Why: `Command::External` catches subcommand typos as well as URLs. `None`
/// is what hands a typo back to clap's usage error; a `Some(Err(..))` here
/// would replace "did you mean status?" with a repository complaint, and a
/// `Some(Ok(Alias(..)))` would turn it into a registry lookup for an alias
/// nobody registered. A relative path declines for the same reason — clap's
/// usage error names the real problem better than a clone attempt would.
/// Test: itself.
#[test]
fn classify_bare_declines_subcommand_typos() {
    for not_a_repo in [
        "statuss",
        "sessionz",
        "instal",
        "notacommand",
        "",
        "   ",
        "./some/dir",
        "../sibling",
    ] {
        assert!(
            classify_bare(not_a_repo).is_none(),
            "'{not_a_repo}' must fall through to the usage-error path, not become a target"
        );
    }
}

/// A repo-shaped token that names no repo keeps `resolved_url`'s message.
///
/// Why: `https://example.com/` is a URL, so it is not a typo and the usage
/// error would be the wrong answer. The remedy is the one `tm register`
/// already writes, inherited rather than restated.
/// Test: itself.
#[test]
fn classify_bare_surfaces_resolved_url_errors() {
    for (bad, expected) in [
        ("https://example.com/", "names a host"),
        (
            "https://github.com/bobmatnyc/trusty-tools/issues",
            "points inside a repository",
        ),
    ] {
        let err = classify_bare(bad)
            .unwrap_or_else(|| panic!("'{bad}' is repo-SHAPED, so it is never the typo path"))
            .expect_err("but it does not name a repository");
        assert!(
            err.to_string().contains(expected),
            "rejection of '{bad}' must say '{expected}', got: {err}"
        );
    }
}

/// An empty or whitespace-only target names nothing and must say so.
///
/// Test: itself.
#[test]
fn classify_rejects_empty_target() {
    for empty in ["", "   ", "\t"] {
        let err = classify_run_target(empty).expect_err("empty must be refused");
        assert!(
            err.to_string().contains("needs a target"),
            "message must name the remedy: {err}"
        );
    }
}

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

/// `--account` alone selects the account for a plain `owner/repo` target.
#[test]
fn classify_resolves_account_flag() {
    let target =
        classify_run_target_with_account("bobmatnyc/trusty-tools", Some("bob-duetto")).unwrap();
    assert_eq!(
        target,
        RunTarget::Repo {
            owner: "bobmatnyc".into(),
            repo: "trusty-tools".into(),
            clone_url: "https://github.com/bobmatnyc/trusty-tools".into(),
            account: Some("bob-duetto".into()),
        }
    );
}

/// The embedded `<login>@owner/repo` shorthand selects the account with no
/// `--account` flag at all.
#[test]
fn classify_resolves_embedded_account() {
    let target =
        classify_run_target_with_account("bob-duetto@duettoresearch/poc-hotel-supply", None)
            .unwrap();
    assert_eq!(
        target,
        RunTarget::Repo {
            owner: "duettoresearch".into(),
            repo: "poc-hotel-supply".into(),
            clone_url: "https://github.com/duettoresearch/poc-hotel-supply".into(),
            account: Some("bob-duetto".into()),
        }
    );
}

/// `--account` and a DIFFERENT embedded selector on the same invocation is
/// refused rather than silently picking one.
#[test]
fn classify_rejects_conflicting_account() {
    let err = classify_run_target_with_account(
        "bob-duetto@duettoresearch/poc-hotel-supply",
        Some("bobmatnyc"),
    )
    .expect_err("conflicting accounts must be refused");
    assert!(
        err.to_string().contains("conflicting account selection"),
        "{err}"
    );
}

/// `--account` agreeing with the embedded selector is accepted (not an
/// error just because both spellings were used).
#[test]
fn classify_accepts_agreeing_account_flag_and_shorthand() {
    let target = classify_run_target_with_account(
        "bob-duetto@duettoresearch/poc-hotel-supply",
        Some("bob-duetto"),
    )
    .unwrap();
    assert_eq!(
        target,
        RunTarget::Repo {
            owner: "duettoresearch".into(),
            repo: "poc-hotel-supply".into(),
            clone_url: "https://github.com/duettoresearch/poc-hotel-supply".into(),
            account: Some("bob-duetto".into()),
        }
    );
}

/// `classify_bare_with_account` (the `tm <token>` catch-all path, #6441)
/// threads the account through identically to the explicit `tm run` form.
#[test]
fn classify_bare_accepts_account_flag_and_shorthand() {
    let via_flag =
        classify_bare_with_account("bobmatnyc/trusty-tools", Some("bob-duetto")).unwrap();
    assert_eq!(
        via_flag.unwrap(),
        classify_run_target_with_account("bobmatnyc/trusty-tools", Some("bob-duetto")).unwrap()
    );

    let via_shorthand =
        classify_bare_with_account("bob-duetto@duettoresearch/poc-hotel-supply", None).unwrap();
    assert!(matches!(
        via_shorthand.unwrap(),
        RunTarget::Repo {
            account: Some(a),
            ..
        } if a == "bob-duetto"
    ));
}

/// A bare token with no `@` and no `--account` still resolves with no account
/// selected — the pre-#7166 shape, unregressed.
#[test]
fn classify_bare_with_no_account_is_unchanged() {
    let bare = classify_bare("bobmatnyc/trusty-tools").unwrap().unwrap();
    assert!(matches!(bare, RunTarget::Repo { account: None, .. }));
}

/// Turn a `&str` list into the owned tokens clap hands the external arm.
fn toks(items: &[&str]) -> Vec<String> {
    items.iter().map(ToString::to_string).collect()
}

/// 🔴 #5850 REGRESSION: `tm <url> --user <login>` must reach the managed run.
///
/// Why this is the assertion: the owner's invocation put the flag AFTER the
/// repository. clap collected it into the external subcommand's argv instead
/// of the global `--account` field, so `run_external` saw two extra tokens and
/// bailed with "takes no further arguments" — the flag never reached
/// `classify_bare_with_account` at all.
/// Test: itself.
#[test]
fn bare_form_lifts_a_trailing_user_flag() {
    let (rest, account) = split_trailing_account(&toks(&[
        "https://github.com/duettoresearch/jev-matching",
        "--user",
        "bob-duetto",
    ]))
    .expect("a trailing --user must be lifted, not refused");
    assert_eq!(
        rest,
        toks(&["https://github.com/duettoresearch/jev-matching"])
    );
    assert_eq!(account.as_deref(), Some("bob-duetto"));
}

/// The `=` form and the `--account` spelling behave identically.
/// Test: itself.
#[test]
fn bare_form_lifts_an_inline_account_value() {
    let (rest, account) =
        split_trailing_account(&toks(&["acme/widget", "--account=bobmatnyc"])).expect("lifted");
    assert_eq!(rest, toks(&["acme/widget"]));
    assert_eq!(account.as_deref(), Some("bobmatnyc"));
}

/// A flag with no value is an ERROR, never a silent drop.
///
/// Why: dropping it would clone as the machine's global account while the
/// operator believed they had selected one — the #5850 substitution, arrived
/// at from the other direction.
/// Test: itself.
#[test]
fn bare_form_rejects_a_trailing_flag_with_no_value() {
    let err = split_trailing_account(&toks(&["acme/widget", "--user"]))
        .expect_err("a valueless flag must refuse");
    assert!(err.to_string().contains("needs a gh login"), "{err}");
}

/// Every other token survives untouched, so the "takes no further arguments"
/// bail still fires for genuine extra arguments.
/// Test: itself.
#[test]
fn bare_form_leaves_unrelated_tokens_alone() {
    let (rest, account) =
        split_trailing_account(&toks(&["acme/widget", "extra"])).expect("no flag present");
    assert_eq!(rest, toks(&["acme/widget", "extra"]));
    assert_eq!(account, None);
}

/// Two DIFFERENT accounts around the repository are refused, not resolved by
/// position.
/// Test: itself.
#[test]
fn bare_form_refuses_two_different_accounts_around_the_repository() {
    let err = reconcile_bare_account(Some("bobmatnyc".into()), Some("bob-duetto".into()))
        .expect_err("a conflict must refuse");
    assert!(err.to_string().contains("conflicting account"), "{err}");
    assert_eq!(
        reconcile_bare_account(Some("bob-duetto".into()), Some("bob-duetto".into()))
            .expect("agreeing values collapse")
            .as_deref(),
        Some("bob-duetto")
    );
}

/// 🔴 #5850 REGRESSION (fail-open): an EMPTY account value is refused at the
/// lift, never carried downstream.
///
/// Why this is the assertion: `--user=` used to lift as `Some("")`, and
/// `resolve_account` treats a blank flag as absent — so the clone ran as the
/// machine's global account while the operator believed they had pinned one.
/// Covers the inline `=` form and a blank separate value, for both spellings.
/// Test: itself.
#[test]
fn bare_form_rejects_an_empty_account_value() {
    for tokens in [
        &["acme/widget", "--user="][..],
        &["acme/widget", "--account="][..],
        &["acme/widget", "--user", ""][..],
        &["acme/widget", "--account", "   "][..],
        &["acme/widget", "--user=  "][..],
    ] {
        let err = split_trailing_account(&toks(tokens))
            .expect_err("an empty account value must refuse, not fall back to the global account");
        assert!(
            err.to_string().contains("needs a gh login"),
            "{tokens:?}: {err}"
        );
    }
}

/// 🔴 #5850 REGRESSION (wiring): the real parse of `tm <url> --user <login>`
/// reaches a `RunTarget::Repo` carrying that login.
///
/// Why this is the assertion: the lift's unit tests stay green if
/// `resolve_external` stops calling it. Driving clap's own output through the
/// resolver fails the moment the lift is unwired, because the trailing tokens
/// then hit the "takes no further arguments" refusal.
/// Test: itself.
#[test]
fn bare_form_trailing_user_reaches_the_repo_target() {
    use clap::Parser;
    let cli = crate::cli::Cli::try_parse_from([
        "tm",
        "https://github.com/duettoresearch/jev-matching",
        "--user",
        "bob-duetto",
    ])
    .expect("the bare form parses");
    let Some(crate::cli::Command::External(tokens)) = cli.command else {
        panic!("the bare form must reach the external catch-all");
    };
    let target = resolve_external(&tokens, cli.account)
        .expect("a trailing --user must resolve, not refuse")
        .expect("a repository URL is repo-shaped");
    let RunTarget::Repo {
        owner,
        repo,
        account,
        ..
    } = target
    else {
        panic!("expected a repository target, got {target:?}");
    };
    assert_eq!(
        (owner.as_str(), repo.as_str()),
        ("duettoresearch", "jev-matching")
    );
    assert_eq!(account.as_deref(), Some("bob-duetto"));
}

/// 🔴 #9090 REGRESSION: a trailing `--u <login>` is lifted like `--user`.
///
/// Why this is the assertion: the owner's
/// `tm duettoresearch/duetto-blast-mfes --u bob-duetto` was refused with
/// "takes no further arguments", because `--u` was not an account spelling.
/// Test: itself.
#[test]
fn bare_form_lifts_a_trailing_u_flag() {
    for tokens in [
        &["duettoresearch/duetto-blast-mfes", "--u", "bob-duetto"][..],
        &["duettoresearch/duetto-blast-mfes", "--u=bob-duetto"][..],
    ] {
        let (rest, account) = split_trailing_account(&toks(tokens)).expect("lifted");
        assert_eq!(
            rest,
            toks(&["duettoresearch/duetto-blast-mfes"]),
            "{tokens:?}"
        );
        assert_eq!(account.as_deref(), Some("bob-duetto"), "{tokens:?}");
    }
}

/// The account a parsed invocation selects, read the way `main` reads it: the
/// global field, plus — for the bare form — the trailing-token lift.
fn selected_account(argv: &[&str]) -> Option<String> {
    use clap::Parser;
    let cli = crate::cli::Cli::try_parse_from(argv)
        .unwrap_or_else(|e| panic!("{argv:?} must parse: {e}"));
    match cli.command {
        Some(crate::cli::Command::External(tokens)) => {
            match resolve_external(&tokens, cli.account)
                .unwrap_or_else(|e| panic!("{argv:?} must resolve: {e}"))
            {
                Some(RunTarget::Repo { account, .. }) => account,
                other => panic!("{argv:?}: expected a repository target, got {other:?}"),
            }
        }
        Some(crate::cli::Command::Run { .. } | crate::cli::Command::Register { .. }) => cli.account,
        other => panic!("{argv:?}: unexpected command {other:?}"),
    }
}

/// 🔴 #9090 REGRESSION: every account spelling selects the account in the bare
/// form, `tm run` and `tm register`, before the repository and after it.
///
/// Why this is the assertion: the closure condition is the whole matrix, and a
/// spelling that works in one cell but not another is the #5850 / #9090 shape.
/// `--account` and `--user` rows prove those spellings are unchanged.
/// Test: itself.
#[test]
fn every_account_spelling_selects_the_account_in_every_form_and_position() {
    const REPO: &str = "duettoresearch/duetto-blast-mfes";
    for flag in ["--account", "--user", "--u"] {
        let cases: [Vec<&str>; 6] = [
            vec!["tm", flag, "bob-duetto", REPO],
            vec!["tm", REPO, flag, "bob-duetto"],
            vec!["tm", "run", flag, "bob-duetto", REPO],
            vec!["tm", "run", REPO, flag, "bob-duetto"],
            vec!["tm", "register", flag, "bob-duetto", REPO],
            vec!["tm", "register", REPO, flag, "bob-duetto"],
        ];
        for argv in cases {
            assert_eq!(
                selected_account(&argv).as_deref(),
                Some("bob-duetto"),
                "{argv:?}"
            );
        }
    }
}

/// 🔴 #9091: a launch whose `[accounts]` table cannot be read is refused with
/// the file and the parse error, before anything is cloned or spawned; a
/// chosen or ambient account passes.
#[test]
fn preflight_refuses_a_broken_accounts_table_naming_the_file() {
    use trusty_mpm::core::gh_org_accounts::{AccountSource, OrgAccounts, ResolvedAccount};
    let path = std::path::Path::new("/home/u/.trusty-mpm/config.toml");
    let broken = OrgAccounts::from_toml("[accounts]\nduettoresearch = bob-duetto\n", path)
        .expect_err("an unquoted login is a syntax error");
    let origin = "https://github.com/duettoresearch/jev.git";

    let err = preflight_verdict(origin, Err(broken.to_string()))
        .expect_err("a broken table refuses the launch")
        .to_string();
    for needle in [origin, "/home/u/.trusty-mpm/config.toml", "not valid TOML"] {
        assert!(err.contains(needle), "{needle}: {err}");
    }
    assert!(err.contains("No session was started"), "{err}");

    let chosen = ResolvedAccount {
        login: "bob-duetto".into(),
        source: AccountSource::OrgMap,
    };
    preflight_verdict(origin, Ok(Some(chosen))).expect("a mapped account launches");
    preflight_verdict(origin, Ok(None)).expect("the ambient identity launches");
}

/// #9124: the account-preflight refusal reaches the terminal; it never quotes
/// the origin's token.
#[test]
fn preflight_refusal_never_quotes_the_origin_token() {
    const TOKEN: &str = "ghp_9124PreflightSyntheticToken000";
    let origin = format!("https://octo:{TOKEN}@github.com/acme/widget.git");
    let err = preflight_verdict(&origin, Err("no [accounts] row".to_string()))
        .expect_err("an unresolved account refuses the launch")
        .to_string();
    assert!(!err.contains(TOKEN), "the token reached the refusal");
    assert!(
        err.contains("https://***@github.com/acme/widget.git"),
        "{err}"
    );
}

/// #9124 sink 3: an owner-less credentialed URL made the token the owner, so
/// it was lowercased into the managed-checkout path (`…/secretqatoken2-
/// example-invalid/x`), the daemon log and the CLI error. No part of it may
/// reach the identity, checked case-insensitively.
#[test]
fn a_token_in_the_url_never_reaches_the_identity_9124() {
    for url in [
        "https://qauser:SECRETQATOKEN2@example.invalid/x.git",
        "https://qauser:SECRETQATOKEN2@example.invalid/org/x.git",
    ] {
        let RunTarget::Repo {
            owner,
            repo,
            account,
            ..
        } = classify_run_target(url).unwrap()
        else {
            panic!("{url} is a repo");
        };
        let identity = format!("{owner}/{repo} {account:?}").to_ascii_lowercase();
        for part in ["secretqatoken2", "qauser"] {
            assert!(!identity.contains(part), "{url} -> {identity}");
        }
        assert_eq!(repo, "x");
    }
}