mahbot 0.11.1

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
//! The embedded prompt assets and the one-pass machinery that fills them in: `rust_embed`
//! over `src/prompt/`, the `\n---\n` section splitter, the `{{key}}` substituter, and the
//! workspace and ticket context blocks installed into a call.
//!
//! Two directories carry tool text: `tool/{name}.md` is a tool's standing description — how to
//! use it, why, and one clause about what it returns — and `reference/{name}.md` is the detail
//! behind it, fetched on demand by the `reference` tool
//! ([`crate::tools::tool_reference`]).
//!
//! Not the prompts themselves — those are the `.md` files, loaded by asset key — and not a
//! template engine: substitution is one pass and never cascades.

use std::collections::HashMap;
use std::fmt::Write;
use std::path::Path;

use regex::Regex;
use std::sync::LazyLock;

#[derive(rust_embed::RustEmbed)]
#[folder = "src/prompt"]
struct PromptAssets;

/// Regex for single-pass template substitution. Only word characters (`[a-zA-Z0-9_]`)
/// match, so a future key must not contain hyphens, dots or spaces; `(?-u)` enforces
/// ASCII-only `\w`, without which `{{résumé}}` would be accepted.
pub(crate) static TEMPLATE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u)\{\{(\w+)\}\}").expect("TEMPLATE_RE must compile"));

/// The text an embedded asset delivers: its bytes with the checkout's line endings
/// normalised to LF.
///
/// `rust_embed` embeds an asset as the working copy holds it, so a checkout that rewrites
/// line endings (`core.autocrlf`) would hand the build CRLF — changing the text a model is
/// sent and, by hiding the `\n---\n` separator, collapsing a variant asset into one section.
/// The repository pins LF for these files, so this is a no-op on a correct checkout.
fn asset_text(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).replace("\r\n", "\n")
}

/// An embedded asset's text, or `None` when no such asset is embedded — for the on-demand tool
/// references, whose keys are chosen at runtime by the model rather than by the code.
#[must_use]
pub(crate) fn prompt_asset(asset_key: &str) -> Option<String> {
    PromptAssets::get(asset_key).map(|file| asset_text(file.data.as_ref()))
}

/// Load a prompt template from embedded assets. Panics if the asset is missing — prompt
/// files are always present, so that is a stale key or a partial checkout.
#[must_use]
pub(crate) fn load_prompt(asset_key: &str) -> String {
    prompt_asset(asset_key).unwrap_or_else(|| {
        panic!(
            "Embedded prompt '{asset_key}' not found. \
             Create the file at src/prompt/{asset_key} and rebuild."
        )
    })
}

/// The one statement of the delivery rule — a produced file reaches the user only when the reply
/// names it — substituted as `{{media_delivery}}` into every prompt an agent that can produce files
/// writes a reply from.
#[must_use]
pub(crate) fn media_delivery() -> String {
    load_prompt("context/media_delivery.md").trim().to_owned()
}

/// Load a prompt asset and split it into `---`-delimited sections (trimmed, empty dropped).
#[must_use]
pub(crate) fn load_prompt_sections(asset_key: &str) -> Vec<String> {
    split_sections(&load_prompt(asset_key))
}

/// Deal a section list out strided across `count` slots, rendered as slot `k`'s own share.
/// No section is left unhanded: the slots share the list in rotation and the surplus stacks
/// onto the leading slots when there are fewer slots than sections. Every section reaches
/// exactly one slot.
#[must_use]
pub(crate) fn deal_sections(sections: &[String], count: usize, k: usize) -> String {
    sections
        .iter()
        .skip(k)
        .step_by(count)
        .map(String::as_str)
        .collect::<Vec<_>>()
        .join("\n\n")
}

fn split_sections(text: &str) -> Vec<String> {
    text.split("\n---\n")
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .collect()
}

/// Append a named file section to the context string, with a markdown header and truncated
/// content. Skips empty content.
fn append_file_section(out: &mut String, name: &str, content: &str) {
    let trimmed = content.trim();
    if trimmed.is_empty() {
        return;
    }
    let _ = writeln!(out, "--- {name} ---\n");
    push_truncated(out, trimmed);
}

