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