Skip to main content

tinyharness_lib/
context.rs

1use std::{
2    fs,
3    path::{Path, PathBuf},
4};
5
6/// Maximum size for a project instruction file (characters).
7/// Files exceeding this are truncated with a notice. Matches Hermes Agent's limit.
8const PROJECT_MD_MAX_CHARS: usize = 20_000;
9
10/// Head retention ratio for truncated files (70%).
11const PROJECT_MD_HEAD_RATIO: f64 = 0.70;
12
13/// File names to search for, in priority order (first match wins).
14/// Mirrors the priority system used by Hermes Agent:
15///   .hermes.md → AGENTS.md → CLAUDE.md → .cursorrules
16pub const DEFAULT_PROJECT_MD_FILE_NAMES: &[&str] = &[
17    "TINYHARNESS.md",
18    ".tinyharness.md",
19    "AGENTS.md",
20    "CLAUDE.md",
21];
22
23/// Compatibility alias — kept for existing internal references.
24pub const PROJECT_MD_FILE_NAMES: &[&str] = DEFAULT_PROJECT_MD_FILE_NAMES;
25
26/// Collected metadata about the workspace/repository the agent is operating in.
27#[derive(Debug, Clone)]
28pub struct WorkspaceContext {
29    /// Absolute path to the workspace root (current working directory).
30    pub root: PathBuf,
31    /// Detected project type (e.g. "Rust", "Node.js", "Python", "Unknown").
32    pub project_type: String,
33    /// Project name extracted from Cargo.toml / package.json / setup.py etc.
34    pub project_name: String,
35    /// Top-level directory listing (files and dirs, one level deep).
36    pub structure: Vec<String>,
37    /// Whether a .git directory exists.
38    pub is_git_repo: bool,
39    /// Detected build command (e.g. "cargo build", "npm run build").
40    pub build_command: String,
41    /// Detected test command.
42    pub test_command: String,
43    /// Contents of the discovered project instruction file (TINYHARNESS.md, AGENTS.md, etc.).
44    /// `None` if no file was found.
45    pub project_md: Option<(String, String)>, // (filename, content)
46    /// Additional project MD files loaded from `.tinyharness/config.json`'s
47    /// `project_md_files` field (e.g. RULES.md, .cursorrules).
48    /// Each entry is (filename, content). Empty if none configured.
49    pub additional_project_mds: Vec<(String, String)>,
50}
51
52impl WorkspaceContext {
53    /// Collect workspace context from the current working directory.
54    ///
55    /// Resolved from the ambient environment — use [`WorkspaceContext::collect_in`]
56    /// when the caller has a [`Paths`](crate::paths::Paths).
57    pub fn collect() -> Self {
58        Self::collect_in(&crate::paths::Paths::default())
59    }
60
61    /// Collect workspace context for an injected set of paths.
62    ///
63    /// The workspace root is `paths.project_dir()`; global settings are read
64    /// from `paths.settings_file()` and project settings are discovered by
65    /// walking up from the root.
66    pub fn collect_in(paths: &crate::paths::Paths) -> Self {
67        let root = paths.project_dir().to_path_buf();
68        let project_type = detect_project_type(&root);
69        let project_name = detect_project_name(&root, &project_type);
70        let structure = list_top_level(&root);
71        let is_git_repo = root.join(".git").is_dir();
72        let (build_command, test_command) = detect_commands(&project_type, &root);
73
74        // Resolve the project MD discovery list (env var > settings > defaults)
75        let settings = crate::config::load_settings_from(paths);
76        let md_files = crate::config::resolve_project_md_files(Some(&settings));
77        let project_md = discover_project_md(&root, &md_files);
78
79        // Load additional MD files from per-project .tinyharness/config.json
80        let additional_project_mds = crate::config::project_settings_or_none(paths)
81            .map(|proj| load_additional_md_files(&root, proj.project_md_files.as_deref()))
82            .unwrap_or_default();
83
84        WorkspaceContext {
85            root,
86            project_type: project_type.to_string(),
87            project_name,
88            structure,
89            is_git_repo,
90            build_command: build_command.to_string(),
91            test_command: test_command.to_string(),
92            project_md,
93            additional_project_mds,
94        }
95    }
96
97    /// Format the context as a human-readable string to inject into the system prompt.
98    pub fn format(&self) -> String {
99        let mut lines = Vec::new();
100
101        lines.push(format!(
102            "You are operating inside a {} project called \"{}\".",
103            self.project_type, self.project_name
104        ));
105        lines.push(format!("Workspace root: {}", self.root.display()));
106
107        if self.is_git_repo {
108            lines.push("This is a git repository.".to_string());
109        }
110
111        lines.push("\nProject structure:".to_string());
112        for entry in &self.structure {
113            lines.push(format!("  {}", entry));
114        }
115
116        if !self.build_command.is_empty() {
117            lines.push(format!("\nBuild command: {}", self.build_command));
118        }
119        if !self.test_command.is_empty() {
120            lines.push(format!("Test command: {}", self.test_command));
121        }
122
123        if let Some((filename, content)) = &self.project_md {
124            lines.push(format!("\n---\n# Project Instructions (from {filename})\n"));
125            lines.push(content.clone());
126        }
127
128        // Append additional project MD files
129        for (filename, content) in &self.additional_project_mds {
130            lines.push(format!(
131                "\n---\n# Additional Instructions (from {filename})\n"
132            ));
133            lines.push(content.clone());
134        }
135
136        lines.join("\n")
137    }
138}
139
140/// Load additional project instruction files specified in per-project config.
141fn load_additional_md_files(root: &Path, files: Option<&[String]>) -> Vec<(String, String)> {
142    let Some(files) = files else {
143        return Vec::new();
144    };
145    files
146        .iter()
147        .filter_map(|name| {
148            let path = root.join(name);
149            if path.is_file()
150                && let Ok(content) = fs::read_to_string(&path)
151            {
152                let truncated = truncate_content(&content, name);
153                Some((name.clone(), truncated))
154            } else {
155                None
156            }
157        })
158        .collect()
159}
160
161/// Detection entry: (language label, marker file(s), build command, test command).
162/// Ordered by priority — first match wins per detection pass.
163struct LanguageSignature {
164    label: &'static str,
165    markers: &'static [&'static str],
166    build_cmd: &'static str,
167    test_cmd: &'static str,
168}
169
170const LANGUAGE_SIGNATURES: &[LanguageSignature] = &[
171    LanguageSignature {
172        label: "Rust",
173        markers: &["Cargo.toml"],
174        build_cmd: "cargo build",
175        test_cmd: "cargo test",
176    },
177    LanguageSignature {
178        label: "Zig",
179        markers: &["build.zig", "build.zig.zon"],
180        build_cmd: "zig build",
181        test_cmd: "zig build test",
182    },
183    LanguageSignature {
184        label: "Deno",
185        markers: &["deno.json", "deno.jsonc"],
186        build_cmd: "deno task build",
187        test_cmd: "deno test",
188    },
189    LanguageSignature {
190        label: "Bun",
191        markers: &["bun.lockb", "bun.lock"],
192        build_cmd: "bun run build",
193        test_cmd: "bun test",
194    },
195    LanguageSignature {
196        label: "Swift",
197        markers: &["Package.swift"],
198        build_cmd: "swift build",
199        test_cmd: "swift test",
200    },
201    LanguageSignature {
202        label: "Ruby",
203        markers: &["Gemfile"],
204        build_cmd: "bundle install",
205        test_cmd: "bundle exec rspec",
206    },
207    LanguageSignature {
208        label: "Elixir",
209        markers: &["mix.exs"],
210        build_cmd: "mix compile",
211        test_cmd: "mix test",
212    },
213    LanguageSignature {
214        label: "Haskell",
215        markers: &["stack.yaml"],
216        build_cmd: "stack build",
217        test_cmd: "stack test",
218    },
219    LanguageSignature {
220        label: "Kotlin",
221        markers: &["build.gradle.kts", "settings.gradle.kts"],
222        build_cmd: "gradle build",
223        test_cmd: "gradle test",
224    },
225    LanguageSignature {
226        label: "Dart/Flutter",
227        markers: &["pubspec.yaml"],
228        build_cmd: "dart run build",
229        test_cmd: "dart test",
230    },
231    LanguageSignature {
232        label: "Nix",
233        markers: &["flake.nix", "default.nix"],
234        build_cmd: "nix build",
235        test_cmd: "nix flake check",
236    },
237    LanguageSignature {
238        label: "Node.js",
239        markers: &["package.json"],
240        build_cmd: "npm run build",
241        test_cmd: "npm test",
242    },
243    LanguageSignature {
244        label: "Python",
245        markers: &[
246            "pyproject.toml",
247            "setup.py",
248            "setup.cfg",
249            "requirements.txt",
250        ],
251        build_cmd: "pip install -e .",
252        test_cmd: "pytest",
253    },
254    LanguageSignature {
255        label: "Go",
256        markers: &["go.mod"],
257        build_cmd: "go build ./...",
258        test_cmd: "go test ./...",
259    },
260    LanguageSignature {
261        label: "Java (Gradle)",
262        markers: &["build.gradle"],
263        build_cmd: "gradle build",
264        test_cmd: "gradle test",
265    },
266    LanguageSignature {
267        label: "Java (Maven)",
268        markers: &["pom.xml"],
269        build_cmd: "mvn compile",
270        test_cmd: "mvn test",
271    },
272    LanguageSignature {
273        label: "C/C++ (CMake)",
274        markers: &["CMakeLists.txt"],
275        build_cmd: "cmake --build build",
276        test_cmd: "ctest",
277    },
278];
279
280/// Glob patterns for additional marker files that are checked after the
281/// ordered signatures. These detect languages whose markers overlap with
282/// other signatures (e.g. `.csproj` for .NET).
283const SECONDARY_MARKERS: &[(&str, &str)] = &[
284    (".NET", "*.csproj"),
285    (".NET", "*.sln"),
286    ("Haskell (Cabal)", "*.cabal"),
287];
288
289fn detect_project_type(root: &Path) -> String {
290    let mut found: Vec<&'static str> = Vec::new();
291
292    for sig in LANGUAGE_SIGNATURES {
293        for marker in sig.markers {
294            if root.join(marker).exists() {
295                if !found.contains(&sig.label) {
296                    found.push(sig.label);
297                }
298                break; // one marker match is enough
299            }
300        }
301    }
302
303    // Secondary check: glob for patterns like *.csproj
304    for (label, pattern) in SECONDARY_MARKERS {
305        if found.contains(label) {
306            continue;
307        }
308        if let Ok(entries) = glob::glob(&root.join(pattern).to_string_lossy())
309            && entries.flatten().next().is_some()
310        {
311            found.push(label);
312        }
313    }
314
315    if found.is_empty() {
316        // Fallback: check for Makefile / Justfile as task-runner hints
317        if root.join("Makefile").exists() {
318            "Unknown (has Makefile)".to_string()
319        } else if root.join("Justfile").exists() {
320            "Unknown (has Justfile)".to_string()
321        } else {
322            "Unknown".to_string()
323        }
324    } else if found.len() == 1 {
325        found[0].to_string()
326    } else {
327        // Monorepo: join all detected types
328        found.join(" + ")
329    }
330}
331
332/// Extract a quoted field value (supports both double and single quotes).
333fn extract_quoted_field<'a>(line: &'a str, key: &str) -> Option<&'a str> {
334    let trimmed = line.trim();
335    for (prefix, quote) in [
336        (format!("{} = \"", key), '"'),
337        (format!("{} = '", key), '\''),
338    ] {
339        if let Some(name) = trimmed
340            .strip_prefix(&prefix)
341            .and_then(|n| n.find(quote).map(|end| &n[..end]))
342        {
343            return Some(name);
344        }
345    }
346    None
347}
348
349fn detect_project_name(root: &Path, project_type: &str) -> String {
350    let fallback = || {
351        root.file_name()
352            .map(|n| n.to_string_lossy().to_string())
353            .unwrap_or_else(|| "Unknown".to_string())
354    };
355
356    // Handle "Rust + Node.js" style monorepo labels
357    let primary = project_type
358        .split_once(" + ")
359        .map(|(a, _)| a)
360        .unwrap_or(project_type);
361
362    match primary {
363        "Rust" => {
364            if let Ok(content) = fs::read_to_string(root.join("Cargo.toml")) {
365                for line in content.lines() {
366                    if let Some(name) = extract_quoted_field(line, "name") {
367                        return name.to_string();
368                    }
369                }
370            }
371            fallback()
372        }
373        "Node.js" | "Bun" | "Deno" => {
374            if let Ok(content) = fs::read_to_string(root.join("package.json"))
375                && let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
376                && let Some(name) = json.get("name").and_then(|n| n.as_str())
377            {
378                return name.to_string();
379            }
380            fallback()
381        }
382        "Python" => {
383            if let Ok(content) = fs::read_to_string(root.join("pyproject.toml")) {
384                for line in content.lines() {
385                    if let Some(name) = extract_quoted_field(line, "name") {
386                        return name.to_string();
387                    }
388                }
389            }
390            fallback()
391        }
392        "Go" => {
393            // Read module name from go.mod
394            if let Ok(content) = fs::read_to_string(root.join("go.mod")) {
395                for line in content.lines() {
396                    if let Some(rest) = line.strip_prefix("module ") {
397                        let name = rest.trim();
398                        if !name.is_empty() {
399                            return name.to_string();
400                        }
401                    }
402                }
403            }
404            fallback()
405        }
406        _ => fallback(),
407    }
408}
409
410fn list_top_level(root: &Path) -> Vec<String> {
411    let mut entries = Vec::new();
412
413    if let Ok(read_dir) = fs::read_dir(root) {
414        for entry in read_dir.flatten() {
415            let path = entry.path();
416            // Skip hidden files/dirs and common ignored directories
417            let name = path
418                .file_name()
419                .map(|n| n.to_string_lossy().to_string())
420                .unwrap_or_default();
421
422            if name.starts_with('.') || name == "target" || name == "node_modules" {
423                continue;
424            }
425
426            if path.is_dir() {
427                // Show dir with trailing slash and list one level of contents
428                let mut children: Vec<String> = Vec::new();
429                if let Ok(sub_dir) = fs::read_dir(&path) {
430                    for sub in sub_dir.flatten() {
431                        let sub_name = sub
432                            .path()
433                            .file_name()
434                            .map(|n| n.to_string_lossy().to_string())
435                            .unwrap_or_default();
436                        if !sub_name.starts_with('.') {
437                            children.push(sub_name);
438                        }
439                    }
440                }
441                children.sort();
442                if children.len() <= 6 {
443                    let child_list = children.join(", ");
444                    entries.push(format!("{}/  ({})", name, child_list));
445                } else {
446                    entries.push(format!("{}/  ({} entries)", name, children.len()));
447                }
448            } else {
449                entries.push(name);
450            }
451        }
452    }
453
454    entries.sort();
455    entries
456}
457
458fn detect_commands(project_type: &str, root: &Path) -> (&'static str, &'static str) {
459    // Handle monorepo labels: use the first detected type's commands
460    let primary = project_type
461        .split_once(" + ")
462        .map(|(a, _)| a)
463        .unwrap_or(project_type);
464
465    for sig in LANGUAGE_SIGNATURES {
466        if sig.label == primary {
467            return (sig.build_cmd, sig.test_cmd);
468        }
469    }
470
471    // Fallback: check for Makefile / Justfile as task-runner hints
472    if root.join("Makefile").exists() {
473        ("make", "make test")
474    } else if root.join("Justfile").exists() {
475        ("just build", "just test")
476    } else {
477        ("", "")
478    }
479}
480
481/// Search for a project instruction file in the current directory and parent
482/// directories up to the filesystem root. Returns the first
483/// match found, following the priority order defined in `file_names`.
484///
485/// This mirrors how CLAUDE.md and HERMES.md discover context files:
486/// walk up from CWD, check each directory for any of the known filenames.
487fn discover_project_md(start_dir: &Path, file_names: &[String]) -> Option<(String, String)> {
488    if file_names.is_empty() {
489        return None;
490    }
491
492    let mut dir = start_dir.to_path_buf();
493
494    loop {
495        for filename in file_names {
496            let candidate = dir.join(filename);
497            if candidate.is_file()
498                && let Ok(content) = fs::read_to_string(&candidate)
499            {
500                let truncated = truncate_content(&content, filename);
501                return Some((filename.to_string(), truncated));
502            }
503        }
504
505        // Walk up one directory
506        if let Some(parent) = dir.parent() {
507            if parent == dir {
508                break;
509            }
510            dir = parent.to_path_buf();
511        } else {
512            break;
513        }
514    }
515
516    None
517}
518
519/// Truncate content that exceeds `PROJECT_MD_MAX_CHARS`.
520/// Uses a head/tail strategy (70% head, 20% tail, with a 10% truncation marker)
521/// to preserve both the beginning (which usually contains the most important
522/// instructions) and the end (which may contain verification steps or gotchas).
523fn truncate_content(content: &str, filename: &str) -> String {
524    if content.len() <= PROJECT_MD_MAX_CHARS {
525        return content.to_string();
526    }
527
528    let head_end = (PROJECT_MD_MAX_CHARS as f64 * PROJECT_MD_HEAD_RATIO) as usize;
529    let tail_size = (PROJECT_MD_MAX_CHARS as f64 * (1.0 - PROJECT_MD_HEAD_RATIO)) as usize;
530
531    let head = &content[..content.floor_char_boundary(head_end)];
532    let tail_start = content.len().saturating_sub(tail_size);
533    let tail = &content[content.floor_char_boundary(tail_start)..];
534
535    let total = content.len();
536    let kept_head = head.len();
537    let kept_tail = tail.len();
538
539    format!(
540        "{head}\n\n[...truncated {filename}: kept {kept_head}+{kept_tail} of {total} chars. Use the read tool to view the full file.]\n\n{tail}"
541    )
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547    use std::fs;
548
549    /// Helper: the default discovery list as owned Strings for tests.
550    fn default_md_names() -> Vec<String> {
551        DEFAULT_PROJECT_MD_FILE_NAMES
552            .iter()
553            .map(|s| s.to_string())
554            .collect()
555    }
556
557    /// Helper: custom discovery list for override tests.
558    fn custom_md_names(names: &[&str]) -> Vec<String> {
559        names.iter().map(|s| s.to_string()).collect()
560    }
561
562    /// Test that TINYHARNESS.md is discovered from the current directory.
563    #[test]
564    fn test_discover_project_md_tinyharness_md() {
565        let dir = tempfile::tempdir().unwrap();
566        let dir_path = dir.path();
567
568        fs::write(dir_path.join("TINYHARNESS.md"), "# Project\n\nUse Rust.").unwrap();
569
570        let result = discover_project_md(dir_path, &default_md_names());
571        assert!(result.is_some());
572        let (filename, content) = result.unwrap();
573        assert_eq!(filename, "TINYHARNESS.md");
574        assert!(content.contains("# Project"));
575        assert!(content.contains("Use Rust."));
576    }
577
578    /// Test priority: TINYHARNESS.md takes precedence over AGENTS.md.
579    #[test]
580    fn test_discover_project_md_priority() {
581        let dir = tempfile::tempdir().unwrap();
582        let dir_path = dir.path();
583
584        fs::write(dir_path.join("TINYHARNESS.md"), "# From TINYHARNESS.md").unwrap();
585        fs::write(dir_path.join("AGENTS.md"), "# From AGENTS.md").unwrap();
586        fs::write(dir_path.join("CLAUDE.md"), "# From CLAUDE.md").unwrap();
587
588        let result = discover_project_md(dir_path, &default_md_names());
589        assert!(result.is_some());
590        let (filename, content) = result.unwrap();
591        assert_eq!(filename, "TINYHARNESS.md");
592        assert!(content.contains("From TINYHARNESS.md"));
593    }
594
595    /// Test fallback: AGENTS.md is found when TINYHARNESS.md doesn't exist.
596    #[test]
597    fn test_discover_project_md_agents_md_fallback() {
598        let dir = tempfile::tempdir().unwrap();
599        let dir_path = dir.path();
600
601        fs::write(dir_path.join("AGENTS.md"), "# From AGENTS.md").unwrap();
602
603        let result = discover_project_md(dir_path, &default_md_names());
604        assert!(result.is_some());
605        let (filename, content) = result.unwrap();
606        assert_eq!(filename, "AGENTS.md");
607        assert!(content.contains("From AGENTS.md"));
608    }
609
610    /// Test fallback: CLAUDE.md is found when higher-priority files don't exist.
611    #[test]
612    fn test_discover_project_md_claude_md_fallback() {
613        let dir = tempfile::tempdir().unwrap();
614        let dir_path = dir.path();
615
616        fs::write(dir_path.join("CLAUDE.md"), "# From CLAUDE.md").unwrap();
617
618        let result = discover_project_md(dir_path, &default_md_names());
619        assert!(result.is_some());
620        let (filename, content) = result.unwrap();
621        assert_eq!(filename, "CLAUDE.md");
622        assert!(content.contains("From CLAUDE.md"));
623    }
624
625    /// Test that no file returns None.
626    #[test]
627    fn test_discover_project_md_none() {
628        let dir = tempfile::tempdir().unwrap();
629        let result = discover_project_md(dir.path(), &default_md_names());
630        assert!(result.is_none());
631    }
632
633    /// Test walking up to parent directories to find the file.
634    #[test]
635    fn test_discover_project_md_walks_up() {
636        let dir = tempfile::tempdir().unwrap();
637        let dir_path = dir.path();
638
639        // Put TINYHARNESS.md in the root, but search from a subdirectory
640        fs::write(dir_path.join("TINYHARNESS.md"), "# Found in parent").unwrap();
641
642        let subdir = dir_path.join("src").join("tools");
643        fs::create_dir_all(&subdir).unwrap();
644
645        let result = discover_project_md(&subdir, &default_md_names());
646        assert!(result.is_some());
647        let (filename, content) = result.unwrap();
648        assert_eq!(filename, "TINYHARNESS.md");
649        assert!(content.contains("Found in parent"));
650    }
651
652    /// Test that .tinyharness.md (hidden variant) is found.
653    #[test]
654    fn test_discover_project_md_hidden_variant() {
655        let dir = tempfile::tempdir().unwrap();
656        let dir_path = dir.path();
657
658        fs::write(dir_path.join(".tinyharness.md"), "# Hidden variant").unwrap();
659
660        let result = discover_project_md(dir_path, &default_md_names());
661        assert!(result.is_some());
662        let (filename, content) = result.unwrap();
663        assert_eq!(filename, ".tinyharness.md");
664        assert!(content.contains("Hidden variant"));
665    }
666
667    /// Test that custom file names work (env var / settings override).
668    #[test]
669    fn test_discover_project_md_custom_names() {
670        let dir = tempfile::tempdir().unwrap();
671        let dir_path = dir.path();
672
673        fs::write(dir_path.join("TEAM_RULES.md"), "# Team Rules").unwrap();
674        fs::write(dir_path.join("CLAUDE.md"), "# Claude Rules").unwrap();
675
676        // Custom order: TEAM_RULES.md first
677        let names = custom_md_names(&["TEAM_RULES.md", "CLAUDE.md"]);
678        let result = discover_project_md(dir_path, &names);
679        assert!(result.is_some());
680        let (filename, content) = result.unwrap();
681        assert_eq!(filename, "TEAM_RULES.md");
682        assert!(content.contains("# Team Rules"));
683    }
684
685    /// Test that when custom list is empty, nothing is found.
686    #[test]
687    fn test_discover_project_md_empty_list() {
688        let dir = tempfile::tempdir().unwrap();
689        let dir_path = dir.path();
690
691        fs::write(dir_path.join("TINYHARNESS.md"), "# Project").unwrap();
692
693        let result = discover_project_md(dir_path, &[]);
694        assert!(result.is_none());
695    }
696
697    /// Test truncation of oversized content.
698    #[test]
699    fn test_truncate_content_under_limit() {
700        let content = "Hello, world!".to_string();
701        let result = truncate_content(&content, "TINYHARNESS.md");
702        assert_eq!(result, content); // No truncation needed
703    }
704
705    /// Test truncation of content that exceeds the limit.
706    #[test]
707    fn test_truncate_content_over_limit() {
708        // Create content that exceeds the limit
709        let content = "A".repeat(PROJECT_MD_MAX_CHARS + 5000);
710        let result = truncate_content(&content, "TINYHARNESS.md");
711
712        // Should contain the truncation marker
713        assert!(result.contains("[...truncated TINYHARNESS.md"));
714        assert!(result.contains("Use the read tool to view the full file"));
715
716        // Total result should be smaller than the original
717        assert!(result.len() < content.len());
718
719        // Should start with the head (A's) and end with the tail (A's)
720        assert!(result.starts_with('A'));
721        assert!(result.ends_with('A'));
722    }
723
724    /// Test that format() includes project_md content when present.
725    #[test]
726    fn test_format_includes_project_md() {
727        let ctx = WorkspaceContext {
728            root: PathBuf::from("/tmp/test"),
729            project_type: "Rust".to_string(),
730            project_name: "test-project".to_string(),
731            structure: vec!["src/  (main.rs)".to_string()],
732            is_git_repo: false,
733            build_command: "cargo build".to_string(),
734            test_command: "cargo test".to_string(),
735            project_md: Some((
736                "TINYHARNESS.md".to_string(),
737                "# My Rules\nAlways use Rust.".to_string(),
738            )),
739            additional_project_mds: Vec::new(),
740        };
741
742        let formatted = ctx.format();
743        assert!(formatted.contains("# Project Instructions (from TINYHARNESS.md)"));
744        assert!(formatted.contains("# My Rules"));
745        assert!(formatted.contains("Always use Rust."));
746    }
747
748    /// Test that format() works when no project_md is found.
749    #[test]
750    fn test_format_without_project_md() {
751        let ctx = WorkspaceContext {
752            root: PathBuf::from("/tmp/test"),
753            project_type: "Rust".to_string(),
754            project_name: "test-project".to_string(),
755            structure: vec!["src/  (main.rs)".to_string()],
756            is_git_repo: false,
757            build_command: "cargo build".to_string(),
758            test_command: "cargo test".to_string(),
759            project_md: None,
760            additional_project_mds: Vec::new(),
761        };
762
763        let formatted = ctx.format();
764        assert!(!formatted.contains("Project Instructions"));
765    }
766
767    /// Test that format() includes additional project MD files.
768    #[test]
769    fn test_format_includes_additional_mds() {
770        let ctx = WorkspaceContext {
771            root: PathBuf::from("/tmp/test"),
772            project_type: "Rust".to_string(),
773            project_name: "test-project".to_string(),
774            structure: vec!["src/  (main.rs)".to_string()],
775            is_git_repo: false,
776            build_command: "cargo build".to_string(),
777            test_command: "cargo test".to_string(),
778            project_md: None,
779            additional_project_mds: vec![("RULES.md".to_string(), "# Custom Rules".to_string())],
780        };
781
782        let formatted = ctx.format();
783        assert!(formatted.contains("# Additional Instructions (from RULES.md)"));
784        assert!(formatted.contains("# Custom Rules"));
785    }
786
787    /// Test priority between .tinyharness.md and AGENTS.md.
788    #[test]
789    fn test_discover_project_md_hidden_over_agents() {
790        let dir = tempfile::tempdir().unwrap();
791        let dir_path = dir.path();
792
793        fs::write(dir_path.join(".tinyharness.md"), "# Hidden").unwrap();
794        fs::write(dir_path.join("AGENTS.md"), "# Agents").unwrap();
795
796        let result = discover_project_md(dir_path, &default_md_names());
797        assert!(result.is_some());
798        let (filename, _) = result.unwrap();
799        assert_eq!(filename, ".tinyharness.md");
800    }
801}