trusty-mpm 1.5.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Behavior tests: project scaffolding, install, hook guard, optimizer,
//! session output / pause / resume / run subcommand parsing.
//!
//! Why: keeping behavior tests in separate files keeps each file under the
//! 500-line cap while grouping tests by the feature they exercise.
//! What: `project_init_*`, `install_*`, `hook_guard_*`, `mpm_hook_*`,
//! `cli_parses_optimizer_*`, `cli_parses_session_{events,breakers,pause,
//! resume,run,output,*}`, `compression_stats_*`, `cli_{parses_overseer,
//! event_summary_*}`, `hook_disable_env_short_circuits`,
//! `test_write_project_hooks_for_dir_targets_project_dir`.
//! Test: `cargo test -p trusty-mpm` runs the full suite.

use clap::Parser;

use crate::cli::{
    Cli, CliCompressionLevel, Command, OptimizerAction, OverseerAction, SessionAction,
};
use crate::commands::install::{
    deploy_report_lines, install_to, mpm_hook_additions, skill_report_lines,
    write_project_hooks_for_dir,
};
use crate::commands::misc::{DISABLE_HOOKS_ENV, SUB_AGENT_ENV, hook};
use crate::commands::project::scaffold_project_dir;
use crate::formatters::session::{event_summary, print_compression_stats};

#[test]
fn project_init_scaffolds_dotdir() {
    // `project init` must create `.trusty-mpm/{config.toml,sessions/,framework/}`
    // with a config skeleton naming the project after its directory. #4832
    // added `framework/`, the project-stable config layer the manifest override
    // now lives in.
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path().join("my-app");
    std::fs::create_dir_all(&project).unwrap();
    let report = scaffold_project_dir(&project).unwrap();
    assert_eq!(report.len(), 3);

    let config = project.join(".trusty-mpm/config.toml");
    let sessions = project.join(".trusty-mpm/sessions");
    let framework = project.join(".trusty-mpm/framework");
    assert!(config.exists());
    assert!(sessions.is_dir());
    assert!(
        framework.is_dir(),
        "#4832: the framework/ config layer is seeded"
    );
    let contents = std::fs::read_to_string(&config).unwrap();
    assert!(contents.contains("name = \"my-app\""));
    assert!(contents.contains("[agents]"));
    assert!(contents.contains("[skills]"));
}

#[test]
fn project_init_keeps_existing_config() {
    // Re-running `project init` must never clobber an edited config.toml.
    let dir = tempfile::tempdir().unwrap();
    let project = dir.path().to_path_buf();
    scaffold_project_dir(&project).unwrap();
    let config = project.join(".trusty-mpm/config.toml");
    std::fs::write(&config, "# edited by hand").unwrap();

    let report = scaffold_project_dir(&project).unwrap();
    assert!(report.iter().any(|l| l.contains("skipped")));
    assert_eq!(
        std::fs::read_to_string(&config).unwrap(),
        "# edited by hand"
    );
}

#[test]
fn cli_parses_install_no_force() {
    let cli = Cli::try_parse_from(["trusty-mpm", "install"]).unwrap();
    match cli.command.unwrap() {
        Command::Install { force, .. } => assert!(!force),
        other => panic!("expected Install, got {other:?}"),
    }
}

#[test]
fn cli_parses_install_with_force() {
    let cli = Cli::try_parse_from(["trusty-mpm", "install", "--force"]).unwrap();
    match cli.command.unwrap() {
        Command::Install { force, .. } => assert!(force),
        other => panic!("expected Install, got {other:?}"),
    }
}

#[test]
fn cli_parses_hook() {
    let cli = Cli::try_parse_from(["trusty-mpm", "hook"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Hook { pm_guard: false }
    ));
}

/// Why (#1977): the managed launcher registers `tm hook --pm-guard` as the
/// PreToolUse enforcement hook; parsing must round-trip the flag so the
/// dispatcher routes to the PM guard instead of the observability relay.
#[test]
fn cli_parses_hook_pm_guard() {
    let cli = Cli::try_parse_from(["trusty-mpm", "hook", "--pm-guard"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Hook { pm_guard: true }
    ));
}

