Skip to main content

orch/engine/
mod.rs

1//! Engine — the core orchestration loop.
2//!
3//! The engine is the central coordinator. It owns the tick loop, backend
4//! connections, channel registry, transport layer, and tmux session manager.
5//!
6//! Submodules handle the heavy lifting:
7//! - [`tick`] — core tick phases (session polling, stuck recovery, routing, dispatch)
8//! - [`sync`] — periodic sync operations (cleanup, PR review, mentions, skills)
9//! - [`review`] — PR review pipeline (review agent, auto-merge, change handling)
10//! - [`cleanup`] — worktree cleanup and merged-PR detection
11//!
12//! This file contains struct definitions, project initialization, and the
13//! main event loop (`serve()`).
14
15pub mod auto_merge;
16pub mod channel_handler;
17pub mod cleanup;
18pub mod commands;
19pub mod cooldown;
20pub mod dependencies;
21pub mod dispatch_guard;
22pub mod events;
23pub mod jobs;
24pub mod relay;
25pub mod review;
26pub mod review_poll;
27pub mod router;
28pub mod runner;
29pub mod subscribers;
30pub mod suspend;
31pub mod sync;
32pub mod tasks;
33pub mod tick;
34
35/// Standard Orch attribution footer for issue bodies, PR bodies, and comments.
36///
37/// Append to every user-visible string posted to GitHub so activity is
38/// clearly attributed to orch rather than appearing as a human post.
39pub fn orch_footer() -> &'static str {
40    "\n\n---\n*Posted by [Orch](https://github.com/gabrielkoerich/orch)*"
41}
42
43/// Build a standard attribution footer for GitHub comments posted by orch bots.
44///
45/// `verb` is "Created", "Reviewed", or "Commented" depending on context.
46pub fn attribution_footer(verb: &str, agent: &str, model: Option<&str>) -> String {
47    match model {
48        Some(m) => format!(
49            "\n\n---\n*{} by {}[bot] via [Orch](https://github.com/gabrielkoerich/orch) using `{}`*",
50            verb, agent, m
51        ),
52        None => format!(
53            "\n\n---\n*{} by {}[bot] via [Orch](https://github.com/gabrielkoerich/orch)*",
54            verb, agent
55        ),
56    }
57}
58
59use crate::backends::{ExternalBackend, ExternalId};
60use crate::channels::capture::CaptureService;
61use crate::channels::discord_ws::DiscordGateway;
62use crate::channels::github::start_webhook_server;
63use crate::channels::notification::NotificationLevel;
64use crate::channels::routing::{ChannelRouter, GlobalChannelConfig, ProjectChannelConfig};
65use crate::channels::slack::SlackChannel;
66use crate::channels::telegram::TelegramChannel;
67use crate::channels::tmux::TmuxChannel;
68use crate::channels::transport::Transport;
69use crate::channels::{Channel, ChannelRegistry, IncomingMessage, OutgoingMessage};
70use crate::cmd::CommandErrorContext;
71use crate::config;
72use crate::engine::cleanup::remove_worktree_and_branch;
73use crate::engine::router::{Router, RouterConfig};
74use crate::engine::runner::worktree::{
75    abort_worktree_rebase, list_project_worktrees, rebase_worktree_on_origin_main,
76    task_id_from_worktree_name, validate_worktree_gitdir,
77};
78use crate::engine::tasks::TaskManager;
79use crate::github::http::{rate_limit_metrics, GhHttp};
80use crate::repo_context::REPO_CONTEXT;
81use crate::store::{TaskStatus, TaskStore};
82use crate::tmux::TmuxManager;
83use runner::WeightSignal;
84// AtomicBool/Ordering removed — shutdown is now immediate (reset tasks + break)
85use std::sync::Arc;
86use tokio::process::Command;
87use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
88
89use crate::backends::Status;
90
91/// Lightweight reference tuple for channel message handling.
92type EngineRef = (
93    String,
94    Arc<dyn ExternalBackend>,
95    Arc<TaskManager>,
96    Option<Arc<TaskStore>>,
97);
98
99/// Per-project engine state.
100///
101/// Each project has its own backend, task runner, and task manager,
102/// but they share the global tmux manager, transport, and semaphore.
103#[derive(Clone)]
104pub struct ProjectEngine {
105    pub repo: String,
106    pub project_dir: std::path::PathBuf,
107    pub backend: Arc<dyn ExternalBackend>,
108    pub task_manager: Arc<TaskManager>,
109    pub runner: Arc<runner::TaskRunner>,
110    pub store: Arc<TaskStore>,
111}
112
113/// A restart ends every review session, so an `in_review` task with no session has no reviewer.
114/// Hand it back to `needs_review` at start, so it does not wait for the stuck-review recovery
115pub(crate) async fn reset_orphaned_reviews(
116    task_manager: &TaskManager,
117    store: &Arc<TaskStore>,
118    repo: &str,
119    tmux: &TmuxManager,
120) -> usize {
121    // The store holds external and internal tasks, the second list is the legacy internal table
122    let mut ids: Vec<ExternalId> = store
123        .list_by_status(repo, crate::store::TaskStatus::InReview)
124        .await
125        .unwrap_or_default()
126        .iter()
127        .map(|t| crate::engine::tasks::store_task_to_external(t).id)
128        .collect();
129    if let Ok(legacy) = task_manager
130        .list_internal_by_status(crate::store::TaskStatus::InReview)
131        .await
132    {
133        ids.extend(legacy.into_iter().map(|t| t.id));
134    }
135    ids.sort_by(|a, b| a.0.cmp(&b.0));
136    ids.dedup_by(|a, b| a.0 == b.0);
137
138    let mut reset = 0;
139    for id in &ids {
140        let session = tmux.session_name(repo, &format!("{}-review", id.0));
141
142        if tmux.session_exists(&session).await {
143            continue;
144        }
145
146        if let Err(e) = task_manager
147            .update_task_status(id, Status::NeedsReview)
148            .await
149        {
150            tracing::warn!(
151                task_id = id.0,
152                ?e,
153                "failed to reset an orphaned review at start"
154            );
155            continue;
156        }
157
158        if let Ok(Some(store_id)) = store.resolve_task_id(repo, &id.0).await {
159            let reason = "startup: review session gone, reset to needs_review";
160
161            if let Err(e) = store
162                .finalize_incomplete_runs(store_id, "aborted", reason)
163                .await
164            {
165                tracing::warn!(
166                    task_id = id.0,
167                    ?e,
168                    "failed to finalize the orphaned review's runs"
169                );
170            }
171        }
172
173        reset += 1;
174    }
175
176    reset
177}
178
179/// Starts the relay client when `relay.url` is set. The token is read in the background, so a
180/// passbox prompt nobody answers never holds up the engine
181fn start_relay_client(project_engines: &[ProjectEngine], notify: &Arc<Notify>) {
182    let url = crate::config::get("relay.url").unwrap_or_default();
183    let Some(store) = project_engines.first().map(|e| Arc::clone(&e.store)) else {
184        return;
185    };
186
187    if url.is_empty() {
188        return;
189    }
190
191    let token_ref = crate::config::get("relay.token").unwrap_or_default();
192    let notify = Arc::clone(notify);
193    tokio::spawn(async move {
194        let mut warned = false;
195        let token = loop {
196            let reference = token_ref.clone();
197            let read = tokio::task::spawn_blocking(move || crate::secret_ref::resolve(&reference))
198                .await
199                .map_err(anyhow::Error::from)
200                .and_then(|r| r);
201
202            match read {
203                Ok(token) if !token.is_empty() => break token,
204                Ok(_) => {
205                    tracing::warn!("relay.token is empty, the relay client stays off");
206                    return;
207                }
208                Err(e) if !warned => {
209                    tracing::warn!(err = %e, "could not read relay.token, retrying every 5 minutes");
210                    warned = true;
211                }
212                Err(_) => {}
213            }
214
215            tokio::time::sleep(std::time::Duration::from_secs(300)).await;
216        };
217
218        relay::run(url, token, store, notify).await;
219    });
220}
221
222/**
223 * Runs `sync_tick` for every project at once, then the tail that is the same for all of them,
224 * in a spawned task. Sync time is the slowest project instead of the sum of all of them
225 * (#3864). The caller must already hold `sync_in_progress`; this releases it when done
226 **/
227#[allow(clippy::too_many_arguments)]
228fn spawn_sync_pass(
229    project_engines: &[ProjectEngine],
230    tmux: &Arc<TmuxManager>,
231    engine_config: &EngineConfig,
232    router: &Arc<RwLock<Router>>,
233    dispatching: &Arc<dashmap::DashMap<String, String>>,
234    auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
235    sync_in_progress: &Arc<std::sync::atomic::AtomicBool>,
236    trigger: &'static str,
237) {
238    let engines = project_engines.to_vec();
239    let tmux = Arc::clone(tmux);
240    let engine_config = engine_config.clone();
241    let router = Arc::clone(router);
242    let dispatching = Arc::clone(dispatching);
243    let auto_merge_in_flight = Arc::clone(auto_merge_in_flight);
244    let guard = Arc::clone(sync_in_progress);
245
246    tokio::spawn(async move {
247        let started = std::time::Instant::now();
248        let mut passes = Vec::with_capacity(engines.len());
249        for engine in &engines {
250            passes.push(REPO_CONTEXT.scope(
251                engine.repo.clone(),
252                sync_one_project(
253                    engine,
254                    &tmux,
255                    &engine_config,
256                    &router,
257                    &dispatching,
258                    &auto_merge_in_flight,
259                ),
260            ));
261        }
262        futures::future::join_all(passes).await;
263
264        sync::sync_shared_tail(&router, engines.first().map(|e| &e.store)).await;
265        tracing::info!(
266            trigger,
267            elapsed_ms = started.elapsed().as_millis() as u64,
268            "sync tick complete"
269        );
270        guard.store(false, std::sync::atomic::Ordering::Release);
271    });
272}
273
274async fn sync_one_project(
275    engine: &ProjectEngine,
276    tmux: &Arc<TmuxManager>,
277    engine_config: &EngineConfig,
278    router: &Arc<RwLock<Router>>,
279    dispatching: &Arc<dashmap::DashMap<String, String>>,
280    auto_merge_in_flight: &Arc<dashmap::DashSet<String>>,
281) {
282    if let Err(e) = sync::sync_tick(
283        &engine.backend,
284        tmux,
285        &engine.repo,
286        engine_config,
287        router,
288        &engine.task_manager,
289        &engine.store,
290        dispatching,
291        auto_merge_in_flight,
292    )
293    .await
294    {
295        tracing::error!(repo = %engine.repo, ?e, "sync tick failed for project");
296    }
297}
298
299/// Milliseconds a group of tick or sync phases may take before it is worth an operator's eye
300const SLOW_PHASE_GROUP_MS: u128 = 1_000;
301
302/**
303 * Logs how long each phase of a tick or sync group took, for one project. Tick and sync time
304 * grows with the project count, and the totals alone did not say which project or phase spent
305 * it (#3864). Info once a group crosses `SLOW_PHASE_GROUP_MS`, so a quiet install stays quiet
306 **/
307pub(crate) fn log_phase_timings(group: &str, repo: &str, phases: &[(&str, u128)]) {
308    let total_ms: u128 = phases.iter().map(|(_, ms)| ms).sum();
309    if total_ms >= SLOW_PHASE_GROUP_MS {
310        tracing::info!(group, repo, total_ms, ?phases, "phase timings");
311    } else {
312        tracing::debug!(group, repo, total_ms, ?phases, "phase timings");
313    }
314}
315
316/// Return the configured agent list from top-level `agents` in config.yml,
317/// falling back to [`router::config::DEFAULT_AGENTS`] when not set.
318///
319/// This is the canonical source of truth for "which agents does orch know
320/// about" — use it instead of `DEFAULT_AGENTS` directly so that
321/// Claude-compatible agents added via config (e.g. `olm`) are recognized
322/// without code changes.
323///
324/// The key is top-level (`agents:`) rather than nested (`engine.agents:`)
325/// because `config::get` serializes nested YAML arrays via `serde_norway::to_string`
326/// which produces YAML block format, not JSON — breaking downstream parsing.
327pub fn configured_agents() -> Vec<String> {
328    if let Ok(agents_str) = crate::config::get("agents") {
329        if !agents_str.is_empty() && agents_str != "[]" {
330            // config::get returns serde_norway::to_string for arrays, which is
331            // YAML block format ("- claude\n- codex\n..."). Parse as YAML first.
332            if let Ok(agents_arr) = serde_norway::from_str::<Vec<String>>(&agents_str) {
333                if !agents_arr.is_empty() {
334                    return agents_arr;
335                }
336            }
337            // Fallback: try JSON (inline arrays) or comma-separated
338            if let Ok(agents_arr) = serde_json::from_str::<Vec<String>>(&agents_str) {
339                if !agents_arr.is_empty() {
340                    return agents_arr;
341                }
342            }
343        }
344    }
345    router::config::DEFAULT_AGENTS
346        .iter()
347        .map(|s| s.to_string())
348        .collect()
349}
350
351/// Engine configuration.
352#[derive(Clone)]
353pub struct EngineConfig {
354    /// Main tick interval
355    pub tick_interval: std::time::Duration,
356    /// GitHub sync interval (cleanup, PR review, mentions)
357    pub sync_interval: std::time::Duration,
358    /// Webhook health check interval (seconds)
359    pub webhook_health_check_interval: Option<std::time::Duration>,
360    /// Maximum parallel task executions
361    pub max_parallel: usize,
362    /// Stuck task timeout for tasks with an active tmux session (seconds)
363    pub stuck_timeout: u64,
364    /// Stuck task timeout for tasks with no active tmux session (seconds).
365    /// Shorter than `stuck_timeout` because no session means the agent has already exited.
366    pub no_session_stuck_timeout: u64,
367    /// Stuck task timeout for in_review tasks with no active tmux session (seconds).
368    /// Longer than `no_session_stuck_timeout` because a review agent ends its tmux session on
369    /// normal completion before its result reaches the engine. A shorter limit resets a task
370    /// whose finished review is still being delivered, and the result is dropped as stale.
371    /// `from_config` keeps it above the review agent's own timeout plus
372    /// `review::REVIEW_RESULT_DELIVERY_SECS`.
373    pub in_review_no_session_stuck_timeout: u64,
374    /// Auto-create follow-up tasks when PR reviews request changes
375    pub auto_create_followup_on_changes: bool,
376    /// Graceful shutdown timeout — how long to wait for running agents before exiting.
377    pub graceful_shutdown_timeout: std::time::Duration,
378    /// Grace period before silence detection kicks in (seconds).
379    /// Allows time for agent startup, model download, API handshake.
380    pub silence_grace_period: u64,
381    /// Cooldown duration for a model detected as silent (seconds).
382    pub silence_cooldown: u64,
383    /// How often to check for a newer orch release and notify channels (seconds).
384    /// Set to 0 to disable. Default: 3600 (1 hour).
385    pub upgrade_check_interval: u64,
386    /// Seconds of continuous startup failure (GitHub unreachable / auth errors)
387    /// before the engine escalates from WARN to ERROR-level logging and sends a
388    /// one-time push notification to configured channels. Set to 0 to disable.
389    /// Default: 3600 (1 hour).
390    pub startup_failure_escalation_secs: u64,
391}
392
393impl Default for EngineConfig {
394    fn default() -> Self {
395        Self {
396            tick_interval: std::time::Duration::from_secs(10),
397            sync_interval: std::time::Duration::from_secs(45),
398            webhook_health_check_interval: Some(std::time::Duration::from_secs(60)),
399            max_parallel: 4,
400            stuck_timeout: 1800,
401            no_session_stuck_timeout: 600,
402            in_review_no_session_stuck_timeout: 1920,
403            auto_create_followup_on_changes: true,
404            graceful_shutdown_timeout: std::time::Duration::from_secs(600),
405            silence_grace_period: 300,
406            silence_cooldown: 3600,
407            upgrade_check_interval: 3600,
408            startup_failure_escalation_secs: 3600,
409        }
410    }
411}
412
413impl EngineConfig {
414    /// Load engine configuration from config files, falling back to defaults.
415    pub fn from_config() -> Self {
416        let mut config = Self::default();
417
418        if let Ok(val) = crate::config::get("engine.tick_interval") {
419            if let Ok(secs) = val.parse::<u64>() {
420                config.tick_interval = std::time::Duration::from_secs(secs);
421            } else {
422                tracing::warn!(key = "engine.tick_interval", value = %val, default_secs = config.tick_interval.as_secs(), "invalid value for engine.tick_interval, using default");
423            }
424        }
425
426        if let Ok(val) = crate::config::get("engine.sync_interval") {
427            if let Ok(secs) = val.parse::<u64>() {
428                config.sync_interval = std::time::Duration::from_secs(secs);
429            } else {
430                tracing::warn!(key = "engine.sync_interval", value = %val, default_secs = config.sync_interval.as_secs(), "invalid value for engine.sync_interval, using default");
431            }
432        }
433
434        if let Ok(val) = crate::config::get("engine.max_parallel") {
435            if let Ok(n) = val.parse::<usize>() {
436                config.max_parallel = n;
437            } else {
438                tracing::warn!(key = "engine.max_parallel", value = %val, default = config.max_parallel, "invalid value for engine.max_parallel, using default");
439            }
440        }
441
442        if let Ok(val) = crate::config::get("engine.stuck_timeout") {
443            if let Ok(secs) = val.parse::<u64>() {
444                config.stuck_timeout = secs;
445            } else {
446                tracing::warn!(key = "engine.stuck_timeout", value = %val, default_secs = config.stuck_timeout, "invalid value for engine.stuck_timeout, using default");
447            }
448        }
449
450        if let Ok(val) = crate::config::get("engine.no_session_stuck_timeout") {
451            if let Ok(secs) = val.parse::<u64>() {
452                config.no_session_stuck_timeout = secs;
453            } else {
454                tracing::warn!(key = "engine.no_session_stuck_timeout", value = %val, default_secs = config.no_session_stuck_timeout, "invalid value for engine.no_session_stuck_timeout, using default");
455            }
456        }
457
458        let mut in_review_from_config = false;
459        if let Ok(val) = crate::config::get("engine.in_review_no_session_stuck_timeout") {
460            if let Ok(secs) = val.parse::<u64>() {
461                config.in_review_no_session_stuck_timeout = secs;
462                in_review_from_config = true;
463            } else {
464                tracing::warn!(key = "engine.in_review_no_session_stuck_timeout", value = %val, default_secs = config.in_review_no_session_stuck_timeout, "invalid value for engine.in_review_no_session_stuck_timeout, using default");
465            }
466        }
467
468        // Keep the no-session review limit over the review agent's own timeout plus delivery
469        // time, whatever either is set to. Under that, recovery resets a task whose finished
470        // review is still on its way to the engine and the result is dropped as stale
471        let review_timeout = crate::engine::review::review_timeout_seconds();
472        let floored = crate::engine::review::no_session_review_floor(
473            config.in_review_no_session_stuck_timeout,
474            review_timeout,
475        );
476        if floored != config.in_review_no_session_stuck_timeout {
477            if in_review_from_config {
478                tracing::warn!(
479                    configured_secs = config.in_review_no_session_stuck_timeout,
480                    review_timeout_secs = review_timeout,
481                    raised_to_secs = floored,
482                    "engine.in_review_no_session_stuck_timeout is below the review timeout plus result delivery time, raising it"
483                );
484            } else {
485                tracing::debug!(
486                    review_timeout_secs = review_timeout,
487                    raised_to_secs = floored,
488                    "raised the default in_review no-session limit over a long review timeout"
489                );
490            }
491            config.in_review_no_session_stuck_timeout = floored;
492        }
493
494        if let Ok(val) = crate::config::get("engine.webhook_health_check_interval") {
495            if let Ok(secs) = val.parse::<u64>() {
496                if secs > 0 {
497                    config.webhook_health_check_interval =
498                        Some(std::time::Duration::from_secs(secs));
499                } else {
500                    config.webhook_health_check_interval = None;
501                }
502            } else {
503                tracing::warn!(key = "engine.webhook_health_check_interval", value = %val, default = ?config.webhook_health_check_interval, "invalid value for engine.webhook_health_check_interval, using default");
504            }
505        }
506
507        if let Ok(val) = crate::config::get("workflow.auto_create_followup_on_changes") {
508            config.auto_create_followup_on_changes = !val.eq_ignore_ascii_case("false");
509        }
510
511        if let Ok(val) = crate::config::get("engine.graceful_shutdown_timeout") {
512            if let Ok(secs) = val.parse::<u64>() {
513                config.graceful_shutdown_timeout = std::time::Duration::from_secs(secs);
514            } else {
515                tracing::warn!(key = "engine.graceful_shutdown_timeout", value = %val, default_secs = config.graceful_shutdown_timeout.as_secs(), "invalid value for engine.graceful_shutdown_timeout, using default");
516            }
517        }
518
519        if let Ok(val) = crate::config::get("engine.silence_grace_period") {
520            if let Ok(secs) = val.parse::<u64>() {
521                config.silence_grace_period = secs;
522            } else {
523                tracing::warn!(key = "engine.silence_grace_period", value = %val, default = config.silence_grace_period, "invalid value for engine.silence_grace_period, using default");
524            }
525        }
526
527        if let Ok(val) = crate::config::get("engine.silence_cooldown") {
528            if let Ok(secs) = val.parse::<u64>() {
529                config.silence_cooldown = secs;
530            } else {
531                tracing::warn!(key = "engine.silence_cooldown", value = %val, default = config.silence_cooldown, "invalid value for engine.silence_cooldown, using default");
532            }
533        }
534
535        if let Ok(val) = crate::config::get("engine.upgrade_check_interval") {
536            if let Ok(secs) = val.parse::<u64>() {
537                config.upgrade_check_interval = secs;
538            } else {
539                tracing::warn!(key = "engine.upgrade_check_interval", value = %val, default = config.upgrade_check_interval, "invalid value for engine.upgrade_check_interval, using default");
540            }
541        }
542
543        if let Ok(val) = crate::config::get("engine.startup_failure_escalation_secs") {
544            if let Ok(secs) = val.parse::<u64>() {
545                config.startup_failure_escalation_secs = secs;
546            } else {
547                tracing::warn!(
548                    key = "engine.startup_failure_escalation_secs",
549                    value = %val,
550                    default_secs = config.startup_failure_escalation_secs,
551                    "invalid value for engine.startup_failure_escalation_secs, using default"
552                );
553            }
554        }
555
556        config
557    }
558}
559
560/// KV key holding the epoch second the GitHub core window resets, so `orch task status`
561/// can show the limit from a separate process.
562pub const RATE_LIMITED_UNTIL_KEY: &str = "github:rate_limited_until";
563
564/// Format an epoch second as a local `HH:MM:SS` for operator-facing output.
565pub fn format_rate_limited_until(reset_at: i64) -> String {
566    chrono::DateTime::from_timestamp(reset_at, 0)
567        .map(|t| {
568            t.with_timezone(&chrono::Local)
569                .format("%H:%M:%S %Z")
570                .to_string()
571        })
572        .unwrap_or_else(|| reset_at.to_string())
573}
574
575/// Announce a GitHub rate-limit window on every operator surface: the log (`orch log`),
576/// a KV flag (`orch task status`) and the channels (Telegram, Discord).
577async fn report_rate_limited(
578    reset_at: i64,
579    store: Option<&Arc<TaskStore>>,
580    transport: Option<&Arc<crate::channels::transport::Transport>>,
581) {
582    let m = rate_limit_metrics();
583    let until = format_rate_limited_until(reset_at);
584    tracing::warn!(
585        reset_at,
586        rate_limit_hits = m.hits,
587        skipped_calls = m.skipped_calls,
588        five_xx_hits = m.five_xx_hits,
589        rest_remaining = ?m.rest_remaining,
590        graphql_remaining = ?m.graphql_remaining,
591        "GitHub API rate limited until {until} — skipping GitHub calls, local work continues"
592    );
593
594    if let Some(store) = store {
595        if let Err(e) = store
596            .kv_set(RATE_LIMITED_UNTIL_KEY, &reset_at.to_string())
597            .await
598        {
599            tracing::warn!(err = %e, "failed to persist GitHub rate-limit flag");
600        }
601    }
602
603    if let Some(transport) = transport {
604        transport.push_notification(crate::channels::notification::TaskNotification {
605            task_id: "github".to_string(),
606            title: "GitHub rate limit".to_string(),
607            status: "blocked".to_string(),
608            agent: "orch".to_string(),
609            duration_seconds: 0.0,
610            summary: format!(
611                "rate limited until {until}. GitHub calls are skipped until then; running agents and local work continue."
612            ),
613            repo: None,
614            notify_target: None,
615            pr_number: None,
616        });
617    }
618}
619
620/// Grow or shrink the dispatch pool toward `target` without cancelling running work.
621///
622/// Growing adds permits at once. Shrinking can only take back the permits that
623/// are free right now, so the return value is the limit actually in force; call
624/// again as running tasks release theirs
625fn resize_dispatch_pool(semaphore: &Semaphore, in_force: usize, target: usize) -> usize {
626    if target > in_force {
627        semaphore.add_permits(target - in_force);
628        return target;
629    }
630
631    if target < in_force {
632        return in_force - semaphore.forget_permits(in_force - target);
633    }
634
635    in_force
636}
637
638/// Config subtrees the engine only reads at startup: the channel gateways hold
639/// long-lived websockets and the webhook listener binds its port once.
640const RESTART_ONLY_KEYS: [&str; 3] = ["channels", "webhook", "relay"];
641
642/// Read the restart-only subtrees so a later reload can tell they changed.
643fn restart_only_snapshot() -> Vec<Option<String>> {
644    RESTART_ONLY_KEYS
645        .iter()
646        .map(|key| crate::config::get(key).ok())
647        .collect()
648}
649
650/// Report the restart-only keys an edit changed. Only the key is logged, never
651/// the value, because `channels.*` holds bot tokens
652fn log_restart_only_changes(old: &[Option<String>], new: &[Option<String>]) -> Vec<&'static str> {
653    let changed: Vec<&'static str> = RESTART_ONLY_KEYS
654        .iter()
655        .zip(old)
656        .zip(new)
657        .filter(|((_, old), new)| old != new)
658        .map(|((key, _), _)| *key)
659        .collect();
660
661    for key in &changed {
662        tracing::info!(key = key, "config changed, takes effect after restart");
663    }
664
665    changed
666}
667
668/// Log every engine setting whose value changed across a config reload, so
669/// `orch log` shows what the operator's edit actually did.
670fn log_engine_config_changes(old: &EngineConfig, new: &EngineConfig) {
671    macro_rules! log_changed {
672        ($($key:literal => $field:ident),+ $(,)?) => {
673            $(if old.$field != new.$field {
674                tracing::info!(key = $key, old = ?old.$field, new = ?new.$field, "config changed");
675            })+
676        };
677    }
678
679    log_changed!(
680        "engine.tick_interval" => tick_interval,
681        "engine.sync_interval" => sync_interval,
682        "engine.webhook_health_check_interval" => webhook_health_check_interval,
683        "engine.max_parallel" => max_parallel,
684        "engine.stuck_timeout" => stuck_timeout,
685        "engine.no_session_stuck_timeout" => no_session_stuck_timeout,
686        "engine.in_review_no_session_stuck_timeout" => in_review_no_session_stuck_timeout,
687        "engine.graceful_shutdown_timeout" => graceful_shutdown_timeout,
688        "engine.silence_grace_period" => silence_grace_period,
689        "engine.silence_cooldown" => silence_cooldown,
690        "engine.upgrade_check_interval" => upgrade_check_interval,
691        "engine.startup_failure_escalation_secs" => startup_failure_escalation_secs,
692        "workflow.auto_create_followup_on_changes" => auto_create_followup_on_changes,
693    );
694}
695
696fn should_run_upgrade_check(
697    last_upgrade_check: Option<std::time::Instant>,
698    upgrade_check_interval: u64,
699) -> bool {
700    if upgrade_check_interval == 0 {
701        return false;
702    }
703
704    last_upgrade_check
705        .map(|last| last.elapsed() >= std::time::Duration::from_secs(upgrade_check_interval))
706        .unwrap_or(true)
707}
708
709/// Connect one project's backend and build its task manager and runner over
710/// the shared store.
711///
712/// `event_tx` wires status transitions into the event bus; pass `None` during
713/// startup, where the bus does not exist yet and task managers are rebuilt
714/// once it does
715async fn connect_project_engine(
716    repo: String,
717    project_dir: std::path::PathBuf,
718    store: Arc<TaskStore>,
719    event_tx: Option<tokio::sync::broadcast::Sender<events::TaskEvent>>,
720) -> anyhow::Result<ProjectEngine> {
721    let backend: Arc<dyn ExternalBackend> =
722        Arc::new(crate::backends::github::GitHubBackend::new(repo.clone())?);
723
724    // A failed health check (rate limit, network, auth) must not drop the project: it would have
725    // no review subscriber until the next restart. Later ticks hit the API again and retry on
726    // their own, so build the engine and warn while the check keeps failing.
727    match backend.health_check().await {
728        Ok(()) => tracing::info!(repo = %repo, backend = backend.name(), "backend connected"),
729        Err(e) => tracing::warn!(
730            repo = %repo,
731            error = %e,
732            "GitHub health check failed for {repo}, starting engine anyway (rate limited, offline or bad credentials?)"
733        ),
734    }
735
736    let task_manager = Arc::new(match event_tx {
737        Some(tx) => TaskManager::with_events(backend.clone(), store.clone(), repo.clone(), tx),
738        None => TaskManager::with_store(backend.clone(), store.clone(), repo.clone()),
739    });
740    let runner = Arc::new(runner::TaskRunner::new(repo.clone()).with_store(store.clone()));
741
742    Ok(ProjectEngine {
743        repo,
744        project_dir,
745        backend,
746        task_manager,
747        runner,
748        store,
749    })
750}
751
752/**
753 * Split the configured project list into the ones not running yet and the names of the ones that
754 * went away. Kept separate from `sync_project_engines` so the comparison can be tested without a
755 * GitHub backend: getting it wrong either spawns a second set of subscribers for a project already
756 * running, or silently never picks a new one up
757 **/
758fn diff_configured_projects(
759    configured: &[(String, std::path::PathBuf)],
760    active_repos: &std::collections::HashSet<String>,
761) -> (Vec<(String, std::path::PathBuf)>, Vec<String>) {
762    let configured_repos: std::collections::HashSet<&str> =
763        configured.iter().map(|(r, _)| r.as_str()).collect();
764
765    let added = configured
766        .iter()
767        .filter(|(repo, _)| !active_repos.contains(repo))
768        .cloned()
769        .collect();
770    let removed = active_repos
771        .iter()
772        .filter(|repo| !configured_repos.contains(repo.as_str()))
773        .cloned()
774        .collect();
775
776    (added, removed)
777}
778
779/// Pick up projects added to `projects:` since startup, and report the ones
780/// that were removed.
781///
782/// A removed project keeps running until the next restart: its subscriber
783/// tasks and any agent it already dispatched outlive the config read
784#[allow(clippy::too_many_arguments)]
785async fn sync_project_engines(
786    project_engines: &mut Vec<ProjectEngine>,
787    active_repos: &mut std::collections::HashSet<String>,
788    event_bus: &events::EventBus,
789    tmux: &Arc<TmuxManager>,
790    capture: &Arc<CaptureService>,
791    semaphore: &Arc<Semaphore>,
792    weight_tx: &mpsc::Sender<WeightSignal>,
793    router: &Arc<RwLock<Router>>,
794    dispatching: &Arc<dashmap::DashMap<String, String>>,
795) {
796    let configured = match config::get_projects_with_paths() {
797        Ok(p) if !p.is_empty() => p,
798        Ok(_) => return,
799        Err(e) => {
800            tracing::warn!(err = %e, "could not re-read the project list, keeping the current one");
801            return;
802        }
803    };
804    let Some(store) = project_engines.first().map(|e| e.store.clone()) else {
805        return;
806    };
807
808    let (added, removed) = diff_configured_projects(&configured, active_repos);
809    for repo in removed {
810        tracing::info!(
811            repo = %repo,
812            "project removed from config, takes effect after restart"
813        );
814    }
815
816    for (repo, project_dir) in added {
817        config::watch(&project_dir.join(".orch.yml"));
818        let engine = match connect_project_engine(
819            repo.clone(),
820            project_dir,
821            store.clone(),
822            Some(event_bus.sender()),
823        )
824        .await
825        {
826            Ok(engine) => engine,
827            Err(e) => {
828                // A failed health check no longer lands here, so this is a backend that could
829                // not be built at all, such as a repo slug that is not `owner/name`
830                tracing::warn!(
831                    repo = %repo,
832                    err = %e,
833                    "project added to config but its backend could not be built, retrying on the next config change"
834                );
835                continue;
836            }
837        };
838
839        subscribers::dispatch::spawn(
840            event_bus.subscribe(),
841            engine.backend.clone(),
842            tmux.clone(),
843            engine.runner.clone(),
844            capture.clone(),
845            semaphore.clone(),
846            engine.task_manager.clone(),
847            weight_tx.clone(),
848            router.clone(),
849            dispatching.clone(),
850            engine.store.clone(),
851            engine.repo.clone(),
852        );
853        subscribers::review::spawn(
854            event_bus.subscribe(),
855            engine.backend.clone(),
856            tmux.clone(),
857            semaphore.clone(),
858            engine.task_manager.clone(),
859            router.clone(),
860            dispatching.clone(),
861            engine.store.clone(),
862            engine.repo.clone(),
863        );
864        subscribers::unblock::spawn(
865            event_bus.subscribe(),
866            engine.backend.clone(),
867            engine.task_manager.clone(),
868            engine.store.clone(),
869            engine.repo.clone(),
870        );
871
872        active_repos.insert(repo.clone());
873        project_engines.push(engine);
874        tracing::info!(repo = %repo, "project added from config, now syncing");
875    }
876}
877
878/// Initialize all project engines from config.
879///
880/// Returns a vector of ProjectEngine, one for each configured project.
881async fn init_project_engines() -> anyhow::Result<Vec<ProjectEngine>> {
882    let projects = config::get_projects_with_paths()?;
883    let repos: Vec<&str> = projects.iter().map(|(r, _)| r.as_str()).collect();
884    tracing::info!(repos = ?repos, "loading projects from config");
885
886    if projects.is_empty() {
887        let config_path = crate::home::config_path()
888            .map(|p| p.display().to_string())
889            .unwrap_or_else(|_| "~/.orch/config.yml".to_string());
890        anyhow::bail!(
891            "no projects configured — add repos under `projects:` in {}",
892            config_path
893        );
894    }
895
896    let mut engines = Vec::new();
897
898    // Initialize unified task store once — all project engines share the same SQLite file.
899    // Creating one pool here avoids N separate connection pools for the same database.
900    let store = Arc::new(TaskStore::open(&crate::store::default_db_path().await?).await?);
901    if crate::cluster::enabled() {
902        crate::cluster::start(&store, &crate::home::orch_home()?.join("raft.db")).await?;
903        crate::cluster::local::serve((*store).clone()).await?;
904    }
905
906    // Load persisted model cooldowns and register store for future writes.
907    // Runs once here so the global cooldown store is not overwritten per project.
908    crate::engine::cooldown::init_cooldown_store(store.clone()).await;
909
910    for (repo, project_dir) in projects {
911        tracing::info!(repo = %repo, "initializing project engine");
912        config::watch(&project_dir.join(".orch.yml"));
913
914        engines.push(connect_project_engine(repo, project_dir, store.clone(), None).await?);
915    }
916
917    Ok(engines)
918}
919
920async fn reconcile_startup_worktrees(project_engines: &[ProjectEngine]) -> anyhow::Result<()> {
921    for engine in project_engines {
922        let repo_root =
923            crate::engine::runner::worktree::resolve_main_repo(&engine.project_dir).await;
924        let repo_root_path = std::path::PathBuf::from(&repo_root);
925        let default_branch =
926            crate::engine::runner::worktree::detect_default_branch(&repo_root_path).await;
927        let worktrees = list_project_worktrees(&repo_root_path).await?;
928
929        // Fetch refs once for all worktrees in this project, so rebase below
930        // operates on up-to-date origin/* refs without N sequential fetches.
931        if let Err(e) = Command::new("git")
932            .args(["-C", &repo_root.to_string_lossy(), "fetch", "origin"])
933            .output_with_context()
934            .await
935        {
936            tracing::warn!(repo = %engine.repo, err = %e, "startup git fetch origin failed, rebases may use stale refs");
937        }
938
939        let mut orphans_removed: u32 = 0;
940        let mut invalid_removed: u32 = 0;
941        let mut cleaned: u32 = 0;
942        let mut valid_kept: u32 = 0;
943
944        for worktree_dir in worktrees {
945            let Some(name) = worktree_dir.file_name().and_then(|n| n.to_str()) else {
946                continue;
947            };
948
949            // Validate gitdir link before doing anything else — a broken .git file
950            // means git commands on this worktree will fail with "not a git repository".
951            if !validate_worktree_gitdir(&worktree_dir).await {
952                tracing::warn!(repo = %engine.repo, worktree = %worktree_dir.display(), "worktree has invalid or missing gitdir, removing");
953                remove_worktree_and_branch(name, &worktree_dir, Some(name), &repo_root_path, false)
954                    .await;
955                invalid_removed += 1;
956                continue;
957            }
958
959            let Some(task_id) = task_id_from_worktree_name(name) else {
960                tracing::info!(repo = %engine.repo, worktree = %worktree_dir.display(), "orphan worktree without task id, removing");
961                remove_worktree_and_branch(name, &worktree_dir, Some(name), &repo_root_path, false)
962                    .await;
963                orphans_removed += 1;
964                continue;
965            };
966
967            let Some(store_id) = engine.store.resolve_task_id(&engine.repo, &task_id).await? else {
968                tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), "worktree has no matching task, removing");
969                remove_worktree_and_branch(
970                    &task_id,
971                    &worktree_dir,
972                    Some(name),
973                    &repo_root_path,
974                    false,
975                )
976                .await;
977                orphans_removed += 1;
978                continue;
979            };
980
981            let task = engine.store.get(store_id).await?;
982            let branch_name = if task.branch.is_empty() {
983                name
984            } else {
985                task.branch.as_str()
986            };
987
988            match task.status {
989                TaskStatus::New
990                | TaskStatus::Routed
991                | TaskStatus::InProgress
992                | TaskStatus::NeedsReview
993                | TaskStatus::InReview => {
994                    tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), "rebasing startup worktree");
995                    if let Err(e) =
996                        rebase_worktree_on_origin_main(&worktree_dir, &default_branch).await
997                    {
998                        // If rebase failed we already made efforts to stash and
999                        // restore changes safely. Log the error and reset the
1000                        // task as before. The worktree removal path is used
1001                        // to avoid leaving corrupted worktrees around.
1002                        tracing::warn!(repo = %engine.repo, task_id = %task_id, err = %e, "startup rebase failed, resetting task");
1003                        abort_worktree_rebase(&worktree_dir).await;
1004                        let keep_remote = task.pr_number.is_some();
1005                        remove_worktree_and_branch(
1006                            &task_id,
1007                            &worktree_dir,
1008                            Some(branch_name),
1009                            &repo_root_path,
1010                            keep_remote,
1011                        )
1012                        .await;
1013                        match engine.store.resolve_task_id(&engine.repo, &task_id).await {
1014                            Ok(Some(reset_id)) => {
1015                                if let Err(e) = engine.store.reset_to_new(reset_id).await {
1016                                    tracing::warn!(task_id, err = %e, "failed to reset task to new after rebase failure");
1017                                }
1018                            }
1019                            Ok(None) => {
1020                                tracing::warn!(
1021                                    task_id,
1022                                    "task not found in store during reconciliation"
1023                                );
1024                            }
1025                            Err(e) => {
1026                                tracing::warn!(task_id, err = %e, "failed to resolve task ID during reconciliation");
1027                            }
1028                        }
1029                        if let Err(e) = engine
1030                            .task_manager
1031                            .update_task_status(
1032                                &ExternalId(task_id.clone()),
1033                                crate::backends::Status::New,
1034                            )
1035                            .await
1036                        {
1037                            tracing::warn!(task_id, err = %e, "failed to update backend status during reconciliation");
1038                        }
1039                        cleaned += 1;
1040                    } else {
1041                        valid_kept += 1;
1042                    }
1043                }
1044                // A blocked or waiting task resumes from this work, and without a PR the branch
1045                // may hold the only copy of it
1046                TaskStatus::Blocked | TaskStatus::Waiting => {
1047                    valid_kept += 1;
1048                }
1049                TaskStatus::Done => {
1050                    tracing::info!(repo = %engine.repo, task_id = %task_id, worktree = %worktree_dir.display(), status = ?task.status, "terminal task worktree, removing");
1051                    remove_worktree_and_branch(
1052                        &task_id,
1053                        &worktree_dir,
1054                        Some(branch_name),
1055                        &repo_root_path,
1056                        false,
1057                    )
1058                    .await;
1059                    cleaned += 1;
1060                }
1061            }
1062        }
1063
1064        tracing::info!(
1065            repo = %engine.repo,
1066            orphans_removed,
1067            invalid_removed,
1068            cleaned,
1069            valid_kept,
1070            "worktree reconciliation: {orphans_removed} orphans removed, {invalid_removed} invalid removed, {cleaned} cleaned, {valid_kept} valid kept"
1071        );
1072
1073        // Prune stale .git/worktrees/ entries whose directories no longer exist.
1074        // This handles entries left behind by crashes or manual directory removal.
1075        let prune = Command::new("git")
1076            .args(["-C", &repo_root.to_string_lossy(), "worktree", "prune"])
1077            .output_with_context()
1078            .await;
1079        match prune {
1080            Ok(output) if output.status.success() => {
1081                tracing::debug!(repo = %engine.repo, "startup worktree prune completed");
1082            }
1083            Ok(output) => {
1084                let stderr = String::from_utf8_lossy(&output.stderr);
1085                tracing::warn!(repo = %engine.repo, err = %stderr, "startup worktree prune failed");
1086            }
1087            Err(e) => {
1088                tracing::warn!(repo = %engine.repo, err = %e, "startup worktree prune failed");
1089            }
1090        }
1091    }
1092
1093    Ok(())
1094}
1095
1096/// Sync Fibonacci estimates stored in SQLite to the GitHub Projects board for
1097/// all tasks that have a positive estimate.
1098///
1099/// Runs once on startup to catch tasks that were routed before the estimate
1100/// sync feature was available or before `project_estimate_field_id` was
1101/// configured. The underlying mutations are idempotent, so re-syncing an
1102/// already-correct estimate is harmless.
1103async fn reconcile_startup_estimates(project_engines: &[ProjectEngine]) {
1104    use crate::backends::ExternalId;
1105
1106    for engine in project_engines {
1107        let tasks = match engine.store.list_external_tasks_with_estimates().await {
1108            Ok(t) => t,
1109            Err(e) => {
1110                tracing::warn!(repo = %engine.repo, err = %e, "startup estimate reconciliation: store query failed");
1111                continue;
1112            }
1113        };
1114
1115        if tasks.is_empty() {
1116            continue;
1117        }
1118
1119        let mut synced: u32 = 0;
1120        let mut failed: u32 = 0;
1121        for (external_id, estimate) in &tasks {
1122            match engine
1123                .backend
1124                .sync_estimate_to_project(&ExternalId(external_id.clone()), *estimate)
1125                .await
1126            {
1127                Ok(()) => synced += 1,
1128                Err(e) => {
1129                    tracing::debug!(
1130                        repo = %engine.repo,
1131                        task_id = %external_id,
1132                        estimate,
1133                        err = %e,
1134                        "startup estimate reconciliation: sync failed"
1135                    );
1136                    failed += 1;
1137                }
1138            }
1139        }
1140
1141        if synced > 0 || failed > 0 {
1142            tracing::info!(
1143                repo = %engine.repo,
1144                synced,
1145                failed,
1146                "startup estimate reconciliation complete"
1147            );
1148        }
1149    }
1150}
1151
1152/// Read per-project channel configuration from `.orch.yml`.
1153fn read_project_channel_config(project_dir: &std::path::Path) -> ProjectChannelConfig {
1154    let config_path = project_dir.join(".orch.yml");
1155    if !config_path.exists() {
1156        return ProjectChannelConfig::default();
1157    }
1158    let content = match std::fs::read_to_string(&config_path) {
1159        Ok(c) => c,
1160        Err(e) => {
1161            tracing::warn!(
1162                path = %config_path.display(),
1163                error = %e,
1164                "failed to read .orch.yml; channel config will use defaults"
1165            );
1166            return ProjectChannelConfig::default();
1167        }
1168    };
1169    let val: serde_norway::Value = match serde_norway::from_str(&content) {
1170        Ok(v) => v,
1171        Err(e) => {
1172            tracing::warn!(
1173                path = %config_path.display(),
1174                error = %e,
1175                "failed to parse .orch.yml; channel config will use defaults"
1176            );
1177            return ProjectChannelConfig::default();
1178        }
1179    };
1180    let channels = match val.get("channels") {
1181        Some(c) => c,
1182        None => return ProjectChannelConfig::default(),
1183    };
1184    let get_str = |section: &str, key: &str| -> Option<String> {
1185        channels
1186            .get(section)
1187            .and_then(|s| s.get(key))
1188            .and_then(|v| v.as_str())
1189            .map(String::from)
1190    };
1191    ProjectChannelConfig {
1192        telegram_topic_id: get_str("telegram", "topic_id"),
1193        telegram_bot_token: get_str("telegram", "bot_token"),
1194        telegram_chat_id: get_str("telegram", "chat_id"),
1195        discord_channel_id: get_str("discord", "channel_id"),
1196        discord_bot_token: get_str("discord", "bot_token"),
1197        discord_guild_id: get_str("discord", "guild_id"),
1198    }
1199}
1200
1201/// Fetch the latest orch release tag from GitHub via the `gh` CLI (async).
1202///
1203/// Returns the version string (without the leading "v"), or `None` when the
1204/// check fails (no network, unauthenticated, `gh` not installed, etc.).
1205async fn fetch_latest_release_version() -> Option<String> {
1206    let output = Command::new("gh")
1207        .args([
1208            "api",
1209            "repos/gabrielkoerich/orch/releases/latest",
1210            "--jq",
1211            ".tag_name",
1212        ])
1213        .output()
1214        .await
1215        .ok()?;
1216    if !output.status.success() {
1217        return None;
1218    }
1219    let tag = String::from_utf8(output.stdout).ok()?;
1220    let version = tag.trim().trim_start_matches('v').to_string();
1221    if version.is_empty() {
1222        None
1223    } else {
1224        Some(version)
1225    }
1226}
1227
1228/// Check if a newer orch release is available and send channel notifications
1229/// asking the operator to upgrade manually. Upgrading is operator-only — the
1230/// service never runs `brew` itself.
1231///
1232/// Uses the store's KV to throttle checks (`upgrade:last_check_at`) and
1233/// deduplicate notifications (`upgrade:last_notified_version`). Each distinct
1234/// latest version is notified about once; the notification repeats only when
1235/// an even newer version is released.
1236async fn check_and_notify_upgrade(
1237    store: &Arc<TaskStore>,
1238    channels: &Arc<ChannelRegistry>,
1239    current_version: &str,
1240    check_interval: std::time::Duration,
1241) {
1242    let last_check_key = "upgrade:last_check_at";
1243    let last_notified_key = "upgrade:last_notified_version";
1244
1245    // Throttle: only check once per interval.
1246    let now = chrono::Utc::now().timestamp();
1247    if let Ok(Some(last_check_str)) = store.kv_get(last_check_key).await {
1248        if let Ok(last_check) = last_check_str.parse::<i64>() {
1249            if now - last_check < check_interval.as_secs() as i64 {
1250                return;
1251            }
1252        }
1253    }
1254
1255    // Record check timestamp (best-effort).
1256    let _ = store.kv_set(last_check_key, &now.to_string()).await;
1257
1258    let latest = match fetch_latest_release_version().await {
1259        Some(v) => v,
1260        None => {
1261            tracing::debug!("upgrade check: failed to fetch latest release version");
1262            return;
1263        }
1264    };
1265
1266    if latest == current_version {
1267        tracing::debug!(current = %current_version, "orch is up to date");
1268        return;
1269    }
1270
1271    tracing::warn!(
1272        current_version = %current_version,
1273        latest_version = %latest,
1274        "orch upgrade available"
1275    );
1276
1277    // Operator-only upgrade: send channel notifications so the operator can
1278    // upgrade on their own schedule. The service never runs brew itself.
1279
1280    // Deduplicate: don't re-notify for the same latest version.
1281    if let Ok(Some(last_notified)) = store.kv_get(last_notified_key).await {
1282        if last_notified == latest {
1283            tracing::debug!(latest = %latest, "upgrade already notified");
1284            return;
1285        }
1286    }
1287
1288    let msg_telegram = format!(
1289        "⚠️ <b>Orch Upgrade Available</b>\n\n\
1290         Service: <code>{current_version}</code>\n\
1291         Latest:  <code>{latest}</code>\n\n\
1292         Run: <code>brew update && brew upgrade orch && brew services restart orch</code>"
1293    );
1294
1295    let msg_discord = format!(
1296        "⚠️ **Orch Upgrade Available**\n\n\
1297         Service: `{current_version}`\n\
1298         Latest:  `{latest}`\n\n\
1299         Run: `brew update && brew upgrade orch && brew services restart orch`"
1300    );
1301
1302    let msg_slack = format!(
1303        "⚠️ *Orch Upgrade Available*\n\n\
1304         Service: `{current_version}`\n\
1305         Latest:  `{latest}`\n\n\
1306         Run: `brew update && brew upgrade orch && brew services restart orch`"
1307    );
1308
1309    for channel in channels.iter() {
1310        let (body, metadata, topic_id) = match channel.name() {
1311            "telegram" => (
1312                msg_telegram.clone(),
1313                serde_json::json!({"preformatted_html": true}),
1314                None,
1315            ),
1316            "discord" => (msg_discord.clone(), serde_json::json!({}), None),
1317            "slack" => (msg_slack.clone(), serde_json::json!({}), None),
1318            _ => continue,
1319        };
1320
1321        let msg = OutgoingMessage {
1322            thread_id: "upgrade".to_string(),
1323            body,
1324            reply_to: None,
1325            metadata,
1326            topic_id,
1327        };
1328
1329        if let Err(e) = channel.send(&msg).await {
1330            tracing::warn!(
1331                channel = channel.name(),
1332                ?e,
1333                "failed to send upgrade notification"
1334            );
1335        }
1336    }
1337
1338    // Record that we notified for this latest version.
1339    let _ = store.kv_set(last_notified_key, &latest).await;
1340}
1341
1342/// Send a one-time escalation notification when the startup retry loop has been
1343/// spinning for longer than `startup_failure_escalation_secs`.
1344///
1345/// This is called *before* the channel registry is initialised (the retry loop
1346/// sits above it in `serve()`), so we construct channel objects directly from
1347/// config — mirroring the approach used during normal channel registration, but
1348/// without relying on `ChannelRegistry`.
1349async fn send_startup_escalation_notification(elapsed_secs: u64) {
1350    let duration = crate::channels::notification::format_duration(elapsed_secs as f64);
1351
1352    let msg_telegram = format!(
1353        "🚨 <b>Orch startup blocked — GitHub unreachable</b>\n\n\
1354         The engine has been retrying backend connections for {}\n\
1355         without success. All task processing, routing, and scheduled\n\
1356         jobs are paused. Check service logs with `orch log -f`.",
1357        duration
1358    );
1359
1360    let msg_discord = format!(
1361        "🚨 **Orch startup blocked — GitHub unreachable**\n\n\
1362         The engine has been retrying backend connections for {}\n\
1363         without success. All task processing, routing, and scheduled\n\
1364         jobs are paused. Check service logs with `orch log -f`.",
1365        duration
1366    );
1367
1368    let msg_slack = format!(
1369        "🚨 *Orch startup blocked — GitHub unreachable*\n\n\
1370         The engine has been retrying backend connections for {}\n\
1371         without success. All task processing, routing, and scheduled\n\
1372         jobs are paused. Check service logs with `orch log -f`.",
1373        duration
1374    );
1375
1376    // Telegram
1377    let tg_token = crate::config::get("channels.telegram.bot_token");
1378    let tg_chat_id = crate::config::get("channels.telegram.chat_id");
1379    if let (Ok(token), Ok(chat_id)) = (&tg_token, &tg_chat_id) {
1380        if !token.is_empty() && !chat_id.is_empty() {
1381            if let Ok(channel) = TelegramChannel::new(token.clone(), Some(chat_id.clone())) {
1382                let msg = OutgoingMessage {
1383                    thread_id: "startup_escalation".to_string(),
1384                    body: msg_telegram.clone(),
1385                    reply_to: None,
1386                    metadata: serde_json::json!({ "preformatted_html": true }),
1387                    topic_id: crate::config::get("channels.telegram.general_topic_id").ok(),
1388                };
1389                if let Err(e) = channel.send(&msg).await {
1390                    tracing::warn!(?e, "failed to send startup escalation via telegram");
1391                } else {
1392                    tracing::info!("startup escalation notification sent to telegram");
1393                }
1394            }
1395        }
1396    }
1397
1398    // Discord
1399    if let Ok(token) = crate::config::get("channels.discord.bot_token") {
1400        let channel_id = crate::config::get("channels.discord.channel_id")
1401            .or_else(|_| crate::config::get("channels.discord.general_channel_id"));
1402        if !token.is_empty() {
1403            if let Some(cid) = channel_id.ok().filter(|s| !s.is_empty()) {
1404                let shard_id = crate::config::get("channels.discord.shard_id")
1405                    .ok()
1406                    .and_then(|v| v.parse::<u64>().ok())
1407                    .unwrap_or(0);
1408                let shard_count = crate::config::get("channels.discord.shard_count")
1409                    .ok()
1410                    .and_then(|v| v.parse::<u64>().ok())
1411                    .unwrap_or(1);
1412                if let Ok(gateway) = DiscordGateway::new(token, Some(cid), shard_id, shard_count) {
1413                    let msg = OutgoingMessage {
1414                        thread_id: "startup_escalation".to_string(),
1415                        body: msg_discord.clone(),
1416                        reply_to: None,
1417                        metadata: serde_json::Value::Null,
1418                        topic_id: None,
1419                    };
1420                    if let Err(e) = gateway.send(&msg).await {
1421                        tracing::warn!(?e, "failed to send startup escalation via discord");
1422                    } else {
1423                        tracing::info!("startup escalation notification sent to discord");
1424                    }
1425                }
1426            }
1427        }
1428    }
1429
1430    // Slack
1431    if let Ok(token) = crate::config::get("channels.slack.bot_token") {
1432        let channel_id = crate::config::get("channels.slack.channel_id");
1433        if !token.is_empty() {
1434            if let Ok(cid) = channel_id {
1435                if let Ok(channel) = SlackChannel::new(token, Some(cid)) {
1436                    let msg = OutgoingMessage {
1437                        thread_id: "startup_escalation".to_string(),
1438                        body: msg_slack.clone(),
1439                        reply_to: None,
1440                        metadata: serde_json::Value::Null,
1441                        topic_id: None,
1442                    };
1443                    if let Err(e) = channel.send(&msg).await {
1444                        tracing::warn!(?e, "failed to send startup escalation via slack");
1445                    } else {
1446                        tracing::info!("startup escalation notification sent to slack");
1447                    }
1448                }
1449            }
1450        }
1451    }
1452}
1453
1454/// Start the orch service.
1455///
1456/// This is the main entry point — called by `orch serve`.
1457pub async fn serve() -> anyhow::Result<()> {
1458    let killed = crate::home::kill_other_orch_serve_processes(std::time::Duration::from_secs(30));
1459    if killed > 0 {
1460        tracing::info!(count = killed, "terminated stale orch serve processes");
1461    }
1462
1463    tracing::info!("orch engine starting");
1464
1465    // Pre-create standard directories with async I/O so subsequent synchronous
1466    // callers (state_dir, orch_home, etc.) find them already present and their
1467    // create_dir_all calls become fast no-ops.
1468    if let Err(e) = crate::home::init_dirs().await {
1469        tracing::warn!("failed to initialize orch directories: {e}");
1470    }
1471
1472    // Pre-warm the config cache with async I/O so get() / get_list() calls in
1473    // hot async paths never block a Tokio thread on std::fs::read_to_string.
1474    if let Err(e) = crate::config::warm_cache().await {
1475        tracing::warn!("failed to warm config cache: {e}");
1476    }
1477
1478    let mut config = EngineConfig::from_config();
1479
1480    tracing::info!("internal database ready");
1481
1482    // Initialize project engines — retry with backoff so a network outage at
1483    // startup doesn't cause a crash-loop (launchd KeepAlive would restart us
1484    // immediately, filling the error log with 600+ identical messages).
1485    //
1486    // IMPORTANT: errors from init_project_engines() must NEVER propagate past
1487    // this loop to main().  If they did, anyhow would write "Error: …" to stderr,
1488    // which brew routes to orch.error.log — polluting it even when projects ARE
1489    // configured correctly but GitHub is temporarily unreachable.
1490    let startup_escalation_secs = config.startup_failure_escalation_secs;
1491    let mut project_engines = {
1492        let mut delay_secs = 5u64;
1493        let mut attempt = 0u32;
1494        let mut escalated = false;
1495        let start = std::time::Instant::now();
1496        loop {
1497            attempt += 1;
1498            match init_project_engines().await {
1499                Ok(engines) => break engines,
1500                Err(e) => {
1501                    let elapsed = start.elapsed().as_secs();
1502
1503                    // Short blips (under the escalation threshold) stay at WARN
1504                    // so they don't flood the operator's attention. Once the
1505                    // outage crosses the threshold, escalate to ERROR-level
1506                    // logging and send a one-time push notification to configured
1507                    // channels — "transient" has clearly become "prolonged."
1508                    if startup_escalation_secs > 0
1509                        && !escalated
1510                        && elapsed >= startup_escalation_secs
1511                    {
1512                        escalated = true;
1513                        tracing::error!(
1514                            delay_secs,
1515                            attempt,
1516                            elapsed_secs = elapsed,
1517                            threshold_secs = startup_escalation_secs,
1518                            "project backends unavailable for {} — escalating startup failure: {e}",
1519                            crate::channels::notification::format_duration(elapsed as f64)
1520                        );
1521                        // Send one-time notification to configured channels.
1522                        // Channels aren't registered yet at this stage, so we
1523                        // construct them directly from config (mirrors orch notify).
1524                        send_startup_escalation_notification(elapsed).await;
1525                    } else {
1526                        tracing::warn!(
1527                            delay_secs,
1528                            attempt,
1529                            "project backends unavailable, retrying: {e}"
1530                        );
1531                    }
1532
1533                    tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;
1534                    delay_secs = (delay_secs * 2).min(120);
1535                }
1536            }
1537        }
1538    };
1539
1540    tracing::info!(
1541        project_count = project_engines.len(),
1542        "initialized project engines"
1543    );
1544
1545    // Full set of currently-configured project repos, used by the per-tick global
1546    // sweeps (e.g. `dispatch_routed_tasks_global`) to distinguish "orphaned" tasks
1547    // (repo no longer in config) from tasks belonging to some other active project.
1548    let mut active_repos: std::collections::HashSet<String> =
1549        project_engines.iter().map(|e| e.repo.clone()).collect();
1550
1551    // Create the event bus for task status transitions
1552    let event_bus = events::EventBus::new(256);
1553    if let Err(e) = event_bus.start_ws_server().await {
1554        tracing::warn!(
1555            ?e,
1556            "failed to start event websocket server, continuing without it"
1557        );
1558    }
1559
1560    // Check for a newer orch release in the background and log if the service is behind.
1561    // The periodic checker sends channel notifications after channels are initialized;
1562    // upgrading is operator-only and never runs automatically.
1563    {
1564        let current = env!("ORCH_VERSION").to_string();
1565        tokio::spawn(async move {
1566            if let Some(latest) = fetch_latest_release_version().await {
1567                if latest != current {
1568                    tracing::warn!(
1569                        current_version = %current,
1570                        latest_version = %latest,
1571                        "orch service is behind the latest release — run: brew update && brew upgrade orch && brew services restart orch"
1572                    );
1573                }
1574            }
1575        });
1576    }
1577
1578    // Re-create task managers with shared store and event bus
1579    for engine in &mut project_engines {
1580        engine.task_manager = Arc::new(TaskManager::with_events(
1581            engine.backend.clone(),
1582            engine.store.clone(),
1583            engine.repo.clone(),
1584            event_bus.sender(),
1585        ));
1586    }
1587
1588    // Startup reconciliation decides task status, so only the leader runs it
1589    let leads = project_engines.first().is_none_or(|e| e.store.is_leader());
1590    if leads {
1591        if let Err(e) = reconcile_startup_worktrees(&project_engines).await {
1592            tracing::warn!(err = %e, "startup worktree reconciliation failed");
1593        }
1594    }
1595
1596    if leads {
1597        // Run estimate reconciliation in the background so it never blocks startup.
1598        // Each GraphQL mutation takes ~0.8 s; with hundreds of tasks this would
1599        // otherwise delay the engine reaching its main loop by several minutes.
1600        let engines_snapshot: Vec<ProjectEngine> = project_engines.clone();
1601        tokio::spawn(async move {
1602            reconcile_startup_estimates(&engines_snapshot).await;
1603        });
1604    }
1605
1606    // Build ChannelRouter from global config + per-project configs
1607    let global_channel_config = GlobalChannelConfig {
1608        telegram_general_topic_id: crate::config::get("channels.telegram.general_topic_id").ok(),
1609        discord_general_channel_id: crate::config::get("channels.discord.general_channel_id").ok(),
1610        control_telegram_topic_id: crate::config::get("control.channels.telegram.topic_id").ok(),
1611        control_discord_channel_id: crate::config::get("control.channels.discord.channel_id").ok(),
1612    };
1613    let project_channel_configs: Vec<(String, ProjectChannelConfig)> = project_engines
1614        .iter()
1615        .map(|e| {
1616            let cfg = read_project_channel_config(&e.project_dir);
1617            (e.repo.clone(), cfg)
1618        })
1619        .collect();
1620    let channel_router = Arc::new(ChannelRouter::new(
1621        &global_channel_config,
1622        &project_channel_configs,
1623    ));
1624    tracing::info!(
1625        projects = ?channel_router.projects(),
1626        "channel router initialized"
1627    );
1628
1629    // Initialize tmux manager (shared across all projects)
1630    let tmux = Arc::new(TmuxManager::new());
1631    // Kill leftover sessions from a previous process. This is daemon start only,
1632    // never a tick, because nextest makes a once-flag in tick_all kill live agents
1633    tick::startup_cleanup(&tmux).await;
1634
1635    // Initialize transport
1636    let transport = Arc::new(Transport::new());
1637
1638    // Initialize capture service and start background loop
1639    let capture = Arc::new(CaptureService::new(transport.clone()));
1640    let capture_for_tick = capture.clone();
1641    tokio::spawn(async move {
1642        capture.start().await;
1643    });
1644
1645    // Initialize channel registry
1646    let mut channel_registry = ChannelRegistry::new();
1647
1648    // Try to initialize Telegram channel
1649    if let Ok(token) = crate::config::get("channels.telegram.bot_token") {
1650        if !token.is_empty() {
1651            let chat_id = crate::config::get("channels.telegram.chat_id").ok();
1652            match TelegramChannel::new(token, chat_id) {
1653                Ok(telegram) => {
1654                    if let Err(e) = telegram.health_check().await {
1655                        tracing::warn!(?e, "telegram channel health check failed, skipping");
1656                    } else {
1657                        channel_registry.register(Box::new(telegram));
1658                        tracing::info!("telegram channel registered");
1659                    }
1660                }
1661                Err(e) => {
1662                    tracing::warn!(?e, "failed to create telegram channel, skipping");
1663                }
1664            }
1665        }
1666    }
1667
1668    // Try to initialize Discord Gateway channel (websocket)
1669    if let Ok(token) = crate::config::get("channels.discord.bot_token") {
1670        if !token.is_empty() {
1671            let channel_id = crate::config::get("channels.discord.channel_id").ok();
1672            let shard_id = crate::config::get("channels.discord.shard_id")
1673                .ok()
1674                .and_then(|v| v.parse::<u64>().ok())
1675                .unwrap_or(0);
1676            let shard_count = crate::config::get("channels.discord.shard_count")
1677                .ok()
1678                .and_then(|v| v.parse::<u64>().ok())
1679                .unwrap_or(1);
1680            match DiscordGateway::new(token, channel_id, shard_id, shard_count) {
1681                Ok(discord) => {
1682                    if let Err(e) = discord.health_check().await {
1683                        tracing::warn!(?e, "discord gateway health check failed, skipping");
1684                    } else {
1685                        channel_registry.register(Box::new(discord));
1686                        tracing::info!(shard_id, shard_count, "discord gateway registered");
1687                    }
1688                }
1689                Err(e) => {
1690                    tracing::warn!(?e, "failed to create discord gateway, skipping");
1691                }
1692            }
1693        }
1694    }
1695
1696    // Try to initialize Slack channel
1697    if let Ok(token) = crate::config::get("channels.slack.bot_token") {
1698        if !token.is_empty() {
1699            let channel_id = crate::config::get("channels.slack.channel_id").ok();
1700            match SlackChannel::new(token, channel_id) {
1701                Ok(slack) => {
1702                    if let Err(e) = slack.health_check().await {
1703                        tracing::warn!(?e, "slack channel health check failed, skipping");
1704                    } else {
1705                        channel_registry.register(Box::new(slack));
1706                        tracing::info!("slack channel registered");
1707                    }
1708                }
1709                Err(e) => {
1710                    tracing::warn!(?e, "failed to create slack channel, skipping");
1711                }
1712            }
1713        }
1714    }
1715
1716    // Initialize tmux channel with transport for output streaming
1717    let tmux_channel = TmuxChannel::with_transport(transport.clone());
1718    channel_registry.register(Box::new(tmux_channel));
1719    tracing::info!("tmux channel registered");
1720
1721    // Start all channels and collect their message receivers
1722    let mut channel_receivers: Vec<tokio::sync::mpsc::Receiver<IncomingMessage>> = Vec::new();
1723    for channel in channel_registry.iter() {
1724        match channel.start().await {
1725            Ok(rx) => {
1726                tracing::info!(channel = channel.name(), "channel started");
1727                channel_receivers.push(rx);
1728            }
1729            Err(e) => {
1730                tracing::warn!(channel = channel.name(), ?e, "failed to start channel");
1731            }
1732        }
1733    }
1734
1735    // Wrap channel registry in Arc for shared access (notification dispatcher needs it)
1736    let channel_registry = Arc::new(channel_registry);
1737
1738    // Spawn tasks to handle incoming channel messages (if any channels are active)
1739    let transport_for_messages = transport.clone();
1740    let tmux_for_messages = tmux.clone();
1741    let capture_for_messages = capture_for_tick.clone();
1742    let channels_for_messages = channel_registry.clone();
1743    // Lightweight engine references for command execution and task creation
1744    let engine_refs: Vec<EngineRef> = project_engines
1745        .iter()
1746        .map(|e| {
1747            (
1748                e.repo.clone(),
1749                e.backend.clone(),
1750                e.task_manager.clone(),
1751                Some(e.store.clone()),
1752            )
1753        })
1754        .collect();
1755    // Shared in-memory map for pending project picks (General channel multi-project picker).
1756    let pending_picks: channel_handler::PendingPicks =
1757        std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
1758    let router_for_messages = channel_router.clone();
1759    for mut rx in channel_receivers {
1760        let transport = transport_for_messages.clone();
1761        let tmux = tmux_for_messages.clone();
1762        let capture = capture_for_messages.clone();
1763        let channels = channels_for_messages.clone();
1764        let engine_refs = engine_refs.clone();
1765        let ch_router = router_for_messages.clone();
1766        let picks = pending_picks.clone();
1767        tokio::spawn(async move {
1768            while let Some(msg) = rx.recv().await {
1769                tracing::debug!(channel = %msg.channel, thread = %msg.thread_id, "received message from channel");
1770                channel_handler::handle_channel_message(
1771                    msg,
1772                    &transport,
1773                    &tmux,
1774                    &capture,
1775                    &channels,
1776                    &engine_refs,
1777                    &ch_router,
1778                    &picks,
1779                )
1780                .await;
1781            }
1782        });
1783    }
1784
1785    // Post-restart confirmation: if the service was restarted via the /restart control command,
1786    // a KV marker was stored before shutdown. Send a confirmation to the originating channel now
1787    // that we're back online. Use a short delay to let the channel connections re-establish.
1788    {
1789        let restart_channels = channel_registry.clone();
1790        let restart_store = project_engines.first().map(|e| e.store.clone());
1791        if let Some(store) = restart_store {
1792            tokio::spawn(async move {
1793                tokio::time::sleep(std::time::Duration::from_secs(5)).await;
1794                match store.kv_get("control:restart_pending").await {
1795                    Ok(Some(conv_key)) => {
1796                        if let Some((ch_name, thread_id, topic_id)) =
1797                            crate::channels::transport::parse_conversation_key(&conv_key)
1798                        {
1799                            for ch in restart_channels.iter() {
1800                                if ch.name() == ch_name {
1801                                    let msg = OutgoingMessage {
1802                                        thread_id: thread_id.to_string(),
1803                                        body: "orch restarted successfully.".to_string(),
1804                                        reply_to: None,
1805                                        metadata: serde_json::json!({}),
1806                                        topic_id: topic_id.map(|t| t.to_string()),
1807                                    };
1808                                    if let Err(e) = ch.send(&msg).await {
1809                                        tracing::warn!(
1810                                            channel = ch_name,
1811                                            error = %e,
1812                                            "failed to send restart confirmation"
1813                                        );
1814                                    }
1815                                    break;
1816                                }
1817                            }
1818                        }
1819                        if let Err(e) = store.kv_delete("control:restart_pending").await {
1820                            tracing::warn!(error = %e, "failed to clear control:restart_pending");
1821                        }
1822                    }
1823                    Ok(None) => {} // no pending restart, nothing to do
1824                    Err(e) => {
1825                        tracing::warn!(error = %e, "failed to read control:restart_pending");
1826                    }
1827                }
1828            });
1829        }
1830    }
1831
1832    // Spawn notification dispatcher — reads task completion notifications
1833    // from transport and broadcasts to configured channels.
1834    //
1835    // Routing priority:
1836    // 1. Dedicated channel: if the notification has a `repo` and the
1837    //    ChannelRouter maps it to a topic/channel, send there with `topic_id`.
1838    // 2. Subscribed channels: send to each (channel, thread_id) subscribed to
1839    //    the repo, using `format_with_project()` so recipients know the source.
1840    // 3. Fallback: if no repo or no dedicated channel, broadcast to all
1841    //    channels without a topic_id (legacy behaviour).
1842    {
1843        let mut notification_rx = transport.subscribe_notifications();
1844        let channels = channel_registry.clone();
1845        let notif_router = channel_router.clone();
1846        // Grab a store reference for subscription lookups.
1847        let notif_store: Option<Arc<TaskStore>> = project_engines.first().map(|e| e.store.clone());
1848        tokio::spawn(async move {
1849            loop {
1850                match notification_rx.recv().await {
1851                    Ok(notification) => {
1852                        let level = NotificationLevel::from_config();
1853                        if !level.should_notify(&notification.status) {
1854                            tracing::debug!(
1855                                task_id = %notification.task_id,
1856                                status = %notification.status,
1857                                "notification suppressed by level={:?}",
1858                                level
1859                            );
1860                            continue;
1861                        }
1862
1863                        tracing::info!(
1864                            task_id = %notification.task_id,
1865                            status = %notification.status,
1866                            repo = ?notification.repo,
1867                            "routing notification to channels"
1868                        );
1869
1870                        // Track whether we sent to at least one dedicated/subscribed target.
1871                        let mut routed = false;
1872
1873                        // 0. Direct target: if notify_target is set, send straight to
1874                        //    that Telegram chat_id and skip all other routing.
1875                        if let Some(ref target) = notification.notify_target {
1876                            let telegram = channels.iter().find(|c| c.name() == "telegram");
1877                            if let Some(channel) = telegram {
1878                                let body = notification.format_telegram();
1879                                let metadata = serde_json::json!({
1880                                    "preformatted_html": true,
1881                                    "chat_id_override": target
1882                                });
1883                                let msg = OutgoingMessage {
1884                                    thread_id: notification.task_id.clone(),
1885                                    body,
1886                                    reply_to: None,
1887                                    metadata,
1888                                    topic_id: None,
1889                                };
1890                                if let Err(e) = channel.send(&msg).await {
1891                                    tracing::warn!(
1892                                        task_id = %notification.task_id,
1893                                        target,
1894                                        ?e,
1895                                        "failed to send to notify_target"
1896                                    );
1897                                } else {
1898                                    routed = true;
1899                                }
1900                            }
1901                        }
1902
1903                        if routed {
1904                            // notify_target handled — skip further routing
1905                        } else if let Some(repo) = notification.repo.as_deref() {
1906                            // Track destinations already sent to in this iteration so
1907                            // the dedicated (path 1) and subscribed (path 2) loops
1908                            // don't double-fire the same Telegram/Discord destination
1909                            // when a repo's configured topic and a `channel_subscriptions`
1910                            // row resolve to the same `(channel, topic_id)`.
1911                            let mut sent: std::collections::HashSet<(String, Option<String>)> =
1912                                std::collections::HashSet::new();
1913
1914                            // 1. Dedicated channel targets for this repo.
1915                            for channel in channels.iter() {
1916                                let ch_name = channel.name();
1917                                if let Some(topic_id) =
1918                                    notif_router.target_for_project(repo, ch_name)
1919                                {
1920                                    let body = match ch_name {
1921                                        "telegram" => notification.format_telegram(),
1922                                        "discord" => notification.format_discord(),
1923                                        "slack" => notification.format_slack(),
1924                                        _ => continue,
1925                                    };
1926                                    let metadata = if ch_name == "telegram" {
1927                                        serde_json::json!({"preformatted_html": true})
1928                                    } else {
1929                                        serde_json::json!({})
1930                                    };
1931                                    let resolved_topic = Some(topic_id.to_string());
1932                                    let msg = OutgoingMessage {
1933                                        thread_id: notification.task_id.clone(),
1934                                        body,
1935                                        reply_to: None,
1936                                        metadata,
1937                                        topic_id: resolved_topic.clone(),
1938                                    };
1939                                    if let Err(e) = channel.send(&msg).await {
1940                                        tracing::warn!(
1941                                            channel = ch_name,
1942                                            task_id = %notification.task_id,
1943                                            ?e,
1944                                            "failed to send to dedicated channel"
1945                                        );
1946                                    } else {
1947                                        sent.insert((ch_name.to_string(), resolved_topic));
1948                                        routed = true;
1949                                    }
1950                                }
1951                            }
1952
1953                            // 2. Subscribed channels for this repo.
1954                            if let Some(store) = &notif_store {
1955                                match store.list_subscribers_for_repo(repo).await {
1956                                    Ok(subscribers) => {
1957                                        for (ch_name, thread_id, topic_id) in subscribers {
1958                                            let channel =
1959                                                channels.iter().find(|c| c.name() == ch_name);
1960                                            let Some(channel) = channel else {
1961                                                continue;
1962                                            };
1963                                            let resolved_topic = if topic_id.is_empty() {
1964                                                None
1965                                            } else {
1966                                                Some(topic_id.clone())
1967                                            };
1968                                            // Skip if a dedicated send to the same
1969                                            // (channel, topic_id) already happened.
1970                                            if sent.contains(&(
1971                                                ch_name.clone(),
1972                                                resolved_topic.clone(),
1973                                            )) {
1974                                                tracing::debug!(
1975                                                    channel = %ch_name,
1976                                                    task_id = %notification.task_id,
1977                                                    topic_id = ?resolved_topic,
1978                                                    "skipping duplicate subscriber dispatch — destination already received from dedicated path"
1979                                                );
1980                                                continue;
1981                                            }
1982                                            let body = notification.format_with_project(&ch_name);
1983                                            let metadata = if ch_name == "telegram" {
1984                                                serde_json::json!({"preformatted_html": true})
1985                                            } else {
1986                                                serde_json::json!({})
1987                                            };
1988                                            let msg = OutgoingMessage {
1989                                                thread_id: thread_id.clone(),
1990                                                body,
1991                                                reply_to: None,
1992                                                metadata,
1993                                                topic_id: resolved_topic.clone(),
1994                                            };
1995                                            if let Err(e) = channel.send(&msg).await {
1996                                                tracing::warn!(
1997                                                    channel = %ch_name,
1998                                                    task_id = %notification.task_id,
1999                                                    ?e,
2000                                                    "failed to send to subscribed channel"
2001                                                );
2002                                            } else {
2003                                                sent.insert((ch_name.clone(), resolved_topic));
2004                                                routed = true;
2005                                            }
2006                                        }
2007                                    }
2008                                    Err(e) => {
2009                                        tracing::warn!(
2010                                            repo,
2011                                            ?e,
2012                                            "failed to list subscribers for repo"
2013                                        );
2014                                    }
2015                                }
2016                            }
2017                        }
2018
2019                        // 3. Fallback: broadcast to all channels when no routing happened.
2020                        if !routed {
2021                            for channel in channels.iter() {
2022                                let (body, should_send, is_telegram) = match channel.name() {
2023                                    "telegram" => (notification.format_telegram(), true, true),
2024                                    "discord" => (notification.format_discord(), true, false),
2025                                    "slack" => (notification.format_slack(), true, false),
2026                                    // GitHub is already handled by backend.post_comment()
2027                                    // tmux doesn't need task completion notifications
2028                                    _ => (String::new(), false, false),
2029                                };
2030
2031                                if !should_send {
2032                                    continue;
2033                                }
2034
2035                                let metadata = if is_telegram {
2036                                    serde_json::json!({"preformatted_html": true})
2037                                } else {
2038                                    serde_json::json!({})
2039                                };
2040                                let msg = OutgoingMessage {
2041                                    thread_id: notification.task_id.clone(),
2042                                    body,
2043                                    reply_to: None,
2044                                    metadata,
2045                                    topic_id: None,
2046                                };
2047
2048                                if let Err(e) = channel.send(&msg).await {
2049                                    tracing::warn!(
2050                                        channel = channel.name(),
2051                                        task_id = %notification.task_id,
2052                                        ?e,
2053                                        "failed to send notification"
2054                                    );
2055                                }
2056                            }
2057                        }
2058                    }
2059                    Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
2060                        tracing::warn!(missed = n, "notification receiver lagged");
2061                    }
2062                    Err(tokio::sync::broadcast::error::RecvError::Closed) => {
2063                        tracing::debug!("notification channel closed");
2064                        break;
2065                    }
2066                }
2067            }
2068        });
2069        tracing::info!("notification dispatcher started");
2070    }
2071
2072    // Notify used by webhook events to wake up the engine tick immediately
2073    let webhook_notify = Arc::new(Notify::new());
2074
2075    // Track webhook state for health checks and fallback.
2076    // When webhooks are disabled, `in_fallback_mode` stays true so sync
2077    // uses the faster fallback interval for polling.
2078    let webhook_port: Option<u16>;
2079    let mut webhook_healthy: bool;
2080    let mut last_webhook_health_check = std::time::Instant::now();
2081    // Start webhook server if configured
2082    let webhook_enabled = crate::config::get("webhook.enabled")
2083        .map(|v| v == "true")
2084        .unwrap_or(false);
2085
2086    // Shared status updated by the server-spawn task and the health-check loop.
2087    let webhook_status = Arc::new(tokio::sync::Mutex::new(
2088        crate::webhook_status::WebhookStatus::default(),
2089    ));
2090
2091    if webhook_enabled {
2092        let port: u16 = crate::config::get("webhook.port")
2093            .ok()
2094            .and_then(|v| v.parse().ok())
2095            .unwrap_or(8080);
2096        webhook_port = Some(port);
2097        let secret = crate::config::get("webhook.secret").unwrap_or_default();
2098        let webhook_repo = project_engines
2099            .first()
2100            .map(|e| e.repo.clone())
2101            .unwrap_or_default();
2102
2103        let (tx, mut rx) = tokio::sync::mpsc::channel::<IncomingMessage>(64);
2104
2105        // Initialise status: configured, not yet healthy.
2106        let to_save = {
2107            let mut s = webhook_status.lock().await;
2108            s.configured = true;
2109            s.port = Some(port);
2110            s.healthy = false;
2111            s.fallback_mode = false;
2112            s.clone()
2113        };
2114        to_save.save().await;
2115
2116        // Spawn the HTTP server with exponential-backoff retry on transient
2117        // bind errors (e.g. EADDRINUSE).  After MAX_ATTEMPTS the engine falls
2118        // back to polling and updates the shared status accordingly.
2119        const WEBHOOK_MAX_ATTEMPTS: u32 = 5;
2120        let status_for_spawn = webhook_status.clone();
2121        tokio::spawn(async move {
2122            use crate::channels::github::{is_transient_bind_error, webhook_backoff_delay};
2123            let mut attempt = 0u32;
2124            loop {
2125                attempt += 1;
2126                tracing::info!(attempt, port, "attempting to start webhook server");
2127                match start_webhook_server(port, secret.clone(), webhook_repo.clone(), tx.clone())
2128                    .await
2129                {
2130                    Ok(_) => {
2131                        tracing::info!(attempt, "webhook server exited cleanly");
2132                        break;
2133                    }
2134                    Err(e) => {
2135                        let reason = e.to_string();
2136                        tracing::error!(attempt, %reason, "webhook server failed");
2137                        if attempt >= WEBHOOK_MAX_ATTEMPTS || !is_transient_bind_error(&e) {
2138                            let kind = if attempt >= WEBHOOK_MAX_ATTEMPTS {
2139                                "max attempts reached"
2140                            } else {
2141                                "non-transient error"
2142                            };
2143                            tracing::error!(
2144                                attempt,
2145                                %reason,
2146                                kind,
2147                                orch_webhook_in_fallback = true,
2148                                "webhook server giving up, switching to polling fallback"
2149                            );
2150                            let to_save = {
2151                                let mut s = status_for_spawn.lock().await;
2152                                s.fallback_mode = true;
2153                                s.healthy = false;
2154                                s.last_failure_reason = Some(reason);
2155                                s.startup_attempts = attempt;
2156                                s.clone()
2157                            };
2158                            to_save.save().await;
2159                            break;
2160                        }
2161                        let delay = webhook_backoff_delay(attempt);
2162                        tracing::warn!(
2163                            attempt,
2164                            delay_ms = delay.as_millis(),
2165                            %reason,
2166                            "webhook bind failed (transient), retrying with backoff"
2167                        );
2168                        {
2169                            let to_save = {
2170                                let mut s = status_for_spawn.lock().await;
2171                                s.startup_attempts = attempt;
2172                                s.last_failure_reason = Some(reason);
2173                                s.clone()
2174                            };
2175                            to_save.save().await;
2176                        }
2177                        tokio::time::sleep(delay).await;
2178                    }
2179                }
2180            }
2181        });
2182
2183        // Spawn the message forwarding task (reads from webhook channel)
2184        let notify = webhook_notify.clone();
2185        let transport_for_webhook = transport.clone();
2186        tokio::spawn(async move {
2187            while let Some(msg) = rx.recv().await {
2188                tracing::info!(
2189                    channel = %msg.channel,
2190                    thread = %msg.thread_id,
2191                    event = %msg.metadata.get("event").and_then(|v| v.as_str()).unwrap_or("unknown"),
2192                    action = %msg.metadata.get("action").and_then(|v| v.as_str()).unwrap_or("unknown"),
2193                    "webhook event received, triggering immediate tick"
2194                );
2195                let route = transport_for_webhook.route(&msg).await;
2196                tracing::info!(
2197                    channel = %msg.channel,
2198                    route = ?route,
2199                    "webhook event routed"
2200                );
2201                // Wake up the engine tick immediately instead of waiting up to 10s
2202                notify.notify_one();
2203            }
2204        });
2205
2206        webhook_healthy = true;
2207        tracing::info!(port, orch_webhook_up = true, "webhook server started");
2208    } else {
2209        webhook_port = None;
2210        webhook_healthy = false;
2211        {
2212            let to_save = {
2213                let mut s = webhook_status.lock().await;
2214                s.configured = false;
2215                s.fallback_mode = true;
2216                s.clone()
2217            };
2218            to_save.save().await;
2219        }
2220        tracing::info!(
2221            orch_webhook_in_fallback = true,
2222            "webhook server disabled, using polling fallback mode"
2223        );
2224    }
2225
2226    start_relay_client(&project_engines, &webhook_notify);
2227    crate::github::app::start_loader();
2228
2229    // Agent router (selects agent + model per task) - shared across projects.
2230    // Router::from_config() may run `opencode models` when the config uses opencode.
2231    // spawn_blocking keeps the Tokio runtime thread free during that I/O
2232    let router = Arc::new(RwLock::new(
2233        match tokio::task::spawn_blocking(Router::from_config).await {
2234            Ok(r) => r,
2235            Err(e) => {
2236                tracing::error!(?e, "router init panicked in spawn_blocking, using default");
2237                tokio::task::spawn_blocking(|| Router::new(RouterConfig::default()))
2238                    .await
2239                    .unwrap_or_else(|e2| {
2240                        panic!("router default init also panicked in spawn_blocking — cannot start engine without a router: {e2:?}");
2241                    })
2242            }
2243        },
2244    ));
2245    {
2246        let r = router.read().await;
2247        tracing::info!(
2248            mode = %r.config.mode,
2249            agents = ?r.available_agents,
2250            fallback = %r.config.fallback_executor,
2251            "router initialized"
2252        );
2253    }
2254
2255    // Concurrency limiter (shared across all projects). `parallel_in_force` is the
2256    // limit actually handed out, which lags `config.max_parallel` after a shrink
2257    // until the running tasks give their permits back.
2258    let semaphore = Arc::new(Semaphore::new(config.max_parallel));
2259    let mut parallel_in_force = config.max_parallel;
2260
2261    // In-memory dispatch guard: tracks task IDs currently being dispatched.
2262    // Guards against GitHub API eventual consistency — after update_status(InProgress),
2263    // the label-removal webhook can trigger an immediate tick where list_by_status(Routed)
2264    // still returns the task (search index propagation delay). The tmux session does not
2265    // exist until the runner completes worktree setup (~10s later), so session_exists
2266    // alone is insufficient. Keyed by "{repo}/{task_id}".
2267    let dispatching: Arc<dashmap::DashMap<String, String>> = Arc::new(dashmap::DashMap::new());
2268
2269    // In-memory guard to prevent double-spawn of auto-merge background tasks.
2270    // Since review_open_prs runs every sync_tick (~10s) but CI polling can take
2271    // up to 10 minutes, we track which tasks already have an auto-merge in flight.
2272    let auto_merge_in_flight: Arc<dashmap::DashSet<String>> = Arc::new(dashmap::DashSet::new());
2273
2274    // Subscribe to config file changes for hot reload
2275    let mut config_rx = crate::config::subscribe();
2276
2277    // Track sync interval
2278    let mut last_sync = std::time::Instant::now();
2279
2280    // Track upgrade check interval
2281    let mut last_upgrade_check: Option<std::time::Instant> = None;
2282
2283    // Reset epoch of the GitHub rate-limit window already reported, so the log line,
2284    // the KV flag and the channel notification fire once per window instead of per tick
2285    let mut rate_limit_reported: Option<i64> = None;
2286
2287    // Channel for weight signals from task runners back to the router
2288    let (weight_tx, mut weight_rx) = mpsc::channel::<WeightSignal>(64);
2289
2290    // A restart ends every review session, so reset each in_review task left without one
2291    for engine in project_engines.iter().filter(|_| leads) {
2292        let reset =
2293            reset_orphaned_reviews(&engine.task_manager, &engine.store, &engine.repo, &tmux).await;
2294
2295        if reset > 0 {
2296            tracing::info!(repo = %engine.repo, reset, "reset orphaned reviews to needs_review on startup");
2297        }
2298    }
2299
2300    // Spawn dispatch subscribers — react to Routed events immediately
2301    for engine in &project_engines {
2302        subscribers::dispatch::spawn(
2303            event_bus.subscribe(),
2304            engine.backend.clone(),
2305            tmux.clone(),
2306            engine.runner.clone(),
2307            capture_for_tick.clone(),
2308            semaphore.clone(),
2309            engine.task_manager.clone(),
2310            weight_tx.clone(),
2311            router.clone(),
2312            dispatching.clone(),
2313            engine.store.clone(),
2314            engine.repo.clone(),
2315        );
2316    }
2317    tracing::info!("dispatch subscriber started");
2318
2319    // Spawn review subscribers — react to NeedsReview events immediately
2320    for engine in &project_engines {
2321        subscribers::review::spawn(
2322            event_bus.subscribe(),
2323            engine.backend.clone(),
2324            tmux.clone(),
2325            semaphore.clone(),
2326            engine.task_manager.clone(),
2327            router.clone(),
2328            dispatching.clone(),
2329            engine.store.clone(),
2330            engine.repo.clone(),
2331        );
2332    }
2333    tracing::info!("review subscriber started");
2334
2335    // Spawn unblock subscribers — react to Done events, unblock parent tasks immediately
2336    for engine in &project_engines {
2337        subscribers::unblock::spawn(
2338            event_bus.subscribe(),
2339            engine.backend.clone(),
2340            engine.task_manager.clone(),
2341            engine.store.clone(),
2342            engine.repo.clone(),
2343        );
2344    }
2345    tracing::info!("unblock subscriber started");
2346
2347    // Spawn notify subscriber — reacts to ALL events, pushes to transport.
2348    // Spawned once (not per-project) since the transport handles all repos.
2349    subscribers::notify::spawn(event_bus.subscribe(), transport.clone());
2350    tracing::info!("notify subscriber started");
2351
2352    // Main loop
2353    tracing::info!(
2354        tick = ?config.tick_interval,
2355        sync = ?config.sync_interval,
2356        parallel = config.max_parallel,
2357        "entering main loop"
2358    );
2359    // Values of the settings that only take effect at startup, so a reload can
2360    // tell the operator their edit needs a restart.
2361    let mut restart_only = restart_only_snapshot();
2362
2363    let mut interval = tokio::time::interval(config.tick_interval);
2364
2365    // Signal handlers (launchd/systemd send SIGTERM to stop services, SIGHUP for reload/restart)
2366    let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
2367    let mut sighup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
2368
2369    // Guard to prevent concurrent sync_tick runs (sync is spawned as a background task).
2370    let sync_in_progress = Arc::new(std::sync::atomic::AtomicBool::new(false));
2371
2372    // Tick watchdog: detects when the main loop hasn't completed a tick in > 60s.
2373    // Updates an atomic timestamp at the end of each tick iteration.
2374    let last_tick_epoch = Arc::new(std::sync::atomic::AtomicU64::new(
2375        std::time::SystemTime::now()
2376            .duration_since(std::time::UNIX_EPOCH)
2377            .unwrap_or_default()
2378            .as_secs(),
2379    ));
2380    {
2381        let last_tick_epoch = Arc::clone(&last_tick_epoch);
2382        let tick_interval_secs = config.tick_interval.as_secs();
2383        tokio::spawn(async move {
2384            // Check every 30s whether the main loop is still ticking.
2385            let mut watchdog_interval = tokio::time::interval(std::time::Duration::from_secs(30));
2386            // Own suspend baseline, independent of the main loop's checkpoint(). The
2387            // watchdog's interval timer also freezes during a host suspend, so this
2388            // detects the gap from its own wake-up instead of racing the main loop's
2389            // checkpoint() for the same GAP_LOG entry (see #3544).
2390            let mut suspend_detector = crate::engine::suspend::SuspendDetector::new();
2391            loop {
2392                watchdog_interval.tick().await;
2393                let own_gap = suspend_detector.check();
2394                let last = last_tick_epoch.load(std::sync::atomic::Ordering::Relaxed);
2395                let now = std::time::SystemTime::now()
2396                    .duration_since(std::time::UNIX_EPOCH)
2397                    .unwrap_or_default()
2398                    .as_secs();
2399                let stale_secs = now.saturating_sub(last);
2400                // Warn if the tick loop hasn't completed in > 6× the tick interval (at least 60s).
2401                let threshold = (tick_interval_secs * 6).max(60);
2402                if stale_secs > threshold {
2403                    // A host suspend/resume gap fully explains a stale window that
2404                    // isn't an actual stall — the process (and its timers) were
2405                    // simply not scheduled while the host was asleep. Prefer this
2406                    // watchdog's own detector (immune to the checkpoint race above);
2407                    // fall back to the shared log in case the main loop's checkpoint()
2408                    // already ran and recorded a larger gap.
2409                    let shared_gap = crate::engine::suspend::gap_detected_within(
2410                        std::time::Duration::from_secs(stale_secs),
2411                    );
2412                    let gap = match (own_gap, shared_gap) {
2413                        (Some(a), Some(b)) => Some(a.max(b)),
2414                        (Some(a), None) => Some(a),
2415                        (None, Some(b)) => Some(b),
2416                        (None, None) => None,
2417                    };
2418                    if let Some(gap) = gap {
2419                        let gap_secs = gap.num_seconds() as u64;
2420                        if gap_secs >= stale_secs {
2421                            tracing::info!(
2422                                stale_secs,
2423                                threshold,
2424                                suspend_gap_secs = gap_secs,
2425                                "tick loop stale window explained by host suspend/resume, not a stall"
2426                            );
2427                        } else {
2428                            tracing::error!(
2429                                stale_secs,
2430                                threshold,
2431                                suspend_gap_secs = gap_secs,
2432                                "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — suspend gap of {}s only partially explains the stall",
2433                                stale_secs,
2434                                threshold,
2435                                gap_secs,
2436                            );
2437                        }
2438                    } else {
2439                        tracing::error!(
2440                            stale_secs,
2441                            threshold,
2442                            "WATCHDOG: tick loop has not completed a tick in {}s (threshold {}s) — possible stall",
2443                            stale_secs,
2444                            threshold,
2445                        );
2446                    }
2447                }
2448            }
2449        });
2450    }
2451
2452    loop {
2453        tokio::select! {
2454            _ = interval.tick() => {
2455                let tick_start = std::time::Instant::now();
2456
2457                // Detect a host suspend/resume gap once per iteration, in one place.
2458                // The watchdog and stuck-task recovery both read from this instead of
2459                // re-deriving suspend information from their own wall-clock deltas.
2460                if let Some(gap) = crate::engine::suspend::checkpoint() {
2461                    tracing::info!(
2462                        gap_secs = gap.num_seconds(),
2463                        "host suspend/resume gap detected, discounting from stuck-task age checks"
2464                    );
2465                }
2466
2467                // Finish a pending shrink of the dispatch pool as running tasks
2468                // release their permits. Only logs when a permit was actually
2469                // taken back, so a long-running task does not log every tick.
2470                if parallel_in_force != config.max_parallel {
2471                    let resized =
2472                        resize_dispatch_pool(&semaphore, parallel_in_force, config.max_parallel);
2473                    if resized != parallel_in_force {
2474                        parallel_in_force = resized;
2475                        tracing::info!(
2476                            in_force = parallel_in_force,
2477                            target = config.max_parallel,
2478                            "dispatch pool resized"
2479                        );
2480                    }
2481                }
2482
2483                // Tick weight recovery for rate-limited agents
2484                {
2485                    let mut rw = router.write().await;
2486                    rw.tick_weight_recovery();
2487                }
2488
2489                // Report the GitHub rate limit once per window, then tick anyway. Calls
2490                // into GitHub now fail fast instead of sleeping until the reset, so the
2491                // local phases keep moving and the watchdog does not see a stalled loop.
2492                if let Some(remaining) = GhHttp::is_rate_limited() {
2493                    let reset_at = chrono::Utc::now()
2494                        .timestamp()
2495                        .saturating_add(i64::try_from(remaining.as_secs()).unwrap_or(i64::MAX));
2496                    // Tolerate jitter in the header so one window reports once
2497                    if rate_limit_reported.is_none_or(|prev| (reset_at - prev).abs() > 60) {
2498                        rate_limit_reported = Some(reset_at);
2499                        report_rate_limited(reset_at, project_engines.first().map(|e| &e.store), Some(&transport)).await;
2500                    }
2501                } else if let Some(prev) = rate_limit_reported.take() {
2502                    tracing::info!(
2503                        limited_until = prev,
2504                        "GitHub API rate limit cleared"
2505                    );
2506                    if let Some(engine) = project_engines.first() {
2507                        let _ = engine.store.kv_delete(RATE_LIMITED_UNTIL_KEY).await;
2508                    }
2509                }
2510
2511                // Core tick: poll tasks for all projects
2512                tick::tick_all(
2513                    &project_engines,
2514                    &tmux,
2515                    &capture_for_tick,
2516                    &semaphore,
2517                    &config,
2518                    &router,
2519                    &weight_tx,
2520                    &dispatching,
2521                    Some(&transport),
2522                    &active_repos,
2523                    &auto_merge_in_flight,
2524                ).await;
2525
2526                // Drain pending weight signals after tick processing so the router
2527                // learns from outcomes produced by this iteration's task dispatches.
2528                while let Ok(signal) = weight_rx.try_recv() {
2529                    let mut rw = router.write().await;
2530                    match signal {
2531                        WeightSignal::RateLimited { ref agent } => {
2532                            rw.record_rate_limit(agent);
2533                        }
2534                        WeightSignal::Success { ref agent } => {
2535                            rw.record_success(agent);
2536                        }
2537                        WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
2538                    }
2539                }
2540
2541                // Periodic sync (less frequent) — spawned as a background task so it
2542                // cannot block the main tick loop. A stalled sync (hung HTTP call, slow
2543                // DB query, lock contention) previously parked all tokio workers for 12+
2544                // minutes because it ran inline. See issue #2574.
2545                if last_sync.elapsed() >= config.sync_interval {
2546                    if sync_in_progress.compare_exchange(
2547                        false,
2548                        true,
2549                        std::sync::atomic::Ordering::AcqRel,
2550                        std::sync::atomic::Ordering::Relaxed,
2551                    ).is_ok() {
2552                        spawn_sync_pass(
2553                            &project_engines,
2554                            &tmux,
2555                            &config,
2556                            &router,
2557                            &dispatching,
2558                            &auto_merge_in_flight,
2559                            &sync_in_progress,
2560                            "periodic",
2561                        );
2562                    } else {
2563                        tracing::debug!("sync tick still in progress, skipping");
2564                    }
2565                    // Records sync *schedule* time (not completion). This prevents
2566                    // re-entering the sync branch every tick while one is in flight.
2567                    // The sync_in_progress guard handles actual concurrency control.
2568                    last_sync = std::time::Instant::now();
2569                }
2570
2571                // Periodic webhook health check
2572                if webhook_enabled {
2573                    let health_check_interval = config.webhook_health_check_interval
2574                        .unwrap_or(std::time::Duration::from_secs(60));
2575
2576                    if last_webhook_health_check.elapsed() >= health_check_interval {
2577                        if let Some(port) = webhook_port {
2578                            let (health, failure_reason) =
2579                                crate::channels::github::check_webhook_health(port).await;
2580                            if health != webhook_healthy {
2581                                webhook_healthy = health;
2582                                if webhook_healthy {
2583                                    tracing::info!(port, orch_webhook_up = true, "webhook health restored");
2584                                } else {
2585                                    tracing::warn!(
2586                                        port,
2587                                        orch_webhook_up = false,
2588                                        reason = failure_reason.as_deref().unwrap_or("unknown"),
2589                                        "webhook health check failed"
2590                                    );
2591                                }
2592                            }
2593                            // Persist updated status.
2594                            {
2595                                let to_save = {
2596                                    let mut s = webhook_status.lock().await;
2597                                    s.healthy = health;
2598                                    s.last_check_utc = Some(chrono::Utc::now());
2599                                    if health {
2600                                        s.last_failure_reason = None;
2601                                    } else if failure_reason.is_some() {
2602                                        s.last_failure_reason = failure_reason;
2603                                    }
2604                                    s.clone()
2605                                };
2606                                to_save.save().await;
2607                            }
2608                        }
2609                        last_webhook_health_check = std::time::Instant::now();
2610                    }
2611                }
2612
2613                // Periodic upgrade check — notify channels when a newer release is available.
2614                if should_run_upgrade_check(last_upgrade_check, config.upgrade_check_interval) {
2615                    if let Some(store) = project_engines.first().map(|e| e.store.clone()) {
2616                        let channels = channel_registry.clone();
2617                        let current = env!("ORCH_VERSION").to_string();
2618                        let check_interval =
2619                            std::time::Duration::from_secs(config.upgrade_check_interval);
2620                        tokio::spawn(async move {
2621                            check_and_notify_upgrade(&store, &channels, &current, check_interval)
2622                                .await;
2623                        });
2624                    }
2625                    last_upgrade_check = Some(std::time::Instant::now());
2626                }
2627
2628                // Update watchdog timestamp + log tick duration.
2629                let tick_elapsed = tick_start.elapsed();
2630                if tick_elapsed.as_secs() > 30 {
2631                    tracing::warn!(elapsed_ms = tick_elapsed.as_millis() as u64, "slow tick");
2632                } else {
2633                    tracing::debug!(elapsed_ms = tick_elapsed.as_millis() as u64, "tick complete");
2634                }
2635                last_tick_epoch.store(
2636                    std::time::SystemTime::now()
2637                        .duration_since(std::time::UNIX_EPOCH)
2638                        .unwrap_or_default()
2639                        .as_secs(),
2640                    std::sync::atomic::Ordering::Relaxed,
2641                );
2642            }
2643            // Webhook events trigger an immediate tick (bypass polling interval)
2644            _ = webhook_notify.notified() => {
2645                if let Some(remaining) = GhHttp::is_rate_limited() {
2646                    tracing::warn!(
2647                        remaining_secs = remaining.as_secs(),
2648                        "GitHub API rate-limited, skipping webhook-triggered tick"
2649                    );
2650                } else {
2651                    tracing::info!("webhook event triggered immediate tick");
2652
2653                    tick::tick_all(
2654                        &project_engines,
2655                        &tmux,
2656                        &capture_for_tick,
2657                        &semaphore,
2658                        &config,
2659                        &router,
2660                        &weight_tx,
2661                        &dispatching,
2662                        Some(&transport),
2663                        &active_repos,
2664                        &auto_merge_in_flight,
2665                    ).await;
2666
2667                // Drain pending weight signals after webhook-triggered tick processing.
2668                while let Ok(signal) = weight_rx.try_recv() {
2669                    let mut rw = router.write().await;
2670                    match signal {
2671                        WeightSignal::RateLimited { ref agent } => {
2672                            rw.record_rate_limit(agent);
2673                        }
2674                        WeightSignal::Success { ref agent } => {
2675                            rw.record_success(agent);
2676                        }
2677                        WeightSignal::Rerouted | WeightSignal::Blocked | WeightSignal::None => {}
2678                    }
2679                }
2680
2681                // Also attempt to run an immediate sync (ingest/cleanup) in the
2682                // background so webhook-driven events (e.g. new issues) are
2683                // picked up without waiting for the periodic sync interval.
2684                // Reuse the same sync_in_progress guard used by the periodic
2685                // branch to avoid concurrent syncs.
2686                if sync_in_progress.compare_exchange(
2687                    false,
2688                    true,
2689                    std::sync::atomic::Ordering::AcqRel,
2690                    std::sync::atomic::Ordering::Relaxed,
2691                ).is_ok() {
2692                    spawn_sync_pass(
2693                        &project_engines,
2694                        &tmux,
2695                        &config,
2696                        &router,
2697                        &dispatching,
2698                        &auto_merge_in_flight,
2699                        &sync_in_progress,
2700                        "webhook",
2701                    );
2702                    // Record schedule time so periodic sync doesn't immediately re-run.
2703                    last_sync = std::time::Instant::now();
2704                } else {
2705                    tracing::debug!("sync tick still in progress, skipping webhook-triggered immediate sync");
2706                }
2707                }
2708
2709                // Also reset the interval so we don't get a redundant tick right after
2710                interval.reset();
2711            }
2712            result = config_rx.recv() => {
2713                // A notification only arrives for a file that parsed, so there is no
2714                // broken-config case to guard against here (see `config::reload_file`).
2715                let reload = match result {
2716                    Ok(path) => {
2717                        tracing::info!(path = %path.display(), "config file changed, reloading");
2718                        true
2719                    }
2720                    Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
2721                        tracing::warn!(missed = n, "config change receiver lagged, reloading");
2722                        true
2723                    }
2724                    Err(tokio::sync::broadcast::error::RecvError::Closed) => {
2725                        tracing::warn!("config change channel closed");
2726                        false
2727                    }
2728                };
2729
2730                if reload {
2731                    // Reload engine config
2732                    let new_config = EngineConfig::from_config();
2733                    log_engine_config_changes(&config, &new_config);
2734
2735                    let new_restart_only = restart_only_snapshot();
2736                    log_restart_only_changes(&restart_only, &new_restart_only);
2737                    restart_only = new_restart_only;
2738
2739                    let tick_changed = new_config.tick_interval != config.tick_interval;
2740                    config = new_config;
2741
2742                    // Reset tick interval if it changed
2743                    if tick_changed {
2744                        interval = tokio::time::interval(config.tick_interval);
2745                        tracing::info!(tick = ?config.tick_interval, "tick interval updated");
2746                    }
2747
2748                    // Resize the dispatch pool. A shrink only takes the permits that are
2749                    // free right now; the rest are taken as running tasks finish.
2750                    if parallel_in_force != config.max_parallel {
2751                        parallel_in_force = resize_dispatch_pool(
2752                            &semaphore,
2753                            parallel_in_force,
2754                            config.max_parallel,
2755                        );
2756                        tracing::info!(
2757                            in_force = parallel_in_force,
2758                            target = config.max_parallel,
2759                            "dispatch pool resized"
2760                        );
2761                    }
2762
2763                    // Reload router config (async-safe: use reload_async to avoid blocking the runtime)
2764                    {
2765                        let mut router_guard = router.write().await;
2766                        router_guard.reload_async().await;
2767                    }
2768
2769                    // Pick up projects added to `projects:`
2770                    sync_project_engines(
2771                        &mut project_engines,
2772                        &mut active_repos,
2773                        &event_bus,
2774                        &tmux,
2775                        &capture_for_tick,
2776                        &semaphore,
2777                        &weight_tx,
2778                        &router,
2779                        &dispatching,
2780                    ).await;
2781
2782                    tracing::info!(
2783                        tick = ?config.tick_interval,
2784                        sync = ?config.sync_interval,
2785                        parallel = config.max_parallel,
2786                        projects = project_engines.len(),
2787                        "config reloaded"
2788                    );
2789                }
2790            }
2791            signal_name = async {
2792                tokio::select! {
2793                    _ = tokio::signal::ctrl_c() => "SIGINT",
2794                    _ = sigterm.recv() => "SIGTERM",
2795                    _ = sighup.recv() => "SIGHUP",
2796                }
2797            } => {
2798                tracing::info!(signal = signal_name, "beginning graceful shutdown");
2799
2800                // Wrap the entire shutdown sequence in a timeout to enforce the configured limit.
2801                // This prevents indefinite blocking if status updates or tmux operations hang.
2802                let shutdown_result = tokio::time::timeout(
2803                    config.graceful_shutdown_timeout,
2804                    async {
2805                        // Reset in_progress tasks to routed so they re-dispatch after restart.
2806                        // Also reset in_review tasks to needs_review — their review agent
2807                        // tmux sessions will be killed when the process exits.
2808                        let mut reset_count = 0u32;
2809                        let mut review_reset_count = 0u32;
2810                        for engine in &project_engines {
2811                            if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InProgress).await {
2812                                for task in &tasks {
2813                                    if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::Routed).await {
2814                                        tracing::warn!(task_id = task.id.0, ?e, "failed to reset task on shutdown");
2815                                    } else {
2816                                        if let Ok(Some(store_id)) =
2817                                            engine.store.resolve_task_id(&engine.repo, &task.id.0).await
2818                                        {
2819                                            if let Err(e) = engine
2820                                                .store
2821                                                .finalize_incomplete_runs(
2822                                                    store_id,
2823                                                    "aborted",
2824                                                    "graceful shutdown: reset in_progress task to routed",
2825                                                )
2826                                                .await
2827                                            {
2828                                                tracing::warn!(
2829                                                    task_id = task.id.0,
2830                                                    ?e,
2831                                                    "failed to finalize incomplete runs on shutdown"
2832                                                );
2833                                            }
2834                                        }
2835                                        reset_count += 1;
2836                                    }
2837                                }
2838                            }
2839                            // Also reset internal in_progress tasks
2840                            if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, crate::store::TaskStatus::InProgress).await {
2841                                for task in &tasks {
2842                                    let task_id = format!("internal:{}", task.id);
2843                                    if let Err(e) = engine.task_manager.update_task_status(
2844                                        &crate::backends::ExternalId(task_id.clone()),
2845                                        Status::Routed,
2846                                    ).await {
2847                                        tracing::warn!(task_id, ?e, "failed to reset internal task on shutdown");
2848                                    } else {
2849                                        if let Err(e) = engine
2850                                            .store
2851                                            .finalize_incomplete_runs(
2852                                                task.id,
2853                                                "aborted",
2854                                                "graceful shutdown: reset in_progress task to routed",
2855                                            )
2856                                            .await
2857                                        {
2858                                            tracing::warn!(
2859                                                task_id,
2860                                                ?e,
2861                                                "failed to finalize incomplete internal runs on shutdown"
2862                                            );
2863                                        }
2864                                        reset_count += 1;
2865                                    }
2866                                }
2867                            }
2868                            // Reset in_review tasks — review agent sessions die on shutdown
2869                            if let Ok(tasks) = engine.task_manager.list_external_by_status(Status::InReview).await {
2870                                for task in &tasks {
2871                                    if let Err(e) = engine.task_manager.update_task_status(&task.id, Status::NeedsReview).await {
2872                                        tracing::warn!(task_id = task.id.0, ?e, "failed to reset in_review task on shutdown");
2873                                    } else {
2874                                        if let Ok(Some(store_id)) =
2875                                            engine.store.resolve_task_id(&engine.repo, &task.id.0).await
2876                                        {
2877                                            if let Err(e) = engine
2878                                                .store
2879                                                .finalize_incomplete_runs(
2880                                                    store_id,
2881                                                    "aborted",
2882                                                    "graceful shutdown: reset in_review task to needs_review",
2883                                                )
2884                                                .await
2885                                            {
2886                                                tracing::warn!(
2887                                                    task_id = task.id.0,
2888                                                    ?e,
2889                                                    "failed to finalize incomplete review runs on shutdown"
2890                                                );
2891                                            }
2892                                        }
2893                                        review_reset_count += 1;
2894                                    }
2895                                }
2896                            }
2897                            // Also reset internal in_review tasks
2898                            if let Ok(tasks) = engine.store.list_internal_by_status(&engine.repo, crate::store::TaskStatus::InReview).await {
2899                                for task in &tasks {
2900                                    let task_id = format!("internal:{}", task.id);
2901                                    if let Err(e) = engine.task_manager.update_task_status(
2902                                        &crate::backends::ExternalId(task_id.clone()),
2903                                        Status::NeedsReview,
2904                                    ).await {
2905                                        tracing::warn!(task_id, ?e, "failed to reset internal in_review task on shutdown");
2906                                    } else {
2907                                        if let Err(e) = engine
2908                                            .store
2909                                            .finalize_incomplete_runs(
2910                                                task.id,
2911                                                "aborted",
2912                                                "graceful shutdown: reset in_review task to needs_review",
2913                                            )
2914                                            .await
2915                                        {
2916                                            tracing::warn!(
2917                                                task_id,
2918                                                ?e,
2919                                                "failed to finalize incomplete internal review runs on shutdown"
2920                                            );
2921                                        }
2922                                        review_reset_count += 1;
2923                                    }
2924                                }
2925                            }
2926                        }
2927                        if reset_count > 0 {
2928                            tracing::info!(reset_count, "reset in_progress tasks to routed for re-dispatch");
2929                        }
2930                        if review_reset_count > 0 {
2931                            tracing::info!(review_reset_count, "reset in_review tasks to needs_review for re-dispatch");
2932                        }
2933
2934                        // Kill all orch-managed tmux sessions so stale sessions don't
2935                        // block dispatch after restart (session_exists check).
2936                        let mut killed_sessions = Vec::new();
2937                        if let Ok(sessions) = tmux.list_sessions().await {
2938                            for session in &sessions {
2939                                if session.name.starts_with("orch-") {
2940                                    if let Err(e) = tmux.kill_session(&session.name).await {
2941                                        tracing::warn!(session = %session.name, error = %e, "failed to kill tmux session");
2942                                    } else {
2943                                        killed_sessions.push(session.name.clone());
2944                                    }
2945                                }
2946                            }
2947                            if !killed_sessions.is_empty() {
2948                                tracing::info!(killed = killed_sessions.len(), "killing orch tmux sessions on shutdown");
2949                            }
2950                        }
2951
2952                        // Wait for sessions to actually die before exiting.
2953                        // Prevents race where process exits before tmux finishes cleanup.
2954                        if !killed_sessions.is_empty() {
2955                            let still_alive = tmux
2956                                .wait_for_sessions_dead(
2957                                    &killed_sessions,
2958                                    std::time::Duration::from_millis(100),
2959                                    std::time::Duration::from_secs(5),
2960                                )
2961                                .await;
2962                            if still_alive > 0 {
2963                                tracing::warn!(
2964                                    still_alive,
2965                                    "some tmux sessions did not terminate cleanly - they will be cleaned up on startup"
2966                                );
2967                            }
2968                            tracing::info!(killed = killed_sessions.len() - still_alive, "confirmed tmux sessions terminated");
2969                        }
2970                    },
2971                ).await;
2972
2973                if shutdown_result.is_err() {
2974                    tracing::error!(
2975                        timeout_secs = config.graceful_shutdown_timeout.as_secs(),
2976                        "graceful shutdown timed out, forcing exit"
2977                    );
2978                }
2979
2980                break;
2981            }
2982        }
2983    }
2984
2985    // Clean up event bus port file and service version file
2986    events::cleanup_port_file().await;
2987    crate::cluster::local::cleanup().await;
2988    events::cleanup_version_file();
2989
2990    // transport and channels drop here at end of scope
2991    let _ = transport;
2992    tracing::info!("orch engine stopped");
2993    Ok(())
2994}
2995
2996#[cfg(test)]
2997mod tests {
2998    use super::*;
2999
3000    async fn in_review_task(store: &TaskStore, number: &str) -> i64 {
3001        let id = store
3002            .upsert_external(&crate::store::UpsertExternal {
3003                repo: "owner/repo",
3004                ext_id: number,
3005                title: "Under review",
3006                body: "",
3007                author: "",
3008                url: "",
3009                labels: &[],
3010                origin: "github",
3011            })
3012            .await
3013            .unwrap();
3014        store
3015            .update_status(id, crate::store::TaskStatus::InReview)
3016            .await
3017            .unwrap();
3018        id
3019    }
3020
3021    #[tokio::test]
3022    async fn a_review_without_a_session_goes_back_to_needs_review_and_a_live_one_stays() {
3023        let store = Arc::new(TaskStore::open_memory().await.unwrap());
3024        let backend: Arc<dyn ExternalBackend> =
3025            Arc::new(crate::backends::test_helpers::NoopBackend);
3026        let task_manager =
3027            TaskManager::with_store(backend, store.clone(), "owner/repo".to_string());
3028        let tmux = TmuxManager::isolated();
3029        let orphaned = in_review_task(&store, "11").await;
3030        let live = in_review_task(&store, "12").await;
3031        let session = tmux
3032            .create_session("owner/repo", "12-review", "/tmp", "sleep 30", &[])
3033            .await
3034            .unwrap();
3035        let _guard = crate::tmux::SessionGuard(session);
3036
3037        let reset = reset_orphaned_reviews(&task_manager, &store, "owner/repo", &tmux).await;
3038
3039        assert_eq!(reset, 1);
3040        assert_eq!(
3041            store.get(orphaned).await.unwrap().status,
3042            crate::store::TaskStatus::NeedsReview
3043        );
3044        assert_eq!(
3045            store.get(live).await.unwrap().status,
3046            crate::store::TaskStatus::InReview
3047        );
3048    }
3049
3050    #[test]
3051    fn growing_max_parallel_lets_more_tasks_run_without_a_restart() {
3052        let semaphore = Arc::new(Semaphore::new(4));
3053        let held: Vec<_> = (0..4)
3054            .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3055            .collect();
3056        assert!(
3057            semaphore.clone().try_acquire_owned().is_err(),
3058            "pool is full"
3059        );
3060
3061        let in_force = resize_dispatch_pool(&semaphore, 4, 8);
3062        assert_eq!(in_force, 8);
3063
3064        let grown: Vec<_> = (0..4)
3065            .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3066            .collect();
3067        assert_eq!(held.len() + grown.len(), 8, "8 tasks run at once");
3068        assert!(
3069            semaphore.clone().try_acquire_owned().is_err(),
3070            "pool is full"
3071        );
3072    }
3073
3074    #[test]
3075    fn shrinking_max_parallel_never_cancels_a_running_task() {
3076        let semaphore = Arc::new(Semaphore::new(8));
3077        let mut held: Vec<_> = (0..8)
3078            .map(|_| semaphore.clone().try_acquire_owned().unwrap())
3079            .collect();
3080
3081        // Nothing is free, so all 8 tasks keep their permits and keep running.
3082        let mut in_force = resize_dispatch_pool(&semaphore, 8, 4);
3083        assert_eq!(in_force, 8);
3084        assert_eq!(held.len(), 8);
3085
3086        // Three finish. Their permits are taken back instead of handed out again.
3087        held.truncate(5);
3088        in_force = resize_dispatch_pool(&semaphore, in_force, 4);
3089        assert_eq!(in_force, 5);
3090        assert!(semaphore.clone().try_acquire_owned().is_err());
3091
3092        // One more finishes and the pool settles at the new limit.
3093        held.truncate(4);
3094        in_force = resize_dispatch_pool(&semaphore, in_force, 4);
3095        assert_eq!(in_force, 4);
3096        assert!(semaphore.clone().try_acquire_owned().is_err());
3097
3098        // A slot freed after that is handed out, since 4 is now the real limit.
3099        held.truncate(3);
3100        assert!(semaphore.clone().try_acquire_owned().is_ok());
3101    }
3102
3103    #[test]
3104    fn a_project_added_to_the_config_is_picked_up_and_running_ones_are_not_respawned() {
3105        let configured = vec![
3106            (
3107                "owner/one".to_string(),
3108                std::path::PathBuf::from("/srv/one"),
3109            ),
3110            (
3111                "owner/two".to_string(),
3112                std::path::PathBuf::from("/srv/two"),
3113            ),
3114        ];
3115        let active: std::collections::HashSet<String> =
3116            ["owner/one".to_string()].into_iter().collect();
3117
3118        let (added, removed) = diff_configured_projects(&configured, &active);
3119        assert_eq!(
3120            added,
3121            vec![(
3122                "owner/two".to_string(),
3123                std::path::PathBuf::from("/srv/two")
3124            )],
3125            "only the new project is started, so owner/one keeps its single set of subscribers"
3126        );
3127        assert!(removed.is_empty());
3128    }
3129
3130    #[test]
3131    fn a_project_dropped_from_the_config_is_reported_and_not_restarted() {
3132        let configured = vec![(
3133            "owner/one".to_string(),
3134            std::path::PathBuf::from("/srv/one"),
3135        )];
3136        let active: std::collections::HashSet<String> =
3137            ["owner/one".to_string(), "owner/gone".to_string()]
3138                .into_iter()
3139                .collect();
3140
3141        let (added, removed) = diff_configured_projects(&configured, &active);
3142        assert!(added.is_empty(), "nothing new to start");
3143        assert_eq!(removed, vec!["owner/gone".to_string()]);
3144    }
3145
3146    #[test]
3147    fn an_unchanged_project_list_starts_nothing() {
3148        let configured = vec![(
3149            "owner/one".to_string(),
3150            std::path::PathBuf::from("/srv/one"),
3151        )];
3152        let active: std::collections::HashSet<String> =
3153            ["owner/one".to_string()].into_iter().collect();
3154
3155        assert_eq!(
3156            diff_configured_projects(&configured, &active),
3157            (vec![], vec![])
3158        );
3159    }
3160
3161    #[test]
3162    fn restart_only_keys_are_the_settings_read_once_at_startup() {
3163        // Guards the docs table: every key listed here is documented as needing
3164        // `orch service restart`, and nothing reloadable may be added to it.
3165        assert_eq!(RESTART_ONLY_KEYS, ["channels", "webhook", "relay"]);
3166    }
3167
3168    #[test]
3169    fn a_changed_restart_only_key_is_reported_and_an_unchanged_one_is_not() {
3170        let before = vec![Some("bot_token: a\n".to_string()), None];
3171
3172        assert!(
3173            log_restart_only_changes(&before, &before.clone()).is_empty(),
3174            "a reload that did not touch these keys must stay quiet"
3175        );
3176
3177        // An edited token and a newly added webhook block are both changes
3178        let after = vec![
3179            Some("bot_token: b\n".to_string()),
3180            Some("port: 8080\n".to_string()),
3181        ];
3182        assert_eq!(
3183            log_restart_only_changes(&before, &after),
3184            ["channels", "webhook"]
3185        );
3186
3187        // Only the edited key is reported when the other is untouched
3188        let token_only = vec![Some("bot_token: b\n".to_string()), None];
3189        assert_eq!(log_restart_only_changes(&before, &token_only), ["channels"]);
3190    }
3191
3192    #[test]
3193    fn resize_dispatch_pool_is_a_noop_at_the_current_limit() {
3194        let semaphore = Arc::new(Semaphore::new(4));
3195        assert_eq!(resize_dispatch_pool(&semaphore, 4, 4), 4);
3196        assert_eq!(semaphore.available_permits(), 4);
3197    }
3198
3199    #[test]
3200    fn engine_config_defaults() {
3201        let config = EngineConfig::default();
3202        assert_eq!(config.tick_interval, std::time::Duration::from_secs(10));
3203        assert_eq!(config.sync_interval, std::time::Duration::from_secs(45));
3204        assert_eq!(config.max_parallel, 4);
3205        assert_eq!(config.stuck_timeout, 1800);
3206        assert_eq!(config.no_session_stuck_timeout, 600);
3207        assert!(
3208            config.no_session_stuck_timeout < config.stuck_timeout,
3209            "no_session_stuck_timeout must be shorter than stuck_timeout"
3210        );
3211        assert_eq!(
3212            config.graceful_shutdown_timeout,
3213            std::time::Duration::from_secs(600)
3214        );
3215        assert_eq!(config.upgrade_check_interval, 3600);
3216    }
3217
3218    #[test]
3219    fn engine_config_from_config_uses_defaults_when_no_config() {
3220        let config = EngineConfig::from_config();
3221        assert_eq!(config.tick_interval, std::time::Duration::from_secs(10));
3222        assert_eq!(config.sync_interval, std::time::Duration::from_secs(45));
3223        // max_parallel may be overridden by user config; just check it's reasonable
3224        assert!(config.max_parallel >= 1 && config.max_parallel <= 64);
3225        assert_eq!(config.stuck_timeout, 1800);
3226        assert_eq!(config.no_session_stuck_timeout, 600);
3227        assert_eq!(
3228            config.graceful_shutdown_timeout,
3229            std::time::Duration::from_secs(600)
3230        );
3231        assert_eq!(config.upgrade_check_interval, 3600);
3232    }
3233
3234    #[test]
3235    fn engine_config_no_session_timeout_is_under_15_minutes() {
3236        let config = EngineConfig::default();
3237        assert!(
3238            config.no_session_stuck_timeout <= 900,
3239            "no_session_stuck_timeout ({}) exceeds 15 minutes",
3240            config.no_session_stuck_timeout
3241        );
3242    }
3243
3244    #[test]
3245    fn upgrade_check_runs_immediately_when_never_checked() {
3246        assert!(should_run_upgrade_check(None, 3600));
3247    }
3248
3249    #[test]
3250    fn upgrade_check_waits_for_interval_after_first_run() {
3251        assert!(!should_run_upgrade_check(
3252            Some(std::time::Instant::now()),
3253            3600
3254        ));
3255    }
3256
3257    #[test]
3258    fn upgrade_check_can_be_disabled() {
3259        assert!(!should_run_upgrade_check(None, 0));
3260    }
3261
3262    #[test]
3263    fn configured_agents_parses_yaml_block_array() {
3264        // config::get returns serde_norway::to_string for arrays, which is YAML block format
3265        let yaml_str = "- claude\n- codex\n- opencode\n- olm\n";
3266        let parsed: Vec<String> = serde_norway::from_str(yaml_str).unwrap();
3267        assert_eq!(parsed, vec!["claude", "codex", "opencode", "olm"]);
3268    }
3269
3270    #[test]
3271    fn configured_agents_parses_json_inline_array() {
3272        let json_str = r#"["claude","codex","olm"]"#;
3273        let parsed: Vec<String> = serde_json::from_str(json_str).unwrap();
3274        assert_eq!(parsed, vec!["claude", "codex", "olm"]);
3275    }
3276
3277    #[test]
3278    fn configured_agents_fallback_returns_default_agents() {
3279        // When no config is present, configured_agents() returns DEFAULT_AGENTS
3280        let defaults = configured_agents();
3281        assert!(defaults.contains(&"claude".to_string()));
3282        assert!(defaults.contains(&"codex".to_string()));
3283        assert!(defaults.contains(&"opencode".to_string()));
3284    }
3285
3286    /// Integration test that requires a fully working tmux environment with
3287    /// reliable capture-pane timing. Runs locally but not in CI (GitHub Actions
3288    /// has tmux installed but capture-pane timing is unreliable).
3289    ///
3290    /// DO NOT REMOVE #[ignore] — this test was un-ignored in PR #608 which
3291    /// broke CI. The `tmux -V` skip check is insufficient because tmux CAN
3292    /// create sessions on CI runners, but capture-pane output is empty or
3293    /// delayed, causing the assertion to fail after a 10s timeout.
3294    #[tokio::test]
3295    #[ignore]
3296    async fn integration_channel_to_tmux_to_capture() {
3297        use crate::channels::capture::CaptureService;
3298        use crate::channels::transport::Transport;
3299        use crate::tmux::{SessionGuard, TmuxManager};
3300        use std::sync::Arc;
3301
3302        // Create transport and capture service
3303        let transport = Arc::new(Transport::new());
3304        let capture = Arc::new(CaptureService::new(transport.clone()));
3305        let tmux = TmuxManager::new();
3306
3307        let task_id = "testtask1".to_string();
3308        let session_name = format!("orch-test-{}", task_id);
3309
3310        // Start a detached tmux session
3311        let _ = tmux
3312            .command()
3313            .args(["new-session", "-d", "-s", &session_name])
3314            .output()
3315            .await
3316            .expect("failed to start tmux session");
3317
3318        // Guard ensures session cleanup even on panic
3319        let _guard = SessionGuard(session_name.clone());
3320
3321        // Register session with capture service and transport binding
3322        capture
3323            .register_session("owner/repo", &task_id, &session_name)
3324            .await;
3325        transport
3326            .bind(
3327                "owner/repo",
3328                &task_id,
3329                &session_name,
3330                "telegram",
3331                "12345",
3332                None,
3333            )
3334            .await;
3335
3336        // Spawn capture.run() which exits when session is unregistered
3337        let capture_clone = capture.clone();
3338        let capture_handle = tokio::spawn(async move { capture_clone.run().await });
3339
3340        // Subscribe to transport output for this task
3341        let mut rx = transport
3342            .subscribe("owner/repo", &task_id)
3343            .await
3344            .expect("no subscription");
3345
3346        // Send a message into the tmux session via tmux send-keys (simulate channel input)
3347        let send = tmux
3348            .command()
3349            .args([
3350                "send-keys",
3351                "-t",
3352                &session_name,
3353                "echo from-channel",
3354                "Enter",
3355            ])
3356            .output()
3357            .await
3358            .expect("failed to send keys");
3359        assert!(send.status.success());
3360
3361        // Wait for an output chunk from capture -> transport
3362        let mut got = false;
3363        for _ in 0..20 {
3364            if let Ok(Ok(c)) =
3365                tokio::time::timeout(std::time::Duration::from_millis(500), rx.recv()).await
3366            {
3367                if c.content.contains("from-channel") {
3368                    got = true;
3369                    break;
3370                }
3371            }
3372        }
3373
3374        // Clean up: unregister session (tmux kill handled by SessionGuard on drop)
3375        capture.unregister_session("owner/repo", &task_id).await;
3376
3377        // Wait for capture.run to finish
3378        let _ = capture_handle.await;
3379
3380        assert!(got, "did not observe tmux output via capture/transport");
3381    }
3382
3383    // ── read_project_channel_config tests ─────────────────────────────────
3384
3385    #[test]
3386    fn read_project_channel_config_returns_defaults_when_no_file() {
3387        let dir = tempfile::tempdir().expect("tempdir");
3388        let cfg = read_project_channel_config(dir.path());
3389        assert!(cfg.telegram_topic_id.is_none());
3390        assert!(cfg.discord_channel_id.is_none());
3391    }
3392
3393    #[test]
3394    fn read_project_channel_config_parses_telegram_and_discord() {
3395        let dir = tempfile::tempdir().expect("tempdir");
3396        let orch_yml = dir.path().join(".orch.yml");
3397        std::fs::write(
3398            &orch_yml,
3399            "channels:\n  telegram:\n    topic_id: \"42\"\n  discord:\n    channel_id: \"9999\"\n",
3400        )
3401        .expect("write .orch.yml");
3402        let cfg = read_project_channel_config(dir.path());
3403        assert_eq!(cfg.telegram_topic_id.as_deref(), Some("42"));
3404        assert_eq!(cfg.discord_channel_id.as_deref(), Some("9999"));
3405    }
3406
3407    #[test]
3408    fn read_project_channel_config_handles_partial_channels() {
3409        let dir = tempfile::tempdir().expect("tempdir");
3410        let orch_yml = dir.path().join(".orch.yml");
3411        std::fs::write(&orch_yml, "channels:\n  telegram:\n    topic_id: \"7\"\n")
3412            .expect("write .orch.yml");
3413        let cfg = read_project_channel_config(dir.path());
3414        assert_eq!(cfg.telegram_topic_id.as_deref(), Some("7"));
3415        assert!(cfg.discord_channel_id.is_none());
3416    }
3417
3418    #[test]
3419    fn read_project_channel_config_handles_malformed_yaml() {
3420        let dir = tempfile::tempdir().expect("tempdir");
3421        let orch_yml = dir.path().join(".orch.yml");
3422        std::fs::write(&orch_yml, "channels: [\nbad yaml").expect("write .orch.yml");
3423        let cfg = read_project_channel_config(dir.path());
3424        // Should return defaults (not panic) and emit a warn! log with the parse error.
3425        assert!(cfg.telegram_topic_id.is_none());
3426        assert!(cfg.discord_channel_id.is_none());
3427    }
3428
3429    #[test]
3430    #[cfg(unix)]
3431    fn read_project_channel_config_handles_unreadable_file() {
3432        let dir = tempfile::tempdir().expect("tempdir");
3433        // A directory fails to read for every user, root included, where chmod 000 does not
3434        std::fs::create_dir(dir.path().join(".orch.yml")).expect("create .orch.yml dir");
3435        let cfg = read_project_channel_config(dir.path());
3436        // Should return defaults (not panic) and emit a warn! log with the read error.
3437        assert!(cfg.telegram_topic_id.is_none());
3438        assert!(cfg.discord_channel_id.is_none());
3439    }
3440}