trusty-mpm 1.0.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
//! Telegram-specific rendering of [`CommandResult`].
//!
//! Why: the executor returns a structured, UI-agnostic [`CommandResult`]; the
//! Telegram bot must turn that into HTML message text and, for the session
//! list, an inline keyboard. Keeping the rendering pure (no network, no
//! teloxide runtime) makes it unit-testable.
//! What: [`TelegramFormatter::format`] produces the HTML body and
//! [`TelegramFormatter::keyboard_for`] the optional inline keyboard.
//! Test: `cargo test -p trusty-mpm-telegram` covers each variant's rendering.

use crate::client::{CommandResult, DiscoveredProjectSummary, HealthReport, ManagedSessionView};
use teloxide::types::{InlineKeyboardButton, InlineKeyboardMarkup};

mod fleet;
pub use fleet::format_fleet_by_project;

#[cfg(test)]
mod tests;

/// How many characters of a session id to show in chat output.
///
/// Why: full UUIDs are unreadable on a phone; the first 8 chars disambiguate in
/// practice while keeping messages compact.
const SHORT_ID_LEN: usize = 8;

/// Renders [`CommandResult`]s into Telegram HTML messages and keyboards.
///
/// Why: the bot's message handler stays thin — it executes a command and hands
/// the result here for presentation.
/// What: a stateless formatter; both methods are associated functions.
/// Test: the `format_*` tests in `tests.rs`.
pub struct TelegramFormatter;

