Skip to main content

zeph_core/
instructions.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::collections::HashSet;
5use std::io::Read as _;
6use std::path::{Path, PathBuf};
7use std::time::Duration;
8
9use notify_debouncer_mini::{DebouncedEventKind, new_debouncer};
10use tokio::sync::mpsc;
11
12use crate::config::ProviderKind;
13
14pub enum InstructionEvent {
15    Changed,
16}
17
18pub struct InstructionWatcher {
19    _handle: tokio::task::JoinHandle<()>,
20}
21
22impl InstructionWatcher {
23    /// Start watching directories for instruction file (.md) changes.
24    ///
25    /// Sends `InstructionEvent::Changed` on any `.md` filesystem change (debounced 500ms).
26    ///
27    /// # Errors
28    ///
29    /// Returns an error if the filesystem watcher cannot be initialized.
30    pub fn start(
31        paths: &[PathBuf],
32        tx: mpsc::Sender<InstructionEvent>,
33    ) -> Result<Self, notify::Error> {
34        let (notify_tx, mut notify_rx) = mpsc::channel(16);
35
36        let mut debouncer = new_debouncer(
37            Duration::from_millis(500),
38            move |events: Result<Vec<notify_debouncer_mini::DebouncedEvent>, notify::Error>| {
39                let events = match events {
40                    Ok(events) => events,
41                    Err(e) => {
42                        tracing::warn!("instruction watcher error: {e}");
43                        return;
44                    }
45                };
46
47                let has_md_change = events.iter().any(|e| {
48                    e.kind == DebouncedEventKind::Any
49                        && e.path.extension().is_some_and(|ext| ext == "md")
50                });
51
52                if has_md_change {
53                    let _ = notify_tx.try_send(());
54                }
55            },
56        )?;
57
58        for path in paths {
59            if path.exists()
60                && let Err(e) = debouncer
61                    .watcher()
62                    .watch(path, notify::RecursiveMode::NonRecursive)
63            {
64                tracing::warn!(path = %path.display(), error = %e, "failed to watch instruction path");
65            }
66        }
67
68        tracing::debug!(paths = paths.len(), "starting instruction watcher");
69        let handle = tokio::spawn(async move {
70            let _debouncer = debouncer;
71            while notify_rx.recv().await.is_some() {
72                tracing::debug!("instruction file change detected, signaling reload");
73                if tx.send(InstructionEvent::Changed).await.is_err() {
74                    break;
75                }
76            }
77        });
78
79        Ok(Self { _handle: handle })
80    }
81}
82
83/// Parameters needed to re-run `load_instructions()` on hot-reload.
84pub struct InstructionReloadState {
85    pub base_dir: PathBuf,
86    pub provider_kinds: Vec<ProviderKind>,
87    pub explicit_files: Vec<PathBuf>,
88    pub auto_detect: bool,
89}
90
91/// Maximum size of a single instruction file. Files exceeding this limit are skipped.
92const MAX_FILE_SIZE: u64 = 256 * 1024; // 256 KiB
93
94/// A loaded instruction block from a single file.
95#[derive(Debug, Clone)]
96pub struct InstructionBlock {
97    /// Absolute path of the source file.
98    pub source: PathBuf,
99    /// UTF-8 text content of the file.
100    pub content: String,
101}
102
103/// Load instruction blocks from provider-specific and explicit files.
104///
105/// `base_dir` is resolved as the process working directory at startup via
106/// `std::env::current_dir()`. This matches the directory from which the user
107/// launches `zeph` and is therefore the most natural project root for file
108/// discovery. Non-git projects are fully supported; git root is not used.
109///
110/// Candidate paths are collected in this order:
111/// 1. Always: `base_dir/zeph.md` and `base_dir/.zeph/zeph.md`.
112/// 2. If `auto_detect`, per-provider paths from `detection_paths()` for each kind.
113/// 3. `explicit_files` as provided (trusted — user controls config.toml).
114///
115/// Deduplication uses `fs::canonicalize`. Paths that do not exist are silently
116/// skipped; canonicalize fails on nonexistent paths, so they cannot be deduped
117/// via symlinks against existing paths — this is an acceptable edge case documented here.
118pub fn load_instructions(
119    base_dir: &Path,
120    provider_kinds: &[ProviderKind],
121    explicit_files: &[PathBuf],
122    auto_detect: bool,
123) -> Vec<InstructionBlock> {
124    let canonical_base = match std::fs::canonicalize(base_dir) {
125        Ok(c) => c,
126        Err(e) => {
127            tracing::warn!(path = %base_dir.display(), error = %e, "failed to canonicalize base_dir, skipping all instruction files");
128            return Vec::new();
129        }
130    };
131
132    let mut candidates: Vec<PathBuf> = Vec::new();
133
134    // zeph.md is always checked regardless of provider or auto_detect setting.
135    candidates.push(base_dir.join("zeph.md"));
136    candidates.push(base_dir.join(".zeph").join("zeph.md"));
137
138    if auto_detect {
139        for &kind in provider_kinds {
140            candidates.extend(detection_paths(kind, base_dir));
141        }
142    }
143
144    // Explicit files are trusted (user controls config). Resolve relative to base_dir.
145    for p in explicit_files {
146        if p.is_absolute() {
147            candidates.push(p.clone());
148        } else {
149            candidates.push(base_dir.join(p));
150        }
151    }
152
153    // Deduplicate by canonical path. Only existing paths can be canonicalized.
154    let mut seen: HashSet<PathBuf> = HashSet::new();
155    let mut result: Vec<InstructionBlock> = Vec::new();
156
157    for path in candidates {
158        // Canonicalize first to resolve symlinks before opening — eliminates TOCTOU race.
159        // Nonexistent or unreadable paths are silently skipped.
160        let Ok(canonical) = std::fs::canonicalize(&path) else {
161            continue;
162        };
163
164        if !canonical.starts_with(&canonical_base) {
165            tracing::warn!(path = %canonical.display(), "instruction file escapes project root, skipping");
166            continue;
167        }
168
169        if !seen.insert(canonical.clone()) {
170            // Already loaded this path via a different candidate or symlink.
171            continue;
172        }
173
174        // Open the canonical path after boundary check — no TOCTOU window for symlink swap.
175        let Ok(file) = std::fs::File::open(&canonical) else {
176            continue;
177        };
178
179        let meta = match file.metadata() {
180            Ok(m) => m,
181            Err(e) => {
182                tracing::warn!(path = %path.display(), error = %e, "failed to read instruction file metadata, skipping");
183                continue;
184            }
185        };
186
187        if !meta.is_file() {
188            continue;
189        }
190
191        if meta.len() > MAX_FILE_SIZE {
192            tracing::warn!(
193                path = %path.display(),
194                size = meta.len(),
195                limit = MAX_FILE_SIZE,
196                "instruction file exceeds 256 KiB size limit, skipping"
197            );
198            continue;
199        }
200
201        let mut content = String::new();
202        match std::io::BufReader::new(file).read_to_string(&mut content) {
203            Ok(_) => {}
204            Err(e) => {
205                tracing::warn!(path = %path.display(), error = %e, "failed to read instruction file, skipping");
206                continue;
207            }
208        }
209
210        if content.contains('\0') {
211            tracing::warn!(path = %path.display(), "instruction file contains null bytes, skipping");
212            continue;
213        }
214
215        if content.is_empty() {
216            tracing::debug!(path = %path.display(), "instruction file is empty, skipping");
217            continue;
218        }
219
220        tracing::debug!(path = %path.display(), bytes = content.len(), "loaded instruction file");
221        result.push(InstructionBlock {
222            source: path,
223            content,
224        });
225    }
226
227    result
228}
229
230/// Returns candidate file paths for a given provider.
231///
232/// Uses an exhaustive match — adding a new `ProviderKind` variant will cause
233/// a compile error here, forcing the developer to update the detection table.
234fn detection_paths(kind: ProviderKind, base: &Path) -> Vec<PathBuf> {
235    match kind {
236        ProviderKind::Claude => {
237            let mut paths = vec![
238                base.join("CLAUDE.md"),
239                base.join(".claude").join("CLAUDE.md"),
240            ];
241            // Collect .claude/rules/*.md sorted by name for deterministic order.
242            let rules_dir = base.join(".claude").join("rules");
243            if let Ok(entries) = std::fs::read_dir(&rules_dir) {
244                let mut rule_files: Vec<PathBuf> = entries
245                    .filter_map(std::result::Result::ok)
246                    .map(|e| e.path())
247                    .filter(|p| p.extension().is_some_and(|ext| ext == "md"))
248                    .collect();
249                rule_files.sort();
250                paths.extend(rule_files);
251            }
252            paths
253        }
254        ProviderKind::OpenAi => {
255            vec![base.join("AGENTS.override.md"), base.join("AGENTS.md")]
256        }
257        ProviderKind::Compatible
258        | ProviderKind::Ollama
259        | ProviderKind::Candle
260        | ProviderKind::Gemini => {
261            vec![base.join("AGENTS.md")]
262        }
263        // Router and Orchestrator delegate to their sub-providers; detection
264        // is handled by the caller collecting sub-provider kinds separately.
265        ProviderKind::Router | ProviderKind::Orchestrator => vec![],
266    }
267}
268
269#[cfg(test)]
270mod watcher_tests {
271    use super::*;
272    use tokio::sync::mpsc;
273
274    #[tokio::test]
275    async fn start_with_valid_directory() {
276        let dir = tempfile::tempdir().unwrap();
277        let (tx, _rx) = mpsc::channel(16);
278        let result = InstructionWatcher::start(&[dir.path().to_path_buf()], tx);
279        assert!(result.is_ok());
280    }
281
282    #[tokio::test]
283    async fn start_with_empty_paths() {
284        let (tx, _rx) = mpsc::channel(16);
285        let result = InstructionWatcher::start(&[], tx);
286        assert!(result.is_ok());
287    }
288
289    #[tokio::test]
290    async fn detects_md_file_change() {
291        let dir = tempfile::tempdir().unwrap();
292        let (tx, mut rx) = mpsc::channel(16);
293        let _watcher = InstructionWatcher::start(&[dir.path().to_path_buf()], tx).unwrap();
294
295        let md_path = dir.path().join("zeph.md");
296        std::fs::write(&md_path, "initial").unwrap();
297
298        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
299        std::fs::write(&md_path, "updated").unwrap();
300
301        let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv()).await;
302        assert!(
303            result.is_ok(),
304            "expected InstructionEvent::Changed within timeout"
305        );
306    }
307
308    #[tokio::test]
309    async fn ignores_non_md_file_change() {
310        let dir = tempfile::tempdir().unwrap();
311        let (tx, mut rx) = mpsc::channel(16);
312        let _watcher = InstructionWatcher::start(&[dir.path().to_path_buf()], tx).unwrap();
313
314        let other_path = dir.path().join("notes.txt");
315        std::fs::write(&other_path, "content").unwrap();
316
317        let result = tokio::time::timeout(std::time::Duration::from_millis(1500), rx.recv()).await;
318        assert!(result.is_err(), "should not receive event for non-.md file");
319    }
320
321    #[tokio::test]
322    async fn detects_md_file_deletion() {
323        let dir = tempfile::tempdir().unwrap();
324        let md_path = dir.path().join("zeph.md");
325        std::fs::write(&md_path, "content").unwrap();
326
327        let (tx, mut rx) = mpsc::channel(16);
328        let _watcher = InstructionWatcher::start(&[dir.path().to_path_buf()], tx).unwrap();
329
330        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
331        std::fs::remove_file(&md_path).unwrap();
332
333        let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv()).await;
334        assert!(
335            result.is_ok(),
336            "expected InstructionEvent::Changed on .md deletion"
337        );
338    }
339}
340
341#[cfg(test)]
342mod reload_tests {
343    use super::*;
344
345    #[test]
346    fn reload_returns_updated_blocks_when_file_changes() {
347        let dir = tempfile::tempdir().unwrap();
348        let md_path = dir.path().join("zeph.md");
349        std::fs::write(&md_path, "initial content").unwrap();
350
351        let blocks = load_instructions(dir.path(), &[], &[], false);
352        assert_eq!(blocks.len(), 1);
353        assert_eq!(blocks[0].content, "initial content");
354
355        std::fs::write(&md_path, "updated content").unwrap();
356        let blocks2 = load_instructions(dir.path(), &[], &[], false);
357        assert_eq!(blocks2.len(), 1);
358        assert_eq!(blocks2[0].content, "updated content");
359    }
360
361    #[test]
362    fn reload_returns_empty_when_file_deleted() {
363        let dir = tempfile::tempdir().unwrap();
364        let md_path = dir.path().join("zeph.md");
365        std::fs::write(&md_path, "content").unwrap();
366
367        let blocks = load_instructions(dir.path(), &[], &[], false);
368        assert_eq!(blocks.len(), 1);
369
370        std::fs::remove_file(&md_path).unwrap();
371        let blocks2 = load_instructions(dir.path(), &[], &[], false);
372        assert!(
373            blocks2.is_empty(),
374            "deleted file should not be loaded on reload"
375        );
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382    use std::fs;
383    use tempfile::TempDir;
384
385    fn make_file(dir: &Path, name: &str, content: &str) -> PathBuf {
386        let path = dir.join(name);
387        if let Some(parent) = path.parent() {
388            fs::create_dir_all(parent).unwrap();
389        }
390        fs::write(&path, content).unwrap();
391        path
392    }
393
394    #[test]
395    fn zeph_md_loaded_even_when_auto_detect_disabled() {
396        let dir = TempDir::new().unwrap();
397        make_file(dir.path(), "zeph.md", "some content");
398        let blocks = load_instructions(dir.path(), &[], &[], false);
399        assert_eq!(blocks.len(), 1);
400        assert_eq!(blocks[0].content, "some content");
401    }
402
403    #[test]
404    fn empty_when_no_auto_detect_and_no_explicit_and_no_zeph_md() {
405        let dir = TempDir::new().unwrap();
406        let blocks = load_instructions(dir.path(), &[], &[], false);
407        assert!(blocks.is_empty());
408    }
409
410    #[test]
411    fn finds_zeph_md_in_base_dir() {
412        let dir = TempDir::new().unwrap();
413        make_file(dir.path(), "zeph.md", "zeph instructions");
414        let blocks = load_instructions(dir.path(), &[], &[], true);
415        assert_eq!(blocks.len(), 1);
416        assert_eq!(blocks[0].content, "zeph instructions");
417    }
418
419    #[test]
420    fn finds_dot_zeph_zeph_md() {
421        let dir = TempDir::new().unwrap();
422        make_file(dir.path(), ".zeph/zeph.md", "nested zeph instructions");
423        let blocks = load_instructions(dir.path(), &[], &[], true);
424        assert_eq!(blocks.len(), 1);
425        assert_eq!(blocks[0].content, "nested zeph instructions");
426    }
427
428    #[test]
429    fn detection_paths_claude() {
430        let dir = TempDir::new().unwrap();
431        make_file(dir.path(), "CLAUDE.md", "# Claude");
432        make_file(dir.path(), ".claude/CLAUDE.md", "# Dot Claude");
433        make_file(dir.path(), ".claude/rules/a.md", "rule a");
434        make_file(dir.path(), ".claude/rules/b.md", "rule b");
435
436        let blocks = load_instructions(dir.path(), &[ProviderKind::Claude], &[], true);
437        let sources: Vec<_> = blocks
438            .iter()
439            .map(|b| b.source.file_name().unwrap().to_str().unwrap())
440            .collect();
441        assert!(sources.contains(&"CLAUDE.md"));
442        assert!(sources.contains(&"a.md"));
443        assert!(sources.contains(&"b.md"));
444    }
445
446    #[test]
447    fn detection_paths_openai() {
448        let dir = TempDir::new().unwrap();
449        make_file(dir.path(), "AGENTS.md", "# Agents");
450
451        let paths = detection_paths(ProviderKind::OpenAi, dir.path());
452        assert!(paths.iter().any(|p| p.file_name().unwrap() == "AGENTS.md"));
453        assert!(
454            paths
455                .iter()
456                .any(|p| p.file_name().unwrap() == "AGENTS.override.md")
457        );
458    }
459
460    #[test]
461    fn detection_paths_ollama_and_compatible_and_candle() {
462        let dir = TempDir::new().unwrap();
463        for kind in [
464            ProviderKind::Ollama,
465            ProviderKind::Compatible,
466            ProviderKind::Candle,
467        ] {
468            let paths = detection_paths(kind, dir.path());
469            assert_eq!(paths.len(), 1);
470            assert_eq!(paths[0].file_name().unwrap(), "AGENTS.md");
471        }
472    }
473
474    #[test]
475    fn detection_paths_router_and_orchestrator_empty() {
476        let dir = TempDir::new().unwrap();
477        assert!(detection_paths(ProviderKind::Router, dir.path()).is_empty());
478        assert!(detection_paths(ProviderKind::Orchestrator, dir.path()).is_empty());
479    }
480
481    #[test]
482    fn deduplication_by_canonical_path() {
483        let dir = TempDir::new().unwrap();
484        make_file(dir.path(), "AGENTS.md", "content");
485
486        // Both Ollama and Compatible resolve to AGENTS.md — should appear once.
487        let blocks = load_instructions(
488            dir.path(),
489            &[ProviderKind::Ollama, ProviderKind::Compatible],
490            &[],
491            true,
492        );
493        let agents_count = blocks
494            .iter()
495            .filter(|b| b.source.file_name().unwrap() == "AGENTS.md")
496            .count();
497        assert_eq!(agents_count, 1);
498    }
499
500    #[test]
501    fn skips_files_exceeding_size_limit() {
502        let dir = TempDir::new().unwrap();
503        let path = dir.path().join("big.md");
504        // Write slightly more than 512 KB.
505        let big = vec![b'x'; 513 * 1024];
506        fs::write(&path, &big).unwrap();
507        let blocks = load_instructions(dir.path(), &[], &[path], false);
508        assert!(blocks.is_empty());
509    }
510
511    #[test]
512    fn skips_empty_files() {
513        let dir = TempDir::new().unwrap();
514        make_file(dir.path(), "zeph.md", "");
515        let blocks = load_instructions(dir.path(), &[], &[], true);
516        assert!(blocks.is_empty());
517    }
518
519    #[test]
520    fn nonexistent_paths_are_silently_skipped() {
521        let dir = TempDir::new().unwrap();
522        let nonexistent = dir.path().join("does_not_exist.md");
523        let blocks = load_instructions(dir.path(), &[], &[nonexistent], false);
524        assert!(blocks.is_empty());
525    }
526
527    #[test]
528    fn explicit_relative_path_resolved_against_base_dir() {
529        let dir = TempDir::new().unwrap();
530        make_file(dir.path(), "custom.md", "custom content");
531        let blocks = load_instructions(dir.path(), &[], &[PathBuf::from("custom.md")], false);
532        assert_eq!(blocks.len(), 1);
533        assert_eq!(blocks[0].content, "custom content");
534    }
535
536    #[test]
537    fn invalid_utf8_file_is_skipped() {
538        let dir = TempDir::new().unwrap();
539        let path = dir.path().join("bad.md");
540        // Write bytes that are not valid UTF-8.
541        fs::write(&path, b"\xff\xfe invalid utf8 \x80\x81").unwrap();
542        let blocks = load_instructions(dir.path(), &[], &[path], false);
543        assert!(blocks.is_empty());
544    }
545
546    #[test]
547    fn multiple_providers_union_without_overlap() {
548        let dir = TempDir::new().unwrap();
549        make_file(dir.path(), "CLAUDE.md", "claude content");
550        make_file(dir.path(), "AGENTS.md", "agents content");
551
552        let blocks = load_instructions(
553            dir.path(),
554            &[ProviderKind::Claude, ProviderKind::OpenAi],
555            &[],
556            true,
557        );
558        let names: Vec<_> = blocks
559            .iter()
560            .map(|b| b.source.file_name().unwrap().to_str().unwrap())
561            .collect();
562        assert!(names.contains(&"CLAUDE.md"), "Claude file missing");
563        assert!(names.contains(&"AGENTS.md"), "OpenAI file missing");
564    }
565
566    #[test]
567    fn zeph_md_always_loaded_with_provider_auto_detect() {
568        let dir = TempDir::new().unwrap();
569        make_file(dir.path(), "zeph.md", "zeph rules");
570        // OpenAI provider has no AGENTS.md present, only zeph.md.
571        let blocks = load_instructions(dir.path(), &[ProviderKind::OpenAi], &[], true);
572        assert_eq!(blocks.len(), 1);
573        assert_eq!(blocks[0].content, "zeph rules");
574    }
575
576    #[cfg(unix)]
577    #[test]
578    fn symlink_deduplication() {
579        use std::os::unix::fs::symlink;
580        let dir = TempDir::new().unwrap();
581        make_file(dir.path(), "CLAUDE.md", "claude content");
582        symlink(
583            dir.path().join("CLAUDE.md"),
584            dir.path().join("CLAUDE_link.md"),
585        )
586        .unwrap();
587
588        // Load the original and the symlink — should appear only once after dedup.
589        let blocks = load_instructions(
590            dir.path(),
591            &[ProviderKind::Claude],
592            &[PathBuf::from("CLAUDE_link.md")],
593            true,
594        );
595        let claude_count = blocks
596            .iter()
597            .filter(|b| b.content == "claude content")
598            .count();
599        assert_eq!(claude_count, 1, "symlink should be deduped with original");
600    }
601
602    #[cfg(unix)]
603    #[test]
604    fn symlink_escaping_project_root_is_rejected() {
605        use std::os::unix::fs::symlink;
606        let outside = TempDir::new().unwrap();
607        let inside = TempDir::new().unwrap();
608        make_file(outside.path(), "secret.md", "secret content");
609
610        // Create a symlink inside the project dir pointing outside.
611        let link = inside.path().join("evil.md");
612        symlink(outside.path().join("secret.md"), &link).unwrap();
613
614        let blocks = load_instructions(inside.path(), &[], &[link], false);
615        assert!(
616            blocks.is_empty(),
617            "file escaping project root must be rejected"
618        );
619    }
620
621    #[test]
622    fn file_with_null_bytes_is_skipped() {
623        let dir = TempDir::new().unwrap();
624        let path = dir.path().join("null.md");
625        fs::write(&path, b"content\x00more").unwrap();
626        let blocks = load_instructions(dir.path(), &[], &[path], false);
627        assert!(blocks.is_empty());
628    }
629}