mahbot 0.4.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Role metadata consolidation — single source of truth for all static [`Role`] properties.
//!
//! This module is the canonical home for [`Role`]'s static methods, trait impls,
//! and metadata lookups — including role descriptions, discovery prompts,
//! tool assignments, and [`RoleInfo`]. Used by [`crate::agent`] and other modules
//! that need role data.

use std::sync::LazyLock;

use strum::IntoEnumIterator;

use crate::Role;

/// Role string for diagnostics comments — used both when posting diagnostics
/// comments and in the circuit breaker filter. Must stay in sync between
/// both sites to prevent silent miscounting on re-dispatch.
pub(crate) const DIAGNOSTICS_ROLE: &str = "diagnostics";

/// Role string for system comments — used when posting system comments on
/// tickets (notifications, circuit breaker trip comments, agent summaries)
/// and when filtering comments in circuit breaker [`CircuitBreakerKind::should_trip`]
/// implementations. Must stay in sync between all sites to prevent silent miscounting.
pub(crate) const SYSTEM_ROLE: &str = "system";

/// Role string for sanitation comments — used both when posting sanitation
/// failure marker comments and in the circuit breaker filter. Must stay in
/// sync between both sites to prevent silent miscounting on re-dispatch.
pub(crate) const SANITATION_ROLE: &str = "sanitation_admin";

// ── RoleInfo ──────────────────────────────────────────────────────────────

/// All static metadata for a [`Role`] variant.
///
/// Every accessor goes through a single match in [`role_info()`], replacing
/// the match statements that were previously scattered across the codebase
/// for role metadata lookups. Icon widgets live in `theme::role_icon()`.
///
/// Adding a new role requires updating the [`Role`] enum in `lib.rs`,
/// creating prompt files at `src/prompt/role/{name}.md` and
/// `src/prompt/summarize/{name}.md` (and optionally
/// `src/prompt/discovery/{name}.md` if `has_discovery` is true),
/// adding an arm in this match, the [`Role::tools()`] method,
/// and the `theme::role_icon()` match.
/// The compiler will catch missing arms in exhaustive matches, but it
/// cannot catch an arm that returns an empty tool set or silently uses
/// struct update defaults — the tests in this module guard against those:
///
/// * `badge_fg` black sentinel (struct update syntax)
/// * `display_label` empty string sentinel (struct update syntax)
/// * `default_reasoning_effort` non-empty (struct update)
/// * [`Role::tools()`] non-empty for every variant
/// * `role_description()` contains real content (no placeholder)
/// * `summary_prompt()` contains real content (no placeholder)
/// * `discovery_prompt()` contains real content (no placeholder, for roles where `has_discovery` is true)
pub struct RoleInfo {
    /// Whether this role has a discovery prompt for workspace exploration.
    pub has_discovery: bool,
    /// Whether this role requires a vision-capable (multimodal) model.
    ///
    /// Controls two downstream behaviors:
    /// 1. **Message enrichment** (in `main.rs`): local image files are uploaded as
    ///    data URIs instead of being transcribed to text.
    /// 2. **Provider payload format** (in `agent.rs`): user-provided image markers
    ///    are embedded as `image_url` parts in the chat request.
    ///
    /// Only [`Role::Artist`] currently sets this to `true`.
    /// Note: image/video *generation* tools ([`ImageGenTool`], [`VideoGenTool`])
    /// use their own generation model configuration and do **not** depend on this flag.
    pub requires_multimodal: bool,
    /// Badge foreground color as an RGB tuple.
    ///
    /// Converted to an [`iced::Color`] badge in `gui/theme.rs`. The badge
    /// background is always this color at 0.1 alpha.
    pub badge_fg: (f32, f32, f32),
    /// Default reasoning effort for this role.
    ///
    /// Authoritative since mahbot-1819: reasoning effort is no longer
    /// user-tunable and stored `config_role.reasoning_effort` values are never
    /// consulted, so this baked default is what request time always uses.
    pub default_reasoning_effort: &'static str,
    /// Human-readable display label (e.g. `"QA"` for [`Role::Qa`]).
    pub display_label: &'static str,
}

// ── Single source of truth ────────────────────────────────────────────────

