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