Skip to main content

orch/engine/
mod.rs

1//! Engine — the core orchestration loop.
2//!
3//! The engine is the central coordinator. It owns the tick loop, backend
4//! connections, channel registry, transport layer, and tmux session manager.
5//!
6//! Submodules handle the heavy lifting:
7//! - [`tick`] — core tick phases (session polling, stuck recovery, routing, dispatch)
8//! - [`sync`] — periodic sync operations (cleanup, PR review, mentions)
9//! - [`review`] — PR review pipeline (review agent, auto-merge, change handling)
10//! - [`cleanup`] — worktree cleanup and merged-PR detection
11//!
12//! This file contains struct definitions, project initialization, and the
13//! main event loop (`serve()`).
14
15pub mod agents;
16pub(crate) mod chore;
17pub mod ci;
18pub mod git;
19pub mod review;
20pub mod router;
21pub mod runner;
22pub mod service;
23pub mod subscribers;
24pub mod sync;
25pub mod tasks;
26pub mod tick;
27
28use crate::backends::{ExternalBackend, ExternalId};
29use crate::channels::capture::CaptureService;
30use crate::config;
31use crate::engine::agents::registry;
32use crate::engine::router::{Router, RouterConfig};
33use crate::engine::service::cluster_projects;
34/// Standard Orch attribution footer for issue bodies, PR bodies, and comments.
35///
36/// Append to every user-visible string posted to GitHub so activity is
37/// clearly attributed to orch rather than appearing as a human post.
38use crate::engine::service::relay;
39use crate::engine::service::serve;
40use crate::engine::sync::events as items;
41use crate::engine::tasks::TaskManager;
42use crate::engine::tasks::events;
43use crate::engine::tick::repo_context::REPO_CONTEXT;
44use crate::github::app;
45use crate::github::http::GhHttp;
46use crate::store::{TaskStatus, TaskStore};
47use crate::sys::tmux::TmuxManager;
48use runner::WeightSignal;
49// AtomicBool/Ordering removed — shutdown is now immediate (reset tasks + break)
50use crate::backends::Status;
51use crate::backends::github::GitHubBackend;
52use crate::backends::outbox;
53use crate::engine::review as engine_review;
54use crate::engine::tasks as engine_tasks;
55use crate::security::secret_ref;
56use futures::future;
57pub use serve::{WebUi, serve};
58use std::collections::HashSet;
59use std::fmt;
60use std::fmt::Debug;
61use std::fmt::Formatter;
62use std::path::PathBuf;
63use std::sync::Arc;
64use std::sync::atomic::AtomicBool;
65use std::sync::atomic::Ordering;
66use std::time::Duration;
67use std::time::Instant;
68use tokio::fs;
69use tokio::sync::broadcast::Sender;
70use tokio::sync::mpsc::UnboundedSender;
71use tokio::sync::{Notify, RwLock, Semaphore, mpsc};
72use tokio::task;
73use tokio::time;
74
75pub fn orch_footer() -> &'static str {
76    "\n\n---\n*Posted by [Orch](https://github.com/gabrielkoerich/orch)*"
77}
78
79/// Build a standard attribution footer for GitHub comments posted by orch bots.
80///
81/// `verb` is "Created", "Reviewed", or "Commented" depending on context.
82pub fn attribution_footer(verb: &str, agent: &str, model: Option<&str>) -> String {
83    match model {
84        Some(m) => format!(
85            "\n\n---\n*{verb} by {agent}[bot] via [Orch](https://github.com/gabrielkoerich/orch) using `{m}`*"
86        ),
87        None => format!(
88            "\n\n---\n*{verb} by {agent}[bot] via [Orch](https://github.com/gabrielkoerich/orch)*"
89        ),
90    }
91}
92
93/// Lightweight reference tuple for channel message handling.
94type EngineRef = (
95    String,
96    Arc<dyn ExternalBackend>,
97    Arc<TaskManager>,
98    Option<Arc<TaskStore>>,
99);
100
101/// Per-project engine state.
102///
103/// Each project has its own backend, task runner, and task manager,
104/// but they share the global tmux manager, transport, and semaphore.
105#[derive(Clone)]
106pub struct ProjectEngine {
107    pub repo: String,
108    /// The checkout, or for a project only other nodes host the directory with its `.orch.yml`
109    pub project_dir: PathBuf,
110    /// False for a project only other nodes of the cluster host
111    pub hosted: bool,
112    pub backend: Arc<dyn ExternalBackend>,
113    pub task_manager: Arc<TaskManager>,
114    pub runner: Arc<runner::TaskRunner>,
115    pub store: Arc<TaskStore>,
116}
117
118impl Debug for ProjectEngine {
119    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
120        f.debug_struct("ProjectEngine")
121            .field("repo", &self.repo)
122            .field("project_dir", &self.project_dir)
123            .field("hosted", &self.hosted)
124            .finish_non_exhaustive()
125    }
126}
127
128/// A restart ends every review session, so an `in_review` task with no session has no reviewer.
129/// Hand it back to `needs_review` at start, so it does not wait for the stuck-review recovery
130pub(crate) async fn reset_orphaned_reviews(
131    task_manager: &TaskManager,
132    store: &Arc<TaskStore>,
133    repo: &str,
134    tmux: &TmuxManager,
135) -> usize {
136    // The store holds external and internal tasks, the second list is the legacy internal table
137    // A review another node runs keeps its own session there
138    let mut ids: Vec<ExternalId> = store
139        .list_by_status(repo, TaskStatus::InReview)
140        .await
141        .unwrap_or_default()
142        .iter()
143        .filter(|t| !store.runs_elsewhere(t))
144        .map(|t| engine_tasks::store_task_to_external(t).id)
145        .collect();
146    if let Ok(legacy) = task_manager
147        .list_internal_by_status(TaskStatus::InReview)
148        .await
149    {
150        ids.extend(legacy.into_iter().map(|t| t.id));
151    }
152    ids.sort_by(|a, b| a.0.cmp(&b.0));
153    ids.dedup_by(|a, b| a.0 == b.0);
154
155    let mut reset = 0;
156    for id in &ids {
157        let session = tmux.session_name(repo, &format!("{}-review", id.0));
158
159        if tmux.session_exists(&session).await {
160            continue;
161        }
162
163        if let Err(e) = task_manager
164            .update_task_status(id, Status::NeedsReview)
165            .await
166        {
167            tracing::warn!(
168                task_id = id.0,
169                ?e,
170                "failed to reset an orphaned review at start"
171            );
172            continue;
173        }
174
175        if let Ok(Some(store_id)) = store.resolve_task_id(repo, &id.0).await {
176            let reason = "startup: review session gone, reset to needs_review";
177
178            if let Err(e) = store
179                .finalize_incomplete_runs(store_id, "aborted", reason)
180                .await
181            {
182                tracing::warn!(
183                    task_id = id.0,
184                    ?e,
185                    "failed to finalize the orphaned review's runs"
186                );
187            }
188        }
189
190        reset += 1;
191    }
192
193    reset
194}
195
196/// Starts the relay client when `relay.url` is set. The token is read in the background, so a
197/// passbox prompt nobody answers never holds up the engine
198/// Starts the relay client when `relay.url` is set. True when the GitHub App is set up too, so the
199/// engine acts on the item each event names
200fn start_relay_client(store: &Arc<TaskStore>, signals: &UnboundedSender<relay::Signal>) -> bool {
201    // The global config only: a project file must never point a secret at its own endpoint
202    let url = config::get_global("relay.url").unwrap_or_default();
203    let store = Arc::clone(store);
204
205    if url.is_empty() {
206        return false;
207    }
208
209    let token_ref = config::get_global("relay.token").unwrap_or_default();
210    let signals = signals.clone();
211    tokio::spawn(async move {
212        let mut warned = false;
213        let token = loop {
214            let reference = token_ref.clone();
215            let read = task::spawn_blocking(move || secret_ref::resolve(&reference))
216                .await
217                .map_err(anyhow::Error::from)
218                .and_then(|r| r);
219
220            match read {
221                Ok(token) if !token.is_empty() => break token,
222                Ok(_) => {
223                    tracing::warn!("relay.token is empty, the relay client stays off");
224                    return;
225                }
226                Err(e) if !warned => {
227                    tracing::warn!(err = %e, "could not read relay.token, retrying every 5 minutes");
228                    warned = true;
229                }
230                Err(_) => {}
231            }
232
233            time::sleep(Duration::from_secs(300)).await;
234        };
235
236        relay::run(url, token, store, signals).await;
237    });
238
239    let items = app::configured();
240    if !items {
241        tracing::info!("no GitHub App set up, relay events wake the full sync");
242    }
243    items
244}
245
246/**
247 * Acts on the item a relay event names in a spawned task, then wakes the tick so the CI gate,
248 * dispatch and merge see the result. Holds the repository's lock, so it never overlaps a sync of
249 * that project
250 **/
251#[expect(
252    clippy::too_many_arguments,
253    reason = "the spawned task takes its own handle to each piece of engine state"
254)]
255fn spawn_relay_item(
256    engine: &ProjectEngine,
257    event: relay::Event,
258    tmux: &Arc<TmuxManager>,
259    engine_config: &EngineConfig,
260    router: &Arc<RwLock<Router>>,
261    dispatching: &Arc<dashmap::DashMap<String, String>>,
262    auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
263    tick: &Arc<Notify>,
264) {
265    let engine = engine.clone();
266    let tmux = Arc::clone(tmux);
267    let engine_config = engine_config.clone();
268    let router = Arc::clone(router);
269    let dispatching = Arc::clone(dispatching);
270    let auto_merge_in_flight = Arc::clone(auto_merge_in_flight);
271    let tick = Arc::clone(tick);
272
273    tokio::spawn(REPO_CONTEXT.scope(engine.repo.clone(), async move {
274        let target = items::target(&event);
275        if target == items::Target::Ignore {
276            tracing::debug!(repo = %engine.repo, event = %event.name, action = %event.action, "relay event ignored");
277            return;
278        }
279
280        tracing::info!(repo = %engine.repo, event = %event.name, action = %event.action, ?target, "relay event");
281
282        let followup = {
283            let lock = items::repo_lock(&engine.repo);
284            let _held = lock.lock().await;
285            let gh = match GhHttp::new() {
286                Ok(gh) => gh,
287                Err(e) => {
288                    tracing::warn!(err = %e, "failed to create GitHub HTTP client for a relay event");
289                    return;
290                }
291            };
292            let router_config = router.read().await.config.clone();
293            let ctx = items::ItemContext {
294                backend: &engine.backend,
295                repo: &engine.repo,
296                config: &engine_config,
297                task_manager: &engine.task_manager,
298                store: &engine.store,
299                dispatching: &dispatching,
300                auto_merge_in_flight: &auto_merge_in_flight,
301                router_config: &router_config,
302                gh: &gh,
303            };
304            match Box::pin(items::apply(&ctx, target)).await {
305                Ok(followup) => followup,
306                Err(e) => {
307                    tracing::warn!(err = %e, event = %event.name, "relay event handling failed, the reconciliation pass retries it");
308                    items::Followup::None
309                }
310            }
311        };
312
313        if followup == items::Followup::SyncRepo {
314            sync_one_project(
315                &engine,
316                &tmux,
317                &engine_config,
318                &router,
319                &dispatching,
320                &auto_merge_in_flight,
321            )
322            .await;
323        }
324
325        tick.notify_one();
326    }));
327}
328
329/**
330 * Sends the pending outbox rows, runs `sync_tick` for every project at once, then the tail that is the same for all of them,
331 * in a spawned task. Sync time is the slowest project instead of the sum of all of them
332 * (#3864). The caller must already hold `sync_in_progress`; this releases it when done
333 **/
334#[expect(
335    clippy::too_many_arguments,
336    reason = "the spawned task takes its own handle to each piece of engine state"
337)]
338fn spawn_sync_pass(
339    project_engines: &[ProjectEngine],
340    tmux: &Arc<TmuxManager>,
341    engine_config: &EngineConfig,
342    router: &Arc<RwLock<Router>>,
343    dispatching: &Arc<dashmap::DashMap<String, String>>,
344    auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
345    sync_in_progress: &Arc<AtomicBool>,
346    trigger: &'static str,
347) {
348    let engines = project_engines.to_vec();
349    let tmux = Arc::clone(tmux);
350    let engine_config = engine_config.clone();
351    let router = Arc::clone(router);
352    let dispatching = Arc::clone(dispatching);
353    let auto_merge_in_flight = Arc::clone(auto_merge_in_flight);
354    let guard = Arc::clone(sync_in_progress);
355
356    tokio::spawn(async move {
357        let started = Instant::now();
358        sync::sync_shared_head(engines.first().map(|e| &e.store)).await;
359        let mut passes = Vec::with_capacity(engines.len());
360        for engine in &engines {
361            passes.push(REPO_CONTEXT.scope(
362                engine.repo.clone(),
363                sync_one_project(
364                    engine,
365                    &tmux,
366                    &engine_config,
367                    &router,
368                    &dispatching,
369                    &auto_merge_in_flight,
370                ),
371            ));
372        }
373        future::join_all(passes).await;
374
375        sync::sync_shared_tail(&router, engines.first().map(|e| &e.store)).await;
376        tracing::info!(
377            trigger,
378            elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
379            "sync tick complete"
380        );
381        guard.store(false, Ordering::Release);
382    });
383}
384
385async fn sync_one_project(
386    engine: &ProjectEngine,
387    tmux: &Arc<TmuxManager>,
388    engine_config: &EngineConfig,
389    router: &Arc<RwLock<Router>>,
390    dispatching: &Arc<dashmap::DashMap<String, String>>,
391    auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
392) {
393    let lock = items::repo_lock(&engine.repo);
394    let _held = lock.lock().await;
395    if let Err(e) = Box::pin(sync::sync_tick(
396        &engine.backend,
397        tmux,
398        &engine.repo,
399        engine_config,
400        router,
401        &engine.task_manager,
402        &engine.store,
403        dispatching,
404        auto_merge_in_flight,
405    ))
406    .await
407    {
408        tracing::error!(repo = %engine.repo, ?e, "sync tick failed for project");
409    }
410}
411
412/// Milliseconds a group of tick or sync phases may take before it is worth an operator's eye
413const SLOW_PHASE_GROUP_MS: u128 = 1_000;
414
415/**
416 * Logs how long each phase of a tick or sync group took, for one project. Tick and sync time
417 * grows with the project count, and the totals alone did not say which project or phase spent
418 * it (#3864). Info once a group crosses `SLOW_PHASE_GROUP_MS`, so a quiet install stays quiet
419 **/
420pub(crate) fn log_phase_timings(group: &str, repo: &str, phases: &[(&str, u128)]) {
421    let total_ms: u128 = phases.iter().map(|(_, ms)| ms).sum();
422    if total_ms >= SLOW_PHASE_GROUP_MS {
423        tracing::info!(group, repo, total_ms, ?phases, "phase timings");
424    } else {
425        tracing::debug!(group, repo, total_ms, ?phases, "phase timings");
426    }
427}
428
429/// The `agents:` entries of config.yml as written, or [`router::config::DEFAULT_AGENTS`] when
430/// the key is not set. An entry is a CLI name or `runner:process`, see [`registry::parse_entry`]
431pub fn configured_agent_entries() -> Vec<String> {
432    if let Ok(agents_str) = config::get("agents")
433        && !agents_str.is_empty()
434        && agents_str != "[]"
435    {
436        // config::get returns serde_norway::to_string for arrays, which is
437        // YAML block format ("- claude\n- codex\n..."). Parse as YAML first.
438        if let Ok(agents_arr) = serde_norway::from_str::<Vec<String>>(&agents_str)
439            && !agents_arr.is_empty()
440        {
441            return agents_arr;
442        }
443        // Fallback: try JSON (inline arrays) or comma-separated
444        if let Ok(agents_arr) = serde_json::from_str::<Vec<String>>(&agents_str)
445            && !agents_arr.is_empty()
446        {
447            return agents_arr;
448        }
449    }
450    router::config::DEFAULT_AGENTS
451        .iter()
452        .map(ToString::to_string)
453        .collect()
454}
455
456/// The names of the configured agents. For a `runner:process` entry the name is the process,
457/// which is also its key in `model_map`, its `agent:` label and its binary on `PATH`
458pub fn configured_agents() -> Vec<String> {
459    configured_agent_entries()
460        .iter()
461        .map(|entry| registry::parse_entry(entry).1.to_string())
462        .collect()
463}
464
465/// Seconds a live session may run past its own timeout before stuck recovery takes it. The
466/// `timeout` wrapper ends the agent at the limit, and the runner still collects the result
467pub const RUN_TIMEOUT_GRACE_SECS: u64 = 300;
468
469/// The limit the `timeout` wrapper puts on one agent run, per complexity
470#[derive(Clone, Copy, Debug, PartialEq, Eq)]
471pub struct RunTimeouts {
472    pub base: u64,
473    pub medium: u64,
474    pub complex: u64,
475}
476
477impl Default for RunTimeouts {
478    fn default() -> Self {
479        Self {
480            base: 1800,
481            medium: 1800,
482            complex: 1800,
483        }
484    }
485}
486
487impl RunTimeouts {
488    /// `workflow.timeout_seconds` (at least 1800), raised by
489    /// `workflow.timeout_by_complexity.{medium,complex}` but never below the base
490    pub fn from_config() -> Self {
491        let read =
492            |key: &str| -> Option<u64> { config::get(key).ok().and_then(|s| s.parse().ok()) };
493        let base = read("workflow.timeout_seconds").unwrap_or(1800).max(1800);
494        Self {
495            base,
496            medium: read("workflow.timeout_by_complexity.medium")
497                .unwrap_or(base)
498                .max(base),
499            complex: read("workflow.timeout_by_complexity.complex")
500                .unwrap_or(base)
501                .max(base),
502        }
503    }
504
505    pub fn for_complexity(&self, complexity: Option<&str>) -> u64 {
506        match complexity {
507            Some("complex") => self.complex,
508            Some("medium") => self.medium,
509            _ => self.base,
510        }
511    }
512}
513
514/// Engine configuration.
515#[derive(Clone, Debug)]
516pub struct EngineConfig {
517    /// Main tick interval
518    pub tick_interval: Duration,
519    /// GitHub sync interval (cleanup, PR review, mentions)
520    pub sync_interval: Duration,
521    /// Full sync interval while a connected relay delivers the GitHub App's events
522    pub reconcile_interval: Duration,
523    /// Webhook health check interval (seconds)
524    pub webhook_health_check_interval: Option<Duration>,
525    /// Maximum parallel task executions
526    pub max_parallel: usize,
527    /// Stuck task timeout for tasks with an active tmux session (seconds)
528    pub stuck_timeout: u64,
529    /// Stuck task timeout for tasks with no active tmux session (seconds).
530    /// Shorter than `stuck_timeout` because no session means the agent has already exited.
531    pub no_session_stuck_timeout: u64,
532    /// Stuck task timeout for in_review tasks with no active tmux session (seconds).
533    /// Longer than `no_session_stuck_timeout` because a review agent ends its tmux session on
534    /// normal completion before its result reaches the engine. A shorter limit resets a task
535    /// whose finished review is still being delivered, and the result is dropped as stale.
536    /// `from_config` keeps it above the review agent's own timeout plus
537    /// `review::REVIEW_RESULT_DELIVERY_SECS`.
538    pub in_review_no_session_stuck_timeout: u64,
539    /// Per-run agent timeouts. A live session is not stuck before its own timeout runs out
540    pub run_timeouts: RunTimeouts,
541    /// Auto-create follow-up tasks when PR reviews request changes
542    pub auto_create_followup_on_changes: bool,
543    /// Graceful shutdown timeout — how long to wait for running agents before exiting.
544    pub graceful_shutdown_timeout: Duration,
545    /// Grace period before silence detection kicks in (seconds).
546    /// Allows time for agent startup, model download, API handshake.
547    pub silence_grace_period: u64,
548    /// Cooldown duration for a model detected as silent (seconds).
549    pub silence_cooldown: u64,
550    /// How often to check for a newer orch release and notify channels (seconds).
551    /// Set to 0 to disable. Default: 3600 (1 hour).
552    pub upgrade_check_interval: u64,
553    /// Seconds of continuous startup failure (GitHub unreachable / auth errors)
554    /// before the engine escalates from WARN to ERROR-level logging and sends a
555    /// one-time push notification to configured channels. Set to 0 to disable.
556    /// Default: 3600 (1 hour).
557    pub startup_failure_escalation_secs: u64,
558}
559
560impl Default for EngineConfig {
561    fn default() -> Self {
562        Self {
563            tick_interval: Duration::from_secs(10),
564            sync_interval: Duration::from_secs(45),
565            reconcile_interval: Duration::from_secs(600),
566            webhook_health_check_interval: Some(Duration::from_secs(60)),
567            max_parallel: 4,
568            stuck_timeout: 1800,
569            no_session_stuck_timeout: 600,
570            in_review_no_session_stuck_timeout: 1920,
571            run_timeouts: RunTimeouts::default(),
572            auto_create_followup_on_changes: true,
573            graceful_shutdown_timeout: Duration::from_secs(600),
574            silence_grace_period: 300,
575            silence_cooldown: 3600,
576            upgrade_check_interval: 3600,
577            startup_failure_escalation_secs: 3600,
578        }
579    }
580}
581
582impl EngineConfig {
583    pub fn tick_interval_secs(&self) -> u64 {
584        self.tick_interval.as_secs()
585    }
586
587    /// How often to check the webhook server's health, 60 s unless configured
588    pub fn webhook_health_check_interval(&self) -> Duration {
589        self.webhook_health_check_interval
590            .unwrap_or(Duration::from_secs(60))
591    }
592
593    pub fn graceful_shutdown_secs(&self) -> u64 {
594        self.graceful_shutdown_timeout.as_secs()
595    }
596
597    /// Stuck limit for an in_progress task whose session is alive: `stuck_timeout`, raised to the
598    /// run's own timeout plus `RUN_TIMEOUT_GRACE_SECS`
599    pub fn live_session_stuck_limit(&self, complexity: Option<&str>) -> u64 {
600        self.stuck_timeout.max(
601            self.run_timeouts
602                .for_complexity(complexity)
603                .saturating_add(RUN_TIMEOUT_GRACE_SECS),
604        )
605    }
606
607    /// Load engine configuration from config files, falling back to defaults.
608    pub fn from_config() -> Self {
609        let mut config = Self::default();
610
611        if let Ok(val) = config::get("engine.tick_interval") {
612            if let Ok(secs) = val.parse::<u64>() {
613                config.tick_interval = Duration::from_secs(secs);
614            } else {
615                tracing::warn!(key = "engine.tick_interval", value = %val, default_secs = config.tick_interval.as_secs(), "invalid value for engine.tick_interval, using default");
616            }
617        }
618
619        if let Ok(val) = config::get("engine.sync_interval") {
620            if let Ok(secs) = val.parse::<u64>() {
621                config.sync_interval = Duration::from_secs(secs);
622            } else {
623                tracing::warn!(key = "engine.sync_interval", value = %val, default_secs = config.sync_interval.as_secs(), "invalid value for engine.sync_interval, using default");
624            }
625        }
626
627        if let Ok(val) = config::get("engine.reconcile_interval") {
628            if let Ok(secs) = val.parse::<u64>() {
629                config.reconcile_interval = Duration::from_secs(secs);
630            } else {
631                tracing::warn!(key = "engine.reconcile_interval", value = %val, default_secs = config.reconcile_interval.as_secs(), "invalid value for engine.reconcile_interval, using default");
632            }
633        }
634
635        if let Ok(val) = config::get("engine.max_parallel") {
636            if let Ok(n) = val.parse::<usize>() {
637                config.max_parallel = n;
638            } else {
639                tracing::warn!(key = "engine.max_parallel", value = %val, default = config.max_parallel, "invalid value for engine.max_parallel, using default");
640            }
641        }
642
643        if let Ok(val) = config::get("engine.stuck_timeout") {
644            if let Ok(secs) = val.parse::<u64>() {
645                config.stuck_timeout = secs;
646            } else {
647                tracing::warn!(key = "engine.stuck_timeout", value = %val, default_secs = config.stuck_timeout, "invalid value for engine.stuck_timeout, using default");
648            }
649        }
650
651        if let Ok(val) = config::get("engine.no_session_stuck_timeout") {
652            if let Ok(secs) = val.parse::<u64>() {
653                config.no_session_stuck_timeout = secs;
654            } else {
655                tracing::warn!(key = "engine.no_session_stuck_timeout", value = %val, default_secs = config.no_session_stuck_timeout, "invalid value for engine.no_session_stuck_timeout, using default");
656            }
657        }
658
659        let mut in_review_from_config = false;
660        if let Ok(val) = config::get("engine.in_review_no_session_stuck_timeout") {
661            if let Ok(secs) = val.parse::<u64>() {
662                config.in_review_no_session_stuck_timeout = secs;
663                in_review_from_config = true;
664            } else {
665                tracing::warn!(key = "engine.in_review_no_session_stuck_timeout", value = %val, default_secs = config.in_review_no_session_stuck_timeout, "invalid value for engine.in_review_no_session_stuck_timeout, using default");
666            }
667        }
668
669        // Keep the no-session review limit over the review agent's own timeout plus delivery
670        // time, whatever either is set to. Under that, recovery resets a task whose finished
671        // review is still on its way to the engine and the result is dropped as stale
672        let review_timeout = engine_review::review_timeout_seconds();
673        let floored = engine_review::no_session_review_floor(
674            config.in_review_no_session_stuck_timeout,
675            review_timeout,
676        );
677        if floored != config.in_review_no_session_stuck_timeout {
678            if in_review_from_config {
679                tracing::warn!(
680                    configured_secs = config.in_review_no_session_stuck_timeout,
681                    review_timeout_secs = review_timeout,
682                    raised_to_secs = floored,
683                    "engine.in_review_no_session_stuck_timeout is below the review timeout plus result delivery time, raising it"
684                );
685            } else {
686                tracing::debug!(
687                    review_timeout_secs = review_timeout,
688                    raised_to_secs = floored,
689                    "raised the default in_review no-session limit over a long review timeout"
690                );
691            }
692            config.in_review_no_session_stuck_timeout = floored;
693        }
694
695        config.run_timeouts = RunTimeouts::from_config();
696
697        if let Ok(val) = config::get("engine.webhook_health_check_interval") {
698            if let Ok(secs) = val.parse::<u64>() {
699                if secs > 0 {
700                    config.webhook_health_check_interval = Some(Duration::from_secs(secs));
701                } else {
702                    config.webhook_health_check_interval = None;
703                }
704            } else {
705                tracing::warn!(key = "engine.webhook_health_check_interval", value = %val, default = ?config.webhook_health_check_interval, "invalid value for engine.webhook_health_check_interval, using default");
706            }
707        }
708
709        if let Ok(val) = config::get("workflow.auto_create_followup_on_changes") {
710            config.auto_create_followup_on_changes = !val.eq_ignore_ascii_case("false");
711        }
712
713        if let Ok(val) = config::get("engine.graceful_shutdown_timeout") {
714            if let Ok(secs) = val.parse::<u64>() {
715                config.graceful_shutdown_timeout = Duration::from_secs(secs);
716            } else {
717                tracing::warn!(key = "engine.graceful_shutdown_timeout", value = %val, default_secs = config.graceful_shutdown_timeout.as_secs(), "invalid value for engine.graceful_shutdown_timeout, using default");
718            }
719        }
720
721        if let Ok(val) = config::get("engine.silence_grace_period") {
722            if let Ok(secs) = val.parse::<u64>() {
723                config.silence_grace_period = secs;
724            } else {
725                tracing::warn!(key = "engine.silence_grace_period", value = %val, default = config.silence_grace_period, "invalid value for engine.silence_grace_period, using default");
726            }
727        }
728
729        if let Ok(val) = config::get("engine.silence_cooldown") {
730            if let Ok(secs) = val.parse::<u64>() {
731                config.silence_cooldown = secs;
732            } else {
733                tracing::warn!(key = "engine.silence_cooldown", value = %val, default = config.silence_cooldown, "invalid value for engine.silence_cooldown, using default");
734            }
735        }
736
737        if let Ok(val) = config::get("engine.upgrade_check_interval") {
738            if let Ok(secs) = val.parse::<u64>() {
739                config.upgrade_check_interval = secs;
740            } else {
741                tracing::warn!(key = "engine.upgrade_check_interval", value = %val, default = config.upgrade_check_interval, "invalid value for engine.upgrade_check_interval, using default");
742            }
743        }
744
745        if let Ok(val) = config::get("engine.startup_failure_escalation_secs") {
746            if let Ok(secs) = val.parse::<u64>() {
747                config.startup_failure_escalation_secs = secs;
748            } else {
749                tracing::warn!(
750                    key = "engine.startup_failure_escalation_secs",
751                    value = %val,
752                    default_secs = config.startup_failure_escalation_secs,
753                    "invalid value for engine.startup_failure_escalation_secs, using default"
754                );
755            }
756        }
757
758        config
759    }
760}
761
762/// KV key holding the epoch second the GitHub core window resets, so `orch task status`
763/// can show the limit from a separate process.
764pub const RATE_LIMITED_UNTIL_KEY: &str = "github:rate_limited_until";
765
766/// Format an epoch second as a local `HH:MM:SS` for operator-facing output.
767pub fn format_rate_limited_until(reset_at: i64) -> String {
768    chrono::DateTime::from_timestamp(reset_at, 0).map_or_else(
769        || reset_at.to_string(),
770        |t| {
771            t.with_timezone(&chrono::Local)
772                .format("%H:%M:%S %Z")
773                .to_string()
774        },
775    )
776}
777
778/// Connect one project's backend and build its task manager and runner over
779/// the shared store.
780///
781/// `event_tx` wires status transitions into the event bus; pass `None` during
782/// startup, where the bus does not exist yet and task managers are rebuilt
783/// once it does
784async fn connect_project_engine(
785    repo: String,
786    project_dir: PathBuf,
787    store: Arc<TaskStore>,
788    event_tx: Option<Sender<events::TaskEvent>>,
789    hosted: bool,
790) -> anyhow::Result<ProjectEngine> {
791    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
792    let backend = outbox::wrap(backend, &store, &repo);
793
794    // A failed health check (rate limit, network, auth) must not drop the project: it would have
795    // no review subscriber until the next restart. Later ticks hit the API again and retry on
796    // their own, so build the engine and warn while the check keeps failing.
797    match backend.health_check().await {
798        Ok(()) => tracing::info!(repo = %repo, backend = backend.name(), "backend connected"),
799        Err(e) => tracing::warn!(
800            repo = %repo,
801            error = %e,
802            "GitHub health check failed for {repo}, starting engine anyway (rate limited, offline or bad credentials?)"
803        ),
804    }
805
806    let task_manager = Arc::new(match event_tx {
807        Some(tx) => {
808            TaskManager::with_events(Arc::clone(&backend), Arc::clone(&store), repo.clone(), tx)
809        }
810        None => TaskManager::with_store(Arc::clone(&backend), Arc::clone(&store), repo.clone()),
811    });
812    let runner = Arc::new(runner::TaskRunner::new(repo.clone()).with_store(Arc::clone(&store)));
813
814    Ok(ProjectEngine {
815        repo,
816        project_dir,
817        hosted,
818        backend,
819        task_manager,
820        runner,
821        store,
822    })
823}
824
825/**
826 * Split the configured project list into the ones not running yet and the names of the ones that
827 * went away. Kept separate from `sync_project_engines` so the comparison can be tested without a
828 * GitHub backend: getting it wrong either spawns a second set of subscribers for a project already
829 * running, or silently never picks a new one up
830 **/
831fn diff_configured_projects(
832    configured: &[(String, PathBuf)],
833    active_repos: &HashSet<String>,
834) -> (Vec<(String, PathBuf)>, Vec<String>) {
835    let configured_repos: HashSet<&str> = configured.iter().map(|(r, _)| r.as_str()).collect();
836
837    let added = configured
838        .iter()
839        .filter(|(repo, _)| !active_repos.contains(repo))
840        .cloned()
841        .collect();
842    let removed = active_repos
843        .iter()
844        .filter(|repo| !configured_repos.contains(repo.as_str()))
845        .cloned()
846        .collect();
847
848    (added, removed)
849}
850
851/// The engine handles every project's subscribers share
852#[derive(Clone, Copy)]
853pub(crate) struct Shared<'a> {
854    pub(crate) event_bus: &'a events::EventBus,
855    pub(crate) tmux: &'a Arc<TmuxManager>,
856    pub(crate) capture: &'a Arc<CaptureService>,
857    pub(crate) semaphore: &'a Arc<Semaphore>,
858    pub(crate) review_semaphore: &'a Arc<Semaphore>,
859    pub(crate) weight_tx: &'a mpsc::Sender<WeightSignal>,
860    pub(crate) router: &'a Arc<RwLock<Router>>,
861    pub(crate) dispatching: &'a Arc<dashmap::DashMap<String, String>>,
862}
863
864/// Start the dispatch, review and unblock subscribers of a project added after startup
865fn spawn_project_subscribers(engine: &ProjectEngine, shared: Shared<'_>) {
866    subscribers::dispatch::spawn(
867        shared.event_bus.subscribe(),
868        Arc::clone(&engine.backend),
869        Arc::clone(shared.tmux),
870        Arc::clone(&engine.runner),
871        Arc::clone(shared.capture),
872        Arc::clone(shared.semaphore),
873        Arc::clone(&engine.task_manager),
874        shared.weight_tx.clone(),
875        Arc::clone(shared.router),
876        Arc::clone(shared.dispatching),
877        Arc::clone(&engine.store),
878        engine.repo.clone(),
879    );
880    subscribers::review::spawn(
881        shared.event_bus.subscribe(),
882        Arc::clone(&engine.backend),
883        Arc::clone(shared.tmux),
884        Arc::clone(shared.review_semaphore),
885        Arc::clone(&engine.task_manager),
886        Arc::clone(shared.router),
887        Arc::clone(shared.dispatching),
888        Arc::clone(&engine.store),
889        engine.repo.clone(),
890    );
891    subscribers::unblock::spawn(
892        shared.event_bus.subscribe(),
893        Arc::clone(&engine.backend),
894        Arc::clone(&engine.task_manager),
895        Arc::clone(&engine.store),
896        engine.repo.clone(),
897    );
898}
899
900/// The repos this node has a checkout of
901pub(crate) fn hosted_repos(project_engines: &[ProjectEngine]) -> HashSet<String> {
902    project_engines
903        .iter()
904        .filter(|e| e.hosted)
905        .map(|e| e.repo.clone())
906        .collect()
907}
908
909/// Pick up projects added to `projects:` since startup, and report the ones
910/// that were removed.
911///
912/// A removed project keeps running until the next restart: its subscriber
913/// tasks and any agent it already dispatched outlive the config read
914async fn sync_project_engines(
915    store: &Arc<TaskStore>,
916    project_engines: &mut Vec<ProjectEngine>,
917    active_repos: &mut HashSet<String>,
918    shared: Shared<'_>,
919) {
920    let configured = match config::get_projects_with_paths() {
921        Ok(p) if !p.is_empty() => p,
922        Ok(_) => return,
923        Err(e) => {
924            tracing::warn!(err = %e, "could not re-read the project list, keeping the current one");
925            return;
926        }
927    };
928    let (added, removed) = diff_configured_projects(&configured, &hosted_repos(project_engines));
929    for repo in removed {
930        tracing::info!(
931            repo = %repo,
932            "project removed from config, takes effect after restart"
933        );
934    }
935
936    for (repo, project_dir) in added {
937        config::watch(&project_dir.join(".orch.yml"));
938        // A project this node served for another node now has a checkout here
939        if let Some(engine) = project_engines.iter_mut().find(|e| e.repo == repo) {
940            engine.project_dir = project_dir;
941            engine.hosted = true;
942            tracing::info!(repo = %repo, "project added from config, now hosted here");
943            continue;
944        }
945
946        let engine = match connect_project_engine(
947            repo.clone(),
948            project_dir,
949            Arc::clone(store),
950            Some(shared.event_bus.sender()),
951            true,
952        )
953        .await
954        {
955            Ok(engine) => engine,
956            Err(e) => {
957                // A failed health check no longer lands here, so this is a backend that could
958                // not be built at all, such as a repo slug that is not `owner/name`
959                tracing::warn!(
960                    repo = %repo,
961                    err = %e,
962                    "project added to config but its backend could not be built, retrying on the next config change"
963                );
964                continue;
965            }
966        };
967
968        spawn_project_subscribers(&engine, shared);
969        active_repos.insert(repo.clone());
970        project_engines.push(engine);
971        tracing::info!(repo = %repo, "project added from config, now syncing");
972    }
973}
974
975/**
976 * Serve the projects other nodes of the cluster host and this node does not, offline nodes
977 * included, so the leader polls, ingests and routes for every project. Their `.orch.yml` comes from
978 * the default branch, refreshed in the background while this node leads. Nothing on one machine
979 **/
980pub(crate) async fn sync_cluster_projects(
981    store: &Arc<TaskStore>,
982    project_engines: &mut Vec<ProjectEngine>,
983    active_repos: &mut HashSet<String>,
984    shared: Shared<'_>,
985    contents: Option<&Arc<dyn cluster_projects::Contents>>,
986) {
987    // A witness never leads and runs nothing, so it serves no project
988    if config::get_global("cluster.witness").is_ok_and(|w| w == "true") {
989        return;
990    }
991
992    let remote = cluster_projects::remote_projects(store, &hosted_repos(project_engines)).await;
993    if remote.is_empty() {
994        return;
995    }
996
997    let mut dirs = Vec::with_capacity(remote.len());
998    for repo in &remote {
999        match cluster_projects::config_dir(repo) {
1000            Ok(dir) => dirs.push((repo.clone(), dir)),
1001            Err(e) => tracing::warn!(repo = %repo, err = %e, "skipping a cluster project"),
1002        }
1003    }
1004
1005    if store.is_leader()
1006        && let Some(contents) = contents
1007    {
1008        let contents = Arc::clone(contents);
1009        let refresh = dirs.clone();
1010        tokio::spawn(async move {
1011            cluster_projects::refresh_all(contents.as_ref(), &refresh).await;
1012        });
1013    }
1014
1015    for (repo, dir) in dirs {
1016        if active_repos.contains(&repo) {
1017            continue;
1018        }
1019
1020        if let Err(e) = fs::create_dir_all(&dir).await {
1021            tracing::warn!(repo = %repo, err = %e, "cannot create the directory for a cluster project's config");
1022            continue;
1023        }
1024
1025        let engine = match connect_project_engine(
1026            repo.clone(),
1027            dir,
1028            Arc::clone(store),
1029            Some(shared.event_bus.sender()),
1030            false,
1031        )
1032        .await
1033        {
1034            Ok(engine) => engine,
1035            Err(e) => {
1036                tracing::warn!(repo = %repo, err = %e, "cannot serve a project another node hosts");
1037                continue;
1038            }
1039        };
1040        spawn_project_subscribers(&engine, shared);
1041        active_repos.insert(repo.clone());
1042        project_engines.push(engine);
1043        tracing::info!(repo = %repo, "serving a project another node hosts");
1044    }
1045}
1046
1047#[cfg(test)]
1048mod tests;