trusty-mpm 1.3.4

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! `tm` / `trusty-mpm` — unified MPM CLI entry point.
//!
//! Why: this file is intentionally thin. All logic is in the submodules below;
//! `main` only parses arguments, sets up tracing for long-running modes, and
//! dispatches to the appropriate handler function.
//! What: module declarations, lazy HELP initializer, `main()` with clap
//! dispatch.
//! Test: `cargo test -p trusty-mpm` runs the full suite in `tests.rs`.

mod cli;
mod cli_manager;
mod commands;
mod formatters;
mod generate;
mod gh_identity;
mod tracing_setup;
mod types;

use std::io::IsTerminal as _;

use clap::Parser;
use cli::{Cli, Command};
use commands::{
    agent::agent,
    compress::run_compress,
    daemon::{restart, run_daemon, start, stop_daemon},
    generate::generate,
    hooks::clean as hooks_clean,
    install::install,
    launch::{connect, launch},
    manager::manager,
    misc::{attach_cmd, coordinator, doctor, health, hook, optimizer, overseer, status, validate},
    project::project,
    projects::projects,
    repair::repair_deploy,
    services::services,
    session::session,
    slack::slack,
    telegram::telegram,
};

#[cfg(test)]
#[path = "tests.rs"]
mod tests;

#[cfg(test)]
#[path = "tests_behavior_a.rs"]
mod tests_behavior_a;

#[cfg(test)]
#[path = "install_policy_tests.rs"]
mod install_policy_tests;

#[cfg(test)]
#[path = "tests_behavior_b_tests.rs"]
mod tests_behavior_b;

#[cfg(test)]
#[path = "tests_behavior_c_tests.rs"]
mod tests_behavior_c;

#[cfg(test)]
#[path = "tests_behavior_d_tests.rs"]
mod tests_behavior_d;

#[cfg(test)]
#[path = "tests_behavior_e_tests.rs"]
mod tests_behavior_e;

#[cfg(test)]
#[path = "tests_behavior_generate_tests.rs"]
mod tests_behavior_generate;

#[cfg(test)]
#[path = "tests_behavior_hooks_tests.rs"]
mod tests_behavior_hooks;

#[cfg(test)]
#[path = "tests_behavior_repair_tests.rs"]
mod tests_behavior_repair;

#[cfg(test)]
#[path = "tests_behavior_reset_agents_tests.rs"]
mod tests_behavior_reset_agents;

#[cfg(test)]
#[path = "tests_behavior_skill_tiers_tests.rs"]
mod tests_behavior_skill_tiers;

#[cfg(test)]
#[path = "tests_behavior_2890_skills_tests.rs"]
mod tests_behavior_2890_skills;

#[cfg(test)]
#[path = "tests_behavior_2903_skills_tests.rs"]
mod tests_behavior_2903_skills;

#[cfg(test)]
#[path = "tests_behavior_2911_documentation_style_tests.rs"]
mod tests_behavior_2911_documentation_style;

#[cfg(test)]
#[path = "tests_behavior_rust_build_performance_tests.rs"]
mod tests_behavior_rust_build_performance;

#[cfg(test)]
#[path = "tests_projects.rs"]
mod tests_projects;

#[cfg(test)]
#[path = "tests_projects_config_tests.rs"]
mod tests_projects_config_tests;

#[cfg(test)]
#[path = "tests_manager.rs"]
mod tests_manager;

#[cfg(test)]
#[path = "tests_project_trust_tests.rs"]
mod tests_project_trust;

/// Lazy-loaded help configuration for "did you mean?" suggestions (issue #216).
///
/// Why: the YAML help bundle is checked in as a string literal; loading it
/// lazily avoids any parse work on the (common) fast path where every argument
/// is valid.
/// What: parses `help.yaml` once on first access via `std::sync::LazyLock`.
/// Test: the suggestion path is exercised indirectly by the clap parse tests.
static HELP: std::sync::LazyLock<trusty_common::help::HelpConfig> =
    std::sync::LazyLock::new(|| {
        trusty_common::help::load_help(include_str!("../../../help.yaml"))
            .expect("trusty-mpm help.yaml is bundled and valid")
    });

