trusty-mpm 1.8.2

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

use crate::session_manager::worktree_keep_list::KeepList;

/// 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,
};

/// The `agents:` group and its first occupant `agents.ticketing` (#6918),
/// split out for the same SLOC reason as `untracked_sync`. See that module's
/// doc for why two of its fields exist only to be refused.
pub mod agents;
pub use agents::{
    AgentsConfig, ConfiguredLabel, DEFAULT_ASSIGNEE, LabelRole, REQUIRED_PR_LINK_KEYWORD,
    ResolvedTicketing, TICKETING_BLOCK_TEMPLATE, TicketingConfig, TicketingConfigError,
    resolve_ticketing,
};

/// Cloud log-drain config shape + resolution (#6535), split out for the same
/// SLOC reason as `untracked_sync`. See that module's doc for why a malformed
/// section is an error rather than a silent fall-back to defaults.
pub mod log_drain;
pub use log_drain::{
    DEFAULT_INTERVAL_SECS as LOG_DRAIN_DEFAULT_INTERVAL_SECS, DisabledSource, LogDrainConfig,
    LogDrainConfigError, LogDrainSetting, LogDrainSourceConfig, ResolvedDrainDestination,
    ResolvedLogDrain, STATE_SUBDIR as LOG_DRAIN_STATE_SUBDIR, resolve_log_drain,
};

/// 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";

// #5203: the layout constants live with the resolver in trusty-common so the
// crates that cannot depend on trusty-mpm read the same values. Re-exported
// here (rather than redeclared) to keep every existing `trusty_tools_config::`
// spelling working.
pub use trusty_common::workspace_layout::{
    DEFAULT_WORKSPACE_DIR, DEFAULT_WORKTREES_DIRNAME, WORKSPACE_ROOT_ENV, WORKTREES_DIRNAME_ENV,
};

/// 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)]
// #5204: `#[non_exhaustive]` so adding a settings field stays non-breaking.
// Without it, every new `pub` field on this all-public struct is a
// `constructible_struct_adds_field` major under cargo-semver-checks — the
// #4088 class of break, which a workspace `cargo check` cannot catch because
// the root path override pairs local source with local dependency.
#[non_exhaustive]
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>,

    /// Directory name under a project checkout that holds session worktrees.
    ///
    /// `None` → the built-in default `.worktrees`. Must be a single path
    /// component; anything else is rejected back to the default rather than
    /// allowed to escape the checkout.
    ///
    /// #5204: host-level rather than project-level for the same structural
    /// reason `workspace_root` is (see `core::project_config`'s module doc) —
    /// the detection sites in trusty-search and trusty-memory are handed an
    /// opaque path and must identify the worktree base BEFORE they could locate
    /// the project whose config would answer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worktrees_dirname: 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 10,000-line `history-limit`,
    /// `mouse on`, and `alternate-screen off` (#5364). 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>,

    /// Cloud log drain (the `log_drain:` YAML section, #6535).
    ///
    /// `None` → the drain is disabled and the daemon spawns no scheduler; that
    /// is the default and requires no config file. When present, the section is
    /// VALIDATED even while `enabled: false` — see
    /// [`resolve_log_drain`] for why a malformed section is a hard error.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub log_drain: Option<LogDrainConfig>,

    /// Per-agent settings (the `agents:` YAML section, #6918).
    ///
    /// `None` → every bundled agent runs on its built-in defaults, which for
    /// `agents.ticketing` is byte-for-byte the #6914 behaviour. See
    /// [`resolve_ticketing`] for the resolution and the two rules a block
    /// cannot relax.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agents: Option<AgentsConfig>,

    /// Disk-dashboard settings (the `disk:` YAML section, #6927).
    ///
    /// `None` → an EMPTY keep-list, which is a no-op gate: nothing is kept and
    /// the classifier behaves exactly as it did before #6927. Nothing is
    /// hard-coded here — a keep-list is only ever what the operator wrote.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disk: Option<DiskConfig>,

    /// Startup-context budget (the `startup_context:` YAML section, #7424).
    ///
    /// `None` → the shipped defaults: the `tm doctor` check is on, warns at
    /// 50,000 tokens, and samples the project's ten newest sessions. The
    /// section type and its resolver live in
    /// [`crate::core::startup_context`] beside the policy they configure, the
    /// same arrangement `log_drain` and `agents` use.
    ///
    /// ```yaml
    /// startup_context:
    ///   ceiling_tokens: 50000
    ///   sessions: 10
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub startup_context: Option<crate::core::startup_context::StartupContextConfig>,

    /// Machine-level Rust build settings (the `build:` YAML section, #6868).
    ///
    /// `None` → the shipped defaults: a shared cargo target directory at
    /// `~/.trusty-tools/cargo-target/<owner>/<repo>` derived from the project's
    /// `origin` remote, half the host's cores (minimum 2) of build jobs, and no
    /// sccache. The `rust_build_env` doctor row never fails on an absent
    /// section. The section type and its resolver live in
    /// [`crate::core::build_env`] beside the policy they configure, the same
    /// arrangement `log_drain`, `agents` and `startup_context` use.
    ///
    /// ```yaml
    /// build:
    ///   cargo_target_dir: ~/.trusty-tools/cargo-target/bobmatnyc/trusty-tools
    ///   build_jobs: 8
    ///   sccache: false
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<crate::core::build_env::BuildConfig>,
}

