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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! trusty-mpm's `~/.trusty-tools/trusty-mpm/config.yaml` settings + workspace-root
//! resolution (#1220).
//!
//! Why: #1220 introduces two related conventions for trusty-mpm. (1) the
//! cross-crate config convention `~/.trusty-tools/<crate>/config.yaml` — trusty-mpm
//! reads its slice (`~/.trusty-tools/trusty-mpm/config.yaml`) for the workspace-root
//! template, the auto-resume default, and the default model; (2) the managed-session
//! workspace-root default moves from `~/.trusty-mpm/workspaces/<project>/<id>/` to
//! `~/trusty-mpm-projects/<owner>/<repo>/<id>/`, deriving `<owner>/<repo>` from the
//! target repo's GitHub remote. Keeping the typed config AND the root resolver in one
//! module keeps the precedence rules (env > config > built-in default) in a single
//! tested place and well under the 500-SLOC cap.
//!
//! What: [`TrustyToolsConfig`] is the YAML-deserialised settings struct
//! (`workspace_root_template`, `auto_resume`, `default_model`), loaded via
//! [`TrustyToolsConfig::load`] (delegates to `trusty_common::crate_config`).
//! [`workspace_root`] resolves the absolute root for managed-session workspaces with
//! precedence **`TRUSTY_MPM_WORKSPACE_ROOT` env > config template > built-in default
//! (`~/trusty-mpm-projects`)**, expanding a leading `~`. [`workspace_subpath`] joins
//! the `<owner>/<repo>` identity onto that root.
//!
//! Test: `default_template_is_trusty_mpm_projects`, `env_overrides_config_and_default`,
//! `config_template_used_when_no_env`, `tilde_expansion`, `subpath_nests_owner_repo`.

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use trusty_common::github_path::GithubPath;

/// Untracked/secret file sync config shape + resolution (#2196), split into
/// its own module to keep this file under the 500-SLOC production cap. See
/// that module's doc for the full rationale.
pub mod untracked_sync;
pub use untracked_sync::{
    DEFAULT_UNTRACKED_SYNC_PATTERNS, ResolvedUntrackedSync, UntrackedSyncConfig,
    resolve_untracked_sync,
};

/// Crate name used as the `~/.trusty-tools/<crate>/` directory segment.
///
/// Why: the cross-crate convention keys each crate's config dir by its crate name;
/// a constant keeps trusty-mpm's segment from drifting.
/// What: `"trusty-mpm"`.
/// Test: `config_dir_is_trusty_mpm` indirectly via `crate_config` path tests.
pub const CRATE_NAME: &str = "trusty-mpm";

/// Sub-directory of `~/.trusty-tools/trusty-mpm/` that holds the shared,
/// tm-owned `CLAUDE_CONFIG_DIR` for every DAEMON-managed session (DOC-34).
///
/// Why: managed sessions must NOT read the target project's committed `.claude/`
/// (which ships a partial/broken agent roster and shadows the framework set,
/// #1996). Pointing the launched `claude` at a tm-owned config home under the
/// shared `~/.trusty-tools` base — the same base the #1220 crate-config
/// convention already uses — segregates the framework agents/skills/hooks/mcp
/// from whatever the project happens to commit. Naming the segment once keeps
/// the accessor and any future migration in agreement.
/// What: `"claude-config"`, joined onto `~/.trusty-tools/trusty-mpm/`.
/// Test: `managed_claude_config_dir_nests_under_trusty_tools`.
pub const MANAGED_CLAUDE_CONFIG_SUBDIR: &str = "claude-config";

/// Built-in default workspace-root directory name under `$HOME` (#1220).
///
/// Why: #1220 fixes the new default at `~/trusty-mpm-projects/`. Naming it once
/// keeps the resolver and the migration scan in agreement.
/// What: `"trusty-mpm-projects"`.
/// Test: `default_template_is_trusty_mpm_projects`.
pub const DEFAULT_WORKSPACE_DIR: &str = "trusty-mpm-projects";

/// Environment variable that overrides the resolved workspace root.
///
/// Why: operators (and tests) need an escape hatch that wins over the config file,
/// matching the pre-#1220 behaviour where this env var alone selected the root.
/// What: `"TRUSTY_MPM_WORKSPACE_ROOT"`.
/// Test: `env_overrides_config_and_default`.
pub const WORKSPACE_ROOT_ENV: &str = "TRUSTY_MPM_WORKSPACE_ROOT";

