1use crate::backends::Mention;
12use crate::backends::{ExternalBackend, ExternalId, ExternalTask};
13use crate::store;
14use crate::store::MemoryEntry;
15use crate::store::TaskStore;
16use crate::store::cluster::progress::{self, Record};
17use crate::sys::cmd::CommandErrorContext;
18use crate::sys::home;
19use futures::future::join_all;
20use std::collections::HashSet;
21use std::fmt::Write as _;
22use std::path::Path;
23use std::sync::Arc;
24use tokio::fs;
25use tokio::process::Command;
26
27#[derive(Debug, Default)]
29pub struct TaskContext {
30 pub task_context: String,
32 pub parent_context: String,
34 pub project_instructions: String,
36 pub repo_tree: String,
38 pub git_diff: String,
40 pub issue_comments: String,
42 pub pr_review_context: String,
44 pub memory: Vec<MemoryEntry>,
46 pub progress: String,
48}
49
50pub async fn load_task_context(task_id: &str) -> String {
52 let contexts_dir = home::contexts_dir().unwrap_or_default();
53
54 let path = contexts_dir.join(format!("task-{task_id}.md"));
55 fs::read_to_string(&path).await.unwrap_or_default()
56}
57
58pub async fn build_parent_context(
60 task: &ExternalTask,
61 backend: &dyn ExternalBackend,
62 store: &Option<Arc<TaskStore>>,
63 repo: &str,
64) -> String {
65 let parent_id = match store::opt_store_get_task(store, repo, &task.id.0)
67 .await
68 .and_then(|t| t.parent_id)
69 {
70 Some(id) => id.to_string(),
71 None => return String::new(),
72 };
73
74 let mut ctx = String::new();
75
76 let Ok(parent) = backend.get_task(&ExternalId(parent_id.clone())).await else {
78 return String::new();
79 };
80
81 let _ = writeln!(
82 ctx,
83 "## Parent Task #{}\n\n**Title**: {}\n\n{}\n",
84 parent.id.0, parent.title, parent.body
85 );
86
87 if let Ok(siblings) = backend.get_sub_issues(&ExternalId(parent_id)).await {
89 let siblings: Vec<ExternalId> = siblings.into_iter().filter(|s| s.0 != task.id.0).collect();
91
92 if !siblings.is_empty() {
93 ctx.push_str("## Sibling Tasks\n\n");
94
95 let task_futs = siblings.iter().map(|id| backend.get_task(id));
97 let task_results = join_all(task_futs).await;
98
99 let store_futs = siblings
101 .iter()
102 .map(|id| store::opt_store_get_task(store, repo, &id.0));
103 let store_results = join_all(store_futs).await;
104
105 for (i, maybe_task_res) in task_results.into_iter().enumerate() {
106 if let Ok(sib) = maybe_task_res {
107 let status = sib
108 .labels
109 .iter()
110 .find(|l| l.starts_with("status:"))
111 .map_or_else(|| "unknown".to_string(), |s| s.replace("status:", ""));
112 let _ = writeln!(ctx, "- #{} [{}]: {}", sib.id.0, status, sib.title);
113
114 if let Some(Some(task_rec)) = store_results.get(i) {
116 let summary = &task_rec.summary;
117 if !summary.is_empty() {
118 let _ = writeln!(ctx, " Summary: {summary}");
119 }
120 }
121 }
122 }
123
124 ctx.push('\n');
125 }
126 }
127
128 ctx
129}
130
131pub async fn build_project_instructions(project_dir: &Path) -> String {
133 let mut instructions = String::new();
134 let mut seen = HashSet::new();
135
136 for filename in &["CLAUDE.md", "AGENTS.md", "README.md"] {
137 let path = project_dir.join(filename);
138 let Ok(real) = fs::canonicalize(&path).await else {
140 continue;
141 };
142
143 if !seen.insert(real) {
144 continue;
145 }
146
147 if let Ok(content) = fs::read_to_string(&path).await
148 && !content.is_empty()
149 {
150 let _ = writeln!(instructions, "## {filename}\n\n{content}\n");
151 }
152 }
153
154 instructions
155}
156
157pub async fn build_repo_tree(project_dir: &Path) -> String {
159 let output = Command::new("git")
160 .args(["ls-files"])
161 .current_dir(project_dir)
162 .output_with_context()
163 .await;
164
165 match output {
166 Ok(o) if o.status.success() => {
167 let full = String::from_utf8_lossy(&o.stdout);
168 let all_lines: Vec<&str> = full.lines().collect();
169 let total = all_lines.len();
170 if total > 200 {
171 format!(
172 "{}\n... (truncated, {} total files)",
173 all_lines[..200].join("\n"),
174 total
175 )
176 } else {
177 all_lines.join("\n")
178 }
179 }
180 _ => String::new(),
181 }
182}
183
184pub async fn build_git_diff(project_dir: &Path, default_branch: &str) -> String {
186 let output = Command::new("git")
187 .args(["diff", &format!("origin/{default_branch}...HEAD")])
188 .current_dir(project_dir)
189 .output_with_context()
190 .await;
191
192 match output {
193 Ok(o) if o.status.success() => {
194 let diff = String::from_utf8_lossy(&o.stdout);
195 if diff.len() > 10000 {
197 let mut boundary = 10000;
199 while !diff.is_char_boundary(boundary) {
200 boundary -= 1;
201 }
202 format!("{}...\n(diff truncated at 10000 chars)", &diff[..boundary])
203 } else {
204 diff.to_string()
205 }
206 }
207 _ => String::new(),
208 }
209}
210
211pub async fn build_git_log(project_dir: &Path, default_branch: &str) -> String {
214 let output = Command::new("git")
215 .args([
216 "log",
217 "--oneline",
218 &format!("origin/{default_branch}..HEAD"),
219 ])
220 .current_dir(project_dir)
221 .output_with_context()
222 .await;
223
224 match output {
225 Ok(o) if o.status.success() => {
226 let log = String::from_utf8_lossy(&o.stdout);
227 let all_lines: Vec<&str> = log.lines().collect();
228 let total = all_lines.len();
229 if total > 100 {
230 format!(
231 "{}\n... (truncated, {} total commits)",
232 all_lines[..100].join("\n"),
233 total
234 )
235 } else {
236 all_lines.join("\n")
237 }
238 }
239 _ => String::new(),
240 }
241}
242
243fn is_bot_comment(mention: &Mention) -> bool {
245 if mention.author.ends_with("[bot]") {
247 return true;
248 }
249 if mention.body.starts_with("## Automated Review") {
251 return true;
252 }
253 false
254}
255
256pub async fn fetch_issue_comments(
261 backend: &dyn ExternalBackend,
262 task_id: &str,
263 limit: usize,
264) -> String {
265 let id = ExternalId(task_id.to_string());
266 let all_comments = match backend.list_issue_comments(&id).await {
267 Ok(c) => c,
268 Err(e) => {
269 tracing::debug!(task_id, error = %e, "failed to fetch issue comments");
270 return String::new();
271 }
272 };
273
274 let human_comments: Vec<_> = all_comments
276 .into_iter()
277 .filter(|c| !is_bot_comment(c))
278 .collect();
279
280 let start = human_comments.len().saturating_sub(limit);
281 let mut formatted = String::new();
282 for comment in &human_comments[start..] {
283 let _ = writeln!(
284 formatted,
285 "**@{}** ({}):\n{}\n",
286 comment.author, comment.created_at, comment.body
287 );
288 }
289
290 formatted
291}
292
293pub async fn build_memory_context(
296 task_id: &str,
297 store: &Option<Arc<TaskStore>>,
298 repo: &str,
299) -> (String, Vec<MemoryEntry>) {
300 const MAX_MEMORY_ENTRIES: usize = 3;
301
302 let memory = match store::get_recent_memory_result(store, repo, task_id, MAX_MEMORY_ENTRIES)
303 .await
304 {
305 Ok(Some(entries)) => entries,
306 Ok(None) => Vec::new(),
307 Err(e) => {
308 tracing::warn!(task_id, error = %e, "build_memory_context: failed to read memory from store — proceeding without prior learnings");
309 Vec::new()
310 }
311 };
312
313 if memory.is_empty() {
314 return (String::new(), vec![]);
315 }
316
317 let mut context = String::new();
318 context.push_str("## Previous Attempts Memory\n\n");
319 context.push_str("Learnings from previous task attempts:\n\n");
320
321 for entry in &memory {
322 let _ = write!(
323 context,
324 "### Attempt #{} (Agent: {})",
325 entry.attempt, entry.agent
326 );
327
328 if let Some(ref model) = entry.model {
329 let _ = write!(context, ", Model: {model}");
330 }
331 context.push('\n');
332
333 if !entry.approach.is_empty() {
334 let _ = writeln!(context, "**Approach**: {}", entry.approach);
335 }
336
337 if !entry.learnings.is_empty() {
338 context.push_str("**Key Learnings**:\n");
339 for learning in &entry.learnings {
340 let _ = writeln!(context, "- {learning}");
341 }
342 }
343
344 if let Some(ref error) = entry.error {
345 let _ = writeln!(context, "**Error**: {error}");
346 }
347
348 if !entry.files_modified.is_empty() {
349 let _ = writeln!(
350 context,
351 "**Files Modified**: {}",
352 entry.files_modified.join(", ")
353 );
354 }
355
356 context.push('\n');
357 }
358
359 (context, memory)
360}
361
362pub async fn build_progress_context(
364 task_id: &str,
365 store: &Option<Arc<TaskStore>>,
366 repo: &str,
367) -> String {
368 let Some(s) = store.as_ref() else {
369 return String::new();
370 };
371 let Ok(Some(id)) = s.resolve_task_id(repo, task_id).await else {
372 return String::new();
373 };
374 match progress::list(s, id).await {
375 Ok(records) => format_progress(&records),
376 Err(e) => {
377 tracing::warn!(task_id, error = %e, "failed to read the progress records");
378 String::new()
379 }
380 }
381}
382
383pub(crate) fn format_progress(records: &[Record]) -> String {
384 let mut out = String::new();
385 for r in records {
386 let commit: String = r.commit.chars().take(12).collect();
387 let _ = writeln!(out, "- {} on {}, commit {commit}", r.ts, r.node);
388 for (label, text) in [("Done", &r.done), ("Left", &r.left), ("State", &r.state)] {
389 if !text.is_empty() {
390 let _ = writeln!(out, " - {label}: {text}");
391 }
392 }
393 }
394
395 out
396}
397
398pub async fn load_pr_review_context(
400 task_id: &str,
401 store: &Option<Arc<TaskStore>>,
402 repo: &str,
403) -> String {
404 store::opt_store_get_task(store, repo, task_id)
405 .await
406 .map(|t| t.pr_review_context)
407 .unwrap_or_default()
408}
409
410pub async fn build_full_context(
412 task: &ExternalTask,
413 backend: Option<&dyn ExternalBackend>,
414 project_dir: &Path,
415 default_branch: &str,
416 attempts: u32,
417 store: &Option<Arc<TaskStore>>,
418 repo: &str,
419) -> TaskContext {
420 let (
421 task_context,
422 parent_context,
423 project_instructions,
424 repo_tree,
425 git_diff,
426 issue_comments,
427 pr_review_context,
428 (_, memory),
429 progress,
430 ) = tokio::join!(
431 load_task_context(&task.id.0),
432 async {
433 if let Some(b) = backend {
434 build_parent_context(task, b, store, repo).await
435 } else {
436 String::new()
437 }
438 },
439 build_project_instructions(project_dir),
440 build_repo_tree(project_dir),
441 async {
442 if attempts > 0 {
443 build_git_diff(project_dir, default_branch).await
444 } else {
445 String::new()
446 }
447 },
448 async {
449 if let Some(b) = backend {
450 fetch_issue_comments(b, &task.id.0, 10).await
451 } else {
452 String::new()
453 }
454 },
455 load_pr_review_context(&task.id.0, store, repo),
456 build_memory_context(&task.id.0, store, repo),
457 build_progress_context(&task.id.0, store, repo),
458 );
459
460 TaskContext {
461 task_context,
462 parent_context,
463 project_instructions,
464 repo_tree,
465 git_diff,
466 issue_comments,
467 pr_review_context,
468 memory,
469 progress,
470 }
471}
472
473#[cfg(test)]
474mod tests {
475 use std::env;
476 #[cfg(unix)]
477 use std::fs as std_fs;
478 #[cfg(unix)]
479 use std::os::unix::fs as unix_fs;
480
481 use super::*;
482
483 #[tokio::test]
484 async fn test_build_memory_context_empty() {
485 let (context, memory) = build_memory_context("nonexistent-task-12345", &None, "").await;
486 assert_eq!(context, "");
487 assert!(memory.is_empty(), "{memory:?}");
488 }
489
490 #[tokio::test]
491 async fn test_build_project_instructions_empty_dir() {
492 let dir = env::temp_dir().join("orch_test_nonexistent");
493 let instructions = build_project_instructions(&dir).await;
494 assert_eq!(instructions, "");
495 }
496
497 #[cfg(unix)]
498 #[tokio::test]
499 async fn project_instructions_read_a_symlinked_file_once() {
500 let dir = tempfile::tempdir().unwrap();
501 std_fs::write(dir.path().join("AGENTS.md"), "agent rules").unwrap();
502 unix_fs::symlink("AGENTS.md", dir.path().join("CLAUDE.md")).unwrap();
503 std_fs::write(dir.path().join("README.md"), "readme").unwrap();
504
505 let instructions = build_project_instructions(dir.path()).await;
506 assert_eq!(instructions.matches("agent rules").count(), 1);
507 assert!(instructions.contains("## CLAUDE.md"));
508 assert!(!instructions.contains("## AGENTS.md"));
509 assert!(instructions.contains("readme"));
510 }
511
512 #[test]
513 fn test_task_context_default_values() {
514 let ctx = TaskContext {
515 task_context: String::new(),
516 parent_context: String::new(),
517 project_instructions: String::new(),
518 repo_tree: String::new(),
519 git_diff: String::new(),
520 issue_comments: String::new(),
521 pr_review_context: String::new(),
522 memory: vec![],
523 progress: String::new(),
524 };
525
526 assert_eq!(ctx.task_context, "");
527 assert!(ctx.memory.is_empty(), "{:?}", ctx.memory);
528 }
529
530 #[tokio::test]
531 async fn the_agent_message_carries_the_progress_records() {
532 let store = Arc::new(TaskStore::open_memory().await.unwrap());
533 let task = ExternalTask {
534 id: ExternalId("5".into()),
535 title: "Moved".into(),
536 body: "do it".into(),
537 state: "open".into(),
538 labels: vec![],
539 author: "u".into(),
540 created_at: String::new(),
541 updated_at: String::new(),
542 url: String::new(),
543 };
544 let id = store
545 .upsert_external(&store::UpsertExternal::from((&task, "o/r")))
546 .await
547 .unwrap();
548 progress::append(
549 &store,
550 id,
551 &Record {
552 node: "m4".into(),
553 ts: "2026-12-01T10:00:00Z".into(),
554 branch: "gh-issue-5-moved".into(),
555 commit: "0123456789abcdef".into(),
556 committed_by: "agent".into(),
557 pushed_by: "orch".into(),
558 error: None,
559 done: "parser handles quoted args".into(),
560 left: "wire into CLI".into(),
561 state: "tests fail on empty input".into(),
562 },
563 )
564 .await
565 .unwrap();
566
567 let progress = build_progress_context("5", &Some(Arc::clone(&store)), "o/r").await;
568 let ctx = TaskContext {
569 progress,
570 ..TaskContext::default()
571 };
572 let message = super::super::agent::build_agent_message(&task, &ctx, 0);
573 assert!(message.contains("## Progress So Far"), "{message}");
574 for text in [
575 "on m4, commit 0123456789ab",
576 "Done: parser handles quoted args",
577 "Left: wire into CLI",
578 "State: tests fail on empty input",
579 ] {
580 assert!(message.contains(text), "{text}: {message}");
581 }
582 assert!(
583 build_progress_context("6", &Some(store), "o/r")
584 .await
585 .is_empty()
586 );
587 }
588}