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