/// trusty-mpm's slice of the `~/.trusty-tools/<crate>/config.yaml` convention.
///
/// Why: gives operators a single declarative file for the settings #1220 calls out
/// — the workspace-root template, the auto-resume default, and the default model —
/// instead of relying solely on env vars or the legacy `~/.trusty-mpm/config.toml`
/// (which stays for its existing agent/model sections; this is the NEW, additive
/// YAML surface).
/// What: every field is optional so an absent file or absent key falls back to the
/// built-in default. `workspace_root_template` may contain a leading `~`.
/// Test: `config_template_used_when_no_env`, the `crate_config` round-trip tests.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TrustyToolsConfig {
    /// Template directory for managed-session workspace roots.
    ///
    /// `None` → the built-in default `~/trusty-mpm-projects`. A leading `~` is
    /// expanded to the home directory. Sessions nest as
    /// `<this>/<owner>/<repo>/<session-id>/`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_root_template: Option<String>,

    /// Default supervisor auto-resume preference surfaced in the console Config UI.
    ///
    /// `None` → unset (the supervisor's own default / persisted `auto_resume` file
    /// wins). This field lets the convention express the preference declaratively.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_resume: Option<bool>,

    /// Default model id (or tier alias) for launched sessions.
    ///
    /// `None` → fall back to the existing `~/.trusty-mpm/config.toml` model
    /// resolution. Present here so the console Config UI can edit it via the
    /// #1220 convention without touching the legacy TOML.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_model: Option<String>,

    /// `tm watch` defaults (the `watch:` YAML section).
    ///
    /// `None` → no configured defaults; the watch CLI flags supply their own
    /// built-in defaults. Present so an operator can pin a board's repo, routing
    /// label, and poll interval declaratively instead of typing them every run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub watch: Option<WatchConfig>,

    /// Per-project GitHub identity binding (the `github:` YAML section, #1265).
    ///
    /// `None` → no binding; every `gh` call inherits the ambient gh identity
    /// (current behaviour, no regression). When present, the resolved overrides
    /// are applied to every `gh` subprocess `tm` spawns for the active project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub github: Option<GithubConfig>,

    /// Statically-declared projects for the project registry (#1519 MR-1).
    ///
    /// `None` / absent → no static projects; the registry starts empty and is
    /// populated by MCP `project_register` calls and boot auto-registration from
    /// session history. When present, each entry is upserted into the registry
    /// at daemon startup, so an operator can declare frequently-used repos once
    /// in config rather than registering them via MCP on every restart.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub projects: Vec<ProjectConfig>,

    /// Daemon-level safety toggles (the `daemon:` YAML section, #1836).
    ///
    /// `None` → every toggle defaults to its safe value (MCP-initiated spawning
    /// stays disabled).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daemon: Option<DaemonConfig>,

    /// Global allowlisted untracked/secret file sync settings (the
    /// `untracked_sync:` YAML section, #2196).
    ///
    /// `None` → the built-in default applies: sync is ENABLED with the
    /// built-in `.env*` pattern set (see [`resolve_untracked_sync`]). A
    /// per-project `untracked_sync` override (on [`ProjectConfig`]) takes
    /// precedence over this global section for that project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub untracked_sync: Option<UntrackedSyncConfig>,

    /// Managed-tmux scrollback + mouse ergonomics (the `tmux:` YAML section,
    /// #2398).
    ///
    /// `None` → the built-in defaults apply: a 100,000-line `history-limit`
    /// and `mouse on`. See [`resolve_tmux_options`] for the full precedence
    /// and [`TmuxConfig`] for the field-level docs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tmux: Option<TmuxConfig>,
}

/// The `daemon:` section of `~/.trusty-tools/trusty-mpm/config.yaml` (#1836).
///
/// Why: the ARIA incident showed that an MCP-triggered `session_new` call can
/// silently provision real infrastructure (clone + worktree + tmux + harness)
/// for any repo an LLM caller names, with no operator confirmation. The fix is
/// an explicit, declarative opt-in an operator sets once — rather than a
/// per-call flag a careless/compromised caller could always supply.
/// What: currently one toggle, `allow_mcp_spawn`; resolution precedence (env >
/// config > safe default) lives in
/// [`crate::daemon::managed_routes::mcp_spawn_gate::mcp_spawn_enabled`], not
/// here — this is purely the on-disk shape.
/// Test: `daemon_config_yaml_round_trip`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaemonConfig {
    /// Whether MCP-initiated session spawns (`session_new` and friends) are
    /// permitted to provision new infrastructure.
    ///
    /// `None`/`Some(false)` → disabled (the safe default, #1836): an MCP
    /// caller's `session_new` is refused before any workspace is touched.
    /// `Some(true)` → opts in to MCP-initiated spawning (still subject to the
    /// #1837 registry allowlist gate). The `tm` CLI's own spawn path (`tm
    /// launch`/`tm connect`/`tm ticket`) is NEVER gated by this flag — it
    /// always spawns.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allow_mcp_spawn: Option<bool>,
}

/// Built-in default tmux `history-limit`/`mouse` (#2398), now the single
/// shared source of truth in `trusty_common::tmux` (#3004) so
/// trusty-agents' independent tmux implementation uses the identical
/// defaults. Re-exported here so every existing reference to
/// `DEFAULT_TMUX_HISTORY_LIMIT`/`DEFAULT_TMUX_MOUSE` in this module keeps
/// compiling unchanged.
/// Test: `tmux_options_default_when_no_config`.
pub use trusty_common::tmux::{DEFAULT_TMUX_HISTORY_LIMIT, DEFAULT_TMUX_MOUSE};

/// Minimum tmux `history-limit` accepted from config (#2398 QA finding).
///
/// Why: `history-limit 0` does NOT mean "unlimited" in tmux — it means "keep
/// no scrollback beyond the visible screen", the exact opposite of what an
/// operator setting `tmux.history_limit: 0` almost certainly intended (this
/// is a common mental-model mismatch with tools where `0` conventionally
/// means unbounded). Rather than silently honouring a self-defeating value
/// that reintroduces the unscrollable-session problem #2398 exists to fix, a
/// configured value below this floor is clamped UP to it.
/// What: `1_000`. Deliberately below [`DEFAULT_TMUX_HISTORY_LIMIT`] so an
/// operator who intentionally wants a SMALL (but still usable) scrollback
/// can still dial it down — only the pathological `0` (or another
/// near-zero value) is corrected.
/// Test: `tmux_options_clamps_zero_history_limit`,
/// `tmux_options_clamps_below_minimum`.
pub const MIN_TMUX_HISTORY_LIMIT: u32 = 1_000;

