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
//! Daemon-side implementation of the console-facing MCP tools (#1222 / P2).
//!
//! Why: trusty-console renders the Sessions tab natively by polling the daemon
//! over MCP (per the #1104 HTTP-only-in-console principle). It needs three tools
//! the existing catalog did not provide: `console_metrics` (the standard
//! [`trusty_common::console_metrics::ConsoleMetricsReport`] every trusty service
//! exposes so the console poller is service-agnostic), `supervisor_status` (the
//! fleet-state snapshot plus the auto-resume control state), and `auto_resume_set`
//! (the console's non-CLI control for enabling/disabling auto-resume — RFC §6 Q6).
//! Putting them here keeps `mcp_backend.rs` under the 500-SLOC production cap.
//! What: three free async functions over `&Arc<DaemonState>`:
//! [`console_metrics`] builds a report whose `metrics` payload carries the
//! `FleetMetrics` and supervisor flags; [`supervisor_status`] returns the same
//! fleet snapshot as a bare object; [`auto_resume_set`] persists the operator's
//! desired flag and echoes the resulting state. All return the same JSON shapes
//! across MCP and any future HTTP transport.
//! Test: `cargo test -p trusty-mpm daemon::mcp_console` covers report shape,
//! fleet derivation, and the auto-resume persistence round-trip.

use std::path::Path;
use std::sync::Arc;

use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use trusty_common::console_metrics::{ConsoleMetricsReport, ServiceHealth, make_report};

use crate::core::auto_resume;
use crate::core::paths::FrameworkPaths;
use crate::core::trusty_tools_config::{self, TrustyToolsConfig};
use crate::daemon::state::DaemonState;
use crate::supervisor::metrics::FleetMetrics;
use crate::supervisor::publish::{self, SupervisorMetricsStatus};

/// Schema version of the `console_metrics` `metrics` payload for trusty-mpm.
///
/// Why: the console bumps its UI when this changes; starting at 1 establishes the
/// contract for the Sessions tab.
/// What: monotonically-increasing integer carried in every report.
/// Test: asserted in `console_metrics_report_has_expected_shape`.
const METRICS_SCHEMA_VERSION: u32 = 1;

/// Service version reported in `console_metrics` (the crate semver).
const SERVICE_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Build the supervisor/auto-resume + fleet snapshot shared by both
/// `console_metrics` and `supervisor_status`.
///
/// Why: both tools surface the same fleet counts and auto-resume state; deriving
/// them in one place keeps the two tool payloads in lockstep.
/// What: lists the managed session records, derives [`FleetMetrics`] from them,
/// and reads the persisted desired + live env auto-resume flags. Returns a JSON
/// object: `{ fleet, auto_resume: { desired, env, pending_restart } }`.
///
/// Auto-resume control fields:
/// - `desired`: the operator's persisted choice (console-mutable), or `null` when
///   the file could not be read.
/// - `env`: the flag the DAEMON's environment carries. The supervisor is a
///   separate process (`bin/tm/commands/supervisor.rs`) and `--auto-resume` sets
///   its config without touching the env, so this is an inference about another
///   process, not an observation of it. It is only consulted when no override
///   file exists — i.e. before the operator has ever used the toggle. Closing
///   that gap means adding the supervisor's resolved flag to the snapshot it
///   already publishes (#6288); tracked separately.
/// - `effective`: what the supervisor's next sweep will do — the persisted file
///   when it exists, otherwise `env`, or `null` when the file could not be read.
/// - `read_error`: `null` normally; the I/O error string when the desired-state
///   file exists but could not be read. #5208: this used to be swallowed into a
///   fabricated `desired: false`, which reported a confident "off" while the
///   supervisor was holding its last known value — the two surfaces diverging
///   exactly when the file is broken.
/// - `pending_restart`: always `false` since #5208. It used to be `desired != env`
///   because the supervisor read only its boot env, so a console toggle really did
///   need a restart. The supervisor now re-reads the file every sweep, so the
///   "restart pending" hint would be a false claim; the key is kept for wire
///   compatibility until the console drops it.
///
/// #6288 adds `supervisor_metrics`, describing where `fleet.run_stats` came
/// from — see [`merge_supervisor_metrics`].
///
/// Test: `supervisor_status_reports_fleet_and_auto_resume`.
async fn fleet_snapshot(state: &Arc<DaemonState>) -> Value {
    let mgr = state.session_manager().await;
    let records = mgr.list().await;
    let mut fleet = FleetMetrics::from_records(&records);
    // #6288: `from_records` leaves `run_stats` at its default — those counters
    // live in the separate supervisor process. Merge in what it published.
    let supervisor_metrics = merge_supervisor_metrics(
        &mut fleet,
        &publish::metrics_path(&FrameworkPaths::default()),
        Utc::now(),
    );

    // #5208: read the tri-state override so `effective` can say "no file → the
    // supervisor's boot env stands" rather than flattening absence into `false`,
    // and report an unreadable file as unknown rather than as a confident `false`.
    let (over, read_error) = match auto_resume::read_override() {
        Ok(v) => (v, None),
        Err(e) => (None, Some(e.to_string())),
    };
    let env = auto_resume::effective_from_env();
    let unknown = read_error.is_some();

    json!({
        "fleet": fleet,
        "auto_resume": {
            "desired": if unknown { Value::Null } else { json!(over.unwrap_or(false)) },
            "env": env,
            "effective": if unknown { Value::Null } else { json!(over.unwrap_or(env)) },
            "read_error": read_error,
            "pending_restart": false,
        },
        "supervisor_metrics": supervisor_metrics,
    })
}

