meerkat 0.6.25

Modular, high-performance agent harness for LLM-powered applications
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
//! Unified system prompt assembly.
//!
//! Single canonical path for building the final system prompt with clear
//! precedence rules:
//!
//! 1. Per-request override (via `per_request_prompt`) — wins outright.
//! 2. Config-level file override (`config.agent.system_prompt_file`).
//! 3. Config-level inline override (`config.agent.system_prompt`).
//! 4. Default system prompt + AGENTS.md files.
//! 5. Config-level tool instructions (`config.agent.tool_instructions`).
//! 6. Dispatcher-provided tool usage instructions (appended last).

use meerkat_core::{Config, SystemPromptConfig, prompt::normalize_agents_md_content};
use std::path::Path;

/// Assemble the final system prompt. Single canonical path.
///
/// `per_request_prompt` is the per-request override from `AgentBuildConfig.system_prompt`.
/// `extra_sections` is a forward-compatible slot for additional content
/// (e.g., skill inventory in Phase 3). For now callers pass `&[]`.
pub async fn assemble_system_prompt(
    config: &Config,
    per_request_prompt: Option<&str>,
    context_root: Option<&Path>,
    extra_sections: &[&str],
    tool_usage_instructions: &str,
) -> String {
    // 1. Per-request override wins outright (skips AGENTS.md and config).
    if let Some(prompt) = per_request_prompt {
        return append_sections(prompt, extra_sections, &[], tool_usage_instructions);
    }

    // 2-4. This crate owns filesystem reads and prompt precedence, then passes
    // already-loaded content into core's pure renderer.
    let mut spc = SystemPromptConfig::new();

    // 2. Config-level file override → feeds into SystemPromptConfig.
    if let Some(ref path) = config.agent.system_prompt_file {
        match tokio::fs::read_to_string(path).await {
            Ok(content) => spc.system_prompt = Some(content),
            Err(e) => tracing::warn!("system_prompt_file not readable: {}: {e}", path.display()),
        }
    }

    // 3. Config-level inline override (lower precedence than file).
    if spc.system_prompt.is_none()
        && let Some(ref prompt) = config.agent.system_prompt
    {
        spc.system_prompt = Some(prompt.clone());
    }

    // AGENTS.md is resolved only from explicit context roots.
    if let Some(context) = context_root
        && let Some(content) = load_project_agents_md_in(context).await
    {
        spc = spc.with_project_agents_md_content(content);
    }

    // 4. compose() uses the override if set, otherwise DEFAULT_SYSTEM_PROMPT.
    //    Either way, AGENTS.md files are appended (global + project).
    let base = spc.compose().await;

    // 5. Append config-level tool instructions (if any) before dispatcher instructions.
    let config_tool_sections: Vec<&str> = config
        .agent
        .tool_instructions
        .as_deref()
        .into_iter()
        .collect();

    append_sections(
        &base,
        extra_sections,
        &config_tool_sections,
        tool_usage_instructions,
    )
}

async fn load_project_agents_md_in(dir: &Path) -> Option<String> {
    for candidate in [dir.join("AGENTS.md"), dir.join(".rkat/AGENTS.md")] {
        if let Some(content) = load_agents_md_file(&candidate).await {
            return Some(content);
        }
    }
    None
}

async fn load_agents_md_file(path: &Path) -> Option<String> {
    if !tokio::fs::try_exists(path).await.ok()? {
        return None;
    }

    let content = tokio::fs::read_to_string(path).await.ok()?;
    normalize_agents_md_content(&content)
}

