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