Skip to main content

orch/engine/
sync.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
11use super::EngineConfig;
12use super::ci_bootstrap;
13use super::cleanup::{check_merged_prs, cleanup_done_worktrees, prune_old_run_output};
14use super::commands::{CommandOutcome, CommandStoreOps, parse_command, validate_and_run_command};
15use super::review_poll::review_open_prs;
16use crate::backends::ExternalId;
17use crate::backends::ExternalTask;
18use crate::backends::{ExternalBackend, Mention, Status};
19use crate::config;
20use crate::engine;
21use crate::engine::auto_merge::{CI_FAILURE_AUTO_MERGE_STAGE, is_pr_behind, required_checks_state};
22use crate::engine::cleanup::cleanup_task_worktree;
23use crate::engine::commands::CommandGh;
24use crate::engine::commands::OwnerCommand;
25use crate::engine::cooldown;
26use crate::engine::cooldown::{
27    cooldown_reason, github_circuit_remaining_secs, is_agent_in_cooldown, is_github_circuit_open,
28    is_model_in_cooldown, refresh_degraded_agents,
29};
30use crate::engine::dependencies;
31use crate::engine::review;
32use crate::engine::router::Router;
33use crate::engine::router::RouterConfig;
34use crate::engine::router::config as router_config;
35use crate::engine::runner::agents::patterns;
36use crate::engine::tasks;
37use crate::engine::tasks::{TaskManager, status_to_task_status};
38use crate::github::http::GhHttp;
39use crate::github::types::extract_issue_number_from_url;
40use crate::store;
41use crate::store::Task;
42use crate::store::TaskRun;
43use crate::store::TaskStatus;
44use crate::store::TaskStore;
45use crate::tmux::TmuxManager;
46use dashmap::{DashMap, DashSet};
47use futures::future;
48use std::collections::HashMap;
49use std::collections::HashSet;
50use std::sync::Arc;
51use std::time::Duration;
52use std::time::Instant;
53use tokio::sync::OnceCell;
54use tokio::sync::RwLock;
55use tokio::time;
56
57/// Read a KV value from the store.
58///
59/// Returns `None` if the store is unavailable, the key doesn't exist, OR if
60/// the store query fails. Use [`try_kv_get_prefer_store`] if you need to
61/// distinguish between "key not found" and actual errors.
62async fn kv_get_prefer_store(store: Option<&Arc<TaskStore>>, key: &str) -> Option<String> {
63    match try_kv_get_prefer_store(store, key).await {
64        Ok(opt) => opt,
65        Err(e) => {
66            tracing::error!(key, err = %e, "kv_get failed");
67            None
68        }
69    }
70}
71
72/// Try to read a KV value from the store, returning errors instead of
73/// silently discarding them.
74///
75/// Returns `Ok(None)` if the store is unavailable or the key doesn't exist.
76/// Returns `Err` if the store query fails.
77async fn try_kv_get_prefer_store(
78    store: Option<&Arc<TaskStore>>,
79    key: &str,
80) -> anyhow::Result<Option<String>> {
81    if let Some(s) = store {
82        Ok(s.kv_get(key).await?)
83    } else {
84        Ok(None)
85    }
86}
87
88/// Write a KV value to the store.
89///
90/// Logs warnings on failure but provides no way for callers to know if the
91/// write succeeded. Use [`try_kv_set_prefer_store`] if you need to handle
92/// errors or guarantee persistence (e.g., for circuit breaker state).
93async fn kv_set_prefer_store(store: Option<&Arc<TaskStore>>, key: &str, value: &str) {
94    if let Err(e) = try_kv_set_prefer_store(store, key, value).await {
95        tracing::error!(key, err = %e, "kv_set failed");
96    }
97}
98
99/// Try to write a KV value to the store, returning errors instead of
100/// silently logging them.
101///
102/// Returns `Ok(())` if the store is unavailable (best-effort) or if the
103/// write succeeds. Returns `Err` if the store query fails.
104async fn try_kv_set_prefer_store(
105    store: Option<&Arc<TaskStore>>,
106    key: &str,
107    value: &str,
108) -> anyhow::Result<()> {
109    if let Some(s) = store {
110        s.kv_set(key, value).await?;
111    }
112    Ok(())
113}
114
115#[derive(Debug, Clone)]
116pub(crate) struct ReviewTaskSnapshot {
117    pub external: ExternalTask,
118    pub stored: Task,
119}
120
121async fn prefetch_review_tasks(
122    store: &Arc<TaskStore>,
123    repo: &str,
124) -> anyhow::Result<(
125    Vec<ReviewTaskSnapshot>,
126    Vec<ReviewTaskSnapshot>,
127    Vec<ReviewTaskSnapshot>,
128)> {
129    // Approved tasks wait on the same merge path as a review in progress
130    let mut in_review = store.list_by_status(repo, TaskStatus::InReview).await?;
131    in_review.extend(store.list_by_status(repo, TaskStatus::Approved).await?);
132    let in_review = in_review
133        .into_iter()
134        .map(|stored| ReviewTaskSnapshot {
135            external: tasks::store_task_to_external(&stored),
136            stored,
137        })
138        .collect();
139    let needs_review = store
140        .list_by_status(repo, TaskStatus::NeedsReview)
141        .await?
142        .into_iter()
143        .map(|stored| ReviewTaskSnapshot {
144            external: tasks::store_task_to_external(&stored),
145            stored,
146        })
147        .collect();
148
149    // Also prefetch blocked tasks that have a branch or PR number recorded.
150    // These can be merged externally (or manually) but previously were invisible
151    // to the merged-PR checker, leaving tasks stuck in Blocked after merges.
152    let blocked_candidates = store
153        .list_by_status(repo, TaskStatus::Blocked)
154        .await?
155        .into_iter()
156        .filter(|stored| stored.pr_number.is_some() || !stored.branch.is_empty())
157        .map(|stored| ReviewTaskSnapshot {
158            external: tasks::store_task_to_external(&stored),
159            stored,
160        })
161        .collect();
162
163    Ok((in_review, needs_review, blocked_candidates))
164}
165
166async fn fetch_comments_since(
167    backend: &Arc<dyn ExternalBackend>,
168    since: &str,
169) -> anyhow::Result<Vec<Mention>> {
170    backend.get_mentions(since).await
171}
172
173fn filter_mentions_by_since(comments: &[Mention], since: &str) -> Vec<Mention> {
174    comments
175        .iter()
176        .filter(|comment| comment.created_at.as_str() > since)
177        .cloned()
178        .collect()
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182enum FailureCategory {
183    FalseFailure,
184    RateLimit,
185    CreditExhausted,
186    SilentExit0,
187    Timeout,
188    ConnectionError,
189    CliFlagError,
190    AllAgentsExhausted,
191    ParseError,
192    MaxAttempts,
193    PushFailed,
194    PrCreateFailed,
195    ModelUnavailable,
196    Unknown,
197}
198
199impl FailureCategory {
200    /// Whether auto-unblock may put the task back in the queue on its own.
201    ///
202    /// `MaxAttempts` is deliberately absent: the task already ran the configured
203    /// number of times, so an automatic retry just restarts the loop that produced
204    /// the block. It stays blocked until `orch task unblock` or `orch task retry`
205    /// (#3783)
206    fn is_recoverable(self) -> bool {
207        matches!(
208            self,
209            FailureCategory::FalseFailure
210                | FailureCategory::RateLimit
211                | FailureCategory::CreditExhausted
212                | FailureCategory::SilentExit0
213                | FailureCategory::Timeout
214                | FailureCategory::ConnectionError
215                | FailureCategory::CliFlagError
216                | FailureCategory::AllAgentsExhausted
217                | FailureCategory::ParseError
218                | FailureCategory::ModelUnavailable
219        )
220    }
221
222    fn as_str(self) -> &'static str {
223        match self {
224            FailureCategory::FalseFailure => "FalseFailure",
225            FailureCategory::RateLimit => "RateLimit",
226            FailureCategory::CreditExhausted => "CreditExhausted",
227            FailureCategory::SilentExit0 => "SilentExit0",
228            FailureCategory::Timeout => "Timeout",
229            FailureCategory::ConnectionError => "ConnectionError",
230            FailureCategory::CliFlagError => "CliFlagError",
231            FailureCategory::AllAgentsExhausted => "AllAgentsExhausted",
232            FailureCategory::ParseError => "ParseError",
233            FailureCategory::MaxAttempts => "MaxAttempts",
234            FailureCategory::PushFailed => "PushFailed",
235            FailureCategory::PrCreateFailed => "PrCreateFailed",
236            FailureCategory::ModelUnavailable => "ModelUnavailable",
237            FailureCategory::Unknown => "Unknown",
238        }
239    }
240}
241
242fn classify_failure(error: &str, outcome: &str) -> FailureCategory {
243    let lower = error.to_lowercase();
244
245    if outcome == "timeout" || lower.contains("timeout") {
246        return FailureCategory::Timeout;
247    }
248
249    // Credit exhaustion is a transient condition (credits replenish, billing cycles
250    // reset). Classifying it as recoverable allows auto-unblock to retry once the
251    // credit-related cooldown expires, instead of permanently blocking the task.
252    //
253    // Checked before the generic rate-limit branch below: billing-cycle exhaustion
254    // messages (e.g. Kimi's "usage limit for this billing cycle") also contain
255    // "usage limit"/"rate limit" substrings, so checking outcome/content-based
256    // rate-limit patterns first would misclassify them as plain RateLimit (issue
257    // #3529). `outcome` also carries the specific string from `classify_run_outcome`
258    // when the task_run already recorded it.
259    if outcome == "billing_cycle_exhausted"
260        || outcome == "credit_exhausted"
261        || outcome == "org_level_disabled"
262        || cooldown::detect_credit_exhaustion(&lower).is_some()
263    {
264        return FailureCategory::CreditExhausted;
265    }
266
267    if outcome == "rate_limit" || lower.contains("rate limit") || lower.contains("usage limit") {
268        return FailureCategory::RateLimit;
269    }
270
271    if error.trim().is_empty() {
272        return FailureCategory::FalseFailure;
273    }
274
275    if lower.contains("all agents exhausted") {
276        return FailureCategory::AllAgentsExhausted;
277    }
278
279    if lower.contains("max attempts") || lower.contains("exceeded max attempts") {
280        return FailureCategory::MaxAttempts;
281    }
282
283    if lower.contains("output-format=stream-json") && lower.contains("requires --verbose") {
284        return FailureCategory::CliFlagError;
285    }
286
287    if lower.contains("model unavailable")
288        || lower.contains("model not found")
289        || (lower.contains("does not exist") && lower.contains("model"))
290    {
291        return FailureCategory::ModelUnavailable;
292    }
293
294    if lower.contains("push failed") {
295        return FailureCategory::PushFailed;
296    }
297
298    if lower.contains("create pr failed")
299        || lower.contains("failed to create pull request")
300        || lower.contains("pull request creation failed")
301    {
302        return FailureCategory::PrCreateFailed;
303    }
304
305    if lower.contains("exit 0") {
306        return FailureCategory::SilentExit0;
307    }
308
309    if outcome == "parse_error"
310        || outcome == "truncated"
311        || lower.contains("invalid response")
312        || lower.contains("parse error")
313        || lower.contains("truncated")
314    {
315        return FailureCategory::ParseError;
316    }
317
318    if patterns::detect_network_error(&lower).is_some() {
319        return FailureCategory::ConnectionError;
320    }
321
322    FailureCategory::Unknown
323}
324
325fn classify_failure_from_run(run: &TaskRun) -> Option<FailureCategory> {
326    // Completed successfully — no failure to classify.
327    if run.outcome == "success" && run.error.trim().is_empty() {
328        return None;
329    }
330
331    // Skip runs with no meaningful data. Some runs are created then never
332    // populated (aborted/stale work). Treat these as non-failures so they
333    // don't block auto-unblock logic which considers recent failures.
334    // Historically an all-NULL/empty run would be promoted to Unknown which
335    // prevented auto-unblock. Ensure we early-return None for truly empty
336    // runs (no outcome, no error, no exit_code, no output).
337    if run.outcome.trim().is_empty()
338        && run.error.trim().is_empty()
339        && run.exit_code.is_none()
340        && run.stdout.trim().is_empty()
341        && run.stderr.trim().is_empty()
342    {
343        return None;
344    }
345
346    let has_output = !run.stdout.trim().is_empty() || !run.stderr.trim().is_empty();
347    if run.exit_code == Some(0) && !has_output && run.outcome != "success" {
348        return Some(FailureCategory::SilentExit0);
349    }
350
351    let mut category = classify_failure(&run.error, &run.outcome);
352
353    // Promote a bare "false failure" to Unknown only when we have a
354    // concrete non-zero exit code or other signs the run truly failed.
355    // Do NOT promote when exit_code is None (incomplete run) — those are
356    // handled above by skipping. This prevents NULL/aborted runs from
357    // turning recoverable FalseFailure into non-recoverable Unknown.
358    // Only promote when we have explicit evidence: a non-zero exit code
359    // or non-empty stdout/stderr. If exit_code is None we keep FalseFailure
360    // so the run remains recoverable.
361    if category == FailureCategory::FalseFailure {
362        let has_nonzero_exit = run.exit_code.is_some() && run.exit_code != Some(0);
363        let has_output = !run.stdout.trim().is_empty() || !run.stderr.trim().is_empty();
364        if has_nonzero_exit || has_output {
365            category = FailureCategory::Unknown;
366        }
367    }
368
369    Some(category)
370}
371
372/// Resolve the parent task ID for a mention.
373///
374/// - If the mention is on a PR, look up the task that owns that PR via `pr_number`.
375/// - If the mention is on an issue, look up the task by external_id (issue number).
376///
377/// Returns:
378/// - `Ok(Some(id))` — parent found
379/// - `Ok(None)` — no matching parent (genuine miss, e.g. unknown issue/PR)
380/// - `Err(_)` — lookup failed (DB error); caller should defer/retry
381async fn resolve_mention_parent_id(
382    store: &TaskStore,
383    repo: &str,
384    issue_num: &str,
385    is_pr: bool,
386) -> anyhow::Result<Option<i64>> {
387    if is_pr {
388        if let Ok(pr_num) = issue_num.parse::<i32>() {
389            store.resolve_id_by_pr_number(repo, pr_num).await
390        } else {
391            Ok(None)
392        }
393    } else {
394        store.resolve_id_by_external(repo, issue_num).await
395    }
396}
397
398/// Create a sentinel mention task in the store and advance the cursor.
399async fn record_mention_task(
400    store: &TaskStore,
401    repo: &str,
402    mention: &Mention,
403    title: &str,
404    body: &str,
405    parent_id: Option<i64>,
406    cursor: &mut MentionCursor,
407) -> bool {
408    match store
409        .create_internal(repo, title, body, "mention", &mention.id, parent_id)
410        .await
411    {
412        Ok(task_id) => {
413            tracing::info!(task_id, mention_id = %mention.id, "created mention task");
414            cursor.advance(&mention.created_at);
415            true
416        }
417        Err(e) => {
418            tracing::warn!(mention_id = %mention.id, err = %e, "failed to create mention task");
419            false
420        }
421    }
422}
423
424/// Advance the mention cursor if the timestamp is newer.
425fn advance_cursor(last_safe_ts: &mut Option<String>, ts: &str) {
426    if last_safe_ts.as_deref() < Some(ts) {
427        *last_safe_ts = Some(ts.to_string());
428    }
429}
430
431#[derive(Debug, Default)]
432struct MentionCursor {
433    last_safe_ts: Option<String>,
434    blocked_by_gap: bool,
435}
436
437impl MentionCursor {
438    fn advance(&mut self, ts: &str) {
439        if self.blocked_by_gap {
440            return;
441        }
442        advance_cursor(&mut self.last_safe_ts, ts);
443    }
444
445    fn block_on_gap(&mut self) {
446        self.blocked_by_gap = true;
447    }
448
449    fn into_last_safe_ts(self) -> Option<String> {
450        self.last_safe_ts
451    }
452}
453
454/// What to do with a comment in the unified scan loop.
455#[derive(Debug, PartialEq)]
456pub(crate) enum CommentAction {
457    /// Already processed or not relevant — skip.
458    Skip,
459    /// Slash command without @mention — execute the command.
460    ExecuteCommand {
461        command: OwnerCommand,
462        issue_num: String,
463    },
464    /// @mention with a slash command — execute and record sentinel task.
465    ExecuteCommandForMention {
466        command: OwnerCommand,
467        issue_num: String,
468    },
469    /// @mention without command — create internal task for agent to respond.
470    CreateMentionTask { issue_num: Option<String> },
471}
472
473/// Classify a comment into the appropriate action.
474///
475/// Pure function — no I/O, no async. Determines what the scan loop should do
476/// with each comment based on its content and whether it was already processed.
477pub(crate) fn classify_comment(
478    body: &str,
479    issue_url: Option<&str>,
480    current_user: &str,
481    already_processed: bool,
482) -> CommentAction {
483    if already_processed {
484        return CommentAction::Skip;
485    }
486
487    let is_mention =
488        body.contains(current_user) || body.contains("@orch") || body.contains("@orchestrator");
489    let command = parse_command(body);
490    let issue_num = issue_url.and_then(extract_issue_number_from_url);
491
492    match (command, is_mention, issue_num) {
493        (Some(cmd), true, Some(num)) => CommentAction::ExecuteCommandForMention {
494            command: cmd,
495            issue_num: num,
496        },
497        (Some(cmd), false, Some(num)) => CommentAction::ExecuteCommand {
498            command: cmd,
499            issue_num: num,
500        },
501        // Command but no issue URL — if it's a mention, create task; otherwise skip
502        (Some(_), true, None) => CommentAction::CreateMentionTask { issue_num: None },
503        // Mention without command — create task for agent
504        (None, true, issue_num) => CommentAction::CreateMentionTask { issue_num },
505        // Neither mention nor command — skip
506        (Some(_), false, None) | (None, false, _) => CommentAction::Skip,
507    }
508}
509
510/// Handle a slash command from a mention. Records a sentinel task and advances
511/// the cursor on success; logs a warning and returns early if the mention has
512/// no valid issue URL.
513///
514/// Execute a slash command mentioned by `@orch` on a comment.
515///
516/// Returns:
517/// - `Ok(true)` — command processed and cursor may continue advancing
518/// - `Ok(false)` — mention task insert failed, or validation hit a transient
519///   GitHub error; caller must stop cursor advancement so the next tick retries
520/// - `Err(_)` — DB lookup failed for parent_id; caller must NOT advance cursor
521///   so this mention is retried on the next sync
522#[expect(
523    clippy::too_many_arguments,
524    reason = "the sync tick hands over its shared state piece by piece"
525)]
526async fn handle_slash_command(
527    backend: &Arc<dyn ExternalBackend>,
528    store: Option<&Arc<TaskStore>>,
529    repo: &str,
530    task_manager: &Arc<TaskManager>,
531    gh: &dyn CommandGh,
532    mention: &Mention,
533    command: &OwnerCommand,
534    cursor: &mut MentionCursor,
535) -> anyhow::Result<bool> {
536    let Some(issue_num) = mention
537        .issue_url
538        .as_deref()
539        .and_then(extract_issue_number_from_url)
540    else {
541        tracing::warn!(comment_id = %mention.id, "slash command without valid issue number");
542        return Ok(true);
543    };
544
545    let store_opt: Option<Arc<dyn CommandStoreOps>> =
546        store.map(|s| Arc::clone(s) as Arc<dyn CommandStoreOps>);
547    let outcome = validate_and_run_command(
548        backend,
549        gh,
550        repo,
551        &issue_num,
552        command,
553        &mention.author,
554        &store_opt,
555        task_manager,
556    )
557    .await;
558
559    // Extract is_pr from the outcome (avoids a second get_issue call)
560    let is_pr = match &outcome {
561        CommandOutcome::Executed { is_pr }
562        | CommandOutcome::NotOpen { is_pr }
563        | CommandOutcome::NotCollaborator { is_pr } => *is_pr,
564        CommandOutcome::FetchFailed | CommandOutcome::CollaboratorCheckFailed => {
565            // Nothing was executed and nothing was posted to GitHub. Leave the cursor
566            // before this comment so the next tick retries the command.
567            tracing::warn!(
568                comment_id = %mention.id,
569                command = %command,
570                "deferring @orch slash command after a transient GitHub error"
571            );
572            return Ok(false);
573        }
574    };
575
576    // Record a sentinel task for the mention (with correct parent_id).
577    // On DB lookup failure, defer so the mention can be retried on next sync.
578    if let Some(s) = store {
579        let parent_id = match resolve_mention_parent_id(s, repo, &issue_num, is_pr).await {
580            Ok(parent_id) => parent_id,
581            Err(e) => {
582                tracing::warn!(
583                    comment_id = %mention.id,
584                    err = %e,
585                    "deferring mention task due to parent lookup failure"
586                );
587                return Err(e);
588            }
589        };
590
591        let (title, body) = match &outcome {
592            CommandOutcome::NotOpen { .. } => (
593                format!(
594                    "Skipped @orch command on closed #{issue_num} from @{}",
595                    mention.author
596                ),
597                format!(
598                    "Mention by @{}:\n\n{}\n\n**Skipped:** target is closed",
599                    mention.author, mention.body
600                ),
601            ),
602            CommandOutcome::NotCollaborator { .. } => (
603                format!(
604                    "Skipped @orch command on #{issue_num} from non-collaborator @{}",
605                    mention.author
606                ),
607                format!(
608                    "Mention by @{}:\n\n{}\n\n**Skipped:** author is not a collaborator",
609                    mention.author, mention.body
610                ),
611            ),
612            CommandOutcome::Executed { .. } => (
613                format!(
614                    "Respond to mention by @{} on task #{issue_num} — command executed",
615                    mention.author
616                ),
617                format!(
618                    "Mention by @{} on #{issue_num}:\n\n{}\n\n**Status:** Command executed",
619                    mention.author, mention.body
620                ),
621            ),
622            CommandOutcome::FetchFailed | CommandOutcome::CollaboratorCheckFailed => {
623                tracing::debug!("skipping mention task record due to earlier command failure");
624                return Ok(true);
625            }
626        };
627
628        let created = record_mention_task(s, repo, mention, &title, &body, parent_id, cursor).await;
629        if !created {
630            return Ok(false);
631        }
632    }
633    Ok(true)
634}
635
636fn auto_unblock_cooldown_elapsed(count: i32, last_at: &str) -> bool {
637    if count == 0 {
638        return true;
639    }
640
641    let required = match count {
642        1 => chrono::Duration::minutes(30),
643        2 => chrono::Duration::hours(2),
644        _ => return false,
645    };
646
647    if last_at.trim().is_empty() {
648        return true;
649    }
650
651    match chrono::DateTime::parse_from_rfc3339(last_at) {
652        Ok(ts) => chrono::Utc::now() - ts.with_timezone(&chrono::Utc) >= required,
653        Err(_) => true,
654    }
655}
656
657/// True when a blocked task reached auto-merge and CI failed there.
658/// Pre-review and bootstrap CI-failure reasons share the "CI failure limit" words
659/// and must stay blocked for a person (#4140)
660fn is_ci_failure_block(task: &Task) -> bool {
661    let reason = task.block_reason.as_deref().unwrap_or("");
662    if reason.contains("CI checks timed out") {
663        return true;
664    }
665    reason.contains("CI failure limit") && reason.contains(CI_FAILURE_AUTO_MERGE_STAGE)
666}
667
668fn ci_failure_unblock_cooldown_elapsed(task: &Task) -> bool {
669    if task.auto_unblock_count == 0 {
670        return true;
671    }
672
673    // Short cooldowns — the PR may close quickly after the first check.
674    // We never permanently block (no `_ => return false`): eventually the PR
675    // will close or a human will intervene.
676    let required = match task.auto_unblock_count {
677        1 => chrono::Duration::minutes(10),
678        2 => chrono::Duration::hours(1),
679        3 => chrono::Duration::hours(6),
680        _ => chrono::Duration::hours(24),
681    };
682
683    let last_at = &task.auto_unblock_last_at;
684    if last_at.trim().is_empty() {
685        return true;
686    }
687
688    match chrono::DateTime::parse_from_rfc3339(last_at) {
689        Ok(ts) => chrono::Utc::now() - ts.with_timezone(&chrono::Utc) >= required,
690        Err(_) => true,
691    }
692}
693
694async fn try_unblock_ci_failure_task(
695    gh: &GhHttp,
696    repo: &str,
697    task_manager: &Arc<TaskManager>,
698    store: &Arc<TaskStore>,
699    task: &Task,
700    auto_merge_in_flight: &Arc<DashSet<String>>,
701) -> anyhow::Result<bool> {
702    let Some(pr_number) = task.pr_number.and_then(|n| u64::try_from(n).ok()) else {
703        tracing::debug!(
704            task_id = task.id,
705            "CI failure blocked task has no PR number"
706        );
707        return Ok(false);
708    };
709
710    let pr = match gh.get_pr(repo, pr_number).await {
711        Ok(p) => p,
712        Err(e) => {
713            tracing::warn!(task_id = task.id, pr_number, err = %e, "failed to get PR status for CI failure block");
714            return Ok(false);
715        }
716    };
717
718    tracing::debug!(
719        task_id = task.id,
720        pr_number,
721        merged = pr.merged,
722        state = ?pr.state,
723        "verifying PR state for CI failure blocked task"
724    );
725
726    if !pr.merged.unwrap_or(false) && pr.state.eq_ignore_ascii_case("closed") {
727        tracing::info!(
728            task_id = task.id,
729            pr_number,
730            "PR closed unmerged — leaving CI failure blocked task blocked"
731        );
732        let new_reason = format!(
733            "CI failure limit reached (PR #{pr_number} closed unmerged — no further auto-recovery)"
734        );
735        if task.block_reason.as_deref() != Some(new_reason.as_str()) {
736            let fields = vec![("block_reason", serde_json::json!(new_reason))];
737            store.set_fields_silent(task.id, &fields).await?;
738        }
739        return Ok(false);
740    }
741
742    if pr.merged.unwrap_or(false) {
743        tracing::info!(
744            task_id = task.id,
745            pr_number,
746            "PR merged — unblocking CI failure blocked task"
747        );
748        let ext_id = task
749            .external_id
750            .clone()
751            .unwrap_or_else(|| format!("internal:{}", task.id));
752        // Update the store directly by the already-resolved numeric id instead of going
753        // through `task_manager.update_task_status`, which resolves by `self.repo` — this
754        // sweep runs cross-repo, so `task.repo` may not match the caller's own repo scope.
755        task_manager
756            .mark_task_done_by_store_id(task.id, &task.repo, &ExternalId(ext_id))
757            .await?;
758        let fields = vec![
759            ("block_reason", serde_json::Value::Null),
760            ("auto_unblock_count", serde_json::json!(0)),
761            ("auto_unblock_last_at", serde_json::json!("")),
762            ("auto_unblock_last_reason", serde_json::json!("")),
763        ];
764        store.set_fields(task.id, &fields).await?;
765        return Ok(true);
766    }
767
768    // Skip if a recovery merge is already in flight for this task. The poll loop
769    // can take up to 10 minutes, and the same task may be seen by both the per-repo
770    // sync_tick and the global sweep in the same tick window.
771    let task_id_str = task
772        .external_id
773        .clone()
774        .unwrap_or_else(|| format!("internal:{}", task.id));
775    if auto_merge_in_flight.contains(&task_id_str) {
776        tracing::debug!(
777            task_id = task.id,
778            pr_number,
779            "CI-failure recovery merge already in flight — skipping"
780        );
781        return Ok(false);
782    }
783
784    // Recovery was built for approved PRs. A pre-review CI block can share a
785    // rewritten "during auto-merge" reason, so require a recorded approval
786    if !review::has_recorded_approval(store, repo, &task_id_str, pr_number).await {
787        tracing::info!(
788            task_id = task.id,
789            pr_number,
790            "CI-failure recovery skipped, PR has no approving review"
791        );
792        return Ok(false);
793    }
794
795    // Give the PR an active chance to recover: merge the base branch into the PR
796    // branch to re-trigger CI, then re-enable GitHub auto-merge. GitHub's queue
797    // can silently stall even when checks are green and the branch is up to date,
798    // so after arming auto-merge we poll for completion and fall back to a direct
799    // merge once the PR is mergeable and CI is passing.
800    let branch_update_result = gh.update_pr_branch(repo, pr_number).await;
801    match branch_update_result {
802        Ok(()) => {
803            tracing::info!(
804                task_id = task.id,
805                pr_number,
806                "updated CI-failure-blocked PR branch against base to retrigger CI"
807            );
808        }
809        Err(ref e) => {
810            // warn, not debug, so a silently-broken corrective retry doesn't look like a working one (#3561)
811            tracing::warn!(
812                task_id = task.id,
813                pr_number,
814                err = %e,
815                outcome = "branch_update_failed",
816                "failed to update CI-failure-blocked PR branch (may already be up to date)"
817            );
818        }
819    }
820
821    if let Err(e) = gh.enable_auto_merge(repo, pr_number).await {
822        tracing::warn!(task_id = task.id, pr_number, err = %e, "failed to re-enable auto-merge after branch update");
823    }
824
825    // Record this attempt so the cooldown advances even though the actual
826    // poll/merge now runs in the background.
827    let pr_state = pr.state.as_str();
828    let current_reason = task.block_reason.as_deref().unwrap_or("");
829    let rewrite_reason = current_reason.contains(CI_FAILURE_AUTO_MERGE_STAGE);
830    let new_reason = if let Err(ref e) = branch_update_result {
831        format!(
832            "CI failure limit reached {CI_FAILURE_AUTO_MERGE_STAGE} (PR #{pr_number} still open, state: {pr_state}, branch update failed: {e})"
833        )
834    } else {
835        format!(
836            "CI failure limit reached {CI_FAILURE_AUTO_MERGE_STAGE} (PR #{pr_number} still open, state: {pr_state})"
837        )
838    };
839    let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
840    // Increment auto_unblock_count so the cooldown backoff (24h, 3d, never) kicks in
841    // and we don't hammer the GitHub API every tick for a PR that stays open.
842    let new_count = task.auto_unblock_count.saturating_add(1);
843    let mut fields = Vec::new();
844    if rewrite_reason {
845        fields.push(("block_reason", serde_json::json!(&new_reason)));
846    }
847    fields.push(("auto_unblock_count", serde_json::json!(new_count)));
848    fields.push(("auto_unblock_last_at", serde_json::json!(&now)));
849    // Use set_fields_silent so the probe write does not bump updated_at on stale
850    // blocked tasks — triage queries keyed off updated_at must only see real
851    // status/result changes, not periodic re-checks of an open PR.
852    store.set_fields_silent(task.id, &fields).await?;
853
854    // Spawn the poll and direct-merge fallback in the background so the
855    // recovery sweep does not block the main tick loop (or sync_tick) while
856    // CI runs. The in-flight guard prevents double-spawns across ticks.
857    auto_merge_in_flight.insert(task_id_str.clone());
858    let gh_clone = gh.clone();
859    let repo_string = repo.to_string();
860    let task_manager_clone = Arc::clone(task_manager);
861    let store_clone = Arc::clone(store);
862    let task_clone = task.clone();
863    let in_flight_clone = Arc::clone(auto_merge_in_flight);
864
865    tokio::spawn(async move {
866        let _guard = scopeguard::guard((), |()| {
867            in_flight_clone.remove(&task_id_str);
868        });
869
870        match poll_and_merge_recovered_pr(&gh_clone, &repo_string, pr_number, task_clone.id).await {
871            Ok(true) => {
872                tracing::info!(
873                    task_id = task_clone.id,
874                    pr_number,
875                    "CI-failure-blocked PR merged during recovery sweep"
876                );
877                let ext_id = task_clone
878                    .external_id
879                    .clone()
880                    .unwrap_or_else(|| format!("internal:{}", task_clone.id));
881                let fields = [
882                    ("block_reason", serde_json::Value::Null),
883                    ("auto_unblock_count", serde_json::json!(0)),
884                    ("auto_unblock_last_at", serde_json::json!("")),
885                    ("auto_unblock_last_reason", serde_json::json!("")),
886                ];
887                if let Err(e) = task_manager_clone
888                    .update_task_status_and_result_by_store_id(
889                        task_clone.id,
890                        &task_clone.repo,
891                        &ExternalId(ext_id),
892                        Status::Done,
893                        &fields,
894                    )
895                    .await
896                {
897                    tracing::warn!(
898                        task_id = task_clone.id,
899                        pr_number,
900                        err = %e,
901                        "failed to mark CI-failure-blocked task done after recovery merge"
902                    );
903                }
904                if let Err(e) =
905                    cleanup_task_worktree(&format!("{}", task_clone.id), &repo_string, &store_clone)
906                        .await
907                {
908                    tracing::warn!(
909                        task_id = task_clone.id,
910                        pr_number,
911                        err = %e,
912                        "cleanup after CI-failure recovery merge failed"
913                    );
914                }
915            }
916            Ok(false) => {
917                tracing::debug!(
918                    task_id = task_clone.id,
919                    pr_number,
920                    "CI-failure-blocked PR not merged this recovery tick — poll completed without merge"
921                );
922            }
923            Err(e) => {
924                tracing::warn!(
925                    task_id = task_clone.id,
926                    pr_number,
927                    err = %e,
928                    "error while polling CI-failure-blocked PR for recovery"
929                );
930            }
931        }
932    });
933
934    Ok(false)
935}
936
937/// Poll a recovered CI-failure PR until it merges or its checks settle, then
938/// attempt a direct merge if GitHub's auto-merge queue has not completed it.
939///
940/// GitHub's `enablePullRequestAutoMerge` hands the PR off to GitHub's queue and
941/// returns immediately; the queue can stall silently. This helper mirrors the
942/// primary `auto_merge_pr` polling pattern but is scoped to the recovery sweep:
943/// it waits for required checks to pass, verifies the PR is not behind the base
944/// branch, and calls `gh.merge_pr()` directly when the PR is ready but still
945/// open. Returns `Ok(true)` only when the PR is merged, `Ok(false)` when the
946/// PR is closed unmerged or needs to wait for a future tick.
947async fn poll_and_merge_recovered_pr(
948    gh: &GhHttp,
949    repo: &str,
950    pr_number: u64,
951    task_id: i64,
952) -> anyhow::Result<bool> {
953    // The branch can fall behind while CI runs. Retry the update-branch call a
954    // few times inside the poll loop instead of exiting and waiting for the next
955    // 24-hour recovery cooldown.
956    const MAX_BEHIND_RETRIES: u32 = 3;
957
958    let max_wait_secs: u64 = config::get("workflow.ci_poll_max_wait_secs")
959        .ok()
960        .and_then(|s| s.parse().ok())
961        .unwrap_or(600);
962    let base_interval_secs: u64 = config::get("workflow.ci_poll_interval_secs")
963        .ok()
964        .and_then(|s| s.parse().ok())
965        .unwrap_or(15);
966    let max_wait = Duration::from_secs(max_wait_secs);
967    let start = Instant::now();
968    let mut poll_count: u32 = 0;
969    let mut behind_retries: u32 = 0;
970
971    let initial_pr = gh.get_pr(repo, pr_number).await?;
972    let base_branch = initial_pr.base.ref_.clone();
973    let required_contexts = gh
974        .get_required_status_check_contexts(repo, &base_branch)
975        .await?;
976    let repo_has_workflows = if required_contexts.is_empty() {
977        gh.has_workflows(repo).await?
978    } else {
979        true
980    };
981
982    loop {
983        let pr = gh.get_pr(repo, pr_number).await?;
984        if pr.merged.unwrap_or(false) {
985            tracing::info!(
986                task_id = task_id,
987                pr_number,
988                "PR merged during recovery poll"
989            );
990            return Ok(true);
991        }
992        if pr.state.eq_ignore_ascii_case("closed") {
993            tracing::info!(
994                task_id = task_id,
995                pr_number,
996                "PR closed unmerged during recovery poll — leaving task blocked"
997            );
998            return Ok(false);
999        }
1000
1001        if pr.mergeable == Some(false) {
1002            tracing::info!(
1003                task_id = task_id,
1004                pr_number,
1005                outcome = "poll_exited_without_merge",
1006                reason = "merge_conflicts",
1007                "PR has merge conflicts after recovery update — leaving for next recovery cycle"
1008            );
1009            return Ok(false);
1010        }
1011
1012        if is_pr_behind(&pr) {
1013            if behind_retries >= MAX_BEHIND_RETRIES {
1014                tracing::info!(
1015                    task_id = task_id,
1016                    pr_number,
1017                    behind_retries,
1018                    max_behind_retries = MAX_BEHIND_RETRIES,
1019                    outcome = "poll_exited_without_merge",
1020                    reason = "behind_retry_exhausted",
1021                    "PR still behind base after recovery retries — leaving for next recovery cycle"
1022                );
1023                return Ok(false);
1024            }
1025            behind_retries += 1;
1026            match gh.update_pr_branch(repo, pr_number).await {
1027                Ok(()) => {
1028                    tracing::info!(
1029                        task_id = task_id,
1030                        pr_number,
1031                        behind_retries,
1032                        "PR was behind base — updated branch and continuing recovery poll"
1033                    );
1034                    continue;
1035                }
1036                Err(e) => {
1037                    tracing::warn!(
1038                        task_id = task_id,
1039                        pr_number,
1040                        behind_retries,
1041                        err = %e,
1042                        outcome = "branch_update_failed",
1043                        "failed to update behind PR branch during recovery poll"
1044                    );
1045                    return Ok(false);
1046                }
1047            }
1048        }
1049
1050        let head_sha = pr.head.sha.clone();
1051        let (state, total, passing, failing, pending) = if required_contexts.is_empty() {
1052            gh.get_combined_status(
1053                repo,
1054                &head_sha,
1055                repo_has_workflows,
1056                pr.mergeable_state.as_deref(),
1057            )
1058            .await?
1059        } else {
1060            let check_runs = gh.get_check_runs(repo, &head_sha).await?;
1061            let statuses = gh.get_commit_status_contexts(repo, &head_sha).await?;
1062            required_checks_state(&required_contexts, &check_runs, &statuses)
1063        };
1064
1065        tracing::info!(
1066            task_id = task_id,
1067            pr_number,
1068            state = %state,
1069            total,
1070            passing,
1071            failing,
1072            pending,
1073            "CI recovery status check"
1074        );
1075
1076        match state.as_str() {
1077            "success" => {
1078                tracing::info!(
1079                    task_id = task_id,
1080                    pr_number,
1081                    "CI green after recovery — attempting direct merge"
1082                );
1083                match gh.merge_pr(repo, pr_number, true, &head_sha).await {
1084                    Ok(()) => {
1085                        tracing::info!(
1086                            task_id = task_id,
1087                            pr_number,
1088                            "direct merge succeeded after recovery"
1089                        );
1090                        return Ok(true);
1091                    }
1092                    Err(e) => {
1093                        let err = e.to_string().to_ascii_lowercase();
1094                        tracing::warn!(
1095                            task_id = task_id,
1096                            pr_number,
1097                            err = %e,
1098                            "direct merge failed after recovery"
1099                        );
1100                        // If the PR became merged between the get_pr call and the
1101                        // merge attempt, treat it as success rather than a failed tick.
1102                        if err.contains("already merged")
1103                            || err.contains("no merge commit")
1104                            || err.contains("pull request already merged")
1105                        {
1106                            return Ok(true);
1107                        }
1108                        // The head moved after we read it, and updating the branch would skip CI on the new commit
1109                        if err.contains("head branch was modified")
1110                            || err.contains("sha does not match")
1111                        {
1112                            tracing::info!(
1113                                task_id = task_id,
1114                                pr_number,
1115                                outcome = "poll_exited_without_merge",
1116                                reason = "head_moved",
1117                                "merge rejected because the head sha changed"
1118                            );
1119                            return Ok(false);
1120                        }
1121                        // GitHub may reject the merge because the branch fell behind
1122                        // again while CI was finishing. Retry the branch update inside
1123                        // the poll window instead of waiting for the next sweep.
1124                        if (err.contains("head branch is out of date")
1125                            || err.contains("behind")
1126                            || err.contains("409"))
1127                            && behind_retries < MAX_BEHIND_RETRIES
1128                        {
1129                            behind_retries += 1;
1130                            match gh.update_pr_branch(repo, pr_number).await {
1131                                Ok(()) => {
1132                                    tracing::info!(
1133                                        task_id = task_id,
1134                                        pr_number,
1135                                        behind_retries,
1136                                        "merge rejected due to out-of-date branch — updated and continuing recovery poll"
1137                                    );
1138                                    continue;
1139                                }
1140                                Err(update_err) => {
1141                                    tracing::warn!(
1142                                        task_id = task_id,
1143                                        pr_number,
1144                                        behind_retries,
1145                                        err = %update_err,
1146                                        outcome = "branch_update_failed",
1147                                        "failed to update out-of-date PR branch during recovery poll"
1148                                    );
1149                                }
1150                            }
1151                        }
1152                        tracing::info!(
1153                            task_id = task_id,
1154                            pr_number,
1155                            outcome = "poll_exited_without_merge",
1156                            reason = "direct_merge_failed",
1157                            "direct merge did not succeed — leaving for next recovery cycle"
1158                        );
1159                        return Ok(false);
1160                    }
1161                }
1162            }
1163            "failure" => {
1164                tracing::info!(
1165                    task_id = task_id,
1166                    pr_number,
1167                    outcome = "poll_exited_without_merge",
1168                    reason = "ci_failure",
1169                    "CI still failing after recovery — will retry later"
1170                );
1171                return Ok(false);
1172            }
1173            _ => {}
1174        }
1175
1176        if start.elapsed() >= max_wait {
1177            tracing::info!(
1178                task_id = task_id,
1179                pr_number,
1180                outcome = "poll_exited_without_merge",
1181                reason = "poll_timeout",
1182                "CI still pending after recovery poll timeout — will retry later"
1183            );
1184            return Ok(false);
1185        }
1186
1187        poll_count += 1;
1188        let multiplier = (2_u64).pow(poll_count.saturating_sub(1)).min(4);
1189        let sleep_secs = base_interval_secs.saturating_mul(multiplier);
1190        time::sleep(Duration::from_secs(sleep_secs)).await;
1191    }
1192}
1193
1194/// Exact `block_reason` written when a task's NeedsReview refire counter exhausts
1195/// during a rebroadcast escalation (`refire_and_escalate_stale_needs_review_global`).
1196/// Shared with `auto_recover_rebroadcast_blocked_tasks_global` so escalation and
1197/// recovery never drift apart on the literal string
1198const REBROADCAST_BLOCK_REASON: &str = "review agent rebroadcast escalated after repeated retries";
1199
1200/// Global sweep: auto-recover rebroadcast-blocked tasks across all repos.
1201///
1202/// When a NeedsReview refire counter exhausts, the task is blocked with
1203/// `REBROADCAST_BLOCK_REASON`. Once any review agent is routable again, this
1204/// sweep resets matching tasks to `NeedsReview` so the subscriber can pick them up.
1205/// Writes through the store via `*_by_store_id` helpers, not a repo-scoped
1206/// `TaskManager`. Called once per main tick from `tick_global_sweeps`.
1207///
1208/// Before resetting, the attached PR's live state is checked (mirroring
1209/// `try_unblock_ci_failure_task`): merged means the task is marked done, closed
1210/// unmerged means it stays blocked with an annotated reason, and only an open PR
1211/// (or no PR) falls through to `NeedsReview`. A 5-minute block age prevents
1212/// same-tick escalate/recover flapping. Reset-to-NeedsReview still requires at
1213/// least one routable review agent
1214pub(crate) async fn auto_recover_rebroadcast_blocked_tasks_global(
1215    router: &Router,
1216    task_manager: &Arc<TaskManager>,
1217    store: &Arc<TaskStore>,
1218    active_repos: &HashSet<String>,
1219) -> anyhow::Result<()> {
1220    const MIN_BLOCK_AGE_MINUTES: i64 = 5;
1221
1222    let all_blocked = match store.list_all_by_status_global(TaskStatus::Blocked).await {
1223        Ok(tasks) => tasks,
1224        Err(e) => {
1225            tracing::warn!(err = %e, "global rebroadcast-blocked sweep: failed to list blocked tasks");
1226            return Ok(());
1227        }
1228    };
1229
1230    let now = chrono::Utc::now();
1231    let candidates: Vec<_> = all_blocked
1232        .into_iter()
1233        .filter(|t| {
1234            if t.block_reason.as_deref() != Some(REBROADCAST_BLOCK_REASON) {
1235                return false;
1236            }
1237            // A repo outside the active set has no review subscriber, so a reset would loop
1238            if !active_repos.contains(&t.repo) {
1239                return false;
1240            }
1241            // Only recover tasks blocked long enough to rule out same-tick escalations.
1242            match chrono::DateTime::parse_from_rfc3339(&t.updated_at) {
1243                Ok(updated_at) => {
1244                    let age = now - updated_at.with_timezone(&chrono::Utc);
1245                    age.num_minutes() >= MIN_BLOCK_AGE_MINUTES
1246                }
1247                Err(_) => true,
1248            }
1249        })
1250        .collect();
1251
1252    if candidates.is_empty() {
1253        return Ok(());
1254    }
1255
1256    let gh = match GhHttp::new() {
1257        Ok(g) => Some(g),
1258        Err(e) => {
1259            tracing::warn!(err = %e, "global rebroadcast-blocked sweep: failed to create GhHttp — skipping PR-state checks this tick");
1260            None
1261        }
1262    };
1263
1264    // Skip reset-to-NeedsReview when no review agent is routable, re-firing
1265    // while cooled would immediately re-exhaust the counter
1266    let any_routable =
1267        !router.available_agents.is_empty() && router.healthy_agent_count("review") > 0;
1268
1269    for task in candidates {
1270        let ext_id = task
1271            .external_id
1272            .clone()
1273            .unwrap_or_else(|| format!("internal:{}", task.id));
1274
1275        if let (Some(gh), Some(pr_number)) =
1276            (&gh, task.pr_number.and_then(|n| u64::try_from(n).ok()))
1277        {
1278            match gh.get_pr(&task.repo, pr_number).await {
1279                Ok(pr) => {
1280                    if pr.merged.unwrap_or(false) {
1281                        tracing::info!(
1282                            task_id = task.id,
1283                            repo = %task.repo,
1284                            pr_number,
1285                            "global rebroadcast-blocked sweep: PR already merged — marking task done"
1286                        );
1287                        if let Err(e) = task_manager
1288                            .mark_task_done_by_store_id(
1289                                task.id,
1290                                &task.repo,
1291                                &ExternalId(ext_id.clone()),
1292                            )
1293                            .await
1294                        {
1295                            tracing::warn!(task_id = task.id, repo = %task.repo, err = %e, "global rebroadcast-blocked sweep: failed to mark merged task done");
1296                            continue;
1297                        }
1298                        let fields: &[(&str, serde_json::Value)] = &[
1299                            ("block_reason", serde_json::Value::Null),
1300                            ("needs_review_refires", serde_json::json!(0)),
1301                        ];
1302                        if let Err(e) = store.set_fields(task.id, fields).await {
1303                            tracing::warn!(task_id = task.id, err = %e, "global rebroadcast-blocked sweep: failed to clear fields after marking done");
1304                        }
1305                        continue;
1306                    }
1307                    if pr.state.eq_ignore_ascii_case("closed") {
1308                        tracing::info!(
1309                            task_id = task.id,
1310                            repo = %task.repo,
1311                            pr_number,
1312                            "global rebroadcast-blocked sweep: PR closed unmerged — leaving task blocked, not re-dispatching"
1313                        );
1314                        let new_reason = format!(
1315                            "{REBROADCAST_BLOCK_REASON} (PR #{pr_number} closed unmerged — no further auto-recovery)"
1316                        );
1317                        let fields: &[(&str, serde_json::Value)] =
1318                            &[("block_reason", serde_json::json!(new_reason))];
1319                        // set_fields_silent: this is a terminal annotation, not a real
1320                        // status change — don't bump updated_at so triage queries keyed
1321                        // off it aren't confused by a task that stays blocked forever.
1322                        if let Err(e) = store.set_fields_silent(task.id, fields).await {
1323                            tracing::warn!(task_id = task.id, err = %e, "global rebroadcast-blocked sweep: failed to annotate closed-unmerged block reason");
1324                        }
1325                        continue;
1326                    }
1327                    // PR still open — fall through to the reset-to-NeedsReview path.
1328                }
1329                Err(e) => {
1330                    tracing::warn!(task_id = task.id, repo = %task.repo, pr_number, err = %e, "global rebroadcast-blocked sweep: failed to get PR status — skipping this tick");
1331                    continue;
1332                }
1333            }
1334        }
1335
1336        if !any_routable {
1337            continue;
1338        }
1339
1340        if let Err(e) = task_manager
1341            .update_task_status_by_store_id(
1342                task.id,
1343                &task.repo,
1344                &ExternalId(ext_id.clone()),
1345                Status::NeedsReview,
1346            )
1347            .await
1348        {
1349            tracing::warn!(task_id = task.id, repo = %task.repo, err = %e, "global rebroadcast-blocked sweep: failed to reset task to needs_review — skipping");
1350            continue;
1351        }
1352
1353        let fields: &[(&str, serde_json::Value)] = &[
1354            ("block_reason", serde_json::Value::Null),
1355            ("needs_review_refires", serde_json::json!(0)),
1356        ];
1357        if let Err(e) = store.set_fields(task.id, fields).await {
1358            tracing::warn!(task_id = task.id, err = %e, "global rebroadcast-blocked sweep: failed to clear block_reason/needs_review_refires after status reset");
1359        }
1360
1361        tracing::info!(
1362            task_id = task.id,
1363            repo = %task.repo,
1364            ext_id = %ext_id,
1365            "global rebroadcast-blocked sweep: auto-recovered rebroadcast-blocked task — review agents now available"
1366        );
1367    }
1368
1369    Ok(())
1370}
1371
1372async fn auto_unblock_blocked_tasks(
1373    repo: &str,
1374    task_manager: &Arc<TaskManager>,
1375    store: &Arc<TaskStore>,
1376    dispatching: &Arc<DashMap<String, String>>,
1377    auto_merge_in_flight: &Arc<DashSet<String>>,
1378) -> anyhow::Result<()> {
1379    let blocked = match store.list_by_status(repo, TaskStatus::Blocked).await {
1380        Ok(tasks) => tasks,
1381        Err(e) => {
1382            tracing::warn!(err = %e, "failed to list blocked tasks — skipping auto-unblock this tick");
1383            return Ok(());
1384        }
1385    };
1386
1387    if blocked.is_empty() {
1388        return Ok(());
1389    }
1390
1391    // Batch-load all runs for blocked tasks in a single query instead of N individual queries.
1392    let task_ids: Vec<i64> = blocked.iter().map(|t| t.id).collect();
1393    let mut runs_by_task = match store.get_runs_batch(&task_ids).await {
1394        Ok(map) => map,
1395        Err(e) => {
1396            tracing::warn!(err = %e, "get_runs_batch failed — skipping auto-unblock this tick");
1397            return Ok(());
1398        }
1399    };
1400
1401    // Separate CI-failure blocked tasks from other blocked tasks.
1402    let (ci_failure_tasks, other_blocked): (Vec<_>, Vec<_>) =
1403        blocked.into_iter().partition(is_ci_failure_block);
1404
1405    // Handle CI-failure blocked tasks by verifying PR state.
1406    if !ci_failure_tasks.is_empty() {
1407        let gh = match GhHttp::new() {
1408            Ok(g) => Some(g),
1409            Err(e) => {
1410                tracing::warn!(err = %e, "failed to create GhHttp — skipping CI failure unblock this tick");
1411                None
1412            }
1413        };
1414        for task in ci_failure_tasks {
1415            if ci_failure_unblock_cooldown_elapsed(&task)
1416                && let Some(ref gh) = gh
1417                && let Err(e) = try_unblock_ci_failure_task(
1418                    gh,
1419                    repo,
1420                    task_manager,
1421                    store,
1422                    &task,
1423                    auto_merge_in_flight,
1424                )
1425                .await
1426            {
1427                tracing::warn!(task_id = task.id, err = %e, "CI failure unblock check failed");
1428            }
1429        }
1430    }
1431
1432    // Process regular blocked tasks (those without a block_reason).
1433    for task in other_blocked {
1434        if task.block_reason.is_some() {
1435            continue;
1436        }
1437
1438        let task_id_str = task
1439            .external_id
1440            .clone()
1441            .unwrap_or_else(|| format!("internal:{}", task.id));
1442        let dispatch_key = format!("{repo}/{task_id_str}");
1443        if dispatching.contains_key(&dispatch_key) {
1444            continue;
1445        }
1446
1447        let runs = runs_by_task.remove(&task.id).unwrap_or_default();
1448        let relevant_runs: Vec<_> = runs
1449            .into_iter()
1450            .filter(|r| r.run_type == "agent" || r.run_type == "review")
1451            .collect();
1452        let mut failures = Vec::new();
1453        let mut has_review_failure = false;
1454        for run in relevant_runs.iter().rev() {
1455            if let Some(category) = classify_failure_from_run(run) {
1456                if run.run_type == "review" {
1457                    has_review_failure = true;
1458                }
1459                failures.push(category);
1460            }
1461            if failures.len() >= 3 {
1462                break;
1463            }
1464        }
1465
1466        if failures.is_empty() || !failures.iter().all(|f| f.is_recoverable()) {
1467            continue;
1468        }
1469
1470        // Determine the most recent failure category as the "reason key" for this unblock.
1471        let reason_key = failures.first().map_or("", |f| f.as_str());
1472
1473        // Detect reason changes to reset exponential backoff.
1474        // New reasons bypass old cooldown windows and start fresh attempt counters.
1475        let current_reason = task.auto_unblock_last_reason.clone();
1476        let reason_changed = reason_key != current_reason;
1477
1478        // Compute effective counter: when the reason changes, start from 0;
1479        // otherwise use the accumulated count for exponential backoff.
1480        let cooldown_count = if reason_changed {
1481            0
1482        } else {
1483            task.auto_unblock_count
1484        };
1485
1486        // Gate on attempt count using the effective count — if the reason changed, the
1487        // counter was reset above so cooldown_count is 0 and a new reason always gets a
1488        // fresh attempt regardless of how many times the old reason fired.
1489        if cooldown_count >= 3 {
1490            continue;
1491        }
1492
1493        if !auto_unblock_cooldown_elapsed(cooldown_count, &task.auto_unblock_last_at) {
1494            continue;
1495        }
1496
1497        // Compute the new counter value: when reason changed, cooldown_count is 0,
1498        // so incrementing gives 1 (first attempt for the new reason). When the reason is the
1499        // same, advance from current count for exponential backoff.
1500        let new_count = cooldown_count + 1;
1501        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
1502
1503        let ext_id = task
1504            .external_id
1505            .clone()
1506            .unwrap_or_else(|| format!("internal:{}", task.id));
1507        let new_status = if has_review_failure {
1508            Status::NeedsReview
1509        } else {
1510            Status::New
1511        };
1512        let new_status_str = if has_review_failure {
1513            "needs_review"
1514        } else {
1515            "new"
1516        };
1517
1518        // First update the status; only increment the counter if this succeeds.
1519        // This prevents transient GitHub API errors from exhausting the retry quota.
1520        if let Err(e) = task_manager
1521            .update_task_status(&ExternalId(ext_id), new_status)
1522            .await
1523        {
1524            tracing::warn!(
1525                task_id = task.id,
1526                err = %e,
1527                "auto-unblock failed to update status — counter not incremented"
1528            );
1529            continue;
1530        }
1531
1532        // Status update succeeded; now record the counter increment and clear related fields.
1533        let mut fields: Vec<(&str, serde_json::Value)> = vec![
1534            ("auto_unblock_count", serde_json::json!(new_count)),
1535            ("auto_unblock_last_at", serde_json::json!(now)),
1536            ("auto_unblock_last_reason", serde_json::json!(reason_key)),
1537            ("agent", serde_json::Value::Null),
1538            ("model", serde_json::Value::Null),
1539        ];
1540        fields.push(("no_code_reroutes", serde_json::json!(0)));
1541        fields.push(("no_code_last_agent", serde_json::json!("")));
1542        if has_review_failure {
1543            fields.push(("review_agent_failures", serde_json::json!(0)));
1544            fields.push(("review_invocations", serde_json::json!(0)));
1545            fields.push(("review_resets", serde_json::json!(0)));
1546        }
1547        if let Err(e) = store.set_fields(task.id, &fields).await {
1548            tracing::warn!(task_id = task.id, err = %e, "failed to set auto_unblock fields after successful status update");
1549            // Task is unblocked (correct behavior) but counter hasn't advanced.
1550            // Slightly over-eager retries are better than permanent task stalls.
1551        }
1552
1553        if let Err(e) = store
1554            .append_activity(
1555                task.id,
1556                "auto_unblock",
1557                Some("blocked"),
1558                Some(new_status_str),
1559                None,
1560                None,
1561                Some(&serde_json::json!({
1562                    "reason": reason_key,
1563                    "count": if reason_changed { 1 } else { task.auto_unblock_count + 1 },
1564                    "failures": failures.iter().map(|f| format!("{f:?}")).collect::<Vec<_>>(),
1565                })),
1566            )
1567            .await
1568        {
1569            tracing::warn!(task_id = task.id, err = %e, "failed to log auto_unblock activity");
1570        }
1571
1572        tracing::info!(
1573            task_id = task.id,
1574            failures = ?failures,
1575            review_failure = has_review_failure,
1576            "auto-unblocked task with recoverable failures"
1577        );
1578    }
1579
1580    Ok(())
1581}
1582
1583/// Global sweep for CI-failure blocked tasks from inactive or removed projects.
1584///
1585/// `auto_unblock_blocked_tasks` is called from `sync_tick` and only runs for the
1586/// currently-active repo. Tasks that were blocked for a project that is later removed
1587/// from orch config never get processed and accumulate in the DB indefinitely.
1588///
1589/// This function queries all blocked tasks across all repos and handles merge-time
1590/// CI-failure cases (`during auto-merge` or `CI checks timed out`) so they are
1591/// eventually cleaned up regardless of project activity. Pre-review CI-failure
1592/// blocks stay blocked for a person. Called once per main tick from
1593/// `tick_global_sweeps`.
1594pub(crate) async fn auto_unblock_ci_failure_blocked_tasks_global(
1595    task_manager: &Arc<TaskManager>,
1596    store: &Arc<TaskStore>,
1597    auto_merge_in_flight: &Arc<DashSet<String>>,
1598) -> anyhow::Result<()> {
1599    let all_blocked = match store.list_all_by_status_global(TaskStatus::Blocked).await {
1600        Ok(tasks) => tasks,
1601        Err(e) => {
1602            tracing::warn!(err = %e, "global CI-failure blocked sweep: failed to list blocked tasks");
1603            return Ok(());
1604        }
1605    };
1606
1607    let ci_failure_tasks: Vec<_> = all_blocked
1608        .into_iter()
1609        .filter(is_ci_failure_block)
1610        .collect();
1611    if ci_failure_tasks.is_empty() {
1612        return Ok(());
1613    }
1614
1615    let gh = match GhHttp::new() {
1616        Ok(g) => g,
1617        Err(e) => {
1618            tracing::warn!(err = %e, "global CI-failure blocked sweep: failed to create GhHttp");
1619            return Ok(());
1620        }
1621    };
1622
1623    for task in ci_failure_tasks {
1624        if !ci_failure_unblock_cooldown_elapsed(&task) {
1625            continue;
1626        }
1627        if let Err(e) = try_unblock_ci_failure_task(
1628            &gh,
1629            &task.repo,
1630            task_manager,
1631            store,
1632            &task,
1633            auto_merge_in_flight,
1634        )
1635        .await
1636        {
1637            tracing::warn!(
1638                task_id = task.id,
1639                repo = %task.repo,
1640                err = %e,
1641                "global CI-failure blocked sweep: unblock check failed"
1642            );
1643        }
1644    }
1645
1646    Ok(())
1647}
1648
1649/// Global sweep: re-fire stale NeedsReview tasks and escalate persistently-stuck ones
1650/// to Blocked, across all repos.
1651///
1652/// Two cases where the event-driven subscriber in `subscribers/review.rs` can miss
1653/// a NeedsReview task: all review slots are busy when the event fires, or the
1654/// broadcast receiver lagged and dropped it. Re-publish the NeedsReview status
1655/// after a short idle window so the subscriber can pick it up when a slot is free.
1656/// Using a status re-fire rather than spawning the review agent directly keeps this
1657/// path stateless. The subscriber is still the sole spawner and uses the InReview
1658/// transition as its atomic guard (issue #857)
1659///
1660/// Queries across all repos and writes through the store via `*_by_store_id`
1661/// TaskManager helpers. Called once per main tick from `tick_global_sweeps`
1662pub(crate) async fn refire_and_escalate_stale_needs_review_global(
1663    task_manager: &Arc<TaskManager>,
1664    store: &Arc<TaskStore>,
1665    router: &Router,
1666    dispatching: &Arc<DashMap<String, String>>,
1667    active_repos: &HashSet<String>,
1668) -> anyhow::Result<()> {
1669    const MIN_STALE_NEEDS_REVIEW_MINUTES: i64 = 1;
1670    const MAX_NEEDS_REVIEW_REFIRE_ATTEMPTS: u64 = 5;
1671
1672    let needs_review_tasks = match store
1673        .list_all_by_status_global(TaskStatus::NeedsReview)
1674        .await
1675    {
1676        Ok(tasks) => tasks,
1677        Err(e) => {
1678            tracing::warn!(err = %e, "global NeedsReview refire sweep: failed to list needs_review tasks");
1679            return Ok(());
1680        }
1681    };
1682
1683    if needs_review_tasks.is_empty() {
1684        return Ok(());
1685    }
1686
1687    // Re-firing while every review agent is cooled wastes the counter and can
1688    // escalate a task to Blocked while the subscriber would only bail again
1689    let all_review_agents_cooled = router.healthy_agent_count("review") == 0;
1690    if all_review_agents_cooled {
1691        tracing::info!(
1692            count = needs_review_tasks.len(),
1693            "global NeedsReview refire sweep: no review agent available — skipping this pass"
1694        );
1695        return Ok(());
1696    }
1697
1698    for stored in needs_review_tasks {
1699        // No review subscriber listens for a repo outside the active set
1700        if !active_repos.contains(&stored.repo) {
1701            continue;
1702        }
1703
1704        let external = tasks::store_task_to_external(&stored);
1705        let ext_id = external.id.clone();
1706        let repo = stored.repo.clone();
1707
1708        let age_minutes = match chrono::DateTime::parse_from_rfc3339(&external.updated_at) {
1709            Ok(updated_at) => {
1710                let age = chrono::Utc::now() - updated_at.with_timezone(&chrono::Utc);
1711                if age.num_minutes() < MIN_STALE_NEEDS_REVIEW_MINUTES {
1712                    continue;
1713                }
1714                Some(age.num_minutes())
1715            }
1716            Err(_) => None,
1717        };
1718
1719        // Skip tasks actively being dispatched by their owning repo's engine loop.
1720        let dispatch_key = format!("{}/{}", repo, ext_id.0);
1721        if dispatching.contains_key(&dispatch_key) {
1722            continue;
1723        }
1724
1725        let current_refires = u64::try_from(stored.needs_review_refires).unwrap_or(0);
1726        let new_refires = current_refires + 1;
1727
1728        if new_refires > MAX_NEEDS_REVIEW_REFIRE_ATTEMPTS {
1729            tracing::warn!(
1730                task_id = stored.id,
1731                repo = %repo,
1732                new_refires,
1733                "global NeedsReview refire sweep: escalating to Blocked after repeated refires"
1734            );
1735            let fields = [
1736                ("block_reason", serde_json::json!(REBROADCAST_BLOCK_REASON)),
1737                (
1738                    "last_error",
1739                    serde_json::json!(format!("escalated after {} retries", new_refires)),
1740                ),
1741            ];
1742            if let Err(e) = task_manager
1743                .update_task_status_and_result_by_store_id(
1744                    stored.id,
1745                    &repo,
1746                    &ext_id,
1747                    Status::Blocked,
1748                    &fields,
1749                )
1750                .await
1751            {
1752                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");
1753                continue;
1754            }
1755            if let Err(e) = store::store_increment_by_id(
1756                &Some(Arc::clone(store)),
1757                stored.id,
1758                "needs_review_refires",
1759            )
1760            .await
1761            {
1762                tracing::warn!(
1763                    task_id = stored.id,
1764                    repo = %repo,
1765                    err = %e,
1766                    "global NeedsReview refire sweep: failed to increment needs_review_refires after escalation"
1767                );
1768            }
1769            continue;
1770        }
1771
1772        // Exponential backoff: MIN * 2^(current_refires)
1773        let required_minutes =
1774            MIN_STALE_NEEDS_REVIEW_MINUTES * (1i64 << u32::try_from(current_refires).unwrap_or(0));
1775
1776        let should_fire = match age_minutes {
1777            Some(age) => age >= required_minutes,
1778            None => true,
1779        };
1780
1781        if !should_fire {
1782            continue;
1783        }
1784
1785        if let Err(e) = task_manager
1786            .update_task_status_by_store_id(stored.id, &repo, &ext_id, Status::NeedsReview)
1787            .await
1788        {
1789            tracing::warn!(
1790                task_id = stored.id,
1791                repo = %repo,
1792                err = %e,
1793                "global NeedsReview refire sweep: failed to re-fire NeedsReview event — not incrementing counter"
1794            );
1795            continue;
1796        }
1797
1798        let fired_refires = match store::store_increment_by_id(
1799            &Some(Arc::clone(store)),
1800            stored.id,
1801            "needs_review_refires",
1802        )
1803        .await
1804        {
1805            Ok(v) => v,
1806            Err(e) => {
1807                tracing::warn!(
1808                    task_id = stored.id,
1809                    repo = %repo,
1810                    err = %e,
1811                    "global NeedsReview refire sweep: failed to increment needs_review_refires after re-fire"
1812                );
1813                current_refires + 1
1814            }
1815        };
1816
1817        tracing::info!(
1818            task_id = stored.id,
1819            repo = %repo,
1820            age_minutes,
1821            refires = fired_refires,
1822            required_minutes,
1823            "global NeedsReview refire sweep: re-firing NeedsReview event for stale task"
1824        );
1825    }
1826
1827    Ok(())
1828}
1829
1830/// Sync tick — runs every 45s.
1831///
1832/// Handles less-frequent operations:
1833/// - Cleanup finished worktrees
1834/// - Check for merged PRs → mark tasks done
1835/// - Scan for @mentions
1836#[expect(
1837    clippy::too_many_arguments,
1838    reason = "the engine passes its shared handles one by one"
1839)]
1840pub(crate) async fn sync_tick(
1841    backend: &Arc<dyn ExternalBackend>,
1842    tmux: &Arc<TmuxManager>,
1843    repo: &str,
1844    config: &EngineConfig,
1845    router: &Arc<RwLock<Router>>,
1846    task_manager: &Arc<TaskManager>,
1847    store: &Arc<TaskStore>,
1848    dispatching: &Arc<DashMap<String, String>>,
1849    auto_merge_in_flight: &Arc<DashSet<String>>,
1850) -> anyhow::Result<()> {
1851    // One node polls GitHub and decides for the whole cluster
1852    if !store.is_leader() {
1853        return Ok(());
1854    }
1855
1856    tracing::debug!("sync tick");
1857
1858    let mut phases: Vec<(&str, u128)> = Vec::new();
1859    let mut at = Instant::now();
1860
1861    // Global GitHub 5xx circuit breaker — skip non-critical background work
1862    // during sustained GitHub outages to reduce churn and wasted API calls.
1863    let gh_circuit_open = is_github_circuit_open();
1864
1865    if gh_circuit_open {
1866        let remaining = github_circuit_remaining_secs();
1867        tracing::debug!(
1868            remaining_secs = remaining,
1869            "GitHub 5xx circuit breaker open — skipping non-critical sync work"
1870        );
1871        // Persist circuit breaker state as a metric for operators.
1872        // This is critical for avoiding thundering herd after restart during outages.
1873        if let Err(e) =
1874            try_kv_set_prefer_store(Some(store), "metrics:orch.github_5xx_circuit.open", "1").await
1875        {
1876            tracing::error!(err = %e, "failed to persist circuit breaker state — may cause thundering herd after restart");
1877        }
1878    } else if let Err(e) =
1879        try_kv_set_prefer_store(Some(store), "metrics:orch.github_5xx_circuit.open", "0").await
1880    {
1881        tracing::error!(err = %e, "failed to clear circuit breaker state");
1882    }
1883
1884    // 0. Ingest all active external tasks into the unified store.
1885    //    This ensures the store has data for tasks created before dual-write was added.
1886    if !gh_circuit_open {
1887        if let Err(e) = ingest_external_tasks(backend, repo, store).await {
1888            tracing::debug!(err = %e, "external task ingest failed");
1889        }
1890        phases.push(("ingest", at.elapsed().as_millis()));
1891        at = Instant::now();
1892
1893        // Reconcile existing board members too: labels can change without a
1894        // local task transition, and a human/automation may move a card. The
1895        // backend only writes drifted fields through the shared GitHub client.
1896        if let Err(e) = backend.reconcile_project_statuses().await {
1897            tracing::warn!(err = %e, "project status reconciliation failed");
1898        }
1899        phases.push(("board_reconcile", at.elapsed().as_millis()));
1900    }
1901    at = Instant::now();
1902
1903    // 1. Cleanup worktrees for done tasks (background — must not block routing/dispatch)
1904    if !gh_circuit_open {
1905        let backend = Arc::clone(backend);
1906        let repo = repo.to_string();
1907        let task_manager = Arc::clone(task_manager);
1908        let store = Arc::clone(store);
1909        tokio::spawn(async move {
1910            if let Err(e) = cleanup_done_worktrees(&backend, &repo, &task_manager, &store).await {
1911                tracing::warn!(err = %e, "worktree cleanup failed");
1912            }
1913            if let Err(e) = prune_old_run_output(&store).await {
1914                tracing::warn!(err = %e, "task run pruning failed");
1915            }
1916        });
1917    }
1918
1919    let (in_review_tasks, needs_review_tasks, blocked_review_candidates) =
1920        match prefetch_review_tasks(store, repo).await {
1921            Ok(tasks) => tasks,
1922            Err(e) => {
1923                tracing::warn!(err = %e, "failed to prefetch review tasks");
1924                (vec![], vec![], vec![])
1925            }
1926        };
1927    phases.push(("prefetch_review", at.elapsed().as_millis()));
1928    at = Instant::now();
1929
1930    if !gh_circuit_open {
1931        let mention_fallback = chrono::Utc::now() - chrono::Duration::hours(24);
1932        let mention_since = kv_get_prefer_store(Some(store), "mentions_last_checked")
1933            .await
1934            .unwrap_or_else(|| mention_fallback.format("%Y-%m-%dT%H:%M:%SZ").to_string());
1935        let shared_since = mention_since.clone();
1936
1937        let cached_router_config = router.read().await.config.clone();
1938        // Include blocked tasks that have branch/pr info when checking for merged PRs.
1939        let mut combined_needs = needs_review_tasks.clone();
1940        combined_needs.extend(blocked_review_candidates.clone());
1941
1942        let (merge_result, comments_result, review_result) = tokio::join!(
1943            check_merged_prs(
1944                backend,
1945                repo,
1946                store,
1947                task_manager,
1948                &in_review_tasks,
1949                &combined_needs,
1950            ),
1951            fetch_comments_since(backend, &shared_since),
1952            async {
1953                let gh = match GhHttp::new() {
1954                    Ok(g) => g,
1955                    Err(e) => {
1956                        tracing::warn!(err = %e, "failed to create GitHub HTTP client for review poll");
1957                        return Ok(());
1958                    }
1959                };
1960                Box::pin(review_open_prs(
1961                    backend,
1962                    repo,
1963                    config,
1964                    task_manager,
1965                    store,
1966                    dispatching,
1967                    auto_merge_in_flight,
1968                    &in_review_tasks,
1969                    &gh,
1970                    &cached_router_config,
1971                ))
1972                .await
1973            }
1974        );
1975
1976        if let Err(e) = merge_result {
1977            tracing::warn!(err = %e, "PR merge check failed");
1978        }
1979
1980        match comments_result {
1981            Ok(comments) => {
1982                let filtered = filter_mentions_by_since(&comments, &mention_since);
1983
1984                if let Err(e) =
1985                    scan_comments(backend, Some(store), repo, task_manager, Some(&filtered)).await
1986                {
1987                    tracing::warn!(err = %e, "comment scan failed");
1988                }
1989            }
1990            Err(e) => {
1991                tracing::warn!(err = %e, "comment fetch failed");
1992            }
1993        }
1994
1995        if let Err(e) = review_result {
1996            tracing::warn!(err = %e, "PR review failed");
1997        }
1998
1999        if let Err(e) = ci_bootstrap::apply_pending(store, task_manager, repo).await {
2000            tracing::warn!(err = %e, "CI bootstrap ruleset apply failed");
2001        }
2002
2003        phases.push(("merge_comments_review", at.elapsed().as_millis()));
2004    }
2005    at = Instant::now();
2006
2007    // 5. Stale InReview recovery lives in `tick_recover_stuck_tasks`, the single owner of an
2008    // in_review task whose review session is gone or hung. It ran here too, after one minute,
2009    // which beat a finished review's result to the engine and dropped it as stale
2010
2011    // 5c. Detect stale InProgress tasks and recover them.
2012    //
2013    // Similar to stale InReview detection, we check for InProgress tasks whose
2014    // agent tmux session has died (crash, OOM, etc.) and reset them to Routed
2015    // so they can be re-dispatched.
2016    let in_progress_tasks: Vec<_> = match store.list_by_status(repo, TaskStatus::InProgress).await {
2017        Ok(tasks) => tasks
2018            .into_iter()
2019            .map(|stored| {
2020                let external = tasks::store_task_to_external(&stored);
2021                (stored, external)
2022            })
2023            .collect(),
2024        Err(e) => {
2025            tracing::warn!(err = %e, "failed to list in_progress tasks — skipping stale InProgress check");
2026            vec![]
2027        }
2028    };
2029
2030    if !in_progress_tasks.is_empty() {
2031        // Fetch all live tmux sessions once instead of one subprocess call per task.
2032        let live_sessions: HashSet<String> = tmux
2033            .list_sessions()
2034            .await
2035            .unwrap_or_default()
2036            .into_iter()
2037            .map(|s| s.name)
2038            .collect();
2039
2040        for (_stored, external) in &in_progress_tasks {
2041            // A task is only considered stale if it has been in InProgress for > 5 minutes.
2042            const MIN_STALE_MINUTES: i64 = 5;
2043
2044            let task_id = &external.id.0;
2045
2046            // Skip tasks currently being processed by the main tick (dispatch + agent flow).
2047            let dispatch_key = format!("{repo}/{task_id}");
2048            {
2049                if dispatching.contains_key(&dispatch_key) {
2050                    tracing::debug!(
2051                        task_id = %task_id,
2052                        "task locked by dispatch flow, skipping stale check"
2053                    );
2054                    continue;
2055                }
2056            }
2057
2058            // Skip tasks that just transitioned to InProgress — allow time for the
2059            // agent to start its tmux session before treating it as stale.
2060            match chrono::DateTime::parse_from_rfc3339(&external.updated_at) {
2061                Ok(updated_at) => {
2062                    let age = chrono::Utc::now() - updated_at.with_timezone(&chrono::Utc);
2063                    if age.num_minutes() < MIN_STALE_MINUTES {
2064                        tracing::debug!(
2065                            task_id = %task_id,
2066                            age_seconds = age.num_seconds(),
2067                            "InProgress task is too young to be considered stale, skipping"
2068                        );
2069                        continue;
2070                    }
2071                }
2072                Err(e) => {
2073                    tracing::warn!(
2074                        task_id = %task_id,
2075                        ts = %external.updated_at,
2076                        err = %e,
2077                        "invalid updated_at timestamp — treating task as potentially stale"
2078                    );
2079                }
2080            }
2081
2082            let agent_session = tmux.session_name(repo, task_id);
2083            if live_sessions.contains(&agent_session) {
2084                // Agent is still alive — skip.
2085                continue;
2086            }
2087
2088            // No agent session exists. The agent is dead regardless of
2089            // session tracking — hard restart, crash, or flag not persisted.
2090            // Reset to Routed so the dispatcher can re-spawn it.
2091            {
2092                tracing::warn!(
2093                    task_id = %task_id,
2094                    session = %agent_session,
2095                    "InProgress task has no active agent session — resetting to Routed"
2096                );
2097                match task_manager
2098                    .update_task_status_if(&external.id, Status::Routed, Status::InProgress)
2099                    .await
2100                {
2101                    Err(e) => {
2102                        tracing::error!(task_id = %task_id, err = %e, "failed to reset stale InProgress task — task may be stuck in InProgress indefinitely");
2103                    }
2104                    Ok(false) => {
2105                        tracing::debug!(
2106                            task_id = %task_id,
2107                            "stale InProgress reset skipped — task already transitioned (concurrent Done/Blocked/NeedsReview)"
2108                        );
2109                    }
2110                    Ok(true) => {
2111                        // Successfully reset to Routed
2112                    }
2113                }
2114            }
2115        }
2116    }
2117
2118    phases.push(("stale_in_progress", at.elapsed().as_millis()));
2119    at = Instant::now();
2120    // 5c. Auto-unblock tasks with recoverable failures.
2121    if let Err(e) =
2122        auto_unblock_blocked_tasks(repo, task_manager, store, dispatching, auto_merge_in_flight)
2123            .await
2124    {
2125        tracing::warn!(err = %e, "auto-unblock failed");
2126    }
2127
2128    phases.push(("auto_unblock", at.elapsed().as_millis()));
2129
2130    engine::log_phase_timings("sync", repo, &phases);
2131    Ok(())
2132}
2133
2134/**
2135 * Agent health is the same whichever project asks, so it runs once per sync pass rather than
2136 * once per project. Called after every project's `sync_tick`
2137 **/
2138pub(crate) async fn sync_shared_tail(router: &Arc<RwLock<Router>>, store: Option<&Arc<TaskStore>>) {
2139    let Some(store) = store else {
2140        return;
2141    };
2142    if !store.is_leader() {
2143        return;
2144    }
2145
2146    // Pre-emptive health check: refresh degraded-agent flags from the rate_limits table.
2147    // Clone what is needed out of the router first, so the write lock is not starved for the
2148    // duration of the DB query
2149    let (available_agents, config) = {
2150        let r = router.read().await;
2151        (r.available_agents.clone(), r.config.clone())
2152    };
2153    let model_checker = |agent: &str| -> bool {
2154        for comp in &["simple", "medium", "complex", "review"] {
2155            if config.has_available_model_for_complexity(agent, comp) {
2156                return true;
2157            }
2158        }
2159        false
2160    };
2161    refresh_degraded_agents(
2162        store,
2163        &available_agents,
2164        &model_checker,
2165        router_config::health_check_window_hours(),
2166        router_config::degraded_rate_limit_threshold(),
2167    )
2168    .await;
2169
2170    emit_degraded_agents_if_needed(&available_agents, &config, Some(store)).await;
2171}
2172
2173/// Scan for @mentions and handle them.
2174///
2175/// Checks recent issue comments for @orch (and legacy @orchestrator) mentions.
2176/// Unified comment scanner — handles both @mentions and slash commands in one pass.
2177///
2178/// For each comment, classifies it via [`classify_comment`] and dispatches:
2179/// - Slash commands → validate + execute (with sentinel task if it was an @mention)
2180/// - @mentions without commands → create internal task for agent to respond
2181/// - Everything else → skip
2182async fn scan_comments(
2183    backend: &Arc<dyn ExternalBackend>,
2184    store: Option<&Arc<TaskStore>>,
2185    repo: &str,
2186    task_manager: &Arc<TaskManager>,
2187    prefetched_comments: Option<&[Mention]>,
2188) -> anyhow::Result<()> {
2189    let current_user = match backend.get_authenticated_user().await {
2190        Ok(Some(u)) => format!("@{u}"),
2191        Ok(None) => {
2192            tracing::debug!("backend does not support user identity, skipping comment scan");
2193            return Ok(());
2194        }
2195        Err(e) => {
2196            tracing::warn!(err = %e, "failed to get current user, skipping comment scan");
2197            return Ok(());
2198        }
2199    };
2200
2201    let comments = if let Some(c) = prefetched_comments {
2202        c.to_vec()
2203    } else {
2204        let fallback = chrono::Utc::now() - chrono::Duration::hours(24);
2205        let since_str = match kv_get_prefer_store(store, "mentions_last_checked").await {
2206            Some(ts) => ts,
2207            None => fallback.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
2208        };
2209        match backend.get_mentions(&since_str).await {
2210            Ok(m) => m,
2211            Err(e) => {
2212                tracing::warn!(err = %e, "failed to get comments");
2213                return Ok(());
2214            }
2215        }
2216    };
2217
2218    // Dedup set: mention tasks already created (by source_id).
2219    let existing_mentions: HashSet<String> = if let Some(s) = store {
2220        match s.list_source_ids_by_source(repo, "mention", 30).await {
2221            Ok(ids) => ids.into_iter().collect(),
2222            Err(e) => {
2223                tracing::warn!(err = %e, "failed to load mention source IDs — skipping to prevent duplicates");
2224                return Ok(());
2225            }
2226        }
2227    } else {
2228        HashSet::new()
2229    };
2230
2231    // Lazily create GhHttp — only allocate when we actually need to make GitHub
2232    // API calls.  This avoids network initialization in test environments where
2233    // the code path never reaches an API call.
2234    let gh_cell: OnceCell<GhHttp> = OnceCell::new();
2235    let get_gh = || async { gh_cell.get_or_try_init(|| async { GhHttp::new() }).await };
2236
2237    // Pre-classify all comments up front so we can batch the is_pull_request
2238    // checks for CreateMentionTask entries before entering the main loop.
2239    let actions: Vec<CommentAction> = comments
2240        .iter()
2241        .map(|c| {
2242            classify_comment(
2243                &c.body,
2244                c.issue_url.as_deref(),
2245                &current_user,
2246                existing_mentions.contains(&c.id),
2247            )
2248        })
2249        .collect();
2250
2251    // Collect (comment_index, issue_num) for all CreateMentionTask entries that
2252    // need an is_pull_request check, then resolve them all concurrently with
2253    // join_all to avoid N × RTT serial API calls inside the loop.
2254    let pr_check_inputs: Vec<(usize, String)> = actions
2255        .iter()
2256        .enumerate()
2257        .filter_map(|(i, action)| {
2258            if let CommentAction::CreateMentionTask {
2259                issue_num: Some(num),
2260            } = action
2261            {
2262                Some((i, num.clone()))
2263            } else {
2264                None
2265            }
2266        })
2267        .collect();
2268
2269    // Only create GhHttp if we actually have PR checks to perform.
2270    let is_pr_values: Vec<bool> = if pr_check_inputs.is_empty() {
2271        Vec::new()
2272    } else {
2273        let gh = get_gh().await?;
2274        future::join_all(
2275            pr_check_inputs
2276                .iter()
2277                .map(|(_, num)| async move { gh.is_pull_request(repo, num).await }),
2278        )
2279        .await
2280    };
2281
2282    // Build a lookup map: comment_index → is_pr.
2283    let is_pr_map: HashMap<usize, bool> = pr_check_inputs
2284        .iter()
2285        .map(|(i, _)| *i)
2286        .zip(is_pr_values)
2287        .collect();
2288
2289    let mut cursor = MentionCursor::default();
2290
2291    for (comment_idx, (comment, action)) in comments.iter().zip(actions).enumerate() {
2292        match action {
2293            CommentAction::Skip => {
2294                cursor.advance(&comment.created_at);
2295            }
2296
2297            CommentAction::ExecuteCommand { command, issue_num } => {
2298                let store_opt: Option<Arc<dyn CommandStoreOps>> =
2299                    store.map(|s| Arc::clone(s) as Arc<dyn CommandStoreOps>);
2300                let gh = get_gh().await?;
2301                let outcome = validate_and_run_command(
2302                    backend,
2303                    gh,
2304                    repo,
2305                    &issue_num,
2306                    &command,
2307                    &comment.author,
2308                    &store_opt,
2309                    task_manager,
2310                )
2311                .await;
2312                match outcome {
2313                    // Validation hit a transient GitHub error: nothing ran and nothing
2314                    // was posted. Stop the cursor so the next tick retries this comment.
2315                    CommandOutcome::FetchFailed | CommandOutcome::CollaboratorCheckFailed => {
2316                        tracing::warn!(
2317                            comment_id = %comment.id,
2318                            command = %command,
2319                            "deferring slash command after a transient GitHub error"
2320                        );
2321                        cursor.block_on_gap();
2322                        break;
2323                    }
2324                    // The outcome comment (success or error) was already posted to
2325                    // GitHub, so re-processing would create duplicates.
2326                    CommandOutcome::Executed { .. }
2327                    | CommandOutcome::NotOpen { .. }
2328                    | CommandOutcome::NotCollaborator { .. } => cursor.advance(&comment.created_at),
2329                }
2330            }
2331
2332            CommentAction::ExecuteCommandForMention { command, .. } => {
2333                if let Err(e) = backend.acknowledge_mention(&comment.id).await {
2334                    tracing::debug!(err = %e, mention_id = %comment.id, "failed to acknowledge mention");
2335                    // Do NOT advance the cursor or call handle_slash_command — the GitHub
2336                    // reaction was never posted. Retry on next tick once the network
2337                    // glitch has resolved.
2338                } else {
2339                    // Parent lookup failure propagates via `?` — scan_comments returns early
2340                    // without advancing the cursor so the mention is retried on next sync.
2341                    let gh = get_gh().await?;
2342                    let advanced_safely = handle_slash_command(
2343                        backend,
2344                        store,
2345                        repo,
2346                        task_manager,
2347                        gh,
2348                        comment,
2349                        &command,
2350                        &mut cursor,
2351                    )
2352                    .await?;
2353                    if !advanced_safely {
2354                        cursor.block_on_gap();
2355                        break;
2356                    }
2357                }
2358            }
2359
2360            CommentAction::CreateMentionTask { issue_num } => {
2361                if let Err(e) = backend.acknowledge_mention(&comment.id).await {
2362                    tracing::debug!(err = %e, mention_id = %comment.id, "failed to acknowledge mention");
2363                    // Do NOT record the mention task or advance the cursor — the GitHub
2364                    // reaction was never posted. Retry on next tick once the network
2365                    // glitch has resolved.
2366                } else {
2367                    // Use the pre-fetched value — no serial API call here.
2368                    // issue_num may be None (e.g. bot mentioned with no issue URL), in
2369                    // which case is_pr_map has no entry; default to false (the None arm
2370                    // of the downstream match ignores is_pr entirely).
2371                    let is_pr = is_pr_map.get(&comment_idx).copied().unwrap_or(false);
2372
2373                    let (title, task_body) = match (&issue_num, is_pr) {
2374                        (Some(num), false) => (
2375                            format!("Respond to mention by @{} on task #{num}", comment.author),
2376                            format!(
2377                                "Mention by @{} on GitHub issue #{num}:\n\n{}\n\n---\nThis mention was posted on issue #{num}. Review the full issue to understand the context before responding.",
2378                                comment.author, comment.body
2379                            ),
2380                        ),
2381                        (Some(num), true) => (
2382                            format!("Respond to mention by @{} on PR #{num}", comment.author),
2383                            format!(
2384                                "Mention by @{} on GitHub PR #{num}:\n\n{}\n\n---\nThis mention was posted on PR #{num}. Review the full PR (diff, description, and comments) to understand the context before responding.",
2385                                comment.author, comment.body
2386                            ),
2387                        ),
2388                        (None, _) => (
2389                            format!("Respond to mention by @{}", comment.author),
2390                            format!("Mention by @{}:\n\n{}", comment.author, comment.body),
2391                        ),
2392                    };
2393
2394                    if let Some(s) = store {
2395                        // On DB lookup failure, do NOT record the mention task or advance
2396                        // the cursor — the mention will be retried on next sync.
2397                        let parent_id = match issue_num {
2398                            Some(ref num) => {
2399                                match resolve_mention_parent_id(s, repo, num, is_pr).await {
2400                                    Ok(id) => id,
2401                                    Err(e) => {
2402                                        tracing::warn!(
2403                                            mention_id = %comment.id,
2404                                            err = %e,
2405                                            "deferring mention task due to parent lookup failure"
2406                                        );
2407                                        return Err(anyhow::anyhow!(
2408                                            "deferring mention {} due to parent lookup failure",
2409                                            comment.id
2410                                        ));
2411                                    }
2412                                }
2413                            }
2414                            None => None,
2415                        };
2416                        if !record_mention_task(
2417                            s,
2418                            repo,
2419                            comment,
2420                            &title,
2421                            &task_body,
2422                            parent_id,
2423                            &mut cursor,
2424                        )
2425                        .await
2426                        {
2427                            cursor.block_on_gap();
2428                            break;
2429                        }
2430                    }
2431                }
2432            }
2433        }
2434    }
2435
2436    if let Some(ts) = cursor.into_last_safe_ts() {
2437        kv_set_prefer_store(store, "mentions_last_checked", &ts).await;
2438    }
2439
2440    Ok(())
2441}
2442
2443/// Per-agent degradation detail collected during the alerting check.
2444struct DegradedAgentDetail {
2445    /// Agent name (e.g. "claude", "codex").
2446    agent: String,
2447    /// Reason the agent is degraded: the stored cooldown reason when the agent
2448    /// itself is in cooldown, or `"no_available_model"` when all model pools
2449    /// are individually cooled.
2450    reason: String,
2451    /// Models that are individually in cooldown for this agent, deduped across
2452    /// all complexity tiers.
2453    cooled_models: Vec<String>,
2454}
2455
2456/// Per-agent pool health used for stale model pool detection.
2457struct AgentPoolHealth {
2458    agent: String,
2459    cooled_models: Vec<String>,
2460    persistent_failed_models: Vec<String>,
2461    total_configured_models: usize,
2462}
2463
2464/// Inspect router & cooldown state and emit metrics every tick.
2465///
2466/// - `metrics:orch.agents_degraded.count` is written on every call with the
2467///   current number of degraded agents (0 when healthy).
2468/// - When `count >= 3` a WARN log is emitted with full dimensions (agent
2469///   names, cooled models, cooldown reasons) and a dedicated alert metric
2470///   `metrics:orch.agents_degraded.alert` is set to `"1"`. The alert is
2471///   cleared to `"0"` when the count drops below the threshold.
2472pub(crate) async fn emit_degraded_agents_if_needed(
2473    available_agents: &[String],
2474    config: &RouterConfig,
2475    store: Option<&Arc<TaskStore>>,
2476) {
2477    // Edge-triggered: only log when the affected-agents set changes, so a
2478    // persistent condition doesn't flood the log every sync tick.
2479    const STALE_AGENTS_KV: &str = "metrics:orch.model_pool_stale_persistent.agents";
2480
2481    // Complexity tiers to check for configured models.
2482    const COMPLEXITIES: &[&str] = &["simple", "medium", "complex", "review"];
2483    const HEAVILY_COOLED_RATIO_THRESHOLD: f64 = 0.5;
2484
2485    let mut details: Vec<DegradedAgentDetail> = Vec::new();
2486    let mut pool_health: Vec<AgentPoolHealth> = Vec::new();
2487
2488    for agent in available_agents {
2489        let agent_in_cd = is_agent_in_cooldown(agent);
2490
2491        // Collect individually cooled models across all complexity tiers (deduped).
2492        let mut cooled_models: Vec<String> = Vec::new();
2493        let mut persistent_failed_models: Vec<String> = Vec::new();
2494        let mut seen_models = HashSet::new();
2495        for comp in COMPLEXITIES {
2496            if let Some(pool) = config.model_pool_for_complexity(agent, comp) {
2497                for model in pool {
2498                    if seen_models.insert(model.clone()) && is_model_in_cooldown(agent, &model) {
2499                        let key = format!("{agent}:{model}");
2500                        if matches!(
2501                            cooldown_reason(&key).as_deref(),
2502                            Some("persistent_model_error" | "model_not_found")
2503                        ) {
2504                            persistent_failed_models.push(model.clone());
2505                        }
2506                        cooled_models.push(model);
2507                    }
2508                }
2509            }
2510        }
2511        let total_configured_models = seen_models.len();
2512        pool_health.push(AgentPoolHealth {
2513            agent: agent.clone(),
2514            cooled_models: cooled_models.clone(),
2515            persistent_failed_models: persistent_failed_models.clone(),
2516            total_configured_models,
2517        });
2518
2519        // An agent is degraded if it is in agent-level cooldown OR has no
2520        // available (non-cooled) model across any complexity tier.
2521        let has_model = COMPLEXITIES
2522            .iter()
2523            .any(|comp| config.has_available_model_for_complexity(agent, comp));
2524
2525        if agent_in_cd || !has_model {
2526            let reason = if agent_in_cd {
2527                cooldown_reason(agent).unwrap_or_else(|| "agent_cooldown".to_string())
2528            } else {
2529                "no_available_model".to_string()
2530            };
2531            details.push(DegradedAgentDetail {
2532                agent: agent.clone(),
2533                reason,
2534                cooled_models,
2535            });
2536        }
2537    }
2538
2539    let count = details.len();
2540
2541    // Always persist the count metric so operators can scrape it every tick,
2542    // including when the count is 0.
2543    if let Err(e) = try_kv_set_prefer_store(
2544        store,
2545        "metrics:orch.agents_degraded.count",
2546        &count.to_string(),
2547    )
2548    .await
2549    {
2550        tracing::warn!(err = %e, "failed to persist degraded agents count metric");
2551    }
2552
2553    if count >= 3 {
2554        // Build structured dimension strings for the log.
2555        let degraded_agents: Vec<&str> = details.iter().map(|d| d.agent.as_str()).collect();
2556        let cooled_models_dim: Vec<String> = details
2557            .iter()
2558            .filter(|d| !d.cooled_models.is_empty())
2559            .map(|d| format!("{}:[{}]", d.agent, d.cooled_models.join(",")))
2560            .collect();
2561        let reasons_dim: Vec<String> = details
2562            .iter()
2563            .map(|d| format!("{}={}", d.agent, d.reason))
2564            .collect();
2565
2566        tracing::warn!(
2567            degraded_count = count,
2568            degraded_agents = ?degraded_agents,
2569            cooled_models = %cooled_models_dim.join("; "),
2570            cooldown_reasons = %reasons_dim.join("; "),
2571            "multi-agent degradation detected"
2572        );
2573
2574        // Dedicated alert metric: "1" while the threshold is exceeded.
2575        if let Err(e) =
2576            try_kv_set_prefer_store(store, "metrics:orch.agents_degraded.alert", "1").await
2577        {
2578            tracing::warn!(err = %e, "failed to persist degraded agents alert metric");
2579        }
2580    } else if let Err(e) =
2581        try_kv_set_prefer_store(store, "metrics:orch.agents_degraded.alert", "0").await
2582    {
2583        // Clear the alert metric when healthy.
2584        tracing::warn!(err = %e, "failed to clear degraded agents alert metric");
2585    }
2586
2587    // Additional operator signal for dead/stale model pools:
2588    // alert when any agent has at least 50% of configured models cooled and at
2589    // least one persistent model failure marker in cooldown reason.
2590    let heavily_cooled_agents: Vec<String> = pool_health
2591        .iter()
2592        .filter_map(|d| {
2593            if d.total_configured_models == 0 || d.persistent_failed_models.is_empty() {
2594                return None;
2595            }
2596            #[expect(
2597                clippy::cast_precision_loss,
2598                reason = "model counts are far below 2^52"
2599            )]
2600            let ratio = d.cooled_models.len() as f64 / d.total_configured_models as f64;
2601            (ratio >= HEAVILY_COOLED_RATIO_THRESHOLD).then(|| {
2602                format!(
2603                    "{}:{}/{}:{}",
2604                    d.agent,
2605                    d.cooled_models.len(),
2606                    d.total_configured_models,
2607                    d.persistent_failed_models.join(",")
2608                )
2609            })
2610        })
2611        .collect();
2612
2613    let current_dim = heavily_cooled_agents.join(",");
2614    let prev_dim = kv_get_prefer_store(store, STALE_AGENTS_KV)
2615        .await
2616        .unwrap_or_default();
2617
2618    if heavily_cooled_agents.is_empty() {
2619        if !prev_dim.is_empty() {
2620            tracing::info!("agent model pool stale condition cleared");
2621        }
2622        if let Err(e) = try_kv_set_prefer_store(store, STALE_AGENTS_KV, "").await {
2623            tracing::warn!(err = %e, "failed to clear stale model pool agents state");
2624        }
2625        if let Err(e) =
2626            try_kv_set_prefer_store(store, "metrics:orch.model_pool_stale_persistent.alert", "0")
2627                .await
2628        {
2629            tracing::warn!(err = %e, "failed to clear stale model pool alert metric");
2630        }
2631    } else {
2632        if current_dim != prev_dim {
2633            tracing::warn!(
2634                affected_agents = ?heavily_cooled_agents,
2635                "agent model pool appears stale: persistent model failures in heavily cooled pool"
2636            );
2637        }
2638        if let Err(e) = try_kv_set_prefer_store(store, STALE_AGENTS_KV, &current_dim).await {
2639            tracing::warn!(err = %e, "failed to persist stale model pool agents state");
2640        }
2641        if let Err(e) =
2642            try_kv_set_prefer_store(store, "metrics:orch.model_pool_stale_persistent.alert", "1")
2643                .await
2644        {
2645            tracing::warn!(err = %e, "failed to persist stale model pool alert metric");
2646        }
2647    }
2648}
2649
2650/// Ingest all active external tasks into the unified SQLite store.
2651///
2652/// Upserts each task so the store stays in sync with the backend.
2653/// Fetches all open issues (including unlabeled ones) so newly created
2654/// issues appear in the store immediately, not only after they get a
2655/// `status:*` label.  This is best-effort — individual task failures
2656/// are logged and skipped.
2657pub(crate) async fn ingest_external_tasks(
2658    backend: &Arc<dyn ExternalBackend>,
2659    repo: &str,
2660    store: &Arc<TaskStore>,
2661) -> anyhow::Result<()> {
2662    #[derive(Clone)]
2663    struct DuplicateTarget {
2664        id: String,
2665        status_label: String,
2666    }
2667
2668    let mut existing_by_title: HashMap<String, DuplicateTarget> = HashMap::new();
2669    let mut accepted_by_title: HashMap<String, DuplicateTarget> = HashMap::new();
2670
2671    let cutoff = (chrono::Utc::now() - chrono::Duration::hours(24))
2672        .format("%Y-%m-%dT%H:%M:%SZ")
2673        .to_string();
2674    match store.list_for_doctor(repo, &cutoff).await {
2675        Ok(recent) => {
2676            let mut insert_target = |task: &Task| {
2677                if task.origin == "internal" {
2678                    return;
2679                }
2680                let Some(ext_id) = task.external_id.as_ref() else {
2681                    return;
2682                };
2683                let status_label = task
2684                    .labels
2685                    .iter()
2686                    .find(|l| l.starts_with("status:"))
2687                    .cloned()
2688                    .unwrap_or_default();
2689                existing_by_title
2690                    .entry(task.title.clone())
2691                    .or_insert(DuplicateTarget {
2692                        id: ext_id.clone(),
2693                        status_label,
2694                    });
2695            };
2696
2697            // Prefer active tasks over recently done ones when selecting a canonical issue.
2698            for task in recent.iter().filter(|t| t.status != TaskStatus::Done) {
2699                insert_target(task);
2700            }
2701            for task in recent.iter().filter(|t| t.status == TaskStatus::Done) {
2702                insert_target(task);
2703            }
2704        }
2705        Err(e) => {
2706            tracing::warn!(repo, err = %e, "ingest: failed to load recent tasks for dedup");
2707        }
2708    }
2709
2710    // Fetch every open issue, with no `since` filter. The GitHub backend overrides
2711    // list_active_open_issues() to use one list_all_open_issues() request.
2712    //
2713    // A `since` cursor keys on updated_at, so an open issue with no task was skipped
2714    // forever once the cursor passed its updated_at, and the cursor had to be reset,
2715    // sentinelled and periodically ignored to recover (#3545, #3787, #3792). An
2716    // unfiltered listing has no such state and is cheaper too: its URL repeats, so
2717    // `get_all_pages` sends it conditionally and GitHub answers 304 while nothing
2718    // changed. A 304 does not count against the REST quota, a `since` fetch does.
2719    let all_tasks: Vec<(ExternalTask, Option<Status>)> =
2720        match backend.list_active_open_issues().await {
2721            Ok(tasks) => tasks,
2722            Err(e) => {
2723                tracing::warn!(
2724                    repo,
2725                    err = %e,
2726                    "ingest: failed to list open issues — no new issue is ingested this cycle"
2727                );
2728                return Ok(());
2729            }
2730        };
2731
2732    // Upsert into the store, collecting store IDs for batch status check
2733    // Also acknowledge newly detected issues (eyes reaction).
2734    let mut id_status_pairs: Vec<(i64, Status)> = Vec::new();
2735    // Collect (store_id, node_id) for newly ingested tasks so we can batch-fetch
2736    // estimate values from GitHub Projects after the loop.
2737    let mut new_task_node_ids: Vec<(i64, String)> = Vec::new();
2738    // Pre-load existing external IDs for this repo to avoid N+1 queries
2739    // (each get_by_external_id call is an individual SQL query). If the
2740    // lookup fails, fall back to an empty set so we conservatively treat
2741    // tasks as new (they will be upserted below).
2742    let existing_ext_ids: HashSet<String> = match store.existing_external_ids(repo).await {
2743        Ok(s) => s,
2744        Err(e) => {
2745            tracing::warn!(repo = repo, err = %e, "ingest: failed to load existing external ids — proceeding");
2746            HashSet::new()
2747        }
2748    };
2749    for (task, status) in &all_tasks {
2750        // Check if this task already exists in the store before upserting.
2751        // Use the pre-loaded HashSet to avoid issuing N individual queries.
2752        let is_new = !existing_ext_ids.contains(&task.id.0);
2753
2754        if is_new {
2755            let duplicate_target = existing_by_title
2756                .get(&task.title)
2757                .or_else(|| accepted_by_title.get(&task.title));
2758            if let Some(target) = duplicate_target
2759                && target.id != task.id.0
2760            {
2761                let label = target.status_label.as_str();
2762                let should_dedupe =
2763                    match backend.has_open_issue_with_title(&task.title, label).await {
2764                        Ok(true) => true,
2765                        Ok(false) => false,
2766                        Err(e) => {
2767                            tracing::warn!(
2768                                task_id = task.id.0,
2769                                err = %e,
2770                                "ingest: dedup check failed — defaulting to keep issue"
2771                            );
2772                            false
2773                        }
2774                    };
2775
2776                if should_dedupe {
2777                    let comment = format!(
2778                        "Duplicate of #{id} — closing to avoid duplicate work.{footer}",
2779                        id = target.id,
2780                        footer = engine::orch_footer()
2781                    );
2782                    if let Err(e) = backend.post_comment(&task.id, &comment).await {
2783                        tracing::warn!(
2784                            task_id = task.id.0,
2785                            err = %e,
2786                            "ingest: failed to comment on duplicate issue"
2787                        );
2788                    }
2789                    match backend.update_status(&task.id, Status::Done).await {
2790                        Ok(()) => {
2791                            tracing::info!(
2792                                task_id = task.id.0,
2793                                duplicate_of = target.id,
2794                                "ingest: closed duplicate issue"
2795                            );
2796                            continue;
2797                        }
2798                        Err(e) => {
2799                            tracing::warn!(
2800                                task_id = task.id.0,
2801                                err = %e,
2802                                "ingest: failed to close duplicate issue — falling through to ingest normally"
2803                            );
2804                        }
2805                    }
2806                }
2807            }
2808        }
2809
2810        match store.ensure_external_task(repo, task).await {
2811            Ok(store_id) => {
2812                if let Ok(number) = task.id.0.parse::<i64>()
2813                    && let Err(err) = dependencies::sync_issue_dependencies(
2814                        backend.as_ref(),
2815                        store,
2816                        store_id,
2817                        repo,
2818                        Some(number),
2819                        &task.body,
2820                    )
2821                    .await
2822                {
2823                    tracing::warn!(
2824                        task_id = task.id.0,
2825                        err = %err,
2826                        "ingest: dependency sync failed"
2827                    );
2828                }
2829                if let Some(s) = status {
2830                    id_status_pairs.push((store_id, *s));
2831                }
2832                // Acknowledge newly detected issues with an eyes reaction.
2833                if is_new {
2834                    let status_label = task
2835                        .labels
2836                        .iter()
2837                        .find(|l| l.starts_with("status:"))
2838                        .cloned()
2839                        .unwrap_or_default();
2840                    accepted_by_title
2841                        .entry(task.title.clone())
2842                        .or_insert(DuplicateTarget {
2843                            id: task.id.0.clone(),
2844                            status_label,
2845                        });
2846                    if let Err(e) = backend.acknowledge_issue(&task.id).await {
2847                        tracing::debug!(
2848                            task_id = task.id.0,
2849                            err = %e,
2850                            "ingest: acknowledgment failed"
2851                        );
2852                    }
2853                    // Sync to project board only for newly ingested tasks.
2854                    // Collect the returned node_id so we can batch-fetch estimates.
2855                    let task_status = status.unwrap_or(Status::New);
2856                    match backend.sync_to_project(&task.id, task_status).await {
2857                        Ok(Some(node_id)) => {
2858                            new_task_node_ids.push((store_id, node_id));
2859                        }
2860                        Ok(None) => {
2861                            // Project sync not configured or failed — no node_id to collect.
2862                        }
2863                        Err(e) => {
2864                            tracing::debug!(
2865                                task_id = task.id.0,
2866                                err = %e,
2867                                "ingest: project board sync failed"
2868                            );
2869                        }
2870                    }
2871                }
2872            }
2873            Err(e) => {
2874                tracing::debug!(task_id = task.id.0, ?e, "ingest: upsert failed");
2875            }
2876        }
2877    }
2878
2879    // Batch-fetch all upserted tasks in a single query, then sync status for NEW tasks.
2880    // Only sync status from backend → store for NEW tasks (first ingest).
2881    // Once a task exists in the store, its status is authoritative —
2882    // re-ingestion must not overwrite store-first status changes
2883    // (e.g., store has Routed but GitHub still shows New labels).
2884    if !id_status_pairs.is_empty() {
2885        let all_ids: Vec<i64> = id_status_pairs.iter().map(|(id, _)| *id).collect();
2886        let existing_map = match store.get_batch(&all_ids).await {
2887            Ok(map) => map,
2888            Err(e) => {
2889                tracing::warn!(err = %e, task_count = all_ids.len(), "ingest: get_batch failed — skipping initial status sync for newly ingested tasks this tick");
2890                return Ok(());
2891            }
2892        };
2893        for (store_id, status) in id_status_pairs {
2894            if let Some(existing) = existing_map.get(&store_id)
2895                && existing.status == TaskStatus::New
2896            {
2897                let db_status = status_to_task_status(status);
2898                if db_status != TaskStatus::New
2899                    && let Err(e) = store.update_status(store_id, db_status).await
2900                {
2901                    tracing::debug!(?e, "ingest: status sync failed");
2902                }
2903            }
2904        }
2905    }
2906
2907    // Batch-fetch estimate values from GitHub Projects for newly ingested tasks.
2908    // For each task where `tasks.estimate == 0`, populate it from the project board.
2909    if !new_task_node_ids.is_empty() {
2910        let node_ids: Vec<String> = new_task_node_ids.iter().map(|(_, n)| n.clone()).collect();
2911        match backend.get_project_item_estimates(&node_ids).await {
2912            Ok(estimates) => {
2913                for (store_id, node_id) in new_task_node_ids {
2914                    if let Some(&estimate) = estimates.get(&node_id)
2915                        && estimate > 0
2916                        && let Err(e) = store.set_estimate_if_zero(store_id, estimate).await
2917                    {
2918                        tracing::debug!(
2919                            store_id,
2920                            estimate,
2921                            err = %e,
2922                            "ingest: failed to set estimate from project"
2923                        );
2924                    }
2925                }
2926            }
2927            Err(e) => {
2928                tracing::debug!(
2929                    err = %e,
2930                    "ingest: project estimate fetch failed — skipping estimate sync this tick"
2931                );
2932            }
2933        }
2934    }
2935
2936    Ok(())
2937}
2938
2939#[cfg(test)]
2940mod tests {
2941    use super::*;
2942    use super::{CommentAction, MentionCursor, classify_comment};
2943    use crate::backends::test_helpers::NoopBackend;
2944    use crate::backends::{ExternalId, ExternalTask, Mention, Status};
2945    use crate::engine::auto_merge::{CI_FAILURE_BEFORE_REVIEW_STAGE, ci_failure_limit_reason};
2946    use crate::engine::commands::OwnerCommand;
2947    use crate::engine::cooldown::record_persistent_model_failure;
2948    use crate::engine::cooldown::set_agent_cooldown;
2949    use crate::engine::dispatch_guard::DispatchGuard;
2950    use crate::engine::router::Router;
2951    use crate::engine::router::RouterConfig;
2952    use crate::github::token::ENV_LOCK;
2953    use crate::github::types::GitHubIssue;
2954    use crate::github::types::GitHubUser;
2955    use crate::store::NewTask;
2956    use crate::store::{RunTokenUsage, TaskStore};
2957    use async_trait::async_trait;
2958    use serial_test::serial;
2959    use std::env;
2960    use std::slice;
2961    use std::sync::Arc;
2962    use std::sync::atomic::AtomicUsize;
2963    use std::sync::atomic::Ordering;
2964    use tokio::sync::Mutex;
2965    use tokio::sync::oneshot;
2966    use wiremock::matchers::{method, path};
2967    use wiremock::{Mock, MockServer, ResponseTemplate};
2968
2969    // ── ingest_external_tasks tests ─────────────────────────────────────────
2970
2971    /// Mock backend that returns configurable tasks per status.
2972    struct IngestMockBackend {
2973        /// Stored as (status_label, tasks) pairs since Status doesn't impl Hash.
2974        tasks: Vec<(String, Vec<ExternalTask>)>,
2975        dedup_result: bool,
2976        comments: Mutex<Vec<(String, String)>>,
2977        status_updates: Mutex<Vec<(String, Status)>>,
2978        project_syncs: Mutex<Vec<(String, Status)>>,
2979        project_reconciliations: AtomicUsize,
2980        /// Counts `list_active_open_issues` calls.
2981        list_calls: AtomicUsize,
2982    }
2983
2984    impl IngestMockBackend {
2985        fn with_tasks(tasks: Vec<(Status, ExternalTask)>) -> Arc<Self> {
2986            Self::with_tasks_and_dedup(tasks, false)
2987        }
2988
2989        fn with_tasks_and_dedup(
2990            tasks: Vec<(Status, ExternalTask)>,
2991            dedup_result: bool,
2992        ) -> Arc<Self> {
2993            let mut grouped: Vec<(String, Vec<ExternalTask>)> = Vec::new();
2994            for (status, task) in tasks {
2995                let label = status.as_label().to_string();
2996                if let Some(entry) = grouped.iter_mut().find(|(l, _)| l == &label) {
2997                    entry.1.push(task);
2998                } else {
2999                    grouped.push((label, vec![task]));
3000                }
3001            }
3002            Arc::new(Self {
3003                tasks: grouped,
3004                dedup_result,
3005                comments: Mutex::new(Vec::new()),
3006                status_updates: Mutex::new(Vec::new()),
3007                project_syncs: Mutex::new(Vec::new()),
3008                project_reconciliations: AtomicUsize::new(0),
3009                list_calls: AtomicUsize::new(0),
3010            })
3011        }
3012    }
3013
3014    #[async_trait]
3015    impl ExternalBackend for IngestMockBackend {
3016        fn name(&self) -> &'static str {
3017            "ingest-mock"
3018        }
3019        async fn create_task(&self, _: &str, _: &str, _: &[String]) -> anyhow::Result<ExternalId> {
3020            Ok(ExternalId("new".into()))
3021        }
3022        async fn get_task(&self, _: &ExternalId) -> anyhow::Result<ExternalTask> {
3023            anyhow::bail!("not implemented")
3024        }
3025        async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
3026            let label = status.as_label().to_string();
3027            Ok(self
3028                .tasks
3029                .iter()
3030                .find(|(l, _)| l == &label)
3031                .map(|(_, t)| t.clone())
3032                .unwrap_or_default())
3033        }
3034        async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
3035            Ok(vec![])
3036        }
3037        async fn list_active_open_issues(
3038            &self,
3039        ) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
3040            self.list_calls.fetch_add(1, Ordering::Relaxed);
3041            let mut result = Vec::new();
3042            for (label, tasks) in &self.tasks {
3043                let status = match label.as_str() {
3044                    "status:routed" => Some(Status::Routed),
3045                    "status:in_progress" => Some(Status::InProgress),
3046                    "status:needs_review" => Some(Status::NeedsReview),
3047                    "status:in_review" => Some(Status::InReview),
3048                    "status:approved" => Some(Status::Approved),
3049                    "status:blocked" => Some(Status::Blocked),
3050                    _ => None,
3051                };
3052                for task in tasks {
3053                    result.push((task.clone(), status));
3054                }
3055            }
3056            Ok(result)
3057        }
3058        async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()> {
3059            self.comments
3060                .lock()
3061                .await
3062                .push((id.0.clone(), body.to_string()));
3063            Ok(())
3064        }
3065        async fn set_labels(&self, _: &ExternalId, _: &[String]) -> anyhow::Result<()> {
3066            Ok(())
3067        }
3068        async fn remove_label(&self, _: &ExternalId, _: &str) -> anyhow::Result<()> {
3069            Ok(())
3070        }
3071        async fn get_sub_issues(&self, _: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
3072            Ok(vec![])
3073        }
3074        async fn health_check(&self) -> anyhow::Result<()> {
3075            Ok(())
3076        }
3077        async fn get_mentions(&self, _: &str) -> anyhow::Result<Vec<Mention>> {
3078            Ok(vec![])
3079        }
3080        async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
3081            self.status_updates
3082                .lock()
3083                .await
3084                .push((id.0.clone(), status));
3085            Ok(())
3086        }
3087
3088        async fn has_open_issue_with_title(&self, _: &str, _: &str) -> anyhow::Result<bool> {
3089            Ok(self.dedup_result)
3090        }
3091
3092        async fn sync_to_project(
3093            &self,
3094            id: &ExternalId,
3095            status: Status,
3096        ) -> anyhow::Result<Option<String>> {
3097            self.project_syncs.lock().await.push((id.0.clone(), status));
3098            Ok(None) // Mock doesn't have real node IDs.
3099        }
3100
3101        async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
3102            self.project_reconciliations.fetch_add(1, Ordering::Relaxed);
3103            Ok(())
3104        }
3105    }
3106
3107    fn make_ext_task(id: &str, title: &str) -> ExternalTask {
3108        ExternalTask {
3109            id: ExternalId(id.to_string()),
3110            title: title.to_string(),
3111            body: String::new(),
3112            state: "open".to_string(),
3113            labels: vec![],
3114            author: "user".to_string(),
3115            created_at: "2026-01-01T00:00:00Z".to_string(),
3116            updated_at: "2026-01-01T00:00:00Z".to_string(),
3117            url: format!("https://github.com/owner/repo/issues/{id}"),
3118        }
3119    }
3120
3121    #[serial(cooldown_state)]
3122    #[tokio::test]
3123    async fn ingest_upserts_tasks_into_store() {
3124        cooldown::reset_global_state().await;
3125        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![
3126            (Status::New, make_ext_task("1", "First issue")),
3127            (Status::InProgress, make_ext_task("2", "Second issue")),
3128        ]);
3129        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3130
3131        ingest_external_tasks(&backend, "owner/repo", &store)
3132            .await
3133            .unwrap();
3134
3135        // Both tasks should be in the store
3136        let all = store.list_all("owner/repo").await.unwrap();
3137        assert_eq!(all.len(), 2);
3138
3139        let task1 = store
3140            .get_by_external_id("owner/repo", "1")
3141            .await
3142            .unwrap()
3143            .unwrap();
3144        assert_eq!(task1.title, "First issue");
3145        assert_eq!(task1.status, TaskStatus::New);
3146
3147        let task2 = store
3148            .get_by_external_id("owner/repo", "2")
3149            .await
3150            .unwrap()
3151            .unwrap();
3152        assert_eq!(task2.title, "Second issue");
3153        assert_eq!(task2.status, TaskStatus::InProgress);
3154    }
3155
3156    #[serial(cooldown_state)]
3157    #[tokio::test]
3158    async fn ingest_takes_every_open_issue_whatever_its_age_or_the_last_ingest() {
3159        // An issue opened after a restart reaches the store on the first sync, and so does
3160        // one whose updated_at predates any window a `since` cursor would have used. The
3161        // ingest keeps no cursor, so a stale KV value from an older build changes nothing.
3162        cooldown::reset_global_state().await;
3163        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3164        store
3165            .kv_set("issues_last_ingested:owner/repo", "2026-10-26T00:00:00Z")
3166            .await
3167            .unwrap();
3168
3169        let mut old = make_ext_task("73", "Filed weeks ago, never ingested");
3170        old.updated_at = "2026-01-01T00:00:00Z".to_string();
3171        let backend = IngestMockBackend::with_tasks(vec![(Status::New, old)]);
3172        let backend_dyn: Arc<dyn ExternalBackend> = Arc::<IngestMockBackend>::clone(&backend);
3173        ingest_external_tasks(&backend_dyn, "owner/repo", &store)
3174            .await
3175            .unwrap();
3176        assert!(
3177            store
3178                .get_by_external_id("owner/repo", "73")
3179                .await
3180                .unwrap()
3181                .is_some()
3182        );
3183
3184        // A second sync, standing in for the one right after a restart, sees a new issue.
3185        let backend = IngestMockBackend::with_tasks(vec![(
3186            Status::New,
3187            make_ext_task("78", "Opened after the restart"),
3188        )]);
3189        let backend_dyn: Arc<dyn ExternalBackend> = Arc::<IngestMockBackend>::clone(&backend);
3190        ingest_external_tasks(&backend_dyn, "owner/repo", &store)
3191            .await
3192            .unwrap();
3193        assert_eq!(
3194            backend.list_calls.load(Ordering::Relaxed),
3195            1,
3196            "one sync is one listing"
3197        );
3198        assert!(
3199            store
3200                .get_by_external_id("owner/repo", "78")
3201                .await
3202                .unwrap()
3203                .is_some()
3204        );
3205        assert_eq!(
3206            store
3207                .kv_get("issues_last_ingested:owner/repo")
3208                .await
3209                .unwrap()
3210                .as_deref(),
3211            Some("2026-10-26T00:00:00Z"),
3212            "the ingest must keep no cursor, so a stale one is never read or advanced"
3213        );
3214    }
3215
3216    #[serial(cooldown_state)]
3217    #[tokio::test]
3218    async fn ingest_updates_existing_tasks() {
3219        cooldown::reset_global_state().await;
3220        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![(
3221            Status::Routed,
3222            make_ext_task("42", "Updated title"),
3223        )]);
3224        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3225
3226        // Pre-create the task
3227        store
3228            .create(&NewTask {
3229                external_id: Some("42".to_string()),
3230                repo: "owner/repo".to_string(),
3231                origin: "github".to_string(),
3232                title: "Original title".to_string(),
3233                ..Default::default()
3234            })
3235            .await
3236            .unwrap();
3237
3238        ingest_external_tasks(&backend, "owner/repo", &store)
3239            .await
3240            .unwrap();
3241
3242        // Should have updated the title
3243        let task = store
3244            .get_by_external_id("owner/repo", "42")
3245            .await
3246            .unwrap()
3247            .unwrap();
3248        assert_eq!(task.title, "Updated title");
3249        assert_eq!(task.status, TaskStatus::Routed);
3250    }
3251
3252    #[serial(cooldown_state)]
3253    #[tokio::test]
3254    async fn ingest_closes_duplicate_titles() {
3255        cooldown::reset_global_state().await;
3256
3257        let backend = IngestMockBackend::with_tasks_and_dedup(
3258            vec![(Status::New, make_ext_task("2", "Duplicate issue"))],
3259            true,
3260        );
3261        let backend_dyn: Arc<dyn ExternalBackend> = Arc::<IngestMockBackend>::clone(&backend);
3262        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3263
3264        store
3265            .create(&NewTask {
3266                external_id: Some("1".to_string()),
3267                repo: "owner/repo".to_string(),
3268                origin: "github".to_string(),
3269                title: "Duplicate issue".to_string(),
3270                labels: vec!["status:new".to_string()],
3271                ..Default::default()
3272            })
3273            .await
3274            .unwrap();
3275
3276        ingest_external_tasks(&backend_dyn, "owner/repo", &store)
3277            .await
3278            .unwrap();
3279
3280        let all = store.list_all("owner/repo").await.unwrap();
3281        assert_eq!(all.len(), 1);
3282
3283        let comments = backend.comments.lock().await;
3284        assert_eq!(comments.len(), 1);
3285        assert!(comments[0].1.contains("Duplicate of #1"));
3286
3287        let status_updates = backend.status_updates.lock().await;
3288        assert_eq!(status_updates.len(), 1);
3289        assert_eq!(status_updates[0].0, "2");
3290        assert_eq!(status_updates[0].1, Status::Done);
3291    }
3292
3293    #[serial(cooldown_state)]
3294    #[tokio::test]
3295    async fn ingest_handles_empty_backend() {
3296        cooldown::reset_global_state().await;
3297        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
3298        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3299
3300        // Should not error on empty backend
3301        let result = ingest_external_tasks(&backend, "owner/repo", &store).await;
3302        assert!(result.is_ok());
3303
3304        let all = store.list_all("owner/repo").await.unwrap();
3305        assert!(all.is_empty());
3306    }
3307
3308    #[serial(cooldown_state)]
3309    #[tokio::test]
3310    async fn ingest_syncs_status_correctly_across_statuses() {
3311        cooldown::reset_global_state().await;
3312        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![
3313            (Status::New, make_ext_task("1", "New")),
3314            (Status::Routed, make_ext_task("2", "Routed")),
3315            (Status::InProgress, make_ext_task("3", "InProgress")),
3316            (Status::NeedsReview, make_ext_task("4", "NeedsReview")),
3317            (Status::InReview, make_ext_task("5", "InReview")),
3318            (Status::Blocked, make_ext_task("6", "Blocked")),
3319        ]);
3320        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3321
3322        ingest_external_tasks(&backend, "owner/repo", &store)
3323            .await
3324            .unwrap();
3325
3326        let counts = store.status_counts("owner/repo").await.unwrap();
3327        assert_eq!(counts.get("new"), Some(&1));
3328        assert_eq!(counts.get("routed"), Some(&1));
3329        assert_eq!(counts.get("in_progress"), Some(&1));
3330        assert_eq!(counts.get("needs_review"), Some(&1));
3331        assert_eq!(counts.get("in_review"), Some(&1));
3332        assert_eq!(counts.get("blocked"), Some(&1));
3333    }
3334
3335    #[serial(cooldown_state)]
3336    #[tokio::test]
3337    async fn ingest_does_not_overwrite_store_authoritative_status() {
3338        cooldown::reset_global_state().await;
3339        // Backend reports task as New (GitHub labels haven't caught up yet)
3340        let backend: Arc<dyn ExternalBackend> =
3341            IngestMockBackend::with_tasks(vec![(Status::New, make_ext_task("99", "My task"))]);
3342        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3343
3344        // Pre-create the task and advance it to Routed in the store
3345        let id = store
3346            .create(&NewTask {
3347                external_id: Some("99".to_string()),
3348                repo: "owner/repo".to_string(),
3349                origin: "github".to_string(),
3350                title: "My task".to_string(),
3351                ..Default::default()
3352            })
3353            .await
3354            .unwrap();
3355        store.update_status(id, TaskStatus::Routed).await.unwrap();
3356
3357        // Ingest should NOT overwrite Routed back to New
3358        ingest_external_tasks(&backend, "owner/repo", &store)
3359            .await
3360            .unwrap();
3361
3362        let task = store.get(id).await.unwrap();
3363        assert_eq!(
3364            task.status,
3365            TaskStatus::Routed,
3366            "ingest must not overwrite store-authoritative status"
3367        );
3368    }
3369
3370    #[serial(cooldown_state)]
3371    #[tokio::test]
3372    async fn ingest_sync_to_project_called_only_for_new_tasks() {
3373        cooldown::reset_global_state().await;
3374
3375        // Two tasks: "10" is pre-existing, "11" is new.
3376        let backend = IngestMockBackend::with_tasks(vec![
3377            (Status::New, make_ext_task("10", "Existing task")),
3378            (Status::New, make_ext_task("11", "New task")),
3379        ]);
3380        let backend_dyn: Arc<dyn ExternalBackend> = Arc::<IngestMockBackend>::clone(&backend);
3381        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3382
3383        // Pre-insert task "10" so it already exists in the store.
3384        store
3385            .create(&NewTask {
3386                external_id: Some("10".to_string()),
3387                repo: "owner/repo".to_string(),
3388                origin: "github".to_string(),
3389                title: "Existing task".to_string(),
3390                ..Default::default()
3391            })
3392            .await
3393            .unwrap();
3394
3395        ingest_external_tasks(&backend_dyn, "owner/repo", &store)
3396            .await
3397            .unwrap();
3398
3399        let syncs = backend.project_syncs.lock().await;
3400        // Only the new task "11" should trigger sync_to_project — not the pre-existing "10".
3401        assert_eq!(
3402            syncs.len(),
3403            1,
3404            "sync_to_project must be called exactly once (for new task only), got: {syncs:?}"
3405        );
3406        assert_eq!(syncs[0].0, "11", "sync_to_project must target the new task");
3407    }
3408
3409    #[serial(cooldown_state)]
3410    #[tokio::test]
3411    async fn ingest_handles_mixed_labeled_and_unlabeled_open_issues() {
3412        // Simulate a backend where some issues have no status label (routable/unlabeled)
3413        // and others carry active status labels.  Both kinds must be ingested and the
3414        // store status must reflect the label where present.
3415        struct MixedBackend;
3416
3417        #[async_trait]
3418        impl ExternalBackend for MixedBackend {
3419            fn name(&self) -> &'static str {
3420                "mixed"
3421            }
3422            async fn create_task(
3423                &self,
3424                _: &str,
3425                _: &str,
3426                _: &[String],
3427            ) -> anyhow::Result<ExternalId> {
3428                Ok(ExternalId("x".into()))
3429            }
3430            async fn get_task(&self, _: &ExternalId) -> anyhow::Result<ExternalTask> {
3431                anyhow::bail!("not implemented")
3432            }
3433            async fn list_by_status(&self, _: Status) -> anyhow::Result<Vec<ExternalTask>> {
3434                Ok(vec![])
3435            }
3436            /// Return a mix: one unlabeled (no status) + one labeled in_progress.
3437            async fn list_active_open_issues(
3438                &self,
3439            ) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
3440                Ok(vec![
3441                    (make_ext_task("100", "Unlabeled routable"), None),
3442                    (
3443                        make_ext_task("101", "In progress issue"),
3444                        Some(Status::InProgress),
3445                    ),
3446                ])
3447            }
3448            async fn post_comment(&self, _: &ExternalId, _: &str) -> anyhow::Result<()> {
3449                Ok(())
3450            }
3451            async fn set_labels(&self, _: &ExternalId, _: &[String]) -> anyhow::Result<()> {
3452                Ok(())
3453            }
3454            async fn remove_label(&self, _: &ExternalId, _: &str) -> anyhow::Result<()> {
3455                Ok(())
3456            }
3457            async fn get_sub_issues(&self, _: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
3458                Ok(vec![])
3459            }
3460            async fn health_check(&self) -> anyhow::Result<()> {
3461                Ok(())
3462            }
3463            async fn get_mentions(&self, _: &str) -> anyhow::Result<Vec<Mention>> {
3464                Ok(vec![])
3465            }
3466            async fn update_status(&self, _: &ExternalId, _: Status) -> anyhow::Result<()> {
3467                Ok(())
3468            }
3469            async fn has_open_issue_with_title(&self, _: &str, _: &str) -> anyhow::Result<bool> {
3470                Ok(false)
3471            }
3472            async fn sync_to_project(
3473                &self,
3474                _: &ExternalId,
3475                _: Status,
3476            ) -> anyhow::Result<Option<String>> {
3477                Ok(None)
3478            }
3479        }
3480
3481        cooldown::reset_global_state().await;
3482
3483        let backend: Arc<dyn ExternalBackend> = Arc::new(MixedBackend);
3484        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3485
3486        ingest_external_tasks(&backend, "owner/repo", &store)
3487            .await
3488            .unwrap();
3489
3490        let all = store.list_all("owner/repo").await.unwrap();
3491        assert_eq!(all.len(), 2, "both issues must be ingested");
3492
3493        let unlabeled = store
3494            .get_by_external_id("owner/repo", "100")
3495            .await
3496            .unwrap()
3497            .unwrap();
3498        assert_eq!(
3499            unlabeled.status,
3500            TaskStatus::New,
3501            "unlabeled issue should start as New"
3502        );
3503
3504        let in_progress = store
3505            .get_by_external_id("owner/repo", "101")
3506            .await
3507            .unwrap()
3508            .unwrap();
3509        assert_eq!(
3510            in_progress.status,
3511            TaskStatus::InProgress,
3512            "labeled in_progress issue must be synced to InProgress"
3513        );
3514    }
3515
3516    // ── kv_get_prefer_store / kv_set_prefer_store ────────────────────
3517
3518    #[serial(cooldown_state)]
3519    #[tokio::test]
3520    async fn kv_get_prefer_store_reads_from_store() {
3521        cooldown::reset_global_state().await;
3522        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3523
3524        store.kv_set("k1", "store_val").await.unwrap();
3525
3526        let opt = Some(&store);
3527        let val = kv_get_prefer_store(opt, "k1").await;
3528        assert_eq!(val.as_deref(), Some("store_val"));
3529    }
3530
3531    #[serial(cooldown_state)]
3532    #[tokio::test]
3533    async fn kv_get_prefer_store_returns_none_without_store() {
3534        cooldown::reset_global_state().await;
3535        let opt: Option<&Arc<TaskStore>> = None;
3536        let val = kv_get_prefer_store(opt, "k2").await;
3537        assert_eq!(val, None);
3538    }
3539
3540    #[serial(cooldown_state)]
3541    #[tokio::test]
3542    async fn kv_set_prefer_store_writes_to_store() {
3543        cooldown::reset_global_state().await;
3544        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3545
3546        let opt = Some(&store);
3547        kv_set_prefer_store(opt, "k3", "val3").await;
3548
3549        assert_eq!(store.kv_get("k3").await.unwrap().as_deref(), Some("val3"));
3550    }
3551
3552    #[serial(cooldown_state)]
3553    #[tokio::test]
3554    async fn kv_set_prefer_store_noop_without_store() {
3555        cooldown::reset_global_state().await;
3556        let opt: Option<&Arc<TaskStore>> = None;
3557        // Should not panic
3558        kv_set_prefer_store(opt, "k4", "val4").await;
3559    }
3560
3561    // ── try_kv_get_prefer_store / try_kv_set_prefer_store ────────────────
3562
3563    #[serial(cooldown_state)]
3564    #[tokio::test]
3565    async fn try_kv_get_prefer_store_returns_value_from_store() {
3566        cooldown::reset_global_state().await;
3567        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3568        store.kv_set("try_k1", "try_val1").await.unwrap();
3569
3570        let opt = Some(&store);
3571        let result = try_kv_get_prefer_store(opt, "try_k1").await;
3572        assert_eq!(result.unwrap().as_deref(), Some("try_val1"));
3573    }
3574
3575    #[serial(cooldown_state)]
3576    #[tokio::test]
3577    async fn try_kv_get_prefer_store_returns_none_for_missing_key() {
3578        cooldown::reset_global_state().await;
3579        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3580        let opt = Some(&store);
3581
3582        let result = try_kv_get_prefer_store(opt, "nonexistent_key").await;
3583        assert_eq!(result.unwrap(), None); // Key doesn't exist, but query succeeded
3584    }
3585
3586    #[serial(cooldown_state)]
3587    #[tokio::test]
3588    async fn try_kv_get_prefer_store_returns_none_without_store() {
3589        cooldown::reset_global_state().await;
3590        let opt: Option<&Arc<TaskStore>> = None;
3591        let result = try_kv_get_prefer_store(opt, "try_k2").await;
3592        assert_eq!(result.unwrap(), None);
3593    }
3594
3595    #[serial(cooldown_state)]
3596    #[tokio::test]
3597    async fn try_kv_set_prefer_store_writes_to_store() {
3598        cooldown::reset_global_state().await;
3599        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3600        let opt = Some(&store);
3601
3602        let result = try_kv_set_prefer_store(opt, "try_k3", "try_val3").await;
3603        assert!(result.is_ok());
3604        assert_eq!(
3605            store.kv_get("try_k3").await.unwrap().as_deref(),
3606            Some("try_val3")
3607        );
3608    }
3609
3610    #[serial(cooldown_state)]
3611    #[tokio::test]
3612    async fn try_kv_set_prefer_store_ok_without_store() {
3613        cooldown::reset_global_state().await;
3614        let opt: Option<&Arc<TaskStore>> = None;
3615        // Should not error - best effort when store unavailable
3616        let result = try_kv_set_prefer_store(opt, "try_k4", "try_val4").await;
3617        assert!(result.is_ok());
3618    }
3619
3620    // ── dispatching lock tests ──────────────────────────────────────────
3621
3622    #[serial(cooldown_state)]
3623    #[test]
3624    fn dispatching_set_blocks_duplicate_processing() {
3625        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
3626
3627        let repo = "owner/repo";
3628        let task_id = "42";
3629        let dispatch_key = format!("{repo}/{task_id}");
3630
3631        // Initially not in the map
3632        assert!(!dispatching.contains_key(&dispatch_key));
3633
3634        // Insert — simulates dispatch starting
3635        dispatching.insert(dispatch_key.clone(), task_id.to_string());
3636
3637        // Now should be blocked
3638        assert!(
3639            dispatching.contains_key(&dispatch_key),
3640            "task should be locked while dispatching"
3641        );
3642
3643        // Remove — simulates review completion
3644        dispatching.remove(&dispatch_key);
3645
3646        // Now should be free again
3647        assert!(
3648            !dispatching.contains_key(&dispatch_key),
3649            "task should be unlocked after review completes"
3650        );
3651    }
3652
3653    #[serial(cooldown_state)]
3654    #[test]
3655    fn dispatching_set_does_not_block_other_tasks() {
3656        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
3657
3658        let repo = "owner/repo";
3659
3660        // Lock task 42
3661        let key_42 = format!("{repo}/42");
3662        dispatching.insert(key_42.clone(), "42".to_string());
3663
3664        // Task 43 should NOT be blocked
3665        let key_43 = format!("{repo}/43");
3666        assert!(
3667            dispatching.contains_key(&key_42),
3668            "task 42 should be locked"
3669        );
3670        assert!(
3671            !dispatching.contains_key(&key_43),
3672            "task 43 should not be locked"
3673        );
3674    }
3675
3676    /// Regression test for a6d8b9a.
3677    ///
3678    /// Before the fix, `sync_tick` step 5 transitioned a task to `InReview` and then
3679    /// spawned a `tokio::spawn` review agent WITHOUT first inserting the `dispatch_key`
3680    /// into the dispatching set. This created a window where `review_open_prs` (step 4)
3681    /// in a concurrent sync tick could see the task as `InReview`, find the key absent,
3682    /// and re-dispatch it — silently discarding human `CHANGES_REQUESTED` feedback when
3683    /// the review agent later completed and marked the task `Done`.
3684    ///
3685    /// The fix: insert `dispatch_key` BEFORE `tokio::spawn`, remove it AFTER the future
3686    /// completes. This test verifies that invariant using tokio channels to synchronize
3687    /// with a simulated concurrent caller (review_open_prs).
3688    #[serial(cooldown_state)]
3689    #[tokio::test]
3690    async fn dispatch_key_held_during_review_agent_execution() {
3691        cooldown::reset_global_state().await;
3692
3693        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
3694
3695        let dispatch_key = "owner/repo/42".to_string();
3696
3697        // Step 1: insert before spawning — this is the invariant added by a6d8b9a.
3698        dispatching.insert(dispatch_key.clone(), "42".to_string());
3699
3700        let (agent_started_tx, agent_started_rx) = oneshot::channel::<()>();
3701        let (check_done_tx, check_done_rx) = oneshot::channel::<()>();
3702
3703        let dispatching_agent = Arc::clone(&dispatching);
3704        let key_agent = dispatch_key.clone();
3705
3706        // Step 2: spawn review agent — key is ALREADY in the set (fix invariant holds).
3707        let review_task = tokio::spawn(async move {
3708            agent_started_tx.send(()).unwrap();
3709            // Simulate review agent work — hold until the concurrent check is done.
3710            check_done_rx.await.unwrap();
3711            // Remove from dispatching set on completion (mirror of tick.rs/sync.rs).
3712            dispatching_agent.remove(&key_agent);
3713        });
3714
3715        // Step 3: concurrent review_open_prs check — simulates step 4 of another
3716        // sync_tick invocation running while the review agent is still active.
3717        agent_started_rx.await.unwrap();
3718        assert!(
3719            dispatching.contains_key(&dispatch_key),
3720            "dispatch_key must be visible in the dispatching set while the review \
3721             agent is running — without the a6d8b9a fix, review_open_prs would see \
3722             the key absent and re-dispatch the task, silently dropping \
3723             CHANGES_REQUESTED feedback"
3724        );
3725
3726        // Step 4: review agent completes.
3727        check_done_tx.send(()).unwrap();
3728        review_task.await.unwrap();
3729
3730        // Step 5: key released — review_open_prs can now act on the task if needed.
3731        assert!(
3732            !dispatching.contains_key(&dispatch_key),
3733            "dispatch_key must be removed from the dispatching set after the \
3734             review agent completes so subsequent sync ticks can process the task"
3735        );
3736    }
3737
3738    /// Regression test for issue #833.
3739    ///
3740    /// Before the fix, `dispatch_key` was inserted into the `dispatching` HashSet
3741    /// *outside* the spawned task but removed *inside* it.  When the spawned async
3742    /// block panicked (e.g. an `unwrap()` inside `review_and_merge`), Tokio caught
3743    /// the panic and terminated the task without running the cleanup code, leaving
3744    /// the key in the set permanently.  Subsequent stuck-task recovery would reset
3745    /// the task to `NeedsReview`, but the subscriber/sync would see the key still
3746    /// present and skip it forever — a permanent review loop until service restart.
3747    ///
3748    /// The fix introduces `DispatchGuard`, a RAII wrapper whose `Drop` impl removes
3749    /// the key unconditionally, even when the task unwinds via panic.
3750    #[serial(cooldown_state)]
3751    #[tokio::test]
3752    async fn dispatch_guard_releases_key_on_panic() {
3753        cooldown::reset_global_state().await;
3754
3755        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
3756        let key = "owner/repo/42".to_string();
3757
3758        // Insert key before spawn — mirrors the production invariant established
3759        // by the a6d8b9a fix (key must be visible before the spawn so concurrent
3760        // review_open_prs callers see it and skip the task).
3761        dispatching.insert(key.clone(), "42".to_string());
3762
3763        // Create the guard (takes ownership of the removal obligation).
3764        let guard = DispatchGuard::new(Arc::clone(&dispatching), key.clone());
3765
3766        // Spawn a task that panics before the normal completion path.
3767        let handle = tokio::spawn(async move {
3768            let _guard = guard; // moved in; Drop removes key whether we panic or not
3769            panic!("simulated panic inside review_and_merge");
3770        });
3771
3772        // Absorb the JoinError — the panic is expected.
3773        let _ = handle.await;
3774
3775        // Key MUST be gone even though the task panicked.
3776        assert!(
3777            !dispatching.contains_key(&key),
3778            "dispatch key must be removed from the dispatching set even when the \
3779             spawned review task panics — without DispatchGuard the key leaks and \
3780             the task gets stuck in a permanent review loop"
3781        );
3782    }
3783
3784    #[serial(cooldown_state)]
3785    #[tokio::test]
3786    async fn sync_tick_reconciles_board_without_ingesting_or_transitioning_tasks() {
3787        cooldown::reset_global_state().await;
3788        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3789        let mock = IngestMockBackend::with_tasks(vec![]);
3790        let backend: Arc<dyn ExternalBackend> = Arc::<IngestMockBackend>::clone(&mock);
3791        let task_manager = Arc::new(TaskManager::with_store(
3792            Arc::clone(&backend),
3793            Arc::clone(&store),
3794            "owner/repo".to_string(),
3795        ));
3796        let dispatching = Arc::new(DashMap::new());
3797        Box::pin(sync_tick(
3798            &backend,
3799            &Arc::new(TmuxManager::new()),
3800            "owner/repo",
3801            &EngineConfig::default(),
3802            &Arc::new(RwLock::new(Router::new_for_test(
3803                RouterConfig::default(),
3804                vec!["claude".to_string()],
3805            ))),
3806            &task_manager,
3807            &store,
3808            &dispatching,
3809            &Arc::new(DashSet::new()),
3810        ))
3811        .await
3812        .unwrap();
3813        assert_eq!(mock.project_reconciliations.load(Ordering::Relaxed), 1);
3814        assert!(mock.project_syncs.lock().await.is_empty());
3815        assert!(mock.status_updates.lock().await.is_empty());
3816        assert!(dispatching.is_empty());
3817        assert!(
3818            store
3819                .existing_external_ids("owner/repo")
3820                .await
3821                .unwrap()
3822                .is_empty()
3823        );
3824    }
3825
3826    #[serial(cooldown_state)]
3827    #[tokio::test]
3828    async fn needs_review_refire_increments_and_fires_when_old_enough() {
3829        cooldown::reset_global_state().await;
3830        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3831        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
3832        let task_manager = Arc::new(TaskManager::with_store(
3833            backend,
3834            Arc::clone(&store),
3835            "owner/repo".to_string(),
3836        ));
3837        let router = reviewer_router();
3838        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
3839
3840        let id = store
3841            .upsert_external(&crate::store::UpsertExternal {
3842                repo: "owner/repo",
3843                ext_id: "201",
3844                title: "Needs review old",
3845                body: "",
3846                author: "",
3847                url: "",
3848                labels: &[],
3849                origin: "github",
3850            })
3851            .await
3852            .unwrap();
3853        store
3854            .update_status(id, TaskStatus::NeedsReview)
3855            .await
3856            .unwrap();
3857        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
3858            .bind(id)
3859            .execute(store.pool())
3860            .await
3861            .unwrap();
3862
3863        let t = store.get(id).await.unwrap();
3864        assert_eq!(t.needs_review_refires, 0);
3865
3866        refire_and_escalate_stale_needs_review_global(
3867            &task_manager,
3868            &store,
3869            &router,
3870            &dispatching,
3871            &sweep_repos(),
3872        )
3873        .await
3874        .unwrap();
3875
3876        let t2 = store.get(id).await.unwrap();
3877        assert_eq!(t2.needs_review_refires, 1);
3878        assert_eq!(t2.status, TaskStatus::NeedsReview);
3879    }
3880
3881    #[serial(cooldown_state)]
3882    #[tokio::test]
3883    async fn needs_review_backoff_delays_fire_but_increments_counter() {
3884        cooldown::reset_global_state().await;
3885        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3886        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
3887        let task_manager = Arc::new(TaskManager::with_store(
3888            backend,
3889            Arc::clone(&store),
3890            "owner/repo".to_string(),
3891        ));
3892        let router = reviewer_router();
3893        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
3894
3895        let id = store
3896            .upsert_external(&crate::store::UpsertExternal {
3897                repo: "owner/repo",
3898                ext_id: "202",
3899                title: "Needs review backoff",
3900                body: "",
3901                author: "",
3902                url: "",
3903                labels: &[],
3904                origin: "github",
3905            })
3906            .await
3907            .unwrap();
3908        store
3909            .update_status(id, TaskStatus::NeedsReview)
3910            .await
3911            .unwrap();
3912
3913        store
3914            .set_fields(id, &[("needs_review_refires", serde_json::json!(1))])
3915            .await
3916            .unwrap();
3917
3918        // Age 1 minute: stale enough to consider, but backoff at refires=1 needs 2 minutes
3919        let now_minus_1 = (chrono::Utc::now() - chrono::Duration::minutes(1))
3920            .format("%Y-%m-%dT%H:%M:%SZ")
3921            .to_string();
3922        sqlx::query("UPDATE tasks SET updated_at = ? WHERE id = ?")
3923            .bind(now_minus_1.clone())
3924            .bind(id)
3925            .execute(store.pool())
3926            .await
3927            .unwrap();
3928
3929        let before = store.get(id).await.unwrap();
3930        assert_eq!(before.needs_review_refires, 1);
3931
3932        refire_and_escalate_stale_needs_review_global(
3933            &task_manager,
3934            &store,
3935            &router,
3936            &dispatching,
3937            &sweep_repos(),
3938        )
3939        .await
3940        .unwrap();
3941
3942        let after = store.get(id).await.unwrap();
3943        // Counter must not increment on a backoff delay, only on an actual re-fire
3944        assert_eq!(after.needs_review_refires, 1);
3945        assert_eq!(after.updated_at, now_minus_1);
3946        assert_eq!(after.status, TaskStatus::NeedsReview);
3947    }
3948
3949    /// Router with one claude review model, so the refire sweeps see a reviewer.
3950    fn reviewer_router() -> Router {
3951        let mut config = RouterConfig::default();
3952        config.model_map.insert(
3953            "review".to_string(),
3954            HashMap::from([("claude".to_string(), vec!["sonnet".to_string()])]),
3955        );
3956        Router::new_for_test(config, vec!["claude".to_string()])
3957    }
3958
3959    #[serial(cooldown_state)]
3960    #[tokio::test]
3961    async fn needs_review_escalates_to_blocked_after_max_refires() {
3962        cooldown::reset_global_state().await;
3963        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3964        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
3965        let task_manager = Arc::new(TaskManager::with_store(
3966            backend,
3967            Arc::clone(&store),
3968            "owner/repo".to_string(),
3969        ));
3970        let router = reviewer_router();
3971        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
3972
3973        let id = store
3974            .upsert_external(&crate::store::UpsertExternal {
3975                repo: "owner/repo",
3976                ext_id: "203",
3977                title: "Needs review escalate",
3978                body: "",
3979                author: "",
3980                url: "",
3981                labels: &[],
3982                origin: "github",
3983            })
3984            .await
3985            .unwrap();
3986        store
3987            .update_status(id, TaskStatus::NeedsReview)
3988            .await
3989            .unwrap();
3990
3991        // Counter at MAX (5): the next pass is attempt 6 and escalates
3992        store
3993            .set_fields(id, &[("needs_review_refires", serde_json::json!(5))])
3994            .await
3995            .unwrap();
3996        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
3997            .bind(id)
3998            .execute(store.pool())
3999            .await
4000            .unwrap();
4001
4002        refire_and_escalate_stale_needs_review_global(
4003            &task_manager,
4004            &store,
4005            &router,
4006            &dispatching,
4007            &sweep_repos(),
4008        )
4009        .await
4010        .unwrap();
4011
4012        let after = store.get(id).await.unwrap();
4013        assert_eq!(after.status, TaskStatus::Blocked);
4014        assert!(after.block_reason.is_some());
4015    }
4016
4017    /// Exactly MAX_NEEDS_REVIEW_REFIRE_ATTEMPTS refires are allowed before
4018    /// escalation. Task stays NeedsReview at 5 refires and only blocks on the 6th
4019    #[serial(cooldown_state)]
4020    #[tokio::test]
4021    async fn needs_review_allows_max_refires_before_escalation() {
4022        cooldown::reset_global_state().await;
4023        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4024        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4025        let task_manager = Arc::new(TaskManager::with_store(
4026            backend,
4027            Arc::clone(&store),
4028            "owner/repo".to_string(),
4029        ));
4030        let router = reviewer_router();
4031        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4032
4033        let id = store
4034            .upsert_external(&crate::store::UpsertExternal {
4035                repo: "owner/repo",
4036                ext_id: "204",
4037                title: "Max refires test",
4038                body: "",
4039                author: "",
4040                url: "",
4041                labels: &[],
4042                origin: "github",
4043            })
4044            .await
4045            .unwrap();
4046        store
4047            .update_status(id, TaskStatus::NeedsReview)
4048            .await
4049            .unwrap();
4050
4051        // Counter at MAX-1 (4): incrementing hits MAX (5) and must not escalate
4052        store
4053            .set_fields(id, &[("needs_review_refires", serde_json::json!(4))])
4054            .await
4055            .unwrap();
4056        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
4057            .bind(id)
4058            .execute(store.pool())
4059            .await
4060            .unwrap();
4061
4062        refire_and_escalate_stale_needs_review_global(
4063            &task_manager,
4064            &store,
4065            &router,
4066            &dispatching,
4067            &sweep_repos(),
4068        )
4069        .await
4070        .unwrap();
4071
4072        let after = store.get(id).await.unwrap();
4073        assert_eq!(after.status, TaskStatus::NeedsReview);
4074        assert_eq!(after.needs_review_refires, 5);
4075        assert!(after.block_reason.is_none());
4076    }
4077
4078    /// Every repo the sweep tests use, so each counts as active
4079    fn sweep_repos() -> HashSet<String> {
4080        ["owner/repo", "inactive/repo", "some/repo", "active/repo"]
4081            .into_iter()
4082            .map(String::from)
4083            .collect()
4084    }
4085
4086    /// A repo outside the active set has no review subscriber (#4024)
4087    #[serial(cooldown_state)]
4088    #[tokio::test]
4089    async fn global_sweeps_leave_tasks_of_a_removed_repo_alone() {
4090        cooldown::reset_global_state().await;
4091        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4092        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4093        let task_manager = Arc::new(TaskManager::with_store(
4094            backend,
4095            Arc::clone(&store),
4096            "active/repo".to_string(),
4097        ));
4098        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4099        let router = router_with_healthy_review_agent();
4100        let active: HashSet<String> = ["active/repo".to_string()].into_iter().collect();
4101
4102        let review_id = store
4103            .create_internal("removed/repo", "Needs review", "", "cron", "1", None)
4104            .await
4105            .unwrap();
4106        store
4107            .update_status(review_id, TaskStatus::NeedsReview)
4108            .await
4109            .unwrap();
4110        let blocked_id = store
4111            .create_internal("removed/repo", "Rebroadcast blocked", "", "cron", "2", None)
4112            .await
4113            .unwrap();
4114        store
4115            .update_status(blocked_id, TaskStatus::Blocked)
4116            .await
4117            .unwrap();
4118        store
4119            .set_block_reason(blocked_id, Some(REBROADCAST_BLOCK_REASON))
4120            .await
4121            .unwrap();
4122        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z'")
4123            .execute(store.pool())
4124            .await
4125            .unwrap();
4126
4127        refire_and_escalate_stale_needs_review_global(
4128            &task_manager,
4129            &store,
4130            &router,
4131            &dispatching,
4132            &active,
4133        )
4134        .await
4135        .unwrap();
4136        auto_recover_rebroadcast_blocked_tasks_global(&router, &task_manager, &store, &active)
4137            .await
4138            .unwrap();
4139
4140        let review = store.get(review_id).await.unwrap();
4141        assert_eq!(review.status, TaskStatus::NeedsReview);
4142        assert_eq!(review.needs_review_refires, 0);
4143        let blocked = store.get(blocked_id).await.unwrap();
4144        assert_eq!(blocked.status, TaskStatus::Blocked);
4145        assert_eq!(
4146            blocked.block_reason.as_deref(),
4147            Some(REBROADCAST_BLOCK_REASON)
4148        );
4149    }
4150
4151    // ── refire_and_escalate_stale_needs_review_global ──────────────────────
4152
4153    fn router_with_healthy_review_agent() -> Router {
4154        let mut config = RouterConfig::default();
4155        config
4156            .model_map
4157            .entry("review".to_string())
4158            .or_default()
4159            .insert("claude".to_string(), vec!["sonnet".to_string()]);
4160        let mut router = Router::new(config);
4161        router.available_agents = vec!["claude".to_string()];
4162        router
4163    }
4164
4165    /// Regression test for #3469: a task stuck in NeedsReview for a repo that
4166    /// is not the TaskManager's own repo must still be refired. The sweep
4167    /// queries via `list_all_by_status_global` and writes through the store
4168    /// directly, bypassing the repo-scoped TaskManager
4169    #[serial(cooldown_state)]
4170    #[tokio::test]
4171    async fn global_refire_sweep_refires_stale_task_from_inactive_repo() {
4172        cooldown::reset_global_state().await;
4173        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4174        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4175        // TaskManager scoped to the active repo — NOT the repo the task belongs to.
4176        let task_manager = Arc::new(TaskManager::with_store(
4177            backend,
4178            Arc::clone(&store),
4179            "active/repo".to_string(),
4180        ));
4181        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4182        let router = router_with_healthy_review_agent();
4183
4184        let id = store
4185            .upsert_external(&crate::store::UpsertExternal {
4186                repo: "inactive/repo",
4187                ext_id: "490",
4188                title: "Stale needs_review from inactive repo",
4189                body: "",
4190                author: "",
4191                url: "",
4192                labels: &[],
4193                origin: "github",
4194            })
4195            .await
4196            .unwrap();
4197        store
4198            .update_status(id, TaskStatus::NeedsReview)
4199            .await
4200            .unwrap();
4201        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
4202            .bind(id)
4203            .execute(store.pool())
4204            .await
4205            .unwrap();
4206
4207        refire_and_escalate_stale_needs_review_global(
4208            &task_manager,
4209            &store,
4210            &router,
4211            &dispatching,
4212            &sweep_repos(),
4213        )
4214        .await
4215        .unwrap();
4216
4217        let task = store.get(id).await.unwrap();
4218        assert_eq!(
4219            task.needs_review_refires, 1,
4220            "cross-repo task must be refired"
4221        );
4222        assert_eq!(task.status, TaskStatus::NeedsReview);
4223    }
4224
4225    /// After `MAX_NEEDS_REVIEW_REFIRE_ATTEMPTS` refires, a cross-repo task must
4226    /// escalate to Blocked
4227    #[serial(cooldown_state)]
4228    #[tokio::test]
4229    async fn global_refire_sweep_escalates_cross_repo_task_to_blocked() {
4230        cooldown::reset_global_state().await;
4231        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4232        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4233        let task_manager = Arc::new(TaskManager::with_store(
4234            backend,
4235            Arc::clone(&store),
4236            "active/repo".to_string(),
4237        ));
4238        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4239        let router = router_with_healthy_review_agent();
4240
4241        let id = store
4242            .upsert_external(&crate::store::UpsertExternal {
4243                repo: "inactive/repo",
4244                ext_id: "493",
4245                title: "Exhausted refires from inactive repo",
4246                body: "",
4247                author: "",
4248                url: "",
4249                labels: &[],
4250                origin: "github",
4251            })
4252            .await
4253            .unwrap();
4254        store
4255            .update_status(id, TaskStatus::NeedsReview)
4256            .await
4257            .unwrap();
4258        store
4259            .set_fields(id, &[("needs_review_refires", serde_json::json!(5))])
4260            .await
4261            .unwrap();
4262        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
4263            .bind(id)
4264            .execute(store.pool())
4265            .await
4266            .unwrap();
4267
4268        refire_and_escalate_stale_needs_review_global(
4269            &task_manager,
4270            &store,
4271            &router,
4272            &dispatching,
4273            &sweep_repos(),
4274        )
4275        .await
4276        .unwrap();
4277
4278        let task = store.get(id).await.unwrap();
4279        assert_eq!(task.status, TaskStatus::Blocked);
4280        assert_eq!(
4281            task.block_reason.as_deref(),
4282            Some("review agent rebroadcast escalated after repeated retries")
4283        );
4284    }
4285
4286    /// When every review agent is cooled, the sweep must skip entirely.
4287    /// Re-firing while all agents are cooled would waste the refire counter and
4288    /// could escalate a task to Blocked because agents happened to be
4289    /// temporarily unavailable
4290    #[serial(cooldown_state)]
4291    #[tokio::test]
4292    async fn global_refire_sweep_skips_when_all_review_agents_cooled() {
4293        cooldown::reset_global_state().await;
4294        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4295        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4296        let task_manager = Arc::new(TaskManager::with_store(
4297            backend,
4298            Arc::clone(&store),
4299            "active/repo".to_string(),
4300        ));
4301        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4302        // RouterConfig::default() has no "review" model map entries, so the one
4303        // available agent has no healthy model for "review" — all cooled.
4304        let router = Router::new_for_test(RouterConfig::default(), vec!["claude".to_string()]);
4305
4306        let id = store
4307            .upsert_external(&crate::store::UpsertExternal {
4308                repo: "inactive/repo",
4309                ext_id: "494",
4310                title: "Stale needs_review while agents cooled",
4311                body: "",
4312                author: "",
4313                url: "",
4314                labels: &[],
4315                origin: "github",
4316            })
4317            .await
4318            .unwrap();
4319        store
4320            .update_status(id, TaskStatus::NeedsReview)
4321            .await
4322            .unwrap();
4323        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
4324            .bind(id)
4325            .execute(store.pool())
4326            .await
4327            .unwrap();
4328
4329        refire_and_escalate_stale_needs_review_global(
4330            &task_manager,
4331            &store,
4332            &router,
4333            &dispatching,
4334            &sweep_repos(),
4335        )
4336        .await
4337        .unwrap();
4338
4339        let task = store.get(id).await.unwrap();
4340        assert_eq!(
4341            task.needs_review_refires, 0,
4342            "counter must not be touched while cooled"
4343        );
4344        assert_eq!(task.status, TaskStatus::NeedsReview);
4345    }
4346
4347    /// With no available review agent at all, the sweep must not count re-fires
4348    /// or escalate to Blocked.
4349    #[serial(cooldown_state)]
4350    #[tokio::test]
4351    async fn global_refire_sweep_skips_when_no_reviewer_available() {
4352        cooldown::reset_global_state().await;
4353        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4354        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4355        let task_manager = Arc::new(TaskManager::with_store(
4356            backend,
4357            Arc::clone(&store),
4358            "active/repo".to_string(),
4359        ));
4360        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4361        let router = Router::new_for_test(RouterConfig::default(), vec![]);
4362
4363        let id = store
4364            .upsert_external(&crate::store::UpsertExternal {
4365                repo: "some/repo",
4366                ext_id: "495",
4367                title: "needs_review with no reviewer",
4368                body: "",
4369                author: "",
4370                url: "",
4371                labels: &[],
4372                origin: "github",
4373            })
4374            .await
4375            .unwrap();
4376        store
4377            .update_status(id, TaskStatus::NeedsReview)
4378            .await
4379            .unwrap();
4380        store
4381            .set_fields(id, &[("needs_review_refires", serde_json::json!(5))])
4382            .await
4383            .unwrap();
4384        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
4385            .bind(id)
4386            .execute(store.pool())
4387            .await
4388            .unwrap();
4389
4390        refire_and_escalate_stale_needs_review_global(
4391            &task_manager,
4392            &store,
4393            &router,
4394            &dispatching,
4395            &sweep_repos(),
4396        )
4397        .await
4398        .unwrap();
4399
4400        let task = store.get(id).await.unwrap();
4401        assert_eq!(task.status, TaskStatus::NeedsReview);
4402        assert_eq!(task.needs_review_refires, 5);
4403    }
4404
4405    /// Regression test for #3499: a task blocked with the rebroadcast-escalation
4406    /// reason after surviving one review round (`review_cycles > 0`) must be
4407    /// recovered back to NeedsReview once review agents are routable again.
4408    /// Previously the `review_cycles != 0` filter excluded these tasks, stranding
4409    /// them permanently even when agents recovered.
4410    #[serial(cooldown_state)]
4411    #[tokio::test]
4412    async fn auto_recover_rebroadcast_blocked_task_after_review_cycle() {
4413        cooldown::reset_global_state().await;
4414        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4415        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4416        let task_manager = Arc::new(TaskManager::with_store(
4417            backend,
4418            Arc::clone(&store),
4419            "owner/repo".to_string(),
4420        ));
4421        let router = router_with_healthy_review_agent();
4422
4423        let id = store
4424            .upsert_external(&crate::store::UpsertExternal {
4425                repo: "owner/repo",
4426                ext_id: "511",
4427                title: "Rebroadcast blocked after review",
4428                body: "",
4429                author: "",
4430                url: "",
4431                labels: &[],
4432                origin: "github",
4433            })
4434            .await
4435            .unwrap();
4436        store.update_status(id, TaskStatus::Blocked).await.unwrap();
4437        store
4438            .set_block_reason(
4439                id,
4440                Some("review agent rebroadcast escalated after repeated retries"),
4441            )
4442            .await
4443            .unwrap();
4444        store
4445            .set_fields(id, &[("review_cycles", serde_json::json!(1))])
4446            .await
4447            .unwrap();
4448        store
4449            .set_fields(id, &[("needs_review_refires", serde_json::json!(6))])
4450            .await
4451            .unwrap();
4452        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
4453            .bind(id)
4454            .execute(store.pool())
4455            .await
4456            .unwrap();
4457
4458        auto_recover_rebroadcast_blocked_tasks_global(
4459            &router,
4460            &task_manager,
4461            &store,
4462            &sweep_repos(),
4463        )
4464        .await
4465        .unwrap();
4466
4467        let task = store.get(id).await.unwrap();
4468        assert_eq!(
4469            task.status,
4470            TaskStatus::NeedsReview,
4471            "blocked rebroadcast task must be recovered to needs_review"
4472        );
4473        assert!(
4474            task.block_reason.is_none(),
4475            "block_reason must be cleared on recovery"
4476        );
4477        assert_eq!(
4478            task.needs_review_refires, 0,
4479            "needs_review_refires must be reset to 0 on recovery"
4480        );
4481    }
4482
4483    /// A fresh InReview task (<1 min old) should NOT be reset — the review
4484    /// agent may still be starting up.
4485    #[serial(cooldown_state)]
4486    #[tokio::test]
4487    async fn stale_in_review_recovery_skips_fresh_tasks() {
4488        cooldown::reset_global_state().await;
4489        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4490        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4491        let task_manager = Arc::new(TaskManager::with_store(
4492            Arc::clone(&backend),
4493            Arc::clone(&store),
4494            "owner/repo".to_string(),
4495        ));
4496        let tmux = Arc::new(TmuxManager::new());
4497        let router = Arc::new(RwLock::new(Router::new_for_test(
4498            RouterConfig::default(),
4499            vec!["claude".to_string()],
4500        )));
4501        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4502        let auto_merge_in_flight: Arc<DashSet<String>> = Arc::new(DashSet::new());
4503
4504        let id = store
4505            .upsert_external(&crate::store::UpsertExternal {
4506                repo: "owner/repo",
4507                ext_id: "66",
4508                title: "Fresh review",
4509                body: "",
4510                author: "",
4511                url: "",
4512                labels: &[],
4513                origin: "github",
4514            })
4515            .await
4516            .unwrap();
4517        store.update_status(id, TaskStatus::InReview).await.unwrap();
4518        store
4519            .set_fields(id, &[("branch", serde_json::json!("feature/66"))])
4520            .await
4521            .unwrap();
4522        // Don't backdate — task is fresh (just created)
4523
4524        Box::pin(sync_tick(
4525            &backend,
4526            &tmux,
4527            "owner/repo",
4528            &EngineConfig::default(),
4529            &router,
4530            &task_manager,
4531            &store,
4532            &dispatching,
4533            &auto_merge_in_flight,
4534        ))
4535        .await
4536        .unwrap();
4537
4538        // Should stay InReview — too young to be considered orphaned
4539        let task = store.get(id).await.unwrap();
4540        assert_eq!(task.status, TaskStatus::InReview);
4541    }
4542
4543    #[serial(cooldown_state)]
4544    #[tokio::test]
4545    async fn auto_unblock_routes_recoverable_failure() {
4546        cooldown::reset_global_state().await;
4547        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4548        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4549        let task_manager = Arc::new(TaskManager::with_store(
4550            backend,
4551            Arc::clone(&store),
4552            "owner/repo".to_string(),
4553        ));
4554        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4555
4556        let id = store
4557            .upsert_external(&crate::store::UpsertExternal {
4558                repo: "owner/repo",
4559                ext_id: "77",
4560                title: "Blocked task",
4561                body: "",
4562                author: "",
4563                url: "",
4564                labels: &[],
4565                origin: "github",
4566            })
4567            .await
4568            .unwrap();
4569        store.update_status(id, TaskStatus::Blocked).await.unwrap();
4570        store
4571            .set_fields(
4572                id,
4573                &[
4574                    ("agent", serde_json::json!("codex")),
4575                    ("model", serde_json::json!("gpt-5")),
4576                ],
4577            )
4578            .await
4579            .unwrap();
4580
4581        let run_id = store
4582            .start_run(&crate::store::StartRun {
4583                task_id: id,
4584                attempt: 1,
4585                run_type: "agent",
4586                agent: "codex",
4587                model: "gpt-5",
4588                command: "codex --model gpt-5",
4589                prompt: "do thing",
4590            })
4591            .await
4592            .unwrap();
4593        store
4594            .complete_run(&crate::store::CompleteRun {
4595                run_id,
4596                exit_code: Some(1),
4597                stdout: "",
4598                stderr: "",
4599                parsed: "",
4600                outcome: "rate_limit",
4601                error: "rate limit exceeded",
4602                tokens: RunTokenUsage::default(),
4603            })
4604            .await
4605            .unwrap();
4606
4607        auto_unblock_blocked_tasks(
4608            "owner/repo",
4609            &task_manager,
4610            &store,
4611            &dispatching,
4612            &Arc::new(DashSet::new()),
4613        )
4614        .await
4615        .unwrap();
4616
4617        let task = store.get(id).await.unwrap();
4618        assert_eq!(task.status, TaskStatus::New);
4619        assert!(task.agent.is_none());
4620        assert!(task.model.is_none());
4621        assert_eq!(task.auto_unblock_count, 1);
4622        assert_ne!(task.auto_unblock_last_at, "");
4623        assert_eq!(task.auto_unblock_last_reason, "RateLimit");
4624    }
4625
4626    #[serial(cooldown_state)]
4627    #[tokio::test]
4628    async fn auto_unblock_skips_manual_block() {
4629        cooldown::reset_global_state().await;
4630        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4631        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4632        let task_manager = Arc::new(TaskManager::with_store(
4633            backend,
4634            Arc::clone(&store),
4635            "owner/repo".to_string(),
4636        ));
4637        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4638
4639        let id = store
4640            .upsert_external(&crate::store::UpsertExternal {
4641                repo: "owner/repo",
4642                ext_id: "88",
4643                title: "Manually blocked",
4644                body: "",
4645                author: "",
4646                url: "",
4647                labels: &[],
4648                origin: "github",
4649            })
4650            .await
4651            .unwrap();
4652        store.update_status(id, TaskStatus::Blocked).await.unwrap();
4653        store
4654            .set_block_reason(id, Some("waiting on input"))
4655            .await
4656            .unwrap();
4657
4658        let run_id = store
4659            .start_run(&crate::store::StartRun {
4660                task_id: id,
4661                attempt: 1,
4662                run_type: "agent",
4663                agent: "codex",
4664                model: "gpt-5",
4665                command: "codex --model gpt-5",
4666                prompt: "do thing",
4667            })
4668            .await
4669            .unwrap();
4670        store
4671            .complete_run(&crate::store::CompleteRun {
4672                run_id,
4673                exit_code: Some(1),
4674                stdout: "",
4675                stderr: "",
4676                parsed: "",
4677                outcome: "rate_limit",
4678                error: "rate limit exceeded",
4679                tokens: RunTokenUsage::default(),
4680            })
4681            .await
4682            .unwrap();
4683
4684        auto_unblock_blocked_tasks(
4685            "owner/repo",
4686            &task_manager,
4687            &store,
4688            &dispatching,
4689            &Arc::new(DashSet::new()),
4690        )
4691        .await
4692        .unwrap();
4693
4694        let task = store.get(id).await.unwrap();
4695        assert_eq!(task.status, TaskStatus::Blocked);
4696        assert_eq!(task.auto_unblock_count, 0);
4697    }
4698
4699    // ── FailureCategory::as_str ─────────────────────────────────────────
4700
4701    #[serial(cooldown_state)]
4702    #[test]
4703    fn failure_category_as_str() {
4704        // as_str() must return a stable, human-readable string used as the
4705        // reason key in auto_unblock tracking (stored in auto_unblock_last_reason).
4706        assert_eq!(FailureCategory::RateLimit.as_str(), "RateLimit");
4707        assert_eq!(FailureCategory::Timeout.as_str(), "Timeout");
4708        assert_eq!(
4709            FailureCategory::ModelUnavailable.as_str(),
4710            "ModelUnavailable"
4711        );
4712        assert_eq!(FailureCategory::MaxAttempts.as_str(), "MaxAttempts");
4713        assert_eq!(FailureCategory::Unknown.as_str(), "Unknown");
4714        assert_eq!(FailureCategory::SilentExit0.as_str(), "SilentExit0");
4715        assert_eq!(FailureCategory::ConnectionError.as_str(), "ConnectionError");
4716        assert_eq!(FailureCategory::CliFlagError.as_str(), "CliFlagError");
4717        assert_eq!(
4718            FailureCategory::AllAgentsExhausted.as_str(),
4719            "AllAgentsExhausted"
4720        );
4721        assert_eq!(FailureCategory::ParseError.as_str(), "ParseError");
4722        assert_eq!(FailureCategory::FalseFailure.as_str(), "FalseFailure");
4723        assert_eq!(FailureCategory::PushFailed.as_str(), "PushFailed");
4724        assert_eq!(FailureCategory::PrCreateFailed.as_str(), "PrCreateFailed");
4725    }
4726
4727    // ── classify_failure: ModelUnavailable ──────────────────────────────
4728
4729    #[serial(cooldown_state)]
4730    #[test]
4731    fn classify_failure_model_unavailable_phrase_is_recoverable() {
4732        let category = classify_failure(
4733            "model unavailable (anthropic/claude-sonnet-4-6): Model not found: anthropic/claude-sonnet-4-6",
4734            "error",
4735        );
4736        assert_eq!(
4737            category,
4738            FailureCategory::ModelUnavailable,
4739            "\"model unavailable\" error must classify as ModelUnavailable"
4740        );
4741        assert!(
4742            category.is_recoverable(),
4743            "ModelUnavailable must be recoverable so auto-unblock can re-route"
4744        );
4745    }
4746
4747    // ── classify_failure: CreditExhausted (billing cycle) ──────────────
4748    #[serial(cooldown_state)]
4749    #[test]
4750    fn classify_failure_kimi_billing_cycle_is_credit_exhausted_not_rate_limit() {
4751        // Regression test for issue #3529: Kimi's billing-cycle exhaustion message
4752        // contains "usage limit", which also matches the generic rate-limit content
4753        // check. Credit exhaustion must be checked first so the failure is
4754        // categorized as CreditExhausted, not RateLimit, even when the stored
4755        // outcome is still "rate_limit" (e.g. from a task_run recorded before this
4756        // fix landed).
4757        let error = "kimi rate limit: Failed to authenticate. API Error: 403 You've reached \
4758                      your usage limit for this billing cycle. Your quota will be refreshed soon.";
4759        let category = classify_failure(error, "rate_limit");
4760        assert_eq!(
4761            category,
4762            FailureCategory::CreditExhausted,
4763            "billing-cycle exhaustion must classify as CreditExhausted, not RateLimit"
4764        );
4765        assert!(category.is_recoverable());
4766    }
4767
4768    #[serial(cooldown_state)]
4769    #[test]
4770    fn classify_failure_billing_cycle_exhausted_outcome_is_credit_exhausted() {
4771        // New task_runs store the specific "billing_cycle_exhausted" outcome
4772        // (post-fix). classify_failure must recognize it directly too.
4773        let category = classify_failure("some billing message", "billing_cycle_exhausted");
4774        assert_eq!(category, FailureCategory::CreditExhausted);
4775    }
4776
4777    #[serial(cooldown_state)]
4778    #[test]
4779    fn classify_failure_generic_rate_limit_is_still_rate_limit() {
4780        // Genuine rate limits (no billing-cycle/credit-exhaustion markers) must
4781        // remain RateLimit, not be swallowed by the reordered credit-exhaustion check.
4782        let category = classify_failure("429 Too Many Requests", "rate_limit");
4783        assert_eq!(category, FailureCategory::RateLimit);
4784    }
4785
4786    // ── classify_failure: PrCreateFailed ──────────────────────────────
4787    #[serial(cooldown_state)]
4788    #[test]
4789    fn classify_failure_pr_create_failed_specific_patterns() {
4790        // These should be classified as PrCreateFailed
4791        assert_eq!(
4792            classify_failure("create pr failed", ""),
4793            FailureCategory::PrCreateFailed
4794        );
4795        assert_eq!(
4796            classify_failure("failed to create pull request", ""),
4797            FailureCategory::PrCreateFailed
4798        );
4799        assert_eq!(
4800            classify_failure("pull request creation failed", ""),
4801            FailureCategory::PrCreateFailed
4802        );
4803
4804        // These should NOT be classified as PrCreateFailed (they were before the fix)
4805        assert_ne!(
4806            classify_failure("network failed while fetching pull request status", ""),
4807            FailureCategory::PrCreateFailed
4808        );
4809        assert_ne!(
4810            classify_failure("connection failed, retrying pull request check", ""),
4811            FailureCategory::PrCreateFailed
4812        );
4813        assert_ne!(
4814            classify_failure("pull request created but failed to merge", ""),
4815            FailureCategory::PrCreateFailed
4816        );
4817    }
4818
4819    #[serial(cooldown_state)]
4820    #[test]
4821    fn classify_failure_model_not_found_is_recoverable() {
4822        let category = classify_failure("Model not found: gpt-5-ultra", "error");
4823        assert_eq!(
4824            category,
4825            FailureCategory::ModelUnavailable,
4826            "\"model not found\" error must classify as ModelUnavailable"
4827        );
4828        assert!(category.is_recoverable());
4829    }
4830
4831    #[serial(cooldown_state)]
4832    #[test]
4833    fn classify_failure_model_does_not_exist_is_recoverable() {
4834        let category = classify_failure("The model `claude-opus-99` does not exist", "error");
4835        assert_eq!(category, FailureCategory::ModelUnavailable);
4836        assert!(category.is_recoverable());
4837    }
4838
4839    #[serial(cooldown_state)]
4840    #[tokio::test]
4841    async fn auto_unblock_routes_task_blocked_by_model_unavailable() {
4842        cooldown::reset_global_state().await;
4843        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4844        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4845        let task_manager = Arc::new(TaskManager::with_store(
4846            backend,
4847            Arc::clone(&store),
4848            "owner/repo".to_string(),
4849        ));
4850        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4851
4852        let id = store
4853            .upsert_external(&crate::store::UpsertExternal {
4854                repo: "owner/repo",
4855                ext_id: "1202",
4856                title: "Task blocked by model unavailable",
4857                body: "",
4858                author: "",
4859                url: "",
4860                labels: &[],
4861                origin: "github",
4862            })
4863            .await
4864            .unwrap();
4865        store.update_status(id, TaskStatus::Blocked).await.unwrap();
4866
4867        let run_id = store
4868            .start_run(&crate::store::StartRun {
4869                task_id: id,
4870                attempt: 1,
4871                run_type: "agent",
4872                agent: "opencode",
4873                model: "anthropic/claude-sonnet-4-6",
4874                command: "opencode",
4875                prompt: "fix the bug",
4876            })
4877            .await
4878            .unwrap();
4879        store
4880            .complete_run(&crate::store::CompleteRun {
4881                run_id,
4882                exit_code: Some(1),
4883                stdout: "",
4884                stderr: "",
4885                parsed: "",
4886                outcome: "error",
4887                error: "model unavailable (anthropic/claude-sonnet-4-6): Model not found: anthropic/claude-sonnet-4-6",
4888                tokens: RunTokenUsage::default(),
4889            })
4890            .await
4891            .unwrap();
4892
4893        auto_unblock_blocked_tasks(
4894            "owner/repo",
4895            &task_manager,
4896            &store,
4897            &dispatching,
4898            &Arc::new(DashSet::new()),
4899        )
4900        .await
4901        .unwrap();
4902
4903        let task = store.get(id).await.unwrap();
4904        assert_eq!(
4905            task.status,
4906            TaskStatus::New,
4907            "task blocked by model unavailable must be auto-unblocked and re-routed"
4908        );
4909        assert_eq!(task.auto_unblock_count, 1);
4910        assert_eq!(task.auto_unblock_last_reason, "ModelUnavailable");
4911    }
4912
4913    // ── auto_unblock: reason-reset (regression for #1227) ─────────────────
4914
4915    #[serial(cooldown_state)]
4916    #[tokio::test]
4917    async fn auto_unblock_resets_count_when_reason_changes() {
4918        cooldown::reset_global_state().await;
4919        // Regression test for #1227: when a task is blocked for a different failure
4920        // reason than the last auto-unblock, the counter should reset to 0 (immediate
4921        // retry) instead of accumulating across unrelated failures.
4922        let store = Arc::new(TaskStore::open_memory().await.unwrap());
4923        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
4924        let task_manager = Arc::new(TaskManager::with_store(
4925            backend,
4926            Arc::clone(&store),
4927            "owner/repo".to_string(),
4928        ));
4929        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
4930
4931        let id = store
4932            .upsert_external(&crate::store::UpsertExternal {
4933                repo: "owner/repo",
4934                ext_id: "1227",
4935                title: "Task with different failure reason",
4936                body: "",
4937                author: "",
4938                url: "",
4939                labels: &[],
4940                origin: "github",
4941            })
4942            .await
4943            .unwrap();
4944        store.update_status(id, TaskStatus::Blocked).await.unwrap();
4945        // Simulate: task was previously auto-unblocked for ModelUnavailable (count=1)
4946        store
4947            .set_fields(
4948                id,
4949                &[
4950                    ("auto_unblock_count", serde_json::json!(1)),
4951                    (
4952                        "auto_unblock_last_reason",
4953                        serde_json::json!("ModelUnavailable"),
4954                    ),
4955                ],
4956            )
4957            .await
4958            .unwrap();
4959
4960        // Add a run with a DIFFERENT failure: RateLimit
4961        let run_id = store
4962            .start_run(&crate::store::StartRun {
4963                task_id: id,
4964                attempt: 2,
4965                run_type: "agent",
4966                agent: "claude",
4967                model: "opus",
4968                command: "claude",
4969                prompt: "fix the bug",
4970            })
4971            .await
4972            .unwrap();
4973        store
4974            .complete_run(&crate::store::CompleteRun {
4975                run_id,
4976                exit_code: Some(1),
4977                stdout: "",
4978                stderr: "",
4979                parsed: "",
4980                outcome: "error",
4981                error: "rate limit reached for model opus",
4982                tokens: RunTokenUsage::default(),
4983            })
4984            .await
4985            .unwrap();
4986
4987        auto_unblock_blocked_tasks(
4988            "owner/repo",
4989            &task_manager,
4990            &store,
4991            &dispatching,
4992            &Arc::new(DashSet::new()),
4993        )
4994        .await
4995        .unwrap();
4996
4997        let task = store.get(id).await.unwrap();
4998        assert_eq!(
4999            task.status,
5000            TaskStatus::New,
5001            "task must be auto-unblocked even with count=1 from a different reason"
5002        );
5003        // Count is reset to 0, then incremented to 1 for the new reason
5004        assert_eq!(task.auto_unblock_count, 1);
5005        assert_eq!(
5006            task.auto_unblock_last_reason, "RateLimit",
5007            "reason must be updated to the new failure category"
5008        );
5009    }
5010
5011    /**
5012     * A task blocked for "exceeded max attempts" has already run the configured number
5013     * of times. Auto-unblock must leave it alone — flipping it back to new/needs_review
5014     * on the next tick restarted the very loop that produced the block (#3783)
5015     **/
5016    #[serial(cooldown_state)]
5017    #[tokio::test]
5018    async fn auto_unblock_leaves_max_attempts_blocked_task_alone() {
5019        cooldown::reset_global_state().await;
5020        let store = Arc::new(TaskStore::open_memory().await.unwrap());
5021        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
5022        let task_manager = Arc::new(TaskManager::with_store(
5023            backend,
5024            Arc::clone(&store),
5025            "owner/repo".to_string(),
5026        ));
5027        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
5028
5029        let id = store
5030            .upsert_external(&crate::store::UpsertExternal {
5031                repo: "owner/repo",
5032                ext_id: "3783",
5033                title: "Approved work sent back to the agent",
5034                body: "",
5035                author: "",
5036                url: "",
5037                labels: &[],
5038                origin: "github",
5039            })
5040            .await
5041            .unwrap();
5042        store.update_status(id, TaskStatus::Blocked).await.unwrap();
5043
5044        let run_id = store
5045            .start_run(&crate::store::StartRun {
5046                task_id: id,
5047                attempt: 11,
5048                run_type: "agent",
5049                agent: "claude",
5050                model: "opus",
5051                command: "claude",
5052                prompt: "fix the bug",
5053            })
5054            .await
5055            .unwrap();
5056        store
5057            .complete_run(&crate::store::CompleteRun {
5058                run_id,
5059                exit_code: Some(1),
5060                stdout: "",
5061                stderr: "",
5062                parsed: "",
5063                outcome: "error",
5064                error: "exceeded max attempts (11/10). Use `/retry` to reset.",
5065                tokens: RunTokenUsage::default(),
5066            })
5067            .await
5068            .unwrap();
5069
5070        auto_unblock_blocked_tasks(
5071            "owner/repo",
5072            &task_manager,
5073            &store,
5074            &dispatching,
5075            &Arc::new(DashSet::new()),
5076        )
5077        .await
5078        .unwrap();
5079
5080        let task = store.get(id).await.unwrap();
5081        assert_eq!(
5082            task.status,
5083            TaskStatus::Blocked,
5084            "max-attempts block must survive the next tick until a person acts"
5085        );
5086        assert_eq!(
5087            task.auto_unblock_count, 0,
5088            "no auto-unblock attempt should be recorded"
5089        );
5090    }
5091
5092    #[serial(cooldown_state)]
5093    #[tokio::test]
5094    async fn auto_unblock_stores_reason_on_first_unblock() {
5095        cooldown::reset_global_state().await;
5096        // When a task is auto-unblocked for the first time, the failure reason
5097        // should be stored so subsequent blocks can be compared.
5098        let store = Arc::new(TaskStore::open_memory().await.unwrap());
5099        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
5100        let task_manager = Arc::new(TaskManager::with_store(
5101            backend,
5102            Arc::clone(&store),
5103            "owner/repo".to_string(),
5104        ));
5105        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
5106
5107        let id = store
5108            .upsert_external(&crate::store::UpsertExternal {
5109                repo: "owner/repo",
5110                ext_id: "1227b",
5111                title: "Task for first-time reason storage",
5112                body: "",
5113                author: "",
5114                url: "",
5115                labels: &[],
5116                origin: "github",
5117            })
5118            .await
5119            .unwrap();
5120        store.update_status(id, TaskStatus::Blocked).await.unwrap();
5121
5122        let run_id = store
5123            .start_run(&crate::store::StartRun {
5124                task_id: id,
5125                attempt: 1,
5126                run_type: "agent",
5127                agent: "claude",
5128                model: "opus",
5129                command: "claude",
5130                prompt: "fix the bug",
5131            })
5132            .await
5133            .unwrap();
5134        store
5135            .complete_run(&crate::store::CompleteRun {
5136                run_id,
5137                exit_code: Some(1),
5138                stdout: "",
5139                stderr: "",
5140                parsed: "",
5141                outcome: "timeout",
5142                error: "task timed out",
5143                tokens: RunTokenUsage::default(),
5144            })
5145            .await
5146            .unwrap();
5147
5148        auto_unblock_blocked_tasks(
5149            "owner/repo",
5150            &task_manager,
5151            &store,
5152            &dispatching,
5153            &Arc::new(DashSet::new()),
5154        )
5155        .await
5156        .unwrap();
5157
5158        let task = store.get(id).await.unwrap();
5159        assert_eq!(task.status, TaskStatus::New);
5160        assert_eq!(task.auto_unblock_count, 1);
5161        assert_eq!(
5162            task.auto_unblock_last_reason, "Timeout",
5163            "reason must be stored on first auto-unblock"
5164        );
5165    }
5166
5167    // ── classify_failure: sparse checkout (regression for substring false positive) ──
5168
5169    #[serial(cooldown_state)]
5170    #[test]
5171    fn classify_failure_sparse_checkout_not_parse_error() {
5172        // Regression test for #1204: "sparse" substring contains "parse",
5173        // so overly broad substring match would misclassify git sparse-checkout errors
5174        let category = classify_failure("error: cannot reset paths in a sparse checkout", "error");
5175        assert_ne!(
5176            category,
5177            FailureCategory::ParseError,
5178            "sparse checkout errors must NOT be classified as ParseError"
5179        );
5180        assert_eq!(
5181            category,
5182            FailureCategory::Unknown,
5183            "sparse checkout errors should be Unknown (not recoverable auto-unblock)"
5184        );
5185    }
5186
5187    #[serial(cooldown_state)]
5188    #[test]
5189    fn classify_failure_sparse_index_not_parse_error() {
5190        // Another sparse-checkout variant that contains "parse"
5191        let category = classify_failure("failed due to sparse index configuration", "error");
5192        assert_ne!(category, FailureCategory::ParseError);
5193        assert_eq!(category, FailureCategory::Unknown);
5194    }
5195
5196    // ── classify_failure: truncated (issue #3473) ───────────────────────
5197
5198    /// A review output truncated by the model's token budget (opencode
5199    /// step_finish reason=length) must classify as recoverable, so a task
5200    /// blocked after repeated truncations can be auto-unblocked instead of
5201    /// requiring manual intervention.
5202    #[serial(cooldown_state)]
5203    #[test]
5204    fn classify_failure_truncated_is_recoverable() {
5205        let category = classify_failure(
5206            "truncated: review output was cut off before completion \
5207             (output/reasoning token budget exceeded)",
5208            "truncated",
5209        );
5210        assert_eq!(
5211            category,
5212            FailureCategory::ParseError,
5213            "truncated outcome must classify as a recoverable parse-style failure"
5214        );
5215        assert!(
5216            category.is_recoverable(),
5217            "truncated failures must be recoverable so auto-unblock can retry"
5218        );
5219    }
5220
5221    #[serial(cooldown_state)]
5222    #[test]
5223    fn dispatching_key_includes_repo_for_cross_project_isolation() {
5224        let dispatching: Arc<DashMap<String, String>> = Arc::new(DashMap::new());
5225
5226        // Lock task 42 in repo A
5227        let key_a = "owner/repo-a/42".to_string();
5228        dispatching.insert(key_a.clone(), "42".to_string());
5229
5230        // Same task ID in repo B should NOT be blocked
5231        let key_b = "owner/repo-b/42".to_string();
5232        assert!(dispatching.contains_key(&key_a));
5233        assert!(
5234            !dispatching.contains_key(&key_b),
5235            "same task ID in different repo should not be blocked"
5236        );
5237    }
5238
5239    #[serial(cooldown_state)]
5240    #[tokio::test]
5241    async fn emit_degraded_agents_writes_metric_when_three_or_more_agents_degraded() {
5242        cooldown::reset_global_state().await;
5243
5244        let store = Arc::new(TaskStore::open_memory().await.unwrap());
5245
5246        // Create a router and set deterministic available agents
5247        let mut config = RouterConfig::default();
5248        config
5249            .model_map
5250            .entry("medium".to_string())
5251            .or_default()
5252            .insert(
5253                "test-agent-3a".to_string(),
5254                vec!["test-model-a".to_string()],
5255            );
5256        config
5257            .model_map
5258            .entry("medium".to_string())
5259            .or_default()
5260            .insert(
5261                "test-agent-3b".to_string(),
5262                vec!["test-model-b".to_string()],
5263            );
5264        config
5265            .model_map
5266            .entry("medium".to_string())
5267            .or_default()
5268            .insert(
5269                "test-agent-3c".to_string(),
5270                vec!["test-model-c".to_string()],
5271            );
5272        config
5273            .model_map
5274            .entry("medium".to_string())
5275            .or_default()
5276            .insert(
5277                "test-agent-3d".to_string(),
5278                vec!["test-model-d".to_string()],
5279            );
5280        let mut router = Router::new(config);
5281        router.available_agents = vec![
5282            "test-agent-3a".to_string(),
5283            "test-agent-3b".to_string(),
5284            "test-agent-3c".to_string(),
5285            "test-agent-3d".to_string(),
5286        ];
5287
5288        // Place three agents into cooldown
5289        set_agent_cooldown("test-agent-3a", 3600).await;
5290        set_agent_cooldown("test-agent-3b", 3600).await;
5291        set_agent_cooldown("test-agent-3c", 3600).await;
5292
5293        // Call the helper and assert KV metrics written
5294        emit_degraded_agents_if_needed(&router.available_agents, &router.config, Some(&store))
5295            .await;
5296
5297        // Count metric always written
5298        let count_val = store
5299            .kv_get("metrics:orch.agents_degraded.count")
5300            .await
5301            .unwrap();
5302        assert_eq!(count_val.as_deref(), Some("3"));
5303
5304        // Alert metric set to "1" when threshold crossed
5305        let alert_val = store
5306            .kv_get("metrics:orch.agents_degraded.alert")
5307            .await
5308            .unwrap();
5309        assert_eq!(alert_val.as_deref(), Some("1"));
5310    }
5311
5312    #[serial(cooldown_state)]
5313    #[tokio::test]
5314    async fn emit_degraded_agents_clears_alert_when_below_threshold() {
5315        cooldown::reset_global_state().await;
5316
5317        let store = Arc::new(TaskStore::open_memory().await.unwrap());
5318
5319        let mut config = RouterConfig::default();
5320        config
5321            .model_map
5322            .entry("medium".to_string())
5323            .or_default()
5324            .insert(
5325                "test-agent-2a".to_string(),
5326                vec!["test-model-a".to_string()],
5327            );
5328        config
5329            .model_map
5330            .entry("medium".to_string())
5331            .or_default()
5332            .insert(
5333                "test-agent-2b".to_string(),
5334                vec!["test-model-b".to_string()],
5335            );
5336        let mut router = Router::new(config);
5337        router.available_agents = vec!["test-agent-2a".to_string(), "test-agent-2b".to_string()];
5338
5339        // Place only two agents into cooldown — below the threshold of 3
5340        set_agent_cooldown("test-agent-2a", 3600).await;
5341        set_agent_cooldown("test-agent-2b", 3600).await;
5342
5343        emit_degraded_agents_if_needed(&router.available_agents, &router.config, Some(&store))
5344            .await;
5345
5346        // Count metric still written (always-emit)
5347        let count_val = store
5348            .kv_get("metrics:orch.agents_degraded.count")
5349            .await
5350            .unwrap();
5351        assert_eq!(count_val.as_deref(), Some("2"));
5352
5353        // Alert metric cleared (set to "0") — no WARN should fire
5354        let alert_val = store
5355            .kv_get("metrics:orch.agents_degraded.alert")
5356            .await
5357            .unwrap();
5358        assert_eq!(alert_val.as_deref(), Some("0"));
5359
5360        let stale_pool_alert = store
5361            .kv_get("metrics:orch.model_pool_stale_persistent.alert")
5362            .await
5363            .unwrap();
5364        assert_eq!(stale_pool_alert.as_deref(), Some("0"));
5365    }
5366
5367    #[serial(cooldown_state)]
5368    #[tokio::test]
5369    async fn emit_degraded_agents_sets_stale_pool_alert_for_persistent_model_failures() {
5370        cooldown::reset_global_state().await;
5371
5372        let store = Arc::new(TaskStore::open_memory().await.unwrap());
5373
5374        let mut config = RouterConfig::default();
5375        config
5376            .model_map
5377            .entry("medium".to_string())
5378            .or_default()
5379            .insert(
5380                "test-agent-stale".to_string(),
5381                vec!["model-a".to_string(), "model-b".to_string()],
5382            );
5383        let mut router = Router::new(config);
5384        router.available_agents = vec!["test-agent-stale".to_string()];
5385
5386        // 50% cooled + persistent reason should trigger stale-pool alert.
5387        record_persistent_model_failure("test-agent-stale", "model-a").await;
5388
5389        emit_degraded_agents_if_needed(&router.available_agents, &router.config, Some(&store))
5390            .await;
5391
5392        let stale_pool_alert = store
5393            .kv_get("metrics:orch.model_pool_stale_persistent.alert")
5394            .await
5395            .unwrap();
5396        assert_eq!(stale_pool_alert.as_deref(), Some("1"));
5397    }
5398
5399    // ── classify_comment tests ──────────────────────────────────────────
5400
5401    #[serial(cooldown_state)]
5402    #[test]
5403    fn classify_skip_already_processed() {
5404        let action = classify_comment(
5405            "@orch /retry",
5406            Some("https://api.github.com/repos/o/r/issues/1"),
5407            "@bot",
5408            true,
5409        );
5410        assert_eq!(action, CommentAction::Skip);
5411    }
5412
5413    #[serial(cooldown_state)]
5414    #[test]
5415    fn classify_skip_irrelevant_comment() {
5416        let action = classify_comment("just a regular comment", None, "@bot", false);
5417        assert_eq!(action, CommentAction::Skip);
5418    }
5419
5420    #[serial(cooldown_state)]
5421    #[test]
5422    fn classify_command_without_mention() {
5423        let action = classify_comment(
5424            "/retry",
5425            Some("https://api.github.com/repos/o/r/issues/42"),
5426            "@bot",
5427            false,
5428        );
5429        assert_eq!(
5430            action,
5431            CommentAction::ExecuteCommand {
5432                command: OwnerCommand::Retry,
5433                issue_num: "42".to_string(),
5434            }
5435        );
5436    }
5437
5438    #[serial(cooldown_state)]
5439    #[test]
5440    fn classify_command_with_mention() {
5441        let action = classify_comment(
5442            "@orch /close",
5443            Some("https://api.github.com/repos/o/r/issues/7"),
5444            "@bot",
5445            false,
5446        );
5447        assert_eq!(
5448            action,
5449            CommentAction::ExecuteCommandForMention {
5450                command: OwnerCommand::Close,
5451                issue_num: "7".to_string(),
5452            }
5453        );
5454    }
5455
5456    #[serial(cooldown_state)]
5457    #[test]
5458    fn classify_mention_without_command() {
5459        let action = classify_comment(
5460            "@orch can you look at this?",
5461            Some("https://api.github.com/repos/o/r/issues/99"),
5462            "@bot",
5463            false,
5464        );
5465        assert_eq!(
5466            action,
5467            CommentAction::CreateMentionTask {
5468                issue_num: Some("99".to_string()),
5469            }
5470        );
5471    }
5472
5473    #[serial(cooldown_state)]
5474    #[test]
5475    fn classify_mention_without_issue_url() {
5476        let action = classify_comment("@orch help me", None, "@bot", false);
5477        assert_eq!(action, CommentAction::CreateMentionTask { issue_num: None });
5478    }
5479
5480    #[serial(cooldown_state)]
5481    #[test]
5482    fn classify_command_no_mention_no_url_skips() {
5483        let action = classify_comment("/retry", None, "@bot", false);
5484        assert_eq!(action, CommentAction::Skip);
5485    }
5486
5487    #[serial(cooldown_state)]
5488    #[test]
5489    fn classify_mention_via_current_user() {
5490        let action = classify_comment(
5491            "@bot please help",
5492            Some("https://api.github.com/repos/o/r/issues/5"),
5493            "@bot",
5494            false,
5495        );
5496        assert_eq!(
5497            action,
5498            CommentAction::CreateMentionTask {
5499                issue_num: Some("5".to_string()),
5500            }
5501        );
5502    }
5503
5504    #[serial(cooldown_state)]
5505    #[test]
5506    fn classify_command_with_mention_no_url_creates_task() {
5507        // @mention + command but no issue URL → can't run command, create mention task
5508        let action = classify_comment("@orch /retry", None, "@bot", false);
5509        assert_eq!(action, CommentAction::CreateMentionTask { issue_num: None });
5510    }
5511
5512    #[serial(cooldown_state)]
5513    #[test]
5514    fn mention_cursor_stops_advancing_after_gap() {
5515        let mut cursor = MentionCursor::default();
5516        cursor.advance("2026-01-01T00:00:00Z");
5517        cursor.block_on_gap();
5518        cursor.advance("2026-01-02T00:00:00Z");
5519
5520        assert_eq!(
5521            cursor.into_last_safe_ts().as_deref(),
5522            Some("2026-01-01T00:00:00Z")
5523        );
5524    }
5525
5526    #[serial(cooldown_state)]
5527    #[test]
5528    fn mention_cursor_tracks_max_timestamp_until_gap() {
5529        let mut cursor = MentionCursor::default();
5530        cursor.advance("2026-01-01T00:00:00Z");
5531        cursor.advance("2026-01-01T00:05:00Z");
5532        cursor.block_on_gap();
5533        cursor.advance("2026-01-01T00:10:00Z");
5534
5535        assert_eq!(
5536            cursor.into_last_safe_ts().as_deref(),
5537            Some("2026-01-01T00:05:00Z")
5538        );
5539    }
5540
5541    // ── scan_comments: acknowledge_mention failure does not advance cursor ────
5542
5543    /// Backend that tracks acknowledge_mention calls and can be configured to fail them.
5544    struct AckTrackingBackend {
5545        ack_calls: Mutex<Vec<String>>,
5546        posted: Mutex<Vec<String>>,
5547        ack_failure: bool,
5548        inner: NoopBackend,
5549    }
5550
5551    impl AckTrackingBackend {
5552        fn new(ack_failure: bool) -> Arc<Self> {
5553            Arc::new(Self {
5554                ack_calls: Mutex::new(Vec::new()),
5555                posted: Mutex::new(Vec::new()),
5556                ack_failure,
5557                inner: NoopBackend,
5558            })
5559        }
5560
5561        fn fail_on_ack(&self) -> bool {
5562            self.ack_failure
5563        }
5564    }
5565
5566    #[async_trait]
5567    impl ExternalBackend for AckTrackingBackend {
5568        fn name(&self) -> &'static str {
5569            "ack-tracking"
5570        }
5571
5572        async fn acknowledge_mention(&self, comment_id: &str) -> anyhow::Result<()> {
5573            self.ack_calls.lock().await.push(comment_id.to_string());
5574            if self.fail_on_ack() {
5575                // Return a transient error to simulate network glitch.
5576                anyhow::bail!("network error: temporary failure posting reaction");
5577            }
5578            Ok(())
5579        }
5580
5581        // Override get_authenticated_user to ensure scan proceeds.
5582        async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
5583            Ok(Some("bot".into()))
5584        }
5585
5586        // Override get_mentions to return empty (we use prefetched comments).
5587        async fn get_mentions(&self, _since: &str) -> anyhow::Result<Vec<Mention>> {
5588            Ok(vec![])
5589        }
5590
5591        // Delegate everything else to NoopBackend.
5592        async fn create_task(&self, t: &str, b: &str, l: &[String]) -> anyhow::Result<ExternalId> {
5593            self.inner.create_task(t, b, l).await
5594        }
5595        async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
5596            self.inner.get_task(id).await
5597        }
5598        async fn list_by_status(&self, s: Status) -> anyhow::Result<Vec<ExternalTask>> {
5599            self.inner.list_by_status(s).await
5600        }
5601        async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
5602            self.inner.list_routable().await
5603        }
5604        async fn post_comment(&self, id: &ExternalId, b: &str) -> anyhow::Result<()> {
5605            self.posted.lock().await.push(b.to_string());
5606            self.inner.post_comment(id, b).await
5607        }
5608        async fn set_labels(&self, id: &ExternalId, l: &[String]) -> anyhow::Result<()> {
5609            self.inner.set_labels(id, l).await
5610        }
5611        async fn remove_label(&self, id: &ExternalId, l: &str) -> anyhow::Result<()> {
5612            self.inner.remove_label(id, l).await
5613        }
5614        async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
5615            self.inner.get_sub_issues(id).await
5616        }
5617        async fn create_sub_task(
5618            &self,
5619            p: &ExternalId,
5620            t: &str,
5621            b: &str,
5622            l: &[String],
5623        ) -> anyhow::Result<ExternalId> {
5624            self.inner.create_sub_task(p, t, b, l).await
5625        }
5626        async fn ensure_status_label(&self, l: &str) -> anyhow::Result<()> {
5627            self.inner.ensure_status_label(l).await
5628        }
5629        async fn has_open_issue_with_title(&self, t: &str, l: &str) -> anyhow::Result<bool> {
5630            self.inner.has_open_issue_with_title(t, l).await
5631        }
5632        async fn health_check(&self) -> anyhow::Result<()> {
5633            self.inner.health_check().await
5634        }
5635        async fn is_pr_merged(&self, b: &str) -> anyhow::Result<bool> {
5636            self.inner.is_pr_merged(b).await
5637        }
5638        async fn update_status(&self, id: &ExternalId, s: Status) -> anyhow::Result<()> {
5639            self.inner.update_status(id, s).await
5640        }
5641    }
5642
5643    /// When acknowledge_mention fails for CreateMentionTask, the cursor must NOT
5644    /// advance and no mention task should be created. The next tick will retry.
5645    #[serial(cooldown_state)]
5646    #[tokio::test]
5647    async fn create_mention_task_skips_on_ack_failure() {
5648        cooldown::reset_global_state().await;
5649        let backend: Arc<AckTrackingBackend> = AckTrackingBackend::new(true);
5650        let store: Arc<TaskStore> = Arc::new(TaskStore::open_memory().await.unwrap());
5651
5652        // Set an initial cursor so we can verify it wasn't advanced.
5653        let initial_ts = "2026-01-01T00:00:00Z";
5654        store
5655            .kv_set("mentions_last_checked", initial_ts)
5656            .await
5657            .unwrap();
5658
5659        let mention = Mention {
5660            id: "mention-abc".into(),
5661            body: "@bot can you help?".into(),
5662            author: "alice".into(),
5663            created_at: "2026-01-02T00:00:00Z".into(),
5664            issue_url: Some("https://api.github.com/repos/owner/repo/issues/42".into()),
5665        };
5666
5667        let backend_trait: Arc<dyn ExternalBackend> = Arc::<AckTrackingBackend>::clone(&backend);
5668        let task_manager = Arc::new(TaskManager::new(Arc::clone(&backend_trait)));
5669
5670        scan_comments(
5671            &backend_trait,
5672            Some(&store),
5673            "owner/repo",
5674            &task_manager,
5675            Some(&[mention]),
5676        )
5677        .await
5678        .unwrap();
5679
5680        // acknowledge_mention was called with the mention ID.
5681        let calls = backend.ack_calls.lock().await;
5682        assert_eq!(
5683            &**calls,
5684            &["mention-abc"],
5685            "acknowledge_mention must be called"
5686        );
5687
5688        // No mention task was created.
5689        let all = store.list_all("owner/repo").await.unwrap();
5690        assert!(
5691            all.is_empty(),
5692            "no task should be created when acknowledge_mention fails"
5693        );
5694
5695        // Cursor was NOT advanced.
5696        let cursor = store.kv_get("mentions_last_checked").await.unwrap();
5697        assert_eq!(
5698            cursor.as_deref(),
5699            Some(initial_ts),
5700            "cursor must not advance when acknowledge_mention fails"
5701        );
5702    }
5703
5704    /// When acknowledge_mention fails for ExecuteCommandForMention, handle_slash_command
5705    /// must NOT be called and no mention task should be created.
5706    #[serial(cooldown_state)]
5707    #[tokio::test]
5708    async fn execute_command_for_mention_skips_on_ack_failure() {
5709        cooldown::reset_global_state().await;
5710        let backend: Arc<AckTrackingBackend> = AckTrackingBackend::new(true);
5711        let store: Arc<TaskStore> = Arc::new(TaskStore::open_memory().await.unwrap());
5712
5713        let initial_ts = "2026-01-01T00:00:00Z";
5714        store
5715            .kv_set("mentions_last_checked", initial_ts)
5716            .await
5717            .unwrap();
5718
5719        // Mention with a slash command and issue URL → ExecuteCommandForMention.
5720        let mention = Mention {
5721            id: "mention-def".into(),
5722            body: "@bot /close".into(),
5723            author: "alice".into(),
5724            created_at: "2026-01-02T00:00:00Z".into(),
5725            issue_url: Some("https://api.github.com/repos/owner/repo/issues/42".into()),
5726        };
5727
5728        let backend_trait: Arc<dyn ExternalBackend> = Arc::<AckTrackingBackend>::clone(&backend);
5729        let task_manager = Arc::new(TaskManager::new(Arc::clone(&backend_trait)));
5730
5731        scan_comments(
5732            &backend_trait,
5733            Some(&store),
5734            "owner/repo",
5735            &task_manager,
5736            Some(&[mention]),
5737        )
5738        .await
5739        .unwrap();
5740
5741        // acknowledge_mention was called.
5742        let calls = backend.ack_calls.lock().await;
5743        assert_eq!(&**calls, &["mention-def"]);
5744
5745        // No mention task was created (handle_slash_command was not called).
5746        let all = store.list_all("owner/repo").await.unwrap();
5747        assert!(
5748            all.is_empty(),
5749            "no task should be created when acknowledge_mention fails for ExecuteCommandForMention"
5750        );
5751
5752        // Cursor was NOT advanced.
5753        let cursor = store.kv_get("mentions_last_checked").await.unwrap();
5754        assert_eq!(
5755            cursor.as_deref(),
5756            Some(initial_ts),
5757            "cursor must not advance when acknowledge_mention fails for ExecuteCommandForMention"
5758        );
5759    }
5760
5761    // ── slash commands retry after a transient GitHub error ──────────────────
5762
5763    /// GitHub stub whose `get_issue` fails once, then succeeds.
5764    #[derive(Default)]
5765    struct FlakyGh {
5766        get_issue_calls: AtomicUsize,
5767    }
5768
5769    #[async_trait]
5770    impl CommandGh for FlakyGh {
5771        async fn get_issue(&self, _repo: &str, number: &str) -> anyhow::Result<GitHubIssue> {
5772            if self.get_issue_calls.fetch_add(1, Ordering::SeqCst) == 0 {
5773                anyhow::bail!("network error: temporary failure fetching issue");
5774            }
5775            Ok(GitHubIssue {
5776                number: number.parse().unwrap_or(0),
5777                id: 1,
5778                title: "t".into(),
5779                body: None,
5780                state: "open".into(),
5781                labels: Vec::new(),
5782                user: GitHubUser {
5783                    login: "alice".into(),
5784                },
5785                created_at: String::new(),
5786                updated_at: String::new(),
5787                html_url: String::new(),
5788                node_id: None,
5789                pull_request: None,
5790                author_association: Some("OWNER".into()),
5791                state_reason: None,
5792            })
5793        }
5794
5795        async fn is_collaborator(&self, _repo: &str, _username: &str) -> anyhow::Result<bool> {
5796            Ok(true)
5797        }
5798
5799        async fn close_issue(&self, _repo: &str, _number: &str) -> anyhow::Result<()> {
5800            Ok(())
5801        }
5802    }
5803
5804    /// A transient `get_issue` failure must leave the cursor before the comment so
5805    /// the next scan retries it — and the command must then run exactly once.
5806    #[serial(cooldown_state)]
5807    #[tokio::test]
5808    async fn slash_command_retries_after_transient_fetch_failure() {
5809        cooldown::reset_global_state().await;
5810        let backend: Arc<AckTrackingBackend> = AckTrackingBackend::new(false);
5811        let store: Arc<TaskStore> = Arc::new(TaskStore::open_memory().await.unwrap());
5812        let initial_ts = "2026-01-01T00:00:00Z";
5813
5814        let mention = Mention {
5815            id: "mention-ghi".into(),
5816            body: "@bot /unblock".into(),
5817            author: "alice".into(),
5818            created_at: "2026-01-02T00:00:00Z".into(),
5819            issue_url: Some("https://api.github.com/repos/owner/repo/issues/42".into()),
5820        };
5821
5822        let backend_trait: Arc<dyn ExternalBackend> = Arc::<AckTrackingBackend>::clone(&backend);
5823        let task_manager = Arc::new(TaskManager::new(Arc::clone(&backend_trait)));
5824        let gh = FlakyGh::default();
5825        let mut cursor = MentionCursor::default();
5826
5827        // First scan: get_issue fails.
5828        let advanced_safely = handle_slash_command(
5829            &backend_trait,
5830            Some(&store),
5831            "owner/repo",
5832            &task_manager,
5833            &gh,
5834            &mention,
5835            &OwnerCommand::Unblock,
5836            &mut cursor,
5837        )
5838        .await
5839        .unwrap();
5840
5841        assert!(
5842            !advanced_safely,
5843            "a transient fetch failure must stop cursor advancement"
5844        );
5845        assert!(
5846            cursor.last_safe_ts.is_none(),
5847            "cursor must stay before the comment so the next tick retries it"
5848        );
5849        assert!(
5850            store.list_all("owner/repo").await.unwrap().is_empty(),
5851            "no mention task on a transient failure"
5852        );
5853        assert!(
5854            backend.posted.lock().await.is_empty(),
5855            "nothing is posted to GitHub on a transient failure"
5856        );
5857        assert_eq!(
5858            filter_mentions_by_since(slice::from_ref(&mention), initial_ts).len(),
5859            1,
5860            "the comment is still in range for the next scan"
5861        );
5862
5863        // Second scan: get_issue succeeds and the command runs.
5864        let mut cursor = MentionCursor::default();
5865        let advanced_safely = handle_slash_command(
5866            &backend_trait,
5867            Some(&store),
5868            "owner/repo",
5869            &task_manager,
5870            &gh,
5871            &mention,
5872            &OwnerCommand::Unblock,
5873            &mut cursor,
5874        )
5875        .await
5876        .unwrap();
5877
5878        assert!(advanced_safely);
5879        assert_eq!(
5880            cursor.into_last_safe_ts().as_deref(),
5881            Some("2026-01-02T00:00:00Z"),
5882            "cursor advances once the command actually runs"
5883        );
5884        assert_eq!(
5885            backend.posted.lock().await.len(),
5886            1,
5887            "the command runs once, posting a single confirmation"
5888        );
5889        assert_eq!(
5890            store.list_all("owner/repo").await.unwrap().len(),
5891            1,
5892            "one sentinel mention task for the executed command"
5893        );
5894    }
5895
5896    /// In the plain `ExecuteCommand` arm the GitHub client points at a dead port
5897    /// under `cfg(test)`, so `get_issue` always fails — the cursor must stay put.
5898    #[serial(cooldown_state)]
5899    #[tokio::test]
5900    async fn execute_command_keeps_cursor_on_fetch_failure() {
5901        cooldown::reset_global_state().await;
5902        let backend: Arc<AckTrackingBackend> = AckTrackingBackend::new(false);
5903        let store: Arc<TaskStore> = Arc::new(TaskStore::open_memory().await.unwrap());
5904
5905        let initial_ts = "2026-01-01T00:00:00Z";
5906        store
5907            .kv_set("mentions_last_checked", initial_ts)
5908            .await
5909            .unwrap();
5910
5911        // Slash command without a mention → ExecuteCommand.
5912        let comment = Mention {
5913            id: "comment-jkl".into(),
5914            body: "/unblock".into(),
5915            author: "alice".into(),
5916            created_at: "2026-01-02T00:00:00Z".into(),
5917            issue_url: Some("https://api.github.com/repos/owner/repo/issues/42".into()),
5918        };
5919
5920        let backend_trait: Arc<dyn ExternalBackend> = Arc::<AckTrackingBackend>::clone(&backend);
5921        let task_manager = Arc::new(TaskManager::new(Arc::clone(&backend_trait)));
5922
5923        scan_comments(
5924            &backend_trait,
5925            Some(&store),
5926            "owner/repo",
5927            &task_manager,
5928            Some(&[comment]),
5929        )
5930        .await
5931        .unwrap();
5932
5933        assert!(
5934            backend.posted.lock().await.is_empty(),
5935            "nothing is posted when the issue fetch fails"
5936        );
5937        assert_eq!(
5938            store
5939                .kv_get("mentions_last_checked")
5940                .await
5941                .unwrap()
5942                .as_deref(),
5943            Some(initial_ts),
5944            "cursor must not advance past a command that never ran"
5945        );
5946    }
5947
5948    // ── is_ci_failure_block ────────────────────────────────────────────────
5949
5950    fn make_task(block_reason: Option<String>) -> Task {
5951        Task {
5952            id: 1,
5953            external_id: None,
5954            repo: "owner/repo".to_string(),
5955            origin: String::new(),
5956            title: String::new(),
5957            body: String::new(),
5958            status: TaskStatus::Blocked,
5959            source: String::new(),
5960            source_id: String::new(),
5961            author: String::new(),
5962            url: String::new(),
5963            labels: vec![],
5964            agent: None,
5965            model: None,
5966            complexity: String::new(),
5967            estimate: 0,
5968            route_reason: String::new(),
5969            agent_profile: String::new(),
5970            route_attempts: 0,
5971            attempts: 0,
5972            branch: String::new(),
5973            worktree: String::new(),
5974            worktree_cleaned: false,
5975            owner_node: None,
5976            summary: String::new(),
5977            last_error: String::new(),
5978            parent_id: None,
5979            block_reason,
5980            pr_number: Some(42),
5981            pr_review_context: String::new(),
5982            last_review_ts: String::new(),
5983            review_ts_map: String::new(),
5984            last_comment_review_ts: String::new(),
5985            merge_conflict_retries: 0,
5986            ci_merge_failures: 0,
5987            pr_create_failures: 0,
5988            push_failures: 0,
5989            network_retries: 0,
5990            timeout_retries: 0,
5991            review_agent_failures: 0,
5992            review_resets: 0,
5993            review_cycles: 0,
5994            review_invocations: 0,
5995            needs_review_refires: 0,
5996            input_tokens: 0,
5997            output_tokens: 0,
5998            total_cost_usd: 0.0,
5999            model_reroute_chain: String::new(),
6000            limit_reroute_chain: String::new(),
6001            memory: vec![],
6002            delegations: vec![],
6003            auto_unblock_count: 0,
6004            auto_unblock_last_at: String::new(),
6005            auto_unblock_last_reason: String::new(),
6006            ci_recovery_count: 0,
6007            no_code_reroutes: 0,
6008            no_code_last_agent: String::new(),
6009            created_at: String::new(),
6010            updated_at: String::new(),
6011        }
6012    }
6013
6014    #[serial(cooldown_state)]
6015    #[test]
6016    fn is_ci_failure_block_matches_ci_failure_limit() {
6017        let task = make_task(Some(ci_failure_limit_reason(CI_FAILURE_AUTO_MERGE_STAGE)));
6018        assert!(is_ci_failure_block(&task));
6019    }
6020
6021    #[serial(cooldown_state)]
6022    #[test]
6023    fn is_ci_failure_block_matches_ci_checks_timeout() {
6024        let task = make_task(Some(
6025            "CI checks timed out after 3 auto-merge failures".to_string(),
6026        ));
6027        assert!(is_ci_failure_block(&task));
6028    }
6029
6030    #[serial(cooldown_state)]
6031    #[test]
6032    fn is_ci_failure_block_false_for_before_review() {
6033        let task = make_task(Some(ci_failure_limit_reason(
6034            CI_FAILURE_BEFORE_REVIEW_STAGE,
6035        )));
6036        assert!(
6037            !is_ci_failure_block(&task),
6038            "pre-review CI blocks must not enter the recovery sweep"
6039        );
6040    }
6041
6042    #[serial(cooldown_state)]
6043    #[test]
6044    fn is_ci_failure_block_false_for_bootstrap() {
6045        let task = make_task(Some(
6046            "CI failure limit (3) reached after the CI bootstrap merge".to_string(),
6047        ));
6048        assert!(!is_ci_failure_block(&task));
6049    }
6050
6051    #[serial(cooldown_state)]
6052    #[test]
6053    fn is_ci_failure_block_false_for_regular_block() {
6054        let task = make_task(Some("waiting on input".to_string()));
6055        assert!(!is_ci_failure_block(&task));
6056    }
6057
6058    #[serial(cooldown_state)]
6059    #[test]
6060    fn is_ci_failure_block_false_for_none_reason() {
6061        let task = make_task(None);
6062        assert!(!is_ci_failure_block(&task));
6063    }
6064
6065    // ── ci_failure_unblock_cooldown_elapsed ────────────────────────────────
6066
6067    #[serial(cooldown_state)]
6068    #[test]
6069    fn ci_failure_cooldown_zero_count_immediate() {
6070        // count=0 means never attempted — always allow immediate attempt
6071        let task = make_task(None);
6072        assert!(ci_failure_unblock_cooldown_elapsed(&task));
6073    }
6074
6075    #[serial(cooldown_state)]
6076    #[test]
6077    fn ci_failure_cooldown_empty_last_at_immediate() {
6078        // count=1 but empty last_at means it was never recorded — allow immediate
6079        let mut task = make_task(None);
6080        task.auto_unblock_count = 1;
6081        assert!(ci_failure_unblock_cooldown_elapsed(&task));
6082    }
6083
6084    #[serial(cooldown_state)]
6085    #[test]
6086    fn ci_failure_cooldown_invalid_timestamp_immediate() {
6087        // invalid timestamp should not block
6088        let mut task = make_task(None);
6089        task.auto_unblock_count = 1;
6090        task.auto_unblock_last_at = "not-a-timestamp".to_string();
6091        assert!(ci_failure_unblock_cooldown_elapsed(&task));
6092    }
6093
6094    #[serial(cooldown_state)]
6095    #[test]
6096    fn ci_failure_cooldown_high_count_still_eventually_elapses() {
6097        // count >= 3 must NOT be a permanent block — verify a sufficiently old
6098        // timestamp eventually elapses the cooldown.
6099        let long_ago = (chrono::Utc::now() - chrono::Duration::days(30)).to_rfc3339();
6100        for count in [3i32, 5, 99] {
6101            let mut task = make_task(None);
6102            task.auto_unblock_count = count;
6103            task.auto_unblock_last_at = long_ago.clone();
6104            assert!(
6105                ci_failure_unblock_cooldown_elapsed(&task),
6106                "count={count} should eventually elapse"
6107            );
6108        }
6109    }
6110
6111    #[serial(cooldown_state)]
6112    #[test]
6113    fn ci_failure_cooldown_recent_timestamp_still_blocks() {
6114        // A recent timestamp should still gate the check at every count.
6115        let just_now = chrono::Utc::now().to_rfc3339();
6116        for count in [1i32, 2, 3, 99] {
6117            let mut task = make_task(None);
6118            task.auto_unblock_count = count;
6119            task.auto_unblock_last_at = just_now.clone();
6120            assert!(
6121                !ci_failure_unblock_cooldown_elapsed(&task),
6122                "count={count} should still be cooling down"
6123            );
6124        }
6125    }
6126
6127    // ── auto_unblock_ci_failure_blocked_tasks_global ───────────────────────
6128
6129    #[serial(cooldown_state)]
6130    #[tokio::test]
6131    async fn global_ci_failure_sweep_returns_ok_with_no_blocked_tasks() {
6132        cooldown::reset_global_state().await;
6133        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6134        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6135        let task_manager = Arc::new(TaskManager::with_store(
6136            backend,
6137            Arc::clone(&store),
6138            "owner/repo".to_string(),
6139        ));
6140        auto_unblock_ci_failure_blocked_tasks_global(
6141            &task_manager,
6142            &store,
6143            &Arc::new(DashSet::new()),
6144        )
6145        .await
6146        .unwrap();
6147    }
6148
6149    #[serial(cooldown_state)]
6150    #[tokio::test]
6151    async fn global_ci_failure_sweep_skips_tasks_in_cooldown() {
6152        // Tasks with a fresh auto_unblock_last_at are skipped before reaching GhHttp,
6153        // so this test works without a real GitHub token.
6154        cooldown::reset_global_state().await;
6155        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6156        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6157        let task_manager = Arc::new(TaskManager::with_store(
6158            backend,
6159            Arc::clone(&store),
6160            "active/repo".to_string(),
6161        ));
6162
6163        // Insert a CI-failure task from an inactive repo with a very recent last_at.
6164        let id = store
6165            .upsert_external(&crate::store::UpsertExternal {
6166                repo: "inactive/repo",
6167                ext_id: "10",
6168                title: "Old blocked task",
6169                body: "",
6170                author: "",
6171                url: "",
6172                labels: &[],
6173                origin: "github",
6174            })
6175            .await
6176            .unwrap();
6177        store.update_status(id, TaskStatus::Blocked).await.unwrap();
6178        let just_now = chrono::Utc::now().to_rfc3339();
6179        store
6180            .set_fields(
6181                id,
6182                &[
6183                    (
6184                        "block_reason",
6185                        serde_json::json!("CI failure limit reached during auto-merge"),
6186                    ),
6187                    ("pr_number", serde_json::json!(99)),
6188                    ("auto_unblock_count", serde_json::json!(1)),
6189                    ("auto_unblock_last_at", serde_json::json!(just_now)),
6190                ],
6191            )
6192            .await
6193            .unwrap();
6194
6195        auto_unblock_ci_failure_blocked_tasks_global(
6196            &task_manager,
6197            &store,
6198            &Arc::new(DashSet::new()),
6199        )
6200        .await
6201        .unwrap();
6202
6203        // Cooldown not elapsed — task must remain untouched.
6204        let task = store.get(id).await.unwrap();
6205        assert_eq!(
6206            task.auto_unblock_count, 1,
6207            "task in cooldown must not be processed"
6208        );
6209    }
6210
6211    #[serial(cooldown_state)]
6212    #[tokio::test]
6213    async fn global_ci_failure_sweep_ignores_pre_review_blocks() {
6214        cooldown::reset_global_state().await;
6215        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6216        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6217        let task_manager = Arc::new(TaskManager::with_store(
6218            backend,
6219            Arc::clone(&store),
6220            "active/repo".to_string(),
6221        ));
6222
6223        let id = store
6224            .upsert_external(&crate::store::UpsertExternal {
6225                repo: "inactive/repo",
6226                ext_id: "21",
6227                title: "CI failed before review",
6228                body: "",
6229                author: "",
6230                url: "",
6231                labels: &[],
6232                origin: "github",
6233            })
6234            .await
6235            .unwrap();
6236        store.update_status(id, TaskStatus::Blocked).await.unwrap();
6237        let reason = ci_failure_limit_reason(CI_FAILURE_BEFORE_REVIEW_STAGE);
6238        store
6239            .set_fields(
6240                id,
6241                &[
6242                    ("block_reason", serde_json::json!(&reason)),
6243                    ("pr_number", serde_json::json!(4102)),
6244                ],
6245            )
6246            .await
6247            .unwrap();
6248
6249        auto_unblock_ci_failure_blocked_tasks_global(
6250            &task_manager,
6251            &store,
6252            &Arc::new(DashSet::new()),
6253        )
6254        .await
6255        .unwrap();
6256
6257        let task = store.get(id).await.unwrap();
6258        assert_eq!(task.status, TaskStatus::Blocked);
6259        assert_eq!(task.block_reason.as_deref(), Some(reason.as_str()));
6260        assert_eq!(
6261            task.auto_unblock_count, 0,
6262            "pre-review CI blocks must not enter recovery"
6263        );
6264    }
6265
6266    #[serial(cooldown_state)]
6267    #[tokio::test]
6268    async fn global_ci_failure_sweep_ignores_non_ci_failure_blocks() {
6269        cooldown::reset_global_state().await;
6270        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6271        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6272        let task_manager = Arc::new(TaskManager::with_store(
6273            backend,
6274            Arc::clone(&store),
6275            "active/repo".to_string(),
6276        ));
6277
6278        // Insert a non-CI-failure blocked task — should be ignored entirely.
6279        let id = store
6280            .upsert_external(&crate::store::UpsertExternal {
6281                repo: "inactive/repo",
6282                ext_id: "20",
6283                title: "Manual block",
6284                body: "",
6285                author: "",
6286                url: "",
6287                labels: &[],
6288                origin: "github",
6289            })
6290            .await
6291            .unwrap();
6292        store.update_status(id, TaskStatus::Blocked).await.unwrap();
6293        store
6294            .set_fields(
6295                id,
6296                &[("block_reason", serde_json::json!("waiting for human input"))],
6297            )
6298            .await
6299            .unwrap();
6300
6301        auto_unblock_ci_failure_blocked_tasks_global(
6302            &task_manager,
6303            &store,
6304            &Arc::new(DashSet::new()),
6305        )
6306        .await
6307        .unwrap();
6308
6309        // Non-CI-failure tasks must remain blocked.
6310        let task = store.get(id).await.unwrap();
6311        assert_eq!(task.status, TaskStatus::Blocked);
6312    }
6313
6314    // ── auto_recover_rebroadcast_blocked_tasks_global ───────────────────────
6315
6316    #[serial(cooldown_state)]
6317    #[tokio::test]
6318    async fn global_rebroadcast_sweep_returns_ok_with_no_blocked_tasks() {
6319        cooldown::reset_global_state().await;
6320        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6321        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6322        let task_manager = Arc::new(TaskManager::with_store(
6323            backend,
6324            Arc::clone(&store),
6325            "owner/repo".to_string(),
6326        ));
6327        let router = router_with_healthy_review_agent();
6328        auto_recover_rebroadcast_blocked_tasks_global(
6329            &router,
6330            &task_manager,
6331            &store,
6332            &sweep_repos(),
6333        )
6334        .await
6335        .unwrap();
6336    }
6337
6338    #[serial(cooldown_state)]
6339    #[tokio::test]
6340    async fn global_rebroadcast_sweep_ignores_non_rebroadcast_blocks() {
6341        cooldown::reset_global_state().await;
6342        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6343        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6344        let task_manager = Arc::new(TaskManager::with_store(
6345            backend,
6346            Arc::clone(&store),
6347            "active/repo".to_string(),
6348        ));
6349        let router = router_with_healthy_review_agent();
6350
6351        let id = store
6352            .upsert_external(&crate::store::UpsertExternal {
6353                repo: "inactive/repo",
6354                ext_id: "30",
6355                title: "Manual block",
6356                body: "",
6357                author: "",
6358                url: "",
6359                labels: &[],
6360                origin: "github",
6361            })
6362            .await
6363            .unwrap();
6364        store.update_status(id, TaskStatus::Blocked).await.unwrap();
6365        store
6366            .set_fields(
6367                id,
6368                &[("block_reason", serde_json::json!("waiting for human input"))],
6369            )
6370            .await
6371            .unwrap();
6372        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
6373            .bind(id)
6374            .execute(store.pool())
6375            .await
6376            .unwrap();
6377
6378        auto_recover_rebroadcast_blocked_tasks_global(
6379            &router,
6380            &task_manager,
6381            &store,
6382            &sweep_repos(),
6383        )
6384        .await
6385        .unwrap();
6386
6387        let task = store.get(id).await.unwrap();
6388        assert_eq!(task.status, TaskStatus::Blocked);
6389        assert_eq!(
6390            task.block_reason.as_deref(),
6391            Some("waiting for human input")
6392        );
6393    }
6394
6395    #[serial(cooldown_state)]
6396    #[tokio::test]
6397    async fn global_rebroadcast_sweep_skips_freshly_blocked_tasks() {
6398        cooldown::reset_global_state().await;
6399        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6400        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6401        let task_manager = Arc::new(TaskManager::with_store(
6402            backend,
6403            Arc::clone(&store),
6404            "active/repo".to_string(),
6405        ));
6406        let router = router_with_healthy_review_agent();
6407
6408        let id = store
6409            .upsert_external(&crate::store::UpsertExternal {
6410                repo: "inactive/repo",
6411                ext_id: "40",
6412                title: "Just escalated",
6413                body: "",
6414                author: "",
6415                url: "",
6416                labels: &[],
6417                origin: "github",
6418            })
6419            .await
6420            .unwrap();
6421        store.update_status(id, TaskStatus::Blocked).await.unwrap();
6422        store
6423            .set_fields(
6424                id,
6425                &[("block_reason", serde_json::json!(REBROADCAST_BLOCK_REASON))],
6426            )
6427            .await
6428            .unwrap();
6429        // No backdating — escalated "just now" in this same tick, must not be
6430        // immediately un-blocked by the same pass.
6431
6432        auto_recover_rebroadcast_blocked_tasks_global(
6433            &router,
6434            &task_manager,
6435            &store,
6436            &sweep_repos(),
6437        )
6438        .await
6439        .unwrap();
6440
6441        let task = store.get(id).await.unwrap();
6442        assert_eq!(task.status, TaskStatus::Blocked);
6443    }
6444
6445    /// Regression test for #3532: a rebroadcast-blocked task whose repo is not
6446    /// the TaskManager's own repo must still be recovered. The sweep queries
6447    /// across all repos and writes through the store directly, bypassing the
6448    /// repo-scoped TaskManager
6449    #[serial(cooldown_state)]
6450    #[tokio::test]
6451    async fn global_rebroadcast_sweep_recovers_task_from_inactive_repo() {
6452        cooldown::reset_global_state().await;
6453        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6454        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6455        let task_manager = Arc::new(TaskManager::with_store(
6456            backend,
6457            Arc::clone(&store),
6458            "active/repo".to_string(),
6459        ));
6460        let router = router_with_healthy_review_agent();
6461
6462        let id = store
6463            .upsert_external(&crate::store::UpsertExternal {
6464                repo: "inactive/repo",
6465                ext_id: "458",
6466                title: "Rebroadcast blocked from inactive repo",
6467                body: "",
6468                author: "",
6469                url: "",
6470                labels: &[],
6471                origin: "github",
6472            })
6473            .await
6474            .unwrap();
6475        store.update_status(id, TaskStatus::Blocked).await.unwrap();
6476        store
6477            .set_fields(
6478                id,
6479                &[
6480                    ("block_reason", serde_json::json!(REBROADCAST_BLOCK_REASON)),
6481                    ("needs_review_refires", serde_json::json!(6)),
6482                ],
6483            )
6484            .await
6485            .unwrap();
6486        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
6487            .bind(id)
6488            .execute(store.pool())
6489            .await
6490            .unwrap();
6491
6492        auto_recover_rebroadcast_blocked_tasks_global(
6493            &router,
6494            &task_manager,
6495            &store,
6496            &sweep_repos(),
6497        )
6498        .await
6499        .unwrap();
6500
6501        let task = store.get(id).await.unwrap();
6502        assert_eq!(
6503            task.status,
6504            TaskStatus::NeedsReview,
6505            "cross-repo rebroadcast-blocked task must be recovered to needs_review"
6506        );
6507        assert!(
6508            task.block_reason.is_none(),
6509            "block_reason must be cleared on recovery"
6510        );
6511        assert_eq!(
6512            task.needs_review_refires, 0,
6513            "needs_review_refires must be reset to 0 on recovery"
6514        );
6515    }
6516
6517    /// Runs `try_unblock_ci_failure_task` against a mock GitHub that reports the
6518    /// given PR state, for a task blocked on a CI failure with PR #7
6519    async fn ci_failure_unblock_with_pr(state: &str, merged: bool) -> (Task, bool) {
6520        ci_failure_unblock(state, merged, "CI failure limit reached during auto-merge").await
6521    }
6522
6523    async fn ci_failure_unblock_open_with_reason(reason: &str) -> (Task, bool) {
6524        ci_failure_unblock("open", false, reason).await
6525    }
6526
6527    #[expect(
6528        clippy::await_holding_lock,
6529        reason = "the env lock stays held across the awaits so tests do not race on GH_TOKEN"
6530    )]
6531    async fn ci_failure_unblock(state: &str, merged: bool, block_reason: &str) -> (Task, bool) {
6532        let _env_guard = ENV_LOCK.lock().unwrap();
6533        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
6534        unsafe { env::set_var("GH_TOKEN", "test_token") };
6535
6536        let server = MockServer::start().await;
6537        Mock::given(method("GET"))
6538            .and(path("/repos/o/r/pulls/7"))
6539            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
6540                "number": 7,
6541                "title": "t",
6542                "body": null,
6543                "state": state,
6544                "head": { "ref": "task-branch", "sha": "abc" },
6545                "base": { "ref": "main", "sha": "def" },
6546                "mergeable": null,
6547                "mergeable_state": null,
6548                "merged": merged,
6549                "html_url": "https://example.test/o/r/pull/7"
6550            })))
6551            .mount(&server)
6552            .await;
6553        let gh = GhHttp::for_test(server.uri(), None);
6554
6555        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6556        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6557        let task_manager = Arc::new(TaskManager::with_store(
6558            backend,
6559            Arc::clone(&store),
6560            "o/r".to_string(),
6561        ));
6562        let id = store
6563            .upsert_external(&crate::store::UpsertExternal {
6564                repo: "o/r",
6565                ext_id: "900",
6566                title: "CI failure blocked",
6567                body: "",
6568                author: "",
6569                url: "",
6570                labels: &[],
6571                origin: "github",
6572            })
6573            .await
6574            .unwrap();
6575        store.update_status(id, TaskStatus::Blocked).await.unwrap();
6576        store
6577            .set_fields(
6578                id,
6579                &[
6580                    ("pr_number", serde_json::json!(7)),
6581                    ("block_reason", serde_json::json!(block_reason)),
6582                ],
6583            )
6584            .await
6585            .unwrap();
6586        let task = store.get(id).await.unwrap();
6587
6588        let unblocked = try_unblock_ci_failure_task(
6589            &gh,
6590            "o/r",
6591            &task_manager,
6592            &store,
6593            &task,
6594            &Arc::new(DashSet::new()),
6595        )
6596        .await
6597        .unwrap();
6598        (store.get(id).await.unwrap(), unblocked)
6599    }
6600
6601    #[serial(cooldown_state)]
6602    #[tokio::test]
6603    async fn ci_failure_recovery_keeps_a_task_blocked_when_its_pr_closed_unmerged() {
6604        let (task, unblocked) = ci_failure_unblock_with_pr("closed", false).await;
6605
6606        assert!(!unblocked);
6607        assert_eq!(task.status, TaskStatus::Blocked);
6608        let reason = task.block_reason.unwrap_or_default();
6609        assert!(
6610            reason.contains("PR #7 closed unmerged"),
6611            "block_reason must record the closed PR, got: {reason}"
6612        );
6613    }
6614
6615    #[serial(cooldown_state)]
6616    #[tokio::test]
6617    async fn ci_failure_recovery_marks_a_task_done_when_its_pr_merged() {
6618        let (task, unblocked) = ci_failure_unblock_with_pr("closed", true).await;
6619
6620        assert!(unblocked);
6621        assert_eq!(task.status, TaskStatus::Done);
6622        assert!(task.block_reason.is_none());
6623    }
6624
6625    #[serial(cooldown_state)]
6626    #[tokio::test]
6627    async fn ci_failure_recovery_skips_an_open_pr_with_no_approving_review() {
6628        let reason = ci_failure_limit_reason(CI_FAILURE_BEFORE_REVIEW_STAGE);
6629        let (task, unblocked) = ci_failure_unblock_open_with_reason(&reason).await;
6630
6631        assert!(!unblocked);
6632        assert_eq!(task.status, TaskStatus::Blocked);
6633        assert_eq!(task.block_reason.as_deref(), Some(reason.as_str()));
6634        assert_eq!(
6635            task.auto_unblock_count, 0,
6636            "unreviewed PRs must not arm auto-merge or count a recovery attempt"
6637        );
6638    }
6639
6640    #[serial(cooldown_state)]
6641    #[tokio::test]
6642    async fn ci_failure_recovery_skips_a_rewritten_reason_without_approval() {
6643        let reason = "CI failure limit reached during auto-merge (PR #7 still open, state: open)";
6644        let (task, unblocked) = ci_failure_unblock_open_with_reason(reason).await;
6645
6646        assert!(!unblocked);
6647        assert_eq!(task.status, TaskStatus::Blocked);
6648        assert_eq!(task.block_reason.as_deref(), Some(reason));
6649        assert_eq!(
6650            task.auto_unblock_count, 0,
6651            "a rewritten merge-time reason without a recorded approval must not recover"
6652        );
6653    }
6654
6655    /// With no routable review agent, the sweep must not reset the task, that
6656    /// would immediately re-exhaust the refire counter
6657    #[serial(cooldown_state)]
6658    #[tokio::test]
6659    async fn global_rebroadcast_sweep_skips_reset_without_routable_review_agent() {
6660        cooldown::reset_global_state().await;
6661        let store = Arc::new(TaskStore::open_memory().await.unwrap());
6662        let backend: Arc<dyn ExternalBackend> = IngestMockBackend::with_tasks(vec![]);
6663        let task_manager = Arc::new(TaskManager::with_store(
6664            backend,
6665            Arc::clone(&store),
6666            "active/repo".to_string(),
6667        ));
6668        // RouterConfig::default() has no "review" model map entries, so the one
6669        // available agent has no healthy model for "review" — nothing is routable.
6670        let router = Router::new_for_test(RouterConfig::default(), vec!["claude".to_string()]);
6671
6672        let id = store
6673            .upsert_external(&crate::store::UpsertExternal {
6674                repo: "inactive/repo",
6675                ext_id: "459",
6676                title: "Rebroadcast blocked, no routable agents",
6677                body: "",
6678                author: "",
6679                url: "",
6680                labels: &[],
6681                origin: "github",
6682            })
6683            .await
6684            .unwrap();
6685        store.update_status(id, TaskStatus::Blocked).await.unwrap();
6686        store
6687            .set_fields(
6688                id,
6689                &[("block_reason", serde_json::json!(REBROADCAST_BLOCK_REASON))],
6690            )
6691            .await
6692            .unwrap();
6693        sqlx::query("UPDATE tasks SET updated_at = '2020-01-01T00:00:00Z' WHERE id = ?")
6694            .bind(id)
6695            .execute(store.pool())
6696            .await
6697            .unwrap();
6698
6699        auto_recover_rebroadcast_blocked_tasks_global(
6700            &router,
6701            &task_manager,
6702            &store,
6703            &sweep_repos(),
6704        )
6705        .await
6706        .unwrap();
6707
6708        let task = store.get(id).await.unwrap();
6709        assert_eq!(task.status, TaskStatus::Blocked);
6710        assert_eq!(task.block_reason.as_deref(), Some(REBROADCAST_BLOCK_REASON));
6711    }
6712}