zeph-core 0.12.6

Core agent loop, configuration, context builder, metrics, and vault for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::sync::LazyLock;

use zeph_memory::TokenCounter;

use crate::instructions::InstructionBlock;

const BASE_PROMPT_HEADER: &str = "\
You are Zeph, an AI coding assistant running in the user's terminal.";

const TOOL_USE_LEGACY: &str = "\
\n\n## Tool Use\n\
The ONLY way to execute commands is by writing bash in a fenced code block \
with the `bash` language tag. The block runs automatically and the output is returned to you.\n\
\n\
Example:\n\
```bash\n\
ls -la\n\
```\n\
\n\
Do NOT invent other formats (tool_code, tool_call, <execute>, etc.). \
Only ```bash blocks are executed; anything else is treated as plain text.";

const TOOL_USE_NATIVE: &str = "\
\n\n## Tool Use\n\
You have access to tools via the API. Use them by calling the appropriate tool \
with the required parameters. Do NOT write fenced code blocks to invoke tools; \
use the structured tool_use mechanism instead.\n\
\n\
**CRITICAL: When `read_file` is available, you MUST use it instead of bash \
alternatives (`cat`, `head`, `tail`, `sed`). DO NOT invoke bash for file reading. \
`read_file` returns structured output with line numbers and metadata.**\n\
\n\
Similarly prefer `write_file` over shell redirects, and `list_directory` / \
`find_path` over `ls` / `find` when available.";

const BASE_PROMPT_TAIL: &str = "\
\n\n## Skills\n\
Skills are instructions that may appear below inside XML tags. \
Read them and follow the instructions.\n\
\n\
If you see a list of other skill names and descriptions, those are \
for reference only. You cannot invoke or load them. Ignore them unless \
the user explicitly asks about a skill by name.\n\
\n\
## Guidelines\n\
- Be concise. Avoid unnecessary preamble.\n\
- Before editing files, read them first to understand current state.\n\
- When exploring a codebase, start with directory listing, then targeted grep/find.\n\
- For destructive commands (rm, git push --force), warn the user first.\n\
- Do not hallucinate file contents or command outputs.\n\
- If a command fails, analyze the error before retrying.\n\
\n\
## Security\n\
- Never include secrets, API keys, or tokens in command output.\n\
- Do not force-push to main/master branches.\n\
- Do not execute commands that could cause data loss without confirmation.";

static PROMPT_LEGACY: LazyLock<String> = LazyLock::new(|| {
    let mut s = String::with_capacity(
        BASE_PROMPT_HEADER.len() + TOOL_USE_LEGACY.len() + BASE_PROMPT_TAIL.len(),
    );
    s.push_str(BASE_PROMPT_HEADER);
    s.push_str(TOOL_USE_LEGACY);
    s.push_str(BASE_PROMPT_TAIL);
    s
});

static PROMPT_NATIVE: LazyLock<String> = LazyLock::new(|| {
    let mut s = String::with_capacity(
        BASE_PROMPT_HEADER.len() + TOOL_USE_NATIVE.len() + BASE_PROMPT_TAIL.len(),
    );
    s.push_str(BASE_PROMPT_HEADER);
    s.push_str(TOOL_USE_NATIVE);
    s.push_str(BASE_PROMPT_TAIL);
    s
});

#[must_use]
pub fn build_system_prompt(
    skills_prompt: &str,
    env: Option<&EnvironmentContext>,
    tool_catalog: Option<&str>,
    native_tools: bool,
) -> String {
    build_system_prompt_with_instructions(skills_prompt, env, tool_catalog, native_tools, &[])
}

