trusty-mpm 1.7.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
802
803
804
805
806
807
808
809
//! `tm projects` registry verbs: list / register / show / status (#2115).
//!
//! Why: the registry-B half of the project control plane โ€” enumerate, upsert,
//! inspect (config + read-only nested sessions), and roll up a project's status.
//! Each verb is a thin client over a `DaemonClient` method (`projects.rs`),
//! rendering either a human view or, with `--json`, the raw wire JSON for
//! scripting (matching the `--json`-everywhere convention of `tm sessions`).
//! What: [`list`], [`register`], [`show`], [`status`] plus the pure human-render
//! helpers they delegate to. `show`'s nested sessions come from the fleet endpoint
//! (read-only per ยง3.1); the render explicitly points mutation at `tm sessions`.
//! Test: `render_status_line_*`, `render_project_line_*` (pure render) in the
//! `tests` submodule; live HTTP via the daemon route tests.

use trusty_mpm::client::DaemonClient;
use trusty_mpm::client::http_client::projects::{ProjectStatusWire, RegisterProjectArgs};
use trusty_mpm::project::Project;
use trusty_mpm::project_config::{self, ConfigEdit};

use crate::cli::ConfigAction;

/// Owned inputs for [`register`], mirroring the `Register` clap variant.
///
/// Why: passing the seven register fields as one struct keeps the dispatcher and
/// this handler's signature readable (clippy `too_many_arguments`).
/// What: the register flags; `tags` is empty (not `None`) when unspecified.
/// Test: covered via `register`'s live-HTTP path.
pub(crate) struct RegisterInput {
    pub name: String,
    pub repo_url: String,
    pub default_branch: Option<String>,
    pub description: Option<String>,
    pub tags: Vec<String>,
    pub stack_hint: Option<String>,
    pub gh_user: Option<String>,
    pub gh_account: Option<String>,
    /// #5851: scoped `gh` config home written to `github.config_dir`.
    pub gh_config_dir: Option<std::path::PathBuf>,
}

/// Build a `DaemonClient` from the CLI's shared `(reqwest::Client, url)` pair.
fn daemon(client: &reqwest::Client, url: &str) -> DaemonClient {
    DaemonClient::with_client(client.clone(), url.to_string())
}

/// `tm projects list [--json] [--tag <t>]` โ€” enumerate registered projects.
pub(crate) async fn list(
    client: &reqwest::Client,
    url: &str,
    json: bool,
    tag: Option<String>,
) -> anyhow::Result<()> {
    let projects = daemon(client, url)
        .registry_list_projects(tag.as_deref())
        .await?;
    if json {
        println!("{}", serde_json::to_string_pretty(&projects)?);
        return Ok(());
    }
    if projects.is_empty() {
        println!("no projects registered");
        return Ok(());
    }
    for p in &projects {
        println!("{}", render_project_line(p));
    }
    Ok(())
}