/// The `tmux:` section of `~/.trusty-tools/trusty-mpm/config.yaml` (#2398).
///
/// Why: managed sessions inherited tmux's tiny default `history-limit`
/// (2000 lines), making long PM sessions unscrollable. Both fields are
/// optional so an absent section (or a partly-filled one) falls back to the
/// built-in defaults — no regression for existing configs.
/// What: `history_limit` (scrollback lines retained per pane) and `mouse`
/// (server-wide wheel-scroll/copy-mode toggle). Resolution precedence
/// (config > built-in default, clamped to [`MIN_TMUX_HISTORY_LIMIT`]) lives
/// in [`resolve_tmux_options`], not here — this is purely the on-disk shape.
/// Test: `tmux_config_yaml_round_trip`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TmuxConfig {
    /// Scrollback lines retained per pane (tmux `history-limit`).
    ///
    /// `None` → [`DEFAULT_TMUX_HISTORY_LIMIT`]. A configured value below
    /// [`MIN_TMUX_HISTORY_LIMIT`] (including `0`, which tmux treats as "no
    /// scrollback", not "unlimited") is clamped up to it — see
    /// [`resolve_tmux_options`]. Only affects panes created AFTER this is
    /// applied — tmux captures `history-limit` into a pane's ring buffer at
    /// creation time, so an already-running pane's scrollback is never
    /// retroactively grown (a tmux limitation, not a trusty-mpm one).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub history_limit: Option<u32>,

    /// Whether mouse-wheel scrolling / copy-mode is enabled (tmux `mouse`).
    ///
    /// `None` → [`DEFAULT_TMUX_MOUSE`] (`true`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mouse: Option<bool>,
}

/// Resolved tmux scrollback + mouse ergonomics, after applying config
/// overrides on top of the built-in defaults (#2398).
///
/// Why: [`crate::daemon::tmux::TmuxDriver::apply_scrollback_options`] needs
/// concrete `u32`/`bool` values, not the optional on-disk shape; resolving
/// once here keeps the precedence logic in a single tested place.
/// What: `history_limit` and `mouse`, both always populated.
/// Test: `tmux_options_default_when_no_config`, `tmux_options_config_override`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedTmuxOptions {
    /// Scrollback lines retained per pane.
    pub history_limit: u32,
    /// Whether mouse-wheel scrolling / copy-mode is enabled.
    pub mouse: bool,
}

/// Resolve the effective tmux scrollback + mouse options for managed
/// sessions (#2398).
///
/// Why: gives every tmux-session-creating call site (normal spawn, resume/
/// restart, GUI spawn-mode, config-restart, and the CLI/TUI paths that create
/// sessions directly) a single answer, so a future config change cannot land
/// in one call site and be forgotten in another.
/// What: applies precedence **config `tmux.history_limit`/`tmux.mouse`
/// override > built-in default** ([`DEFAULT_TMUX_HISTORY_LIMIT`] /
/// [`DEFAULT_TMUX_MOUSE`]) for each field independently, then clamps
/// `history_limit` up to [`MIN_TMUX_HISTORY_LIMIT`] — a configured `0` (or
/// any other near-zero value) does NOT mean "unlimited" in tmux, so it is
/// corrected rather than honoured verbatim (#2398 QA finding).
/// Test: `tmux_options_default_when_no_config`, `tmux_options_config_override`,
/// `tmux_options_clamps_zero_history_limit`, `tmux_options_clamps_below_minimum`.
pub fn resolve_tmux_options(config: &TrustyToolsConfig) -> ResolvedTmuxOptions {
    let section = config.tmux.as_ref();
    let history_limit = section
        .and_then(|t| t.history_limit)
        .unwrap_or(DEFAULT_TMUX_HISTORY_LIMIT)
        .max(MIN_TMUX_HISTORY_LIMIT);
    ResolvedTmuxOptions {
        history_limit,
        mouse: section.and_then(|t| t.mouse).unwrap_or(DEFAULT_TMUX_MOUSE),
    }
}

/// The `github:` section of `~/.trusty-tools/trusty-mpm/config.yaml` (#1265).
///
/// Why: a host may have several GitHub identities (a personal account, a work
/// account, a bot, a GitHub Enterprise host) and `tm`'s many `gh` calls must use
/// the RIGHT one for the active project rather than whichever identity happens to
/// be ambient. Binding the identity per-project — alongside the `watch:` section
/// that already keys defaults to the active board — lets an operator pin
/// "this project's gh actions use THIS account/token/host" declaratively. Every
/// field is optional so an absent section (or a partly-filled one) cleanly falls
/// back to the ambient gh identity, guaranteeing no regression for existing setups.
/// What: optional `config_dir` (a private gh config home), `token_env` (the NAME
/// of an env var or keychain reference to resolve a token from at call time —
/// never a plaintext token), `account` (a gh username), and `host` (the gh host,
/// default `github.com`, also used for clone-URL synthesis). The resolution
/// precedence and the env overrides each field maps to live in the
/// `gh_identity` module, not here — this is purely the on-disk shape.
/// Test: round-trips via the `crate_config` tests; resolution in `gh_identity`;
/// the no-plaintext-token guarantee is asserted by `github_config_stores_only_env_name`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GithubConfig {
    /// A private gh config home directory → exported as `GH_CONFIG_DIR`.
    ///
    /// `None` → not set. When set, `gh` reads its auth/config from this directory
    /// instead of the user's default `~/.config/gh`, isolating the identity
    /// WITHOUT mutating any global gh state. This is the highest-precedence,
    /// least-invasive strategy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_dir: Option<PathBuf>,

    /// The NAME of an env var to resolve a token from at runtime → `GH_TOKEN`.
    ///
    /// `None` → not set. This is intentionally the env-var NAME, never a token:
    /// the plaintext secret never lives in the config file or this struct. At
    /// call time `std::env::var(<this name>)` resolves the actual token; if the
    /// named var is absent the strategy is skipped (precedence falls through).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_env: Option<String>,

    /// A gh username to select as the active account.
    ///
    /// `None` → not set. The least-precise strategy: `gh` has no universal
    /// per-invocation `--user` flag, so binding by account alone has caveats
    /// (documented in `gh_identity`). Prefer `config_dir` or `token_env`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub account: Option<String>,

    /// The gh host (e.g. `github.example.com` for GitHub Enterprise).
    ///
    /// `None` → the built-in default `github.com`. When set it is exported as
    /// `GH_HOST` (independent of the identity strategy) AND used to synthesise
    /// clone URLs as `https://<host>/<owner>/<repo>` (closes the GHE part of
    /// #1261).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub host: Option<String>,
}

