Skip to main content

orch/engine/tick/
mod.rs

1//! Core tick loop phases.
2//!
3//! The engine ticks every ~10 seconds. Each tick runs six phases:
4//! 1. Poll tmux for finished sessions
5//! 2. Recover stuck in-progress tasks
6//! 3. Route and dispatch:
7//!    - 3a. Route new tasks to agents
8//!    - 3b. Dispatch routed tasks (spawn agents)
9//! 4. Unblock parents whose children are all done
10//! 5. Run cron job scheduler
11//!
12//! [`tick_all`] runs them for every project. Phases 1-2 and 3b-5 run for all projects at
13//! once; only routing is serial, because it holds the router write lock. Store-wide work
14//! (`tick_global_sweeps`, `reconcile_dependencies`) runs once per tick, not once per project.
15
16mod dispatch;
17mod recovery;
18pub mod repo_context;
19
20use super::{EngineConfig, ProjectEngine};
21use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Status};
22use crate::channels::capture::CaptureService;
23use crate::channels::transport::Transport;
24use crate::cooldown::{github_circuit_remaining_secs, is_github_circuit_open};
25use crate::engine;
26use crate::engine::router::config as router_config;
27use crate::engine::router::{AllAgentsCooledError, Router, RouterConfig};
28use crate::engine::runner::{TaskRunner, WeightSignal};
29use crate::engine::sync;
30use crate::engine::tasks;
31use crate::engine::tasks::dependencies;
32use crate::engine::tasks::jobs;
33use crate::engine::tasks::{TaskManager, is_internal_id};
34use crate::engine::tick::repo_context::REPO_CONTEXT;
35use crate::github::http;
36use crate::store;
37use crate::store::StoreRoute;
38use crate::store::Task;
39use crate::store::TaskStatus;
40use crate::store::TaskStore;
41use crate::store::WaitingOnDependency;
42use crate::store::{store_set_by_id, store_touch_updated_at};
43use crate::sys::tmux::TmuxManager;
44use dashmap::{DashMap, DashSet};
45use dispatch::skips_agent;
46pub(crate) use dispatch::{
47    DispatchMode, dispatch_mode_from_router, dispatch_routed_tasks_global, tick_dispatch_tasks,
48};
49use futures::future;
50use recovery::{StuckTaskTiming, finalize_open_runs_for_recovery};
51pub(crate) use recovery::{
52    recover_untracked_repo_stuck_tasks, tick_detect_silent_agents, tick_recover_stuck_tasks,
53};
54use std::collections::HashMap;
55use std::collections::HashSet;
56use std::path::Path;
57use std::sync::Arc;
58use std::sync::OnceLock;
59use std::time::{Instant, SystemTime};
60use tokio::sync::RwLock;
61use tokio::sync::{Semaphore, mpsc};
62
63/// Per outer engine-loop quota for expensive routing calls.
64///
65/// Routing runs once per active project. Without a quota shared by all of them,
66/// `router.max_tasks_per_tick = 1` still permits one slow LLM routing call per
67/// project, multiplying 45s router timeouts into multi-minute watchdog stalls.
68pub(crate) struct RoutingTickQuota {
69    remaining: usize,
70}
71
72impl RoutingTickQuota {
73    pub(crate) fn new(max: usize) -> Self {
74        Self { remaining: max }
75    }
76
77    fn is_exhausted(&self) -> bool {
78        self.remaining == 0
79    }
80
81    fn remaining(&self) -> usize {
82        self.remaining
83    }
84
85    fn consume_one(&mut self) -> bool {
86        if self.remaining == 0 {
87            return false;
88        }
89        self.remaining -= 1;
90        true
91    }
92}
93
94/// Cleanup stale tmux sessions from previous engine runs.
95/// Called once from `serve()` before the main loop, never from a tick
96pub(crate) async fn startup_cleanup(tmux: &TmuxManager) {
97    let start_time = SystemTime::now()
98        .duration_since(SystemTime::UNIX_EPOCH)
99        .unwrap_or_default()
100        .as_secs();
101    tracing::info!(
102        start_time,
103        "running startup cleanup for stale tmux sessions"
104    );
105
106    match tmux.kill_stale_sessions(start_time).await {
107        Ok(killed) => {
108            if killed > 0 {
109                tracing::info!(killed, "startup cleanup killed stale sessions");
110            } else {
111                tracing::debug!("no stale tmux sessions found on startup");
112            }
113        }
114        Err(e) => {
115            tracing::warn!(error = %e, "failed to run startup cleanup");
116        }
117    }
118}
119
120async fn recover_routed_blocked_dispatch(
121    backend: &Arc<dyn ExternalBackend>,
122    store: &Arc<TaskStore>,
123    task_manager: &Arc<TaskManager>,
124    repo: &str,
125    task: &ExternalTask,
126    timing: &StuckTaskTiming,
127) {
128    tracing::warn!(
129        task_id = task.id.0,
130        age_mins = timing.age.num_minutes(),
131        threshold_mins = timing.threshold / 60,
132        "recovering routed task: dispatch blocked by stale tmux session → new"
133    );
134
135    let resolved_store_id = match store.resolve_task_id(repo, &task.id.0).await {
136        Ok(Some(id)) => Some(id),
137        Ok(None) => {
138            tracing::warn!(
139                task_id = %task.id.0,
140                repo,
141                "resolve_task_id returned None during routed-task recovery"
142            );
143            None
144        }
145        Err(e) => {
146            tracing::error!(
147                task_id = %task.id.0,
148                repo,
149                error = %e,
150                "resolve_task_id failed during routed-task recovery"
151            );
152            None
153        }
154    };
155
156    if let Some(store_id) = resolved_store_id {
157        if let Err(e) = store_set_by_id(
158            Some(store),
159            store_id,
160            &[
161                ("agent", serde_json::Value::Null),
162                ("model", serde_json::Value::Null),
163                ("route_attempts", serde_json::json!(0)),
164            ],
165        )
166        .await
167        {
168            tracing::warn!(
169                task_id = task.id.0,
170                ?e,
171                "failed to clear routing fields for routed stuck task — will retry next tick"
172            );
173            return;
174        }
175        finalize_open_runs_for_recovery(
176            store,
177            store_id,
178            "stuck-task recovery: stale session blocking dispatch killed",
179        )
180        .await;
181    }
182
183    if let Err(e) = task_manager.update_task_status(&task.id, Status::New).await {
184        tracing::warn!(
185            task_id = task.id.0,
186            ?e,
187            "failed to reset routed stuck task status"
188        );
189        return;
190    }
191
192    store::store_log_activity(
193        &Some(Arc::clone(store)),
194        repo,
195        &task.id.0,
196        "rerouted",
197        Some("routed"),
198        Some("new"),
199        None::<&str>,
200        None::<&str>,
201        Some(&serde_json::json!({
202            "failure_reason": "routed_blocked_by_existing_session",
203            "age_minutes": timing.age.num_minutes(),
204            "had_session": true,
205        })),
206    )
207    .await;
208
209    if !is_internal_id(&task.id.0) {
210        let backend_clone = Arc::clone(backend);
211        let task_id_clone = task.id.clone();
212        let body = format!(
213            "[{}] recovered: stuck routed task — existing tmux session blocked dispatch for {}m; cleared route for retry{}",
214            chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ"),
215            timing.age.num_minutes(),
216            engine::orch_footer()
217        );
218        tokio::spawn(async move {
219            if let Err(e) = backend_clone.post_comment(&task_id_clone, &body).await {
220                tracing::warn!(
221                    task_id = task_id_clone.0,
222                    ?e,
223                    "failed to post routed-task recovery comment"
224                );
225            }
226        });
227    }
228}
229
230/// Phase 1 of tick: poll tmux for finished sessions and clean them up.
231pub(crate) async fn tick_check_session_completions(
232    tmux: &Arc<TmuxManager>,
233    repo: &str,
234    capture: &Arc<CaptureService>,
235    store: &Arc<TaskStore>,
236) -> anyhow::Result<()> {
237    let _span = tracing::info_span!("engine.tick.phase1.sessions").entered();
238    let session_snapshot = tmux.snapshot().await;
239    // Derive the short project name from repo (owner/repo -> repo), matching
240    // TmuxManager::session_name's derivation exactly (including the ".git" strip)
241    // so a repo configured with a ".git" suffix doesn't silently fail to match
242    // its own live sessions here — leaving stuck-task recovery as the only
243    // (later, coarser-grained) safety net for this repo's session completions.
244    let repo_name = repo
245        .rsplit('/')
246        .next()
247        .unwrap_or(repo)
248        .trim_end_matches(".git");
249    for (session, active) in session_snapshot {
250        // Only handle sessions that belong to this repo/project.
251        if session.project != repo_name {
252            continue;
253        }
254
255        if !active {
256            tracing::info!(
257                session = %session.name,
258                task_id = %session.task_id,
259                "session completed, collecting results"
260            );
261            // Touch the store.updated_at immediately when we observe a completed
262            // session so the stuck-task recovery phase doesn't incorrectly
263            // reclaim this task while the runner is still finishing
264            // post-processing (race: session observed dead → tick reclaim).
265            // Best-effort: no-ops if the task isn't present in the store.
266            //
267            // session.task_id uses hyphens (e.g. "internal-63714") because the
268            // tmux session name sanitizes colons to hyphens. resolve_task_id only
269            // handles "internal:" prefix, so we must convert back before touching.
270            // Review sessions carry a "-review" suffix tracked under the main task.
271            let store_task_id = {
272                let base = session
273                    .task_id
274                    .strip_suffix("-review")
275                    .unwrap_or(&session.task_id);
276                if let Some(n) = base.strip_prefix("internal-") {
277                    format!("internal:{n}")
278                } else {
279                    base.to_string()
280                }
281            };
282            store_touch_updated_at(&Some(Arc::clone(store)), repo, &store_task_id).await;
283            // Unregister from capture service using the task id the capture service
284            // was registered under (task id without project prefix).
285            capture.unregister_session(repo, &session.task_id).await;
286            // Kill the actual tmux session name we discovered (do not reconstruct)
287            if let Err(e) = tmux.kill_session(&session.name).await {
288                tracing::debug!(
289                    session = %session.name,
290                    ?e,
291                    "kill_session failed (session may already be gone)"
292                );
293            }
294        }
295    }
296    Ok(())
297}
298
299/// The tier whose run timeout the task runs with: the tier of its stored model, which differs from
300/// its own complexity when the model came from an adjacent tier
301fn run_tier(router: &RouterConfig, task: &Task) -> String {
302    match (task.agent.as_deref(), task.model.as_deref()) {
303        (Some(a), Some(m)) if !m.is_empty() => router.tier_of_model(a, m, &task.complexity),
304        _ => task.complexity.clone(),
305    }
306}
307
308/// The router config for this tick, loaded on first use. A full load re-reads the config and
309/// repeats its startup warnings, so one tick shares one load across every live run
310fn tick_router(
311    cell: &OnceLock<RouterConfig>,
312    load: impl FnOnce() -> RouterConfig,
313) -> &RouterConfig {
314    cell.get_or_init(load)
315}
316
317fn should_use_backend(task_id: &str) -> bool {
318    !is_internal_id(task_id)
319}
320
321/**
322 * The three store-wide recovery sweeps, run once per tick rather than once per project.
323 *
324 * Each one reads every repo, so a per-project call duplicates the work. The NeedsReview
325 * sweep also reads `needs_review_refires` and then increments it, so concurrent per-project
326 * passes all see the same count and four projects burn four of the five refire attempts in
327 * one tick (#3864)
328 **/
329pub(crate) async fn tick_global_sweeps(
330    task_manager: &Arc<TaskManager>,
331    store: &Arc<TaskStore>,
332    router: &Router,
333    dispatching: &Arc<DashMap<String, String>>,
334    auto_merge_in_flight: &Arc<DashSet<String>>,
335    active_repos: &HashSet<String>,
336) {
337    // Global sweep for CI-failure blocked tasks from inactive or removed projects.
338    // auto_unblock_blocked_tasks runs inside sync_tick and is scoped to the active repo.
339    // Tasks blocked for projects no longer in orch config are never processed there.
340    // This sweep covers all repos so stale CI-failure blocks are eventually resolved.
341    if let Err(e) = sync::auto_unblock_ci_failure_blocked_tasks_global(
342        task_manager,
343        store,
344        auto_merge_in_flight,
345    )
346    .await
347    {
348        tracing::warn!(err = %e, "global CI-failure blocked sweep failed");
349    }
350
351    // Re-fire stale NeedsReview tasks and escalate persistently-stuck ones to
352    // Blocked, across all repos
353    if let Err(e) = sync::refire_and_escalate_stale_needs_review_global(
354        task_manager,
355        store,
356        router,
357        dispatching,
358        active_repos,
359    )
360    .await
361    {
362        tracing::warn!(err = %e, "global NeedsReview refire/escalation sweep failed");
363    }
364
365    // Recover rebroadcast-blocked tasks once a review agent is routable, across
366    // all repos
367    if let Err(e) = sync::auto_recover_rebroadcast_blocked_tasks_global(
368        router,
369        task_manager,
370        store,
371        active_repos,
372    )
373    .await
374    {
375        tracing::warn!(err = %e, "global rebroadcast-blocked recovery sweep failed");
376    }
377}
378
379/// Phase 3a of tick: route status:new tasks to an agent and transition them to status:routed.
380pub(crate) async fn tick_route_tasks(
381    backend: &Arc<dyn ExternalBackend>,
382    task_manager: &Arc<TaskManager>,
383    router: &mut Router,
384    store: &Arc<TaskStore>,
385    repo: &str,
386    routing_quota: &mut RoutingTickQuota,
387) -> anyhow::Result<()> {
388    let _span = tracing::info_span!("engine.tick.phase3a.route").entered();
389    if let Err(err) = dependencies::apply_claim_gates(store).await {
390        tracing::warn!(err = %err, "dependency claim gate failed");
391    }
392    if routing_quota.is_exhausted() {
393        tracing::debug!("routing quota exhausted for this tick — skipping repo routing phase");
394        return Ok(());
395    }
396
397    // Global GitHub 5xx circuit breaker — skip routing during sustained GitHub outages
398    // to avoid routing-heavy retry storms. Tasks will remain in 'new' status and be
399    // retried when the circuit closes.
400    if is_github_circuit_open() {
401        let remaining = github_circuit_remaining_secs();
402        tracing::info!(
403            remaining_secs = remaining,
404            "GitHub 5xx circuit breaker open — skipping routing phase"
405        );
406        return Ok(());
407    }
408    let new_tasks = task_manager.list_routable().await?;
409    let routable: Vec<&ExternalTask> = new_tasks
410        .iter()
411        .filter(|t| !skips_agent(&t.labels))
412        .collect();
413
414    // Pre-emptive health check: refresh degraded-agent flags once per tick,
415    // not per-task (previously this ran inside route() causing N redundant
416    // DB queries when routing N tasks in the same tick).
417    if !routable.is_empty() {
418        let start = Instant::now();
419        router.refresh_health(store).await;
420        tracing::debug!(
421            duration_ms = start.elapsed().as_millis(),
422            "router.refresh_health completed"
423        );
424    }
425
426    // Limit routing to the remaining global quota for this outer engine tick.
427    for task in routable.into_iter().take(routing_quota.remaining()) {
428        if !routing_quota.consume_one() {
429            break;
430        }
431        let _task_span = tracing::info_span!("engine.route", task_id = %task.id.0).entered();
432
433        let task_start = Instant::now();
434        match router.route(task, store, repo).await {
435            Ok(result) => {
436                tracing::debug!(task_id = %task.id.0, duration_ms = task_start.elapsed().as_millis(), "route completed");
437                // Store route result in store
438                if let Err(e) = router
439                    .store_route_result(&task.id.0, &result, store, repo)
440                    .await
441                {
442                    tracing::warn!(
443                        task_id = task.id.0,
444                        ?e,
445                        "failed to store route result; skipping Routed transition"
446                    );
447                    continue;
448                }
449
450                if is_internal_id(&task.id.0) {
451                    // Internal tasks: update DB status, skip GitHub label ops.
452                    if let Err(e) = task_manager
453                        .update_task_status(&task.id, Status::Routed)
454                        .await
455                    {
456                        tracing::warn!(
457                            task_id = task.id.0,
458                            ?e,
459                            "failed to set internal status:routed"
460                        );
461                        continue;
462                    }
463                } else {
464                    // Fire-and-forget: label operations are cosmetic (routing already
465                    // persisted in DB). Spawning them prevents blocking the tick loop
466                    // on 6-9 sequential HTTP calls (~3-9s overhead per routed task).
467                    let backend_clone = Arc::clone(backend);
468                    let task_id_clone = task.id.clone();
469                    let task_labels: Vec<String> = task.labels.clone();
470                    let new_labels = {
471                        let mut labels = vec![
472                            format!("agent:{}", result.agent),
473                            format!("complexity:{}", result.complexity),
474                        ];
475                        if let Some(ref model) = result.model {
476                            labels.push(format!("model:{model}"));
477                        }
478                        labels
479                    };
480                    tokio::spawn(async move {
481                        // Remove old agent/complexity/model labels
482                        for label in &task_labels {
483                            if (label.starts_with("agent:")
484                                || label.starts_with("complexity:")
485                                || label.starts_with("model:"))
486                                && let Err(e) =
487                                    backend_clone.remove_label(&task_id_clone, label).await
488                            {
489                                tracing::warn!(task_id = task_id_clone.0, label, error = %e, "failed to remove stale routing label during re-route");
490                            }
491                        }
492                        // Add new labels
493                        if let Err(e) = backend_clone.set_labels(&task_id_clone, &new_labels).await
494                        {
495                            tracing::warn!(
496                                task_id = task_id_clone.0,
497                                ?e,
498                                "failed to set routing labels"
499                            );
500                        }
501                    });
502
503                    // Transition to routed
504                    if let Err(e) = task_manager
505                        .update_task_status(&task.id, Status::Routed)
506                        .await
507                    {
508                        tracing::warn!(task_id = task.id.0, ?e, "failed to set status:routed");
509                        continue;
510                    }
511                }
512
513                // Dual-write: upsert task + store route result in SQLite
514                match store.upsert_external(&task.upsert_row(repo)).await {
515                    Ok(store_id) => {
516                        let profile_json =
517                            serde_json::to_string(&result.profile).unwrap_or_default();
518                        if let Err(e) = store
519                            .store_route(&crate::store::StoreRoute {
520                                id: store_id,
521                                agent: &result.agent,
522                                model: result.model.as_deref(),
523                                complexity: &result.complexity,
524                                estimate: result.estimate,
525                                reason: &result.reason,
526                                profile: &profile_json,
527                            })
528                            .await
529                        {
530                            tracing::debug!(
531                                task_id = task.id.0,
532                                ?e,
533                                "dual-write: store_route failed"
534                            );
535                        }
536                        if let Err(e) = store.update_status(store_id, TaskStatus::Routed).await {
537                            tracing::debug!(
538                                task_id = task.id.0,
539                                ?e,
540                                "dual-write: update_status failed"
541                            );
542                        }
543                        // Sync the estimate to GitHub Projects if the router assigned one.
544                        // Fire-and-forget: do NOT await inline — GraphQL mutations can take
545                        // up to 30 s and would block the entire tick loop on every routed task.
546                        if result.estimate > 0 {
547                            let backend_clone = Arc::clone(backend);
548                            let task_id = task.id.clone();
549                            let estimate = result.estimate;
550                            tokio::spawn(async move {
551                                if let Err(e) = backend_clone
552                                    .sync_estimate_to_project(&task_id, estimate)
553                                    .await
554                                {
555                                    tracing::debug!(
556                                        task_id = task_id.0,
557                                        estimate,
558                                        err = %e,
559                                        "dual-write: estimate project sync failed"
560                                    );
561                                }
562                            });
563                        }
564                    }
565                    Err(e) => {
566                        tracing::debug!(
567                            task_id = task.id.0,
568                            ?e,
569                            "dual-write: upsert_external failed"
570                        );
571                    }
572                }
573
574                if let Some(ref warning) = result.warning {
575                    tracing::warn!(task_id = task.id.0, warning, "routing sanity warning");
576                }
577
578                tracing::info!(
579                    task_id = task.id.0,
580                    agent = %result.agent,
581                    complexity = %result.complexity,
582                    reason = %result.reason,
583                    "task routed"
584                );
585            }
586            Err(e) => {
587                if let Some(cooled) = e.downcast_ref::<AllAgentsCooledError>() {
588                    tracing::error!(
589                        task_id = %task.id.0,
590                        scope = %cooled.scope(),
591                        remaining_secs = ?cooled.remaining_secs(),
592                        degraded = ?cooled.degraded(),
593                        "ALL AGENTS COOLED — no agent available to route this task. \
594                         Task stays in 'new' and will be retried on every tick. \
595                         Check `orch cooldown list` to see what is blocking dispatch."
596                    );
597                    continue;
598                }
599                if let Some(waiting) = e.downcast_ref::<WaitingOnDependency>() {
600                    tracing::info!(
601                        task_id = %task.id.0,
602                        blockers = %waiting.blockers.join(", "),
603                        "task is waiting on a dependency"
604                    );
605                    continue;
606                }
607                tracing::error!(task_id = task.id.0, ?e, "routing failed, skipping task");
608            }
609        }
610    }
611    Ok(())
612}
613
614/// Global routing sweep: route status:new tasks from inactive or removed repos.
615///
616/// `tick_route_tasks` is scoped to the active repo per-tick and never processes
617/// tasks whose `repo` field differs from the current project. When a project is
618/// removed from the orch config, its tasks accumulate in `new` indefinitely
619/// because no tick ever runs for that repo. This sweep covers all repos so
620/// orphaned new tasks are eventually routed.
621///
622/// `active_repos` must be the full set of currently-configured project repos,
623/// not just the repo of the tick that called this — mirroring
624/// `dispatch_routed_tasks_global` (see its doc comment for the "racing the real
625/// per-repo dispatch" failure mode this guards against). Filtering on
626/// `t.repo != current_repo` alone (the previous behavior) made every *other*
627/// active repo's new tasks look "orphaned" too and routed them a tick early,
628/// through the wrong repo's tick.
629pub(crate) async fn route_new_tasks_global(
630    router: &mut Router,
631    store: &Arc<TaskStore>,
632    active_repos: &HashSet<String>,
633    routing_quota: &mut RoutingTickQuota,
634) -> anyhow::Result<()> {
635    if routing_quota.is_exhausted() {
636        tracing::debug!("routing quota exhausted for this tick — skipping global routing sweep");
637        return Ok(());
638    }
639
640    let all_new = store.list_all_by_status_global(TaskStatus::New).await?;
641    let orphaned: Vec<&Task> = all_new
642        .iter()
643        .filter(|t| !active_repos.contains(&t.repo))
644        .filter(|t| !skips_agent(&t.labels))
645        .collect();
646
647    if orphaned.is_empty() {
648        return Ok(());
649    }
650
651    tracing::info!(
652        count = orphaned.len(),
653        "global routing sweep: found new tasks from inactive repos"
654    );
655
656    router.refresh_health(store).await;
657
658    for task in orphaned.into_iter().take(routing_quota.remaining()) {
659        if !routing_quota.consume_one() {
660            break;
661        }
662        let ext_task = tasks::store_task_to_external(task);
663        let task_start = Instant::now();
664        match router.route(&ext_task, store, &task.repo).await {
665            Ok(result) => {
666                tracing::debug!(
667                    task_id = %ext_task.id.0,
668                    repo = %task.repo,
669                    duration_ms = task_start.elapsed().as_millis(),
670                    "global sweep: route completed"
671                );
672                let profile_json = serde_json::to_string(&result.profile).unwrap_or_default();
673                if let Err(e) = store
674                    .store_route(&StoreRoute {
675                        id: task.id,
676                        agent: &result.agent,
677                        model: result.model.as_deref(),
678                        complexity: &result.complexity,
679                        estimate: result.estimate,
680                        reason: &result.reason,
681                        profile: &profile_json,
682                    })
683                    .await
684                {
685                    tracing::warn!(
686                        task_id = %ext_task.id.0,
687                        repo = %task.repo,
688                        err = %e,
689                        "global sweep: failed to store route result; skipping status update"
690                    );
691                    continue;
692                }
693                match store.update_status(task.id, TaskStatus::Routed).await {
694                    Err(e) => {
695                        tracing::warn!(
696                            task_id = %ext_task.id.0,
697                            repo = %task.repo,
698                            err = %e,
699                            "global sweep: failed to set status:routed"
700                        );
701                    }
702                    _ => {
703                        tracing::info!(
704                            task_id = %ext_task.id.0,
705                            repo = %task.repo,
706                            agent = %result.agent,
707                            complexity = %result.complexity,
708                            "global sweep: task routed"
709                        );
710                    }
711                }
712                if let Some(ref warning) = result.warning {
713                    tracing::warn!(task_id = %ext_task.id.0, warning, "global sweep: routing sanity warning");
714                }
715            }
716            Err(e) => {
717                if let Some(cooled) = e.downcast_ref::<AllAgentsCooledError>() {
718                    tracing::error!(
719                        task_id = %ext_task.id.0,
720                        repo = %task.repo,
721                        scope = %cooled.scope(),
722                        remaining_secs = ?cooled.remaining_secs(),
723                        degraded = ?cooled.degraded(),
724                        "global sweep: ALL AGENTS COOLED — task stays in 'new'"
725                    );
726                    continue;
727                }
728                if let Some(waiting) = e.downcast_ref::<WaitingOnDependency>() {
729                    tracing::info!(
730                        task_id = %ext_task.id.0,
731                        repo = %task.repo,
732                        blockers = %waiting.blockers.join(", "),
733                        "global sweep: task is waiting on a dependency"
734                    );
735                    continue;
736                }
737                tracing::error!(
738                    task_id = %ext_task.id.0,
739                    repo = %task.repo,
740                    err = ?e,
741                    "global sweep: routing failed, skipping task"
742                );
743            }
744        }
745    }
746
747    Ok(())
748}
749
750/// Phase 4 of tick: unblock parent tasks whose sub-issues are all done.
751pub(crate) async fn tick_unblock_parents(
752    backend: &Arc<dyn ExternalBackend>,
753    task_manager: &Arc<TaskManager>,
754    store: &Arc<TaskStore>,
755    repo: &str,
756) -> anyhow::Result<()> {
757    let blocked = task_manager.list_all_by_status(Status::Blocked).await?;
758
759    // Pre-filter: skip tasks that are blocked for a known reason (e.g. CI failure,
760    // escalation). These are not waiting on children, so there is no point making
761    // a GraphQL call for them.
762    let store_blocked = store.list_by_status(repo, TaskStatus::Blocked).await?;
763    let has_block_reason: HashSet<String> = store_blocked
764        .iter()
765        .filter(|t| t.block_reason.is_some())
766        .filter_map(|t| t.external_id.clone())
767        .collect();
768
769    // Spawn a concurrent task for each candidate blocked task.
770    // Previously these ran sequentially; get_sub_issues is a GraphQL call taking 1-3 s each,
771    // and with 4 blocked tasks that was 4-12 s of sequential latency every tick.
772    let handles: Vec<_> = blocked
773        .into_iter()
774        .filter(|task| {
775            if has_block_reason.contains(&task.id.0) {
776                tracing::debug!(
777                    task_id = task.id.0,
778                    "skipping blocked task with known block_reason"
779                );
780                false
781            } else {
782                true
783            }
784        })
785        .map(|task| {
786            let backend_clone = Arc::clone(backend);
787            let task_manager_clone = Arc::clone(task_manager);
788            let store_clone = Arc::clone(store);
789            let repo_owned = repo.to_string();
790            tokio::spawn(async move {
791                let task_id = &task.id;
792
793                let mut children: Vec<ExternalId> = Vec::new();
794                let mut child_statuses: HashMap<
795                    String,
796                    TaskStatus,
797                > = HashMap::new();
798
799                match store_clone.resolve_task_id(&repo_owned, &task_id.0).await {
800                    Ok(Some(parent_store_id)) => {
801                        match store_clone.list_children(&repo_owned, parent_store_id).await {
802                            Ok(store_children) => {
803                                for child in store_children {
804                                    let Some(child_external_id) = child.external_id else {
805                                        continue;
806                                    };
807                                    child_statuses.insert(child_external_id.clone(), child.status);
808                                    children.push(ExternalId(child_external_id));
809                                }
810                            }
811                            Err(e) => {
812                                tracing::debug!(
813                                    task_id = task_id.0,
814                                    ?e,
815                                    "failed to list store-linked children"
816                                );
817                            }
818                        }
819                    }
820                    Ok(None) => {}
821                    Err(e) => {
822                        tracing::debug!(
823                            task_id = task_id.0,
824                            ?e,
825                            "failed to resolve blocked task in store for child lookup"
826                        );
827                    }
828                }
829
830                if !is_internal_id(&task_id.0) {
831                    match backend_clone.get_sub_issues(task_id).await {
832                        Ok(ids) => {
833                            let mut seen: HashSet<String> =
834                                children.iter().map(|child| child.0.clone()).collect();
835                            for id in ids {
836                                if seen.insert(id.0.clone()) {
837                                    children.push(id);
838                                }
839                            }
840                        }
841                        Err(e) => {
842                            tracing::debug!(task_id = task_id.0, ?e, "failed to get sub-issues");
843                        }
844                    }
845                }
846
847                // No children means nothing to wait on — skip (may be blocked for other reasons)
848                if children.is_empty() {
849                    return;
850                }
851
852                // Check if every child is done using the local store (batched) and
853                // fall back to the backend only for children not present in the store.
854                let mut all_done = true;
855                // Build owned strings for the batch lookup (needed for &str slices below)
856                let child_ext_strs: Vec<String> =
857                    children.iter().map(|c| c.0.clone()).collect();
858                let child_exts: Vec<&str> =
859                    child_ext_strs.iter().map(String::as_str).collect();
860                // Query store for statuses of any children present locally
861                match store_clone
862                    .get_statuses_by_external_ids(&repo_owned, &child_exts)
863                    .await
864                { Ok(map) => {
865                    for (k, v) in map {
866                        child_statuses.insert(k, v);
867                    }
868                } _ => {
869                    tracing::debug!(
870                        task_id = task_id.0,
871                        "failed to batch-query store for child statuses; falling back to per-child lookups"
872                    );
873                }}
874
875                for child_id in &children {
876                    // Check store first
877                    if let Some(status) = child_statuses.get(&child_id.0) {
878                        if *status != TaskStatus::Done {
879                            all_done = false;
880                            break;
881                        }
882                        continue;
883                    }
884
885                    // Not found in store — fall back to backend check
886                    match backend_clone.get_task(child_id).await {
887                        Ok(child) => {
888                            if !child.labels.iter().any(|l| l == Status::Done.as_label()) {
889                                all_done = false;
890                                break;
891                            }
892                        }
893                        Err(e) => {
894                            tracing::debug!(task_id = task_id.0, child = %child_id.0, ?e, "failed to fetch child task from backend — treating as not done");
895                            all_done = false;
896                            break;
897                        }
898                    }
899                }
900
901                if all_done {
902                    tracing::info!(
903                        task_id = task_id.0,
904                        children = children.len(),
905                        "all children done, unblocking parent"
906                    );
907                    if let Err(e) =
908                        task_manager_clone.update_task_status(task_id, Status::New).await
909                    {
910                        tracing::warn!(task_id = task_id.0, ?e, "failed to unblock parent");
911                    }
912                }
913            })
914        })
915        .collect();
916
917    for handle in handles {
918        if let Err(e) = handle.await {
919            tracing::warn!(?e, "phase 4 sub-issue check panicked");
920        }
921    }
922    Ok(())
923}
924
925/// Phase 5 of tick: run cron job matching and fire any due jobs.
926pub(crate) async fn tick_job_scheduler(
927    jobs_path: &Path,
928    backend: &Arc<dyn ExternalBackend>,
929    store: Option<&Arc<TaskStore>>,
930    repo: &str,
931    transport: Option<&Arc<Transport>>,
932) -> anyhow::Result<()> {
933    jobs::tick(jobs_path, backend, store, repo, transport).await
934}
935
936/// Core tick for one project, up to the routing phase.
937///
938/// Every phase here is scoped to one project, so all projects can run this at the same time:
939/// 1. `tick_check_session_completions` — poll tmux for finished sessions
940/// 2. `tick_detect_silent_agents`      — cooldown agents that produced no output
941/// 3. `tick_recover_stuck_tasks`       — reset in_progress/in_review tasks with no session
942///
943/// The store-wide work that used to sit in here runs once per tick in `tick_all`:
944/// `tick_global_sweeps` and `reconcile_dependencies`.
945#[expect(
946    clippy::too_many_arguments,
947    reason = "each argument is engine state the tick passes down"
948)]
949pub(crate) async fn tick_before_routing(
950    backend: &Arc<dyn ExternalBackend>,
951    tmux: &Arc<TmuxManager>,
952    repo: &str,
953    capture: &Arc<CaptureService>,
954    config: &EngineConfig,
955    task_manager: &Arc<TaskManager>,
956    dispatching: &Arc<DashMap<String, String>>,
957    store: &Arc<TaskStore>,
958    session_map: &HashMap<String, bool>,
959) {
960    let mut phases: Vec<(&str, u128)> = Vec::new();
961    let mut at = Instant::now();
962
963    if let Err(e) = tick_check_session_completions(tmux, repo, capture, store).await {
964        tracing::warn!(err = %e, "session completion phase failed");
965    }
966    phases.push(("sessions", at.elapsed().as_millis()));
967
968    // Every node tends its own sessions, only the leader decides. Followers dispatch once
969    // tasks are assigned to nodes
970    if !store.is_leader() {
971        super::log_phase_timings("tick.pre_routing", repo, &phases);
972        return;
973    }
974
975    at = Instant::now();
976    if let Err(e) =
977        tick_detect_silent_agents(tmux, repo, capture, backend, task_manager, config, store).await
978    {
979        tracing::warn!(err = %e, "silent-agent detection phase failed");
980    }
981    phases.push(("silent_agents", at.elapsed().as_millis()));
982
983    at = Instant::now();
984    if let Err(e) = tick_recover_stuck_tasks(
985        backend,
986        tmux,
987        repo,
988        task_manager,
989        config,
990        store,
991        session_map,
992        dispatching,
993    )
994    .await
995    {
996        tracing::warn!(err = %e, "stuck-task recovery phase failed");
997    }
998    phases.push(("stuck_tasks", at.elapsed().as_millis()));
999
1000    super::log_phase_timings("tick.pre_routing", repo, &phases);
1001}
1002
1003/// Core tick for one project, after the routing phase.
1004///
1005/// Takes the router's decision as a `DispatchMode` value instead of the router itself, so
1006/// every project can run this at the same time:
1007/// 1. `tick_dispatch_tasks`  — spawn agents for status:routed tasks
1008/// 2. `tick_unblock_parents` — unblock parents whose sub-issues are all done
1009/// 3. `tick_job_scheduler`   — fire due cron jobs
1010#[expect(
1011    clippy::too_many_arguments,
1012    reason = "each argument is engine state the tick passes down"
1013)]
1014pub(crate) async fn tick_after_routing(
1015    backend: &Arc<dyn ExternalBackend>,
1016    tmux: &Arc<TmuxManager>,
1017    repo: &str,
1018    runner: &Arc<TaskRunner>,
1019    capture: &Arc<CaptureService>,
1020    semaphore: &Arc<Semaphore>,
1021    project_dir: &Path,
1022    task_manager: &Arc<TaskManager>,
1023    weight_tx: &mpsc::Sender<WeightSignal>,
1024    dispatch_mode: DispatchMode,
1025    dispatching: &Arc<DashMap<String, String>>,
1026    store: &Arc<TaskStore>,
1027    transport: Option<&Arc<Transport>>,
1028    session_map: &HashMap<String, bool>,
1029) {
1030    let mut phases: Vec<(&str, u128)> = Vec::new();
1031    let mut at = Instant::now();
1032
1033    if let Err(e) = tick_dispatch_tasks(
1034        backend,
1035        tmux,
1036        repo,
1037        runner,
1038        capture,
1039        semaphore,
1040        task_manager,
1041        weight_tx,
1042        dispatch_mode,
1043        dispatching,
1044        store,
1045        session_map,
1046    )
1047    .await
1048    {
1049        tracing::warn!(err = %e, "dispatch phase failed");
1050    }
1051    phases.push(("dispatch", at.elapsed().as_millis()));
1052
1053    at = Instant::now();
1054    if let Err(e) = tick_unblock_parents(backend, task_manager, store, repo).await {
1055        tracing::warn!(err = %e, "parent-unblock phase failed");
1056    }
1057    phases.push(("unblock_parents", at.elapsed().as_millis()));
1058
1059    at = Instant::now();
1060    let jobs_path = project_dir.join(".orch.yml");
1061    if let Err(e) = tick_job_scheduler(&jobs_path, backend, Some(store), repo, transport).await {
1062        tracing::error!(?e, "job scheduler tick failed");
1063    }
1064    phases.push(("jobs", at.elapsed().as_millis()));
1065
1066    super::log_phase_timings("tick.post_routing", repo, &phases);
1067}
1068
1069/// Core tick — runs every 10s for every project.
1070///
1071/// Projects no longer wait on each other: the phases around routing run for all of them at
1072/// once, so tick time tracks the slowest project instead of the sum. Routing stays serial
1073/// because it needs the router write lock and one shared `RoutingTickQuota`, which is what
1074/// gives `router.max_tasks_per_tick` its meaning.
1075///
1076/// The tmux session map, the global sweeps and the dependency reconcile are the same for
1077/// every project, so they run once per tick rather than once per project.
1078#[expect(
1079    clippy::too_many_arguments,
1080    reason = "each argument is engine state the tick passes down"
1081)]
1082pub(crate) async fn tick_all(
1083    engines: &[ProjectEngine],
1084    tmux: &Arc<TmuxManager>,
1085    capture: &Arc<CaptureService>,
1086    semaphore: &Arc<Semaphore>,
1087    config: &EngineConfig,
1088    router: &Arc<RwLock<Router>>,
1089    weight_tx: &mpsc::Sender<WeightSignal>,
1090    dispatching: &Arc<DashMap<String, String>>,
1091    transport: Option<&Arc<Transport>>,
1092    active_repos: &HashSet<String>,
1093    auto_merge_in_flight: &Arc<DashSet<String>>,
1094) {
1095    let _tick_span = tracing::info_span!("engine.tick").entered();
1096
1097    let Some(first) = engines.first() else {
1098        return;
1099    };
1100    // All project engines share one SQLite store, so leadership and the global sweeps below
1101    // are the same whichever project they are read from
1102    let store = &first.store;
1103
1104    // Calls made since the previous tick, so hourly quota exhaustion can be traced
1105    for (project, call_type, calls) in http::drain_call_counts().into_iter().take(10) {
1106        tracing::debug!(
1107            project,
1108            call_type,
1109            calls,
1110            "github api calls since last tick"
1111        );
1112    }
1113
1114    // One `tmux list-panes -a` for every project's stuck-task recovery, instead of one each
1115    let session_map = tmux.batch_session_active().await;
1116
1117    let mut passes = Vec::with_capacity(engines.len());
1118    for engine in engines {
1119        passes.push(REPO_CONTEXT.scope(
1120            engine.repo.clone(),
1121            tick_before_routing(
1122                &engine.backend,
1123                tmux,
1124                &engine.repo,
1125                capture,
1126                config,
1127                &engine.task_manager,
1128                dispatching,
1129                &engine.store,
1130                &session_map,
1131            ),
1132        ));
1133    }
1134    future::join_all(passes).await;
1135
1136    if !store.is_leader() {
1137        return;
1138    }
1139
1140    // Store-wide, so once per tick rather than once per project. Both read every repo, and
1141    // the NeedsReview sweep increments a counter it just read, which concurrent per-project
1142    // passes would each consume (#3864)
1143    let at = Instant::now();
1144    {
1145        let router_guard = router.read().await;
1146        tick_global_sweeps(
1147            &first.task_manager,
1148            store,
1149            &router_guard,
1150            dispatching,
1151            auto_merge_in_flight,
1152            active_repos,
1153        )
1154        .await;
1155    }
1156    let sweeps_ms = at.elapsed().as_millis();
1157
1158    let at = Instant::now();
1159    recover_untracked_repo_stuck_tasks(
1160        tmux,
1161        config,
1162        store,
1163        &session_map,
1164        dispatching,
1165        active_repos,
1166    )
1167    .await;
1168    let untracked_ms = at.elapsed().as_millis();
1169
1170    let at = Instant::now();
1171    if let Err(err) = dependencies::reconcile_dependencies(
1172        first.backend.as_ref(),
1173        store,
1174        transport.map(AsRef::as_ref),
1175    )
1176    .await
1177    {
1178        tracing::warn!(err = %err, "dependency reconcile failed");
1179    }
1180    super::log_phase_timings(
1181        "tick.global",
1182        &first.repo,
1183        &[
1184            ("global_sweeps", sweeps_ms),
1185            ("untracked_stuck", untracked_ms),
1186            ("dependencies", at.elapsed().as_millis()),
1187        ],
1188    );
1189
1190    {
1191        let mut router_guard = router.write().await;
1192        let mut routing_quota = RoutingTickQuota::new(router_config::max_tasks_per_routing_tick());
1193        for engine in engines {
1194            let at = Instant::now();
1195            REPO_CONTEXT
1196                .scope(engine.repo.clone(), async {
1197                    if let Err(e) = tick_route_tasks(
1198                        &engine.backend,
1199                        &engine.task_manager,
1200                        &mut router_guard,
1201                        &engine.store,
1202                        &engine.repo,
1203                        &mut routing_quota,
1204                    )
1205                    .await
1206                    {
1207                        tracing::warn!(err = %e, "routing phase failed");
1208                    }
1209                })
1210                .await;
1211            super::log_phase_timings(
1212                "tick.routing",
1213                &engine.repo,
1214                &[("route", at.elapsed().as_millis())],
1215            );
1216        }
1217
1218        // Global routing sweep for tasks from inactive or removed repos.
1219        // tick_route_tasks is scoped to the active repo; tasks from projects no longer
1220        // in config are never returned by list_routable and would stay in 'new' indefinitely.
1221        if let Err(e) =
1222            route_new_tasks_global(&mut router_guard, store, active_repos, &mut routing_quota).await
1223        {
1224            tracing::warn!(err = %e, "global new-task routing sweep failed");
1225        }
1226    }
1227
1228    let dispatch_mode = dispatch_mode_from_router(&*router.read().await);
1229
1230    // Re-read the session map: the completion phase above kills the sessions of finished
1231    // agents, and dispatch must not treat a killed session as one that still blocks a task
1232    let session_map = tmux.batch_session_active().await;
1233
1234    let mut passes = Vec::with_capacity(engines.len());
1235    for engine in engines {
1236        passes.push(REPO_CONTEXT.scope(
1237            engine.repo.clone(),
1238            tick_after_routing(
1239                &engine.backend,
1240                tmux,
1241                &engine.repo,
1242                &engine.runner,
1243                capture,
1244                semaphore,
1245                &engine.project_dir,
1246                &engine.task_manager,
1247                weight_tx,
1248                dispatch_mode,
1249                dispatching,
1250                &engine.store,
1251                transport,
1252                &session_map,
1253            ),
1254        ));
1255    }
1256    future::join_all(passes).await;
1257
1258    // Global dispatch sweep for routed tasks from inactive or removed repos.
1259    // tick_dispatch_tasks is scoped to each active repo; tasks from projects no longer
1260    // in config are never returned by list_external_by_status and would stay in
1261    // 'routed' indefinitely (see #3413). Excludes the full active-repo set, not just
1262    // one repo, so it doesn't treat other active repos as orphaned.
1263    if let Err(e) = dispatch_routed_tasks_global(
1264        tmux,
1265        capture,
1266        semaphore,
1267        weight_tx,
1268        dispatch_mode,
1269        dispatching,
1270        store,
1271        &session_map,
1272        active_repos,
1273    )
1274    .await
1275    {
1276        tracing::warn!(err = %e, "global routed-task dispatch sweep failed");
1277    }
1278}
1279
1280/// Status a finished run moves to. Only a successful run with no PR (or with the review agent
1281/// off) becomes `done`. A failed run stays in `needs_review` with its issue open
1282pub(crate) fn display_status_for(
1283    signal: &WeightSignal,
1284    enable_review: bool,
1285    has_pr: bool,
1286) -> &'static str {
1287    match signal {
1288        WeightSignal::Success { .. } if enable_review => {
1289            if has_pr {
1290                "needs_review"
1291            } else {
1292                "done"
1293            }
1294        }
1295        // Silence detection or another non-rate-limit reset already moved the task to "new".
1296        // Converting it to needs_review would trigger the no-code shortcut and falsely close it
1297        WeightSignal::RateLimited { .. } | WeightSignal::Rerouted => "new",
1298        WeightSignal::Blocked => "blocked",
1299        // The review path re-routes a task with no PR and no commits
1300        WeightSignal::Failed { .. } => "needs_review",
1301        // None means the runner guard skipped the task or the status was unrecognised
1302        WeightSignal::None if enable_review => "needs_review",
1303        WeightSignal::Success { .. } | WeightSignal::None => "done",
1304    }
1305}
1306
1307#[cfg(test)]
1308mod tests;
1309
1310#[cfg(test)]
1311mod recovery_tests;
1312
1313#[cfg(test)]
1314mod dispatch_tests;