/// Build the system prompt, injecting instruction blocks into the volatile section
/// (Block 2 — after env context, before skills and tool catalog).
///
/// Instruction file content is user-editable and must NOT be placed in the stable
/// cache block. It is injected here, in the dynamic/volatile section, so that
/// prompt-caching (epic #1082) is not disrupted.
#[must_use]
pub fn build_system_prompt_with_instructions(
    skills_prompt: &str,
    env: Option<&EnvironmentContext>,
    tool_catalog: Option<&str>,
    native_tools: bool,
    instructions: &[InstructionBlock],
) -> String {
    let base = if native_tools {
        &*PROMPT_NATIVE
    } else {
        &*PROMPT_LEGACY
    };
    let instructions_len: usize = instructions
        .iter()
        .map(|b| b.source.display().to_string().len() + b.content.len() + 30)
        .sum();
    let dynamic_len = env.map_or(0, |e| e.format().len() + 2)
        + instructions_len
        + tool_catalog.map_or(0, |c| if c.is_empty() { 0 } else { c.len() + 2 })
        + if skills_prompt.is_empty() {
            0
        } else {
            skills_prompt.len() + 2
        };
    let mut prompt = String::with_capacity(base.len() + dynamic_len);
    prompt.push_str(base);

    if let Some(env) = env {
        prompt.push_str("\n\n");
        prompt.push_str(&env.format());
    }

    // Instruction blocks are placed after env context (volatile, user-editable content).
    // Safety: instruction content is user-trusted (controlled via local files and config).
    // No sanitization is applied — see instructions.rs doc comment for trust model.
    for block in instructions {
        prompt.push_str("\n\n<!-- instructions: ");
        prompt.push_str(
            &block
                .source
                .file_name()
                .unwrap_or_default()
                .to_string_lossy(),
        );
        prompt.push_str(" -->\n");
        prompt.push_str(&block.content);
    }

    if let Some(catalog) = tool_catalog
        && !catalog.is_empty()
    {
        prompt.push_str("\n\n");
        prompt.push_str(catalog);
    }

    if !skills_prompt.is_empty() {
        prompt.push_str("\n\n");
        prompt.push_str(skills_prompt);
    }

    prompt
}

#[derive(Debug, Clone)]
pub struct EnvironmentContext {
    pub working_dir: String,
    pub git_branch: Option<String>,
    pub os: String,
    pub model_name: String,
}

impl EnvironmentContext {
    #[must_use]
    pub fn gather(model_name: &str) -> Self {
        let working_dir =
            std::env::current_dir().map_or_else(|_| "unknown".into(), |p| p.display().to_string());

        let git_branch = std::process::Command::new("git")
            .args(["branch", "--show-current"])
            .output()
            .ok()
            .and_then(|o| {
                if o.status.success() {
                    Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                } else {
                    None
                }
            });

        Self {
            working_dir,
            git_branch,
            os: std::env::consts::OS.into(),
            model_name: model_name.into(),
        }
    }

    /// Update only the git branch, leaving all other fields unchanged.
    pub fn refresh_git_branch(&mut self) {
        self.git_branch = std::process::Command::new("git")
            .args(["branch", "--show-current"])
            .output()
            .ok()
            .and_then(|o| {
                if o.status.success() {
                    Some(String::from_utf8_lossy(&o.stdout).trim().to_string())
                } else {
                    None
                }
            });
    }

    #[must_use]
    pub fn format(&self) -> String {
        use std::fmt::Write;
        let mut out = String::from("<environment>\n");
        let _ = writeln!(out, "  working_directory: {}", self.working_dir);
        let _ = writeln!(out, "  os: {}", self.os);
        let _ = writeln!(out, "  model: {}", self.model_name);
        if let Some(ref branch) = self.git_branch {
            let _ = writeln!(out, "  git_branch: {branch}");
        }
        out.push_str("</environment>");
        out
    }
}

#[derive(Debug, Clone)]
pub struct BudgetAllocation {
    pub system_prompt: usize,
    pub skills: usize,
    pub summaries: usize,
    pub semantic_recall: usize,
    pub cross_session: usize,
    pub code_context: usize,
    pub recent_history: usize,
    pub response_reserve: usize,
}

#[derive(Debug, Clone)]
pub struct ContextBudget {
    max_tokens: usize,
    reserve_ratio: f32,
}

impl ContextBudget {
    #[must_use]
    pub fn new(max_tokens: usize, reserve_ratio: f32) -> Self {
        Self {
            max_tokens,
            reserve_ratio,
        }
    }

