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