/// Built-in default GitHub host used for clone-URL synthesis and `GH_HOST`.
///
/// Why: when no `github.host` is configured, clone URLs and gh fall back to the
/// public host. Naming it once keeps the resolver and the URL synthesiser aligned.
/// What: `"github.com"`.
/// Test: `default_host_is_github_com` in `gh_identity`.
pub const DEFAULT_GITHUB_HOST: &str = "github.com";

/// The `watch:` section of `~/.trusty-tools/trusty-mpm/config.yaml`.
///
/// Why: `tm watch poll|listen` routes board issues to managed sessions; an
/// operator running it repeatedly (or from cron) wants to pin the board repo,
/// the routing label, and the poll interval once rather than passing them on
/// every invocation. Every field is optional so an absent section or key falls
/// back to the CLI flag's built-in default; CLI flags always override config.
/// What: optional `repo` (`owner/repo`), `label` (routing label), and
/// `interval_secs` (listen-mode poll cadence). Resolution precedence lives in
/// the `watch::args` module, not here — this is purely the on-disk shape.
/// Test: round-trips via the `crate_config` tests; precedence in `watch::args`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WatchConfig {
    /// Default board repository as `owner/repo` (e.g. `bobmatnyc/trusty-tools`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repo: Option<String>,

    /// Default routing label; only issues carrying it are picked up.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,

    /// Default poll interval (seconds) for `listen` mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interval_secs: Option<u64>,
}

/// A single project entry declared in the `projects:` YAML section (#1519 MR-1).
///
/// Why: operators who use a fixed set of repos want to declare them once in
/// `config.yaml` so the project registry is pre-populated on daemon startup
/// without requiring MCP `project_register` calls. Every field beyond `name`
/// and `repo_url` is optional so a minimal two-line entry is valid.
/// What: on-disk shape for one project declaration. The daemon reads these at
/// startup and upserts them into the `ProjectRegistry` via `seed_from_config`.
/// Test: `registry_seed_from_config` in the `project::registry` module.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectConfig {
    /// Short name used as the registry key (e.g. `trusty-tools`).
    pub name: String,

    /// Full repository URL (e.g. `https://github.com/owner/trusty-tools`).
    pub repo_url: String,

    /// Default branch; falls back to `"main"` when absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_branch: Option<String>,

    /// Optional technology-stack hint (e.g. `"rust"`, `"python"`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stack_hint: Option<String>,

    /// Classification tags (e.g. `["backend", "production"]`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,

    /// Free-form description of the project.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Preferred GitHub account login for `gh` operations on this project (#2081).
    ///
    /// `None` → no preference declared; `gh_user` is left unset on the seeded
    /// [`crate::project::record::Project`], so `gh` calls for this project use
    /// whatever identity is ambient. See `Project::gh_user` for the full
    /// rationale and the non-mutating resolution mechanism
    /// ([`crate::core::gh_account::resolve_gh_account_env`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gh_user: Option<String>,

    /// GitHub account login pinned for this project's spawned sessions (#3025).
    /// `None` → no pinning (no regression). `Some(login)` → mirrored onto the
    /// seeded [`crate::project::record::Project::gh_account`] by
    /// `seed_from_config`; resolved into `GH_TOKEN`/`GH_USER` spawn-env
    /// overrides via [`crate::core::gh_account::resolve_gh_account_env`].
    /// Test: `project_config_gh_user_yaml_round_trip` (extended).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub gh_account: Option<String>,

    /// Per-project `gh`-CLI identity binding (#2184), overriding the global
    /// `github:` section for this project only.
    ///
    /// Why: #1265's `github:` section is a single global binding, but a host
    /// working on several projects may need a DIFFERENT `gh` identity per
    /// project (e.g. a personal account for an OSS repo, a work account for a
    /// client repo). This is a SEPARATE concern from `gh_user` above: `gh_user`
    /// only documents a preferred login for the non-mutating
    /// `ensure_gh_account_for_project` enforcement path (#2081), while `github`
    /// carries the full `config_dir`/`token_env`/`account`/`host` binding that
    /// [`crate::core::gh_identity::resolve_gh_env`] resolves into concrete env
    /// overrides for every `gh` subprocess `tm` spawns for this project.
    /// What: `None` → this project has no override; resolution falls back to
    /// the global `github:` section, then to the ambient gh identity (no
    /// regression). `Some(cfg)` → `cfg` is resolved in place of the global
    /// section for every `gh` call scoped to this project. Mirrored onto the
    /// seeded [`crate::project::record::Project::github`] by `seed_from_config`.
    /// Test: `project_config_github_and_commit_identity_yaml_round_trip`;
    /// resolution precedence in `core::gh_identity`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub github: Option<GithubConfig>,

    /// Preferred git commit author name for commits made on behalf of this
    /// project (#2184).
    ///
    /// Why: `tm`'s managed/provisioner git operations previously never set a
    /// commit identity, inheriting whatever `user.name` happened to be
    /// globally configured (or none, causing a hard commit failure). A
    /// per-project override lets an operator pin the right author for
    /// projects that require a specific bot/service identity, independent of
    /// the `gh`-CLI identity above (commit authorship and `gh` API auth are
    /// distinct git/GitHub concerns).
    /// What: `None` → no override; git uses whatever `user.name` is already
    /// configured (no regression). `Some(name)` → applied as `-c
    /// user.name=<name>` on every git invocation the provisioner makes for
    /// this project. Mirrored onto
    /// [`crate::project::record::Project::commit_name`] by `seed_from_config`.
    /// Test: `project_config_github_and_commit_identity_yaml_round_trip`;
    /// applied via `core::git_identity::GitIdentity::commit_config_args`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commit_name: Option<String>,

    /// Preferred git commit author email for commits made on behalf of this
    /// project (#2184). See [`Self::commit_name`] for the full rationale;
    /// applied as `-c user.email=<email>` alongside it.
    /// Test: `project_config_github_and_commit_identity_yaml_round_trip`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commit_email: Option<String>,

    /// Per-project untracked/secret file sync override (#2196), overriding
    /// the global `untracked_sync:` section for this project only.
    ///
    /// `None` → no override; resolution falls through to the global section,
    /// then the built-in default. See [`resolve_untracked_sync`] for the
    /// full precedence chain.
    /// Test: `untracked_sync_config_yaml_round_trip`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub untracked_sync: Option<UntrackedSyncConfig>,

    /// Per-project "launch on main" opt-out (#3455), mirrored onto
    /// [`crate::project::record::Project::worktree`] by `seed_from_config`.
    ///
    /// `None`/`Some(true)` → default, no regression: this project's managed
    /// sessions each get their own `.worktrees/<session>` git worktree.
    /// `Some(false)` → sessions run directly in the resolved local checkout
    /// instead — no clone, no worktree, no dedicated branch. See
    /// [`crate::project::record::Project::worktree_enabled`] for the
    /// resolved default and `tm projects config <name> set worktree
    /// true|false` for the runtime-registry equivalent (the registry, not
    /// this static config, is what `spawn_managed_routed` actually consults
    /// at spawn time — this field only seeds it).
    /// Test: covered by `registry::seed_from_config` round-trip coverage.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worktree: Option<bool>,
}