/// Binary entry point.
///
/// Why: separation of concerns — `main` owns the lifecycle (arg parsing,
/// tracing init, exit codes) while the handlers own the domain logic.
/// What: tries to parse via `clap::Parser::try_parse`, prints a "did you
/// mean?" hint on an unknown-subcommand error, then dispatches.
///
/// #2118: a bare `tm projects` (no verb) on an interactive terminal is
/// intercepted HERE, before `Cli::try_parse()` even runs, and launches the
/// 4-pane project-control-plane TUI skeleton. The interception happens this
/// early — rather than by relaxing `ProjectsAction` to `Option` and branching
/// inside the dispatcher — specifically so `tm projects <verb>` and a
/// non-interactive bare `tm projects` both flow through the completely
/// unmodified clap definition: the latter must keep failing with a clap usage
/// error (exit code 2), unchanged from the pre-#2118 behavior. (The EXACT
/// clap `ErrorKind` — and therefore the exact rendered wording — for that
/// bare-invocation usage error is not itself a stable cross-environment
/// property of this unmodified definition; see `tests_projects::
/// cli_rejects_bare_projects_with_a_usage_error`'s doc for the evidence. The
/// invariant this interception actually depends on, and the one that IS
/// stable, is the non-zero exit code.) "Interactive" requires BOTH stdin and
/// stdout to be real terminals (`commands::projects::should_launch_bare_tui`)
/// — stdout alone is not enough: a supervisor/wrapper that redirects stdin
/// from `/dev/null` while leaving stdout attached to a pty would otherwise
/// launch a raw-mode TUI with no keyboard path able to exit it. See
/// `commands::projects::should_launch_bare_tui` and
/// `commands::projects::launch_bare_tui`.
/// Test: integration tests in `tests.rs` exercise every dispatch branch; the
/// #2118 interception gate is unit tested in `commands::projects::tests`.
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Why: parse via `try_parse` so we can attach the workspace-shared
    // "did you mean?" suggestion (issue #216) before exiting on a clap error.
    let argv: Vec<String> = std::env::args().collect();

    // #2118: see this function's module doc for why this runs before parsing.
    // Requires BOTH stdin and stdout to be real terminals — stdout alone is
    // not a safe interactivity signal (see the module doc).
    if commands::projects::should_launch_bare_tui(
        &argv,
        std::io::stdin().is_terminal(),
        std::io::stdout().is_terminal(),
    ) {
        return commands::projects::launch_bare_tui().await;
    }

    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(e) => {
            e.print().ok();
            if matches!(
                e.kind(),
                clap::error::ErrorKind::InvalidSubcommand | clap::error::ErrorKind::UnknownArgument
            ) {
                trusty_common::help::print_suggestion_hint(&argv, &HELP);
            }
            std::process::exit(e.exit_code());
        }
    };

    // #2405 (LOW fix from PR #2528 review): the universal `config` credential
    // CLI is a lightweight, daemon-less command. Dispatch it BEFORE any
    // daemon-URL resolution (#2517's bounded client + gateway-first
    // `resolve_daemon_url_via_gateway` probe below) so `tm config keys …`
    // never pays a loopback daemon probe or the tracing/migration setup that
    // follows. Mirrors the tagent/tga early config short-circuit (#2405).
    if let Some(Command::Config(cmd)) = cli.command {
        return cmd.run().await;
    }

    // #2997: the internal disclaim-exec shim is the lightweight leaf a managed
    // tmux pane routes `claude` through so it is spawned with macOS TCC
    // responsibility disclaimed. It must run BEFORE any daemon-URL resolution,
    // tracing/migration setup, or client construction below — it is a bare
    // `posix_spawn` + wait that exits with the child's code and never talks to
    // the daemon. (Emitted into the pane command by
    // `trusty_mpm::core::spawn_disclaim::disclaim_pane_command`.)
    if let Some(Command::InternalSpawnDisclaimed { argv: spawn_argv }) = cli.command {
        // #4398 HIGH (critic review on PR #4431): `infer_subcommands` makes
        // clap resolve ANY unambiguous prefix of "internal-spawn-disclaimed"
        // to this hidden variant — see `commands::spawn_disclaimed::
        // invoked_literally`'s doc for the full rationale. Reject anything
        // that didn't arrive via the exact, full spelling before ever
        // reaching the disclaimed-spawn leaf.
        if !commands::spawn_disclaimed::invoked_literally(&argv) {
            eprintln!(
                "error: '{}' must be invoked by its exact name, not an abbreviation",
                trusty_mpm::core::spawn_disclaim::PANE_DISCLAIM_SUBCOMMAND
            );
            std::process::exit(2);
        }
        return commands::spawn_disclaimed::run(spawn_argv);
    }

    // Long-running daemon mode: init file-rotating tracing + bug-capture layer
    // (identical to the former trusty-mpmd binary). Short-lived CLI invocations
    // skip subscriber init entirely — they have no meaningful log volume and
    // there is no global registry yet to conflict with.
    //
    // Both guards must live for the full duration of `main`:
    //   - `_daemon_log_guard`: the non-blocking writer's WorkerGuard; dropping
    //     it flushes and joins the background I/O thread — early drop silently
    //     discards buffered log records.
    //   - `_error_store`: the ErrorStore handle returned by `bug_capture_layer`.
    //     The capture ring is Arc-backed but the *write* end is held by the
    //     tracing layer, while the *read* end lives in `_error_store`. Dropping
    //     `_error_store` before `main` returns means any consumer (MCP preview,
    //     HTTP endpoint, future DaemonState slot) that tries to read the ring
    //     after the store is gone will get an empty result. Phase 2 (#478) will
    //     move `_error_store` into `DaemonState`; until then it must be kept
    //     alive at main-scope.
    //
    // Both are declared unconditionally (as Option) so the borrow checker is
    // satisfied regardless of which cfg branch runs.
    #[cfg(feature = "daemon")]
    let mut _daemon_log_guard: Option<tracing_appender::non_blocking::WorkerGuard> = None;
    // Why: `_error_store` carries the read half of the bug-capture ring buffer.
    // Binding it here (not inside the inner block below) keeps it alive until
    // `main` returns, matching the original trusty-mpmd binary's lifetime.
    // What: holds the `ErrorStore` returned by `bug_capture_layer`; the write
    // half lives inside the tracing layer registered with the global subscriber.
    // Test: dropping this before `run_daemon` completes would cause the capture
    // ring to appear empty on any subsequent read; the daemon integration tests
    // exercise the full tracing→capture→preview path via HTTP.
    #[cfg(feature = "daemon")]
    let mut _error_store: Option<trusty_common::error_capture::ErrorStore> = None;

    // #4573: `tm sessions instructions` is where an operator asks "why didn't my
    // CLAUDE.md override apply?", and every line of the code written to answer
    // that is `tracing` — which went nowhere, because only the daemon/supervisor
    // branch below ever registered a subscriber. See `tracing_setup` for the full
    // rationale and for why the writer is explicitly stderr.
    tracing_setup::init_cli_diagnostics_if_wanted(&cli.command);

    // Long-running modes (daemon, supervisor) get the full file-rotating tracing
    // + bug-capture layer; short-lived CLI invocations skip subscriber init.
    if matches!(
        cli.command,
        Some(Command::Daemon { .. }) | Some(Command::Supervisor { .. })
    ) {
        #[cfg(feature = "daemon")]
        {
            // File logging: write daily-rotated logs to ~/.trusty-mpm/logs/ in
            // addition to the existing stderr stream.
            let log_dir = dirs::home_dir()
                .ok_or_else(|| anyhow::anyhow!("cannot resolve home directory"))?
                .join(".trusty-mpm")
                .join("logs");
            std::fs::create_dir_all(&log_dir)?;
            let file_appender = tracing_appender::rolling::daily(&log_dir, "trusty-mpm.log");
            let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
            _daemon_log_guard = Some(guard);

            // EnvFilter is not Clone, so we build two independent instances that
            // both re-parse RUST_LOG from the environment — one for the stderr
            // layer, one for the file layer. This is intentional: each layer
            // needs its own owned filter, and re-parsing is cheap at startup.
            let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "info".into());
            let file_filter = tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "info".into());

            // Bug-reporting Phase 1 (#478): compose the bug-capture layer so
            // ERROR events are captured to <data_dir>/trusty-mpm/errors.jsonl
            // and an in-memory ring without modifying any call sites.
            // Capture writes ONLY to JSONL + in-memory ring — never stdout —
            // so this is safe for both the HTTP daemon and the MCP stdio path.
            let (capture_layer, store) = trusty_common::error_capture::bug_capture_layer(
                "trusty-mpm",
                trusty_common::error_capture::DEFAULT_CAPTURE_CAPACITY,
                env!("CARGO_PKG_VERSION"),
            );
            // Move store into the main-scope binding so it outlives this block
            // and remains reachable for the entire daemon run (see comment above).
            _error_store = Some(store);

            use tracing_subscriber::Layer as _;
            use tracing_subscriber::layer::SubscriberExt as _;
            use tracing_subscriber::util::SubscriberInitExt as _;
            tracing_subscriber::registry()
                .with(
                    tracing_subscriber::fmt::layer()
                        // MCP mode speaks JSON-RPC on stdout — keep tracing on stderr.
                        .with_writer(std::io::stderr)
                        .with_filter(env_filter),
                )
                .with(
                    tracing_subscriber::fmt::layer()
                        .with_writer(non_blocking)
                        .with_ansi(false)
                        .with_filter(file_filter),
                )
                .with(capture_layer)
                .init();
        }
        // #4573: shares `tracing_setup`'s stderr-only builder with the CLI
        // inspection path — the two were byte-for-byte the same builder.
        #[cfg(not(feature = "daemon"))]
        tracing_setup::init_stderr_only("info");
    }

    // #1905: one-time migration removing stale pre-rename `mpm-*` skill
    // directories left over from the mpm-*→tm-* skill rename. Gated on a
    // marker file (`~/.trusty-mpm/migrations.json`) so it does real work at
    // most once per machine, then becomes a single cheap file read on every
    // later `tm` invocation — this is deliberately NOT a permanent
    // `tm doctor` check (see `core::doctor::run_doctor`'s doc comment).
    {
        let paths = trusty_mpm::core::paths::FrameworkPaths::default();
        trusty_mpm::core::stale_skills::run_stale_mpm_skills_migration_once(
            &paths.root,
            &paths.claude_skills_dir(),
        );
    }

    // #2517: the top-level CLI client must carry the same bounded
    // connect/request timeouts `DaemonClient` uses (issue #2471/#2512) — a
    // bare `reqwest::Client::new()` here has NO timeout, so `tm status`
    // against a daemon that accepts the TCP connection but never answers
    // hung for the OS-level socket timeout (observed 55.63s live-verify)
    // instead of the intended ~10s bound. `daemon_healthy` (used by `tm
    // status`/`tm start`) and the gateway probe below both send through
    // this SAME client, so both are now bounded too.
    let client = trusty_mpm::client::http_client::default_client();
    // Resolve the daemon URL once with gateway-first probing:
    //   1. Explicit --url/TRUSTY_MPM_URL, whenever it was actually supplied
    //      (`cli.url` is `Option<String>` — see its doc, #2487) → use it
    //      directly, bypassing the gateway entirely. There is no comparison
    //      against DEFAULT_DAEMON_URL: `Some` here always means the operator
    //      made a real choice, even one that happens to equal the default URL
    //      verbatim. Before #2487 `cli.url` was a plain `String` with
    //      `default_value = DEFAULT_URL`, so an explicit
    //      `TRUSTY_MPM_URL=http://127.0.0.1:7880` was indistinguishable from
    //      "nothing was set" and fell through to the gateway probe below —
    //      silently rerouting every `tm` subcommand (including `tm projects
    //      config … set`) through the trusty-console proxy on port 7788
    //      instead of the daemon on 7880.
    //   2. trusty-console gateway (`http://{console}/api/mpm`) if the console is
    //      running and the daemon is reachable through it (#1849 Phase 2).
    //   3. Lock file (daemon may bind to an ephemeral port) → default.
    // The gateway path routes all `tm` traffic through the unified web UI while
    // preserving full direct-fallback behaviour when the console is absent.
    // Stale TRUSTY_MPM_URL values (#1731) are still probed before falling back.
    //
    // #1737 note: this top-level resolution is deliberately NOT gated on
    // explicit-URL reachability, even though an explicit override never falls
    // back here (step (a) of the gateway resolver returns it verbatim — see
    // that function's doc). `tm hook` has an intentional FAIL-OPEN contract
    // that must survive an unreachable `--url`/`TRUSTY_MPM_URL` — a Claude
    // Code hook must never fail the user's turn because the best-effort
    // daemon POST could not connect (see `tests/tm_hook_idle_parking.rs`,
    // which asserts exit 0 even for `--url http://127.0.0.1:1`); a blanket
    // probe-and-abort here would regress it. A command that instead wants
    // "explicit URL must be reachable, error otherwise" semantics calls
    // [`trusty_mpm::core::resolve_daemon_url_for_cli`] itself, on top of this
    // shared resolution, before running any of its own fallback-prone logic —
    // `commands::guided::run_guided_default` (the bare `tm` dispatch target
    // below) does exactly that: it was the one LIVE instance of the #1737
    // silent-fallback bug (its daemon-autostart step ignores whichever URL it
    // is handed and always re-resolves implicitly), so it now probes
    // `explicit` up front and errors — translated to exit 75 below — instead
    // of silently auto-starting/reconnecting to a different daemon.
    let url = trusty_mpm::core::resolve_daemon_url_via_gateway(&client, cli.url.as_deref()).await;
    // Why: handlers return `anyhow::Result`; we capture the dispatch result here
    // so the top-level boundary can translate the typed `PruneError::SmUnavailable`
    // (issue #1313) into the documented exit code 75. Doing the `process::exit`
    // here — rather than inside the async `prune_idle` — guarantees no live async
    // resource (the reqwest client, JoinSet tasks) is skipped over by exiting.
    let result = match cli.command {
        None => commands::guided::run_guided_default(&client, &url, cli.url.as_deref()).await,
        Some(Command::Status) => status(&client, &url).await,
        Some(Command::Start) => start(&client, &url).await,
        Some(Command::Serve { stdio }) => {
            if stdio {
                // #1221: MCP stdio bridge — forward JSON-RPC to the daemon's
                // loopback POST /rpc, auto-starting the daemon and reconnecting
                // with backoff. This is the `.mcp.json` entry point.
                commands::serve_stdio::run_stdio_bridge().await
            } else {
                start(&client, &url).await
            }
        }
        Some(Command::Stop) => stop_daemon().await,
        Some(Command::Restart) => restart(&client, &url).await,
        Some(Command::Project { action }) => project(&client, &url, action).await,
        // #2116: `sessions` (plural) is the canonical top-level command.
        Some(Command::Sessions { action }) => session(&client, &url, action).await,
        Some(Command::Projects { action }) => projects(&client, &url, action).await,
        Some(Command::Manager { action }) => manager(&client, &url, action).await,
        // #2116: `session` (singular) is a hidden deprecated alias of `sessions`.
        // The notice fires here — exactly once per invocation, regardless of
        // which verb was invoked — before dispatching to the identical handler.
        Some(Command::Session { action }) => {
            commands::session::emit_top_level_alias_notice();
            session(&client, &url, action).await
        }
        Some(Command::Events) => commands::misc::events(&client, &url).await,
        Some(Command::Doctor { flags }) => doctor(&url, &flags).await,
        Some(Command::Validate { path, repair }) => validate(path, repair).await,
        Some(Command::Hooks { action }) => {
            use cli::HooksAction;
            match action {
                HooksAction::Clean { path, force } => hooks_clean(path, force),
            }
        }
        Some(Command::Agent { action }) => agent(action).await,
        Some(Command::Generate { action }) => generate(action).await,
        Some(Command::Health) => health(&url).await,
        Some(Command::Tui {
            url: tui_url,
            interval_ms,
        }) => {
            let resolved = trusty_mpm::core::resolve_daemon_url(tui_url.as_deref());
            trusty_mpm::tui::run(resolved, interval_ms).await
        }
        Some(Command::Gui) => launch_gui(),
        Some(Command::Telegram { cmd }) => telegram(&url, cmd).await,
        Some(Command::Slack { cmd }) => slack(cmd).await,
        Some(Command::Install {
            force,
            reset_agents,
            reset_agents_workspaces,
            reconcile_skills,
        }) => {
            install(
                force,
                reset_agents,
                reset_agents_workspaces,
                reconcile_skills,
            )
            .await
        }
        Some(Command::Hook { pm_guard }) => {
            if pm_guard {
                commands::pm_guard::pm_guard(&url).await
            } else {
                hook(&client, &url).await
            }
        }
        Some(Command::Compress { tool }) => run_compress(&tool).await,
        Some(Command::Daemon {
            addr,
            tailscale,
            mcp,
            force,
        }) => run_daemon(addr, tailscale, mcp, force).await,
        Some(Command::Supervisor {
            addr,
            interval,
            auto_resume,
            no_classify,
        }) => commands::supervisor::run_supervisor(addr, interval, auto_resume, no_classify).await,
        Some(Command::Launch { dir, style }) => launch(&client, &url, dir, style).await,
        Some(Command::Connect { dir }) => connect(&client, &url, dir).await,
        Some(Command::Attach { target, json }) => attach_cmd(&client, &url, &target, json).await,
        Some(Command::Optimizer { action }) => optimizer(&client, &url, action).await,
        Some(Command::Overseer { action }) => overseer(&client, &url, action).await,
        Some(Command::Coordinator { message, action }) => {
            // DOC-14 SM-STDIO (#1291): `tm sm serve --stdio` runs the JSON-RPC
            // over STDIO adapter; a plain `tm sm <message>` chats as before.
            match action {
                Some(action) => commands::sm_serve::run_sm_serve(action).await,
                None => match message {
                    Some(message) => coordinator(&url, message).await,
                    None => Err(anyhow::anyhow!(
                        "provide a message (`tm sm <message>`) or a subcommand \
                         (`tm sm serve --stdio`)"
                    )),
                },
            }
        }
        Some(Command::Services { action }) => services(action),
        Some(Command::Repair { action }) => {
            use cli::RepairAction;
            match action {
                RepairAction::Deploy { force } => repair_deploy(force),
                RepairAction::PushGuard { path, dry_run } => {
                    commands::push_guard::repair_push_guard(path, dry_run)
                }
            }
        }
        Some(Command::Auth { action }) => {
            use cli::AuthAction;
            match action {
                AuthAction::SetToken { token, stdin } => commands::auth::set_token(token, stdin),
                AuthAction::ClearToken => commands::auth::clear_token(),
                AuthAction::Status => commands::auth::status(),
            }
        }
        Some(Command::Catalog { action }) => commands::managed::catalog(action).await,
        Some(Command::Ticket {
            issue,
            system,
            notes,
            runtime,
        }) => commands::ticket::ticket(&client, &url, issue, system, notes, runtime).await,
        Some(Command::Issue { cmd, system }) => commands::issue::issue(cmd, system),
        Some(Command::Watch { cmd }) => dispatch_watch(&client, &url, cmd).await,
        // #1045: the metaharness boots standalone (no daemon, no HTTP client).
        // The handler is async because `meta run` (#1049/#1051) launches a real
        // `claude` tmux session and `--demo` polls for it to exit. A demo
        // verification failure/timeout returns `Err`, which `main` maps to a
        // non-zero process exit (the #1051 acceptance criterion).
        Some(Command::Meta { action }) => commands::meta::meta(action).await,

        // DOC-24: standalone managed driver commands.
        // Each command resolves ManagedPaths once at entry (closes #1566):
        // --root flag > TRUSTY_MPM_ROOT env > XDG config file > default.
        Some(Command::Register {
            alias,
            url,
            force,
            root,
        }) => {
            let paths = commands::managed_root::resolve_managed_paths(root.as_deref())?;
            commands::standalone::register_cmd(&paths, &alias, &url, force)
        }
        Some(Command::Ls {
            terms,
            projects,
            json,
            source_id,
            current,
            all,
            root,
        }) => {
            if projects {
                // #2311: `--projects`/`-p` preserves the DOC-24 alias/project list.
                // `terms` (the sort/filter grammar) is session-mode only; ignored here.
                let paths = commands::managed_root::resolve_managed_paths(root.as_deref())?;
                commands::standalone::ls_cmd(&paths, json)
            } else {
                // #2311: bare `tm ls` is the interactive managed-session connector
                // (TTY-aware; static + pipeable when non-TTY / --json / --all / 0).
                let (sort, term) = commands::session_picker::parse_ls_terms(&terms);
                commands::session_picker::run_ls_connector(
                    &client, &url, json, source_id, current, all, sort, term,
                )
                .await
            }
        }
        Some(Command::Load { alias, root }) => {
            let paths = commands::managed_root::resolve_managed_paths(root.as_deref())?;
            commands::standalone::load_cmd(&paths, &alias)
        }
        Some(Command::Run { alias, task, root }) => {
            // F5: --task is not yet implemented in the MVP standalone driver.
            // Per spec (DOC-24), autonomous/task dispatch is the session-manager
            // layer, not `tm run`. Warn clearly so the flag is not silently
            // dropped without user awareness.
            if let Some(ref t) = task {
                eprintln!(
                    "warning: --task '{t}' is not yet implemented in the standalone MVP \
                     and will be ignored. Task dispatch is handled by the session-manager \
                     layer (a future phase of DOC-24)."
                );
            }
            let paths = commands::managed_root::resolve_managed_paths(root.as_deref())?;
            commands::standalone::run_cmd(&paths, &alias)
        }
        Some(Command::Path { alias, root }) => {
            let paths = commands::managed_root::resolve_managed_paths(root.as_deref())?;
            commands::standalone::path_cmd(&paths, &alias)
        }
        Some(Command::Login { root }) => {
            let paths = commands::managed_root::resolve_managed_paths(root.as_deref())?;
            commands::standalone::login_cmd(&paths)
        }
        Some(Command::Rm { alias, root }) => {
            let paths = commands::managed_root::resolve_managed_paths(root.as_deref())?;
            commands::standalone::rm_cmd(&paths, &alias)
        }
        Some(Command::Update { alias, root }) => {
            let paths = commands::managed_root::resolve_managed_paths(root.as_deref())?;
            commands::standalone::update_cmd(&paths, alias.as_deref())
        }
        Some(Command::Sessctl { action }) => {
            commands::sessctl::dispatch(&client, &url, action).await
        }
        Some(Command::Statusline) => commands::statusline::run_statusline(),
        Some(Command::Banner { reconnecting }) => {
            commands::banner::run_banner_preview(reconnecting)
        }
        // `tm mcp …` is a direct, daemon-less command family (like the standalone
        // driver): it edits the tm-owned config dir's `.claude.json` on disk.
        Some(Command::Mcp { cmd }) => match cmd {
            cli::McpCmd::Add {
                name,
                transport,
                env,
                header,
                command_and_args,
                root,
            } => commands::mcp::add_cmd(
                root.as_deref(),
                &name,
                transport,
                &env,
                &header,
                &command_and_args,
            ),
            cli::McpCmd::Remove { name, root } => commands::mcp::remove_cmd(root.as_deref(), &name),
            cli::McpCmd::List { json, root } => commands::mcp::list_cmd(root.as_deref(), json),
            cli::McpCmd::Get { name, json, root } => {
                commands::mcp::get_cmd(root.as_deref(), &name, json)
            }
            cli::McpCmd::Test { name, json, root } => {
                commands::mcp::test_cmd(root.as_deref(), name.as_deref(), json).await
            }
        },
        // Unreachable at runtime: `Command::Config` is dispatched — and
        // `cli.command` returned early — before this match ever runs (see the
        // #2405 early short-circuit above, right after `Cli::try_parse`).
        // The arm still must exist for match exhaustiveness over `Command`.
        Some(Command::Config(_)) => unreachable!("config dispatched before daemon-URL resolution"),
        // Unreachable for the same reason as `Config`: the #2997 disclaim-exec
        // shim returned early right after `Config` above, before this match.
        Some(Command::InternalSpawnDisclaimed { .. }) => {
            unreachable!("internal-spawn-disclaimed dispatched before daemon-URL resolution")
        }
    };

    // Top-level exit-code translation: a `tm session prune-idle` that found the
    // Session Manager unavailable returns `PruneError::SmUnavailable`. That is a
    // graceful no-op, not a failure, so exit with the distinct code 75 (the
    // pause skill branches on it) instead of anyhow's default 1. Any other error
    // propagates normally (exit 1); `Ok` returns cleanly.
    if let Err(err) = &result
        && matches!(
            err.downcast_ref::<commands::prune::PruneError>(),
            Some(commands::prune::PruneError::SmUnavailable)
        )
    {
        std::process::exit(commands::prune::EXIT_SM_UNAVAILABLE);
    }
    // #1737: the bare `tm` guided default returns `DaemonUrlError::Unreachable`
    // when an EXPLICIT `--url`/`TRUSTY_MPM_URL` fails its reachability probe
    // (see `commands::guided::run_guided_default`'s guard, which already
    // printed the message — this arm only translates the exit code, mirroring
    // the `PruneError::SmUnavailable` block above so the two "target
    // unavailable" conventions exit identically).
    if let Err(err) = &result
        && err
            .downcast_ref::<trusty_mpm::core::DaemonUrlError>()
            .is_some()
    {
        std::process::exit(trusty_mpm::core::exit_codes::EXIT_UNAVAILABLE);
    }
    result
}