/// Why (#1956): `tm compress --tool bash` is the pipe-filter stage the
/// `tm hook` PreToolUse Bash rewrite targets; parsing must round-trip the
/// required `--tool` flag.
#[test]
fn cli_parses_compress() {
    let cli = Cli::try_parse_from(["trusty-mpm", "compress", "--tool", "bash"]).unwrap();
    match cli.command.unwrap() {
        Command::Compress { tool } => assert_eq!(tool, "bash"),
        other => panic!("expected Compress, got {other:?}"),
    }
}

/// Why: when `CLAUDE_MPM_SUB_AGENT` is present in the env, the hook
/// handler must return Ok(()) without performing any I/O — that is the
/// whole point of the sub-agent guard.
/// What: sets the env var, calls `hook` with a deliberately-unreachable
/// daemon URL, asserts the call returns Ok in well under the daemon's
/// connect timeout (so we know the network code never ran).
#[tokio::test]
async fn hook_guard_short_circuits() {
    // SAFETY: tokio's current_thread runtime is single-threaded; this
    // env-var dance is isolated to the test.
    unsafe {
        std::env::set_var(SUB_AGENT_ENV, "1");
    }
    let client = reqwest::Client::new();
    let started = std::time::Instant::now();
    // Use a URL we know cannot be reached. If the guard fails the call
    // would consume the full 2s timeout; the assert below catches that.
    let res = hook(&client, "http://127.0.0.1:1").await;
    let elapsed = started.elapsed();
    unsafe {
        std::env::remove_var(SUB_AGENT_ENV);
    }
    assert!(res.is_ok(), "guard branch must return Ok");
    assert!(
        elapsed < std::time::Duration::from_millis(500),
        "guard must short-circuit without network I/O; took {elapsed:?}"
    );
}

/// Why: when `TRUSTY_MPM_DISABLE_HOOKS` is set, the hook handler must
/// short-circuit immediately without I/O — this is the universal opt-out
/// for build shells / CI where the hook must not fire.
/// What: sets the env var, calls `hook` with an unreachable URL, and
/// asserts the call returns Ok(()) without blocking the 500 ms connect
/// timeout that would fire if network code ran.
#[tokio::test]
async fn hook_disable_env_short_circuits() {
    // SAFETY: test is single-threaded (tokio current_thread).
    unsafe {
        std::env::set_var(DISABLE_HOOKS_ENV, "1");
    }
    let client = reqwest::Client::new();
    let started = std::time::Instant::now();
    let res = hook(&client, "http://127.0.0.1:1").await;
    let elapsed = started.elapsed();
    unsafe {
        std::env::remove_var(DISABLE_HOOKS_ENV);
    }
    assert!(res.is_ok(), "DISABLE_HOOKS_ENV branch must return Ok");
    assert!(
        elapsed < std::time::Duration::from_millis(500),
        "DISABLE_HOOKS_ENV must short-circuit without network I/O; took {elapsed:?}"
    );
}

/// Why: `write_project_hooks_for_dir` must write hooks into the project's
/// `.claude/settings.json` — NOT into any global file. This verifies that
/// the function targets the correct path.
/// What: creates a tempdir acting as the project root, calls the function,
/// asserts the file is created at `<project>/.claude/settings.json` with
/// MPM hook entries present and the command using an absolute path.
#[test]
fn test_write_project_hooks_for_dir_targets_project_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let project_dir = tmp.path();
    let settings = project_dir.join(".claude").join("settings.json");

    // The file must not exist before the call.
    assert!(!settings.exists());

    let wrote = write_project_hooks_for_dir(project_dir).unwrap();
    assert!(wrote, "must report file was written");
    assert!(settings.exists(), "project settings must be created");

    let text = std::fs::read_to_string(&settings).unwrap();
    let val: serde_json::Value = serde_json::from_str(&text).unwrap();
    let hooks = val.get("hooks").expect("hooks key must be present");
    assert!(
        hooks.get("PreToolUse").is_some(),
        "PreToolUse hook must be written"
    );

    // The command must end with " hook" (and start with '/' if current_exe
    // is resolvable in test, which it always is under cargo test).
    let cmd = hooks["PreToolUse"][0]["hooks"][0]["command"]
        .as_str()
        .unwrap();
    assert!(
        cmd.ends_with(" hook"),
        "hook command must end with ' hook', got: {cmd:?}"
    );
}

