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