1pub use crate::github::types::ReviewIssue;
10use crate::store;
11use crate::store::TaskStore;
12use std::collections::HashSet;
13use std::collections::hash_map::DefaultHasher;
14use std::fs;
15use std::fs::File;
16use std::hash::Hash;
17use std::hash::Hasher;
18use std::io::Read;
19use std::io::Seek;
20use std::io::SeekFrom;
21use std::path::{Path, PathBuf};
22use std::result;
23use std::sync::Arc;
24use std::thread;
25use std::time::Duration;
26use std::time::SystemTime;
27
28use tokio::fs as tokio_fs;
29use tokio::task;
30use tokio::time;
31use crate::config as app_config;
33pub use crate::cooldown::{
34 clear_expired_cooldowns, is_agent_in_cooldown, is_model_in_cooldown,
35 record_agent_failure_with_message, record_model_failure, set_agent_cooldown,
36};
37use crate::engine;
38use crate::engine::agents::parser::AgentResponse;
39use crate::engine::router::config;
40use crate::engine::runner::ndjson;
41use crate::store::MemoryEntry;
42use crate::store::Task;
43use crate::sys::cmd_cache;
44use crate::sys::home;
45
46const JITTER_FACTOR: f64 = 0.3;
47
48const MAX_OUTPUT_SIZE_BYTES: u64 = 10 * 1024 * 1024;
51
52fn read_file_with_limit<P: AsRef<Path>>(path: P, max_bytes: u64) -> anyhow::Result<String> {
58 let path = path.as_ref();
59 let metadata = fs::metadata(path)?;
60
61 if !metadata.is_file() {
62 anyhow::bail!("not a file: {}", path.display());
63 }
64
65 let file_size = metadata.len();
66
67 if file_size <= max_bytes {
69 return fs::read_to_string(path).map_err(Into::into);
70 }
71
72 let mut file = File::open(path)?;
74 let start_pos = file_size.saturating_sub(max_bytes);
75 file.seek(SeekFrom::Start(start_pos))?;
76
77 let mut buffer = Vec::with_capacity(usize::try_from(max_bytes).unwrap_or(0));
78 file.read_to_end(&mut buffer)?;
79
80 let content = String::from_utf8_lossy(&buffer);
82
83 tracing::warn!(
85 path = %path.display(),
86 file_size = file_size,
87 max_bytes = max_bytes,
88 "output file truncated: exceeded size limit"
89 );
90
91 Ok(content.into_owned())
92}
93
94pub(crate) fn calculate_backoff_delay(retry_count: usize) -> u64 {
99 let base_delay = config::retry_base_delay_ms();
100 let max_delay = config::retry_max_delay_ms();
101
102 let exponential =
104 base_delay * (2_u64.saturating_pow(u32::try_from(retry_count).unwrap_or(u32::MAX)));
105 let capped = exponential.min(max_delay);
106
107 #[expect(
112 clippy::cast_precision_loss,
113 clippy::cast_possible_truncation,
114 clippy::cast_sign_loss,
115 reason = "a jitter range in milliseconds, far below 2^52 and never negative"
116 )]
117 let jitter_range = (capped as f64 * JITTER_FACTOR) as u64;
118 let jitter = {
119 let mut h = DefaultHasher::new();
120 SystemTime::now().hash(&mut h);
121 thread::current().id().hash(&mut h);
122 h.finish() % (jitter_range * 2 + 1)
123 };
124
125 capped.saturating_sub(jitter_range) + jitter
126}
127
128fn fallback_retry_count(task: Option<&Task>) -> usize {
129 task.map_or(0, |t| {
130 let chain_retry_count = t
131 .limit_reroute_chain
132 .split(',')
133 .filter(|entry| !entry.is_empty())
134 .count();
135 let network_retry_count = usize::try_from(t.network_retries).unwrap_or(0);
136 chain_retry_count.max(network_retry_count)
137 })
138}
139
140pub async fn wait_for_fallback_backoff(
143 task_id: &str,
144 store: &Option<Arc<TaskStore>>,
145 repo: &str,
146) -> u64 {
147 let task = store::opt_store_get_task(store, repo, task_id).await;
148
149 let retry_count = fallback_retry_count(task.as_ref());
152
153 let delay = calculate_backoff_delay(retry_count);
154
155 if delay > 0 {
156 tracing::debug!(
157 task_id,
158 retry_count = retry_count,
159 delay_ms = delay,
160 "fallback backoff: waiting before retry"
161 );
162 time::sleep(Duration::from_millis(delay)).await;
163 }
164
165 delay
166}
167
168#[derive(Debug, Clone)]
173pub enum WeightSignal {
174 Success { agent: String },
176 RateLimited { agent: String },
178 Failed { agent: String },
181 Blocked,
183 Rerouted,
186 None,
188}
189
190pub async fn read_output_file(task_id: &str, primary_path: &Path, repo: &str) -> String {
195 if let Some(content) = task::spawn_blocking({
197 let p = primary_path.to_path_buf();
198 move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
199 })
200 .await
201 .ok()
202 .and_then(result::Result::ok)
203 && !content.is_empty()
204 {
205 return content;
206 }
207
208 if let Ok(task_dir) = home::task_dir_async(repo, task_id).await {
210 let attempts_dir = task_dir.join("attempts");
211 if tokio_fs::metadata(&attempts_dir)
213 .await
214 .is_ok_and(|m| m.is_dir())
215 {
216 let mut attempt_nums: Vec<u32> = task::spawn_blocking({
217 let a = attempts_dir.clone();
218 move || {
219 match fs::read_dir(&a) {
220 Ok(entries) => {
221 let mut nums = Vec::new();
222 for entry in entries {
223 match entry {
224 Ok(e) => {
225 if let Some(n) =
226 e.file_name().to_str().and_then(|n| n.parse().ok())
227 {
228 nums.push(n);
229 }
230 }
231 Err(e) => tracing::warn!(
232 path = %a.display(),
233 err = %e,
234 "error reading attempt dir entry in output fallback"
235 ),
236 }
237 }
238 nums
239 }
240 Err(e) => {
241 tracing::warn!(path = %a.display(), err = %e, "failed to read attempts dir in output fallback");
242 Vec::new()
243 }
244 }
245 }
246 })
247 .await
248 .unwrap_or_default();
249
250 attempt_nums.sort_unstable_by(|a, b| b.cmp(a)); for n in attempt_nums {
252 let p = attempts_dir.join(n.to_string()).join("output.json");
253 if let Some(content) = task::spawn_blocking({
254 let p = p.clone();
255 move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
256 })
257 .await
258 .ok()
259 .and_then(result::Result::ok)
260 && !content.is_empty()
261 {
262 tracing::info!(task_id, path = %p.display(), "read output from attempt dir");
263 return content;
264 }
265 }
266 }
267 }
268
269 let state_dir = home::state_dir().unwrap_or_else(|_| PathBuf::from("/tmp"));
271
272 let mut fallbacks = vec![
273 PathBuf::from(format!("/tmp/output-{task_id}.json")),
274 state_dir.join(format!("output-{task_id}.json")),
275 ];
276
277 if let Ok(legacy_path) = home::state_file(&format!("output-{task_id}.json"))
278 && !fallbacks.contains(&legacy_path)
279 {
280 fallbacks.push(legacy_path);
281 }
282
283 for path in &fallbacks {
284 if let Some(content) = task::spawn_blocking({
285 let p = path.clone();
286 move || read_file_with_limit(p, MAX_OUTPUT_SIZE_BYTES)
287 })
288 .await
289 .ok()
290 .and_then(result::Result::ok)
291 && !content.is_empty()
292 {
293 tracing::info!(task_id, path = %path.display(), "read output from legacy fallback");
294 return content;
295 }
296 }
297
298 String::new()
299}
300
301pub fn pick_fallback_agent(
303 current_agent: &str,
304 chain: &str,
305 available_agents: &[String],
306) -> Option<String> {
307 clear_expired_cooldowns();
309
310 let chain_set: HashSet<&str> = if chain.is_empty() {
311 HashSet::new()
312 } else {
313 chain.split(',').collect()
314 };
315
316 for agent in available_agents {
320 if agent == current_agent || chain_set.contains(agent.as_str()) {
321 continue;
322 }
323 if is_agent_in_cooldown(agent) {
324 continue;
325 }
326 return Some(agent.clone());
333 }
334
335 None
336}
337
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub enum RetryableError {
341 Timeout,
343 Interrupted,
345 UsageLimit,
347 AuthError,
349 Failed,
351 MissingTooling,
353 ModelUnavailable,
357}
358
359impl RetryableError {
360 pub fn type_str(self) -> &'static str {
363 match self {
364 RetryableError::Timeout => "timeout",
365 RetryableError::Interrupted => "interrupted",
366 RetryableError::UsageLimit => "rate_limit",
367 RetryableError::AuthError => "auth_error",
368 RetryableError::ModelUnavailable => "model_unavailable",
369 RetryableError::Failed | RetryableError::MissingTooling => "failed",
370 }
371 }
372}
373
374#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct FailoverOutcome {
377 pub status: String,
379 pub next_agent: Option<String>,
381}
382
383impl FailoverOutcome {
384 fn with_status(status: impl Into<String>) -> Self {
385 Self {
386 status: status.into(),
387 next_agent: None,
388 }
389 }
390
391 fn switched(next_agent: String) -> Self {
392 Self {
393 status: "new".to_string(),
394 next_agent: Some(next_agent),
395 }
396 }
397}
398
399pub async fn handle_failover(
410 task_id: &str,
411 agent_name: &str,
412 error_type: RetryableError,
413 error_message: &str,
414 credit_recorded: bool,
415 store: &Option<Arc<TaskStore>>,
416 repo: &str,
417) -> FailoverOutcome {
418 let chain = get_reroute_chain(task_id, store, repo).await;
420 let chain = update_reroute_chain(task_id, agent_name, &chain, store, repo).await;
421
422 if error_type == RetryableError::Timeout
423 && let Some(status) =
424 block_after_repeated_timeouts(task_id, error_message, store, repo).await
425 {
426 return FailoverOutcome::with_status(status);
427 }
428
429 let available: Vec<String> = engine::configured_agents()
431 .into_iter()
432 .filter(|a| cmd_cache::command_exists(a))
433 .collect();
434
435 let chain_set: HashSet<&str> = if chain.is_empty() {
437 HashSet::new()
438 } else {
439 chain.split(',').collect()
440 };
441 let is_exhausted = available.iter().all(|a| chain_set.contains(a.as_str()));
442
443 if is_exhausted {
444 let is_retryable = matches!(
450 error_type,
451 RetryableError::UsageLimit
452 | RetryableError::AuthError
453 | RetryableError::ModelUnavailable
454 | RetryableError::Timeout
455 | RetryableError::Interrupted
456 );
457 let next_status = if is_retryable { "new" } else { "blocked" };
458
459 tracing::warn!(
460 task_id,
461 agent = agent_name,
462 error_type = ?error_type,
463 next_status,
464 "all agents exhausted"
465 );
466
467 let mut store_fields: Vec<(&str, serde_json::Value)> = Vec::new();
468
469 if is_retryable {
470 let msg = format!("{error_message} (all agents exhausted, will retry when available)");
473 store_fields.push(("last_error", serde_json::json!(msg)));
474 store_fields.push(("limit_reroute_chain", serde_json::json!("")));
475 } else {
476 let msg = format!("{error_message} (all agents exhausted)");
477 let block_reason = format!(
478 "all agents exhausted: {} — {}",
479 error_type.type_str(),
480 error_message
481 );
482 store_fields.push(("last_error", serde_json::json!(msg)));
483 store_fields.push(("block_reason", serde_json::json!(block_reason)));
484 }
485
486 if let Err(e) = store::store_set_result(store, repo, task_id, &store_fields).await {
487 tracing::warn!(task_id, err = %e, "failed to write agents_exhausted fields to store");
488 }
489
490 let details = serde_json::json!({
492 "failure_reason": error_type.type_str(),
493 "error_message": error_message,
494 "chain": chain,
495 "agents_exhausted": true,
496 "is_retryable": is_retryable,
497 });
498 store::store_log_activity(
499 store,
500 repo,
501 task_id,
502 "rerouted",
503 Some("in_progress"),
504 Some(next_status),
505 None::<&str>,
506 None::<&str>,
507 Some(&details),
508 )
509 .await;
510
511 return FailoverOutcome::with_status(next_status);
512 }
513
514 if let Some(next) = pick_fallback_agent(agent_name, &chain, &available) {
516 tracing::info!(
517 task_id,
518 from = agent_name,
519 to = next,
520 error_type = ?error_type,
521 "failover: switching to fallback agent"
522 );
523
524 if !matches!(
526 error_type,
527 RetryableError::MissingTooling
528 | RetryableError::ModelUnavailable
529 | RetryableError::Timeout
530 | RetryableError::Interrupted
531 ) {
532 if !credit_recorded {
535 record_agent_failure_with_message(agent_name, error_message).await;
536 }
537
538 set_agent_cooldown(agent_name, 120).await;
543 }
544
545 let msg = format!("{error_message}, switching to {next} for re-route");
548 if let Err(e) = store::store_set_result(
549 store,
550 repo,
551 task_id,
552 &[
553 ("agent", serde_json::json!(next)),
554 ("model", serde_json::json!("")),
555 ("last_error", serde_json::json!(msg)),
556 ],
557 )
558 .await
559 {
560 tracing::warn!(task_id, err = %e, "failed to write failover agent to store");
561 }
562
563 wait_for_fallback_backoff(task_id, store, repo).await;
569
570 let details = serde_json::json!({
572 "failure_reason": error_type.type_str(),
573 "error_message": error_message,
574 "from_agent": agent_name,
575 "to_agent": next,
576 "chain": chain,
577 });
578 store::store_log_activity(
579 store,
580 repo,
581 task_id,
582 "rerouted",
583 Some("in_progress"),
584 Some("new"),
585 Some(&next),
586 None::<&str>,
587 Some(&details),
588 )
589 .await;
590
591 return FailoverOutcome::switched(next);
592 }
593
594 tracing::warn!(task_id, agent = agent_name, "no fallback agents available");
596
597 let is_retryable = matches!(
598 error_type,
599 RetryableError::UsageLimit
600 | RetryableError::AuthError
601 | RetryableError::ModelUnavailable
602 | RetryableError::Timeout
603 | RetryableError::Interrupted
604 );
605
606 if !matches!(
608 error_type,
609 RetryableError::MissingTooling
610 | RetryableError::ModelUnavailable
611 | RetryableError::Timeout
612 | RetryableError::Interrupted
613 ) && !credit_recorded
614 {
615 record_agent_failure_with_message(agent_name, error_message).await;
616 }
617
618 if is_retryable {
619 wait_for_fallback_backoff(task_id, store, repo).await;
622
623 let msg = format!("{error_message} (no fallback agents, will retry)");
624 if let Err(e) = store::store_set_result(
625 store,
626 repo,
627 task_id,
628 &[
629 ("last_error", serde_json::json!(msg)),
630 ("limit_reroute_chain", serde_json::json!("")),
631 ],
632 )
633 .await
634 {
635 tracing::warn!(task_id, err = %e, "failed to write no_fallback retry fields to store");
636 }
637
638 let details = serde_json::json!({
639 "failure_reason": error_type.type_str(),
640 "error_message": error_message,
641 "chain": chain,
642 "no_fallback_available": true,
643 "is_retryable": true,
644 });
645 store::store_log_activity(
646 store,
647 repo,
648 task_id,
649 "rerouted",
650 Some("in_progress"),
651 Some("new"),
652 None::<&str>,
653 None::<&str>,
654 Some(&details),
655 )
656 .await;
657
658 return FailoverOutcome::with_status("new");
659 }
660
661 let msg = format!("{error_message}, no fallback agents");
662 if let Err(e) = store::store_set_result(
663 store,
664 repo,
665 task_id,
666 &[("last_error", serde_json::json!(msg))],
667 )
668 .await
669 {
670 tracing::warn!(task_id, err = %e, "failed to write no_fallback last_error to store");
671 }
672
673 let details = serde_json::json!({
675 "failure_reason": error_type.type_str(),
676 "error_message": error_message,
677 "chain": chain,
678 "no_fallback_available": true,
679 });
680 store::store_log_activity(
681 store,
682 repo,
683 task_id,
684 "rerouted",
685 Some("in_progress"),
686 Some("needs_review"),
687 None::<&str>,
688 None::<&str>,
689 Some(&details),
690 )
691 .await;
692
693 FailoverOutcome::with_status("needs_review")
694}
695
696pub async fn block_after_repeated_timeouts(
699 task_id: &str,
700 error_message: &str,
701 store: &Option<Arc<TaskStore>>,
702 repo: &str,
703) -> Option<String> {
704 let max: i64 = app_config::get("workflow.max_timeout_retries")
705 .ok()
706 .and_then(|v| v.parse().ok())
707 .unwrap_or(3);
708 let count = match store::store_increment(store, repo, task_id, "timeout_retries").await {
709 Ok(count) => i64::try_from(count).unwrap_or(i64::MAX),
710 Err(e) => {
711 tracing::warn!(task_id, err = %e, "failed to increment timeout_retries");
712 return None;
713 }
714 };
715 if count < max {
716 return None;
717 }
718
719 let block_reason = format!("timed out {count} times");
720 tracing::warn!(
721 task_id,
722 count,
723 max,
724 "timeout retries exhausted, blocking task"
725 );
726 if let Err(e) = store::store_set_result(
727 store,
728 repo,
729 task_id,
730 &[
731 (
732 "last_error",
733 serde_json::json!(format!("{error_message} ({block_reason})")),
734 ),
735 ("block_reason", serde_json::json!(block_reason)),
736 ("limit_reroute_chain", serde_json::json!("")),
737 ],
738 )
739 .await
740 {
741 tracing::warn!(task_id, err = %e, "failed to write timeout block fields to store");
742 }
743 let details = serde_json::json!({
744 "failure_reason": "timeout",
745 "error_message": error_message,
746 "timeout_retries": count,
747 });
748 store::store_log_activity(
749 store,
750 repo,
751 task_id,
752 "rerouted",
753 Some("in_progress"),
754 Some("blocked"),
755 None::<&str>,
756 None::<&str>,
757 Some(&details),
758 )
759 .await;
760 Some("blocked".to_string())
761}
762
763pub async fn get_reroute_chain(
765 task_id: &str,
766 store: &Option<Arc<TaskStore>>,
767 repo: &str,
768) -> String {
769 store::opt_store_get_task(store, repo, task_id)
770 .await
771 .map(|t| t.limit_reroute_chain)
772 .unwrap_or_default()
773 .trim()
774 .to_string()
775}
776
777pub async fn update_reroute_chain(
779 task_id: &str,
780 current_agent: &str,
781 existing_chain: &str,
782 store: &Option<Arc<TaskStore>>,
783 repo: &str,
784) -> String {
785 let mut chain = existing_chain.to_string();
786 if chain.is_empty() {
787 chain = current_agent.to_string();
788 } else if !chain.split(',').any(|a| a == current_agent) {
789 chain = format!("{chain},{current_agent}");
790 }
791
792 if let Err(e) = store::store_set_result(
793 store,
794 repo,
795 task_id,
796 &[("limit_reroute_chain", serde_json::json!(chain))],
797 )
798 .await
799 {
800 tracing::warn!(task_id, err = %e, "failed to write limit_reroute_chain to store");
801 }
802 chain
803}
804
805#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
807pub struct ReviewResponse {
808 pub decision: String,
810 pub notes: String,
812 pub test_results: Option<String>,
814 pub issues: Vec<ReviewIssue>,
816}
817
818pub fn parse_review_response(text: &str) -> anyhow::Result<ReviewResponse> {
824 let resp = parse_review_json(text)?;
825 if matches!(resp.decision.as_str(), "approve" | "request_changes") {
826 return Ok(resp);
827 }
828
829 let stripped = text.replace("approve|request_changes", "");
832 infer_review_response_from_text(&stripped)
833 .ok_or_else(|| anyhow::anyhow!("invalid review decision: {}", resp.decision))
834}
835
836fn parse_review_json(text: &str) -> anyhow::Result<ReviewResponse> {
837 if let Ok(resp) = serde_json::from_str::<ReviewResponse>(text) {
839 return Ok(resp);
840 }
841
842 if let Some(json_str) = extract_json_block(text)
844 && let Ok(resp) = serde_json::from_str::<ReviewResponse>(&json_str)
845 {
846 return Ok(resp);
847 }
848
849 if let Some(resp) = extract_review_response_object(text) {
850 return Ok(resp);
851 }
852
853 anyhow::bail!("failed to parse review response")
854}
855
856fn infer_review_response_from_text(text: &str) -> Option<ReviewResponse> {
857 let lower = text.to_ascii_lowercase();
858 let has_changes_requested =
859 lower.contains("changes requested") || lower.contains("request_changes");
860 if has_changes_requested {
861 return Some(ReviewResponse {
862 decision: "request_changes".to_string(),
863 notes: "Inferred decision from plain-text review output.".to_string(),
864 test_results: None,
865 issues: Vec::new(),
866 });
867 }
868
869 let positive_approval = lower
872 .split(|c: char| !c.is_ascii_alphabetic())
873 .any(|word| word == "lgtm")
874 || lower.contains("decision is `approve`")
875 || lower.contains("decision: `approve`")
876 || lower.contains("decision is approve")
877 || lower.contains("decision: approve");
878 if positive_approval {
879 return Some(ReviewResponse {
880 decision: "approve".to_string(),
881 notes: "Inferred decision from plain-text review output.".to_string(),
882 test_results: None,
883 issues: Vec::new(),
884 });
885 }
886
887 None
888}
889
890pub fn infer_review_response(text: &str) -> Option<ReviewResponse> {
894 infer_review_response_from_text(text)
895}
896
897fn extract_json_block(text: &str) -> Option<String> {
902 let mut search_from = 0;
903 while let Some(start) = text[search_from..].find("```json") {
904 let abs_start = search_from + start;
905 let after_tag = abs_start + "```json".len();
906 let Some(rest) = text[after_tag..].strip_prefix('\n') else {
907 search_from = after_tag;
908 continue;
909 };
910 let content_start = text.len() - rest.len();
911 let Some(end_offset) = rest.find("```") else {
912 search_from = content_start;
913 continue;
914 };
915 let end = content_start + end_offset;
916 let content = text[content_start..end].trim();
917 if content.starts_with('{') {
918 return Some(content.to_string());
919 }
920 search_from = end + 3;
921 }
922 None
923}
924
925fn extract_review_response_object(text: &str) -> Option<ReviewResponse> {
929 let mut start: Option<usize> = None;
930 let mut depth: i32 = 0;
931 let mut in_string = false;
932 let mut escape = false;
933
934 for (idx, ch) in text.char_indices() {
935 if start.is_some() {
936 if in_string {
937 if escape {
938 escape = false;
939 } else if ch == '\\' {
940 escape = true;
941 } else if ch == '"' {
942 in_string = false;
943 }
944 continue;
945 }
946
947 match ch {
948 '"' => in_string = true,
949 '{' => depth += 1,
950 '}' => {
951 depth -= 1;
952 if depth == 0 {
953 debug_assert!(
954 start.is_some(),
955 "start must be Some when depth returns to 0"
956 );
957 let start_idx = start.unwrap_or(0);
958 let candidate = &text[start_idx..=idx];
959 if let Ok(resp) = serde_json::from_str::<ReviewResponse>(candidate) {
960 return Some(resp);
961 }
962 start = None;
963 }
964 }
965 _ => {}
966 }
967 continue;
968 }
969
970 if ch == '{' {
971 start = Some(idx);
972 depth = 1;
973 in_string = false;
974 escape = false;
975 }
976 }
977
978 None
979}
980
981#[expect(
983 clippy::too_many_arguments,
984 reason = "a memory entry records the task, attempt, agent, model and outcome"
985)]
986pub async fn store_learnings_from_response(
987 task_id: &str,
988 attempt: u32,
989 agent: &str,
990 model: Option<&str>,
991 response: &AgentResponse,
992 error: Option<&str>,
993 store: &Option<Arc<TaskStore>>,
994 repo: &str,
995 raw_stdout: &str,
996) {
997 let files_modified = if response.files.is_empty() {
999 let extracted = ndjson::extract_files_changed(raw_stdout);
1000 if !extracted.is_empty() {
1001 tracing::debug!(
1002 task_id,
1003 count = extracted.len(),
1004 "files_modified: fell back to NDJSON extraction (agent reported none)"
1005 );
1006 }
1007 extracted
1008 } else {
1009 response.files.clone()
1010 };
1011
1012 let entry = MemoryEntry {
1014 attempt,
1015 agent: agent.to_string(),
1016 model: model.map(String::from),
1017 learnings: response.learnings.clone(),
1018 error: error.map(String::from),
1019 files_modified,
1020 approach: response.summary.clone(),
1021 timestamp: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
1022 };
1023
1024 if let Some(st) = store
1025 && let Ok(Some(store_id)) = st.resolve_task_id(repo, task_id).await
1026 {
1027 match st.append_memory(store_id, &entry).await {
1028 Err(e) => {
1029 tracing::warn!(task_id, error = ?e, "failed to store memory");
1030 }
1031 _ => {
1032 tracing::debug!(task_id, attempt, "stored memory for attempt");
1033 }
1034 }
1035 }
1036}
1037
1038pub async fn store_failure_memory(
1040 task_id: &str,
1041 attempt: u32,
1042 agent: &str,
1043 model: Option<&str>,
1044 error: &str,
1045 store: &Option<Arc<TaskStore>>,
1046 repo: &str,
1047) {
1048 let entry = MemoryEntry {
1049 attempt,
1050 agent: agent.to_string(),
1051 model: model.map(String::from),
1052 learnings: vec![],
1053 error: Some(error.to_string()),
1054 files_modified: vec![],
1055 approach: String::new(),
1056 timestamp: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(),
1057 };
1058
1059 if let Some(st) = store
1060 && let Ok(Some(store_id)) = st.resolve_task_id(repo, task_id).await
1061 {
1062 match st.append_memory(store_id, &entry).await {
1063 Err(e) => {
1064 tracing::warn!(task_id, error = ?e, "failed to store failure memory");
1065 }
1066 _ => {
1067 tracing::debug!(task_id, attempt, "stored failure memory");
1068 }
1069 }
1070 }
1071}
1072
1073#[cfg(test)]
1074mod tests;