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
//! Build and spawn the attended `claude` session for a managed alias.
//!
//! Why: `tm run <alias>` is the claude-mpm replacement — it ensures the alias
//! is loaded, sets `CLAUDE_CONFIG_DIR` to the tm-global config dir (the
//! load-bearing isolation primitive, DOC-24 SPEC-STANDALONE-MPM-05c), and
//! launches `claude` in the project's `repo/` directory. Auth follows the
//! WI-10 two-path model: when `ANTHROPIC_API_KEY` is set, `claude` is launched
//! with `--bare` (bypasses keychain/OAuth); otherwise, the session relies on
//! the keychain entry created by `tm login`. This module is intentionally
//! unit-testable: `build_launch_command` and `build_login_command` return
//! configured `Command`s without spawning them.
//! What: four public functions — `build_launch_command` (pure, unit-testable),
//! `build_login_command` (pure, unit-testable), `check_credentials` (env check),
//! and `run_alias` (orchestrator that calls load, checks auth, builds and spawns
//! the command).
//! Test: `test_build_launch_command_sets_env_and_cwd`,
//! `test_build_launch_command_adds_bare_with_api_key`,
//! `test_build_launch_command_no_bare_without_api_key`,
//! `test_build_login_command_sets_env_and_invocation`,
//! `test_check_credentials_with_env_var`.

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use anyhow::Context;

use super::load::load_alias;
use super::registry::ManagedRegistry;

/// Build the `claude` launch `Command` for a managed repo directory.
///
/// Why: separating command construction from spawning makes the launch contract
/// unit-testable without actually starting a process. The caller (or a test)
/// can inspect program, current_dir, args, and env before spawning. The
/// WI-10 two-path auth model is encoded here: when `api_key` is `Some(_)`, the
/// `--bare` flag is added so Claude Code bypasses keychain/OAuth and uses the
/// API key directly; otherwise the keychain entry created by `tm login` is used.
/// `--dangerously-skip-permissions` is always added for fully unattended orchestration
/// (consistent with all other tm-initiated Claude launches).
/// Stdio is set to `Stdio::inherit()` explicitly so the attended interactive
/// session is always connected to the terminal, even if a future caller switches
/// from `.status()` to `.output()`.
/// What: returns a `Command` with program `"claude"`, cwd `repo_path`,
/// env `CLAUDE_CONFIG_DIR=<claude_config_dir>`, stdin/stdout/stderr set to
/// `Stdio::inherit()`, `--dangerously-skip-permissions`, and (when `api_key` is
/// `Some(s)` with a non-empty `s`) the `--bare` arg. Does NOT spawn.
///
/// Issue #4467: also scrubs Claude Code's inherited process-local session
/// markers via [`crate::core::claude_env_scrub::scrub_command`]. This is the one
/// `tm` launch path where the transcript-saving suppression fires deterministically
/// — there is no tmux here, so upstream's `tmux show-environment -g` escape hatch
/// returns false immediately and an inherited `CLAUDE_CODE_CHILD_SESSION` always
/// wins.
///
/// Issues #6495/#7160/#8405: also provisions the renderer and mouse-capture
/// defaults via [`crate::core::alt_screen::apply_configured_to_command`]. The
/// renderer is the one config `tmux.alternate_screen` decides (`true` → `=0`,
/// `false` → `=1`), assigned whatever the launching shell exports; the
/// mouse-capture default still yields to an exported value.
///
/// Issue #7422: `mcp_config` names the composed, default-deny MCP file, and
/// `--mcp-config <it>` is appended only when it is `Some` (#7892: never
/// `--strict-mcp-config`, which would suppress the operator's user scope).
/// The caller passes the path its own `provision` call returned, so the file
/// and the flag come from one decision — this builder never derives a path a
/// caller did not write, which is what let `doctor_transcript_saving` build an
/// argv naming a file that did not exist.
/// Test: `test_build_launch_command_carries_the_mcp_config_flag_and_not_strict`,
/// `test_build_launch_command_omits_the_mcp_config_flag_without_a_file`,
/// `test_build_launch_command_sets_env_and_cwd`,
/// `test_build_launch_command_adds_bare_with_api_key`,
/// `test_build_launch_command_no_bare_without_api_key`,
/// `test_build_launch_command_includes_bypass_permissions`,
/// `test_build_launch_command_scrubs_inherited_session_markers`,
/// `test_build_launch_command_assigns_the_configured_renderer`,
/// `test_build_launch_command_defaults_the_mouse_capture_off`.
pub fn build_launch_command_configured(
    repo_path: &Path,
    claude_config_dir: &Path,
    api_key: Option<&str>,
    mcp_config: Option<&Path>,
    alternate_screen: bool,
) -> Command {
    let mut cmd = Command::new("claude");
    cmd.current_dir(repo_path);
    // #4467: strip Claude Code's inherited process-local session markers. This
    // path matters MORE than the tmux ones, not less: `tm run` spawns `claude`
    // directly with no tmux, and upstream's escape hatch bails on its first line
    // (`if(!Z.TMUX) return false`), so an inherited `CLAUDE_CODE_CHILD_SESSION`
    // suppresses transcript saving DETERMINISTICALLY here rather than depending
    // on the tmux server's global env. Runs before the `CLAUDE_CONFIG_DIR`
    // assignment below so the deliberate value always wins (#4455).
    crate::core::claude_env_scrub::scrub_command(&mut cmd);
    // #6495/#8405: the config-decided renderer, whatever this shell exports.
    crate::core::alt_screen::apply_configured_to_command(&mut cmd, alternate_screen);
    cmd.env("CLAUDE_CONFIG_DIR", claude_config_dir);
    cmd.stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit());
    // Always add bypass-permissions for fully automated orchestration (consistent with
    // all other tm launch paths that use PERMISSION_MODE_FLAG).
    cmd.arg(crate::core::model_inject::PERMISSION_MODE_FLAG);
    // #7892: the additive `--mcp-config`, never `--strict-mcp-config`. The
    // caller passes the file its own `provision` call just wrote, so the flag
    // and the file come from ONE decision — a builder that named the path
    // itself would emit an argv pointing at a file nobody composed. Argv tokens
    // go straight to `exec`, so the path is unquoted.
    cmd.args(crate::core::session_mcp_scope::mcp_config_argv(mcp_config));
    // WI-10: when ANTHROPIC_API_KEY is set, add --bare so Claude Code bypasses
    // keychain/OAuth reads and uses the API key directly. When the key is absent
    // the session relies on the keychain entry created by `tm login`.
    if let Some(key) = api_key
        && !key.trim().is_empty()
    {
        cmd.arg("--bare");
    }
    cmd
}