/// Why: re-running `tm install` against a settings file that already
/// carries the MPM hook block must not rewrite the file. This is the
/// idempotency requirement.
/// What: builds the additions block, merges it into an empty document,
/// then merges the same additions back into the result, and asserts the
/// two outputs are deeply equal.
#[test]
fn mpm_hook_additions_is_idempotent_under_merge() {
    use trusty_common::claude_config::merge_hook_entries;
    let additions = mpm_hook_additions();
    let once = merge_hook_entries(&serde_json::json!({}), &additions);
    let twice = merge_hook_entries(&once, &additions);
    assert_eq!(once, twice, "second merge must be a no-op");
    // And every expected event lands exactly once.
    for event in ["PreToolUse", "PostToolUse", "Stop"] {
        let arr = once["hooks"][event].as_array().expect("event array");
        assert_eq!(arr.len(), 1, "{event}: expected one matcher block");
    }
}

#[test]
fn install_writes_all_artifacts() {
    // A fresh install must write every bundled artifact to disk under the
    // framework root, with matching content.
    let dir = tempfile::tempdir().unwrap();
    let paths = trusty_mpm::core::paths::FrameworkPaths::under(dir.path());
    let report = install_to(&paths, false).unwrap();
    assert_eq!(report.len(), trusty_mpm::core::bundle::ALL.len());
    for artifact in trusty_mpm::core::bundle::ALL {
        let dest = paths.framework.join(artifact.rel_path);
        assert!(dest.exists(), "missing {}", artifact.rel_path);
        let written = std::fs::read_to_string(&dest).unwrap();
        assert_eq!(written, artifact.contents);
    }
}

// `InstallPolicy::Overwrite`-vs-`SeedOnce` behavior tests (issue #3381) live in
// `install_policy_tests.rs` — kept out of this file to stay under the 500-SLOC
// production-file cap (this file's basename doesn't match the `_tests.rs`
// test-cap pattern).

#[test]
#[ignore = "requires bundled framework artifacts (base-agent) — run locally after tm install"]
fn install_then_deploy_composes_agents() {
    // Installing the bundled agent sources and then deploying them must
    // produce composed, inheritance-flattened files in `.claude/agents/`.
    let dir = tempfile::tempdir().unwrap();
    let paths = trusty_mpm::core::paths::FrameworkPaths::under(dir.path());
    install_to(&paths, false).unwrap();

    let result = trusty_mpm::core::agent_deployer::deploy_agents(
        &paths.agent_source_dir(),
        &paths.claude_agents_dir(),
    )
    .unwrap();
    // #4724: EVERY bundled agent deploys on a fresh target — derived from the
    // bundle manifest `install_to` just wrote, never a literal. The old
    // `assert_eq!(result.deployed.len(), 6)` was accurate when six agents
    // shipped and has been stale ever since (the roster is 42); a second
    // literal would go stale the next time anyone adds an agent, which is
    // exactly how this got here.
    //
    // Comparing the SETS, not just the counts, is what makes this a real gate:
    // an equal count with different membership would mean the deployer silently
    // dropped one bundled agent and picked up something else, and a length-only
    // assertion cannot see that.
    let mut expected_agents: Vec<String> = trusty_mpm::core::bundle::ALL
        .iter()
        .filter_map(|a| a.rel_path.strip_prefix("agents/"))
        .filter(|name| name.ends_with(".md"))
        .map(str::to_string)
        .collect();
    expected_agents.sort();
    assert!(
        expected_agents.len() > 20,
        "the bundle manifest yielded {} agent artifact(s) — the filter broke, \
         and a gate that examined nothing is not a passing gate",
        expected_agents.len()
    );

    let mut deployed_agents: Vec<String> = result.deployed.clone();
    deployed_agents.sort();
    assert_eq!(
        deployed_agents, expected_agents,
        "every bundled agent artifact must deploy on a fresh target (#4724)"
    );
    assert!(result.skipped.is_empty());

    // The composed engineer carries inherited base content and no
    // `extends:` for Claude Code to interpret.
    let engineer = std::fs::read_to_string(paths.claude_agents_dir().join("engineer.md")).unwrap();
    assert!(engineer.contains("BASE-AGENT"));
    assert!(engineer.contains("BASE-ENGINEER"));
    assert!(engineer.contains("# Engineer"));
    assert!(!engineer.contains("extends:"));

    // The report formatter renders a composed-chain line.
    let lines = deploy_report_lines(&result, &paths.agent_source_dir());
    assert!(
        lines
            .iter()
            .any(|l| l.contains("engineer.md") && l.contains("composed:")),
        "lines = {lines:?}"
    );
}

