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