/// [`build_launch_command_configured`] carrying the PM prompt file (#8286).
///
/// Why: the owner rule is that every PM launch mode delivers its prompt
/// through `--append-system-prompt-file`; `tm run` launched a bare `claude`.
/// `prompt_file` is required, so a prompt-less `tm run` cannot be built here.
/// What: the configured command plus `--append-system-prompt-file <path>`,
/// unquoted because the argv goes straight to `exec`.
/// Test: `run_launch_command_carries_the_prompt_file`,
/// `pm_launch_builders_carry_the_prompt_file`.
pub fn build_launch_command_with_prompt(
    repo_path: &Path,
    claude_config_dir: &Path,
    api_key: Option<&str>,
    mcp_config: Option<&Path>,
    prompt_file: &Path,
    alternate_screen: bool,
) -> Command {
    let mut cmd = build_launch_command_configured(
        repo_path,
        claude_config_dir,
        api_key,
        mcp_config,
        alternate_screen,
    );
    cmd.arg("--append-system-prompt-file").arg(prompt_file);
    cmd
}

/// The `claude` command `tm run` spawns, with the renderer the config under
/// `config_root` decides (#8405).
///
/// Why: the one seam where `run_alias` turns the operator's config into the
/// renderer, split out so a test can drive it from a config root.
/// What: [`build_launch_command_with_prompt`] with
/// [`crate::core::alt_screen::configured_alternate_screen_in`].
/// Test: `run_launch_command_follows_the_configured_renderer`,
/// `run_launch_command_carries_the_prompt_file`.
fn run_launch_command(
    config_root: Option<&Path>,
    repo_path: &Path,
    claude_config_dir: &Path,
    api_key: Option<&str>,
    mcp_config: Option<&Path>,
    prompt_file: &Path,
) -> Command {
    build_launch_command_with_prompt(
        repo_path,
        claude_config_dir,
        api_key,
        mcp_config,
        prompt_file,
        crate::core::alt_screen::configured_alternate_screen_in(config_root),
    )
}

