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 cooldown;
21pub mod dependencies;
22pub mod dispatch_guard;
23pub mod events;
24pub mod jobs;
25pub mod priority;
26pub mod push_retry;
27pub mod relay;
28pub mod review;
29pub mod review_gate;
30pub mod review_poll;
31pub mod review_shipcheck;
32pub mod router;
33pub mod runner;
34mod serve;
35mod startup;
36pub mod subscribers;
37pub mod suspend;
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::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    /// Stuck limit for an in_progress task whose session is alive: `stuck_timeout`, raised to the
489    /// run's own timeout plus `RUN_TIMEOUT_GRACE_SECS`
490    pub fn live_session_stuck_limit(&self, complexity: Option<&str>) -> u64 {
491        self.stuck_timeout.max(
492            self.run_timeouts
493                .for_complexity(complexity)
494                .saturating_add(RUN_TIMEOUT_GRACE_SECS),
495        )
496    }
497
498    /// Load engine configuration from config files, falling back to defaults.
499    pub fn from_config() -> Self {
500        let mut config = Self::default();
501
502        if let Ok(val) = config::get("engine.tick_interval") {
503            if let Ok(secs) = val.parse::<u64>() {
504                config.tick_interval = Duration::from_secs(secs);
505            } else {
506                tracing::warn!(key = "engine.tick_interval", value = %val, default_secs = config.tick_interval.as_secs(), "invalid value for engine.tick_interval, using default");
507            }
508        }
509
510        if let Ok(val) = config::get("engine.sync_interval") {
511            if let Ok(secs) = val.parse::<u64>() {
512                config.sync_interval = Duration::from_secs(secs);
513            } else {
514                tracing::warn!(key = "engine.sync_interval", value = %val, default_secs = config.sync_interval.as_secs(), "invalid value for engine.sync_interval, using default");
515            }
516        }
517
518        if let Ok(val) = config::get("engine.max_parallel") {
519            if let Ok(n) = val.parse::<usize>() {
520                config.max_parallel = n;
521            } else {
522                tracing::warn!(key = "engine.max_parallel", value = %val, default = config.max_parallel, "invalid value for engine.max_parallel, using default");
523            }
524        }
525
526        if let Ok(val) = config::get("engine.stuck_timeout") {
527            if let Ok(secs) = val.parse::<u64>() {
528                config.stuck_timeout = secs;
529            } else {
530                tracing::warn!(key = "engine.stuck_timeout", value = %val, default_secs = config.stuck_timeout, "invalid value for engine.stuck_timeout, using default");
531            }
532        }
533
534        if let Ok(val) = config::get("engine.no_session_stuck_timeout") {
535            if let Ok(secs) = val.parse::<u64>() {
536                config.no_session_stuck_timeout = secs;
537            } else {
538                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");
539            }
540        }
541
542        let mut in_review_from_config = false;
543        if let Ok(val) = config::get("engine.in_review_no_session_stuck_timeout") {
544            if let Ok(secs) = val.parse::<u64>() {
545                config.in_review_no_session_stuck_timeout = secs;
546                in_review_from_config = true;
547            } else {
548                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");
549            }
550        }
551
552        // Keep the no-session review limit over the review agent's own timeout plus delivery
553        // time, whatever either is set to. Under that, recovery resets a task whose finished
554        // review is still on its way to the engine and the result is dropped as stale
555        let review_timeout = engine_review::review_timeout_seconds();
556        let floored = engine_review::no_session_review_floor(
557            config.in_review_no_session_stuck_timeout,
558            review_timeout,
559        );
560        if floored != config.in_review_no_session_stuck_timeout {
561            if in_review_from_config {
562                tracing::warn!(
563                    configured_secs = config.in_review_no_session_stuck_timeout,
564                    review_timeout_secs = review_timeout,
565                    raised_to_secs = floored,
566                    "engine.in_review_no_session_stuck_timeout is below the review timeout plus result delivery time, raising it"
567                );
568            } else {
569                tracing::debug!(
570                    review_timeout_secs = review_timeout,
571                    raised_to_secs = floored,
572                    "raised the default in_review no-session limit over a long review timeout"
573                );
574            }
575            config.in_review_no_session_stuck_timeout = floored;
576        }
577
578        config.run_timeouts = RunTimeouts::from_config();
579
580        if let Ok(val) = config::get("engine.webhook_health_check_interval") {
581            if let Ok(secs) = val.parse::<u64>() {
582                if secs > 0 {
583                    config.webhook_health_check_interval = Some(Duration::from_secs(secs));
584                } else {
585                    config.webhook_health_check_interval = None;
586                }
587            } else {
588                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");
589            }
590        }
591
592        if let Ok(val) = config::get("workflow.auto_create_followup_on_changes") {
593            config.auto_create_followup_on_changes = !val.eq_ignore_ascii_case("false");
594        }
595
596        if let Ok(val) = config::get("engine.graceful_shutdown_timeout") {
597            if let Ok(secs) = val.parse::<u64>() {
598                config.graceful_shutdown_timeout = Duration::from_secs(secs);
599            } else {
600                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");
601            }
602        }
603
604        if let Ok(val) = config::get("engine.silence_grace_period") {
605            if let Ok(secs) = val.parse::<u64>() {
606                config.silence_grace_period = secs;
607            } else {
608                tracing::warn!(key = "engine.silence_grace_period", value = %val, default = config.silence_grace_period, "invalid value for engine.silence_grace_period, using default");
609            }
610        }
611
612        if let Ok(val) = config::get("engine.silence_cooldown") {
613            if let Ok(secs) = val.parse::<u64>() {
614                config.silence_cooldown = secs;
615            } else {
616                tracing::warn!(key = "engine.silence_cooldown", value = %val, default = config.silence_cooldown, "invalid value for engine.silence_cooldown, using default");
617            }
618        }
619
620        if let Ok(val) = config::get("engine.upgrade_check_interval") {
621            if let Ok(secs) = val.parse::<u64>() {
622                config.upgrade_check_interval = secs;
623            } else {
624                tracing::warn!(key = "engine.upgrade_check_interval", value = %val, default = config.upgrade_check_interval, "invalid value for engine.upgrade_check_interval, using default");
625            }
626        }
627
628        if let Ok(val) = config::get("engine.startup_failure_escalation_secs") {
629            if let Ok(secs) = val.parse::<u64>() {
630                config.startup_failure_escalation_secs = secs;
631            } else {
632                tracing::warn!(
633                    key = "engine.startup_failure_escalation_secs",
634                    value = %val,
635                    default_secs = config.startup_failure_escalation_secs,
636                    "invalid value for engine.startup_failure_escalation_secs, using default"
637                );
638            }
639        }
640
641        config
642    }
643}
644
645/// KV key holding the epoch second the GitHub core window resets, so `orch task status`
646/// can show the limit from a separate process.
647pub const RATE_LIMITED_UNTIL_KEY: &str = "github:rate_limited_until";
648
649/// Format an epoch second as a local `HH:MM:SS` for operator-facing output.
650pub fn format_rate_limited_until(reset_at: i64) -> String {
651    chrono::DateTime::from_timestamp(reset_at, 0).map_or_else(
652        || reset_at.to_string(),
653        |t| {
654            t.with_timezone(&chrono::Local)
655                .format("%H:%M:%S %Z")
656                .to_string()
657        },
658    )
659}
660
661/// Connect one project's backend and build its task manager and runner over
662/// the shared store.
663///
664/// `event_tx` wires status transitions into the event bus; pass `None` during
665/// startup, where the bus does not exist yet and task managers are rebuilt
666/// once it does
667async fn connect_project_engine(
668    repo: String,
669    project_dir: PathBuf,
670    store: Arc<TaskStore>,
671    event_tx: Option<Sender<events::TaskEvent>>,
672) -> anyhow::Result<ProjectEngine> {
673    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
674
675    // A failed health check (rate limit, network, auth) must not drop the project: it would have
676    // no review subscriber until the next restart. Later ticks hit the API again and retry on
677    // their own, so build the engine and warn while the check keeps failing.
678    match backend.health_check().await {
679        Ok(()) => tracing::info!(repo = %repo, backend = backend.name(), "backend connected"),
680        Err(e) => tracing::warn!(
681            repo = %repo,
682            error = %e,
683            "GitHub health check failed for {repo}, starting engine anyway (rate limited, offline or bad credentials?)"
684        ),
685    }
686
687    let task_manager = Arc::new(match event_tx {
688        Some(tx) => {
689            TaskManager::with_events(Arc::clone(&backend), Arc::clone(&store), repo.clone(), tx)
690        }
691        None => TaskManager::with_store(Arc::clone(&backend), Arc::clone(&store), repo.clone()),
692    });
693    let runner = Arc::new(runner::TaskRunner::new(repo.clone()).with_store(Arc::clone(&store)));
694
695    Ok(ProjectEngine {
696        repo,
697        project_dir,
698        backend,
699        task_manager,
700        runner,
701        store,
702    })
703}
704
705/**
706 * Split the configured project list into the ones not running yet and the names of the ones that
707 * went away. Kept separate from `sync_project_engines` so the comparison can be tested without a
708 * GitHub backend: getting it wrong either spawns a second set of subscribers for a project already
709 * running, or silently never picks a new one up
710 **/
711fn diff_configured_projects(
712    configured: &[(String, PathBuf)],
713    active_repos: &HashSet<String>,
714) -> (Vec<(String, PathBuf)>, Vec<String>) {
715    let configured_repos: HashSet<&str> = configured.iter().map(|(r, _)| r.as_str()).collect();
716
717    let added = configured
718        .iter()
719        .filter(|(repo, _)| !active_repos.contains(repo))
720        .cloned()
721        .collect();
722    let removed = active_repos
723        .iter()
724        .filter(|repo| !configured_repos.contains(repo.as_str()))
725        .cloned()
726        .collect();
727
728    (added, removed)
729}
730
731/// Pick up projects added to `projects:` since startup, and report the ones
732/// that were removed.
733///
734/// A removed project keeps running until the next restart: its subscriber
735/// tasks and any agent it already dispatched outlive the config read
736#[expect(
737    clippy::too_many_arguments,
738    reason = "a new project engine needs every shared engine handle"
739)]
740async fn sync_project_engines(
741    store: &Arc<TaskStore>,
742    project_engines: &mut Vec<ProjectEngine>,
743    active_repos: &mut HashSet<String>,
744    event_bus: &events::EventBus,
745    tmux: &Arc<TmuxManager>,
746    capture: &Arc<CaptureService>,
747    semaphore: &Arc<Semaphore>,
748    review_semaphore: &Arc<Semaphore>,
749    weight_tx: &mpsc::Sender<WeightSignal>,
750    router: &Arc<RwLock<Router>>,
751    dispatching: &Arc<dashmap::DashMap<String, String>>,
752) {
753    let configured = match config::get_projects_with_paths() {
754        Ok(p) if !p.is_empty() => p,
755        Ok(_) => return,
756        Err(e) => {
757            tracing::warn!(err = %e, "could not re-read the project list, keeping the current one");
758            return;
759        }
760    };
761    let (added, removed) = diff_configured_projects(&configured, active_repos);
762    for repo in removed {
763        tracing::info!(
764            repo = %repo,
765            "project removed from config, takes effect after restart"
766        );
767    }
768
769    for (repo, project_dir) in added {
770        config::watch(&project_dir.join(".orch.yml"));
771        let engine = match connect_project_engine(
772            repo.clone(),
773            project_dir,
774            Arc::clone(store),
775            Some(event_bus.sender()),
776        )
777        .await
778        {
779            Ok(engine) => engine,
780            Err(e) => {
781                // A failed health check no longer lands here, so this is a backend that could
782                // not be built at all, such as a repo slug that is not `owner/name`
783                tracing::warn!(
784                    repo = %repo,
785                    err = %e,
786                    "project added to config but its backend could not be built, retrying on the next config change"
787                );
788                continue;
789            }
790        };
791
792        subscribers::dispatch::spawn(
793            event_bus.subscribe(),
794            Arc::clone(&engine.backend),
795            Arc::clone(tmux),
796            Arc::clone(&engine.runner),
797            Arc::clone(capture),
798            Arc::clone(semaphore),
799            Arc::clone(&engine.task_manager),
800            weight_tx.clone(),
801            Arc::clone(router),
802            Arc::clone(dispatching),
803            Arc::clone(&engine.store),
804            engine.repo.clone(),
805        );
806        subscribers::review::spawn(
807            event_bus.subscribe(),
808            Arc::clone(&engine.backend),
809            Arc::clone(tmux),
810            Arc::clone(review_semaphore),
811            Arc::clone(&engine.task_manager),
812            Arc::clone(router),
813            Arc::clone(dispatching),
814            Arc::clone(&engine.store),
815            engine.repo.clone(),
816        );
817        subscribers::unblock::spawn(
818            event_bus.subscribe(),
819            Arc::clone(&engine.backend),
820            Arc::clone(&engine.task_manager),
821            Arc::clone(&engine.store),
822            engine.repo.clone(),
823        );
824
825        active_repos.insert(repo.clone());
826        project_engines.push(engine);
827        tracing::info!(repo = %repo, "project added from config, now syncing");
828    }
829}
830
831#[cfg(test)]
832mod tests;