mahbot 0.11.3

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Admin-defined custom roles: the record (name, authorial prompt, tool subset, default
//! branching) plus its validation. There is exactly one owner — the admin — so no owner column;
//! two surfaces reach these functions: the admin's configuration tool (a role granted
//! `mahbot_config` runs at his strength) and the local Settings page. The tool set is the
//! boundary, by design.

use anyhow::Result;

use crate::db;

crate::define_store! {
    pub(crate) static CUSTOM_ROLES: CustomRoleStore,
    expect = "CUSTOM_ROLES not initialized — call init_all_stores() first",
}

crate::columns! {
    CUSTOM_ROLE_COLUMNS [CR] {
        NAME     => "name",
        PROMPT   => "prompt",
        TOOLS    => "tools",
        BEHAVIOR => "behavior",
    }
}

/// Upper bound on a custom role's name, in characters.
pub(crate) const MAX_ROLE_NAME_CHARS: usize = 32;

/// Upper bound on a custom role branch identifier, in characters.
pub(crate) const MAX_ROLE_IDENTIFIER_CHARS: usize = 32;

/// How a custom role branches when a launch names no branch: keep one continuable conversation
/// ([`Self::Continuous`]) or run once and report back ([`Self::OneOff`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CustomRoleBehavior {
    Continuous,
    OneOff,
}

impl CustomRoleBehavior {
    #[must_use]
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Continuous => "continuous",
            Self::OneOff => "one_off",
        }
    }

    pub(crate) fn parse(s: &str) -> anyhow::Result<Self> {
        match s {
            "continuous" => Ok(Self::Continuous),
            "one_off" => Ok(Self::OneOff),
            other => anyhow::bail!("unknown custom role behavior '{other}'"),
        }
    }
}

/// The label the settings picker shows — never the stored value.
impl std::fmt::Display for CustomRoleBehavior {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Continuous => "Keep one branch",
            Self::OneOff => "One-off run",
        })
    }
}

#[derive(Debug, Clone)]
pub(crate) struct CustomRole {
    pub name: String,
    /// The administrator's authorial text — the whole definition of the role.
    pub prompt: String,
    /// The chosen tool subset: `"tool"`, `"tool:kind1,kind2"` or `"custom:<script>"` entries
    /// ([`crate::tools::grants`]).
    pub tools: Vec<String>,
    pub behavior: CustomRoleBehavior,
}

fn custom_role_from_row(row: &db::Row) -> Result<CustomRole> {
    Ok(CustomRole {
        name: row.get(COL_CR_NAME)?,
        prompt: row.get(COL_CR_PROMPT)?,
        tools: decode_tools(&row.get::<String>(COL_CR_TOOLS)?),
        behavior: CustomRoleBehavior::parse(&row.get::<String>(COL_CR_BEHAVIOR)?)?,
    })
}

/// Encode the tool subset for the `tools` column — only this module writes it.
fn encode_tools(tools: &[String]) -> String {
    serde_json::to_string(tools).expect("a tool name list is always serializable")
}

/// Decode the `tools` column. A value that does not decode reads as the empty subset rather
/// than failing the listing — only this module writes the column.
fn decode_tools(raw: &str) -> Vec<String> {
    serde_json::from_str(raw).unwrap_or_default()
}

/// Every custom role, ordered by name.
pub(crate) async fn list() -> Result<Vec<CustomRole>> {
    let sql = format!("SELECT {CUSTOM_ROLE_COLUMNS} FROM custom_roles ORDER BY name ASC");
    let rows = store().conn.query(&sql, db::params![]).await?;
    rows.iter().map(custom_role_from_row).collect()
}

pub(crate) async fn get(name: &str) -> Result<Option<CustomRole>> {
    let sql = format!("SELECT {CUSTOM_ROLE_COLUMNS} FROM custom_roles WHERE name = ?1");
    let rows = store().conn.query(&sql, db::params![name]).await?;
    rows.first().map(custom_role_from_row).transpose()
}