/// `tm projects register <name> --repo-url ...` โ€” idempotent upsert.
///
/// Why: `register` is an UNQUALIFIED upsert โ€” every call, including the
/// automatic ones `run_managed`/`tm register --account` now make on a bare
/// `tm --account <login> <url>` (#7166), replaces the persisted record
/// wholesale. Silently rebinding a project's `gh_account` this way โ€” later
/// spawns, fetches, pushes, and `gh` calls all follow it โ€” deserves a visible
/// trail even when the call itself succeeds, not just a warning on failure.
/// What: reads the project's CURRENT `gh_account` (best-effort โ€” a fetch
/// failure, e.g. because the project does not exist yet, is treated as "no
/// prior value" rather than aborting the register) BEFORE the upsert; after
/// a successful upsert, delegates the "is this a loggable change" decision to
/// the pure [`account_change_log_line`].
/// Test: `account_change_log_line_*` (pure-function coverage of the decision;
/// the HTTP fetch-then-upsert sequencing itself has no hermetic test in this
/// file โ€” see that function's doc).
pub(crate) async fn register(
    client: &reqwest::Client,
    url: &str,
    input: RegisterInput,
) -> anyhow::Result<()> {
    let previous_gh_account = daemon(client, url)
        .registry_get_project(&input.name)
        .await
        .ok()
        .and_then(|p| p.gh_account);
    let new_gh_account = input.gh_account.clone();
    let name_for_log = input.name.clone();

    let args = RegisterProjectArgs {
        name: input.name,
        repo_url: input.repo_url,
        default_branch: input.default_branch,
        description: input.description,
        tags: if input.tags.is_empty() {
            None
        } else {
            Some(input.tags)
        },
        stack_hint: input.stack_hint,
        gh_user: input.gh_user,
        gh_account: input.gh_account,
        // #5851: pairs with `gh_account` so one command arms both keys
        // `configured_account_pair` requires.
        gh_config_dir: input.gh_config_dir,
        // #3455: not a `register`-time flag โ€” set via `tm projects config
        // <name> set worktree true|false` instead (mirrors how the other
        // configurator-only fields have no `register` flag either).
        worktree: None,
    };
    let project = daemon(client, url).registry_register_project(&args).await?;
    println!(
        "registered project '{}' ({} @ {})",
        project.name, project.repo_url, project.default_branch
    );
    // #7166 review follow-up: a successful upsert that REPLACES a previously
    // pinned account is a fact worth a visible trail, not just a failure warning.
    if let Some(line) = account_change_log_line(
        &name_for_log,
        previous_gh_account.as_deref(),
        new_gh_account.as_deref(),
    ) {
        tracing::info!("{line}");
    }
    Ok(())
}

/// Decide whether a `register` call's `gh_account` change is loggable, and
/// render the line if so (#7166 review follow-up).
///
/// Why: split out of [`register`] so the decision โ€” old and new both `Some`
/// AND different โ€” is asserted without an HTTP round trip.
/// What: `None` unless BOTH `previous` and `new` are `Some` and unequal โ€” a
/// brand-new project (`previous: None`) or one moving from unset to set is
/// not a "change" worth flagging, only a REPLACEMENT is.
/// Test: `account_change_log_line_logs_a_real_change`,
/// `account_change_log_line_silent_when_unchanged`,
/// `account_change_log_line_silent_when_previously_unset`,
/// `account_change_log_line_silent_when_new_is_unset`.
fn account_change_log_line(
    name: &str,
    previous: Option<&str>,
    new: Option<&str>,
) -> Option<String> {
    match (previous, new) {
        (Some(old), Some(new)) if old != new => Some(format!(
            "tm: project '{name}' gh_account changed: '{old}' -> '{new}'"
        )),
        _ => None,
    }
}