/// The `disk:` section of `~/.trusty-tools/trusty-mpm/config.yaml` (#6927).
///
/// Why: DOC-73 §16.2 makes the owner keep-list a first-class gate in
/// `worktree_reclaim::classify`, and a gate whose input is an operator
/// decision needs a declarative home. This is that home: one list, in the file
/// the console Config tab already reads and writes.
/// What: `keep_list` holds directories and globs. A directory entry keeps that
/// directory and everything under it, so naming a workspace keeps every
/// worktree inside it; an entry containing `*?[]{` compiles as a glob. See
/// [`crate::session_manager::worktree_keep_list::KeepList`] for the matching
/// rules and for what happens to a pattern that will not compile.
///
/// ```yaml
/// disk:
///   keep_list:
///     - ~/work/hotstats
///     - "**/scratch-*"
///   max_usage_pct: 90
/// ```
///
/// Test: `disk_config_yaml_round_trip`, `disk_keep_list_defaults_to_empty`,
/// `max_usage_pct_round_trips`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DiskConfig {
    /// Worktree paths and glob patterns that are never proposed for reclaim.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keep_list: Vec<String>,

    /// Disk-usage percentage at or above which no new worktree is created
    /// (#7497).
    ///
    /// `None` → the built-in
    /// [`DEFAULT_MAX_USAGE_PCT`](crate::core::disk_usage_guard::DEFAULT_MAX_USAGE_PCT).
    /// A value outside `1..=100` is REJECTED rather than applied — see
    /// [`resolve_max_usage_pct`](crate::core::disk_usage_guard::resolve_max_usage_pct)
    /// for why a nonsense threshold must not become a permissive one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_usage_pct: Option<u8>,
}