/// Default values shared by most [`Role`] variants in [`role_info()`].
///
/// Used via struct update syntax (`..BASE_ROLE_INFO`) to keep each arm
/// concise and make future field additions cheap.
const BASE_ROLE_INFO: RoleInfo = RoleInfo {
    has_discovery: true,
    requires_multimodal: false,
    badge_fg: (0.0, 0.0, 0.0),
    default_reasoning_effort: "high",
    display_label: "",
};

/// Look up static metadata for a role.
///
/// # Panics
/// Never — this is a complete match over all [`Role`] variants.
#[must_use]
#[allow(clippy::trivially_copy_pass_by_ref)]
pub const fn role_info(role: &Role) -> &'static RoleInfo {
    match role {
        Role::Manager => &RoleInfo {
            badge_fg: (0.816, 0.635, 0.082),
            default_reasoning_effort: "xhigh",
            display_label: "Manager",
            ..BASE_ROLE_INFO
        },
        Role::Engineer => &RoleInfo {
            badge_fg: (0.855, 0.439, 0.173),
            display_label: "Engineer",
            ..BASE_ROLE_INFO
        },
        Role::Analyst => &RoleInfo {
            badge_fg: (0.263, 0.522, 0.745),
            display_label: "Analyst",
            ..BASE_ROLE_INFO
        },
        Role::Coder => &RoleInfo {
            badge_fg: (0.353, 0.604, 0.416),
            display_label: "Coder",
            ..BASE_ROLE_INFO
        },
        Role::Qa => &RoleInfo {
            badge_fg: (0.545, 0.494, 0.784),
            display_label: "QA",
            ..BASE_ROLE_INFO
        },
        Role::Reviewer => &RoleInfo {
            badge_fg: (0.431, 0.494, 0.784),
            display_label: "Reviewer",
            ..BASE_ROLE_INFO
        },
        Role::Discovery => &RoleInfo {
            has_discovery: false,
            default_reasoning_effort: "xhigh",
            badge_fg: (0.227, 0.663, 0.624),
            display_label: "Discovery",
            ..BASE_ROLE_INFO
        },
        Role::Artist => &RoleInfo {
            has_discovery: false,
            requires_multimodal: true,
            badge_fg: (0.808, 0.365, 0.592),
            default_reasoning_effort: "high",
            display_label: "Artist",
        },
        Role::Maintainer => &RoleInfo {
            badge_fg: (0.753, 0.376, 0.502),
            default_reasoning_effort: "xhigh",
            display_label: "Maintainer",
            ..BASE_ROLE_INFO
        },
        Role::Sanitation => &RoleInfo {
            badge_fg: (0.482, 0.482, 0.482),
            display_label: "Sanitation",
            ..BASE_ROLE_INFO
        },
        Role::Assistant => &RoleInfo {
            has_discovery: false,
            badge_fg: (0.153, 0.820, 0.757),
            default_reasoning_effort: "xhigh",
            display_label: "Assistant",
            ..BASE_ROLE_INFO
        },
    }
}

// ── Trait impls ─────────────────────────────────────────────────────────

/// Valid role names, pre-computed once to avoid re-iteration in error paths.
static ALL_ROLE_NAMES: LazyLock<String> = LazyLock::new(|| {
    Role::iter()
        .map(|r| r.as_str())
        .collect::<Vec<_>>()
        .join(", ")
});

impl std::str::FromStr for Role {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let lower = s.to_ascii_lowercase();
        Role::iter().find(|r| r.as_str() == lower).ok_or_else(|| {
            anyhow::anyhow!("Unknown role '{s}', expected one of: {}", *ALL_ROLE_NAMES)
        })
    }
}

// ── Role metadata methods ──────────────────────────────────────────────