/// The 1.7.0 shape of [`build_launch_command_configured`] (#8405).
///
/// Why: trusty-mpm 1.7.x is published; removing this signature would fail the
/// semver gate for a patch release.
/// What: delegates with the renderer read from the operator's config
/// ([`crate::core::alt_screen::configured_alternate_screen`]).
///
/// Superseded by [`build_launch_command_configured`], which takes the renderer explicitly;
/// kept un-`#[deprecated]` because that attribute is a minor-level change
/// the 1.7.x patch semver gate refuses (#8405).
pub fn build_launch_command(
    repo_path: &Path,
    claude_config_dir: &Path,
    api_key: Option<&str>,
    mcp_config: Option<&Path>,
) -> Command {
    build_launch_command_configured(
        repo_path,
        claude_config_dir,
        api_key,
        mcp_config,
        crate::core::alt_screen::configured_alternate_screen(),
    )
}

/// Build the `claude auth login` `Command` for the tm-global config dir.
///
/// Why: `tm login` needs to run the OAuth login flow under
/// `CLAUDE_CONFIG_DIR=<tm-global-config-dir>` so the resulting keychain entry
/// is keyed to that dir and `tm run` sessions can authenticate on the user's
/// Claude Max/Pro plan. Factoring out the command construction makes it
/// unit-testable without launching a browser. Stdio inheritance is set
/// explicitly (not left to the `.status()` default) so a future caller using
/// `.output()` cannot silently suppress the interactive OAuth prompt.
/// What: returns a `Command` with program `"claude"`, args `["auth", "login"]`,
/// env `CLAUDE_CONFIG_DIR=<claude_config_dir>`, and stdin/stdout/stderr all
/// set to `Stdio::inherit()`. Does NOT spawn.
/// Test: `test_build_login_command_sets_env_and_invocation`.
pub fn build_login_command(claude_config_dir: &Path) -> Command {
    let mut cmd = Command::new("claude");
    cmd.args(["auth", "login"]);
    cmd.env("CLAUDE_CONFIG_DIR", claude_config_dir);
    cmd.stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit());
    cmd
}

/// Determine whether the managed session will have a usable auth path.
///
/// Why: CLAUDE_CONFIG_DIR (A9) relocates the entire `~/.claude/` tree including
/// `.credentials.json`; a clean tm-global config dir is therefore unauthenticated.
/// WI-10 defines two valid auth paths — `ANTHROPIC_API_KEY` (+`--bare`) and the
/// keychain login created by `tm login`. This function encodes the same two-path
/// check so `run_alias` can emit an informative warning when neither appears
/// available, without blocking the launch (a keychain entry cannot be probed
/// non-interactively).
/// Accepting `api_key` as a parameter (rather than reading the env directly)
/// removes env mutation from tests and keeps this pure under parallel test
/// runners (F4 fix).
/// What: returns `AuthState::ApiKey` when `api_key` is `Some(s)` with a
/// non-empty `s`; `AuthState::CredentialsFile` when
/// `<claude_config_dir>/.credentials.json` exists; `AuthState::Unknown`
/// otherwise (the keychain entry, if any, cannot be probed from Rust without
/// spawning `claude auth status`, so we issue a hint instead of a hard failure).
/// Test: `test_check_credentials_with_key_param`,
/// `test_check_credentials_with_file`.
#[derive(Debug, PartialEq, Eq)]
pub enum AuthState {
    /// ANTHROPIC_API_KEY is set — `--bare` will be used.
    ApiKey,
    /// `.credentials.json` exists in the tm-global config dir (MCP OAuth tokens
    /// only, not primary session auth; kept for diagnostic purposes).
    CredentialsFile,
    /// Neither path is detectable non-interactively (keychain entry may still
    /// exist from a prior `tm login` — issue a hint, not a hard failure).
    Unknown,
}

