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
//! Coordinator: a cross-session activity layer for the TUI/GUI.
//!
//! Why: the operator wants one conversational surface that has visibility into
//! *every* active Claude Code session at once — "what's happening across my
//! sessions?" — and a way to route a command at a named session by prefix. The
//! daemon already owns the session registry and tmux capture, so the
//! coordinator is a thin assembly layer over them: it builds a trimmed activity
//! snapshot and either routes a prefixed command straight to a session or hands
//! the snapshot to the LLM chat assistant for a free-text answer.
//! What: [`CoordinatorContext`] is the snapshot; [`build_coordinator_context`]
//! assembles it from [`DaemonState`]; [`parse_session_prefix`] recognises an
//! `@prefix:` / `prefix:` routing prefix; [`coordinator_system_prompt`] renders
//! the snapshot into an LLM system prompt.
//! Test: `cargo test -p trusty-mpm-daemon coordinator` covers the prefix parser
//! and the system-prompt rendering without a tmux host or network.

use chrono::{DateTime, Utc};
use serde::Serialize;

use crate::core::session::SessionStatus;

use super::services::TmuxService;
use super::state::DaemonState;

/// Number of recent global events included in a coordinator snapshot.
const RECENT_EVENT_LIMIT: usize = 20;

/// Number of trailing pane lines captured per session for the snapshot.
const SESSION_OUTPUT_LINES: u32 = 20;

/// A trimmed snapshot of current session activity for LLM context.
///
/// Why: the LLM chat assistant needs a compact, structured view of what every
/// session is doing; a full registry dump would be too large and noisy.
/// What: the per-session summaries plus the last [`RECENT_EVENT_LIMIT`] global
/// hook events and the time the snapshot was built.
/// Test: `build_coordinator_context` is exercised by `context_builds_from_state`.
#[derive(Debug, Clone, Serialize)]
pub struct CoordinatorContext {
    /// Per-session activity summaries.
    pub sessions: Vec<SessionSummary>,
    /// The most recent global hook events (oldest first), capped at 20.
    pub recent_events: Vec<EventSummary>,
    /// When this snapshot was assembled.
    pub generated_at: DateTime<Utc>,
}

/// One session's activity summary inside a [`CoordinatorContext`].
///
/// Why: the coordinator and its LLM prompt need a flat, render-ready view of a
/// session — its name, a short routing prefix, status, and a recent-output
/// excerpt — without the full `Session` record.
/// What: identity fields plus the captured tail of the session's tmux pane.
/// Test: `parse_session_prefix` matches against the `name`/`prefix` fields.
#[derive(Debug, Clone, Serialize)]
pub struct SessionSummary {
    /// Session id (UUID string).
    pub id: String,
    /// tmux session name, e.g. `tm-aipowerranking-01`.
    pub name: String,
    /// Short routing prefix, e.g. `aipowerranking-01` (the managed prefix dropped).
    pub prefix: String,
    /// Working directory the session runs in.
    pub workdir: String,
    /// Lifecycle status as a word: `Active` / `Paused` / `Stopped` / ….
    pub status: String,
    /// Number of active delegations the session has running.
    pub active_delegations: u32,
    /// Last [`SESSION_OUTPUT_LINES`] lines captured from the session's pane.
    pub recent_output: Vec<String>,
    /// The latest daemon-cached LLM summary for this session, if one exists.
    ///
    /// Why: the sessions TUI renders a per-session summary bullet (DOC-16 §4.3)
    /// and must not pay for N fresh LLM calls per poll (#1275). This is the
    /// *cached* summary the activity monitor last produced for `/activity` — read
    /// synchronously, never inferred here. `None` when no summary exists yet or
    /// inference is unconfigured (the degraded placeholder is never surfaced, D1).
    /// What: an optional single-line summary string.
    /// Test: `context_summary_absent_without_cache`, `session_summary_serializes_new_fields`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_summary: Option<String>,
    /// Whether an inference call for this session is currently in flight.
    ///
    /// Why: the TUI blinks the session's bullet while it is actively summarizing
    /// (DOC-16 §3.3, D1). This is the honest in-progress signal — true only while
    /// a real classifier call runs, `false` otherwise (including when inference is
    /// unconfigured so no call ever starts).
    /// What: a boolean in-flight flag.
    /// Test: `context_summary_absent_without_cache`, `session_summary_serializes_new_fields`.
    #[serde(default)]
    pub summarizing: bool,
}

