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