/// Overlay the supervisor's published `run_stats` onto `fleet`, and say where
/// they came from (#6288).
///
/// Why: `FleetMetrics::from_records` can only see the session store. The sweep,
/// auto-resume, resume-failure and classification counters live in the separate
/// `tm supervisor` process, so before #6288 `console_metrics` and
/// `supervisor_status` reported a confident zero for all four no matter how long
/// the supervisor had been running. The counters now arrive through
/// `<framework root>/supervisor-metrics.json`.
///
/// FAIL-OPEN CHECK: a missing, unreadable, or corrupt file must never read as
/// "zero sweeps" — that is the defect, one layer out. Every outcome is named on
/// the wire in `supervisor_metrics.status`:
/// - `current` — a snapshot inside its own staleness window
///   ([`publish::stale_after_secs`], sized from the cadence the writing
///   supervisor runs at); its `run_stats` are merged into `fleet`.
/// - `stale` — an older snapshot, still merged (it is the last real
///   observation), but flagged so the console does not present it as live.
///   `interval_secs` and `stale_after_secs` ride along so a reader can see which
///   window the verdict used.
/// - `unavailable` — nothing usable; `fleet.run_stats` stays at its default AND
///   `reason` says why, so a reader can tell "the supervisor is not running"
///   from "the supervisor has run zero sweeps".
///
/// What: reads `path` via [`publish::read_status_at`], merges `run_stats` for
/// the two snapshot-bearing outcomes, and returns the JSON block described
/// above. Takes `path` and `now` as parameters rather than resolving
/// `FrameworkPaths::default()` internally so a test can drive the whole round
/// trip against a temp file instead of the developer's live `~/.trusty-mpm`.
/// Test: `supervisor_metrics_merge_absent_file_is_unavailable_not_zero`,
/// `supervisor_metrics_merge_flags_a_stale_snapshot`, and — end to end from real
/// sweeps — `supervisor::tests::supervisor_metrics_merge_reports_real_run_stats`.
pub(crate) fn merge_supervisor_metrics(
    fleet: &mut FleetMetrics,
    path: &Path,
    now: DateTime<Utc>,
) -> Value {
    match publish::read_status_at(path, now) {
        SupervisorMetricsStatus::Current {
            snapshot,
            age_secs,
            stale_after_secs,
        } => {
            let interval_secs = snapshot.interval_secs;
            fleet.run_stats = snapshot.fleet.run_stats;
            json!({
                "status": "current",
                "written_at": snapshot.written_at,
                "age_secs": age_secs,
                "interval_secs": interval_secs,
                "stale_after_secs": stale_after_secs,
            })
        }
        SupervisorMetricsStatus::Stale {
            snapshot,
            age_secs,
            stale_after_secs,
        } => {
            let interval_secs = snapshot.interval_secs;
            fleet.run_stats = snapshot.fleet.run_stats;
            json!({
                "status": "stale",
                "written_at": snapshot.written_at,
                "age_secs": age_secs,
                "interval_secs": interval_secs,
                "stale_after_secs": stale_after_secs,
            })
        }
        // No snapshot means no cadence to report a window for; a threshold here
        // would be a number invented by the reader.
        SupervisorMetricsStatus::Unavailable { reason } => json!({
            "status": "unavailable",
            "reason": reason,
        }),
    }
}