impl TrustyToolsConfig {
    /// Load trusty-mpm's config from `~/.trusty-tools/trusty-mpm/config.yaml`.
    ///
    /// Why: the daemon and CLI read this once at startup; collapsing absent /
    /// home-unknown / malformed to defaults (with a logged warning for malformed)
    /// means a bad file never aborts startup.
    /// What: delegates to [`trusty_common::crate_config::load_or_default`] for
    /// [`CRATE_NAME`].
    /// Test: `config_template_used_when_no_env` (round-trips via `crate_config`).
    pub fn load() -> Self {
        trusty_common::crate_config::load_or_default::<Self>(CRATE_NAME)
    }
}

/// Resolve the shared tm-owned `CLAUDE_CONFIG_DIR` for daemon-managed sessions.
///
/// Why: the daemon managed-spawn path must launch `claude` with a
/// `CLAUDE_CONFIG_DIR` that supplies the framework agent roster, skills, hooks,
/// and MCP servers from a tm-controlled location — NOT from the target
/// project's committed `.claude/` and NOT from the operator's `~/.claude`
/// (DOC-34 / #1996). This accessor is the single source of truth for that path
/// so the provisioner and the spawn-command builder can never disagree.
/// What: `~/.trusty-tools/trusty-mpm/claude-config/`, delegating to
/// [`trusty_common::crate_config::crate_config_dir`] for the `~/.trusty-tools/<crate>`
/// base and joining [`MANAGED_CLAUDE_CONFIG_SUBDIR`]. Returns `None` only when
/// the home directory cannot be resolved (a stripped CI environment).
/// Test: `managed_claude_config_dir_nests_under_trusty_tools`.
pub fn managed_claude_config_dir() -> Option<PathBuf> {
    trusty_common::crate_config::crate_config_dir(CRATE_NAME)
        .map(|dir| dir.join(MANAGED_CLAUDE_CONFIG_SUBDIR))
}

/// Resolve the managed `CLAUDE_CONFIG_DIR` under an explicit base (hermetic).
///
/// Why: the production accessor calls `dirs::home_dir()`, which unit tests must
/// not depend on. Pointing `base` at a `tempfile::TempDir` keeps the layout
/// assertion hermetic and parallel-safe.
/// What: `<base>/.trusty-tools/trusty-mpm/claude-config/`.
/// Test: `managed_claude_config_dir_nests_under_trusty_tools`.
pub fn managed_claude_config_dir_at(base: &Path) -> PathBuf {
    trusty_common::crate_config::crate_config_dir_at(base, CRATE_NAME)
        .join(MANAGED_CLAUDE_CONFIG_SUBDIR)
}

/// Expand a leading `~` in a path template to the home directory.
///
/// Why: config templates and the built-in default are written home-relative
/// (`~/trusty-mpm-projects`); the resolver must turn them into absolute paths.
/// What: replaces a leading `~` (optionally `~/`) with `home`; other paths pass
/// through unchanged. Absolute paths and templates without `~` are returned as-is.
/// Test: `tilde_expansion`.
fn expand_tilde(template: &str, home: &Path) -> PathBuf {
    if let Some(rest) = template.strip_prefix("~/") {
        home.join(rest)
    } else if template == "~" {
        home.to_path_buf()
    } else {
        PathBuf::from(template)
    }
}

/// Resolve the absolute workspace root for managed sessions.
///
/// Why: the spawn path needs ONE answer for "where do session workspaces live?"
/// with #1220's new default and an env/config override, in a tested place so the
/// HTTP route and the MCP tool cannot diverge.
/// What: applies the precedence **`TRUSTY_MPM_WORKSPACE_ROOT` env > config
/// `workspace_root_template` > built-in `~/trusty-mpm-projects`**, expanding a
/// leading `~`. Falls back to `/tmp/trusty-mpm-projects` only when the home
/// directory is unresolvable AND nothing absolute was supplied.
/// Test: `default_template_is_trusty_mpm_projects`, `env_overrides_config_and_default`,
/// `config_template_used_when_no_env`.
pub fn workspace_root(config: &TrustyToolsConfig) -> PathBuf {
    let home = dirs::home_dir();

    // 1. Env override wins (back-compat with the pre-#1220 behaviour).
    if let Ok(raw) = std::env::var(WORKSPACE_ROOT_ENV) {
        let raw = raw.trim();
        if !raw.is_empty() {
            return match &home {
                Some(h) => expand_tilde(raw, h),
                None => PathBuf::from(raw),
            };
        }
    }

    // 2. Config template (from ~/.trusty-tools/trusty-mpm/config.yaml).
    if let Some(template) = config
        .workspace_root_template
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        return match &home {
            Some(h) => expand_tilde(template, h),
            None => PathBuf::from(template),
        };
    }

    // 3. Built-in default: ~/trusty-mpm-projects.
    match home {
        Some(h) => h.join(DEFAULT_WORKSPACE_DIR),
        None => PathBuf::from("/tmp").join(DEFAULT_WORKSPACE_DIR),
    }
}

