Skip to main content

orch/engine/service/
serve.rs

1//! The engine service loop and config reload
2
3/// Standard Orch attribution footer for issue bodies, PR bodies, and comments.
4///
5/// Append to every user-visible string posted to GitHub so activity is
6/// clearly attributed to orch rather than appearing as a human post.
7use crate::channels::capture::CaptureService;
8use crate::channels::discord_ws::DiscordGateway;
9use crate::channels::github::start_webhook_server;
10use crate::channels::leader;
11use crate::channels::leader::LEADER_CHECK_INTERVAL;
12use crate::channels::notification::NotificationLevel;
13use crate::channels::remote::ClusterSessions;
14use crate::channels::routing::{ChannelRouter, GlobalChannelConfig, ProjectChannelConfig};
15use crate::channels::slack::SlackChannel;
16use crate::channels::telegram::TelegramChannel;
17use crate::channels::tmux::TmuxChannel;
18use crate::channels::transport::Transport;
19use crate::channels::{Channel, ChannelRegistry, IncomingMessage, OutgoingMessage};
20use crate::config;
21use crate::engine::router::{Router, RouterConfig};
22use crate::engine::runner::WeightSignal;
23use crate::engine::tasks::TaskManager;
24use crate::engine::tasks::events::TaskEvent;
25use crate::github::http::{GhHttp, rate_limit_metrics};
26use crate::store::TaskStore;
27use crate::sys::tmux::TmuxManager;
28use async_trait::async_trait;
29use tokio::sync::broadcast;
30// AtomicBool/Ordering removed — shutdown is now immediate (reset tasks + break)
31use super::channel_handler;
32use super::cluster_projects::Contents;
33use super::registry;
34use super::shutdown;
35use super::startup::{
36    check_and_notify_upgrade, fetch_latest_release_version, init_project_engines,
37    open_shared_store, read_project_channel_config, reconcile_startup_estimates,
38    reconcile_startup_worktrees, send_startup_escalation_notification, should_run_upgrade_check,
39};
40use crate::channels::github;
41use crate::channels::github::is_transient_bind_error;
42use crate::channels::github::webhook_backoff_delay;
43use crate::channels::notification;
44use crate::channels::notification::TaskNotification;
45use crate::channels::transport;
46use crate::cooldown as engine_cooldown;
47use crate::engine::service::redeliver;
48use crate::engine::service::schedule::{Reaction, SyncSchedule};
49use crate::engine::tasks::events;
50use crate::engine::{
51    EngineConfig, EngineRef, ProjectEngine, RATE_LIMITED_UNTIL_KEY, Shared,
52    format_rate_limited_until, hosted_repos, reset_orphaned_reviews, spawn_relay_item,
53    spawn_sync_pass, start_relay_client, subscribers, sync_cluster_projects, sync_project_engines,
54    tick,
55};
56use crate::github::app;
57use crate::security::secret_ref;
58use crate::store::cluster::lease::Lease;
59use crate::store::cluster::local;
60use crate::store::cluster::registry as cluster_registry;
61use crate::sys::home;
62use crate::sys::suspend as engine_suspend;
63use crate::sys::suspend::SuspendDetector;
64use crate::webhook_status::WebhookStatus;
65use std::collections::HashMap;
66use std::collections::HashSet;
67use std::sync::Arc;
68use std::sync::atomic::AtomicBool;
69use std::sync::atomic::AtomicU64;
70use std::sync::atomic::Ordering;
71use std::time as std_time;
72use std::time::Duration;
73use std::time::Instant;
74use std::time::SystemTime;
75use tokio::signal;
76use tokio::signal::unix;
77use tokio::signal::unix::SignalKind;
78use tokio::sync::Mutex;
79use tokio::sync::broadcast::error::RecvError;
80use tokio::sync::mpsc::Receiver;
81use tokio::sync::{Notify, RwLock, Semaphore, mpsc};
82use tokio::task;
83use tokio::time;
84
85/// Announce a GitHub rate-limit window on every operator surface: the log (`orch log`),
86/// a KV flag (`orch task status`) and the channels (Telegram, Discord).
87async fn report_rate_limited(
88    reset_at: i64,
89    store: Option<&Arc<TaskStore>>,
90    transport: Option<&Arc<Transport>>,
91) {
92    let m = rate_limit_metrics();
93    let until = format_rate_limited_until(reset_at);
94    tracing::warn!(
95        reset_at,
96        rate_limit_hits = m.hits,
97        skipped_calls = m.skipped_calls,
98        five_xx_hits = m.five_xx_hits,
99        rest_remaining = ?m.rest_remaining,
100        graphql_remaining = ?m.graphql_remaining,
101        "GitHub API rate limited until {until} — skipping GitHub calls, local work continues"
102    );
103
104    if let Some(store) = store
105        && let Err(e) = store
106            .kv_set(RATE_LIMITED_UNTIL_KEY, &reset_at.to_string())
107            .await
108    {
109        tracing::warn!(err = %e, "failed to persist GitHub rate-limit flag");
110    }
111
112    if let Some(transport) = transport {
113        transport.push_notification(TaskNotification {
114            task_id: "github".to_string(),
115            title: "GitHub rate limit".to_string(),
116            status: "blocked".to_string(),
117            agent: "orch".to_string(),
118            duration_seconds: 0.0,
119            summary: format!(
120                "rate limited until {until}. GitHub calls are skipped until then; running agents and local work continue."
121            ),
122            repo: None,
123            notify_target: None,
124            pr_number: None,
125        });
126    }
127}
128
129/// Grow or shrink the dispatch pool toward `target` without cancelling running work.
130///
131/// Growing adds permits at once. Shrinking can only take back the permits that
132/// are free right now, so the return value is the limit actually in force; call
133/// again as running tasks release theirs
134pub(crate) fn resize_dispatch_pool(semaphore: &Semaphore, in_force: usize, target: usize) -> usize {
135    if target > in_force {
136        semaphore.add_permits(target - in_force);
137        return target;
138    }
139
140    if target < in_force {
141        return in_force - semaphore.forget_permits(in_force - target);
142    }
143
144    in_force
145}
146
147/// Config subtrees the engine only reads at startup: the channel gateways hold
148/// long-lived websockets and the webhook listener binds its port once.
149pub(crate) const RESTART_ONLY_KEYS: [&str; 3] = ["channels", "webhook", "relay"];
150
151/// Feeds the weight signals from this iteration's runs to the router
152async fn drain_weight_signals(router: &RwLock<Router>, weight_rx: &mut Receiver<WeightSignal>) {
153    while let Ok(signal) = weight_rx.try_recv() {
154        let mut rw = router.write().await;
155        match signal {
156            WeightSignal::RateLimited { ref agent } => {
157                rw.record_rate_limit(agent);
158            }
159            WeightSignal::Success { ref agent } => {
160                rw.record_success(agent);
161            }
162            WeightSignal::Failed { .. }
163            | WeightSignal::Rerouted
164            | WeightSignal::Blocked
165            | WeightSignal::None => {}
166        }
167    }
168}
169
170/// Read the restart-only subtrees so a later reload can tell they changed.
171fn restart_only_snapshot() -> Vec<Option<String>> {
172    RESTART_ONLY_KEYS
173        .iter()
174        .map(|key| config::get(key).ok())
175        .collect()
176}
177
178/// Report the restart-only keys an edit changed. Only the key is logged, never
179/// the value, because `channels.*` holds bot tokens
180pub(crate) fn log_restart_only_changes(
181    old: &[Option<String>],
182    new: &[Option<String>],
183) -> Vec<&'static str> {
184    let changed: Vec<&'static str> = RESTART_ONLY_KEYS
185        .iter()
186        .zip(old)
187        .zip(new)
188        .filter(|((_, old), new)| old != new)
189        .map(|((key, _), _)| *key)
190        .collect();
191
192    for key in &changed {
193        tracing::info!(key = key, "config changed, takes effect after restart");
194    }
195
196    changed
197}
198
199/// Log every engine setting whose value changed across a config reload, so
200/// `orch log` shows what the operator's edit actually did.
201fn log_engine_config_changes(old: &EngineConfig, new: &EngineConfig) {
202    macro_rules! log_changed {
203        ($($key:literal => $field:ident),+ $(,)?) => {
204            $(if old.$field != new.$field {
205                tracing::info!(key = $key, old = ?old.$field, new = ?new.$field, "config changed");
206            })+
207        };
208    }
209
210    log_changed!(
211        "engine.tick_interval" => tick_interval,
212        "engine.sync_interval" => sync_interval,
213        "engine.reconcile_interval" => reconcile_interval,
214        "engine.webhook_health_check_interval" => webhook_health_check_interval,
215        "engine.max_parallel" => max_parallel,
216        "engine.stuck_timeout" => stuck_timeout,
217        "engine.no_session_stuck_timeout" => no_session_stuck_timeout,
218        "engine.in_review_no_session_stuck_timeout" => in_review_no_session_stuck_timeout,
219        "engine.graceful_shutdown_timeout" => graceful_shutdown_timeout,
220        "engine.silence_grace_period" => silence_grace_period,
221        "engine.silence_cooldown" => silence_cooldown,
222        "engine.upgrade_check_interval" => upgrade_check_interval,
223        "engine.startup_failure_escalation_secs" => startup_failure_escalation_secs,
224        "workflow.auto_create_followup_on_changes" => auto_create_followup_on_changes,
225    );
226}
227
228/// Start the orch service.
229///
230/// This is the main entry point — called by `orch serve`.
231/// The web UI the daemon starts once its store and event bus exist, and stops at shutdown
232#[async_trait]
233pub trait WebUi: Send + Sync {
234    async fn start(
235        &self,
236        store: Arc<TaskStore>,
237        events: broadcast::Sender<TaskEvent>,
238    ) -> anyhow::Result<()>;
239
240    async fn stop(&self);
241}
242
243pub async fn serve(web: &dyn WebUi) -> anyhow::Result<()> {
244    let killed = home::prepare_serve(Duration::from_secs(30)).await;
245    if killed > 0 {
246        tracing::info!(count = killed, "terminated stale orch serve processes");
247    }
248
249    tracing::info!("orch engine starting");
250
251    // Pre-warm the config cache with async I/O so get() / get_list() calls in
252    // hot async paths never block a Tokio thread on std::fs::read_to_string.
253    if let Err(e) = config::warm_cache().await {
254        tracing::warn!("failed to warm config cache: {e}");
255    }
256
257    let mut config = EngineConfig::from_config();
258
259    // One store for every project, opened before them so the web UI can run with none. A failure
260    // here retries like a project failure did, so launchd does not restart the service in a loop
261    let store = {
262        let mut delay_secs = 5u64;
263        let mut escalated = false;
264        let start = Instant::now();
265        loop {
266            match open_shared_store().await {
267                Ok(store) => break store,
268                Err(e) => {
269                    let elapsed = start.elapsed().as_secs();
270                    let escalation = config.startup_failure_escalation_secs;
271                    // Escalates once like a project that will not start, then keeps retrying
272                    if escalation > 0 && !escalated && elapsed >= escalation {
273                        escalated = true;
274                        tracing::error!(
275                            elapsed_secs = elapsed,
276                            "the store or the cluster has not started, escalating: {e:#}"
277                        );
278                        send_startup_escalation_notification(elapsed).await;
279                    } else {
280                        tracing::warn!(
281                            delay_secs,
282                            "could not open the store or start the cluster, retrying: {e:#}"
283                        );
284                    }
285
286                    time::sleep(Duration::from_secs(delay_secs)).await;
287                    delay_secs = (delay_secs * 2).min(120);
288                }
289            }
290        }
291    };
292
293    // Load persisted model cooldowns and register store for future writes.
294    // Runs once here so the global cooldown store is not overwritten per project.
295    engine_cooldown::init_cooldown_store(Arc::clone(&store)).await;
296    tracing::info!("internal database ready");
297
298    // Create the event bus for task status transitions
299    let event_bus = events::EventBus::new(256);
300    if let Err(e) = event_bus.start_ws_server().await {
301        tracing::warn!(
302            ?e,
303            "failed to start event websocket server, continuing without it"
304        );
305    }
306
307    // Before the projects, so a first run with none can add one from the UI
308    if let Err(e) = web.start(Arc::clone(&store), event_bus.sender()).await {
309        tracing::warn!(?e, "failed to start the web UI, continuing without it");
310    }
311
312    // Initialize project engines — retry with backoff so a network outage at
313    // startup doesn't cause a crash-loop (launchd KeepAlive would restart us
314    // immediately, filling the error log with 600+ identical messages).
315    //
316    // IMPORTANT: errors from init_project_engines() must NEVER propagate past
317    // this loop to main().  If they did, anyhow would write "Error: …" to stderr,
318    // which brew routes to orch.error.log — polluting it even when projects ARE
319    // configured correctly but GitHub is temporarily unreachable.
320    let startup_escalation_secs = config.startup_failure_escalation_secs;
321    let mut project_engines = {
322        let mut delay_secs = 5u64;
323        let mut attempt = 0u32;
324        let mut escalated = false;
325        let start = Instant::now();
326        loop {
327            attempt += 1;
328            match init_project_engines(&store).await {
329                Ok(engines) => break engines,
330                Err(e) => {
331                    let elapsed = start.elapsed().as_secs();
332
333                    // Short blips (under the escalation threshold) stay at WARN
334                    // so they don't flood the operator's attention. Once the
335                    // outage crosses the threshold, escalate to ERROR-level
336                    // logging and send a one-time push notification to configured
337                    // channels — "transient" has clearly become "prolonged."
338                    if startup_escalation_secs > 0
339                        && !escalated
340                        && elapsed >= startup_escalation_secs
341                    {
342                        escalated = true;
343                        #[expect(clippy::cast_precision_loss, reason = "a display duration")]
344                        let outage = notification::format_duration(elapsed as f64);
345                        tracing::error!(
346                            delay_secs,
347                            attempt,
348                            elapsed_secs = elapsed,
349                            threshold_secs = startup_escalation_secs,
350                            "project backends unavailable for {outage} — escalating startup failure: {e}",
351                        );
352                        // Send one-time notification to configured channels.
353                        // Channels aren't registered yet at this stage, so we
354                        // construct them directly from config (mirrors orch notify).
355                        send_startup_escalation_notification(elapsed).await;
356                    } else {
357                        tracing::warn!(
358                            delay_secs,
359                            attempt,
360                            "project backends unavailable, retrying: {e}"
361                        );
362                    }
363
364                    time::sleep(Duration::from_secs(delay_secs)).await;
365                    delay_secs = (delay_secs * 2).min(120);
366                }
367            }
368        }
369    };
370
371    tracing::info!(
372        project_count = project_engines.len(),
373        "initialized project engines"
374    );
375
376    // Full set of currently-configured project repos, used by the per-tick global
377    // sweeps (e.g. `dispatch_routed_tasks_global`) to distinguish "orphaned" tasks
378    // (repo no longer in config) from tasks belonging to some other active project.
379    let mut active_repos: HashSet<String> =
380        project_engines.iter().map(|e| e.repo.clone()).collect();
381
382    // Check for a newer orch release in the background and log if the service is behind.
383    // The periodic checker sends channel notifications after channels are initialized;
384    // upgrading is operator-only and never runs automatically.
385    {
386        let current = env!("ORCH_VERSION").to_string();
387        tokio::spawn(async move {
388            if let Some(latest) = fetch_latest_release_version().await
389                && latest != current
390            {
391                tracing::warn!(
392                    current_version = %current,
393                    latest_version = %latest,
394                    "orch service is behind the latest release — run: brew update && brew upgrade orch && brew services restart orch"
395                );
396            }
397        });
398    }
399
400    // Re-create task managers with shared store and event bus
401    for engine in &mut project_engines {
402        engine.task_manager = Arc::new(TaskManager::with_events(
403            Arc::clone(&engine.backend),
404            Arc::clone(&engine.store),
405            engine.repo.clone(),
406            event_bus.sender(),
407        ));
408    }
409
410    // Every node reconciles the worktrees of the tasks it holds, see `TaskStore::reconciles_here`
411    let leads = project_engines.first().is_none_or(|e| e.store.is_leader());
412    if let Err(e) = reconcile_startup_worktrees(&project_engines).await {
413        tracing::warn!(err = %e, "startup worktree reconciliation failed");
414    }
415
416    if leads {
417        // Run estimate reconciliation in the background so it never blocks startup.
418        // Each GraphQL mutation takes ~0.8 s; with hundreds of tasks this would
419        // otherwise delay the engine reaching its main loop by several minutes.
420        let engines_snapshot: Vec<ProjectEngine> = project_engines.clone();
421        tokio::spawn(async move {
422            reconcile_startup_estimates(&engines_snapshot).await;
423        });
424    }
425
426    // Build ChannelRouter from global config + per-project configs
427    let global_channel_config = GlobalChannelConfig {
428        telegram_general_topic_id: config::get("channels.telegram.general_topic_id").ok(),
429        discord_general_channel_id: config::get("channels.discord.general_channel_id").ok(),
430        control_telegram_topic_id: config::get("control.channels.telegram.topic_id").ok(),
431        control_discord_channel_id: config::get("control.channels.discord.channel_id").ok(),
432    };
433    let project_channel_configs: Vec<(String, ProjectChannelConfig)> = project_engines
434        .iter()
435        .map(|e| {
436            let cfg = read_project_channel_config(&e.project_dir);
437            (e.repo.clone(), cfg)
438        })
439        .collect();
440    let channel_router = Arc::new(ChannelRouter::new(
441        &global_channel_config,
442        &project_channel_configs,
443    ));
444    tracing::info!(
445        projects = ?channel_router.projects(),
446        "channel router initialized"
447    );
448
449    // Initialize tmux manager (shared across all projects)
450    let tmux = Arc::new(TmuxManager::new());
451    // Kill leftover sessions from a previous process. This is daemon start only,
452    // never a tick, because nextest makes a once-flag in tick_all kill live agents
453    tick::startup_cleanup(&tmux).await;
454
455    // Initialize transport
456    let transport = Arc::new(Transport::new());
457
458    // Initialize capture service and start background loop
459    let capture = Arc::new(
460        CaptureService::new(Arc::clone(&transport))
461            .with_remote(Arc::new(ClusterSessions::new(Arc::clone(&store)))),
462    );
463    let capture_for_tick = Arc::clone(&capture);
464    tokio::spawn(async move {
465        capture.start().await;
466    });
467
468    // Initialize channel registry. In a cluster only the leader runs the bots
469    let mut channel_registry = ChannelRegistry::new();
470    let clustered = store.node().is_some();
471    let mut leader_channels = Vec::new();
472
473    // Try to initialize Telegram channel
474    if let Ok(token) = secret_ref::config_secret("channels.telegram.bot_token").await
475        && !token.is_empty()
476    {
477        let chat_id = config::get("channels.telegram.chat_id").ok();
478        let allowed_users =
479            config::get_list("channels.telegram.allowed_user_ids").unwrap_or_default();
480        match TelegramChannel::new(token, chat_id).map(|t| t.with_allowed_users(allowed_users)) {
481            Ok(telegram) => {
482                if let Err(e) = telegram.health_check().await {
483                    tracing::warn!(?e, "telegram channel health check failed, skipping");
484                } else {
485                    channel_registry.register(leader::gate(
486                        Box::new(telegram),
487                        clustered,
488                        &mut leader_channels,
489                    ));
490                    tracing::info!("telegram channel registered");
491                }
492            }
493            Err(e) => {
494                tracing::warn!(?e, "failed to create telegram channel, skipping");
495            }
496        }
497    }
498
499    // Try to initialize Discord Gateway channel (websocket)
500    if let Ok(token) = secret_ref::config_secret("channels.discord.bot_token").await
501        && !token.is_empty()
502    {
503        let channel_id = config::get("channels.discord.channel_id").ok();
504        let shard_id = config::get("channels.discord.shard_id")
505            .ok()
506            .and_then(|v| v.parse::<u64>().ok())
507            .unwrap_or(0);
508        let shard_count = config::get("channels.discord.shard_count")
509            .ok()
510            .and_then(|v| v.parse::<u64>().ok())
511            .unwrap_or(1);
512        let allowed_users =
513            config::get_list("channels.discord.allowed_user_ids").unwrap_or_default();
514        match DiscordGateway::new(token, channel_id, shard_id, shard_count)
515            .map(|d| d.with_access(channel_router.discord_channel_ids(), allowed_users))
516        {
517            Ok(discord) => {
518                if let Err(e) = discord.health_check().await {
519                    tracing::warn!(?e, "discord gateway health check failed, skipping");
520                } else {
521                    channel_registry.register(leader::gate(
522                        Box::new(discord),
523                        clustered,
524                        &mut leader_channels,
525                    ));
526                    tracing::info!(shard_id, shard_count, "discord gateway registered");
527                }
528            }
529            Err(e) => {
530                tracing::warn!(?e, "failed to create discord gateway, skipping");
531            }
532        }
533    }
534
535    // Try to initialize Slack channel
536    if let Ok(token) = secret_ref::config_secret("channels.slack.bot_token").await
537        && !token.is_empty()
538    {
539        let channel_id = config::get("channels.slack.channel_id").ok();
540        let allowed_users = config::get_list("channels.slack.allowed_user_ids").unwrap_or_default();
541        match SlackChannel::new(token, channel_id)
542            .map(|s| s.with_access(channel_router.slack_channel_ids(), allowed_users))
543        {
544            Ok(slack) => {
545                if let Err(e) = slack.health_check().await {
546                    tracing::warn!(?e, "slack channel health check failed, skipping");
547                } else {
548                    channel_registry.register(leader::gate(
549                        Box::new(slack),
550                        clustered,
551                        &mut leader_channels,
552                    ));
553                    tracing::info!("slack channel registered");
554                }
555            }
556            Err(e) => {
557                tracing::warn!(?e, "failed to create slack channel, skipping");
558            }
559        }
560    }
561
562    // Initialize tmux channel with transport for output streaming
563    let tmux_channel = TmuxChannel::with_transport(Arc::clone(&transport));
564    channel_registry.register(Box::new(tmux_channel));
565    tracing::info!("tmux channel registered");
566
567    // Start all channels and collect their message receivers
568    let mut channel_receivers: Vec<Receiver<IncomingMessage>> = Vec::new();
569    for channel in channel_registry.iter() {
570        match channel.start().await {
571            Ok(rx) => {
572                tracing::info!(channel = channel.name(), "channel started");
573                channel_receivers.push(rx);
574            }
575            Err(e) => {
576                tracing::warn!(channel = channel.name(), ?e, "failed to start channel");
577            }
578        }
579    }
580
581    if !leader_channels.is_empty() {
582        let store = Arc::clone(&store);
583        tokio::spawn(leader::follow_leader(
584            leader_channels,
585            move || store.is_leader(),
586            LEADER_CHECK_INTERVAL,
587        ));
588    }
589
590    // Wrap channel registry in Arc for shared access (notification dispatcher needs it)
591    let channel_registry = Arc::new(channel_registry);
592
593    // Spawn tasks to handle incoming channel messages (if any channels are active)
594    let transport_for_messages = Arc::clone(&transport);
595    let tmux_for_messages = Arc::clone(&tmux);
596    let capture_for_messages = Arc::clone(&capture_for_tick);
597    let channels_for_messages = Arc::clone(&channel_registry);
598    // Lightweight engine references for command execution and task creation
599    let engine_refs: Vec<EngineRef> = project_engines
600        .iter()
601        .map(|e| {
602            (
603                e.repo.clone(),
604                Arc::clone(&e.backend),
605                Arc::clone(&e.task_manager),
606                Some(Arc::clone(&e.store)),
607            )
608        })
609        .collect();
610    // Shared in-memory map for pending project picks (General channel multi-project picker).
611    let pending_picks: channel_handler::PendingPicks = Arc::new(Mutex::new(HashMap::new()));
612    let router_for_messages = Arc::clone(&channel_router);
613    for mut rx in channel_receivers {
614        let transport = Arc::clone(&transport_for_messages);
615        let tmux = Arc::clone(&tmux_for_messages);
616        let capture = Arc::clone(&capture_for_messages);
617        let channels = Arc::clone(&channels_for_messages);
618        let engine_refs = engine_refs.clone();
619        let ch_router = Arc::clone(&router_for_messages);
620        let picks = Arc::clone(&pending_picks);
621        tokio::spawn(async move {
622            while let Some(msg) = rx.recv().await {
623                tracing::debug!(channel = %msg.channel, thread = %msg.thread_id, "received message from channel");
624                channel_handler::handle_channel_message(
625                    msg,
626                    &transport,
627                    &tmux,
628                    &capture,
629                    &channels,
630                    &engine_refs,
631                    &ch_router,
632                    &picks,
633                )
634                .await;
635            }
636        });
637    }
638
639    // Post-restart confirmation: if the service was restarted via the /restart control command,
640    // a KV marker was stored before shutdown. Send a confirmation to the originating channel now
641    // that we're back online. Use a short delay to let the channel connections re-establish.
642    {
643        let restart_channels = Arc::clone(&channel_registry);
644        let restart_store = Some(Arc::clone(&store));
645        if let Some(store) = restart_store {
646            tokio::spawn(async move {
647                time::sleep(Duration::from_secs(5)).await;
648                match store.kv_get("control:restart_pending").await {
649                    Ok(Some(conv_key)) => {
650                        if let Some((ch_name, thread_id, topic_id)) =
651                            transport::parse_conversation_key(&conv_key)
652                        {
653                            for ch in restart_channels.iter() {
654                                if ch.name() == ch_name {
655                                    let msg = OutgoingMessage {
656                                        thread_id: thread_id.to_string(),
657                                        body: "orch restarted successfully.".to_string(),
658                                        reply_to: None,
659                                        metadata: serde_json::json!({}),
660                                        topic_id: topic_id.map(ToString::to_string),
661                                    };
662                                    if let Err(e) = ch.send(&msg).await {
663                                        tracing::warn!(
664                                            channel = ch_name,
665                                            error = %e,
666                                            "failed to send restart confirmation"
667                                        );
668                                    }
669                                    break;
670                                }
671                            }
672                        }
673                        if let Err(e) = store.kv_delete("control:restart_pending").await {
674                            tracing::warn!(error = %e, "failed to clear control:restart_pending");
675                        }
676                    }
677                    Ok(None) => {} // no pending restart, nothing to do
678                    Err(e) => {
679                        tracing::warn!(error = %e, "failed to read control:restart_pending");
680                    }
681                }
682            });
683        }
684    }
685
686    // Spawn notification dispatcher — reads task completion notifications
687    // from transport and broadcasts to configured channels.
688    //
689    // Routing priority:
690    // 1. Dedicated channel: if the notification has a `repo` and the
691    //    ChannelRouter maps it to a topic/channel, send there with `topic_id`.
692    // 2. Subscribed channels: send to each (channel, thread_id) subscribed to
693    //    the repo, using `format_with_project()` so recipients know the source.
694    // 3. Fallback: if no repo or no dedicated channel, broadcast to all
695    //    channels without a topic_id (legacy behaviour).
696    {
697        let mut notification_rx = transport.subscribe_notifications();
698        let channels = Arc::clone(&channel_registry);
699        let notif_router = Arc::clone(&channel_router);
700        // Grab a store reference for subscription lookups.
701        let notif_store: Option<Arc<TaskStore>> = Some(Arc::clone(&store));
702        tokio::spawn(async move {
703            loop {
704                match notification_rx.recv().await {
705                    Ok(notification) => {
706                        let level = NotificationLevel::from_config();
707                        if !level.should_notify(&notification.status) {
708                            tracing::debug!(
709                                task_id = %notification.task_id,
710                                status = %notification.status,
711                                "notification suppressed by level={:?}",
712                                level
713                            );
714                            continue;
715                        }
716
717                        tracing::info!(
718                            task_id = %notification.task_id,
719                            status = %notification.status,
720                            repo = ?notification.repo,
721                            "routing notification to channels"
722                        );
723
724                        // Track whether we sent to at least one dedicated/subscribed target.
725                        let mut routed = false;
726
727                        // 0. Direct target: if notify_target is set, send straight to
728                        //    that Telegram chat_id and skip all other routing.
729                        if let Some(ref target) = notification.notify_target {
730                            let telegram = channels.iter().find(|c| c.name() == "telegram");
731                            if let Some(channel) = telegram {
732                                let body = notification.format_telegram();
733                                let metadata = serde_json::json!({
734                                    "preformatted_html": true,
735                                    "chat_id_override": target
736                                });
737                                let msg = OutgoingMessage {
738                                    thread_id: notification.task_id.clone(),
739                                    body,
740                                    reply_to: None,
741                                    metadata,
742                                    topic_id: None,
743                                };
744                                match channel.send(&msg).await {
745                                    Err(e) => {
746                                        tracing::warn!(
747                                            task_id = %notification.task_id,
748                                            target,
749                                            ?e,
750                                            "failed to send to notify_target"
751                                        );
752                                    }
753                                    _ => {
754                                        routed = true;
755                                    }
756                                }
757                            }
758                        }
759
760                        if routed {
761                            // notify_target handled — skip further routing
762                        } else if let Some(repo) = notification.repo.as_deref() {
763                            // Track destinations already sent to in this iteration so
764                            // the dedicated (path 1) and subscribed (path 2) loops
765                            // don't double-fire the same Telegram/Discord destination
766                            // when a repo's configured topic and a `channel_subscriptions`
767                            // row resolve to the same `(channel, topic_id)`.
768                            let mut sent: HashSet<(String, Option<String>)> = HashSet::new();
769
770                            // 1. Dedicated channel targets for this repo.
771                            for channel in channels.iter() {
772                                let ch_name = channel.name();
773                                if let Some(topic_id) =
774                                    notif_router.target_for_project(repo, ch_name)
775                                {
776                                    let body = match ch_name {
777                                        "telegram" => notification.format_telegram(),
778                                        "discord" => notification.format_discord(),
779                                        "slack" => notification.format_slack(),
780                                        _ => continue,
781                                    };
782                                    let metadata = if ch_name == "telegram" {
783                                        serde_json::json!({"preformatted_html": true})
784                                    } else {
785                                        serde_json::json!({})
786                                    };
787                                    let resolved_topic = Some(topic_id.to_string());
788                                    let msg = OutgoingMessage {
789                                        thread_id: notification.task_id.clone(),
790                                        body,
791                                        reply_to: None,
792                                        metadata,
793                                        topic_id: resolved_topic.clone(),
794                                    };
795                                    if let Err(e) = channel.send(&msg).await {
796                                        tracing::warn!(
797                                            channel = ch_name,
798                                            task_id = %notification.task_id,
799                                            ?e,
800                                            "failed to send to dedicated channel"
801                                        );
802                                    } else {
803                                        sent.insert((ch_name.to_string(), resolved_topic));
804                                        routed = true;
805                                    }
806                                }
807                            }
808
809                            // 2. Subscribed channels for this repo.
810                            if let Some(store) = &notif_store {
811                                match store.list_subscribers_for_repo(repo).await {
812                                    Ok(subscribers) => {
813                                        for (ch_name, thread_id, topic_id) in subscribers {
814                                            let channel =
815                                                channels.iter().find(|c| c.name() == ch_name);
816                                            let Some(channel) = channel else {
817                                                continue;
818                                            };
819                                            let resolved_topic = if topic_id.is_empty() {
820                                                None
821                                            } else {
822                                                Some(topic_id.clone())
823                                            };
824                                            // Skip if a dedicated send to the same
825                                            // (channel, topic_id) already happened.
826                                            if sent.contains(&(
827                                                ch_name.clone(),
828                                                resolved_topic.clone(),
829                                            )) {
830                                                tracing::debug!(
831                                                    channel = %ch_name,
832                                                    task_id = %notification.task_id,
833                                                    topic_id = ?resolved_topic,
834                                                    "skipping duplicate subscriber dispatch — destination already received from dedicated path"
835                                                );
836                                                continue;
837                                            }
838                                            let body = notification.format_with_project(&ch_name);
839                                            let metadata = if ch_name == "telegram" {
840                                                serde_json::json!({"preformatted_html": true})
841                                            } else {
842                                                serde_json::json!({})
843                                            };
844                                            let msg = OutgoingMessage {
845                                                thread_id: thread_id.clone(),
846                                                body,
847                                                reply_to: None,
848                                                metadata,
849                                                topic_id: resolved_topic.clone(),
850                                            };
851                                            if let Err(e) = channel.send(&msg).await {
852                                                tracing::warn!(
853                                                    channel = %ch_name,
854                                                    task_id = %notification.task_id,
855                                                    ?e,
856                                                    "failed to send to subscribed channel"
857                                                );
858                                            } else {
859                                                sent.insert((ch_name.clone(), resolved_topic));
860                                                routed = true;
861                                            }
862                                        }
863                                    }
864                                    Err(e) => {
865                                        tracing::warn!(
866                                            repo,
867                                            ?e,
868                                            "failed to list subscribers for repo"
869                                        );
870                                    }
871                                }
872                            }
873                        }
874
875                        // 3. Fallback: broadcast to all channels when no routing happened.
876                        if !routed {
877                            for channel in channels.iter() {
878                                let (body, should_send, is_telegram) = match channel.name() {
879                                    "telegram" => (notification.format_telegram(), true, true),
880                                    "discord" => (notification.format_discord(), true, false),
881                                    "slack" => (notification.format_slack(), true, false),
882                                    // GitHub is already handled by backend.post_comment()
883                                    // tmux doesn't need task completion notifications
884                                    _ => (String::new(), false, false),
885                                };
886
887                                if !should_send {
888                                    continue;
889                                }
890
891                                let metadata = if is_telegram {
892                                    serde_json::json!({"preformatted_html": true})
893                                } else {
894                                    serde_json::json!({})
895                                };
896                                let msg = OutgoingMessage {
897                                    thread_id: notification.task_id.clone(),
898                                    body,
899                                    reply_to: None,
900                                    metadata,
901                                    topic_id: None,
902                                };
903
904                                if let Err(e) = channel.send(&msg).await {
905                                    tracing::warn!(
906                                        channel = channel.name(),
907                                        task_id = %notification.task_id,
908                                        ?e,
909                                        "failed to send notification"
910                                    );
911                                }
912                            }
913                        }
914                    }
915                    Err(RecvError::Lagged(n)) => {
916                        tracing::warn!(missed = n, "notification receiver lagged");
917                    }
918                    Err(RecvError::Closed) => {
919                        tracing::debug!("notification channel closed");
920                        break;
921                    }
922                }
923            }
924        });
925        tracing::info!("notification dispatcher started");
926    }
927
928    // Notify used by webhook events to wake up the engine tick immediately
929    let webhook_notify = Arc::new(Notify::new());
930
931    // `WebhookStatus::fallback_mode` is only shown by `orch webhook status`, the sync
932    // tick always runs every `engine.sync_interval` whether or not webhooks work
933    let webhook_port: Option<u16>;
934    let mut webhook_healthy: bool;
935    let mut last_webhook_health_check = Instant::now();
936    // Start webhook server if configured
937    let webhook_enabled = config::get_global("webhook.enabled").is_ok_and(|v| v == "true");
938    // No readable secret keeps the webhook server off, it never accepts unsigned requests
939    let webhook_secret = if webhook_enabled {
940        secret_ref::config_secret("webhook.secret")
941            .await
942            .ok()
943            .filter(|s| !s.trim().is_empty())
944    } else {
945        None
946    };
947    if webhook_enabled && webhook_secret.is_none() {
948        tracing::error!(
949            "webhook.enabled needs a readable webhook.secret, the webhook server stays off"
950        );
951    }
952    let webhook_enabled = webhook_enabled && webhook_secret.is_some();
953    let webhook_secret = webhook_secret.unwrap_or_default();
954
955    // Shared status updated by the server-spawn task and the health-check loop.
956    let webhook_status = Arc::new(Mutex::new(WebhookStatus::default()));
957
958    if webhook_enabled {
959        // Spawn the HTTP server with exponential-backoff retry on transient
960        // bind errors (e.g. EADDRINUSE).  After MAX_ATTEMPTS the engine falls
961        // back to polling and updates the shared status accordingly.
962        const WEBHOOK_MAX_ATTEMPTS: u32 = 5;
963        let port: u16 = config::get("webhook.port")
964            .ok()
965            .and_then(|v| v.parse().ok())
966            .unwrap_or(8080);
967        webhook_port = Some(port);
968        let secret = webhook_secret.clone();
969        let webhook_repo = project_engines
970            .first()
971            .map(|e| e.repo.clone())
972            .unwrap_or_default();
973
974        let (tx, mut rx) = mpsc::channel::<IncomingMessage>(64);
975
976        // Initialise status: configured, not yet healthy.
977        let to_save = {
978            let mut s = webhook_status.lock().await;
979            s.configured = true;
980            s.port = Some(port);
981            s.healthy = false;
982            s.fallback_mode = false;
983            s.clone()
984        };
985        to_save.save().await;
986
987        let status_for_spawn = Arc::clone(&webhook_status);
988        tokio::spawn(async move {
989            let mut attempt = 0u32;
990            loop {
991                attempt += 1;
992                tracing::info!(attempt, port, "attempting to start webhook server");
993                match start_webhook_server(port, secret.clone(), webhook_repo.clone(), tx.clone())
994                    .await
995                {
996                    Ok(()) => {
997                        tracing::info!(attempt, "webhook server exited cleanly");
998                        break;
999                    }
1000                    Err(e) => {
1001                        let reason = e.to_string();
1002                        tracing::error!(attempt, %reason, "webhook server failed");
1003                        if attempt >= WEBHOOK_MAX_ATTEMPTS || !is_transient_bind_error(&e) {
1004                            let kind = if attempt >= WEBHOOK_MAX_ATTEMPTS {
1005                                "max attempts reached"
1006                            } else {
1007                                "non-transient error"
1008                            };
1009                            tracing::error!(
1010                                attempt,
1011                                %reason,
1012                                kind,
1013                                orch_webhook_in_fallback = true,
1014                                "webhook server giving up, switching to polling fallback"
1015                            );
1016                            let to_save = {
1017                                let mut s = status_for_spawn.lock().await;
1018                                s.fallback_mode = true;
1019                                s.healthy = false;
1020                                s.last_failure_reason = Some(reason);
1021                                s.startup_attempts = attempt;
1022                                s.clone()
1023                            };
1024                            to_save.save().await;
1025                            break;
1026                        }
1027                        let delay = webhook_backoff_delay(attempt);
1028                        tracing::warn!(
1029                            attempt,
1030                            delay_ms = delay.as_millis(),
1031                            %reason,
1032                            "webhook bind failed (transient), retrying with backoff"
1033                        );
1034                        {
1035                            let to_save = {
1036                                let mut s = status_for_spawn.lock().await;
1037                                s.startup_attempts = attempt;
1038                                s.last_failure_reason = Some(reason);
1039                                s.clone()
1040                            };
1041                            to_save.save().await;
1042                        }
1043                        time::sleep(delay).await;
1044                    }
1045                }
1046            }
1047        });
1048
1049        // Spawn the message forwarding task (reads from webhook channel)
1050        let notify = Arc::clone(&webhook_notify);
1051        let transport_for_webhook = Arc::clone(&transport);
1052        tokio::spawn(async move {
1053            while let Some(msg) = rx.recv().await {
1054                tracing::info!(
1055                    channel = %msg.channel,
1056                    thread = %msg.thread_id,
1057                    event = %msg.metadata.get("event").and_then(|v| v.as_str()).unwrap_or("unknown"),
1058                    action = %msg.metadata.get("action").and_then(|v| v.as_str()).unwrap_or("unknown"),
1059                    "webhook event received, triggering immediate tick"
1060                );
1061                let route = transport_for_webhook.route(&msg).await;
1062                tracing::info!(
1063                    channel = %msg.channel,
1064                    route = ?route,
1065                    "webhook event routed"
1066                );
1067                // Wake up the engine tick immediately instead of waiting up to 10s
1068                notify.notify_one();
1069            }
1070        });
1071
1072        webhook_healthy = true;
1073        tracing::info!(port, orch_webhook_up = true, "webhook server started");
1074    } else {
1075        webhook_port = None;
1076        webhook_healthy = false;
1077        {
1078            let to_save = {
1079                let mut s = webhook_status.lock().await;
1080                s.configured = false;
1081                s.fallback_mode = true;
1082                s.clone()
1083            };
1084            to_save.save().await;
1085        }
1086        tracing::info!(
1087            orch_webhook_in_fallback = true,
1088            "webhook server disabled, using polling fallback mode"
1089        );
1090    }
1091
1092    // The sender stays here, so the receiver never closes when the relay is off
1093    let (relay_tx, mut relay_rx) = mpsc::unbounded_channel();
1094    let relay_items = start_relay_client(&store, &relay_tx);
1095    // Woken when a relay event's item was handled, to run the tick at once
1096    let item_tick = Arc::new(Notify::new());
1097    app::start_loader();
1098
1099    // Agent router (selects agent + model per task) - shared across projects.
1100    // Router::from_config() may run `opencode models` when the config uses opencode.
1101    // spawn_blocking keeps the Tokio runtime thread free during that I/O
1102    let router = Arc::new(RwLock::new(
1103        match task::spawn_blocking(Router::from_config).await {
1104            Ok(r) => r,
1105            Err(e) => {
1106                tracing::error!(?e, "router init panicked in spawn_blocking, using default");
1107                task::spawn_blocking(|| Router::new(RouterConfig::default()))
1108                    .await
1109                    .unwrap_or_else(|e2| {
1110                        panic!("router default init also panicked in spawn_blocking — cannot start engine without a router: {e2:?}");
1111                    })
1112            }
1113        },
1114    ));
1115    {
1116        let r = router.read().await;
1117        tracing::info!(
1118            mode = %r.config.mode,
1119            agents = ?r.available_agents,
1120            fallback = %r.config.fallback_executor,
1121            "router initialized"
1122        );
1123    }
1124
1125    // Concurrency limiter (shared across all projects). `parallel_in_force` is the
1126    // limit actually handed out, which lags `config.max_parallel` after a shrink
1127    // until the running tasks give their permits back.
1128    let semaphore = Arc::new(Semaphore::new(config.max_parallel));
1129    let mut parallel_in_force = config.max_parallel;
1130    // Reviews get their own pool, one reviewer per worker, so a busy worker pool never
1131    // starves a review (#3971)
1132    let review_semaphore = Arc::new(Semaphore::new(config.max_parallel));
1133    let mut review_in_force = config.max_parallel;
1134
1135    // In-memory dispatch guard: tracks task IDs currently being dispatched.
1136    // Guards against GitHub API eventual consistency — after update_status(InProgress),
1137    // the label-removal webhook can trigger an immediate tick where list_by_status(Routed)
1138    // still returns the task (search index propagation delay). The tmux session does not
1139    // exist until the runner completes worktree setup (~10s later), so session_exists
1140    // alone is insufficient. Keyed by "{repo}/{task_id}".
1141    let dispatching: Arc<dashmap::DashMap<String, String>> = Arc::new(dashmap::DashMap::new());
1142
1143    // In-memory guard to prevent double-spawn of auto-merge background tasks.
1144    // Since review_open_prs runs every sync_tick (~10s) but CI polling can take
1145    // up to 10 minutes, we track which tasks already have an auto-merge in flight.
1146    let auto_merge_in_flight: Arc<dashmap::DashSet<String>> = Arc::new(dashmap::DashSet::new());
1147
1148    // Subscribe to config file changes for hot reload
1149    let mut config_rx = config::subscribe();
1150
1151    // When the full sync of every project runs
1152    let mut schedule = SyncSchedule::new(relay_items, Instant::now());
1153    // A node that becomes leader runs one full sync
1154    let mut was_leader = false;
1155
1156    // Track upgrade check interval
1157    let mut last_upgrade_check: Option<Instant> = None;
1158
1159    // Reset epoch of the GitHub rate-limit window already reported, so the log line,
1160    // the KV flag and the channel notification fire once per window instead of per tick
1161    let mut rate_limit_reported: Option<i64> = None;
1162
1163    // Channel for weight signals from task runners back to the router
1164    let (weight_tx, mut weight_rx) = mpsc::channel::<WeightSignal>(64);
1165
1166    // A restart ends every review session, so reset each in_review task left without one
1167    for engine in project_engines.iter().filter(|_| leads) {
1168        let reset =
1169            reset_orphaned_reviews(&engine.task_manager, &engine.store, &engine.repo, &tmux).await;
1170
1171        if reset > 0 {
1172            tracing::info!(repo = %engine.repo, reset, "reset orphaned reviews to needs_review on startup");
1173        }
1174    }
1175
1176    // Spawn dispatch subscribers — react to Routed events immediately
1177    for engine in &project_engines {
1178        subscribers::dispatch::spawn(
1179            event_bus.subscribe(),
1180            Arc::clone(&engine.backend),
1181            Arc::clone(&tmux),
1182            Arc::clone(&engine.runner),
1183            Arc::clone(&capture_for_tick),
1184            Arc::clone(&semaphore),
1185            Arc::clone(&engine.task_manager),
1186            weight_tx.clone(),
1187            Arc::clone(&router),
1188            Arc::clone(&dispatching),
1189            Arc::clone(&engine.store),
1190            engine.repo.clone(),
1191        );
1192    }
1193    tracing::info!("dispatch subscriber started");
1194
1195    // Spawn review subscribers — react to NeedsReview events immediately
1196    for engine in &project_engines {
1197        subscribers::review::spawn(
1198            event_bus.subscribe(),
1199            Arc::clone(&engine.backend),
1200            Arc::clone(&tmux),
1201            Arc::clone(&review_semaphore),
1202            Arc::clone(&engine.task_manager),
1203            Arc::clone(&router),
1204            Arc::clone(&dispatching),
1205            Arc::clone(&engine.store),
1206            engine.repo.clone(),
1207        );
1208    }
1209    tracing::info!("review subscriber started");
1210
1211    // Spawn unblock subscribers — react to Done events, unblock parent tasks immediately
1212    for engine in &project_engines {
1213        subscribers::unblock::spawn(
1214            event_bus.subscribe(),
1215            Arc::clone(&engine.backend),
1216            Arc::clone(&engine.task_manager),
1217            Arc::clone(&engine.store),
1218            engine.repo.clone(),
1219        );
1220    }
1221    tracing::info!("unblock subscriber started");
1222
1223    // Spawn notify subscriber — reacts to ALL events, pushes to transport.
1224    // Spawned once (not per-project) since the transport handles all repos.
1225    subscribers::notify::spawn(event_bus.subscribe(), Arc::clone(&transport));
1226    tracing::info!("notify subscriber started");
1227
1228    // Main loop
1229    tracing::info!(
1230        tick = ?config.tick_interval,
1231        sync = ?config.sync_interval,
1232        parallel = config.max_parallel,
1233        "entering main loop"
1234    );
1235    // Values of the settings that only take effect at startup, so a reload can
1236    // tell the operator their edit needs a restart.
1237    let mut restart_only = restart_only_snapshot();
1238
1239    let mut interval = time::interval(config.tick_interval);
1240
1241    // Signal handlers (launchd/systemd send SIGTERM to stop services, SIGHUP for reload/restart)
1242    let mut sigterm = unix::signal(SignalKind::terminate())?;
1243    let mut sighup = unix::signal(SignalKind::hangup())?;
1244
1245    // Guard to prevent concurrent sync_tick runs (sync is spawned as a background task).
1246    let sync_in_progress = Arc::new(AtomicBool::new(false));
1247
1248    // Tick watchdog: detects when the main loop hasn't completed a tick in > 60s.
1249    // Updates an atomic timestamp at the end of each tick iteration.
1250    let last_tick_epoch = Arc::new(AtomicU64::new(
1251        SystemTime::now()
1252            .duration_since(std_time::UNIX_EPOCH)
1253            .unwrap_or_default()
1254            .as_secs(),
1255    ));
1256    {
1257        let last_tick_epoch = Arc::clone(&last_tick_epoch);
1258        let tick_interval_secs = config.tick_interval_secs();
1259        tokio::spawn(async move {
1260            // Check every 30s whether the main loop is still ticking.
1261            let mut watchdog_interval = time::interval(Duration::from_secs(30));
1262            // Own suspend baseline, independent of the main loop's checkpoint(). The
1263            // watchdog's interval timer also freezes during a host suspend, so this
1264            // detects the gap from its own wake-up instead of racing the main loop's
1265            // checkpoint() for the same GAP_LOG entry (see #3544).
1266            let mut suspend_detector = SuspendDetector::new();
1267            loop {
1268                watchdog_interval.tick().await;
1269                let last = last_tick_epoch.load(Ordering::Relaxed);
1270                let now = SystemTime::now()
1271                    .duration_since(std_time::UNIX_EPOCH)
1272                    .unwrap_or_default()
1273                    .as_secs();
1274                let stale_secs = now.saturating_sub(last);
1275                // Warn if the tick loop hasn't completed in > 6× the tick interval (at least 60s).
1276                let threshold = (tick_interval_secs * 6).max(60);
1277                // Every wake-up, so the detector keeps its own baseline
1278                let gap = suspend_detector.gap_within(Duration::from_secs(stale_secs));
1279                if stale_secs > threshold {
1280                    // A host suspend/resume gap fully explains a stale window that
1281                    // isn't an actual stall — the process (and its timers) were
1282                    // simply not scheduled while the host was asleep. Prefer this
1283                    // watchdog's own detector (immune to the checkpoint race above);
1284                    // fall back to the shared log in case the main loop's checkpoint()
1285                    // already ran and recorded a larger gap.
1286                    if let Some(gap) = gap {
1287                        let gap_secs = u64::try_from(gap.num_seconds()).unwrap_or(0);
1288                        if gap_secs >= stale_secs {
1289                            tracing::info!(
1290                                stale_secs,
1291                                threshold,
1292                                suspend_gap_secs = gap_secs,
1293                                "tick loop stale window explained by host suspend/resume, not a stall"
1294                            );
1295                        } else {
1296                            tracing::error!(
1297                                stale_secs,
1298                                threshold,
1299                                suspend_gap_secs = gap_secs,
1300                                "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — suspend gap of {}s only partially explains the stall",
1301                                stale_secs,
1302                                threshold,
1303                                gap_secs,
1304                            );
1305                        }
1306                    } else {
1307                        tracing::error!(
1308                            stale_secs,
1309                            threshold,
1310                            "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — possible stall",
1311                            stale_secs,
1312                            threshold,
1313                        );
1314                    }
1315                }
1316            }
1317        });
1318    }
1319
1320    // When this node last wrote its registry entry. None writes it on the next tick
1321    let mut registry_written: Option<Instant> = None;
1322    // Reads the `.orch.yml` of the projects other nodes host. None on one machine
1323    let contents: Option<Arc<dyn Contents>> = if clustered {
1324        match GhHttp::new() {
1325            Ok(gh) => Some(Arc::new(gh)),
1326            Err(e) => {
1327                tracing::warn!(err = %e, "no GitHub client, the projects other nodes host keep the global settings");
1328                None
1329            }
1330        }
1331    } else {
1332        None
1333    };
1334    // When this node last renewed the leases on its runs
1335    let mut leases_renewed: Option<Instant> = None;
1336
1337    loop {
1338        tokio::select! {
1339            _ = interval.tick() => {
1340                let tick_start = Instant::now();
1341
1342                if clustered && registry_written.is_none_or(|at| at.elapsed() >= cluster_registry::HEARTBEAT) {
1343                    registry_written = Some(Instant::now());
1344                    registry::publish(&store, &hosted_repos(&project_engines), &router, config.max_parallel).await;
1345                    sync_cluster_projects(
1346                        &store,
1347                        &mut project_engines,
1348                        &mut active_repos,
1349                        Shared {
1350                            event_bus: &event_bus,
1351                            tmux: &tmux,
1352                            capture: &capture_for_tick,
1353                            semaphore: &semaphore,
1354                            review_semaphore: &review_semaphore,
1355                            weight_tx: &weight_tx,
1356                            router: &router,
1357                            dispatching: &dispatching,
1358                        },
1359                        contents.as_ref(),
1360                    ).await;
1361                }
1362
1363                let lease = Lease::load();
1364                if clustered && leases_renewed.is_none_or(|at| at.elapsed() >= lease.renew) {
1365                    leases_renewed = Some(Instant::now());
1366                    registry::renew_leases(&store, lease);
1367                }
1368
1369                // Detect a host suspend/resume gap once per iteration, in one place.
1370                // The watchdog and stuck-task recovery both read from this instead of
1371                // re-deriving suspend information from their own wall-clock deltas.
1372                if let Some(gap) = engine_suspend::checkpoint() {
1373                    tracing::info!(
1374                        gap_secs = gap.num_seconds(),
1375                        "host suspend/resume gap detected, discounting from stuck-task age checks"
1376                    );
1377                }
1378
1379                // Finish a pending shrink of the dispatch pool as running tasks
1380                // release their permits. Only logs when a permit was actually
1381                // taken back, so a long-running task does not log every tick.
1382                if review_in_force != config.max_parallel {
1383                    review_in_force =
1384                        resize_dispatch_pool(&review_semaphore, review_in_force, config.max_parallel);
1385                }
1386                if parallel_in_force != config.max_parallel {
1387                    let resized =
1388                        resize_dispatch_pool(&semaphore, parallel_in_force, config.max_parallel);
1389                    if resized != parallel_in_force {
1390                        parallel_in_force = resized;
1391                        tracing::info!(
1392                            in_force = parallel_in_force,
1393                            target = config.max_parallel,
1394                            "dispatch pool resized"
1395                        );
1396                    }
1397                }
1398
1399                // Tick weight recovery for rate-limited agents
1400                {
1401                    let mut rw = router.write().await;
1402                    rw.tick_weight_recovery();
1403                }
1404
1405                // Report the GitHub rate limit once per window, then tick anyway. Calls
1406                // into GitHub now fail fast instead of sleeping until the reset, so the
1407                // local phases keep moving and the watchdog does not see a stalled loop.
1408                if let Some(remaining) = GhHttp::is_rate_limited() {
1409                    let reset_at = chrono::Utc::now()
1410                        .timestamp()
1411                        .saturating_add(i64::try_from(remaining.as_secs()).unwrap_or(i64::MAX));
1412                    // Tolerate jitter in the header so one window reports once
1413                    if rate_limit_reported.is_none_or(|prev| (reset_at - prev).abs() > 60) {
1414                        rate_limit_reported = Some(reset_at);
1415                        report_rate_limited(reset_at, Some(&store), Some(&transport)).await;
1416                    }
1417                } else if let Some(prev) = rate_limit_reported.take() {
1418                    tracing::info!(
1419                        limited_until = prev,
1420                        "GitHub API rate limit cleared"
1421                    );
1422                    let _ = store.kv_delete(RATE_LIMITED_UNTIL_KEY).await;
1423                }
1424
1425                // Core tick: poll tasks for all projects
1426                tick::tick_all(
1427                    &project_engines,
1428                    &tmux,
1429                    &capture_for_tick,
1430                    &semaphore,
1431                    &config,
1432                    &router,
1433                    &weight_tx,
1434                    &dispatching,
1435                    Some(&transport),
1436                    &active_repos,
1437                    &auto_merge_in_flight,
1438                ).await;
1439
1440                // A cluster node starts the runs the leader assigned to it
1441                tick::worker::run_assigned(
1442                    &project_engines,
1443                    tick::worker::Worker {
1444                        tmux: &tmux,
1445                        capture: &capture_for_tick,
1446                        semaphore: &semaphore,
1447                        review_semaphore: &review_semaphore,
1448                        router: &router,
1449                        weight_tx: &weight_tx,
1450                        dispatching: &dispatching,
1451                    },
1452                ).await;
1453
1454                // Drain pending weight signals after tick processing so the router
1455                // learns from outcomes produced by this iteration's task dispatches.
1456                drain_weight_signals(&router, &mut weight_rx).await;
1457
1458                // Periodic sync (less frequent) — spawned as a background task so it
1459                // cannot block the main tick loop. A stalled sync (hung HTTP call, slow
1460                // DB query, lock contention) previously parked all tokio workers for 12+
1461                // minutes because it ran inline. See issue #2574.
1462                if clustered {
1463                    let leader = store.is_leader();
1464                    if leader && !was_leader {
1465                        schedule.force();
1466                    }
1467                    was_leader = leader;
1468                }
1469
1470                if schedule.due(&config, Instant::now()) {
1471                    if sync_in_progress.compare_exchange(
1472                        false,
1473                        true,
1474                        Ordering::AcqRel,
1475                        Ordering::Relaxed,
1476                    ).is_ok() {
1477                        spawn_sync_pass(
1478                            &project_engines,
1479                            &tmux,
1480                            &config,
1481                            &router,
1482                            &dispatching,
1483                            &auto_merge_in_flight,
1484                            &sync_in_progress,
1485                            if schedule.reconciling() { "reconcile" } else { "periodic" },
1486                        );
1487                        // GitHub never retries a webhook the relay lost, so ask for it again
1488                        if schedule.reconciling() && store.is_leader() {
1489                            redeliver::spawn(&store);
1490                        }
1491                        // Records sync *schedule* time (not completion). This prevents
1492                        // re-entering the sync branch every tick while one is in flight
1493                        schedule.ran(Instant::now());
1494                    } else {
1495                        tracing::debug!("sync tick still in progress, skipping");
1496                    }
1497                }
1498
1499                // Periodic webhook health check
1500                if webhook_enabled {
1501                    let health_check_interval = config.webhook_health_check_interval();
1502
1503                    if last_webhook_health_check.elapsed() >= health_check_interval {
1504                        if let Some(port) = webhook_port {
1505                            let (health, failure_reason) =
1506                                github::check_webhook_health(port).await;
1507                            if health != webhook_healthy {
1508                                webhook_healthy = health;
1509                                if webhook_healthy {
1510                                    tracing::info!(port, orch_webhook_up = true, "webhook health restored");
1511                                } else {
1512                                    tracing::warn!(
1513                                        port,
1514                                        orch_webhook_up = false,
1515                                        reason = failure_reason.as_deref().unwrap_or("unknown"),
1516                                        "webhook health check failed"
1517                                    );
1518                                }
1519                            }
1520                            // Persist updated status.
1521                            {
1522                                let to_save = {
1523                                    let mut s = webhook_status.lock().await;
1524                                    s.healthy = health;
1525                                    s.last_check_utc = Some(chrono::Utc::now());
1526                                    if health {
1527                                        s.last_failure_reason = None;
1528                                    } else if failure_reason.is_some() {
1529                                        s.last_failure_reason = failure_reason;
1530                                    }
1531                                    s.clone()
1532                                };
1533                                to_save.save().await;
1534                            }
1535                        }
1536                        last_webhook_health_check = Instant::now();
1537                    }
1538                }
1539
1540                // Periodic upgrade check — notify channels when a newer release is available.
1541                if should_run_upgrade_check(last_upgrade_check, config.upgrade_check_interval) {
1542                    let store = Arc::clone(&store);
1543                    let channels = Arc::clone(&channel_registry);
1544                    let current = env!("ORCH_VERSION").to_string();
1545                    let check_interval = Duration::from_secs(config.upgrade_check_interval);
1546                    tokio::spawn(async move {
1547                        check_and_notify_upgrade(&store, &channels, &current, check_interval)
1548                            .await;
1549                    });
1550                    last_upgrade_check = Some(Instant::now());
1551                }
1552
1553                // Update watchdog timestamp + log tick duration.
1554                let tick_elapsed = tick_start.elapsed();
1555                if tick_elapsed.as_secs() > 30 {
1556                    tracing::warn!(
1557                        elapsed_ms = u64::try_from(tick_elapsed.as_millis()).unwrap_or(u64::MAX),
1558                        "slow tick"
1559                    );
1560                } else {
1561                    tracing::debug!(
1562                        elapsed_ms = u64::try_from(tick_elapsed.as_millis()).unwrap_or(u64::MAX),
1563                        "tick complete"
1564                    );
1565                }
1566                last_tick_epoch.store(
1567                    SystemTime::now()
1568                        .duration_since(std_time::UNIX_EPOCH)
1569                        .unwrap_or_default()
1570                        .as_secs(),
1571                    Ordering::Relaxed,
1572                );
1573            }
1574            Some(signal) = relay_rx.recv() => {
1575                match schedule.on_signal(signal) {
1576                    Reaction::None => {
1577                        // A connect, disconnect or gap asks for a full sync, run it now
1578                        if schedule.due(&config, Instant::now()) {
1579                            interval.reset_immediately();
1580                        }
1581                    }
1582                    Reaction::Wake => webhook_notify.notify_one(),
1583                    Reaction::Item(event) => {
1584                        let engine = project_engines
1585                            .iter()
1586                            .find(|e| e.repo.eq_ignore_ascii_case(&event.repo));
1587                        // Only the leader reads GitHub, the same as for the sync
1588                        if !store.is_leader() {
1589                            tracing::debug!(repo = %event.repo, "not the leader, relay event left to the leader");
1590                        } else if let Some(remaining) = GhHttp::is_rate_limited() {
1591                            tracing::warn!(remaining_secs = remaining.as_secs(), repo = %event.repo, "GitHub API rate-limited, relay event left to the reconciliation pass");
1592                        } else if engine_cooldown::is_github_circuit_open() {
1593                            tracing::warn!(repo = %event.repo, "GitHub 5xx circuit open, relay event left to the reconciliation pass");
1594                        } else if let Some(engine) = engine {
1595                            spawn_relay_item(
1596                                engine,
1597                                event,
1598                                &tmux,
1599                                &config,
1600                                &router,
1601                                &dispatching,
1602                                &auto_merge_in_flight,
1603                                &item_tick,
1604                            );
1605                        } else {
1606                            tracing::debug!(repo = %event.repo, "relay event for a repository orch does not manage");
1607                        }
1608                    }
1609                }
1610            }
1611            // A relay event's item was handled, so run the tick for it without a full sync
1612            () = item_tick.notified() => {
1613                if GhHttp::is_rate_limited().is_none() {
1614                    tick::tick_all(
1615                        &project_engines,
1616                        &tmux,
1617                        &capture_for_tick,
1618                        &semaphore,
1619                        &config,
1620                        &router,
1621                        &weight_tx,
1622                        &dispatching,
1623                        Some(&transport),
1624                        &active_repos,
1625                        &auto_merge_in_flight,
1626                    ).await;
1627                    drain_weight_signals(&router, &mut weight_rx).await;
1628                }
1629                interval.reset();
1630            }
1631            // Webhook events trigger an immediate tick (bypass polling interval)
1632            () = webhook_notify.notified() => {
1633                if let Some(remaining) = GhHttp::is_rate_limited() {
1634                    tracing::warn!(
1635                        remaining_secs = remaining.as_secs(),
1636                        "GitHub API rate-limited, skipping webhook-triggered tick"
1637                    );
1638                } else {
1639                    tracing::info!("webhook event triggered immediate tick");
1640
1641                    tick::tick_all(
1642                        &project_engines,
1643                        &tmux,
1644                        &capture_for_tick,
1645                        &semaphore,
1646                        &config,
1647                        &router,
1648                        &weight_tx,
1649                        &dispatching,
1650                        Some(&transport),
1651                        &active_repos,
1652                        &auto_merge_in_flight,
1653                    ).await;
1654
1655                // Drain pending weight signals after webhook-triggered tick processing.
1656                drain_weight_signals(&router, &mut weight_rx).await;
1657
1658                // Also attempt to run an immediate sync (ingest/cleanup) in the
1659                // background so webhook-driven events (e.g. new issues) are
1660                // picked up without waiting for the periodic sync interval.
1661                // Reuse the same sync_in_progress guard used by the periodic
1662                // branch to avoid concurrent syncs.
1663                if sync_in_progress.compare_exchange(
1664                    false,
1665                    true,
1666                    Ordering::AcqRel,
1667                    Ordering::Relaxed,
1668                ).is_ok() {
1669                    spawn_sync_pass(
1670                        &project_engines,
1671                        &tmux,
1672                        &config,
1673                        &router,
1674                        &dispatching,
1675                        &auto_merge_in_flight,
1676                        &sync_in_progress,
1677                        "webhook",
1678                    );
1679                    // Record schedule time so periodic sync doesn't immediately re-run.
1680                    schedule.ran(Instant::now());
1681                } else {
1682                    tracing::debug!("sync tick still in progress, skipping webhook-triggered immediate sync");
1683                }
1684                }
1685
1686                // Also reset the interval so we don't get a redundant tick right after
1687                interval.reset();
1688            }
1689            result = config_rx.recv() => {
1690                // A notification only arrives for a file that parsed, so there is no
1691                // broken-config case to guard against here (see `config::reload_file`).
1692                let reload = match result {
1693                    Ok(path) => {
1694                        tracing::info!(path = %path.display(), "config file changed, reloading");
1695                        true
1696                    }
1697                    Err(RecvError::Lagged(n)) => {
1698                        tracing::warn!(missed = n, "config change receiver lagged, reloading");
1699                        true
1700                    }
1701                    Err(RecvError::Closed) => {
1702                        tracing::warn!("config change channel closed");
1703                        false
1704                    }
1705                };
1706
1707                if reload {
1708                    // Reload engine config
1709                    let new_config = EngineConfig::from_config();
1710                    log_engine_config_changes(&config, &new_config);
1711
1712                    let new_restart_only = restart_only_snapshot();
1713                    log_restart_only_changes(&restart_only, &new_restart_only);
1714                    restart_only = new_restart_only;
1715
1716                    let tick_changed = new_config.tick_interval != config.tick_interval;
1717                    config = new_config;
1718
1719                    // Reset tick interval if it changed
1720                    if tick_changed {
1721                        interval = time::interval(config.tick_interval);
1722                        tracing::info!(tick = ?config.tick_interval, "tick interval updated");
1723                    }
1724
1725                    // Resize the dispatch pool. A shrink only takes the permits that are
1726                    // free right now; the rest are taken as running tasks finish.
1727                    if review_in_force != config.max_parallel {
1728                        review_in_force = resize_dispatch_pool(
1729                            &review_semaphore,
1730                            review_in_force,
1731                            config.max_parallel,
1732                        );
1733                    }
1734                    if parallel_in_force != config.max_parallel {
1735                        parallel_in_force = resize_dispatch_pool(
1736                            &semaphore,
1737                            parallel_in_force,
1738                            config.max_parallel,
1739                        );
1740                        tracing::info!(
1741                            in_force = parallel_in_force,
1742                            target = config.max_parallel,
1743                            "dispatch pool resized"
1744                        );
1745                    }
1746
1747                    // Reload router config (async-safe: use reload_async to avoid blocking the runtime)
1748                    {
1749                        let mut router_guard = router.write().await;
1750                        router_guard.reload_async().await;
1751                    }
1752
1753                    // Pick up projects added to `projects:`
1754                    sync_project_engines(
1755                        &store,
1756                        &mut project_engines,
1757                        &mut active_repos,
1758                        Shared {
1759                            event_bus: &event_bus,
1760                            tmux: &tmux,
1761                            capture: &capture_for_tick,
1762                            semaphore: &semaphore,
1763                            review_semaphore: &review_semaphore,
1764                            weight_tx: &weight_tx,
1765                            router: &router,
1766                            dispatching: &dispatching,
1767                        },
1768                    ).await;
1769
1770                    // The registry entry carries the projects, agents and slots, so write it now
1771                    registry_written = None;
1772
1773                    tracing::info!(
1774                        tick = ?config.tick_interval,
1775                        sync = ?config.sync_interval,
1776                        parallel = config.max_parallel,
1777                        projects = project_engines.len(),
1778                        "config reloaded"
1779                    );
1780                }
1781            }
1782            signal_name = async {
1783                tokio::select! {
1784                    _ = signal::ctrl_c() => "SIGINT",
1785                    _ = sigterm.recv() => "SIGTERM",
1786                    _ = sighup.recv() => "SIGHUP",
1787                }
1788            } => {
1789                tracing::info!(signal = signal_name, "beginning graceful shutdown");
1790
1791                // Wrap the entire shutdown sequence in a timeout to enforce the configured limit.
1792                // This prevents indefinite blocking if status updates or tmux operations hang.
1793                let shutdown_result = time::timeout(
1794                    config.graceful_shutdown_timeout,
1795                    async {
1796                        let resets = shutdown::reset_own_runs(&project_engines).await;
1797                        resets.log();
1798
1799                        // Kill all orch-managed tmux sessions so stale sessions don't
1800                        // block dispatch after restart (session_exists check).
1801                        let mut killed_sessions = Vec::new();
1802                        if let Ok(sessions) = tmux.list_sessions().await {
1803                            for session in &sessions {
1804                                if session.name.starts_with("orch-") {
1805                                    match tmux.kill_session(&session.name).await { Err(e) => {
1806                                        tracing::warn!(session = %session.name, error = %e, "failed to kill tmux session");
1807                                    } _ => {
1808                                        killed_sessions.push(session.name.clone());
1809                                    }}
1810                                }
1811                            }
1812                            if !killed_sessions.is_empty() {
1813                                tracing::info!(killed = killed_sessions.len(), "killing orch tmux sessions on shutdown");
1814                            }
1815                        }
1816
1817                        // Wait for sessions to actually die before exiting.
1818                        // Prevents race where process exits before tmux finishes cleanup.
1819                        if !killed_sessions.is_empty() {
1820                            let still_alive = tmux
1821                                .wait_for_sessions_dead(
1822                                    &killed_sessions,
1823                                    Duration::from_millis(100),
1824                                    Duration::from_secs(5),
1825                                )
1826                                .await;
1827                            if still_alive > 0 {
1828                                tracing::warn!(
1829                                    still_alive,
1830                                    "some tmux sessions did not terminate cleanly - they will be cleaned up on startup"
1831                                );
1832                            }
1833                            tracing::info!(killed = killed_sessions.len() - still_alive, "confirmed tmux sessions terminated");
1834                        }
1835                    },
1836                ).await;
1837
1838                if shutdown_result.is_err() {
1839                    tracing::error!(
1840                        timeout_secs = config.graceful_shutdown_secs(),
1841                        "graceful shutdown timed out, forcing exit"
1842                    );
1843                }
1844
1845                break;
1846            }
1847        }
1848    }
1849
1850    // Clean up event bus port file and service version file
1851    events::cleanup_port_file().await;
1852    local::cleanup().await;
1853    web.stop().await;
1854    events::cleanup_version_file();
1855
1856    // transport and channels drop here at end of scope
1857    let _ = transport;
1858    tracing::info!("orch engine stopped");
1859    Ok(())
1860}