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