/// The account's personal memory — a continuity record for its own Assistant only, never
/// context for another role or another account.
pub(crate) const MEMORY_FILE: &str = "MEMORY.md";

/// How much of one workspace file a context render keeps, in characters (Unicode scalar
/// values), not bytes.
pub(crate) const MAX_WORKSPACE_FILE_CHARS: usize = 10_000;

const WORKSPACE_FILES: &[&str] = &[
    "README.md",
    "BOOTSTRAP.md",
    MEMORY_FILE,
    "CLAUDE.md",
    "AGENTS.md",
    "AGENTS.local.md",
    "CLAUDE.local.md",
    ".cursorrules",
    "copilot-instructions.md",
    ".github/copilot-instructions.md",
];

/// Build workspace context content from workspace files. `personal_memory` admits the
/// [`MEMORY_FILE`] section: only the Assistant of the account whose personal folder this is
/// passes `true`, so this builder never renders a continuity record for anyone else.
pub(crate) async fn build_workspace_context(workspace: &Path, personal_memory: bool) -> String {
    let mut out = String::new();
    for &filename in WORKSPACE_FILES {
        if filename == MEMORY_FILE && !personal_memory {
            continue;
        }
        let path = workspace.join(filename);
        if let Ok(raw) = tokio::fs::read_to_string(&path).await {
            append_file_section(&mut out, filename, &raw);
        }
    }
    for (rel_path, content) in discover_claude_rules(workspace).await {
        append_file_section(&mut out, &rel_path, &content);
    }
    out
}

/// Wrap workspace context content in a stable `<workspace-context>` block; empty when
/// `content` is blank.
pub(crate) fn wrap_workspace_context(content: &str) -> String {
    let trimmed = content.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    format!("\n<workspace-context>\n{trimmed}\n</workspace-context>\n")
}

/// The general (non-role) workspace context block for non-agent LLM calls. Uses the stored
/// general context row (role = NULL) when discovery produced one, else the file-derived
/// builder minus the personal memory (a non-agent call is nobody's Assistant session). Stable
/// per workspace; empty when no source has content.
async fn build_general_workspace_context(ws: &crate::Workspace) -> String {
    // Degrade to the file-derived fallback when the store is uninitialized (early tests) —
    // never panic on a missing global.
    let stored = match crate::workspace::WORKSPACES.get() {
        Some(store) => store.get_general_context(&ws.name).await.ok().flatten(),
        None => None,
    };
    let content = match stored {
        Some(ctx) => ctx,
        None => build_workspace_context(ws.as_path(), false).await,
    };
    wrap_workspace_context(&content)
}

/// Prepend the general workspace context to `messages` as the leading system message when a
/// stored or file-derived context exists. No-op otherwise.
pub(crate) async fn prepend_general_context(
    messages: &mut Vec<crate::ChatMessage>,
    ws: &crate::Workspace,
) {
    let context = build_general_workspace_context(ws).await;
    if !context.is_empty() {
        messages.insert(0, crate::ChatMessage::system(&context));
    }
}

/// Format a ticket as a `<current-ticket>` block for injection as a separate system message
/// (after the workspace context, before the user message).
pub(crate) fn format_ticket_block(ticket: &crate::pipeline::board::Ticket) -> String {
    let mut comments = String::new();
    if !ticket.comments.is_empty() {
        let _ = writeln!(comments);
        let _ = writeln!(comments, "### Comments ({})", ticket.comments.len());
        let _ = writeln!(comments);

        for comment in &ticket.comments {
            let ts = format_local_timestamp(&comment.created_at);
            let _ = writeln!(comments, "**{}** ({}):", comment.role, ts);
            let _ = writeln!(comments, "{}", comment.content);
            let _ = writeln!(comments);
            let _ = writeln!(comments, "---");
            let _ = writeln!(comments);
        }
    }

    substitute(
        &load_prompt("context/ticket.md"),
        &[
            ("{{ticket_id}}", &ticket.id),
            ("{{ticket_title}}", &ticket.title),
            ("{{ticket_reporter}}", &ticket.reporter),
            ("{{ticket_priority}}", &format!("P{}", ticket.priority)),
            ("{{ticket_description}}", &ticket.description),
            ("{{ticket_comments}}", &comments),
        ],
    )
}