/// Check which auth path is available for the managed session.
///
/// Why: see `AuthState` doc; encodes the WI-10 two-path check without probing
/// the macOS keychain (requires spawning `claude auth status`).
/// What: evaluates `api_key` then `.credentials.json` presence and returns the
/// matching `AuthState`.
/// Test: `test_check_credentials_with_key_param`, `test_check_credentials_with_file`.
pub fn check_credentials(claude_config_dir: &Path, api_key: Option<&str>) -> AuthState {
    if let Some(key) = api_key
        && !key.trim().is_empty()
    {
        return AuthState::ApiKey;
    }
    if claude_config_dir.join(".credentials.json").exists() {
        return AuthState::CredentialsFile;
    }
    AuthState::Unknown
}

/// Load and run an interactive `claude` session for the given alias.
///
/// Why: `tm run <alias>` is the primary daily-driver entry point. It calls
/// `load_alias` unconditionally (idempotent), then applies the WI-10 two-path
/// auth model: when `ANTHROPIC_API_KEY` is set the session launches with
/// `--bare` (API-key path); otherwise it relies on the keychain entry created
/// by `tm login` (keychain path). A best-effort stderr hint is emitted when
/// neither a seeded `.credentials.json` nor `ANTHROPIC_API_KEY` is detected,
/// pointing users to `tm login` — but we do not block, because a valid keychain
/// entry cannot be probed without spawning `claude auth status`.
/// What: (1) `load_alias` — idempotent, (2) reads `ANTHROPIC_API_KEY` and
/// calls `check_credentials` for a hint, (3) writes the PM prompt file and
/// builds the command with [`build_launch_command_with_prompt`] (which adds
/// `--bare` when the key is set); a prompt that cannot be written refuses the
/// run (#8286), (4)
/// spawns via `crate::core::spawn_disclaim::disclaimed_status` (macOS:
/// disclaims TCC responsibility for the child so consent prompts attribute to
/// `claude` rather than the signed `trusty-mpm`/`tm` binary, issue #2997;
/// elsewhere: plain `Command::status()`) and waits. The attended session's
/// non-zero exit code is not treated as a tm error (Ctrl-C → 130, typing
/// `exit` → 0/1, etc. are all normal).
/// Test: end-to-end requires a real `claude` binary; auth-path logic is covered
/// by `test_build_launch_command_adds_bare_with_api_key` and
/// `test_build_launch_command_no_bare_without_api_key`; the disclaim spawn
/// itself is covered by `disclaimed_status_*` in `crate::core::spawn_disclaim`.
pub fn run_alias(alias: &str, managed_root: &Path, claude_config_dir: &Path) -> anyhow::Result<()> {
    let repo_path = load_alias(alias, managed_root, claude_config_dir)
        .with_context(|| format!("failed to load alias '{alias}'"))?;

    // Read ANTHROPIC_API_KEY at the call site so `check_credentials` remains
    // pure and unit-testable without env mutation (F4 fix).
    let api_key = std::env::var("ANTHROPIC_API_KEY").ok();

    match check_credentials(claude_config_dir, api_key.as_deref()) {
        AuthState::ApiKey => {
            // API key present → --bare will be added by build_launch_command.
        }
        AuthState::CredentialsFile => {
            // .credentials.json exists — likely MCP OAuth tokens; the primary
            // keychain session auth was established by `tm login`.
        }
        AuthState::Unknown => {
            // Cannot detect a keychain entry without spawning `claude auth
            // status`; emit a non-blocking hint so the user knows about tm login.
            eprintln!(
                "hint: no ANTHROPIC_API_KEY and no .credentials.json found in {}.\n\
                 If you haven't run `tm login` yet, do so once to authenticate\n\
                 managed sessions on your Claude Max/Pro plan.\n\
                 Alternatively, export ANTHROPIC_API_KEY to use the API-key path.",
                claude_config_dir.display()
            );
        }
    }

    // #7422: compose this session's MCP config before building the command that
    // names it. A failure aborts `tm run` rather than launching with the
    // unscoped shared server map.
    let mcp_config = crate::core::session_mcp_scope::provision(&repo_path, claude_config_dir)
        .context("failed to compose the session-scoped MCP config")?;

    // #8286: `tm run` launches a PM, so it carries the PM prompt file and
    // refuses when that file cannot be written. One profile resolution gives
    // the prompt and the stamp (#8453).
    // #9012: the PM instructions are runtime content; none refuses `tm run`.
    let content = crate::core::content_source::framework_content_for(&repo_path)
        .context("cannot compose the PM instructions")?;
    let cli = crate::core::session_launch::cli_launch(&content, &repo_path, None);
    let prompt_file = crate::core::model_inject::write_pm_prompt_file_in(
        &std::env::temp_dir(),
        &cli.prompt,
        &repo_path,
        "run",
    )?;

    let mut cmd = run_launch_command(
        // #8405: the operator's config decides the renderer.
        crate::core::alt_screen::operator_config_root().as_deref(),
        &repo_path,
        claude_config_dir,
        api_key.as_deref(),
        Some(&mcp_config),
        &prompt_file,
    );
    // #8286: assigned after the builder's scrub, so this value wins.
    let (stamp_name, stamp_value) = crate::core::session_profile::launch_env(cli.profile);
    cmd.env(stamp_name, stamp_value);
    // Routed through the disclaim-aware spawn (issue #2997) rather than
    // `cmd.status()` directly: on macOS this disclaims TCC responsibility for
    // the child, so mis-attributed consent prompts (media library, App-Data,
    // and anything a `cargo build` the session runs touches) are attributed
    // to `claude`'s own stable code identity instead of the signed
    // `trusty-mpm`/`tm` binary. See `crate::core::spawn_disclaim` module docs.
    crate::core::spawn_disclaim::disclaimed_status(&mut cmd)
        .context("failed to spawn 'claude'; is it installed and on PATH?")?;

    // A non-zero exit from an attended interactive session (Ctrl-C → 130,
    // `/exit` → 0, etc.) is normal end-of-session, not a tm error.
    Ok(())
}

