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