/// Create a custom role. The name must be free (an existing role is never replaced).
pub(crate) async fn create(
    name: &str,
    prompt: &str,
    tools: &[String],
    behavior: CustomRoleBehavior,
) -> Result<()> {
    validate_name(name)?;
    let scripts = available_scripts(tools, &[]).await?;
    validate_tools_against(tools, &[], &scripts)?;
    anyhow::ensure!(
        !prompt.trim().is_empty(),
        "a custom role needs a prompt — the administrator's text is the whole definition"
    );
    anyhow::ensure!(
        get(name).await?.is_none(),
        "a custom role named '{name}' already exists"
    );
    store()
        .conn
        .execute(
            "INSERT INTO custom_roles (name, prompt, tools, behavior, created_at) \
             VALUES (?1, ?2, ?3, ?4, ?5)",
            db::params![
                name,
                prompt,
                encode_tools(tools),
                behavior.as_str(),
                db::now(),
            ],
        )
        .await?;
    Ok(())
}

/// Update the provided fields of an existing custom role; the omitted ones keep their value.
pub(crate) async fn update(
    name: &str,
    prompt: Option<&str>,
    tools: Option<&[String]>,
    behavior: Option<CustomRoleBehavior>,
) -> Result<()> {
    let existing = get(name)
        .await?
        .ok_or_else(|| anyhow::anyhow!("no custom role named '{name}'"))?;
    let prompt = prompt.unwrap_or(&existing.prompt);
    anyhow::ensure!(
        !prompt.trim().is_empty(),
        "a custom role needs a prompt — the administrator's text is the whole definition"
    );
    let tools = tools.unwrap_or(&existing.tools);
    let scripts = available_scripts(tools, &existing.tools).await?;
    validate_tools_against(tools, &existing.tools, &scripts)?;
    let behavior = behavior.unwrap_or(existing.behavior);
    store()
        .conn
        .execute(
            "UPDATE custom_roles SET prompt = ?2, tools = ?3, behavior = ?4 WHERE name = ?1",
            db::params![name, prompt, encode_tools(tools), behavior.as_str()],
        )
        .await?;
    Ok(())
}

/// Delete a custom role: confirm it exists, drop its record, remove the automations addressed
/// to it, stop every branch of the role (so a running one is cancelled and never resumed), then
/// tell the owner through his Assistant.
///
/// The record goes FIRST: everything after it is best-effort, so a failure leaves the role fully
/// deleted and reported rather than half-removed — and a record whose automation removal failed
/// still gets them removed when they fire.
pub(crate) async fn delete(name: &str) -> Result<()> {
    // Check existence FIRST: a nonexistent role must never mutate its automations.
    anyhow::ensure!(get(name).await?.is_some(), "no custom role named '{name}'");
    let deleted = store()
        .conn
        .execute(
            "DELETE FROM custom_roles WHERE name = ?1",
            db::params![name],
        )
        .await?;
    // Sanity check on the row count (the existence check above already proved the record).
    anyhow::ensure!(deleted > 0, "no custom role named '{name}'");
    // Past the record: nothing below aborts, so the owner is always told.
    let removed = match crate::automations::delete_automations_for_role(name).await {
        Ok(removed) => removed,
        Err(e) => {
            tracing::warn!(
                role = %name,
                error = %e,
                "Failed to remove a deleted custom role's automations — they are dropped when they fire"
            );
            0
        }
    };
    // "Continued branches of a deleted role are never resumed — they no longer have a prompt or
    // a tool set": stop each one now, so a running launch is cancelled and its deferred
    // envelopes cannot re-drive it after a restart. A failed stop or branch listing must not skip
    // the owner notice below, so both are logged and the delete continues.
    let branches = match crate::session::store().custom_role_sessions(name).await {
        Ok(branches) => branches,
        Err(e) => {
            tracing::warn!(
                role = %name,
                error = %e,
                "Failed to list a deleted custom role's branches — continuing without stops"
            );
            Vec::new()
        }
    };
    for agent_id in &branches {
        if let Err(e) = crate::launch::stop(agent_id).await {
            tracing::warn!(
                role = %name,
                agent_id = %agent_id,
                error = %e,
                "Failed to stop a branch of the deleted custom role — continuing"
            );
        }
    }
    let content = crate::prompt::substitute(
        &crate::prompt::load_prompt("custom_role_deleted.md"),
        &[("{{role}}", name)],
    );
    if let Err(e) = crate::agent::message_router::deliver_assistant_notice(
        &crate::session::assistant_agent_id(crate::users::ADMIN_USER_NAME),
        crate::users::ADMIN_USER_NAME,
        content,
    )
    .await
    {
        tracing::warn!(
            role = %name,
            error = %e,
            "Failed to deliver the custom role deletion notice — routing best-effort"
        );
    }
    tracing::debug!(role = %name, removed, branches = branches.len(), "custom role deleted");
    Ok(())
}

