trusty-mpm 0.19.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
//! Unit tests for the Slack adapter's pure logic.
//!
//! Why: the adapter's correctness-critical pieces — Socket-Mode envelope parsing,
//! the bot-message guard (no reply loops), the rolling-history cap, the action
//! footer, and dotenv token resolution — are all pure and must be tested without
//! a live Slack socket or the daemon (the live WebSocket loop is deferred to a
//! real Slack app; see the PR body).
//! What: covers `parse_envelope`, `ack_frame`, `record_chat_turn`,
//! `action_footer`, and `resolve_token`.
//! Test: this IS the test module.

use super::*;

#[test]
fn parse_envelope_slash_command() {
    let raw = r#"{
        "type": "slash_commands",
        "envelope_id": "env-1",
        "payload": {
            "command": "/fleet",
            "text": "",
            "channel_id": "C123"
        }
    }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::SlashCommand {
            envelope_id: "env-1".into(),
            command: "/fleet".into(),
            text: String::new(),
            channel: "C123".into(),
        }
    );
}

#[test]
fn parse_envelope_slash_command_with_text() {
    let raw = r#"{
        "type": "slash_commands",
        "envelope_id": "env-2",
        "payload": { "command": "/msend", "text": "sess-1 build now", "channel_id": "C9" }
    }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::SlashCommand {
            envelope_id: "env-2".into(),
            command: "/msend".into(),
            text: "sess-1 build now".into(),
            channel: "C9".into(),
        }
    );
}

#[test]
fn parse_envelope_message() {
    let raw = r#"{
        "type": "events_api",
        "envelope_id": "env-3",
        "payload": {
            "event": { "type": "message", "text": "spin up a session", "channel": "C7", "user": "U1" }
        }
    }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::Message {
            envelope_id: "env-3".into(),
            text: "spin up a session".into(),
            channel: "C7".into(),
        }
    );
}

#[test]
fn parse_envelope_ignores_bot_message() {
    // A message carrying a bot_id is the bot's own post — ignore it (no reply
    // loops) but still surface the envelope id so the loop ACKs it.
    let raw = r#"{
        "type": "events_api",
        "envelope_id": "env-4",
        "payload": {
            "event": { "type": "message", "text": "hi", "channel": "C7", "bot_id": "B1" }
        }
    }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::Ignored {
            envelope_id: Some("env-4".into())
        }
    );
}

#[test]
fn parse_envelope_ignores_subtype_bot_message() {
    let raw = r#"{
        "type": "events_api",
        "envelope_id": "env-5",
        "payload": {
            "event": { "type": "message", "subtype": "bot_message", "text": "hi", "channel": "C7" }
        }
    }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::Ignored {
            envelope_id: Some("env-5".into())
        }
    );
}

#[test]
fn parse_envelope_ignores_empty_message() {
    let raw = r#"{
        "type": "events_api",
        "envelope_id": "env-6",
        "payload": { "event": { "type": "message", "text": "   ", "channel": "C7" } }
    }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::Ignored {
            envelope_id: Some("env-6".into())
        }
    );
}

#[test]
fn parse_envelope_hello_is_ignored() {
    // The `hello` envelope (sent on connect) needs no ACK and no reply.
    let raw = r#"{ "type": "hello" }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::Ignored { envelope_id: None }
    );
}

#[test]
fn parse_envelope_disconnect_surfaces_reason() {
    // A `disconnect` envelope now surfaces its reason so the loop can classify it
    // (permanent → stop, transient → reconnect) rather than silently ignoring it.
    let raw = r#"{ "type": "disconnect", "reason": "refresh_requested" }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::Disconnect {
            reason: "refresh_requested".into()
        }
    );
    // A reason-less disconnect surfaces an empty reason (classified transient).
    let raw = r#"{ "type": "disconnect" }"#;
    assert_eq!(
        parse_envelope(raw),
        SlackEvent::Disconnect {
            reason: String::new()
        }
    );
}

