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