/// Best-effort persist of an account selection onto the daemon's registry-B
/// project record, shared by `run_managed`'s post-clone step and `tm register
/// --account`'s handler (#7166 review follow-up CRITICAL/HIGH).
///
/// Why: both callers need the IDENTICAL two fixes โ€” thread the per-account gh
/// config dir into `RegisterInput.gh_config_dir` (instead of the old
/// unconditional `None`, which left every session spawn AFTER this one on the
/// demoted `gh auth token -u` selector) and preserve the project's current
/// `default_branch` (instead of resetting it to `"main"` on every
/// `--account` run) โ€” a single call site is how a divergence between two
/// hand-duplicated copies is prevented, not just how it is fixed once.
/// `warning_context` (e.g. `"cloned as {account}"`, `"registered"`) makes the
/// two callers' user-facing warnings read naturally without duplicating the
/// three-step body.
/// What: resolves `gh_config_dir` via
/// [`trusty_mpm::daemon::managed_routes::inproject::account_config_dir_for`]
/// through [`resolve_account_gh_config_dir`], `default_branch` via
/// [`current_default_branch`], then calls [`register`] with both โ€” printing a
/// `warning:` line (never aborting; the clone/registration this follows
/// already succeeded) on either the config-dir build or the final upsert
/// failing.
/// Test: the two decisions this delegates to โ€”
/// [`resolve_account_gh_config_dir`] and [`default_branch_to_preserve`] (via
/// [`current_default_branch`]) โ€” are tested directly below; this function is
/// thin call-site wiring with no branch logic of its own to test
/// hermetically.
pub(crate) async fn auto_persist_account_selection(
    client: &reqwest::Client,
    url: &str,
    name: String,
    repo_url: String,
    account: &str,
    warning_context: &str,
) {
    let (gh_config_dir, config_dir_warning) = resolve_account_gh_config_dir(
        trusty_mpm::daemon::managed_routes::inproject::account_config_dir_for(account),
    );
    if let Some(w) = config_dir_warning {
        eprintln!(
            "warning: {warning_context}, but could not build its per-account gh config \
             directory to persist on the project registration: {w}. Later spawns for this \
             project will fall back to the less reliable `gh auth token -u` selector."
        );
    }

    let default_branch = current_default_branch(client, url, &name).await;

    if let Err(e) = register(
        client,
        url,
        RegisterInput {
            name,
            repo_url,
            default_branch,
            description: None,
            tags: Vec::new(),
            stack_hint: None,
            gh_user: None,
            gh_account: Some(account.to_string()),
            gh_config_dir,
        },
    )
    .await
    {
        eprintln!(
            "warning: {warning_context}, but could not persist that account on the project \
             registration: {e}. Later spawns for this project will not automatically reuse it \
             โ€” pin it by hand with `tm projects register --gh-account {account} โ€ฆ`."
        );
    }
}

/// Decide whether an account-selected auto-[`register`] call should persist a
/// `gh_config_dir`, from the per-account config dir bootstrap's own result
/// (#7166 review follow-up CRITICAL).
///
/// Why: `run_managed`/`tm register --account`'s auto-persist call used to pass
/// `gh_config_dir: None` unconditionally, discarding the discriminating
/// per-account directory
/// [`trusty_mpm::daemon::managed_routes::inproject::account_config_dir_for`]
/// just built or reused. Every session spawn AFTER the first clone then fell
/// back to `resolve_gh_account_env_for_registry`'s demoted `gh auth token -u
/// <account>` arm โ€” the exact "does not discriminate between logged-in
/// accounts on a keyring-backed host" defect #7166 exists to close.
/// What: `Ok(dir)` โ†’ `(Some(dir), None)`, the dir to persist; `Err(message)`
/// โ†’ `(None, Some(message))`, so the caller can warn without aborting an
/// already-succeeded clone/registration (matches [`register`]'s own
/// best-effort failure handling).
/// Test: `resolve_account_gh_config_dir_persists_a_built_dir`,
/// `resolve_account_gh_config_dir_warns_and_omits_on_failure`.
fn resolve_account_gh_config_dir(
    build_result: Result<std::path::PathBuf, String>,
) -> (Option<std::path::PathBuf>, Option<String>) {
    match build_result {
        Ok(dir) => (Some(dir), None),
        Err(message) => (None, Some(message)),
    }
}