fn format_local_timestamp(iso_str: &str) -> String {
    crate::db::parse_utc_timestamp(iso_str).map_or_else(
        |e| {
            tracing::warn!(iso_str = %iso_str, error = %e, "Failed to parse timestamp, falling back to raw string");
            iso_str.to_string()
        },
        |dt| {
            dt.with_timezone(&chrono::Local)
                .format("%Y-%m-%d %H:%M:%S")
                .to_string()
        },
    )
}

fn truncation_point(text: &str) -> Option<usize> {
    text.char_indices()
        .nth(MAX_WORKSPACE_FILE_CHARS)
        .map(|(idx, _)| idx)
}

pub(crate) fn exceeds_workspace_file_limit(text: &str) -> bool {
    truncation_point(text).is_some()
}

fn push_truncated(out: &mut String, text: &str) {
    if let Some(idx) = truncation_point(text) {
        out.push_str(&text[..idx]);
        let _ = writeln!(
            out,
            "\n\n{}\n",
            substitute(
                &load_prompt("context/truncation_notice.md"),
                &[("{{max_chars}}", &MAX_WORKSPACE_FILE_CHARS.to_string())],
            ),
        );
    } else {
        out.push_str(text);
        out.push_str("\n\n");
    }
}

/// Discover `.claude/rules/*.md` files and return their relative paths with their content, in
/// deterministic byte-sorted name order (not `read_dir` order), so identical rules render
/// byte-identically and the workspace-context block stays stable across renders. Names within
/// one directory are unique, so the sort cannot tie.
async fn discover_claude_rules(workspace: &Path) -> Vec<(String, String)> {
    let rules_dir = workspace.join(".claude").join("rules");

    let Ok(mut entries) = tokio::fs::read_dir(&rules_dir).await else {
        return Vec::new();
    };

    let mut files = Vec::new();
    while let Ok(Some(entry)) = entries.next_entry().await {
        let path = entry.path();
        if path.extension().is_some_and(|e| e == "md") {
            files.push(path);
        }
    }
    files.sort_by(|a, b| a.file_name().cmp(&b.file_name()));

    let mut rules = Vec::new();
    for path in files {
        if let Ok(content) = tokio::fs::read_to_string(&path).await {
            let rel_path = path
                .strip_prefix(workspace)
                .unwrap_or(&path)
                .display()
                .to_string();
            rules.push((rel_path, content));
        }
    }
    rules
}

