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
use std::collections::HashMap;
use std::fmt::Write;
use std::path::Path;

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

// ── Prompt Asset Loading ─────────────────────────────────────────────

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

/// Regex for single-pass template substitution.
///
/// Only matches keys consisting of word characters (`\w` = `[a-zA-Z0-9_]`).
/// Future template keys must not contain hyphens, dots, or spaces.
/// Uses `(?-u)` to enforce ASCII-only `\w` — without it, the regex crate
/// defaults to Unicode-aware matching which would accept `{{résumé}}`.
pub(crate) static TEMPLATE_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?-u)\{\{(\w+)\}\}").expect("TEMPLATE_RE must compile"));

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

/// Load a prompt asset and split it into `---`-delimited sections (trimmed,
/// empty sections dropped).
#[must_use]
pub(crate) fn load_prompt_sections(asset_key: &str) -> Vec<String> {
    load_prompt(asset_key)
        .split("\n---\n")
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .collect()
}

// Utils

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

/// Build workspace context content from workspace files.
pub(crate) async fn build_workspace_context(workspace: &Path) -> String {
    const WORKSPACE_FILES: &[&str] = &[
        "README.md",
        "BOOTSTRAP.md",
        "MEMORY.md",
        "CLAUDE.md",
        "AGENTS.md",
        "AGENTS.local.md",
        "CLAUDE.local.md",
        ".cursorrules",
        "copilot-instructions.md",
        ".github/copilot-instructions.md",
    ];

    let mut out = String::new();
    for &filename in WORKSPACE_FILES {
        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.
/// Returns an empty string 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")
}

/// Build the general (non-role) workspace context block for non-agent LLM
/// calls, wrapped in a stable `<workspace-context>` block.
///
/// Uses the stored general context row (role = NULL) when discovery has
/// produced one; otherwise falls back to the file-derived context builder
/// (the same fallback role agents use). The block is stable per workspace —
/// it does not vary between requests. Returns an empty string when no
/// context source has content (no stored row and no context files).
pub(crate) async fn build_general_workspace_context(ws: &crate::Workspace) -> String {
    // Degrade to the file-derived fallback when the store is uninitialized
    // (e.g. 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()).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 memory context, before user message).
pub(crate) fn format_ticket_block(ticket: &crate::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),
        ],
    )
}

/// Parse an ISO 8601 timestamp and format it as local date+time.
fn format_local_timestamp(iso_str: &str) -> String {
    crate::turso::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()
        },
    )
}

