mahbot 0.7.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
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! 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 — `"diagnostics"`.
///
/// Used when posting diagnostics success/failure comments (`diagnostics.rs`),
/// as the diagnostics run's shell spill-owner key (`tools/shell/mod.rs`, via
/// `cleanup_agent_spills`), as the sentinel that collapses diagnostics comments
/// to a summary in the GUI board (`gui/board.rs`), and as the
/// diagnostics-discovery agent id / stale-write log label (`workspace.rs`).
///
/// The literal is a key: it's compared against `comment.role` (`gui/board.rs`)
/// and against agent ids (the shell spill collision guard in `tools/shell/mod.rs`),
/// so a change must be coordinated across those sites.
pub(crate) const DIAGNOSTICS_ROLE: &str = "diagnostics";

/// Role string for system comments — `"system"`.
///
/// Used only to post non-agent ticket comments: the engineer hard-failure
/// notice (`development.rs`) and the phase-reset / bounce-breaker trip notices
/// (`pipeline/mod.rs`). It is posting-only — no site reads or compares a
/// comment's role against this value, and the GUI badge for `"system"` is an
/// unrelated generic fallback in `gui/theme.rs`.
pub(crate) const SYSTEM_ROLE: &str = "system";

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

/// All static metadata for a [`Role`] variant.
///
/// Static role metadata lives here and is looked up through a single match in
/// [`role_info()`], replacing the match statements that were previously
/// scattered across the codebase for role metadata lookups. Exception:
/// prompt-loading accessors (`role_description`, `role_description_for`,
/// `discovery_prompt`, `summary_prompt`) read the embedded `.md` assets
/// directly. 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,
    /// 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: reasoning effort is baked into the binary and not
    /// user-tunable, so this 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. Arms that spell out every
/// field (Discovery, Assistant) do so because clippy's
/// `needless_update` fires when the base contributes nothing, so the update
/// syntax is only valid when at least one field comes from the base.
const BASE_ROLE_INFO: RoleInfo = RoleInfo {
    has_discovery: true,
    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),
            default_reasoning_effort: "xhigh",
            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",
        },
        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",
        },
    }
}

// ── 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()
    }

    /// 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()))
    }

    /// Role description for this role, widened for the admin's Assistant.
    ///
    /// Only the Assistant has a separate description when the triggering
    /// account is the admin; every other role returns its canonical
    /// [`Role::role_description`] regardless of `is_admin`.
    #[must_use]
    pub fn role_description_for(&self, is_admin: bool) -> String {
        if *self == Role::Assistant && is_admin {
            crate::prompt::load_prompt("role/assistant_admin.md")
        } else {
            self.role_description()
        }
    }

    /// 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;
#[cfg(not(target_os = "macos"))]
use crate::tools::ComputerTool;
use crate::tools::{
    AddAlarmTool, AddCommentTool, AnalyzeTool, ChromeTool, CreateTicketTool, CustomTool,
    DispatchMode, EditTool, GetTicketTool, ImageGenTool, ImplementTool, ListAlarmsTool,
    ListTicketsTool, MahbotConfigTool, MahbotDebugTool, ReadTool, RemoveAlarmTool, ResearchTool,
    SearchArchivedTicketsTool, SearchTool, SendMessageToManagerTool, ShellMode, ShellTool,
    SleepTool, UpdateTicketTool, VideoEditTool, VideoGenTool, WebSearchBackend, WebSearchTool,
    WorkspaceControlTool,
};

impl Role {
    /// Core read/search tools — plus the shell in `shell` mode when one is
    /// requested — for the inspector roles (Analyst, QA, Reviewer, Discovery,
    /// Maintainer). None of them may mutate the workspace, so none gets `edit`;
    /// they differ only in the shell mode, and an Analyst in a guest's personal
    /// workspace loses the shell entirely (see [`Self::analyst_shell_allowed`]).
    fn inspector_core_tools(shell: Option<ShellMode>) -> Vec<Box<dyn Tool>> {
        let mut tools: Vec<Box<dyn Tool>> =
            vec![Box::new(ReadTool::general()), Box::new(SearchTool)];
        if let Some(mode) = shell {
            tools.push(Box::new(ShellTool::new(mode)));
        }
        tools
    }