/// Dispatch a `tm watch poll|listen` invocation to its handler.
///
/// Why: keeps `main`'s match arm thin by folding the flattened [`WatchArgs`] into
/// the [`commands::watch`] entry points in one place, mapping the shared CLI flags
/// onto the module's `RawWatchArgs` and the safety-gate booleans.
/// What: builds a `RawWatchArgs` from the parsed flags and calls
/// [`commands::watch::poll`] or [`commands::watch::listen`] accordingly, threading
/// the `--execute`/`--dry-run` safety flags and the spawn runtime through.
/// Test: the resolution/safety logic is unit-tested in `commands::watch::tests`;
/// CLI parsing in `tests.rs` (`cli_parses_watch_*`).
async fn dispatch_watch(
    client: &reqwest::Client,
    url: &str,
    cmd: cli::WatchCmd,
) -> anyhow::Result<()> {
    use cli::{WatchArgs, WatchCmd};
    use commands::watch::args::RawWatchArgs;

    fn raw(args: &WatchArgs) -> RawWatchArgs {
        RawWatchArgs {
            project: args.project.clone(),
            label: args.label.clone(),
            interval_secs: args.interval_secs,
            state: args.state,
        }
    }

    match cmd {
        WatchCmd::Poll { args } => {
            commands::watch::poll(
                client,
                url,
                raw(&args),
                args.execute,
                args.dry_run,
                args.runtime,
            )
            .await
        }
        WatchCmd::Listen { args } => {
            commands::watch::listen(
                client,
                url,
                raw(&args),
                args.execute,
                args.dry_run,
                args.runtime,
            )
            .await
        }
    }
}