impl Role {
    /// Canonical role name as a `&'static str` (lowercase).
    ///
    /// Delegates to the [`strum::IntoStaticStr`] derive, which produces
    /// string literals with a `'static` lifetime. This is the canonical
    /// method for obtaining the role's string representation.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        self.into()
    }

    /// Whether this role requires a vision-capable (multimodal) model.
    #[must_use]
    pub const fn requires_multimodal(&self) -> bool {
        role_info(self).requires_multimodal
    }

    /// Human-readable display label (e.g. `"QA"` for [`Role::Qa`]).
    #[must_use]
    pub const fn display_label(&self) -> &'static str {
        role_info(self).display_label
    }

    /// Role description loaded from embedded prompt files.
    #[must_use]
    pub fn role_description(&self) -> String {
        crate::prompt::load_prompt(&format!("role/{}.md", self.as_str()))
    }

    /// Discovery prompt for this role, loaded from embedded prompt files.
    ///
    /// # Panics
    /// Panics if the role does not have a discovery prompt (see
    /// [`RoleInfo::has_discovery`]) — callers must check `has_discovery`
    /// before calling this method or use a role that is known to have one.
    #[must_use]
    pub fn discovery_prompt(&self) -> String {
        let info = role_info(self);
        if info.has_discovery {
            crate::prompt::load_prompt(&format!("discovery/{}.md", self.as_str()))
        } else {
            panic!("Discovery prompt for role '{self}' does not exist")
        }
    }

    /// Conversation compaction prompt for this role, loaded from
    /// `src/prompt/summarize/{role}.md`.
    #[must_use]
    pub fn summary_prompt(&self) -> String {
        crate::prompt::load_prompt(&format!("summarize/{}.md", self.as_str()))
    }
}

// ── Tool set factory ──────────────────────────────────────────────────────

use crate::Tool;
use crate::Workspace;
use crate::config::CONFIG;
use crate::tools::{
    AddCommentTool, AnalyzeTool, BrowserTool, CreateTicketTool, DispatchMode, EditTool,
    GetTicketTool, ImageGenTool, ImplementTool, ListTicketsTool, ReadTool, ResearchTool,
    SearchArchivedTicketsTool, SearchTool, ShellMode, ShellTool, UpdateTicketTool, VideoEditTool,
    VideoGenTool, WebSearchBackend, WebSearchTool,
};

impl Role {
    /// Core read/search/read-only-shell tools for inspector-style roles
    /// (Analyst, QA, Reviewer, Discovery, Maintainer).
    fn readonly_core_tools() -> Vec<Box<dyn Tool>> {
        vec![
            Box::new(ReadTool),
            Box::new(SearchTool),
            Box::new(ShellTool::new(ShellMode::ReadOnly)),
        ]
    }

    /// Core full-shell/read/edit/search tools for full-access roles
    /// (Engineer, Coder).
    fn full_core_tools() -> Vec<Box<dyn Tool>> {
        vec![
            Box::new(ShellTool::new(ShellMode::Full)),
            Box::new(ReadTool),
            Box::new(EditTool),
            Box::new(SearchTool),
        ]
    }

    /// Build the tool set for this role.
    ///
    /// Ticket tools are bound to `ws` at construction time — all their
    /// operations are confined to that workspace.
    #[must_use]
    pub(crate) fn tools(self, ws: &Workspace) -> Vec<Box<dyn Tool>> {
        let mut tools: Vec<Box<dyn Tool>> = match self {
            Role::Engineer => {
                let mut t = Self::full_core_tools();
                t.push(Box::new(AnalyzeTool::new(
                    DispatchMode::Sync,
                    Role::Engineer,
                )));
                t.push(Box::new(ImplementTool));
                t
            }
            Role::Manager => {
                vec![
                    Box::new(CreateTicketTool::new("manager", ws)),
                    Box::new(UpdateTicketTool::new(ws)),
                    Box::new(ListTicketsTool::new(ws)),
                    Box::new(GetTicketTool::new(ws)),
                    Box::new(AddCommentTool::new(ws)),
                    Box::new(SearchArchivedTicketsTool::new(ws)),
                    Box::new(AnalyzeTool::new(DispatchMode::Async, Role::Manager)),
                    Box::new(ResearchTool::new(Role::Manager)),
                ]
            }
            Role::Analyst => {
                let mut t = Self::readonly_core_tools();
                t.push(Box::new(BrowserTool::default()));
                t
            }
            Role::Coder => Self::full_core_tools(),
            Role::Qa | Role::Reviewer | Role::Discovery => Self::readonly_core_tools(),
            Role::Sanitation => {
                // Sanitation deliberately has NO search tools (local `search`
                // or `web_search`): the role inspects and cleans specific
                // filesystem artifacts and never needs to index the temp tree
                // or hit the web — for the periodic temp-dir cleaner a
                // `search` over the whole temp folder would index junk and
                // start filesystem watchers. Read + read-only shell cover
                // inspection and temp-root mutation (mahbot-1779).
                vec![
                    Box::new(ReadTool),
                    Box::new(ShellTool::new(ShellMode::ReadOnly)),
                ]
            }
            Role::Artist => {
                vec![
                    Box::new(SearchTool),
                    Box::new(ImageGenTool),
                    Box::new(VideoGenTool),
                    Box::new(VideoEditTool),
                ]
            }
            Role::Maintainer => {
                let mut t = Self::readonly_core_tools();
                t.push(Box::new(AnalyzeTool::new(
                    DispatchMode::Sync,
                    Role::Maintainer,
                )));
                t.push(Box::new(CreateTicketTool::new("maintainer", ws)));
                t
            }
            Role::Assistant => {
                vec![Box::new(AnalyzeTool::new(
                    DispatchMode::Async,
                    Role::Assistant,
                ))]
            }
        };

        if !matches!(self, Role::Manager | Role::Sanitation) {
            Self::add_web_search_tool(&mut tools);
        }

        tools
    }