/// Validate a custom role's name: non-empty, within [`MAX_ROLE_NAME_CHARS`], every char ASCII
/// alphanumeric / `_` / `-`, the first an ASCII letter, and not colliding with a built-in agent
/// namespace ([`crate::session::custom_role_name_is_reserved`]).
pub(crate) fn validate_name(name: &str) -> Result<()> {
    validate_segment(name, MAX_ROLE_NAME_CHARS, "a custom role name")?;
    anyhow::ensure!(
        name.starts_with(|c: char| c.is_ascii_alphabetic()),
        "a custom role name must start with a letter — rename it to begin with an ASCII letter"
    );
    anyhow::ensure!(
        !crate::session::custom_role_name_is_reserved(name),
        "a custom role name must not collide with a built-in agent namespace ({}) — choose a \
         name outside that set",
        crate::session::reserved_custom_role_prefixes()
            .map(|prefix| prefix.trim_end_matches('_'))
            .collect::<Vec<_>>()
            .join(", ")
    );
    Ok(())
}

/// Validate a custom role branch identifier: the same charset and length rule as a name, but it
/// may start with any allowed char and carries no reserved-namespace restriction (an identifier
/// is never the leading segment of an agent address).
pub(crate) fn validate_identifier(identifier: &str) -> Result<()> {
    validate_segment(identifier, MAX_ROLE_IDENTIFIER_CHARS, "an identifier")
        .map_err(|e| anyhow::anyhow!("invalid custom role branch: {e}"))
}

/// Validate a worker branch name: the same charset and length rule as a custom role identifier,
/// with a wording of its own.
pub(crate) fn validate_worker_branch(branch: &str) -> Result<()> {
    validate_segment(branch, MAX_ROLE_IDENTIFIER_CHARS, "a branch")
        .map_err(|e| anyhow::anyhow!("invalid worker branch: {e}"))
}

/// Shared charset/length check for a name or an identifier.
fn validate_segment(value: &str, max_chars: usize, what: &str) -> Result<()> {
    anyhow::ensure!(!value.is_empty(), "{what} must not be empty — name one");
    anyhow::ensure!(
        value.chars().count() <= max_chars,
        "{what} must be at most {max_chars} characters — shorten it"
    );
    for c in value.chars() {
        anyhow::ensure!(
            c.is_ascii_alphanumeric() || c == '_' || c == '-',
            "{what} may only contain ASCII letters, digits, '_' and '-' — replace every other character"
        );
    }
    Ok(())
}

/// Validate a tool subset a caller wrote, against the catalog of what a custom role may be given
/// ([`crate::Role::custom_role_tool_catalog`]) and the scripts usable right now (`scripts`). Each
/// entry is `"tool"` (the tool with its narrowest kind), `"tool:kind1,kind2"` or
/// `"custom:<script>"` ([`crate::tools::grants`]); an empty subset is allowed, an unknown tool, a
/// tool a custom role cannot hold, an unknown kind, a name the grammar cannot express and a name
/// given twice are not.
///
/// Names the record ALREADY holds are exempt from the catalog check: a tool this installation
/// cannot serve right now, one no longer offered, or a script whose file has since gone stays on
/// the record — the launch simply omits it, and a call to it is refused — so editing another field
/// must never drop it.
pub(crate) fn validate_tools_against(
    tools: &[String],
    held: &[String],
    scripts: &[String],
) -> Result<()> {
    let catalog = crate::Role::custom_role_tool_catalog();
    // parse() validates the grammar: an unknown kind, a kind on a kindless tool, a kind named
    // twice on one tool, a script name that is not a plain file name, and a name given twice.
    let grants = crate::tools::grants::parse(tools)?;
    let held = crate::tools::grants::parse_lossy(held);
    for grant in &grants {
        if held.iter().any(|entry| entry.names_the_same(grant)) {
            continue;
        }
        match grant {
            crate::tools::grants::Grant::Tool { tool, .. } => anyhow::ensure!(
                catalog.contains(&tool.as_str()),
                "tool '{tool}' is not available to a custom role"
            ),
            crate::tools::grants::Grant::Script { name } => anyhow::ensure!(
                scripts.iter().any(|script| script == name),
                "custom tool '{name}' is not available to a custom role"
            ),
        }
    }
    Ok(())
}

