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