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