Skip to main content

orch/engine/service/
serve.rs

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