/// Best-effort lookup of an already-registered project's CURRENT
/// `default_branch`, for an auto-persist [`register`] caller with no explicit
/// value of its own (#7166 review follow-up HIGH).
///
/// Why: the daemon's `register_project_registry_op` preserves every OTHER
/// optional field across a re-register (`.or_else(|| existing...)`), but
/// `default_branch` is not one of them โ€” a bare `None` resolves to `"main"`
/// unconditionally. `run_managed`/`tm register --account`'s auto-persist call
/// fires on EVERY `--account` invocation, including a reused checkout, so
/// without this lookup a project with a customized default branch (e.g.
/// `develop`) was silently reset to `main` on every one of them.
/// What: a best-effort `registry_get_project` fetch, then
/// [`default_branch_to_preserve`] โ€” a lookup failure (including "project does
/// not exist yet") is treated as "no prior value" rather than aborting,
/// mirroring [`register`]'s own `previous_gh_account` fetch.
/// Test: exercised via `run_target`/`main.rs`'s call sites; the decision
/// itself is [`default_branch_to_preserve`], tested directly below.
async fn current_default_branch(client: &reqwest::Client, url: &str, name: &str) -> Option<String> {
    let existing = daemon(client, url).registry_get_project(name).await.ok();
    default_branch_to_preserve(existing.as_ref())
}

/// Pure decision behind [`current_default_branch`]: pass through an existing
/// project's `default_branch`, or `None` for a genuinely new one (which the
/// daemon then defaults to `"main"`).
/// Test: `default_branch_to_preserve_keeps_existing`,
/// `default_branch_to_preserve_is_none_for_a_new_project`.
fn default_branch_to_preserve(existing: Option<&Project>) -> Option<String> {
    existing.map(|p| p.default_branch.clone())
}

/// `tm projects show <name> [--json]` โ€” config + read-only nested sessions.
pub(crate) async fn show(
    client: &reqwest::Client,
    url: &str,
    name: &str,
    json: bool,
) -> anyhow::Result<()> {
    let daemon = daemon(client, url);
    let project = daemon.registry_get_project(name).await?;

    // Read-only nested sessions via the fleet endpoint (ยง3.1). A fleet read
    // failure must not sink the whole `show` โ€” the config is the primary payload
    // โ€” so degrade to an empty session list on error, but warn so the operator
    // knows the session list may be incomplete rather than genuinely empty.
    let sessions = match daemon.fleet_managed_sessions().await {
        Ok(groups) => groups
            .into_iter()
            .find(|g| g.project_name == project.name)
            .map(|g| g.sessions)
            .unwrap_or_default(),
        Err(e) => {
            eprintln!("warning: could not read sessions: {e}");
            Vec::new()
        }
    };

    if json {
        let out = serde_json::json!({
            "project": project,
            "sessions": sessions.iter().map(|s| serde_json::json!({
                "id": s.id, "name": s.name, "state": s.state,
                "branch": s.branch, "task": s.task,
            })).collect::<Vec<_>>(),
        });
        println!("{}", serde_json::to_string_pretty(&out)?);
        return Ok(());
    }

    println!("{}", render_project_line(&project));
    if let Some(desc) = &project.description {
        println!("  description: {desc}");
    }
    if !project.tags.is_empty() {
        println!("  tags: {}", project.tags.join(", "));
    }
    if let Some(gh) = &project.gh_user {
        println!("  gh_user: {gh}");
    }
    if let Some(gh) = &project.gh_account {
        println!("  gh_account: {gh}");
    }
    println!(
        "  sessions ({}) [read-only โ€” mutate via `tm sessions <verb>`]:",
        sessions.len()
    );
    if sessions.is_empty() {
        println!("    (none)");
    } else {
        for s in &sessions {
            let branch = s.branch.as_deref().unwrap_or("-");
            println!("    {} {} [{}] {}", s.id, s.name, s.state, branch);
        }
    }
    Ok(())
}