#[test]
fn install_then_deploy_deploys_skills() {
    // Regression for #386: a fresh install must populate `.claude/skills/`
    // from the bundled skill sources, not leave it empty. Calls the SAME
    // multi-tier orchestrator `install()`'s skill step actually calls (PR
    // #2818 review, round 3) rather than the raw single-tier
    // `deploy_skills` — with no user-tier source present, the two are
    // equivalent, but this keeps the test aligned with the real call site.
    let dir = tempfile::tempdir().unwrap();
    let paths = trusty_mpm::core::paths::FrameworkPaths::under(dir.path());
    install_to(&paths, false).unwrap();
    let result = trusty_mpm::core::skill_tiers::deploy_all_skill_tiers(
        &paths.skill_source_dir(),
        &paths.user_skill_source_dir(),
        &paths.claude_skills_dir(),
        |_| true,
    )
    .unwrap()
    .stats;
    // The full /tm- skill portfolio deploys on first install: 21 skills total
    // — 19 /tm- portfolio skills (tm-circuit-breaker, tm-verification-protocols,
    // tm-tool-usage-guide, tm-git-file-tracking, tm-adr, tm-workflow,
    // tm-agent-architecture, tm-postmortem, tm-bug-reporting,
    // tm-teaching-templates, tm-ticketing,
    // tm-delegation-patterns, tm-session-management, tm-session-pause,
    // tm-session-resume, tm-init, tm-issues-prune, tm-cli-operations,
    // tm-slack) + tm-doctor + the tm overview skill
    // (tm-skills-portfolio epic: the `example-skill.md` placeholder and the
    // 11 mpm-* guidance skills no longer ship; the previously-orphaned
    // tm-doctor.md is now wired in; issue #2185 added tm-issues-prune; issue
    // #2321 added tm-cli-operations; issue #4447 added
    // tm-slack-canvas-delivery, replaced 1-for-1 by tm-slack, issue #4761) + 2 (issue
    // #2890: code-review-standards, contract-driven-testing — code-critic's
    // declared `skills:` dependencies; see
    // `tests_behavior_2890_skills_tests.rs` for the dedicated deep assertions
    // on those two, kept out of this file to stay under the 500-SLOC
    // production cap — this file, unlike its `_tests.rs`-suffixed siblings,
    // is NOT classified as a test file by the SLOC gate) + 93 (issue #2903,
    // skill-port batch 1: 25 upstream universal/ skill entry points + 68
    // references/*.md files carried alongside multi-file skills; see
    // `tests_behavior_2903_skills_tests.rs` for the dedicated deep
    // assertions, kept out of this file for the same SLOC-cap reason) + 7
    // (issue #2911: the `documentation-style` bundled skill — entry SKILL.md
    // plus 6 references/*.md files; see
    // `tests_behavior_2911_documentation_style_tests.rs` for the dedicated
    // deep assertions, kept out of this file for the same SLOC-cap reason)
    // + 7 (issue #2913: the `tm-capabilities` auto-generated harness catalog
    // — entry SKILL.md plus 5 generated + 1 hand-authored references/*.md
    // files; see `tests_behavior_generate_tests.rs` for the generator's own
    // coverage, kept out of this file for the same SLOC-cap reason) + 1
    // (rust-build-performance, per Bob directive 2026-07-17: a single
    // flat-file bundled skill declared by rust-engineer and tauri-engineer;
    // see `tests_behavior_rust_build_performance_tests.rs` for the dedicated
    // deploy-reachability assertion).
    // Issue #5202 retired tm-pr-workflow into tm-workflow: 22 - 1 = 21.
    // 21 + 2 + 93 + 7 + 7 + 1 = 131. See `bundle_tm_skills.rs`/
    // `bundle_tm_capabilities.rs`/`bundle.rs`
    // (CODE_REVIEW_STANDARDS, CONTRACT_DRIVEN_TESTING)/`bundle_all.rs::ALL`
    // for the authoritative list.
    // Stats report stems (no .md suffix) because each skill lands as
    // <dest>/<name>/SKILL.md to match Claude Code's native discovery format.
    for expected in [
        "tm-circuit-breaker",
        "tm-doctor",
        "tm-issues-prune",
        "tm-cli-operations",
        "tm-capabilities",
        "documentation-style",
    ] {
        assert!(
            result.deployed.contains(&expected.to_string()),
            "{expected} must be deployed; got {:?}",
            result.deployed
        );
    }
    assert_eq!(
        result.deployed.len(),
        132,
        "expected 132 skill files deployed (19 /tm- portfolio + tm-doctor + tm overview \
         + code-review-standards + contract-driven-testing + 93 skill-port batch-1 entries \
         + 7 documentation-style entries + 8 tm-capabilities entries (#4946 added \
         references/framework.md) + 1 rust-build-performance entry); got {:?}",
        result.deployed
    );
    assert!(result.skipped.is_empty());
    assert!(result.unchanged.is_empty());
    // Each skill must be deployed as a directory with SKILL.md inside.
    let deployed = paths
        .claude_skills_dir()
        .join("tm-circuit-breaker")
        .join("SKILL.md");
    assert!(
        deployed.is_file(),
        "expected skill at {}",
        deployed.display()
    );
    let lines = skill_report_lines(&result);
    assert!(
        lines.iter().any(|l| l.contains("tm-circuit-breaker")),
        "lines = {lines:?}"
    );
}

