Skip to main content

orch/engine/service/
serve.rs

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