1use crate::backends::Mention;
12use crate::backends::{ExternalBackend, ExternalId, ExternalTask};
13use crate::cmd::CommandErrorContext;
14use crate::home;
15use crate::store;
16use crate::store::MemoryEntry;
17use crate::store::TaskStore;
18use futures::future::join_all;
19use std::collections::HashSet;
20use std::fmt::Write as _;
21use std::path::Path;
22use std::sync::Arc;
23use tokio::fs;
24use tokio::process::Command;
25
26#[derive(Debug, Default)]
28pub struct TaskContext {
29 pub task_context: String,
31 pub parent_context: String,
33 pub project_instructions: String,
35 pub repo_tree: String,
37 pub git_diff: String,
39 pub issue_comments: String,
41 pub pr_review_context: String,
43 pub memory: Vec<MemoryEntry>,
45}
46
47pub async fn load_task_context(task_id: &str) -> String {
49 let contexts_dir = home::contexts_dir().unwrap_or_default();
50
51 let path = contexts_dir.join(format!("task-{task_id}.md"));
52 fs::read_to_string(&path).await.unwrap_or_default()
53}
54
55pub async fn build_parent_context(
57 task: &ExternalTask,
58 backend: &dyn ExternalBackend,
59 store: &Option<Arc<TaskStore>>,
60 repo: &str,
61) -> String {
62 let parent_id = match store::opt_store_get_task(store, repo, &task.id.0)
64 .await
65 .and_then(|t| t.parent_id)
66 {
67 Some(id) => id.to_string(),
68 None => return String::new(),
69 };
70
71 let mut ctx = String::new();
72
73 let Ok(parent) = backend.get_task(&ExternalId(parent_id.clone())).await else {
75 return String::new();
76 };
77
78 let _ = writeln!(
79 ctx,
80 "## Parent Task #{}\n\n**Title**: {}\n\n{}\n",
81 parent.id.0, parent.title, parent.body
82 );
83
84 if let Ok(siblings) = backend.get_sub_issues(&ExternalId(parent_id)).await {
86 let siblings: Vec<ExternalId> = siblings.into_iter().filter(|s| s.0 != task.id.0).collect();
88
89 if !siblings.is_empty() {
90 ctx.push_str("## Sibling Tasks\n\n");
91
92 let task_futs = siblings.iter().map(|id| backend.get_task(id));
94 let task_results = join_all(task_futs).await;
95
96 let store_futs = siblings
98 .iter()
99 .map(|id| store::opt_store_get_task(store, repo, &id.0));
100 let store_results = join_all(store_futs).await;
101
102 for (i, maybe_task_res) in task_results.into_iter().enumerate() {
103 if let Ok(sib) = maybe_task_res {
104 let status = sib
105 .labels
106 .iter()
107 .find(|l| l.starts_with("status:"))
108 .map_or_else(|| "unknown".to_string(), |s| s.replace("status:", ""));
109 let _ = writeln!(ctx, "- #{} [{}]: {}", sib.id.0, status, sib.title);
110
111 if let Some(Some(task_rec)) = store_results.get(i) {
113 let summary = &task_rec.summary;
114 if !summary.is_empty() {
115 let _ = writeln!(ctx, " Summary: {summary}");
116 }
117 }
118 }
119 }
120
121 ctx.push('\n');
122 }
123 }
124
125 ctx
126}
127
128pub async fn build_project_instructions(project_dir: &Path) -> String {
130 let mut instructions = String::new();
131 let mut seen = HashSet::new();
132
133 for filename in &["CLAUDE.md", "AGENTS.md", "README.md"] {
134 let path = project_dir.join(filename);
135 let Ok(real) = fs::canonicalize(&path).await else {
137 continue;
138 };
139
140 if !seen.insert(real) {
141 continue;
142 }
143
144 if let Ok(content) = fs::read_to_string(&path).await
145 && !content.is_empty()
146 {
147 let _ = writeln!(instructions, "## {filename}\n\n{content}\n");
148 }
149 }
150
151 instructions
152}
153
154pub async fn build_repo_tree(project_dir: &Path) -> String {
156 let output = Command::new("git")
157 .args(["ls-files"])
158 .current_dir(project_dir)
159 .output_with_context()
160 .await;
161
162 match output {
163 Ok(o) if o.status.success() => {
164 let full = String::from_utf8_lossy(&o.stdout);
165 let all_lines: Vec<&str> = full.lines().collect();
166 let total = all_lines.len();
167 if total > 200 {
168 format!(
169 "{}\n... (truncated, {} total files)",
170 all_lines[..200].join("\n"),
171 total
172 )
173 } else {
174 all_lines.join("\n")
175 }
176 }
177 _ => String::new(),
178 }
179}
180
181pub async fn build_git_diff(project_dir: &Path, default_branch: &str) -> String {
183 let output = Command::new("git")
184 .args(["diff", &format!("origin/{default_branch}...HEAD")])
185 .current_dir(project_dir)
186 .output_with_context()
187 .await;
188
189 match output {
190 Ok(o) if o.status.success() => {
191 let diff = String::from_utf8_lossy(&o.stdout);
192 if diff.len() > 10000 {
194 let mut boundary = 10000;
196 while !diff.is_char_boundary(boundary) {
197 boundary -= 1;
198 }
199 format!("{}...\n(diff truncated at 10000 chars)", &diff[..boundary])
200 } else {
201 diff.to_string()
202 }
203 }
204 _ => String::new(),
205 }
206}
207
208pub async fn build_git_log(project_dir: &Path, default_branch: &str) -> String {
211 let output = Command::new("git")
212 .args([
213 "log",
214 "--oneline",
215 &format!("origin/{default_branch}..HEAD"),
216 ])
217 .current_dir(project_dir)
218 .output_with_context()
219 .await;
220
221 match output {
222 Ok(o) if o.status.success() => {
223 let log = String::from_utf8_lossy(&o.stdout);
224 let all_lines: Vec<&str> = log.lines().collect();
225 let total = all_lines.len();
226 if total > 100 {
227 format!(
228 "{}\n... (truncated, {} total commits)",
229 all_lines[..100].join("\n"),
230 total
231 )
232 } else {
233 all_lines.join("\n")
234 }
235 }
236 _ => String::new(),
237 }
238}
239
240fn is_bot_comment(mention: &Mention) -> bool {
242 if mention.author.ends_with("[bot]") {
244 return true;
245 }
246 if mention.body.starts_with("## Automated Review") {
248 return true;
249 }
250 false
251}
252
253pub async fn fetch_issue_comments(
258 backend: &dyn ExternalBackend,
259 task_id: &str,
260 limit: usize,
261) -> String {
262 let id = ExternalId(task_id.to_string());
263 let all_comments = match backend.list_issue_comments(&id).await {
264 Ok(c) => c,
265 Err(e) => {
266 tracing::debug!(task_id, error = %e, "failed to fetch issue comments");
267 return String::new();
268 }
269 };
270
271 let human_comments: Vec<_> = all_comments
273 .into_iter()
274 .filter(|c| !is_bot_comment(c))
275 .collect();
276
277 let start = human_comments.len().saturating_sub(limit);
278 let mut formatted = String::new();
279 for comment in &human_comments[start..] {
280 let _ = writeln!(
281 formatted,
282 "**@{}** ({}):\n{}\n",
283 comment.author, comment.created_at, comment.body
284 );
285 }
286
287 formatted
288}
289
290pub async fn build_memory_context(
293 task_id: &str,
294 store: &Option<Arc<TaskStore>>,
295 repo: &str,
296) -> (String, Vec<MemoryEntry>) {
297 const MAX_MEMORY_ENTRIES: usize = 3;
298
299 let memory = match store::get_recent_memory_result(store, repo, task_id, MAX_MEMORY_ENTRIES)
300 .await
301 {
302 Ok(Some(entries)) => entries,
303 Ok(None) => Vec::new(),
304 Err(e) => {
305 tracing::warn!(task_id, error = %e, "build_memory_context: failed to read memory from store — proceeding without prior learnings");
306 Vec::new()
307 }
308 };
309
310 if memory.is_empty() {
311 return (String::new(), vec![]);
312 }
313
314 let mut context = String::new();
315 context.push_str("## Previous Attempts Memory\n\n");
316 context.push_str("Learnings from previous task attempts:\n\n");
317
318 for entry in &memory {
319 let _ = write!(
320 context,
321 "### Attempt #{} (Agent: {})",
322 entry.attempt, entry.agent
323 );
324
325 if let Some(ref model) = entry.model {
326 let _ = write!(context, ", Model: {model}");
327 }
328 context.push('\n');
329
330 if !entry.approach.is_empty() {
331 let _ = writeln!(context, "**Approach**: {}", entry.approach);
332 }
333
334 if !entry.learnings.is_empty() {
335 context.push_str("**Key Learnings**:\n");
336 for learning in &entry.learnings {
337 let _ = writeln!(context, "- {learning}");
338 }
339 }
340
341 if let Some(ref error) = entry.error {
342 let _ = writeln!(context, "**Error**: {error}");
343 }
344
345 if !entry.files_modified.is_empty() {
346 let _ = writeln!(
347 context,
348 "**Files Modified**: {}",
349 entry.files_modified.join(", ")
350 );
351 }
352
353 context.push('\n');
354 }
355
356 (context, memory)
357}
358
359pub async fn load_pr_review_context(
361 task_id: &str,
362 store: &Option<Arc<TaskStore>>,
363 repo: &str,
364) -> String {
365 store::opt_store_get_task(store, repo, task_id)
366 .await
367 .map(|t| t.pr_review_context)
368 .unwrap_or_default()
369}
370
371pub async fn build_full_context(
373 task: &ExternalTask,
374 backend: Option<&dyn ExternalBackend>,
375 project_dir: &Path,
376 default_branch: &str,
377 attempts: u32,
378 store: &Option<Arc<TaskStore>>,
379 repo: &str,
380) -> TaskContext {
381 let (
382 task_context,
383 parent_context,
384 project_instructions,
385 repo_tree,
386 git_diff,
387 issue_comments,
388 pr_review_context,
389 (_, memory),
390 ) = tokio::join!(
391 load_task_context(&task.id.0),
392 async {
393 if let Some(b) = backend {
394 build_parent_context(task, b, store, repo).await
395 } else {
396 String::new()
397 }
398 },
399 build_project_instructions(project_dir),
400 build_repo_tree(project_dir),
401 async {
402 if attempts > 0 {
403 build_git_diff(project_dir, default_branch).await
404 } else {
405 String::new()
406 }
407 },
408 async {
409 if let Some(b) = backend {
410 fetch_issue_comments(b, &task.id.0, 10).await
411 } else {
412 String::new()
413 }
414 },
415 load_pr_review_context(&task.id.0, store, repo),
416 build_memory_context(&task.id.0, store, repo),
417 );
418
419 TaskContext {
420 task_context,
421 parent_context,
422 project_instructions,
423 repo_tree,
424 git_diff,
425 issue_comments,
426 pr_review_context,
427 memory,
428 }
429}
430
431#[cfg(test)]
432mod tests {
433 use std::env;
434 #[cfg(unix)]
435 use std::fs as std_fs;
436 #[cfg(unix)]
437 use std::os::unix::fs as unix_fs;
438
439 use super::*;
440
441 #[tokio::test]
442 async fn test_build_memory_context_empty() {
443 let (context, memory) = build_memory_context("nonexistent-task-12345", &None, "").await;
444 assert_eq!(context, "");
445 assert!(memory.is_empty(), "{memory:?}");
446 }
447
448 #[tokio::test]
449 async fn test_build_project_instructions_empty_dir() {
450 let dir = env::temp_dir().join("orch_test_nonexistent");
451 let instructions = build_project_instructions(&dir).await;
452 assert_eq!(instructions, "");
453 }
454
455 #[cfg(unix)]
456 #[tokio::test]
457 async fn project_instructions_read_a_symlinked_file_once() {
458 let dir = tempfile::tempdir().unwrap();
459 std_fs::write(dir.path().join("AGENTS.md"), "agent rules").unwrap();
460 unix_fs::symlink("AGENTS.md", dir.path().join("CLAUDE.md")).unwrap();
461 std_fs::write(dir.path().join("README.md"), "readme").unwrap();
462
463 let instructions = build_project_instructions(dir.path()).await;
464 assert_eq!(instructions.matches("agent rules").count(), 1);
465 assert!(instructions.contains("## CLAUDE.md"));
466 assert!(!instructions.contains("## AGENTS.md"));
467 assert!(instructions.contains("readme"));
468 }
469
470 #[test]
471 fn test_task_context_default_values() {
472 let ctx = TaskContext {
473 task_context: String::new(),
474 parent_context: String::new(),
475 project_instructions: String::new(),
476 repo_tree: String::new(),
477 git_diff: String::new(),
478 issue_comments: String::new(),
479 pr_review_context: String::new(),
480 memory: vec![],
481 };
482
483 assert_eq!(ctx.task_context, "");
484 assert!(ctx.memory.is_empty(), "{:?}", ctx.memory);
485 }
486}