#[test]
fn cli_parses_optimizer_status() {
    let cli = Cli::try_parse_from(["trusty-mpm", "optimizer", "status"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Optimizer {
            action: OptimizerAction::Status
        }
    ));
}

#[test]
fn cli_parses_optimizer_set() {
    let cli = Cli::try_parse_from(["trusty-mpm", "optimizer", "set", "trim"]).unwrap();
    match cli.command.unwrap() {
        Command::Optimizer {
            action: OptimizerAction::Set { level },
        } => assert!(matches!(level, CliCompressionLevel::Trim)),
        other => panic!("expected optimizer set, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_events() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "events", "abc-123"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Events { id_or_name },
        } => assert_eq!(id_or_name, "abc-123"),
        other => panic!("expected session events, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_breakers() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "breakers"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Session {
            action: SessionAction::Breakers
        }
    ));
}

#[test]
fn cli_parses_session_pause() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "pause", "tmpm-quiet-falcon"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Pause { id_or_name, note },
        } => {
            assert_eq!(id_or_name, "tmpm-quiet-falcon");
            assert_eq!(note, None);
        }
        other => panic!("expected session pause, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_pause_with_note() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "session",
        "pause",
        "abc-123",
        "--note",
        "stepping away",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Pause { id_or_name, note },
        } => {
            assert_eq!(id_or_name, "abc-123");
            assert_eq!(note.as_deref(), Some("stepping away"));
        }
        other => panic!("expected session pause, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_resume() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "resume", "abc-123"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Resume { id_or_name },
        } => assert_eq!(id_or_name, "abc-123"),
        other => panic!("expected session resume, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_run() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "run", "abc-123", "help me"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action:
                SessionAction::Run {
                    id_or_name,
                    command,
                    summarize,
                },
        } => {
            assert_eq!(id_or_name, "abc-123");
            assert_eq!(command, "help me");
            assert!(!summarize);
        }
        other => panic!("expected session run, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_run_with_summarize() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "session",
        "run",
        "tmpm-abc",
        "help",
        "--summarize",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Run { summarize, .. },
        } => assert!(summarize),
        other => panic!("expected session run, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_output_defaults() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "output", "abc-123"]).unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action:
                SessionAction::Output {
                    id_or_name,
                    lines,
                    summarize,
                },
        } => {
            assert_eq!(id_or_name, "abc-123");
            assert_eq!(lines, 50);
            assert!(!summarize);
        }
        other => panic!("expected session output, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_output_with_lines() {
    let cli = Cli::try_parse_from([
        "trusty-mpm",
        "session",
        "output",
        "abc-123",
        "--lines",
        "120",
    ])
    .unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Output { lines, .. },
        } => assert_eq!(lines, 120),
        other => panic!("expected session output, got {other:?}"),
    }
}