/// Back the `console_metrics` tool with a [`ConsoleMetricsReport`].
///
/// Why: the trusty-console metrics poller calls `console_metrics` on every
/// service uniformly; trusty-mpm must speak the same contract so it appears in
/// the dashboard like the other services.
/// What: classifies health (`Ok` normally, `Degraded` when any session is
/// `errored`), packs the fleet + auto-resume snapshot into the report's flexible
/// `metrics` field, and returns it as a JSON object the console deserialises with
/// `trusty_common::console_metrics::parse_report`.
/// Test: `console_metrics_report_has_expected_shape`.
pub async fn console_metrics(state: &Arc<DaemonState>) -> Result<Value, String> {
    let snapshot = fleet_snapshot(state).await;
    let errored = snapshot
        .get("fleet")
        .and_then(|f| f.get("errored"))
        .and_then(Value::as_u64)
        .unwrap_or(0);
    let status = if errored > 0 {
        ServiceHealth::Degraded
    } else {
        ServiceHealth::Ok
    };

    let report: ConsoleMetricsReport = make_report(
        "trusty-mpm",
        "Trusty MPM",
        SERVICE_VERSION,
        status,
        snapshot,
        METRICS_SCHEMA_VERSION,
    );

    serde_json::to_value(&report).map_err(|e| format!("serialising console_metrics report: {e}"))
}

/// Back the `supervisor_status` tool with the fleet + auto-resume snapshot.
///
/// Why: the Sessions tab's supervisor widget needs fleet counts by lifecycle
/// state and the current auto-resume control state in one call, without parsing
/// the full `console_metrics` envelope.
/// What: returns the bare `{ fleet, auto_resume }` object from [`fleet_snapshot`].
/// Test: `supervisor_status_reports_fleet_and_auto_resume`.
pub async fn supervisor_status(state: &Arc<DaemonState>) -> Result<Value, String> {
    Ok(fleet_snapshot(state).await)
}

/// Back the `auto_resume_set` tool: persist the operator's desired flag.
///
/// Why: the console toggle must durably record whether auto-resume should be on
/// (RFC §6 Q6 — controls live in the console, not CLI-only). The supervisor runs
/// as a separate process, so this writes the desired state the supervisor reads
/// on its next sweep rather than mutating a live env var.
/// What: writes `~/.trusty-mpm/auto_resume`, then echoes the same
/// `{ desired, env, effective, pending_restart }` block [`fleet_snapshot`]
/// returns. Since #5208 the write is load-bearing: the supervisor re-reads the
/// file every sweep, so `effective` is `enabled` and no restart is pending.
/// Test: `write_then_read_round_trips` (the persistence),
/// `supervisor_honours_console_desired_state_without_restart` (the supervisor
/// acting on it). This function itself writes the real `~/.trusty-mpm` root, so
/// it is deliberately not unit-tested against a live `$HOME`.
pub async fn auto_resume_set(enabled: bool) -> Result<Value, String> {
    auto_resume::write_desired(enabled)
        .map_err(|e| format!("persisting auto_resume desired state: {e}"))?;

    Ok(json!({
        "desired": enabled,
        "env": auto_resume::effective_from_env(),
        // #5208: the file outranks the boot env and is re-read every sweep. The
        // write above succeeded, so there is nothing unknown to report here.
        "effective": enabled,
        "read_error": Value::Null,
        "pending_restart": false,
    }))
}

