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