    /// Appends a web search tool based on the current configuration.
    ///
    /// At most one web search tool is registered — if an explicit provider
    /// is configured but its API key is missing, no tool is added.
    /// Auto-selection: Firecrawl wins ties (both keys set, no preference).
    /// The caller is responsible for skipping this for Manager (who is
    /// expected to delegate web searches to analysts via [`AnalyzeTool`])
    /// and Sanitation (whose toolset is deliberately search-free — see
    /// [`Role::tools`]).
    fn add_web_search_tool(tools: &mut Vec<Box<dyn Tool>>) {
        let provider = CONFIG.web_search_provider();
        let firecrawl_key = CONFIG.firecrawl_key();
        let exa_key = CONFIG.exa_key();

        let backend: Option<WebSearchBackend> = match provider.as_deref() {
            Some(p) if p.eq_ignore_ascii_case("firecrawl") => {
                firecrawl_key.map(|key| WebSearchBackend::Firecrawl { key })
            }
            Some(p) if p.eq_ignore_ascii_case("exa") => {
                exa_key.map(|key| WebSearchBackend::Exa { key })
            }
            Some(other) => {
                tracing::warn!("Unknown web_search_provider: {other}");
                None
            }
            None => firecrawl_key
                .map(|key| WebSearchBackend::Firecrawl { key })
                .or_else(|| exa_key.map(|key| WebSearchBackend::Exa { key })),
        };

        if let Some(backend) = backend {
            tools.push(Box::new(WebSearchTool::new(backend)));
        }
    }
}

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

    #[test]
    fn role_roundtrip() {
        // FromStr for every variant by lowercase name
        for role in Role::iter() {
            let parsed: crate::Role = role.as_str().parse().unwrap();
            assert_eq!(parsed, role, "roundtrip failed for '{}'", role.as_str());
            // Display (strum-generated) must match the canonical as_str()
            assert_eq!(role.to_string(), role.as_str());
            // as_str() returns a &'static str — verify it's non-empty
            assert!(
                !role.as_str().is_empty(),
                "as_str() empty for '{}'",
                role.as_str()
            );
        }

        // Error case
        assert!("unknown_role".parse::<crate::Role>().is_err());
    }

    #[test]
    fn requires_multimodal_only_artist() {
        // Only Artist should require multimodal; every other role should not.
        for role in Role::iter() {
            let info = super::role_info(&role);
            let expected = matches!(role, crate::Role::Artist);
            assert_eq!(
                info.requires_multimodal,
                expected,
                "{}: expected requires_multimodal={expected}, got {}",
                role.as_str(),
                info.requires_multimodal
            );
        }
    }

    #[test]
    fn badge_colors_set() {
        // Guards against the BASE_ROLE_INFO default of (0,0,0) — a new role
        // added with struct update syntax must set badge_fg explicitly.
        for role in Role::iter() {
            let info = super::role_info(&role);
            let (r, g, b) = info.badge_fg;
            let is_black = r == 0.0 && g == 0.0 && b == 0.0;
            assert!(
                !is_black,
                "{}: badge_fg must not be (0,0,0) — set a visible color",
                role.as_str()
            );
        }
    }

    #[test]
    fn defaults_set() {
        // Guards against an empty default_reasoning_effort — a new role added
        // with struct update syntax must set it if it differs from the
        // BASE_ROLE_INFO default, and even the base must be non-empty.
        for role in Role::iter() {
            let info = super::role_info(&role);
            assert!(
                !info.default_reasoning_effort.is_empty(),
                "{}: default_reasoning_effort must not be empty",
                role.as_str()
            );
        }
    }

    #[test]
    fn display_labels_set() {
        // Guards against the BASE_ROLE_INFO sentinel of "" — every role must
        // set a display_label explicitly.
        for role in Role::iter() {
            let info = super::role_info(&role);
            assert!(
                !info.display_label.is_empty(),
                "{}: display_label must not be empty — set a display_label in role_info()",
                role.as_str()
            );
        }
    }

    #[test]
    fn all_roles_have_tools() {
        // Guards against an empty Vec in Role::tools() — the compiler catches
        // missing arms in the match, but cannot catch an arm that returns
        // vec![]. Every role needs at least one tool to function.
        for role in Role::iter() {
            let tools = role.tools(&crate::workspace::test_ws("test"));
            assert!(
                !tools.is_empty(),
                "{}: Role::tools() must not be empty — every role needs at least one tool",
                role.as_str()
            );
        }
    }

    #[test]
    #[serial_test::serial(config_persist)] // swaps the process-global CONFIG
    fn sanitation_toolset_is_read_and_shell_only() {
        // Acceptance pin (mahbot-1779): the Sanitation role advertises NO
        // search tools — even with web search configured — exactly read +
        // read-only shell.
        let snapshot = crate::config::CONFIG.snapshot();
        crate::config::CONFIG.swap(crate::config::ConfigData::STRUCT_FIELDS_DEFAULT);
        let _ = crate::config::CONFIG.set_string_field("web_search_provider", "exa");
        let _ = crate::config::CONFIG.set_string_field("exa_key", "test-key");
        let names: Vec<&str> = crate::Role::Sanitation
            .tools(&crate::workspace::test_ws("test"))
            .iter()
            .map(|t| t.name())
            .collect();
        crate::config::CONFIG.swap(snapshot);
        assert_eq!(
            names,
            ["read", "shell"],
            "Sanitation toolset must be exactly read + read-only shell, got: {names:?}"
        );
    }

    #[test]
    fn qa_display_label() {
        // QA has a special display label (not "Qa").
        let info = super::role_info(&crate::Role::Qa);
        assert_eq!(info.display_label, "QA");
    }

    #[test]
    fn all_roles_have_role_description() {
        // Guards against an empty or unsubstituted role description file.
        for role in Role::iter() {
            let desc = role.role_description();
            assert!(
                !desc.trim().is_empty(),
                "{}: role_description() must not be empty",
                role.as_str()
            );
            assert!(
                !crate::prompt::TEMPLATE_RE.is_match(&desc),
                "{}: role description must not contain unsubstituted template keys",
                role.as_str()
            );
        }
    }

    #[test]
    fn all_roles_have_summary_prompt() {
        // Guards against an empty or unsubstituted summary prompt file.
        for role in Role::iter() {
            let prompt = role.summary_prompt();
            assert!(
                !prompt.trim().is_empty(),
                "{}: summary_prompt() must not be empty",
                role.as_str()
            );
            assert!(
                !crate::prompt::TEMPLATE_RE.is_match(&prompt),
                "{}: summary prompt must not contain unsubstituted template keys",
                role.as_str()
            );
        }
    }

    #[test]
    fn all_roles_have_discovery_prompt() {
        // Guards against an empty or unsubstituted discovery prompt file.
        for role in Role::iter() {
            if !super::role_info(&role).has_discovery {
                continue;
            }
            let prompt = role.discovery_prompt();
            assert!(
                !prompt.trim().is_empty(),
                "{}: discovery_prompt() must not be empty",
                role.as_str()
            );
            assert!(
                !crate::prompt::TEMPLATE_RE.is_match(&prompt),
                "{}: discovery prompt must not contain unsubstituted template keys",
                role.as_str()
            );
        }
    }
}