#[test]
fn classify_disconnect_reason_permanent_vs_transient() {
    // Permanent: the connection can never be re-established / creds are dead.
    for reason in [
        "app_deactivated",
        "invalid_auth",
        "account_inactive",
        "token_revoked",
        "token_expired",
        "not_authed",
        "missing_scope",
        "no_permission",
    ] {
        assert_eq!(
            classify_disconnect_reason(reason),
            DisconnectKind::Permanent,
            "expected `{reason}` to be permanent",
        );
    }
    // Permanent reasons match case-insensitively and inside a wrapped error string
    // (e.g. the `apps.connections.open failed: …` context).
    assert_eq!(
        classify_disconnect_reason("apps.connections.open failed: INVALID_AUTH"),
        DisconnectKind::Permanent
    );
    // Transient: routine recycles and unknown reasons reconnect with backoff.
    for reason in [
        "refresh_requested",
        "warning",
        "link_disabled",
        "",
        "socket gone",
    ] {
        assert_eq!(
            classify_disconnect_reason(reason),
            DisconnectKind::Transient,
            "expected `{reason}` to be transient",
        );
    }
}

#[test]
fn next_backoff_doubles_and_caps() {
    use std::time::Duration;
    let cap = Duration::from_secs(60);
    // Doubles below the cap.
    assert_eq!(
        next_backoff(Duration::from_secs(2), cap),
        Duration::from_secs(4)
    );
    assert_eq!(
        next_backoff(Duration::from_secs(4), cap),
        Duration::from_secs(8)
    );
    // Saturates at the cap and never exceeds it.
    assert_eq!(next_backoff(Duration::from_secs(40), cap), cap);
    assert_eq!(next_backoff(cap, cap), cap);
    // Never overflows near MAX.
    assert_eq!(next_backoff(Duration::MAX, cap), cap);
}

#[test]
fn parse_envelope_garbage_is_ignored() {
    assert_eq!(
        parse_envelope("not json"),
        SlackEvent::Ignored { envelope_id: None }
    );
}