/// 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) and
/// `alternate-screen` (#5151), 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 in this module keeps compiling unchanged.
/// Test: `tmux_options_default_when_no_config`.
pub use trusty_common::tmux::{
    DEFAULT_TMUX_ALTERNATE_SCREEN, 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,
/// extended by #5151).
///
/// Why: managed sessions inherited tmux's tiny default `history-limit`
/// (2000 lines), making long PM sessions unscrollable. Every field is
/// 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), `mouse`
/// (server-wide wheel-scroll/copy-mode toggle), and `alternate_screen`
/// (whether panes may use the terminal alternate screen buffer). 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`.
///
/// `#[non_exhaustive]` (#5151): this section is designed to grow — it went from
/// two fields to three when `alternate_screen` landed, and adding a `pub` field
/// to an exhaustively-constructible struct is a SemVer break, because external
/// code can no longer use a struct literal. Marking it non-exhaustive makes
/// every future field addition non-breaking by construction. Downstream code
/// builds one via [`Default`] plus field assignment, or gets one from
/// [`TrustyToolsConfig::load`]; reading fields is unaffected. Same treatment
/// `trusty-common`'s `IndexOptions` got in #5065.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
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>,

    /// Whether programs in a pane may use the terminal alternate screen
    /// buffer (tmux `alternate-screen`). `None` →
    /// [`DEFAULT_TMUX_ALTERNATE_SCREEN`], which is `false` since #5364 — set
    /// `alternate_screen: true` to restore tmux's factory behaviour.
    ///
    /// **Why the default is `false`.** A full-screen TUI (Claude Code
    /// included) draws into the alternate screen, and tmux discards that
    /// buffer instead of appending it to the pane's scrollback. That is why a
    /// `tm` session can hold tens of thousands of lines of `history-limit` and
    /// still show you nothing to scroll back through: the history is not
    /// missing, it was never written to the pane. `false` makes the TUI draw
    /// into the normal buffer, so its output lands in scrollback. #5151 added
    /// this knob but defaulted it to `true`, leaving the bug in place for
    /// anyone who never found it; #5364 flipped the default so a managed
    /// session scrolls out of the box.
    ///
    /// **What that costs — the accepted tradeoff.** The effect is
    /// server-wide, and every trusty-* managed session shares ONE tmux server,
    /// so this changes every pane on it, not just the ones running an agent.
    /// `vim`, `less`, `htop` and `man` all stop restoring the screen they
    /// covered: each leaves its final frame behind, smeared into the
    /// scrollback on exit, sometimes with redraw garbage from partial
    /// repaints. The repo owner accepted that in exchange for working
    /// scrollback (#5364). It is also not retroactive — anything already
    /// written while the alternate screen was up stays unrecoverable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alternate_screen: 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`, `mouse` and `alternate_screen`, all always
/// populated.
/// Test: `tmux_options_default_when_no_config`, `tmux_options_config_override`.
///
/// `#[non_exhaustive]` (#5151): tracks [`TmuxConfig`] field-for-field, so it
/// grows whenever that does — see its doc for why the attribute is here.
/// [`resolve_tmux_options`] is the only intended way to obtain one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResolvedTmuxOptions {
    /// Scrollback lines retained per pane.
    pub history_limit: u32,
    /// Whether mouse-wheel scrolling / copy-mode is enabled.
    pub mouse: bool,
    /// Whether panes may use the terminal alternate screen buffer (#5151).
    /// See [`TmuxConfig::alternate_screen`] for what turning it off costs.
    pub alternate_screen: 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 override > built-in default**
/// ([`DEFAULT_TMUX_HISTORY_LIMIT`] / [`DEFAULT_TMUX_MOUSE`] /
/// [`DEFAULT_TMUX_ALTERNATE_SCREEN`]) 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).
/// `alternate_screen` is NOT clamped or corrected: both values are legitimate,
/// so a configured value is honoured verbatim. Its default is `false` (#5364),
/// which is deliberately NOT tmux's factory value — see
/// [`TmuxConfig::alternate_screen`] for the scrollback it buys and the
/// screen-restore behaviour it gives up server-wide.
/// Test: `tmux_options_default_when_no_config`, `tmux_options_config_override`,
/// `tmux_options_clamps_zero_history_limit`, `tmux_options_clamps_below_minimum`,
/// `tmux_options_alternate_screen_defaults_off`,
/// `tmux_options_alternate_screen_config_override`.
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),
        // #5364: absent config now resolves to `off` so scrollback works
        // without the operator opting in; `true` restores tmux's factory value.
        alternate_screen: section
            .and_then(|t| t.alternate_screen)
            .unwrap_or(DEFAULT_TMUX_ALTERNATE_SCREEN),
    }
}

/// 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 {
        let cfg = trusty_common::crate_config::load_or_default::<Self>(CRATE_NAME);
        // #5207: the parse above is LENIENT and stays that way — see
        // `core::config_keys` for why `deny_unknown_fields` on this struct would
        // turn one typo into a whole-file discard. Report what it dropped.
        if let Some(path) = trusty_common::crate_config::crate_config_path(CRATE_NAME)
            && let Ok(raw) = std::fs::read_to_string(&path)
            && let Some(doc) = crate::core::config_keys::yaml_document(&raw)
        {
            crate::core::config_keys::report_unknown_keys(&path.display().to_string(), &doc, &cfg);
        }
        cfg
    }
}