/// Resolve the repo path for an alias without launching it.
///
/// Why: `tm path <alias>` prints the stable `repo/` directory so an IDE or
/// script can open the project without running `tm run`.
/// What: resolves `<managed_root>/projects/<alias>/repo/`, checks the marker
/// exists, and returns the path.
/// Test: exercised by `path_cmd` in the CLI command layer.
pub fn resolve_repo_path(alias: &str, managed_root: &Path) -> anyhow::Result<PathBuf> {
    let registry = ManagedRegistry::load(managed_root)
        .with_context(|| format!("failed to load registry from {}", managed_root.display()))?;
    registry
        .get(alias)
        .with_context(|| format!("alias '{alias}' is not registered"))?;

    let repo = managed_root.join("projects").join(alias).join("repo");
    let marker = repo.join(".trusty-mpm").join("managed.toml");
    if !marker.exists() {
        anyhow::bail!("alias '{alias}' is registered but not loaded; run `tm load {alias}` first");
    }
    Ok(repo)
}

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

    /// #7422: given a composed file, `tm run`'s argv names exactly that file.
    #[test]
    fn test_build_launch_command_carries_the_mcp_config_flag_and_not_strict() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        let cfg = tmp.path().join("claude-config");
        let composed = tmp.path().join("state").join("session-mcp").join("ab.json");

        let cmd = build_launch_command_configured(&repo, &cfg, None, Some(&composed), false);

        let args: Vec<String> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            !args.iter().any(|a| a == "--strict-mcp-config"),
            "the launch line must never narrow the user scope: {args:?}"
        );
        let pos = args
            .iter()
            .position(|a| a == "--mcp-config")
            .expect("--mcp-config must be present");
        assert_eq!(
            args[pos + 1],
            composed.display().to_string(),
            "the flag must name the file the caller composed, unquoted for exec"
        );
    }

    /// #7422: a caller that composed no file gets no flag, so no argv can name
    /// a path nobody wrote (`doctor_transcript_saving`'s probe is that caller).
    #[test]
    fn test_build_launch_command_omits_the_mcp_config_flag_without_a_file() {
        let tmp = TempDir::new().unwrap();
        let cmd = build_launch_command_configured(
            &tmp.path().join("repo"),
            &tmp.path().join("claude-config"),
            None,
            None,
            false,
        );
        let args: Vec<String> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            !args
                .iter()
                .any(|a| a == "--strict-mcp-config" || a == "--mcp-config"),
            "no composed file means no flag naming one: {args:?}"
        );
    }

    #[test]
    fn test_build_launch_command_sets_env_and_cwd() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        let cfg = tmp.path().join("claude-config");

        let cmd = build_launch_command_configured(&repo, &cfg, None, None, false);

        // Verify program is "claude".
        assert_eq!(cmd.get_program(), "claude");

        // Verify cwd is repo_path.
        assert_eq!(cmd.get_current_dir(), Some(repo.as_path()));

        // Verify CLAUDE_CONFIG_DIR env is set.
        let env_vars: Vec<_> = cmd.get_envs().collect();
        let claude_cfg_var = env_vars
            .iter()
            .find(|(k, _)| *k == std::ffi::OsStr::new("CLAUDE_CONFIG_DIR"));
        assert!(
            claude_cfg_var.is_some(),
            "CLAUDE_CONFIG_DIR should be set in the command env"
        );
        if let Some((_, val)) = claude_cfg_var {
            assert_eq!(*val, Some(cfg.as_os_str()));
        }
    }

    // WI-10: `--bare` MUST be present when api_key is supplied (API-key path).
    #[test]
    fn test_build_launch_command_adds_bare_with_api_key() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        let cfg = tmp.path().join("claude-config");

        let cmd =
            build_launch_command_configured(&repo, &cfg, Some("sk-ant-test-key"), None, false);

        let args: Vec<_> = cmd.get_args().collect();
        assert!(
            args.iter().any(|a| a == &std::ffi::OsStr::new("--bare")),
            "expected --bare in args when api_key is set; got {args:?}"
        );
    }

    // WI-10: `--bare` MUST NOT be present when no api_key (keychain path).
    #[test]
    fn test_build_launch_command_no_bare_without_api_key() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        let cfg = tmp.path().join("claude-config");

        // None key → no --bare
        let cmd = build_launch_command_configured(&repo, &cfg, None, None, false);
        let args: Vec<_> = cmd.get_args().collect();
        assert!(
            !args.iter().any(|a| a == &std::ffi::OsStr::new("--bare")),
            "--bare must not be present when api_key is None; got {args:?}"
        );

        // Empty key → no --bare (treated same as None)
        let cmd2 = build_launch_command_configured(&repo, &cfg, Some(""), None, false);
        let args2: Vec<_> = cmd2.get_args().collect();
        assert!(
            !args2.iter().any(|a| a == &std::ffi::OsStr::new("--bare")),
            "--bare must not be present for empty api_key; got {args2:?}"
        );

        // Whitespace-only key → no --bare
        let cmd3 = build_launch_command_configured(&repo, &cfg, Some("   "), None, false);
        let args3: Vec<_> = cmd3.get_args().collect();
        assert!(
            !args3.iter().any(|a| a == &std::ffi::OsStr::new("--bare")),
            "--bare must not be present for whitespace-only key; got {args3:?}"
        );
    }

    // Every `tm run` launch must carry the bypass-permissions flag so unattended
    // orchestration never blocks on interactive prompts.
    #[test]
    fn test_build_launch_command_includes_bypass_permissions() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        let cfg = tmp.path().join("claude-config");

        // Without API key.
        let cmd = build_launch_command_configured(&repo, &cfg, None, None, false);
        let args: Vec<_> = cmd.get_args().collect();
        assert!(
            args.iter()
                .any(|a| *a == std::ffi::OsStr::new("--dangerously-skip-permissions")),
            "expected --dangerously-skip-permissions in args (no key); got {args:?}"
        );

        // With API key (--bare should co-exist with bypass flag).
        let cmd2 =
            build_launch_command_configured(&repo, &cfg, Some("sk-ant-test-key"), None, false);
        let args2: Vec<_> = cmd2.get_args().collect();
        assert!(
            args2
                .iter()
                .any(|a| *a == std::ffi::OsStr::new("--dangerously-skip-permissions")),
            "expected --dangerously-skip-permissions with api key; got {args2:?}"
        );
        assert!(
            args2.iter().any(|a| *a == std::ffi::OsStr::new("--bare")),
            "expected --bare to co-exist with bypass flag; got {args2:?}"
        );
    }

    // #4467: `tm run` is the ONE tm launch path with no tmux, so upstream's
    // `tmux show-environment -g` escape hatch returns false at its first line and
    // an inherited CLAUDE_CODE_CHILD_SESSION suppresses transcript saving every
    // time — deterministically, not probe-dependently. Marker names are
    // hard-coded so this cannot go vacuous if the shared list is emptied.
    #[test]
    fn test_build_launch_command_scrubs_inherited_session_markers() {
        let tmp = TempDir::new().unwrap();
        let repo = tmp.path().join("repo");
        let cfg = tmp.path().join("claude-config");
        let cmd = build_launch_command_configured(&repo, &cfg, None, None, false);

        let envs: Vec<(String, Option<String>)> = cmd
            .get_envs()
            .map(|(k, v)| {
                (
                    k.to_string_lossy().into_owned(),
                    v.map(|v| v.to_string_lossy().into_owned()),
                )
            })
            .collect();

        for marker in [
            "CLAUDE_CODE_CHILD_SESSION",
            "CLAUDE_CODE_SESSION_ID",
            "CLAUDECODE",
            "CLAUDE_PID",
            "CLAUDE_EFFORT",
            "CLAUDE_CODE_EXECPATH",
        ] {
            assert!(
                envs.contains(&(marker.to_owned(), None)),
                "{marker} must be REMOVED (None) for the `tm run` session: {envs:?}"
            );
        }

        // Over-scrub guard: the scrub runs BEFORE the deliberate assignment, so
        // CLAUDE_CONFIG_DIR must survive it as a SET value (#4455 / #4451).
        assert!(
            envs.contains(&(
                "CLAUDE_CONFIG_DIR".to_owned(),
                Some(cfg.display().to_string())
            )),
            "CLAUDE_CONFIG_DIR must survive the scrub as a set value: {envs:?}"
        );
    }

    /// #8453: `tm run` from a supervisor session must not hand the child that
    /// session's `TRUSTY_MPM_SESSION_PROFILE`; the child has no stamp of its own.
    #[test]
    fn test_build_launch_command_never_passes_on_the_profile_stamp() {
        let tmp = TempDir::new().unwrap();
        let cmd = build_launch_command_configured(tmp.path(), tmp.path(), None, None, false);
        assert!(
            cmd.get_envs()
                .any(|(k, v)| k == "TRUSTY_MPM_SESSION_PROFILE" && v.is_none()),
            "the profile stamp must be REMOVED for the `tm run` session"
        );
    }

    /// #8286: `tm run` hands `claude` the PM prompt file. FAILS BEFORE THIS
    /// CHANGE: the argv carried no `--append-system-prompt-file`.
    #[test]
    fn run_launch_command_carries_the_prompt_file() {
        let tmp = TempDir::new().unwrap();
        let prompt = tmp.path().join("pm prompt.txt");
        let cmd = run_launch_command(
            None,
            &tmp.path().join("repo"),
            &tmp.path().join("cfg"),
            None,
            None,
            &prompt,
        );
        let args: Vec<String> = cmd
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        let pos = args
            .iter()
            .position(|a| a == "--append-system-prompt-file")
            .expect("tm run must carry --append-system-prompt-file");
        assert_eq!(args[pos + 1], prompt.display().to_string(), "{args:?}");
    }

    /// #8405: `tm run` assigns the renderer config decides, in both
    /// directions, whatever the launching shell exports. At df212601d the
    /// builder yielded to an exported value, so this fails there under any
    /// ambient environment: one of the two directions disagrees with it.
    /// #8405: `run_alias`'s seam reads the renderer from its config root, both
    /// directions. Fails if the seam ignores the config.
    #[test]
    fn run_launch_command_follows_the_configured_renderer() {
        use crate::core::alt_screen::ALT_SCREEN_ENV_VAR;

        let tmp = TempDir::new().unwrap();
        for (alternate_screen, want) in [(true, "0"), (false, "1")] {
            let root = TempDir::new().unwrap();
            std::fs::write(
                root.path().join("config.yaml"),
                format!("tmux:\n  alternate_screen: {alternate_screen}\n"),
            )
            .unwrap();
            let cmd = run_launch_command(
                Some(root.path()),
                &tmp.path().join("repo"),
                &tmp.path().join("cfg"),
                None,
                None,
                &tmp.path().join("p.txt"),
            );
            let carried = cmd
                .get_envs()
                .find(|(k, _)| *k == ALT_SCREEN_ENV_VAR)
                .and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()));
            assert_eq!(
                carried.as_deref(),
                Some(want),
                "alternate_screen={alternate_screen}"
            );
        }
    }

    #[test]
    fn test_build_launch_command_assigns_the_configured_renderer() {
        use crate::core::alt_screen::ALT_SCREEN_ENV_VAR;

        let tmp = TempDir::new().unwrap();
        for (alternate_screen, want) in [(true, "0"), (false, "1")] {
            let cmd = build_launch_command_configured(
                &tmp.path().join("repo"),
                &tmp.path().join("cfg"),
                None,
                None,
                alternate_screen,
            );
            let carried = cmd
                .get_envs()
                .find(|(k, _)| *k == ALT_SCREEN_ENV_VAR)
                .and_then(|(_, v)| v.map(|v| v.to_string_lossy().into_owned()));
            assert_eq!(
                carried.as_deref(),
                Some(want),
                "alternate_screen={alternate_screen}"
            );
        }
    }

    /// #7160: the mouse-capture default still yields to an exported value.
    #[test]
    fn test_build_launch_command_defaults_the_mouse_capture_off() {
        use crate::core::alt_screen::{MOUSE_DEFAULT, MOUSE_ENV_VAR};

        let tmp = TempDir::new().unwrap();
        let cmd = build_launch_command_configured(
            &tmp.path().join("repo"),
            &tmp.path().join("cfg"),
            None,
            None,
            false,
        );

        let carried_by_the_launch = std::env::var_os(MOUSE_ENV_VAR).is_some();
        let provisioned = cmd.get_envs().any(|(k, v)| {
            k == MOUSE_ENV_VAR && v.is_some_and(|v| v == std::ffi::OsStr::new(MOUSE_DEFAULT))
        });
        assert_eq!(
            provisioned, !carried_by_the_launch,
            "tm run must provision {MOUSE_ENV_VAR}={MOUSE_DEFAULT} when the \
             launch carries no value, and leave an operator value untouched when it does"
        );
    }

    // WI-10: `tm login` command builder sets the correct program, args, and env.
    #[test]
    fn test_build_login_command_sets_env_and_invocation() {
        let tmp = TempDir::new().unwrap();
        let cfg = tmp.path().join("claude-config");

        let cmd = build_login_command(&cfg);

        assert_eq!(cmd.get_program(), "claude");

        let args: Vec<_> = cmd.get_args().collect();
        assert_eq!(
            args,
            vec![std::ffi::OsStr::new("auth"), std::ffi::OsStr::new("login")],
            "expected [auth, login], got {args:?}"
        );

        let env_vars: Vec<_> = cmd.get_envs().collect();
        let cfg_var = env_vars
            .iter()
            .find(|(k, _)| *k == std::ffi::OsStr::new("CLAUDE_CONFIG_DIR"));
        assert!(
            cfg_var.is_some(),
            "CLAUDE_CONFIG_DIR must be set on the login command"
        );
        if let Some((_, val)) = cfg_var {
            assert_eq!(*val, Some(cfg.as_os_str()));
        }
    }

    // F4: check_credentials now accepts the key value as a parameter so tests
    // never need unsafe env mutation (safe under parallel test runners).
    #[test]
    fn test_check_credentials_with_key_param() {
        let tmp = TempDir::new().unwrap();
        let cfg = tmp.path().to_path_buf();

        // Non-empty key → ApiKey.
        assert_eq!(
            check_credentials(&cfg, Some("sk-test-key")),
            AuthState::ApiKey
        );

        // Empty / whitespace-only key → falls through to file/unknown check.
        assert_eq!(check_credentials(&cfg, Some("")), AuthState::Unknown);
        assert_eq!(check_credentials(&cfg, Some("   ")), AuthState::Unknown);

        // None key, no file → Unknown.
        assert_eq!(check_credentials(&cfg, None), AuthState::Unknown);
    }

    #[test]
    fn test_check_credentials_with_file() {
        let tmp = TempDir::new().unwrap();
        let cfg = tmp.path().to_path_buf();

        // No key, file exists → CredentialsFile.
        std::fs::write(cfg.join(".credentials.json"), r#"{"token":"t"}"#).unwrap();
        assert_eq!(check_credentials(&cfg, None), AuthState::CredentialsFile);

        // Both key and file → ApiKey (API key takes precedence).
        assert_eq!(
            check_credentials(&cfg, Some("sk-also-valid")),
            AuthState::ApiKey
        );
    }
}