Skip to main content

orch/engine/
serve.rs

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