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