#[test]
fn cli_parses_session_output_with_summarize() {
    let cli = Cli::try_parse_from(["trusty-mpm", "session", "output", "tmpm-abc", "--summarize"])
        .unwrap();
    match cli.command.unwrap() {
        Command::Session {
            action: SessionAction::Output { summarize, .. },
        } => assert!(summarize),
        other => panic!("expected session output, got {other:?}"),
    }
}

#[test]
fn compression_stats_line_skipped_when_uncompressed() {
    // A response with a null `compress_level` is raw output; no stats line.
    let body = serde_json::json!({
        "output": "raw",
        "compress_level": serde_json::Value::Null,
    });
    // The helper must not panic and must treat a null level as "no stats".
    assert!(
        body.get("compress_level")
            .and_then(|v| v.as_str())
            .is_none()
    );
    print_compression_stats(&body);
}

#[test]
fn compression_stats_line_printed_when_compressed() {
    // A response carrying a level and byte counts is exercised end-to-end;
    // the helper computes a percentage without panicking.
    let body = serde_json::json!({
        "output": "summary",
        "original_bytes": 4096,
        "compressed_bytes": 312,
        "compress_level": "summarise",
    });
    assert_eq!(
        body.get("compress_level").and_then(|v| v.as_str()),
        Some("summarise")
    );
    print_compression_stats(&body);
}

#[test]
fn cli_session_pause_requires_arg() {
    assert!(Cli::try_parse_from(["trusty-mpm", "session", "pause"]).is_err());
}

#[test]
fn cli_session_run_requires_command() {
    assert!(Cli::try_parse_from(["trusty-mpm", "session", "run", "abc-123"]).is_err());
}

#[test]
fn cli_parses_overseer_status() {
    let cli = Cli::try_parse_from(["trusty-mpm", "overseer", "status"]).unwrap();
    assert!(matches!(
        cli.command.unwrap(),
        Command::Overseer {
            action: OverseerAction::Status
        }
    ));
}

#[test]
fn event_summary_prefers_tool_field() {
    let payload = serde_json::json!({"tool": "Bash", "input": {"command": "ls"}});
    assert_eq!(event_summary(&payload), "tool=Bash");
}

#[test]
fn event_summary_truncates_long_payloads() {
    let payload = serde_json::json!({"k": "x".repeat(200)});
    let summary = event_summary(&payload);
    assert!(summary.chars().count() <= 61);
    assert!(summary.ends_with('\u{2026}'));
}