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