/// Join a project's `<owner>/<repo>` identity onto the workspace root.
///
/// Why: #1220 nests sessions under `<root>/<owner>/<repo>/` so multiple sessions
/// on the same repo group together and the path mirrors the GitHub identity.
/// What: returns `<root>/<owner>/<repo>` for the given [`GithubPath`]. The session
/// id is appended by the provisioner, not here, so this stays the "project home".
/// Test: `subpath_nests_owner_repo`.
pub fn workspace_subpath(config: &TrustyToolsConfig, gh: &GithubPath) -> PathBuf {
    workspace_root(config).join(&gh.owner).join(&gh.repo)
}

/// Process-global lock serialising every test that mutates the workspace-root /
/// repos-root environment variables.
///
/// Why: `cargo test` runs the whole crate's tests in parallel threads sharing one
/// process env. Both this module's env tests AND
/// `crate::daemon::managed_routes::inproject`'s `TRUSTY_MPM_REPOS_ROOT` test mutate
/// `TRUSTY_MPM_WORKSPACE_ROOT` / `TRUSTY_MPM_REPOS_ROOT`; without a SHARED lock a
/// per-module mutex lets them race (one test's `remove_var` clobbers another's
/// `set_var`), causing flaky failures. Exposing ONE crate-wide lock guarantees
/// mutual exclusion across modules.
/// What: returns a guard over a single `static` mutex; poisoning is recovered so a
/// panicking test cannot deadlock the rest.
/// Test: used by the env-precedence tests here and in `inproject`.
#[cfg(test)]
pub(crate) fn env_test_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    LOCK.lock().unwrap_or_else(|e| e.into_inner())
}

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

    /// Serialise env mutation so the env-reading tests cannot race each other
    /// across the shared test process. Delegates to the crate-wide
    /// [`super::env_test_lock`] so env tests in OTHER modules are serialised too.
    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
        super::env_test_lock()
    }

    /// Why (DOC-34): the managed `CLAUDE_CONFIG_DIR` MUST resolve under the
    /// shared `~/.trusty-tools/trusty-mpm/` base (never `~/.trusty-mpm` or the
    /// project). Pinning the exact layout guards the segregation guarantee.
    /// Test: itself.
    #[test]
    fn managed_claude_config_dir_nests_under_trusty_tools() {
        let base = PathBuf::from("/home/bob");
        assert_eq!(
            managed_claude_config_dir_at(&base),
            PathBuf::from("/home/bob/.trusty-tools/trusty-mpm/claude-config")
        );
        // The production accessor, when home resolves, must agree with the
        // hermetic `_at` variant on the trailing `.trusty-tools/trusty-mpm/...`
        // segments regardless of the actual home directory.
        if let Some(dir) = managed_claude_config_dir() {
            assert!(
                dir.ends_with("trusty-mpm/claude-config"),
                "managed config dir must end with trusty-mpm/claude-config, got {}",
                dir.display()
            );
            assert!(
                dir.to_string_lossy().contains(".trusty-tools"),
                "managed config dir must live under .trusty-tools, got {}",
                dir.display()
            );
        }
    }

    /// Why: the built-in default (no env, no config) must be the #1220 path.
    /// Test: itself.
    #[test]
    fn default_template_is_trusty_mpm_projects() {
        let _g = env_lock();
        // SAFETY: guarded by env_lock; restored below.
        unsafe { std::env::remove_var(WORKSPACE_ROOT_ENV) };
        let root = workspace_root(&TrustyToolsConfig::default());
        assert!(
            root.ends_with(DEFAULT_WORKSPACE_DIR),
            "expected …/{DEFAULT_WORKSPACE_DIR}, got {}",
            root.display()
        );
    }

    /// Why: the env var must win over both the config template and the default.
    /// Test: itself.
    #[test]
    fn env_overrides_config_and_default() {
        let _g = env_lock();
        let cfg = TrustyToolsConfig {
            workspace_root_template: Some("~/from-config".into()),
            ..Default::default()
        };
        // SAFETY: guarded by env_lock; removed at end.
        unsafe { std::env::set_var(WORKSPACE_ROOT_ENV, "/explicit/env/root") };
        let root = workspace_root(&cfg);
        unsafe { std::env::remove_var(WORKSPACE_ROOT_ENV) };
        assert_eq!(root, PathBuf::from("/explicit/env/root"));
    }

    /// Why: with no env override, the config template must be used (and `~`
    /// expanded), beating the built-in default.
    /// Test: itself.
    #[test]
    fn config_template_used_when_no_env() {
        let _g = env_lock();
        unsafe { std::env::remove_var(WORKSPACE_ROOT_ENV) };
        let cfg = TrustyToolsConfig {
            workspace_root_template: Some("/custom/projects".into()),
            ..Default::default()
        };
        let root = workspace_root(&cfg);
        assert_eq!(root, PathBuf::from("/custom/projects"));
    }

    /// Why: a leading `~` in a template must expand to the home directory.
    /// Test: itself.
    #[test]
    fn tilde_expansion() {
        let home = PathBuf::from("/home/bob");
        assert_eq!(
            expand_tilde("~/trusty-mpm-projects", &home),
            PathBuf::from("/home/bob/trusty-mpm-projects")
        );
        assert_eq!(expand_tilde("~", &home), home);
        assert_eq!(expand_tilde("/abs/path", &home), PathBuf::from("/abs/path"));
    }

    /// Why: the `github:` section must round-trip through YAML so an operator's
    /// declarative binding survives load/save unchanged (and absent fields stay
    /// absent rather than serialising as nulls).
    /// Test: itself.
    #[test]
    fn github_config_yaml_round_trip() {
        let cfg = TrustyToolsConfig {
            github: Some(GithubConfig {
                config_dir: Some(PathBuf::from("/home/bob/.config/gh-work")),
                token_env: Some("WORK_GH_TOKEN".into()),
                account: Some("bob-work".into()),
                host: Some("github.example.com".into()),
            }),
            ..Default::default()
        };
        let yaml = serde_yaml::to_string(&cfg).expect("serialise");
        let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
        assert_eq!(cfg, back);
        // Absent top-level fields must not appear in the YAML.
        assert!(!yaml.contains("workspace_root_template"), "yaml: {yaml}");
        assert!(yaml.contains("github:"), "yaml: {yaml}");
    }

    /// Why: the #1265 no-plaintext-token guarantee — the config stores only the
    /// NAME of the env var, never the secret value. A reviewer must be able to
    /// assert this invariant mechanically.
    /// Test: itself.
    #[test]
    fn github_config_stores_only_env_name() {
        let cfg = GithubConfig {
            token_env: Some("MY_GH_TOKEN".into()),
            ..Default::default()
        };
        // The struct field is named `token_env` and holds the var NAME; there is
        // no field that could hold a token value. Serialised form proves it.
        let yaml = serde_yaml::to_string(&cfg).expect("serialise");
        assert!(yaml.contains("token_env"), "yaml: {yaml}");
        assert!(yaml.contains("MY_GH_TOKEN"), "yaml: {yaml}");
        assert!(
            !yaml.contains("token:"),
            "must not have a bare token field: {yaml}"
        );
    }

    /// Why (#2081): a `projects:` entry's `gh_user` preference must round-trip
    /// through YAML, and an absent `gh_user` must not serialise (matching every
    /// other optional field on `ProjectConfig`) so existing configs deserialise
    /// unchanged.
    /// Test: itself.
    #[test]
    fn project_config_gh_user_yaml_round_trip() {
        let cfg = TrustyToolsConfig {
            projects: vec![ProjectConfig {
                name: "trusty-tools".into(),
                repo_url: "https://github.com/bobmatnyc/trusty-tools".into(),
                default_branch: Some("main".into()),
                stack_hint: None,
                tags: None,
                description: None,
                gh_user: Some("bobmatnyc".into()),
                gh_account: Some("bobmatnyc".into()),
                github: None,
                commit_name: None,
                commit_email: None,
                untracked_sync: None,
                worktree: None,
            }],
            ..Default::default()
        };
        let yaml = serde_yaml::to_string(&cfg).expect("serialise");
        assert!(yaml.contains("gh_user"), "yaml: {yaml}");
        assert!(yaml.contains("gh_account"), "yaml: {yaml}");
        let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
        assert_eq!(cfg, back);

        // Absent gh_user/gh_account must not serialise.
        let no_pref = TrustyToolsConfig {
            projects: vec![ProjectConfig {
                name: "other".into(),
                repo_url: "https://github.com/o/other".into(),
                default_branch: None,
                stack_hint: None,
                tags: None,
                description: None,
                gh_user: None,
                gh_account: None,
                github: None,
                commit_name: None,
                commit_email: None,
                untracked_sync: None,
                worktree: None,
            }],
            ..Default::default()
        };
        let yaml_no_pref = serde_yaml::to_string(&no_pref).expect("serialise");
        assert!(!yaml_no_pref.contains("gh_user"), "yaml: {yaml_no_pref}");
        assert!(!yaml_no_pref.contains("gh_account"), "yaml: {yaml_no_pref}");
    }

    /// Why (#2184): a project's per-project `github:` binding and commit
    /// identity (`commit_name`/`commit_email`) must round-trip through YAML,
    /// and absent fields must not serialise — matching every other optional
    /// `ProjectConfig` field so existing configs deserialise unchanged.
    /// Test: itself.
    #[test]
    fn project_config_github_and_commit_identity_yaml_round_trip() {
        let cfg = TrustyToolsConfig {
            projects: vec![ProjectConfig {
                name: "work-repo".into(),
                repo_url: "https://github.com/acme/work-repo".into(),
                default_branch: None,
                stack_hint: None,
                tags: None,
                description: None,
                gh_user: None,
                gh_account: None,
                github: Some(GithubConfig {
                    config_dir: Some(PathBuf::from("/home/bob/.config/gh-work")),
                    token_env: None,
                    account: Some("bob-work".into()),
                    host: None,
                }),
                commit_name: Some("Bob (work bot)".into()),
                commit_email: Some("bob@acme.example.com".into()),
                untracked_sync: None,
                worktree: None,
            }],
            ..Default::default()
        };
        let yaml = serde_yaml::to_string(&cfg).expect("serialise");
        assert!(yaml.contains("github:"), "yaml: {yaml}");
        assert!(yaml.contains("commit_name"), "yaml: {yaml}");
        assert!(yaml.contains("commit_email"), "yaml: {yaml}");
        let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
        assert_eq!(cfg, back);

        // Absent per-project github/commit fields must not serialise.
        let minimal = TrustyToolsConfig {
            projects: vec![ProjectConfig {
                name: "minimal".into(),
                repo_url: "https://github.com/o/minimal".into(),
                default_branch: None,
                stack_hint: None,
                tags: None,
                description: None,
                gh_user: None,
                gh_account: None,
                github: None,
                commit_name: None,
                commit_email: None,
                untracked_sync: None,
                worktree: None,
            }],
            ..Default::default()
        };
        let yaml_minimal = serde_yaml::to_string(&minimal).expect("serialise");
        assert!(!yaml_minimal.contains("github:"), "yaml: {yaml_minimal}");
        assert!(
            !yaml_minimal.contains("commit_name"),
            "yaml: {yaml_minimal}"
        );
        assert!(
            !yaml_minimal.contains("commit_email"),
            "yaml: {yaml_minimal}"
        );
    }

    /// Why: the `daemon:` section (#1836) must round-trip through YAML, and an
    /// absent section must not serialise at all (matching every other optional
    /// top-level section).
    /// Test: itself.
    #[test]
    fn daemon_config_yaml_round_trip() {
        let cfg = TrustyToolsConfig {
            daemon: Some(DaemonConfig {
                allow_mcp_spawn: Some(true),
            }),
            ..Default::default()
        };
        let yaml = serde_yaml::to_string(&cfg).expect("serialise");
        let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
        assert_eq!(cfg, back);
        assert!(yaml.contains("allow_mcp_spawn"), "yaml: {yaml}");

        // Absent daemon section must not serialise.
        let empty = TrustyToolsConfig::default();
        let yaml_empty = serde_yaml::to_string(&empty).expect("serialise");
        assert!(!yaml_empty.contains("daemon"), "yaml: {yaml_empty}");
    }

    /// Why: the `tmux:` section (#2398) must round-trip through YAML, and an
    /// absent section must not serialise at all (matching every other
    /// optional top-level section).
    /// Test: itself.
    #[test]
    fn tmux_config_yaml_round_trip() {
        let cfg = TrustyToolsConfig {
            tmux: Some(TmuxConfig {
                history_limit: Some(50_000),
                mouse: Some(false),
            }),
            ..Default::default()
        };
        let yaml = serde_yaml::to_string(&cfg).expect("serialise");
        let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
        assert_eq!(cfg, back);
        assert!(yaml.contains("history_limit"), "yaml: {yaml}");
        assert!(yaml.contains("mouse"), "yaml: {yaml}");

        // Absent tmux section must not serialise.
        let empty = TrustyToolsConfig::default();
        let yaml_empty = serde_yaml::to_string(&empty).expect("serialise");
        assert!(!yaml_empty.contains("tmux"), "yaml: {yaml_empty}");
    }

    /// Why: with no `tmux:` section at all, resolution must fall back to the
    /// built-in defaults (100,000-line history-limit, mouse on).
    /// Test: itself.
    #[test]
    fn tmux_options_default_when_no_config() {
        let opts = resolve_tmux_options(&TrustyToolsConfig::default());
        assert_eq!(opts.history_limit, DEFAULT_TMUX_HISTORY_LIMIT);
        assert_eq!(opts.mouse, DEFAULT_TMUX_MOUSE);
    }

    /// Why: an explicit `tmux:` section must override the built-in defaults,
    /// field-by-field (a partial section still falls back per-field).
    /// Test: itself.
    #[test]
    fn tmux_options_config_override() {
        let cfg = TrustyToolsConfig {
            tmux: Some(TmuxConfig {
                history_limit: Some(250_000),
                mouse: Some(false),
            }),
            ..Default::default()
        };
        let opts = resolve_tmux_options(&cfg);
        assert_eq!(opts.history_limit, 250_000);
        assert!(!opts.mouse);

        // Partial override: only history_limit set, mouse falls back to default.
        let partial = TrustyToolsConfig {
            tmux: Some(TmuxConfig {
                history_limit: Some(10_000),
                mouse: None,
            }),
            ..Default::default()
        };
        let opts = resolve_tmux_options(&partial);
        assert_eq!(opts.history_limit, 10_000);
        assert_eq!(opts.mouse, DEFAULT_TMUX_MOUSE);
    }

    /// Why (#2398 QA finding): `history-limit 0` means "no scrollback" in
    /// tmux, not "unlimited" — a configured `0` must be clamped up to
    /// [`MIN_TMUX_HISTORY_LIMIT`] rather than honoured verbatim, which would
    /// silently reintroduce the unscrollable-session problem this feature
    /// exists to fix.
    /// Test: itself.
    #[test]
    fn tmux_options_clamps_zero_history_limit() {
        let cfg = TrustyToolsConfig {
            tmux: Some(TmuxConfig {
                history_limit: Some(0),
                mouse: None,
            }),
            ..Default::default()
        };
        let opts = resolve_tmux_options(&cfg);
        assert_eq!(opts.history_limit, MIN_TMUX_HISTORY_LIMIT);
    }

    /// Why: any near-zero configured value below the floor is clamped, not
    /// just the literal `0` case.
    /// Test: itself.
    #[test]
    fn tmux_options_clamps_below_minimum() {
        let cfg = TrustyToolsConfig {
            tmux: Some(TmuxConfig {
                history_limit: Some(42),
                mouse: None,
            }),
            ..Default::default()
        };
        let opts = resolve_tmux_options(&cfg);
        assert_eq!(opts.history_limit, MIN_TMUX_HISTORY_LIMIT);

        // A value AT the floor is left untouched (not bumped further).
        let at_floor = TrustyToolsConfig {
            tmux: Some(TmuxConfig {
                history_limit: Some(MIN_TMUX_HISTORY_LIMIT),
                mouse: None,
            }),
            ..Default::default()
        };
        assert_eq!(
            resolve_tmux_options(&at_floor).history_limit,
            MIN_TMUX_HISTORY_LIMIT
        );
    }

    /// Why: the project subpath must nest `<owner>/<repo>` under the root in that
    /// order (the #1220 layout the migration scan also relies on).
    /// Test: itself.
    #[test]
    fn subpath_nests_owner_repo() {
        let _g = env_lock();
        unsafe { std::env::remove_var(WORKSPACE_ROOT_ENV) };
        let cfg = TrustyToolsConfig {
            workspace_root_template: Some("/projects".into()),
            ..Default::default()
        };
        let gh = GithubPath {
            owner: "bobmatnyc".into(),
            repo: "trusty-tools".into(),
        };
        assert_eq!(
            workspace_subpath(&cfg, &gh),
            PathBuf::from("/projects/bobmatnyc/trusty-tools")
        );
    }

    // untracked_sync (#2196) resolution + YAML round-trip tests live in
    // `untracked_sync::tests` (split out to keep this file under the
    // 500-SLOC cap; see that module's doc).
}