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