impl TelegramFormatter {
    /// Render a [`CommandResult`] into an HTML message body.
    ///
    /// Why: every command's reply text is produced here so presentation is
    /// consistent and testable. All dynamic / daemon-sourced text is run through
    /// [`html_escape`] before interpolation so `ParseMode::Html` never encounters
    /// bare `<`, `>`, or `&` characters — including the `<arg>` placeholders in
    /// `CommandResult::Help` that previously caused Telegram to silently drop the
    /// reply (issue #1514).
    /// What: matches each variant and returns an HTML-formatted string suitable
    /// for teloxide's `ParseMode::Html`. Intentional HTML tags (e.g. `<b>`,
    /// `<code>`, `<pre>`) are written as literals; user/daemon-sourced content is
    /// always HTML-escaped before insertion.
    /// Test: `format_sessions_*`, `pair_code_command_formats_correctly`,
    /// `help_escapes_angle_bracket_placeholders`, etc.
    pub fn format(result: &CommandResult) -> String {
        match result {
            CommandResult::Sessions(sessions) => {
                if sessions.is_empty() {
                    return "No active sessions.".to_string();
                }
                let mut text = String::from("<b>trusty-mpm sessions</b>\n");
                for s in sessions {
                    let dot = if s.status.eq_ignore_ascii_case("active") {
                        "🟢"
                    } else {
                        "🔴"
                    };
                    text.push_str(&format!(
                        "\n{dot} <code>{}</code> — {}\n  📁 <code>{}</code>\n",
                        short_id(&s.id),
                        s.status,
                        s.workdir,
                    ));
                }
                text
            }
            CommandResult::SessionDetail { id, events, .. } => {
                if events.is_empty() {
                    format!("Session {id}: no recent events")
                } else {
                    let lines = events
                        .iter()
                        .map(|e| format!("• {e}"))
                        .collect::<Vec<_>>()
                        .join("\n");
                    format!("<b>Session {}</b>\n{lines}", short_id(id))
                }
            }
            CommandResult::OverseerStatus {
                enabled,
                handler,
                decisions,
            } => format!(
                "<b>Overseer Status</b>\nHandler: <code>{handler}</code>\nEnabled: {}\n\
                 Recent decisions: allow ({}), block ({}), flag ({})",
                if *enabled { "✅" } else { "❌" },
                decisions.allow,
                decisions.block,
                decisions.flag,
            ),
            CommandResult::TmuxSessions(sessions) => {
                if sessions.is_empty() {
                    return "No tmux sessions found.".to_string();
                }
                let lines = sessions
                    .iter()
                    .map(|s| {
                        let tag = if s.managed {
                            "🟢 managed"
                        } else {
                            "⚪ external"
                        };
                        format!("• <code>{}</code> — {tag}", s.name)
                    })
                    .collect::<Vec<_>>()
                    .join("\n");
                format!("<b>tmux sessions</b>\n{lines}")
            }
            CommandResult::DiscoveredProjects(projects) => format_discovered_projects(projects),
            CommandResult::Adopted { session } => {
                format!("✅ Adopted tmux session <code>{session}</code> for oversight")
            }
            CommandResult::Discovered { count } => {
                if *count == 0 {
                    "🔍 No new Claude Code tmux sessions found".to_string()
                } else {
                    format!("🔍 Discovered and adopted {count} Claude Code tmux session(s)")
                }
            }
            CommandResult::ProjectRegistered { path } => {
                format!("✅ Registered project <code>{path}</code>")
            }
            CommandResult::ConfigAnalysis {
                project,
                recommendations,
            } => {
                if recommendations.is_empty() {
                    format!(
                        "<b>Claude config</b> for <code>{project}</code>\n\
                         No recommendations — config looks healthy."
                    )
                } else {
                    let lines = recommendations
                        .iter()
                        .map(|r| format!("• {}", r.message))
                        .collect::<Vec<_>>()
                        .join("\n");
                    format!("<b>Claude config</b> for <code>{project}</code>\n{lines}")
                }
            }
            CommandResult::Snapshot { session, output } => {
                let tail: Vec<&str> = output.lines().rev().take(50).collect();
                let lines = tail.into_iter().rev().collect::<Vec<_>>().join("\n");
                if lines.is_empty() {
                    format!("Session <code>{session}</code>: empty pane")
                } else {
                    format!(
                        "<b>Snapshot: {session}</b>\n<pre>{}</pre>",
                        html_escape(&lines)
                    )
                }
            }
            CommandResult::Killed { session_id } => {
                format!("🗑️ Session {} killed", short_id(session_id))
            }
            CommandResult::CommandSent { session, output } => {
                if output.trim().is_empty() {
                    format!("📨 Sent to <code>{session}</code> — no output captured")
                } else {
                    format!("<b>📨 {session}</b>\n<pre>{}</pre>", html_escape(output))
                }
            }
            CommandResult::ChatReply { reply } => html_escape(reply),
            CommandResult::Approved { session_id } => {
                format!("✅ Permission approved for session {session_id}")
            }
            CommandResult::Denied { session_id } => {
                format!("❌ Permission denied for session {session_id}")
            }
            CommandResult::PairCode {
                code,
                expires_in_seconds,
            } => format!(
                "<b>Pairing code:</b> <code>{code}</code>\n\
                 Expires in {} minutes\n\nSend to your bot: <code>/pair {code}</code>",
                expires_in_seconds / 60,
            ),
            CommandResult::PairSuccess { chat_info } => {
                format!(
                    "✅ Successfully paired! This chat ({chat_info}) is now registered for alerts."
                )
            }
            CommandResult::PairState { paired } => {
                if *paired {
                    "✅ Bot is paired with this daemon. Type /help to see commands.".to_string()
                } else {
                    "👋 Welcome to trusty-mpm bot! To pair this bot with your daemon, run \
                     `tm pair` on your server, then send the code with /pair <code>"
                        .to_string()
                }
            }
            CommandResult::AlertSubscriptions(lines) => {
                format!("<b>Alert subscription</b>\n{}", lines.join("\n"))
            }
            CommandResult::Doctor(report) => format_doctor_report(report),
            CommandResult::SessionStarted {
                session,
                workdir,
                deployed,
            } => {
                let mode = if *deployed {
                    "launched (framework deployed)"
                } else {
                    "connected (no deployment)"
                };
                format!("✅ Session <b>{session}</b> {mode}\n<code>{workdir}</code>")
            }
            CommandResult::ManagedSpawned {
                id,
                name,
                state,
                runtime,
                attach_cmd,
            } => format!(
                "✅ Spawned <b>{}</b> (<code>{}</code>) [{}] runtime={}\n\
                 attach: <code>{}</code>",
                html_escape(name),
                short_id(id),
                html_escape(state),
                html_escape(runtime),
                html_escape(attach_cmd),
            ),
            // #1433: adoption mirrors a spawn's identity shape; render it the same
            // way (different verb prose). Added in the session-adopt branch — the
            // Telegram engineer may relocate/restyle this arm on rebase.
            CommandResult::ManagedAdopted {
                id,
                name,
                state,
                cwd,
                runtime,
                attach_cmd,
            } => format!(
                "✅ Adopted <b>{}</b> (<code>{}</code>) [{}] runtime={}\n\
                 cwd: <code>{}</code>\n\
                 attach: <code>{}</code>",
                html_escape(name),
                short_id(id),
                html_escape(state),
                html_escape(runtime),
                html_escape(cwd),
                html_escape(attach_cmd),
            ),
            CommandResult::ManagedSessions(sessions) => format_managed_sessions(sessions),
            CommandResult::ManagedFleet(fleet) => format_fleet_by_project(fleet),
            CommandResult::ManagedSession(view) => format_managed_session(view),
            CommandResult::ManagedSent { id, tmux_name } => {
                format!(
                    "📨 Sent to managed <code>{}</code> ({})",
                    html_escape(tmux_name),
                    short_id(id)
                )
            }
            CommandResult::ManagedAnswered {
                id,
                answer,
                tmux_name,
            } => format!(
                "✅ Answered decision on <code>{}</code> ({}) → <code>{}</code>",
                html_escape(tmux_name),
                short_id(id),
                html_escape(answer),
            ),
            CommandResult::ManagedActivity {
                id,
                state,
                summary,
                pending_decision,
                ..
            } => {
                let decision = pending_decision
                    .as_deref()
                    .map(|d| format!("\n⚠️ pending: {}", html_escape(d)))
                    .unwrap_or_default();
                format!(
                    "<b>Activity {} [{}]</b>\n{}{decision}",
                    short_id(id),
                    html_escape(state),
                    html_escape(summary),
                )
            }
            CommandResult::ManagedAttachCmd { id, attach_cmd } => {
                format!(
                    "<b>Attach {}</b>\n<code>{}</code>",
                    short_id(id),
                    html_escape(attach_cmd),
                )
            }
            CommandResult::ManagedLifecycle {
                id,
                name,
                state,
                action,
            } => format!(
                "✅ {} ({}) {} → {}",
                html_escape(name),
                short_id(id),
                html_escape(action),
                html_escape(state),
            ),
            CommandResult::Help(text) => html_escape(text),
            CommandResult::Health(report) => format_health(report),
            CommandResult::Error(msg) => format!("❌ {}", html_escape(msg)),
        }
    }

