1pub mod auto_merge;
16pub mod channel_handler;
17pub mod cleanup;
18pub mod commands;
19pub mod cooldown;
20pub mod dependencies;
21pub mod dispatch_guard;
22pub mod events;
23pub mod jobs;
24pub mod relay;
25pub mod review;
26pub mod review_poll;
27pub mod router;
28pub mod runner;
29pub mod subscribers;
30pub mod suspend;
31pub mod sync;
32pub mod tasks;
33pub mod tick;
34
35pub fn orch_footer() -> &'static str {
40 "\n\n---\n*Posted by [Orch](https://github.com/gabrielkoerich/orch)*"
41}
42
43pub fn attribution_footer(verb: &str, agent: &str, model: Option<&str>) -> String {
47 match model {
48 Some(m) => format!(
49 "\n\n---\n*{} by {}[bot] via [Orch](https://github.com/gabrielkoerich/orch) using `{}`*",
50 verb, agent, m
51 ),
52 None => format!(
53 "\n\n---\n*{} by {}[bot] via [Orch](https://github.com/gabrielkoerich/orch)*",
54 verb, agent
55 ),
56 }
57}
58
59use crate::backends::{ExternalBackend, ExternalId};
60use crate::channels::capture::CaptureService;
61use crate::channels::discord_ws::DiscordGateway;
62use crate::channels::github::start_webhook_server;
63use crate::channels::notification::NotificationLevel;
64use crate::channels::routing::{ChannelRouter, GlobalChannelConfig, ProjectChannelConfig};
65use crate::channels::slack::SlackChannel;
66use crate::channels::telegram::TelegramChannel;
67use crate::channels::tmux::TmuxChannel;
68use crate::channels::transport::Transport;
69use crate::channels::{Channel, ChannelRegistry, IncomingMessage, OutgoingMessage};
70use crate::cmd::CommandErrorContext;
71use crate::config;
72use crate::engine::cleanup::remove_worktree_and_branch;
73use crate::engine::router::{Router, RouterConfig};
74use crate::engine::runner::worktree::{
75 abort_worktree_rebase, list_project_worktrees, rebase_worktree_on_origin_main,
76 task_id_from_worktree_name, validate_worktree_gitdir,
77};
78use crate::engine::tasks::TaskManager;
79use crate::github::http::{rate_limit_metrics, GhHttp};
80use crate::repo_context::REPO_CONTEXT;
81use crate::store::{TaskStatus, TaskStore};
82use crate::tmux::TmuxManager;
83use runner::WeightSignal;
84use std::sync::Arc;
86use tokio::process::Command;
87use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
88
89use crate::backends::Status;
90
91type EngineRef = (
93 String,
94 Arc<dyn ExternalBackend>,
95 Arc<TaskManager>,
96 Option<Arc<TaskStore>>,
97);
98
99#[derive(Clone)]
104pub struct ProjectEngine {
105 pub repo: String,
106 pub project_dir: std::path::PathBuf,
107 pub backend: Arc<dyn ExternalBackend>,
108 pub task_manager: Arc<TaskManager>,
109 pub runner: Arc<runner::TaskRunner>,
110 pub store: Arc<TaskStore>,
111}
112
113pub(crate) async fn reset_orphaned_reviews(
116 task_manager: &TaskManager,
117 store: &Arc<TaskStore>,
118 repo: &str,
119 tmux: &TmuxManager,
120) -> usize {
121 let mut ids: Vec<ExternalId> = store
123 .list_by_status(repo, crate::store::TaskStatus::InReview)
124 .await
125 .unwrap_or_default()
126 .iter()
127 .map(|t| crate::engine::tasks::store_task_to_external(t).id)
128 .collect();
129 if let Ok(legacy) = task_manager
130 .list_internal_by_status(crate::store::TaskStatus::InReview)
131 .await
132 {
133 ids.extend(legacy.into_iter().map(|t| t.id));
134 }
135 ids.sort_by(|a, b| a.0.cmp(&b.0));
136 ids.dedup_by(|a, b| a.0 == b.0);
137
138 let mut reset = 0;
139 for id in &ids {
140 let session = tmux.session_name(repo, &format!("{}-review", id.0));
141
142 if tmux.session_exists(&session).await {
143 continue;
144 }
145
146 if let Err(e) = task_manager
147 .update_task_status(id, Status::NeedsReview)
148 .await
149 {
150 tracing::warn!(
151 task_id = id.0,
152 ?e,
153 "failed to reset an orphaned review at start"
154 );
155 continue;
156 }
157
158 if let Ok(Some(store_id)) = store.resolve_task_id(repo, &id.0).await {
159 let reason = "startup: review session gone, reset to needs_review";
160
161 if let Err(e) = store
162 .finalize_incomplete_runs(store_id, "aborted", reason)
163 .await
164 {
165 tracing::warn!(
166 task_id = id.0,
167 ?e,
168 "failed to finalize the orphaned review's runs"
169 );
170 }
171 }
172
173 reset += 1;
174 }
175
176 reset
177}
178
179fn start_relay_client(project_engines: &[ProjectEngine], notify: &Arc<Notify>) {
182 let url = crate::config::get("relay.url").unwrap_or_default();
183 let Some(store) = project_engines.first().map(|e| Arc::clone(&e.store)) else {
184 return;
185 };
186
187 if url.is_empty() {
188 return;
189 }
190
191 let token_ref = crate::config::get("relay.token").unwrap_or_default();
192 let notify = Arc::clone(notify);
193 tokio::spawn(async move {
194 let mut warned = false;
195 let token = loop {
196 let reference = token_ref.clone();
197 let read = tokio::task::spawn_blocking(move || crate::secret_ref::resolve(&reference))
198 .await
199 .map_err(anyhow::Error::from)
200 .and_then(|r| r);
201
202 match read {
203 Ok(token) if !token.is_empty() => break token,
204 Ok(_) => {
205 tracing::warn!("relay.token is empty, the relay client stays off");
206 return;
207 }
208 Err(e) if !warned => {
209 tracing::warn!(err = %e, "could not read relay.token, retrying every 5 minutes");
210 warned = true;
211 }
212 Err(_) => {}
213 }
214
215 tokio::time::sleep(std::time::Duration::from_secs(300)).await;
216 };
217
218 relay::run(url, token, store, notify).await;
219 });
220}
221
222#[allow(clippy::too_many_arguments)]
228fn spawn_sync_pass(
229 project_engines: &[ProjectEngine],
230 tmux: &Arc<TmuxManager>,
231 engine_config: &EngineConfig,
232 router: &Arc<RwLock<Router>>,
233 dispatching: &Arc<dashmap::DashMap<String, String>>,
234 auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
235 sync_in_progress: &Arc<std::sync::atomic::AtomicBool>,
236 trigger: &'static str,
237) {
238 let engines = project_engines.to_vec();
239 let tmux = Arc::clone(tmux);
240 let engine_config = engine_config.clone();
241 let router = Arc::clone(router);
242 let dispatching = Arc::clone(dispatching);
243 let auto_merge_in_flight = Arc::clone(auto_merge_in_flight);
244 let guard = Arc::clone(sync_in_progress);
245
246 tokio::spawn(async move {
247 let started = std::time::Instant::now();
248 let mut passes = Vec::with_capacity(engines.len());
249 for engine in &engines {
250 passes.push(REPO_CONTEXT.scope(
251 engine.repo.clone(),
252 sync_one_project(
253 engine,
254 &tmux,
255 &engine_config,
256 &router,
257 &dispatching,
258 &auto_merge_in_flight,
259 ),
260 ));
261 }
262 futures::future::join_all(passes).await;
263
264 sync::sync_shared_tail(&router, engines.first().map(|e| &e.store)).await;
265 tracing::info!(
266 trigger,
267 elapsed_ms = started.elapsed().as_millis() as u64,
268 "sync tick complete"
269 );
270 guard.store(false, std::sync::atomic::Ordering::Release);
271 });
272}
273
274async fn sync_one_project(
275 engine: &ProjectEngine,
276 tmux: &Arc<TmuxManager>,
277 engine_config: &EngineConfig,
278 router: &Arc<RwLock<Router>>,
279 dispatching: &Arc<dashmap::DashMap<String, String>>,
280 auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
281) {
282 if let Err(e) = sync::sync_tick(
283 &engine.backend,
284 tmux,
285 &engine.repo,
286 engine_config,
287 router,
288 &engine.task_manager,
289 &engine.store,
290 dispatching,
291 auto_merge_in_flight,
292 )
293 .await
294 {
295 tracing::error!(repo = %engine.repo, ?e, "sync tick failed for project");
296 }
297}
298
299const SLOW_PHASE_GROUP_MS: u128 = 1_000;
301
302pub(crate) fn log_phase_timings(group: &str, repo: &str, phases: &[(&str, u128)]) {
308 let total_ms: u128 = phases.iter().map(|(_, ms)| ms).sum();
309 if total_ms >= SLOW_PHASE_GROUP_MS {
310 tracing::info!(group, repo, total_ms, ?phases, "phase timings");
311 } else {
312 tracing::debug!(group, repo, total_ms, ?phases, "phase timings");
313 }
314}
315
316pub fn configured_agents() -> Vec<String> {
328 if let Ok(agents_str) = crate::config::get("agents") {
329 if !agents_str.is_empty() && agents_str != "[]" {
330 if let Ok(agents_arr) = serde_norway::from_str::<Vec<String>>(&agents_str) {
333 if !agents_arr.is_empty() {
334 return agents_arr;
335 }
336 }
337 if let Ok(agents_arr) = serde_json::from_str::<Vec<String>>(&agents_str) {
339 if !agents_arr.is_empty() {
340 return agents_arr;
341 }
342 }
343 }
344 }
345 router::config::DEFAULT_AGENTS
346 .iter()
347 .map(|s| s.to_string())
348 .collect()
349}
350
351#[derive(Clone)]
353pub struct EngineConfig {
354 pub tick_interval: std::time::Duration,
356 pub sync_interval: std::time::Duration,
358 pub webhook_health_check_interval: Option<std::time::Duration>,
360 pub max_parallel: usize,
362 pub stuck_timeout: u64,
364 pub no_session_stuck_timeout: u64,
367 pub in_review_no_session_stuck_timeout: u64,
374 pub auto_create_followup_on_changes: bool,
376 pub graceful_shutdown_timeout: std::time::Duration,
378 pub silence_grace_period: u64,
381 pub silence_cooldown: u64,
383 pub upgrade_check_interval: u64,
386 pub startup_failure_escalation_secs: u64,
391}
392
393impl Default for EngineConfig {
394 fn default() -> Self {
395 Self {
396 tick_interval: std::time::Duration::from_secs(10),
397 sync_interval: std::time::Duration::from_secs(45),
398 webhook_health_check_interval: Some(std::time::Duration::from_secs(60)),
399 max_parallel: 4,
400 stuck_timeout: 1800,
401 no_session_stuck_timeout: 600,
402 in_review_no_session_stuck_timeout: 1920,
403 auto_create_followup_on_changes: true,
404 graceful_shutdown_timeout: std::time::Duration::from_secs(600),
405 silence_grace_period: 300,
406 silence_cooldown: 3600,
407 upgrade_check_interval: 3600,
408 startup_failure_escalation_secs: 3600,
409 }
410 }
411}
412
413impl EngineConfig {
414 pub fn from_config() -> Self {
416 let mut config = Self::default();
417
418 if let Ok(val) = crate::config::get("engine.tick_interval") {
419 if let Ok(secs) = val.parse::<u64>() {
420 config.tick_interval = std::time::Duration::from_secs(secs);
421 } else {
422 tracing::warn!(key = "engine.tick_interval", value = %val, default_secs = config.tick_interval.as_secs(), "invalid value for engine.tick_interval, using default");
423 }
424 }
425
426 if let Ok(val) = crate::config::get("engine.sync_interval") {
427 if let Ok(secs) = val.parse::<u64>() {
428 config.sync_interval = std::time::Duration::from_secs(secs);
429 } else {
430 tracing::warn!(key = "engine.sync_interval", value = %val, default_secs = config.sync_interval.as_secs(), "invalid value for engine.sync_interval, using default");
431 }
432 }
433
434 if let Ok(val) = crate::config::get("engine.max_parallel") {
435 if let Ok(n) = val.parse::<usize>() {
436 config.max_parallel = n;
437 } else {
438 tracing::warn!(key = "engine.max_parallel", value = %val, default = config.max_parallel, "invalid value for engine.max_parallel, using default");
439 }
440 }
441
442 if let Ok(val) = crate::config::get("engine.stuck_timeout") {
443 if let Ok(secs) = val.parse::<u64>() {
444 config.stuck_timeout = secs;
445 } else {
446 tracing::warn!(key = "engine.stuck_timeout", value = %val, default_secs = config.stuck_timeout, "invalid value for engine.stuck_timeout, using default");
447 }
448 }
449
450 if let Ok(val) = crate::config::get("engine.no_session_stuck_timeout") {
451 if let Ok(secs) = val.parse::<u64>() {
452 config.no_session_stuck_timeout = secs;
453 } else {
454 tracing::warn!(key = "engine.no_session_stuck_timeout", value = %val, default_secs = config.no_session_stuck_timeout, "invalid value for engine.no_session_stuck_timeout, using default");
455 }
456 }
457
458 let mut in_review_from_config = false;
459 if let Ok(val) = crate::config::get("engine.in_review_no_session_stuck_timeout") {
460 if let Ok(secs) = val.parse::<u64>() {
461 config.in_review_no_session_stuck_timeout = secs;
462 in_review_from_config = true;
463 } else {
464 tracing::warn!(key = "engine.in_review_no_session_stuck_timeout", value = %val, default_secs = config.in_review_no_session_stuck_timeout, "invalid value for engine.in_review_no_session_stuck_timeout, using default");
465 }
466 }
467
468 let review_timeout = crate::engine::review::review_timeout_seconds();
472 let floored = crate::engine::review::no_session_review_floor(
473 config.in_review_no_session_stuck_timeout,
474 review_timeout,
475 );
476 if floored != config.in_review_no_session_stuck_timeout {
477 if in_review_from_config {
478 tracing::warn!(
479 configured_secs = config.in_review_no_session_stuck_timeout,
480 review_timeout_secs = review_timeout,
481 raised_to_secs = floored,
482 "engine.in_review_no_session_stuck_timeout is below the review timeout plus result delivery time, raising it"
483 );
484 } else {
485 tracing::debug!(
486 review_timeout_secs = review_timeout,
487 raised_to_secs = floored,
488 "raised the default in_review no-session limit over a long review timeout"
489 );
490 }
491 config.in_review_no_session_stuck_timeout = floored;
492 }
493
494 if let Ok(val) = crate::config::get("engine.webhook_health_check_interval") {
495 if let Ok(secs) = val.parse::<u64>() {
496 if secs > 0 {
497 config.webhook_health_check_interval =
498 Some(std::time::Duration::from_secs(secs));
499 } else {
500 config.webhook_health_check_interval = None;
501 }
502 } else {
503 tracing::warn!(key = "engine.webhook_health_check_interval", value = %val, default = ?config.webhook_health_check_interval, "invalid value for engine.webhook_health_check_interval, using default");
504 }
505 }
506
507 if let Ok(val) = crate::config::get("workflow.auto_create_followup_on_changes") {
508 config.auto_create_followup_on_changes = !val.eq_ignore_ascii_case("false");
509 }
510
511 if let Ok(val) = crate::config::get("engine.graceful_shutdown_timeout") {
512 if let Ok(secs) = val.parse::<u64>() {
513 config.graceful_shutdown_timeout = std::time::Duration::from_secs(secs);
514 } else {
515 tracing::warn!(key = "engine.graceful_shutdown_timeout", value = %val, default_secs = config.graceful_shutdown_timeout.as_secs(), "invalid value for engine.graceful_shutdown_timeout, using default");
516 }
517 }
518
519 if let Ok(val) = crate::config::get("engine.silence_grace_period") {
520 if let Ok(secs) = val.parse::<u64>() {
521 config.silence_grace_period = secs;
522 } else {
523 tracing::warn!(key = "engine.silence_grace_period", value = %val, default = config.silence_grace_period, "invalid value for engine.silence_grace_period, using default");
524 }
525 }
526
527 if let Ok(val) = crate::config::get("engine.silence_cooldown") {
528 if let Ok(secs) = val.parse::<u64>() {
529 config.silence_cooldown = secs;
530 } else {
531 tracing::warn!(key = "engine.silence_cooldown", value = %val, default = config.silence_cooldown, "invalid value for engine.silence_cooldown, using default");
532 }
533 }
534
535 if let Ok(val) = crate::config::get("engine.upgrade_check_interval") {
536 if let Ok(secs) = val.parse::<u64>() {
537 config.upgrade_check_interval = secs;
538 } else {
539 tracing::warn!(key = "engine.upgrade_check_interval", value = %val, default = config.upgrade_check_interval, "invalid value for engine.upgrade_check_interval, using default");
540 }
541 }
542
543 if let Ok(val) = crate::config::get("engine.startup_failure_escalation_secs") {
544 if let Ok(secs) = val.parse::<u64>() {
545 config.startup_failure_escalation_secs = secs;
546 } else {
547 tracing::warn!(
548 key = "engine.startup_failure_escalation_secs",
549 value = %val,
550 default_secs = config.startup_failure_escalation_secs,
551 "invalid value for engine.startup_failure_escalation_secs, using default"
552 );
553 }
554 }
555
556 config
557 }
558}
559
560pub const RATE_LIMITED_UNTIL_KEY: &str = "github:rate_limited_until";
563
564pub fn format_rate_limited_until(reset_at: i64) -> String {
566 chrono::DateTime::from_timestamp(reset_at, 0)
567 .map(|t| {
568 t.with_timezone(&chrono::Local)
569 .format("%H:%M:%S %Z")
570 .to_string()
571 })
572 .unwrap_or_else(|| reset_at.to_string())
573}
574
575async fn report_rate_limited(
578 reset_at: i64,
579 store: Option<&Arc<TaskStore>>,
580 transport: Option<&Arc<crate::channels::transport::Transport>>,
581) {
582 let m = rate_limit_metrics();
583 let until = format_rate_limited_until(reset_at);
584 tracing::warn!(
585 reset_at,
586 rate_limit_hits = m.hits,
587 skipped_calls = m.skipped_calls,
588 five_xx_hits = m.five_xx_hits,
589 rest_remaining = ?m.rest_remaining,
590 graphql_remaining = ?m.graphql_remaining,
591 "GitHub API rate limited until {until} — skipping GitHub calls, local work continues"
592 );
593
594 if let Some(store) = store {
595 if let Err(e) = store
596 .kv_set(RATE_LIMITED_UNTIL_KEY, &reset_at.to_string())
597 .await
598 {
599 tracing::warn!(err = %e, "failed to persist GitHub rate-limit flag");
600 }
601 }
602
603 if let Some(transport) = transport {
604 transport.push_notification(crate::channels::notification::TaskNotification {
605 task_id: "github".to_string(),
606 title: "GitHub rate limit".to_string(),
607 status: "blocked".to_string(),
608 agent: "orch".to_string(),
609 duration_seconds: 0.0,
610 summary: format!(
611 "rate limited until {until}. GitHub calls are skipped until then; running agents and local work continue."
612 ),
613 repo: None,
614 notify_target: None,
615 pr_number: None,
616 });
617 }
618}
619
620fn resize_dispatch_pool(semaphore: &Semaphore, in_force: usize, target: usize) -> usize {
626 if target > in_force {
627 semaphore.add_permits(target - in_force);
628 return target;
629 }
630
631 if target < in_force {
632 return in_force - semaphore.forget_permits(in_force - target);
633 }
634
635 in_force
636}
637
638const RESTART_ONLY_KEYS: [&str; 3] = ["channels", "webhook", "relay"];
641
642fn restart_only_snapshot() -> Vec<Option<String>> {
644 RESTART_ONLY_KEYS
645 .iter()
646 .map(|key| crate::config::get(key).ok())
647 .collect()
648}
649
650fn log_restart_only_changes(old: &[Option<String>], new: &[Option<String>]) -> Vec<&'static str> {
653 let changed: Vec<&'static str> = RESTART_ONLY_KEYS
654 .iter()
655 .zip(old)
656 .zip(new)
657 .filter(|((_, old), new)| old != new)
658 .map(|((key, _), _)| *key)
659 .collect();
660
661 for key in &changed {
662 tracing::info!(key = key, "config changed, takes effect after restart");
663 }
664
665 changed
666}
667
668fn log_engine_config_changes(old: &EngineConfig, new: &EngineConfig) {
671 macro_rules! log_changed {
672 ($($key:literal => $field:ident),+ $(,)?) => {
673 $(if old.$field != new.$field {
674 tracing::info!(key = $key, old = ?old.$field, new = ?new.$field, "config changed");
675 })+
676 };
677 }
678
679 log_changed!(
680 "engine.tick_interval" => tick_interval,
681 "engine.sync_interval" => sync_interval,
682 "engine.webhook_health_check_interval" => webhook_health_check_interval,
683 "engine.max_parallel" => max_parallel,
684 "engine.stuck_timeout" => stuck_timeout,
685 "engine.no_session_stuck_timeout" => no_session_stuck_timeout,
686 "engine.in_review_no_session_stuck_timeout" => in_review_no_session_stuck_timeout,
687 "engine.graceful_shutdown_timeout" => graceful_shutdown_timeout,
688 "engine.silence_grace_period" => silence_grace_period,
689 "engine.silence_cooldown" => silence_cooldown,
690 "engine.upgrade_check_interval" => upgrade_check_interval,
691 "engine.startup_failure_escalation_secs" => startup_failure_escalation_secs,
692 "workflow.auto_create_followup_on_changes" => auto_create_followup_on_changes,
693 );
694}
695
696fn should_run_upgrade_check(
697 last_upgrade_check: Option<std::time::Instant>,
698 upgrade_check_interval: u64,
699) -> bool {
700 if upgrade_check_interval == 0 {
701 return false;
702 }
703
704 last_upgrade_check
705 .map(|last| last.elapsed() >= std::time::Duration::from_secs(upgrade_check_interval))
706 .unwrap_or(true)
707}
708
709async fn connect_project_engine(
716 repo: String,
717 project_dir: std::path::PathBuf,
718 store: Arc<TaskStore>,
719 event_tx: Option<tokio::sync::broadcast::Sender<events::TaskEvent>>,
720) -> anyhow::Result<ProjectEngine> {
721 let backend: Arc<dyn ExternalBackend> =
722 Arc::new(crate::backends::github::GitHubBackend::new(repo.clone())?);
723
724 match backend.health_check().await {
728 Ok(()) => tracing::info!(repo = %repo, backend = backend.name(), "backend connected"),
729 Err(e) => tracing::warn!(
730 repo = %repo,
731 error = %e,
732 "GitHub health check failed for {repo}, starting engine anyway (rate limited, offline or bad credentials?)"
733 ),
734 }
735
736 let task_manager = Arc::new(match event_tx {
737 Some(tx) => TaskManager::with_events(backend.clone(), store.clone(), repo.clone(), tx),
738 None => TaskManager::with_store(backend.clone(), store.clone(), repo.clone()),
739 });
740 let runner = Arc::new(runner::TaskRunner::new(repo.clone()).with_store(store.clone()));
741
742 Ok(ProjectEngine {
743 repo,
744 project_dir,
745 backend,
746 task_manager,
747 runner,
748 store,
749 })
750}
751
752fn diff_configured_projects(
759 configured: &[(String, std::path::PathBuf)],
760 active_repos: &std::collections::HashSet<String>,
761) -> (Vec<(String, std::path::PathBuf)>, Vec<String>) {
762 let configured_repos: std::collections::HashSet<&str> =
763 configured.iter().map(|(r, _)| r.as_str()).collect();
764
765 let added = configured
766 .iter()
767 .filter(|(repo, _)| !active_repos.contains(repo))
768 .cloned()
769 .collect();
770 let removed = active_repos
771 .iter()
772 .filter(|repo| !configured_repos.contains(repo.as_str()))
773 .cloned()
774 .collect();
775
776 (added, removed)
777}
778
779#[allow(clippy::too_many_arguments)]
785async fn sync_project_engines(
786 project_engines: &mut Vec<ProjectEngine>,
787 active_repos: &mut std::collections::HashSet<String>,
788 event_bus: &events::EventBus,
789 tmux: &Arc<TmuxManager>,
790 capture: &Arc<CaptureService>,
791 semaphore: &Arc<Semaphore>,
792 weight_tx: &mpsc::Sender<WeightSignal>,
793 router: &Arc<RwLock<Router>>,
794 dispatching: &Arc<dashmap::DashMap<String, String>>,
795) {
796 let configured = match config::get_projects_with_paths() {
797 Ok(p) if !p.is_empty() => p,
798 Ok(_) => return,
799 Err(e) => {
800 tracing::warn!(err = %e, "could not re-read the project list, keeping the current one");
801 return;
802 }
803 };
804 let Some(store) = project_engines.first().map(|e| e.store.clone()) else {
805 return;
806 };
807
808 let (added, removed) = diff_configured_projects(&configured, active_repos);
809 for repo in removed {
810 tracing::info!(
811 repo = %repo,
812 "project removed from config, takes effect after restart"
813 );
814 }
815
816 for (repo, project_dir) in added {
817 config::watch(&project_dir.join(".orch.yml"));
818 let engine = match connect_project_engine(
819 repo.clone(),
820 project_dir,
821 store.clone(),
822 Some(event_bus.sender()),
823 )
824 .await
825 {
826 Ok(engine) => engine,
827 Err(e) => {
828 tracing::warn!(
831 repo = %repo,
832 err = %e,
833 "project added to config but its backend could not be built, retrying on the next config change"
834 );
835 continue;
836 }
837 };
838
839 subscribers::dispatch::spawn(
840 event_bus.subscribe(),
841 engine.backend.clone(),
842 tmux.clone(),
843 engine.runner.clone(),
844 capture.clone(),
845 semaphore.clone(),
846 engine.task_manager.clone(),
847 weight_tx.clone(),
848 router.clone(),
849 dispatching.clone(),
850 engine.store.clone(),
851 engine.repo.clone(),
852 );
853 subscribers::review::spawn(
854 event_bus.subscribe(),
855 engine.backend.clone(),
856 tmux.clone(),
857 semaphore.clone(),
858 engine.task_manager.clone(),
859 router.clone(),
860 dispatching.clone(),
861 engine.store.clone(),
862 engine.repo.clone(),
863 );
864 subscribers::unblock::spawn(
865 event_bus.subscribe(),
866 engine.backend.clone(),
867 engine.task_manager.clone(),
868 engine.store.clone(),
869 engine.repo.clone(),
870 );
871
872 active_repos.insert(repo.clone());
873 project_engines.push(engine);
874 tracing::info!(repo = %repo, "project added from config, now syncing");
875 }
876}
877
878async fn init_project_engines() -> anyhow::Result<Vec<ProjectEngine>> {
882 let projects = config::get_projects_with_paths()?;
883 let repos: Vec<&str> = projects.iter().map(|(r, _)| r.as_str()).collect();
884 tracing::info!(repos = ?repos, "loading projects from config");
885
886 if projects.is_empty() {
887 let config_path = crate::home::config_path()
888 .map(|p| p.display().to_string())
889 .unwrap_or_else(|_| "~/.orch/config.yml".to_string());
890 anyhow::bail!(
891 "no projects configured — add repos under `projects:` in {}",
892 config_path
893 );
894 }
895
896 let mut engines = Vec::new();
897
898 let store = Arc::new(TaskStore::open(&crate::store::default_db_path().await?).await?);
901 if crate::cluster::enabled() {
902 crate::cluster::start(&store, &crate::home::orch_home()?.join("raft.db")).await?;
903 crate::cluster::local::serve((*store).clone()).await?;
904 }
905
906 crate::engine::cooldown::init_cooldown_store(store.clone()).await;
909
910 for (repo, project_dir) in projects {
911 tracing::info!(repo = %repo, "initializing project engine");
912 config::watch(&project_dir.join(".orch.yml"));
913
914 engines.push(connect_project_engine(repo, project_dir, store.clone(), None).await?);
915 }
916
917 Ok(engines)
918}
919
920async fn reconcile_startup_worktrees(project_engines: &[ProjectEngine]) -> anyhow::Result<()> {
921 for engine in project_engines {
922 let repo_root =
923 crate::engine::runner::worktree::resolve_main_repo(&engine.project_dir).await;
924 let repo_root_path = std::path::PathBuf::from(&repo_root);
925 let default_branch =
926 crate::engine::runner::worktree::detect_default_branch(&repo_root_path).await;
927 let worktrees = list_project_worktrees(&repo_root_path).await?;
928
929 if let Err(e) = Command::new("git")
932 .args(["-C", &repo_root.to_string_lossy(), "fetch", "origin"])
933 .output_with_context()
934 .await
935 {
936 tracing::warn!(repo = %engine.repo, err = %e, "startup git fetch origin failed, rebases may use stale refs");
937 }
938
939 let mut orphans_removed: u32 = 0;
940 let mut invalid_removed: u32 = 0;
941 let mut cleaned: u32 = 0;
942 let mut valid_kept: u32 = 0;
943
944 for worktree_dir in worktrees {
945 let Some(name) = worktree_dir.file_name().and_then(|n| n.to_str()) else {
946 continue;
947 };
948
949 if !validate_worktree_gitdir(&worktree_dir).await {
952 tracing::warn!(repo = %engine.repo, worktree = %worktree_dir.display(), "worktree has invalid or missing gitdir, removing");
953 remove_worktree_and_branch(name, &worktree_dir, Some(name), &repo_root_path, false)
954 .await;
955 invalid_removed += 1;
956 continue;
957 }
958
959 let Some(task_id) = task_id_from_worktree_name(name) else {
960 tracing::info!(repo = %engine.repo, worktree = %worktree_dir.display(), "orphan worktree without task id, removing");
961 remove_worktree_and_branch(name, &worktree_dir, Some(name), &repo_root_path, false)
962 .await;
963 orphans_removed += 1;
964 continue;
965 };
966
967 let Some(store_id) = engine.store.resolve_task_id(&engine.repo, &task_id).await? else {
968 tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), "worktree has no matching task, removing");
969 remove_worktree_and_branch(
970 &task_id,
971 &worktree_dir,
972 Some(name),
973 &repo_root_path,
974 false,
975 )
976 .await;
977 orphans_removed += 1;
978 continue;
979 };
980
981 let task = engine.store.get(store_id).await?;
982 let branch_name = if task.branch.is_empty() {
983 name
984 } else {
985 task.branch.as_str()
986 };
987
988 match task.status {
989 TaskStatus::New
990 | TaskStatus::Routed
991 | TaskStatus::InProgress
992 | TaskStatus::NeedsReview
993 | TaskStatus::InReview => {
994 tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), "rebasing startup worktree");
995 if let Err(e) =
996 rebase_worktree_on_origin_main(&worktree_dir, &default_branch).await
997 {
998 tracing::warn!(repo = %engine.repo, task_id = %task_id, err = %e, "startup rebase failed, resetting task");
1003 abort_worktree_rebase(&worktree_dir).await;
1004 let keep_remote = task.pr_number.is_some();
1005 remove_worktree_and_branch(
1006 &task_id,
1007 &worktree_dir,
1008 Some(branch_name),
1009 &repo_root_path,
1010 keep_remote,
1011 )
1012 .await;
1013 match engine.store.resolve_task_id(&engine.repo, &task_id).await {
1014 Ok(Some(reset_id)) => {
1015 if let Err(e) = engine.store.reset_to_new(reset_id).await {
1016 tracing::warn!(task_id, err = %e, "failed to reset task to new after rebase failure");
1017 }
1018 }
1019 Ok(None) => {
1020 tracing::warn!(
1021 task_id,
1022 "task not found in store during reconciliation"
1023 );
1024 }
1025 Err(e) => {
1026 tracing::warn!(task_id, err = %e, "failed to resolve task ID during reconciliation");
1027 }
1028 }
1029 if let Err(e) = engine
1030 .task_manager
1031 .update_task_status(
1032 &ExternalId(task_id.clone()),
1033 crate::backends::Status::New,
1034 )
1035 .await
1036 {
1037 tracing::warn!(task_id, err = %e, "failed to update backend status during reconciliation");
1038 }
1039 cleaned += 1;
1040 } else {
1041 valid_kept += 1;
1042 }
1043 }
1044 TaskStatus::Blocked | TaskStatus::Waiting => {
1047 valid_kept += 1;
1048 }
1049 TaskStatus::Done => {
1050 tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), status = ?task.status, "terminal task worktree, removing");
1051 remove_worktree_and_branch(
1052 &task_id,
1053 &worktree_dir,
1054 Some(branch_name),
1055 &repo_root_path,
1056 false,
1057 )
1058 .await;
1059 cleaned += 1;
1060 }
1061 }
1062 }
1063
1064 tracing::info!(
1065 repo = %engine.repo,
1066 orphans_removed,
1067 invalid_removed,
1068 cleaned,
1069 valid_kept,
1070 "worktree reconciliation: {orphans_removed} orphans removed, {invalid_removed} invalid removed, {cleaned} cleaned, {valid_kept} valid kept"
1071 );
1072
1073 let prune = Command::new("git")
1076 .args(["-C", &repo_root.to_string_lossy(), "worktree", "prune"])
1077 .output_with_context()
1078 .await;
1079 match prune {
1080 Ok(output) if output.status.success() => {
1081 tracing::debug!(repo = %engine.repo, "startup worktree prune completed");
1082 }
1083 Ok(output) => {
1084 let stderr = String::from_utf8_lossy(&output.stderr);
1085 tracing::warn!(repo = %engine.repo, err = %stderr, "startup worktree prune failed");
1086 }
1087 Err(e) => {
1088 tracing::warn!(repo = %engine.repo, err = %e, "startup worktree prune failed");
1089 }
1090 }
1091 }
1092
1093 Ok(())
1094}
1095
1096async fn reconcile_startup_estimates(project_engines: &[ProjectEngine]) {
1104 use crate::backends::ExternalId;
1105
1106 for engine in project_engines {
1107 let tasks = match engine.store.list_external_tasks_with_estimates().await {
1108 Ok(t) => t,
1109 Err(e) => {
1110 tracing::warn!(repo = %engine.repo, err = %e, "startup estimate reconciliation: store query failed");
1111 continue;
1112 }
1113 };
1114
1115 if tasks.is_empty() {
1116 continue;
1117 }
1118
1119 let mut synced: u32 = 0;
1120 let mut failed: u32 = 0;
1121 for (external_id, estimate) in &tasks {
1122 match engine
1123 .backend
1124 .sync_estimate_to_project(&ExternalId(external_id.clone()), *estimate)
1125 .await
1126 {
1127 Ok(()) => synced += 1,
1128 Err(e) => {
1129 tracing::debug!(
1130 repo = %engine.repo,
1131 task_id = %external_id,
1132 estimate,
1133 err = %e,
1134 "startup estimate reconciliation: sync failed"
1135 );
1136 failed += 1;
1137 }
1138 }
1139 }
1140
1141 if synced > 0 || failed > 0 {
1142 tracing::info!(
1143 repo = %engine.repo,
1144 synced,
1145 failed,
1146 "startup estimate reconciliation complete"
1147 );
1148 }
1149 }
1150}
1151
1152fn read_project_channel_config(project_dir: &std::path::Path) -> ProjectChannelConfig {
1154 let config_path = project_dir.join(".orch.yml");
1155 if !config_path.exists() {
1156 return ProjectChannelConfig::default();
1157 }
1158 let content = match std::fs::read_to_string(&config_path) {
1159 Ok(c) => c,
1160 Err(e) => {
1161 tracing::warn!(
1162 path = %config_path.display(),
1163 error = %e,
1164 "failed to read .orch.yml; channel config will use defaults"
1165 );
1166 return ProjectChannelConfig::default();
1167 }
1168 };
1169 let val: serde_norway::Value = match serde_norway::from_str(&content) {
1170 Ok(v) => v,
1171 Err(e) => {
1172 tracing::warn!(
1173 path = %config_path.display(),
1174 error = %e,
1175 "failed to parse .orch.yml; channel config will use defaults"
1176 );
1177 return ProjectChannelConfig::default();
1178 }
1179 };
1180 let channels = match val.get("channels") {
1181 Some(c) => c,
1182 None => return ProjectChannelConfig::default(),
1183 };
1184 let get_str = |section: &str, key: &str| -> Option<String> {
1185 channels
1186 .get(section)
1187 .and_then(|s| s.get(key))
1188 .and_then(|v| v.as_str())
1189 .map(String::from)
1190 };
1191 ProjectChannelConfig {
1192 telegram_topic_id: get_str("telegram", "topic_id"),
1193 telegram_bot_token: get_str("telegram", "bot_token"),
1194 telegram_chat_id: get_str("telegram", "chat_id"),
1195 discord_channel_id: get_str("discord", "channel_id"),
1196 discord_bot_token: get_str("discord", "bot_token"),
1197 discord_guild_id: get_str("discord", "guild_id"),
1198 }
1199}
1200
1201async fn fetch_latest_release_version() -> Option<String> {
1206 let output = Command::new("gh")
1207 .args([
1208 "api",
1209 "repos/gabrielkoerich/orch/releases/latest",
1210 "--jq",
1211 ".tag_name",
1212 ])
1213 .output()
1214 .await
1215 .ok()?;
1216 if !output.status.success() {
1217 return None;
1218 }
1219 let tag = String::from_utf8(output.stdout).ok()?;
1220 let version = tag.trim().trim_start_matches('v').to_string();
1221 if version.is_empty() {
1222 None
1223 } else {
1224 Some(version)
1225 }
1226}
1227
1228async fn check_and_notify_upgrade(
1237 store: &Arc<TaskStore>,
1238 channels: &Arc<ChannelRegistry>,
1239 current_version: &str,
1240 check_interval: std::time::Duration,
1241) {
1242 let last_check_key = "upgrade:last_check_at";
1243 let last_notified_key = "upgrade:last_notified_version";
1244
1245 let now = chrono::Utc::now().timestamp();
1247 if let Ok(Some(last_check_str)) = store.kv_get(last_check_key).await {
1248 if let Ok(last_check) = last_check_str.parse::<i64>() {
1249 if now - last_check < check_interval.as_secs() as i64 {
1250 return;
1251 }
1252 }
1253 }
1254
1255 let _ = store.kv_set(last_check_key, &now.to_string()).await;
1257
1258 let latest = match fetch_latest_release_version().await {
1259 Some(v) => v,
1260 None => {
1261 tracing::debug!("upgrade check: failed to fetch latest release version");
1262 return;
1263 }
1264 };
1265
1266 if latest == current_version {
1267 tracing::debug!(current = %current_version, "orch is up to date");
1268 return;
1269 }
1270
1271 tracing::warn!(
1272 current_version = %current_version,
1273 latest_version = %latest,
1274 "orch upgrade available"
1275 );
1276
1277 if let Ok(Some(last_notified)) = store.kv_get(last_notified_key).await {
1282 if last_notified == latest {
1283 tracing::debug!(latest = %latest, "upgrade already notified");
1284 return;
1285 }
1286 }
1287
1288 let msg_telegram = format!(
1289 "⚠️ <b>Orch Upgrade Available</b>\n\n\
1290 Service: <code>{current_version}</code>\n\
1291 Latest: <code>{latest}</code>\n\n\
1292 Run: <code>brew update && brew upgrade orch && brew services restart orch</code>"
1293 );
1294
1295 let msg_discord = format!(
1296 "⚠️ **Orch Upgrade Available**\n\n\
1297 Service: `{current_version}`\n\
1298 Latest: `{latest}`\n\n\
1299 Run: `brew update && brew upgrade orch && brew services restart orch`"
1300 );
1301
1302 let msg_slack = format!(
1303 "⚠️ *Orch Upgrade Available*\n\n\
1304 Service: `{current_version}`\n\
1305 Latest: `{latest}`\n\n\
1306 Run: `brew update && brew upgrade orch && brew services restart orch`"
1307 );
1308
1309 for channel in channels.iter() {
1310 let (body, metadata, topic_id) = match channel.name() {
1311 "telegram" => (
1312 msg_telegram.clone(),
1313 serde_json::json!({"preformatted_html": true}),
1314 None,
1315 ),
1316 "discord" => (msg_discord.clone(), serde_json::json!({}), None),
1317 "slack" => (msg_slack.clone(), serde_json::json!({}), None),
1318 _ => continue,
1319 };
1320
1321 let msg = OutgoingMessage {
1322 thread_id: "upgrade".to_string(),
1323 body,
1324 reply_to: None,
1325 metadata,
1326 topic_id,
1327 };
1328
1329 if let Err(e) = channel.send(&msg).await {
1330 tracing::warn!(
1331 channel = channel.name(),
1332 ?e,
1333 "failed to send upgrade notification"
1334 );
1335 }
1336 }
1337
1338 let _ = store.kv_set(last_notified_key, &latest).await;
1340}
1341
1342async fn send_startup_escalation_notification(elapsed_secs: u64) {
1350 let duration = crate::channels::notification::format_duration(elapsed_secs as f64);
1351
1352 let msg_telegram = format!(
1353 "🚨 <b>Orch startup blocked — GitHub unreachable</b>\n\n\
1354 The engine has been retrying backend connections for {}\n\
1355 without success. All task processing, routing, and scheduled\n\
1356 jobs are paused. Check service logs with `orch log -f`.",
1357 duration
1358 );
1359
1360 let msg_discord = format!(
1361 "🚨 **Orch startup blocked — GitHub unreachable**\n\n\
1362 The engine has been retrying backend connections for {}\n\
1363 without success. All task processing, routing, and scheduled\n\
1364 jobs are paused. Check service logs with `orch log -f`.",
1365 duration
1366 );
1367
1368 let msg_slack = format!(
1369 "🚨 *Orch startup blocked — GitHub unreachable*\n\n\
1370 The engine has been retrying backend connections for {}\n\
1371 without success. All task processing, routing, and scheduled\n\
1372 jobs are paused. Check service logs with `orch log -f`.",
1373 duration
1374 );
1375
1376 let tg_token = crate::config::get("channels.telegram.bot_token");
1378 let tg_chat_id = crate::config::get("channels.telegram.chat_id");
1379 if let (Ok(token), Ok(chat_id)) = (&tg_token, &tg_chat_id) {
1380 if !token.is_empty() && !chat_id.is_empty() {
1381 if let Ok(channel) = TelegramChannel::new(token.clone(), Some(chat_id.clone())) {
1382 let msg = OutgoingMessage {
1383 thread_id: "startup_escalation".to_string(),
1384 body: msg_telegram.clone(),
1385 reply_to: None,
1386 metadata: serde_json::json!({ "preformatted_html": true }),
1387 topic_id: crate::config::get("channels.telegram.general_topic_id").ok(),
1388 };
1389 if let Err(e) = channel.send(&msg).await {
1390 tracing::warn!(?e, "failed to send startup escalation via telegram");
1391 } else {
1392 tracing::info!("startup escalation notification sent to telegram");
1393 }
1394 }
1395 }
1396 }
1397
1398 if let Ok(token) = crate::config::get("channels.discord.bot_token") {
1400 let channel_id = crate::config::get("channels.discord.channel_id")
1401 .or_else(|_| crate::config::get("channels.discord.general_channel_id"));
1402 if !token.is_empty() {
1403 if let Some(cid) = channel_id.ok().filter(|s| !s.is_empty()) {
1404 let shard_id = crate::config::get("channels.discord.shard_id")
1405 .ok()
1406 .and_then(|v| v.parse::<u64>().ok())
1407 .unwrap_or(0);
1408 let shard_count = crate::config::get("channels.discord.shard_count")
1409 .ok()
1410 .and_then(|v| v.parse::<u64>().ok())
1411 .unwrap_or(1);
1412 if let Ok(gateway) = DiscordGateway::new(token, Some(cid), shard_id, shard_count) {
1413 let msg = OutgoingMessage {
1414 thread_id: "startup_escalation".to_string(),
1415 body: msg_discord.clone(),
1416 reply_to: None,
1417 metadata: serde_json::Value::Null,
1418 topic_id: None,
1419 };
1420 if let Err(e) = gateway.send(&msg).await {
1421 tracing::warn!(?e, "failed to send startup escalation via discord");
1422 } else {
1423 tracing::info!("startup escalation notification sent to discord");
1424 }
1425 }
1426 }
1427 }
1428 }
1429
1430 if let Ok(token) = crate::config::get("channels.slack.bot_token") {
1432 let channel_id = crate::config::get("channels.slack.channel_id");
1433 if !token.is_empty() {
1434 if let Ok(cid) = channel_id {
1435 if let Ok(channel) = SlackChannel::new(token, Some(cid)) {
1436 let msg = OutgoingMessage {
1437 thread_id: "startup_escalation".to_string(),
1438 body: msg_slack.clone(),
1439 reply_to: None,
1440 metadata: serde_json::Value::Null,
1441 topic_id: None,
1442 };
1443 if let Err(e) = channel.send(&msg).await {
1444 tracing::warn!(?e, "failed to send startup escalation via slack");
1445 } else {
1446 tracing::info!("startup escalation notification sent to slack");
1447 }
1448 }
1449 }
1450 }
1451 }
1452}
1453
1454pub async fn serve() -> anyhow::Result<()> {
1458 let killed = crate::home::kill_other_orch_serve_processes(std::time::Duration::from_secs(30));
1459 if killed > 0 {
1460 tracing::info!(count = killed, "terminated stale orch serve processes");
1461 }
1462
1463 tracing::info!("orch engine starting");
1464
1465 if let Err(e) = crate::home::init_dirs().await {
1469 tracing::warn!("failed to initialize orch directories: {e}");
1470 }
1471
1472 if let Err(e) = crate::config::warm_cache().await {
1475 tracing::warn!("failed to warm config cache: {e}");
1476 }
1477
1478 let mut config = EngineConfig::from_config();
1479
1480 tracing::info!("internal database ready");
1481
1482 let startup_escalation_secs = config.startup_failure_escalation_secs;
1491 let mut project_engines = {
1492 let mut delay_secs = 5u64;
1493 let mut attempt = 0u32;
1494 let mut escalated = false;
1495 let start = std::time::Instant::now();
1496 loop {
1497 attempt += 1;
1498 match init_project_engines().await {
1499 Ok(engines) => break engines,
1500 Err(e) => {
1501 let elapsed = start.elapsed().as_secs();
1502
1503 if startup_escalation_secs > 0
1509 && !escalated
1510 && elapsed >= startup_escalation_secs
1511 {
1512 escalated = true;
1513 tracing::error!(
1514 delay_secs,
1515 attempt,
1516 elapsed_secs = elapsed,
1517 threshold_secs = startup_escalation_secs,
1518 "project backends unavailable for {} — escalating startup failure: {e}",
1519 crate::channels::notification::format_duration(elapsed as f64)
1520 );
1521 send_startup_escalation_notification(elapsed).await;
1525 } else {
1526 tracing::warn!(
1527 delay_secs,
1528 attempt,
1529 "project backends unavailable, retrying: {e}"
1530 );
1531 }
1532
1533 tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;
1534 delay_secs = (delay_secs * 2).min(120);
1535 }
1536 }
1537 }
1538 };
1539
1540 tracing::info!(
1541 project_count = project_engines.len(),
1542 "initialized project engines"
1543 );
1544
1545 let mut active_repos: std::collections::HashSet<String> =
1549 project_engines.iter().map(|e| e.repo.clone()).collect();
1550
1551 let event_bus = events::EventBus::new(256);
1553 if let Err(e) = event_bus.start_ws_server().await {
1554 tracing::warn!(
1555 ?e,
1556 "failed to start event websocket server, continuing without it"
1557 );
1558 }
1559
1560 {
1564 let current = env!("ORCH_VERSION").to_string();
1565 tokio::spawn(async move {
1566 if let Some(latest) = fetch_latest_release_version().await {
1567 if latest != current {
1568 tracing::warn!(
1569 current_version = %current,
1570 latest_version = %latest,
1571 "orch service is behind the latest release — run: brew update && brew upgrade orch && brew services restart orch"
1572 );
1573 }
1574 }
1575 });
1576 }
1577
1578 for engine in &mut project_engines {
1580 engine.task_manager = Arc::new(TaskManager::with_events(
1581 engine.backend.clone(),
1582 engine.store.clone(),
1583 engine.repo.clone(),
1584 event_bus.sender(),
1585 ));
1586 }
1587
1588 let leads = project_engines.first().is_none_or(|e| e.store.is_leader());
1590 if leads {
1591 if let Err(e) = reconcile_startup_worktrees(&project_engines).await {
1592 tracing::warn!(err = %e, "startup worktree reconciliation failed");
1593 }
1594 }
1595
1596 if leads {
1597 let engines_snapshot: Vec<ProjectEngine> = project_engines.clone();
1601 tokio::spawn(async move {
1602 reconcile_startup_estimates(&engines_snapshot).await;
1603 });
1604 }
1605
1606 let global_channel_config = GlobalChannelConfig {
1608 telegram_general_topic_id: crate::config::get("channels.telegram.general_topic_id").ok(),
1609 discord_general_channel_id: crate::config::get("channels.discord.general_channel_id").ok(),
1610 control_telegram_topic_id: crate::config::get("control.channels.telegram.topic_id").ok(),
1611 control_discord_channel_id: crate::config::get("control.channels.discord.channel_id").ok(),
1612 };
1613 let project_channel_configs: Vec<(String, ProjectChannelConfig)> = project_engines
1614 .iter()
1615 .map(|e| {
1616 let cfg = read_project_channel_config(&e.project_dir);
1617 (e.repo.clone(), cfg)
1618 })
1619 .collect();
1620 let channel_router = Arc::new(ChannelRouter::new(
1621 &global_channel_config,
1622 &project_channel_configs,
1623 ));
1624 tracing::info!(
1625 projects = ?channel_router.projects(),
1626 "channel router initialized"
1627 );
1628
1629 let tmux = Arc::new(TmuxManager::new());
1631 tick::startup_cleanup(&tmux).await;
1634
1635 let transport = Arc::new(Transport::new());
1637
1638 let capture = Arc::new(CaptureService::new(transport.clone()));
1640 let capture_for_tick = capture.clone();
1641 tokio::spawn(async move {
1642 capture.start().await;
1643 });
1644
1645 let mut channel_registry = ChannelRegistry::new();
1647
1648 if let Ok(token) = crate::config::get("channels.telegram.bot_token") {
1650 if !token.is_empty() {
1651 let chat_id = crate::config::get("channels.telegram.chat_id").ok();
1652 match TelegramChannel::new(token, chat_id) {
1653 Ok(telegram) => {
1654 if let Err(e) = telegram.health_check().await {
1655 tracing::warn!(?e, "telegram channel health check failed, skipping");
1656 } else {
1657 channel_registry.register(Box::new(telegram));
1658 tracing::info!("telegram channel registered");
1659 }
1660 }
1661 Err(e) => {
1662 tracing::warn!(?e, "failed to create telegram channel, skipping");
1663 }
1664 }
1665 }
1666 }
1667
1668 if let Ok(token) = crate::config::get("channels.discord.bot_token") {
1670 if !token.is_empty() {
1671 let channel_id = crate::config::get("channels.discord.channel_id").ok();
1672 let shard_id = crate::config::get("channels.discord.shard_id")
1673 .ok()
1674 .and_then(|v| v.parse::<u64>().ok())
1675 .unwrap_or(0);
1676 let shard_count = crate::config::get("channels.discord.shard_count")
1677 .ok()
1678 .and_then(|v| v.parse::<u64>().ok())
1679 .unwrap_or(1);
1680 match DiscordGateway::new(token, channel_id, shard_id, shard_count) {
1681 Ok(discord) => {
1682 if let Err(e) = discord.health_check().await {
1683 tracing::warn!(?e, "discord gateway health check failed, skipping");
1684 } else {
1685 channel_registry.register(Box::new(discord));
1686 tracing::info!(shard_id, shard_count, "discord gateway registered");
1687 }
1688 }
1689 Err(e) => {
1690 tracing::warn!(?e, "failed to create discord gateway, skipping");
1691 }
1692 }
1693 }
1694 }
1695
1696 if let Ok(token) = crate::config::get("channels.slack.bot_token") {
1698 if !token.is_empty() {
1699 let channel_id = crate::config::get("channels.slack.channel_id").ok();
1700 match SlackChannel::new(token, channel_id) {
1701 Ok(slack) => {
1702 if let Err(e) = slack.health_check().await {
1703 tracing::warn!(?e, "slack channel health check failed, skipping");
1704 } else {
1705 channel_registry.register(Box::new(slack));
1706 tracing::info!("slack channel registered");
1707 }
1708 }
1709 Err(e) => {
1710 tracing::warn!(?e, "failed to create slack channel, skipping");
1711 }
1712 }
1713 }
1714 }
1715
1716 let tmux_channel = TmuxChannel::with_transport(transport.clone());
1718 channel_registry.register(Box::new(tmux_channel));
1719 tracing::info!("tmux channel registered");
1720
1721 let mut channel_receivers: Vec<tokio::sync::mpsc::Receiver<IncomingMessage>> = Vec::new();
1723 for channel in channel_registry.iter() {
1724 match channel.start().await {
1725 Ok(rx) => {
1726 tracing::info!(channel = channel.name(), "channel started");
1727 channel_receivers.push(rx);
1728 }
1729 Err(e) => {
1730 tracing::warn!(channel = channel.name(), ?e, "failed to start channel");
1731 }
1732 }
1733 }
1734
1735 let channel_registry = Arc::new(channel_registry);
1737
1738 let transport_for_messages = transport.clone();
1740 let tmux_for_messages = tmux.clone();
1741 let capture_for_messages = capture_for_tick.clone();
1742 let channels_for_messages = channel_registry.clone();
1743 let engine_refs: Vec<EngineRef> = project_engines
1745 .iter()
1746 .map(|e| {
1747 (
1748 e.repo.clone(),
1749 e.backend.clone(),
1750 e.task_manager.clone(),
1751 Some(e.store.clone()),
1752 )
1753 })
1754 .collect();
1755 let pending_picks: channel_handler::PendingPicks =
1757 std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
1758 let router_for_messages = channel_router.clone();
1759 for mut rx in channel_receivers {
1760 let transport = transport_for_messages.clone();
1761 let tmux = tmux_for_messages.clone();
1762 let capture = capture_for_messages.clone();
1763 let channels = channels_for_messages.clone();
1764 let engine_refs = engine_refs.clone();
1765 let ch_router = router_for_messages.clone();
1766 let picks = pending_picks.clone();
1767 tokio::spawn(async move {
1768 while let Some(msg) = rx.recv().await {
1769 tracing::debug!(channel = %msg.channel, thread = %msg.thread_id, "received message from channel");
1770 channel_handler::handle_channel_message(
1771 msg,
1772 &transport,
1773 &tmux,
1774 &capture,
1775 &channels,
1776 &engine_refs,
1777 &ch_router,
1778 &picks,
1779 )
1780 .await;
1781 }
1782 });
1783 }
1784
1785 {
1789 let restart_channels = channel_registry.clone();
1790 let restart_store = project_engines.first().map(|e| e.store.clone());
1791 if let Some(store) = restart_store {
1792 tokio::spawn(async move {
1793 tokio::time::sleep(std::time::Duration::from_secs(5)).await;
1794 match store.kv_get("control:restart_pending").await {
1795 Ok(Some(conv_key)) => {
1796 if let Some((ch_name, thread_id, topic_id)) =
1797 crate::channels::transport::parse_conversation_key(&conv_key)
1798 {
1799 for ch in restart_channels.iter() {
1800 if ch.name() == ch_name {
1801 let msg = OutgoingMessage {
1802 thread_id: thread_id.to_string(),
1803 body: "orch restarted successfully.".to_string(),
1804 reply_to: None,
1805 metadata: serde_json::json!({}),
1806 topic_id: topic_id.map(|t| t.to_string()),
1807 };
1808 if let Err(e) = ch.send(&msg).await {
1809 tracing::warn!(
1810 channel = ch_name,
1811 error = %e,
1812 "failed to send restart confirmation"
1813 );
1814 }
1815 break;
1816 }
1817 }
1818 }
1819 if let Err(e) = store.kv_delete("control:restart_pending").await {
1820 tracing::warn!(error = %e, "failed to clear control:restart_pending");
1821 }
1822 }
1823 Ok(None) => {} Err(e) => {
1825 tracing::warn!(error = %e, "failed to read control:restart_pending");
1826 }
1827 }
1828 });
1829 }
1830 }
1831
1832 {
1843 let mut notification_rx = transport.subscribe_notifications();
1844 let channels = channel_registry.clone();
1845 let notif_router = channel_router.clone();
1846 let notif_store: Option<Arc<TaskStore>> = project_engines.first().map(|e| e.store.clone());
1848 tokio::spawn(async move {
1849 loop {
1850 match notification_rx.recv().await {
1851 Ok(notification) => {
1852 let level = NotificationLevel::from_config();
1853 if !level.should_notify(¬ification.status) {
1854 tracing::debug!(
1855 task_id = %notification.task_id,
1856 status = %notification.status,
1857 "notification suppressed by level={:?}",
1858 level
1859 );
1860 continue;
1861 }
1862
1863 tracing::info!(
1864 task_id = %notification.task_id,
1865 status = %notification.status,
1866 repo = ?notification.repo,
1867 "routing notification to channels"
1868 );
1869
1870 let mut routed = false;
1872
1873 if let Some(ref target) = notification.notify_target {
1876 let telegram = channels.iter().find(|c| c.name() == "telegram");
1877 if let Some(channel) = telegram {
1878 let body = notification.format_telegram();
1879 let metadata = serde_json::json!({
1880 "preformatted_html": true,
1881 "chat_id_override": target
1882 });
1883 let msg = OutgoingMessage {
1884 thread_id: notification.task_id.clone(),
1885 body,
1886 reply_to: None,
1887 metadata,
1888 topic_id: None,
1889 };
1890 if let Err(e) = channel.send(&msg).await {
1891 tracing::warn!(
1892 task_id = %notification.task_id,
1893 target,
1894 ?e,
1895 "failed to send to notify_target"
1896 );
1897 } else {
1898 routed = true;
1899 }
1900 }
1901 }
1902
1903 if routed {
1904 } else if let Some(repo) = notification.repo.as_deref() {
1906 let mut sent: std::collections::HashSet<(String, Option<String>)> =
1912 std::collections::HashSet::new();
1913
1914 for channel in channels.iter() {
1916 let ch_name = channel.name();
1917 if let Some(topic_id) =
1918 notif_router.target_for_project(repo, ch_name)
1919 {
1920 let body = match ch_name {
1921 "telegram" => notification.format_telegram(),
1922 "discord" => notification.format_discord(),
1923 "slack" => notification.format_slack(),
1924 _ => continue,
1925 };
1926 let metadata = if ch_name == "telegram" {
1927 serde_json::json!({"preformatted_html": true})
1928 } else {
1929 serde_json::json!({})
1930 };
1931 let resolved_topic = Some(topic_id.to_string());
1932 let msg = OutgoingMessage {
1933 thread_id: notification.task_id.clone(),
1934 body,
1935 reply_to: None,
1936 metadata,
1937 topic_id: resolved_topic.clone(),
1938 };
1939 if let Err(e) = channel.send(&msg).await {
1940 tracing::warn!(
1941 channel = ch_name,
1942 task_id = %notification.task_id,
1943 ?e,
1944 "failed to send to dedicated channel"
1945 );
1946 } else {
1947 sent.insert((ch_name.to_string(), resolved_topic));
1948 routed = true;
1949 }
1950 }
1951 }
1952
1953 if let Some(store) = ¬if_store {
1955 match store.list_subscribers_for_repo(repo).await {
1956 Ok(subscribers) => {
1957 for (ch_name, thread_id, topic_id) in subscribers {
1958 let channel =
1959 channels.iter().find(|c| c.name() == ch_name);
1960 let Some(channel) = channel else {
1961 continue;
1962 };
1963 let resolved_topic = if topic_id.is_empty() {
1964 None
1965 } else {
1966 Some(topic_id.clone())
1967 };
1968 if sent.contains(&(
1971 ch_name.clone(),
1972 resolved_topic.clone(),
1973 )) {
1974 tracing::debug!(
1975 channel = %ch_name,
1976 task_id = %notification.task_id,
1977 topic_id = ?resolved_topic,
1978 "skipping duplicate subscriber dispatch — destination already received from dedicated path"
1979 );
1980 continue;
1981 }
1982 let body = notification.format_with_project(&ch_name);
1983 let metadata = if ch_name == "telegram" {
1984 serde_json::json!({"preformatted_html": true})
1985 } else {
1986 serde_json::json!({})
1987 };
1988 let msg = OutgoingMessage {
1989 thread_id: thread_id.clone(),
1990 body,
1991 reply_to: None,
1992 metadata,
1993 topic_id: resolved_topic.clone(),
1994 };
1995 if let Err(e) = channel.send(&msg).await {
1996 tracing::warn!(
1997 channel = %ch_name,
1998 task_id = %notification.task_id,
1999 ?e,
2000 "failed to send to subscribed channel"
2001 );
2002 } else {
2003 sent.insert((ch_name.clone(), resolved_topic));
2004 routed = true;
2005 }
2006 }
2007 }
2008 Err(e) => {
2009 tracing::warn!(
2010 repo,
2011 ?e,
2012 "failed to list subscribers for repo"
2013 );
2014 }
2015 }
2016 }
2017 }
2018
2019 if !routed {
2021 for channel in channels.iter() {
2022 let (body, should_send, is_telegram) = match channel.name() {
2023 "telegram" => (notification.format_telegram(), true, true),
2024 "discord" => (notification.format_discord(), true, false),
2025 "slack" => (notification.format_slack(), true, false),
2026 _ => (String::new(), false, false),
2029 };
2030
2031 if !should_send {
2032 continue;
2033 }
2034
2035 let metadata = if is_telegram {
2036 serde_json::json!({"preformatted_html": true})
2037 } else {
2038 serde_json::json!({})
2039 };
2040 let msg = OutgoingMessage {
2041 thread_id: notification.task_id.clone(),
2042 body,
2043 reply_to: None,
2044 metadata,
2045 topic_id: None,
2046 };
2047
2048 if let Err(e) = channel.send(&msg).await {
2049 tracing::warn!(
2050 channel = channel.name(),
2051 task_id = %notification.task_id,
2052 ?e,
2053 "failed to send notification"
2054 );
2055 }
2056 }
2057 }
2058 }
2059 Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
2060 tracing::warn!(missed = n, "notification receiver lagged");
2061 }
2062 Err(tokio::sync::broadcast::error::RecvError::Closed) => {
2063 tracing::debug!("notification channel closed");
2064 break;
2065 }
2066 }
2067 }
2068 });
2069 tracing::info!("notification dispatcher started");
2070 }
2071
2072 let webhook_notify = Arc::new(Notify::new());
2074
2075 let webhook_port: Option<u16>;
2079 let mut webhook_healthy: bool;
2080 let mut last_webhook_health_check = std::time::Instant::now();
2081 let webhook_enabled = crate::config::get("webhook.enabled")
2083 .map(|v| v == "true")
2084 .unwrap_or(false);
2085
2086 let webhook_status = Arc::new(tokio::sync::Mutex::new(
2088 crate::webhook_status::WebhookStatus::default(),
2089 ));
2090
2091 if webhook_enabled {
2092 let port: u16 = crate::config::get("webhook.port")
2093 .ok()
2094 .and_then(|v| v.parse().ok())
2095 .unwrap_or(8080);
2096 webhook_port = Some(port);
2097 let secret = crate::config::get("webhook.secret").unwrap_or_default();
2098 let webhook_repo = project_engines
2099 .first()
2100 .map(|e| e.repo.clone())
2101 .unwrap_or_default();
2102
2103 let (tx, mut rx) = tokio::sync::mpsc::channel::<IncomingMessage>(64);
2104
2105 let to_save = {
2107 let mut s = webhook_status.lock().await;
2108 s.configured = true;
2109 s.port = Some(port);
2110 s.healthy = false;
2111 s.fallback_mode = false;
2112 s.clone()
2113 };
2114 to_save.save().await;
2115
2116 const WEBHOOK_MAX_ATTEMPTS: u32 = 5;
2120 let status_for_spawn = webhook_status.clone();
2121 tokio::spawn(async move {
2122 use crate::channels::github::{is_transient_bind_error, webhook_backoff_delay};
2123 let mut attempt = 0u32;
2124 loop {
2125 attempt += 1;
2126 tracing::info!(attempt, port, "attempting to start webhook server");
2127 match start_webhook_server(port, secret.clone(), webhook_repo.clone(), tx.clone())
2128 .await
2129 {
2130 Ok(_) => {
2131 tracing::info!(attempt, "webhook server exited cleanly");
2132 break;
2133 }
2134 Err(e) => {
2135 let reason = e.to_string();
2136 tracing::error!(attempt, %reason, "webhook server failed");
2137 if attempt >= WEBHOOK_MAX_ATTEMPTS || !is_transient_bind_error(&e) {
2138 let kind = if attempt >= WEBHOOK_MAX_ATTEMPTS {
2139 "max attempts reached"
2140 } else {
2141 "non-transient error"
2142 };
2143 tracing::error!(
2144 attempt,
2145 %reason,
2146 kind,
2147 orch_webhook_in_fallback = true,
2148 "webhook server giving up, switching to polling fallback"
2149 );
2150 let to_save = {
2151 let mut s = status_for_spawn.lock().await;
2152 s.fallback_mode = true;
2153 s.healthy = false;
2154 s.last_failure_reason = Some(reason);
2155 s.startup_attempts = attempt;
2156 s.clone()
2157 };
2158 to_save.save().await;
2159 break;
2160 }
2161 let delay = webhook_backoff_delay(attempt);
2162 tracing::warn!(
2163 attempt,
2164 delay_ms = delay.as_millis(),
2165 %reason,
2166 "webhook bind failed (transient), retrying with backoff"
2167 );
2168 {
2169 let to_save = {
2170 let mut s = status_for_spawn.lock().await;
2171 s.startup_attempts = attempt;
2172 s.last_failure_reason = Some(reason);
2173 s.clone()
2174 };
2175 to_save.save().await;
2176 }
2177 tokio::time::sleep(delay).await;
2178 }
2179 }
2180 }
2181 });
2182
2183 let notify = webhook_notify.clone();
2185 let transport_for_webhook = transport.clone();
2186 tokio::spawn(async move {
2187 while let Some(msg) = rx.recv().await {
2188 tracing::info!(
2189 channel = %msg.channel,
2190 thread = %msg.thread_id,
2191 event = %msg.metadata.get("event").and_then(|v| v.as_str()).unwrap_or("unknown"),
2192 action = %msg.metadata.get("action").and_then(|v| v.as_str()).unwrap_or("unknown"),
2193 "webhook event received, triggering immediate tick"
2194 );
2195 let route = transport_for_webhook.route(&msg).await;
2196 tracing::info!(
2197 channel = %msg.channel,
2198 route = ?route,
2199 "webhook event routed"
2200 );
2201 notify.notify_one();
2203 }
2204 });
2205
2206 webhook_healthy = true;
2207 tracing::info!(port, orch_webhook_up = true, "webhook server started");
2208 } else {
2209 webhook_port = None;
2210 webhook_healthy = false;
2211 {
2212 let to_save = {
2213 let mut s = webhook_status.lock().await;
2214 s.configured = false;
2215 s.fallback_mode = true;
2216 s.clone()
2217 };
2218 to_save.save().await;
2219 }
2220 tracing::info!(
2221 orch_webhook_in_fallback = true,
2222 "webhook server disabled, using polling fallback mode"
2223 );
2224 }
2225
2226 start_relay_client(&project_engines, &webhook_notify);
2227 crate::github::app::start_loader();
2228
2229 let router = Arc::new(RwLock::new(
2233 match tokio::task::spawn_blocking(Router::from_config).await {
2234 Ok(r) => r,
2235 Err(e) => {
2236 tracing::error!(?e, "router init panicked in spawn_blocking, using default");
2237 tokio::task::spawn_blocking(|| Router::new(RouterConfig::default()))
2238 .await
2239 .unwrap_or_else(|e2| {
2240 panic!("router default init also panicked in spawn_blocking — cannot start engine without a router: {e2:?}");
2241 })
2242 }
2243 },
2244 ));
2245 {
2246 let r = router.read().await;
2247 tracing::info!(
2248 mode = %r.config.mode,
2249 agents = ?r.available_agents,
2250 fallback = %r.config.fallback_executor,
2251 "router initialized"
2252 );
2253 }
2254
2255 let semaphore = Arc::new(Semaphore::new(config.max_parallel));
2259 let mut parallel_in_force = config.max_parallel;
2260
2261 let dispatching: Arc<dashmap::DashMap<String, String>> = Arc::new(dashmap::DashMap::new());
2268
2269 let auto_merge_in_flight: Arc<dashmap::DashSet<String>> = Arc::new(dashmap::DashSet::new());
2273
2274 let mut config_rx = crate::config::subscribe();
2276
2277 let mut last_sync = std::time::Instant::now();
2279
2280 let mut last_upgrade_check: Option<std::time::Instant> = None;
2282
2283 let mut rate_limit_reported: Option<i64> = None;
2286
2287 let (weight_tx, mut weight_rx) = mpsc::channel::<WeightSignal>(64);
2289
2290 for engine in project_engines.iter().filter(|_| leads) {
2292 let reset =
2293 reset_orphaned_reviews(&engine.task_manager, &engine.store, &engine.repo, &tmux).await;
2294
2295 if reset > 0 {
2296 tracing::info!(repo = %engine.repo, reset, "reset orphaned reviews to needs_review on startup");
2297 }
2298 }
2299
2300 for engine in &project_engines {
2302 subscribers::dispatch::spawn(
2303 event_bus.subscribe(),
2304 engine.backend.clone(),
2305 tmux.clone(),
2306 engine.runner.clone(),
2307 capture_for_tick.clone(),
2308 semaphore.clone(),
2309 engine.task_manager.clone(),
2310 weight_tx.clone(),
2311 router.clone(),
2312 dispatching.clone(),
2313 engine.store.clone(),
2314 engine.repo.clone(),
2315 );
2316 }
2317 tracing::info!("dispatch subscriber started");
2318
2319 for engine in &project_engines {
2321 subscribers::review::spawn(
2322 event_bus.subscribe(),
2323 engine.backend.clone(),
2324 tmux.clone(),
2325 semaphore.clone(),
2326 engine.task_manager.clone(),
2327 router.clone(),
2328 dispatching.clone(),
2329 engine.store.clone(),
2330 engine.repo.clone(),
2331 );
2332 }
2333 tracing::info!("review subscriber started");
2334
2335 for engine in &project_engines {
2337 subscribers::unblock::spawn(
2338 event_bus.subscribe(),
2339 engine.backend.clone(),
2340 engine.task_manager.clone(),
2341 engine.store.clone(),
2342 engine.repo.clone(),
2343 );
2344 }
2345 tracing::info!("unblock subscriber started");
2346
2347 subscribers::notify::spawn(event_bus.subscribe(), transport.clone());
2350 tracing::info!("notify subscriber started");
2351
2352 tracing::info!(
2354 tick = ?config.tick_interval,
2355 sync = ?config.sync_interval,
2356 parallel = config.max_parallel,
2357 "entering main loop"
2358 );
2359 let mut restart_only = restart_only_snapshot();
2362
2363 let mut interval = tokio::time::interval(config.tick_interval);
2364
2365 let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
2367 let mut sighup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
2368
2369 let sync_in_progress = Arc::new(std::sync::atomic::AtomicBool::new(false));
2371
2372 let last_tick_epoch = Arc::new(std::sync::atomic::AtomicU64::new(
2375 std::time::SystemTime::now()
2376 .duration_since(std::time::UNIX_EPOCH)
2377 .unwrap_or_default()
2378 .as_secs(),
2379 ));
2380 {
2381 let last_tick_epoch = Arc::clone(&last_tick_epoch);
2382 let tick_interval_secs = config.tick_interval.as_secs();
2383 tokio::spawn(async move {
2384 let mut watchdog_interval = tokio::time::interval(std::time::Duration::from_secs(30));
2386 let mut suspend_detector = crate::engine::suspend::SuspendDetector::new();
2391 loop {
2392 watchdog_interval.tick().await;
2393 let own_gap = suspend_detector.check();
2394 let last = last_tick_epoch.load(std::sync::atomic::Ordering::Relaxed);
2395 let now = std::time::SystemTime::now()
2396 .duration_since(std::time::UNIX_EPOCH)
2397 .unwrap_or_default()
2398 .as_secs();
2399 let stale_secs = now.saturating_sub(last);
2400 let threshold = (tick_interval_secs * 6).max(60);
2402 if stale_secs > threshold {
2403 let shared_gap = crate::engine::suspend::gap_detected_within(
2410 std::time::Duration::from_secs(stale_secs),
2411 );
2412 let gap = match (own_gap, shared_gap) {
2413 (Some(a), Some(b)) => Some(a.max(b)),
2414 (Some(a), None) => Some(a),
2415 (None, Some(b)) => Some(b),
2416 (None, None) => None,
2417 };
2418 if let Some(gap) = gap {
2419 let gap_secs = gap.num_seconds() as u64;
2420 if gap_secs >= stale_secs {
2421 tracing::info!(
2422 stale_secs,
2423 threshold,
2424 suspend_gap_secs = gap_secs,
2425 "tick loop stale window explained by host suspend/resume, not a stall"
2426 );
2427 } else {
2428 tracing::error!(
2429 stale_secs,
2430 threshold,
2431 suspend_gap_secs = gap_secs,
2432 "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — suspend gap of {}s only partially explains the stall",
2433 stale_secs,
2434 threshold,
2435 gap_secs,
2436 );
2437 }
2438 } else {
2439 tracing::error!(
2440 stale_secs,
2441 threshold,
2442 "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — possible stall",
2443 stale_secs,
2444 threshold,
2445 );
2446 }
2447 }
2448 }
2449 });
2450 }
2451
2452 loop {
2453 tokio::select! {
2454 _ = interval.tick() => {
2455 let tick_start = std::time::Instant::now();
2456
2457 if let Some(gap) = crate::engine::suspend::checkpoint() {
2461 tracing::info!(
2462 gap_secs = gap.num_seconds(),
2463 "host suspend/resume gap detected, discounting from stuck-task age checks"
2464 );
2465 }
2466
2467 if parallel_in_force != config.max_parallel {
2471 let resized =
2472 resize_dispatch_pool(&semaphore, parallel_in_force, config.max_parallel);
2473 if resized != parallel_in_force {
2474 parallel_in_force = resized;
2475 tracing::info!(
2476 in_force = parallel_in_force,
2477 target = config.max_parallel,
2478 "dispatch pool resized"
2479 );
2480 }
2481 }
2482
2483 {
2485 let mut rw = router.write().await;
2486 rw.tick_weight_recovery();
2487 }
2488
2489 if let Some(remaining) = GhHttp::is_rate_limited() {
2493 let reset_at = chrono::Utc::now()
2494 .timestamp()
2495 .saturating_add(i64::try_from(remaining.as_secs()).unwrap_or(i64::MAX));
2496 if rate_limit_reported.is_none_or(|prev| (reset_at - prev).abs() > 60) {
2498 rate_limit_reported = Some(reset_at);
2499 report_rate_limited(reset_at, project_engines.first().map(|e| &e.store), Some(&transport)).await;
2500 }
2501 } else if let Some(prev) = rate_limit_reported.take() {
2502 tracing::info!(
2503 limited_until = prev,
2504 "GitHub API rate limit cleared"
2505 );
2506 if let Some(engine) = project_engines.first() {
2507 let _ = engine.store.kv_delete(RATE_LIMITED_UNTIL_KEY).await;
2508 }
2509 }
2510
2511 tick::tick_all(
2513 &project_engines,
2514 &tmux,
2515 &capture_for_tick,
2516 &semaphore,
2517 &config,
2518 &router,
2519 &weight_tx,
2520 &dispatching,
2521 Some(&transport),
2522 &active_repos,
2523 &auto_merge_in_flight,
2524 ).await;
2525
2526 while let Ok(signal) = weight_rx.try_recv() {
2529 let mut rw = router.write().await;
2530 match signal {
2531 WeightSignal::RateLimited { ref agent } => {
2532 rw.record_rate_limit(agent);
2533 }
2534 WeightSignal::Success { ref agent } => {
2535 rw.record_success(agent);
2536 }
2537 WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
2538 }
2539 }
2540
2541 if last_sync.elapsed() >= config.sync_interval {
2546 if sync_in_progress.compare_exchange(
2547 false,
2548 true,
2549 std::sync::atomic::Ordering::AcqRel,
2550 std::sync::atomic::Ordering::Relaxed,
2551 ).is_ok() {
2552 spawn_sync_pass(
2553 &project_engines,
2554 &tmux,
2555 &config,
2556 &router,
2557 &dispatching,
2558 &auto_merge_in_flight,
2559 &sync_in_progress,
2560 "periodic",
2561 );
2562 } else {
2563 tracing::debug!("sync tick still in progress, skipping");
2564 }
2565 last_sync = std::time::Instant::now();
2569 }
2570
2571 if webhook_enabled {
2573 let health_check_interval = config.webhook_health_check_interval
2574 .unwrap_or(std::time::Duration::from_secs(60));
2575
2576 if last_webhook_health_check.elapsed() >= health_check_interval {
2577 if let Some(port) = webhook_port {
2578 let (health, failure_reason) =
2579 crate::channels::github::check_webhook_health(port).await;
2580 if health != webhook_healthy {
2581 webhook_healthy = health;
2582 if webhook_healthy {
2583 tracing::info!(port, orch_webhook_up = true, "webhook health restored");
2584 } else {
2585 tracing::warn!(
2586 port,
2587 orch_webhook_up = false,
2588 reason = failure_reason.as_deref().unwrap_or("unknown"),
2589 "webhook health check failed"
2590 );
2591 }
2592 }
2593 {
2595 let to_save = {
2596 let mut s = webhook_status.lock().await;
2597 s.healthy = health;
2598 s.last_check_utc = Some(chrono::Utc::now());
2599 if health {
2600 s.last_failure_reason = None;
2601 } else if failure_reason.is_some() {
2602 s.last_failure_reason = failure_reason;
2603 }
2604 s.clone()
2605 };
2606 to_save.save().await;
2607 }
2608 }
2609 last_webhook_health_check = std::time::Instant::now();
2610 }
2611 }
2612
2613 if should_run_upgrade_check(last_upgrade_check, config.upgrade_check_interval) {
2615 if let Some(store) = project_engines.first().map(|e| e.store.clone()) {
2616 let channels = channel_registry.clone();
2617 let current = env!("ORCH_VERSION").to_string();
2618 let check_interval =
2619 std::time::Duration::from_secs(config.upgrade_check_interval);
2620 tokio::spawn(async move {
2621 check_and_notify_upgrade(&store, &channels, ¤t, check_interval)
2622 .await;
2623 });
2624 }
2625 last_upgrade_check = Some(std::time::Instant::now());
2626 }
2627
2628 let tick_elapsed = tick_start.elapsed();
2630 if tick_elapsed.as_secs() > 30 {
2631 tracing::warn!(elapsed_ms = tick_elapsed.as_millis() as u64, "slow tick");
2632 } else {
2633 tracing::debug!(elapsed_ms = tick_elapsed.as_millis() as u64, "tick complete");
2634 }
2635 last_tick_epoch.store(
2636 std::time::SystemTime::now()
2637 .duration_since(std::time::UNIX_EPOCH)
2638 .unwrap_or_default()
2639 .as_secs(),
2640 std::sync::atomic::Ordering::Relaxed,
2641 );
2642 }
2643 _ = webhook_notify.notified() => {
2645 if let Some(remaining) = GhHttp::is_rate_limited() {
2646 tracing::warn!(
2647 remaining_secs = remaining.as_secs(),
2648 "GitHub API rate-limited, skipping webhook-triggered tick"
2649 );
2650 } else {
2651 tracing::info!("webhook event triggered immediate tick");
2652
2653 tick::tick_all(
2654 &project_engines,
2655 &tmux,
2656 &capture_for_tick,
2657 &semaphore,
2658 &config,
2659 &router,
2660 &weight_tx,
2661 &dispatching,
2662 Some(&transport),
2663 &active_repos,
2664 &auto_merge_in_flight,
2665 ).await;
2666
2667 while let Ok(signal) = weight_rx.try_recv() {
2669 let mut rw = router.write().await;
2670 match signal {
2671 WeightSignal::RateLimited { ref agent } => {
2672 rw.record_rate_limit(agent);
2673 }
2674 WeightSignal::Success { ref agent } => {
2675 rw.record_success(agent);
2676 }
2677 WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
2678 }
2679 }
2680
2681 if sync_in_progress.compare_exchange(
2687 false,
2688 true,
2689 std::sync::atomic::Ordering::AcqRel,
2690 std::sync::atomic::Ordering::Relaxed,
2691 ).is_ok() {
2692 spawn_sync_pass(
2693 &project_engines,
2694 &tmux,
2695 &config,
2696 &router,
2697 &dispatching,
2698 &auto_merge_in_flight,
2699 &sync_in_progress,
2700 "webhook",
2701 );
2702 last_sync = std::time::Instant::now();
2704 } else {
2705 tracing::debug!("sync tick still in progress, skipping webhook-triggered immediate sync");
2706 }
2707 }
2708
2709 interval.reset();
2711 }
2712 result = config_rx.recv() => {
2713 let reload = match result {
2716 Ok(path) => {
2717 tracing::info!(path = %path.display(), "config file changed, reloading");
2718 true
2719 }
2720 Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
2721 tracing::warn!(missed = n, "config change receiver lagged, reloading");
2722 true
2723 }
2724 Err(tokio::sync::broadcast::error::RecvError::Closed) => {
2725 tracing::warn!("config change channel closed");
2726 false
2727 }
2728 };
2729
2730 if reload {
2731 let new_config = EngineConfig::from_config();
2733 log_engine_config_changes(&config, &new_config);
2734
2735 let new_restart_only = restart_only_snapshot();
2736 log_restart_only_changes(&restart_only, &new_restart_only);
2737 restart_only = new_restart_only;
2738
2739 let tick_changed = new_config.tick_interval != config.tick_interval;
2740 config = new_config;
2741
2742 if tick_changed {
2744 interval = tokio::time::interval(config.tick_interval);
2745 tracing::info!(tick = ?config.tick_interval, "tick interval updated");
2746 }
2747
2748 if parallel_in_force != config.max_parallel {
2751 parallel_in_force = resize_dispatch_pool(
2752 &semaphore,
2753 parallel_in_force,
2754 config.max_parallel,
2755 );
2756 tracing::info!(
2757 in_force = parallel_in_force,
2758 target = config.max_parallel,
2759 "dispatch pool resized"
2760 );
2761 }
2762
2763 {
2765 let mut router_guard = router.write().await;
2766 router_guard.reload_async().await;
2767 }
2768
2769 sync_project_engines(
2771 &mut project_engines,
2772 &mut active_repos,
2773 &event_bus,
2774 &tmux,
2775 &capture_for_tick,
2776 &semaphore,
2777 &weight_tx,
2778 &router,
2779 &dispatching,
2780 ).await;
2781
2782 tracing::info!(
2783 tick = ?config.tick_interval,
2784 sync = ?config.sync_interval,
2785 parallel = config.max_parallel,
2786 projects = project_engines.len(),
2787 "config reloaded"
2788 );
2789 }
2790 }
2791 signal_name = async {
2792 tokio::select! {
2793 _ = tokio::signal::ctrl_c() => "SIGINT",
2794 _ = sigterm.recv() => "SIGTERM",
2795 _ = sighup.recv() => "SIGHUP",
2796 }
2797 } => {
2798 tracing::info!(signal = signal_name, "beginning graceful shutdown");
2799
2800 let shutdown_result = tokio::time::timeout(
2803 config.graceful_shutdown_timeout,
2804 async {
2805 let mut reset_count = 0u32;
2809 let mut review_reset_count = 0u32;
2810 for engine in &project_engines {
2811 if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InProgress).await {
2812 for task in &tasks {
2813 if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::Routed).await {
2814 tracing::warn!(task_id = task.id.0, ?e, "failed to reset task on shutdown");
2815 } else {
2816 if let Ok(Some(store_id)) =
2817 engine.store.resolve_task_id(&engine.repo, &task.id.0).await
2818 {
2819 if let Err(e) = engine
2820 .store
2821 .finalize_incomplete_runs(
2822 store_id,
2823 "aborted",
2824 "graceful shutdown: reset in_progress task to routed",
2825 )
2826 .await
2827 {
2828 tracing::warn!(
2829 task_id = task.id.0,
2830 ?e,
2831 "failed to finalize incomplete runs on shutdown"
2832 );
2833 }
2834 }
2835 reset_count += 1;
2836 }
2837 }
2838 }
2839 if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, crate::store::TaskStatus::InProgress).await {
2841 for task in &tasks {
2842 let task_id = format!("internal:{}", task.id);
2843 if let Err(e) = engine.task_manager.update_task_status(
2844 &crate::backends::ExternalId(task_id.clone()),
2845 Status::Routed,
2846 ).await {
2847 tracing::warn!(task_id, ?e, "failed to reset internal task on shutdown");
2848 } else {
2849 if let Err(e) = engine
2850 .store
2851 .finalize_incomplete_runs(
2852 task.id,
2853 "aborted",
2854 "graceful shutdown: reset in_progress task to routed",
2855 )
2856 .await
2857 {
2858 tracing::warn!(
2859 task_id,
2860 ?e,
2861 "failed to finalize incomplete internal runs on shutdown"
2862 );
2863 }
2864 reset_count += 1;
2865 }
2866 }
2867 }
2868 if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InReview).await {
2870 for task in &tasks {
2871 if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::NeedsReview).await {
2872 tracing::warn!(task_id = task.id.0, ?e, "failed to reset in_review task on shutdown");
2873 } else {
2874 if let Ok(Some(store_id)) =
2875 engine.store.resolve_task_id(&engine.repo, &task.id.0).await
2876 {
2877 if let Err(e) = engine
2878 .store
2879 .finalize_incomplete_runs(
2880 store_id,
2881 "aborted",
2882 "graceful shutdown: reset in_review task to needs_review",
2883 )
2884 .await
2885 {
2886 tracing::warn!(
2887 task_id = task.id.0,
2888 ?e,
2889 "failed to finalize incomplete review runs on shutdown"
2890 );
2891 }
2892 }
2893 review_reset_count += 1;
2894 }
2895 }
2896 }
2897 if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, crate::store::TaskStatus::InReview).await {
2899 for task in &tasks {
2900 let task_id = format!("internal:{}", task.id);
2901 if let Err(e) = engine.task_manager.update_task_status(
2902 &crate::backends::ExternalId(task_id.clone()),
2903 Status::NeedsReview,
2904 ).await {
2905 tracing::warn!(task_id, ?e, "failed to reset internal in_review task on shutdown");
2906 } else {
2907 if let Err(e) = engine
2908 .store
2909 .finalize_incomplete_runs(
2910 task.id,
2911 "aborted",
2912 "graceful shutdown: reset in_review task to needs_review",
2913 )
2914 .await
2915 {
2916 tracing::warn!(
2917 task_id,
2918 ?e,
2919 "failed to finalize incomplete internal review runs on shutdown"
2920 );
2921 }
2922 review_reset_count += 1;
2923 }
2924 }
2925 }
2926 }
2927 if reset_count > 0 {
2928 tracing::info!(reset_count, "reset in_progress tasks to routed for re-dispatch");
2929 }
2930 if review_reset_count > 0 {
2931 tracing::info!(review_reset_count, "reset in_review tasks to needs_review for re-dispatch");
2932 }
2933
2934 let mut killed_sessions = Vec::new();
2937 if let Ok(sessions) = tmux.list_sessions().await {
2938 for session in &sessions {
2939 if session.name.starts_with("orch-") {
2940 if let Err(e) = tmux.kill_session(&session.name).await {
2941 tracing::warn!(session = %session.name, error = %e, "failed to kill tmux session");
2942 } else {
2943 killed_sessions.push(session.name.clone());
2944 }
2945 }
2946 }
2947 if !killed_sessions.is_empty() {
2948 tracing::info!(killed = killed_sessions.len(), "killing orch tmux sessions on shutdown");
2949 }
2950 }
2951
2952 if !killed_sessions.is_empty() {
2955 let still_alive = tmux
2956 .wait_for_sessions_dead(
2957 &killed_sessions,
2958 std::time::Duration::from_millis(100),
2959 std::time::Duration::from_secs(5),
2960 )
2961 .await;
2962 if still_alive > 0 {
2963 tracing::warn!(
2964 still_alive,
2965 "some tmux sessions did not terminate cleanly - they will be cleaned up on startup"
2966 );
2967 }
2968 tracing::info!(killed = killed_sessions.len() - still_alive, "confirmed tmux sessions terminated");
2969 }
2970 },
2971 ).await;
2972
2973 if shutdown_result.is_err() {
2974 tracing::error!(
2975 timeout_secs = config.graceful_shutdown_timeout.as_secs(),
2976 "graceful shutdown timed out, forcing exit"
2977 );
2978 }
2979
2980 break;
2981 }
2982 }
2983 }
2984
2985 events::cleanup_port_file().await;
2987 crate::cluster::local::cleanup().await;
2988 events::cleanup_version_file();
2989
2990 let _ = transport;
2992 tracing::info!("orch engine stopped");
2993 Ok(())
2994}
2995
2996#[cfg(test)]
2997mod tests {
2998 use super::*;
2999
3000 async fn in_review_task(store: &TaskStore, number: &str) -> i64 {
3001 let id = store
3002 .upsert_external(&crate::store::UpsertExternal {
3003 repo: "owner/repo",
3004 ext_id: number,
3005 title: "Under review",
3006 body: "",
3007 author: "",
3008 url: "",
3009 labels: &[],
3010 origin: "github",
3011 })
3012 .await
3013 .unwrap();
3014 store
3015 .update_status(id, crate::store::TaskStatus::InReview)
3016 .await
3017 .unwrap();
3018 id
3019 }
3020
3021 #[tokio::test]
3022 async fn a_review_without_a_session_goes_back_to_needs_review_and_a_live_one_stays() {
3023 let store = Arc::new(TaskStore::open_memory().await.unwrap());
3024 let backend: Arc<dyn ExternalBackend> =
3025 Arc::new(crate::backends::test_helpers::NoopBackend);
3026 let task_manager =
3027 TaskManager::with_store(backend, store.clone(), "owner/repo".to_string());
3028 let tmux = TmuxManager::isolated();
3029 let orphaned = in_review_task(&store, "11").await;
3030 let live = in_review_task(&store, "12").await;
3031 let session = tmux
3032 .create_session("owner/repo", "12-review", "/tmp", "sleep 30", &[])
3033 .await
3034 .unwrap();
3035 let _guard = crate::tmux::SessionGuard(session);
3036
3037 let reset = reset_orphaned_reviews(&task_manager, &store, "owner/repo", &tmux).await;
3038
3039 assert_eq!(reset, 1);
3040 assert_eq!(
3041 store.get(orphaned).await.unwrap().status,
3042 crate::store::TaskStatus::NeedsReview
3043 );
3044 assert_eq!(
3045 store.get(live).await.unwrap().status,
3046 crate::store::TaskStatus::InReview
3047 );
3048 }
3049
3050 #[test]
3051 fn growing_max_parallel_lets_more_tasks_run_without_a_restart() {
3052 let semaphore = Arc::new(Semaphore::new(4));
3053 let held: Vec<_> = (0..4)
3054 .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3055 .collect();
3056 assert!(
3057 semaphore.clone().try_acquire_owned().is_err(),
3058 "pool is full"
3059 );
3060
3061 let in_force = resize_dispatch_pool(&semaphore, 4, 8);
3062 assert_eq!(in_force, 8);
3063
3064 let grown: Vec<_> = (0..4)
3065 .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3066 .collect();
3067 assert_eq!(held.len() + grown.len(), 8, "8 tasks run at once");
3068 assert!(
3069 semaphore.clone().try_acquire_owned().is_err(),
3070 "pool is full"
3071 );
3072 }
3073
3074 #[test]
3075 fn shrinking_max_parallel_never_cancels_a_running_task() {
3076 let semaphore = Arc::new(Semaphore::new(8));
3077 let mut held: Vec<_> = (0..8)
3078 .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3079 .collect();
3080
3081 let mut in_force = resize_dispatch_pool(&semaphore, 8, 4);
3083 assert_eq!(in_force, 8);
3084 assert_eq!(held.len(), 8);
3085
3086 held.truncate(5);
3088 in_force = resize_dispatch_pool(&semaphore, in_force, 4);
3089 assert_eq!(in_force, 5);
3090 assert!(semaphore.clone().try_acquire_owned().is_err());
3091
3092 held.truncate(4);
3094 in_force = resize_dispatch_pool(&semaphore, in_force, 4);
3095 assert_eq!(in_force, 4);
3096 assert!(semaphore.clone().try_acquire_owned().is_err());
3097
3098 held.truncate(3);
3100 assert!(semaphore.clone().try_acquire_owned().is_ok());
3101 }
3102
3103 #[test]
3104 fn a_project_added_to_the_config_is_picked_up_and_running_ones_are_not_respawned() {
3105 let configured = vec![
3106 (
3107 "owner/one".to_string(),
3108 std::path::PathBuf::from("/srv/one"),
3109 ),
3110 (
3111 "owner/two".to_string(),
3112 std::path::PathBuf::from("/srv/two"),
3113 ),
3114 ];
3115 let active: std::collections::HashSet<String> =
3116 ["owner/one".to_string()].into_iter().collect();
3117
3118 let (added, removed) = diff_configured_projects(&configured, &active);
3119 assert_eq!(
3120 added,
3121 vec![(
3122 "owner/two".to_string(),
3123 std::path::PathBuf::from("/srv/two")
3124 )],
3125 "only the new project is started, so owner/one keeps its single set of subscribers"
3126 );
3127 assert!(removed.is_empty());
3128 }
3129
3130 #[test]
3131 fn a_project_dropped_from_the_config_is_reported_and_not_restarted() {
3132 let configured = vec![(
3133 "owner/one".to_string(),
3134 std::path::PathBuf::from("/srv/one"),
3135 )];
3136 let active: std::collections::HashSet<String> =
3137 ["owner/one".to_string(), "owner/gone".to_string()]
3138 .into_iter()
3139 .collect();
3140
3141 let (added, removed) = diff_configured_projects(&configured, &active);
3142 assert!(added.is_empty(), "nothing new to start");
3143 assert_eq!(removed, vec!["owner/gone".to_string()]);
3144 }
3145
3146 #[test]
3147 fn an_unchanged_project_list_starts_nothing() {
3148 let configured = vec![(
3149 "owner/one".to_string(),
3150 std::path::PathBuf::from("/srv/one"),
3151 )];
3152 let active: std::collections::HashSet<String> =
3153 ["owner/one".to_string()].into_iter().collect();
3154
3155 assert_eq!(
3156 diff_configured_projects(&configured, &active),
3157 (vec![], vec![])
3158 );
3159 }
3160
3161 #[test]
3162 fn restart_only_keys_are_the_settings_read_once_at_startup() {
3163 assert_eq!(RESTART_ONLY_KEYS, ["channels", "webhook", "relay"]);
3166 }
3167
3168 #[test]
3169 fn a_changed_restart_only_key_is_reported_and_an_unchanged_one_is_not() {
3170 let before = vec![Some("bot_token: a\n".to_string()), None];
3171
3172 assert!(
3173 log_restart_only_changes(&before, &before.clone()).is_empty(),
3174 "a reload that did not touch these keys must stay quiet"
3175 );
3176
3177 let after = vec![
3179 Some("bot_token: b\n".to_string()),
3180 Some("port: 8080\n".to_string()),
3181 ];
3182 assert_eq!(
3183 log_restart_only_changes(&before, &after),
3184 ["channels", "webhook"]
3185 );
3186
3187 let token_only = vec![Some("bot_token: b\n".to_string()), None];
3189 assert_eq!(log_restart_only_changes(&before, &token_only), ["channels"]);
3190 }
3191
3192 #[test]
3193 fn resize_dispatch_pool_is_a_noop_at_the_current_limit() {
3194 let semaphore = Arc::new(Semaphore::new(4));
3195 assert_eq!(resize_dispatch_pool(&semaphore, 4, 4), 4);
3196 assert_eq!(semaphore.available_permits(), 4);
3197 }
3198
3199 #[test]
3200 fn engine_config_defaults() {
3201 let config = EngineConfig::default();
3202 assert_eq!(config.tick_interval, std::time::Duration::from_secs(10));
3203 assert_eq!(config.sync_interval, std::time::Duration::from_secs(45));
3204 assert_eq!(config.max_parallel, 4);
3205 assert_eq!(config.stuck_timeout, 1800);
3206 assert_eq!(config.no_session_stuck_timeout, 600);
3207 assert!(
3208 config.no_session_stuck_timeout < config.stuck_timeout,
3209 "no_session_stuck_timeout must be shorter than stuck_timeout"
3210 );
3211 assert_eq!(
3212 config.graceful_shutdown_timeout,
3213 std::time::Duration::from_secs(600)
3214 );
3215 assert_eq!(config.upgrade_check_interval, 3600);
3216 }
3217
3218 #[test]
3219 fn engine_config_from_config_uses_defaults_when_no_config() {
3220 let config = EngineConfig::from_config();
3221 assert_eq!(config.tick_interval, std::time::Duration::from_secs(10));
3222 assert_eq!(config.sync_interval, std::time::Duration::from_secs(45));
3223 assert!(config.max_parallel >= 1 && config.max_parallel <= 64);
3225 assert_eq!(config.stuck_timeout, 1800);
3226 assert_eq!(config.no_session_stuck_timeout, 600);
3227 assert_eq!(
3228 config.graceful_shutdown_timeout,
3229 std::time::Duration::from_secs(600)
3230 );
3231 assert_eq!(config.upgrade_check_interval, 3600);
3232 }
3233
3234 #[test]
3235 fn engine_config_no_session_timeout_is_under_15_minutes() {
3236 let config = EngineConfig::default();
3237 assert!(
3238 config.no_session_stuck_timeout <= 900,
3239 "no_session_stuck_timeout ({}) exceeds 15 minutes",
3240 config.no_session_stuck_timeout
3241 );
3242 }
3243
3244 #[test]
3245 fn upgrade_check_runs_immediately_when_never_checked() {
3246 assert!(should_run_upgrade_check(None, 3600));
3247 }
3248
3249 #[test]
3250 fn upgrade_check_waits_for_interval_after_first_run() {
3251 assert!(!should_run_upgrade_check(
3252 Some(std::time::Instant::now()),
3253 3600
3254 ));
3255 }
3256
3257 #[test]
3258 fn upgrade_check_can_be_disabled() {
3259 assert!(!should_run_upgrade_check(None, 0));
3260 }
3261
3262 #[test]
3263 fn configured_agents_parses_yaml_block_array() {
3264 let yaml_str = "- claude\n- codex\n- opencode\n- olm\n";
3266 let parsed: Vec<String> = serde_norway::from_str(yaml_str).unwrap();
3267 assert_eq!(parsed, vec!["claude", "codex", "opencode", "olm"]);
3268 }
3269
3270 #[test]
3271 fn configured_agents_parses_json_inline_array() {
3272 let json_str = r#"["claude","codex","olm"]"#;
3273 let parsed: Vec<String> = serde_json::from_str(json_str).unwrap();
3274 assert_eq!(parsed, vec!["claude", "codex", "olm"]);
3275 }
3276
3277 #[test]
3278 fn configured_agents_fallback_returns_default_agents() {
3279 let defaults = configured_agents();
3281 assert!(defaults.contains(&"claude".to_string()));
3282 assert!(defaults.contains(&"codex".to_string()));
3283 assert!(defaults.contains(&"opencode".to_string()));
3284 }
3285
3286 #[tokio::test]
3295 #[ignore]
3296 async fn integration_channel_to_tmux_to_capture() {
3297 use crate::channels::capture::CaptureService;
3298 use crate::channels::transport::Transport;
3299 use crate::tmux::{SessionGuard, TmuxManager};
3300 use std::sync::Arc;
3301
3302 let transport = Arc::new(Transport::new());
3304 let capture = Arc::new(CaptureService::new(transport.clone()));
3305 let tmux = TmuxManager::new();
3306
3307 let task_id = "testtask1".to_string();
3308 let session_name = format!("orch-test-{}", task_id);
3309
3310 let _ = tmux
3312 .command()
3313 .args(["new-session", "-d", "-s", &session_name])
3314 .output()
3315 .await
3316 .expect("failed to start tmux session");
3317
3318 let _guard = SessionGuard(session_name.clone());
3320
3321 capture
3323 .register_session("owner/repo", &task_id, &session_name)
3324 .await;
3325 transport
3326 .bind(
3327 "owner/repo",
3328 &task_id,
3329 &session_name,
3330 "telegram",
3331 "12345",
3332 None,
3333 )
3334 .await;
3335
3336 let capture_clone = capture.clone();
3338 let capture_handle = tokio::spawn(async move { capture_clone.run().await });
3339
3340 let mut rx = transport
3342 .subscribe("owner/repo", &task_id)
3343 .await
3344 .expect("no subscription");
3345
3346 let send = tmux
3348 .command()
3349 .args([
3350 "send-keys",
3351 "-t",
3352 &session_name,
3353 "echo from-channel",
3354 "Enter",
3355 ])
3356 .output()
3357 .await
3358 .expect("failed to send keys");
3359 assert!(send.status.success());
3360
3361 let mut got = false;
3363 for _ in 0..20 {
3364 if let Ok(Ok(c)) =
3365 tokio::time::timeout(std::time::Duration::from_millis(500), rx.recv()).await
3366 {
3367 if c.content.contains("from-channel") {
3368 got = true;
3369 break;
3370 }
3371 }
3372 }
3373
3374 capture.unregister_session("owner/repo", &task_id).await;
3376
3377 let _ = capture_handle.await;
3379
3380 assert!(got, "did not observe tmux output via capture/transport");
3381 }
3382
3383 #[test]
3386 fn read_project_channel_config_returns_defaults_when_no_file() {
3387 let dir = tempfile::tempdir().expect("tempdir");
3388 let cfg = read_project_channel_config(dir.path());
3389 assert!(cfg.telegram_topic_id.is_none());
3390 assert!(cfg.discord_channel_id.is_none());
3391 }
3392
3393 #[test]
3394 fn read_project_channel_config_parses_telegram_and_discord() {
3395 let dir = tempfile::tempdir().expect("tempdir");
3396 let orch_yml = dir.path().join(".orch.yml");
3397 std::fs::write(
3398 &orch_yml,
3399 "channels:\n telegram:\n topic_id: \"42\"\n discord:\n channel_id: \"9999\"\n",
3400 )
3401 .expect("write .orch.yml");
3402 let cfg = read_project_channel_config(dir.path());
3403 assert_eq!(cfg.telegram_topic_id.as_deref(), Some("42"));
3404 assert_eq!(cfg.discord_channel_id.as_deref(), Some("9999"));
3405 }
3406
3407 #[test]
3408 fn read_project_channel_config_handles_partial_channels() {
3409 let dir = tempfile::tempdir().expect("tempdir");
3410 let orch_yml = dir.path().join(".orch.yml");
3411 std::fs::write(&orch_yml, "channels:\n telegram:\n topic_id: \"7\"\n")
3412 .expect("write .orch.yml");
3413 let cfg = read_project_channel_config(dir.path());
3414 assert_eq!(cfg.telegram_topic_id.as_deref(), Some("7"));
3415 assert!(cfg.discord_channel_id.is_none());
3416 }
3417
3418 #[test]
3419 fn read_project_channel_config_handles_malformed_yaml() {
3420 let dir = tempfile::tempdir().expect("tempdir");
3421 let orch_yml = dir.path().join(".orch.yml");
3422 std::fs::write(&orch_yml, "channels: [\nbad yaml").expect("write .orch.yml");
3423 let cfg = read_project_channel_config(dir.path());
3424 assert!(cfg.telegram_topic_id.is_none());
3426 assert!(cfg.discord_channel_id.is_none());
3427 }
3428
3429 #[test]
3430 #[cfg(unix)]
3431 fn read_project_channel_config_handles_unreadable_file() {
3432 let dir = tempfile::tempdir().expect("tempdir");
3433 std::fs::create_dir(dir.path().join(".orch.yml")).expect("create .orch.yml dir");
3435 let cfg = read_project_channel_config(dir.path());
3436 assert!(cfg.telegram_topic_id.is_none());
3438 assert!(cfg.discord_channel_id.is_none());
3439 }
3440}