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::outbox;
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::agents::patterns;
27use crate::engine::ci::bootstrap;
28use crate::engine::git::cleanup::ReviewTaskSnapshot;
29use crate::engine::git::cleanup::{check_merged_prs, cleanup_done_worktrees, prune_old_run_output};
30use crate::engine::review::poll::review_open_prs;
31use crate::engine::router::Router;
32use crate::engine::router::RouterConfig;
33use crate::engine::router::config as router_config;
34use crate::engine::tasks;
35use crate::engine::tasks::dependencies;
36use crate::engine::tasks::{TaskManager, status_to_task_status};
37use crate::github::http::GhHttp;
38use crate::store;
39use crate::store::Task;
40use crate::store::TaskRun;
41use crate::store::TaskStatus;
42use crate::store::TaskStore;
43use crate::sys::tmux::TmuxManager;
44use comments::{
45    fetch_comments_since, filter_mentions_by_since, read_mention_cursor, scan_comments,
46};
47use dashmap::{DashMap, DashSet};
48use std::collections::HashMap;
49use std::collections::HashSet;
50use std::sync::Arc;
51use std::time::Instant;
52use tokio::sync::RwLock;
53use unblock::{REBROADCAST_BLOCK_REASON, auto_unblock_blocked_tasks};
54pub(crate) use unblock::{
55    auto_recover_rebroadcast_blocked_tasks_global, auto_unblock_ci_failure_blocked_tasks_global,
56};
57
58/// Read a KV value from the store.
59///
60/// Returns `None` if the store is unavailable, the key doesn't exist, OR if
61/// the store query fails. Use [`try_kv_get_prefer_store`] if you need to
62/// distinguish between "key not found" and actual errors.
63async fn kv_get_prefer_store(store: Option<&Arc<TaskStore>>, key: &str) -> Option<String> {
64    match try_kv_get_prefer_store(store, key).await {
65        Ok(opt) => opt,
66        Err(e) => {
67            tracing::error!(key, err = %e, "kv_get failed");
68            None
69        }
70    }
71}
72
73/// Try to read a KV value from the store, returning errors instead of
74/// silently discarding them.
75///
76/// Returns `Ok(None)` if the store is unavailable or the key doesn't exist.
77/// Returns `Err` if the store query fails.
78async fn try_kv_get_prefer_store(
79    store: Option<&Arc<TaskStore>>,
80    key: &str,
81) -> anyhow::Result<Option<String>> {
82    if let Some(s) = store {
83        Ok(s.kv_get(key).await?)
84    } else {
85        Ok(None)
86    }
87}
88
89/// Write a KV value to the store.
90///
91/// Logs warnings on failure but provides no way for callers to know if the
92/// write succeeded. Use [`try_kv_set_prefer_store`] if you need to handle
93/// errors or guarantee persistence (e.g., for circuit breaker state).
94async fn kv_set_prefer_store(store: Option<&Arc<TaskStore>>, key: &str, value: &str) {
95    if let Err(e) = try_kv_set_prefer_store(store, key, value).await {
96        tracing::error!(key, err = %e, "kv_set failed");
97    }
98}
99
100/// Try to write a KV value to the store, returning errors instead of
101/// silently logging them.
102///
103/// Returns `Ok(())` if the store is unavailable (best-effort) or if the
104/// write succeeds. Returns `Err` if the store query fails.
105async fn try_kv_set_prefer_store(
106    store: Option<&Arc<TaskStore>>,
107    key: &str,
108    value: &str,
109) -> anyhow::Result<()> {
110    if let Some(s) = store {
111        s.kv_set(key, value).await?;
112    }
113    Ok(())
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_since = read_mention_cursor(Some(store), repo).await;
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            // Another node runs it, so the local sessions say nothing about it
747            if store.runs_elsewhere(stored) {
748                continue;
749            }
750
751            // Skip tasks currently being processed by the main tick (dispatch + agent flow).
752            let dispatch_key = format!("{repo}/{task_id}");
753            {
754                if dispatching.contains_key(&dispatch_key) {
755                    tracing::debug!(
756                        task_id = %task_id,
757                        "task locked by dispatch flow, skipping stale check"
758                    );
759                    continue;
760                }
761            }
762
763            // Skip tasks that just transitioned to InProgress — allow time for the
764            // agent to start its tmux session before treating it as stale.
765            match chrono::DateTime::parse_from_rfc3339(&external.updated_at) {
766                Ok(updated_at) => {
767                    let age = chrono::Utc::now() - updated_at.with_timezone(&chrono::Utc);
768                    if age.num_minutes() < MIN_STALE_MINUTES {
769                        tracing::debug!(
770                            task_id = %task_id,
771                            age_seconds = age.num_seconds(),
772                            "InProgress task is too young to be considered stale, skipping"
773                        );
774                        continue;
775                    }
776                }
777                Err(e) => {
778                    tracing::warn!(
779                        task_id = %task_id,
780                        ts = %external.updated_at,
781                        err = %e,
782                        "invalid updated_at timestamp — treating task as potentially stale"
783                    );
784                }
785            }
786
787            let agent_session = tmux.session_name(repo, task_id);
788            if live_sessions.contains(&agent_session) {
789                // Agent is still alive — skip.
790                continue;
791            }
792
793            // No agent session exists. The agent is dead regardless of
794            // session tracking — hard restart, crash, or flag not persisted.
795            // Reset to Routed so the dispatcher can re-spawn it.
796            {
797                tracing::warn!(
798                    task_id = %task_id,
799                    session = %agent_session,
800                    "InProgress task has no active agent session — resetting to Routed"
801                );
802                match task_manager
803                    .update_task_status_if(&external.id, Status::Routed, Status::InProgress)
804                    .await
805                {
806                    Err(e) => {
807                        tracing::error!(task_id = %task_id, err = %e, "failed to reset stale InProgress task — task may be stuck in InProgress indefinitely");
808                    }
809                    Ok(false) => {
810                        tracing::debug!(
811                            task_id = %task_id,
812                            "stale InProgress reset skipped — task already transitioned (concurrent Done/Blocked/NeedsReview)"
813                        );
814                    }
815                    Ok(true) => {
816                        // Successfully reset to Routed
817                    }
818                }
819            }
820        }
821    }
822
823    phases.push(("stale_in_progress", at.elapsed().as_millis()));
824    at = Instant::now();
825    // 5c. Auto-unblock tasks with recoverable failures.
826    if let Err(e) =
827        auto_unblock_blocked_tasks(repo, task_manager, store, dispatching, auto_merge_in_flight)
828            .await
829    {
830        tracing::warn!(err = %e, "auto-unblock failed");
831    }
832
833    phases.push(("auto_unblock", at.elapsed().as_millis()));
834
835    engine::log_phase_timings("sync", repo, &phases);
836    Ok(())
837}
838
839/**
840 * Sends the GitHub writes a stopped leader left pending, before any project decides anything new.
841 * The rows span every project, so this runs once per sync pass and never next to an `auto_merge_pr`
842 **/
843pub(crate) async fn sync_shared_head(store: Option<&Arc<TaskStore>>) {
844    let Some(store) = store else {
845        return;
846    };
847    if let Err(e) = outbox::retry_pending(store, &outbox::GitHub).await {
848        tracing::warn!(err = %e, "outbox: pending GitHub writes not sent");
849    }
850}
851
852/**
853 * Agent health is the same whichever project asks, so it runs once per sync pass rather than
854 * once per project. Called after every project's `sync_tick`
855 **/
856pub(crate) async fn sync_shared_tail(router: &Arc<RwLock<Router>>, store: Option<&Arc<TaskStore>>) {
857    let Some(store) = store else {
858        return;
859    };
860    if !store.is_leader() {
861        return;
862    }
863
864    // Pre-emptive health check: refresh degraded-agent flags from the rate_limits table.
865    // Clone what is needed out of the router first, so the write lock is not starved for the
866    // duration of the DB query
867    let (available_agents, config) = {
868        let r = router.read().await;
869        (r.available_agents.clone(), r.config.clone())
870    };
871    let model_checker = |agent: &str| -> bool {
872        for comp in &["simple", "medium", "complex", "review"] {
873            if config.has_available_model_for_complexity(agent, comp) {
874                return true;
875            }
876        }
877        false
878    };
879    refresh_degraded_agents(
880        store,
881        &available_agents,
882        &model_checker,
883        router_config::health_check_window_hours(),
884        router_config::degraded_rate_limit_threshold(),
885    )
886    .await;
887
888    emit_degraded_agents_if_needed(&available_agents, &config, Some(store)).await;
889}
890
891/// Per-agent degradation detail collected during the alerting check.
892struct DegradedAgentDetail {
893    /// Agent name (e.g. "claude", "codex").
894    agent: String,
895    /// Reason the agent is degraded: the stored cooldown reason when the agent
896    /// itself is in cooldown, or `"no_available_model"` when all model pools
897    /// are individually cooled.
898    reason: String,
899    /// Models that are individually in cooldown for this agent, deduped across
900    /// all complexity tiers.
901    cooled_models: Vec<String>,
902}
903
904/// Per-agent pool health used for stale model pool detection.
905struct AgentPoolHealth {
906    agent: String,
907    cooled_models: Vec<String>,
908    persistent_failed_models: Vec<String>,
909    total_configured_models: usize,
910}
911
912/// Inspect router & cooldown state and emit metrics every tick.
913///
914/// - `metrics:orch.agents_degraded.count` is written on every call with the
915///   current number of degraded agents (0 when healthy).
916/// - When `count >= 3` a WARN log is emitted with full dimensions (agent
917///   names, cooled models, cooldown reasons) and a dedicated alert metric
918///   `metrics:orch.agents_degraded.alert` is set to `"1"`. The alert is
919///   cleared to `"0"` when the count drops below the threshold.
920pub(crate) async fn emit_degraded_agents_if_needed(
921    available_agents: &[String],
922    config: &RouterConfig,
923    store: Option<&Arc<TaskStore>>,
924) {
925    // Edge-triggered: only log when the affected-agents set changes, so a
926    // persistent condition doesn't flood the log every sync tick.
927    const STALE_AGENTS_KV: &str = "metrics:orch.model_pool_stale_persistent.agents";
928
929    // Complexity tiers to check for configured models.
930    const COMPLEXITIES: &[&str] = &["simple", "medium", "complex", "review"];
931    const HEAVILY_COOLED_RATIO_THRESHOLD: f64 = 0.5;
932
933    let mut details: Vec<DegradedAgentDetail> = Vec::new();
934    let mut pool_health: Vec<AgentPoolHealth> = Vec::new();
935
936    for agent in available_agents {
937        let agent_in_cd = is_agent_in_cooldown(agent);
938
939        // Collect individually cooled models across all complexity tiers (deduped).
940        let mut cooled_models: Vec<String> = Vec::new();
941        let mut persistent_failed_models: Vec<String> = Vec::new();
942        let mut seen_models = HashSet::new();
943        for comp in COMPLEXITIES {
944            if let Some(pool) = config.model_pool_for_complexity(agent, comp) {
945                for model in pool {
946                    if seen_models.insert(model.clone()) && is_model_in_cooldown(agent, &model) {
947                        let key = format!("{agent}:{model}");
948                        if matches!(
949                            cooldown_reason(&key).as_deref(),
950                            Some("persistent_model_error" | "model_not_found")
951                        ) {
952                            persistent_failed_models.push(model.clone());
953                        }
954                        cooled_models.push(model);
955                    }
956                }
957            }
958        }
959        let total_configured_models = seen_models.len();
960        pool_health.push(AgentPoolHealth {
961            agent: agent.clone(),
962            cooled_models: cooled_models.clone(),
963            persistent_failed_models: persistent_failed_models.clone(),
964            total_configured_models,
965        });
966
967        // An agent is degraded if it is in agent-level cooldown OR has no
968        // available (non-cooled) model across any complexity tier.
969        let has_model = COMPLEXITIES
970            .iter()
971            .any(|comp| config.has_available_model_for_complexity(agent, comp));
972
973        if agent_in_cd || !has_model {
974            let reason = if agent_in_cd {
975                cooldown_reason(agent).unwrap_or_else(|| "agent_cooldown".to_string())
976            } else {
977                "no_available_model".to_string()
978            };
979            details.push(DegradedAgentDetail {
980                agent: agent.clone(),
981                reason,
982                cooled_models,
983            });
984        }
985    }
986
987    let count = details.len();
988
989    // Always persist the count metric so operators can scrape it every tick,
990    // including when the count is 0.
991    if let Err(e) = try_kv_set_prefer_store(
992        store,
993        "metrics:orch.agents_degraded.count",
994        &count.to_string(),
995    )
996    .await
997    {
998        tracing::warn!(err = %e, "failed to persist degraded agents count metric");
999    }
1000
1001    if count >= 3 {
1002        // Build structured dimension strings for the log.
1003        let degraded_agents: Vec<&str> = details.iter().map(|d| d.agent.as_str()).collect();
1004        let cooled_models_dim: Vec<String> = details
1005            .iter()
1006            .filter(|d| !d.cooled_models.is_empty())
1007            .map(|d| format!("{}:[{}]", d.agent, d.cooled_models.join(",")))
1008            .collect();
1009        let reasons_dim: Vec<String> = details
1010            .iter()
1011            .map(|d| format!("{}={}", d.agent, d.reason))
1012            .collect();
1013
1014        tracing::warn!(
1015            degraded_count = count,
1016            degraded_agents = ?degraded_agents,
1017            cooled_models = %cooled_models_dim.join("; "),
1018            cooldown_reasons = %reasons_dim.join("; "),
1019            "multi-agent degradation detected"
1020        );
1021
1022        // Dedicated alert metric: "1" while the threshold is exceeded.
1023        if let Err(e) =
1024            try_kv_set_prefer_store(store, "metrics:orch.agents_degraded.alert", "1").await
1025        {
1026            tracing::warn!(err = %e, "failed to persist degraded agents alert metric");
1027        }
1028    } else if let Err(e) =
1029        try_kv_set_prefer_store(store, "metrics:orch.agents_degraded.alert", "0").await
1030    {
1031        // Clear the alert metric when healthy.
1032        tracing::warn!(err = %e, "failed to clear degraded agents alert metric");
1033    }
1034
1035    // Additional operator signal for dead/stale model pools:
1036    // alert when any agent has at least 50% of configured models cooled and at
1037    // least one persistent model failure marker in cooldown reason.
1038    let heavily_cooled_agents: Vec<String> = pool_health
1039        .iter()
1040        .filter_map(|d| {
1041            if d.total_configured_models == 0 || d.persistent_failed_models.is_empty() {
1042                return None;
1043            }
1044            #[expect(
1045                clippy::cast_precision_loss,
1046                reason = "model counts are far below 2^52"
1047            )]
1048            let ratio = d.cooled_models.len() as f64 / d.total_configured_models as f64;
1049            (ratio >= HEAVILY_COOLED_RATIO_THRESHOLD).then(|| {
1050                format!(
1051                    "{}:{}/{}:{}",
1052                    d.agent,
1053                    d.cooled_models.len(),
1054                    d.total_configured_models,
1055                    d.persistent_failed_models.join(",")
1056                )
1057            })
1058        })
1059        .collect();
1060
1061    let current_dim = heavily_cooled_agents.join(",");
1062    let prev_dim = kv_get_prefer_store(store, STALE_AGENTS_KV)
1063        .await
1064        .unwrap_or_default();
1065
1066    if heavily_cooled_agents.is_empty() {
1067        if !prev_dim.is_empty() {
1068            tracing::info!("agent model pool stale condition cleared");
1069        }
1070        if let Err(e) = try_kv_set_prefer_store(store, STALE_AGENTS_KV, "").await {
1071            tracing::warn!(err = %e, "failed to clear stale model pool agents state");
1072        }
1073        if let Err(e) =
1074            try_kv_set_prefer_store(store, "metrics:orch.model_pool_stale_persistent.alert", "0")
1075                .await
1076        {
1077            tracing::warn!(err = %e, "failed to clear stale model pool alert metric");
1078        }
1079    } else {
1080        if current_dim != prev_dim {
1081            tracing::warn!(
1082                affected_agents = ?heavily_cooled_agents,
1083                "agent model pool appears stale: persistent model failures in heavily cooled pool"
1084            );
1085        }
1086        if let Err(e) = try_kv_set_prefer_store(store, STALE_AGENTS_KV, &current_dim).await {
1087            tracing::warn!(err = %e, "failed to persist stale model pool agents state");
1088        }
1089        if let Err(e) =
1090            try_kv_set_prefer_store(store, "metrics:orch.model_pool_stale_persistent.alert", "1")
1091                .await
1092        {
1093            tracing::warn!(err = %e, "failed to persist stale model pool alert metric");
1094        }
1095    }
1096}
1097
1098/// Ingest all active external tasks into the unified SQLite store.
1099///
1100/// Upserts each task so the store stays in sync with the backend.
1101/// Fetches all open issues (including unlabeled ones) so newly created
1102/// issues appear in the store immediately, not only after they get a
1103/// `status:*` label.  This is best-effort — individual task failures
1104/// are logged and skipped.
1105pub(crate) async fn ingest_external_tasks(
1106    backend: &Arc<dyn ExternalBackend>,
1107    repo: &str,
1108    store: &Arc<TaskStore>,
1109) -> anyhow::Result<()> {
1110    #[derive(Clone)]
1111    struct DuplicateTarget {
1112        id: String,
1113        status_label: String,
1114    }
1115
1116    let mut existing_by_title: HashMap<String, DuplicateTarget> = HashMap::new();
1117    let mut accepted_by_title: HashMap<String, DuplicateTarget> = HashMap::new();
1118
1119    let cutoff = (chrono::Utc::now() - chrono::Duration::hours(24))
1120        .format("%Y-%m-%dT%H:%M:%SZ")
1121        .to_string();
1122    match store.list_for_doctor(repo, &cutoff).await {
1123        Ok(recent) => {
1124            let mut insert_target = |task: &Task| {
1125                if task.origin == "internal" {
1126                    return;
1127                }
1128                let Some(ext_id) = task.external_id.as_ref() else {
1129                    return;
1130                };
1131                let status_label = task
1132                    .labels
1133                    .iter()
1134                    .find(|l| l.starts_with("status:"))
1135                    .cloned()
1136                    .unwrap_or_default();
1137                existing_by_title
1138                    .entry(task.title.clone())
1139                    .or_insert(DuplicateTarget {
1140                        id: ext_id.clone(),
1141                        status_label,
1142                    });
1143            };
1144
1145            // Prefer active tasks over recently done ones when selecting a canonical issue.
1146            for task in recent.iter().filter(|t| t.status != TaskStatus::Done) {
1147                insert_target(task);
1148            }
1149            for task in recent.iter().filter(|t| t.status == TaskStatus::Done) {
1150                insert_target(task);
1151            }
1152        }
1153        Err(e) => {
1154            tracing::warn!(repo, err = %e, "ingest: failed to load recent tasks for dedup");
1155        }
1156    }
1157
1158    // Fetch every open issue, with no `since` filter. The GitHub backend overrides
1159    // list_active_open_issues() to use one list_all_open_issues() request.
1160    //
1161    // A `since` cursor keys on updated_at, so an open issue with no task was skipped
1162    // forever once the cursor passed its updated_at, and the cursor had to be reset,
1163    // sentinelled and periodically ignored to recover (#3545, #3787, #3792). An
1164    // unfiltered listing has no such state and is cheaper too: its URL repeats, so
1165    // `get_all_pages` sends it conditionally and GitHub answers 304 while nothing
1166    // changed. A 304 does not count against the REST quota, a `since` fetch does.
1167    let all_tasks: Vec<(ExternalTask, Option<Status>)> =
1168        match backend.list_active_open_issues().await {
1169            Ok(tasks) => tasks,
1170            Err(e) => {
1171                tracing::warn!(
1172                    repo,
1173                    err = %e,
1174                    "ingest: failed to list open issues — no new issue is ingested this cycle"
1175                );
1176                return Ok(());
1177            }
1178        };
1179
1180    // Upsert into the store, collecting store IDs for batch status check
1181    // Also acknowledge newly detected issues (eyes reaction).
1182    let mut id_status_pairs: Vec<(i64, Status)> = Vec::new();
1183    // Collect (store_id, node_id) for newly ingested tasks so we can batch-fetch
1184    // estimate values from GitHub Projects after the loop.
1185    let mut new_task_node_ids: Vec<(i64, String)> = Vec::new();
1186    // Pre-load existing external IDs for this repo to avoid N+1 queries
1187    // (each get_by_external_id call is an individual SQL query). If the
1188    // lookup fails, fall back to an empty set so we conservatively treat
1189    // tasks as new (they will be upserted below).
1190    let existing_ext_ids: HashSet<String> = match store.existing_external_ids(repo).await {
1191        Ok(s) => s,
1192        Err(e) => {
1193            tracing::warn!(repo = repo, err = %e, "ingest: failed to load existing external ids — proceeding");
1194            HashSet::new()
1195        }
1196    };
1197    for (task, status) in &all_tasks {
1198        // Check if this task already exists in the store before upserting.
1199        // Use the pre-loaded HashSet to avoid issuing N individual queries.
1200        let is_new = !existing_ext_ids.contains(&task.id.0);
1201
1202        if is_new {
1203            let duplicate_target = existing_by_title
1204                .get(&task.title)
1205                .or_else(|| accepted_by_title.get(&task.title));
1206            if let Some(target) = duplicate_target
1207                && target.id != task.id.0
1208            {
1209                let label = target.status_label.as_str();
1210                let should_dedupe =
1211                    match backend.has_open_issue_with_title(&task.title, label).await {
1212                        Ok(true) => true,
1213                        Ok(false) => false,
1214                        Err(e) => {
1215                            tracing::warn!(
1216                                task_id = task.id.0,
1217                                err = %e,
1218                                "ingest: dedup check failed — defaulting to keep issue"
1219                            );
1220                            false
1221                        }
1222                    };
1223
1224                if should_dedupe {
1225                    let comment = format!(
1226                        "Duplicate of #{id} — closing to avoid duplicate work.{footer}",
1227                        id = target.id,
1228                        footer = engine::orch_footer()
1229                    );
1230                    if let Err(e) = backend.post_comment(&task.id, &comment).await {
1231                        tracing::warn!(
1232                            task_id = task.id.0,
1233                            err = %e,
1234                            "ingest: failed to comment on duplicate issue"
1235                        );
1236                    }
1237                    match backend.update_status(&task.id, Status::Done).await {
1238                        Ok(()) => {
1239                            tracing::info!(
1240                                task_id = task.id.0,
1241                                duplicate_of = target.id,
1242                                "ingest: closed duplicate issue"
1243                            );
1244                            continue;
1245                        }
1246                        Err(e) => {
1247                            tracing::warn!(
1248                                task_id = task.id.0,
1249                                err = %e,
1250                                "ingest: failed to close duplicate issue — falling through to ingest normally"
1251                            );
1252                        }
1253                    }
1254                }
1255            }
1256        }
1257
1258        match store
1259            .upsert_external(&UpsertExternal::from((task, repo)))
1260            .await
1261        {
1262            Ok(store_id) => {
1263                if let Ok(number) = task.id.0.parse::<i64>()
1264                    && let Err(err) = dependencies::sync_issue_dependencies(
1265                        backend.as_ref(),
1266                        store,
1267                        store_id,
1268                        repo,
1269                        Some(number),
1270                        &task.body,
1271                    )
1272                    .await
1273                {
1274                    tracing::warn!(
1275                        task_id = task.id.0,
1276                        err = %err,
1277                        "ingest: dependency sync failed"
1278                    );
1279                }
1280                if let Some(s) = status {
1281                    id_status_pairs.push((store_id, *s));
1282                }
1283                // Acknowledge newly detected issues with an eyes reaction.
1284                if is_new {
1285                    let status_label = task
1286                        .labels
1287                        .iter()
1288                        .find(|l| l.starts_with("status:"))
1289                        .cloned()
1290                        .unwrap_or_default();
1291                    accepted_by_title
1292                        .entry(task.title.clone())
1293                        .or_insert(DuplicateTarget {
1294                            id: task.id.0.clone(),
1295                            status_label,
1296                        });
1297                    if let Err(e) = backend.acknowledge_issue(&task.id).await {
1298                        tracing::debug!(
1299                            task_id = task.id.0,
1300                            err = %e,
1301                            "ingest: acknowledgment failed"
1302                        );
1303                    }
1304                    // Sync to project board only for newly ingested tasks.
1305                    // Collect the returned node_id so we can batch-fetch estimates.
1306                    let task_status = status.unwrap_or(Status::New);
1307                    match backend.sync_to_project(&task.id, task_status).await {
1308                        Ok(Some(node_id)) => {
1309                            new_task_node_ids.push((store_id, node_id));
1310                        }
1311                        Ok(None) => {
1312                            // Project sync not configured or failed — no node_id to collect.
1313                        }
1314                        Err(e) => {
1315                            tracing::debug!(
1316                                task_id = task.id.0,
1317                                err = %e,
1318                                "ingest: project board sync failed"
1319                            );
1320                        }
1321                    }
1322                }
1323            }
1324            Err(e) => {
1325                tracing::debug!(task_id = task.id.0, ?e, "ingest: upsert failed");
1326            }
1327        }
1328    }
1329
1330    // Batch-fetch all upserted tasks in a single query, then sync status for NEW tasks.
1331    // Only sync status from backend → store for NEW tasks (first ingest).
1332    // Once a task exists in the store, its status is authoritative —
1333    // re-ingestion must not overwrite store-first status changes
1334    // (e.g., store has Routed but GitHub still shows New labels).
1335    if !id_status_pairs.is_empty() {
1336        let all_ids: Vec<i64> = id_status_pairs.iter().map(|(id, _)| *id).collect();
1337        let existing_map = match store.get_batch(&all_ids).await {
1338            Ok(map) => map,
1339            Err(e) => {
1340                tracing::warn!(err = %e, task_count = all_ids.len(), "ingest: get_batch failed — skipping initial status sync for newly ingested tasks this tick");
1341                return Ok(());
1342            }
1343        };
1344        for (store_id, status) in id_status_pairs {
1345            if let Some(existing) = existing_map.get(&store_id)
1346                && existing.status == TaskStatus::New
1347            {
1348                let db_status = status_to_task_status(status);
1349                if db_status != TaskStatus::New
1350                    && let Err(e) = store.update_status(store_id, db_status).await
1351                {
1352                    tracing::debug!(?e, "ingest: status sync failed");
1353                }
1354            }
1355        }
1356    }
1357
1358    // Batch-fetch estimate values from GitHub Projects for newly ingested tasks.
1359    // For each task where `tasks.estimate == 0`, populate it from the project board.
1360    if !new_task_node_ids.is_empty() {
1361        let node_ids: Vec<String> = new_task_node_ids.iter().map(|(_, n)| n.clone()).collect();
1362        match backend.get_project_item_estimates(&node_ids).await {
1363            Ok(estimates) => {
1364                for (store_id, node_id) in new_task_node_ids {
1365                    if let Some(&estimate) = estimates.get(&node_id)
1366                        && estimate > 0
1367                        && let Err(e) = store.set_estimate_if_zero(store_id, estimate).await
1368                    {
1369                        tracing::debug!(
1370                            store_id,
1371                            estimate,
1372                            err = %e,
1373                            "ingest: failed to set estimate from project"
1374                        );
1375                    }
1376                }
1377            }
1378            Err(e) => {
1379                tracing::debug!(
1380                    err = %e,
1381                    "ingest: project estimate fetch failed — skipping estimate sync this tick"
1382                );
1383            }
1384        }
1385    }
1386
1387    Ok(())
1388}
1389
1390#[cfg(test)]
1391mod tests;
1392
1393#[cfg(test)]
1394mod unblock_tests;
1395
1396#[cfg(test)]
1397mod comments_tests;