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