1use std::{
2 fs,
3 path::{Path, PathBuf},
4};
5
6const PROJECT_MD_MAX_CHARS: usize = 20_000;
9
10const PROJECT_MD_HEAD_RATIO: f64 = 0.70;
12
13pub const DEFAULT_PROJECT_MD_FILE_NAMES: &[&str] = &[
17 "TINYHARNESS.md",
18 ".tinyharness.md",
19 "AGENTS.md",
20 "CLAUDE.md",
21];
22
23pub const PROJECT_MD_FILE_NAMES: &[&str] = DEFAULT_PROJECT_MD_FILE_NAMES;
25
26#[derive(Debug, Clone)]
28pub struct WorkspaceContext {
29 pub root: PathBuf,
31 pub project_type: String,
33 pub project_name: String,
35 pub structure: Vec<String>,
37 pub is_git_repo: bool,
39 pub build_command: String,
41 pub test_command: String,
43 pub project_md: Option<(String, String)>, pub additional_project_mds: Vec<(String, String)>,
50}
51
52impl WorkspaceContext {
53 pub fn collect() -> Self {
55 let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
56 let project_type = detect_project_type(&root);
57 let project_name = detect_project_name(&root, &project_type);
58 let structure = list_top_level(&root);
59 let is_git_repo = root.join(".git").is_dir();
60 let (build_command, test_command) = detect_commands(&project_type, &root);
61
62 let settings = crate::config::load_settings();
64 let md_files = crate::config::resolve_project_md_files(Some(&settings));
65 let project_md = discover_project_md(&root, &md_files);
66
67 let additional_project_mds =
69 if let Some(Ok(proj)) = crate::config::discover_project_settings(&root) {
70 load_additional_md_files(&root, proj.project_md_files.as_deref())
71 } else {
72 Vec::new()
73 };
74
75 WorkspaceContext {
76 root,
77 project_type: project_type.to_string(),
78 project_name,
79 structure,
80 is_git_repo,
81 build_command: build_command.to_string(),
82 test_command: test_command.to_string(),
83 project_md,
84 additional_project_mds,
85 }
86 }
87
88 pub fn format(&self) -> String {
90 let mut lines = Vec::new();
91
92 lines.push(format!(
93 "You are operating inside a {} project called \"{}\".",
94 self.project_type, self.project_name
95 ));
96 lines.push(format!("Workspace root: {}", self.root.display()));
97
98 if self.is_git_repo {
99 lines.push("This is a git repository.".to_string());
100 }
101
102 lines.push("\nProject structure:".to_string());
103 for entry in &self.structure {
104 lines.push(format!(" {}", entry));
105 }
106
107 if !self.build_command.is_empty() {
108 lines.push(format!("\nBuild command: {}", self.build_command));
109 }
110 if !self.test_command.is_empty() {
111 lines.push(format!("Test command: {}", self.test_command));
112 }
113
114 if let Some((filename, content)) = &self.project_md {
115 lines.push(format!("\n---\n# Project Instructions (from {filename})\n"));
116 lines.push(content.clone());
117 }
118
119 for (filename, content) in &self.additional_project_mds {
121 lines.push(format!(
122 "\n---\n# Additional Instructions (from {filename})\n"
123 ));
124 lines.push(content.clone());
125 }
126
127 lines.join("\n")
128 }
129}
130
131fn load_additional_md_files(root: &Path, files: Option<&[String]>) -> Vec<(String, String)> {
133 let Some(files) = files else {
134 return Vec::new();
135 };
136 files
137 .iter()
138 .filter_map(|name| {
139 let path = root.join(name);
140 if path.is_file()
141 && let Ok(content) = fs::read_to_string(&path)
142 {
143 let truncated = truncate_content(&content, name);
144 Some((name.clone(), truncated))
145 } else {
146 None
147 }
148 })
149 .collect()
150}
151
152struct LanguageSignature {
155 label: &'static str,
156 markers: &'static [&'static str],
157 build_cmd: &'static str,
158 test_cmd: &'static str,
159}
160
161const LANGUAGE_SIGNATURES: &[LanguageSignature] = &[
162 LanguageSignature {
163 label: "Rust",
164 markers: &["Cargo.toml"],
165 build_cmd: "cargo build",
166 test_cmd: "cargo test",
167 },
168 LanguageSignature {
169 label: "Zig",
170 markers: &["build.zig", "build.zig.zon"],
171 build_cmd: "zig build",
172 test_cmd: "zig build test",
173 },
174 LanguageSignature {
175 label: "Deno",
176 markers: &["deno.json", "deno.jsonc"],
177 build_cmd: "deno task build",
178 test_cmd: "deno test",
179 },
180 LanguageSignature {
181 label: "Bun",
182 markers: &["bun.lockb", "bun.lock"],
183 build_cmd: "bun run build",
184 test_cmd: "bun test",
185 },
186 LanguageSignature {
187 label: "Swift",
188 markers: &["Package.swift"],
189 build_cmd: "swift build",
190 test_cmd: "swift test",
191 },
192 LanguageSignature {
193 label: "Ruby",
194 markers: &["Gemfile"],
195 build_cmd: "bundle install",
196 test_cmd: "bundle exec rspec",
197 },
198 LanguageSignature {
199 label: "Elixir",
200 markers: &["mix.exs"],
201 build_cmd: "mix compile",
202 test_cmd: "mix test",
203 },
204 LanguageSignature {
205 label: "Haskell",
206 markers: &["stack.yaml"],
207 build_cmd: "stack build",
208 test_cmd: "stack test",
209 },
210 LanguageSignature {
211 label: "Kotlin",
212 markers: &["build.gradle.kts", "settings.gradle.kts"],
213 build_cmd: "gradle build",
214 test_cmd: "gradle test",
215 },
216 LanguageSignature {
217 label: "Dart/Flutter",
218 markers: &["pubspec.yaml"],
219 build_cmd: "dart run build",
220 test_cmd: "dart test",
221 },
222 LanguageSignature {
223 label: "Nix",
224 markers: &["flake.nix", "default.nix"],
225 build_cmd: "nix build",
226 test_cmd: "nix flake check",
227 },
228 LanguageSignature {
229 label: "Node.js",
230 markers: &["package.json"],
231 build_cmd: "npm run build",
232 test_cmd: "npm test",
233 },
234 LanguageSignature {
235 label: "Python",
236 markers: &[
237 "pyproject.toml",
238 "setup.py",
239 "setup.cfg",
240 "requirements.txt",
241 ],
242 build_cmd: "pip install -e .",
243 test_cmd: "pytest",
244 },
245 LanguageSignature {
246 label: "Go",
247 markers: &["go.mod"],
248 build_cmd: "go build ./...",
249 test_cmd: "go test ./...",
250 },
251 LanguageSignature {
252 label: "Java (Gradle)",
253 markers: &["build.gradle"],
254 build_cmd: "gradle build",
255 test_cmd: "gradle test",
256 },
257 LanguageSignature {
258 label: "Java (Maven)",
259 markers: &["pom.xml"],
260 build_cmd: "mvn compile",
261 test_cmd: "mvn test",
262 },
263 LanguageSignature {
264 label: "C/C++ (CMake)",
265 markers: &["CMakeLists.txt"],
266 build_cmd: "cmake --build build",
267 test_cmd: "ctest",
268 },
269];
270
271const SECONDARY_MARKERS: &[(&str, &str)] = &[
275 (".NET", "*.csproj"),
276 (".NET", "*.sln"),
277 ("Haskell (Cabal)", "*.cabal"),
278];
279
280fn detect_project_type(root: &Path) -> String {
281 let mut found: Vec<&'static str> = Vec::new();
282
283 for sig in LANGUAGE_SIGNATURES {
284 for marker in sig.markers {
285 if root.join(marker).exists() {
286 if !found.contains(&sig.label) {
287 found.push(sig.label);
288 }
289 break; }
291 }
292 }
293
294 for (label, pattern) in SECONDARY_MARKERS {
296 if found.contains(label) {
297 continue;
298 }
299 if let Ok(entries) = glob::glob(&root.join(pattern).to_string_lossy())
300 && entries.flatten().next().is_some()
301 {
302 found.push(label);
303 }
304 }
305
306 if found.is_empty() {
307 if root.join("Makefile").exists() {
309 "Unknown (has Makefile)".to_string()
310 } else if root.join("Justfile").exists() {
311 "Unknown (has Justfile)".to_string()
312 } else {
313 "Unknown".to_string()
314 }
315 } else if found.len() == 1 {
316 found[0].to_string()
317 } else {
318 found.join(" + ")
320 }
321}
322
323fn extract_quoted_field<'a>(line: &'a str, key: &str) -> Option<&'a str> {
325 let trimmed = line.trim();
326 for (prefix, quote) in [
327 (format!("{} = \"", key), '"'),
328 (format!("{} = '", key), '\''),
329 ] {
330 if let Some(name) = trimmed
331 .strip_prefix(&prefix)
332 .and_then(|n| n.find(quote).map(|end| &n[..end]))
333 {
334 return Some(name);
335 }
336 }
337 None
338}
339
340fn detect_project_name(root: &Path, project_type: &str) -> String {
341 let fallback = || {
342 root.file_name()
343 .map(|n| n.to_string_lossy().to_string())
344 .unwrap_or_else(|| "Unknown".to_string())
345 };
346
347 let primary = project_type
349 .split_once(" + ")
350 .map(|(a, _)| a)
351 .unwrap_or(project_type);
352
353 match primary {
354 "Rust" => {
355 if let Ok(content) = fs::read_to_string(root.join("Cargo.toml")) {
356 for line in content.lines() {
357 if let Some(name) = extract_quoted_field(line, "name") {
358 return name.to_string();
359 }
360 }
361 }
362 fallback()
363 }
364 "Node.js" | "Bun" | "Deno" => {
365 if let Ok(content) = fs::read_to_string(root.join("package.json"))
366 && let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
367 && let Some(name) = json.get("name").and_then(|n| n.as_str())
368 {
369 return name.to_string();
370 }
371 fallback()
372 }
373 "Python" => {
374 if let Ok(content) = fs::read_to_string(root.join("pyproject.toml")) {
375 for line in content.lines() {
376 if let Some(name) = extract_quoted_field(line, "name") {
377 return name.to_string();
378 }
379 }
380 }
381 fallback()
382 }
383 "Go" => {
384 if let Ok(content) = fs::read_to_string(root.join("go.mod")) {
386 for line in content.lines() {
387 if let Some(rest) = line.strip_prefix("module ") {
388 let name = rest.trim();
389 if !name.is_empty() {
390 return name.to_string();
391 }
392 }
393 }
394 }
395 fallback()
396 }
397 _ => fallback(),
398 }
399}
400
401fn list_top_level(root: &Path) -> Vec<String> {
402 let mut entries = Vec::new();
403
404 if let Ok(read_dir) = fs::read_dir(root) {
405 for entry in read_dir.flatten() {
406 let path = entry.path();
407 let name = path
409 .file_name()
410 .map(|n| n.to_string_lossy().to_string())
411 .unwrap_or_default();
412
413 if name.starts_with('.') || name == "target" || name == "node_modules" {
414 continue;
415 }
416
417 if path.is_dir() {
418 let mut children: Vec<String> = Vec::new();
420 if let Ok(sub_dir) = fs::read_dir(&path) {
421 for sub in sub_dir.flatten() {
422 let sub_name = sub
423 .path()
424 .file_name()
425 .map(|n| n.to_string_lossy().to_string())
426 .unwrap_or_default();
427 if !sub_name.starts_with('.') {
428 children.push(sub_name);
429 }
430 }
431 }
432 children.sort();
433 if children.len() <= 6 {
434 let child_list = children.join(", ");
435 entries.push(format!("{}/ ({})", name, child_list));
436 } else {
437 entries.push(format!("{}/ ({} entries)", name, children.len()));
438 }
439 } else {
440 entries.push(name);
441 }
442 }
443 }
444
445 entries.sort();
446 entries
447}
448
449fn detect_commands(project_type: &str, root: &Path) -> (&'static str, &'static str) {
450 let primary = project_type
452 .split_once(" + ")
453 .map(|(a, _)| a)
454 .unwrap_or(project_type);
455
456 for sig in LANGUAGE_SIGNATURES {
457 if sig.label == primary {
458 return (sig.build_cmd, sig.test_cmd);
459 }
460 }
461
462 if root.join("Makefile").exists() {
464 ("make", "make test")
465 } else if root.join("Justfile").exists() {
466 ("just build", "just test")
467 } else {
468 ("", "")
469 }
470}
471
472fn discover_project_md(start_dir: &Path, file_names: &[String]) -> Option<(String, String)> {
479 if file_names.is_empty() {
480 return None;
481 }
482
483 let mut dir = start_dir.to_path_buf();
484
485 loop {
486 for filename in file_names {
487 let candidate = dir.join(filename);
488 if candidate.is_file()
489 && let Ok(content) = fs::read_to_string(&candidate)
490 {
491 let truncated = truncate_content(&content, filename);
492 return Some((filename.to_string(), truncated));
493 }
494 }
495
496 if let Some(parent) = dir.parent() {
498 if parent == dir {
499 break;
500 }
501 dir = parent.to_path_buf();
502 } else {
503 break;
504 }
505 }
506
507 None
508}
509
510fn truncate_content(content: &str, filename: &str) -> String {
515 if content.len() <= PROJECT_MD_MAX_CHARS {
516 return content.to_string();
517 }
518
519 let head_end = (PROJECT_MD_MAX_CHARS as f64 * PROJECT_MD_HEAD_RATIO) as usize;
520 let tail_size = (PROJECT_MD_MAX_CHARS as f64 * (1.0 - PROJECT_MD_HEAD_RATIO)) as usize;
521
522 let head = &content[..content.floor_char_boundary(head_end)];
523 let tail_start = content.len().saturating_sub(tail_size);
524 let tail = &content[content.floor_char_boundary(tail_start)..];
525
526 let total = content.len();
527 let kept_head = head.len();
528 let kept_tail = tail.len();
529
530 format!(
531 "{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}"
532 )
533}
534
535#[cfg(test)]
536mod tests {
537 use super::*;
538 use std::fs;
539
540 fn default_md_names() -> Vec<String> {
542 DEFAULT_PROJECT_MD_FILE_NAMES
543 .iter()
544 .map(|s| s.to_string())
545 .collect()
546 }
547
548 fn custom_md_names(names: &[&str]) -> Vec<String> {
550 names.iter().map(|s| s.to_string()).collect()
551 }
552
553 #[test]
555 fn test_discover_project_md_tinyharness_md() {
556 let dir = tempfile::tempdir().unwrap();
557 let dir_path = dir.path();
558
559 fs::write(dir_path.join("TINYHARNESS.md"), "# Project\n\nUse Rust.").unwrap();
560
561 let result = discover_project_md(dir_path, &default_md_names());
562 assert!(result.is_some());
563 let (filename, content) = result.unwrap();
564 assert_eq!(filename, "TINYHARNESS.md");
565 assert!(content.contains("# Project"));
566 assert!(content.contains("Use Rust."));
567 }
568
569 #[test]
571 fn test_discover_project_md_priority() {
572 let dir = tempfile::tempdir().unwrap();
573 let dir_path = dir.path();
574
575 fs::write(dir_path.join("TINYHARNESS.md"), "# From TINYHARNESS.md").unwrap();
576 fs::write(dir_path.join("AGENTS.md"), "# From AGENTS.md").unwrap();
577 fs::write(dir_path.join("CLAUDE.md"), "# From CLAUDE.md").unwrap();
578
579 let result = discover_project_md(dir_path, &default_md_names());
580 assert!(result.is_some());
581 let (filename, content) = result.unwrap();
582 assert_eq!(filename, "TINYHARNESS.md");
583 assert!(content.contains("From TINYHARNESS.md"));
584 }
585
586 #[test]
588 fn test_discover_project_md_agents_md_fallback() {
589 let dir = tempfile::tempdir().unwrap();
590 let dir_path = dir.path();
591
592 fs::write(dir_path.join("AGENTS.md"), "# From AGENTS.md").unwrap();
593
594 let result = discover_project_md(dir_path, &default_md_names());
595 assert!(result.is_some());
596 let (filename, content) = result.unwrap();
597 assert_eq!(filename, "AGENTS.md");
598 assert!(content.contains("From AGENTS.md"));
599 }
600
601 #[test]
603 fn test_discover_project_md_claude_md_fallback() {
604 let dir = tempfile::tempdir().unwrap();
605 let dir_path = dir.path();
606
607 fs::write(dir_path.join("CLAUDE.md"), "# From CLAUDE.md").unwrap();
608
609 let result = discover_project_md(dir_path, &default_md_names());
610 assert!(result.is_some());
611 let (filename, content) = result.unwrap();
612 assert_eq!(filename, "CLAUDE.md");
613 assert!(content.contains("From CLAUDE.md"));
614 }
615
616 #[test]
618 fn test_discover_project_md_none() {
619 let dir = tempfile::tempdir().unwrap();
620 let result = discover_project_md(dir.path(), &default_md_names());
621 assert!(result.is_none());
622 }
623
624 #[test]
626 fn test_discover_project_md_walks_up() {
627 let dir = tempfile::tempdir().unwrap();
628 let dir_path = dir.path();
629
630 fs::write(dir_path.join("TINYHARNESS.md"), "# Found in parent").unwrap();
632
633 let subdir = dir_path.join("src").join("tools");
634 fs::create_dir_all(&subdir).unwrap();
635
636 let result = discover_project_md(&subdir, &default_md_names());
637 assert!(result.is_some());
638 let (filename, content) = result.unwrap();
639 assert_eq!(filename, "TINYHARNESS.md");
640 assert!(content.contains("Found in parent"));
641 }
642
643 #[test]
645 fn test_discover_project_md_hidden_variant() {
646 let dir = tempfile::tempdir().unwrap();
647 let dir_path = dir.path();
648
649 fs::write(dir_path.join(".tinyharness.md"), "# Hidden variant").unwrap();
650
651 let result = discover_project_md(dir_path, &default_md_names());
652 assert!(result.is_some());
653 let (filename, content) = result.unwrap();
654 assert_eq!(filename, ".tinyharness.md");
655 assert!(content.contains("Hidden variant"));
656 }
657
658 #[test]
660 fn test_discover_project_md_custom_names() {
661 let dir = tempfile::tempdir().unwrap();
662 let dir_path = dir.path();
663
664 fs::write(dir_path.join("TEAM_RULES.md"), "# Team Rules").unwrap();
665 fs::write(dir_path.join("CLAUDE.md"), "# Claude Rules").unwrap();
666
667 let names = custom_md_names(&["TEAM_RULES.md", "CLAUDE.md"]);
669 let result = discover_project_md(dir_path, &names);
670 assert!(result.is_some());
671 let (filename, content) = result.unwrap();
672 assert_eq!(filename, "TEAM_RULES.md");
673 assert!(content.contains("# Team Rules"));
674 }
675
676 #[test]
678 fn test_discover_project_md_empty_list() {
679 let dir = tempfile::tempdir().unwrap();
680 let dir_path = dir.path();
681
682 fs::write(dir_path.join("TINYHARNESS.md"), "# Project").unwrap();
683
684 let result = discover_project_md(dir_path, &[]);
685 assert!(result.is_none());
686 }
687
688 #[test]
690 fn test_truncate_content_under_limit() {
691 let content = "Hello, world!".to_string();
692 let result = truncate_content(&content, "TINYHARNESS.md");
693 assert_eq!(result, content); }
695
696 #[test]
698 fn test_truncate_content_over_limit() {
699 let content = "A".repeat(PROJECT_MD_MAX_CHARS + 5000);
701 let result = truncate_content(&content, "TINYHARNESS.md");
702
703 assert!(result.contains("[...truncated TINYHARNESS.md"));
705 assert!(result.contains("Use the read tool to view the full file"));
706
707 assert!(result.len() < content.len());
709
710 assert!(result.starts_with('A'));
712 assert!(result.ends_with('A'));
713 }
714
715 #[test]
717 fn test_format_includes_project_md() {
718 let ctx = WorkspaceContext {
719 root: PathBuf::from("/tmp/test"),
720 project_type: "Rust".to_string(),
721 project_name: "test-project".to_string(),
722 structure: vec!["src/ (main.rs)".to_string()],
723 is_git_repo: false,
724 build_command: "cargo build".to_string(),
725 test_command: "cargo test".to_string(),
726 project_md: Some((
727 "TINYHARNESS.md".to_string(),
728 "# My Rules\nAlways use Rust.".to_string(),
729 )),
730 additional_project_mds: Vec::new(),
731 };
732
733 let formatted = ctx.format();
734 assert!(formatted.contains("# Project Instructions (from TINYHARNESS.md)"));
735 assert!(formatted.contains("# My Rules"));
736 assert!(formatted.contains("Always use Rust."));
737 }
738
739 #[test]
741 fn test_format_without_project_md() {
742 let ctx = WorkspaceContext {
743 root: PathBuf::from("/tmp/test"),
744 project_type: "Rust".to_string(),
745 project_name: "test-project".to_string(),
746 structure: vec!["src/ (main.rs)".to_string()],
747 is_git_repo: false,
748 build_command: "cargo build".to_string(),
749 test_command: "cargo test".to_string(),
750 project_md: None,
751 additional_project_mds: Vec::new(),
752 };
753
754 let formatted = ctx.format();
755 assert!(!formatted.contains("Project Instructions"));
756 }
757
758 #[test]
760 fn test_format_includes_additional_mds() {
761 let ctx = WorkspaceContext {
762 root: PathBuf::from("/tmp/test"),
763 project_type: "Rust".to_string(),
764 project_name: "test-project".to_string(),
765 structure: vec!["src/ (main.rs)".to_string()],
766 is_git_repo: false,
767 build_command: "cargo build".to_string(),
768 test_command: "cargo test".to_string(),
769 project_md: None,
770 additional_project_mds: vec![("RULES.md".to_string(), "# Custom Rules".to_string())],
771 };
772
773 let formatted = ctx.format();
774 assert!(formatted.contains("# Additional Instructions (from RULES.md)"));
775 assert!(formatted.contains("# Custom Rules"));
776 }
777
778 #[test]
780 fn test_discover_project_md_hidden_over_agents() {
781 let dir = tempfile::tempdir().unwrap();
782 let dir_path = dir.path();
783
784 fs::write(dir_path.join(".tinyharness.md"), "# Hidden").unwrap();
785 fs::write(dir_path.join("AGENTS.md"), "# Agents").unwrap();
786
787 let result = discover_project_md(dir_path, &default_md_names());
788 assert!(result.is_some());
789 let (filename, _) = result.unwrap();
790 assert_eq!(filename, ".tinyharness.md");
791 }
792}