#[test]
fn ack_frame_shape() {
    assert_eq!(ack_frame("env-1"), r#"{"envelope_id":"env-1"}"#);
}

#[test]
fn envelope_id_of_extracts_each_variant() {
    assert_eq!(
        envelope_id_of(&SlackEvent::SlashCommand {
            envelope_id: "a".into(),
            command: "/x".into(),
            text: String::new(),
            channel: "C".into(),
        }),
        Some("a".to_string())
    );
    assert_eq!(
        envelope_id_of(&SlackEvent::Message {
            envelope_id: "b".into(),
            text: "hi".into(),
            channel: "C".into(),
        }),
        Some("b".to_string())
    );
    assert_eq!(
        envelope_id_of(&SlackEvent::Ignored {
            envelope_id: Some("c".into())
        }),
        Some("c".to_string())
    );
    assert_eq!(
        envelope_id_of(&SlackEvent::Ignored { envelope_id: None }),
        None
    );
}

#[test]
fn record_chat_turn_caps_history() {
    let mut entry: Vec<ChatMessage> = Vec::new();
    // Each call adds a user + assistant turn (2 messages), so pushing
    // MAX_CHAT_HISTORY_TURNS full pairs writes 2*MAX messages — strictly MORE
    // than the cap. This guarantees the test fails if the cap were removed.
    let turns = MAX_CHAT_HISTORY_TURNS;
    let messages_pushed = 2 * turns;
    for i in 0..turns {
        record_chat_turn(&mut entry, &format!("u{i}"), &format!("a{i}"));
    }
    assert!(
        messages_pushed > MAX_CHAT_HISTORY_TURNS,
        "sanity: we must push MORE than the cap so this test is not vacuous"
    );
    // EXACT equality: the length is clamped precisely to the cap, not merely <=.
    assert_eq!(entry.len(), MAX_CHAT_HISTORY_TURNS);
    // The oldest non-evicted message: we pushed [u0,a0,...,u{N-1},a{N-1}] (2N
    // msgs) and drained the front 2N-N = N messages, so the first survivor is
    // the user turn at index N/2 (= MAX_CHAT_HISTORY_TURNS/2).
    let first_retained_turn = MAX_CHAT_HISTORY_TURNS / 2;
    assert_eq!(entry[0].role, "user");
    assert_eq!(entry[0].content, format!("u{first_retained_turn}"));
    // And everything older than that was evicted.
    assert!(
        !entry
            .iter()
            .any(|m| m.content == format!("u{}", first_retained_turn - 1)),
        "the turn before the first retained one must have been evicted"
    );
    // The most recent user message survived.
    let last_user = entry
        .iter()
        .rev()
        .find_map(|m| (m.role == "user").then(|| m.content.clone()));
    assert_eq!(
        last_user.as_deref(),
        Some(&format!("u{}", MAX_CHAT_HISTORY_TURNS - 1)[..])
    );
}

#[test]
fn pid_file_guard_removes_on_drop() {
    // Why: the guard must remove the PID file on EVERY exit path of `run`.
    // Test: create a temp PID file, drop the guard, assert the file is gone.
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("slack.pid");
    std::fs::write(&path, "12345").expect("write pid");
    assert!(path.exists(), "precondition: PID file exists before drop");
    {
        let _guard = PidFileGuard { path: path.clone() };
    } // guard drops here
    assert!(!path.exists(), "guard must remove the PID file on drop");
}

#[test]
fn pid_file_guard_drop_missing_is_silent() {
    // Why: a `tm slack stop` may have already removed the file before `run`
    // returns; the guard's drop must be a no-op (best-effort), never a panic.
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("slack.pid");
    // No file written — drop must tolerate a missing file silently.
    {
        let _guard = PidFileGuard { path: path.clone() };
    }
    assert!(!path.exists(), "missing PID file stays absent, no panic");
}

#[test]
fn record_chat_turn_skips_empty_reply() {
    let mut entry: Vec<ChatMessage> = Vec::new();
    record_chat_turn(&mut entry, "hello", "");
    // Only the user turn is recorded; an empty assistant reply is skipped.
    assert_eq!(entry.len(), 1);
    assert_eq!(entry[0].role, "user");
}

#[test]
fn action_footer_lists_verbs() {
    let footer = action_footer(Some(&["sessions.list".into(), "sessions.health".into()]));
    assert_eq!(
        footer.as_deref(),
        Some("\n\n_ran: sessions.list, sessions.health_")
    );
}

#[test]
fn action_footer_absent_when_empty() {
    assert_eq!(action_footer(None), None);
    let empty: Vec<String> = Vec::new();
    assert_eq!(action_footer(Some(&empty)), None);
}

#[test]
fn resolve_token_reads_dotenv() {
    use std::io::Write;
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join(".env.local");
    let mut f = std::fs::File::create(&path).expect("create dotenv");
    writeln!(f, "# a comment").unwrap();
    writeln!(f, "SLACK_BOT_TOKEN=\"xoxb-secret\"").unwrap();
    drop(f);

    // read_dotenv_key is the testable core (resolve_token reads from the cwd).
    assert_eq!(
        read_dotenv_key(&path, "SLACK_BOT_TOKEN").as_deref(),
        Some("xoxb-secret")
    );
    assert_eq!(read_dotenv_key(&path, "MISSING"), None);
}

#[test]
fn resolve_token_missing_is_none() {
    let missing = std::path::Path::new("/nonexistent/.env.local");
    assert_eq!(read_dotenv_key(missing, "SLACK_BOT_TOKEN"), None);
}

#[test]
fn pid_file_path_is_under_framework_root() {
    // The PID file lives under the framework root so start (writer) and stop
    // (reader) agree on one location.
    let path = pid_file_path();
    assert!(path.ends_with("slack.pid"));
    assert!(
        path.to_string_lossy()
            .contains(crate::core::paths::FRAMEWORK_DIR_NAME)
    );
}

#[test]
fn stop_via_pid_file_missing_is_not_running() {
    // No PID file → the bot is simply not running (not an error).
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("slack.pid");
    assert_eq!(stop_via_pid_file(&path), StopOutcome::NotRunning);
}

#[test]
fn stop_via_pid_file_garbage_is_failed_and_removes_file() {
    // A corrupt PID file is a real failure, and the file is cleaned up so the
    // next start is not poisoned.
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("slack.pid");
    std::fs::write(&path, "not-a-pid").expect("write pid");
    match stop_via_pid_file(&path) {
        StopOutcome::Failed(_) => {}
        other => panic!("expected Failed, got {other:?}"),
    }
    assert!(!path.exists(), "corrupt PID file should be removed");
}

#[cfg(unix)]
#[test]
fn stop_via_pid_file_stale_pid_is_not_running() {
    // A recorded PID that no longer exists is a stale file, not a failure; the
    // file is still removed. We use PID 999999999 which is far beyond any live
    // process (kill returns ESRCH → NotRunning).
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("slack.pid");
    std::fs::write(&path, "999999999").expect("write pid");
    assert_eq!(stop_via_pid_file(&path), StopOutcome::NotRunning);
    assert!(!path.exists(), "stale PID file should be removed");
}