/// Serialise a [`TrustyToolsConfig`] into the JSON the console Config tab renders,
/// annotated with the resolved absolute workspace root.
///
/// Why: both `config_read` and `config_write` return the same shape — the raw
/// config fields plus the `workspace_root` the resolver would actually use — so the
/// UI can show the effective path even when the template field is null. One helper
/// keeps the two tools in lockstep. #2184 adds the global `github` binding and the
/// full `projects` list (each entry now carries its own optional `github`/
/// `commit_name`/`commit_email` per-project override) so the Config tab can render
/// and edit them without a separate MCP round-trip or hand-editing the YAML.
/// #2196 adds the global `untracked_sync` allowlist section (each `projects`
/// entry already carries its own optional `untracked_sync` override via its
/// own `Serialize` impl, so no separate top-level field is needed for that).
/// What: returns `{ workspace_root_template, auto_resume, default_model, github,
/// untracked_sync, projects, workspace_root }` where `workspace_root` is
/// [`trusty_tools_config::workspace_root`].
/// Test: `config_read_returns_resolved_root`,
/// `config_to_json_includes_github_and_projects`,
/// `config_to_json_includes_untracked_sync`.
fn config_to_json(config: &TrustyToolsConfig) -> Value {
    json!({
        "workspace_root_template": config.workspace_root_template,
        "auto_resume": config.auto_resume,
        "default_model": config.default_model,
        "github": config.github,
        "untracked_sync": config.untracked_sync,
        // #6535: the cloud log-drain section, so the Config tab can render
        // where logs go and whether the drain is on without a second read.
        "log_drain": config.log_drain,
        // #6927: the Disk view renders the keep-list beside the worktrees it
        // keeps, so the Config tab must be able to read it back.
        "disk": config.disk,
        "projects": config.projects,
        "workspace_root": trusty_tools_config::workspace_root(config).to_string_lossy(),
    })
}

/// Back the `config_read` tool: load and return the config-convention file.
///
/// Why: the console Config tab (#1220) reads the current
/// `~/.trusty-tools/trusty-mpm/config.yaml` to render its form.
/// What: loads [`TrustyToolsConfig`] (absent file → defaults) and serialises it via
/// [`config_to_json`], including the resolved absolute workspace root.
/// Test: `config_read_returns_resolved_root`.
pub fn config_read() -> Result<Value, String> {
    Ok(config_to_json(&TrustyToolsConfig::load()))
}

/// Back the `config_write` tool: merge edits and persist the config file.
///
/// Why: the console Config tab's save action durably records the operator's
/// workspace-root / auto-resume / default-model choices (#1220), and — since
/// #2184 — the global GitHub identity binding plus per-project GitHub/commit
/// identity overrides, and — since #2196 — the global/per-project untracked-
/// secret-file sync allowlist, all without touching the legacy
/// `~/.trusty-mpm/config.toml` or requiring the operator to hand-edit YAML.
/// What: loads the current config, applies [`apply_config_write`] (the
/// testable merge step), writes it back via
/// [`trusty_common::crate_config::save`], and returns the merged config (with
/// the resolved root) on success.
/// Test: `config_write_merges_and_persists` covers `apply_config_write`
/// directly (no real filesystem I/O against the operator's real config file —
/// see that function's own doc for why `config_write` itself is not unit
/// tested against the real file).
#[allow(clippy::too_many_arguments)]
pub fn config_write(
    workspace_root_template: Option<&str>,
    auto_resume: Option<bool>,
    default_model: Option<&str>,
    project_name: Option<&str>,
    github_config_dir: Option<&str>,
    github_token_env: Option<&str>,
    github_account: Option<&str>,
    github_host: Option<&str>,
    commit_name: Option<&str>,
    commit_email: Option<&str>,
    untracked_sync_patterns: Option<Vec<String>>,
    untracked_sync_enabled: Option<bool>,
) -> Result<Value, String> {
    let mut config = TrustyToolsConfig::load();
    apply_config_write(
        &mut config,
        workspace_root_template,
        auto_resume,
        default_model,
        project_name,
        github_config_dir,
        github_token_env,
        github_account,
        github_host,
        commit_name,
        commit_email,
        untracked_sync_patterns,
        untracked_sync_enabled,
    )?;

    trusty_common::crate_config::save(trusty_tools_config::CRATE_NAME, &config)
        .map_err(|e| format!("persisting trusty-mpm config: {e}"))?;

    Ok(config_to_json(&config))
}

