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(
2236 match tokio::task::spawn_blocking(Router::from_config).await {
2237 Ok(r) => r,
2238 Err(e) => {
2239 tracing::error!(?e, "router init panicked in spawn_blocking, using default");
2240 tokio::task::spawn_blocking(|| Router::new(RouterConfig::default()))
2241 .await
2242 .unwrap_or_else(|e2| {
2243 panic!("router default init also panicked in spawn_blocking — cannot start engine without a router: {e2:?}");
2244 })
2245 }
2246 },
2247 ));
2248 {
2249 let r = router.read().await;
2250 tracing::info!(
2251 mode = %r.config.mode,
2252 agents = ?r.available_agents,
2253 fallback = %r.config.fallback_executor,
2254 "router initialized"
2255 );
2256 }
2257
2258 let semaphore = Arc::new(Semaphore::new(config.max_parallel));
2262 let mut parallel_in_force = config.max_parallel;
2263
2264 let dispatching: Arc<dashmap::DashMap<String, String>> = Arc::new(dashmap::DashMap::new());
2271
2272 let auto_merge_in_flight: Arc<dashmap::DashSet<String>> = Arc::new(dashmap::DashSet::new());
2276
2277 let mut config_rx = crate::config::subscribe();
2279
2280 let mut last_sync = std::time::Instant::now();
2282
2283 let mut last_upgrade_check: Option<std::time::Instant> = None;
2285
2286 let mut rate_limit_reported: Option<i64> = None;
2289
2290 let (weight_tx, mut weight_rx) = mpsc::channel::<WeightSignal>(64);
2292
2293 for engine in project_engines.iter().filter(|_| leads) {
2295 let reset =
2296 reset_orphaned_reviews(&engine.task_manager, &engine.store, &engine.repo, &tmux).await;
2297
2298 if reset > 0 {
2299 tracing::info!(repo = %engine.repo, reset, "reset orphaned reviews to needs_review on startup");
2300 }
2301 }
2302
2303 for engine in &project_engines {
2305 subscribers::dispatch::spawn(
2306 event_bus.subscribe(),
2307 engine.backend.clone(),
2308 tmux.clone(),
2309 engine.runner.clone(),
2310 capture_for_tick.clone(),
2311 semaphore.clone(),
2312 engine.task_manager.clone(),
2313 weight_tx.clone(),
2314 router.clone(),
2315 dispatching.clone(),
2316 engine.store.clone(),
2317 engine.repo.clone(),
2318 );
2319 }
2320 tracing::info!("dispatch subscriber started");
2321
2322 for engine in &project_engines {
2324 subscribers::review::spawn(
2325 event_bus.subscribe(),
2326 engine.backend.clone(),
2327 tmux.clone(),
2328 semaphore.clone(),
2329 engine.task_manager.clone(),
2330 router.clone(),
2331 dispatching.clone(),
2332 engine.store.clone(),
2333 engine.repo.clone(),
2334 );
2335 }
2336 tracing::info!("review subscriber started");
2337
2338 for engine in &project_engines {
2340 subscribers::unblock::spawn(
2341 event_bus.subscribe(),
2342 engine.backend.clone(),
2343 engine.task_manager.clone(),
2344 engine.store.clone(),
2345 engine.repo.clone(),
2346 );
2347 }
2348 tracing::info!("unblock subscriber started");
2349
2350 subscribers::notify::spawn(event_bus.subscribe(), transport.clone());
2353 tracing::info!("notify subscriber started");
2354
2355 tracing::info!(
2357 tick = ?config.tick_interval,
2358 sync = ?config.sync_interval,
2359 parallel = config.max_parallel,
2360 "entering main loop"
2361 );
2362 let mut restart_only = restart_only_snapshot();
2365
2366 let mut interval = tokio::time::interval(config.tick_interval);
2367
2368 let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
2370 let mut sighup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
2371
2372 let sync_in_progress = Arc::new(std::sync::atomic::AtomicBool::new(false));
2374
2375 let last_tick_epoch = Arc::new(std::sync::atomic::AtomicU64::new(
2378 std::time::SystemTime::now()
2379 .duration_since(std::time::UNIX_EPOCH)
2380 .unwrap_or_default()
2381 .as_secs(),
2382 ));
2383 {
2384 let last_tick_epoch = Arc::clone(&last_tick_epoch);
2385 let tick_interval_secs = config.tick_interval.as_secs();
2386 tokio::spawn(async move {
2387 let mut watchdog_interval = tokio::time::interval(std::time::Duration::from_secs(30));
2389 let mut suspend_detector = crate::engine::suspend::SuspendDetector::new();
2394 loop {
2395 watchdog_interval.tick().await;
2396 let own_gap = suspend_detector.check();
2397 let last = last_tick_epoch.load(std::sync::atomic::Ordering::Relaxed);
2398 let now = std::time::SystemTime::now()
2399 .duration_since(std::time::UNIX_EPOCH)
2400 .unwrap_or_default()
2401 .as_secs();
2402 let stale_secs = now.saturating_sub(last);
2403 let threshold = (tick_interval_secs * 6).max(60);
2405 if stale_secs > threshold {
2406 let shared_gap = crate::engine::suspend::gap_detected_within(
2413 std::time::Duration::from_secs(stale_secs),
2414 );
2415 let gap = match (own_gap, shared_gap) {
2416 (Some(a), Some(b)) => Some(a.max(b)),
2417 (Some(a), None) => Some(a),
2418 (None, Some(b)) => Some(b),
2419 (None, None) => None,
2420 };
2421 if let Some(gap) = gap {
2422 let gap_secs = gap.num_seconds() as u64;
2423 if gap_secs >= stale_secs {
2424 tracing::info!(
2425 stale_secs,
2426 threshold,
2427 suspend_gap_secs = gap_secs,
2428 "tick loop stale window explained by host suspend/resume, not a stall"
2429 );
2430 } else {
2431 tracing::error!(
2432 stale_secs,
2433 threshold,
2434 suspend_gap_secs = gap_secs,
2435 "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — suspend gap of {}s only partially explains the stall",
2436 stale_secs,
2437 threshold,
2438 gap_secs,
2439 );
2440 }
2441 } else {
2442 tracing::error!(
2443 stale_secs,
2444 threshold,
2445 "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — possible stall",
2446 stale_secs,
2447 threshold,
2448 );
2449 }
2450 }
2451 }
2452 });
2453 }
2454
2455 loop {
2456 tokio::select! {
2457 _ = interval.tick() => {
2458 let tick_start = std::time::Instant::now();
2459
2460 if let Some(gap) = crate::engine::suspend::checkpoint() {
2464 tracing::info!(
2465 gap_secs = gap.num_seconds(),
2466 "host suspend/resume gap detected, discounting from stuck-task age checks"
2467 );
2468 }
2469
2470 if parallel_in_force != config.max_parallel {
2474 let resized =
2475 resize_dispatch_pool(&semaphore, parallel_in_force, config.max_parallel);
2476 if resized != parallel_in_force {
2477 parallel_in_force = resized;
2478 tracing::info!(
2479 in_force = parallel_in_force,
2480 target = config.max_parallel,
2481 "dispatch pool resized"
2482 );
2483 }
2484 }
2485
2486 {
2488 let mut rw = router.write().await;
2489 rw.tick_weight_recovery();
2490 }
2491
2492 if let Some(remaining) = GhHttp::is_rate_limited() {
2496 let reset_at = chrono::Utc::now()
2497 .timestamp()
2498 .saturating_add(i64::try_from(remaining.as_secs()).unwrap_or(i64::MAX));
2499 if rate_limit_reported.is_none_or(|prev| (reset_at - prev).abs() > 60) {
2501 rate_limit_reported = Some(reset_at);
2502 report_rate_limited(reset_at, project_engines.first().map(|e| &e.store), Some(&transport)).await;
2503 }
2504 } else if let Some(prev) = rate_limit_reported.take() {
2505 tracing::info!(
2506 limited_until = prev,
2507 "GitHub API rate limit cleared"
2508 );
2509 if let Some(engine) = project_engines.first() {
2510 let _ = engine.store.kv_delete(RATE_LIMITED_UNTIL_KEY).await;
2511 }
2512 }
2513
2514 tick::tick_all(
2516 &project_engines,
2517 &tmux,
2518 &capture_for_tick,
2519 &semaphore,
2520 &config,
2521 &router,
2522 &weight_tx,
2523 &dispatching,
2524 Some(&transport),
2525 &active_repos,
2526 &auto_merge_in_flight,
2527 ).await;
2528
2529 while let Ok(signal) = weight_rx.try_recv() {
2532 let mut rw = router.write().await;
2533 match signal {
2534 WeightSignal::RateLimited { ref agent } => {
2535 rw.record_rate_limit(agent);
2536 }
2537 WeightSignal::Success { ref agent } => {
2538 rw.record_success(agent);
2539 }
2540 WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
2541 }
2542 }
2543
2544 if last_sync.elapsed() >= config.sync_interval {
2549 if sync_in_progress.compare_exchange(
2550 false,
2551 true,
2552 std::sync::atomic::Ordering::AcqRel,
2553 std::sync::atomic::Ordering::Relaxed,
2554 ).is_ok() {
2555 spawn_sync_pass(
2556 &project_engines,
2557 &tmux,
2558 &config,
2559 &router,
2560 &dispatching,
2561 &auto_merge_in_flight,
2562 &sync_in_progress,
2563 "periodic",
2564 );
2565 } else {
2566 tracing::debug!("sync tick still in progress, skipping");
2567 }
2568 last_sync = std::time::Instant::now();
2572 }
2573
2574 if webhook_enabled {
2576 let health_check_interval = config.webhook_health_check_interval
2577 .unwrap_or(std::time::Duration::from_secs(60));
2578
2579 if last_webhook_health_check.elapsed() >= health_check_interval {
2580 if let Some(port) = webhook_port {
2581 let (health, failure_reason) =
2582 crate::channels::github::check_webhook_health(port).await;
2583 if health != webhook_healthy {
2584 webhook_healthy = health;
2585 if webhook_healthy {
2586 tracing::info!(port, orch_webhook_up = true, "webhook health restored");
2587 } else {
2588 tracing::warn!(
2589 port,
2590 orch_webhook_up = false,
2591 reason = failure_reason.as_deref().unwrap_or("unknown"),
2592 "webhook health check failed"
2593 );
2594 }
2595 }
2596 {
2598 let to_save = {
2599 let mut s = webhook_status.lock().await;
2600 s.healthy = health;
2601 s.last_check_utc = Some(chrono::Utc::now());
2602 if health {
2603 s.last_failure_reason = None;
2604 } else if failure_reason.is_some() {
2605 s.last_failure_reason = failure_reason;
2606 }
2607 s.clone()
2608 };
2609 to_save.save().await;
2610 }
2611 }
2612 last_webhook_health_check = std::time::Instant::now();
2613 }
2614 }
2615
2616 if should_run_upgrade_check(last_upgrade_check, config.upgrade_check_interval) {
2618 if let Some(store) = project_engines.first().map(|e| e.store.clone()) {
2619 let channels = channel_registry.clone();
2620 let current = env!("ORCH_VERSION").to_string();
2621 let check_interval =
2622 std::time::Duration::from_secs(config.upgrade_check_interval);
2623 tokio::spawn(async move {
2624 check_and_notify_upgrade(&store, &channels, ¤t, check_interval)
2625 .await;
2626 });
2627 }
2628 last_upgrade_check = Some(std::time::Instant::now());
2629 }
2630
2631 let tick_elapsed = tick_start.elapsed();
2633 if tick_elapsed.as_secs() > 30 {
2634 tracing::warn!(elapsed_ms = tick_elapsed.as_millis() as u64, "slow tick");
2635 } else {
2636 tracing::debug!(elapsed_ms = tick_elapsed.as_millis() as u64, "tick complete");
2637 }
2638 last_tick_epoch.store(
2639 std::time::SystemTime::now()
2640 .duration_since(std::time::UNIX_EPOCH)
2641 .unwrap_or_default()
2642 .as_secs(),
2643 std::sync::atomic::Ordering::Relaxed,
2644 );
2645 }
2646 _ = webhook_notify.notified() => {
2648 if let Some(remaining) = GhHttp::is_rate_limited() {
2649 tracing::warn!(
2650 remaining_secs = remaining.as_secs(),
2651 "GitHub API rate-limited, skipping webhook-triggered tick"
2652 );
2653 } else {
2654 tracing::info!("webhook event triggered immediate tick");
2655
2656 tick::tick_all(
2657 &project_engines,
2658 &tmux,
2659 &capture_for_tick,
2660 &semaphore,
2661 &config,
2662 &router,
2663 &weight_tx,
2664 &dispatching,
2665 Some(&transport),
2666 &active_repos,
2667 &auto_merge_in_flight,
2668 ).await;
2669
2670 while let Ok(signal) = weight_rx.try_recv() {
2672 let mut rw = router.write().await;
2673 match signal {
2674 WeightSignal::RateLimited { ref agent } => {
2675 rw.record_rate_limit(agent);
2676 }
2677 WeightSignal::Success { ref agent } => {
2678 rw.record_success(agent);
2679 }
2680 WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
2681 }
2682 }
2683
2684 if sync_in_progress.compare_exchange(
2690 false,
2691 true,
2692 std::sync::atomic::Ordering::AcqRel,
2693 std::sync::atomic::Ordering::Relaxed,
2694 ).is_ok() {
2695 spawn_sync_pass(
2696 &project_engines,
2697 &tmux,
2698 &config,
2699 &router,
2700 &dispatching,
2701 &auto_merge_in_flight,
2702 &sync_in_progress,
2703 "webhook",
2704 );
2705 last_sync = std::time::Instant::now();
2707 } else {
2708 tracing::debug!("sync tick still in progress, skipping webhook-triggered immediate sync");
2709 }
2710 }
2711
2712 interval.reset();
2714 }
2715 result = config_rx.recv() => {
2716 let reload = match result {
2719 Ok(path) => {
2720 tracing::info!(path = %path.display(), "config file changed, reloading");
2721 true
2722 }
2723 Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
2724 tracing::warn!(missed = n, "config change receiver lagged, reloading");
2725 true
2726 }
2727 Err(tokio::sync::broadcast::error::RecvError::Closed) => {
2728 tracing::warn!("config change channel closed");
2729 false
2730 }
2731 };
2732
2733 if reload {
2734 let new_config = EngineConfig::from_config();
2736 log_engine_config_changes(&config, &new_config);
2737
2738 let new_restart_only = restart_only_snapshot();
2739 log_restart_only_changes(&restart_only, &new_restart_only);
2740 restart_only = new_restart_only;
2741
2742 let tick_changed = new_config.tick_interval != config.tick_interval;
2743 config = new_config;
2744
2745 if tick_changed {
2747 interval = tokio::time::interval(config.tick_interval);
2748 tracing::info!(tick = ?config.tick_interval, "tick interval updated");
2749 }
2750
2751 if parallel_in_force != config.max_parallel {
2754 parallel_in_force = resize_dispatch_pool(
2755 &semaphore,
2756 parallel_in_force,
2757 config.max_parallel,
2758 );
2759 tracing::info!(
2760 in_force = parallel_in_force,
2761 target = config.max_parallel,
2762 "dispatch pool resized"
2763 );
2764 }
2765
2766 {
2768 let mut router_guard = router.write().await;
2769 router_guard.reload_async().await;
2770 }
2771
2772 sync_project_engines(
2774 &mut project_engines,
2775 &mut active_repos,
2776 &event_bus,
2777 &tmux,
2778 &capture_for_tick,
2779 &semaphore,
2780 &weight_tx,
2781 &router,
2782 &dispatching,
2783 ).await;
2784
2785 tracing::info!(
2786 tick = ?config.tick_interval,
2787 sync = ?config.sync_interval,
2788 parallel = config.max_parallel,
2789 projects = project_engines.len(),
2790 "config reloaded"
2791 );
2792 }
2793 }
2794 signal_name = async {
2795 tokio::select! {
2796 _ = tokio::signal::ctrl_c() => "SIGINT",
2797 _ = sigterm.recv() => "SIGTERM",
2798 _ = sighup.recv() => "SIGHUP",
2799 }
2800 } => {
2801 tracing::info!(signal = signal_name, "beginning graceful shutdown");
2802
2803 let shutdown_result = tokio::time::timeout(
2806 config.graceful_shutdown_timeout,
2807 async {
2808 let mut reset_count = 0u32;
2812 let mut review_reset_count = 0u32;
2813 for engine in &project_engines {
2814 if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InProgress).await {
2815 for task in &tasks {
2816 if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::Routed).await {
2817 tracing::warn!(task_id = task.id.0, ?e, "failed to reset task on shutdown");
2818 } else {
2819 if let Ok(Some(store_id)) =
2820 engine.store.resolve_task_id(&engine.repo, &task.id.0).await
2821 {
2822 if let Err(e) = engine
2823 .store
2824 .finalize_incomplete_runs(
2825 store_id,
2826 "aborted",
2827 "graceful shutdown: reset in_progress task to routed",
2828 )
2829 .await
2830 {
2831 tracing::warn!(
2832 task_id = task.id.0,
2833 ?e,
2834 "failed to finalize incomplete runs on shutdown"
2835 );
2836 }
2837 }
2838 reset_count += 1;
2839 }
2840 }
2841 }
2842 if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, crate::store::TaskStatus::InProgress).await {
2844 for task in &tasks {
2845 let task_id = format!("internal:{}", task.id);
2846 if let Err(e) = engine.task_manager.update_task_status(
2847 &crate::backends::ExternalId(task_id.clone()),
2848 Status::Routed,
2849 ).await {
2850 tracing::warn!(task_id, ?e, "failed to reset internal task on shutdown");
2851 } else {
2852 if let Err(e) = engine
2853 .store
2854 .finalize_incomplete_runs(
2855 task.id,
2856 "aborted",
2857 "graceful shutdown: reset in_progress task to routed",
2858 )
2859 .await
2860 {
2861 tracing::warn!(
2862 task_id,
2863 ?e,
2864 "failed to finalize incomplete internal runs on shutdown"
2865 );
2866 }
2867 reset_count += 1;
2868 }
2869 }
2870 }
2871 if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InReview).await {
2873 for task in &tasks {
2874 if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::NeedsReview).await {
2875 tracing::warn!(task_id = task.id.0, ?e, "failed to reset in_review task on shutdown");
2876 } else {
2877 if let Ok(Some(store_id)) =
2878 engine.store.resolve_task_id(&engine.repo, &task.id.0).await
2879 {
2880 if let Err(e) = engine
2881 .store
2882 .finalize_incomplete_runs(
2883 store_id,
2884 "aborted",
2885 "graceful shutdown: reset in_review task to needs_review",
2886 )
2887 .await
2888 {
2889 tracing::warn!(
2890 task_id = task.id.0,
2891 ?e,
2892 "failed to finalize incomplete review runs on shutdown"
2893 );
2894 }
2895 }
2896 review_reset_count += 1;
2897 }
2898 }
2899 }
2900 if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, crate::store::TaskStatus::InReview).await {
2902 for task in &tasks {
2903 let task_id = format!("internal:{}", task.id);
2904 if let Err(e) = engine.task_manager.update_task_status(
2905 &crate::backends::ExternalId(task_id.clone()),
2906 Status::NeedsReview,
2907 ).await {
2908 tracing::warn!(task_id, ?e, "failed to reset internal in_review task on shutdown");
2909 } else {
2910 if let Err(e) = engine
2911 .store
2912 .finalize_incomplete_runs(
2913 task.id,
2914 "aborted",
2915 "graceful shutdown: reset in_review task to needs_review",
2916 )
2917 .await
2918 {
2919 tracing::warn!(
2920 task_id,
2921 ?e,
2922 "failed to finalize incomplete internal review runs on shutdown"
2923 );
2924 }
2925 review_reset_count += 1;
2926 }
2927 }
2928 }
2929 }
2930 if reset_count > 0 {
2931 tracing::info!(reset_count, "reset in_progress tasks to routed for re-dispatch");
2932 }
2933 if review_reset_count > 0 {
2934 tracing::info!(review_reset_count, "reset in_review tasks to needs_review for re-dispatch");
2935 }
2936
2937 let mut killed_sessions = Vec::new();
2940 if let Ok(sessions) = tmux.list_sessions().await {
2941 for session in &sessions {
2942 if session.name.starts_with("orch-") {
2943 if let Err(e) = tmux.kill_session(&session.name).await {
2944 tracing::warn!(session = %session.name, error = %e, "failed to kill tmux session");
2945 } else {
2946 killed_sessions.push(session.name.clone());
2947 }
2948 }
2949 }
2950 if !killed_sessions.is_empty() {
2951 tracing::info!(killed = killed_sessions.len(), "killing orch tmux sessions on shutdown");
2952 }
2953 }
2954
2955 if !killed_sessions.is_empty() {
2958 let still_alive = tmux
2959 .wait_for_sessions_dead(
2960 &killed_sessions,
2961 std::time::Duration::from_millis(100),
2962 std::time::Duration::from_secs(5),
2963 )
2964 .await;
2965 if still_alive > 0 {
2966 tracing::warn!(
2967 still_alive,
2968 "some tmux sessions did not terminate cleanly - they will be cleaned up on startup"
2969 );
2970 }
2971 tracing::info!(killed = killed_sessions.len() - still_alive, "confirmed tmux sessions terminated");
2972 }
2973 },
2974 ).await;
2975
2976 if shutdown_result.is_err() {
2977 tracing::error!(
2978 timeout_secs = config.graceful_shutdown_timeout.as_secs(),
2979 "graceful shutdown timed out, forcing exit"
2980 );
2981 }
2982
2983 break;
2984 }
2985 }
2986 }
2987
2988 events::cleanup_port_file().await;
2990 crate::cluster::local::cleanup().await;
2991 events::cleanup_version_file();
2992
2993 let _ = transport;
2995 tracing::info!("orch engine stopped");
2996 Ok(())
2997}
2998
2999#[cfg(test)]
3000mod tests {
3001 use super::*;
3002
3003 async fn in_review_task(store: &TaskStore, number: &str) -> i64 {
3004 let id = store
3005 .upsert_external(&crate::store::UpsertExternal {
3006 repo: "owner/repo",
3007 ext_id: number,
3008 title: "Under review",
3009 body: "",
3010 author: "",
3011 url: "",
3012 labels: &[],
3013 origin: "github",
3014 })
3015 .await
3016 .unwrap();
3017 store
3018 .update_status(id, crate::store::TaskStatus::InReview)
3019 .await
3020 .unwrap();
3021 id
3022 }
3023
3024 #[tokio::test]
3025 async fn a_review_without_a_session_goes_back_to_needs_review_and_a_live_one_stays() {
3026 let store = Arc::new(TaskStore::open_memory().await.unwrap());
3027 let backend: Arc<dyn ExternalBackend> =
3028 Arc::new(crate::backends::test_helpers::NoopBackend);
3029 let task_manager =
3030 TaskManager::with_store(backend, store.clone(), "owner/repo".to_string());
3031 let tmux = TmuxManager::isolated();
3032 let orphaned = in_review_task(&store, "11").await;
3033 let live = in_review_task(&store, "12").await;
3034 let session = tmux
3035 .create_session("owner/repo", "12-review", "/tmp", "sleep 30", &[])
3036 .await
3037 .unwrap();
3038 let _guard = crate::tmux::SessionGuard(session);
3039
3040 let reset = reset_orphaned_reviews(&task_manager, &store, "owner/repo", &tmux).await;
3041
3042 assert_eq!(reset, 1);
3043 assert_eq!(
3044 store.get(orphaned).await.unwrap().status,
3045 crate::store::TaskStatus::NeedsReview
3046 );
3047 assert_eq!(
3048 store.get(live).await.unwrap().status,
3049 crate::store::TaskStatus::InReview
3050 );
3051 }
3052
3053 #[test]
3054 fn growing_max_parallel_lets_more_tasks_run_without_a_restart() {
3055 let semaphore = Arc::new(Semaphore::new(4));
3056 let held: Vec<_> = (0..4)
3057 .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3058 .collect();
3059 assert!(
3060 semaphore.clone().try_acquire_owned().is_err(),
3061 "pool is full"
3062 );
3063
3064 let in_force = resize_dispatch_pool(&semaphore, 4, 8);
3065 assert_eq!(in_force, 8);
3066
3067 let grown: Vec<_> = (0..4)
3068 .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3069 .collect();
3070 assert_eq!(held.len() + grown.len(), 8, "8 tasks run at once");
3071 assert!(
3072 semaphore.clone().try_acquire_owned().is_err(),
3073 "pool is full"
3074 );
3075 }
3076
3077 #[test]
3078 fn shrinking_max_parallel_never_cancels_a_running_task() {
3079 let semaphore = Arc::new(Semaphore::new(8));
3080 let mut held: Vec<_> = (0..8)
3081 .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3082 .collect();
3083
3084 let mut in_force = resize_dispatch_pool(&semaphore, 8, 4);
3086 assert_eq!(in_force, 8);
3087 assert_eq!(held.len(), 8);
3088
3089 held.truncate(5);
3091 in_force = resize_dispatch_pool(&semaphore, in_force, 4);
3092 assert_eq!(in_force, 5);
3093 assert!(semaphore.clone().try_acquire_owned().is_err());
3094
3095 held.truncate(4);
3097 in_force = resize_dispatch_pool(&semaphore, in_force, 4);
3098 assert_eq!(in_force, 4);
3099 assert!(semaphore.clone().try_acquire_owned().is_err());
3100
3101 held.truncate(3);
3103 assert!(semaphore.clone().try_acquire_owned().is_ok());
3104 }
3105
3106 #[test]
3107 fn a_project_added_to_the_config_is_picked_up_and_running_ones_are_not_respawned() {
3108 let configured = vec![
3109 (
3110 "owner/one".to_string(),
3111 std::path::PathBuf::from("/srv/one"),
3112 ),
3113 (
3114 "owner/two".to_string(),
3115 std::path::PathBuf::from("/srv/two"),
3116 ),
3117 ];
3118 let active: std::collections::HashSet<String> =
3119 ["owner/one".to_string()].into_iter().collect();
3120
3121 let (added, removed) = diff_configured_projects(&configured, &active);
3122 assert_eq!(
3123 added,
3124 vec![(
3125 "owner/two".to_string(),
3126 std::path::PathBuf::from("/srv/two")
3127 )],
3128 "only the new project is started, so owner/one keeps its single set of subscribers"
3129 );
3130 assert!(removed.is_empty());
3131 }
3132
3133 #[test]
3134 fn a_project_dropped_from_the_config_is_reported_and_not_restarted() {
3135 let configured = vec![(
3136 "owner/one".to_string(),
3137 std::path::PathBuf::from("/srv/one"),
3138 )];
3139 let active: std::collections::HashSet<String> =
3140 ["owner/one".to_string(), "owner/gone".to_string()]
3141 .into_iter()
3142 .collect();
3143
3144 let (added, removed) = diff_configured_projects(&configured, &active);
3145 assert!(added.is_empty(), "nothing new to start");
3146 assert_eq!(removed, vec!["owner/gone".to_string()]);
3147 }
3148
3149 #[test]
3150 fn an_unchanged_project_list_starts_nothing() {
3151 let configured = vec![(
3152 "owner/one".to_string(),
3153 std::path::PathBuf::from("/srv/one"),
3154 )];
3155 let active: std::collections::HashSet<String> =
3156 ["owner/one".to_string()].into_iter().collect();
3157
3158 assert_eq!(
3159 diff_configured_projects(&configured, &active),
3160 (vec![], vec![])
3161 );
3162 }
3163
3164 #[test]
3165 fn restart_only_keys_are_the_settings_read_once_at_startup() {
3166 assert_eq!(RESTART_ONLY_KEYS, ["channels", "webhook", "relay"]);
3169 }
3170
3171 #[test]
3172 fn a_changed_restart_only_key_is_reported_and_an_unchanged_one_is_not() {
3173 let before = vec![Some("bot_token: a\n".to_string()), None];
3174
3175 assert!(
3176 log_restart_only_changes(&before, &before.clone()).is_empty(),
3177 "a reload that did not touch these keys must stay quiet"
3178 );
3179
3180 let after = vec![
3182 Some("bot_token: b\n".to_string()),
3183 Some("port: 8080\n".to_string()),
3184 ];
3185 assert_eq!(
3186 log_restart_only_changes(&before, &after),
3187 ["channels", "webhook"]
3188 );
3189
3190 let token_only = vec![Some("bot_token: b\n".to_string()), None];
3192 assert_eq!(log_restart_only_changes(&before, &token_only), ["channels"]);
3193 }
3194
3195 #[test]
3196 fn resize_dispatch_pool_is_a_noop_at_the_current_limit() {
3197 let semaphore = Arc::new(Semaphore::new(4));
3198 assert_eq!(resize_dispatch_pool(&semaphore, 4, 4), 4);
3199 assert_eq!(semaphore.available_permits(), 4);
3200 }
3201
3202 #[test]
3203 fn engine_config_defaults() {
3204 let config = EngineConfig::default();
3205 assert_eq!(config.tick_interval, std::time::Duration::from_secs(10));
3206 assert_eq!(config.sync_interval, std::time::Duration::from_secs(45));
3207 assert_eq!(config.max_parallel, 4);
3208 assert_eq!(config.stuck_timeout, 1800);
3209 assert_eq!(config.no_session_stuck_timeout, 600);
3210 assert!(
3211 config.no_session_stuck_timeout < config.stuck_timeout,
3212 "no_session_stuck_timeout must be shorter than stuck_timeout"
3213 );
3214 assert_eq!(
3215 config.graceful_shutdown_timeout,
3216 std::time::Duration::from_secs(600)
3217 );
3218 assert_eq!(config.upgrade_check_interval, 3600);
3219 }
3220
3221 #[test]
3222 fn engine_config_from_config_uses_defaults_when_no_config() {
3223 let config = EngineConfig::from_config();
3224 assert_eq!(config.tick_interval, std::time::Duration::from_secs(10));
3225 assert_eq!(config.sync_interval, std::time::Duration::from_secs(45));
3226 assert!(config.max_parallel >= 1 && config.max_parallel <= 64);
3228 assert_eq!(config.stuck_timeout, 1800);
3229 assert_eq!(config.no_session_stuck_timeout, 600);
3230 assert_eq!(
3231 config.graceful_shutdown_timeout,
3232 std::time::Duration::from_secs(600)
3233 );
3234 assert_eq!(config.upgrade_check_interval, 3600);
3235 }
3236
3237 #[test]
3238 fn engine_config_no_session_timeout_is_under_15_minutes() {
3239 let config = EngineConfig::default();
3240 assert!(
3241 config.no_session_stuck_timeout <= 900,
3242 "no_session_stuck_timeout ({}) exceeds 15 minutes",
3243 config.no_session_stuck_timeout
3244 );
3245 }
3246
3247 #[test]
3248 fn upgrade_check_runs_immediately_when_never_checked() {
3249 assert!(should_run_upgrade_check(None, 3600));
3250 }
3251
3252 #[test]
3253 fn upgrade_check_waits_for_interval_after_first_run() {
3254 assert!(!should_run_upgrade_check(
3255 Some(std::time::Instant::now()),
3256 3600
3257 ));
3258 }
3259
3260 #[test]
3261 fn upgrade_check_can_be_disabled() {
3262 assert!(!should_run_upgrade_check(None, 0));
3263 }
3264
3265 #[test]
3266 fn configured_agents_parses_yaml_block_array() {
3267 let yaml_str = "- claude\n- codex\n- opencode\n- olm\n";
3269 let parsed: Vec<String> = serde_norway::from_str(yaml_str).unwrap();
3270 assert_eq!(parsed, vec!["claude", "codex", "opencode", "olm"]);
3271 }
3272
3273 #[test]
3274 fn configured_agents_parses_json_inline_array() {
3275 let json_str = r#"["claude","codex","olm"]"#;
3276 let parsed: Vec<String> = serde_json::from_str(json_str).unwrap();
3277 assert_eq!(parsed, vec!["claude", "codex", "olm"]);
3278 }
3279
3280 #[test]
3281 fn configured_agents_fallback_returns_default_agents() {
3282 let defaults = configured_agents();
3284 assert!(defaults.contains(&"claude".to_string()));
3285 assert!(defaults.contains(&"codex".to_string()));
3286 assert!(defaults.contains(&"opencode".to_string()));
3287 }
3288
3289 #[tokio::test]
3298 #[ignore]
3299 async fn integration_channel_to_tmux_to_capture() {
3300 use crate::channels::capture::CaptureService;
3301 use crate::channels::transport::Transport;
3302 use crate::tmux::{SessionGuard, TmuxManager};
3303 use std::sync::Arc;
3304
3305 let transport = Arc::new(Transport::new());
3307 let capture = Arc::new(CaptureService::new(transport.clone()));
3308 let tmux = TmuxManager::new();
3309
3310 let task_id = "testtask1".to_string();
3311 let session_name = format!("orch-test-{}", task_id);
3312
3313 let _ = tmux
3315 .command()
3316 .args(["new-session", "-d", "-s", &session_name])
3317 .output()
3318 .await
3319 .expect("failed to start tmux session");
3320
3321 let _guard = SessionGuard(session_name.clone());
3323
3324 capture
3326 .register_session("owner/repo", &task_id, &session_name)
3327 .await;
3328 transport
3329 .bind(
3330 "owner/repo",
3331 &task_id,
3332 &session_name,
3333 "telegram",
3334 "12345",
3335 None,
3336 )
3337 .await;
3338
3339 let capture_clone = capture.clone();
3341 let capture_handle = tokio::spawn(async move { capture_clone.run().await });
3342
3343 let mut rx = transport
3345 .subscribe("owner/repo", &task_id)
3346 .await
3347 .expect("no subscription");
3348
3349 let send = tmux
3351 .command()
3352 .args([
3353 "send-keys",
3354 "-t",
3355 &session_name,
3356 "echo from-channel",
3357 "Enter",
3358 ])
3359 .output()
3360 .await
3361 .expect("failed to send keys");
3362 assert!(send.status.success());
3363
3364 let mut got = false;
3366 for _ in 0..20 {
3367 if let Ok(Ok(c)) =
3368 tokio::time::timeout(std::time::Duration::from_millis(500), rx.recv()).await
3369 {
3370 if c.content.contains("from-channel") {
3371 got = true;
3372 break;
3373 }
3374 }
3375 }
3376
3377 capture.unregister_session("owner/repo", &task_id).await;
3379
3380 let _ = capture_handle.await;
3382
3383 assert!(got, "did not observe tmux output via capture/transport");
3384 }
3385
3386 #[test]
3389 fn read_project_channel_config_returns_defaults_when_no_file() {
3390 let dir = tempfile::tempdir().expect("tempdir");
3391 let cfg = read_project_channel_config(dir.path());
3392 assert!(cfg.telegram_topic_id.is_none());
3393 assert!(cfg.discord_channel_id.is_none());
3394 }
3395
3396 #[test]
3397 fn read_project_channel_config_parses_telegram_and_discord() {
3398 let dir = tempfile::tempdir().expect("tempdir");
3399 let orch_yml = dir.path().join(".orch.yml");
3400 std::fs::write(
3401 &orch_yml,
3402 "channels:\n telegram:\n topic_id: \"42\"\n discord:\n channel_id: \"9999\"\n",
3403 )
3404 .expect("write .orch.yml");
3405 let cfg = read_project_channel_config(dir.path());
3406 assert_eq!(cfg.telegram_topic_id.as_deref(), Some("42"));
3407 assert_eq!(cfg.discord_channel_id.as_deref(), Some("9999"));
3408 }
3409
3410 #[test]
3411 fn read_project_channel_config_handles_partial_channels() {
3412 let dir = tempfile::tempdir().expect("tempdir");
3413 let orch_yml = dir.path().join(".orch.yml");
3414 std::fs::write(&orch_yml, "channels:\n telegram:\n topic_id: \"7\"\n")
3415 .expect("write .orch.yml");
3416 let cfg = read_project_channel_config(dir.path());
3417 assert_eq!(cfg.telegram_topic_id.as_deref(), Some("7"));
3418 assert!(cfg.discord_channel_id.is_none());
3419 }
3420
3421 #[test]
3422 fn read_project_channel_config_handles_malformed_yaml() {
3423 let dir = tempfile::tempdir().expect("tempdir");
3424 let orch_yml = dir.path().join(".orch.yml");
3425 std::fs::write(&orch_yml, "channels: [\nbad yaml").expect("write .orch.yml");
3426 let cfg = read_project_channel_config(dir.path());
3427 assert!(cfg.telegram_topic_id.is_none());
3429 assert!(cfg.discord_channel_id.is_none());
3430 }
3431
3432 #[test]
3433 #[cfg(unix)]
3434 fn read_project_channel_config_handles_unreadable_file() {
3435 let dir = tempfile::tempdir().expect("tempdir");
3436 std::fs::create_dir(dir.path().join(".orch.yml")).expect("create .orch.yml dir");
3438 let cfg = read_project_channel_config(dir.path());
3439 assert!(cfg.telegram_topic_id.is_none());
3441 assert!(cfg.discord_channel_id.is_none());
3442 }
3443}