/// Single-pass template substitution: all `{{key}}` patterns are replaced at once from
/// `replacements`, so values are never re-substituted — a value containing a later key appears
/// literally.
///
/// Keys must be word characters (`[a-zA-Z0-9_]`); a key with hyphens or dots stays in the
/// output unexpanded. A key with no replacement is left literal and warns at runtime, so a typo
/// shows up in the log instead of silently corrupting the prompt. Callers pass keys with the
/// full wrapper (`"{{ticket_id}}"`).
pub(crate) fn substitute(template: &str, replacements: &[(&str, &str)]) -> String {
    let map: HashMap<&str, &str> = replacements.iter().copied().collect();
    TEMPLATE_RE
        .replace_all(template, |caps: &regex::Captures| {
            let whole = caps
                .get(0)
                .expect("capture group 0 always matches")
                .as_str();
            if let Some(val) = map.get(whole) {
                (*val).to_owned()
            } else {
                tracing::warn!(
                    template_var = %whole,
                    "prompt substitution: no replacement provided for '{whole}' — \
                     literal text will appear in the prompt output. \
                     Check that the variable name in the template matches a \
                     replacement key at the call site."
                );
                whole.to_owned()
            }
        })
        .into_owned()
}

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

    /// One pass over the template with the replacements at hand: a key with no replacement is
    /// left as the literal `{{key}}`, and a template with no placeholders comes back unchanged.
    #[test]
    fn substitute_cases() {
        type Pair = (&'static str, &'static str);
        /// Case name, template, replacements, expected output.
        type Case = (&'static str, &'static str, &'static [Pair], &'static str);

        let cases: &[Case] = &[
            (
                "both keys replaced",
                "Hello {{name}}, your {{item}} is ready.",
                &[("{{name}}", "Alice"), ("{{item}}", "order")],
                "Hello Alice, your order is ready.",
            ),
            (
                "unknown key preserved",
                "Hello {{name}}, here is {{missing}} key.",
                &[("{{name}}", "Alice")],
                "Hello Alice, here is {{missing}} key.",
            ),
            ("empty template", "", &[("{{key}}", "value")], ""),
            ("no replacements", "Hello {{name}}!", &[], "Hello {{name}}!"),
        ];
        for (case, template, replacements, expected) in cases {
            assert_eq!(
                substitute(template, replacements),
                *expected,
                "case '{case}'"
            );
        }
    }

    #[test]
    fn substitute_no_cascade() {
        // A replacement value containing a later key pattern must NOT be re-substituted —
        // the cascade bug from sequential str::replace().
        let result = substitute(
            "First: {{a}}, Second: {{b}}",
            &[("{{a}}", "value-{{b}}"), ("{{b}}", "actual-b")],
        );
        assert_eq!(result, "First: value-{{b}}, Second: actual-b");
    }

    /// Only the `.md` rules are discovered, and a rule the loader cannot read (a directory
    /// named `*.md`) is skipped rather than failing the scan.
    #[tokio::test]
    async fn discover_claude_rules_finds_only_readable_md_files() {
        let dir = tempfile::tempdir().unwrap();
        let rules_dir = dir.path().join(".claude").join("rules");
        std::fs::create_dir_all(&rules_dir).unwrap();
        std::fs::write(rules_dir.join("testing.md"), "Test content").unwrap();
        std::fs::write(rules_dir.join("style.md"), "Style rules").unwrap();
        std::fs::write(rules_dir.join("notes.txt"), "irrelevant").unwrap();
        std::fs::create_dir(rules_dir.join("broken.md")).unwrap();

        let rules = discover_claude_rules(dir.path()).await;
        let paths: Vec<&str> = rules.iter().map(|(p, _)| p.as_str()).collect();
        assert_eq!(
            paths,
            [".claude/rules/style.md", ".claude/rules/testing.md"],
            "only the readable .md rules are discovered"
        );
    }

    #[tokio::test]
    async fn discover_claude_rules_missing_dir() {
        let dir = tempfile::tempdir().unwrap();
        let rules = discover_claude_rules(dir.path()).await;
        assert!(rules.is_empty());
    }

    #[tokio::test]
    async fn discover_claude_rules_returns_sorted_order() {
        let dir = tempfile::tempdir().unwrap();
        let rules_dir = dir.path().join(".claude").join("rules");
        std::fs::create_dir_all(&rules_dir).unwrap();
        // Scrambled creation order — `read_dir` order is not guaranteed, so the loader must
        // return rules byte-sorted for a stable render.
        for name in ["zebra", "alpha", "middle"] {
            std::fs::write(
                rules_dir.join(format!("{name}.md")),
                format!("{name} rules"),
            )
            .unwrap();
        }

        let rules = discover_claude_rules(dir.path()).await;
        let paths: Vec<&str> = rules.iter().map(|(p, _)| p.as_str()).collect();
        assert_eq!(
            paths,
            [
                ".claude/rules/alpha.md",
                ".claude/rules/middle.md",
                ".claude/rules/zebra.md",
            ]
        );
    }

    /// The context cut is also the nightly inventory's trigger: 10,000 characters render
    /// whole, 10,001 do not, and the count is characters — a multi-byte file measures the same.
    #[test]
    fn the_file_limit_counts_characters() {
        let fits = "ё".repeat(MAX_WORKSPACE_FILE_CHARS);
        assert_eq!(
            fits.len(),
            MAX_WORKSPACE_FILE_CHARS * 2,
            "two bytes per char"
        );
        assert!(!exceeds_workspace_file_limit(&fits));
        assert!(exceeds_workspace_file_limit(&format!("{fits}ё")));
    }
}