/// 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)
}

/// 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: #5203 moved the precedence chain itself into
/// [`trusty_common::workspace_layout::resolve_workspace_root`] so `trusty-code`
/// — which cannot depend on this crate — resolves the identical value. This
/// function is now the trusty-mpm-shaped façade over it: unwrap the template
/// from [`TrustyToolsConfig`] and delegate. The precedence is unchanged
/// (**`TRUSTY_MPM_WORKSPACE_ROOT` env > config `workspace_root_template` >
/// built-in `~/trusty-mpm-projects`**).
/// 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 {
    // #5203: one resolver, in trusty-common, for every consumer.
    trusty_common::workspace_layout::resolve_workspace_root(
        config.workspace_root_template.as_deref(),
    )
}

/// Resolve the session-worktree base directory name (#5204).
///
/// Why: the creation sites (`provisioner::workspace`,
/// `daemon::managed_routes::inproject`) need the single name new worktrees are
/// created under. Detection sites must use `worktree_dir_names` instead —
/// see that function for why the two differ.
/// What: delegates to [`trusty_common::workspace_layout::worktrees_dirname`],
/// which applies **`TRUSTY_MPM_WORKTREES_DIRNAME` env > config
/// `worktrees_dirname` > built-in `.worktrees`**.
/// Test: `worktrees_dirname_defaults_to_dot_worktrees`,
/// `worktrees_dirname_honours_config`.
pub fn worktrees_dirname(config: &TrustyToolsConfig) -> String {
    // #5203/#5204: one resolver, in trusty-common, for every consumer.
    trusty_common::workspace_layout::resolve_worktrees_dirname(config.worktrees_dirname.as_deref())
}

/// The operator's keep-list patterns, or an empty list (#6927).
///
/// Why: named rather than read inline at each call site so the DEFAULT — no
/// `disk:` section means no kept worktrees — is stated once. The patterns stay
/// raw here; compiling them into a matcher is
/// [`KeepList::from_patterns`](crate::session_manager::worktree_keep_list::KeepList::from_patterns)'
/// job, which keeps this module free of the matching rules and free of any
/// dependency on the classifier.
/// What: `config.disk.keep_list`, or `[]`.
/// Test: `disk_keep_list_defaults_to_empty`, `disk_config_yaml_round_trip`.
pub fn disk_keep_list_patterns(config: &TrustyToolsConfig) -> Vec<String> {
    config
        .disk
        .as_ref()
        .map(|d| d.keep_list.clone())
        .unwrap_or_default()
}

/// Read the operator's keep-list, FAILING CLOSED on a config that will not
/// parse (#6927).
///
/// Why: [`TrustyToolsConfig::load`] collapses every YAML error to `Default`, by
/// design — a bad config must not stop the daemon starting. Applied to a
/// PROTECTIVE list that rule inverts its meaning: a typo in an unrelated
/// section left `disk` at `None`, produced an empty keep-list, and let
/// `tm session prune-worktrees --merged-prs` delete a worktree the operator had
/// vetoed, with only a `warn!` line to say so. This loader is why every
/// keep-list consumer now distinguishes "no `disk:` section" from "config
/// unreadable".
/// What: the fallible [`trusty_common::crate_config::load`], not
/// `load_or_default`. An absent file (or an unknown home) is an EMPTY list,
/// which is the documented default and permits. A read or parse failure builds
/// [`KeepList::unreadable`], which keeps every path — see that constructor.
/// Test: `an_unparseable_config_yields_an_unreadable_keep_list`,
/// `an_absent_config_yields_an_empty_keep_list`,
/// `a_valid_config_yields_the_operators_patterns`,
/// `a_malformed_config_refuses_to_reclaim_a_merged_clean_worktree`.
pub(crate) fn load_disk_keep_list() -> KeepList {
    // An unknown home is "no config", which is the documented empty default —
    // the same answer `crate_config::load` gives for it.
    let Some(home) = dirs::home_dir() else {
        return KeepList::default();
    };
    load_disk_keep_list_at(&home)
}

