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