/// Launch the Tauri desktop GUI by shelling out to the `trusty-mpm-gui` binary.
///
/// Why: the GUI lives in the separate, publish=false `trusty-mpm-gui` crate
/// (it owns Tauri's `build.rs` + `tauri.conf.json`, which cannot be published
/// cleanly to crates.io). Declaring it as an optional Cargo dependency blocks
/// `cargo publish` for trusty-mpm, so `tm gui` instead launches a separately
/// installed `trusty-mpm-gui` binary — matching the Single-Install convention.
/// What: resolves the `trusty-mpm-gui` executable next to the running `tm`
/// binary (via `current_exe().parent()`), falling back to a bare `trusty-mpm-gui`
/// name so the OS resolves it on `PATH`. Spawns it and waits for it to exit,
/// returning an actionable error if the binary is not installed.
/// Test: the not-found → install-hint mapping is covered by `tests.rs`
/// (`gui_not_found_error_has_install_hint`), which exercises `gui_status_to_result`
/// directly with a synthetic `NotFound` error.
fn launch_gui() -> anyhow::Result<()> {
    let program = resolve_gui_binary();
    gui_status_to_result(std::process::Command::new(&program).status())
}

/// Map the outcome of spawning `trusty-mpm-gui` to a CLI-friendly result.
///
/// Why: factoring the result mapping out of `launch_gui` keeps the actionable
/// "not installed" hint unit-testable without actually spawning a GUI process.
/// What: success → `Ok`; non-zero exit → error with the status; `NotFound`
/// spawn error → the install hint; any other spawn error → a context error.
/// Test: `tests.rs::gui_not_found_error_has_install_hint`.
fn gui_status_to_result(status: std::io::Result<std::process::ExitStatus>) -> anyhow::Result<()> {
    match status {
        Ok(status) if status.success() => Ok(()),
        Ok(status) => anyhow::bail!("trusty-mpm-gui exited with status: {status}"),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => anyhow::bail!(
            "trusty-mpm-gui is not installed.\n\
             Install it with: cargo install trusty-mpm-gui\n\
             (the desktop GUI ships as a separate Tauri crate; `tm gui` launches it)"
        ),
        Err(err) => Err(anyhow::Error::new(err).context("failed to launch trusty-mpm-gui")),
    }
}