/// The pure merge step behind `config_write` (#2184).
///
/// Why: `config_write` persists to the operator's REAL
/// `~/.trusty-tools/trusty-mpm/config.yaml` (there is no dependency-injected
/// base directory in production), so unit-testing `config_write` itself would
/// mutate the developer's actual config file on every `cargo test` run.
/// Extracting the merge decision into a pure `&mut TrustyToolsConfig` function
/// makes the actual field-merge logic — including the #2184 `project_name`
/// routing — fully unit-testable in memory, with `config_write` reduced to
/// "load, merge, save".
/// What: when `workspace_root_template`/`auto_resume`/`default_model` are
/// `Some`, they overlay the corresponding TOP-LEVEL field (unchanged
/// behaviour, #1220). When `project_name` is `None`, the `github_*` args
/// overlay the GLOBAL `config.github` tier (creating it if absent and at
/// least one `github_*` field is supplied); `commit_*` args with no
/// `project_name` are rejected (#2184 defines commit identity as
/// project-scoped only). When `project_name` is `Some(name)`, the `github_*`
/// AND `commit_*` args overlay the MATCHING entry in `config.projects`
/// instead — `Err` when no entry with that `name` already exists
/// (`config_write` deliberately does not fabricate a `ProjectConfig` with an
/// empty `repo_url`; register the project first via `project_register` or a
/// static `config.projects` entry). Each `github_*` field only overlays its
/// own sub-field — omitted sub-fields keep their previous value, matching the
/// top-level "omitted fields unchanged" contract. `untracked_sync_patterns`/
/// `untracked_sync_enabled` (#2196) follow the SAME `project_name` routing as
/// `github_*` (global tier when `project_name` is `None`, that project's own
/// tier when `Some`) — unlike commit identity, untracked-sync HAS a global
/// tier, so no project_name is required for it.
/// Test: `config_write_merges_top_level_fields`,
/// `config_write_sets_global_github_binding`,
/// `config_write_sets_project_github_and_commit_identity`,
/// `config_write_project_not_found_errors`,
/// `config_write_preserves_omitted_github_subfields`,
/// `config_write_global_commit_identity_rejected`,
/// `config_write_sets_global_untracked_sync`,
/// `config_write_sets_project_untracked_sync`.
#[allow(clippy::too_many_arguments)]
fn apply_config_write(
    config: &mut TrustyToolsConfig,
    workspace_root_template: Option<&str>,
    auto_resume: Option<bool>,
    default_model: Option<&str>,
    project_name: Option<&str>,
    github_config_dir: Option<&str>,
    github_token_env: Option<&str>,
    github_account: Option<&str>,
    github_host: Option<&str>,
    commit_name: Option<&str>,
    commit_email: Option<&str>,
    untracked_sync_patterns: Option<Vec<String>>,
    untracked_sync_enabled: Option<bool>,
) -> Result<(), String> {
    if let Some(t) = workspace_root_template {
        config.workspace_root_template = Some(t.to_string());
    }
    if let Some(a) = auto_resume {
        config.auto_resume = Some(a);
    }
    if let Some(m) = default_model {
        config.default_model = Some(m.to_string());
    }

    let has_github_edit = github_config_dir.is_some()
        || github_token_env.is_some()
        || github_account.is_some()
        || github_host.is_some();
    let has_commit_edit = commit_name.is_some() || commit_email.is_some();
    let has_untracked_sync_edit =
        untracked_sync_patterns.is_some() || untracked_sync_enabled.is_some();
    if !has_github_edit && !has_commit_edit && !has_untracked_sync_edit {
        return Ok(());
    }

    match project_name {
        None => {
            if has_github_edit {
                config.github = Some(merge_github_config(
                    config.github.take(),
                    github_config_dir,
                    github_token_env,
                    github_account,
                    github_host,
                ));
            }
            if has_untracked_sync_edit {
                config.untracked_sync = Some(merge_untracked_sync_config(
                    config.untracked_sync.take(),
                    untracked_sync_patterns,
                    untracked_sync_enabled,
                ));
            }
            // #2184 defines commit identity as PROJECT-scoped only (no global
            // tier) — a caller supplying commit_name/commit_email with no
            // project_name has nowhere to persist them.
            if has_commit_edit {
                return Err(
                    "commit_name/commit_email require project_name (commit identity is \
                     project-scoped; there is no global commit identity tier)"
                        .to_string(),
                );
            }
        }
        Some(name) => {
            let entry = config
                .projects
                .iter_mut()
                .find(|p| p.name == name)
                .ok_or_else(|| {
                    format!(
                        "project '{name}' not found in config.projects; register it first \
                         (e.g. via `project_register` or a static config.yaml entry) before \
                         setting its github/commit identity"
                    )
                })?;
            if has_github_edit {
                entry.github = Some(merge_github_config(
                    entry.github.take(),
                    github_config_dir,
                    github_token_env,
                    github_account,
                    github_host,
                ));
            }
            if has_untracked_sync_edit {
                entry.untracked_sync = Some(merge_untracked_sync_config(
                    entry.untracked_sync.take(),
                    untracked_sync_patterns,
                    untracked_sync_enabled,
                ));
            }
            if let Some(n) = commit_name {
                entry.commit_name = Some(n.to_string());
            }
            if let Some(e) = commit_email {
                entry.commit_email = Some(e.to_string());
            }
        }
    }

    Ok(())
}