/// `tm projects status <name> [--json]` โ€” deterministic status rollup.
pub(crate) async fn status(
    client: &reqwest::Client,
    url: &str,
    name: &str,
    json: bool,
) -> anyhow::Result<()> {
    let status = daemon(client, url).project_status(name).await?;
    if json {
        // Re-serialize the parsed rollup. Additive #2382 fields the client does
        // not model are dropped here; `--json` consumers that need them can hit
        // the endpoint directly. The human view below is the stable surface.
        let out = serde_json::json!({
            "project_name": status.project_name,
            "repo_url": status.repo_url,
            "sessions": {
                "provisioning": status.sessions.provisioning,
                "active": status.sessions.active,
                "stopped": status.sessions.stopped,
                "errored": status.sessions.errored,
                "decommissioned": status.sessions.decommissioned,
                "total": status.sessions.total,
            },
            "last_activity_at": status.last_activity_at,
            "config": {
                "gh_user_set": status.config.gh_user_set,
                "github_binding_set": status.config.github_binding_set,
                "gh_account_set": status.config.gh_account_set,
            },
        });
        println!("{}", serde_json::to_string_pretty(&out)?);
        return Ok(());
    }
    for line in render_status(&status) {
        println!("{line}");
    }
    Ok(())
}

/// `tm projects config <name> [set|unset|tags]` โ€” view or edit config fields
/// (DOC-35 ยง3.1/ยง6, #2120).
///
/// Why: the deterministic CLI half of the configurator โ€” a thin client over
/// `PATCH /api/v1/projects/{name}` via the shared
/// [`trusty_mpm::project_config`] edit model, so this front end and the TUI
/// form can never drift on what a given edit means on the wire (ยง6 RESOLVED).
/// What: `action = None` is a read-only view (GET, human or `--json`); each
/// `Some(ConfigAction)` variant maps to exactly one [`ConfigEdit`] and PATCHes
/// it. `Tags` with both `--add`/`--remove` empty is rejected client-side
/// (disclosed judgment call โ€” a friendlier `bail!` here rather than sending a
/// genuine no-op PATCH the server would just idempotently accept).
/// Test: `cli_parses_projects_config_*` (parse) in `tests_projects.rs`;
/// `projects_config_shared_cases_match_cli_arg_building` exercises this
/// module's own edit-to-`ConfigEdit` mapping against the shared case table;
/// live HTTP via the daemon route tests.
pub(crate) async fn config(
    client: &reqwest::Client,
    url: &str,
    name: &str,
    json: bool,
    action: Option<ConfigAction>,
) -> anyhow::Result<()> {
    match action {
        None => config_view(client, url, name, json).await,
        Some(ConfigAction::Set {
            field: crate::cli::SettableConfigField::Worktree,
            value,
        }) => {
            // #3455: `worktree` is the one settable field with a non-string
            // (bool) wire type; validate client-side so the daemon always
            // receives exactly "true"/"false" โ€” never free text.
            let normalized = normalize_bool_flag(&value)?;
            config_apply(
                client,
                url,
                name,
                ConfigEdit::Set(project_config::ConfigField::Worktree, normalized),
            )
            .await
        }
        Some(ConfigAction::Set { field, value }) => {
            config_apply(client, url, name, ConfigEdit::Set(field.into(), value)).await
        }
        Some(ConfigAction::Unset { field }) => {
            config_apply(client, url, name, ConfigEdit::Unset(field.into())).await
        }
        Some(ConfigAction::Tags { add, remove }) => {
            if add.is_empty() && remove.is_empty() {
                anyhow::bail!("tags: provide --add and/or --remove");
            }
            config_apply(client, url, name, ConfigEdit::Tags { add, remove }).await
        }
    }
}

/// `tm projects config <name>` (no subcommand) โ€” read-only config view.
async fn config_view(
    client: &reqwest::Client,
    url: &str,
    name: &str,
    json: bool,
) -> anyhow::Result<()> {
    let project = daemon(client, url).registry_get_project(name).await?;
    if json {
        println!("{}", serde_json::to_string_pretty(&project)?);
        return Ok(());
    }
    println!("{}", render_config_view(&project));
    Ok(())
}