    #[must_use]
    pub fn max_tokens(&self) -> usize {
        self.max_tokens
    }

    #[must_use]
    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss
    )]
    pub fn allocate(
        &self,
        system_prompt: &str,
        skills_prompt: &str,
        tc: &TokenCounter,
    ) -> BudgetAllocation {
        if self.max_tokens == 0 {
            return BudgetAllocation {
                system_prompt: 0,
                skills: 0,
                summaries: 0,
                semantic_recall: 0,
                cross_session: 0,
                code_context: 0,
                recent_history: 0,
                response_reserve: 0,
            };
        }

        let response_reserve = (self.max_tokens as f32 * self.reserve_ratio) as usize;
        let mut available = self.max_tokens.saturating_sub(response_reserve);

        let system_prompt_tokens = tc.count_tokens(system_prompt);
        let skills_tokens = tc.count_tokens(skills_prompt);

        available = available.saturating_sub(system_prompt_tokens + skills_tokens);

        let summaries = (available as f32 * 0.08) as usize;
        let semantic_recall = (available as f32 * 0.08) as usize;
        let cross_session = (available as f32 * 0.04) as usize;
        let code_context = (available as f32 * 0.30) as usize;
        let recent_history = (available as f32 * 0.50) as usize;

        BudgetAllocation {
            system_prompt: system_prompt_tokens,
            skills: skills_tokens,
            summaries,
            semantic_recall,
            cross_session,
            code_context,
            recent_history,
            response_reserve,
        }
    }
}

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

    #[test]
    fn without_skills() {
        let prompt = build_system_prompt("", None, None, false);
        assert!(prompt.starts_with("You are Zeph"));
        assert!(!prompt.contains("available_skills"));
    }

    #[test]
    fn with_skills() {
        let prompt = build_system_prompt(
            "<available_skills>test</available_skills>",
            None,
            None,
            false,
        );
        assert!(prompt.contains("You are Zeph"));
        assert!(prompt.contains("<available_skills>"));
    }

    #[test]
    fn context_budget_max_tokens_accessor() {
        let budget = ContextBudget::new(1000, 0.2);
        assert_eq!(budget.max_tokens(), 1000);
    }

    #[test]
    fn budget_allocation_basic() {
        let budget = ContextBudget::new(1000, 0.20);
        let system = "system prompt";
        let skills = "skills prompt";

        let tc = zeph_memory::TokenCounter::new();
        let alloc = budget.allocate(system, skills, &tc);

        assert_eq!(alloc.response_reserve, 200);
        assert!(alloc.system_prompt > 0);
        assert!(alloc.skills > 0);
        assert!(alloc.summaries > 0);
        assert!(alloc.semantic_recall > 0);
        assert!(alloc.cross_session > 0);
        assert!(alloc.recent_history > 0);
    }

    #[test]
    fn budget_allocation_reserve() {
        let tc = zeph_memory::TokenCounter::new();
        let budget = ContextBudget::new(1000, 0.30);
        let alloc = budget.allocate("", "", &tc);

        assert_eq!(alloc.response_reserve, 300);
    }

    #[test]
    fn budget_allocation_zero_disables() {
        let tc = zeph_memory::TokenCounter::new();
        let budget = ContextBudget::new(0, 0.20);
        let alloc = budget.allocate("test", "test", &tc);

        assert_eq!(alloc.system_prompt, 0);
        assert_eq!(alloc.skills, 0);
        assert_eq!(alloc.summaries, 0);
        assert_eq!(alloc.semantic_recall, 0);
        assert_eq!(alloc.cross_session, 0);
        assert_eq!(alloc.code_context, 0);
        assert_eq!(alloc.recent_history, 0);
        assert_eq!(alloc.response_reserve, 0);
    }

    #[test]
    fn budget_allocation_small_window() {
        let tc = zeph_memory::TokenCounter::new();
        let budget = ContextBudget::new(100, 0.20);
        let system = "very long system prompt that uses many tokens";
        let skills = "also a long skills prompt";

        let alloc = budget.allocate(system, skills, &tc);

        assert!(alloc.response_reserve > 0);
    }

    #[test]
    fn environment_context_gather() {
        let env = EnvironmentContext::gather("test-model");
        assert!(!env.working_dir.is_empty());
        assert_eq!(env.os, std::env::consts::OS);
        assert_eq!(env.model_name, "test-model");
    }

    #[test]
    fn refresh_git_branch_does_not_panic() {
        let mut env = EnvironmentContext::gather("test-model");
        let original_dir = env.working_dir.clone();
        let original_os = env.os.clone();
        let original_model = env.model_name.clone();

        env.refresh_git_branch();

        // Other fields must remain unchanged.
        assert_eq!(env.working_dir, original_dir);
        assert_eq!(env.os, original_os);
        assert_eq!(env.model_name, original_model);
        // git_branch is Some or None — both are valid. Just verify format output is coherent.
        let formatted = env.format();
        assert!(formatted.starts_with("<environment>"));
        assert!(formatted.ends_with("</environment>"));
    }

    #[test]
    fn refresh_git_branch_overwrites_previous_branch() {
        let mut env = EnvironmentContext {
            working_dir: "/tmp".into(),
            git_branch: Some("old-branch".into()),
            os: "linux".into(),
            model_name: "test".into(),
        };
        env.refresh_git_branch();
        // After refresh, git_branch reflects the actual git state (Some or None).
        // Importantly the call must not panic and must no longer hold "old-branch"
        // when running outside a git repo with that branch name.
        // We just verify the field is in a valid state (Some string or None).
        match &env.git_branch {
            Some(b) => assert!(!b.contains('\n'), "branch name must not contain newlines"),
            None => {} // not in a git repo — acceptable
        }
    }

    #[test]
    fn environment_context_format() {
        let env = EnvironmentContext {
            working_dir: "/tmp/test".into(),
            git_branch: Some("main".into()),
            os: "macos".into(),
            model_name: "qwen3:8b".into(),
        };
        let formatted = env.format();
        assert!(formatted.starts_with("<environment>"));
        assert!(formatted.ends_with("</environment>"));
        assert!(formatted.contains("working_directory: /tmp/test"));
        assert!(formatted.contains("os: macos"));
        assert!(formatted.contains("model: qwen3:8b"));
        assert!(formatted.contains("git_branch: main"));
    }

    #[test]
    fn environment_context_format_no_git() {
        let env = EnvironmentContext {
            working_dir: "/tmp".into(),
            git_branch: None,
            os: "linux".into(),
            model_name: "test".into(),
        };
        let formatted = env.format();
        assert!(!formatted.contains("git_branch"));
    }

    #[test]
    fn build_system_prompt_with_env() {
        let env = EnvironmentContext {
            working_dir: "/tmp".into(),
            git_branch: None,
            os: "linux".into(),
            model_name: "test".into(),
        };
        let prompt = build_system_prompt("skills here", Some(&env), None, false);
        assert!(prompt.contains("You are Zeph"));
        assert!(prompt.contains("<environment>"));
        assert!(prompt.contains("skills here"));
    }

    #[test]
    fn build_system_prompt_without_env() {
        let prompt = build_system_prompt("skills here", None, None, false);
        assert!(prompt.contains("You are Zeph"));
        assert!(!prompt.contains("<environment>"));
        assert!(prompt.contains("skills here"));
    }

    #[test]
    fn base_prompt_contains_guidelines() {
        let prompt = build_system_prompt("", None, None, false);
        assert!(prompt.contains("## Tool Use"));
        assert!(prompt.contains("## Guidelines"));
        assert!(prompt.contains("## Security"));
    }

    #[test]
    fn budget_allocation_cross_session_percentage() {
        let budget = ContextBudget::new(10000, 0.20);
        let tc = zeph_memory::TokenCounter::new();
        let alloc = budget.allocate("", "", &tc);

        // cross_session = 4%, summaries = 8%, recall = 8%
        assert!(alloc.cross_session > 0);
        assert!(alloc.cross_session < alloc.summaries);
        assert_eq!(alloc.summaries, alloc.semantic_recall);
    }
}