/// Overlay supplied `github_*` sub-fields onto an existing (or absent)
/// [`trusty_tools_config::GithubConfig`], keeping omitted sub-fields unchanged.
///
/// Why: shared by both the global and per-project branches of
/// [`apply_config_write`] so the "only overlay what was supplied" rule cannot
/// drift between the two.
/// What: starts from `existing.unwrap_or_default()`, overlays each `Some`
/// argument onto the matching field, and returns the result (never
/// meaningfully empty — the caller only invokes this when at least one
/// `github_*` field was supplied).
/// Test: `config_write_preserves_omitted_github_subfields`.
fn merge_github_config(
    existing: Option<trusty_tools_config::GithubConfig>,
    config_dir: Option<&str>,
    token_env: Option<&str>,
    account: Option<&str>,
    host: Option<&str>,
) -> trusty_tools_config::GithubConfig {
    let mut cfg = existing.unwrap_or_default();
    if let Some(d) = config_dir {
        cfg.config_dir = Some(d.into());
    }
    if let Some(t) = token_env {
        cfg.token_env = Some(t.to_string());
    }
    if let Some(a) = account {
        cfg.account = Some(a.to_string());
    }
    if let Some(h) = host {
        cfg.host = Some(h.to_string());
    }
    cfg
}

/// Overlay supplied `untracked_sync_*` fields onto an existing (or absent)
/// [`trusty_tools_config::UntrackedSyncConfig`] (#2196), keeping an omitted
/// field unchanged.
///
/// Why: mirrors [`merge_github_config`]'s "only overlay what was supplied"
/// rule so both `apply_config_write` branches (global/per-project) stay in
/// lockstep.
/// What: starts from `existing.unwrap_or_default()`, overlays `patterns`/
/// `enabled` when `Some`, and returns the result.
/// Test: `config_write_sets_global_untracked_sync`,
/// `config_write_sets_project_untracked_sync`.
fn merge_untracked_sync_config(
    existing: Option<trusty_tools_config::UntrackedSyncConfig>,
    patterns: Option<Vec<String>>,
    enabled: Option<bool>,
) -> trusty_tools_config::UntrackedSyncConfig {
    let mut cfg = existing.unwrap_or_default();
    if let Some(p) = patterns {
        cfg.patterns = Some(p);
    }
    if let Some(e) = enabled {
        cfg.enabled = Some(e);
    }
    cfg
}

#[cfg(test)]
mod tests;