/// Append extra sections and tool instructions to a base prompt.
fn append_sections(
    base: &str,
    extra_sections: &[&str],
    config_tool_sections: &[&str],
    tool_instructions: &str,
) -> String {
    let mut prompt = base.to_string();
    for section in extra_sections {
        if !section.is_empty() {
            prompt.push_str("\n\n");
            prompt.push_str(section);
        }
    }
    for section in config_tool_sections {
        if !section.is_empty() {
            prompt.push_str("\n\n");
            prompt.push_str(section);
        }
    }
    if !tool_instructions.is_empty() {
        prompt.push_str("\n\n");
        prompt.push_str(tool_instructions);
    }
    prompt
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use meerkat_core::prompt::{AGENTS_MD_MAX_BYTES, DEFAULT_SYSTEM_PROMPT};
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn default_config() -> Config {
        Config::default()
    }

    // --- Precedence level 1: per-request override ---

    #[tokio::test]
    async fn test_per_request_override_wins() {
        let config = default_config();
        let result =
            assemble_system_prompt(&config, Some("Per-request prompt"), None, &[], "").await;
        assert_eq!(result, "Per-request prompt");
    }

    #[tokio::test]
    async fn test_per_request_override_skips_config_fields() {
        let mut config = default_config();
        config.agent.system_prompt = Some("Config inline prompt".to_string());
        config.agent.tool_instructions = Some("Config tool instructions".to_string());

        let result =
            assemble_system_prompt(&config, Some("Per-request prompt"), None, &[], "").await;
        // Per-request override skips config.agent.system_prompt and tool_instructions
        assert_eq!(result, "Per-request prompt");
        assert!(!result.contains("Config inline"));
        assert!(!result.contains("Config tool instructions"));
    }

    #[tokio::test]
    async fn test_per_request_override_still_appends_dispatcher_tools() {
        let config = default_config();
        let result = assemble_system_prompt(
            &config,
            Some("Per-request prompt"),
            None,
            &[],
            "Dispatcher tool instructions",
        )
        .await;
        assert!(result.starts_with("Per-request prompt"));
        assert!(result.contains("Dispatcher tool instructions"));
    }

    // --- Precedence level 2: config file override ---

    #[tokio::test]
    async fn test_config_file_override() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("prompt.txt");
        tokio::fs::write(&file_path, "File-based prompt")
            .await
            .unwrap();

        let mut config = default_config();
        config.agent.system_prompt_file = Some(file_path);

        let result = assemble_system_prompt(&config, None, None, &[], "").await;
        assert!(result.contains("File-based prompt"));
        assert!(!result.contains(DEFAULT_SYSTEM_PROMPT));
    }

    #[tokio::test]
    async fn test_config_file_beats_inline() {
        let temp = TempDir::new().unwrap();
        let file_path = temp.path().join("prompt.txt");
        tokio::fs::write(&file_path, "File-based prompt")
            .await
            .unwrap();

        let mut config = default_config();
        config.agent.system_prompt_file = Some(file_path);
        config.agent.system_prompt = Some("Inline prompt".to_string());

        let result = assemble_system_prompt(&config, None, None, &[], "").await;
        assert!(result.contains("File-based prompt"));
        assert!(!result.contains("Inline prompt"));
    }

    #[tokio::test]
    async fn test_config_file_unreadable_falls_through() {
        let mut config = default_config();
        config.agent.system_prompt_file = Some(PathBuf::from("/nonexistent/path/prompt.txt"));
        config.agent.system_prompt = Some("Inline fallback".to_string());

        let result = assemble_system_prompt(&config, None, None, &[], "").await;
        // File unreadable → falls through to inline
        assert!(result.contains("Inline fallback"));
    }

    // --- Precedence level 3: config inline override ---

    #[tokio::test]
    async fn test_config_inline_override() {
        let mut config = default_config();
        config.agent.system_prompt = Some("Inline prompt".to_string());

        let result = assemble_system_prompt(&config, None, None, &[], "").await;
        assert!(result.contains("Inline prompt"));
        assert!(!result.contains(DEFAULT_SYSTEM_PROMPT));
    }

    #[tokio::test]
    async fn test_context_root_agents_md_appended_to_config_inline() {
        let temp = TempDir::new().unwrap();
        let agents_path = temp.path().join("AGENTS.md");
        tokio::fs::write(&agents_path, "Context root instructions")
            .await
            .unwrap();

        let mut config = default_config();
        config.agent.system_prompt = Some("Inline prompt".to_string());

        let result = assemble_system_prompt(&config, None, Some(temp.path()), &[], "").await;
        assert!(result.contains("Inline prompt"));
        assert!(result.contains("Context root instructions"));
        assert!(!result.contains(DEFAULT_SYSTEM_PROMPT));
        let inline_pos = result.find("Inline prompt").unwrap();
        let agents_pos = result.find("Context root instructions").unwrap();
        assert!(inline_pos < agents_pos);
    }

    #[tokio::test]
    async fn test_context_root_agents_md_size_limit_owned_by_prompt_assembly() {
        let temp = TempDir::new().unwrap();
        let agents_path = temp.path().join("AGENTS.md");
        tokio::fs::write(&agents_path, "x".repeat(AGENTS_MD_MAX_BYTES + 1000))
            .await
            .unwrap();

        let config = default_config();
        let result = assemble_system_prompt(&config, None, Some(temp.path()), &[], "").await;
        let agents_section_start = result.find("# Project Instructions").unwrap();
        let agents_content = &result[agents_section_start..];
        assert!(agents_content.len() <= AGENTS_MD_MAX_BYTES + 100);
    }

    #[tokio::test]
    async fn test_context_root_agents_md_falls_back_when_root_file_is_unusable() {
        let temp = TempDir::new().unwrap();
        let agents_path = temp.path().join("AGENTS.md");
        tokio::fs::write(&agents_path, [0xff, 0xfe]).await.unwrap();
        let rkat_dir = temp.path().join(".rkat");
        tokio::fs::create_dir_all(&rkat_dir).await.unwrap();
        tokio::fs::write(rkat_dir.join("AGENTS.md"), "Fallback instructions")
            .await
            .unwrap();

        let config = default_config();
        let result = assemble_system_prompt(&config, None, Some(temp.path()), &[], "").await;
        assert!(result.contains("Fallback instructions"));
    }

    // --- Precedence level 4: default prompt ---

    #[tokio::test]
    async fn test_default_prompt_when_no_overrides() {
        let config = default_config();
        let result = assemble_system_prompt(&config, None, None, &[], "").await;
        assert!(result.contains(DEFAULT_SYSTEM_PROMPT));
    }

    // --- Precedence level 5: config tool instructions ---

    #[tokio::test]
    async fn test_config_tool_instructions_appended() {
        let mut config = default_config();
        config.agent.tool_instructions = Some("Use tools carefully".to_string());

        let result = assemble_system_prompt(&config, None, None, &[], "").await;
        assert!(result.contains("Use tools carefully"));
    }

    #[tokio::test]
    async fn test_config_tool_instructions_before_dispatcher() {
        let mut config = default_config();
        config.agent.tool_instructions = Some("Config tools".to_string());

        let result = assemble_system_prompt(&config, None, None, &[], "Dispatcher tools").await;
        let config_pos = result.find("Config tools").unwrap();
        let dispatcher_pos = result.find("Dispatcher tools").unwrap();
        assert!(
            config_pos < dispatcher_pos,
            "Config tool instructions should come before dispatcher tool instructions"
        );
    }

    // --- Precedence level 6: dispatcher tool instructions ---

    #[tokio::test]
    async fn test_dispatcher_tool_instructions_appended() {
        let config = default_config();
        let result =
            assemble_system_prompt(&config, None, None, &[], "Dispatcher tool instructions").await;
        assert!(result.contains("Dispatcher tool instructions"));
    }

    // --- Extra sections (forward-compatible for skills) ---

    #[tokio::test]
    async fn test_extra_sections_appended() {
        let config = default_config();
        let result = assemble_system_prompt(
            &config,
            None,
            None,
            &["## Available Skills\n- /task-workflow"],
            "",
        )
        .await;
        assert!(result.contains("## Available Skills"));
        assert!(result.contains("/task-workflow"));
    }

    #[tokio::test]
    async fn test_extra_sections_before_tool_instructions() {
        let mut config = default_config();
        config.agent.tool_instructions = Some("Config tools".to_string());

        let result =
            assemble_system_prompt(&config, None, None, &["Skills section"], "Dispatcher tools")
                .await;
        let skills_pos = result.find("Skills section").unwrap();
        let config_tools_pos = result.find("Config tools").unwrap();
        let dispatcher_pos = result.find("Dispatcher tools").unwrap();
        assert!(skills_pos < config_tools_pos);
        assert!(config_tools_pos < dispatcher_pos);
    }

    #[tokio::test]
    async fn test_empty_extra_sections_no_double_newlines() {
        let config = default_config();
        let result = assemble_system_prompt(&config, None, None, &["", ""], "").await;
        // Should not have extra blank sections
        assert!(!result.contains("\n\n\n\n"));
    }

    // --- Integration: all layers together ---

    #[tokio::test]
    async fn test_full_precedence_chain() {
        let mut config = default_config();
        config.agent.system_prompt = Some("Inline base".to_string());
        config.agent.tool_instructions = Some("Config tools".to_string());

        let result = assemble_system_prompt(
            &config,
            None,
            None,
            &["Skills inventory"],
            "Dispatcher tools",
        )
        .await;

        assert!(result.contains("Inline base"));
        assert!(result.contains("Skills inventory"));
        assert!(result.contains("Config tools"));
        assert!(result.contains("Dispatcher tools"));

        // Verify ordering
        let base_pos = result.find("Inline base").unwrap();
        let skills_pos = result.find("Skills inventory").unwrap();
        let config_pos = result.find("Config tools").unwrap();
        let dispatcher_pos = result.find("Dispatcher tools").unwrap();

        assert!(base_pos < skills_pos);
        assert!(skills_pos < config_pos);
        assert!(config_pos < dispatcher_pos);
    }

    // --- Additional instructions via extra_sections ---

    #[tokio::test]
    async fn test_additional_instructions_appear_after_skills_before_tool_instructions() {
        let mut config = default_config();
        config.agent.tool_instructions = Some("Config tools".to_string());

        let result = assemble_system_prompt(
            &config,
            None,
            None,
            &[
                "Skills section",
                "Additional instruction 1",
                "Additional instruction 2",
            ],
            "Dispatcher tools",
        )
        .await;

        let skills_pos = result.find("Skills section").unwrap();
        let instr1_pos = result.find("Additional instruction 1").unwrap();
        let instr2_pos = result.find("Additional instruction 2").unwrap();
        let config_pos = result.find("Config tools").unwrap();
        let dispatcher_pos = result.find("Dispatcher tools").unwrap();

        assert!(skills_pos < instr1_pos, "instructions after skills");
        assert!(instr1_pos < instr2_pos, "instructions preserve order");
        assert!(instr2_pos < config_pos, "instructions before config tools");
        assert!(
            config_pos < dispatcher_pos,
            "config tools before dispatcher"
        );
    }

    #[tokio::test]
    async fn test_additional_instructions_not_after_tool_instructions() {
        let config = default_config();
        let result = assemble_system_prompt(
            &config,
            None,
            None,
            &["My additional instruction"],
            "Dispatcher tools block",
        )
        .await;

        let instruction_pos = result.find("My additional instruction").unwrap();
        let dispatcher_pos = result.find("Dispatcher tools block").unwrap();
        assert!(
            instruction_pos < dispatcher_pos,
            "additional instructions must NOT appear after dispatcher tool instructions"
        );
    }
}