/// One hook event inside a [`CoordinatorContext`].
///
/// Why: the LLM prompt lists recent cross-session events; the full
/// `HookEventRecord` carries an opaque payload the prompt does not need.
/// What: the event's wire name, the originating session id, and the timestamp.
/// Test: covered by `context_builds_from_state`.
#[derive(Debug, Clone, Serialize)]
pub struct EventSummary {
    /// Originating session id (UUID string).
    pub session: String,
    /// Hook event wire name, e.g. `PreToolUse`.
    pub event: String,
    /// RFC3339 timestamp the daemon received the event.
    pub at: String,
}

/// Derive a short routing prefix from a tmux session name.
///
/// Why: operators address a session by a short word (e.g. `aipowerranking-01`
/// under the current `tm-<leaf>-NN` scheme, #1955), not its full
/// `tm-aipowerranking-01` tmux name; the prefix is that name with ONLY the
/// managed prefix dropped — the `-NN` serial is intentionally KEPT (not
/// stripped further) because it is what disambiguates multiple concurrent
/// sessions for the same project (`aipowerranking-01` vs `aipowerranking-02`);
/// dropping it would make [`parse_session_prefix`] unable to route between
/// them. A legacy `tmpm-<leaf>` name (no serial) still yields the bare leaf.
/// Delegates to [`crate::core::names::strip_managed_prefix`] so both the
/// current `tm-` scheme and legacy `tmpm-`/`trusty-mpm-` names strip
/// correctly.
/// What: strips whichever managed prefix `name` carries; otherwise returns the
/// name unchanged.
/// Test: `prefix_strips_managed_prefixes`.
fn derive_prefix(name: &str) -> String {
    crate::core::names::strip_managed_prefix(name).to_string()
}

/// Build a [`CoordinatorContext`] from the daemon's current state.
///
/// Why: the coordinator chat endpoint needs a fresh activity snapshot on every
/// request — the LLM answer is only as good as the context it is handed.
/// What: lists every session, derives a routing prefix and a status word for
/// each, and (for non-`Stopped` sessions) captures the last
/// [`SESSION_OUTPUT_LINES`] pane lines via [`TmuxService::capture`] — which
/// degrades to an empty list when tmux is absent. Enriches each session with the
/// daemon-cached `last_summary` and live `summarizing` flag read synchronously
/// from the shared [`ActivityMonitor`](crate::activity::monitor::ActivityMonitor)
/// sidecar — NO fresh LLM call is made here, so the per-poll cost stays O(sessions)
/// map lookups regardless of session count (#1275, DOC-16 §6.2). Also folds the
/// daemon's recent hook events down to [`EventSummary`] rows.
/// Test: `context_builds_from_state` (tmux-absent path),
/// `context_summary_absent_without_cache` (sidecar read), and the monitor-level
/// `cached_summary_reflects_llm_verdict` (the value the sidecar surfaces).
pub fn build_coordinator_context(state: &DaemonState) -> CoordinatorContext {
    // The activity monitor owns the per-session summary cache populated by the
    // `/activity` route. Reading its sidecar is a cheap, synchronous, no-network
    // lookup — exactly what a per-poll context build needs (it must NOT fan out
    // N LLM calls). Accessing it lazily constructs the shared monitor once.
    let monitor = state.activity_monitor();
    let sessions = state
        .list_sessions()
        .into_iter()
        .map(|session| {
            // Capturing a stopped session's pane is pointless — its tmux window
            // is gone — so only live sessions get an output excerpt.
            let recent_output = if session.status == SessionStatus::Stopped {
                Vec::new()
            } else {
                let raw = TmuxService::capture(&session, SESSION_OUTPUT_LINES);
                raw.lines().map(str::to_string).collect()
            };
            let session_id = session.id.0.to_string();
            SessionSummary {
                last_summary: monitor.cached_summary(&session_id),
                summarizing: monitor.is_summarizing(&session_id),
                id: session_id,
                name: session.tmux_name.clone(),
                prefix: derive_prefix(&session.tmux_name),
                workdir: session.workdir.clone(),
                status: session.status.to_string(),
                active_delegations: session.active_delegations,
                recent_output,
            }
        })
        .collect();

    let recent = state.recent_hook_events();
    let start = recent.len().saturating_sub(RECENT_EVENT_LIMIT);
    let recent_events = recent[start..]
        .iter()
        .map(|record| EventSummary {
            session: record.session.0.to_string(),
            event: record.event.wire_name().to_string(),
            at: record.at.to_rfc3339(),
        })
        .collect();

    CoordinatorContext {
        sessions,
        recent_events,
        generated_at: Utc::now(),
    }
}