/// Resolve the path to the `trusty-mpm-gui` executable.
///
/// Why: a `cargo install`-based deployment lands every trusty-* binary in the
/// same directory (`~/.cargo/bin`), so the sibling-of-`tm` lookup is the most
/// reliable. We fall back to the bare binary name so a `PATH`-installed GUI is
/// still found when `current_exe()` is unavailable or the sibling is missing.
/// What: returns `<dir-of-current-exe>/trusty-mpm-gui` when that file exists,
/// otherwise the bare `trusty-mpm-gui` name (resolved by the OS via `PATH`).
/// Test: indirectly exercised by `launch_gui`'s missing-binary test; the
/// sibling-exists branch is environment-dependent and not unit-tested.
fn resolve_gui_binary() -> std::path::PathBuf {
    const GUI_BIN: &str = "trusty-mpm-gui";
    if let Ok(exe) = std::env::current_exe()
        && let Some(dir) = exe.parent()
    {
        // Include the platform executable suffix (`.exe` on Windows; "" on
        // macOS/Linux) so the sibling lookup finds the GUI binary on every OS.
        let sibling = dir.join(format!("{GUI_BIN}{}", std::env::consts::EXE_SUFFIX));
        if sibling.is_file() {
            return sibling;
        }
    }
    std::path::PathBuf::from(GUI_BIN)
}