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 PROJECT_MD_FILE_NAMES: &[&str] = &[
17 "TINYHARNESS.md",
18 ".tinyharness.md",
19 "AGENTS.md",
20 "CLAUDE.md",
21];
22
23#[derive(Debug, Clone)]
25pub struct WorkspaceContext {
26 pub root: PathBuf,
28 pub project_type: String,
30 pub project_name: String,
32 pub structure: Vec<String>,
34 pub is_git_repo: bool,
36 pub build_command: String,
38 pub test_command: String,
40 pub project_md: Option<(String, String)>, }
44
45impl WorkspaceContext {
46 pub fn collect() -> Self {
48 let root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
49 let project_type = detect_project_type(&root);
50 let project_name = detect_project_name(&root, project_type);
51 let structure = list_top_level(&root);
52 let is_git_repo = root.join(".git").is_dir();
53 let (build_command, test_command) = detect_commands(project_type);
54 let project_md = discover_project_md(&root);
55
56 WorkspaceContext {
57 root,
58 project_type: project_type.to_string(),
59 project_name,
60 structure,
61 is_git_repo,
62 build_command: build_command.to_string(),
63 test_command: test_command.to_string(),
64 project_md,
65 }
66 }
67
68 pub fn format(&self) -> String {
70 let mut lines = Vec::new();
71
72 lines.push(format!(
73 "You are operating inside a {} project called \"{}\".",
74 self.project_type, self.project_name
75 ));
76 lines.push(format!("Workspace root: {}", self.root.display()));
77
78 if self.is_git_repo {
79 lines.push("This is a git repository.".to_string());
80 }
81
82 lines.push("\nProject structure:".to_string());
83 for entry in &self.structure {
84 lines.push(format!(" {}", entry));
85 }
86
87 if !self.build_command.is_empty() {
88 lines.push(format!("\nBuild command: {}", self.build_command));
89 }
90 if !self.test_command.is_empty() {
91 lines.push(format!("Test command: {}", self.test_command));
92 }
93
94 lines.push("\nUse the available tools (ls, read, write, edit, grep, run, glob) to explore and modify files.".to_string());
95 lines.push(
96 "Always read a file before editing it. Prefer the glob tool over 'find' or 'ls -R'."
97 .to_string(),
98 );
99
100 if let Some((filename, content)) = &self.project_md {
101 lines.push(format!("\n---\n# Project Instructions (from {filename})\n"));
102 lines.push(content.clone());
103 }
104
105 lines.join("\n")
106 }
107}
108
109fn detect_project_type(root: &Path) -> &'static str {
110 if root.join("Cargo.toml").exists() {
111 "Rust"
112 } else if root.join("package.json").exists() {
113 "Node.js"
114 } else if root.join("setup.py").exists() || root.join("pyproject.toml").exists() {
115 "Python"
116 } else if root.join("go.mod").exists() {
117 "Go"
118 } else if root.join("pom.xml").exists() || root.join("build.gradle").exists() {
119 "Java"
120 } else if root.join("CMakeLists.txt").exists() {
121 "C/C++ (CMake)"
122 } else if root.join("Makefile").exists() {
123 "C/C++ (Make)"
124 } else {
125 "Unknown"
126 }
127}
128
129fn extract_quoted_field<'a>(line: &'a str, key: &str) -> Option<&'a str> {
131 let trimmed = line.trim();
132 for (prefix, quote) in [
133 (format!("{} = \"", key), '"'),
134 (format!("{} = '", key), '\''),
135 ] {
136 if let Some(name) = trimmed
137 .strip_prefix(&prefix)
138 .and_then(|n| n.find(quote).map(|end| &n[..end]))
139 {
140 return Some(name);
141 }
142 }
143 None
144}
145
146fn detect_project_name(root: &Path, project_type: &str) -> String {
147 let fallback = || {
148 root.file_name()
149 .map(|n| n.to_string_lossy().to_string())
150 .unwrap_or_else(|| "Unknown".to_string())
151 };
152
153 match project_type {
154 "Rust" => {
155 if let Ok(content) = fs::read_to_string(root.join("Cargo.toml")) {
156 for line in content.lines() {
157 if let Some(name) = extract_quoted_field(line, "name") {
158 return name.to_string();
159 }
160 }
161 }
162 fallback()
163 }
164 "Node.js" => {
165 if let Ok(content) = fs::read_to_string(root.join("package.json"))
166 && let Ok(json) = serde_json::from_str::<serde_json::Value>(&content)
167 && let Some(name) = json.get("name").and_then(|n| n.as_str())
168 {
169 return name.to_string();
170 }
171 fallback()
172 }
173 _ => fallback(),
174 }
175}
176
177fn list_top_level(root: &Path) -> Vec<String> {
178 let mut entries = Vec::new();
179
180 if let Ok(read_dir) = fs::read_dir(root) {
181 for entry in read_dir.flatten() {
182 let path = entry.path();
183 let name = path
185 .file_name()
186 .map(|n| n.to_string_lossy().to_string())
187 .unwrap_or_default();
188
189 if name.starts_with('.') || name == "target" || name == "node_modules" {
190 continue;
191 }
192
193 if path.is_dir() {
194 let mut children: Vec<String> = Vec::new();
196 if let Ok(sub_dir) = fs::read_dir(&path) {
197 for sub in sub_dir.flatten() {
198 let sub_name = sub
199 .path()
200 .file_name()
201 .map(|n| n.to_string_lossy().to_string())
202 .unwrap_or_default();
203 if !sub_name.starts_with('.') {
204 children.push(sub_name);
205 }
206 }
207 }
208 children.sort();
209 if children.len() <= 6 {
210 let child_list = children.join(", ");
211 entries.push(format!("{}/ ({})", name, child_list));
212 } else {
213 entries.push(format!("{}/ ({} entries)", name, children.len()));
214 }
215 } else {
216 entries.push(name);
217 }
218 }
219 }
220
221 entries.sort();
222 entries
223}
224
225fn detect_commands(project_type: &str) -> (&'static str, &'static str) {
226 match project_type {
227 "Rust" => ("cargo build", "cargo test"),
228 "Node.js" => ("npm run build", "npm test"),
229 "Python" => ("pip install -e .", "pytest"),
230 "Go" => ("go build ./...", "go test ./..."),
231 _ => ("", ""),
232 }
233}
234
235fn discover_project_md(start_dir: &Path) -> Option<(String, String)> {
242 let mut dir = start_dir.to_path_buf();
243
244 loop {
245 for &filename in PROJECT_MD_FILE_NAMES {
246 let candidate = dir.join(filename);
247 if candidate.is_file()
248 && let Ok(content) = fs::read_to_string(&candidate)
249 {
250 let truncated = truncate_content(&content, filename);
251 return Some((filename.to_string(), truncated));
252 }
253 }
254
255 if let Some(parent) = dir.parent() {
257 if parent == dir {
259 break;
260 }
261 dir = parent.to_path_buf();
262
263 } else {
268 break;
269 }
270 }
271
272 None
273}
274
275fn truncate_content(content: &str, filename: &str) -> String {
280 if content.len() <= PROJECT_MD_MAX_CHARS {
281 return content.to_string();
282 }
283
284 let head_end = (PROJECT_MD_MAX_CHARS as f64 * PROJECT_MD_HEAD_RATIO) as usize;
285 let tail_size = (PROJECT_MD_MAX_CHARS as f64 * (1.0 - PROJECT_MD_HEAD_RATIO)) as usize;
286
287 let head = &content[..content.floor_char_boundary(head_end)];
288 let tail_start = content.len().saturating_sub(tail_size);
289 let tail = &content[content.floor_char_boundary(tail_start)..];
290
291 let total = content.len();
292 let kept_head = head.len();
293 let kept_tail = tail.len();
294
295 format!(
296 "{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}"
297 )
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303 use std::fs;
304
305 #[test]
307 fn test_discover_project_md_tinyharness_md() {
308 let dir = tempfile::tempdir().unwrap();
309 let dir_path = dir.path();
310
311 fs::write(dir_path.join("TINYHARNESS.md"), "# Project\n\nUse Rust.").unwrap();
312
313 let result = discover_project_md(dir_path);
314 assert!(result.is_some());
315 let (filename, content) = result.unwrap();
316 assert_eq!(filename, "TINYHARNESS.md");
317 assert!(content.contains("# Project"));
318 assert!(content.contains("Use Rust."));
319 }
320
321 #[test]
323 fn test_discover_project_md_priority() {
324 let dir = tempfile::tempdir().unwrap();
325 let dir_path = dir.path();
326
327 fs::write(dir_path.join("TINYHARNESS.md"), "# From TINYHARNESS.md").unwrap();
328 fs::write(dir_path.join("AGENTS.md"), "# From AGENTS.md").unwrap();
329 fs::write(dir_path.join("CLAUDE.md"), "# From CLAUDE.md").unwrap();
330
331 let result = discover_project_md(dir_path);
332 assert!(result.is_some());
333 let (filename, content) = result.unwrap();
334 assert_eq!(filename, "TINYHARNESS.md");
335 assert!(content.contains("From TINYHARNESS.md"));
336 }
337
338 #[test]
340 fn test_discover_project_md_agents_md_fallback() {
341 let dir = tempfile::tempdir().unwrap();
342 let dir_path = dir.path();
343
344 fs::write(dir_path.join("AGENTS.md"), "# From AGENTS.md").unwrap();
345
346 let result = discover_project_md(dir_path);
347 assert!(result.is_some());
348 let (filename, content) = result.unwrap();
349 assert_eq!(filename, "AGENTS.md");
350 assert!(content.contains("From AGENTS.md"));
351 }
352
353 #[test]
355 fn test_discover_project_md_claude_md_fallback() {
356 let dir = tempfile::tempdir().unwrap();
357 let dir_path = dir.path();
358
359 fs::write(dir_path.join("CLAUDE.md"), "# From CLAUDE.md").unwrap();
360
361 let result = discover_project_md(dir_path);
362 assert!(result.is_some());
363 let (filename, content) = result.unwrap();
364 assert_eq!(filename, "CLAUDE.md");
365 assert!(content.contains("From CLAUDE.md"));
366 }
367
368 #[test]
370 fn test_discover_project_md_none() {
371 let dir = tempfile::tempdir().unwrap();
372 let result = discover_project_md(dir.path());
373 assert!(result.is_none());
374 }
375
376 #[test]
378 fn test_discover_project_md_walks_up() {
379 let dir = tempfile::tempdir().unwrap();
380 let dir_path = dir.path();
381
382 fs::write(dir_path.join("TINYHARNESS.md"), "# Found in parent").unwrap();
384
385 let subdir = dir_path.join("src").join("tools");
386 fs::create_dir_all(&subdir).unwrap();
387
388 let result = discover_project_md(&subdir);
389 assert!(result.is_some());
390 let (filename, content) = result.unwrap();
391 assert_eq!(filename, "TINYHARNESS.md");
392 assert!(content.contains("Found in parent"));
393 }
394
395 #[test]
397 fn test_discover_project_md_hidden_variant() {
398 let dir = tempfile::tempdir().unwrap();
399 let dir_path = dir.path();
400
401 fs::write(dir_path.join(".tinyharness.md"), "# Hidden variant").unwrap();
402
403 let result = discover_project_md(dir_path);
404 assert!(result.is_some());
405 let (filename, content) = result.unwrap();
406 assert_eq!(filename, ".tinyharness.md");
407 assert!(content.contains("Hidden variant"));
408 }
409
410 #[test]
412 fn test_truncate_content_under_limit() {
413 let content = "Hello, world!".to_string();
414 let result = truncate_content(&content, "TINYHARNESS.md");
415 assert_eq!(result, content); }
417
418 #[test]
420 fn test_truncate_content_over_limit() {
421 let content = "A".repeat(PROJECT_MD_MAX_CHARS + 5000);
423 let result = truncate_content(&content, "TINYHARNESS.md");
424
425 assert!(result.contains("[...truncated TINYHARNESS.md"));
427 assert!(result.contains("Use the read tool to view the full file"));
428
429 assert!(result.len() < content.len());
431
432 assert!(result.starts_with('A'));
434 assert!(result.ends_with('A'));
435 }
436
437 #[test]
439 fn test_format_includes_project_md() {
440 let ctx = WorkspaceContext {
441 root: PathBuf::from("/tmp/test"),
442 project_type: "Rust".to_string(),
443 project_name: "test-project".to_string(),
444 structure: vec!["src/ (main.rs)".to_string()],
445 is_git_repo: false,
446 build_command: "cargo build".to_string(),
447 test_command: "cargo test".to_string(),
448 project_md: Some((
449 "TINYHARNESS.md".to_string(),
450 "# My Rules\nAlways use Rust.".to_string(),
451 )),
452 };
453
454 let formatted = ctx.format();
455 assert!(formatted.contains("# Project Instructions (from TINYHARNESS.md)"));
456 assert!(formatted.contains("# My Rules"));
457 assert!(formatted.contains("Always use Rust."));
458 }
459
460 #[test]
462 fn test_format_without_project_md() {
463 let ctx = WorkspaceContext {
464 root: PathBuf::from("/tmp/test"),
465 project_type: "Rust".to_string(),
466 project_name: "test-project".to_string(),
467 structure: vec!["src/ (main.rs)".to_string()],
468 is_git_repo: false,
469 build_command: "cargo build".to_string(),
470 test_command: "cargo test".to_string(),
471 project_md: None,
472 };
473
474 let formatted = ctx.format();
475 assert!(!formatted.contains("Project Instructions"));
476 }
477
478 #[test]
480 fn test_discover_project_md_hidden_over_agents() {
481 let dir = tempfile::tempdir().unwrap();
482 let dir_path = dir.path();
483
484 fs::write(dir_path.join(".tinyharness.md"), "# Hidden").unwrap();
485 fs::write(dir_path.join("AGENTS.md"), "# Agents").unwrap();
486
487 let result = discover_project_md(dir_path);
488 assert!(result.is_some());
489 let (filename, _) = result.unwrap();
490 assert_eq!(filename, ".tinyharness.md");
491 }
492}