/// Parse an `@prefix:` / `prefix:` session-routing prefix from user input.
///
/// Why: the coordinator lets the operator address one session directly — a
/// message that starts with `@aipowerranking:` (or the bare `aipowerranking:`)
/// is routed straight to that session's tmux pane, bypassing the LLM.
/// What: takes the text before the first `:` as a candidate prefix (a leading
/// `@` is stripped) and matches it case-insensitively against each session's
/// full tmux `name` or its short `prefix`. A bare (no `@`) prefix only matches
/// when it is unambiguous — exactly one session matches — so plain prose with a
/// stray colon is never misrouted. Returns `(session_tmux_name, remaining)` on
/// a match, `None` otherwise (no colon, empty prefix, or no/ambiguous match).
/// Test: `parses_at_prefix`, `parses_full_tmux_name`, `bare_prefix_unambiguous`,
/// `bare_prefix_ambiguous_is_none`, `no_colon_is_none`.
pub fn parse_session_prefix(input: &str, sessions: &[SessionSummary]) -> Option<(String, String)> {
    let trimmed = input.trim_start();
    let (head, rest) = trimmed.split_once(':')?;
    let had_at = head.starts_with('@');
    let candidate = head.trim_start_matches('@').trim();
    if candidate.is_empty() {
        return None;
    }
    let candidate_lc = candidate.to_lowercase();

    let matches: Vec<&SessionSummary> = sessions
        .iter()
        .filter(|s| {
            s.name.to_lowercase() == candidate_lc || s.prefix.to_lowercase() == candidate_lc
        })
        .collect();

    let session = match matches.as_slice() {
        [one] => *one,
        // Multiple sessions match a bare prefix: refuse to guess.
        _ if !had_at => return None,
        // An explicit `@` prefix with no (or an ambiguous) match also fails —
        // the operator named a session that does not uniquely exist.
        _ => return None,
    };

    Some((session.name.clone(), rest.trim().to_string()))
}

