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