/// [`load_disk_keep_list`] against an explicit home directory (hermetic).
///
/// Why: the production reader resolves `dirs::home_dir()`, which a test must
/// not depend on. Pointing `base` at a `tempfile::TempDir` is what lets the
/// fail-closed path be proved end to end — write a config there, run a reclaim
/// against a scratch worktree store, assert nothing was deleted.
/// What: `<base>/.trusty-tools/trusty-mpm/config.yaml`, with the same
/// absent/valid/unreadable three-way as [`load_disk_keep_list`].
/// Test: `an_unparseable_config_yields_an_unreadable_keep_list`,
/// `a_malformed_config_refuses_to_reclaim_a_merged_clean_worktree`.
pub(crate) fn load_disk_keep_list_at(base: &Path) -> KeepList {
    let path = trusty_common::crate_config::crate_config_path_at(base, CRATE_NAME);
    match trusty_common::crate_config::load_at::<TrustyToolsConfig>(&path) {
        Ok(Some(config)) => KeepList::from_patterns(&disk_keep_list_patterns(&config)),
        Ok(None) => KeepList::default(),
        Err(e) => KeepList::unreadable(e.to_string()),
    }
}

/// 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())
}

/// Pin `TRUSTY_MPM_WORKSPACE_ROOT` at an empty fixture dir for one test (#6551).
///
/// Why: `prune_worktrees_core` and `reconcile_worktrees_core` resolve the
/// worktree root through `TrustyToolsConfig::load()` on EVERY call, and with the
/// variable unset that resolves to `$HOME/trusty-mpm-projects` — the operator's
/// real fleet. Two consequences, both observed: the two transports enumerate
/// ~200 real worktrees instead of the `TempDir` fixture, and a sibling test that
/// sets or clears this same process-global variable between the HTTP call and
/// the RPC call splits the parity comparison. Pinning it removes both, because
/// the two calls then read one value that names an empty directory.
///
/// What: takes the crate-wide `env_test_lock` and sets the variable, restoring
/// the previous value (or removing it) on drop, unwinding panics included.
/// BOTH guards are needed and they cover different populations, exactly as
/// `prune::tests::prune_spares_a_stopped_records_workspace` records:
/// `env_test_lock` serialises the env-precedence tests, `#[serial_test::serial]`
/// serialises `connectors::tm_tests`, which mutates this variable under
/// `serial` alone. The lock is held across the awaited route calls on purpose —
/// releasing it earlier is the race.
///
/// `#[serial_test::file_serial]` is deliberately NOT used: the pinned resource
/// is a process environment variable, so under `cargo nextest`'s
/// process-per-test model (#4162) each test already has its own copy and there
/// is nothing shared across processes to serialise.
///
/// Test: `managed_prune_worktrees_enumerates_only_the_pinned_workspace_root`.
#[cfg(test)]
pub(crate) struct WorkspaceRootEnv {
    _lock: std::sync::MutexGuard<'static, ()>,
    prev: Option<std::ffi::OsString>,
}

#[cfg(test)]
impl WorkspaceRootEnv {
    /// Pin the variable at `root` until the guard drops.
    pub(crate) fn pin(root: &std::path::Path) -> Self {
        let lock = env_test_lock();
        let key = WORKSPACE_ROOT_ENV;
        let prev = std::env::var_os(key);
        // SAFETY: the crate-wide `env_test_lock` is held for this value's whole
        // lifetime, and every other mutator of this variable takes it too.
        unsafe { std::env::set_var(key, root) };
        Self { _lock: lock, prev }
    }
}

#[cfg(test)]
impl Drop for WorkspaceRootEnv {
    fn drop(&mut self) {
        let key = WORKSPACE_ROOT_ENV;
        // SAFETY: `_lock` is still held — it is dropped after this field.
        unsafe {
            match self.prev.take() {
                Some(v) => std::env::set_var(key, v),
                None => std::env::remove_var(key),
            }
        }
    }
}

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