    /// Build the inline keyboard for a [`CommandResult`], if it warrants one.
    ///
    /// Why: several lists decorate their rows with action buttons — `/sessions`
    /// gets `[Status] [Approve] [Deny]`, `/projects` gets a `[Set Active]`
    /// button per project, and `/tmux` gets an `[Adopt]` button for each
    /// unmanaged session.
    /// What: returns one button row per item for the list variants above,
    /// `None` for every other variant. Callback data is `verb:arg` so the
    /// callback handler can route the tap.
    /// Test: `keyboard_for_sessions_has_rows`, `keyboard_for_projects_has_rows`,
    /// `keyboard_for_tmux_adopts_external`, `keyboard_for_help_is_none`.
    pub fn keyboard_for(result: &CommandResult) -> Option<InlineKeyboardMarkup> {
        match result {
            CommandResult::Sessions(sessions) if !sessions.is_empty() => {
                let rows: Vec<Vec<InlineKeyboardButton>> = sessions
                    .iter()
                    .map(|s| {
                        vec![
                            InlineKeyboardButton::callback("📋 Status", format!("status:{}", s.id)),
                            InlineKeyboardButton::callback(
                                "✅ Approve",
                                format!("approve:{}", s.id),
                            ),
                            InlineKeyboardButton::callback("❌ Deny", format!("deny:{}", s.id)),
                        ]
                    })
                    .collect();
                Some(InlineKeyboardMarkup::new(rows))
            }
            CommandResult::DiscoveredProjects(projects) if !projects.is_empty() => {
                let rows: Vec<Vec<InlineKeyboardButton>> = projects
                    .iter()
                    .filter(|p| callback_fits(&p.path))
                    .map(|p| {
                        vec![InlineKeyboardButton::callback(
                            format!("📁 Set Active — {}", project_basename(&p.path)),
                            format!("setproj:{}", p.path),
                        )]
                    })
                    .collect();
                if rows.is_empty() {
                    None
                } else {
                    Some(InlineKeyboardMarkup::new(rows))
                }
            }
            CommandResult::TmuxSessions(sessions) => {
                let rows: Vec<Vec<InlineKeyboardButton>> = sessions
                    .iter()
                    .filter(|s| !s.managed && callback_fits(&s.name))
                    .map(|s| {
                        vec![InlineKeyboardButton::callback(
                            format!("➕ Adopt — {}", s.name),
                            format!("adopt:{}", s.name),
                        )]
                    })
                    .collect();
                if rows.is_empty() {
                    None
                } else {
                    Some(InlineKeyboardMarkup::new(rows))
                }
            }
            // `/fleet` and `/get` decorate each session with a `🎯 Focus` button
            // so a tap focuses it (the "session click" of TELUI-6, #1440).
            CommandResult::ManagedFleet(fleet) => fleet::focus_keyboard(fleet),
            CommandResult::ManagedSession(view) => {
                fleet::session_focus_keyboard(&view.id, &view.name)
            }
            _ => None,
        }
    }
}

