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