/// Apply one [`ConfigEdit`] via `PATCH /api/v1/projects/{name}` and print the
/// updated config.
///
/// Why: the single call site every `ConfigAction` variant in [`config`]
/// routes through โ€” one PATCH, one render, matching [`register`]'s
/// print-after-write convention.
/// What: builds the wire args via [`project_config::build_patch_args`] (the
/// SAME builder the TUI form's submit uses), PATCHes, and renders the
/// server's returned (authoritative, post-write) record. A 400/404 surfaces
/// as an `anyhow::Error` via `DaemonClient::registry_patch_project`, whose
/// message now carries the daemon's actual rejection reason (#2485) โ€”
/// propagated unchanged, printed by `main`'s default error handler.
async fn config_apply(
    client: &reqwest::Client,
    url: &str,
    name: &str,
    edit: ConfigEdit,
) -> anyhow::Result<()> {
    let args = project_config::build_patch_args(&edit);
    let project = daemon(client, url)
        .registry_patch_project(name, &args)
        .await?;
    println!("updated project '{}'", project.name);
    println!("{}", render_config_view(&project));
    Ok(())
}

/// Render a project's configurator-scoped fields (DOC-35 ยง6's field table):
/// `default_branch`, `description`, `tags`, `stack_hint`, `gh_user` โ€” no
/// nested sessions (that is `show`'s job, not `config`'s).
fn render_config_view(p: &Project) -> String {
    let lines = [
        format!("{} ({})", p.name, p.repo_url),
        format!("  default_branch: {}", p.default_branch),
        format!(
            "  description: {}",
            p.description.as_deref().unwrap_or("(unset)")
        ),
        format!(
            "  tags: {}",
            if p.tags.is_empty() {
                "(none)".to_string()
            } else {
                p.tags.join(", ")
            }
        ),
        format!(
            "  stack_hint: {}",
            p.stack_hint.as_deref().unwrap_or("(unset)")
        ),
        format!("  gh_user: {}", p.gh_user.as_deref().unwrap_or("(unset)")),
        format!(
            "  gh_account: {}",
            p.gh_account.as_deref().unwrap_or("(unset)")
        ),
        format!(
            "  worktree: {}",
            if p.worktree_enabled() {
                "true (isolated per-session worktree)"
            } else {
                "false (launch on main โ€” #3455)"
            }
        ),
    ];
    lines.join("\n")
}

/// Validate a `tm projects config <name> set worktree <value>` value (#3455).
///
/// Why: `worktree` is the one settable field with a `bool` wire type, not a
/// `String` โ€” reject anything but `true`/`false` HERE, client-side, so the
/// daemon's `ConfigEdit::Set(ConfigField::Worktree, _)` handling can safely
/// assume the string is always one of the two literals rather than doing its
/// own silent best-effort parse.
/// What: case-insensitively accepts `"true"`/`"false"`, returning the
/// canonical lowercase form; any other input is an `anyhow::Error` naming the
/// rejected value.
/// Test: `normalize_bool_flag_accepts_true_false_case_insensitive`,
/// `normalize_bool_flag_rejects_other_values`.
fn normalize_bool_flag(value: &str) -> anyhow::Result<String> {
    match value.trim().to_ascii_lowercase().as_str() {
        "true" => Ok("true".to_string()),
        "false" => Ok("false".to_string()),
        other => anyhow::bail!("worktree: expected 'true' or 'false', got {other:?}"),
    }
}

/// Render one project as a compact `name  repo_url  (branch)` line.
///
/// Why: shared between `list`, `show`, and the singular `tm project list`
/// (#5994), which appends its own `[plugin-trusted]` marker to this line rather
/// than growing a second renderer that could drift from it.
/// What: name, repo URL, and default branch on one line.
/// Test: `render_project_line_basic`.
pub(crate) fn render_project_line(p: &Project) -> String {
    format!("{}\t{}\t({})", p.name, p.repo_url, p.default_branch)
}

