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
//! Unit tests for [`super`] (the console-facing MCP tool implementations).
//!
//! Why: split out of `mcp_console.rs` so the production module stays under
//! the 500-SLOC cap (mirrors `inproject.rs`/`inproject/tests.rs`); the tests
//! themselves are unchanged.
//! What: `config_read`/`config_write`/`apply_config_write` shape and merge
//! tests (including the #2196 `untracked_sync` cases), the
//! `console_metrics`/`supervisor_status` report-shape tests, and the #6288
//! published-metrics merge.
//! Test: this IS the test module.

use super::*;

fn state() -> Arc<DaemonState> {
    DaemonState::shared()
}

/// Why: `config_read` must always return the four-field shape including the
/// resolved absolute `workspace_root`, even on a fresh install (defaults).
/// Test: this test (reads the real/default config; asserts SHAPE, not values,
/// since the host may have a real config file).
#[tokio::test]
async fn config_read_returns_resolved_root() {
    let got = config_read().expect("config_read");
    assert!(
        got.get("workspace_root_template").is_some(),
        "must carry workspace_root_template key: {got}"
    );
    assert!(
        got["workspace_root"].is_string() && !got["workspace_root"].as_str().unwrap().is_empty(),
        "workspace_root must be a non-empty resolved path: {got}"
    );
}

/// Why: `config_to_json` must surface the #2184 `github`/`projects` fields
/// so the Config tab can render/edit them without a separate round-trip.
/// Test: this test.
#[test]
fn config_to_json_includes_github_and_projects() {
    let config = TrustyToolsConfig {
        github: Some(trusty_tools_config::GithubConfig {
            config_dir: Some("/cfg/global".into()),
            token_env: None,
            account: None,
            host: None,
        }),
        projects: vec![trusty_tools_config::ProjectConfig {
            name: "widget".into(),
            repo_url: "https://github.com/acme/widget".into(),
            default_branch: None,
            stack_hint: None,
            tags: None,
            description: None,
            gh_user: None,
            gh_account: None,
            github: None,
            commit_name: Some("Bot".into()),
            commit_email: None,
            untracked_sync: None,
            worktree: None,
        }],
        ..Default::default()
    };
    let json = config_to_json(&config);
    assert_eq!(json["github"]["config_dir"], "/cfg/global");
    assert_eq!(json["projects"][0]["name"], "widget");
    assert_eq!(json["projects"][0]["commit_name"], "Bot");
}

// ── apply_config_write (#2184) — pure merge logic, no real config file I/O ──

fn project(name: &str) -> trusty_tools_config::ProjectConfig {
    trusty_tools_config::ProjectConfig {
        name: name.to_string(),
        repo_url: format!("https://github.com/acme/{name}"),
        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,
    }
}

