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