/// Render a [`CoordinatorContext`] into an LLM system prompt.
///
/// Why: the coordinator's free-text answers come from the LLM chat assistant;
/// the model can only reason about sessions it is told about, so the snapshot is
/// flattened into a prompt that lists every session (with its routing prefix
/// and a recent-output excerpt) and the recent global events.
/// What: returns a multi-line system prompt — a role preamble, one block per
/// session, the last 10 events, and the `@prefix` routing hint.
/// Test: `system_prompt_lists_sessions`, `system_prompt_handles_empty`.
pub fn coordinator_system_prompt(context: &CoordinatorContext) -> String {
    let mut prompt = String::from(
        "You are the trusty-mpm coordinator. You have visibility into all active \
Claude Code sessions.\n",
    );

    if context.sessions.is_empty() {
        prompt.push_str("\nThere are no active sessions right now.\n");
    } else {
        prompt.push_str("\nCurrent sessions:\n");
        for s in &context.sessions {
            prompt.push_str(&format!(
                "- {} (prefix @{}) — workdir {}, status {}, {} active delegation(s)\n",
                s.name, s.prefix, s.workdir, s.status, s.active_delegations,
            ));
            if !s.recent_output.is_empty() {
                // Keep the excerpt tight — the last 5 lines are enough signal.
                let start = s.recent_output.len().saturating_sub(5);
                for line in &s.recent_output[start..] {
                    prompt.push_str(&format!("    | {line}\n"));
                }
            }
        }
    }

    if !context.recent_events.is_empty() {
        prompt.push_str("\nRecent events:\n");
        let start = context.recent_events.len().saturating_sub(10);
        for e in &context.recent_events[start..] {
            prompt.push_str(&format!("- {} {} ({})\n", e.at, e.event, e.session));
        }
    }

    prompt.push_str(
        "\nAnswer questions about session activity, summarize what is happening, and \
help the user manage sessions. To send a command to a specific session, the user \
can prefix their message with @session-name (or the short prefix).\n",
    );
    prompt
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a `SessionSummary` for the parser tests.
    fn summary(name: &str) -> SessionSummary {
        SessionSummary {
            id: "00000000-0000-0000-0000-000000000000".to_string(),
            name: name.to_string(),
            prefix: derive_prefix(name),
            workdir: "/tmp/proj".to_string(),
            status: "Active".to_string(),
            active_delegations: 0,
            recent_output: Vec::new(),
            last_summary: None,
            summarizing: false,
        }
    }

    #[test]
    fn prefix_strips_managed_prefixes() {
        assert_eq!(derive_prefix("tm-aipowerranking-01"), "aipowerranking-01");
        // Legacy prefix (issue #1955) must still strip correctly.
        assert_eq!(derive_prefix("tmpm-aipowerranking"), "aipowerranking");
        assert_eq!(derive_prefix("frontend"), "frontend");
    }

    #[test]
    fn parses_at_prefix() {
        // `@prefix: msg` strips the `@`, matches the short prefix, and returns
        // the full tmux name plus the trimmed remainder.
        let sessions = [summary("tmpm-aipowerranking")];
        let parsed = parse_session_prefix("@aipowerranking: run the tests", &sessions);
        assert_eq!(
            parsed,
            Some((
                "tmpm-aipowerranking".to_string(),
                "run the tests".to_string()
            ))
        );
    }

    #[test]
    fn parses_full_tmux_name() {
        // The full `tmpm-…` tmux name also matches.
        let sessions = [summary("tmpm-aipowerranking")];
        let parsed = parse_session_prefix("@tmpm-aipowerranking: do X", &sessions);
        assert_eq!(
            parsed,
            Some(("tmpm-aipowerranking".to_string(), "do X".to_string()))
        );
    }

    #[test]
    fn bare_prefix_unambiguous() {
        // A bare (no `@`) prefix routes when exactly one session matches.
        let sessions = [summary("tmpm-aipowerranking"), summary("tmpm-other")];
        let parsed = parse_session_prefix("aipowerranking: status?", &sessions);
        assert_eq!(
            parsed,
            Some(("tmpm-aipowerranking".to_string(), "status?".to_string()))
        );
    }

    #[test]
    fn bare_prefix_ambiguous_is_none() {
        // Plain prose with a stray colon must not be misrouted: a bare prefix
        // that matches nothing yields None rather than guessing.
        let sessions = [summary("tmpm-aipowerranking")];
        assert_eq!(
            parse_session_prefix("note: this is just prose", &sessions),
            None
        );
    }

    #[test]
    fn at_prefix_unknown_session_is_none() {
        // An explicit `@` prefix naming a non-existent session also fails.
        let sessions = [summary("tmpm-aipowerranking")];
        assert_eq!(parse_session_prefix("@ghost: hello", &sessions), None);
    }

    #[test]
    fn no_colon_is_none() {
        let sessions = [summary("tmpm-aipowerranking")];
        assert_eq!(
            parse_session_prefix("just a question with no prefix", &sessions),
            None
        );
    }

    #[test]
    fn empty_prefix_is_none() {
        let sessions = [summary("tmpm-aipowerranking")];
        assert_eq!(parse_session_prefix("@: hello", &sessions), None);
        assert_eq!(parse_session_prefix(": hello", &sessions), None);
    }

    #[test]
    fn system_prompt_lists_sessions() {
        let mut s = summary("tmpm-aipowerranking");
        s.recent_output = vec!["building…".to_string(), "tests passed".to_string()];
        let context = CoordinatorContext {
            sessions: vec![s],
            recent_events: Vec::new(),
            generated_at: Utc::now(),
        };
        let prompt = coordinator_system_prompt(&context);
        assert!(prompt.contains("tmpm-aipowerranking"));
        assert!(prompt.contains("prefix @aipowerranking"));
        assert!(prompt.contains("tests passed"));
        assert!(prompt.contains("@session-name"));
    }

    #[test]
    fn system_prompt_handles_empty() {
        let context = CoordinatorContext {
            sessions: Vec::new(),
            recent_events: Vec::new(),
            generated_at: Utc::now(),
        };
        let prompt = coordinator_system_prompt(&context);
        assert!(prompt.contains("no active sessions"));
    }

    #[test]
    fn context_builds_from_state() {
        // With no sessions registered the snapshot is empty but well-formed;
        // this also exercises the tmux-absent capture path.
        let state = DaemonState::new();
        let context = build_coordinator_context(&state);
        assert!(context.sessions.is_empty());
        assert!(context.recent_events.is_empty());
    }

    /// Construct a minimal Active session for context-builder tests.
    ///
    /// Why: the coordinator tests need a registered session without depending on
    /// the private `state::tests` helper.
    /// What: a Tmux-model session with an Active status.
    /// Test: used by `context_summary_absent_without_cache`.
    fn active_session() -> crate::core::session::Session {
        use crate::core::session::{ControlModel, Session, SessionId, SessionStatus};
        let mut s = Session::new(SessionId::new(), "/tmp/p", ControlModel::Tmux, None);
        s.tmux_name = "tmpm-demo".to_string();
        s.status = SessionStatus::Active;
        s
    }

    #[test]
    fn context_summary_absent_without_cache() {
        // A registered session with no prior activity check has no cached
        // summary and is not summarizing — the regression-safe default that an
        // unconfigured-inference daemon also produces (D1). This also proves
        // build_coordinator_context reads the shared monitor sidecar without
        // panicking and without a fresh LLM call.
        let state = DaemonState::new();
        state.register_session(active_session());

        let context = build_coordinator_context(&state);
        assert_eq!(context.sessions.len(), 1);
        assert_eq!(context.sessions[0].last_summary, None);
        assert!(!context.sessions[0].summarizing);
    }

    #[test]
    fn session_summary_serializes_new_fields() {
        // When a summary is present it serializes; when absent it is skipped, and
        // `summarizing` always serializes (defaulting to false).
        let mut s = summary("tmpm-demo");
        s.last_summary = Some("Refactoring the parser".to_string());
        s.summarizing = true;
        let json = serde_json::to_string(&s).expect("serialize");
        assert!(json.contains("\"last_summary\":\"Refactoring the parser\""));
        assert!(json.contains("\"summarizing\":true"));

        // Absent summary is skipped from the wire (keeps the payload tight).
        let bare = summary("tmpm-demo");
        let bare_json = serde_json::to_string(&bare).expect("serialize");
        assert!(!bare_json.contains("last_summary"));
        assert!(bare_json.contains("\"summarizing\":false"));
    }
}