/// The scripts usable right now, read only when the new list names one the record does not already
/// hold: a held entry is never re-validated, and a prompt-only edit must not depend on the folder
/// being readable.
async fn available_scripts(tools: &[String], held: &[String]) -> Result<Vec<String>> {
    let held = crate::tools::grants::parse_lossy(held);
    let needs_folder = crate::tools::grants::parse_lossy(tools)
        .iter()
        .any(|grant| {
            grant.script().is_some() && !held.iter().any(|entry| entry.names_the_same(grant))
        });
    if needs_folder {
        crate::tools::custom::script_names().await
    } else {
        Ok(Vec::new())
    }
}

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

    /// The stored grant grammar: a tool name, `tool:kind1,kind2`, or `custom:<script>`. A bare name
    /// is the tool's narrowest kind; an unknown kind, a kind on a tool that has no kinds, an
    /// unknown tool, a name the grammar cannot express and a name given twice are all refused.
    #[test]
    fn validate_tools_against_reads_the_grant_grammar() {
        let entries =
            |items: &[&str]| -> Vec<String> { items.iter().map(|s| (*s).to_string()).collect() };
        let check = |tools: &[&str], held: &[&str], scripts: &[&str]| {
            validate_tools_against(&entries(tools), &entries(held), &entries(scripts))
        };
        assert!(check(&["analyze:quick,deep", "send:worker"], &[], &[]).is_ok());
        assert!(check(&["analyze", "send", "read"], &[], &[]).is_ok());
        assert!(
            check(&["analyze:sideways"], &[], &[]).is_err(),
            "an unknown kind is refused"
        );
        assert!(
            check(&["read:quick"], &[], &[]).is_err(),
            "a kind on a tool that has no kinds is refused"
        );
        assert!(
            check(&["not-a-tool"], &[], &[]).is_err(),
            "an unknown tool is refused"
        );
        assert!(
            check(&["read", "read"], &[], &[]).is_err(),
            "a tool named twice is refused"
        );
        assert!(
            check(&["analyze:quick", "analyze:deep"], &[], &[]).is_err(),
            "the same tool split across two entries is refused too"
        );
        assert!(
            check(&["gone"], &["gone"], &[]).is_ok(),
            "a name the record already holds stays valid"
        );
        assert!(
            check(&["computer"], &[], &[]).is_err(),
            "computer use is not offered to a custom role"
        );
        assert!(
            check(&["computer"], &["computer"], &[]).is_ok(),
            "a stored computer grant is left alone when the record is edited"
        );
        assert!(
            check(&["custom"], &[], &[]).is_err(),
            "the plain dispatcher entry is not offered to a custom role"
        );
        assert!(
            check(&["custom"], &["custom"], &[]).is_ok(),
            "a stored dispatcher entry stays on the record so another edit can save"
        );

        // A script is validated against the ones present right now, and one the record already
        // holds survives its file going away.
        assert!(check(&["custom:weather"], &[], &["weather"]).is_ok());
        assert!(
            check(&["custom:weather"], &[], &["other"]).is_err(),
            "a script that is not present is refused like an unknown tool"
        );
        assert!(
            check(&["custom:weather"], &["custom:weather"], &[]).is_ok(),
            "a held script stays valid after its file is deleted"
        );
        assert!(
            check(&["custom:"], &[], &[]).is_err(),
            "a name the grammar cannot express is refused, present or not"
        );
        assert!(
            check(&["custom:weather", "custom:weather"], &[], &["weather"]).is_err(),
            "one script named twice is refused"
        );
        assert!(
            check(&["custom:read", "read"], &[], &["read"]).is_ok(),
            "a script and a tool of the same name are two different things"
        );
    }

    /// A script is handed out through the record's own validators: a name present in the folder is
    /// accepted, one that is not is refused like an unknown tool, and a held one survives its file
    /// going away.
    #[tokio::test]
    async fn a_script_entry_is_validated_against_the_folder() {
        crate::util::test::init_test_stores().await;
        let dir =
            crate::users::personal_workspace_path(crate::users::ADMIN_USER_NAME).join("shared");
        std::fs::create_dir_all(&dir).unwrap();
        let probe = crate::util::test::ProbeFile(dir.join("role_script_probe.ts"));
        std::fs::write(&probe.0, "// @description Probe.\n").unwrap();

        create(
            "scripted",
            "run the probe",
            &["custom:role_script_probe".to_string()],
            CustomRoleBehavior::OneOff,
        )
        .await
        .unwrap();
        assert_eq!(
            get("scripted").await.unwrap().unwrap().tools,
            ["custom:role_script_probe"]
        );

        let err = update(
            "scripted",
            None,
            Some(&["custom:missing_probe".to_string()]),
            None,
        )
        .await
        .unwrap_err()
        .to_string();
        assert!(
            err.contains("custom tool 'missing_probe' is not available to a custom role"),
            "an unknown script is refused like an unknown tool: {err}"
        );

        // The held entry stays when its file goes away, so an unrelated edit still saves.
        std::fs::remove_file(&probe.0).unwrap();
        update("scripted", Some("run it another way"), None, None)
            .await
            .unwrap();
        let saved = get("scripted").await.unwrap().unwrap();
        assert_eq!(saved.prompt, "run it another way");
        assert_eq!(saved.tools, ["custom:role_script_probe"]);
    }

    #[test]
    fn validate_name_accepts_a_good_name_and_rejects_the_rest() {
        assert!(validate_name("briefer").is_ok());
        assert!(validate_name("a_b-1").is_ok());

        // The first char must be a letter.
        assert!(validate_name("1abc").is_err());
        // The record's length bound.
        assert!(validate_name(&"a".repeat(MAX_ROLE_NAME_CHARS + 1)).is_err());
        // ':' is the branch separator and never enters a name.
        assert!(validate_name("a:b").is_err());
        // A name that merely starts with a namespace word shadows nothing.
        assert!(validate_name("rolex").is_ok());
        assert!(validate_name("roleplay").is_ok());
        // Built-in agent namespaces.
        for reserved in ["ticket", "maintainer", "role"] {
            assert!(
                validate_name(reserved).is_err(),
                "'{reserved}' must collide with a built-in namespace"
            );
        }
    }

    #[test]
    fn branch_addresses_are_injective() {
        let default = crate::session::custom_role_agent_id("a_b", None);
        let named = crate::session::custom_role_agent_id("a", Some("b"));
        assert_eq!(default, "role_a_b");
        assert_eq!(named, "role_a:b");
        assert_ne!(
            default, named,
            "('a_b', None) must never alias ('a', Some('b'))"
        );
    }

    /// Stopping a launch is what the recovery paths read: the branch carries the
    /// persisted mark and its deferred envelopes are gone, so boot replay and
    /// the dead-session poller both leave it alone.
    #[tokio::test]
    async fn stop_marks_the_branch_and_drops_its_deferred_envelopes() {
        crate::util::test::init_test_stores().await;
        let branch = crate::session::custom_role_agent_id("stopper", Some("night"));
        crate::util::test::seed_session_row(
            &crate::session::store().conn,
            &branch,
            crate::Role::Custom.as_str(),
            "work on it",
        )
        .await;
        let job = crate::agent::message_router::AgentJob {
            content: "a late result".to_string(),
            workspace_name: crate::users::personal_workspace_name(crate::users::ADMIN_USER_NAME),
            user_name: crate::users::ADMIN_USER_NAME.to_string(),
            channel: "gui".to_string(),
            kind: crate::agent::message_router::MessageKind::AnalyzeToolResult,
            role: crate::Role::Custom,
            reply_target: None,
            pending_job_id: None,
            pause_notice_id: None,
            originating_workspace: None,
            custom_role: Some(crate::Launch {
                role: crate::Role::Custom,
                name: "stopper".to_string(),
                identifier: Some("night".to_string()),
                prompt: "prompt".to_string(),
                tools: Vec::new(),
                agent_id: branch.clone(),
                reply_to: None,
                chain: None,
                extract: None,
            }),
            reply_to_custom: None,
            urgent: false,
            extract: None,
        };
        crate::agent::message_router::persist_pending(&job, "stop_marker_pending".to_string())
            .await
            .unwrap();

        crate::launch::stop(&branch).await.unwrap();

        assert!(crate::session::store().get_launch_stopped(&branch).await);
        let left = crate::jobs::list_pending_jobs(&crate::session::store().conn)
            .await
            .unwrap();
        assert!(
            !left.iter().any(|row| row.id == "stop_marker_pending"),
            "a stopped launch's deferred envelopes are dropped"
        );
    }
}