/// Why: the pre-#2184 top-level fields must still merge exactly as before
/// (no regression from the new params).
/// Test: this test.
#[test]
fn config_write_merges_top_level_fields() {
    let mut config = TrustyToolsConfig::default();
    apply_config_write(
        &mut config,
        Some("~/custom-projects"),
        Some(true),
        Some("opus"),
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .expect("ok");
    assert_eq!(
        config.workspace_root_template.as_deref(),
        Some("~/custom-projects")
    );
    assert_eq!(config.auto_resume, Some(true));
    assert_eq!(config.default_model.as_deref(), Some("opus"));
    assert_eq!(config.github, None, "no github edit supplied");
}

/// Why: with no `project_name`, `github_*` fields must set the GLOBAL
/// `config.github` tier.
/// Test: this test.
#[test]
fn config_write_sets_global_github_binding() {
    let mut config = TrustyToolsConfig::default();
    apply_config_write(
        &mut config,
        None,
        None,
        None,
        None,
        Some("/cfg/global"),
        None,
        None,
        Some("github.example.com"),
        None,
        None,
        None,
        None,
    )
    .expect("ok");
    let gh = config.github.expect("global github set");
    assert_eq!(
        gh.config_dir.as_deref(),
        Some(std::path::Path::new("/cfg/global"))
    );
    assert_eq!(gh.host.as_deref(), Some("github.example.com"));
}

/// Why: with `project_name` set, `github_*`/`commit_*` fields must
/// overlay the MATCHING `config.projects` entry, not the global tier.
/// Test: this test.
#[test]
fn config_write_sets_project_github_and_commit_identity() {
    let mut config = TrustyToolsConfig {
        projects: vec![project("widget")],
        ..Default::default()
    };
    apply_config_write(
        &mut config,
        None,
        None,
        None,
        Some("widget"),
        Some("/cfg/widget"),
        None,
        Some("bob-work"),
        None,
        Some("Widget Bot"),
        Some("widget-bot@example.com"),
        None,
        None,
    )
    .expect("ok");
    assert_eq!(config.github, None, "global tier must be untouched");
    let entry = &config.projects[0];
    let gh = entry.github.as_ref().expect("project github set");
    assert_eq!(
        gh.config_dir.as_deref(),
        Some(std::path::Path::new("/cfg/widget"))
    );
    assert_eq!(gh.account.as_deref(), Some("bob-work"));
    assert_eq!(entry.commit_name.as_deref(), Some("Widget Bot"));
    assert_eq!(
        entry.commit_email.as_deref(),
        Some("widget-bot@example.com")
    );
}

/// Why: setting a project's identity for a `project_name` that is NOT
/// already declared in `config.projects` must error, never fabricate a
/// `ProjectConfig` with an empty `repo_url`.
/// Test: this test.
#[test]
fn config_write_project_not_found_errors() {
    let mut config = TrustyToolsConfig::default();
    let err = apply_config_write(
        &mut config,
        None,
        None,
        None,
        Some("does-not-exist"),
        Some("/cfg/x"),
        None,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .unwrap_err();
    assert!(err.contains("does-not-exist"), "err: {err}");
    assert!(err.contains("not found"), "err: {err}");
}

/// Why: `merge_github_config` must overlay only the SUPPLIED sub-fields,
/// preserving whatever was already set for the omitted ones — matching
/// the top-level "omitted fields unchanged" contract.
/// Test: this test.
#[test]
fn config_write_preserves_omitted_github_subfields() {
    let mut config = TrustyToolsConfig {
        github: Some(trusty_tools_config::GithubConfig {
            config_dir: Some("/cfg/original".into()),
            token_env: None,
            account: Some("original-account".into()),
            host: None,
        }),
        ..Default::default()
    };
    // Only update `host`; config_dir/account must survive untouched.
    apply_config_write(
        &mut config,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        Some("github.example.com"),
        None,
        None,
        None,
        None,
    )
    .expect("ok");
    let gh = config.github.expect("github still set");
    assert_eq!(
        gh.config_dir.as_deref(),
        Some(std::path::Path::new("/cfg/original"))
    );
    assert_eq!(gh.account.as_deref(), Some("original-account"));
    assert_eq!(gh.host.as_deref(), Some("github.example.com"));
}

/// Why: commit identity is project-scoped only (#2184) — supplying
/// `commit_name`/`commit_email` with no `project_name` must be rejected
/// rather than silently discarded or persisted somewhere unexpected.
/// Test: this test.
#[test]
fn config_write_global_commit_identity_rejected() {
    let mut config = TrustyToolsConfig::default();
    let err = apply_config_write(
        &mut config,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        Some("Global Bot"),
        None,
        None,
        None,
    )
    .unwrap_err();
    assert!(err.contains("project_name"), "err: {err}");
}

/// Why: the doc-referenced round-trip contract — every supplied field
/// makes it into the merged config and NOTHING supplied is silently
/// dropped. Exercises the full param list together (the shape
/// `config_write` itself passes through to `apply_config_write`).
/// Test: this test.
#[test]
fn config_write_merges_and_persists() {
    let mut config = TrustyToolsConfig {
        projects: vec![project("widget")],
        ..Default::default()
    };
    apply_config_write(
        &mut config,
        Some("~/custom-projects"),
        Some(false),
        Some("sonnet"),
        Some("widget"),
        Some("/cfg/widget"),
        Some("WIDGET_GH_TOKEN"),
        None,
        Some("github.example.com"),
        Some("Widget Bot"),
        Some("widget-bot@example.com"),
        None,
        None,
    )
    .expect("ok");
    assert_eq!(
        config.workspace_root_template.as_deref(),
        Some("~/custom-projects")
    );
    assert_eq!(config.auto_resume, Some(false));
    assert_eq!(config.default_model.as_deref(), Some("sonnet"));
    let entry = &config.projects[0];
    let gh = entry.github.as_ref().expect("project github set");
    assert_eq!(gh.token_env.as_deref(), Some("WIDGET_GH_TOKEN"));
    assert_eq!(gh.host.as_deref(), Some("github.example.com"));
    assert_eq!(entry.commit_name.as_deref(), Some("Widget Bot"));
}

/// Why (#2196): `config_to_json` must surface the global `untracked_sync`
/// section so the Config tab can render/edit it without a separate
/// round-trip.
/// Test: this test.
#[test]
fn config_to_json_includes_untracked_sync() {
    let config = TrustyToolsConfig {
        untracked_sync: Some(trusty_tools_config::UntrackedSyncConfig {
            patterns: Some(vec![".env".into(), ".env.*".into()]),
            enabled: Some(false),
        }),
        ..Default::default()
    };
    let json = config_to_json(&config);
    assert_eq!(json["untracked_sync"]["enabled"], false);
    assert_eq!(json["untracked_sync"]["patterns"][0], ".env");
}

/// Why (#2196): with no `project_name`, `untracked_sync_*` fields must
/// set the GLOBAL `config.untracked_sync` tier (mirrors
/// `config_write_sets_global_github_binding`).
/// Test: this test.
#[test]
fn config_write_sets_global_untracked_sync() {
    let mut config = TrustyToolsConfig::default();
    apply_config_write(
        &mut config,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        Some(vec![".env".to_string(), ".env.local".to_string()]),
        Some(false),
    )
    .expect("ok");
    let cfg = config.untracked_sync.expect("global untracked_sync set");
    assert_eq!(
        cfg.patterns,
        Some(vec![".env".to_string(), ".env.local".to_string()])
    );
    assert_eq!(cfg.enabled, Some(false));
}

/// Why (#2196): with `project_name` set, `untracked_sync_*` fields must
/// overlay the MATCHING `config.projects` entry, not the global tier —
/// and omitted sub-fields (e.g. `enabled` here) must survive untouched.
/// Test: this test.
#[test]
fn config_write_sets_project_untracked_sync() {
    let mut config = TrustyToolsConfig {
        projects: vec![project("widget")],
        ..Default::default()
    };
    apply_config_write(
        &mut config,
        None,
        None,
        None,
        Some("widget"),
        None,
        None,
        None,
        None,
        None,
        None,
        Some(vec![".env.widget-only".to_string()]),
        None,
    )
    .expect("ok");
    assert_eq!(config.untracked_sync, None, "global tier must be untouched");
    let entry = &config.projects[0];
    let cfg = entry
        .untracked_sync
        .as_ref()
        .expect("project untracked_sync set");
    assert_eq!(cfg.patterns, Some(vec![".env.widget-only".to_string()]));
    assert_eq!(
        cfg.enabled, None,
        "enabled was not supplied; must stay None"
    );
}

/// Why: the console deserialises the report with `parse_report`; the tool must
/// return the exact `ConsoleMetricsReport` shape (service_id, status, and a
/// `metrics.fleet` object).
/// Test: this test.
// NOTE: `DaemonState::shared()` is a PROCESS-WIDE singleton, so other tests in
// this binary may have registered managed sessions before these run. The
// assertions below therefore check SHAPE and field TYPES, never exact fleet
// counts (which are non-deterministic across the shared test process).

#[tokio::test]
async fn console_metrics_report_has_expected_shape() {
    let report = console_metrics(&state()).await.expect("report");
    assert_eq!(report["service_id"], "trusty-mpm");
    assert_eq!(report["display_name"], "Trusty MPM");
    assert_eq!(report["metrics_schema_version"], METRICS_SCHEMA_VERSION);
    // Status is one of the coarse ServiceHealth variants.
    assert!(
        matches!(report["status"].as_str(), Some("ok") | Some("degraded")),
        "status must be ok|degraded: {report}"
    );
    assert!(
        report["metrics"]["fleet"].is_object(),
        "metrics.fleet must be an object: {report}"
    );
    assert!(
        report["metrics"]["fleet"]["total"].is_u64(),
        "metrics.fleet.total must be an integer: {report}"
    );
    assert!(
        report["metrics"]["auto_resume"].is_object(),
        "metrics.auto_resume must be an object: {report}"
    );
    // #6288: the report must always say where `fleet.run_stats` came from, so a
    // zero is never mistaken for "the supervisor swept and did nothing".
    assert!(
        matches!(
            report["metrics"]["supervisor_metrics"]["status"].as_str(),
            Some("current") | Some("stale") | Some("unavailable")
        ),
        "metrics.supervisor_metrics.status must name the read outcome: {report}"
    );
}

/// Why: the supervisor widget reads `fleet` counts and the auto-resume control
/// state from this object; both must be present and well-typed. #5208 added
/// `effective` — the field the Sessions tab actually renders — and `read_error`,
/// which makes an unreadable desired-state file report as unknown instead of as
/// a fabricated `false`.
/// Test: this test; the console-side mapping is `ui/src/autoResume.test.js`.
#[tokio::test]
async fn supervisor_status_reports_fleet_and_auto_resume() {
    let status = supervisor_status(&state()).await.expect("status");
    // Fleet counts must be present and integer-typed (exact values are
    // non-deterministic in the shared-singleton test process).
    assert!(status["fleet"]["active"].is_u64());
    assert!(status["fleet"]["stopped"].is_u64());
    assert!(status["fleet"]["total"].is_u64());

    let ar = &status["auto_resume"];
    assert!(ar["env"].is_boolean());
    assert!(ar["pending_restart"].is_boolean());
    assert_eq!(
        ar["pending_restart"], false,
        "#5208: the supervisor re-reads the file every sweep, so no toggle is \
         ever waiting on a restart"
    );

    // #5208: `desired` / `effective` are booleans when the file is readable and
    // BOTH null when it is not. They must never disagree about which it is —
    // that pairing is what lets the console show "unknown" rather than "off".
    assert!(
        ar.get("effective").is_some(),
        "effective must be on the wire"
    );
    assert!(
        ar.get("read_error").is_some(),
        "read_error must be on the wire"
    );
    if ar["read_error"].is_null() {
        assert!(
            ar["desired"].is_boolean(),
            "readable file → boolean desired"
        );
        assert!(
            ar["effective"].is_boolean(),
            "readable file → boolean effective"
        );
    } else {
        assert!(ar["read_error"].is_string());
        assert!(
            ar["desired"].is_null(),
            "unreadable file must not report false"
        );
        assert!(ar["effective"].is_null());
    }

    // #6288: `run_stats` comes from the supervisor's published file, so the
    // status of that read is on the wire beside the fleet counts.
    let sm = &status["supervisor_metrics"];
    assert!(
        sm.is_object(),
        "supervisor_metrics must be an object: {status}"
    );
    match sm["status"].as_str() {
        Some("current") | Some("stale") => {
            assert!(
                sm["age_secs"].is_i64(),
                "a snapshot read reports its age: {sm}"
            );
            assert!(sm["written_at"].is_string());
        }
        Some("unavailable") => {
            assert!(
                sm["reason"].is_string(),
                "an unavailable snapshot must say why, never report a bare zero: {sm}"
            );
        }
        other => panic!("unexpected supervisor_metrics.status {other:?}: {status}"),
    }
}

/// FAIL-OPEN CHECK (#6288): with no published snapshot, the daemon must leave
/// `run_stats` at its default AND say `unavailable` with a reason. Reporting the
/// zeroed counters silently is the exact defect this slice closes — an operator
/// cannot tell "the supervisor is not running" from "it swept and did nothing".
/// Test: this is the test.
#[test]
fn supervisor_metrics_merge_absent_file_is_unavailable_not_zero() {
    let tmp = tempfile::TempDir::new().expect("tempdir");
    let path = tmp.path().join("supervisor-metrics.json");
    let mut fleet = FleetMetrics::default();

    let block = merge_supervisor_metrics(&mut fleet, &path, Utc::now());

    assert_eq!(block["status"], "unavailable");
    assert!(
        block["reason"].as_str().is_some_and(|r| !r.is_empty()),
        "the zero must arrive with a reason attached: {block}"
    );
    assert_eq!(
        fleet.run_stats,
        crate::supervisor::SupervisorRunStats::default(),
        "with no snapshot the counters stay at their default — the `status` \
         field is what stops that reading as a real zero"
    );
}

/// Why (#6288): a stopped supervisor's last file stays on disk. The daemon must
/// hand back its counters — they are the last real observation — while labelling
/// them `stale` so the console does not present them as live.
/// Test: this is the test.
#[test]
fn supervisor_metrics_merge_flags_a_stale_snapshot() {
    let tmp = tempfile::TempDir::new().expect("tempdir");
    let path = tmp.path().join("supervisor-metrics.json");
    let mut published = FleetMetrics::default();
    published.run_stats.sweeps = 11;
    let interval = std::time::Duration::from_secs(30);
    let threshold = crate::supervisor::publish::stale_after_secs(interval);
    let written_at = Utc::now() - chrono::Duration::seconds(threshold + 30);
    crate::supervisor::publish::write_at(&path, &published, interval, written_at).expect("publish");

    let mut fleet = FleetMetrics::default();
    let block = merge_supervisor_metrics(&mut fleet, &path, Utc::now());

    assert_eq!(block["status"], "stale");
    assert!(block["age_secs"].as_i64().expect("age") > threshold);
    assert_eq!(
        block["stale_after_secs"].as_i64().expect("threshold"),
        threshold,
        "the block must report the window the verdict actually used: {block}"
    );
    assert_eq!(block["interval_secs"], 30);
    assert_eq!(
        fleet.run_stats.sweeps, 11,
        "a stale snapshot's counters are still merged — dropping them would \
         re-create the silent zero one layer out: {block}"
    );
}