/// Render a discovered-project list as a Telegram HTML message body.
///
/// Why: the `/projects` command lists projects mined from `~/.claude/projects/`;
/// keeping the rendering as a free function lets it be unit-tested and reused.
/// What: returns a placeholder line when the list is empty, otherwise one line
/// per project showing the path, recorded session count, and last-used date.
/// Test: `format_discovered_projects_lists_each`, `format_discovered_projects_empty`.
pub fn format_discovered_projects(projects: &[DiscoveredProjectSummary]) -> String {
    if projects.is_empty() {
        return "No projects discovered in Claude Code config.".to_string();
    }
    let mut text = String::from("<b>Discovered projects</b>\n");
    for p in projects {
        let last = p
            .last_session
            .as_deref()
            .map(|s| s.split('T').next().unwrap_or(s).to_string())
            .unwrap_or_else(|| "never".to_string());
        text.push_str(&format!(
            "\n📁 <code>{}</code>\n  {} session(s) · last used {last}\n",
            p.path, p.session_count,
        ));
    }
    text
}

/// Render a managed session-manager session list as a Telegram HTML body.
///
/// Why: `managed-list` reports the managed fleet; keeping the rendering a free
/// function makes it unit-testable and reusable.
/// What: a placeholder when empty, else one line per session: state dot, short
/// id, name, and a pending-decision flag when blocked.
/// Test: `format_managed_sessions_lists_each`.
pub fn format_managed_sessions(sessions: &[ManagedSessionView]) -> String {
    if sessions.is_empty() {
        return "No managed sessions.".to_string();
    }
    let mut text = String::from("<b>managed sessions</b>\n");
    for s in sessions {
        let flag = if s.pending_decision.is_some() {
            " ⚠️"
        } else {
            ""
        };
        text.push_str(&format!(
            "\n• <code>{}</code> {} [{}]{flag}",
            short_id(&s.id),
            html_escape(&s.name),
            html_escape(&s.state),
        ));
    }
    text
}

/// Render one managed session's detail as a Telegram HTML body.
///
/// Why: `managed-get` shows a single session's full record on a phone.
/// What: the name, state, workspace/repo/branch when present, and any pending
/// decision with its proposed default.
/// Test: `format_managed_session_renders_fields`.
pub fn format_managed_session(view: &ManagedSessionView) -> String {
    let mut text = format!(
        "<b>{}</b> (<code>{}</code>) [{}]",
        html_escape(&view.name),
        short_id(&view.id),
        html_escape(&view.state),
    );
    if let Some(ws) = &view.workspace_path {
        text.push_str(&format!("\n📁 <code>{}</code>", html_escape(ws)));
    }
    if let Some(repo) = &view.repo_url {
        let branch = view.branch.as_deref().unwrap_or("");
        text.push_str(&format!(
            "\n🔗 {} {}",
            html_escape(repo),
            html_escape(branch)
        ));
    }
    if let Some(d) = &view.pending_decision {
        let def = view.proposed_default.as_deref().unwrap_or("");
        text.push_str(&format!(
            "\n⚠️ pending: {} (default: <code>{}</code>)",
            html_escape(d),
            html_escape(def),
        ));
    }
    text
}

/// Render a [`DoctorReport`] as a Telegram HTML message body.
///
/// Why: the `/doctor` command's diagnostic must be readable on a phone — one
/// emoji-tagged line per check plus an overall verdict.
/// What: returns a heading, one `<icon> <name> — <message>` line per check, and
/// a final overall-status line.
/// Test: `format_doctor_report_lists_each_check`.
fn format_doctor_report(report: &crate::client::DoctorReport) -> String {
    let mut text = String::from("<b>trusty-mpm doctor</b>\n");
    for check in &report.checks {
        text.push_str(&format!(
            "\n{} <b>{}</b> — {}",
            status_icon(check.status),
            html_escape(&check.name),
            html_escape(&check.message),
        ));
    }
    text.push_str(&format!(
        "\n\n{} <b>overall: {}</b>",
        status_icon(report.overall),
        status_word(report.overall),
    ));
    text
}

