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