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, skills)
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 cleanup;
18pub mod commands;
19pub mod cooldown;
20pub mod dependencies;
21pub mod dispatch_guard;
22pub mod events;
23pub mod jobs;
24pub mod priority;
25pub mod relay;
26pub mod review;
27pub mod review_gate;
28pub mod review_poll;
29pub mod review_shipcheck;
30pub mod router;
31pub mod runner;
32pub mod subscribers;
33pub mod suspend;
34pub mod sync;
35pub mod tasks;
36pub mod tick;
37
38/// Standard Orch attribution footer for issue bodies, PR bodies, and comments.
39///
40/// Append to every user-visible string posted to GitHub so activity is
41/// clearly attributed to orch rather than appearing as a human post.
42use crate::backends::{ExternalBackend, ExternalId};
43use crate::channels::capture::CaptureService;
44use crate::channels::discord_ws::DiscordGateway;
45use crate::channels::github::start_webhook_server;
46use crate::channels::notification::NotificationLevel;
47use crate::channels::routing::{ChannelRouter, GlobalChannelConfig, ProjectChannelConfig};
48use crate::channels::slack::SlackChannel;
49use crate::channels::telegram::TelegramChannel;
50use crate::channels::tmux::TmuxChannel;
51use crate::channels::transport::Transport;
52use crate::channels::{Channel, ChannelRegistry, IncomingMessage, OutgoingMessage};
53use crate::cmd::CommandErrorContext;
54use crate::config;
55use crate::engine::cleanup::remove_worktree_and_branch;
56use crate::engine::router::{Router, RouterConfig};
57use crate::engine::runner::worktree::{
58    abort_worktree_rebase, list_project_worktrees, rebase_worktree_on_origin_main,
59    task_id_from_worktree_name, validate_worktree_gitdir,
60};
61use crate::engine::tasks::TaskManager;
62use crate::github::http::{GhHttp, rate_limit_metrics};
63use crate::repo_context::REPO_CONTEXT;
64use crate::store::{TaskStatus, TaskStore};
65use crate::tmux::TmuxManager;
66use runner::WeightSignal;
67// AtomicBool/Ordering removed — shutdown is now immediate (reset tasks + break)
68use crate::backends::Status;
69use crate::backends::github::GitHubBackend;
70use crate::channels::github;
71use crate::channels::github::is_transient_bind_error;
72use crate::channels::github::webhook_backoff_delay;
73use crate::channels::notification;
74use crate::channels::notification::TaskNotification;
75use crate::channels::transport;
76use crate::cluster;
77use crate::cluster::local;
78use crate::engine::cooldown as engine_cooldown;
79use crate::engine::review as engine_review;
80use crate::engine::runner::git_ops;
81use crate::engine::runner::worktree;
82use crate::engine::suspend as engine_suspend;
83use crate::engine::suspend::SuspendDetector;
84use crate::engine::tasks as engine_tasks;
85use crate::github::app;
86use crate::home;
87use crate::secret_ref;
88use crate::store;
89use crate::webhook_status::WebhookStatus;
90use futures::future;
91use std::collections::HashMap;
92use std::collections::HashSet;
93use std::fmt;
94use std::fmt::Debug;
95use std::fmt::Formatter;
96use std::fs;
97use std::path::Path;
98use std::path::PathBuf;
99use std::sync::Arc;
100use std::sync::atomic::AtomicBool;
101use std::sync::atomic::AtomicU64;
102use std::sync::atomic::Ordering;
103use std::time as std_time;
104use std::time::Duration;
105use std::time::Instant;
106use std::time::SystemTime;
107use tokio::process::Command;
108use tokio::signal;
109use tokio::signal::unix;
110use tokio::signal::unix::SignalKind;
111use tokio::sync::Mutex;
112use tokio::sync::broadcast::Sender;
113use tokio::sync::broadcast::error::RecvError;
114use tokio::sync::mpsc::Receiver;
115use tokio::sync::{Notify, RwLock, Semaphore, mpsc};
116use tokio::task;
117use tokio::time;
118
119pub fn orch_footer() -> &'static str {
120    "\n\n---\n*Posted by [Orch](https://github.com/gabrielkoerich/orch)*"
121}
122
123/// Build a standard attribution footer for GitHub comments posted by orch bots.
124///
125/// `verb` is "Created", "Reviewed", or "Commented" depending on context.
126pub fn attribution_footer(verb: &str, agent: &str, model: Option<&str>) -> String {
127    match model {
128        Some(m) => format!(
129            "\n\n---\n*{verb} by {agent}[bot] via [Orch](https://github.com/gabrielkoerich/orch) using `{m}`*"
130        ),
131        None => format!(
132            "\n\n---\n*{verb} by {agent}[bot] via [Orch](https://github.com/gabrielkoerich/orch)*"
133        ),
134    }
135}
136
137/// Lightweight reference tuple for channel message handling.
138type EngineRef = (
139    String,
140    Arc<dyn ExternalBackend>,
141    Arc<TaskManager>,
142    Option<Arc<TaskStore>>,
143);
144
145/// Per-project engine state.
146///
147/// Each project has its own backend, task runner, and task manager,
148/// but they share the global tmux manager, transport, and semaphore.
149#[derive(Clone)]
150pub struct ProjectEngine {
151    pub repo: String,
152    pub project_dir: PathBuf,
153    pub backend: Arc<dyn ExternalBackend>,
154    pub task_manager: Arc<TaskManager>,
155    pub runner: Arc<runner::TaskRunner>,
156    pub store: Arc<TaskStore>,
157}
158
159impl Debug for ProjectEngine {
160    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
161        f.debug_struct("ProjectEngine")
162            .field("repo", &self.repo)
163            .field("project_dir", &self.project_dir)
164            .finish_non_exhaustive()
165    }
166}
167
168/// A restart ends every review session, so an `in_review` task with no session has no reviewer.
169/// Hand it back to `needs_review` at start, so it does not wait for the stuck-review recovery
170pub(crate) async fn reset_orphaned_reviews(
171    task_manager: &TaskManager,
172    store: &Arc<TaskStore>,
173    repo: &str,
174    tmux: &TmuxManager,
175) -> usize {
176    // The store holds external and internal tasks, the second list is the legacy internal table
177    let mut ids: Vec<ExternalId> = store
178        .list_by_status(repo, TaskStatus::InReview)
179        .await
180        .unwrap_or_default()
181        .iter()
182        .map(|t| engine_tasks::store_task_to_external(t).id)
183        .collect();
184    if let Ok(legacy) = task_manager
185        .list_internal_by_status(TaskStatus::InReview)
186        .await
187    {
188        ids.extend(legacy.into_iter().map(|t| t.id));
189    }
190    ids.sort_by(|a, b| a.0.cmp(&b.0));
191    ids.dedup_by(|a, b| a.0 == b.0);
192
193    let mut reset = 0;
194    for id in &ids {
195        let session = tmux.session_name(repo, &format!("{}-review", id.0));
196
197        if tmux.session_exists(&session).await {
198            continue;
199        }
200
201        if let Err(e) = task_manager
202            .update_task_status(id, Status::NeedsReview)
203            .await
204        {
205            tracing::warn!(
206                task_id = id.0,
207                ?e,
208                "failed to reset an orphaned review at start"
209            );
210            continue;
211        }
212
213        if let Ok(Some(store_id)) = store.resolve_task_id(repo, &id.0).await {
214            let reason = "startup: review session gone, reset to needs_review";
215
216            if let Err(e) = store
217                .finalize_incomplete_runs(store_id, "aborted", reason)
218                .await
219            {
220                tracing::warn!(
221                    task_id = id.0,
222                    ?e,
223                    "failed to finalize the orphaned review's runs"
224                );
225            }
226        }
227
228        reset += 1;
229    }
230
231    reset
232}
233
234/// Starts the relay client when `relay.url` is set. The token is read in the background, so a
235/// passbox prompt nobody answers never holds up the engine
236fn start_relay_client(project_engines: &[ProjectEngine], notify: &Arc<Notify>) {
237    // The global config only: a project file must never point a secret at its own endpoint
238    let url = config::get_global("relay.url").unwrap_or_default();
239    let Some(store) = project_engines.first().map(|e| Arc::clone(&e.store)) else {
240        return;
241    };
242
243    if url.is_empty() {
244        return;
245    }
246
247    let token_ref = config::get_global("relay.token").unwrap_or_default();
248    let notify = Arc::clone(notify);
249    tokio::spawn(async move {
250        let mut warned = false;
251        let token = loop {
252            let reference = token_ref.clone();
253            let read = task::spawn_blocking(move || secret_ref::resolve(&reference))
254                .await
255                .map_err(anyhow::Error::from)
256                .and_then(|r| r);
257
258            match read {
259                Ok(token) if !token.is_empty() => break token,
260                Ok(_) => {
261                    tracing::warn!("relay.token is empty, the relay client stays off");
262                    return;
263                }
264                Err(e) if !warned => {
265                    tracing::warn!(err = %e, "could not read relay.token, retrying every 5 minutes");
266                    warned = true;
267                }
268                Err(_) => {}
269            }
270
271            time::sleep(Duration::from_secs(300)).await;
272        };
273
274        relay::run(url, token, store, notify).await;
275    });
276}
277
278/**
279 * Runs `sync_tick` for every project at once, then the tail that is the same for all of them,
280 * in a spawned task. Sync time is the slowest project instead of the sum of all of them
281 * (#3864). The caller must already hold `sync_in_progress`; this releases it when done
282 **/
283#[expect(
284    clippy::too_many_arguments,
285    reason = "the spawned task takes its own handle to each piece of engine state"
286)]
287fn spawn_sync_pass(
288    project_engines: &[ProjectEngine],
289    tmux: &Arc<TmuxManager>,
290    engine_config: &EngineConfig,
291    router: &Arc<RwLock<Router>>,
292    dispatching: &Arc<dashmap::DashMap<String, String>>,
293    auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
294    sync_in_progress: &Arc<AtomicBool>,
295    trigger: &'static str,
296) {
297    let engines = project_engines.to_vec();
298    let tmux = Arc::clone(tmux);
299    let engine_config = engine_config.clone();
300    let router = Arc::clone(router);
301    let dispatching = Arc::clone(dispatching);
302    let auto_merge_in_flight = Arc::clone(auto_merge_in_flight);
303    let guard = Arc::clone(sync_in_progress);
304
305    tokio::spawn(async move {
306        let started = Instant::now();
307        let mut passes = Vec::with_capacity(engines.len());
308        for engine in &engines {
309            passes.push(REPO_CONTEXT.scope(
310                engine.repo.clone(),
311                sync_one_project(
312                    engine,
313                    &tmux,
314                    &engine_config,
315                    &router,
316                    &dispatching,
317                    &auto_merge_in_flight,
318                ),
319            ));
320        }
321        future::join_all(passes).await;
322
323        sync::sync_shared_tail(&router, engines.first().map(|e| &e.store)).await;
324        tracing::info!(
325            trigger,
326            elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
327            "sync tick complete"
328        );
329        guard.store(false, Ordering::Release);
330    });
331}
332
333async fn sync_one_project(
334    engine: &ProjectEngine,
335    tmux: &Arc<TmuxManager>,
336    engine_config: &EngineConfig,
337    router: &Arc<RwLock<Router>>,
338    dispatching: &Arc<dashmap::DashMap<String, String>>,
339    auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
340) {
341    if let Err(e) = Box::pin(sync::sync_tick(
342        &engine.backend,
343        tmux,
344        &engine.repo,
345        engine_config,
346        router,
347        &engine.task_manager,
348        &engine.store,
349        dispatching,
350        auto_merge_in_flight,
351    ))
352    .await
353    {
354        tracing::error!(repo = %engine.repo, ?e, "sync tick failed for project");
355    }
356}
357
358/// Milliseconds a group of tick or sync phases may take before it is worth an operator's eye
359const SLOW_PHASE_GROUP_MS: u128 = 1_000;
360
361/**
362 * Logs how long each phase of a tick or sync group took, for one project. Tick and sync time
363 * grows with the project count, and the totals alone did not say which project or phase spent
364 * it (#3864). Info once a group crosses `SLOW_PHASE_GROUP_MS`, so a quiet install stays quiet
365 **/
366pub(crate) fn log_phase_timings(group: &str, repo: &str, phases: &[(&str, u128)]) {
367    let total_ms: u128 = phases.iter().map(|(_, ms)| ms).sum();
368    if total_ms >= SLOW_PHASE_GROUP_MS {
369        tracing::info!(group, repo, total_ms, ?phases, "phase timings");
370    } else {
371        tracing::debug!(group, repo, total_ms, ?phases, "phase timings");
372    }
373}
374
375/// Return the configured agent list from top-level `agents` in config.yml,
376/// falling back to [`router::config::DEFAULT_AGENTS`] when not set.
377///
378/// This is the canonical source of truth for "which agents does orch know
379/// about" — use it instead of `DEFAULT_AGENTS` directly so that
380/// Claude-compatible agents added via config (e.g. `olm`) are recognized
381/// without code changes.
382///
383/// The key is top-level (`agents:`) rather than nested (`engine.agents:`)
384/// because `config::get` serializes nested YAML arrays via `serde_norway::to_string`
385/// which produces YAML block format, not JSON — breaking downstream parsing.
386pub fn configured_agents() -> Vec<String> {
387    if let Ok(agents_str) = config::get("agents")
388        && !agents_str.is_empty()
389        && agents_str != "[]"
390    {
391        // config::get returns serde_norway::to_string for arrays, which is
392        // YAML block format ("- claude\n- codex\n..."). Parse as YAML first.
393        if let Ok(agents_arr) = serde_norway::from_str::<Vec<String>>(&agents_str)
394            && !agents_arr.is_empty()
395        {
396            return agents_arr;
397        }
398        // Fallback: try JSON (inline arrays) or comma-separated
399        if let Ok(agents_arr) = serde_json::from_str::<Vec<String>>(&agents_str)
400            && !agents_arr.is_empty()
401        {
402            return agents_arr;
403        }
404    }
405    router::config::DEFAULT_AGENTS
406        .iter()
407        .map(ToString::to_string)
408        .collect()
409}
410
411/// Seconds a live session may run past its own timeout before stuck recovery takes it. The
412/// `timeout` wrapper ends the agent at the limit, and the runner still collects the result
413pub const RUN_TIMEOUT_GRACE_SECS: u64 = 300;
414
415/// The limit the `timeout` wrapper puts on one agent run, per complexity
416#[derive(Clone, Copy, Debug, PartialEq, Eq)]
417pub struct RunTimeouts {
418    pub base: u64,
419    pub medium: u64,
420    pub complex: u64,
421}
422
423impl Default for RunTimeouts {
424    fn default() -> Self {
425        Self {
426            base: 1800,
427            medium: 1800,
428            complex: 1800,
429        }
430    }
431}
432
433impl RunTimeouts {
434    /// `workflow.timeout_seconds` (at least 1800), raised by
435    /// `workflow.timeout_by_complexity.{medium,complex}` but never below the base
436    pub fn from_config() -> Self {
437        let read =
438            |key: &str| -> Option<u64> { config::get(key).ok().and_then(|s| s.parse().ok()) };
439        let base = read("workflow.timeout_seconds").unwrap_or(1800).max(1800);
440        Self {
441            base,
442            medium: read("workflow.timeout_by_complexity.medium")
443                .unwrap_or(base)
444                .max(base),
445            complex: read("workflow.timeout_by_complexity.complex")
446                .unwrap_or(base)
447                .max(base),
448        }
449    }
450
451    pub fn for_complexity(&self, complexity: Option<&str>) -> u64 {
452        match complexity {
453            Some("complex") => self.complex,
454            Some("medium") => self.medium,
455            _ => self.base,
456        }
457    }
458}
459
460/// Engine configuration.
461#[derive(Clone, Debug)]
462pub struct EngineConfig {
463    /// Main tick interval
464    pub tick_interval: Duration,
465    /// GitHub sync interval (cleanup, PR review, mentions)
466    pub sync_interval: Duration,
467    /// Webhook health check interval (seconds)
468    pub webhook_health_check_interval: Option<Duration>,
469    /// Maximum parallel task executions
470    pub max_parallel: usize,
471    /// Stuck task timeout for tasks with an active tmux session (seconds)
472    pub stuck_timeout: u64,
473    /// Stuck task timeout for tasks with no active tmux session (seconds).
474    /// Shorter than `stuck_timeout` because no session means the agent has already exited.
475    pub no_session_stuck_timeout: u64,
476    /// Stuck task timeout for in_review tasks with no active tmux session (seconds).
477    /// Longer than `no_session_stuck_timeout` because a review agent ends its tmux session on
478    /// normal completion before its result reaches the engine. A shorter limit resets a task
479    /// whose finished review is still being delivered, and the result is dropped as stale.
480    /// `from_config` keeps it above the review agent's own timeout plus
481    /// `review::REVIEW_RESULT_DELIVERY_SECS`.
482    pub in_review_no_session_stuck_timeout: u64,
483    /// Per-run agent timeouts. A live session is not stuck before its own timeout runs out
484    pub run_timeouts: RunTimeouts,
485    /// Auto-create follow-up tasks when PR reviews request changes
486    pub auto_create_followup_on_changes: bool,
487    /// Graceful shutdown timeout — how long to wait for running agents before exiting.
488    pub graceful_shutdown_timeout: Duration,
489    /// Grace period before silence detection kicks in (seconds).
490    /// Allows time for agent startup, model download, API handshake.
491    pub silence_grace_period: u64,
492    /// Cooldown duration for a model detected as silent (seconds).
493    pub silence_cooldown: u64,
494    /// How often to check for a newer orch release and notify channels (seconds).
495    /// Set to 0 to disable. Default: 3600 (1 hour).
496    pub upgrade_check_interval: u64,
497    /// Seconds of continuous startup failure (GitHub unreachable / auth errors)
498    /// before the engine escalates from WARN to ERROR-level logging and sends a
499    /// one-time push notification to configured channels. Set to 0 to disable.
500    /// Default: 3600 (1 hour).
501    pub startup_failure_escalation_secs: u64,
502}
503
504impl Default for EngineConfig {
505    fn default() -> Self {
506        Self {
507            tick_interval: Duration::from_secs(10),
508            sync_interval: Duration::from_secs(45),
509            webhook_health_check_interval: Some(Duration::from_secs(60)),
510            max_parallel: 4,
511            stuck_timeout: 1800,
512            no_session_stuck_timeout: 600,
513            in_review_no_session_stuck_timeout: 1920,
514            run_timeouts: RunTimeouts::default(),
515            auto_create_followup_on_changes: true,
516            graceful_shutdown_timeout: Duration::from_secs(600),
517            silence_grace_period: 300,
518            silence_cooldown: 3600,
519            upgrade_check_interval: 3600,
520            startup_failure_escalation_secs: 3600,
521        }
522    }
523}
524
525impl EngineConfig {
526    /// Stuck limit for an in_progress task whose session is alive: `stuck_timeout`, raised to the
527    /// run's own timeout plus `RUN_TIMEOUT_GRACE_SECS`
528    pub fn live_session_stuck_limit(&self, complexity: Option<&str>) -> u64 {
529        self.stuck_timeout.max(
530            self.run_timeouts
531                .for_complexity(complexity)
532                .saturating_add(RUN_TIMEOUT_GRACE_SECS),
533        )
534    }
535
536    /// Load engine configuration from config files, falling back to defaults.
537    pub fn from_config() -> Self {
538        let mut config = Self::default();
539
540        if let Ok(val) = config::get("engine.tick_interval") {
541            if let Ok(secs) = val.parse::<u64>() {
542                config.tick_interval = Duration::from_secs(secs);
543            } else {
544                tracing::warn!(key = "engine.tick_interval", value = %val, default_secs = config.tick_interval.as_secs(), "invalid value for engine.tick_interval, using default");
545            }
546        }
547
548        if let Ok(val) = config::get("engine.sync_interval") {
549            if let Ok(secs) = val.parse::<u64>() {
550                config.sync_interval = Duration::from_secs(secs);
551            } else {
552                tracing::warn!(key = "engine.sync_interval", value = %val, default_secs = config.sync_interval.as_secs(), "invalid value for engine.sync_interval, using default");
553            }
554        }
555
556        if let Ok(val) = config::get("engine.max_parallel") {
557            if let Ok(n) = val.parse::<usize>() {
558                config.max_parallel = n;
559            } else {
560                tracing::warn!(key = "engine.max_parallel", value = %val, default = config.max_parallel, "invalid value for engine.max_parallel, using default");
561            }
562        }
563
564        if let Ok(val) = config::get("engine.stuck_timeout") {
565            if let Ok(secs) = val.parse::<u64>() {
566                config.stuck_timeout = secs;
567            } else {
568                tracing::warn!(key = "engine.stuck_timeout", value = %val, default_secs = config.stuck_timeout, "invalid value for engine.stuck_timeout, using default");
569            }
570        }
571
572        if let Ok(val) = config::get("engine.no_session_stuck_timeout") {
573            if let Ok(secs) = val.parse::<u64>() {
574                config.no_session_stuck_timeout = secs;
575            } else {
576                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");
577            }
578        }
579
580        let mut in_review_from_config = false;
581        if let Ok(val) = config::get("engine.in_review_no_session_stuck_timeout") {
582            if let Ok(secs) = val.parse::<u64>() {
583                config.in_review_no_session_stuck_timeout = secs;
584                in_review_from_config = true;
585            } else {
586                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");
587            }
588        }
589
590        // Keep the no-session review limit over the review agent's own timeout plus delivery
591        // time, whatever either is set to. Under that, recovery resets a task whose finished
592        // review is still on its way to the engine and the result is dropped as stale
593        let review_timeout = engine_review::review_timeout_seconds();
594        let floored = engine_review::no_session_review_floor(
595            config.in_review_no_session_stuck_timeout,
596            review_timeout,
597        );
598        if floored != config.in_review_no_session_stuck_timeout {
599            if in_review_from_config {
600                tracing::warn!(
601                    configured_secs = config.in_review_no_session_stuck_timeout,
602                    review_timeout_secs = review_timeout,
603                    raised_to_secs = floored,
604                    "engine.in_review_no_session_stuck_timeout is below the review timeout plus result delivery time, raising it"
605                );
606            } else {
607                tracing::debug!(
608                    review_timeout_secs = review_timeout,
609                    raised_to_secs = floored,
610                    "raised the default in_review no-session limit over a long review timeout"
611                );
612            }
613            config.in_review_no_session_stuck_timeout = floored;
614        }
615
616        config.run_timeouts = RunTimeouts::from_config();
617
618        if let Ok(val) = config::get("engine.webhook_health_check_interval") {
619            if let Ok(secs) = val.parse::<u64>() {
620                if secs > 0 {
621                    config.webhook_health_check_interval = Some(Duration::from_secs(secs));
622                } else {
623                    config.webhook_health_check_interval = None;
624                }
625            } else {
626                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");
627            }
628        }
629
630        if let Ok(val) = config::get("workflow.auto_create_followup_on_changes") {
631            config.auto_create_followup_on_changes = !val.eq_ignore_ascii_case("false");
632        }
633
634        if let Ok(val) = config::get("engine.graceful_shutdown_timeout") {
635            if let Ok(secs) = val.parse::<u64>() {
636                config.graceful_shutdown_timeout = Duration::from_secs(secs);
637            } else {
638                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");
639            }
640        }
641
642        if let Ok(val) = config::get("engine.silence_grace_period") {
643            if let Ok(secs) = val.parse::<u64>() {
644                config.silence_grace_period = secs;
645            } else {
646                tracing::warn!(key = "engine.silence_grace_period", value = %val, default = config.silence_grace_period, "invalid value for engine.silence_grace_period, using default");
647            }
648        }
649
650        if let Ok(val) = config::get("engine.silence_cooldown") {
651            if let Ok(secs) = val.parse::<u64>() {
652                config.silence_cooldown = secs;
653            } else {
654                tracing::warn!(key = "engine.silence_cooldown", value = %val, default = config.silence_cooldown, "invalid value for engine.silence_cooldown, using default");
655            }
656        }
657
658        if let Ok(val) = config::get("engine.upgrade_check_interval") {
659            if let Ok(secs) = val.parse::<u64>() {
660                config.upgrade_check_interval = secs;
661            } else {
662                tracing::warn!(key = "engine.upgrade_check_interval", value = %val, default = config.upgrade_check_interval, "invalid value for engine.upgrade_check_interval, using default");
663            }
664        }
665
666        if let Ok(val) = config::get("engine.startup_failure_escalation_secs") {
667            if let Ok(secs) = val.parse::<u64>() {
668                config.startup_failure_escalation_secs = secs;
669            } else {
670                tracing::warn!(
671                    key = "engine.startup_failure_escalation_secs",
672                    value = %val,
673                    default_secs = config.startup_failure_escalation_secs,
674                    "invalid value for engine.startup_failure_escalation_secs, using default"
675                );
676            }
677        }
678
679        config
680    }
681}
682
683/// KV key holding the epoch second the GitHub core window resets, so `orch task status`
684/// can show the limit from a separate process.
685pub const RATE_LIMITED_UNTIL_KEY: &str = "github:rate_limited_until";
686
687/// Format an epoch second as a local `HH:MM:SS` for operator-facing output.
688pub fn format_rate_limited_until(reset_at: i64) -> String {
689    chrono::DateTime::from_timestamp(reset_at, 0).map_or_else(
690        || reset_at.to_string(),
691        |t| {
692            t.with_timezone(&chrono::Local)
693                .format("%H:%M:%S %Z")
694                .to_string()
695        },
696    )
697}
698
699/// Announce a GitHub rate-limit window on every operator surface: the log (`orch log`),
700/// a KV flag (`orch task status`) and the channels (Telegram, Discord).
701async fn report_rate_limited(
702    reset_at: i64,
703    store: Option<&Arc<TaskStore>>,
704    transport: Option<&Arc<Transport>>,
705) {
706    let m = rate_limit_metrics();
707    let until = format_rate_limited_until(reset_at);
708    tracing::warn!(
709        reset_at,
710        rate_limit_hits = m.hits,
711        skipped_calls = m.skipped_calls,
712        five_xx_hits = m.five_xx_hits,
713        rest_remaining = ?m.rest_remaining,
714        graphql_remaining = ?m.graphql_remaining,
715        "GitHub API rate limited until {until} — skipping GitHub calls, local work continues"
716    );
717
718    if let Some(store) = store
719        && let Err(e) = store
720            .kv_set(RATE_LIMITED_UNTIL_KEY, &reset_at.to_string())
721            .await
722    {
723        tracing::warn!(err = %e, "failed to persist GitHub rate-limit flag");
724    }
725
726    if let Some(transport) = transport {
727        transport.push_notification(TaskNotification {
728            task_id: "github".to_string(),
729            title: "GitHub rate limit".to_string(),
730            status: "blocked".to_string(),
731            agent: "orch".to_string(),
732            duration_seconds: 0.0,
733            summary: format!(
734                "rate limited until {until}. GitHub calls are skipped until then; running agents and local work continue."
735            ),
736            repo: None,
737            notify_target: None,
738            pr_number: None,
739        });
740    }
741}
742
743/// Grow or shrink the dispatch pool toward `target` without cancelling running work.
744///
745/// Growing adds permits at once. Shrinking can only take back the permits that
746/// are free right now, so the return value is the limit actually in force; call
747/// again as running tasks release theirs
748fn resize_dispatch_pool(semaphore: &Semaphore, in_force: usize, target: usize) -> usize {
749    if target > in_force {
750        semaphore.add_permits(target - in_force);
751        return target;
752    }
753
754    if target < in_force {
755        return in_force - semaphore.forget_permits(in_force - target);
756    }
757
758    in_force
759}
760
761/// Config subtrees the engine only reads at startup: the channel gateways hold
762/// long-lived websockets and the webhook listener binds its port once.
763const RESTART_ONLY_KEYS: [&str; 3] = ["channels", "webhook", "relay"];
764
765/// Read the restart-only subtrees so a later reload can tell they changed.
766fn restart_only_snapshot() -> Vec<Option<String>> {
767    RESTART_ONLY_KEYS
768        .iter()
769        .map(|key| config::get(key).ok())
770        .collect()
771}
772
773/// Report the restart-only keys an edit changed. Only the key is logged, never
774/// the value, because `channels.*` holds bot tokens
775fn log_restart_only_changes(old: &[Option<String>], new: &[Option<String>]) -> Vec<&'static str> {
776    let changed: Vec<&'static str> = RESTART_ONLY_KEYS
777        .iter()
778        .zip(old)
779        .zip(new)
780        .filter(|((_, old), new)| old != new)
781        .map(|((key, _), _)| *key)
782        .collect();
783
784    for key in &changed {
785        tracing::info!(key = key, "config changed, takes effect after restart");
786    }
787
788    changed
789}
790
791/// Log every engine setting whose value changed across a config reload, so
792/// `orch log` shows what the operator's edit actually did.
793fn log_engine_config_changes(old: &EngineConfig, new: &EngineConfig) {
794    macro_rules! log_changed {
795        ($($key:literal => $field:ident),+ $(,)?) => {
796            $(if old.$field != new.$field {
797                tracing::info!(key = $key, old = ?old.$field, new = ?new.$field, "config changed");
798            })+
799        };
800    }
801
802    log_changed!(
803        "engine.tick_interval" => tick_interval,
804        "engine.sync_interval" => sync_interval,
805        "engine.webhook_health_check_interval" => webhook_health_check_interval,
806        "engine.max_parallel" => max_parallel,
807        "engine.stuck_timeout" => stuck_timeout,
808        "engine.no_session_stuck_timeout" => no_session_stuck_timeout,
809        "engine.in_review_no_session_stuck_timeout" => in_review_no_session_stuck_timeout,
810        "engine.graceful_shutdown_timeout" => graceful_shutdown_timeout,
811        "engine.silence_grace_period" => silence_grace_period,
812        "engine.silence_cooldown" => silence_cooldown,
813        "engine.upgrade_check_interval" => upgrade_check_interval,
814        "engine.startup_failure_escalation_secs" => startup_failure_escalation_secs,
815        "workflow.auto_create_followup_on_changes" => auto_create_followup_on_changes,
816    );
817}
818
819fn should_run_upgrade_check(
820    last_upgrade_check: Option<Instant>,
821    upgrade_check_interval: u64,
822) -> bool {
823    if upgrade_check_interval == 0 {
824        return false;
825    }
826
827    last_upgrade_check
828        .is_none_or(|last| last.elapsed() >= Duration::from_secs(upgrade_check_interval))
829}
830
831/// Connect one project's backend and build its task manager and runner over
832/// the shared store.
833///
834/// `event_tx` wires status transitions into the event bus; pass `None` during
835/// startup, where the bus does not exist yet and task managers are rebuilt
836/// once it does
837async fn connect_project_engine(
838    repo: String,
839    project_dir: PathBuf,
840    store: Arc<TaskStore>,
841    event_tx: Option<Sender<events::TaskEvent>>,
842) -> anyhow::Result<ProjectEngine> {
843    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
844
845    // A failed health check (rate limit, network, auth) must not drop the project: it would have
846    // no review subscriber until the next restart. Later ticks hit the API again and retry on
847    // their own, so build the engine and warn while the check keeps failing.
848    match backend.health_check().await {
849        Ok(()) => tracing::info!(repo = %repo, backend = backend.name(), "backend connected"),
850        Err(e) => tracing::warn!(
851            repo = %repo,
852            error = %e,
853            "GitHub health check failed for {repo}, starting engine anyway (rate limited, offline or bad credentials?)"
854        ),
855    }
856
857    let task_manager = Arc::new(match event_tx {
858        Some(tx) => {
859            TaskManager::with_events(Arc::clone(&backend), Arc::clone(&store), repo.clone(), tx)
860        }
861        None => TaskManager::with_store(Arc::clone(&backend), Arc::clone(&store), repo.clone()),
862    });
863    let runner = Arc::new(runner::TaskRunner::new(repo.clone()).with_store(Arc::clone(&store)));
864
865    Ok(ProjectEngine {
866        repo,
867        project_dir,
868        backend,
869        task_manager,
870        runner,
871        store,
872    })
873}
874
875/**
876 * Split the configured project list into the ones not running yet and the names of the ones that
877 * went away. Kept separate from `sync_project_engines` so the comparison can be tested without a
878 * GitHub backend: getting it wrong either spawns a second set of subscribers for a project already
879 * running, or silently never picks a new one up
880 **/
881fn diff_configured_projects(
882    configured: &[(String, PathBuf)],
883    active_repos: &HashSet<String>,
884) -> (Vec<(String, PathBuf)>, Vec<String>) {
885    let configured_repos: HashSet<&str> = configured.iter().map(|(r, _)| r.as_str()).collect();
886
887    let added = configured
888        .iter()
889        .filter(|(repo, _)| !active_repos.contains(repo))
890        .cloned()
891        .collect();
892    let removed = active_repos
893        .iter()
894        .filter(|repo| !configured_repos.contains(repo.as_str()))
895        .cloned()
896        .collect();
897
898    (added, removed)
899}
900
901/// Pick up projects added to `projects:` since startup, and report the ones
902/// that were removed.
903///
904/// A removed project keeps running until the next restart: its subscriber
905/// tasks and any agent it already dispatched outlive the config read
906#[expect(
907    clippy::too_many_arguments,
908    reason = "a new project engine needs every shared engine handle"
909)]
910async fn sync_project_engines(
911    project_engines: &mut Vec<ProjectEngine>,
912    active_repos: &mut HashSet<String>,
913    event_bus: &events::EventBus,
914    tmux: &Arc<TmuxManager>,
915    capture: &Arc<CaptureService>,
916    semaphore: &Arc<Semaphore>,
917    review_semaphore: &Arc<Semaphore>,
918    weight_tx: &mpsc::Sender<WeightSignal>,
919    router: &Arc<RwLock<Router>>,
920    dispatching: &Arc<dashmap::DashMap<String, String>>,
921) {
922    let configured = match config::get_projects_with_paths() {
923        Ok(p) if !p.is_empty() => p,
924        Ok(_) => return,
925        Err(e) => {
926            tracing::warn!(err = %e, "could not re-read the project list, keeping the current one");
927            return;
928        }
929    };
930    let Some(store) = project_engines.first().map(|e| Arc::clone(&e.store)) else {
931        return;
932    };
933
934    let (added, removed) = diff_configured_projects(&configured, active_repos);
935    for repo in removed {
936        tracing::info!(
937            repo = %repo,
938            "project removed from config, takes effect after restart"
939        );
940    }
941
942    for (repo, project_dir) in added {
943        config::watch(&project_dir.join(".orch.yml"));
944        let engine = match connect_project_engine(
945            repo.clone(),
946            project_dir,
947            Arc::clone(&store),
948            Some(event_bus.sender()),
949        )
950        .await
951        {
952            Ok(engine) => engine,
953            Err(e) => {
954                // A failed health check no longer lands here, so this is a backend that could
955                // not be built at all, such as a repo slug that is not `owner/name`
956                tracing::warn!(
957                    repo = %repo,
958                    err = %e,
959                    "project added to config but its backend could not be built, retrying on the next config change"
960                );
961                continue;
962            }
963        };
964
965        subscribers::dispatch::spawn(
966            event_bus.subscribe(),
967            Arc::clone(&engine.backend),
968            Arc::clone(tmux),
969            Arc::clone(&engine.runner),
970            Arc::clone(capture),
971            Arc::clone(semaphore),
972            Arc::clone(&engine.task_manager),
973            weight_tx.clone(),
974            Arc::clone(router),
975            Arc::clone(dispatching),
976            Arc::clone(&engine.store),
977            engine.repo.clone(),
978        );
979        subscribers::review::spawn(
980            event_bus.subscribe(),
981            Arc::clone(&engine.backend),
982            Arc::clone(tmux),
983            Arc::clone(review_semaphore),
984            Arc::clone(&engine.task_manager),
985            Arc::clone(router),
986            Arc::clone(dispatching),
987            Arc::clone(&engine.store),
988            engine.repo.clone(),
989        );
990        subscribers::unblock::spawn(
991            event_bus.subscribe(),
992            Arc::clone(&engine.backend),
993            Arc::clone(&engine.task_manager),
994            Arc::clone(&engine.store),
995            engine.repo.clone(),
996        );
997
998        active_repos.insert(repo.clone());
999        project_engines.push(engine);
1000        tracing::info!(repo = %repo, "project added from config, now syncing");
1001    }
1002}
1003
1004/// Initialize all project engines from config.
1005///
1006/// Returns a vector of ProjectEngine, one for each configured project.
1007async fn init_project_engines() -> anyhow::Result<Vec<ProjectEngine>> {
1008    let projects = config::get_projects_with_paths()?;
1009    let repos: Vec<&str> = projects.iter().map(|(r, _)| r.as_str()).collect();
1010    tracing::info!(repos = ?repos, "loading projects from config");
1011
1012    if projects.is_empty() {
1013        let config_path = home::config_path().map_or_else(
1014            |_| "~/.orch/config.yml".to_string(),
1015            |p| p.display().to_string(),
1016        );
1017        anyhow::bail!("no projects configured — add repos under `projects:` in {config_path}");
1018    }
1019
1020    let mut engines = Vec::new();
1021
1022    // Initialize unified task store once — all project engines share the same SQLite file.
1023    // Creating one pool here avoids N separate connection pools for the same database.
1024    let store = Arc::new(TaskStore::open(&store::default_db_path().await?).await?);
1025    if cluster::enabled() {
1026        cluster::start(&store, &home::orch_home()?.join("raft.db")).await?;
1027        local::serve((*store).clone()).await?;
1028    }
1029
1030    // Load persisted model cooldowns and register store for future writes.
1031    // Runs once here so the global cooldown store is not overwritten per project.
1032    engine_cooldown::init_cooldown_store(Arc::clone(&store)).await;
1033
1034    for (repo, project_dir) in projects {
1035        tracing::info!(repo = %repo, "initializing project engine");
1036        config::watch(&project_dir.join(".orch.yml"));
1037
1038        engines.push(connect_project_engine(repo, project_dir, Arc::clone(&store), None).await?);
1039    }
1040
1041    Ok(engines)
1042}
1043
1044async fn reconcile_startup_worktrees(project_engines: &[ProjectEngine]) -> anyhow::Result<()> {
1045    for engine in project_engines {
1046        let repo_root = worktree::resolve_main_repo(&engine.project_dir).await;
1047        let repo_root_path = PathBuf::from(&repo_root);
1048        let default_branch = worktree::detect_default_branch(&repo_root_path).await;
1049        let worktrees = list_project_worktrees(&repo_root_path).await?;
1050
1051        // Fetch refs once for all worktrees in this project, so rebase below
1052        // operates on up-to-date origin/* refs without N sequential fetches.
1053        if let Err(e) = git_ops::git()
1054            .await
1055            .args(["-C", &repo_root.to_string_lossy(), "fetch", "origin"])
1056            .output_with_context()
1057            .await
1058        {
1059            tracing::warn!(repo = %engine.repo, err = %e, "startup git fetch origin failed, rebases may use stale refs");
1060        }
1061
1062        let mut orphans_removed: u32 = 0;
1063        let mut invalid_removed: u32 = 0;
1064        let mut cleaned: u32 = 0;
1065        let mut valid_kept: u32 = 0;
1066
1067        for worktree_dir in worktrees {
1068            let Some(name) = worktree_dir.file_name().and_then(|n| n.to_str()) else {
1069                continue;
1070            };
1071
1072            // Validate gitdir link before doing anything else — a broken .git file
1073            // means git commands on this worktree will fail with "not a git repository".
1074            if !validate_worktree_gitdir(&worktree_dir).await {
1075                tracing::warn!(repo = %engine.repo, worktree = %worktree_dir.display(), "worktree has invalid or missing gitdir, removing");
1076                remove_worktree_and_branch(name, &worktree_dir, Some(name), &repo_root_path, false)
1077                    .await;
1078                invalid_removed += 1;
1079                continue;
1080            }
1081
1082            let Some(task_id) = task_id_from_worktree_name(name) else {
1083                tracing::info!(repo = %engine.repo, worktree = %worktree_dir.display(), "orphan worktree without task id, removing");
1084                remove_worktree_and_branch(name, &worktree_dir, Some(name), &repo_root_path, false)
1085                    .await;
1086                orphans_removed += 1;
1087                continue;
1088            };
1089
1090            let Some(store_id) = engine.store.resolve_task_id(&engine.repo, &task_id).await? else {
1091                tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), "worktree has no matching task, removing");
1092                remove_worktree_and_branch(
1093                    &task_id,
1094                    &worktree_dir,
1095                    Some(name),
1096                    &repo_root_path,
1097                    false,
1098                )
1099                .await;
1100                orphans_removed += 1;
1101                continue;
1102            };
1103
1104            let task = engine.store.get(store_id).await?;
1105            let branch_name = if task.branch.is_empty() {
1106                name
1107            } else {
1108                task.branch.as_str()
1109            };
1110
1111            match task.status {
1112                TaskStatus::New
1113                | TaskStatus::Routed
1114                | TaskStatus::InProgress
1115                | TaskStatus::NeedsReview
1116                | TaskStatus::InReview => {
1117                    tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), "rebasing startup worktree");
1118                    match rebase_worktree_on_origin_main(&worktree_dir, &default_branch).await {
1119                        Err(e) => {
1120                            // If rebase failed we already made efforts to stash and
1121                            // restore changes safely. Log the error and reset the
1122                            // task as before. The worktree removal path is used
1123                            // to avoid leaving corrupted worktrees around.
1124                            tracing::warn!(repo = %engine.repo, task_id = %task_id, err = %e, "startup rebase failed, resetting task");
1125                            abort_worktree_rebase(&worktree_dir).await;
1126                            let keep_remote = task.pr_number.is_some();
1127                            remove_worktree_and_branch(
1128                                &task_id,
1129                                &worktree_dir,
1130                                Some(branch_name),
1131                                &repo_root_path,
1132                                keep_remote,
1133                            )
1134                            .await;
1135                            match engine.store.resolve_task_id(&engine.repo, &task_id).await {
1136                                Ok(Some(reset_id)) => {
1137                                    if let Err(e) = engine.store.reset_to_new(reset_id).await {
1138                                        tracing::warn!(task_id, err = %e, "failed to reset task to new after rebase failure");
1139                                    }
1140                                }
1141                                Ok(None) => {
1142                                    tracing::warn!(
1143                                        task_id,
1144                                        "task not found in store during reconciliation"
1145                                    );
1146                                }
1147                                Err(e) => {
1148                                    tracing::warn!(task_id, err = %e, "failed to resolve task ID during reconciliation");
1149                                }
1150                            }
1151                            if let Err(e) = engine
1152                                .task_manager
1153                                .update_task_status(&ExternalId(task_id.clone()), Status::New)
1154                                .await
1155                            {
1156                                tracing::warn!(task_id, err = %e, "failed to update backend status during reconciliation");
1157                            }
1158                            cleaned += 1;
1159                        }
1160                        _ => {
1161                            valid_kept += 1;
1162                        }
1163                    }
1164                }
1165                // A blocked or waiting task resumes from this work, and without a PR the branch
1166                // may hold the only copy of it. An approved task's PR is updated on GitHub
1167                TaskStatus::Blocked | TaskStatus::Waiting | TaskStatus::Approved => {
1168                    valid_kept += 1;
1169                }
1170                TaskStatus::Done => {
1171                    tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), status = ?task.status, "terminal task worktree, removing");
1172                    remove_worktree_and_branch(
1173                        &task_id,
1174                        &worktree_dir,
1175                        Some(branch_name),
1176                        &repo_root_path,
1177                        false,
1178                    )
1179                    .await;
1180                    cleaned += 1;
1181                }
1182            }
1183        }
1184
1185        tracing::info!(
1186            repo = %engine.repo,
1187            orphans_removed,
1188            invalid_removed,
1189            cleaned,
1190            valid_kept,
1191            "worktree reconciliation: {orphans_removed} orphans removed, {invalid_removed} invalid removed, {cleaned} cleaned, {valid_kept} valid kept"
1192        );
1193
1194        // Prune stale .git/worktrees/ entries whose directories no longer exist.
1195        // This handles entries left behind by crashes or manual directory removal.
1196        let prune = Command::new("git")
1197            .args(["-C", &repo_root.to_string_lossy(), "worktree", "prune"])
1198            .output_with_context()
1199            .await;
1200        match prune {
1201            Ok(output) if output.status.success() => {
1202                tracing::debug!(repo = %engine.repo, "startup worktree prune completed");
1203            }
1204            Ok(output) => {
1205                let stderr = String::from_utf8_lossy(&output.stderr);
1206                tracing::warn!(repo = %engine.repo, err = %stderr, "startup worktree prune failed");
1207            }
1208            Err(e) => {
1209                tracing::warn!(repo = %engine.repo, err = %e, "startup worktree prune failed");
1210            }
1211        }
1212    }
1213
1214    Ok(())
1215}
1216
1217/// Sync Fibonacci estimates stored in SQLite to the GitHub Projects board for
1218/// all tasks that have a positive estimate.
1219///
1220/// Runs once on startup to catch tasks that were routed before the estimate
1221/// sync feature was available or before `project_estimate_field_id` was
1222/// configured. The underlying mutations are idempotent, so re-syncing an
1223/// already-correct estimate is harmless.
1224async fn reconcile_startup_estimates(project_engines: &[ProjectEngine]) {
1225    for engine in project_engines {
1226        let tasks = match engine.store.list_external_tasks_with_estimates().await {
1227            Ok(t) => t,
1228            Err(e) => {
1229                tracing::warn!(repo = %engine.repo, err = %e, "startup estimate reconciliation: store query failed");
1230                continue;
1231            }
1232        };
1233
1234        if tasks.is_empty() {
1235            continue;
1236        }
1237
1238        let mut synced: u32 = 0;
1239        let mut failed: u32 = 0;
1240        for (external_id, estimate) in &tasks {
1241            match engine
1242                .backend
1243                .sync_estimate_to_project(&ExternalId(external_id.clone()), *estimate)
1244                .await
1245            {
1246                Ok(()) => synced += 1,
1247                Err(e) => {
1248                    tracing::debug!(
1249                        repo = %engine.repo,
1250                        task_id = %external_id,
1251                        estimate,
1252                        err = %e,
1253                        "startup estimate reconciliation: sync failed"
1254                    );
1255                    failed += 1;
1256                }
1257            }
1258        }
1259
1260        if synced > 0 || failed > 0 {
1261            tracing::info!(
1262                repo = %engine.repo,
1263                synced,
1264                failed,
1265                "startup estimate reconciliation complete"
1266            );
1267        }
1268    }
1269}
1270
1271/// Read per-project channel configuration from `.orch.yml`.
1272fn read_project_channel_config(project_dir: &Path) -> ProjectChannelConfig {
1273    let config_path = project_dir.join(".orch.yml");
1274    if !config_path.exists() {
1275        return ProjectChannelConfig::default();
1276    }
1277    let content = match fs::read_to_string(&config_path) {
1278        Ok(c) => c,
1279        Err(e) => {
1280            tracing::warn!(
1281                path = %config_path.display(),
1282                error = %e,
1283                "failed to read .orch.yml; channel config will use defaults"
1284            );
1285            return ProjectChannelConfig::default();
1286        }
1287    };
1288    let val: serde_norway::Value = match serde_norway::from_str(&content) {
1289        Ok(v) => v,
1290        Err(e) => {
1291            tracing::warn!(
1292                path = %config_path.display(),
1293                error = %e,
1294                "failed to parse .orch.yml; channel config will use defaults"
1295            );
1296            return ProjectChannelConfig::default();
1297        }
1298    };
1299    let Some(channels) = val.get("channels") else {
1300        return ProjectChannelConfig::default();
1301    };
1302    let get_str = |section: &str, key: &str| -> Option<String> {
1303        channels
1304            .get(section)
1305            .and_then(|s| s.get(key))
1306            .and_then(|v| v.as_str())
1307            .map(String::from)
1308    };
1309    ProjectChannelConfig {
1310        telegram_topic_id: get_str("telegram", "topic_id"),
1311        discord_channel_id: get_str("discord", "channel_id"),
1312    }
1313}
1314
1315/// Fetch the latest orch release tag from GitHub via the `gh` CLI (async).
1316///
1317/// Returns the version string (without the leading "v"), or `None` when the
1318/// check fails (no network, unauthenticated, `gh` not installed, etc.).
1319async fn fetch_latest_release_version() -> Option<String> {
1320    let output = Command::new("gh")
1321        .args([
1322            "api",
1323            "repos/gabrielkoerich/orch/releases/latest",
1324            "--jq",
1325            ".tag_name",
1326        ])
1327        .output()
1328        .await
1329        .ok()?;
1330    if !output.status.success() {
1331        return None;
1332    }
1333    let tag = String::from_utf8(output.stdout).ok()?;
1334    let version = tag.trim().trim_start_matches('v').to_string();
1335    if version.is_empty() {
1336        None
1337    } else {
1338        Some(version)
1339    }
1340}
1341
1342/// Check if a newer orch release is available and send channel notifications
1343/// asking the operator to upgrade manually. Upgrading is operator-only — the
1344/// service never runs `brew` itself.
1345///
1346/// Uses the store's KV to throttle checks (`upgrade:last_check_at`) and
1347/// deduplicate notifications (`upgrade:last_notified_version`). Each distinct
1348/// latest version is notified about once; the notification repeats only when
1349/// an even newer version is released.
1350async fn check_and_notify_upgrade(
1351    store: &Arc<TaskStore>,
1352    channels: &Arc<ChannelRegistry>,
1353    current_version: &str,
1354    check_interval: Duration,
1355) {
1356    let last_check_key = "upgrade:last_check_at";
1357    let last_notified_key = "upgrade:last_notified_version";
1358
1359    // Throttle: only check once per interval.
1360    let now = chrono::Utc::now().timestamp();
1361    if let Ok(Some(last_check_str)) = store.kv_get(last_check_key).await
1362        && let Ok(last_check) = last_check_str.parse::<i64>()
1363        && now - last_check < i64::try_from(check_interval.as_secs()).unwrap_or(i64::MAX)
1364    {
1365        return;
1366    }
1367
1368    // Record check timestamp (best-effort).
1369    let _ = store.kv_set(last_check_key, &now.to_string()).await;
1370
1371    let Some(latest) = fetch_latest_release_version().await else {
1372        tracing::debug!("upgrade check: failed to fetch latest release version");
1373        return;
1374    };
1375
1376    if latest == current_version {
1377        tracing::debug!(current = %current_version, "orch is up to date");
1378        return;
1379    }
1380
1381    tracing::warn!(
1382        current_version = %current_version,
1383        latest_version = %latest,
1384        "orch upgrade available"
1385    );
1386
1387    // Operator-only upgrade: send channel notifications so the operator can
1388    // upgrade on their own schedule. The service never runs brew itself.
1389
1390    // Deduplicate: don't re-notify for the same latest version.
1391    if let Ok(Some(last_notified)) = store.kv_get(last_notified_key).await
1392        && last_notified == latest
1393    {
1394        tracing::debug!(latest = %latest, "upgrade already notified");
1395        return;
1396    }
1397
1398    let msg_telegram = format!(
1399        "⚠️ <b>Orch Upgrade Available</b>\n\n\
1400         Service: <code>{current_version}</code>\n\
1401         Latest:  <code>{latest}</code>\n\n\
1402         Run: <code>brew update && brew upgrade orch && brew services restart orch</code>"
1403    );
1404
1405    let msg_discord = format!(
1406        "⚠️ **Orch Upgrade Available**\n\n\
1407         Service: `{current_version}`\n\
1408         Latest:  `{latest}`\n\n\
1409         Run: `brew update && brew upgrade orch && brew services restart orch`"
1410    );
1411
1412    let msg_slack = format!(
1413        "⚠️ *Orch Upgrade Available*\n\n\
1414         Service: `{current_version}`\n\
1415         Latest:  `{latest}`\n\n\
1416         Run: `brew update && brew upgrade orch && brew services restart orch`"
1417    );
1418
1419    for channel in channels.iter() {
1420        let (body, metadata, topic_id) = match channel.name() {
1421            "telegram" => (
1422                msg_telegram.clone(),
1423                serde_json::json!({"preformatted_html": true}),
1424                None,
1425            ),
1426            "discord" => (msg_discord.clone(), serde_json::json!({}), None),
1427            "slack" => (msg_slack.clone(), serde_json::json!({}), None),
1428            _ => continue,
1429        };
1430
1431        let msg = OutgoingMessage {
1432            thread_id: "upgrade".to_string(),
1433            body,
1434            reply_to: None,
1435            metadata,
1436            topic_id,
1437        };
1438
1439        if let Err(e) = channel.send(&msg).await {
1440            tracing::warn!(
1441                channel = channel.name(),
1442                ?e,
1443                "failed to send upgrade notification"
1444            );
1445        }
1446    }
1447
1448    // Record that we notified for this latest version.
1449    let _ = store.kv_set(last_notified_key, &latest).await;
1450}
1451
1452/// Send a one-time escalation notification when the startup retry loop has been
1453/// spinning for longer than `startup_failure_escalation_secs`.
1454///
1455/// This is called *before* the channel registry is initialised (the retry loop
1456/// sits above it in `serve()`), so we construct channel objects directly from
1457/// config — mirroring the approach used during normal channel registration, but
1458/// without relying on `ChannelRegistry`.
1459async fn send_startup_escalation_notification(elapsed_secs: u64) {
1460    #[expect(clippy::cast_precision_loss, reason = "a display duration")]
1461    let duration = notification::format_duration(elapsed_secs as f64);
1462
1463    let msg_telegram = format!(
1464        "🚨 <b>Orch startup blocked — GitHub unreachable</b>\n\n\
1465         The engine has been retrying backend connections for {duration}\n\
1466         without success. All task processing, routing, and scheduled\n\
1467         jobs are paused. Check service logs with `orch log -f`."
1468    );
1469
1470    let msg_discord = format!(
1471        "🚨 **Orch startup blocked — GitHub unreachable**\n\n\
1472         The engine has been retrying backend connections for {duration}\n\
1473         without success. All task processing, routing, and scheduled\n\
1474         jobs are paused. Check service logs with `orch log -f`."
1475    );
1476
1477    let msg_slack = format!(
1478        "🚨 *Orch startup blocked — GitHub unreachable*\n\n\
1479         The engine has been retrying backend connections for {duration}\n\
1480         without success. All task processing, routing, and scheduled\n\
1481         jobs are paused. Check service logs with `orch log -f`."
1482    );
1483
1484    // Telegram
1485    let tg_token = secret_ref::config_secret("channels.telegram.bot_token").await;
1486    let tg_chat_id = config::get("channels.telegram.chat_id");
1487    if let (Ok(token), Ok(chat_id)) = (&tg_token, &tg_chat_id)
1488        && !token.is_empty()
1489        && !chat_id.is_empty()
1490        && let Ok(channel) = TelegramChannel::new(token.clone(), Some(chat_id.clone()))
1491    {
1492        let msg = OutgoingMessage {
1493            thread_id: "startup_escalation".to_string(),
1494            body: msg_telegram.clone(),
1495            reply_to: None,
1496            metadata: serde_json::json!({ "preformatted_html": true }),
1497            topic_id: config::get("channels.telegram.general_topic_id").ok(),
1498        };
1499        match channel.send(&msg).await {
1500            Err(e) => {
1501                tracing::warn!(?e, "failed to send startup escalation via telegram");
1502            }
1503            _ => {
1504                tracing::info!("startup escalation notification sent to telegram");
1505            }
1506        }
1507    }
1508
1509    // Discord
1510    if let Ok(token) = secret_ref::config_secret("channels.discord.bot_token").await {
1511        let channel_id = config::get("channels.discord.channel_id")
1512            .or_else(|_| config::get("channels.discord.general_channel_id"));
1513        if !token.is_empty()
1514            && let Some(cid) = channel_id.ok().filter(|s| !s.is_empty())
1515        {
1516            let shard_id = config::get("channels.discord.shard_id")
1517                .ok()
1518                .and_then(|v| v.parse::<u64>().ok())
1519                .unwrap_or(0);
1520            let shard_count = config::get("channels.discord.shard_count")
1521                .ok()
1522                .and_then(|v| v.parse::<u64>().ok())
1523                .unwrap_or(1);
1524            if let Ok(gateway) = DiscordGateway::new(token, Some(cid), shard_id, shard_count) {
1525                let msg = OutgoingMessage {
1526                    thread_id: "startup_escalation".to_string(),
1527                    body: msg_discord.clone(),
1528                    reply_to: None,
1529                    metadata: serde_json::Value::Null,
1530                    topic_id: None,
1531                };
1532                match gateway.send(&msg).await {
1533                    Err(e) => {
1534                        tracing::warn!(?e, "failed to send startup escalation via discord");
1535                    }
1536                    _ => {
1537                        tracing::info!("startup escalation notification sent to discord");
1538                    }
1539                }
1540            }
1541        }
1542    }
1543
1544    // Slack
1545    if let Ok(token) = secret_ref::config_secret("channels.slack.bot_token").await {
1546        let channel_id = config::get("channels.slack.channel_id");
1547        if !token.is_empty()
1548            && let Ok(cid) = channel_id
1549            && let Ok(channel) = SlackChannel::new(token, Some(cid))
1550        {
1551            let msg = OutgoingMessage {
1552                thread_id: "startup_escalation".to_string(),
1553                body: msg_slack.clone(),
1554                reply_to: None,
1555                metadata: serde_json::Value::Null,
1556                topic_id: None,
1557            };
1558            match channel.send(&msg).await {
1559                Err(e) => {
1560                    tracing::warn!(?e, "failed to send startup escalation via slack");
1561                }
1562                _ => {
1563                    tracing::info!("startup escalation notification sent to slack");
1564                }
1565            }
1566        }
1567    }
1568}
1569
1570/// Start the orch service.
1571///
1572/// This is the main entry point — called by `orch serve`.
1573pub async fn serve() -> anyhow::Result<()> {
1574    let killed = home::kill_other_orch_serve_processes(Duration::from_secs(30));
1575    if killed > 0 {
1576        tracing::info!(count = killed, "terminated stale orch serve processes");
1577    }
1578
1579    tracing::info!("orch engine starting");
1580
1581    // Pre-create standard directories with async I/O so subsequent synchronous
1582    // callers (state_dir, orch_home, etc.) find them already present and their
1583    // create_dir_all calls become fast no-ops.
1584    if let Err(e) = home::init_dirs().await {
1585        tracing::warn!("failed to initialize orch directories: {e}");
1586    }
1587
1588    // Pre-warm the config cache with async I/O so get() / get_list() calls in
1589    // hot async paths never block a Tokio thread on std::fs::read_to_string.
1590    if let Err(e) = config::warm_cache().await {
1591        tracing::warn!("failed to warm config cache: {e}");
1592    }
1593
1594    let mut config = EngineConfig::from_config();
1595
1596    tracing::info!("internal database ready");
1597
1598    // Initialize project engines — retry with backoff so a network outage at
1599    // startup doesn't cause a crash-loop (launchd KeepAlive would restart us
1600    // immediately, filling the error log with 600+ identical messages).
1601    //
1602    // IMPORTANT: errors from init_project_engines() must NEVER propagate past
1603    // this loop to main().  If they did, anyhow would write "Error: …" to stderr,
1604    // which brew routes to orch.error.log — polluting it even when projects ARE
1605    // configured correctly but GitHub is temporarily unreachable.
1606    let startup_escalation_secs = config.startup_failure_escalation_secs;
1607    let mut project_engines = {
1608        let mut delay_secs = 5u64;
1609        let mut attempt = 0u32;
1610        let mut escalated = false;
1611        let start = Instant::now();
1612        loop {
1613            attempt += 1;
1614            match init_project_engines().await {
1615                Ok(engines) => break engines,
1616                Err(e) => {
1617                    let elapsed = start.elapsed().as_secs();
1618
1619                    // Short blips (under the escalation threshold) stay at WARN
1620                    // so they don't flood the operator's attention. Once the
1621                    // outage crosses the threshold, escalate to ERROR-level
1622                    // logging and send a one-time push notification to configured
1623                    // channels — "transient" has clearly become "prolonged."
1624                    if startup_escalation_secs > 0
1625                        && !escalated
1626                        && elapsed >= startup_escalation_secs
1627                    {
1628                        escalated = true;
1629                        #[expect(clippy::cast_precision_loss, reason = "a display duration")]
1630                        let outage = notification::format_duration(elapsed as f64);
1631                        tracing::error!(
1632                            delay_secs,
1633                            attempt,
1634                            elapsed_secs = elapsed,
1635                            threshold_secs = startup_escalation_secs,
1636                            "project backends unavailable for {outage} — escalating startup failure: {e}",
1637                        );
1638                        // Send one-time notification to configured channels.
1639                        // Channels aren't registered yet at this stage, so we
1640                        // construct them directly from config (mirrors orch notify).
1641                        send_startup_escalation_notification(elapsed).await;
1642                    } else {
1643                        tracing::warn!(
1644                            delay_secs,
1645                            attempt,
1646                            "project backends unavailable, retrying: {e}"
1647                        );
1648                    }
1649
1650                    time::sleep(Duration::from_secs(delay_secs)).await;
1651                    delay_secs = (delay_secs * 2).min(120);
1652                }
1653            }
1654        }
1655    };
1656
1657    tracing::info!(
1658        project_count = project_engines.len(),
1659        "initialized project engines"
1660    );
1661
1662    // Full set of currently-configured project repos, used by the per-tick global
1663    // sweeps (e.g. `dispatch_routed_tasks_global`) to distinguish "orphaned" tasks
1664    // (repo no longer in config) from tasks belonging to some other active project.
1665    let mut active_repos: HashSet<String> =
1666        project_engines.iter().map(|e| e.repo.clone()).collect();
1667
1668    // Create the event bus for task status transitions
1669    let event_bus = events::EventBus::new(256);
1670    if let Err(e) = event_bus.start_ws_server().await {
1671        tracing::warn!(
1672            ?e,
1673            "failed to start event websocket server, continuing without it"
1674        );
1675    }
1676
1677    // Check for a newer orch release in the background and log if the service is behind.
1678    // The periodic checker sends channel notifications after channels are initialized;
1679    // upgrading is operator-only and never runs automatically.
1680    {
1681        let current = env!("ORCH_VERSION").to_string();
1682        tokio::spawn(async move {
1683            if let Some(latest) = fetch_latest_release_version().await
1684                && latest != current
1685            {
1686                tracing::warn!(
1687                    current_version = %current,
1688                    latest_version = %latest,
1689                    "orch service is behind the latest release — run: brew update && brew upgrade orch && brew services restart orch"
1690                );
1691            }
1692        });
1693    }
1694
1695    // Re-create task managers with shared store and event bus
1696    for engine in &mut project_engines {
1697        engine.task_manager = Arc::new(TaskManager::with_events(
1698            Arc::clone(&engine.backend),
1699            Arc::clone(&engine.store),
1700            engine.repo.clone(),
1701            event_bus.sender(),
1702        ));
1703    }
1704
1705    // Startup reconciliation decides task status, so only the leader runs it
1706    let leads = project_engines.first().is_none_or(|e| e.store.is_leader());
1707    if leads && let Err(e) = reconcile_startup_worktrees(&project_engines).await {
1708        tracing::warn!(err = %e, "startup worktree reconciliation failed");
1709    }
1710
1711    if leads {
1712        // Run estimate reconciliation in the background so it never blocks startup.
1713        // Each GraphQL mutation takes ~0.8 s; with hundreds of tasks this would
1714        // otherwise delay the engine reaching its main loop by several minutes.
1715        let engines_snapshot: Vec<ProjectEngine> = project_engines.clone();
1716        tokio::spawn(async move {
1717            reconcile_startup_estimates(&engines_snapshot).await;
1718        });
1719    }
1720
1721    // Build ChannelRouter from global config + per-project configs
1722    let global_channel_config = GlobalChannelConfig {
1723        telegram_general_topic_id: config::get("channels.telegram.general_topic_id").ok(),
1724        discord_general_channel_id: config::get("channels.discord.general_channel_id").ok(),
1725        control_telegram_topic_id: config::get("control.channels.telegram.topic_id").ok(),
1726        control_discord_channel_id: config::get("control.channels.discord.channel_id").ok(),
1727    };
1728    let project_channel_configs: Vec<(String, ProjectChannelConfig)> = project_engines
1729        .iter()
1730        .map(|e| {
1731            let cfg = read_project_channel_config(&e.project_dir);
1732            (e.repo.clone(), cfg)
1733        })
1734        .collect();
1735    let channel_router = Arc::new(ChannelRouter::new(
1736        &global_channel_config,
1737        &project_channel_configs,
1738    ));
1739    tracing::info!(
1740        projects = ?channel_router.projects(),
1741        "channel router initialized"
1742    );
1743
1744    // Initialize tmux manager (shared across all projects)
1745    let tmux = Arc::new(TmuxManager::new());
1746    // Kill leftover sessions from a previous process. This is daemon start only,
1747    // never a tick, because nextest makes a once-flag in tick_all kill live agents
1748    tick::startup_cleanup(&tmux).await;
1749
1750    // Initialize transport
1751    let transport = Arc::new(Transport::new());
1752
1753    // Initialize capture service and start background loop
1754    let capture = Arc::new(CaptureService::new(Arc::clone(&transport)));
1755    let capture_for_tick = Arc::clone(&capture);
1756    tokio::spawn(async move {
1757        capture.start().await;
1758    });
1759
1760    // Initialize channel registry
1761    let mut channel_registry = ChannelRegistry::new();
1762
1763    // Try to initialize Telegram channel
1764    if let Ok(token) = secret_ref::config_secret("channels.telegram.bot_token").await
1765        && !token.is_empty()
1766    {
1767        let chat_id = config::get("channels.telegram.chat_id").ok();
1768        match TelegramChannel::new(token, chat_id) {
1769            Ok(telegram) => {
1770                if let Err(e) = telegram.health_check().await {
1771                    tracing::warn!(?e, "telegram channel health check failed, skipping");
1772                } else {
1773                    channel_registry.register(Box::new(telegram));
1774                    tracing::info!("telegram channel registered");
1775                }
1776            }
1777            Err(e) => {
1778                tracing::warn!(?e, "failed to create telegram channel, skipping");
1779            }
1780        }
1781    }
1782
1783    // Try to initialize Discord Gateway channel (websocket)
1784    if let Ok(token) = secret_ref::config_secret("channels.discord.bot_token").await
1785        && !token.is_empty()
1786    {
1787        let channel_id = config::get("channels.discord.channel_id").ok();
1788        let shard_id = config::get("channels.discord.shard_id")
1789            .ok()
1790            .and_then(|v| v.parse::<u64>().ok())
1791            .unwrap_or(0);
1792        let shard_count = config::get("channels.discord.shard_count")
1793            .ok()
1794            .and_then(|v| v.parse::<u64>().ok())
1795            .unwrap_or(1);
1796        match DiscordGateway::new(token, channel_id, shard_id, shard_count) {
1797            Ok(discord) => {
1798                if let Err(e) = discord.health_check().await {
1799                    tracing::warn!(?e, "discord gateway health check failed, skipping");
1800                } else {
1801                    channel_registry.register(Box::new(discord));
1802                    tracing::info!(shard_id, shard_count, "discord gateway registered");
1803                }
1804            }
1805            Err(e) => {
1806                tracing::warn!(?e, "failed to create discord gateway, skipping");
1807            }
1808        }
1809    }
1810
1811    // Try to initialize Slack channel
1812    if let Ok(token) = secret_ref::config_secret("channels.slack.bot_token").await
1813        && !token.is_empty()
1814    {
1815        let channel_id = config::get("channels.slack.channel_id").ok();
1816        match SlackChannel::new(token, channel_id) {
1817            Ok(slack) => {
1818                if let Err(e) = slack.health_check().await {
1819                    tracing::warn!(?e, "slack channel health check failed, skipping");
1820                } else {
1821                    channel_registry.register(Box::new(slack));
1822                    tracing::info!("slack channel registered");
1823                }
1824            }
1825            Err(e) => {
1826                tracing::warn!(?e, "failed to create slack channel, skipping");
1827            }
1828        }
1829    }
1830
1831    // Initialize tmux channel with transport for output streaming
1832    let tmux_channel = TmuxChannel::with_transport(Arc::clone(&transport));
1833    channel_registry.register(Box::new(tmux_channel));
1834    tracing::info!("tmux channel registered");
1835
1836    // Start all channels and collect their message receivers
1837    let mut channel_receivers: Vec<Receiver<IncomingMessage>> = Vec::new();
1838    for channel in channel_registry.iter() {
1839        match channel.start().await {
1840            Ok(rx) => {
1841                tracing::info!(channel = channel.name(), "channel started");
1842                channel_receivers.push(rx);
1843            }
1844            Err(e) => {
1845                tracing::warn!(channel = channel.name(), ?e, "failed to start channel");
1846            }
1847        }
1848    }
1849
1850    // Wrap channel registry in Arc for shared access (notification dispatcher needs it)
1851    let channel_registry = Arc::new(channel_registry);
1852
1853    // Spawn tasks to handle incoming channel messages (if any channels are active)
1854    let transport_for_messages = Arc::clone(&transport);
1855    let tmux_for_messages = Arc::clone(&tmux);
1856    let capture_for_messages = Arc::clone(&capture_for_tick);
1857    let channels_for_messages = Arc::clone(&channel_registry);
1858    // Lightweight engine references for command execution and task creation
1859    let engine_refs: Vec<EngineRef> = project_engines
1860        .iter()
1861        .map(|e| {
1862            (
1863                e.repo.clone(),
1864                Arc::clone(&e.backend),
1865                Arc::clone(&e.task_manager),
1866                Some(Arc::clone(&e.store)),
1867            )
1868        })
1869        .collect();
1870    // Shared in-memory map for pending project picks (General channel multi-project picker).
1871    let pending_picks: channel_handler::PendingPicks = Arc::new(Mutex::new(HashMap::new()));
1872    let router_for_messages = Arc::clone(&channel_router);
1873    for mut rx in channel_receivers {
1874        let transport = Arc::clone(&transport_for_messages);
1875        let tmux = Arc::clone(&tmux_for_messages);
1876        let capture = Arc::clone(&capture_for_messages);
1877        let channels = Arc::clone(&channels_for_messages);
1878        let engine_refs = engine_refs.clone();
1879        let ch_router = Arc::clone(&router_for_messages);
1880        let picks = Arc::clone(&pending_picks);
1881        tokio::spawn(async move {
1882            while let Some(msg) = rx.recv().await {
1883                tracing::debug!(channel = %msg.channel, thread = %msg.thread_id, "received message from channel");
1884                channel_handler::handle_channel_message(
1885                    msg,
1886                    &transport,
1887                    &tmux,
1888                    &capture,
1889                    &channels,
1890                    &engine_refs,
1891                    &ch_router,
1892                    &picks,
1893                )
1894                .await;
1895            }
1896        });
1897    }
1898
1899    // Post-restart confirmation: if the service was restarted via the /restart control command,
1900    // a KV marker was stored before shutdown. Send a confirmation to the originating channel now
1901    // that we're back online. Use a short delay to let the channel connections re-establish.
1902    {
1903        let restart_channels = Arc::clone(&channel_registry);
1904        let restart_store = project_engines.first().map(|e| Arc::clone(&e.store));
1905        if let Some(store) = restart_store {
1906            tokio::spawn(async move {
1907                time::sleep(Duration::from_secs(5)).await;
1908                match store.kv_get("control:restart_pending").await {
1909                    Ok(Some(conv_key)) => {
1910                        if let Some((ch_name, thread_id, topic_id)) =
1911                            transport::parse_conversation_key(&conv_key)
1912                        {
1913                            for ch in restart_channels.iter() {
1914                                if ch.name() == ch_name {
1915                                    let msg = OutgoingMessage {
1916                                        thread_id: thread_id.to_string(),
1917                                        body: "orch restarted successfully.".to_string(),
1918                                        reply_to: None,
1919                                        metadata: serde_json::json!({}),
1920                                        topic_id: topic_id.map(ToString::to_string),
1921                                    };
1922                                    if let Err(e) = ch.send(&msg).await {
1923                                        tracing::warn!(
1924                                            channel = ch_name,
1925                                            error = %e,
1926                                            "failed to send restart confirmation"
1927                                        );
1928                                    }
1929                                    break;
1930                                }
1931                            }
1932                        }
1933                        if let Err(e) = store.kv_delete("control:restart_pending").await {
1934                            tracing::warn!(error = %e, "failed to clear control:restart_pending");
1935                        }
1936                    }
1937                    Ok(None) => {} // no pending restart, nothing to do
1938                    Err(e) => {
1939                        tracing::warn!(error = %e, "failed to read control:restart_pending");
1940                    }
1941                }
1942            });
1943        }
1944    }
1945
1946    // Spawn notification dispatcher — reads task completion notifications
1947    // from transport and broadcasts to configured channels.
1948    //
1949    // Routing priority:
1950    // 1. Dedicated channel: if the notification has a `repo` and the
1951    //    ChannelRouter maps it to a topic/channel, send there with `topic_id`.
1952    // 2. Subscribed channels: send to each (channel, thread_id) subscribed to
1953    //    the repo, using `format_with_project()` so recipients know the source.
1954    // 3. Fallback: if no repo or no dedicated channel, broadcast to all
1955    //    channels without a topic_id (legacy behaviour).
1956    {
1957        let mut notification_rx = transport.subscribe_notifications();
1958        let channels = Arc::clone(&channel_registry);
1959        let notif_router = Arc::clone(&channel_router);
1960        // Grab a store reference for subscription lookups.
1961        let notif_store: Option<Arc<TaskStore>> =
1962            project_engines.first().map(|e| Arc::clone(&e.store));
1963        tokio::spawn(async move {
1964            loop {
1965                match notification_rx.recv().await {
1966                    Ok(notification) => {
1967                        let level = NotificationLevel::from_config();
1968                        if !level.should_notify(&notification.status) {
1969                            tracing::debug!(
1970                                task_id = %notification.task_id,
1971                                status = %notification.status,
1972                                "notification suppressed by level={:?}",
1973                                level
1974                            );
1975                            continue;
1976                        }
1977
1978                        tracing::info!(
1979                            task_id = %notification.task_id,
1980                            status = %notification.status,
1981                            repo = ?notification.repo,
1982                            "routing notification to channels"
1983                        );
1984
1985                        // Track whether we sent to at least one dedicated/subscribed target.
1986                        let mut routed = false;
1987
1988                        // 0. Direct target: if notify_target is set, send straight to
1989                        //    that Telegram chat_id and skip all other routing.
1990                        if let Some(ref target) = notification.notify_target {
1991                            let telegram = channels.iter().find(|c| c.name() == "telegram");
1992                            if let Some(channel) = telegram {
1993                                let body = notification.format_telegram();
1994                                let metadata = serde_json::json!({
1995                                    "preformatted_html": true,
1996                                    "chat_id_override": target
1997                                });
1998                                let msg = OutgoingMessage {
1999                                    thread_id: notification.task_id.clone(),
2000                                    body,
2001                                    reply_to: None,
2002                                    metadata,
2003                                    topic_id: None,
2004                                };
2005                                match channel.send(&msg).await {
2006                                    Err(e) => {
2007                                        tracing::warn!(
2008                                            task_id = %notification.task_id,
2009                                            target,
2010                                            ?e,
2011                                            "failed to send to notify_target"
2012                                        );
2013                                    }
2014                                    _ => {
2015                                        routed = true;
2016                                    }
2017                                }
2018                            }
2019                        }
2020
2021                        if routed {
2022                            // notify_target handled — skip further routing
2023                        } else if let Some(repo) = notification.repo.as_deref() {
2024                            // Track destinations already sent to in this iteration so
2025                            // the dedicated (path 1) and subscribed (path 2) loops
2026                            // don't double-fire the same Telegram/Discord destination
2027                            // when a repo's configured topic and a `channel_subscriptions`
2028                            // row resolve to the same `(channel, topic_id)`.
2029                            let mut sent: HashSet<(String, Option<String>)> = HashSet::new();
2030
2031                            // 1. Dedicated channel targets for this repo.
2032                            for channel in channels.iter() {
2033                                let ch_name = channel.name();
2034                                if let Some(topic_id) =
2035                                    notif_router.target_for_project(repo, ch_name)
2036                                {
2037                                    let body = match ch_name {
2038                                        "telegram" => notification.format_telegram(),
2039                                        "discord" => notification.format_discord(),
2040                                        "slack" => notification.format_slack(),
2041                                        _ => continue,
2042                                    };
2043                                    let metadata = if ch_name == "telegram" {
2044                                        serde_json::json!({"preformatted_html": true})
2045                                    } else {
2046                                        serde_json::json!({})
2047                                    };
2048                                    let resolved_topic = Some(topic_id.to_string());
2049                                    let msg = OutgoingMessage {
2050                                        thread_id: notification.task_id.clone(),
2051                                        body,
2052                                        reply_to: None,
2053                                        metadata,
2054                                        topic_id: resolved_topic.clone(),
2055                                    };
2056                                    if let Err(e) = channel.send(&msg).await {
2057                                        tracing::warn!(
2058                                            channel = ch_name,
2059                                            task_id = %notification.task_id,
2060                                            ?e,
2061                                            "failed to send to dedicated channel"
2062                                        );
2063                                    } else {
2064                                        sent.insert((ch_name.to_string(), resolved_topic));
2065                                        routed = true;
2066                                    }
2067                                }
2068                            }
2069
2070                            // 2. Subscribed channels for this repo.
2071                            if let Some(store) = &notif_store {
2072                                match store.list_subscribers_for_repo(repo).await {
2073                                    Ok(subscribers) => {
2074                                        for (ch_name, thread_id, topic_id) in subscribers {
2075                                            let channel =
2076                                                channels.iter().find(|c| c.name() == ch_name);
2077                                            let Some(channel) = channel else {
2078                                                continue;
2079                                            };
2080                                            let resolved_topic = if topic_id.is_empty() {
2081                                                None
2082                                            } else {
2083                                                Some(topic_id.clone())
2084                                            };
2085                                            // Skip if a dedicated send to the same
2086                                            // (channel, topic_id) already happened.
2087                                            if sent.contains(&(
2088                                                ch_name.clone(),
2089                                                resolved_topic.clone(),
2090                                            )) {
2091                                                tracing::debug!(
2092                                                    channel = %ch_name,
2093                                                    task_id = %notification.task_id,
2094                                                    topic_id = ?resolved_topic,
2095                                                    "skipping duplicate subscriber dispatch — destination already received from dedicated path"
2096                                                );
2097                                                continue;
2098                                            }
2099                                            let body = notification.format_with_project(&ch_name);
2100                                            let metadata = if ch_name == "telegram" {
2101                                                serde_json::json!({"preformatted_html": true})
2102                                            } else {
2103                                                serde_json::json!({})
2104                                            };
2105                                            let msg = OutgoingMessage {
2106                                                thread_id: thread_id.clone(),
2107                                                body,
2108                                                reply_to: None,
2109                                                metadata,
2110                                                topic_id: resolved_topic.clone(),
2111                                            };
2112                                            if let Err(e) = channel.send(&msg).await {
2113                                                tracing::warn!(
2114                                                    channel = %ch_name,
2115                                                    task_id = %notification.task_id,
2116                                                    ?e,
2117                                                    "failed to send to subscribed channel"
2118                                                );
2119                                            } else {
2120                                                sent.insert((ch_name.clone(), resolved_topic));
2121                                                routed = true;
2122                                            }
2123                                        }
2124                                    }
2125                                    Err(e) => {
2126                                        tracing::warn!(
2127                                            repo,
2128                                            ?e,
2129                                            "failed to list subscribers for repo"
2130                                        );
2131                                    }
2132                                }
2133                            }
2134                        }
2135
2136                        // 3. Fallback: broadcast to all channels when no routing happened.
2137                        if !routed {
2138                            for channel in channels.iter() {
2139                                let (body, should_send, is_telegram) = match channel.name() {
2140                                    "telegram" => (notification.format_telegram(), true, true),
2141                                    "discord" => (notification.format_discord(), true, false),
2142                                    "slack" => (notification.format_slack(), true, false),
2143                                    // GitHub is already handled by backend.post_comment()
2144                                    // tmux doesn't need task completion notifications
2145                                    _ => (String::new(), false, false),
2146                                };
2147
2148                                if !should_send {
2149                                    continue;
2150                                }
2151
2152                                let metadata = if is_telegram {
2153                                    serde_json::json!({"preformatted_html": true})
2154                                } else {
2155                                    serde_json::json!({})
2156                                };
2157                                let msg = OutgoingMessage {
2158                                    thread_id: notification.task_id.clone(),
2159                                    body,
2160                                    reply_to: None,
2161                                    metadata,
2162                                    topic_id: None,
2163                                };
2164
2165                                if let Err(e) = channel.send(&msg).await {
2166                                    tracing::warn!(
2167                                        channel = channel.name(),
2168                                        task_id = %notification.task_id,
2169                                        ?e,
2170                                        "failed to send notification"
2171                                    );
2172                                }
2173                            }
2174                        }
2175                    }
2176                    Err(RecvError::Lagged(n)) => {
2177                        tracing::warn!(missed = n, "notification receiver lagged");
2178                    }
2179                    Err(RecvError::Closed) => {
2180                        tracing::debug!("notification channel closed");
2181                        break;
2182                    }
2183                }
2184            }
2185        });
2186        tracing::info!("notification dispatcher started");
2187    }
2188
2189    // Notify used by webhook events to wake up the engine tick immediately
2190    let webhook_notify = Arc::new(Notify::new());
2191
2192    // `WebhookStatus::fallback_mode` is only shown by `orch webhook status`, the sync
2193    // tick always runs every `engine.sync_interval` whether or not webhooks work
2194    let webhook_port: Option<u16>;
2195    let mut webhook_healthy: bool;
2196    let mut last_webhook_health_check = Instant::now();
2197    // Start webhook server if configured
2198    let webhook_enabled = config::get_global("webhook.enabled").is_ok_and(|v| v == "true");
2199    // No readable secret keeps the webhook server off, it never accepts unsigned requests
2200    let webhook_secret = if webhook_enabled {
2201        secret_ref::config_secret("webhook.secret")
2202            .await
2203            .ok()
2204            .filter(|s| !s.trim().is_empty())
2205    } else {
2206        None
2207    };
2208    if webhook_enabled && webhook_secret.is_none() {
2209        tracing::error!(
2210            "webhook.enabled needs a readable webhook.secret, the webhook server stays off"
2211        );
2212    }
2213    let webhook_enabled = webhook_enabled && webhook_secret.is_some();
2214    let webhook_secret = webhook_secret.unwrap_or_default();
2215
2216    // Shared status updated by the server-spawn task and the health-check loop.
2217    let webhook_status = Arc::new(Mutex::new(WebhookStatus::default()));
2218
2219    if webhook_enabled {
2220        // Spawn the HTTP server with exponential-backoff retry on transient
2221        // bind errors (e.g. EADDRINUSE).  After MAX_ATTEMPTS the engine falls
2222        // back to polling and updates the shared status accordingly.
2223        const WEBHOOK_MAX_ATTEMPTS: u32 = 5;
2224        let port: u16 = config::get("webhook.port")
2225            .ok()
2226            .and_then(|v| v.parse().ok())
2227            .unwrap_or(8080);
2228        webhook_port = Some(port);
2229        let secret = webhook_secret.clone();
2230        let webhook_repo = project_engines
2231            .first()
2232            .map(|e| e.repo.clone())
2233            .unwrap_or_default();
2234
2235        let (tx, mut rx) = mpsc::channel::<IncomingMessage>(64);
2236
2237        // Initialise status: configured, not yet healthy.
2238        let to_save = {
2239            let mut s = webhook_status.lock().await;
2240            s.configured = true;
2241            s.port = Some(port);
2242            s.healthy = false;
2243            s.fallback_mode = false;
2244            s.clone()
2245        };
2246        to_save.save().await;
2247
2248        let status_for_spawn = Arc::clone(&webhook_status);
2249        tokio::spawn(async move {
2250            let mut attempt = 0u32;
2251            loop {
2252                attempt += 1;
2253                tracing::info!(attempt, port, "attempting to start webhook server");
2254                match start_webhook_server(port, secret.clone(), webhook_repo.clone(), tx.clone())
2255                    .await
2256                {
2257                    Ok(()) => {
2258                        tracing::info!(attempt, "webhook server exited cleanly");
2259                        break;
2260                    }
2261                    Err(e) => {
2262                        let reason = e.to_string();
2263                        tracing::error!(attempt, %reason, "webhook server failed");
2264                        if attempt >= WEBHOOK_MAX_ATTEMPTS || !is_transient_bind_error(&e) {
2265                            let kind = if attempt >= WEBHOOK_MAX_ATTEMPTS {
2266                                "max attempts reached"
2267                            } else {
2268                                "non-transient error"
2269                            };
2270                            tracing::error!(
2271                                attempt,
2272                                %reason,
2273                                kind,
2274                                orch_webhook_in_fallback = true,
2275                                "webhook server giving up, switching to polling fallback"
2276                            );
2277                            let to_save = {
2278                                let mut s = status_for_spawn.lock().await;
2279                                s.fallback_mode = true;
2280                                s.healthy = false;
2281                                s.last_failure_reason = Some(reason);
2282                                s.startup_attempts = attempt;
2283                                s.clone()
2284                            };
2285                            to_save.save().await;
2286                            break;
2287                        }
2288                        let delay = webhook_backoff_delay(attempt);
2289                        tracing::warn!(
2290                            attempt,
2291                            delay_ms = delay.as_millis(),
2292                            %reason,
2293                            "webhook bind failed (transient), retrying with backoff"
2294                        );
2295                        {
2296                            let to_save = {
2297                                let mut s = status_for_spawn.lock().await;
2298                                s.startup_attempts = attempt;
2299                                s.last_failure_reason = Some(reason);
2300                                s.clone()
2301                            };
2302                            to_save.save().await;
2303                        }
2304                        time::sleep(delay).await;
2305                    }
2306                }
2307            }
2308        });
2309
2310        // Spawn the message forwarding task (reads from webhook channel)
2311        let notify = Arc::clone(&webhook_notify);
2312        let transport_for_webhook = Arc::clone(&transport);
2313        tokio::spawn(async move {
2314            while let Some(msg) = rx.recv().await {
2315                tracing::info!(
2316                    channel = %msg.channel,
2317                    thread = %msg.thread_id,
2318                    event = %msg.metadata.get("event").and_then(|v| v.as_str()).unwrap_or("unknown"),
2319                    action = %msg.metadata.get("action").and_then(|v| v.as_str()).unwrap_or("unknown"),
2320                    "webhook event received, triggering immediate tick"
2321                );
2322                let route = transport_for_webhook.route(&msg).await;
2323                tracing::info!(
2324                    channel = %msg.channel,
2325                    route = ?route,
2326                    "webhook event routed"
2327                );
2328                // Wake up the engine tick immediately instead of waiting up to 10s
2329                notify.notify_one();
2330            }
2331        });
2332
2333        webhook_healthy = true;
2334        tracing::info!(port, orch_webhook_up = true, "webhook server started");
2335    } else {
2336        webhook_port = None;
2337        webhook_healthy = false;
2338        {
2339            let to_save = {
2340                let mut s = webhook_status.lock().await;
2341                s.configured = false;
2342                s.fallback_mode = true;
2343                s.clone()
2344            };
2345            to_save.save().await;
2346        }
2347        tracing::info!(
2348            orch_webhook_in_fallback = true,
2349            "webhook server disabled, using polling fallback mode"
2350        );
2351    }
2352
2353    start_relay_client(&project_engines, &webhook_notify);
2354    app::start_loader();
2355
2356    // Agent router (selects agent + model per task) - shared across projects.
2357    // Router::from_config() may run `opencode models` when the config uses opencode.
2358    // spawn_blocking keeps the Tokio runtime thread free during that I/O
2359    let router = Arc::new(RwLock::new(
2360        match task::spawn_blocking(Router::from_config).await {
2361            Ok(r) => r,
2362            Err(e) => {
2363                tracing::error!(?e, "router init panicked in spawn_blocking, using default");
2364                task::spawn_blocking(|| Router::new(RouterConfig::default()))
2365                    .await
2366                    .unwrap_or_else(|e2| {
2367                        panic!("router default init also panicked in spawn_blocking — cannot start engine without a router: {e2:?}");
2368                    })
2369            }
2370        },
2371    ));
2372    {
2373        let r = router.read().await;
2374        tracing::info!(
2375            mode = %r.config.mode,
2376            agents = ?r.available_agents,
2377            fallback = %r.config.fallback_executor,
2378            "router initialized"
2379        );
2380    }
2381
2382    // Concurrency limiter (shared across all projects). `parallel_in_force` is the
2383    // limit actually handed out, which lags `config.max_parallel` after a shrink
2384    // until the running tasks give their permits back.
2385    let semaphore = Arc::new(Semaphore::new(config.max_parallel));
2386    let mut parallel_in_force = config.max_parallel;
2387    // Reviews get their own pool, one reviewer per worker, so a busy worker pool never
2388    // starves a review (#3971)
2389    let review_semaphore = Arc::new(Semaphore::new(config.max_parallel));
2390    let mut review_in_force = config.max_parallel;
2391
2392    // In-memory dispatch guard: tracks task IDs currently being dispatched.
2393    // Guards against GitHub API eventual consistency — after update_status(InProgress),
2394    // the label-removal webhook can trigger an immediate tick where list_by_status(Routed)
2395    // still returns the task (search index propagation delay). The tmux session does not
2396    // exist until the runner completes worktree setup (~10s later), so session_exists
2397    // alone is insufficient. Keyed by "{repo}/{task_id}".
2398    let dispatching: Arc<dashmap::DashMap<String, String>> = Arc::new(dashmap::DashMap::new());
2399
2400    // In-memory guard to prevent double-spawn of auto-merge background tasks.
2401    // Since review_open_prs runs every sync_tick (~10s) but CI polling can take
2402    // up to 10 minutes, we track which tasks already have an auto-merge in flight.
2403    let auto_merge_in_flight: Arc<dashmap::DashSet<String>> = Arc::new(dashmap::DashSet::new());
2404
2405    // Subscribe to config file changes for hot reload
2406    let mut config_rx = config::subscribe();
2407
2408    // Track sync interval
2409    let mut last_sync = Instant::now();
2410
2411    // Track upgrade check interval
2412    let mut last_upgrade_check: Option<Instant> = None;
2413
2414    // Reset epoch of the GitHub rate-limit window already reported, so the log line,
2415    // the KV flag and the channel notification fire once per window instead of per tick
2416    let mut rate_limit_reported: Option<i64> = None;
2417
2418    // Channel for weight signals from task runners back to the router
2419    let (weight_tx, mut weight_rx) = mpsc::channel::<WeightSignal>(64);
2420
2421    // A restart ends every review session, so reset each in_review task left without one
2422    for engine in project_engines.iter().filter(|_| leads) {
2423        let reset =
2424            reset_orphaned_reviews(&engine.task_manager, &engine.store, &engine.repo, &tmux).await;
2425
2426        if reset > 0 {
2427            tracing::info!(repo = %engine.repo, reset, "reset orphaned reviews to needs_review on startup");
2428        }
2429    }
2430
2431    // Spawn dispatch subscribers — react to Routed events immediately
2432    for engine in &project_engines {
2433        subscribers::dispatch::spawn(
2434            event_bus.subscribe(),
2435            Arc::clone(&engine.backend),
2436            Arc::clone(&tmux),
2437            Arc::clone(&engine.runner),
2438            Arc::clone(&capture_for_tick),
2439            Arc::clone(&semaphore),
2440            Arc::clone(&engine.task_manager),
2441            weight_tx.clone(),
2442            Arc::clone(&router),
2443            Arc::clone(&dispatching),
2444            Arc::clone(&engine.store),
2445            engine.repo.clone(),
2446        );
2447    }
2448    tracing::info!("dispatch subscriber started");
2449
2450    // Spawn review subscribers — react to NeedsReview events immediately
2451    for engine in &project_engines {
2452        subscribers::review::spawn(
2453            event_bus.subscribe(),
2454            Arc::clone(&engine.backend),
2455            Arc::clone(&tmux),
2456            Arc::clone(&review_semaphore),
2457            Arc::clone(&engine.task_manager),
2458            Arc::clone(&router),
2459            Arc::clone(&dispatching),
2460            Arc::clone(&engine.store),
2461            engine.repo.clone(),
2462        );
2463    }
2464    tracing::info!("review subscriber started");
2465
2466    // Spawn unblock subscribers — react to Done events, unblock parent tasks immediately
2467    for engine in &project_engines {
2468        subscribers::unblock::spawn(
2469            event_bus.subscribe(),
2470            Arc::clone(&engine.backend),
2471            Arc::clone(&engine.task_manager),
2472            Arc::clone(&engine.store),
2473            engine.repo.clone(),
2474        );
2475    }
2476    tracing::info!("unblock subscriber started");
2477
2478    // Spawn notify subscriber — reacts to ALL events, pushes to transport.
2479    // Spawned once (not per-project) since the transport handles all repos.
2480    subscribers::notify::spawn(event_bus.subscribe(), Arc::clone(&transport));
2481    tracing::info!("notify subscriber started");
2482
2483    // Main loop
2484    tracing::info!(
2485        tick = ?config.tick_interval,
2486        sync = ?config.sync_interval,
2487        parallel = config.max_parallel,
2488        "entering main loop"
2489    );
2490    // Values of the settings that only take effect at startup, so a reload can
2491    // tell the operator their edit needs a restart.
2492    let mut restart_only = restart_only_snapshot();
2493
2494    let mut interval = time::interval(config.tick_interval);
2495
2496    // Signal handlers (launchd/systemd send SIGTERM to stop services, SIGHUP for reload/restart)
2497    let mut sigterm = unix::signal(SignalKind::terminate())?;
2498    let mut sighup = unix::signal(SignalKind::hangup())?;
2499
2500    // Guard to prevent concurrent sync_tick runs (sync is spawned as a background task).
2501    let sync_in_progress = Arc::new(AtomicBool::new(false));
2502
2503    // Tick watchdog: detects when the main loop hasn't completed a tick in > 60s.
2504    // Updates an atomic timestamp at the end of each tick iteration.
2505    let last_tick_epoch = Arc::new(AtomicU64::new(
2506        SystemTime::now()
2507            .duration_since(std_time::UNIX_EPOCH)
2508            .unwrap_or_default()
2509            .as_secs(),
2510    ));
2511    {
2512        let last_tick_epoch = Arc::clone(&last_tick_epoch);
2513        let tick_interval_secs = config.tick_interval.as_secs();
2514        tokio::spawn(async move {
2515            // Check every 30s whether the main loop is still ticking.
2516            let mut watchdog_interval = time::interval(Duration::from_secs(30));
2517            // Own suspend baseline, independent of the main loop's checkpoint(). The
2518            // watchdog's interval timer also freezes during a host suspend, so this
2519            // detects the gap from its own wake-up instead of racing the main loop's
2520            // checkpoint() for the same GAP_LOG entry (see #3544).
2521            let mut suspend_detector = SuspendDetector::new();
2522            loop {
2523                watchdog_interval.tick().await;
2524                let own_gap = suspend_detector.check();
2525                let last = last_tick_epoch.load(Ordering::Relaxed);
2526                let now = SystemTime::now()
2527                    .duration_since(std_time::UNIX_EPOCH)
2528                    .unwrap_or_default()
2529                    .as_secs();
2530                let stale_secs = now.saturating_sub(last);
2531                // Warn if the tick loop hasn't completed in > 6× the tick interval (at least 60s).
2532                let threshold = (tick_interval_secs * 6).max(60);
2533                if stale_secs > threshold {
2534                    // A host suspend/resume gap fully explains a stale window that
2535                    // isn't an actual stall — the process (and its timers) were
2536                    // simply not scheduled while the host was asleep. Prefer this
2537                    // watchdog's own detector (immune to the checkpoint race above);
2538                    // fall back to the shared log in case the main loop's checkpoint()
2539                    // already ran and recorded a larger gap.
2540                    let shared_gap =
2541                        engine_suspend::gap_detected_within(Duration::from_secs(stale_secs));
2542                    let gap = match (own_gap, shared_gap) {
2543                        (Some(a), Some(b)) => Some(a.max(b)),
2544                        (Some(a), None) => Some(a),
2545                        (None, Some(b)) => Some(b),
2546                        (None, None) => None,
2547                    };
2548                    if let Some(gap) = gap {
2549                        let gap_secs = u64::try_from(gap.num_seconds()).unwrap_or(0);
2550                        if gap_secs >= stale_secs {
2551                            tracing::info!(
2552                                stale_secs,
2553                                threshold,
2554                                suspend_gap_secs = gap_secs,
2555                                "tick loop stale window explained by host suspend/resume, not a stall"
2556                            );
2557                        } else {
2558                            tracing::error!(
2559                                stale_secs,
2560                                threshold,
2561                                suspend_gap_secs = gap_secs,
2562                                "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — suspend gap of {}s only partially explains the stall",
2563                                stale_secs,
2564                                threshold,
2565                                gap_secs,
2566                            );
2567                        }
2568                    } else {
2569                        tracing::error!(
2570                            stale_secs,
2571                            threshold,
2572                            "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — possible stall",
2573                            stale_secs,
2574                            threshold,
2575                        );
2576                    }
2577                }
2578            }
2579        });
2580    }
2581
2582    loop {
2583        tokio::select! {
2584            _ = interval.tick() => {
2585                let tick_start = Instant::now();
2586
2587                // Detect a host suspend/resume gap once per iteration, in one place.
2588                // The watchdog and stuck-task recovery both read from this instead of
2589                // re-deriving suspend information from their own wall-clock deltas.
2590                if let Some(gap) = engine_suspend::checkpoint() {
2591                    tracing::info!(
2592                        gap_secs = gap.num_seconds(),
2593                        "host suspend/resume gap detected, discounting from stuck-task age checks"
2594                    );
2595                }
2596
2597                // Finish a pending shrink of the dispatch pool as running tasks
2598                // release their permits. Only logs when a permit was actually
2599                // taken back, so a long-running task does not log every tick.
2600                if review_in_force != config.max_parallel {
2601                    review_in_force =
2602                        resize_dispatch_pool(&review_semaphore, review_in_force, config.max_parallel);
2603                }
2604                if parallel_in_force != config.max_parallel {
2605                    let resized =
2606                        resize_dispatch_pool(&semaphore, parallel_in_force, config.max_parallel);
2607                    if resized != parallel_in_force {
2608                        parallel_in_force = resized;
2609                        tracing::info!(
2610                            in_force = parallel_in_force,
2611                            target = config.max_parallel,
2612                            "dispatch pool resized"
2613                        );
2614                    }
2615                }
2616
2617                // Tick weight recovery for rate-limited agents
2618                {
2619                    let mut rw = router.write().await;
2620                    rw.tick_weight_recovery();
2621                }
2622
2623                // Report the GitHub rate limit once per window, then tick anyway. Calls
2624                // into GitHub now fail fast instead of sleeping until the reset, so the
2625                // local phases keep moving and the watchdog does not see a stalled loop.
2626                if let Some(remaining) = GhHttp::is_rate_limited() {
2627                    let reset_at = chrono::Utc::now()
2628                        .timestamp()
2629                        .saturating_add(i64::try_from(remaining.as_secs()).unwrap_or(i64::MAX));
2630                    // Tolerate jitter in the header so one window reports once
2631                    if rate_limit_reported.is_none_or(|prev| (reset_at - prev).abs() > 60) {
2632                        rate_limit_reported = Some(reset_at);
2633                        report_rate_limited(reset_at, project_engines.first().map(|e| &e.store), Some(&transport)).await;
2634                    }
2635                } else if let Some(prev) = rate_limit_reported.take() {
2636                    tracing::info!(
2637                        limited_until = prev,
2638                        "GitHub API rate limit cleared"
2639                    );
2640                    if let Some(engine) = project_engines.first() {
2641                        let _ = engine.store.kv_delete(RATE_LIMITED_UNTIL_KEY).await;
2642                    }
2643                }
2644
2645                // Core tick: poll tasks for all projects
2646                tick::tick_all(
2647                    &project_engines,
2648                    &tmux,
2649                    &capture_for_tick,
2650                    &semaphore,
2651                    &config,
2652                    &router,
2653                    &weight_tx,
2654                    &dispatching,
2655                    Some(&transport),
2656                    &active_repos,
2657                    &auto_merge_in_flight,
2658                ).await;
2659
2660                // Drain pending weight signals after tick processing so the router
2661                // learns from outcomes produced by this iteration's task dispatches.
2662                while let Ok(signal) = weight_rx.try_recv() {
2663                    let mut rw = router.write().await;
2664                    match signal {
2665                        WeightSignal::RateLimited { ref agent } => {
2666                            rw.record_rate_limit(agent);
2667                        }
2668                        WeightSignal::Success { ref agent } => {
2669                            rw.record_success(agent);
2670                        }
2671                        WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
2672                    }
2673                }
2674
2675                // Periodic sync (less frequent) — spawned as a background task so it
2676                // cannot block the main tick loop. A stalled sync (hung HTTP call, slow
2677                // DB query, lock contention) previously parked all tokio workers for 12+
2678                // minutes because it ran inline. See issue #2574.
2679                if last_sync.elapsed() >= config.sync_interval {
2680                    if sync_in_progress.compare_exchange(
2681                        false,
2682                        true,
2683                        Ordering::AcqRel,
2684                        Ordering::Relaxed,
2685                    ).is_ok() {
2686                        spawn_sync_pass(
2687                            &project_engines,
2688                            &tmux,
2689                            &config,
2690                            &router,
2691                            &dispatching,
2692                            &auto_merge_in_flight,
2693                            &sync_in_progress,
2694                            "periodic",
2695                        );
2696                    } else {
2697                        tracing::debug!("sync tick still in progress, skipping");
2698                    }
2699                    // Records sync *schedule* time (not completion). This prevents
2700                    // re-entering the sync branch every tick while one is in flight.
2701                    // The sync_in_progress guard handles actual concurrency control.
2702                    last_sync = Instant::now();
2703                }
2704
2705                // Periodic webhook health check
2706                if webhook_enabled {
2707                    let health_check_interval = config.webhook_health_check_interval
2708                        .unwrap_or(Duration::from_secs(60));
2709
2710                    if last_webhook_health_check.elapsed() >= health_check_interval {
2711                        if let Some(port) = webhook_port {
2712                            let (health, failure_reason) =
2713                                github::check_webhook_health(port).await;
2714                            if health != webhook_healthy {
2715                                webhook_healthy = health;
2716                                if webhook_healthy {
2717                                    tracing::info!(port, orch_webhook_up = true, "webhook health restored");
2718                                } else {
2719                                    tracing::warn!(
2720                                        port,
2721                                        orch_webhook_up = false,
2722                                        reason = failure_reason.as_deref().unwrap_or("unknown"),
2723                                        "webhook health check failed"
2724                                    );
2725                                }
2726                            }
2727                            // Persist updated status.
2728                            {
2729                                let to_save = {
2730                                    let mut s = webhook_status.lock().await;
2731                                    s.healthy = health;
2732                                    s.last_check_utc = Some(chrono::Utc::now());
2733                                    if health {
2734                                        s.last_failure_reason = None;
2735                                    } else if failure_reason.is_some() {
2736                                        s.last_failure_reason = failure_reason;
2737                                    }
2738                                    s.clone()
2739                                };
2740                                to_save.save().await;
2741                            }
2742                        }
2743                        last_webhook_health_check = Instant::now();
2744                    }
2745                }
2746
2747                // Periodic upgrade check — notify channels when a newer release is available.
2748                if should_run_upgrade_check(last_upgrade_check, config.upgrade_check_interval) {
2749                    if let Some(store) = project_engines.first().map(|e| Arc::clone(&e.store)) {
2750                        let channels = Arc::clone(&channel_registry);
2751                        let current = env!("ORCH_VERSION").to_string();
2752                        let check_interval =
2753                            Duration::from_secs(config.upgrade_check_interval);
2754                        tokio::spawn(async move {
2755                            check_and_notify_upgrade(&store, &channels, &current, check_interval)
2756                                .await;
2757                        });
2758                    }
2759                    last_upgrade_check = Some(Instant::now());
2760                }
2761
2762                // Update watchdog timestamp + log tick duration.
2763                let tick_elapsed = tick_start.elapsed();
2764                if tick_elapsed.as_secs() > 30 {
2765                    tracing::warn!(
2766                        elapsed_ms = u64::try_from(tick_elapsed.as_millis()).unwrap_or(u64::MAX),
2767                        "slow tick"
2768                    );
2769                } else {
2770                    tracing::debug!(
2771                        elapsed_ms = u64::try_from(tick_elapsed.as_millis()).unwrap_or(u64::MAX),
2772                        "tick complete"
2773                    );
2774                }
2775                last_tick_epoch.store(
2776                    SystemTime::now()
2777                        .duration_since(std_time::UNIX_EPOCH)
2778                        .unwrap_or_default()
2779                        .as_secs(),
2780                    Ordering::Relaxed,
2781                );
2782            }
2783            // Webhook events trigger an immediate tick (bypass polling interval)
2784            () = webhook_notify.notified() => {
2785                if let Some(remaining) = GhHttp::is_rate_limited() {
2786                    tracing::warn!(
2787                        remaining_secs = remaining.as_secs(),
2788                        "GitHub API rate-limited, skipping webhook-triggered tick"
2789                    );
2790                } else {
2791                    tracing::info!("webhook event triggered immediate tick");
2792
2793                    tick::tick_all(
2794                        &project_engines,
2795                        &tmux,
2796                        &capture_for_tick,
2797                        &semaphore,
2798                        &config,
2799                        &router,
2800                        &weight_tx,
2801                        &dispatching,
2802                        Some(&transport),
2803                        &active_repos,
2804                        &auto_merge_in_flight,
2805                    ).await;
2806
2807                // Drain pending weight signals after webhook-triggered tick processing.
2808                while let Ok(signal) = weight_rx.try_recv() {
2809                    let mut rw = router.write().await;
2810                    match signal {
2811                        WeightSignal::RateLimited { ref agent } => {
2812                            rw.record_rate_limit(agent);
2813                        }
2814                        WeightSignal::Success { ref agent } => {
2815                            rw.record_success(agent);
2816                        }
2817                        WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
2818                    }
2819                }
2820
2821                // Also attempt to run an immediate sync (ingest/cleanup) in the
2822                // background so webhook-driven events (e.g. new issues) are
2823                // picked up without waiting for the periodic sync interval.
2824                // Reuse the same sync_in_progress guard used by the periodic
2825                // branch to avoid concurrent syncs.
2826                if sync_in_progress.compare_exchange(
2827                    false,
2828                    true,
2829                    Ordering::AcqRel,
2830                    Ordering::Relaxed,
2831                ).is_ok() {
2832                    spawn_sync_pass(
2833                        &project_engines,
2834                        &tmux,
2835                        &config,
2836                        &router,
2837                        &dispatching,
2838                        &auto_merge_in_flight,
2839                        &sync_in_progress,
2840                        "webhook",
2841                    );
2842                    // Record schedule time so periodic sync doesn't immediately re-run.
2843                    last_sync = Instant::now();
2844                } else {
2845                    tracing::debug!("sync tick still in progress, skipping webhook-triggered immediate sync");
2846                }
2847                }
2848
2849                // Also reset the interval so we don't get a redundant tick right after
2850                interval.reset();
2851            }
2852            result = config_rx.recv() => {
2853                // A notification only arrives for a file that parsed, so there is no
2854                // broken-config case to guard against here (see `config::reload_file`).
2855                let reload = match result {
2856                    Ok(path) => {
2857                        tracing::info!(path = %path.display(), "config file changed, reloading");
2858                        true
2859                    }
2860                    Err(RecvError::Lagged(n)) => {
2861                        tracing::warn!(missed = n, "config change receiver lagged, reloading");
2862                        true
2863                    }
2864                    Err(RecvError::Closed) => {
2865                        tracing::warn!("config change channel closed");
2866                        false
2867                    }
2868                };
2869
2870                if reload {
2871                    // Reload engine config
2872                    let new_config = EngineConfig::from_config();
2873                    log_engine_config_changes(&config, &new_config);
2874
2875                    let new_restart_only = restart_only_snapshot();
2876                    log_restart_only_changes(&restart_only, &new_restart_only);
2877                    restart_only = new_restart_only;
2878
2879                    let tick_changed = new_config.tick_interval != config.tick_interval;
2880                    config = new_config;
2881
2882                    // Reset tick interval if it changed
2883                    if tick_changed {
2884                        interval = time::interval(config.tick_interval);
2885                        tracing::info!(tick = ?config.tick_interval, "tick interval updated");
2886                    }
2887
2888                    // Resize the dispatch pool. A shrink only takes the permits that are
2889                    // free right now; the rest are taken as running tasks finish.
2890                    if review_in_force != config.max_parallel {
2891                        review_in_force = resize_dispatch_pool(
2892                            &review_semaphore,
2893                            review_in_force,
2894                            config.max_parallel,
2895                        );
2896                    }
2897                    if parallel_in_force != config.max_parallel {
2898                        parallel_in_force = resize_dispatch_pool(
2899                            &semaphore,
2900                            parallel_in_force,
2901                            config.max_parallel,
2902                        );
2903                        tracing::info!(
2904                            in_force = parallel_in_force,
2905                            target = config.max_parallel,
2906                            "dispatch pool resized"
2907                        );
2908                    }
2909
2910                    // Reload router config (async-safe: use reload_async to avoid blocking the runtime)
2911                    {
2912                        let mut router_guard = router.write().await;
2913                        router_guard.reload_async().await;
2914                    }
2915
2916                    // Pick up projects added to `projects:`
2917                    sync_project_engines(
2918                        &mut project_engines,
2919                        &mut active_repos,
2920                        &event_bus,
2921                        &tmux,
2922                        &capture_for_tick,
2923                        &semaphore,
2924                        &review_semaphore,
2925                        &weight_tx,
2926                        &router,
2927                        &dispatching,
2928                    ).await;
2929
2930                    tracing::info!(
2931                        tick = ?config.tick_interval,
2932                        sync = ?config.sync_interval,
2933                        parallel = config.max_parallel,
2934                        projects = project_engines.len(),
2935                        "config reloaded"
2936                    );
2937                }
2938            }
2939            signal_name = async {
2940                tokio::select! {
2941                    _ = signal::ctrl_c() => "SIGINT",
2942                    _ = sigterm.recv() => "SIGTERM",
2943                    _ = sighup.recv() => "SIGHUP",
2944                }
2945            } => {
2946                tracing::info!(signal = signal_name, "beginning graceful shutdown");
2947
2948                // Wrap the entire shutdown sequence in a timeout to enforce the configured limit.
2949                // This prevents indefinite blocking if status updates or tmux operations hang.
2950                let shutdown_result = time::timeout(
2951                    config.graceful_shutdown_timeout,
2952                    async {
2953                        // Reset in_progress tasks to routed so they re-dispatch after restart.
2954                        // Also reset in_review tasks to needs_review — their review agent
2955                        // tmux sessions will be killed when the process exits.
2956                        let mut reset_count = 0u32;
2957                        let mut review_reset_count = 0u32;
2958                        for engine in &project_engines {
2959                            if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InProgress).await {
2960                                for task in &tasks {
2961                                    if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::Routed).await {
2962                                        tracing::warn!(task_id = task.id.0, ?e, "failed to reset task on shutdown");
2963                                    } else {
2964                                        if let Ok(Some(store_id)) =
2965                                            engine.store.resolve_task_id(&engine.repo, &task.id.0).await
2966                                            && let Err(e) = engine
2967                                                .store
2968                                                .finalize_incomplete_runs(
2969                                                    store_id,
2970                                                    "aborted",
2971                                                    "graceful shutdown: reset in_progress task to routed",
2972                                                )
2973                                                .await
2974                                            {
2975                                                tracing::warn!(
2976                                                    task_id = task.id.0,
2977                                                    ?e,
2978                                                    "failed to finalize incomplete runs on shutdown"
2979                                                );
2980                                            }
2981                                        reset_count += 1;
2982                                    }
2983                                }
2984                            }
2985                            // Also reset internal in_progress tasks
2986                            if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, TaskStatus::InProgress).await {
2987                                for task in &tasks {
2988                                    let task_id = format!("internal:{}", task.id);
2989                                    if let Err(e) = engine.task_manager.update_task_status(
2990                                        &ExternalId(task_id.clone()),
2991                                        Status::Routed,
2992                                    ).await {
2993                                        tracing::warn!(task_id, ?e, "failed to reset internal task on shutdown");
2994                                    } else {
2995                                        if let Err(e) = engine
2996                                            .store
2997                                            .finalize_incomplete_runs(
2998                                                task.id,
2999                                                "aborted",
3000                                                "graceful shutdown: reset in_progress task to routed",
3001                                            )
3002                                            .await
3003                                        {
3004                                            tracing::warn!(
3005                                                task_id,
3006                                                ?e,
3007                                                "failed to finalize incomplete internal runs on shutdown"
3008                                            );
3009                                        }
3010                                        reset_count += 1;
3011                                    }
3012                                }
3013                            }
3014                            // Reset in_review tasks — review agent sessions die on shutdown
3015                            if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InReview).await {
3016                                for task in &tasks {
3017                                    if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::NeedsReview).await {
3018                                        tracing::warn!(task_id = task.id.0, ?e, "failed to reset in_review task on shutdown");
3019                                    } else {
3020                                        if let Ok(Some(store_id)) =
3021                                            engine.store.resolve_task_id(&engine.repo, &task.id.0).await
3022                                            && let Err(e) = engine
3023                                                .store
3024                                                .finalize_incomplete_runs(
3025                                                    store_id,
3026                                                    "aborted",
3027                                                    "graceful shutdown: reset in_review task to needs_review",
3028                                                )
3029                                                .await
3030                                            {
3031                                                tracing::warn!(
3032                                                    task_id = task.id.0,
3033                                                    ?e,
3034                                                    "failed to finalize incomplete review runs on shutdown"
3035                                                );
3036                                            }
3037                                        review_reset_count += 1;
3038                                    }
3039                                }
3040                            }
3041                            // Also reset internal in_review tasks
3042                            if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, TaskStatus::InReview).await {
3043                                for task in &tasks {
3044                                    let task_id = format!("internal:{}", task.id);
3045                                    if let Err(e) = engine.task_manager.update_task_status(
3046                                        &ExternalId(task_id.clone()),
3047                                        Status::NeedsReview,
3048                                    ).await {
3049                                        tracing::warn!(task_id, ?e, "failed to reset internal in_review task on shutdown");
3050                                    } else {
3051                                        if let Err(e) = engine
3052                                            .store
3053                                            .finalize_incomplete_runs(
3054                                                task.id,
3055                                                "aborted",
3056                                                "graceful shutdown: reset in_review task to needs_review",
3057                                            )
3058                                            .await
3059                                        {
3060                                            tracing::warn!(
3061                                                task_id,
3062                                                ?e,
3063                                                "failed to finalize incomplete internal review runs on shutdown"
3064                                            );
3065                                        }
3066                                        review_reset_count += 1;
3067                                    }
3068                                }
3069                            }
3070                        }
3071                        if reset_count > 0 {
3072                            tracing::info!(reset_count, "reset in_progress tasks to routed for re-dispatch");
3073                        }
3074                        if review_reset_count > 0 {
3075                            tracing::info!(review_reset_count, "reset in_review tasks to needs_review for re-dispatch");
3076                        }
3077
3078                        // Kill all orch-managed tmux sessions so stale sessions don't
3079                        // block dispatch after restart (session_exists check).
3080                        let mut killed_sessions = Vec::new();
3081                        if let Ok(sessions) = tmux.list_sessions().await {
3082                            for session in &sessions {
3083                                if session.name.starts_with("orch-") {
3084                                    match tmux.kill_session(&session.name).await { Err(e) => {
3085                                        tracing::warn!(session = %session.name, error = %e, "failed to kill tmux session");
3086                                    } _ => {
3087                                        killed_sessions.push(session.name.clone());
3088                                    }}
3089                                }
3090                            }
3091                            if !killed_sessions.is_empty() {
3092                                tracing::info!(killed = killed_sessions.len(), "killing orch tmux sessions on shutdown");
3093                            }
3094                        }
3095
3096                        // Wait for sessions to actually die before exiting.
3097                        // Prevents race where process exits before tmux finishes cleanup.
3098                        if !killed_sessions.is_empty() {
3099                            let still_alive = tmux
3100                                .wait_for_sessions_dead(
3101                                    &killed_sessions,
3102                                    Duration::from_millis(100),
3103                                    Duration::from_secs(5),
3104                                )
3105                                .await;
3106                            if still_alive > 0 {
3107                                tracing::warn!(
3108                                    still_alive,
3109                                    "some tmux sessions did not terminate cleanly - they will be cleaned up on startup"
3110                                );
3111                            }
3112                            tracing::info!(killed = killed_sessions.len() - still_alive, "confirmed tmux sessions terminated");
3113                        }
3114                    },
3115                ).await;
3116
3117                if shutdown_result.is_err() {
3118                    tracing::error!(
3119                        timeout_secs = config.graceful_shutdown_timeout.as_secs(),
3120                        "graceful shutdown timed out, forcing exit"
3121                    );
3122                }
3123
3124                break;
3125            }
3126        }
3127    }
3128
3129    // Clean up event bus port file and service version file
3130    events::cleanup_port_file().await;
3131    local::cleanup().await;
3132    events::cleanup_version_file();
3133
3134    // transport and channels drop here at end of scope
3135    let _ = transport;
3136    tracing::info!("orch engine stopped");
3137    Ok(())
3138}
3139
3140#[cfg(test)]
3141mod tests {
3142    use std::sync::Arc;
3143
3144    use super::*;
3145    use crate::backends::test_helpers::NoopBackend;
3146    use crate::channels::capture::CaptureService;
3147    use crate::channels::transport::Transport;
3148    use crate::tmux::SessionGuard;
3149    use crate::tmux::TmuxManager;
3150
3151    async fn in_review_task(store: &TaskStore, number: &str) -> i64 {
3152        let id = store
3153            .upsert_external(&crate::store::UpsertExternal {
3154                repo: "owner/repo",
3155                ext_id: number,
3156                title: "Under review",
3157                body: "",
3158                author: "",
3159                url: "",
3160                labels: &[],
3161                origin: "github",
3162            })
3163            .await
3164            .unwrap();
3165        store.update_status(id, TaskStatus::InReview).await.unwrap();
3166        id
3167    }
3168
3169    #[tokio::test]
3170    async fn a_review_without_a_session_goes_back_to_needs_review_and_a_live_one_stays() {
3171        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3172        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
3173        let task_manager =
3174            TaskManager::with_store(backend, Arc::clone(&store), "owner/repo".to_string());
3175        let tmux = TmuxManager::isolated();
3176        let orphaned = in_review_task(&store, "11").await;
3177        let live = in_review_task(&store, "12").await;
3178        let session = tmux
3179            .create_session("owner/repo", "12-review", "/tmp", "sleep 30", &[])
3180            .await
3181            .unwrap();
3182        let _guard = SessionGuard(session);
3183
3184        let reset = reset_orphaned_reviews(&task_manager, &store, "owner/repo", &tmux).await;
3185
3186        assert_eq!(reset, 1);
3187        assert_eq!(
3188            store.get(orphaned).await.unwrap().status,
3189            TaskStatus::NeedsReview
3190        );
3191        assert_eq!(store.get(live).await.unwrap().status, TaskStatus::InReview);
3192    }
3193
3194    #[test]
3195    fn growing_max_parallel_lets_more_tasks_run_without_a_restart() {
3196        let semaphore = Arc::new(Semaphore::new(4));
3197        let held: Vec<_> = (0..4)
3198            .map(|_| Arc::clone(&semaphore).try_acquire_owned().unwrap())
3199            .collect();
3200        assert!(
3201            Arc::clone(&semaphore).try_acquire_owned().is_err(),
3202            "pool is full"
3203        );
3204
3205        let in_force = resize_dispatch_pool(&semaphore, 4, 8);
3206        assert_eq!(in_force, 8);
3207
3208        let grown: Vec<_> = (0..4)
3209            .map(|_| Arc::clone(&semaphore).try_acquire_owned().unwrap())
3210            .collect();
3211        assert_eq!(held.len() + grown.len(), 8, "8 tasks run at once");
3212        assert!(
3213            Arc::clone(&semaphore).try_acquire_owned().is_err(),
3214            "pool is full"
3215        );
3216    }
3217
3218    #[test]
3219    fn shrinking_max_parallel_never_cancels_a_running_task() {
3220        let semaphore = Arc::new(Semaphore::new(8));
3221        let mut held: Vec<_> = (0..8)
3222            .map(|_| Arc::clone(&semaphore).try_acquire_owned().unwrap())
3223            .collect();
3224
3225        // Nothing is free, so all 8 tasks keep their permits and keep running.
3226        let mut in_force = resize_dispatch_pool(&semaphore, 8, 4);
3227        assert_eq!(in_force, 8);
3228        assert_eq!(held.len(), 8);
3229
3230        // Three finish. Their permits are taken back instead of handed out again.
3231        held.truncate(5);
3232        in_force = resize_dispatch_pool(&semaphore, in_force, 4);
3233        assert_eq!(in_force, 5);
3234        assert!(Arc::clone(&semaphore).try_acquire_owned().is_err());
3235
3236        // One more finishes and the pool settles at the new limit.
3237        held.truncate(4);
3238        in_force = resize_dispatch_pool(&semaphore, in_force, 4);
3239        assert_eq!(in_force, 4);
3240        assert!(Arc::clone(&semaphore).try_acquire_owned().is_err());
3241
3242        // A slot freed after that is handed out, since 4 is now the real limit.
3243        held.truncate(3);
3244        assert!(Arc::clone(&semaphore).try_acquire_owned().is_ok());
3245    }
3246
3247    #[test]
3248    fn a_project_added_to_the_config_is_picked_up_and_running_ones_are_not_respawned() {
3249        let configured = vec![
3250            ("owner/one".to_string(), PathBuf::from("/srv/one")),
3251            ("owner/two".to_string(), PathBuf::from("/srv/two")),
3252        ];
3253        let active: HashSet<String> = ["owner/one".to_string()].into_iter().collect();
3254
3255        let (added, removed) = diff_configured_projects(&configured, &active);
3256        assert_eq!(
3257            added,
3258            vec![("owner/two".to_string(), PathBuf::from("/srv/two"))],
3259            "only the new project is started, so owner/one keeps its single set of subscribers"
3260        );
3261        assert!(removed.is_empty(), "{removed:?}");
3262    }
3263
3264    #[test]
3265    fn a_project_dropped_from_the_config_is_reported_and_not_restarted() {
3266        let configured = vec![("owner/one".to_string(), PathBuf::from("/srv/one"))];
3267        let active: HashSet<String> = ["owner/one".to_string(), "owner/gone".to_string()]
3268            .into_iter()
3269            .collect();
3270
3271        let (added, removed) = diff_configured_projects(&configured, &active);
3272        assert!(added.is_empty(), "nothing new to start");
3273        assert_eq!(removed, vec!["owner/gone".to_string()]);
3274    }
3275
3276    #[test]
3277    fn an_unchanged_project_list_starts_nothing() {
3278        let configured = vec![("owner/one".to_string(), PathBuf::from("/srv/one"))];
3279        let active: HashSet<String> = ["owner/one".to_string()].into_iter().collect();
3280
3281        assert_eq!(
3282            diff_configured_projects(&configured, &active),
3283            (vec![], vec![])
3284        );
3285    }
3286
3287    #[test]
3288    fn restart_only_keys_are_the_settings_read_once_at_startup() {
3289        // Guards the docs table: every key listed here is documented as needing
3290        // `orch service restart`, and nothing reloadable may be added to it.
3291        assert_eq!(RESTART_ONLY_KEYS, ["channels", "webhook", "relay"]);
3292    }
3293
3294    #[test]
3295    fn a_changed_restart_only_key_is_reported_and_an_unchanged_one_is_not() {
3296        let before = vec![Some("bot_token: a\n".to_string()), None];
3297
3298        assert!(
3299            log_restart_only_changes(&before, &before.clone()).is_empty(),
3300            "a reload that did not touch these keys must stay quiet"
3301        );
3302
3303        // An edited token and a newly added webhook block are both changes
3304        let after = vec![
3305            Some("bot_token: b\n".to_string()),
3306            Some("port: 8080\n".to_string()),
3307        ];
3308        assert_eq!(
3309            log_restart_only_changes(&before, &after),
3310            ["channels", "webhook"]
3311        );
3312
3313        // Only the edited key is reported when the other is untouched
3314        let token_only = vec![Some("bot_token: b\n".to_string()), None];
3315        assert_eq!(log_restart_only_changes(&before, &token_only), ["channels"]);
3316    }
3317
3318    #[test]
3319    fn resize_dispatch_pool_is_a_noop_at_the_current_limit() {
3320        let semaphore = Arc::new(Semaphore::new(4));
3321        assert_eq!(resize_dispatch_pool(&semaphore, 4, 4), 4);
3322        assert_eq!(semaphore.available_permits(), 4);
3323    }
3324
3325    #[test]
3326    fn live_session_stuck_limit_follows_the_run_timeout() {
3327        let config = EngineConfig {
3328            stuck_timeout: 1800,
3329            run_timeouts: RunTimeouts {
3330                base: 1800,
3331                medium: 2700,
3332                complex: 3600,
3333            },
3334            ..EngineConfig::default()
3335        };
3336        assert_eq!(
3337            config.live_session_stuck_limit(Some("simple")),
3338            1800 + RUN_TIMEOUT_GRACE_SECS
3339        );
3340        assert_eq!(
3341            config.live_session_stuck_limit(Some("medium")),
3342            2700 + RUN_TIMEOUT_GRACE_SECS
3343        );
3344        assert_eq!(
3345            config.live_session_stuck_limit(Some("complex")),
3346            3600 + RUN_TIMEOUT_GRACE_SECS
3347        );
3348
3349        let long_stuck = EngineConfig {
3350            stuck_timeout: 7200,
3351            ..config
3352        };
3353        assert_eq!(long_stuck.live_session_stuck_limit(Some("complex")), 7200);
3354    }
3355
3356    #[test]
3357    fn engine_config_defaults() {
3358        let config = EngineConfig::default();
3359        assert_eq!(config.tick_interval, Duration::from_secs(10));
3360        assert_eq!(config.sync_interval, Duration::from_secs(45));
3361        assert_eq!(config.max_parallel, 4);
3362        assert_eq!(config.stuck_timeout, 1800);
3363        assert_eq!(config.no_session_stuck_timeout, 600);
3364        assert!(
3365            config.no_session_stuck_timeout < config.stuck_timeout,
3366            "no_session_stuck_timeout must be shorter than stuck_timeout"
3367        );
3368        assert_eq!(config.graceful_shutdown_timeout, Duration::from_secs(600));
3369        assert_eq!(config.upgrade_check_interval, 3600);
3370    }
3371
3372    #[test]
3373    fn engine_config_from_config_uses_defaults_when_no_config() {
3374        let config = EngineConfig::from_config();
3375        assert_eq!(config.tick_interval, Duration::from_secs(10));
3376        assert_eq!(config.sync_interval, Duration::from_secs(45));
3377        // max_parallel may be overridden by user config; just check it's reasonable
3378        assert!(config.max_parallel >= 1 && config.max_parallel <= 64);
3379        assert_eq!(config.stuck_timeout, 1800);
3380        assert_eq!(config.no_session_stuck_timeout, 600);
3381        assert_eq!(config.graceful_shutdown_timeout, Duration::from_secs(600));
3382        assert_eq!(config.upgrade_check_interval, 3600);
3383    }
3384
3385    #[test]
3386    fn engine_config_no_session_timeout_is_under_15_minutes() {
3387        let config = EngineConfig::default();
3388        assert!(
3389            config.no_session_stuck_timeout <= 900,
3390            "no_session_stuck_timeout ({}) exceeds 15 minutes",
3391            config.no_session_stuck_timeout
3392        );
3393    }
3394
3395    #[test]
3396    fn upgrade_check_runs_immediately_when_never_checked() {
3397        assert!(should_run_upgrade_check(None, 3600));
3398    }
3399
3400    #[test]
3401    fn upgrade_check_waits_for_interval_after_first_run() {
3402        assert!(!should_run_upgrade_check(Some(Instant::now()), 3600));
3403    }
3404
3405    #[test]
3406    fn upgrade_check_can_be_disabled() {
3407        assert!(!should_run_upgrade_check(None, 0));
3408    }
3409
3410    #[test]
3411    fn configured_agents_parses_yaml_block_array() {
3412        // config::get returns serde_norway::to_string for arrays, which is YAML block format
3413        let yaml_str = "- claude\n- codex\n- opencode\n- olm\n";
3414        let parsed: Vec<String> = serde_norway::from_str(yaml_str).unwrap();
3415        assert_eq!(parsed, vec!["claude", "codex", "opencode", "olm"]);
3416    }
3417
3418    #[test]
3419    fn configured_agents_parses_json_inline_array() {
3420        let json_str = r#"["claude","codex","olm"]"#;
3421        let parsed: Vec<String> = serde_json::from_str(json_str).unwrap();
3422        assert_eq!(parsed, vec!["claude", "codex", "olm"]);
3423    }
3424
3425    #[test]
3426    fn configured_agents_fallback_returns_default_agents() {
3427        // When no config is present, configured_agents() returns DEFAULT_AGENTS
3428        let defaults = configured_agents();
3429        assert!(defaults.contains(&"claude".to_string()));
3430        assert!(defaults.contains(&"codex".to_string()));
3431        assert!(defaults.contains(&"opencode".to_string()));
3432    }
3433
3434    /// Integration test that requires a fully working tmux environment with
3435    /// reliable capture-pane timing. Runs locally but not in CI (GitHub Actions
3436    /// has tmux installed but capture-pane timing is unreliable).
3437    ///
3438    /// DO NOT REMOVE #[ignore] — this test was un-ignored in PR #608 which
3439    /// broke CI. The `tmux -V` skip check is insufficient because tmux CAN
3440    /// create sessions on CI runners, but capture-pane output is empty or
3441    /// delayed, causing the assertion to fail after a 10s timeout.
3442    #[tokio::test]
3443    #[ignore = "capture-pane timing is unreliable on CI runners"]
3444    async fn integration_channel_to_tmux_to_capture() {
3445        // Create transport and capture service
3446        let transport = Arc::new(Transport::new());
3447        let capture = Arc::new(CaptureService::new(Arc::clone(&transport)));
3448        let tmux = TmuxManager::new();
3449
3450        let task_id = "testtask1".to_string();
3451        let session_name = format!("orch-test-{task_id}");
3452
3453        // Start a detached tmux session
3454        let _ = tmux
3455            .command()
3456            .args(["new-session", "-d", "-s", &session_name])
3457            .output()
3458            .await
3459            .expect("failed to start tmux session");
3460
3461        // Guard ensures session cleanup even on panic
3462        let _guard = SessionGuard(session_name.clone());
3463
3464        // Register session with capture service and transport binding
3465        capture
3466            .register_session("owner/repo", &task_id, &session_name)
3467            .await;
3468        transport
3469            .bind(
3470                "owner/repo",
3471                &task_id,
3472                &session_name,
3473                "telegram",
3474                "12345",
3475                None,
3476            )
3477            .await;
3478
3479        // Spawn capture.run() which exits when session is unregistered
3480        let capture_clone = Arc::clone(&capture);
3481        let capture_handle = tokio::spawn(async move { capture_clone.run().await });
3482
3483        // Subscribe to transport output for this task
3484        let mut rx = transport
3485            .subscribe("owner/repo", &task_id)
3486            .await
3487            .expect("no subscription");
3488
3489        // Send a message into the tmux session via tmux send-keys (simulate channel input)
3490        let send = tmux
3491            .command()
3492            .args([
3493                "send-keys",
3494                "-t",
3495                &session_name,
3496                "echo from-channel",
3497                "Enter",
3498            ])
3499            .output()
3500            .await
3501            .expect("failed to send keys");
3502        assert!(send.status.success());
3503
3504        // Wait for an output chunk from capture -> transport
3505        let mut got = false;
3506        for _ in 0..20 {
3507            if let Ok(Ok(c)) = time::timeout(Duration::from_millis(500), rx.recv()).await
3508                && c.content.contains("from-channel")
3509            {
3510                got = true;
3511                break;
3512            }
3513        }
3514
3515        // Clean up: unregister session (tmux kill handled by SessionGuard on drop)
3516        capture.unregister_session("owner/repo", &task_id).await;
3517
3518        // Wait for capture.run to finish
3519        let _ = capture_handle.await;
3520
3521        assert!(got, "did not observe tmux output via capture/transport");
3522    }
3523
3524    // ── read_project_channel_config tests ─────────────────────────────────
3525
3526    #[test]
3527    fn read_project_channel_config_returns_defaults_when_no_file() {
3528        let dir = tempfile::tempdir().expect("tempdir");
3529        let cfg = read_project_channel_config(dir.path());
3530        assert!(cfg.telegram_topic_id.is_none());
3531        assert!(cfg.discord_channel_id.is_none());
3532    }
3533
3534    #[test]
3535    fn read_project_channel_config_parses_telegram_and_discord() {
3536        let dir = tempfile::tempdir().expect("tempdir");
3537        let orch_yml = dir.path().join(".orch.yml");
3538        fs::write(
3539            &orch_yml,
3540            "channels:\n  telegram:\n    topic_id: \"42\"\n  discord:\n    channel_id: \"9999\"\n",
3541        )
3542        .expect("write .orch.yml");
3543        let cfg = read_project_channel_config(dir.path());
3544        assert_eq!(cfg.telegram_topic_id.as_deref(), Some("42"));
3545        assert_eq!(cfg.discord_channel_id.as_deref(), Some("9999"));
3546    }
3547
3548    #[test]
3549    fn read_project_channel_config_handles_partial_channels() {
3550        let dir = tempfile::tempdir().expect("tempdir");
3551        let orch_yml = dir.path().join(".orch.yml");
3552        fs::write(&orch_yml, "channels:\n  telegram:\n    topic_id: \"7\"\n")
3553            .expect("write .orch.yml");
3554        let cfg = read_project_channel_config(dir.path());
3555        assert_eq!(cfg.telegram_topic_id.as_deref(), Some("7"));
3556        assert!(cfg.discord_channel_id.is_none());
3557    }
3558
3559    #[test]
3560    fn read_project_channel_config_handles_malformed_yaml() {
3561        let dir = tempfile::tempdir().expect("tempdir");
3562        let orch_yml = dir.path().join(".orch.yml");
3563        fs::write(&orch_yml, "channels: [\nbad yaml").expect("write .orch.yml");
3564        let cfg = read_project_channel_config(dir.path());
3565        // Should return defaults (not panic) and emit a warn! log with the parse error.
3566        assert!(cfg.telegram_topic_id.is_none());
3567        assert!(cfg.discord_channel_id.is_none());
3568    }
3569
3570    #[test]
3571    #[cfg(unix)]
3572    fn read_project_channel_config_handles_unreadable_file() {
3573        let dir = tempfile::tempdir().expect("tempdir");
3574        // A directory fails to read for every user, root included, where chmod 000 does not
3575        fs::create_dir(dir.path().join(".orch.yml")).expect("create .orch.yml dir");
3576        let cfg = read_project_channel_config(dir.path());
3577        // Should return defaults (not panic) and emit a warn! log with the read error.
3578        assert!(cfg.telegram_topic_id.is_none());
3579        assert!(cfg.discord_channel_id.is_none());
3580    }
3581}