1use crate::backends::ExternalId;
8use crate::channels::capture::CaptureService;
9use crate::channels::discord_ws::DiscordGateway;
10use crate::channels::github::start_webhook_server;
11use crate::channels::leader;
12use crate::channels::leader::LEADER_CHECK_INTERVAL;
13use crate::channels::notification::NotificationLevel;
14use crate::channels::routing::{ChannelRouter, GlobalChannelConfig, ProjectChannelConfig};
15use crate::channels::slack::SlackChannel;
16use crate::channels::telegram::TelegramChannel;
17use crate::channels::tmux::TmuxChannel;
18use crate::channels::transport::Transport;
19use crate::channels::{Channel, ChannelRegistry, IncomingMessage, OutgoingMessage};
20use crate::config;
21use crate::engine::router::{Router, RouterConfig};
22use crate::engine::runner::WeightSignal;
23use crate::engine::tasks::TaskManager;
24use crate::engine::tasks::events::TaskEvent;
25use crate::github::http::{GhHttp, rate_limit_metrics};
26use crate::store::{TaskStatus, TaskStore};
27use crate::sys::tmux::TmuxManager;
28use async_trait::async_trait;
29use tokio::sync::broadcast;
30use super::channel_handler;
32use super::registry;
33use super::startup::{
34 check_and_notify_upgrade, fetch_latest_release_version, init_project_engines,
35 open_shared_store, read_project_channel_config, reconcile_startup_estimates,
36 reconcile_startup_worktrees, send_startup_escalation_notification, should_run_upgrade_check,
37};
38use crate::backends::Status;
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, format_rate_limited_until,
49 reset_orphaned_reviews, spawn_sync_pass, start_relay_client, subscribers, sync_project_engines,
50 tick,
51};
52use crate::github::app;
53use crate::security::secret_ref;
54use crate::store::cluster::local;
55use crate::store::cluster::registry as cluster_registry;
56use crate::sys::home;
57use crate::sys::suspend as engine_suspend;
58use crate::sys::suspend::SuspendDetector;
59use crate::webhook_status::WebhookStatus;
60use std::collections::HashMap;
61use std::collections::HashSet;
62use std::sync::Arc;
63use std::sync::atomic::AtomicBool;
64use std::sync::atomic::AtomicU64;
65use std::sync::atomic::Ordering;
66use std::time as std_time;
67use std::time::Duration;
68use std::time::Instant;
69use std::time::SystemTime;
70use tokio::signal;
71use tokio::signal::unix;
72use tokio::signal::unix::SignalKind;
73use tokio::sync::Mutex;
74use tokio::sync::broadcast::error::RecvError;
75use tokio::sync::mpsc::Receiver;
76use tokio::sync::{Notify, RwLock, Semaphore, mpsc};
77use tokio::task;
78use tokio::time;
79
80async fn report_rate_limited(
83 reset_at: i64,
84 store: Option<&Arc<TaskStore>>,
85 transport: Option<&Arc<Transport>>,
86) {
87 let m = rate_limit_metrics();
88 let until = format_rate_limited_until(reset_at);
89 tracing::warn!(
90 reset_at,
91 rate_limit_hits = m.hits,
92 skipped_calls = m.skipped_calls,
93 five_xx_hits = m.five_xx_hits,
94 rest_remaining = ?m.rest_remaining,
95 graphql_remaining = ?m.graphql_remaining,
96 "GitHub API rate limited until {until} — skipping GitHub calls, local work continues"
97 );
98
99 if let Some(store) = store
100 && let Err(e) = store
101 .kv_set(RATE_LIMITED_UNTIL_KEY, &reset_at.to_string())
102 .await
103 {
104 tracing::warn!(err = %e, "failed to persist GitHub rate-limit flag");
105 }
106
107 if let Some(transport) = transport {
108 transport.push_notification(TaskNotification {
109 task_id: "github".to_string(),
110 title: "GitHub rate limit".to_string(),
111 status: "blocked".to_string(),
112 agent: "orch".to_string(),
113 duration_seconds: 0.0,
114 summary: format!(
115 "rate limited until {until}. GitHub calls are skipped until then; running agents and local work continue."
116 ),
117 repo: None,
118 notify_target: None,
119 pr_number: None,
120 });
121 }
122}
123
124pub(crate) fn resize_dispatch_pool(semaphore: &Semaphore, in_force: usize, target: usize) -> usize {
130 if target > in_force {
131 semaphore.add_permits(target - in_force);
132 return target;
133 }
134
135 if target < in_force {
136 return in_force - semaphore.forget_permits(in_force - target);
137 }
138
139 in_force
140}
141
142pub(crate) const RESTART_ONLY_KEYS: [&str; 3] = ["channels", "webhook", "relay"];
145
146fn restart_only_snapshot() -> Vec<Option<String>> {
148 RESTART_ONLY_KEYS
149 .iter()
150 .map(|key| config::get(key).ok())
151 .collect()
152}
153
154pub(crate) fn log_restart_only_changes(
157 old: &[Option<String>],
158 new: &[Option<String>],
159) -> Vec<&'static str> {
160 let changed: Vec<&'static str> = RESTART_ONLY_KEYS
161 .iter()
162 .zip(old)
163 .zip(new)
164 .filter(|((_, old), new)| old != new)
165 .map(|((key, _), _)| *key)
166 .collect();
167
168 for key in &changed {
169 tracing::info!(key = key, "config changed, takes effect after restart");
170 }
171
172 changed
173}
174
175fn log_engine_config_changes(old: &EngineConfig, new: &EngineConfig) {
178 macro_rules! log_changed {
179 ($($key:literal => $field:ident),+ $(,)?) => {
180 $(if old.$field != new.$field {
181 tracing::info!(key = $key, old = ?old.$field, new = ?new.$field, "config changed");
182 })+
183 };
184 }
185
186 log_changed!(
187 "engine.tick_interval" => tick_interval,
188 "engine.sync_interval" => sync_interval,
189 "engine.webhook_health_check_interval" => webhook_health_check_interval,
190 "engine.max_parallel" => max_parallel,
191 "engine.stuck_timeout" => stuck_timeout,
192 "engine.no_session_stuck_timeout" => no_session_stuck_timeout,
193 "engine.in_review_no_session_stuck_timeout" => in_review_no_session_stuck_timeout,
194 "engine.graceful_shutdown_timeout" => graceful_shutdown_timeout,
195 "engine.silence_grace_period" => silence_grace_period,
196 "engine.silence_cooldown" => silence_cooldown,
197 "engine.upgrade_check_interval" => upgrade_check_interval,
198 "engine.startup_failure_escalation_secs" => startup_failure_escalation_secs,
199 "workflow.auto_create_followup_on_changes" => auto_create_followup_on_changes,
200 );
201}
202
203#[async_trait]
208pub trait WebUi: Send + Sync {
209 async fn start(
210 &self,
211 store: Arc<TaskStore>,
212 events: broadcast::Sender<TaskEvent>,
213 ) -> anyhow::Result<()>;
214
215 async fn stop(&self);
216}
217
218pub async fn serve(web: &dyn WebUi) -> anyhow::Result<()> {
219 let killed = home::prepare_serve(Duration::from_secs(30)).await;
220 if killed > 0 {
221 tracing::info!(count = killed, "terminated stale orch serve processes");
222 }
223
224 tracing::info!("orch engine starting");
225
226 if let Err(e) = config::warm_cache().await {
229 tracing::warn!("failed to warm config cache: {e}");
230 }
231
232 let mut config = EngineConfig::from_config();
233
234 let store = {
237 let mut delay_secs = 5u64;
238 let mut escalated = false;
239 let start = Instant::now();
240 loop {
241 match open_shared_store().await {
242 Ok(store) => break store,
243 Err(e) => {
244 let elapsed = start.elapsed().as_secs();
245 let escalation = config.startup_failure_escalation_secs;
246 if escalation > 0 && !escalated && elapsed >= escalation {
248 escalated = true;
249 tracing::error!(
250 elapsed_secs = elapsed,
251 "the store or the cluster has not started, escalating: {e:#}"
252 );
253 send_startup_escalation_notification(elapsed).await;
254 } else {
255 tracing::warn!(
256 delay_secs,
257 "could not open the store or start the cluster, retrying: {e:#}"
258 );
259 }
260
261 time::sleep(Duration::from_secs(delay_secs)).await;
262 delay_secs = (delay_secs * 2).min(120);
263 }
264 }
265 }
266 };
267
268 engine_cooldown::init_cooldown_store(Arc::clone(&store)).await;
271 tracing::info!("internal database ready");
272
273 let event_bus = events::EventBus::new(256);
275 if let Err(e) = event_bus.start_ws_server().await {
276 tracing::warn!(
277 ?e,
278 "failed to start event websocket server, continuing without it"
279 );
280 }
281
282 if let Err(e) = web.start(Arc::clone(&store), event_bus.sender()).await {
284 tracing::warn!(?e, "failed to start the web UI, continuing without it");
285 }
286
287 let startup_escalation_secs = config.startup_failure_escalation_secs;
296 let mut project_engines = {
297 let mut delay_secs = 5u64;
298 let mut attempt = 0u32;
299 let mut escalated = false;
300 let start = Instant::now();
301 loop {
302 attempt += 1;
303 match init_project_engines(&store).await {
304 Ok(engines) => break engines,
305 Err(e) => {
306 let elapsed = start.elapsed().as_secs();
307
308 if startup_escalation_secs > 0
314 && !escalated
315 && elapsed >= startup_escalation_secs
316 {
317 escalated = true;
318 #[expect(clippy::cast_precision_loss, reason = "a display duration")]
319 let outage = notification::format_duration(elapsed as f64);
320 tracing::error!(
321 delay_secs,
322 attempt,
323 elapsed_secs = elapsed,
324 threshold_secs = startup_escalation_secs,
325 "project backends unavailable for {outage} — escalating startup failure: {e}",
326 );
327 send_startup_escalation_notification(elapsed).await;
331 } else {
332 tracing::warn!(
333 delay_secs,
334 attempt,
335 "project backends unavailable, retrying: {e}"
336 );
337 }
338
339 time::sleep(Duration::from_secs(delay_secs)).await;
340 delay_secs = (delay_secs * 2).min(120);
341 }
342 }
343 }
344 };
345
346 tracing::info!(
347 project_count = project_engines.len(),
348 "initialized project engines"
349 );
350
351 let mut active_repos: HashSet<String> =
355 project_engines.iter().map(|e| e.repo.clone()).collect();
356
357 {
361 let current = env!("ORCH_VERSION").to_string();
362 tokio::spawn(async move {
363 if let Some(latest) = fetch_latest_release_version().await
364 && latest != current
365 {
366 tracing::warn!(
367 current_version = %current,
368 latest_version = %latest,
369 "orch service is behind the latest release — run: brew update && brew upgrade orch && brew services restart orch"
370 );
371 }
372 });
373 }
374
375 for engine in &mut project_engines {
377 engine.task_manager = Arc::new(TaskManager::with_events(
378 Arc::clone(&engine.backend),
379 Arc::clone(&engine.store),
380 engine.repo.clone(),
381 event_bus.sender(),
382 ));
383 }
384
385 let leads = project_engines.first().is_none_or(|e| e.store.is_leader());
387 if leads && let Err(e) = reconcile_startup_worktrees(&project_engines).await {
388 tracing::warn!(err = %e, "startup worktree reconciliation failed");
389 }
390
391 if leads {
392 let engines_snapshot: Vec<ProjectEngine> = project_engines.clone();
396 tokio::spawn(async move {
397 reconcile_startup_estimates(&engines_snapshot).await;
398 });
399 }
400
401 let global_channel_config = GlobalChannelConfig {
403 telegram_general_topic_id: config::get("channels.telegram.general_topic_id").ok(),
404 discord_general_channel_id: config::get("channels.discord.general_channel_id").ok(),
405 control_telegram_topic_id: config::get("control.channels.telegram.topic_id").ok(),
406 control_discord_channel_id: config::get("control.channels.discord.channel_id").ok(),
407 };
408 let project_channel_configs: Vec<(String, ProjectChannelConfig)> = project_engines
409 .iter()
410 .map(|e| {
411 let cfg = read_project_channel_config(&e.project_dir);
412 (e.repo.clone(), cfg)
413 })
414 .collect();
415 let channel_router = Arc::new(ChannelRouter::new(
416 &global_channel_config,
417 &project_channel_configs,
418 ));
419 tracing::info!(
420 projects = ?channel_router.projects(),
421 "channel router initialized"
422 );
423
424 let tmux = Arc::new(TmuxManager::new());
426 tick::startup_cleanup(&tmux).await;
429
430 let transport = Arc::new(Transport::new());
432
433 let capture = Arc::new(CaptureService::new(Arc::clone(&transport)));
435 let capture_for_tick = Arc::clone(&capture);
436 tokio::spawn(async move {
437 capture.start().await;
438 });
439
440 let mut channel_registry = ChannelRegistry::new();
442 let clustered = store.node().is_some();
443 let mut leader_channels = Vec::new();
444
445 if let Ok(token) = secret_ref::config_secret("channels.telegram.bot_token").await
447 && !token.is_empty()
448 {
449 let chat_id = config::get("channels.telegram.chat_id").ok();
450 let allowed_users =
451 config::get_list("channels.telegram.allowed_user_ids").unwrap_or_default();
452 match TelegramChannel::new(token, chat_id).map(|t| t.with_allowed_users(allowed_users)) {
453 Ok(telegram) => {
454 if let Err(e) = telegram.health_check().await {
455 tracing::warn!(?e, "telegram channel health check failed, skipping");
456 } else {
457 channel_registry.register(leader::gate(
458 Box::new(telegram),
459 clustered,
460 &mut leader_channels,
461 ));
462 tracing::info!("telegram channel registered");
463 }
464 }
465 Err(e) => {
466 tracing::warn!(?e, "failed to create telegram channel, skipping");
467 }
468 }
469 }
470
471 if let Ok(token) = secret_ref::config_secret("channels.discord.bot_token").await
473 && !token.is_empty()
474 {
475 let channel_id = config::get("channels.discord.channel_id").ok();
476 let shard_id = config::get("channels.discord.shard_id")
477 .ok()
478 .and_then(|v| v.parse::<u64>().ok())
479 .unwrap_or(0);
480 let shard_count = config::get("channels.discord.shard_count")
481 .ok()
482 .and_then(|v| v.parse::<u64>().ok())
483 .unwrap_or(1);
484 let allowed_users =
485 config::get_list("channels.discord.allowed_user_ids").unwrap_or_default();
486 match DiscordGateway::new(token, channel_id, shard_id, shard_count)
487 .map(|d| d.with_access(channel_router.discord_channel_ids(), allowed_users))
488 {
489 Ok(discord) => {
490 if let Err(e) = discord.health_check().await {
491 tracing::warn!(?e, "discord gateway health check failed, skipping");
492 } else {
493 channel_registry.register(leader::gate(
494 Box::new(discord),
495 clustered,
496 &mut leader_channels,
497 ));
498 tracing::info!(shard_id, shard_count, "discord gateway registered");
499 }
500 }
501 Err(e) => {
502 tracing::warn!(?e, "failed to create discord gateway, skipping");
503 }
504 }
505 }
506
507 if let Ok(token) = secret_ref::config_secret("channels.slack.bot_token").await
509 && !token.is_empty()
510 {
511 let channel_id = config::get("channels.slack.channel_id").ok();
512 let allowed_users = config::get_list("channels.slack.allowed_user_ids").unwrap_or_default();
513 match SlackChannel::new(token, channel_id)
514 .map(|s| s.with_access(channel_router.slack_channel_ids(), allowed_users))
515 {
516 Ok(slack) => {
517 if let Err(e) = slack.health_check().await {
518 tracing::warn!(?e, "slack channel health check failed, skipping");
519 } else {
520 channel_registry.register(leader::gate(
521 Box::new(slack),
522 clustered,
523 &mut leader_channels,
524 ));
525 tracing::info!("slack channel registered");
526 }
527 }
528 Err(e) => {
529 tracing::warn!(?e, "failed to create slack channel, skipping");
530 }
531 }
532 }
533
534 let tmux_channel = TmuxChannel::with_transport(Arc::clone(&transport));
536 channel_registry.register(Box::new(tmux_channel));
537 tracing::info!("tmux channel registered");
538
539 let mut channel_receivers: Vec<Receiver<IncomingMessage>> = Vec::new();
541 for channel in channel_registry.iter() {
542 match channel.start().await {
543 Ok(rx) => {
544 tracing::info!(channel = channel.name(), "channel started");
545 channel_receivers.push(rx);
546 }
547 Err(e) => {
548 tracing::warn!(channel = channel.name(), ?e, "failed to start channel");
549 }
550 }
551 }
552
553 if !leader_channels.is_empty() {
554 let store = Arc::clone(&store);
555 tokio::spawn(leader::follow_leader(
556 leader_channels,
557 move || store.is_leader(),
558 LEADER_CHECK_INTERVAL,
559 ));
560 }
561
562 let channel_registry = Arc::new(channel_registry);
564
565 let transport_for_messages = Arc::clone(&transport);
567 let tmux_for_messages = Arc::clone(&tmux);
568 let capture_for_messages = Arc::clone(&capture_for_tick);
569 let channels_for_messages = Arc::clone(&channel_registry);
570 let engine_refs: Vec<EngineRef> = project_engines
572 .iter()
573 .map(|e| {
574 (
575 e.repo.clone(),
576 Arc::clone(&e.backend),
577 Arc::clone(&e.task_manager),
578 Some(Arc::clone(&e.store)),
579 )
580 })
581 .collect();
582 let pending_picks: channel_handler::PendingPicks = Arc::new(Mutex::new(HashMap::new()));
584 let router_for_messages = Arc::clone(&channel_router);
585 for mut rx in channel_receivers {
586 let transport = Arc::clone(&transport_for_messages);
587 let tmux = Arc::clone(&tmux_for_messages);
588 let capture = Arc::clone(&capture_for_messages);
589 let channels = Arc::clone(&channels_for_messages);
590 let engine_refs = engine_refs.clone();
591 let ch_router = Arc::clone(&router_for_messages);
592 let picks = Arc::clone(&pending_picks);
593 tokio::spawn(async move {
594 while let Some(msg) = rx.recv().await {
595 tracing::debug!(channel = %msg.channel, thread = %msg.thread_id, "received message from channel");
596 channel_handler::handle_channel_message(
597 msg,
598 &transport,
599 &tmux,
600 &capture,
601 &channels,
602 &engine_refs,
603 &ch_router,
604 &picks,
605 )
606 .await;
607 }
608 });
609 }
610
611 {
615 let restart_channels = Arc::clone(&channel_registry);
616 let restart_store = Some(Arc::clone(&store));
617 if let Some(store) = restart_store {
618 tokio::spawn(async move {
619 time::sleep(Duration::from_secs(5)).await;
620 match store.kv_get("control:restart_pending").await {
621 Ok(Some(conv_key)) => {
622 if let Some((ch_name, thread_id, topic_id)) =
623 transport::parse_conversation_key(&conv_key)
624 {
625 for ch in restart_channels.iter() {
626 if ch.name() == ch_name {
627 let msg = OutgoingMessage {
628 thread_id: thread_id.to_string(),
629 body: "orch restarted successfully.".to_string(),
630 reply_to: None,
631 metadata: serde_json::json!({}),
632 topic_id: topic_id.map(ToString::to_string),
633 };
634 if let Err(e) = ch.send(&msg).await {
635 tracing::warn!(
636 channel = ch_name,
637 error = %e,
638 "failed to send restart confirmation"
639 );
640 }
641 break;
642 }
643 }
644 }
645 if let Err(e) = store.kv_delete("control:restart_pending").await {
646 tracing::warn!(error = %e, "failed to clear control:restart_pending");
647 }
648 }
649 Ok(None) => {} Err(e) => {
651 tracing::warn!(error = %e, "failed to read control:restart_pending");
652 }
653 }
654 });
655 }
656 }
657
658 {
669 let mut notification_rx = transport.subscribe_notifications();
670 let channels = Arc::clone(&channel_registry);
671 let notif_router = Arc::clone(&channel_router);
672 let notif_store: Option<Arc<TaskStore>> = Some(Arc::clone(&store));
674 tokio::spawn(async move {
675 loop {
676 match notification_rx.recv().await {
677 Ok(notification) => {
678 let level = NotificationLevel::from_config();
679 if !level.should_notify(¬ification.status) {
680 tracing::debug!(
681 task_id = %notification.task_id,
682 status = %notification.status,
683 "notification suppressed by level={:?}",
684 level
685 );
686 continue;
687 }
688
689 tracing::info!(
690 task_id = %notification.task_id,
691 status = %notification.status,
692 repo = ?notification.repo,
693 "routing notification to channels"
694 );
695
696 let mut routed = false;
698
699 if let Some(ref target) = notification.notify_target {
702 let telegram = channels.iter().find(|c| c.name() == "telegram");
703 if let Some(channel) = telegram {
704 let body = notification.format_telegram();
705 let metadata = serde_json::json!({
706 "preformatted_html": true,
707 "chat_id_override": target
708 });
709 let msg = OutgoingMessage {
710 thread_id: notification.task_id.clone(),
711 body,
712 reply_to: None,
713 metadata,
714 topic_id: None,
715 };
716 match channel.send(&msg).await {
717 Err(e) => {
718 tracing::warn!(
719 task_id = %notification.task_id,
720 target,
721 ?e,
722 "failed to send to notify_target"
723 );
724 }
725 _ => {
726 routed = true;
727 }
728 }
729 }
730 }
731
732 if routed {
733 } else if let Some(repo) = notification.repo.as_deref() {
735 let mut sent: HashSet<(String, Option<String>)> = HashSet::new();
741
742 for channel in channels.iter() {
744 let ch_name = channel.name();
745 if let Some(topic_id) =
746 notif_router.target_for_project(repo, ch_name)
747 {
748 let body = match ch_name {
749 "telegram" => notification.format_telegram(),
750 "discord" => notification.format_discord(),
751 "slack" => notification.format_slack(),
752 _ => continue,
753 };
754 let metadata = if ch_name == "telegram" {
755 serde_json::json!({"preformatted_html": true})
756 } else {
757 serde_json::json!({})
758 };
759 let resolved_topic = Some(topic_id.to_string());
760 let msg = OutgoingMessage {
761 thread_id: notification.task_id.clone(),
762 body,
763 reply_to: None,
764 metadata,
765 topic_id: resolved_topic.clone(),
766 };
767 if let Err(e) = channel.send(&msg).await {
768 tracing::warn!(
769 channel = ch_name,
770 task_id = %notification.task_id,
771 ?e,
772 "failed to send to dedicated channel"
773 );
774 } else {
775 sent.insert((ch_name.to_string(), resolved_topic));
776 routed = true;
777 }
778 }
779 }
780
781 if let Some(store) = ¬if_store {
783 match store.list_subscribers_for_repo(repo).await {
784 Ok(subscribers) => {
785 for (ch_name, thread_id, topic_id) in subscribers {
786 let channel =
787 channels.iter().find(|c| c.name() == ch_name);
788 let Some(channel) = channel else {
789 continue;
790 };
791 let resolved_topic = if topic_id.is_empty() {
792 None
793 } else {
794 Some(topic_id.clone())
795 };
796 if sent.contains(&(
799 ch_name.clone(),
800 resolved_topic.clone(),
801 )) {
802 tracing::debug!(
803 channel = %ch_name,
804 task_id = %notification.task_id,
805 topic_id = ?resolved_topic,
806 "skipping duplicate subscriber dispatch — destination already received from dedicated path"
807 );
808 continue;
809 }
810 let body = notification.format_with_project(&ch_name);
811 let metadata = if ch_name == "telegram" {
812 serde_json::json!({"preformatted_html": true})
813 } else {
814 serde_json::json!({})
815 };
816 let msg = OutgoingMessage {
817 thread_id: thread_id.clone(),
818 body,
819 reply_to: None,
820 metadata,
821 topic_id: resolved_topic.clone(),
822 };
823 if let Err(e) = channel.send(&msg).await {
824 tracing::warn!(
825 channel = %ch_name,
826 task_id = %notification.task_id,
827 ?e,
828 "failed to send to subscribed channel"
829 );
830 } else {
831 sent.insert((ch_name.clone(), resolved_topic));
832 routed = true;
833 }
834 }
835 }
836 Err(e) => {
837 tracing::warn!(
838 repo,
839 ?e,
840 "failed to list subscribers for repo"
841 );
842 }
843 }
844 }
845 }
846
847 if !routed {
849 for channel in channels.iter() {
850 let (body, should_send, is_telegram) = match channel.name() {
851 "telegram" => (notification.format_telegram(), true, true),
852 "discord" => (notification.format_discord(), true, false),
853 "slack" => (notification.format_slack(), true, false),
854 _ => (String::new(), false, false),
857 };
858
859 if !should_send {
860 continue;
861 }
862
863 let metadata = if is_telegram {
864 serde_json::json!({"preformatted_html": true})
865 } else {
866 serde_json::json!({})
867 };
868 let msg = OutgoingMessage {
869 thread_id: notification.task_id.clone(),
870 body,
871 reply_to: None,
872 metadata,
873 topic_id: None,
874 };
875
876 if let Err(e) = channel.send(&msg).await {
877 tracing::warn!(
878 channel = channel.name(),
879 task_id = %notification.task_id,
880 ?e,
881 "failed to send notification"
882 );
883 }
884 }
885 }
886 }
887 Err(RecvError::Lagged(n)) => {
888 tracing::warn!(missed = n, "notification receiver lagged");
889 }
890 Err(RecvError::Closed) => {
891 tracing::debug!("notification channel closed");
892 break;
893 }
894 }
895 }
896 });
897 tracing::info!("notification dispatcher started");
898 }
899
900 let webhook_notify = Arc::new(Notify::new());
902
903 let webhook_port: Option<u16>;
906 let mut webhook_healthy: bool;
907 let mut last_webhook_health_check = Instant::now();
908 let webhook_enabled = config::get_global("webhook.enabled").is_ok_and(|v| v == "true");
910 let webhook_secret = if webhook_enabled {
912 secret_ref::config_secret("webhook.secret")
913 .await
914 .ok()
915 .filter(|s| !s.trim().is_empty())
916 } else {
917 None
918 };
919 if webhook_enabled && webhook_secret.is_none() {
920 tracing::error!(
921 "webhook.enabled needs a readable webhook.secret, the webhook server stays off"
922 );
923 }
924 let webhook_enabled = webhook_enabled && webhook_secret.is_some();
925 let webhook_secret = webhook_secret.unwrap_or_default();
926
927 let webhook_status = Arc::new(Mutex::new(WebhookStatus::default()));
929
930 if webhook_enabled {
931 const WEBHOOK_MAX_ATTEMPTS: u32 = 5;
935 let port: u16 = config::get("webhook.port")
936 .ok()
937 .and_then(|v| v.parse().ok())
938 .unwrap_or(8080);
939 webhook_port = Some(port);
940 let secret = webhook_secret.clone();
941 let webhook_repo = project_engines
942 .first()
943 .map(|e| e.repo.clone())
944 .unwrap_or_default();
945
946 let (tx, mut rx) = mpsc::channel::<IncomingMessage>(64);
947
948 let to_save = {
950 let mut s = webhook_status.lock().await;
951 s.configured = true;
952 s.port = Some(port);
953 s.healthy = false;
954 s.fallback_mode = false;
955 s.clone()
956 };
957 to_save.save().await;
958
959 let status_for_spawn = Arc::clone(&webhook_status);
960 tokio::spawn(async move {
961 let mut attempt = 0u32;
962 loop {
963 attempt += 1;
964 tracing::info!(attempt, port, "attempting to start webhook server");
965 match start_webhook_server(port, secret.clone(), webhook_repo.clone(), tx.clone())
966 .await
967 {
968 Ok(()) => {
969 tracing::info!(attempt, "webhook server exited cleanly");
970 break;
971 }
972 Err(e) => {
973 let reason = e.to_string();
974 tracing::error!(attempt, %reason, "webhook server failed");
975 if attempt >= WEBHOOK_MAX_ATTEMPTS || !is_transient_bind_error(&e) {
976 let kind = if attempt >= WEBHOOK_MAX_ATTEMPTS {
977 "max attempts reached"
978 } else {
979 "non-transient error"
980 };
981 tracing::error!(
982 attempt,
983 %reason,
984 kind,
985 orch_webhook_in_fallback = true,
986 "webhook server giving up, switching to polling fallback"
987 );
988 let to_save = {
989 let mut s = status_for_spawn.lock().await;
990 s.fallback_mode = true;
991 s.healthy = false;
992 s.last_failure_reason = Some(reason);
993 s.startup_attempts = attempt;
994 s.clone()
995 };
996 to_save.save().await;
997 break;
998 }
999 let delay = webhook_backoff_delay(attempt);
1000 tracing::warn!(
1001 attempt,
1002 delay_ms = delay.as_millis(),
1003 %reason,
1004 "webhook bind failed (transient), retrying with backoff"
1005 );
1006 {
1007 let to_save = {
1008 let mut s = status_for_spawn.lock().await;
1009 s.startup_attempts = attempt;
1010 s.last_failure_reason = Some(reason);
1011 s.clone()
1012 };
1013 to_save.save().await;
1014 }
1015 time::sleep(delay).await;
1016 }
1017 }
1018 }
1019 });
1020
1021 let notify = Arc::clone(&webhook_notify);
1023 let transport_for_webhook = Arc::clone(&transport);
1024 tokio::spawn(async move {
1025 while let Some(msg) = rx.recv().await {
1026 tracing::info!(
1027 channel = %msg.channel,
1028 thread = %msg.thread_id,
1029 event = %msg.metadata.get("event").and_then(|v| v.as_str()).unwrap_or("unknown"),
1030 action = %msg.metadata.get("action").and_then(|v| v.as_str()).unwrap_or("unknown"),
1031 "webhook event received, triggering immediate tick"
1032 );
1033 let route = transport_for_webhook.route(&msg).await;
1034 tracing::info!(
1035 channel = %msg.channel,
1036 route = ?route,
1037 "webhook event routed"
1038 );
1039 notify.notify_one();
1041 }
1042 });
1043
1044 webhook_healthy = true;
1045 tracing::info!(port, orch_webhook_up = true, "webhook server started");
1046 } else {
1047 webhook_port = None;
1048 webhook_healthy = false;
1049 {
1050 let to_save = {
1051 let mut s = webhook_status.lock().await;
1052 s.configured = false;
1053 s.fallback_mode = true;
1054 s.clone()
1055 };
1056 to_save.save().await;
1057 }
1058 tracing::info!(
1059 orch_webhook_in_fallback = true,
1060 "webhook server disabled, using polling fallback mode"
1061 );
1062 }
1063
1064 start_relay_client(&store, &webhook_notify);
1065 app::start_loader();
1066
1067 let router = Arc::new(RwLock::new(
1071 match task::spawn_blocking(Router::from_config).await {
1072 Ok(r) => r,
1073 Err(e) => {
1074 tracing::error!(?e, "router init panicked in spawn_blocking, using default");
1075 task::spawn_blocking(|| Router::new(RouterConfig::default()))
1076 .await
1077 .unwrap_or_else(|e2| {
1078 panic!("router default init also panicked in spawn_blocking — cannot start engine without a router: {e2:?}");
1079 })
1080 }
1081 },
1082 ));
1083 {
1084 let r = router.read().await;
1085 tracing::info!(
1086 mode = %r.config.mode,
1087 agents = ?r.available_agents,
1088 fallback = %r.config.fallback_executor,
1089 "router initialized"
1090 );
1091 }
1092
1093 let semaphore = Arc::new(Semaphore::new(config.max_parallel));
1097 let mut parallel_in_force = config.max_parallel;
1098 let review_semaphore = Arc::new(Semaphore::new(config.max_parallel));
1101 let mut review_in_force = config.max_parallel;
1102
1103 let dispatching: Arc<dashmap::DashMap<String, String>> = Arc::new(dashmap::DashMap::new());
1110
1111 let auto_merge_in_flight: Arc<dashmap::DashSet<String>> = Arc::new(dashmap::DashSet::new());
1115
1116 let mut config_rx = config::subscribe();
1118
1119 let mut last_sync = Instant::now();
1121
1122 let mut last_upgrade_check: Option<Instant> = None;
1124
1125 let mut rate_limit_reported: Option<i64> = None;
1128
1129 let (weight_tx, mut weight_rx) = mpsc::channel::<WeightSignal>(64);
1131
1132 for engine in project_engines.iter().filter(|_| leads) {
1134 let reset =
1135 reset_orphaned_reviews(&engine.task_manager, &engine.store, &engine.repo, &tmux).await;
1136
1137 if reset > 0 {
1138 tracing::info!(repo = %engine.repo, reset, "reset orphaned reviews to needs_review on startup");
1139 }
1140 }
1141
1142 for engine in &project_engines {
1144 subscribers::dispatch::spawn(
1145 event_bus.subscribe(),
1146 Arc::clone(&engine.backend),
1147 Arc::clone(&tmux),
1148 Arc::clone(&engine.runner),
1149 Arc::clone(&capture_for_tick),
1150 Arc::clone(&semaphore),
1151 Arc::clone(&engine.task_manager),
1152 weight_tx.clone(),
1153 Arc::clone(&router),
1154 Arc::clone(&dispatching),
1155 Arc::clone(&engine.store),
1156 engine.repo.clone(),
1157 );
1158 }
1159 tracing::info!("dispatch subscriber started");
1160
1161 for engine in &project_engines {
1163 subscribers::review::spawn(
1164 event_bus.subscribe(),
1165 Arc::clone(&engine.backend),
1166 Arc::clone(&tmux),
1167 Arc::clone(&review_semaphore),
1168 Arc::clone(&engine.task_manager),
1169 Arc::clone(&router),
1170 Arc::clone(&dispatching),
1171 Arc::clone(&engine.store),
1172 engine.repo.clone(),
1173 );
1174 }
1175 tracing::info!("review subscriber started");
1176
1177 for engine in &project_engines {
1179 subscribers::unblock::spawn(
1180 event_bus.subscribe(),
1181 Arc::clone(&engine.backend),
1182 Arc::clone(&engine.task_manager),
1183 Arc::clone(&engine.store),
1184 engine.repo.clone(),
1185 );
1186 }
1187 tracing::info!("unblock subscriber started");
1188
1189 subscribers::notify::spawn(event_bus.subscribe(), Arc::clone(&transport));
1192 tracing::info!("notify subscriber started");
1193
1194 tracing::info!(
1196 tick = ?config.tick_interval,
1197 sync = ?config.sync_interval,
1198 parallel = config.max_parallel,
1199 "entering main loop"
1200 );
1201 let mut restart_only = restart_only_snapshot();
1204
1205 let mut interval = time::interval(config.tick_interval);
1206
1207 let mut sigterm = unix::signal(SignalKind::terminate())?;
1209 let mut sighup = unix::signal(SignalKind::hangup())?;
1210
1211 let sync_in_progress = Arc::new(AtomicBool::new(false));
1213
1214 let last_tick_epoch = Arc::new(AtomicU64::new(
1217 SystemTime::now()
1218 .duration_since(std_time::UNIX_EPOCH)
1219 .unwrap_or_default()
1220 .as_secs(),
1221 ));
1222 {
1223 let last_tick_epoch = Arc::clone(&last_tick_epoch);
1224 let tick_interval_secs = config.tick_interval_secs();
1225 tokio::spawn(async move {
1226 let mut watchdog_interval = time::interval(Duration::from_secs(30));
1228 let mut suspend_detector = SuspendDetector::new();
1233 loop {
1234 watchdog_interval.tick().await;
1235 let last = last_tick_epoch.load(Ordering::Relaxed);
1236 let now = SystemTime::now()
1237 .duration_since(std_time::UNIX_EPOCH)
1238 .unwrap_or_default()
1239 .as_secs();
1240 let stale_secs = now.saturating_sub(last);
1241 let threshold = (tick_interval_secs * 6).max(60);
1243 let gap = suspend_detector.gap_within(Duration::from_secs(stale_secs));
1245 if stale_secs > threshold {
1246 if let Some(gap) = gap {
1253 let gap_secs = u64::try_from(gap.num_seconds()).unwrap_or(0);
1254 if gap_secs >= stale_secs {
1255 tracing::info!(
1256 stale_secs,
1257 threshold,
1258 suspend_gap_secs = gap_secs,
1259 "tick loop stale window explained by host suspend/resume, not a stall"
1260 );
1261 } else {
1262 tracing::error!(
1263 stale_secs,
1264 threshold,
1265 suspend_gap_secs = gap_secs,
1266 "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — suspend gap of {}s only partially explains the stall",
1267 stale_secs,
1268 threshold,
1269 gap_secs,
1270 );
1271 }
1272 } else {
1273 tracing::error!(
1274 stale_secs,
1275 threshold,
1276 "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — possible stall",
1277 stale_secs,
1278 threshold,
1279 );
1280 }
1281 }
1282 }
1283 });
1284 }
1285
1286 let mut registry_written: Option<Instant> = None;
1288
1289 loop {
1290 tokio::select! {
1291 _ = interval.tick() => {
1292 let tick_start = Instant::now();
1293
1294 if clustered && registry_written.is_none_or(|at| at.elapsed() >= cluster_registry::HEARTBEAT) {
1295 registry_written = Some(Instant::now());
1296 registry::publish(&store, &active_repos, &router, config.max_parallel).await;
1297 }
1298
1299 if let Some(gap) = engine_suspend::checkpoint() {
1303 tracing::info!(
1304 gap_secs = gap.num_seconds(),
1305 "host suspend/resume gap detected, discounting from stuck-task age checks"
1306 );
1307 }
1308
1309 if review_in_force != config.max_parallel {
1313 review_in_force =
1314 resize_dispatch_pool(&review_semaphore, review_in_force, config.max_parallel);
1315 }
1316 if parallel_in_force != config.max_parallel {
1317 let resized =
1318 resize_dispatch_pool(&semaphore, parallel_in_force, config.max_parallel);
1319 if resized != parallel_in_force {
1320 parallel_in_force = resized;
1321 tracing::info!(
1322 in_force = parallel_in_force,
1323 target = config.max_parallel,
1324 "dispatch pool resized"
1325 );
1326 }
1327 }
1328
1329 {
1331 let mut rw = router.write().await;
1332 rw.tick_weight_recovery();
1333 }
1334
1335 if let Some(remaining) = GhHttp::is_rate_limited() {
1339 let reset_at = chrono::Utc::now()
1340 .timestamp()
1341 .saturating_add(i64::try_from(remaining.as_secs()).unwrap_or(i64::MAX));
1342 if rate_limit_reported.is_none_or(|prev| (reset_at - prev).abs() > 60) {
1344 rate_limit_reported = Some(reset_at);
1345 report_rate_limited(reset_at, Some(&store), Some(&transport)).await;
1346 }
1347 } else if let Some(prev) = rate_limit_reported.take() {
1348 tracing::info!(
1349 limited_until = prev,
1350 "GitHub API rate limit cleared"
1351 );
1352 let _ = store.kv_delete(RATE_LIMITED_UNTIL_KEY).await;
1353 }
1354
1355 tick::tick_all(
1357 &project_engines,
1358 &tmux,
1359 &capture_for_tick,
1360 &semaphore,
1361 &config,
1362 &router,
1363 &weight_tx,
1364 &dispatching,
1365 Some(&transport),
1366 &active_repos,
1367 &auto_merge_in_flight,
1368 ).await;
1369
1370 tick::worker::run_assigned(
1372 &project_engines,
1373 tick::worker::Worker {
1374 tmux: &tmux,
1375 capture: &capture_for_tick,
1376 semaphore: &semaphore,
1377 review_semaphore: &review_semaphore,
1378 router: &router,
1379 weight_tx: &weight_tx,
1380 dispatching: &dispatching,
1381 },
1382 ).await;
1383
1384 while let Ok(signal) = weight_rx.try_recv() {
1387 let mut rw = router.write().await;
1388 match signal {
1389 WeightSignal::RateLimited { ref agent } => {
1390 rw.record_rate_limit(agent);
1391 }
1392 WeightSignal::Success { ref agent } => {
1393 rw.record_success(agent);
1394 }
1395 WeightSignal::Failed { .. }
1396 | WeightSignal::Rerouted
1397 | WeightSignal::Blocked
1398 | WeightSignal::None => {}
1399 }
1400 }
1401
1402 if last_sync.elapsed() >= config.sync_interval {
1407 if sync_in_progress.compare_exchange(
1408 false,
1409 true,
1410 Ordering::AcqRel,
1411 Ordering::Relaxed,
1412 ).is_ok() {
1413 spawn_sync_pass(
1414 &project_engines,
1415 &tmux,
1416 &config,
1417 &router,
1418 &dispatching,
1419 &auto_merge_in_flight,
1420 &sync_in_progress,
1421 "periodic",
1422 );
1423 } else {
1424 tracing::debug!("sync tick still in progress, skipping");
1425 }
1426 last_sync = Instant::now();
1430 }
1431
1432 if webhook_enabled {
1434 let health_check_interval = config.webhook_health_check_interval();
1435
1436 if last_webhook_health_check.elapsed() >= health_check_interval {
1437 if let Some(port) = webhook_port {
1438 let (health, failure_reason) =
1439 github::check_webhook_health(port).await;
1440 if health != webhook_healthy {
1441 webhook_healthy = health;
1442 if webhook_healthy {
1443 tracing::info!(port, orch_webhook_up = true, "webhook health restored");
1444 } else {
1445 tracing::warn!(
1446 port,
1447 orch_webhook_up = false,
1448 reason = failure_reason.as_deref().unwrap_or("unknown"),
1449 "webhook health check failed"
1450 );
1451 }
1452 }
1453 {
1455 let to_save = {
1456 let mut s = webhook_status.lock().await;
1457 s.healthy = health;
1458 s.last_check_utc = Some(chrono::Utc::now());
1459 if health {
1460 s.last_failure_reason = None;
1461 } else if failure_reason.is_some() {
1462 s.last_failure_reason = failure_reason;
1463 }
1464 s.clone()
1465 };
1466 to_save.save().await;
1467 }
1468 }
1469 last_webhook_health_check = Instant::now();
1470 }
1471 }
1472
1473 if should_run_upgrade_check(last_upgrade_check, config.upgrade_check_interval) {
1475 let store = Arc::clone(&store);
1476 let channels = Arc::clone(&channel_registry);
1477 let current = env!("ORCH_VERSION").to_string();
1478 let check_interval = Duration::from_secs(config.upgrade_check_interval);
1479 tokio::spawn(async move {
1480 check_and_notify_upgrade(&store, &channels, ¤t, check_interval)
1481 .await;
1482 });
1483 last_upgrade_check = Some(Instant::now());
1484 }
1485
1486 let tick_elapsed = tick_start.elapsed();
1488 if tick_elapsed.as_secs() > 30 {
1489 tracing::warn!(
1490 elapsed_ms = u64::try_from(tick_elapsed.as_millis()).unwrap_or(u64::MAX),
1491 "slow tick"
1492 );
1493 } else {
1494 tracing::debug!(
1495 elapsed_ms = u64::try_from(tick_elapsed.as_millis()).unwrap_or(u64::MAX),
1496 "tick complete"
1497 );
1498 }
1499 last_tick_epoch.store(
1500 SystemTime::now()
1501 .duration_since(std_time::UNIX_EPOCH)
1502 .unwrap_or_default()
1503 .as_secs(),
1504 Ordering::Relaxed,
1505 );
1506 }
1507 () = webhook_notify.notified() => {
1509 if let Some(remaining) = GhHttp::is_rate_limited() {
1510 tracing::warn!(
1511 remaining_secs = remaining.as_secs(),
1512 "GitHub API rate-limited, skipping webhook-triggered tick"
1513 );
1514 } else {
1515 tracing::info!("webhook event triggered immediate tick");
1516
1517 tick::tick_all(
1518 &project_engines,
1519 &tmux,
1520 &capture_for_tick,
1521 &semaphore,
1522 &config,
1523 &router,
1524 &weight_tx,
1525 &dispatching,
1526 Some(&transport),
1527 &active_repos,
1528 &auto_merge_in_flight,
1529 ).await;
1530
1531 while let Ok(signal) = weight_rx.try_recv() {
1533 let mut rw = router.write().await;
1534 match signal {
1535 WeightSignal::RateLimited { ref agent } => {
1536 rw.record_rate_limit(agent);
1537 }
1538 WeightSignal::Success { ref agent } => {
1539 rw.record_success(agent);
1540 }
1541 WeightSignal::Failed { .. }
1542 | WeightSignal::Rerouted
1543 | WeightSignal::Blocked
1544 | WeightSignal::None => {}
1545 }
1546 }
1547
1548 if sync_in_progress.compare_exchange(
1554 false,
1555 true,
1556 Ordering::AcqRel,
1557 Ordering::Relaxed,
1558 ).is_ok() {
1559 spawn_sync_pass(
1560 &project_engines,
1561 &tmux,
1562 &config,
1563 &router,
1564 &dispatching,
1565 &auto_merge_in_flight,
1566 &sync_in_progress,
1567 "webhook",
1568 );
1569 last_sync = Instant::now();
1571 } else {
1572 tracing::debug!("sync tick still in progress, skipping webhook-triggered immediate sync");
1573 }
1574 }
1575
1576 interval.reset();
1578 }
1579 result = config_rx.recv() => {
1580 let reload = match result {
1583 Ok(path) => {
1584 tracing::info!(path = %path.display(), "config file changed, reloading");
1585 true
1586 }
1587 Err(RecvError::Lagged(n)) => {
1588 tracing::warn!(missed = n, "config change receiver lagged, reloading");
1589 true
1590 }
1591 Err(RecvError::Closed) => {
1592 tracing::warn!("config change channel closed");
1593 false
1594 }
1595 };
1596
1597 if reload {
1598 let new_config = EngineConfig::from_config();
1600 log_engine_config_changes(&config, &new_config);
1601
1602 let new_restart_only = restart_only_snapshot();
1603 log_restart_only_changes(&restart_only, &new_restart_only);
1604 restart_only = new_restart_only;
1605
1606 let tick_changed = new_config.tick_interval != config.tick_interval;
1607 config = new_config;
1608
1609 if tick_changed {
1611 interval = time::interval(config.tick_interval);
1612 tracing::info!(tick = ?config.tick_interval, "tick interval updated");
1613 }
1614
1615 if review_in_force != config.max_parallel {
1618 review_in_force = resize_dispatch_pool(
1619 &review_semaphore,
1620 review_in_force,
1621 config.max_parallel,
1622 );
1623 }
1624 if parallel_in_force != config.max_parallel {
1625 parallel_in_force = resize_dispatch_pool(
1626 &semaphore,
1627 parallel_in_force,
1628 config.max_parallel,
1629 );
1630 tracing::info!(
1631 in_force = parallel_in_force,
1632 target = config.max_parallel,
1633 "dispatch pool resized"
1634 );
1635 }
1636
1637 {
1639 let mut router_guard = router.write().await;
1640 router_guard.reload_async().await;
1641 }
1642
1643 sync_project_engines(
1645 &store,
1646 &mut project_engines,
1647 &mut active_repos,
1648 &event_bus,
1649 &tmux,
1650 &capture_for_tick,
1651 &semaphore,
1652 &review_semaphore,
1653 &weight_tx,
1654 &router,
1655 &dispatching,
1656 ).await;
1657
1658 registry_written = None;
1660
1661 tracing::info!(
1662 tick = ?config.tick_interval,
1663 sync = ?config.sync_interval,
1664 parallel = config.max_parallel,
1665 projects = project_engines.len(),
1666 "config reloaded"
1667 );
1668 }
1669 }
1670 signal_name = async {
1671 tokio::select! {
1672 _ = signal::ctrl_c() => "SIGINT",
1673 _ = sigterm.recv() => "SIGTERM",
1674 _ = sighup.recv() => "SIGHUP",
1675 }
1676 } => {
1677 tracing::info!(signal = signal_name, "beginning graceful shutdown");
1678
1679 let shutdown_result = time::timeout(
1682 config.graceful_shutdown_timeout,
1683 async {
1684 let mut reset_count = 0u32;
1688 let mut review_reset_count = 0u32;
1689 for engine in &project_engines {
1690 if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InProgress).await {
1691 for task in &tasks {
1692 if engine.store.runs_elsewhere_by_ref(&engine.repo, &task.id.0).await {
1694 continue;
1695 }
1696 if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::Routed).await {
1697 tracing::warn!(task_id = task.id.0, ?e, "failed to reset task on shutdown");
1698 } else {
1699 if let Ok(Some(store_id)) =
1700 engine.store.resolve_task_id(&engine.repo, &task.id.0).await
1701 && let Err(e) = engine
1702 .store
1703 .finalize_incomplete_runs(
1704 store_id,
1705 "aborted",
1706 "graceful shutdown: reset in_progress task to routed",
1707 )
1708 .await
1709 {
1710 tracing::warn!(
1711 task_id = task.id.0,
1712 ?e,
1713 "failed to finalize incomplete runs on shutdown"
1714 );
1715 }
1716 reset_count += 1;
1717 }
1718 }
1719 }
1720 if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, TaskStatus::InProgress).await {
1722 for task in tasks.iter().filter(|t| !engine.store.runs_elsewhere(t)) {
1723 let task_id = format!("internal:{}", task.id);
1724 if let Err(e) = engine.task_manager.update_task_status(
1725 &ExternalId(task_id.clone()),
1726 Status::Routed,
1727 ).await {
1728 tracing::warn!(task_id, ?e, "failed to reset internal task on shutdown");
1729 } else {
1730 if let Err(e) = engine
1731 .store
1732 .finalize_incomplete_runs(
1733 task.id,
1734 "aborted",
1735 "graceful shutdown: reset in_progress task to routed",
1736 )
1737 .await
1738 {
1739 tracing::warn!(
1740 task_id,
1741 ?e,
1742 "failed to finalize incomplete internal runs on shutdown"
1743 );
1744 }
1745 reset_count += 1;
1746 }
1747 }
1748 }
1749 if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InReview).await {
1751 for task in &tasks {
1752 if engine.store.runs_elsewhere_by_ref(&engine.repo, &task.id.0).await {
1753 continue;
1754 }
1755 if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::NeedsReview).await {
1756 tracing::warn!(task_id = task.id.0, ?e, "failed to reset in_review task on shutdown");
1757 } else {
1758 if let Ok(Some(store_id)) =
1759 engine.store.resolve_task_id(&engine.repo, &task.id.0).await
1760 && let Err(e) = engine
1761 .store
1762 .finalize_incomplete_runs(
1763 store_id,
1764 "aborted",
1765 "graceful shutdown: reset in_review task to needs_review",
1766 )
1767 .await
1768 {
1769 tracing::warn!(
1770 task_id = task.id.0,
1771 ?e,
1772 "failed to finalize incomplete review runs on shutdown"
1773 );
1774 }
1775 review_reset_count += 1;
1776 }
1777 }
1778 }
1779 if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, TaskStatus::InReview).await {
1781 for task in tasks.iter().filter(|t| !engine.store.runs_elsewhere(t)) {
1782 let task_id = format!("internal:{}", task.id);
1783 if let Err(e) = engine.task_manager.update_task_status(
1784 &ExternalId(task_id.clone()),
1785 Status::NeedsReview,
1786 ).await {
1787 tracing::warn!(task_id, ?e, "failed to reset internal in_review task on shutdown");
1788 } else {
1789 if let Err(e) = engine
1790 .store
1791 .finalize_incomplete_runs(
1792 task.id,
1793 "aborted",
1794 "graceful shutdown: reset in_review task to needs_review",
1795 )
1796 .await
1797 {
1798 tracing::warn!(
1799 task_id,
1800 ?e,
1801 "failed to finalize incomplete internal review runs on shutdown"
1802 );
1803 }
1804 review_reset_count += 1;
1805 }
1806 }
1807 }
1808 }
1809 if reset_count > 0 {
1810 tracing::info!(reset_count, "reset in_progress tasks to routed for re-dispatch");
1811 }
1812 if review_reset_count > 0 {
1813 tracing::info!(review_reset_count, "reset in_review tasks to needs_review for re-dispatch");
1814 }
1815
1816 let mut killed_sessions = Vec::new();
1819 if let Ok(sessions) = tmux.list_sessions().await {
1820 for session in &sessions {
1821 if session.name.starts_with("orch-") {
1822 match tmux.kill_session(&session.name).await { Err(e) => {
1823 tracing::warn!(session = %session.name, error = %e, "failed to kill tmux session");
1824 } _ => {
1825 killed_sessions.push(session.name.clone());
1826 }}
1827 }
1828 }
1829 if !killed_sessions.is_empty() {
1830 tracing::info!(killed = killed_sessions.len(), "killing orch tmux sessions on shutdown");
1831 }
1832 }
1833
1834 if !killed_sessions.is_empty() {
1837 let still_alive = tmux
1838 .wait_for_sessions_dead(
1839 &killed_sessions,
1840 Duration::from_millis(100),
1841 Duration::from_secs(5),
1842 )
1843 .await;
1844 if still_alive > 0 {
1845 tracing::warn!(
1846 still_alive,
1847 "some tmux sessions did not terminate cleanly - they will be cleaned up on startup"
1848 );
1849 }
1850 tracing::info!(killed = killed_sessions.len() - still_alive, "confirmed tmux sessions terminated");
1851 }
1852 },
1853 ).await;
1854
1855 if shutdown_result.is_err() {
1856 tracing::error!(
1857 timeout_secs = config.graceful_shutdown_secs(),
1858 "graceful shutdown timed out, forcing exit"
1859 );
1860 }
1861
1862 break;
1863 }
1864 }
1865 }
1866
1867 events::cleanup_port_file().await;
1869 local::cleanup().await;
1870 web.stop().await;
1871 events::cleanup_version_file();
1872
1873 let _ = transport;
1875 tracing::info!("orch engine stopped");
1876 Ok(())
1877}