Skip to main content

orch/engine/
serve.rs

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