/// Push `text` to `out`, truncating at `MAX_WORKSPACE_FILE_CHARS` if needed.
fn push_truncated(out: &mut String, text: &str) {
    const MAX_WORKSPACE_FILE_CHARS: usize = 10_000;

    if let Some((idx, _)) = text.char_indices().nth(MAX_WORKSPACE_FILE_CHARS) {
        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 + content.
///
/// Files are returned in deterministic raw file-name order (byte sort), not in
/// `read_dir` enumeration order, so identical rules always render
/// byte-identically — keeping the workspace-context block (and therefore the
/// agent system prompt) stable across renders. File names within a single
/// 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 in the template are replaced with their corresponding
/// values from `replacements`. The replacement uses a regex to match all keys
/// at once, so values can never be re-substituted — a value containing a later
/// key will appear literally, not as a replacement.
///
/// Placeholder keys (the text between `{{` and `}}`) must consist entirely
/// of word characters (`[a-zA-Z0-9_]`). Keys with hyphens (`{{my-key}}`),
/// dots (`{{config.key}}`), or other non‑word characters will remain in the
/// output unexpanded.  The existing test `all_template_variables_are_word_chars`
/// enforces this property across all embedded prompt assets.
///
/// If a `{{key}}` appears in the template but has no corresponding entry in
/// `replacements`, a `tracing::warn!` is emitted at runtime and the literal
/// `{{key}}` string is preserved in the output.  This means a typo in either
/// the template or the replacement keys will produce a visible warning in the
/// log rather than silently corrupting the prompt.
///
/// Callers must pass replacement map keys with the full `{{key}}` wrapper
/// (e.g. `"{{ticket_id}}"`), not just the inner key name.
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::*;

    #[test]
    fn substitute_basic_replacement() {
        let result = substitute(
            "Hello {{name}}, your {{item}} is ready.",
            &[("{{name}}", "Alice"), ("{{item}}", "order")],
        );
        assert_eq!(result, "Hello Alice, your order is ready.");
    }

    #[test]
    fn substitute_preserves_unknown_keys() {
        let result = substitute(
            "Hello {{name}}, here is {{missing}} key.",
            &[("{{name}}", "Alice")],
        );
        assert_eq!(result, "Hello Alice, here is {{missing}} key.");
    }

    #[test]
    fn substitute_no_cascade() {
        // If a replacement value contains a later key pattern, it 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");
    }

    #[test]
    fn substitute_empty_template() {
        let result = substitute("", &[("{{key}}", "value")]);
        assert_eq!(result, "");
    }

    #[test]
    fn substitute_no_replacements() {
        let result = substitute("Hello {{name}}!", &[]);
        assert_eq!(result, "Hello {{name}}!");
    }

    #[tokio::test]
    async fn discover_claude_rules_finds_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();
        // Non-markdown file should be ignored
        std::fs::write(rules_dir.join("notes.txt"), "irrelevant").unwrap();

        let rules = discover_claude_rules(dir.path()).await;
        assert_eq!(rules.len(), 2);
        let paths: Vec<&str> = rules.iter().map(|(p, _)| p.as_str()).collect();
        assert!(paths.contains(&".claude/rules/testing.md"));
        assert!(paths.contains(&".claude/rules/style.md"));
    }

    #[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_skips_unreadable() {
        let dir = tempfile::tempdir().unwrap();
        let rules_dir = dir.path().join(".claude").join("rules");
        std::fs::create_dir_all(&rules_dir).unwrap();
        // Create a file that looks like a dir (unreadable as file)
        let bad = rules_dir.join("broken.md");
        std::fs::write(&bad, "fine").unwrap();
        // Create a valid one too
        std::fs::write(rules_dir.join("good.md"), "good content").unwrap();
        // Both should be found since both are readable
        let rules = discover_claude_rules(dir.path()).await;
        assert_eq!(rules.len(), 2);
    }

    #[tokio::test]
    async fn discover_claude_rules_returns_full_content() {
        let dir = tempfile::tempdir().unwrap();
        let rules_dir = dir.path().join(".claude").join("rules");
        std::fs::create_dir_all(&rules_dir).unwrap();
        // Content over MAX_WORKSPACE_FILE_CHARS — truncation is handled by push_truncated later
        let long = "x".repeat(100_000);
        std::fs::write(rules_dir.join("long.md"), &long).unwrap();
        let rules = discover_claude_rules(dir.path()).await;
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].1.len(), 100_000);
    }

    #[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 in deterministic byte-sorted name order for
        // a stable render (a two-render byte-identity test would pass even
        // pre-fix on APFS's stable-enough order).
        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",
            ]
        );
    }

    #[test]
    fn all_template_variables_are_word_chars() {
        // Every {{...}} placeholder in embedded prompt assets must use
        // \w+ keys (ASCII alphanumeric + underscore) so that TEMPLATE_RE
        // can match and substitute them.  Non-conforming keys like
        // {{role-name}} or {{my var}} would silently remain in the
        // prompt output because the regex never matches them.
        let broad_re =
            regex::Regex::new(r"\{\{([^}]+)\}\}").expect("broad placeholder regex must compile");
        for asset_key in PromptAssets::iter() {
            let asset = PromptAssets::get(&asset_key)
                .unwrap_or_else(|| panic!("asset {asset_key} disappeared between iter and get"));
            let content = String::from_utf8_lossy(asset.data.as_ref());
            for cap in broad_re.captures_iter(&content) {
                let var_name = cap.get(1).unwrap().as_str();
                assert!(
                    var_name
                        .chars()
                        .all(|c| c.is_ascii_alphanumeric() || c == '_'),
                    "Template variable '{{{{{var_name}}}}}' in '{asset_key}' contains non-\\w \
                     characters (only ASCII alphanumeric and underscore are allowed).\n\
                     Template keys must match \\w+ so that TEMPLATE_RE can substitute them. \
                     Use underscores instead of hyphens, dots, or spaces.",
                );
            }
        }
    }

    #[test]
    fn all_prompt_assets_load_non_empty() {
        for asset_key in PromptAssets::iter() {
            let content = load_prompt(&asset_key);
            assert!(
                !content.trim().is_empty(),
                "Prompt asset '{asset_key}' is empty or whitespace-only.\n\
                 Each embedded prompt file must contain meaningful content.",
            );
        }
    }
}