/// Render the status rollup as human lines.
///
/// Why: `tm projects status` prints a small multi-line rollup; a pure function of
/// the parsed [`ProjectStatusWire`] keeps it deterministic and testable.
/// What: the identity line, the session histogram, last activity, and the config
/// flags.
/// Test: `render_status_line_counts`, `render_status_no_activity`.
fn render_status(s: &ProjectStatusWire) -> Vec<String> {
    let c = &s.sessions;
    let activity = s
        .last_activity_at
        .map(|t| t.to_rfc3339())
        .unwrap_or_else(|| "never".to_string());
    vec![
        format!("{} ({})", s.project_name, s.repo_url),
        format!(
            "  sessions: {} total  ({} active, {} provisioning, {} stopped, {} errored, {} decommissioned)",
            c.total, c.active, c.provisioning, c.stopped, c.errored, c.decommissioned
        ),
        format!("  last activity: {activity}"),
        format!(
            "  config: gh_user {}, gh_account {}, gh-binding {}",
            if s.config.gh_user_set { "set" } else { "unset" },
            if s.config.gh_account_set {
                "set"
            } else {
                "unset"
            },
            if s.config.github_binding_set {
                "set"
            } else {
                "unset"
            }
        ),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use trusty_mpm::client::http_client::projects::{
        ProjectConfigFlagsWire, SessionStateCountsWire,
    };

    fn project() -> Project {
        Project {
            name: "widget".into(),
            repo_url: "https://github.com/acme/widget".into(),
            default_branch: "main".into(),
            stack_hint: None,
            tags: vec![],
            description: None,
            gh_user: None,
            gh_account: None,
            github: None,
            commit_name: None,
            commit_email: None,
            worktree: None,
        }
    }

    #[test]
    fn render_project_line_basic() {
        let line = render_project_line(&project());
        assert!(line.contains("widget"));
        assert!(line.contains("https://github.com/acme/widget"));
        assert!(line.contains("main"));
    }

    #[test]
    fn normalize_bool_flag_accepts_true_false_case_insensitive() {
        assert_eq!(normalize_bool_flag("true").unwrap(), "true");
        assert_eq!(normalize_bool_flag("FALSE").unwrap(), "false");
        assert_eq!(normalize_bool_flag("  True  ").unwrap(), "true");
    }

    #[test]
    fn normalize_bool_flag_rejects_other_values() {
        assert!(normalize_bool_flag("yes").is_err());
        assert!(normalize_bool_flag("1").is_err());
        assert!(normalize_bool_flag("").is_err());
    }

    #[test]
    fn render_config_view_shows_worktree_status() {
        let mut p = project();
        assert!(
            render_config_view(&p).contains("worktree: true"),
            "default (unset) worktree must render as the true/isolated default"
        );
        p.worktree = Some(false);
        assert!(
            render_config_view(&p).contains("worktree: false"),
            "an explicit opt-out must render as false"
        );
    }

    #[test]
    fn render_status_line_counts() {
        let s = ProjectStatusWire {
            project_name: "widget".into(),
            repo_url: "https://github.com/acme/widget".into(),
            sessions: SessionStateCountsWire {
                provisioning: 1,
                active: 2,
                stopped: 0,
                errored: 1,
                decommissioned: 0,
                total: 4,
            },
            last_activity_at: Some(
                chrono::DateTime::parse_from_rfc3339("2026-07-10T12:00:00Z")
                    .unwrap()
                    .with_timezone(&chrono::Utc),
            ),
            config: ProjectConfigFlagsWire {
                gh_user_set: true,
                github_binding_set: false,
                gh_account_set: true,
            },
        };
        let lines = render_status(&s);
        assert!(lines[0].contains("widget"));
        assert!(lines[1].contains("4 total"));
        assert!(lines[1].contains("2 active"));
        assert!(lines[2].contains("2026-07-10"));
        assert!(lines[3].contains("gh_user set"));
        assert!(lines[3].contains("gh_account set"));
    }

    #[test]
    fn render_config_view_shows_every_field() {
        let mut p = project();
        p.description = Some("the widget".to_string());
        p.tags = vec!["backend".to_string()];
        p.stack_hint = Some("rust".to_string());
        p.gh_user = Some("acme-bot".to_string());
        p.gh_account = Some("acme-bot".to_string());
        let rendered = render_config_view(&p);
        assert!(rendered.contains("default_branch: main"));
        assert!(rendered.contains("description: the widget"));
        assert!(rendered.contains("tags: backend"));
        assert!(rendered.contains("stack_hint: rust"));
        assert!(rendered.contains("gh_user: acme-bot"));
        assert!(rendered.contains("gh_account: acme-bot"));
    }

    #[test]
    fn render_config_view_shows_unset_placeholders() {
        let rendered = render_config_view(&project());
        assert!(rendered.contains("description: (unset)"));
        assert!(rendered.contains("tags: (none)"));
        assert!(rendered.contains("stack_hint: (unset)"));
        assert!(rendered.contains("gh_user: (unset)"));
        assert!(rendered.contains("gh_account: (unset)"));
    }

    #[test]
    fn render_status_no_activity() {
        let s = ProjectStatusWire {
            project_name: "widget".into(),
            repo_url: "u".into(),
            sessions: SessionStateCountsWire::default(),
            last_activity_at: None,
            config: ProjectConfigFlagsWire::default(),
        };
        let lines = render_status(&s);
        assert!(lines[2].contains("never"));
        assert!(lines[3].contains("gh_user unset"));
    }

    // -----------------------------------------------------------------------
    // #7166 review follow-up: `account_change_log_line`.
    // -----------------------------------------------------------------------

    #[test]
    fn account_change_log_line_logs_a_real_change() {
        let line = account_change_log_line("widget", Some("bobmatnyc"), Some("bob-duetto"))
            .expect("a real change must log");
        assert!(line.contains("widget"), "{line}");
        assert!(line.contains("'bobmatnyc' -> 'bob-duetto'"), "{line}");
    }

    #[test]
    fn account_change_log_line_silent_when_unchanged() {
        assert_eq!(
            account_change_log_line("widget", Some("bobmatnyc"), Some("bobmatnyc")),
            None
        );
    }

    #[test]
    fn account_change_log_line_silent_when_previously_unset() {
        // A brand-new project (or one that never had an account pinned) is
        // not a REPLACEMENT โ€” nothing to warn about losing.
        assert_eq!(
            account_change_log_line("widget", None, Some("bobmatnyc")),
            None
        );
    }

    #[test]
    fn account_change_log_line_silent_when_new_is_unset() {
        assert_eq!(
            account_change_log_line("widget", Some("bobmatnyc"), None),
            None
        );
    }

    // -----------------------------------------------------------------------
    // #7166 review follow-up: config-dir persistence and default_branch
    // preservation for the account-selected auto-`register()` call sites.
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_account_gh_config_dir_persists_a_built_dir() {
        let dir = std::path::PathBuf::from("/home/bob/.trusty-mpm/gh-accounts/bob-duetto");
        let (persisted, warning) = resolve_account_gh_config_dir(Ok(dir.clone()));
        assert_eq!(persisted, Some(dir));
        assert!(warning.is_none());
    }

    #[test]
    fn resolve_account_gh_config_dir_warns_and_omits_on_failure() {
        let (persisted, warning) = resolve_account_gh_config_dir(Err("not logged in".to_string()));
        assert!(persisted.is_none());
        assert_eq!(warning.as_deref(), Some("not logged in"));
    }

    #[test]
    fn default_branch_to_preserve_keeps_existing() {
        let mut p = project();
        p.default_branch = "develop".into();
        assert_eq!(
            default_branch_to_preserve(Some(&p)),
            Some("develop".to_string())
        );
    }

    #[test]
    fn default_branch_to_preserve_is_none_for_a_new_project() {
        assert_eq!(default_branch_to_preserve(None), None);
    }
}