Skip to main content

orch/engine/sync/
mod.rs

1//! Sync tick — periodic operations that run less frequently than the core tick.
2//!
3//! The sync tick runs every ~45 seconds and handles:
4//! - Worktree cleanup for done tasks
5//! - Merged-PR detection
6//! - @mention scanning and internal task creation
7//! - PR review processing and follow-up dispatch
8//! - Stale InReview detection
9//! - Owner /slash command scanning
10
11mod comments;
12mod unblock;
13
14use super::EngineConfig;
15use super::ci_bootstrap;
16use super::cleanup::{check_merged_prs, cleanup_done_worktrees, prune_old_run_output};
17use super::review_poll::review_open_prs;
18use crate::backends::ExternalTask;
19use crate::backends::{ExternalBackend, Status};
20use crate::cooldown;
21use crate::cooldown::{
22    cooldown_reason, github_circuit_remaining_secs, is_agent_in_cooldown, is_github_circuit_open,
23    is_model_in_cooldown, refresh_degraded_agents,
24};
25use crate::engine;
26use crate::engine::dependencies;
27use crate::engine::router::Router;
28use crate::engine::router::RouterConfig;
29use crate::engine::router::config as router_config;
30use crate::engine::runner::agents::patterns;
31use crate::engine::tasks;
32use crate::engine::tasks::{TaskManager, status_to_task_status};
33use crate::github::http::GhHttp;
34use crate::store;
35use crate::store::Task;
36use crate::store::TaskRun;
37use crate::store::TaskStatus;
38use crate::store::TaskStore;
39use crate::tmux::TmuxManager;
40use comments::{fetch_comments_since, filter_mentions_by_since, scan_comments};
41use dashmap::{DashMap, DashSet};
42use std::collections::HashMap;
43use std::collections::HashSet;
44use std::sync::Arc;
45use std::time::Instant;
46use tokio::sync::RwLock;
47use unblock::{REBROADCAST_BLOCK_REASON, auto_unblock_blocked_tasks};
48pub(crate) use unblock::{
49    auto_recover_rebroadcast_blocked_tasks_global, auto_unblock_ci_failure_blocked_tasks_global,
50};
51
52/// Read a KV value from the store.
53///
54/// Returns `None` if the store is unavailable, the key doesn't exist, OR if
55/// the store query fails. Use [`try_kv_get_prefer_store`] if you need to
56/// distinguish between "key not found" and actual errors.
57async fn kv_get_prefer_store(store: Option<&Arc<TaskStore>>, key: &str) -> Option<String> {
58    match try_kv_get_prefer_store(store, key).await {
59        Ok(opt) => opt,
60        Err(e) => {
61            tracing::error!(key, err = %e, "kv_get failed");
62            None
63        }
64    }
65}
66
67/// Try to read a KV value from the store, returning errors instead of
68/// silently discarding them.
69///
70/// Returns `Ok(None)` if the store is unavailable or the key doesn't exist.
71/// Returns `Err` if the store query fails.
72async fn try_kv_get_prefer_store(
73    store: Option<&Arc<TaskStore>>,
74    key: &str,
75) -> anyhow::Result<Option<String>> {
76    if let Some(s) = store {
77        Ok(s.kv_get(key).await?)
78    } else {
79        Ok(None)
80    }
81}
82
83/// Write a KV value to the store.
84///
85/// Logs warnings on failure but provides no way for callers to know if the
86/// write succeeded. Use [`try_kv_set_prefer_store`] if you need to handle
87/// errors or guarantee persistence (e.g., for circuit breaker state).
88async fn kv_set_prefer_store(store: Option<&Arc<TaskStore>>, key: &str, value: &str) {
89    if let Err(e) = try_kv_set_prefer_store(store, key, value).await {
90        tracing::error!(key, err = %e, "kv_set failed");
91    }
92}
93
94/// Try to write a KV value to the store, returning errors instead of
95/// silently logging them.
96///
97/// Returns `Ok(())` if the store is unavailable (best-effort) or if the
98/// write succeeds. Returns `Err` if the store query fails.
99async fn try_kv_set_prefer_store(
100    store: Option<&Arc<TaskStore>>,
101    key: &str,
102    value: &str,
103) -> anyhow::Result<()> {
104    if let Some(s) = store {
105        s.kv_set(key, value).await?;
106    }
107    Ok(())
108}
109
110#[derive(Debug, Clone)]
111pub(crate) struct ReviewTaskSnapshot {
112    pub external: ExternalTask,
113    pub stored: Task,
114}
115
116async fn prefetch_review_tasks(
117    store: &Arc<TaskStore>,
118    repo: &str,
119) -> anyhow::Result<(
120    Vec<ReviewTaskSnapshot>,
121    Vec<ReviewTaskSnapshot>,
122    Vec<ReviewTaskSnapshot>,
123)> {
124    // Approved tasks wait on the same merge path as a review in progress
125    let mut in_review = store.list_by_status(repo, TaskStatus::InReview).await?;
126    in_review.extend(store.list_by_status(repo, TaskStatus::Approved).await?);
127    let in_review = in_review
128        .into_iter()
129        .map(|stored| ReviewTaskSnapshot {
130            external: tasks::store_task_to_external(&stored),
131            stored,
132        })
133        .collect();
134    let needs_review = store
135        .list_by_status(repo, TaskStatus::NeedsReview)
136        .await?
137        .into_iter()
138        .map(|stored| ReviewTaskSnapshot {
139            external: tasks::store_task_to_external(&stored),
140            stored,
141        })
142        .collect();
143
144    // Also prefetch blocked tasks that have a branch or PR number recorded.
145    // These can be merged externally (or manually) but previously were invisible
146    // to the merged-PR checker, leaving tasks stuck in Blocked after merges.
147    let blocked_candidates = store
148        .list_by_status(repo, TaskStatus::Blocked)
149        .await?
150        .into_iter()
151        .filter(|stored| stored.pr_number.is_some() || !stored.branch.is_empty())
152        .map(|stored| ReviewTaskSnapshot {
153            external: tasks::store_task_to_external(&stored),
154            stored,
155        })
156        .collect();
157
158    Ok((in_review, needs_review, blocked_candidates))
159}
160
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162enum FailureCategory {
163    FalseFailure,
164    RateLimit,
165    CreditExhausted,
166    SilentExit0,
167    Timeout,
168    ConnectionError,
169    CliFlagError,
170    AllAgentsExhausted,
171    ParseError,
172    MaxAttempts,
173    PushFailed,
174    PrCreateFailed,
175    ModelUnavailable,
176    Unknown,
177}
178
179impl FailureCategory {
180    /// Whether auto-unblock may put the task back in the queue on its own.
181    ///
182    /// `MaxAttempts` is deliberately absent: the task already ran the configured
183    /// number of times, so an automatic retry just restarts the loop that produced
184    /// the block. It stays blocked until `orch task unblock` or `orch task retry`
185    /// (#3783)
186    fn is_recoverable(self) -> bool {
187        matches!(
188            self,
189            FailureCategory::FalseFailure
190                | FailureCategory::RateLimit
191                | FailureCategory::CreditExhausted
192                | FailureCategory::SilentExit0
193                | FailureCategory::Timeout
194                | FailureCategory::ConnectionError
195                | FailureCategory::CliFlagError
196                | FailureCategory::AllAgentsExhausted
197                | FailureCategory::ParseError
198                | FailureCategory::ModelUnavailable
199        )
200    }
201
202    fn as_str(self) -> &'static str {
203        match self {
204            FailureCategory::FalseFailure => "FalseFailure",
205            FailureCategory::RateLimit => "RateLimit",
206            FailureCategory::CreditExhausted => "CreditExhausted",
207            FailureCategory::SilentExit0 => "SilentExit0",
208            FailureCategory::Timeout => "Timeout",
209            FailureCategory::ConnectionError => "ConnectionError",
210            FailureCategory::CliFlagError => "CliFlagError",
211            FailureCategory::AllAgentsExhausted => "AllAgentsExhausted",
212            FailureCategory::ParseError => "ParseError",
213            FailureCategory::MaxAttempts => "MaxAttempts",
214            FailureCategory::PushFailed => "PushFailed",
215            FailureCategory::PrCreateFailed => "PrCreateFailed",
216            FailureCategory::ModelUnavailable => "ModelUnavailable",
217            FailureCategory::Unknown => "Unknown",
218        }
219    }
220}
221
222fn classify_failure(error: &str, outcome: &str) -> FailureCategory {
223    let lower = error.to_lowercase();
224
225    if outcome == "timeout" || lower.contains("timeout") {
226        return FailureCategory::Timeout;
227    }
228
229    // Credit exhaustion is a transient condition (credits replenish, billing cycles
230    // reset). Classifying it as recoverable allows auto-unblock to retry once the
231    // credit-related cooldown expires, instead of permanently blocking the task.
232    //
233    // Checked before the generic rate-limit branch below: billing-cycle exhaustion
234    // messages (e.g. Kimi's "usage limit for this billing cycle") also contain
235    // "usage limit"/"rate limit" substrings, so checking outcome/content-based
236    // rate-limit patterns first would misclassify them as plain RateLimit (issue
237    // #3529). `outcome` also carries the specific string from `classify_run_outcome`
238    // when the task_run already recorded it.
239    if outcome == "billing_cycle_exhausted"
240        || outcome == "credit_exhausted"
241        || outcome == "org_level_disabled"
242        || cooldown::detect_credit_exhaustion(&lower).is_some()
243    {
244        return FailureCategory::CreditExhausted;
245    }
246
247    if outcome == "rate_limit" || lower.contains("rate limit") || lower.contains("usage limit") {
248        return FailureCategory::RateLimit;
249    }
250
251    if error.trim().is_empty() {
252        return FailureCategory::FalseFailure;
253    }
254
255    if lower.contains("all agents exhausted") {
256        return FailureCategory::AllAgentsExhausted;
257    }
258
259    if lower.contains("max attempts") || lower.contains("exceeded max attempts") {
260        return FailureCategory::MaxAttempts;
261    }
262
263    if lower.contains("output-format=stream-json") && lower.contains("requires --verbose") {
264        return FailureCategory::CliFlagError;
265    }
266
267    if lower.contains("model unavailable")
268        || lower.contains("model not found")
269        || (lower.contains("does not exist") && lower.contains("model"))
270    {
271        return FailureCategory::ModelUnavailable;
272    }
273
274    if lower.contains("push failed") {
275        return FailureCategory::PushFailed;
276    }
277
278    if lower.contains("create pr failed")
279        || lower.contains("failed to create pull request")
280        || lower.contains("pull request creation failed")
281    {
282        return FailureCategory::PrCreateFailed;
283    }
284
285    if lower.contains("exit 0") {
286        return FailureCategory::SilentExit0;
287    }
288
289    if outcome == "parse_error"
290        || outcome == "truncated"
291        || lower.contains("invalid response")
292        || lower.contains("parse error")
293        || lower.contains("truncated")
294    {
295        return FailureCategory::ParseError;
296    }
297
298    if patterns::detect_network_error(&lower).is_some() {
299        return FailureCategory::ConnectionError;
300    }
301
302    FailureCategory::Unknown
303}
304
305fn classify_failure_from_run(run: &TaskRun) -> Option<FailureCategory> {
306    // Completed successfully — no failure to classify.
307    if run.outcome == "success" && run.error.trim().is_empty() {
308        return None;
309    }
310
311    // Skip runs with no meaningful data. Some runs are created then never
312    // populated (aborted/stale work). Treat these as non-failures so they
313    // don't block auto-unblock logic which considers recent failures.
314    // Historically an all-NULL/empty run would be promoted to Unknown which
315    // prevented auto-unblock. Ensure we early-return None for truly empty
316    // runs (no outcome, no error, no exit_code, no output).
317    if run.outcome.trim().is_empty()
318        && run.error.trim().is_empty()
319        && run.exit_code.is_none()
320        && run.stdout.trim().is_empty()
321        && run.stderr.trim().is_empty()
322    {
323        return None;
324    }
325
326    let has_output = !run.stdout.trim().is_empty() || !run.stderr.trim().is_empty();
327    if run.exit_code == Some(0) && !has_output && run.outcome != "success" {
328        return Some(FailureCategory::SilentExit0);
329    }
330
331    let mut category = classify_failure(&run.error, &run.outcome);
332
333    // Promote a bare "false failure" to Unknown only when we have a
334    // concrete non-zero exit code or other signs the run truly failed.
335    // Do NOT promote when exit_code is None (incomplete run) — those are
336    // handled above by skipping. This prevents NULL/aborted runs from
337    // turning recoverable FalseFailure into non-recoverable Unknown.
338    // Only promote when we have explicit evidence: a non-zero exit code
339    // or non-empty stdout/stderr. If exit_code is None we keep FalseFailure
340    // so the run remains recoverable.
341    if category == FailureCategory::FalseFailure {
342        let has_nonzero_exit = run.exit_code.is_some() && run.exit_code != Some(0);
343        let has_output = !run.stdout.trim().is_empty() || !run.stderr.trim().is_empty();
344        if has_nonzero_exit || has_output {
345            category = FailureCategory::Unknown;
346        }
347    }
348
349    Some(category)
350}
351
352/// Global sweep: re-fire stale NeedsReview tasks and escalate persistently-stuck ones
353/// to Blocked, across all repos.
354///
355/// Two cases where the event-driven subscriber in `subscribers/review/mod.rs` can miss
356/// a NeedsReview task: all review slots are busy when the event fires, or the
357/// broadcast receiver lagged and dropped it. Re-publish the NeedsReview status
358/// after a short idle window so the subscriber can pick it up when a slot is free.
359/// Using a status re-fire rather than spawning the review agent directly keeps this
360/// path stateless. The subscriber is still the sole spawner and uses the InReview
361/// transition as its atomic guard (issue #857)
362///
363/// Queries across all repos and writes through the store via `*_by_store_id`
364/// TaskManager helpers. Called once per main tick from `tick_global_sweeps`
365pub(crate) async fn refire_and_escalate_stale_needs_review_global(
366    task_manager: &Arc<TaskManager>,
367    store: &Arc<TaskStore>,
368    router: &Router,
369    dispatching: &Arc<DashMap<String, String>>,
370    active_repos: &HashSet<String>,
371) -> anyhow::Result<()> {
372    const MIN_STALE_NEEDS_REVIEW_MINUTES: i64 = 1;
373    const MAX_NEEDS_REVIEW_REFIRE_ATTEMPTS: u64 = 5;
374
375    let needs_review_tasks = match store
376        .list_all_by_status_global(TaskStatus::NeedsReview)
377        .await
378    {
379        Ok(tasks) => tasks,
380        Err(e) => {
381            tracing::warn!(err = %e, "global NeedsReview refire sweep: failed to list needs_review tasks");
382            return Ok(());
383        }
384    };
385
386    if needs_review_tasks.is_empty() {
387        return Ok(());
388    }
389
390    // Re-firing while every review agent is cooled wastes the counter and can
391    // escalate a task to Blocked while the subscriber would only bail again
392    let all_review_agents_cooled = router.healthy_agent_count("review") == 0;
393    if all_review_agents_cooled {
394        tracing::info!(
395            count = needs_review_tasks.len(),
396            "global NeedsReview refire sweep: no review agent available — skipping this pass"
397        );
398        return Ok(());
399    }
400
401    for stored in needs_review_tasks {
402        // No review subscriber listens for a repo outside the active set
403        if !active_repos.contains(&stored.repo) {
404            continue;
405        }
406
407        let external = tasks::store_task_to_external(&stored);
408        let ext_id = external.id.clone();
409        let repo = stored.repo.clone();
410
411        let age_minutes = match chrono::DateTime::parse_from_rfc3339(&external.updated_at) {
412            Ok(updated_at) => {
413                let age = chrono::Utc::now() - updated_at.with_timezone(&chrono::Utc);
414                if age.num_minutes() < MIN_STALE_NEEDS_REVIEW_MINUTES {
415                    continue;
416                }
417                Some(age.num_minutes())
418            }
419            Err(_) => None,
420        };
421
422        // Skip tasks actively being dispatched by their owning repo's engine loop.
423        let dispatch_key = format!("{}/{}", repo, ext_id.0);
424        if dispatching.contains_key(&dispatch_key) {
425            continue;
426        }
427
428        let current_refires = u64::try_from(stored.needs_review_refires).unwrap_or(0);
429        let new_refires = current_refires + 1;
430
431        if new_refires > MAX_NEEDS_REVIEW_REFIRE_ATTEMPTS {
432            tracing::warn!(
433                task_id = stored.id,
434                repo = %repo,
435                new_refires,
436                "global NeedsReview refire sweep: escalating to Blocked after repeated refires"
437            );
438            let fields = [
439                ("block_reason", serde_json::json!(REBROADCAST_BLOCK_REASON)),
440                (
441                    "last_error",
442                    serde_json::json!(format!("escalated after {} retries", new_refires)),
443                ),
444            ];
445            if let Err(e) = task_manager
446                .update_task_status_and_result_by_store_id(
447                    stored.id,
448                    &repo,
449                    &ext_id,
450                    Status::Blocked,
451                    &fields,
452                )
453                .await
454            {
455                tracing::error!(task_id = stored.id, repo = %repo, err = %e, "global NeedsReview refire sweep: escalation to Blocked failed — skipping to avoid silent auto-unblock loop");
456                continue;
457            }
458            if let Err(e) = store::store_increment_by_id(
459                &Some(Arc::clone(store)),
460                stored.id,
461                "needs_review_refires",
462            )
463            .await
464            {
465                tracing::warn!(
466                    task_id = stored.id,
467                    repo = %repo,
468                    err = %e,
469                    "global NeedsReview refire sweep: failed to increment needs_review_refires after escalation"
470                );
471            }
472            continue;
473        }
474
475        // Exponential backoff: MIN * 2^(current_refires)
476        let required_minutes =
477            MIN_STALE_NEEDS_REVIEW_MINUTES * (1i64 << u32::try_from(current_refires).unwrap_or(0));
478
479        let should_fire = match age_minutes {
480            Some(age) => age >= required_minutes,
481            None => true,
482        };
483
484        if !should_fire {
485            continue;
486        }
487
488        if let Err(e) = task_manager
489            .update_task_status_by_store_id(stored.id, &repo, &ext_id, Status::NeedsReview)
490            .await
491        {
492            tracing::warn!(
493                task_id = stored.id,
494                repo = %repo,
495                err = %e,
496                "global NeedsReview refire sweep: failed to re-fire NeedsReview event — not incrementing counter"
497            );
498            continue;
499        }
500
501        let fired_refires = match store::store_increment_by_id(
502            &Some(Arc::clone(store)),
503            stored.id,
504            "needs_review_refires",
505        )
506        .await
507        {
508            Ok(v) => v,
509            Err(e) => {
510                tracing::warn!(
511                    task_id = stored.id,
512                    repo = %repo,
513                    err = %e,
514                    "global NeedsReview refire sweep: failed to increment needs_review_refires after re-fire"
515                );
516                current_refires + 1
517            }
518        };
519
520        tracing::info!(
521            task_id = stored.id,
522            repo = %repo,
523            age_minutes,
524            refires = fired_refires,
525            required_minutes,
526            "global NeedsReview refire sweep: re-firing NeedsReview event for stale task"
527        );
528    }
529
530    Ok(())
531}
532
533/// Sync tick — runs every 45s.
534///
535/// Handles less-frequent operations:
536/// - Cleanup finished worktrees
537/// - Check for merged PRs → mark tasks done
538/// - Scan for @mentions
539#[expect(
540    clippy::too_many_arguments,
541    reason = "the engine passes its shared handles one by one"
542)]
543pub(crate) async fn sync_tick(
544    backend: &Arc<dyn ExternalBackend>,
545    tmux: &Arc<TmuxManager>,
546    repo: &str,
547    config: &EngineConfig,
548    router: &Arc<RwLock<Router>>,
549    task_manager: &Arc<TaskManager>,
550    store: &Arc<TaskStore>,
551    dispatching: &Arc<DashMap<String, String>>,
552    auto_merge_in_flight: &Arc<DashSet<String>>,
553) -> anyhow::Result<()> {
554    // One node polls GitHub and decides for the whole cluster
555    if !store.is_leader() {
556        return Ok(());
557    }
558
559    tracing::debug!("sync tick");
560
561    let mut phases: Vec<(&str, u128)> = Vec::new();
562    let mut at = Instant::now();
563
564    // Global GitHub 5xx circuit breaker — skip non-critical background work
565    // during sustained GitHub outages to reduce churn and wasted API calls.
566    let gh_circuit_open = is_github_circuit_open();
567
568    if gh_circuit_open {
569        let remaining = github_circuit_remaining_secs();
570        tracing::debug!(
571            remaining_secs = remaining,
572            "GitHub 5xx circuit breaker open — skipping non-critical sync work"
573        );
574        // Persist circuit breaker state as a metric for operators.
575        // This is critical for avoiding thundering herd after restart during outages.
576        if let Err(e) =
577            try_kv_set_prefer_store(Some(store), "metrics:orch.github_5xx_circuit.open", "1").await
578        {
579            tracing::error!(err = %e, "failed to persist circuit breaker state — may cause thundering herd after restart");
580        }
581    } else if let Err(e) =
582        try_kv_set_prefer_store(Some(store), "metrics:orch.github_5xx_circuit.open", "0").await
583    {
584        tracing::error!(err = %e, "failed to clear circuit breaker state");
585    }
586
587    // 0. Ingest all active external tasks into the unified store.
588    //    This ensures the store has data for tasks created before dual-write was added.
589    if !gh_circuit_open {
590        if let Err(e) = ingest_external_tasks(backend, repo, store).await {
591            tracing::debug!(err = %e, "external task ingest failed");
592        }
593        phases.push(("ingest", at.elapsed().as_millis()));
594        at = Instant::now();
595
596        // Reconcile existing board members too: labels can change without a
597        // local task transition, and a human/automation may move a card. The
598        // backend only writes drifted fields through the shared GitHub client.
599        if let Err(e) = backend.reconcile_project_statuses().await {
600            tracing::warn!(err = %e, "project status reconciliation failed");
601        }
602        phases.push(("board_reconcile", at.elapsed().as_millis()));
603    }
604    at = Instant::now();
605
606    // 1. Cleanup worktrees for done tasks (background — must not block routing/dispatch)
607    if !gh_circuit_open {
608        let backend = Arc::clone(backend);
609        let repo = repo.to_string();
610        let task_manager = Arc::clone(task_manager);
611        let store = Arc::clone(store);
612        tokio::spawn(async move {
613            if let Err(e) = cleanup_done_worktrees(&backend, &repo, &task_manager, &store).await {
614                tracing::warn!(err = %e, "worktree cleanup failed");
615            }
616            if let Err(e) = prune_old_run_output(&store).await {
617                tracing::warn!(err = %e, "task run pruning failed");
618            }
619        });
620    }
621
622    let (in_review_tasks, needs_review_tasks, blocked_review_candidates) =
623        match prefetch_review_tasks(store, repo).await {
624            Ok(tasks) => tasks,
625            Err(e) => {
626                tracing::warn!(err = %e, "failed to prefetch review tasks");
627                (vec![], vec![], vec![])
628            }
629        };
630    phases.push(("prefetch_review", at.elapsed().as_millis()));
631    at = Instant::now();
632
633    if !gh_circuit_open {
634        let mention_fallback = chrono::Utc::now() - chrono::Duration::hours(24);
635        let mention_since = kv_get_prefer_store(Some(store), "mentions_last_checked")
636            .await
637            .unwrap_or_else(|| mention_fallback.format("%Y-%m-%dT%H:%M:%SZ").to_string());
638        let shared_since = mention_since.clone();
639
640        let cached_router_config = router.read().await.config.clone();
641        // Include blocked tasks that have branch/pr info when checking for merged PRs.
642        let mut combined_needs = needs_review_tasks.clone();
643        combined_needs.extend(blocked_review_candidates.clone());
644
645        let (merge_result, comments_result, review_result) = tokio::join!(
646            check_merged_prs(
647                backend,
648                repo,
649                store,
650                task_manager,
651                &in_review_tasks,
652                &combined_needs,
653            ),
654            fetch_comments_since(backend, &shared_since),
655            async {
656                let gh = match GhHttp::new() {
657                    Ok(g) => g,
658                    Err(e) => {
659                        tracing::warn!(err = %e, "failed to create GitHub HTTP client for review poll");
660                        return Ok(());
661                    }
662                };
663                Box::pin(review_open_prs(
664                    backend,
665                    repo,
666                    config,
667                    task_manager,
668                    store,
669                    dispatching,
670                    auto_merge_in_flight,
671                    &in_review_tasks,
672                    &gh,
673                    &cached_router_config,
674                ))
675                .await
676            }
677        );
678
679        if let Err(e) = merge_result {
680            tracing::warn!(err = %e, "PR merge check failed");
681        }
682
683        match comments_result {
684            Ok(comments) => {
685                let filtered = filter_mentions_by_since(&comments, &mention_since);
686
687                if let Err(e) =
688                    scan_comments(backend, Some(store), repo, task_manager, Some(&filtered)).await
689                {
690                    tracing::warn!(err = %e, "comment scan failed");
691                }
692            }
693            Err(e) => {
694                tracing::warn!(err = %e, "comment fetch failed");
695            }
696        }
697
698        if let Err(e) = review_result {
699            tracing::warn!(err = %e, "PR review failed");
700        }
701
702        if let Err(e) = ci_bootstrap::apply_pending(store, task_manager, repo).await {
703            tracing::warn!(err = %e, "CI bootstrap ruleset apply failed");
704        }
705
706        phases.push(("merge_comments_review", at.elapsed().as_millis()));
707    }
708    at = Instant::now();
709
710    // 5. Stale InReview recovery lives in `tick_recover_stuck_tasks`, the single owner of an
711    // in_review task whose review session is gone or hung. It ran here too, after one minute,
712    // which beat a finished review's result to the engine and dropped it as stale
713
714    // 5c. Detect stale InProgress tasks and recover them.
715    //
716    // Similar to stale InReview detection, we check for InProgress tasks whose
717    // agent tmux session has died (crash, OOM, etc.) and reset them to Routed
718    // so they can be re-dispatched.
719    let in_progress_tasks: Vec<_> = match store.list_by_status(repo, TaskStatus::InProgress).await {
720        Ok(tasks) => tasks
721            .into_iter()
722            .map(|stored| {
723                let external = tasks::store_task_to_external(&stored);
724                (stored, external)
725            })
726            .collect(),
727        Err(e) => {
728            tracing::warn!(err = %e, "failed to list in_progress tasks — skipping stale InProgress check");
729            vec![]
730        }
731    };
732
733    if !in_progress_tasks.is_empty() {
734        // Fetch all live tmux sessions once instead of one subprocess call per task.
735        let live_sessions: HashSet<String> = tmux
736            .list_sessions()
737            .await
738            .unwrap_or_default()
739            .into_iter()
740            .map(|s| s.name)
741            .collect();
742
743        for (_stored, external) in &in_progress_tasks {
744            // A task is only considered stale if it has been in InProgress for > 5 minutes.
745            const MIN_STALE_MINUTES: i64 = 5;
746
747            let task_id = &external.id.0;
748
749            // Skip tasks currently being processed by the main tick (dispatch + agent flow).
750            let dispatch_key = format!("{repo}/{task_id}");
751            {
752                if dispatching.contains_key(&dispatch_key) {
753                    tracing::debug!(
754                        task_id = %task_id,
755                        "task locked by dispatch flow, skipping stale check"
756                    );
757                    continue;
758                }
759            }
760
761            // Skip tasks that just transitioned to InProgress — allow time for the
762            // agent to start its tmux session before treating it as stale.
763            match chrono::DateTime::parse_from_rfc3339(&external.updated_at) {
764                Ok(updated_at) => {
765                    let age = chrono::Utc::now() - updated_at.with_timezone(&chrono::Utc);
766                    if age.num_minutes() < MIN_STALE_MINUTES {
767                        tracing::debug!(
768                            task_id = %task_id,
769                            age_seconds = age.num_seconds(),
770                            "InProgress task is too young to be considered stale, skipping"
771                        );
772                        continue;
773                    }
774                }
775                Err(e) => {
776                    tracing::warn!(
777                        task_id = %task_id,
778                        ts = %external.updated_at,
779                        err = %e,
780                        "invalid updated_at timestamp — treating task as potentially stale"
781                    );
782                }
783            }
784
785            let agent_session = tmux.session_name(repo, task_id);
786            if live_sessions.contains(&agent_session) {
787                // Agent is still alive — skip.
788                continue;
789            }
790
791            // No agent session exists. The agent is dead regardless of
792            // session tracking — hard restart, crash, or flag not persisted.
793            // Reset to Routed so the dispatcher can re-spawn it.
794            {
795                tracing::warn!(
796                    task_id = %task_id,
797                    session = %agent_session,
798                    "InProgress task has no active agent session — resetting to Routed"
799                );
800                match task_manager
801                    .update_task_status_if(&external.id, Status::Routed, Status::InProgress)
802                    .await
803                {
804                    Err(e) => {
805                        tracing::error!(task_id = %task_id, err = %e, "failed to reset stale InProgress task — task may be stuck in InProgress indefinitely");
806                    }
807                    Ok(false) => {
808                        tracing::debug!(
809                            task_id = %task_id,
810                            "stale InProgress reset skipped — task already transitioned (concurrent Done/Blocked/NeedsReview)"
811                        );
812                    }
813                    Ok(true) => {
814                        // Successfully reset to Routed
815                    }
816                }
817            }
818        }
819    }
820
821    phases.push(("stale_in_progress", at.elapsed().as_millis()));
822    at = Instant::now();
823    // 5c. Auto-unblock tasks with recoverable failures.
824    if let Err(e) =
825        auto_unblock_blocked_tasks(repo, task_manager, store, dispatching, auto_merge_in_flight)
826            .await
827    {
828        tracing::warn!(err = %e, "auto-unblock failed");
829    }
830
831    phases.push(("auto_unblock", at.elapsed().as_millis()));
832
833    engine::log_phase_timings("sync", repo, &phases);
834    Ok(())
835}
836
837/**
838 * Agent health is the same whichever project asks, so it runs once per sync pass rather than
839 * once per project. Called after every project's `sync_tick`
840 **/
841pub(crate) async fn sync_shared_tail(router: &Arc<RwLock<Router>>, store: Option<&Arc<TaskStore>>) {
842    let Some(store) = store else {
843        return;
844    };
845    if !store.is_leader() {
846        return;
847    }
848
849    // Pre-emptive health check: refresh degraded-agent flags from the rate_limits table.
850    // Clone what is needed out of the router first, so the write lock is not starved for the
851    // duration of the DB query
852    let (available_agents, config) = {
853        let r = router.read().await;
854        (r.available_agents.clone(), r.config.clone())
855    };
856    let model_checker = |agent: &str| -> bool {
857        for comp in &["simple", "medium", "complex", "review"] {
858            if config.has_available_model_for_complexity(agent, comp) {
859                return true;
860            }
861        }
862        false
863    };
864    refresh_degraded_agents(
865        store,
866        &available_agents,
867        &model_checker,
868        router_config::health_check_window_hours(),
869        router_config::degraded_rate_limit_threshold(),
870    )
871    .await;
872
873    emit_degraded_agents_if_needed(&available_agents, &config, Some(store)).await;
874}
875
876/// Per-agent degradation detail collected during the alerting check.
877struct DegradedAgentDetail {
878    /// Agent name (e.g. "claude", "codex").
879    agent: String,
880    /// Reason the agent is degraded: the stored cooldown reason when the agent
881    /// itself is in cooldown, or `"no_available_model"` when all model pools
882    /// are individually cooled.
883    reason: String,
884    /// Models that are individually in cooldown for this agent, deduped across
885    /// all complexity tiers.
886    cooled_models: Vec<String>,
887}
888
889/// Per-agent pool health used for stale model pool detection.
890struct AgentPoolHealth {
891    agent: String,
892    cooled_models: Vec<String>,
893    persistent_failed_models: Vec<String>,
894    total_configured_models: usize,
895}
896
897/// Inspect router & cooldown state and emit metrics every tick.
898///
899/// - `metrics:orch.agents_degraded.count` is written on every call with the
900///   current number of degraded agents (0 when healthy).
901/// - When `count >= 3` a WARN log is emitted with full dimensions (agent
902///   names, cooled models, cooldown reasons) and a dedicated alert metric
903///   `metrics:orch.agents_degraded.alert` is set to `"1"`. The alert is
904///   cleared to `"0"` when the count drops below the threshold.
905pub(crate) async fn emit_degraded_agents_if_needed(
906    available_agents: &[String],
907    config: &RouterConfig,
908    store: Option<&Arc<TaskStore>>,
909) {
910    // Edge-triggered: only log when the affected-agents set changes, so a
911    // persistent condition doesn't flood the log every sync tick.
912    const STALE_AGENTS_KV: &str = "metrics:orch.model_pool_stale_persistent.agents";
913
914    // Complexity tiers to check for configured models.
915    const COMPLEXITIES: &[&str] = &["simple", "medium", "complex", "review"];
916    const HEAVILY_COOLED_RATIO_THRESHOLD: f64 = 0.5;
917
918    let mut details: Vec<DegradedAgentDetail> = Vec::new();
919    let mut pool_health: Vec<AgentPoolHealth> = Vec::new();
920
921    for agent in available_agents {
922        let agent_in_cd = is_agent_in_cooldown(agent);
923
924        // Collect individually cooled models across all complexity tiers (deduped).
925        let mut cooled_models: Vec<String> = Vec::new();
926        let mut persistent_failed_models: Vec<String> = Vec::new();
927        let mut seen_models = HashSet::new();
928        for comp in COMPLEXITIES {
929            if let Some(pool) = config.model_pool_for_complexity(agent, comp) {
930                for model in pool {
931                    if seen_models.insert(model.clone()) && is_model_in_cooldown(agent, &model) {
932                        let key = format!("{agent}:{model}");
933                        if matches!(
934                            cooldown_reason(&key).as_deref(),
935                            Some("persistent_model_error" | "model_not_found")
936                        ) {
937                            persistent_failed_models.push(model.clone());
938                        }
939                        cooled_models.push(model);
940                    }
941                }
942            }
943        }
944        let total_configured_models = seen_models.len();
945        pool_health.push(AgentPoolHealth {
946            agent: agent.clone(),
947            cooled_models: cooled_models.clone(),
948            persistent_failed_models: persistent_failed_models.clone(),
949            total_configured_models,
950        });
951
952        // An agent is degraded if it is in agent-level cooldown OR has no
953        // available (non-cooled) model across any complexity tier.
954        let has_model = COMPLEXITIES
955            .iter()
956            .any(|comp| config.has_available_model_for_complexity(agent, comp));
957
958        if agent_in_cd || !has_model {
959            let reason = if agent_in_cd {
960                cooldown_reason(agent).unwrap_or_else(|| "agent_cooldown".to_string())
961            } else {
962                "no_available_model".to_string()
963            };
964            details.push(DegradedAgentDetail {
965                agent: agent.clone(),
966                reason,
967                cooled_models,
968            });
969        }
970    }
971
972    let count = details.len();
973
974    // Always persist the count metric so operators can scrape it every tick,
975    // including when the count is 0.
976    if let Err(e) = try_kv_set_prefer_store(
977        store,
978        "metrics:orch.agents_degraded.count",
979        &count.to_string(),
980    )
981    .await
982    {
983        tracing::warn!(err = %e, "failed to persist degraded agents count metric");
984    }
985
986    if count >= 3 {
987        // Build structured dimension strings for the log.
988        let degraded_agents: Vec<&str> = details.iter().map(|d| d.agent.as_str()).collect();
989        let cooled_models_dim: Vec<String> = details
990            .iter()
991            .filter(|d| !d.cooled_models.is_empty())
992            .map(|d| format!("{}:[{}]", d.agent, d.cooled_models.join(",")))
993            .collect();
994        let reasons_dim: Vec<String> = details
995            .iter()
996            .map(|d| format!("{}={}", d.agent, d.reason))
997            .collect();
998
999        tracing::warn!(
1000            degraded_count = count,
1001            degraded_agents = ?degraded_agents,
1002            cooled_models = %cooled_models_dim.join("; "),
1003            cooldown_reasons = %reasons_dim.join("; "),
1004            "multi-agent degradation detected"
1005        );
1006
1007        // Dedicated alert metric: "1" while the threshold is exceeded.
1008        if let Err(e) =
1009            try_kv_set_prefer_store(store, "metrics:orch.agents_degraded.alert", "1").await
1010        {
1011            tracing::warn!(err = %e, "failed to persist degraded agents alert metric");
1012        }
1013    } else if let Err(e) =
1014        try_kv_set_prefer_store(store, "metrics:orch.agents_degraded.alert", "0").await
1015    {
1016        // Clear the alert metric when healthy.
1017        tracing::warn!(err = %e, "failed to clear degraded agents alert metric");
1018    }
1019
1020    // Additional operator signal for dead/stale model pools:
1021    // alert when any agent has at least 50% of configured models cooled and at
1022    // least one persistent model failure marker in cooldown reason.
1023    let heavily_cooled_agents: Vec<String> = pool_health
1024        .iter()
1025        .filter_map(|d| {
1026            if d.total_configured_models == 0 || d.persistent_failed_models.is_empty() {
1027                return None;
1028            }
1029            #[expect(
1030                clippy::cast_precision_loss,
1031                reason = "model counts are far below 2^52"
1032            )]
1033            let ratio = d.cooled_models.len() as f64 / d.total_configured_models as f64;
1034            (ratio >= HEAVILY_COOLED_RATIO_THRESHOLD).then(|| {
1035                format!(
1036                    "{}:{}/{}:{}",
1037                    d.agent,
1038                    d.cooled_models.len(),
1039                    d.total_configured_models,
1040                    d.persistent_failed_models.join(",")
1041                )
1042            })
1043        })
1044        .collect();
1045
1046    let current_dim = heavily_cooled_agents.join(",");
1047    let prev_dim = kv_get_prefer_store(store, STALE_AGENTS_KV)
1048        .await
1049        .unwrap_or_default();
1050
1051    if heavily_cooled_agents.is_empty() {
1052        if !prev_dim.is_empty() {
1053            tracing::info!("agent model pool stale condition cleared");
1054        }
1055        if let Err(e) = try_kv_set_prefer_store(store, STALE_AGENTS_KV, "").await {
1056            tracing::warn!(err = %e, "failed to clear stale model pool agents state");
1057        }
1058        if let Err(e) =
1059            try_kv_set_prefer_store(store, "metrics:orch.model_pool_stale_persistent.alert", "0")
1060                .await
1061        {
1062            tracing::warn!(err = %e, "failed to clear stale model pool alert metric");
1063        }
1064    } else {
1065        if current_dim != prev_dim {
1066            tracing::warn!(
1067                affected_agents = ?heavily_cooled_agents,
1068                "agent model pool appears stale: persistent model failures in heavily cooled pool"
1069            );
1070        }
1071        if let Err(e) = try_kv_set_prefer_store(store, STALE_AGENTS_KV, &current_dim).await {
1072            tracing::warn!(err = %e, "failed to persist stale model pool agents state");
1073        }
1074        if let Err(e) =
1075            try_kv_set_prefer_store(store, "metrics:orch.model_pool_stale_persistent.alert", "1")
1076                .await
1077        {
1078            tracing::warn!(err = %e, "failed to persist stale model pool alert metric");
1079        }
1080    }
1081}
1082
1083/// Ingest all active external tasks into the unified SQLite store.
1084///
1085/// Upserts each task so the store stays in sync with the backend.
1086/// Fetches all open issues (including unlabeled ones) so newly created
1087/// issues appear in the store immediately, not only after they get a
1088/// `status:*` label.  This is best-effort — individual task failures
1089/// are logged and skipped.
1090pub(crate) async fn ingest_external_tasks(
1091    backend: &Arc<dyn ExternalBackend>,
1092    repo: &str,
1093    store: &Arc<TaskStore>,
1094) -> anyhow::Result<()> {
1095    #[derive(Clone)]
1096    struct DuplicateTarget {
1097        id: String,
1098        status_label: String,
1099    }
1100
1101    let mut existing_by_title: HashMap<String, DuplicateTarget> = HashMap::new();
1102    let mut accepted_by_title: HashMap<String, DuplicateTarget> = HashMap::new();
1103
1104    let cutoff = (chrono::Utc::now() - chrono::Duration::hours(24))
1105        .format("%Y-%m-%dT%H:%M:%SZ")
1106        .to_string();
1107    match store.list_for_doctor(repo, &cutoff).await {
1108        Ok(recent) => {
1109            let mut insert_target = |task: &Task| {
1110                if task.origin == "internal" {
1111                    return;
1112                }
1113                let Some(ext_id) = task.external_id.as_ref() else {
1114                    return;
1115                };
1116                let status_label = task
1117                    .labels
1118                    .iter()
1119                    .find(|l| l.starts_with("status:"))
1120                    .cloned()
1121                    .unwrap_or_default();
1122                existing_by_title
1123                    .entry(task.title.clone())
1124                    .or_insert(DuplicateTarget {
1125                        id: ext_id.clone(),
1126                        status_label,
1127                    });
1128            };
1129
1130            // Prefer active tasks over recently done ones when selecting a canonical issue.
1131            for task in recent.iter().filter(|t| t.status != TaskStatus::Done) {
1132                insert_target(task);
1133            }
1134            for task in recent.iter().filter(|t| t.status == TaskStatus::Done) {
1135                insert_target(task);
1136            }
1137        }
1138        Err(e) => {
1139            tracing::warn!(repo, err = %e, "ingest: failed to load recent tasks for dedup");
1140        }
1141    }
1142
1143    // Fetch every open issue, with no `since` filter. The GitHub backend overrides
1144    // list_active_open_issues() to use one list_all_open_issues() request.
1145    //
1146    // A `since` cursor keys on updated_at, so an open issue with no task was skipped
1147    // forever once the cursor passed its updated_at, and the cursor had to be reset,
1148    // sentinelled and periodically ignored to recover (#3545, #3787, #3792). An
1149    // unfiltered listing has no such state and is cheaper too: its URL repeats, so
1150    // `get_all_pages` sends it conditionally and GitHub answers 304 while nothing
1151    // changed. A 304 does not count against the REST quota, a `since` fetch does.
1152    let all_tasks: Vec<(ExternalTask, Option<Status>)> =
1153        match backend.list_active_open_issues().await {
1154            Ok(tasks) => tasks,
1155            Err(e) => {
1156                tracing::warn!(
1157                    repo,
1158                    err = %e,
1159                    "ingest: failed to list open issues — no new issue is ingested this cycle"
1160                );
1161                return Ok(());
1162            }
1163        };
1164
1165    // Upsert into the store, collecting store IDs for batch status check
1166    // Also acknowledge newly detected issues (eyes reaction).
1167    let mut id_status_pairs: Vec<(i64, Status)> = Vec::new();
1168    // Collect (store_id, node_id) for newly ingested tasks so we can batch-fetch
1169    // estimate values from GitHub Projects after the loop.
1170    let mut new_task_node_ids: Vec<(i64, String)> = Vec::new();
1171    // Pre-load existing external IDs for this repo to avoid N+1 queries
1172    // (each get_by_external_id call is an individual SQL query). If the
1173    // lookup fails, fall back to an empty set so we conservatively treat
1174    // tasks as new (they will be upserted below).
1175    let existing_ext_ids: HashSet<String> = match store.existing_external_ids(repo).await {
1176        Ok(s) => s,
1177        Err(e) => {
1178            tracing::warn!(repo = repo, err = %e, "ingest: failed to load existing external ids — proceeding");
1179            HashSet::new()
1180        }
1181    };
1182    for (task, status) in &all_tasks {
1183        // Check if this task already exists in the store before upserting.
1184        // Use the pre-loaded HashSet to avoid issuing N individual queries.
1185        let is_new = !existing_ext_ids.contains(&task.id.0);
1186
1187        if is_new {
1188            let duplicate_target = existing_by_title
1189                .get(&task.title)
1190                .or_else(|| accepted_by_title.get(&task.title));
1191            if let Some(target) = duplicate_target
1192                && target.id != task.id.0
1193            {
1194                let label = target.status_label.as_str();
1195                let should_dedupe =
1196                    match backend.has_open_issue_with_title(&task.title, label).await {
1197                        Ok(true) => true,
1198                        Ok(false) => false,
1199                        Err(e) => {
1200                            tracing::warn!(
1201                                task_id = task.id.0,
1202                                err = %e,
1203                                "ingest: dedup check failed — defaulting to keep issue"
1204                            );
1205                            false
1206                        }
1207                    };
1208
1209                if should_dedupe {
1210                    let comment = format!(
1211                        "Duplicate of #{id} — closing to avoid duplicate work.{footer}",
1212                        id = target.id,
1213                        footer = engine::orch_footer()
1214                    );
1215                    if let Err(e) = backend.post_comment(&task.id, &comment).await {
1216                        tracing::warn!(
1217                            task_id = task.id.0,
1218                            err = %e,
1219                            "ingest: failed to comment on duplicate issue"
1220                        );
1221                    }
1222                    match backend.update_status(&task.id, Status::Done).await {
1223                        Ok(()) => {
1224                            tracing::info!(
1225                                task_id = task.id.0,
1226                                duplicate_of = target.id,
1227                                "ingest: closed duplicate issue"
1228                            );
1229                            continue;
1230                        }
1231                        Err(e) => {
1232                            tracing::warn!(
1233                                task_id = task.id.0,
1234                                err = %e,
1235                                "ingest: failed to close duplicate issue — falling through to ingest normally"
1236                            );
1237                        }
1238                    }
1239                }
1240            }
1241        }
1242
1243        match store.upsert_external(&task.upsert_row(repo)).await {
1244            Ok(store_id) => {
1245                if let Ok(number) = task.id.0.parse::<i64>()
1246                    && let Err(err) = dependencies::sync_issue_dependencies(
1247                        backend.as_ref(),
1248                        store,
1249                        store_id,
1250                        repo,
1251                        Some(number),
1252                        &task.body,
1253                    )
1254                    .await
1255                {
1256                    tracing::warn!(
1257                        task_id = task.id.0,
1258                        err = %err,
1259                        "ingest: dependency sync failed"
1260                    );
1261                }
1262                if let Some(s) = status {
1263                    id_status_pairs.push((store_id, *s));
1264                }
1265                // Acknowledge newly detected issues with an eyes reaction.
1266                if is_new {
1267                    let status_label = task
1268                        .labels
1269                        .iter()
1270                        .find(|l| l.starts_with("status:"))
1271                        .cloned()
1272                        .unwrap_or_default();
1273                    accepted_by_title
1274                        .entry(task.title.clone())
1275                        .or_insert(DuplicateTarget {
1276                            id: task.id.0.clone(),
1277                            status_label,
1278                        });
1279                    if let Err(e) = backend.acknowledge_issue(&task.id).await {
1280                        tracing::debug!(
1281                            task_id = task.id.0,
1282                            err = %e,
1283                            "ingest: acknowledgment failed"
1284                        );
1285                    }
1286                    // Sync to project board only for newly ingested tasks.
1287                    // Collect the returned node_id so we can batch-fetch estimates.
1288                    let task_status = status.unwrap_or(Status::New);
1289                    match backend.sync_to_project(&task.id, task_status).await {
1290                        Ok(Some(node_id)) => {
1291                            new_task_node_ids.push((store_id, node_id));
1292                        }
1293                        Ok(None) => {
1294                            // Project sync not configured or failed — no node_id to collect.
1295                        }
1296                        Err(e) => {
1297                            tracing::debug!(
1298                                task_id = task.id.0,
1299                                err = %e,
1300                                "ingest: project board sync failed"
1301                            );
1302                        }
1303                    }
1304                }
1305            }
1306            Err(e) => {
1307                tracing::debug!(task_id = task.id.0, ?e, "ingest: upsert failed");
1308            }
1309        }
1310    }
1311
1312    // Batch-fetch all upserted tasks in a single query, then sync status for NEW tasks.
1313    // Only sync status from backend → store for NEW tasks (first ingest).
1314    // Once a task exists in the store, its status is authoritative —
1315    // re-ingestion must not overwrite store-first status changes
1316    // (e.g., store has Routed but GitHub still shows New labels).
1317    if !id_status_pairs.is_empty() {
1318        let all_ids: Vec<i64> = id_status_pairs.iter().map(|(id, _)| *id).collect();
1319        let existing_map = match store.get_batch(&all_ids).await {
1320            Ok(map) => map,
1321            Err(e) => {
1322                tracing::warn!(err = %e, task_count = all_ids.len(), "ingest: get_batch failed — skipping initial status sync for newly ingested tasks this tick");
1323                return Ok(());
1324            }
1325        };
1326        for (store_id, status) in id_status_pairs {
1327            if let Some(existing) = existing_map.get(&store_id)
1328                && existing.status == TaskStatus::New
1329            {
1330                let db_status = status_to_task_status(status);
1331                if db_status != TaskStatus::New
1332                    && let Err(e) = store.update_status(store_id, db_status).await
1333                {
1334                    tracing::debug!(?e, "ingest: status sync failed");
1335                }
1336            }
1337        }
1338    }
1339
1340    // Batch-fetch estimate values from GitHub Projects for newly ingested tasks.
1341    // For each task where `tasks.estimate == 0`, populate it from the project board.
1342    if !new_task_node_ids.is_empty() {
1343        let node_ids: Vec<String> = new_task_node_ids.iter().map(|(_, n)| n.clone()).collect();
1344        match backend.get_project_item_estimates(&node_ids).await {
1345            Ok(estimates) => {
1346                for (store_id, node_id) in new_task_node_ids {
1347                    if let Some(&estimate) = estimates.get(&node_id)
1348                        && estimate > 0
1349                        && let Err(e) = store.set_estimate_if_zero(store_id, estimate).await
1350                    {
1351                        tracing::debug!(
1352                            store_id,
1353                            estimate,
1354                            err = %e,
1355                            "ingest: failed to set estimate from project"
1356                        );
1357                    }
1358                }
1359            }
1360            Err(e) => {
1361                tracing::debug!(
1362                    err = %e,
1363                    "ingest: project estimate fetch failed — skipping estimate sync this tick"
1364                );
1365            }
1366        }
1367    }
1368
1369    Ok(())
1370}
1371
1372#[cfg(test)]
1373mod tests;
1374
1375#[cfg(test)]
1376mod unblock_tests;
1377
1378#[cfg(test)]
1379mod comments_tests;