Skip to main content

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