Skip to main content

orch/engine/
jobs.rs

1//! Job scheduler — replaces `jobs_tick.sh`.
2//!
3//! Reads job definitions from `jobs.yml`, checks cron schedules against
4//! the current time, and creates tasks for due jobs. Handles catch-up
5//! for missed schedules (capped at 24h).
6//!
7//! Job types:
8//! - `task`: creates a task (GitHub Issue or internal SQLite) and lets the engine dispatch it
9//! - `bash`: runs a shell command directly (no LLM)
10//! - `self-review`: analyzes task metrics and creates self-improvement issues
11//!
12//! For task jobs, the `external` field controls where the task is created:
13//! - `external: false` (default): Creates an internal SQLite task
14//! - `external: true`: Creates a GitHub Issue
15
16use crate::backends::{ExternalBackend, ExternalId};
17use crate::channels::notification::TaskNotification;
18use crate::channels::transport::Transport;
19use crate::cmd as cmd_mod;
20use crate::config;
21use crate::cron as crate_cron;
22use crate::home;
23use crate::store::TaskStore;
24use crate::store::{JobState, TaskStatus};
25use anyhow::Context;
26use cron::Schedule;
27use serde::{Deserialize, Serialize};
28use std::collections::HashSet;
29use std::fs;
30use std::path::{Path, PathBuf};
31use std::process::{Output, Stdio};
32use std::result;
33use std::str::FromStr;
34use std::sync::Arc;
35use std::time::Duration;
36use tokio::process::Command;
37use tokio::task;
38use tokio::time;
39
40// Note: self-review analysis is now performed by scheduled tasks configured
41// in `.orch.yml` and executed as regular `task` jobs. Hardcoded self-review
42// logic was removed to keep this module a generic job dispatcher.
43
44/// A scheduled job definition (from jobs.yml).
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct Job {
47    pub id: String,
48    #[serde(default = "default_job_type")]
49    pub r#type: String,
50    pub schedule: String,
51    #[serde(default)]
52    pub task: Option<TaskTemplate>,
53    #[serde(default)]
54    pub command: Option<String>,
55    #[serde(default)]
56    pub dir: Option<String>,
57    #[serde(default = "default_enabled")]
58    pub enabled: bool,
59    #[serde(default = "default_external")]
60    pub external: bool, // true = GitHub Issue, false (default) = internal SQLite task
61    /// Send a Telegram notification when this job completes or fails.
62    /// Uses `channels.telegram.chat_id` from config unless `notify_target` overrides it.
63    #[serde(default)]
64    pub notify: bool,
65    /// Override the Telegram chat_id for this job's completion notification.
66    /// Only used when `notify: true`. Falls back to `channels.telegram.chat_id`.
67    #[serde(default)]
68    pub notify_target: Option<String>,
69    /// Path to the `prompts/jobs/*.md` file this job was loaded from, if any.
70    ///
71    /// `None` means the job was defined inline in `.orch.yml` / `config.yml`.
72    /// Set by `scan_prompt_jobs`; skipped during serialization so it never
73    /// leaks into config files.
74    #[serde(skip)]
75    pub prompt_file: Option<PathBuf>,
76}
77
78/// Template for creating a task from a job.
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct TaskTemplate {
81    pub title: String,
82    #[serde(default)]
83    pub body: String,
84    /// Path to a file (typically markdown) whose contents are used as the
85    /// task body. Resolved relative to the directory of the config file
86    /// that defines this job. Mutually exclusive with `body`.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub prompt: Option<String>,
89    #[serde(default)]
90    pub labels: Vec<String>,
91    #[serde(default)]
92    pub agent: Option<String>,
93}
94
95/// Resolve the body for a task template, reading from `prompt` if set.
96///
97/// `base_dir` is the directory containing the jobs config file (used to
98/// resolve relative `prompt` paths).
99pub fn resolve_template_body(template: &TaskTemplate, base_dir: &Path) -> anyhow::Result<String> {
100    match template.prompt.as_deref() {
101        Some(rel) => {
102            let path = Path::new(rel);
103            let full = if path.is_absolute() {
104                path.to_path_buf()
105            } else {
106                base_dir.join(path)
107            };
108            fs::read_to_string(&full)
109                .with_context(|| format!("reading prompt file {}", full.display()))
110        }
111        None => Ok(template.body.clone()),
112    }
113}
114
115/// Working directory for a bash job, resolved against the project `base_dir`
116fn resolve_job_dir(job: &Job, base_dir: &Path) -> PathBuf {
117    match job.dir.as_deref().map(Path::new) {
118        None => base_dir.to_path_buf(),
119        Some(path) if path.is_absolute() => path.to_path_buf(),
120        Some(path) => base_dir.join(path),
121    }
122}
123
124fn default_job_type() -> String {
125    "task".to_string()
126}
127
128fn default_enabled() -> bool {
129    true
130}
131
132fn default_external() -> bool {
133    false // Default to internal (SQLite) tasks
134}
135
136/// Top-level config structure (for reading jobs from .orch.yml / config.yml).
137#[derive(Debug, Serialize, Deserialize)]
138struct ConfigFile {
139    #[serde(default)]
140    jobs: Vec<Job>,
141    // Capture all other fields so we can round-trip them
142    #[serde(flatten)]
143    other: serde_norway::Mapping,
144}
145
146/// Resolve the config file that contains jobs.
147///
148/// Priority:
149/// 1. `.orch.yml` in the current directory (project config)
150/// 2. `.orch.yml` in any registered project directory (from global config)
151/// 3. `~/.orch/config.yml` (global config)
152pub fn resolve_jobs_path() -> PathBuf {
153    // 1. Check cwd
154    let project = PathBuf::from(".orch.yml");
155    if project.exists() {
156        return project;
157    }
158
159    // 2. Check registered project directories (handles brew service running from /)
160    if let Ok(paths) = config::get_project_paths() {
161        for path_str in &paths {
162            let candidate = PathBuf::from(path_str).join(".orch.yml");
163            if candidate.exists() {
164                return candidate;
165            }
166        }
167    }
168
169    // 3. Fall back to global config
170    home::config_path().unwrap_or_else(|_| PathBuf::from(".orch/config.yml"))
171}
172
173/// Load jobs from the orch config file plus any markdown prompt files
174/// discovered under `<base_dir>/prompts/jobs/*.md`.
175///
176/// Inline `jobs:` in `.orch.yml` and discovered prompt files are merged;
177/// duplicate ids across the two sources are rejected.
178pub fn load_jobs(path: &PathBuf) -> anyhow::Result<Vec<Job>> {
179    let base_dir = path
180        .parent()
181        .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
182    let mut jobs: Vec<Job> = if path.exists() {
183        let content =
184            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
185        let file: ConfigFile = serde_norway::from_str(&content)
186            .with_context(|| format!("parsing {}", path.display()))?;
187        file.jobs
188    } else {
189        vec![]
190    };
191
192    let scanned = scan_prompt_jobs(&base_dir)?;
193    let mut seen: HashSet<String> = jobs.iter().map(|j| j.id.clone()).collect();
194    for job in scanned {
195        if !seen.insert(job.id.clone()) {
196            anyhow::bail!(
197                "duplicate job id '{}' — defined in both '{}' and prompts/jobs/",
198                job.id,
199                path.display()
200            );
201        }
202        jobs.push(job);
203    }
204
205    for job in &jobs {
206        validate_job(job, &base_dir)?;
207    }
208    Ok(jobs)
209}
210
211fn validate_job(job: &Job, base_dir: &Path) -> anyhow::Result<()> {
212    let expanded = crate_cron::expand_alias(&job.schedule)
213        .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
214    let normalized = crate_cron::normalize_dow(&expanded);
215    let full_expr = format!("0 {normalized} *");
216    Schedule::from_str(&full_expr)
217        .with_context(|| format!("job '{}': invalid cron schedule '{}'", job.id, job.schedule))?;
218    if let Some(template) = job.task.as_ref() {
219        if template.prompt.is_some() && !template.body.is_empty() {
220            anyhow::bail!(
221                "job '{}': set either 'task.body' or 'task.prompt', not both",
222                job.id
223            );
224        }
225        if let Some(rel) = template.prompt.as_deref() {
226            let candidate = Path::new(rel);
227            let full = if candidate.is_absolute() {
228                candidate.to_path_buf()
229            } else {
230                base_dir.join(candidate)
231            };
232            if !full.exists() {
233                anyhow::bail!(
234                    "job '{}': prompt file not found: {}",
235                    job.id,
236                    full.display()
237                );
238            }
239        }
240    }
241    Ok(())
242}
243
244/// Frontmatter schema for `prompts/jobs/*.md` files.
245#[derive(Debug, Deserialize)]
246struct JobFrontmatter {
247    id: String,
248    schedule: String,
249    title: String,
250    #[serde(default = "default_job_type")]
251    r#type: String,
252    #[serde(default = "default_enabled")]
253    enabled: bool,
254    #[serde(default = "default_external")]
255    external: bool,
256    #[serde(default)]
257    labels: Vec<String>,
258    #[serde(default)]
259    agent: Option<String>,
260    #[serde(default)]
261    notify: bool,
262    #[serde(default)]
263    notify_target: Option<String>,
264    #[serde(default)]
265    command: Option<String>,
266    #[serde(default)]
267    dir: Option<String>,
268}
269
270/// Split a markdown file into (frontmatter, body). Returns `None` if the file
271/// does not start with a `---` fence.
272fn split_frontmatter(content: &str) -> Option<(&str, &str)> {
273    let rest = content
274        .strip_prefix("---\n")
275        .or_else(|| content.strip_prefix("---\r\n"))?;
276    let end = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n"))?;
277    let fm = &rest[..end];
278    let after = &rest[end..];
279    let body = after
280        .strip_prefix("\n---\n")
281        .or_else(|| after.strip_prefix("\n---\r\n"))
282        .unwrap_or(after);
283    Some((fm, body.trim_start_matches('\n')))
284}
285
286/// Scan `<base_dir>/prompts/jobs/*.md` for job-defining markdown files.
287pub fn scan_prompt_jobs(base_dir: &Path) -> anyhow::Result<Vec<Job>> {
288    let dir = base_dir.join("prompts").join("jobs");
289    if !dir.is_dir() {
290        return Ok(vec![]);
291    }
292    let mut entries: Vec<PathBuf> = fs::read_dir(&dir)
293        .with_context(|| format!("reading {}", dir.display()))?
294        .filter_map(result::Result::ok)
295        .map(|e| e.path())
296        .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("md"))
297        .collect();
298    entries.sort();
299
300    let mut jobs = Vec::with_capacity(entries.len());
301    for path in entries {
302        let content =
303            fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
304        let Some((fm, body)) = split_frontmatter(&content) else {
305            continue; // No frontmatter → treat as a plain prompt referenced from .orch.yml
306        };
307        let meta: JobFrontmatter = serde_norway::from_str(fm)
308            .with_context(|| format!("parsing frontmatter in {}", path.display()))?;
309        jobs.push(Job {
310            id: meta.id,
311            r#type: meta.r#type,
312            schedule: meta.schedule,
313            task: Some(TaskTemplate {
314                title: meta.title,
315                body: body.to_string(),
316                prompt: None,
317                labels: meta.labels,
318                agent: meta.agent,
319            }),
320            command: meta.command,
321            dir: meta.dir,
322            enabled: meta.enabled,
323            external: meta.external,
324            notify: meta.notify,
325            notify_target: meta.notify_target,
326            prompt_file: Some(path.clone()),
327        });
328    }
329    Ok(jobs)
330}
331
332/// Save jobs back to the config file, preserving all other keys.
333pub fn save_jobs(path: &PathBuf, jobs: &[Job]) -> anyhow::Result<()> {
334    // Read the existing file to preserve non-jobs keys
335    let mut file: ConfigFile = if path.exists() {
336        let content =
337            fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
338        serde_norway::from_str(&content).with_context(|| format!("parsing {}", path.display()))?
339    } else {
340        ConfigFile {
341            jobs: vec![],
342            other: serde_norway::Mapping::new(),
343        }
344    };
345
346    // Only persist inline jobs (those without a prompt_file source).
347    // Prompt-based jobs live in prompts/jobs/*.md and must not be duplicated
348    // into .orch.yml — doing so causes a "duplicate job id" error on the next
349    // load_jobs call.
350    file.jobs = jobs
351        .iter()
352        .filter(|j| j.prompt_file.is_none())
353        .cloned()
354        .collect();
355    let content = serde_norway::to_string(&file)?;
356    fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
357    Ok(())
358}
359
360/// Update the `enabled:` field in the YAML frontmatter of a prompt-based job
361/// file, preserving all other content unchanged.
362///
363/// The function rewrites only the `enabled:` line inside the opening `---`
364/// fence.  If the field is absent it is inserted before the closing `---`.
365pub fn set_frontmatter_enabled(path: &Path, enabled: bool) -> anyhow::Result<()> {
366    let original =
367        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
368
369    let value = if enabled { "true" } else { "false" };
370
371    // Replace an existing `enabled: <anything>` line inside the frontmatter.
372    // We only touch the first YAML block (between the opening and first closing
373    // `---` fences) to avoid accidentally rewriting the body.
374    let rewritten = rewrite_frontmatter_enabled(&original, value);
375    fs::write(path, rewritten).with_context(|| format!("writing {}", path.display()))?;
376    Ok(())
377}
378
379/// Rewrite the `enabled:` key inside the first `---` fence block of `content`.
380///
381/// If the key is present, its value is replaced.  If absent, it is appended
382/// just before the closing `---` line.  The rest of the document is unchanged.
383fn rewrite_frontmatter_enabled(content: &str, value: &str) -> String {
384    // Locate the opening fence.
385    let Some(rest) = content
386        .strip_prefix("---\n")
387        .or_else(|| content.strip_prefix("---\r\n"))
388    else {
389        // No frontmatter: return unchanged.
390        return content.to_string();
391    };
392
393    // Find the closing fence.
394    let Some(close_pos) = rest.find("\n---\n").or_else(|| rest.find("\n---\r\n")) else {
395        return content.to_string();
396    };
397
398    let fm = &rest[..close_pos];
399    let after_close = &rest[close_pos..]; // starts with "\n---\n" or "\n---\r\n"
400
401    // Rebuild the frontmatter, replacing or inserting `enabled:`.
402    let new_line = format!("enabled: {value}");
403    let mut found = false;
404    let new_fm: String = fm
405        .lines()
406        .map(|line| {
407            if line == "enabled: true" || line == "enabled: false" || line.starts_with("enabled: ")
408            {
409                found = true;
410                new_line.clone()
411            } else {
412                line.to_string()
413            }
414        })
415        .collect::<Vec<_>>()
416        .join("\n");
417
418    let new_fm = if found {
419        new_fm
420    } else {
421        format!("{new_fm}\n{new_line}")
422    };
423
424    format!("---\n{new_fm}{after_close}")
425}
426
427/// Returns `true` if the error indicates a "not found" (404) response.
428///
429/// Used to distinguish permanent task deletion from transient API errors.
430/// A 404 should clear `active_task_id`; other errors (rate limit, 5xx,
431/// network timeout) should be retried next tick without losing the reference.
432fn is_not_found_error(e: &anyhow::Error) -> bool {
433    // Walk the full error chain. Both the HTTP backend ("GitHub API GET {url}
434    // failed (404): ...") and the CLI backend ("... 404 ...") include "404"
435    // in the error string, matching the convention used throughout this codebase.
436    e.chain().any(|cause| cause.to_string().contains("404"))
437}
438
439/// Check all jobs and execute due ones.
440///
441/// Runtime state (last_run, active_task_id, last_task_status) is stored in
442/// SQLite via the `job_state` table, not in the YAML config file.
443pub async fn tick(
444    jobs_path: &Path,
445    backend: &Arc<dyn ExternalBackend>,
446    store: Option<&Arc<TaskStore>>,
447    repo: &str,
448    transport: Option<&Arc<Transport>>,
449) -> anyhow::Result<()> {
450    let jobs_path_clone = jobs_path.to_path_buf();
451    let jobs = match task::spawn_blocking(move || load_jobs(&jobs_path_clone))
452        .await
453        .map_err(|e| anyhow::anyhow!("load_jobs panicked: {e}"))
454        .and_then(|r| r)
455    {
456        Ok(j) => j,
457        Err(e) => {
458            tracing::error!(
459                path = %jobs_path.display(),
460                repo = %repo,
461                ?e,
462                "job config invalid — skipping scheduler tick for this project"
463            );
464            return Ok(());
465        }
466    };
467    let now = chrono::Utc::now();
468
469    for job in &jobs {
470        if !job.enabled {
471            continue;
472        }
473
474        // Load runtime state from SQLite
475        let mut state = if let Some(s) = store {
476            match s.get_job_state(repo, &job.id).await {
477                Ok(Some(st)) => st,
478                Ok(None) => JobState::new(repo, &job.id),
479                Err(e) => {
480                    tracing::error!(job_id = job.id, ?e, "failed to load job state, skipping");
481                    continue;
482                }
483            }
484        } else {
485            JobState::new(repo, &job.id)
486        };
487
488        // Check if schedule matches
489        let is_due = match &state.last_run {
490            Some(last) => match crate_cron::check(&job.schedule, Some(last)) {
491                Ok(v) => v,
492                Err(e) => {
493                    tracing::error!(
494                        job_id = job.id,
495                        schedule = job.schedule,
496                        ?e,
497                        "invalid cron expression, skipping"
498                    );
499                    continue;
500                }
501            },
502            None => match crate_cron::check(&job.schedule, None) {
503                Ok(v) => v,
504                Err(e) => {
505                    tracing::error!(
506                        job_id = job.id,
507                        schedule = job.schedule,
508                        ?e,
509                        "invalid cron expression, skipping"
510                    );
511                    continue;
512                }
513            },
514        };
515
516        if !is_due {
517            continue;
518        }
519
520        // Check if previous task is still active
521        let mut should_clear_task_id = false;
522        let mut should_skip = false;
523
524        if let Some(ref task_id) = state.active_task_id
525            && task_id.is_empty()
526        {
527            state.active_task_id = None;
528        }
529
530        if let Some(ref task_id) = state.active_task_id {
531            let task_id_clone = task_id.clone();
532            let is_active = if job.external {
533                // Check external (GitHub) task
534                match backend.get_task(&ExternalId(task_id_clone.clone())).await {
535                    Ok(task) => {
536                        let status = task.labels.iter().find(|l| l.starts_with("status:"));
537                        match status.map(String::as_str) {
538                            Some(
539                                "status:in_progress"
540                                | "status:routed"
541                                | "status:new"
542                                | "status:needs_review"
543                                | "status:in_review"
544                                | "status:approved"
545                                | "status:waiting",
546                            )
547                            | None => true, // no status label is treated as active
548                            Some(_) => false, // Terminal state
549                        }
550                    }
551                    Err(e) => {
552                        if is_not_found_error(&e) {
553                            tracing::warn!(
554                                job_id = job.id,
555                                task_id = task_id_clone,
556                                "active task not found (404), clearing active_task_id"
557                            );
558                            should_clear_task_id = true;
559                            state.last_task_status = Some("error".to_string());
560                        } else {
561                            tracing::warn!(
562                                job_id = job.id,
563                                task_id = task_id_clone,
564                                ?e,
565                                "transient error fetching active task, skipping tick (active_task_id preserved)"
566                            );
567                            should_skip = true;
568                        }
569                        false
570                    }
571                }
572            } else {
573                // Check internal task via store
574                if let Some(s) = store {
575                    if let Ok(Some(store_id)) = s.resolve_task_id(repo, &task_id_clone).await {
576                        match s.get(store_id).await {
577                            Ok(task) => match task.status {
578                                TaskStatus::New
579                                | TaskStatus::Routed
580                                | TaskStatus::InProgress
581                                | TaskStatus::NeedsReview
582                                | TaskStatus::InReview
583                                | TaskStatus::Approved
584                                | TaskStatus::Waiting => true,
585                                _ => false, // Terminal state (Done, Blocked, Cancelled)
586                            },
587                            Err(e) => {
588                                tracing::warn!(
589                                    job_id = job.id,
590                                    task_id = task_id_clone,
591                                    ?e,
592                                    "cannot fetch internal task from store, clearing active_task_id"
593                                );
594                                should_clear_task_id = true;
595                                false
596                            }
597                        }
598                    } else {
599                        tracing::warn!(
600                            job_id = job.id,
601                            task_id = task_id_clone,
602                            "internal task not found in store, clearing active_task_id"
603                        );
604                        should_clear_task_id = true;
605                        false
606                    }
607                } else {
608                    should_clear_task_id = true;
609                    false
610                }
611            };
612
613            if is_active {
614                tracing::debug!(
615                    job_id = job.id,
616                    task_id = task_id_clone,
617                    external = job.external,
618                    "skipping: previous task still active"
619                );
620                should_skip = true;
621            }
622        }
623
624        // Apply deferred mutations
625        if should_clear_task_id {
626            state.active_task_id = None;
627        }
628
629        if should_skip {
630            continue;
631        }
632
633        tracing::info!(job_id = job.id, r#type = job.r#type, "job due, executing");
634
635        // Persist last_run BEFORE execution to prevent catch-up on restart.
636        // On restart the runtime state is loaded from SQLite, so writing
637        // last_run here ensures a crash during execution won't cause the
638        // job to be considered due again immediately.
639        state.last_run = Some(now.format("%Y-%m-%dT%H:%M:%SZ").to_string());
640        if let Some(s) = store
641            && let Err(e) = s.upsert_job_state(&state).await
642        {
643            tracing::error!(
644                job_id = job.id,
645                ?e,
646                "failed to persist job state before execution — skipping this tick to preserve restart safety"
647            );
648            continue; // retry next tick instead of risking duplicate execution
649        }
650
651        // Execute the job (may mutate state.active_task_id / last_task_status).
652        let base_dir = jobs_path.parent().unwrap_or_else(|| Path::new("."));
653        execute_job(job, &mut state, backend, store, repo, transport, base_dir).await;
654
655        // Persist updated state (active_task_id, last_task_status) after execution.
656        if let Some(s) = store
657            && let Err(e) = s.upsert_job_state(&state).await
658        {
659            tracing::error!(
660                job_id = job.id,
661                ?e,
662                "failed to persist job state after execution"
663            );
664        }
665    }
666
667    Ok(())
668}
669
670/// Runs `bash -c` under a timeout in its own process group, so a timeout kills the commands bash
671/// forked too
672async fn run_bash(
673    cmd: &str,
674    dir: &Path,
675    timeout: Duration,
676) -> result::Result<anyhow::Result<Output>, time::error::Elapsed> {
677    let mut command = Command::new("bash");
678    command
679        .arg("-c")
680        .arg(cmd)
681        .current_dir(dir)
682        .stdin(Stdio::null())
683        .stdout(Stdio::piped())
684        .stderr(Stdio::piped())
685        .kill_on_drop(true);
686    #[cfg(unix)]
687    command.process_group(0);
688
689    let child = match command.spawn() {
690        Ok(child) => child,
691        Err(e) => return Ok(Err(anyhow::anyhow!("failed to execute `bash`: {e}"))),
692    };
693    let pgid = child.id();
694    let out = time::timeout(timeout, child.wait_with_output()).await;
695
696    #[cfg(unix)]
697    if out.is_err()
698        && let Some(pgid) = pgid
699    {
700        cmd_mod::kill_process_group(pgid);
701    }
702
703    out.map(|r| r.map_err(|e| anyhow::anyhow!("failed to execute `bash`: {e}")))
704}
705
706/// Execute a single job immediately (ignoring schedule and active-task guard).
707///
708/// Updates `state` with the result but does NOT persist to SQLite — caller is
709/// responsible for that.
710pub async fn execute_job(
711    job: &Job,
712    state: &mut JobState,
713    backend: &Arc<dyn ExternalBackend>,
714    store: Option<&Arc<TaskStore>>,
715    repo: &str,
716    transport: Option<&Arc<Transport>>,
717    base_dir: &Path,
718) {
719    match job.r#type.as_str() {
720        "task" => {
721            if let Some(ref template) = job.task {
722                let body = match resolve_template_body(template, base_dir) {
723                    Ok(b) => b,
724                    Err(e) => {
725                        tracing::error!(job_id = job.id, ?e, "failed to resolve task body");
726                        state.last_task_status = Some("failed".to_string());
727                        return;
728                    }
729                };
730
731                if job.external {
732                    let mut labels = template.labels.clone();
733                    labels.push("scheduled".to_string());
734                    labels.push(format!("job:{}", job.id));
735
736                    if let Some(ref agent) = template.agent
737                        && !agent.is_empty()
738                    {
739                        labels.push(format!("agent:{agent}"));
740                    }
741
742                    match backend.create_task(&template.title, &body, &labels).await {
743                        Ok(ext_id) => {
744                            tracing::info!(
745                                job_id = job.id,
746                                task_id = ext_id.0,
747                                "created external task"
748                            );
749                            state.active_task_id = Some(ext_id.0);
750                            state.last_task_status = Some("new".to_string());
751                        }
752                        Err(e) => {
753                            tracing::error!(job_id = job.id, ?e, "failed to create external task");
754                            state.last_task_status = Some("failed".to_string());
755                        }
756                    }
757                } else if let Some(s) = store {
758                    match s
759                        .create_internal(repo, &template.title, &body, "cron", &job.id, None)
760                        .await
761                    {
762                        Ok(internal_id) => {
763                            let task_id = format!("internal:{internal_id}");
764                            tracing::info!(job_id = job.id, task_id, "created internal task");
765                            state.active_task_id = Some(task_id);
766                            state.last_task_status = Some("new".to_string());
767                        }
768                        Err(e) => {
769                            tracing::error!(job_id = job.id, ?e, "failed to create internal task");
770                            state.last_task_status = Some("failed".to_string());
771                        }
772                    }
773                } else {
774                    tracing::error!(
775                        job_id = job.id,
776                        "no store available for internal task creation"
777                    );
778                    state.last_task_status = Some("failed".to_string());
779                }
780            }
781        }
782        "bash" => {
783            if let Some(ref cmd) = job.command {
784                // Unset `dir` and relative `dir` resolve against `base_dir`, the project dir.
785                // The brew service cwd is `/`, so `"."` and `"scripts"` would otherwise run there
786                let dir = resolve_job_dir(job, base_dir);
787                tracing::info!(job_id = job.id, cmd, dir = %dir.display(), "running bash command");
788
789                // Configurable timeout with 5-minute default. A bash job that hangs
790                // (network operation, blocking subprocess) would otherwise park a Tokio
791                // worker for its entire duration, blocking the inline tick loop.
792                let timeout_secs: u64 = config::get("jobs.bash_timeout_seconds")
793                    .ok()
794                    .and_then(|s| s.parse().ok())
795                    .unwrap_or(300);
796                let timeout = Duration::from_secs(timeout_secs);
797
798                let output = run_bash(cmd, &dir, timeout).await;
799
800                match output {
801                    Ok(Ok(o)) if o.status.success() => {
802                        state.last_task_status = Some("done".to_string());
803                    }
804                    Ok(Ok(o)) => {
805                        let stderr = String::from_utf8_lossy(&o.stderr);
806                        tracing::warn!(
807                            job_id = job.id,
808                            code = o.status.code(),
809                            %stderr,
810                            "bash command failed"
811                        );
812                        state.last_task_status = Some("failed".to_string());
813                    }
814                    Ok(Err(e)) => {
815                        tracing::error!(job_id = job.id, ?e, "bash command error");
816                        state.last_task_status = Some("failed".to_string());
817                    }
818                    Err(_) => {
819                        tracing::error!(
820                            job_id = job.id,
821                            secs = timeout_secs,
822                            "bash job timed out after {}s, child killed",
823                            timeout_secs
824                        );
825                        state.last_task_status = Some("timeout".to_string());
826                    }
827                }
828            }
829        }
830        // Note: previous versions supported a special-case "self-review"
831        // job type with embedded analysis logic. That logic has been removed
832        // — self-review work should be configured as a regular `task` job in
833        // `.orch.yml` and executed by agents. Unknown job types fall through
834        // to the warning handler below.
835        other => {
836            tracing::warn!(job_id = job.id, r#type = other, "unknown job type");
837        }
838    }
839
840    // Send Telegram notification if requested for this job.
841    if job.notify
842        && let Some(t) = transport
843    {
844        let status = state
845            .last_task_status
846            .as_deref()
847            .unwrap_or("unknown")
848            .to_string();
849        let summary = match status.as_str() {
850            "done" => format!("Job `{}` completed successfully.", job.id),
851            "failed" => format!("Job `{}` failed.", job.id),
852            "new" => format!("Job `{}` created a new task.", job.id),
853            other => format!("Job `{}` finished with status: {other}.", job.id),
854        };
855        // Resolve target chat_id: job override → config default
856        let target = job
857            .notify_target
858            .clone()
859            .or_else(|| config::get("channels.telegram.chat_id").ok());
860        let notification = TaskNotification {
861            task_id: job.id.clone(),
862            title: format!("Job: {}", job.id),
863            status,
864            agent: "scheduler".to_string(),
865            duration_seconds: 0.0,
866            summary,
867            repo: Some(repo.to_string()),
868            notify_target: target,
869            pr_number: None,
870        };
871        t.push_notification(notification);
872    }
873}
874
875// NOTE: self-review analysis is handled by scheduled `task` jobs configured
876// in `.orch.yml` and executed by agents. There is no embedded Rust logic
877// here — this module remains a generic job dispatcher.
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882    use crate::backends::test_helpers::NoopBackend;
883    use std::env;
884    use std::fs;
885    use tempfile::tempdir;
886
887    fn write_config(dir: &Path, content: &str) -> PathBuf {
888        let path = dir.join(".orch.yml");
889        fs::write(&path, content).unwrap();
890        path
891    }
892
893    #[tokio::test]
894    async fn run_bash_timeout_kills_the_child() {
895        let tmp = tempdir().unwrap();
896        let pid_file = tmp.path().join("pid");
897        let cmd = format!("sleep 60 & echo $! > {}; wait", pid_file.display());
898
899        let out = run_bash(&cmd, Path::new("."), Duration::from_secs(1)).await;
900        assert!(out.is_err(), "expected a timeout");
901
902        let pid: i32 = fs::read_to_string(&pid_file)
903            .unwrap()
904            .trim()
905            .parse()
906            .unwrap();
907        let mut gone = false;
908        for _ in 0..20 {
909            if cmd_mod::raw_kill(pid, 0) != 0 {
910                gone = true;
911                break;
912            }
913            time::sleep(Duration::from_millis(100)).await;
914        }
915        assert!(gone, "grandchild {pid} still running after timeout");
916    }
917
918    fn bash_job(id: &str, command: String, dir: Option<&str>) -> Job {
919        Job {
920            id: id.to_string(),
921            r#type: "bash".to_string(),
922            schedule: "* * * * *".to_string(),
923            task: None,
924            command: Some(command),
925            dir: dir.map(str::to_string),
926            enabled: true,
927            external: false,
928            notify: false,
929            notify_target: None,
930            prompt_file: None,
931        }
932    }
933
934    async fn execute_bash(job: &Job, base_dir: &Path) -> JobState {
935        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
936        let mut state = JobState::new("owner/repo", &job.id);
937        execute_job(
938            job,
939            &mut state,
940            &backend,
941            None,
942            "owner/repo",
943            None,
944            base_dir,
945        )
946        .await;
947        state
948    }
949
950    fn read_recorded_cwd(path: &Path) -> PathBuf {
951        let raw = fs::read_to_string(path).expect("bash command should have written cwd.txt");
952        fs::canonicalize(raw.trim()).unwrap()
953    }
954
955    #[tokio::test]
956    async fn bash_job_runs_in_project_dir_not_process_cwd() {
957        let project = tempdir().unwrap();
958        let process_cwd = fs::canonicalize(env::current_dir().unwrap()).unwrap();
959        let project_dir = fs::canonicalize(project.path()).unwrap();
960        assert_ne!(
961            process_cwd, project_dir,
962            "setup: process cwd must differ from the project dir"
963        );
964
965        let out_default = project.path().join("cwd-default.txt");
966        let job = bash_job(
967            "default-dir",
968            format!("pwd > '{}'", out_default.display()),
969            None,
970        );
971        let state = execute_bash(&job, project.path()).await;
972        assert_eq!(
973            state.last_task_status.as_deref(),
974            Some("done"),
975            "bash job with no dir should succeed in the project dir"
976        );
977        assert_eq!(
978            read_recorded_cwd(&out_default),
979            project_dir,
980            "bash job with no dir must run in the project dir"
981        );
982
983        let scripts = project.path().join("scripts");
984        fs::create_dir(&scripts).unwrap();
985        let out_relative = project.path().join("cwd-relative.txt");
986        let job = bash_job(
987            "relative-dir",
988            format!("pwd > '{}'", out_relative.display()),
989            Some("scripts"),
990        );
991        let state = execute_bash(&job, project.path()).await;
992        assert_eq!(
993            state.last_task_status.as_deref(),
994            Some("done"),
995            "bash job should succeed when relative dir resolves to an existing path"
996        );
997        assert_eq!(
998            read_recorded_cwd(&out_relative),
999            fs::canonicalize(&scripts).unwrap(),
1000            "relative dir must resolve against the project dir"
1001        );
1002
1003        let abs = tempdir().unwrap();
1004        let out_abs = project.path().join("cwd-absolute.txt");
1005        let job = bash_job(
1006            "absolute-dir",
1007            format!("pwd > '{}'", out_abs.display()),
1008            Some(abs.path().to_str().unwrap()),
1009        );
1010        let state = execute_bash(&job, project.path()).await;
1011        assert_eq!(
1012            state.last_task_status.as_deref(),
1013            Some("done"),
1014            "bash job should succeed when dir is an absolute path"
1015        );
1016        assert_eq!(
1017            read_recorded_cwd(&out_abs),
1018            fs::canonicalize(abs.path()).unwrap(),
1019            "absolute dir must be used as-is"
1020        );
1021    }
1022
1023    #[test]
1024    fn load_jobs_reads_prompt_from_file() {
1025        let tmp = tempdir().unwrap();
1026        fs::create_dir(tmp.path().join("prompts")).unwrap();
1027        fs::write(tmp.path().join("prompts/hello.md"), "hello from file").unwrap();
1028        let cfg = write_config(
1029            tmp.path(),
1030            r#"
1031jobs:
1032  - id: with-prompt
1033    schedule: "0 9 * * *"
1034    task:
1035      title: "Daily"
1036      prompt: prompts/hello.md
1037"#,
1038        );
1039
1040        let jobs = load_jobs(&cfg).unwrap();
1041        assert_eq!(jobs.len(), 1);
1042        let body = resolve_template_body(jobs[0].task.as_ref().unwrap(), tmp.path()).unwrap();
1043        assert_eq!(body, "hello from file");
1044    }
1045
1046    #[test]
1047    fn load_jobs_rejects_both_body_and_prompt() {
1048        let tmp = tempdir().unwrap();
1049        fs::write(tmp.path().join("p.md"), "x").unwrap();
1050        let cfg = write_config(
1051            tmp.path(),
1052            r#"
1053jobs:
1054  - id: conflict
1055    schedule: "0 9 * * *"
1056    task:
1057      title: "x"
1058      body: "inline"
1059      prompt: p.md
1060"#,
1061        );
1062
1063        let err = load_jobs(&cfg).unwrap_err().to_string();
1064        assert!(err.contains("not both"), "unexpected error: {err}");
1065    }
1066
1067    #[test]
1068    fn load_jobs_rejects_missing_prompt_file() {
1069        let tmp = tempdir().unwrap();
1070        let cfg = write_config(
1071            tmp.path(),
1072            r#"
1073jobs:
1074  - id: missing
1075    schedule: "0 9 * * *"
1076    task:
1077      title: "x"
1078      prompt: does-not-exist.md
1079"#,
1080        );
1081
1082        let err = load_jobs(&cfg).unwrap_err().to_string();
1083        assert!(
1084            err.contains("prompt file not found"),
1085            "unexpected error: {err}"
1086        );
1087    }
1088
1089    #[test]
1090    fn resolve_template_body_falls_back_to_inline_body() {
1091        let tmp = tempdir().unwrap();
1092        let template = TaskTemplate {
1093            title: "t".to_string(),
1094            body: "inline body".to_string(),
1095            prompt: None,
1096            labels: vec![],
1097            agent: None,
1098        };
1099        assert_eq!(
1100            resolve_template_body(&template, tmp.path()).unwrap(),
1101            "inline body"
1102        );
1103    }
1104
1105    fn write_prompt_job(dir: &Path, name: &str, content: &str) {
1106        let jobs_dir = dir.join("prompts").join("jobs");
1107        fs::create_dir_all(&jobs_dir).unwrap();
1108        fs::write(jobs_dir.join(name), content).unwrap();
1109    }
1110
1111    #[test]
1112    fn scan_prompt_jobs_picks_up_frontmatter_files() {
1113        let tmp = tempdir().unwrap();
1114        write_prompt_job(
1115            tmp.path(),
1116            "morning.md",
1117            "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\nlabels: [daily]\nagent: claude\n---\n\nDo morning stuff.\n",
1118        );
1119        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1120        assert_eq!(jobs.len(), 1);
1121        assert_eq!(jobs[0].id, "morning");
1122        assert_eq!(jobs[0].schedule, "0 9 * * *");
1123        let task = jobs[0].task.as_ref().unwrap();
1124        assert_eq!(task.title, "Morning");
1125        assert_eq!(task.body, "Do morning stuff.\n");
1126        assert_eq!(task.labels, vec!["daily".to_string()]);
1127        assert_eq!(task.agent.as_deref(), Some("claude"));
1128    }
1129
1130    #[test]
1131    fn load_jobs_merges_inline_and_scanned() {
1132        let tmp = tempdir().unwrap();
1133        write_prompt_job(
1134            tmp.path(),
1135            "scanned.md",
1136            "---\nid: scanned\nschedule: '0 9 * * *'\ntitle: Scanned\n---\n\nbody\n",
1137        );
1138        let cfg = write_config(
1139            tmp.path(),
1140            r#"
1141jobs:
1142  - id: inline
1143    schedule: "0 10 * * *"
1144    task:
1145      title: "Inline"
1146      body: "x"
1147"#,
1148        );
1149        let jobs = load_jobs(&cfg).unwrap();
1150        let ids: Vec<&str> = jobs.iter().map(|j| j.id.as_str()).collect();
1151        assert!(ids.contains(&"inline"));
1152        assert!(ids.contains(&"scanned"));
1153        assert_eq!(jobs.len(), 2);
1154    }
1155
1156    #[test]
1157    fn load_jobs_rejects_duplicate_id_across_sources() {
1158        let tmp = tempdir().unwrap();
1159        write_prompt_job(
1160            tmp.path(),
1161            "dup.md",
1162            "---\nid: dup\nschedule: '0 9 * * *'\ntitle: Dup\n---\n\nbody\n",
1163        );
1164        let cfg = write_config(
1165            tmp.path(),
1166            r#"
1167jobs:
1168  - id: dup
1169    schedule: "0 10 * * *"
1170    task:
1171      title: "Dup inline"
1172      body: "x"
1173"#,
1174        );
1175        let err = load_jobs(&cfg).unwrap_err().to_string();
1176        assert!(err.contains("duplicate job id"), "unexpected error: {err}");
1177    }
1178
1179    #[test]
1180    fn scan_prompt_jobs_ignores_files_without_frontmatter() {
1181        let tmp = tempdir().unwrap();
1182        write_prompt_job(
1183            tmp.path(),
1184            "plain.md",
1185            "just a prompt body, no frontmatter\n",
1186        );
1187        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1188        assert_eq!(jobs.len(), 0);
1189    }
1190
1191    #[test]
1192    fn load_jobs_works_without_config_file_when_directory_present() {
1193        let tmp = tempdir().unwrap();
1194        write_prompt_job(
1195            tmp.path(),
1196            "solo.md",
1197            "---\nid: solo\nschedule: '0 9 * * *'\ntitle: Solo\n---\n\nbody\n",
1198        );
1199        let missing_cfg = tmp.path().join(".orch.yml");
1200        let jobs = load_jobs(&missing_cfg).unwrap();
1201        assert_eq!(jobs.len(), 1);
1202        assert_eq!(jobs[0].id, "solo");
1203    }
1204
1205    // ──── Issue #3193: frontmatter `enabled: false` must be respected ────────
1206
1207    #[test]
1208    fn scan_prompt_jobs_respects_enabled_false() {
1209        let tmp = tempdir().unwrap();
1210        write_prompt_job(
1211            tmp.path(),
1212            "disabled.md",
1213            "---\nid: disabled\nschedule: '0 9 * * *'\ntitle: Disabled\nenabled: false\n---\n\nbody\n",
1214        );
1215        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1216        assert_eq!(jobs.len(), 1);
1217        assert!(!jobs[0].enabled, "job should be disabled via frontmatter");
1218    }
1219
1220    #[test]
1221    fn scan_prompt_jobs_sets_prompt_file() {
1222        let tmp = tempdir().unwrap();
1223        write_prompt_job(
1224            tmp.path(),
1225            "morning.md",
1226            "---\nid: morning\nschedule: '0 9 * * *'\ntitle: Morning\n---\n\nbody\n",
1227        );
1228        let jobs = scan_prompt_jobs(tmp.path()).unwrap();
1229        assert_eq!(jobs.len(), 1);
1230        assert!(
1231            jobs[0].prompt_file.is_some(),
1232            "prompt_file should be set for frontmatter jobs"
1233        );
1234    }
1235
1236    #[test]
1237    fn save_jobs_does_not_persist_prompt_based_jobs() {
1238        let tmp = tempdir().unwrap();
1239        // A prompt-based job
1240        write_prompt_job(
1241            tmp.path(),
1242            "prompt.md",
1243            "---\nid: from-prompt\nschedule: '0 9 * * *'\ntitle: Prompt Job\n---\n\nbody\n",
1244        );
1245        // An inline job in .orch.yml
1246        let cfg = write_config(
1247            tmp.path(),
1248            "jobs:\n  - id: inline\n    schedule: \"0 10 * * *\"\n    task:\n      title: Inline\n      body: x\n",
1249        );
1250        let jobs = load_jobs(&cfg).unwrap();
1251        assert_eq!(jobs.len(), 2);
1252
1253        // save_jobs should only write the inline job, not the prompt-based one
1254        save_jobs(&cfg, &jobs).unwrap();
1255
1256        let saved = load_jobs(&cfg).unwrap();
1257        assert_eq!(saved.len(), 2, "both jobs should still be loadable");
1258        let ids: Vec<&str> = saved.iter().map(|j| j.id.as_str()).collect();
1259        assert!(ids.contains(&"inline"));
1260        assert!(ids.contains(&"from-prompt"));
1261    }
1262
1263    #[test]
1264    fn rewrite_frontmatter_enabled_replaces_existing_value() {
1265        let input = "---\nid: foo\nschedule: daily\nenabled: true\ntitle: Foo\n---\n\nbody\n";
1266        let out = rewrite_frontmatter_enabled(input, "false");
1267        assert!(
1268            out.contains("enabled: false"),
1269            "should replace enabled: true"
1270        );
1271        assert!(!out.contains("enabled: true"), "old value must be gone");
1272        assert!(out.contains("body"), "body must be preserved");
1273    }
1274
1275    #[test]
1276    fn rewrite_frontmatter_enabled_inserts_when_absent() {
1277        let input = "---\nid: foo\nschedule: daily\ntitle: Foo\n---\n\nbody\n";
1278        let out = rewrite_frontmatter_enabled(input, "false");
1279        assert!(
1280            out.contains("enabled: false"),
1281            "should insert enabled: false"
1282        );
1283        assert!(out.contains("body"), "body must be preserved");
1284    }
1285
1286    #[test]
1287    fn set_frontmatter_enabled_writes_file() {
1288        let tmp = tempdir().unwrap();
1289        let path = tmp.path().join("job.md");
1290        fs::write(
1291            &path,
1292            "---\nid: foo\nschedule: daily\ntitle: Foo\nenabled: true\n---\n\nbody\n",
1293        )
1294        .unwrap();
1295        set_frontmatter_enabled(&path, false).unwrap();
1296        let content = fs::read_to_string(&path).unwrap();
1297        assert!(content.contains("enabled: false"));
1298        assert!(!content.contains("enabled: true"));
1299    }
1300}