/// Render a [`HealthReport`] as a glanceable Telegram health summary.
///
/// Why: the `/health` reply must read at a glance on a phone — daemon up/down
/// first, then catalog freshness and a one-line fleet summary.
/// What: leads with a ✅/❌ liveness line (using `reachable`/`status`); when the
/// daemon is up, appends the catalog-freshness line and the managed fleet counts
/// (total + how many are blocked on a decision). A down daemon renders just the
/// liveness line — no fleet (which would all be zero/misleading).
/// Test: `format_health_up_and_down` in `tests.rs`.
fn format_health(report: &HealthReport) -> String {
    if !report.reachable {
        return format!(
            "❌ <b>daemon unreachable</b>\n<code>{}</code>",
            html_escape(&report.url),
        );
    }
    let catalog = if report.catalog_unknown {
        "catalog: never synced"
    } else if report.catalog_stale {
        "catalog: ⚠️ updates available"
    } else {
        "catalog: up to date"
    };
    format!(
        "✅ <b>daemon {}</b>\n<code>{}</code>\n{}\nfleet: {} session(s), {} awaiting a decision",
        html_escape(&report.status),
        html_escape(&report.url),
        catalog,
        report.managed_total,
        report.managed_pending_decisions,
    )
}

/// The emoji icon for a doctor [`CheckStatus`](crate::core::doctor::CheckStatus).
///
/// Why: the `/doctor` message marks each check with a glanceable status symbol.
/// What: `Ok → ✅`, `Warn → ⚠️`, `Fail → ❌`.
/// Test: covered by `format_doctor_report_lists_each_check`.
fn status_icon(status: crate::core::doctor::CheckStatus) -> &'static str {
    use crate::core::doctor::CheckStatus;
    match status {
        CheckStatus::Ok => "✅",
        CheckStatus::Warn => "⚠️",
        CheckStatus::Fail => "❌",
    }
}

/// A one-word label for a doctor [`CheckStatus`](crate::core::doctor::CheckStatus).
///
/// Why: the overall verdict reads better with a word than a bare icon.
/// What: `Ok → "healthy"`, `Warn → "warnings"`, `Fail → "failed"`.
/// Test: covered by `format_doctor_report_lists_each_check`.
fn status_word(status: crate::core::doctor::CheckStatus) -> &'static str {
    use crate::core::doctor::CheckStatus;
    match status {
        CheckStatus::Ok => "healthy",
        CheckStatus::Warn => "warnings",
        CheckStatus::Fail => "failed",
    }
}

/// True when a string fits within Telegram's 64-byte callback-data budget.
///
/// Why: Telegram rejects inline-keyboard callback data over 64 bytes; a `verb:`
/// prefix (≤8 bytes) plus the argument must stay under the limit, so a button
/// is omitted rather than crashing the bot when the argument is too long.
/// What: returns true when `arg`'s byte length leaves room for the prefix.
/// Test: covered by `keyboard_for_projects_has_rows`.
fn callback_fits(arg: &str) -> bool {
    arg.len() <= 55
}

/// Extract the final path component for a compact button label.
///
/// Why: a full project path is too long for an inline-keyboard button label;
/// the directory name alone identifies the project at a glance.
/// What: returns the last `/`-separated component, or the whole string when it
/// has no separator.
/// Test: covered by `keyboard_for_projects_has_rows`.
fn project_basename(path: &str) -> &str {
    path.rsplit('/')
        .next()
        .filter(|s| !s.is_empty())
        .unwrap_or(path)
}

/// Shorten a session id for compact chat display.
///
/// Why: full UUIDs do not fit comfortably on a phone screen.
/// What: returns the first [`SHORT_ID_LEN`] chars plus an ellipsis, or the id
/// unchanged when already short.
/// Test: `short_id_truncates_long_ids`.
pub(crate) fn short_id(id: &str) -> String {
    if id.len() > SHORT_ID_LEN {
        format!("{}…", &id[..SHORT_ID_LEN])
    } else {
        id.to_string()
    }
}

/// Escape the three HTML-significant characters for teloxide's HTML parse mode.
///
/// Why: snapshot output is arbitrary terminal text; un-escaped `<`/`>`/`&`
/// would break the message or be silently dropped by Telegram.
/// What: replaces `&`, `<`, `>` with their HTML entities.
/// Test: covered indirectly by the snapshot formatting test.
pub fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}