    /// Whether an Analyst running in `ws` keeps its read-only shell.
    ///
    /// Analysts are built with no identity of their own (an empty user name and
    /// `is_admin = false`), so the workspace they inherit from the summoning
    /// session is the only carrier of who called — and it is re-read from
    /// durable state on every construction, so the rule holds across restarts.
    /// A guest's Assistant is pinned to `personal:<user>`, so its analysts
    /// must lose the shell: that shell has no reading restriction and would be
    /// a direct route into the admin's `shared` folder the per-user grants
    /// exist to gate. Anything else — a project workspace (the pipeline's own
    /// analysts), or the admin's own personal workspace — keeps it; an
    /// unrecognised `personal:` name falls to the stricter side.
    fn analyst_shell_allowed(ws: &Workspace) -> bool {
        match crate::users::personal_user_name(&ws.name) {
            Some(user) => crate::users::is_admin_name(user),
            None => true,
        }
    }

    /// Core full-shell/read/edit/search tools for the build roles
    /// (Engineer, Coder).
    fn full_core_tools() -> Vec<Box<dyn Tool>> {
        vec![
            Box::new(ShellTool::new(ShellMode::Full)),
            Box::new(ReadTool::general()),
            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.
    ///
    /// `is_admin` says whether the triggering account is the admin. It only
    /// widens the Assistant's toolset: `shell`, `implement`, `research`,
    /// `computer`, `mahbot_config`, `mahbot_debug`, `workspace_control` and the
    /// Assistant↔Manager chat tools are added. Every other role's toolset is
    /// byte-identical regardless of its value. `computer` exists only where the
    /// capability does: on macOS it is withdrawn, so the admin's toolset there
    /// has no such tool (see `tools/computer/macos.rs`).
    ///
    /// `chrome_sessions` is the run-scoped tracker shared with the agent's
    /// `ChromeTool`: every session the run opens is handed to the run-end
    /// release queue (see `crate::agent::RunEndCleanup`).
    #[must_use]
    pub(crate) fn tools(
        self,
        ws: &Workspace,
        is_admin: bool,
        chrome_sessions: std::sync::Arc<crate::tools::chrome::ChromeRunSessions>,
    ) -> 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::new(
                    DispatchMode::Sync,
                    Role::Engineer,
                )));
                t
            }
            Role::Manager => {
                let reporter = self.as_str();
                vec![
                    Box::new(CreateTicketTool::new(reporter, ws)),
                    Box::new(UpdateTicketTool::new(ws)),
                    Box::new(ListTicketsTool::new(ws)),
                    Box::new(GetTicketTool::new(reporter, ws)),
                    Box::new(AddCommentTool::new(ws)),
                    Box::new(SearchArchivedTicketsTool::new(ws)),
                    Box::new(AnalyzeTool::new(DispatchMode::Async, Role::Manager)),
                    // The Manager often has nothing to say until a ticket
                    // advances or an async analysis lands — sleep
                    // ends the turn instead of a premature/no-op reply.
                    Box::new(SleepTool),
                ]
            }
            Role::Analyst => {
                let shell = Self::analyst_shell_allowed(ws).then_some(ShellMode::ReadOnly);
                let mut t = Self::inspector_core_tools(shell);
                t.push(Box::new(ChromeTool::new(chrome_sessions)));
                t
            }
            Role::Coder => Self::full_core_tools(),
            // QA runs the build roles' unrestricted shell so it can start the
            // product or its service and observe it while it runs. The mode is
            // the only thing it shares with them: no `edit`, and the
            // no-mutation rule lives in `prompt/role/qa.md`.
            Role::Qa => Self::inspector_core_tools(Some(ShellMode::Full)),
            Role::Reviewer | Role::Discovery => {
                Self::inspector_core_tools(Some(ShellMode::ReadOnly))
            }
            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 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.
                vec![
                    Box::new(ReadTool::general()),
                    Box::new(ShellTool::new(ShellMode::ReadOnly)),
                ]
            }
            Role::Maintainer => {
                let mut t = Self::inspector_core_tools(Some(ShellMode::ReadOnly));
                t.push(Box::new(AnalyzeTool::new(
                    DispatchMode::Sync,
                    Role::Maintainer,
                )));
                t.push(Box::new(CreateTicketTool::new("maintainer", ws)));
                t
            }
            Role::Assistant => {
                let mut t: Vec<Box<dyn Tool>> = vec![
                    Box::new(AnalyzeTool::new(DispatchMode::Async, Role::Assistant)),
                    Box::new(AddAlarmTool),
                    Box::new(ListAlarmsTool),
                    Box::new(RemoveAlarmTool),
                    Box::new(EditTool),
                    Box::new(SearchTool),
                    Box::new(SleepTool),
                    // Media tools serve every Assistant alike: the media
                    // models they use resolve per-user, so no access-level
                    // gate applies.
                    Box::new(ImageGenTool),
                    Box::new(VideoGenTool),
                    Box::new(VideoEditTool),
                ];
                // The grant-gated forwarding tool: every Assistant can call
                // admin-authored scripts; the grant (or admin rights) decides
                // what each call may reach.
                t.push(Box::new(CustomTool));
                // A guest's Assistant read access is workspace-bounded; the
                // admin's retains the general ReadTool so it can also read
                // dependency sources / temp files. (Media tools write only into
                // the workspace's generated/ tree in both cases.)
                if is_admin {
                    t.push(Box::new(ReadTool::general()));
                } else {
                    t.push(Box::new(ReadTool::workspace_only()));
                }
                if is_admin {
                    t.push(Box::new(ShellTool::new(ShellMode::Full)));
                    t.push(Box::new(ImplementTool::new(
                        DispatchMode::Async,
                        Role::Assistant,
                    )));
                    t.push(Box::new(ResearchTool::new(Role::Assistant)));
                    // The admin's session is a trusted local session, so the
                    // Assistant can also observe/act on the local GUI directly
                    // (gated per-run by the accessibility grant at agent
                    // construction). No structural authorization gate beyond
                    // `is_admin`, matching the full shell widening. Not on
                    // macOS, where computer use is withdrawn entirely
                    // (see `tools/computer/macos.rs`).
                    #[cfg(not(target_os = "macos"))]
                    t.push(Box::new(ComputerTool));
                    // Assistant→Manager channel (the admin's Assistant only):
                    // address the Manager of a project workspace. The
                    // Manager's messages auto-deliver back (see message_router).
                    t.push(Box::new(SendMessageToManagerTool));
                    // The admin config surface: the merged `mahbot_config`
                    // setup tool and the read-only DB query tool. The admin's
                    // Assistant is now the single user-facing role, so these
                    // migrated over from the removed Support role.
                    t.push(Box::new(MahbotConfigTool));
                    t.push(Box::new(MahbotDebugTool));
                    // The admin's project-pipeline control: freeze/unfreeze a
                    // named workspace's pipeline and list the registered
                    // workspaces with their pause state. The one project action
                    // the Assistant performs itself instead of forwarding to
                    // the Manager (see `role/assistant_admin.md`).
                    t.push(Box::new(WorkspaceControlTool));
                }
                t
            }
        };

        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::*;

    /// Run-scoped chrome session tracker for toolset tests — the caller-visible
    /// per-run tracker is never used here (these tests never open a browser).
    fn test_sessions() -> std::sync::Arc<crate::tools::chrome::ChromeRunSessions> {
        std::sync::Arc::new(crate::tools::chrome::ChromeRunSessions::default())
    }

    #[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 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, and every
        // advertised tool must build its spec: `spec()` loads
        // `src/prompt/tool/{name}.md`, so a misnamed description asset panics
        // here instead of at the first agent run.
        for role in Role::iter() {
            for is_admin in [false, true] {
                let tools = role.tools(
                    &crate::workspace::test_ws("test"),
                    is_admin,
                    test_sessions(),
                );
                assert!(
                    !tools.is_empty(),
                    "{}: Role::tools() must not be empty — every role needs at least one tool",
                    role.as_str()
                );
                for tool in &tools {
                    let _ = tool.spec();
                }
            }
        }
    }

    #[test]
    #[serial_test::serial(config_persist)] // swaps the process-global CONFIG
    fn sanitation_toolset_is_read_and_shell_only() {
        // Acceptance pin: 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"), false, test_sessions())
            .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]
    #[serial_test::serial(config_persist)] // swaps the process-global CONFIG
    fn qa_toolset_is_the_build_shell_without_edit() {
        // Acceptance pin: QA verifies runtime behaviour by starting the product
        // or its service, so it runs the engineer/coder shell (Full mode,
        // background included) — but it must not change the workspace, so it
        // gets no `edit`. The prohibition itself is prompt text
        // (`prompt/role/qa.md`), not a tool restriction.
        let snapshot = crate::config::CONFIG.snapshot();
        crate::config::CONFIG.swap(crate::config::ConfigData::STRUCT_FIELDS_DEFAULT);
        let ws = crate::workspace::test_ws("test");
        let qa = crate::Role::Qa.tools(&ws, false, test_sessions());
        let engineer = crate::Role::Engineer.tools(&ws, false, test_sessions());
        crate::config::CONFIG.swap(snapshot);

        let names: Vec<&str> = qa.iter().map(|t| t.name()).collect();
        assert_eq!(
            names,
            ["read", "search", "shell"],
            "QA toolset must be exactly read + search + the unrestricted shell, got: {names:?}"
        );
        let qa_shell = qa.iter().find(|t| t.name() == "shell").expect("QA shell");
        let engineer_shell = engineer
            .iter()
            .find(|t| t.name() == "shell")
            .expect("engineer shell");
        assert_eq!(
            qa_shell.description(),
            engineer_shell.description(),
            "QA must run the same shell the engineer gets"
        );
        assert!(
            qa_shell.parameters_schema()["properties"]
                .as_object()
                .is_some_and(|props| props.contains_key("background")),
            "QA's shell must advertise the background argument"
        );
    }

    #[test]
    fn manager_does_not_advertise_research() {
        // Acceptance pin: the Manager has no `research` grant — deep research
        // runs are dispatched by the admin's Assistant only (pinned
        // in `assistant_toolset_gates_admin_tools`). The Manager's
        // single delegation path is `analyze`.
        let tools =
            crate::Role::Manager.tools(&crate::workspace::test_ws("test"), false, test_sessions());
        assert!(
            !tools.iter().any(|t| t.name() == "research"),
            "Manager toolset must not contain 'research'"
        );
    }

    #[test]
    fn assistant_toolset_gates_admin_tools() {
        // The Assistant toolset must differ by whether the triggering account
        // is the admin: a guest's Assistant has no shell/implement/research/
        // computer, the admin's does. A guest gets the workspace-only read
        // (`ReadTool::workspace_only()`); the admin keeps the general read
        // (which also permits dependency sources).
        let ws = crate::workspace::test_ws("test");
        let guest = crate::Role::Assistant.tools(&ws, false, test_sessions());
        let admin = crate::Role::Assistant.tools(&ws, true, test_sessions());

        // `computer` is admin-only where the capability exists at all; on macOS
        // it is withdrawn entirely (see `tools/computer/macos.rs`).
        let admin_only: &[&str] = if cfg!(target_os = "macos") {
            &["shell", "implement", "research"]
        } else {
            &["shell", "implement", "research", "computer"]
        };
        for &name in admin_only {
            assert!(
                !guest.iter().any(|t| t.name() == name),
                "a guest's Assistant toolset must not contain '{name}'"
            );
            assert!(
                admin.iter().any(|t| t.name() == name),
                "the admin's Assistant toolset must contain '{name}'"
            );
        }
        if cfg!(target_os = "macos") {
            assert!(
                !admin.iter().any(|t| t.name() == "computer"),
                "the admin's Assistant must not advertise `computer` on macOS"
            );
        }
        // The read boundary is what the model is told: a guest (restricted)
        // only advertises the personal workspace; the admin keeps the general
        // allowlist.
        let guest_read = guest.iter().find(|t| t.name() == "read");
        let guest_path_desc = guest_read
            .map(|t| t.parameters_schema()["properties"]["path"]["description"].to_string())
            .unwrap_or_default();
        assert!(
            guest_path_desc.contains("Only the workspace is accessible"),
            "a guest's Assistant read must advertise the workspace-only boundary, got: {guest_path_desc}"
        );
        let admin_read = admin.iter().find(|t| t.name() == "read");
        let admin_path_desc = admin_read
            .map(|t| t.parameters_schema()["properties"]["path"]["description"].to_string())
            .unwrap_or_default();
        assert!(
            admin_path_desc.contains("policy allowlist"),
            "the admin's Assistant read must advertise the general allowlist boundary, got: {admin_path_desc}"
        );
    }

    #[test]
    fn admin_only_tools_only_in_admin_assistant() {
        // Acceptance pin: the admin's administrative tools — the merged
        // `mahbot_config` setup tool, the read-only `mahbot_debug` query tool
        // and `workspace_control` (the registered workspaces' pipeline
        // pause/resume/list) — are granted ONLY to the admin's Assistant. A
        // guest's Assistant and every other role must never advertise any of
        // them.
        let ws = crate::workspace::test_ws("test");
        for role in Role::iter() {
            for is_admin in [false, true] {
                let names: Vec<&str> = role
                    .tools(&ws, is_admin, test_sessions())
                    .iter()
                    .map(|t| t.name())
                    .collect();
                for name in ["mahbot_config", "mahbot_debug", "workspace_control"] {
                    let has = names.contains(&name);
                    if role == crate::Role::Assistant && is_admin {
                        assert!(has, "the admin's Assistant must advertise `{name}`");
                    } else {
                        assert!(
                            !has,
                            "{}{} must not advertise `{name}`",
                            role.as_str(),
                            if is_admin { " (admin)" } else { "" }
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn custom_tool_is_advertised_by_every_assistant_only() {
        // Acceptance pin: the single forwarding tool goes to every Assistant —
        // the admin's and a guest's alike, since the grants (not the toolset)
        // decide what each call may reach — and to no other role.
        let ws = crate::workspace::test_ws("test");
        for role in Role::iter() {
            for is_admin in [false, true] {
                let has = role
                    .tools(&ws, is_admin, test_sessions())
                    .iter()
                    .any(|t| t.name() == "custom");
                assert_eq!(
                    has,
                    role == crate::Role::Assistant,
                    "{}{} custom-tool availability",
                    role.as_str(),
                    if is_admin { " (admin)" } else { "" }
                );
            }
        }
    }

    #[test]
    fn analyst_shell_follows_the_summoning_session() {
        // The pipeline's own analysts (project workspaces) and the owner
        // admin's Assistant keep the read-only shell; every other user's
        // Assistant summons shell-less analysts, including an unresolvable
        // personal name (fail closed).
        for name in ["proj", "personal:admin"] {
            let ws = crate::workspace::test_ws_named("/tmp/proj", name);
            let has = Role::Analyst
                .tools(&ws, false, test_sessions())
                .iter()
                .any(|t| t.name() == "shell");
            assert!(has, "analysts in {name} must keep the shell");
        }
        for name in ["personal:lyuba", "personal:"] {
            let ws = crate::workspace::test_ws_named("/tmp/personal", name);
            let names: Vec<&str> = Role::Analyst
                .tools(&ws, false, test_sessions())
                .iter()
                .map(|t| t.name())
                .collect();
            assert!(
                !names.contains(&"shell"),
                "analysts in {name} must not get a shell, got {names:?}"
            );
            // Everything else about them is unchanged.
            for expected in ["read", "search", "chrome"] {
                assert!(names.contains(&expected), "{name} keeps {expected}");
            }
        }
    }

    #[test]
    fn computer_tool_only_in_admin_assistant() {
        // Acceptance pin: `computer` is granted ONLY to the admin's
        // Assistant. Every other role (and a guest's Assistant) relies on
        // delegation (chrome/analyze/shell) rather than direct local
        // GUI access, so the tool must never leak into their toolset. On macOS
        // the capability is withdrawn entirely (see `tools/computer/macos.rs`),
        // so no role advertises it there at all.
        let ws = crate::workspace::test_ws("test");
        for role in Role::iter() {
            for is_admin in [false, true] {
                let has = role
                    .tools(&ws, is_admin, test_sessions())
                    .iter()
                    .any(|t| t.name() == "computer");
                if cfg!(target_os = "macos") {
                    assert!(
                        !has,
                        "{}{} must not advertise `computer` on macOS",
                        role.as_str(),
                        if is_admin { " (admin)" } else { "" }
                    );
                } else if role == crate::Role::Assistant && is_admin {
                    assert!(has, "the admin's Assistant must advertise `computer`");
                } else {
                    assert!(
                        !has,
                        "{}{} must not advertise `computer`",
                        role.as_str(),
                        if is_admin { " (admin)" } else { "" }
                    );
                }
            }
        }
    }

    #[test]
    fn manager_chat_tools_only_in_admin_assistant() {
        // Acceptance pin: the Assistant→Manager send tool is granted ONLY
        // to the admin's Assistant. Every other role (and a guest's Assistant)
        // never communicates with a Manager directly.
        let ws = crate::workspace::test_ws("test");
        for role in Role::iter() {
            for is_admin in [false, true] {
                let names: Vec<&str> = role
                    .tools(&ws, is_admin, test_sessions())
                    .iter()
                    .map(|t| t.name())
                    .collect();
                let name = "send_message_to_manager";
                let has = names.contains(&name);
                if role == crate::Role::Assistant && is_admin {
                    assert!(has, "the admin's Assistant must advertise `{name}`");
                } else {
                    assert!(
                        !has,
                        "{}{} must not advertise `{name}`",
                        role.as_str(),
                        if is_admin { " (admin)" } else { "" }
                    );
                }
            }
        }
    }

    #[test]
    fn sleep_tool_only_in_assistant_and_manager_toolsets() {
        // Acceptance pin: `sleep` is granted ONLY to the Assistant (the admin's
        // and a guest's) and the Manager. Other roles always have pending work
        // to do and must not end their turn.
        let ws = crate::workspace::test_ws("test");
        for role in Role::iter() {
            for is_admin in [false, true] {
                let has = role
                    .tools(&ws, is_admin, test_sessions())
                    .iter()
                    .any(|t| t.name() == "sleep");
                if matches!(role, crate::Role::Assistant | crate::Role::Manager) {
                    assert!(
                        has,
                        "{} (is_admin={is_admin}) must advertise `sleep`",
                        role.as_str()
                    );
                } else {
                    assert!(
                        !has,
                        "{}{} must not advertise `sleep`",
                        role.as_str(),
                        if is_admin { " (admin)" } else { "" }
                    );
                }
            }
        }
    }

    #[test]
    fn assistant_role_descriptions_are_populated() {
        // Both Assistant descriptions (a guest's + the admin's) must be
        // non-empty, free of unsubstituted template keys, and carry the
        // alarm-notification marker.
        for is_admin in [false, true] {
            let desc = crate::Role::Assistant.role_description_for(is_admin);
            assert!(
                !desc.trim().is_empty(),
                "Assistant role description must not be empty"
            );
            assert!(
                !crate::prompt::TEMPLATE_RE.is_match(&desc),
                "Assistant role description must not contain unsubstituted template keys"
            );
            assert!(
                desc.contains("<alarm-notification>"),
                "Assistant role description must explain the <alarm-notification> marker"
            );
        }
    }

    #[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, and
        // against a role losing the no-tools / summary-only instruction the
        // summarisation request depends on (its tool set is sent, so the
        // model must be told not to use it).
        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()
            );
            assert!(
                prompt.contains("DO NOT USE ANY TOOLS. ONLY RESPOND WITH THE SUMMARY."),
                "{}: summary prompt must forbid tools and allow only the summary",
                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()
            );
        }
    }
}